1import{_ as hv,r as he,j as Lt}from"./index-BnjeHCXP.js";const QC="GpuTimings",Ex="2.19.2",JC="3f52bb8";function Ud(l,e){for(const t in e){const s=e[t];Array.isArray(s)?l[t]=Ud([],s):s&&typeof s=="object"?l[t]=Ud({},s):l[t]=s}return l}const eE={create(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,l=>{const e=Math.random()*16|0;return(l==="x"?e:e&3|8).toString(16)})}},ve={delimiter:"/",join(...l){let e=l[0];for(let t=0;t<l.length-1;t++){const s=l[t],i=l[t+1];if(i[0]===ve.delimiter){e=i;continue}s&&i&&s[s.length-1]!==ve.delimiter&&i[0]!==ve.delimiter?e+=ve.delimiter+i:e+=i}return e},normalize(l){const e=l.startsWith(ve.delimiter),t=l.endsWith(ve.delimiter),s=l.split("/");let i="",r=[];for(let a=0;a<s.length;a++)if(s[a]!==""&&s[a]!=="."){if(s[a]===".."&&r.length>0){r=r.slice(0,r.length-2);continue}a>0&&r.push(ve.delimiter),r.push(s[a])}return i=r.join(""),!e&&i[0]===ve.delimiter&&(i=i.slice(1)),t&&i[i.length-1]!==ve.delimiter&&(i+=ve.delimiter),i},split(l){const e=l.lastIndexOf(ve.delimiter);return e!==-1?[l.substring(0,e),l.substring(e+1)]:["",l]},getBasename(l){return ve.split(l)[1]},getDirectory(l){return ve.split(l)[0]},getExtension(l){const e=l.split("?")[0].split(".").pop();return e!==l?`.${e}`:""},isRelativePath(l){return l.charAt(0)!=="/"&&l.match(/:\/\//)===null},extractPath(l){let e="";const t=l.split("/");let s=0;if(t.length>1)if(ve.isRelativePath(l))if(t[0]===".")for(s=0;s<t.length-1;++s)e+=s===0?t[s]:`/${t[s]}`;else if(t[0]==="..")for(s=0;s<t.length-1;++s)e+=s===0?t[s]:`/${t[s]}`;else for(e=".",s=0;s<t.length-1;++s)e+=`/${t[s]}`;else for(s=0;s<t.length-1;++s)e+=s===0?t[s]:`/${t[s]}`;return e}},tE=()=>{let l=!1;try{const e=Object.defineProperty({},"passive",{get:function(){return l=!0,!1}});window.addEventListener("testpassive",null,e),window.removeEventListener("testpassive",null,e)}catch{}return l},pi=typeof navigator<"u"?navigator.userAgent:"",Wl=typeof window<"u"?"browser":typeof global<"u"?"node":"worker",al=/android/i.test(pi)?"android":/ip(?:[ao]d|hone)/i.test(pi)?"ios":/windows/i.test(pi)?"windows":/mac os/i.test(pi)?"osx":/linux/i.test(pi)?"linux":/cros/i.test(pi)?"cros":null,sE=Wl!=="browser"?null:/Chrome\/|Chromium\/|Edg.*\//.test(pi)?"chrome":/Safari\//.test(pi)?"safari":/Firefox\//.test(pi)?"firefox":"other",iE=/Macintosh/i.test(pi)&&typeof navigator<"u"&&navigator.maxTouchPoints>0&&!/iPhone|iPad|iPod/i.test(pi),rE=Wl==="browser"&&("ontouchstart"in window||"maxTouchPoints"in navigator&&navigator.maxTouchPoints>0),aE=tE(),Ce={name:al,environment:Wl,browser:Wl==="browser",worker:Wl==="worker",desktop:["windows","osx","linux","cros"].includes(al),mobile:["android","ios"].includes(al),ios:al==="ios",android:al==="android",visionos:iE,touch:rE,passiveEvents:aE,browserName:sE},bx="abcdefghijklmnopqrstuvwxyz",Ax="ABCDEFGHIJKLMNOPQRSTUVWXYZ",nE=bx+Ax,Lm=55296,Px=56319,dv=56320,oE=57343,lE=8205,uv=127462,fv=127487,cE=127995,hE=127999,dE=8400,uE=8447,Fm=65024,Om=65039;function Bm(l,e=0){const t=l.length;if(e<0||e>=t)return null;const s=l.charCodeAt(e);if(t>1&&s>=Lm&&s<=Px){const i=l.charCodeAt(e+1);if(i>=dv&&i<=oE)return{code:(s-Lm)*1024+i-dv+65536,long:!0}}return{code:s,long:!1}}function jr(l,e,t){if(!l)return!1;const s=Bm(l);if(s){const i=s.code;return i>=e&&i<=t}return!1}function fE(l,e){if(e===l.length-1)return 1;if(jr(l[e],Lm,Px)){const t=l.substring(e,e+2),s=l.substring(e+2,e+4);return jr(s,cE,hE)||jr(t,uv,fv)&&jr(s,uv,fv)?4:jr(s,Fm,Om)?3:2}return jr(l[e+1],Fm,Om)?2:1}const vd={ASCII_LOWERCASE:bx,ASCII_UPPERCASE:Ax,ASCII_LETTERS:nE,format(l,...e){for(let t=0;t<e.length;t++)l=l.replace(`{${t}}`,e[t]);return l},getCodePoint(l,e){const t=Bm(l,e);return t&&t.code},getCodePoints(l){if(typeof l!="string")throw new TypeError("Not a string");let e=0;const t=[];let s;for(;s=Bm(l,e);)t.push(s.code),e+=s.long?2:1;return t},getSymbols(l){if(typeof l!="string")throw new TypeError("Not a string");let e=0;const t=l.length,s=[];let i=0,r;for(;e<t;){if(i+=fE(l,e+i),r=l[e+i],jr(r,dE,uE)&&(r=l[e+i++]),jr(r,Fm,Om)&&(r=l[e+i++]),r&&r.charCodeAt(0)===lE){r=l[e+i++];continue}const a=l.substring(e,e+i);s.push(a),e+=i,i=0}return s},fromCodePoint(...l){return l.map(e=>e>65535?(e-=65536,String.fromCharCode((e>>10)+55296,e%1024+56320)):String.fromCharCode(e)).join("")}};class pE{handler;name;callback;scope;_once;_removed=!1;constructor(e,t,s,i,r=!1){this.handler=e,this.name=t,this.callback=s,this.scope=i,this._once=r}off(){this._removed||this.handler.offByHandle(this)}on(e,t,s=this){return this.handler._addCallback(e,t,s,!1)}once(e,t,s=this){return this.handler._addCallback(e,t,s,!0)}set removed(e){e&&(this._removed=!0)}get removed(){return this._removed}toJSON(e){}}class ge{_callbacks=new Map;_callbackActive=new Map;initEventHandler(){this._callbacks=new Map,this._callbackActive=new Map}_addCallback(e,t,s,i){if(this._callbacks.has(e)||this._callbacks.set(e,[]),this._callbackActive.has(e)){const a=this._callbackActive.get(e);a&&a===this._callbacks.get(e)&&this._callbackActive.set(e,a.slice())}const r=new pE(this,e,t,s,i);return this._callbacks.get(e).push(r),r}on(e,t,s=this){return this._addCallback(e,t,s,!1)}once(e,t,s=this){return this._addCallback(e,t,s,!0)}off(e,t,s){if(e)this._callbackActive.has(e)&&this._callbackActive.get(e)===this._callbacks.get(e)&&this._callbackActive.set(e,this._callbackActive.get(e).slice());else for(const[i,r]of this._callbackActive)this._callbacks.has(i)&&this._callbacks.get(i)===r&&this._callbackActive.set(i,r.slice());if(e)if(t){const i=this._callbacks.get(e);if(!i)return this;for(let r=0;r<i.length;r++)i[r].callback===t&&(s&&i[r].scope!==s||(i[r].removed=!0,i.splice(r,1),r--));i.length===0&&this._callbacks.delete(e)}else{const i=this._callbacks.get(e);if(i){for(let r=0;r<i.length;r++)i[r].removed=!0;this._callbacks.delete(e)}}else{for(const i of this._callbacks.values())for(let r=0;r<i.length;r++)i[r].removed=!0;this._callbacks.clear()}return this}offByHandle(e){const t=e.name;e.removed=!0,this._callbackActive.has(t)&&this._callbackActive.get(t)===this._callbacks.get(t)&&this._callbackActive.set(t,this._callbackActive.get(t).slice());const s=this._callbacks.get(t);if(!s)return this;const i=s.indexOf(e);return i!==-1&&(s.splice(i,1),s.length===0&&this._callbacks.delete(t)),this}fire(e,t,s,i,r,a,n,o,c){if(!e)return this;const h=this._callbacks.get(e);if(!h)return this;let d;this._callbackActive.has(e)?this._callbackActive.get(e)!==h&&(d=h.slice()):this._callbackActive.set(e,h);for(let u=0;(d||this._callbackActive.get(e))&&u<(d||this._callbackActive.get(e)).length;u++){const f=(d||this._callbackActive.get(e))[u];if(f.callback&&(f.callback.call(f.scope,t,s,i,r,a,n,o,c),f._once)){const p=this._callbacks.get(e),m=p?p.indexOf(f):-1;if(m!==-1){this._callbackActive.get(e)===p&&this._callbackActive.set(e,this._callbackActive.get(e).slice());const _=this._callbacks.get(e);if(!_)continue;_[m].removed=!0,_.splice(m,1),_.length===0&&this._callbacks.delete(e)}}}return d||this._callbackActive.delete(e),this}hasEvent(e){return!!this._callbacks.get(e)?.length}}class mE{_list=[];_index={};push(e,t){if(this._index[e])throw Error(`Key already in index ${e}`);const s=this._list.push(t)-1;this._index[e]=s}has(e){return this._index[e]!==void 0}get(e){const t=this._index[e];return t!==void 0?this._list[t]:null}remove(e){const t=this._index[e];if(t!==void 0){this._list.splice(t,1),delete this._index[e];for(e in this._index){const s=this._index[e];s>t&&(this._index[e]=s-1)}return!0}return!1}list(){return this._list}clear(){this._list.length=0;for(const e in this._index)delete this._index[e]}}const _E=l=>{const e={};let t=e;return()=>(t===e&&(t=l()),t)};class Ws{static modules={};static wasmSupported=_E(()=>{try{if(typeof WebAssembly=="object"&&typeof WebAssembly.instantiate=="function"){const e=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(e instanceof WebAssembly.Module)return new WebAssembly.Instance(e)instanceof WebAssembly.Instance}}catch{}return!1});static loadScript(e,t){const s=document.createElement("script");s.setAttribute("src",e),s.onload=()=>{t(null)},s.onerror=()=>{t(`Failed to load script='${e}'`)},document.body.appendChild(s)}static loadWasm(e,t,s){const i=Ws.wasmSupported()&&t.glueUrl&&t.wasmUrl?t.glueUrl:t.fallbackUrl;i?Ws.loadScript(i,r=>{if(r)s(r,null);else{const a=window[e];window[e]=void 0,a({locateFile:()=>t.wasmUrl,onAbort:()=>{s("wasm module aborted.")}}).then(n=>{s(null,n)})}}):s("No supported wasm modules found.",null)}static getModule(e){return Ws.modules.hasOwnProperty(e)||(Ws.modules[e]={config:null,initializing:!1,instance:null,callbacks:[]}),Ws.modules[e]}static initialize(e,t){if(t.initializing)return;const s=t.config;(s.glueUrl||s.wasmUrl||s.fallbackUrl)&&(t.initializing=!0,Ws.loadWasm(e,s,(i,r)=>{i?s.errorHandler?s.errorHandler(i):console.error(`failed to initialize module=${e} error=${i}`):(t.instance=r,t.callbacks.forEach(a=>{a(r)}))}
1))}}class Ix{static setConfig(e,t){const s=Ws.getModule(e);s.config=t,s.callbacks.length>0&&Ws.initialize(e,s)}static getConfig(e){return Ws.modules?.[e]?.config}static getInstance(e,t){const s=Ws.getModule(e);s.instance?t(s.instance):(s.callbacks.push(t),s.config&&Ws.initialize(e,s))}}class Dx{arraybuffer;dataView;offset=0;constructor(e){this.arraybuffer=e,this.dataView=new DataView(e)}get remainingBytes(){return this.dataView.byteLength-this.offset}reset(e=0){this.offset=e}skip(e){this.offset+=e}align(e){this.offset=this.offset+e-1&~(e-1)}_inc(e){return this.offset+=e,this.offset-e}readChar(){return String.fromCharCode(this.dataView.getUint8(this.offset++))}readChars(e){let t="";for(let s=0;s<e;++s)t+=this.readChar();return t}readU8(){return this.dataView.getUint8(this.offset++)}readU16(){return this.dataView.getUint16(this._inc(2),!0)}readU32(){return this.dataView.getUint32(this._inc(4),!0)}readU64(){return this.readU32()+2**32*this.readU32()}readU32be(){return this.dataView.getUint32(this._inc(4),!1)}readArray(e){for(let t=0;t<e.length;++t)e[t]=this.readU8()}readLine(){const e=this.dataView;let t="";for(;!(this.offset>=e.byteLength);){const s=String.fromCharCode(this.readU8());if(s===` 2`)break;t+=s}return t}}class zd{items=[];length=0;loopIndex=-1;_sortBy;_sortHandler;constructor(e){this._sortBy=e.sortBy,this._sortHandler=this._doSort.bind(this)}_binarySearch(e){let t=0,s=this.items.length-1;const i=e[this._sortBy];let r,a;for(;t<=s;)r=Math.floor((t+s)/2),a=this.items[r][this._sortBy],a<=i?t=r+1:a>i&&(s=r-1);return t}_doSort(e,t){const s=this._sortBy;return e[s]-t[s]}insert(e){const t=this._binarySearch(e);this.items.splice(t,0,e),this.length++,this.loopIndex>=t&&this.loopIndex++}append(e){this.items.push(e),this.length++}remove(e){const t=this.items.indexOf(e);t<0||(this.items.splice(t,1),this.length--,this.loopIndex>=t&&this.loopIndex--)}sort(){const e=this.loopIndex>=0?this.items[this.loopIndex]:null;this.items.sort(this._sortHandler),e!==null&&(this.loopIndex=this.items.indexOf(e))}}class Mx extends ge{static EVENT_ADD="add";static EVENT_REMOVE="remove";static EVENT_CHANGE="change";_index={};_list=[];_parent;constructor(e){super(),this._parent=e}add(...e){let t=!1;const s=this._processArguments(e,!0);if(!s.length)return t;for(let i=0;i<s.length;i++)this._index[s[i]]||(t=!0,this._index[s[i]]=!0,this._list.push(s[i]),this.fire("add",s[i],this._parent));return t&&this.fire("change",this._parent),t}remove(...e){let t=!1;if(!this._list.length)return t;const s=this._processArguments(e,!0);if(!s.length)return t;for(let i=0;i<s.length;i++)this._index[s[i]]&&(t=!0,delete this._index[s[i]],this._list.splice(this._list.indexOf(s[i]),1),this.fire("remove",s[i],this._parent));return t&&this.fire("change",this._parent),t}clear(){if(!this._list.length)return;const e=this._list.slice(0);this._list=[],this._index={};for(let t=0;t<e.length;t++)this.fire("remove",e[t],this._parent);this.fire("change",this._parent)}has(...e){return this._list.length?this._has(this._processArguments(e)):!1}_has(e){if(!this._list.length||!e.length)return!1;for(let t=0;t<e.length;t++)if(e[t].length===1){if(this._index[e[t][0]])return!0}else{let s=!0;for(let i=0;i<e[t].length;i++)if(!this._index[e[t][i]]){s=!1;break}if(s)return!0}return!1}list(){return this._list.slice(0)}_processArguments(e,t){const s=[];let i=[];if(!e||!e.length)return s;for(let r=0;r<e.length;r++)if(e[r]instanceof Array){t||(i=[]);for(let a=0;a<e[r].length;a++)typeof e[r][a]=="string"&&(t?s.push(e[r][a]):i.push(e[r][a]));!t&&i.length&&s.push(i)}else typeof e[r]=="string"&&(t?s.push(e[r]):s.push([e[r]]));return s}get size(){return this._list.length}}const Gt=typeof window<"u"&&window.performance&&window.performance.now?performance.now.bind(performance):Date.now,gE=/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class jf{scheme;authority;path;query;fragment;constructor(e){const t=e.match(gE);this.scheme=t[2],this.authority=t[4],this.path=t[5],this.query=t[7],this.fragment=t[9]}toString(){let e="";return this.scheme&&(e+=`${this.scheme}:`),this.authority&&(e+=`//${this.authority}`),e+=this.path,this.query&&(e+=`?${this.query}`),this.fragment&&(e+=`#${this.fragment}`),e}getQuery(){const e={};if(this.query){const t=decodeURIComponent(this.query).split("&");for(const s of t){const i=s.split("=");e[i[0]]=i[1]}}return e}setQuery(e){let t="";for(const s in e)e.hasOwnProperty(s)&&(t!==""&&(t+="&"),t+=`${encodeURIComponent(s)}=${encodeURIComponent(e[s])}`);this.query=t}}class G_{static _traceChannels=new Set;static stack=!1;static set(e,t=!0){}static get(e){return G_._traceChannels.has(e)}}const vE=0,H_=1,pv=4,SE=5,H={DEG_TO_RAD:Math.PI/180,RAD_TO_DEG:180/Math.PI,clamp(l,e,t){return l>=t?t:l<=e?e:l},intToBytes24(l){const e=l>>16&255,t=l>>8&255,s=l&255;return[e,t,s]},intToBytes32(l){const e=l>>24&255,t=l>>16&255,s=l>>8&255,i=l&255;return[e,t,s,i]},bytesToInt24(l,e,t){return l.length&&(t=l[2],e=l[1],l=l[0]),l<<16|e<<8|t},bytesToInt32(l,e,t,s){return l.length&&(s=l[3],t=l[2],e=l[1],l=l[0]),(l<<24|e<<16|t<<8|s)>>>0},lerp(l,e,t){return l+(e-l)*H.clamp(t,0,1)},lerpAngle(l,e,t){return e-l>180&&(e-=360),e-l<-180&&(e+=360),H.lerp(l,e,H.clamp(t,0,1))},powerOfTwo(l){return l!==0&&!(l&l-1)},nextPowerOfTwo(l){return l--,l|=l>>1,l|=l>>2,l|=l>>4,l|=l>>8,l|=l>>16,l++,l},nearestPowerOfTwo(l){return Math.pow(2,Math.round(Math.log2(l)))},random(l,e){const t=e-l;return Math.random()*t+l},smoothstep(l,e,t){return t<=l?0:t>=e?1:(t=(t-l)/(e-l),t*t*(3-2*t))},smootherstep(l,e,t){return t<=l?0:t>=e?1:(t=(t-l)/(e-l),t*t*t*(t*(t*6-15)+10))},roundUp(l,e){return e===0?l:Math.ceil(l/e)*e},between(l,e,t,s){const i=Math.min(e,t),r=Math.max(e,t);return s?l>=i&&l<=r:l>i&&l<r}};class Q{r;g;b;a;constructor(e=0,t=0,s=0,i=1){const r=e.length;r===3||r===4?(this.r=e[0],this.g=e[1],this.b=e[2],this.a=e[3]??1):(this.r=e,this.g=t,this.b=s,this.a=i)}clone(){const e=this.constructor;return new e(this.r,this.g,this.b,this.a)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}equals(e){return this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}set(e,t,s,i=1){return this.r=e,this.g=t,this.b=s,this.a=i,this}lerp(e,t,s){return this.r=e.r+s*(t.r-e.r),this.g=e.g+s*(t.g-e.g),this.b=e.b+s*(t.b-e.b),this.a=e.a+s*(t.a-e.a),this}linear(e=this){return this.r=Math.pow(e.r,2.2),this.g=Math.pow(e.g,2.2),this.b=Math.pow(e.b,2.2),this.a=e.a,this}gamma(e=this){return this.r=Math.pow(e.r,1/2.2),this.g=Math.pow(e.g,1/2.2),this.b=Math.pow(e.b,1/2.2),this.a=e.a,this}mulScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}fromString(e){const t=parseInt(e.replace("#","0x"),16);let s;return e.length>7?s=H.intToBytes32(t):(s=H.intToBytes24(t),s[3]=255),this.set(s[0]/255,s[1]/255,s[2]/255,s[3]/255),this}fromArray(e,t=0){return this.r=e[t]??this.r,this.g=e[t+1]??this.g,this.b=e[t+2]??this.b,this.a=e[t+3]??this.a,this}toString(e,t){const{r:s,g:i,b:r,a}=this;if(t||s>1||i>1||r>1)return`${s.toFixed(3)}, ${i.toFixed(3)}, ${r.toFixed(3)}, ${a.toFixed(3)}`;let n=`#${((1<<24)+(Math.round(s*255)<<16)+(Math.round(i*255)<<8)+Math.round(r*255)).toString(16).slice(1)}`;if(e===!0){const o=Math.round(a*255).toString(16);this.a<16/255?n+=`0${o}`:n+=o}return n}toArray(e=[],t=0,s=!0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,s&&(e[t+3]=this.a),e}static BLACK=Object.freeze(new Q(0,0,0,1));static BLUE=Object.freeze(new Q(0,0,1,1));static CYAN=Object.freeze(new Q(0,1,1,1));static GRAY=Object.freeze(new Q(.5,.5,.5,1));static GREEN=Object.freeze(new Q(0,1,0,1));static MAGENTA=Object.freeze(new Q(1,0,1,1));static RED=Object.freeze(new Q(1,0,0,1));static WHITE=Object.freeze(new Q(1,1,1,1));static YELLOW=Object.freeze(new Q(1,1,0,1))}class Rx{_curve;_left=-1/0;_right=1/0;_recip=0;_p0=0;_p1=0;_m0=0;_m1=0;constructor(e,t=0){this._curve=e,this._reset(t)}evaluate(e,t=!1){(t||e<this._left||e>=this._right)&&this._reset(e);let s;const i=this._curve.type;if(i===SE)s=this._p0;else{const r=this._recip===0?0:(e-this._left)*this._recip;i===vE?s=H.lerp(this._p0,this._p1,r):i===H_?s=H.lerp(this._p0,this._p1,r*r*(3-2*r)):s=this._evaluateHermite(this._p0,this._p1,this._m0,this._m1,r)}return s}_reset(e){const t=this._curve.keys,s=t.length;if(!s)this._left=-1/0,this._right=1/0,this._recip=0,this._p0=this._p1=this._m0=this._m1=0;else if(e<t[0][0])this._left=-1/0,this._right=t[0][0],this._recip=0,this._p0=this._p1=t[0][1],this._m0=this._m1=0;else if(e>=t[s-1][0])this._left=t[s-1][0],this._right=1/0,this._recip=0,this._p0=this._p1=t[s-1][1],this._m0=this._m1=0;else{let i=0;for(;e>=t[i+1][0];)i++;this._left=t[i][0],this._right=t[i+1][0];const r=1/(this._right-this._left);this._recip=isFinite(r)?r:0,this._p0=t[i][1],this._p1=t[i+1][1],this._curve.type===pv&&this._calcTangents(t,i)}}_calcTangents(e,t){let s;const i=e[t],r=e[t+1];let a;if(t===0?s=[e[0][0]+(e[0][0]-e[1][0]),e[0][1]+(e[0][1]-e[1][1])]:s=e[t-1],t===e.length-2?a=[e[t+1][0]+(e[t+1][0]-e[t][0]),e[t+1][1]+(e[t+1][1]-e[t][1])]:a=e[t+2],this._curve.type===pv){const n=2*(r[0]-i[0])/(r[0]-s[0]),o=2*(r[0]-i[0])/(a[0]-i[0]);this._m0=this._curve.tension*(isFinite(n)?n:0)*(r[1]-s[1]),this._m1=this._curve.tension*(isFinite(o)?o:0)*(a[1]-i[1])}else{const n=(r[0]-i[0])/(i[0]-s[0]),o=(r[0]-i[0])/(a[0]-r[0]),c=i[1]+(s[1]-i[1])*(isFinite(n)?n:0),h=r[1]+(a[1]-r[1])*(isFinite(o)?o:0),d=this._curve.tension;this._m0=d*(r[1]-c),this._m1=d*(h-i[1])}}_evaluateHermite(e,t,s,i,r){const a=r*r,n=r+r,o=1-r,c=o*o;return e*((1+n)*c)+s*(r*c)+t*(a*(3-n))+i*(a*(r-1))}}class _i{keys=[];type=H_;tension=.5;_eval=new Rx(this);constructor(e){if(e)for(let t=0;t<e.length-1;t+=2)this.keys.push([e[t],e[t+1]]);this.sort()}get length(){return this.keys.length}add(e,t){const s=this.keys,i=s.length;let r=0;for(;r<i&&!(s[r][0]>e);r++);const a=[e,t];return this.keys.splice(r,0,a),a}get(e){return this.keys[e]}sort(){this.keys.sort((e,t)=>
2e[0]-t[0])}value(e){return this._eval.evaluate(e,!0)}closest(e){const t=this.keys,s=t.length;let i=2,r=null;for(let a=0;a<s;a++){const n=Math.abs(e-t[a][0]);if(i>=n)i=n,r=t[a];else break}return r}clone(){const e=new this.constructor;return e.keys=this.keys.map(t=>[...t]),e.type=this.type,e.tension=this.tension,e}quantize(e){e=Math.max(e,2);const t=new Float32Array(e),s=1/(e-1);t[0]=this._eval.evaluate(0,!0);for(let i=1;i<e;i++)t[i]=this._eval.evaluate(s*i);return t}quantizeClamped(e,t,s){const i=this.quantize(e);for(let r=0;r<i.length;++r)i[r]=Math.min(s,Math.max(t,i[r]));return i}}class Ya{curves=[];_type=H_;constructor(...e){if(e.length>1)for(let t=0;t<e.length;t++)this.curves.push(new _i(e[t]));else if(e.length===0)this.curves.push(new _i);else{const t=e[0];if(typeof t=="number")for(let s=0;s<t;s++)this.curves.push(new _i);else for(let s=0;s<t.length;s++)this.curves.push(new _i(t[s]))}}get length(){return this.curves.length}set type(e){this._type=e;for(let t=0;t<this.curves.length;t++)this.curves[t].type=e}get type(){return this._type}get(e){return this.curves[e]}value(e,t=[]){const s=this.curves.length;t.length=s;for(let i=0;i<s;i++)t[i]=this.curves[i].value(e);return t}clone(){const e=new this.constructor;e.curves=[];for(let t=0;t<this.curves.length;t++)e.curves.push(this.curves[t].clone());return e._type=this._type,e}quantize(e){e=Math.max(e,2);const t=this.curves.length,s=new Float32Array(e*t),i=1/(e-1);for(let r=0;r<t;r++){const a=new Rx(this.curves[r]);for(let n=0;n<e;n++)s[n*t+r]=a.evaluate(i*n)}return s}quantizeClamped(e,t,s){const i=this.quantize(e);for(let r=0;r<i.length;++r)i[r]=Math.min(s,Math.max(t,i[r]));return i}}const Nm=new Float32Array(1),mv=new Int32Array(Nm.buffer);class Ja{static float2Half(e){Nm[0]=e;const t=mv[0];let s=t>>16&32768,i=t>>12&2047;const r=t>>23&255;return r<103?s:r>142?(s|=31744,s|=(r===255?0:1)&&t&8388607,s):r<113?(i|=2048,s|=(i>>114-r)+(i>>113-r&1),s):(s|=r-112<<10|i>>1,s+=i&1,s)}static float2RGBA8(e,t){Nm[0]=e;const s=mv[0];t.r=(s>>24&255)/255,t.g=(s>>16&255)/255,t.b=(s>>8&255)/255,t.a=(s&255)/255}}class E{x;y;z;constructor(e=0,t=0,s=0){e.length===3?(this.x=e[0],this.y=e[1],this.z=e[2]):(this.x=e,this.y=t,this.z=s)}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}add2(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addScaled(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}clone(){const e=this.constructor;return new e(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}cross(e,t){const s=e.x,i=e.y,r=e.z,a=t.x,n=t.y,o=t.z;return this.x=i*o-n*r,this.y=r*a-o*s,this.z=s*n-a*i,this}distance(e){const t=this.x-e.x,s=this.y-e.y,i=this.z-e.z;return Math.sqrt(t*t+s*s+i*i)}div(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}div2(e,t){return this.x=e.x/t.x,this.y=e.y/t.y,this.z=e.z/t.z,this}divScalar(e){return this.x/=e,this.y/=e,this.z/=e,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}equals(e){return this.x===e.x&&this.y===e.y&&this.z===e.z}equalsApprox(e,t=1e-6){return Math.abs(this.x-e.x)<t&&Math.abs(this.y-e.y)<t&&Math.abs(this.z-e.z)<t}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}lerp(e,t,s){return this.x=e.x+s*(t.x-e.x),this.y=e.y+s*(t.y-e.y),this.z=e.z+s*(t.z-e.z),this}mul(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}mul2(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}mulScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}normalize(e=this){const t=e.x*e.x+e.y*e.y+e.z*e.z;if(t>0){const s=1/Math.sqrt(t);this.x=e.x*s,this.y=e.y*s,this.z=e.z*s}return this}floor(e=this){return this.x=Math.floor(e.x),this.y=Math.floor(e.y),this.z=Math.floor(e.z),this}ceil(e=this){return this.x=Math.ceil(e.x),this.y=Math.ceil(e.y),this.z=Math.ceil(e.z),this}round(e=this){return this.x=Math.round(e.x),this.y=Math.round(e.y),this.z=Math.round(e.z),this}min(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),e.z<this.z&&(this.z=e.z),this}max(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),this}project(e){const t=this.x*e.x+this.y*e.y+this.z*e.z,s=e.x*e.x+e.y*e.y+e.z*e.z,i=t/s;return this.x=e.x*i,this.y=e.y*i,this.z=e.z*i,this}set(e,t,s){return this.x=e,this.y=t,this.z=s,this}
2sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}sub2(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}fromArray(e,t=0){return this.x=e[t]??this.x,this.y=e[t+1]??this.y,this.z=e[t+2]??this.z,this}toString(){return`[${this.x}, ${this.y}, ${this.z}]`}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}static ZERO=Object.freeze(new E(0,0,0));static HALF=Object.freeze(new E(.5,.5,.5));static ONE=Object.freeze(new E(1,1,1));static UP=Object.freeze(new E(0,1,0));static DOWN=Object.freeze(new E(0,-1,0));static RIGHT=Object.freeze(new E(1,0,0));static LEFT=Object.freeze(new E(-1,0,0));static FORWARD=Object.freeze(new E(0,0,-1));static BACK=Object.freeze(new E(0,0,1))}class xi{data=new Float32Array(9);constructor(){this.data[0]=this.data[4]=this.data[8]=1}clone(){const e=this.constructor;return new e().copy(this)}copy(e){const t=e.data,s=this.data;return s[0]=t[0],s[1]=t[1],s[2]=t[2],s[3]=t[3],s[4]=t[4],s[5]=t[5],s[6]=t[6],s[7]=t[7],s[8]=t[8],this}set(e){const t=this.data;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],this}getX(e=new E){return e.set(this.data[0],this.data[1],this.data[2])}getY(e=new E){return e.set(this.data[3],this.data[4],this.data[5])}getZ(e=new E){return e.set(this.data[6],this.data[7],this.data[8])}equals(e){const t=this.data,s=e.data;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]}isIdentity(){const e=this.data;return e[0]===1&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===1&&e[5]===0&&e[6]===0&&e[7]===0&&e[8]===1}setIdentity(){const e=this.data;return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,this}toString(){return`[${this.data.join(", ")}]`}transpose(e=this){const t=e.data,s=this.data;if(t===s){let i;i=t[1],s[1]=t[3],s[3]=i,i=t[2],s[2]=t[6],s[6]=i,i=t[5],s[5]=t[7],s[7]=i}else s[0]=t[0],s[1]=t[3],s[2]=t[6],s[3]=t[1],s[4]=t[4],s[5]=t[7],s[6]=t[2],s[7]=t[5],s[8]=t[8];return this}setFromMat4(e){const t=e.data,s=this.data;return s[0]=t[0],s[1]=t[1],s[2]=t[2],s[3]=t[4],s[4]=t[5],s[5]=t[6],s[6]=t[8],s[7]=t[9],s[8]=t[10],this}setFromQuat(e){const t=e.x,s=e.y,i=e.z,r=e.w,a=t+t,n=s+s,o=i+i,c=t*a,h=t*n,d=t*o,u=s*n,f=s*o,p=i*o,m=r*a,_=r*n,g=r*o,v=this.data;return v[0]=1-(u+p),v[1]=h+g,v[2]=d-_,v[3]=h-g,v[4]=1-(c+p),v[5]=f+m,v[6]=d+_,v[7]=f-m,v[8]=1-(c+u),this}invertMat4(e){const t=e.data,s=t[0],i=t[1],r=t[2],a=t[4],n=t[5],o=t[6],c=t[8],h=t[9],d=t[10],u=d*n-o*h,f=-d*i+r*h,p=o*i-r*n,m=-d*a+o*c,_=d*s-r*c,g=-o*s+r*a,v=h*a-n*c,x=-h*s+i*c,y=n*s-i*a,S=s*u+i*m+r*v;if(S===0)this.setIdentity();else{const T=1/S,w=this.data;w[0]=u*T,w[1]=f*T,w[2]=p*T,w[3]=m*T,w[4]=_*T,w[5]=g*T,w[6]=v*T,w[7]=x*T,w[8]=y*T}return this}transformVector(e,t=new E){const s=this.data,{x:i,y:r,z:a}=e;return t.x=i*s[0]+r*s[3]+a*s[6],t.y=i*s[1]+r*s[4]+a*s[7],t.z=i*s[2]+r*s[5]+a*s[8],t}static IDENTITY=Object.freeze(new xi);static ZERO=Object.freeze(new xi().set([0,0,0,0,0,0,0,0,0]))}class j{x;y;constructor(e=0,t=0){e.length===2?(this.x=e[0],this.y=e[1]):(this.x=e,this.y=t)}add(e){return this.x+=e.x,this.y+=e.y,this}add2(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addScaled(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}clone(){const e=this.constructor;return new e(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}cross(e){return this.x*e.y-this.y*e.x}distance(e){const t=this.x-e.x,s=this.y-e.y;return Math.sqrt(t*t+s*s)}div(e){return this.x/=e.x,this.y/=e.y,this}div2(e,t){return this.x=e.x/t.x,this.y=e.y/t.y,this}divScalar(e){return this.x/=e,this.y/=e,this}dot(e){return this.x*e.x+this.y*e.y}equals(e){return this.x===e.x&&this.y===e.y}equalsApprox(e,t=1e-6){return Math.abs(this.x-e.x)<t&&Math.abs(this.y-e.y)<t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSq(){return this.x*this.x+this.y*this.y}lerp(e,t,s){return this.x=e.x+s*(t.x-e.x),this.y=e.y+s*(t.y-e.y),this}mul(e){return this.x*=e.x,this.y*=e.y,this}mul2(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this}mulScalar(e){return this.x*=e,this.y*=e,this}normalize(e=this){const t=e.x*e.x+e.y*e.y;if(t>0){const s=1/Math.sqrt(t);this.x=e.x*s,this.y=e.y*s}return this}rotate(e){const t=Math.atan2(this.x,this.y)+e*H.DEG_TO_RAD,s=Math.sqrt(this.x*this.x+this.y*this.y);return this.x=Math.sin(t)*s,this.y=Math.cos(t)*s,this}angle(){return Math.atan2(this.x,this.y)*H.RAD_TO_DEG}angleTo(e){return Math.atan2(this.x*e.y+this.y*e.x,this.x*e.x+this.y*e.y)*H.RAD_TO_DEG}floor(e=this){return this.x=Math.floor(e.x),this.y=Math.floor(e.y),this}ceil(e=this){return this.x=Math.ceil(e.x),this.y=Math.ceil(e.y),this}
2round(e=this){return this.x=Math.round(e.x),this.y=Math.round(e.y),this}min(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),this}max(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),this}set(e,t){return this.x=e,this.y=t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}sub2(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}subScalar(e){return this.x-=e,this.y-=e,this}fromArray(e,t=0){return this.x=e[t]??this.x,this.y=e[t+1]??this.y,this}toString(){return`[${this.x}, ${this.y}]`}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}static angleRad(e,t){return Math.atan2(e.x*t.y-e.y*t.x,e.x*t.x+e.y*t.y)}static ZERO=Object.freeze(new j(0,0));static HALF=Object.freeze(new j(.5,.5));static ONE=Object.freeze(new j(1,1));static UP=Object.freeze(new j(0,1));static DOWN=Object.freeze(new j(0,-1));static RIGHT=Object.freeze(new j(1,0));static LEFT=Object.freeze(new j(-1,0))}class ie{x;y;z;w;constructor(e=0,t=0,s=0,i=0){e.length===4?(this.x=e[0],this.y=e[1],this.z=e[2],this.w=e[3]):(this.x=e,this.y=t,this.z=s,this.w=i)}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}add2(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}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addScaled(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}clone(){const e=this.constructor;return new e(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}div(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}div2(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}divScalar(e){return this.x/=e,this.y/=e,this.z/=e,this.w/=e,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}equals(e){return this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w}equalsApprox(e,t=1e-6){return Math.abs(this.x-e.x)<t&&Math.abs(this.y-e.y)<t&&Math.abs(this.z-e.z)<t&&Math.abs(this.w-e.w)<t}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}lerp(e,t,s){return this.x=e.x+s*(t.x-e.x),this.y=e.y+s*(t.y-e.y),this.z=e.z+s*(t.z-e.z),this.w=e.w+s*(t.w-e.w),this}mul(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}mul2(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}mulScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}normalize(e=this){const t=e.x*e.x+e.y*e.y+e.z*e.z+e.w*e.w;if(t>0){const s=1/Math.sqrt(t);this.x=e.x*s,this.y=e.y*s,this.z=e.z*s,this.w=e.w*s}return this}floor(e=this){return this.x=Math.floor(e.x),this.y=Math.floor(e.y),this.z=Math.floor(e.z),this.w=Math.floor(e.w),this}ceil(e=this){return this.x=Math.ceil(e.x),this.y=Math.ceil(e.y),this.z=Math.ceil(e.z),this.w=Math.ceil(e.w),this}round(e=this){return this.x=Math.round(e.x),this.y=Math.round(e.y),this.z=Math.round(e.z),this.w=Math.round(e.w),this}min(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),e.z<this.z&&(this.z=e.z),e.w<this.w&&(this.w=e.w),this}max(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this}set(e,t,s,i){return this.x=e,this.y=t,this.z=s,this.w=i,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}sub2(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}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}fromArray(e,t=0){return this.x=e[t]??this.x,this.y=e[t+1]??this.y,this.z=e[t+2]??this.z,this.w=e[t+3]??this.w,this}toString(){return`[${this.x}, ${this.y}, ${this.z}, ${this.w}]`}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}static ZERO=Object.freeze(new ie(0,0,0,0));static HALF=Object.freeze(new ie(.5,.5,.5,.5));static ONE=Object.freeze(new ie(1,1,1,1))}const nl=new j,ri=new E,Ai=new E,Pi=new E,uh=new E;class Z{data=new Float32Array(16);constructor(){this.data[0]=this.data[5]=this.data[10]=this.data[15]=1}static _getPerspectiveHalfSize(e,t,s,i,r){r?(e.x=i*Math.tan(t*Math.PI/360),e.y=e.x/s):(e.y=i*Math.tan(t*Math.PI/360),e.x=e.y*s)}add2(e,t){const s=e.data,i=t.data,r=this.data;return r[0]=s[0]+i[0],r[1]=s[1]+i[1],r[2]=s[2]+i[2],r[3]=s[3]+i[3],r[4]=s[4]+i[4],r[5]=s[5]+i[5],r[6]=s[6]+i[6],r[7]=s[7]+i[7],r[8]=s[8]+i[8],r[9]=s[9]+i[9],r[10]=s[10]+i[10],r[11]=s[11]+i[11],r[12]=s[12]+i[12],r[13]=s[13]+i[13],r[14]=s[14]+i[14],r[15]=s[15]+i[15],this}add(e){return this.add2(this,e)}clone(){const e=this.constructor;return new e().copy(this)}copy(e){const t=e.data,s=this.data;return s[0]=t[0],s[1]=t[1],s[2]=t[2],s[3]=t[3],s[4]=t[4],s[5]=t[5],s[6]=t[6],s[7]=t[7],s[8]=t[8],s[9]=t[9],s[10]=t[10],s[11]=t[11],s[12]=t[12],s[13]=t[13],s[14]=t[14],s[15]=t[15],this}equals(e){const t=this.data,s=e.data;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]}isIdentity(){const e=this.data;return e[0]===1&&e[1]===0&&e[2]===0&&e[3]===0&&e[4]===0&&e[5]===1&&e[6]===0&&e[7]===0&&e[8]===0&&e[9]===0&&e[10
2]===1&&e[11]===0&&e[12]===0&&e[13]===0&&e[14]===0&&e[15]===1}mul2(e,t){const s=e.data,i=t.data,r=this.data,a=s[0],n=s[1],o=s[2],c=s[3],h=s[4],d=s[5],u=s[6],f=s[7],p=s[8],m=s[9],_=s[10],g=s[11],v=s[12],x=s[13],y=s[14],S=s[15];let T,w,C,b;return T=i[0],w=i[1],C=i[2],b=i[3],r[0]=a*T+h*w+p*C+v*b,r[1]=n*T+d*w+m*C+x*b,r[2]=o*T+u*w+_*C+y*b,r[3]=c*T+f*w+g*C+S*b,T=i[4],w=i[5],C=i[6],b=i[7],r[4]=a*T+h*w+p*C+v*b,r[5]=n*T+d*w+m*C+x*b,r[6]=o*T+u*w+_*C+y*b,r[7]=c*T+f*w+g*C+S*b,T=i[8],w=i[9],C=i[10],b=i[11],r[8]=a*T+h*w+p*C+v*b,r[9]=n*T+d*w+m*C+x*b,r[10]=o*T+u*w+_*C+y*b,r[11]=c*T+f*w+g*C+S*b,T=i[12],w=i[13],C=i[14],b=i[15],r[12]=a*T+h*w+p*C+v*b,r[13]=n*T+d*w+m*C+x*b,r[14]=o*T+u*w+_*C+y*b,r[15]=c*T+f*w+g*C+S*b,this}mulAffine2(e,t){const s=e.data,i=t.data,r=this.data,a=s[0],n=s[1],o=s[2],c=s[4],h=s[5],d=s[6],u=s[8],f=s[9],p=s[10],m=s[12],_=s[13],g=s[14];let v,x,y;return v=i[0],x=i[1],y=i[2],r[0]=a*v+c*x+u*y,r[1]=n*v+h*x+f*y,r[2]=o*v+d*x+p*y,r[3]=0,v=i[4],x=i[5],y=i[6],r[4]=a*v+c*x+u*y,r[5]=n*v+h*x+f*y,r[6]=o*v+d*x+p*y,r[7]=0,v=i[8],x=i[9],y=i[10],r[8]=a*v+c*x+u*y,r[9]=n*v+h*x+f*y,r[10]=o*v+d*x+p*y,r[11]=0,v=i[12],x=i[13],y=i[14],r[12]=a*v+c*x+u*y+m,r[13]=n*v+h*x+f*y+_,r[14]=o*v+d*x+p*y+g,r[15]=1,this}mul(e){return this.mul2(this,e)}transformPoint(e,t=new E){const s=this.data,{x:i,y:r,z:a}=e;return t.x=i*s[0]+r*s[4]+a*s[8]+s[12],t.y=i*s[1]+r*s[5]+a*s[9]+s[13],t.z=i*s[2]+r*s[6]+a*s[10]+s[14],t}transformVector(e,t=new E){const s=this.data,{x:i,y:r,z:a}=e;return t.x=i*s[0]+r*s[4]+a*s[8],t.y=i*s[1]+r*s[5]+a*s[9],t.z=i*s[2]+r*s[6]+a*s[10],t}transformVec4(e,t=new ie){const s=this.data,{x:i,y:r,z:a,w:n}=e;return t.x=i*s[0]+r*s[4]+a*s[8]+n*s[12],t.y=i*s[1]+r*s[5]+a*s[9]+n*s[13],t.z=i*s[2]+r*s[6]+a*s[10]+n*s[14],t.w=i*s[3]+r*s[7]+a*s[11]+n*s[15],t}setLookAt(e,t,s){Pi.sub2(e,t).normalize(),Ai.copy(s).normalize(),ri.cross(Ai,Pi).normalize(),Ai.cross(Pi,ri);const i=this.data;return i[0]=ri.x,i[1]=ri.y,i[2]=ri.z,i[3]=0,i[4]=Ai.x,i[5]=Ai.y,i[6]=Ai.z,i[7]=0,i[8]=Pi.x,i[9]=Pi.y,i[10]=Pi.z,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}setFrustum(e,t,s,i,r,a){const n=2*r,o=t-e,c=i-s,h=a-r,d=this.data;return d[0]=n/o,d[1]=0,d[2]=0,d[3]=0,d[4]=0,d[5]=n/c,d[6]=0,d[7]=0,d[8]=(t+e)/o,d[9]=(i+s)/c,d[10]=(-a-r)/h,d[11]=-1,d[12]=0,d[13]=0,d[14]=-n*a/h,d[15]=0,this}setPerspective(e,t,s,i,r){return Z._getPerspectiveHalfSize(nl,e,t,s,r),this.setFrustum(-nl.x,nl.x,-nl.y,nl.y,s,i)}setOrtho(e,t,s,i,r,a){const n=this.data;return n[0]=2/(t-e),n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2/(i-s),n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=-2/(a-r),n[11]=0,n[12]=-(t+e)/(t-e),n[13]=-(i+s)/(i-s),n[14]=-(a+r)/(a-r),n[15]=1,this}setFromAxisAngle(e,t){t*=H.DEG_TO_RAD;const{x:s,y:i,z:r}=e,a=Math.cos(t),n=Math.sin(t),o=1-a,c=o*s,h=o*i,d=this.data;return d[0]=c*s+a,d[1]=c*i+n*r,d[2]=c*r-n*i,d[3]=0,d[4]=c*i-n*r,d[5]=h*i+a,d[6]=h*r+n*s,d[7]=0,d[8]=c*r+n*i,d[9]=h*r-s*n,d[10]=o*r*r+a,d[11]=0,d[12]=0,d[13]=0,d[14]=0,d[15]=1,this}setTranslate(e,t,s){const i=this.data;return i[0]=1,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=1,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=1,i[11]=0,i[12]=e,i[13]=t,i[14]=s,i[15]=1,this}setScale(e,t,s){const i=this.data;return i[0]=e,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=t,i[6]=0,i[7]=0,i[8]=0,i[9]=0,i[10]=s,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,this}setViewport(e,t,s,i){const r=this.data;return r[0]=s*.5,r[1]=0,r[2]=0,r[3]=0,r[4]=0,r[5]=i*.5,r[6]=0,r[7]=0,r[8]=0,r[9]=0,r[10]=.5,r[11]=0,r[12]=e+s*.5,r[13]=t+i*.5,r[14]=.5,r[15]=1,this}setReflection(e,t){const s=e.x,i=e.y,r=e.z,a=this.data;return a[0]=1-2*s*s,a[1]=-2*s*i,a[2]=-2*s*r,a[3]=0,a[4]=-2*s*i,a[5]=1-2*i*i,a[6]=-2*i*r,a[7]=0,a[8]=-2*s*r,a[9]=-2*i*r,a[10]=1-2*r*r,a[11]=0,a[12]=-2*s*t,a[13]=-2*i*t,a[14]=-2*r*t,a[15]=1,this}invert(e=this){const t=e.data,s=t[0],i=t[1],r=t[2],a=t[3],n=t[4],o=t[5],c=t[6],h=t[7],d=t[8],u=t[9],f=t[10],p=t[11],m=t[12],_=t[13],g=t[14],v=t[15],x=s*o-i*n,y=s*c-r*n,S=s*h-a*n,T=i*c-r*o,w=i*h-a*o,C=r*h-a*c,b=d*_-u*m,I=d*g-f*m,P=d*v-p*m,L=u*g-f*_,O=u*v-p*_,D=f*v-p*g,N=x*D-y*O+S*L+T*P-w*I+C*b;if(N===0)this.setIdentity();
2else{const k=1/N,A=this.data;A[0]=(o*D-c*O+h*L)*k,A[1]=(-i*D+r*O-a*L)*k,A[2]=(_*C-g*w+v*T)*k,A[3]=(-u*C+f*w-p*T)*k,A[4]=(-n*D+c*P-h*I)*k,A[5]=(s*D-r*P+a*I)*k,A[6]=(-m*C+g*S-v*y)*k,A[7]=(d*C-f*S+p*y)*k,A[8]=(n*O-o*P+h*b)*k,A[9]=(-s*O+i*P-a*b)*k,A[10]=(m*w-_*S+v*x)*k,A[11]=(-d*w+u*S-p*x)*k,A[12]=(-n*L+o*I-c*b)*k,A[13]=(s*L-i*I+r*b)*k,A[14]=(-m*T+_*y-g*x)*k,A[15]=(d*T-u*y+f*x)*k}return this}set(e){const t=this.data;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],this}setIdentity(){const e=this.data;return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}setTRS(e,t,s){const i=t.x,r=t.y,a=t.z,n=t.w,o=s.x,c=s.y,h=s.z,d=i+i,u=r+r,f=a+a,p=i*d,m=i*u,_=i*f,g=r*u,v=r*f,x=a*f,y=n*d,S=n*u,T=n*f,w=this.data;return w[0]=(1-(g+x))*o,w[1]=(m+T)*o,w[2]=(_-S)*o,w[3]=0,w[4]=(m-T)*c,w[5]=(1-(p+x))*c,w[6]=(v+y)*c,w[7]=0,w[8]=(_+S)*h,w[9]=(v-y)*h,w[10]=(1-(p+g))*h,w[11]=0,w[12]=e.x,w[13]=e.y,w[14]=e.z,w[15]=1,this}transpose(e=this){const t=e.data,s=this.data;if(t===s){let i;i=t[1],s[1]=t[4],s[4]=i,i=t[2],s[2]=t[8],s[8]=i,i=t[3],s[3]=t[12],s[12]=i,i=t[6],s[6]=t[9],s[9]=i,i=t[7],s[7]=t[13],s[13]=i,i=t[11],s[11]=t[14],s[14]=i}else s[0]=t[0],s[1]=t[4],s[2]=t[8],s[3]=t[12],s[4]=t[1],s[5]=t[5],s[6]=t[9],s[7]=t[13],s[8]=t[2],s[9]=t[6],s[10]=t[10],s[11]=t[14],s[12]=t[3],s[13]=t[7],s[14]=t[11],s[15]=t[15];return this}getTranslation(e=new E){return e.set(this.data[12],this.data[13],this.data[14])}getX(e=new E){return e.set(this.data[0],this.data[1],this.data[2])}getY(e=new E){return e.set(this.data[4],this.data[5],this.data[6])}getZ(e=new E){return e.set(this.data[8],this.data[9],this.data[10])}getScale(e=new E){return this.getX(ri),this.getY(Ai),this.getZ(Pi),e.set(ri.length(),Ai.length(),Pi.length()),e}get scaleSign(){return this.getX(ri),this.getY(Ai),this.getZ(Pi),ri.cross(ri,Ai),ri.dot(Pi)<0?-1:1}setFromEulerAngles(e,t,s){e*=H.DEG_TO_RAD,t*=H.DEG_TO_RAD,s*=H.DEG_TO_RAD;const i=Math.sin(-e),r=Math.cos(-e),a=Math.sin(-t),n=Math.cos(-t),o=Math.sin(-s),c=Math.cos(-s),h=this.data;return h[0]=n*c,h[1]=-n*o,h[2]=a,h[3]=0,h[4]=r*o+c*i*a,h[5]=r*c-i*a*o,h[6]=-n*i,h[7]=0,h[8]=i*o-r*c*a,h[9]=c*i+r*a*o,h[10]=r*n,h[11]=0,h[12]=0,h[13]=0,h[14]=0,h[15]=1,this}getEulerAngles(e=new E){this.getScale(uh);const t=uh.x,s=uh.y,i=uh.z;if(t===0||s===0||i===0)return e.set(0,0,0);const r=this.data,a=Math.asin(-r[2]/t),n=Math.PI*.5;let o,c;return a<n?a>-n?(o=Math.atan2(r[6]/s,r[10]/i),c=Math.atan2(r[1]/t,r[0]/t)):(c=0,o=-Math.atan2(r[4]/s,r[5]/s)):(c=0,o=Math.atan2(r[4]/s,r[5]/s)),e.set(o,a,c).mulScalar(H.RAD_TO_DEG)}toString(){return`[${this.data.join(", ")}]`}static IDENTITY=Object.freeze(new Z);static ZERO=Object.freeze(new Z().set([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]))}class ae{x;y;z;w;constructor(e=0,t=0,s=0,i=1){e.length===4?(this.x=e[0],this.y=e[1],this.z=e[2],this.w=e[3]):(this.x=e,this.y=t,this.z=s,this.w=i)}clone(){const e=this.constructor;return new e(this.x,this.y,this.z,this.w)}conjugate(e=this){return this.x=e.x*-1,this.y=e.y*-1,this.z=e.z*-1,this.w=e.w,this}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}equals(e){return this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w}equalsApprox(e,t=1e-6){return Math.abs(this.x-e.x)<t&&Math.abs(this.y-e.y)<t&&Math.abs(this.z-e.z)<t&&Math.abs(this.w-e.w)<t}getAxisAngle(e){let t=Math.acos(this.w)*2;const s=Math.sin(t/2);return s!==0?(e.x=this.x/s,e.y=this.y/s,e.z=this.z/s,(e.x<0||e.y<0||e.z<0)&&(e.x*=-1,e.y*=-1,e.z*=-1,t*=-1)):(e.x=1,e.y=0,e.z=0),t*H.RAD_TO_DEG}getEulerAngles(e=new E){let t,s,i;const r=this.x,a=this.y,n=this.z,o=this.w,c=2*(o*a-r*n);return c<=-.99999?(t=2*Math.atan2(r,o),s=-Math.PI/2,i=0):c>=.99999?(t=2*Math.atan2(r,o),s=Math.PI/2,i=0):(t=Math.atan2(2*(o*r+a*n),1-2*(r*r+a*a)),s=Math.asin(c),i=Math.atan2(2*(o*n+r*a),1-2*(a*a+n*n))),e.set(t,s,i).mulScalar(H.RAD_TO_DEG)}invert(e=this){return this.conjugate(e).normalize()}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}lerp(e,t,s){const i=(1-s)*(e.dot(t)<0?-1:1);return this.x=e.x*i+t.x*s,this.y=e.y*i+t.y*s,this.z=e.z*i+t.z*s,this.w=e.w*i+t.w*s,this.normalize()}mul(e){const t=this.x,s=this.y,i=this.z,r=this.w,a=e.x,n=e.y,o=e.z,c=e.w;return this.x=r*a+t*c+s*o-i*n,this.y=r*n+s*c+i*a-t*o,this.z=r*o+i*c+t*n-s*a,this.w=r*c-t*a-s*n-i*o,this}
2mulScalar(e,t=this){return this.x=t.x*e,this.y=t.y*e,this.z=t.z*e,this.w=t.w*e,this}mul2(e,t){const s=e.x,i=e.y,r=e.z,a=e.w,n=t.x,o=t.y,c=t.z,h=t.w;return this.x=a*n+s*h+i*c-r*o,this.y=a*o+i*h+r*n-s*c,this.z=a*c+r*h+s*o-i*n,this.w=a*h-s*n-i*o-r*c,this}normalize(e=this){let t=e.length();return t===0?(this.x=this.y=this.z=0,this.w=1):(t=1/t,this.x=e.x*t,this.y=e.y*t,this.z=e.z*t,this.w=e.w*t),this}set(e,t,s,i){return this.x=e,this.y=t,this.z=s,this.w=i,this}setFromAxisAngle(e,t){t*=.5*H.DEG_TO_RAD;const s=Math.sin(t),i=Math.cos(t);return this.x=s*e.x,this.y=s*e.y,this.z=s*e.z,this.w=i,this}setFromEulerAngles(e,t,s){if(e instanceof E){const d=e;e=d.x,t=d.y,s=d.z}const i=.5*H.DEG_TO_RAD;e*=i,t*=i,s*=i;const r=Math.sin(e),a=Math.cos(e),n=Math.sin(t),o=Math.cos(t),c=Math.sin(s),h=Math.cos(s);return this.x=r*o*h-a*n*c,this.y=a*n*h+r*o*c,this.z=a*o*c-r*n*h,this.w=a*o*h+r*n*c,this}setFromMat4(e){const t=e.data;let s=t[0],i=t[1],r=t[2],a=t[4],n=t[5],o=t[6],c=t[8],h=t[9],d=t[10];s*(n*d-o*h)-i*(a*d-o*c)+r*(a*h-n*c)<0&&(s=-s,i=-i,r=-r);let f;return f=s*s+i*i+r*r,f===0?this.set(0,0,0,1):(f=1/Math.sqrt(f),s*=f,i*=f,r*=f,f=a*a+n*n+o*o,f===0?this.set(0,0,0,1):(f=1/Math.sqrt(f),a*=f,n*=f,o*=f,f=c*c+h*h+d*d,f===0?this.set(0,0,0,1):(f=1/Math.sqrt(f),c*=f,h*=f,d*=f,d<0?s>n?this.set(1+s-n-d,i+a,c+r,o-h):this.set(i+a,1-s+n-d,o+h,c-r):s<-n?this.set(c+r,o+h,1-s-n+d,i-a):this.set(o-h,c-r,i-a,1+s+n+d),this.mulScalar(1/this.length()))))}setFromDirections(e,t){const s=1+e.dot(t);return s<Number.EPSILON?Math.abs(e.x)>Math.abs(e.y)?(this.x=-e.z,this.y=0,this.z=e.x,this.w=0):(this.x=0,this.y=-e.z,this.z=e.y,this.w=0):(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()}slerp(e,t,s){const i=e.x,r=e.y,a=e.z,n=e.w;let o=t.x,c=t.y,h=t.z,d=t.w,u=n*d+i*o+r*c+a*h;if(u<0&&(d=-d,o=-o,c=-c,h=-h,u=-u),Math.abs(u)>=1)return this.w=n,this.x=i,this.y=r,this.z=a,this;const f=Math.acos(u),p=Math.sqrt(1-u*u);if(Math.abs(p)<.001)return this.w=n*.5+d*.5,this.x=i*.5+o*.5,this.y=r*.5+c*.5,this.z=a*.5+h*.5,this;const m=Math.sin((1-s)*f)/p,_=Math.sin(s*f)/p;return this.w=n*m+d*_,this.x=i*m+o*_,this.y=r*m+c*_,this.z=a*m+h*_,this}transformVector(e,t=new E){const s=e.x,i=e.y,r=e.z,a=this.x,n=this.y,o=this.z,c=this.w,h=c*s+n*r-o*i,d=c*i+o*s-a*r,u=c*r+a*i-n*s,f=-a*s-n*i-o*r;return t.x=h*c+f*-a+d*-o-u*-n,t.y=d*c+f*-n+u*-a-h*-o,t.z=u*c+f*-o+h*-n-d*-a,t}fromArray(e,t=0){return this.x=e[t]??this.x,this.y=e[t+1]??this.y,this.z=e[t+2]??this.z,this.w=e[t+3]??this.w,this}toString(){return`[${this.x}, ${this.y}, ${this.z}, ${this.w}]`}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}static IDENTITY=Object.freeze(new ae(0,0,0,1));static ZERO=Object.freeze(new ae(0,0,0,0))}const bn=new E,An=new E,_v=new E,gv=new E,yE=new E;class Le{center=new E;halfExtents=new E(.5,.5,.5);_min=new E;_max=new E;constructor(e,t){e&&this.center.copy(e),t&&this.halfExtents.copy(t)}add(e){const t=this.center,s=t.x,i=t.y,r=t.z,a=this.halfExtents,n=a.x,o=a.y,c=a.z;let h=s-n,d=s+n,u=i-o,f=i+o,p=r-c,m=r+c;const _=e.center,g=_.x,v=_.y,x=_.z,y=e.halfExtents,S=y.x,T=y.y,w=y.z,C=g-S,b=g+S,I=v-T,P=v+T,L=x-w,O=x+w;C<h&&(h=C),b>d&&(d=b),I<u&&(u=I),P>f&&(f=P),L<p&&(p=L),O>m&&(m=O),t.x=(h+d)*.5,t.y=(u+f)*.5,t.z=(p+m)*.5,a.x=(d-h)*.5,a.y=(f-u)*.5,a.z=(m-p)*.5}copy(e){this.center.copy(e.center),this.halfExtents.copy(e.halfExtents)}clone(){return new Le(this.center,this.halfExtents)}intersects(e){const t=this.getMax(),s=this.getMin(),i=e.getMax(),r=e.getMin();return s.x<=i.x&&t.x>=r.x&&s.y<=i.y&&t.y>=r.y&&s.z<=i.z&&t.z>=r.z}_intersectsRay(e,t){const s=bn.copy(this.getMin()).sub(e.origin),i=An.copy(this.getMax()).sub(e.origin),r=e.direction;r.x===0?(s.x=s.x<0?-Number.MAX_VALUE:Number.MAX_VALUE,i.x=i.x<0?-Number.MAX_VALUE:Number.MAX_VALUE):(s.x/=r.x,i.x/=r.x),r.y===0?(s.y=s.y<0?-Number.MAX_VALUE:Number.MAX_VALUE,i.y=i.y<0?-Number.MAX_VALUE:Number.MAX_VALUE):(s.y/=r.y,i.y/=r.y),r.z===0?(s.z=s.z<0?-Number.MAX_VALUE:Number.MAX_VALUE,i.z=i.z<0?-Number.MAX_VALUE:Number.MAX_VALUE):(s.z/=r.z,i.z/=r.z);const a=_v.set(Math.min(s.x,i.x),Math.min(s.y,i.y),Math.min(s.z,i.z)),n=gv.set(Math.max(s.x,i.x),Math.max(s.y,i.y),Math.max(s.z,i.z)),o=Math.min(Math.min(n.x,n.y),n.z),c=Math.max(Math.max(a.x,a.y),a.z),h=o>=c&&c>=0;return h&&t.copy(e.direction).mulScalar(c).add(e.origin),h}_fastIntersectsRay(e){const t=bn,s=An,i=_v,r=gv,a=yE,n=e.direction;return t.sub2(e.origin,this.center),r.set(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z)),i.mul2(t,n),!(r.x>this.halfExtents.x&&i.x>=0||r.y>this.halfExtents.y&&i.y>=0||r.z>this.halfExtents.z&&i.z>=0||(a.set(Math.abs(n.x),Math.abs(n.y),Math.abs(n.z)),s.cross(n,t),s.set(Math.abs(s.x),Math.abs(s.y),Math.abs(s.z)),s.x>this.halfExtents.y*a.z+this.halfExtents.z*a.y)||s.y>this.halfExtents.x*a.z+this.halfExtents.z*a.x||s.z>this.halfExtents.x*a.y+this.halfExtents.y*a.x)}intersectsRay(e,t){return t?this._intersectsRay(e,t):this._fastIntersectsRay(e)}setMinMax(e,t){this.center.add2(t,e).mulScalar(.5),this.halfExtents.sub2(t,e).mulScalar(.5)}getMin(){return this._min.copy(this.center).sub(this.halfExtents)}getMax(){return this._max.copy(this.center).add(this.halfExtents)}containsPoint(e){const t=this.center,s=this.halfExtents;return!(e.x<t.x-s.x||e.x>t.x+s.x||e.y<t.y-s.y||e.y>t.y+s.y||e.z<t.z-s.z||e.z>t.z+s.z)}closestPoint(e,t=new E){const s=this.center,i=this.halfExtents;return t.set(Math.max(s.x-i.x,Math.min(e.x,s.x+i.x)),Math.max(s.y-i.y,Math.min(e.y,s.y+i.y)),Math.max(s.z-i.z,Math.min(e.z,s.z+i.z)))}setFromTransformedAabb(e,t,s=!1){const i=e.center,r=e.halfExtents,a=t.data;let n=a[0],o=a[4],c=a[8],h=a[1],d=a[5],u=a[9],f=a[2],p=a[6],m=a[10];if(s){let _=n*n+o*o+c*c;if(_>0){const g=1/Math.sqrt(_);n*=g,o*=g,c*=g}if(_=h*h+d*d+u*u,_>0){const g=1/Math.sqrt(_);h*=g,d*=g,u*=g}if(_=f*f+p*p+m*m,_>0){const g=1/Math.sqrt(_);f*=g,p*=g,m*=g}}this.center.set(a[12]+n*i.x+o*i.y+c*i.z,a[13]+h*i.x+d*i.y+u*i.z,a[14]+f*i.x+p*i.y+m*i.z),this.halfExtents.set(Math.abs(n)*r.x+Math.abs(o)*r.y+Math.abs(c)*r.z,Math.abs(h)*r.x+Math.abs(d)*r.y+Math.abs(u)*r.z,Math.abs(f)*r.x+Math.abs(p)*r.y+Math.abs(m)*r.z)}static computeMinMax(e,t,s,i=e.length/3){if(i>0){let r=e[0],a=e[1],n=e[2],o=r,c=a,h=n;const d=i*3;for(let u=3;u<d;u+=3){const f=e[u],p=e[u+1],m=e[u+2];f<r&&(r=f),p<a&&(a=p),m<n&&(n=m),f>o&&(o=f),p>c&&(c=p),m>h&&(h=m)}t.set(r,a,n),s.set(o,c,h)}}compute(e,t){Le.computeMinMax(e,bn,An,t),this.setMinMax(bn,An)}intersectsBoundingSphere(e){return this._distanceToBoundingSphereSq(e)<=e.radius*e.radiu
2s}_distanceToBoundingSphereSq(e){const t=this.getMin(),s=this.getMax();let i=0;const r=["x","y","z"];for(let a=0;a<3;++a){let n=0;const o=e.center[r[a]],c=t[r[a]],h=s[r[a]];let d=0;o<c&&(d=c-o,n+=d*d),o>h&&(d=o-h,n+=d*d),i+=n}return i}_expand(e,t){bn.add2(this.getMin(),e),An.add2(this.getMax(),t),this.setMinMax(bn,An)}}const fh=new E,xE=new E;class W_{center;radius;constructor(e=new E,t=.5){this.center=e,this.radius=t}containsPoint(e){const t=fh.sub2(e,this.center).lengthSq(),s=this.radius;return t<s*s}intersectsRay(e,t){const s=fh.copy(e.origin).sub(this.center),i=s.dot(xE.copy(e.direction).normalize()),r=s.dot(s)-this.radius*this.radius;if(r>0&&i>0)return!1;const a=i*i-r;if(a<0)return!1;const n=Math.abs(-i-Math.sqrt(a));return t&&t.copy(e.direction).mulScalar(n).add(e.origin),!0}intersectsBoundingSphere(e){fh.sub2(e.center,this.center);const t=e.radius+this.radius;return fh.lengthSq()<=t*t}}class Lx{normal=new E;distance;constructor(e=E.UP,t=0){this.normal.copy(e),this.distance=t}clone(){const e=this.constructor;return new e().copy(this)}copy(e){return this.normal.copy(e.normal),this.distance=e.distance,this}intersectsLine(e,t,s){const i=this.distance,r=this.normal.dot(e)+i,a=this.normal.dot(t)+i,n=r/(r-a),o=n>=0&&n<=1;return o&&s&&s.lerp(e,t,n),o}intersectsRay(e,t){const s=this.normal.dot(e.direction);if(s===0)return!1;const i=-(this.normal.dot(e.origin)+this.distance)/s;return i>=0&&t&&t.copy(e.direction).mulScalar(i).add(e.origin),i>=0}normalize(){const e=1/this.normal.length();return this.normal.mulScalar(e),this.distance*=e,this}set(e,t,s,i){return this.normal.set(e,t,s),this.distance=i,this}setFromPointNormal(e,t){return this.normal.copy(t),this.distance=-this.normal.dot(e),this}}class X_{planes=[];constructor(){for(let e=0;e<6;e++)this.planes[e]=new Lx}clone(){const e=this.constructor;return new e().copy(this)}copy(e){for(let t=0;t<6;t++)this.planes[t].copy(e.planes[t]);return this}setFromMat4(e){const t=e.data,s=t[0],i=t[1],r=t[2],a=t[3],n=t[4],o=t[5],c=t[6],h=t[7],d=t[8],u=t[9],f=t[10],p=t[11],m=t[12],_=t[13],g=t[14],v=t[15],x=this.planes;x[0].set(a-s,h-n,p-d,v-m).normalize(),x[1].set(a+s,h+n,p+d,v+m).normalize(),x[2].set(a+i,h+o,p+u,v+_).normalize(),x[3].set(a-i,h-o,p-u,v-_).normalize(),x[4].set(a-r,h-c,p-f,v-g).normalize(),x[5].set(a+r,h+c,p+f,v+g).normalize()}containsPoint(e){for(let t=0;t<6;t++){const{normal:s,distance:i}=this.planes[t];if(s.dot(e)+i<=0)return!1}return!0}add(e){const t=this.planes,s=e.planes;for(let i=0;i<6;i++)s[i].distance>t[i].distance&&t[i].copy(s[i]);return this}containsSphere(e){const{center:t,radius:s}=e;let i=0;for(let r=0;r<6;r++){const{normal:a,distance:n}=this.planes[r],o=a.dot(t)+n;if(o<=-s)return 0;o>s&&i++}return i===6?2:1}}class km{origin=new E;direction=E.FORWARD.clone();constructor(e,t){e&&this.origin.copy(e),t&&this.direction.copy(t)}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.set(e.origin,e.direction)}clone(){return new this.constructor(this.origin,this.direction)}}const Ft=0,ue=1,Iu=2,Y_=0,as=1,TE=2,Fx=4,wE=5,j_=6,q_=8,vi=0,CE=2,EE=3,bE=4,Ox=1,Si=4,ct=8,AE=16,PE=32,IE=64,$_=128,Po=256,Ys=0,Vd=1,DE=2,ME=3,Jl=1,ec=2,Gd=4,Yt=0,tc=1,Bx=2,RE=3,sc=0,LE=1,Fe=0,It=1,Ac=2,Pc=3,Ic=4,ia=5,FE=0,Hd=1,Wd=2,Um=3,OE=4,BE=5,NE=6,cr=7,zm=0,Ni=1,ra=2,kE=[1,2,4],K_=0,Z_=1,Du=2,Dc=3,Mu=4,Mc=5,Er=6,Re=7,Rc=8,Ru=9,Ho=10,Lc=11,Ge=12,Lu=13,mt=14,Ti=15,Oi=16,en=17,tn=18,Fu=19,us=20,Fc=21,Ou=22,Bu=23,Wo=24,Xo=25,Oc=26,Bc=27,Q_=28,J_=29,eg=30,Nu=31,ku=32,Uu=33,zu=34,Vu=35,Gu=36,js=37,Hu=38,tg=39,Wu=40,Xu=41,Yu=42,Nc=43,ju=44,sg=45,qu=46,Vi=47,$u=48,Wt=49,kc=50,Ku=51,Zu=52,Qu=53,Xd=54,Yd=55,jd=56,qd=61,$d=62,Kd=63,Ju=64,ig=65,rg=66,ag=67,Zd=68,ja=69,ef=70,tf=71,sf=72,rf=73,af=74,nf=75,fs=new Map([[K_,{name:"A8",size:1,ldr:!0}],[Zu,{name:"R8",size:1,ldr:!0}],[Z_,{name:"L8",size:1,ldr:!0}],[Du,{name:"LA8",size:2,ldr:!0}],[Qu,{name:"RG8",size:2,ldr:!0}],[Dc,{name:"RGB565",size:2,ldr:!0}],[Mu,{name:"RGBA5551",size:2,ldr:!0}],[Mc,{name:"RGBA4",size:2,ldr:!0}],[Er,{name:"RGB8",size:4,ldr:!0}],[Re,{name:"RGBA8",size:4,ldr:!0,srgbFormat:us}],[kc,{name:"R16F",size:2}],[Ku,{name:"RG16F",size:4}],[Lc,{name:"RGB16F",size:8}],[Ge,{name:"RGBA16F",size:8}],[Lu,{name:"RGB32F",size:16}],[mt,{name:"RGBA32F",size:16}],[Ti,{name:"R32F",size:4}],[ef,{name:"RG32F",size:8}],[tf,{name:"RGB9E5",size:4}],[sf,{name:"RG8S",size:2}],[rf,{name:"RGBA8S",size:4}],[af,{name:"RGB10A2",size:4}],[nf,{name:"RGB10A2U",size:4,isUint:!0}],[Oi,{name:"DEPTH",size:4}],[ja,{name:"DEPTH16",size:2}],[en,{name:"DEPTHSTENCIL",size:4}],[tn,{name:"111110F",size:4}],[Fu,{name:"SRGB8",size:4,ldr:!0,srgb:!0}],[us,{name:"SRGBA8",size:4,ldr:!0,srgb:!0}],[Nu,{name:"BGRA8",size:4,ldr:!0}],[Ju,{name:"SBGRA8",size:4,ldr:!0,srgb:!0}],[Rc,{name:"DXT1",blockSize:8,ldr:!0,srgbFormat:Xd}],[Ru,{name:"DXT3",blockSize:16,ldr:!0,srgbFormat:Yd}],[Ho,{name:"DXT5",blockSize:16,ldr:!0,srgbFormat:jd}],[Fc,{name:"ETC1",blockSize:8,ldr:!0}],[Ou,{name:"ETC2_RGB",blockSize:8,ldr:!0,srgbFormat:qd}],[Bu,{name:"ETC2_RGBA",blockSize:16,ldr:!0,srgbFormat:$d}],[Wo,{name:"PVRTC_2BPP_RGB_1",ldr:!0,blockSize:8}],[Xo,{name:"PVRTC_2BPP_RGBA_1",ldr:!0,blockSize:8}],[Oc,{name:"PVRTC_4BPP_RGB_1",ldr:!0,blockSize:8}],[Bc,{name:"PVRTC_4BPP_RGBA_1",ldr:!0,blockSize:8}],[Q_,{name:"ASTC_4x4",blockSize:16,ldr:!0,srgbFormat:Kd}],[J_,{name:"ATC_RGB",blockSize:8,ldr:!0}],[eg,{name:"ATC_RGBA",blockSize:16,ldr:!0}],[ig,{name:"BC6H_RGBF",blockSize:16}],[rg,{name:"BC6H_RGBUF",blockSize:16}],[ag,{name:"BC7_RGBA",blockSize:16,ldr:!0,srgbFormat:Zd}],[Xd,{name:"DXT1_SRGB",blockSize:8,ldr:!0,srgb:!0}],[Yd,{name:"DXT3_SRGBA",blockSize:16,ldr:!0,srgb:!0}],[jd,{name:"DXT5_SRGBA",blockSize:16,ldr:!0,srgb:!0}],[qd,{name:"ETC2_SRGB",blockSize:8,ldr:!0,srgb:!0}],[$d,{name:"ETC2_SRGBA",blockSize:16,ldr:!0,srgb:!0}],[Kd,{name:"ASTC_4x4_SRGB",blockSize:16,ldr:!0,srgb:!0}],[Zd,{name:"BC7_SRGBA",blockSize:16,ldr:!0,srgb:!0}],[ku,{name:"R8I",size:1,isInt:!0}],[zu,{name:"R16I",size:2,isInt:!0}],[Gu,{name:"R32I",size:4,isInt:!0}],[Hu,{name:"RG8I",size:2,isInt:!0}],[Wu,{name:"RG16I",size:4,isInt:!0}],[Yu,{name:"RG32I",size:8,isInt:!0}],[ju,{name:"RGBA8I",size:4,isInt:!0}],[qu,{name:"RGBA16I",size:8,isInt:!0}],[$u,{name:"RGBA32I",size:16,isInt:!0}],[Uu,{name:"R8U",size:1,isUint:!0}],[Vu,{name:"R16U",size:2,isUint:!0}],[js,{name:"R32U",size:4,isUint:!0}],[tg,{name:"RG8U",size:2,isUint:!0}],[Xu,{name:"RG16U",size:4,isUint:!0}],[Nc,{name:"RG32U",size:8,isUint:!0}],[sg,{name:"RGBA8U",size:4,isUint:!0}],[Vi,{name:"RGBA16U",size:8,isUint:!0}],[Wt,{name:"RGBA32U",size:16,isUint:!0}]]),Sd=l=>fs.get(l)?.blockSize!==void 0,Qd=l=>fs.get(l)?.srgb===!0,Qr=l=>{const e=fs.get(l);return e?.isInt===!0||e?.isUint===!0},UE={sampler:"sampler2D",returnType:"vec4"},zE={sampler:"usampler2D",returnType:"uvec4"},VE={sampler:"isampler2D",returnType:"ivec4"},GE={textureType:"texture_2d<f32>",returnType:"vec4f"},HE={textureType:"texture_2d<u32>",returnType:"vec4u"},WE={textureType:"texture_2d<i32>",returnType:"vec4i"},yd=l=>{const e=fs.get(l);return e?.isUint?zE:e?.isInt?VE:UE},ph=l=>{const e=fs.get(l);return e?.isUint?HE:e?.isInt?WE:GE},of=l=>fs.get(l)?.srgbFormat||l,XE=l=>{for(const[e,t]of fs)if(t.srgbFormat===l)return e;return l},YE=l=>{const e=fs.get(l);return!!(e?.ldr&&!e?.srgb)},ng=l=>{switch(l){case Ti:case ef:case Lu:case mt:return Float32Array;case Gu:case Yu:case $u:return Int32Array;case js:case Nc:case Wt:case tf:case af:case nf:return Uint32Array;case zu:case Wu:case qu:return Int16Array;
2case Vu:case Xu:case Vi:case Dc:case Mu:case Mc:case kc:case Ku:case Lc:case Ge:return Uint16Array;case ku:case Hu:case ju:case sf:case rf:return Int8Array;default:return Uint8Array}},lf=0,cf=1,Nx=2,og=3,qs=4,Tr=5,qa=6,Ie="POSITION",Cs="NORMAL",Gi="TANGENT",ki="BLENDWEIGHT",Bs="BLENDINDICES",ns="COLOR",vv="TEXCOORD",Zs="TEXCOORD0",pn="TEXCOORD1",Uc="TEXCOORD2",zc="TEXCOORD3",Vc="TEXCOORD4",Gc="TEXCOORD5",Hc="TEXCOORD6",Wc="TEXCOORD7",Vm="ATTR0",Jd="ATTR1",lg="ATTR2",cg="ATTR3",hg="ATTR4",jE="ATTR5",qE="ATTR6",$E="ATTR7",ic="ATTR8",rc="ATTR9",KE="ATTR10",dg="ATTR11",ug="ATTR12",ZE="ATTR13",fg="ATTR14",Io="ATTR15",QE=1,go=0,JE=2,eb=3,tb=5,qf=0,sb=1,Sv=2,Qs="default",wr="rgbm",eu="rgbe",ac="rgbp",nc="swizzleGGGR",kx="1d",ys="2d",hr="2d-array",dr="cube",tu="cube-array",vo="3d",ls=0,da=1,gi=2,aa=3,na=4,ib="none",Gm="cube",yv="equirect",rb="octahedral",ze="glsl",de="wgsl",ua=0,mr=1,fa=2,mn=3,Yo=4,Xc=5,je=6,hf=7,So=0,_r=1,me=2,sn=3,hs=4,Cr=5,$a=6,gr=7,Ka=8,oc=9,lc=10,cc=11,su=12,Do=13,Ss=14,ab=15,nb=16,df=17,ob=18,lb=19,cb=20,uf=21,ff=22,pg=23,Ux=24,hb=25,le=26,Mo=27,Ro=28,oa=29,Lo=30,pf=31,mf=32,Fo=33,_f=34,gf=35,Oo=36,vf=37,Sf=38,iu=39,mg=40,_g=41,db=42,ub=43,fb=44,pb=45,mb=46,_b=47,gb=48,vb=49,xv=["bool","int","float","vec2","vec3","vec4","ivec2","ivec3","ivec4","bvec2","bvec3","bvec4","mat2","mat3","mat4","sampler2D","samplerCube","","sampler2DShadow","samplerCubeShadow","sampler3D","","","","","sampler2DArray","uint","uvec2","uvec3","uvec4","","","","","","","","","","","","","isampler2D","usampler2D","isamplerCube","usamplerCube","isampler3D","usampler3D","isampler2DArray","usampler2DArray"],zx=[["bool"],["i32"],["f32"],["vec2f","vec2<f32>"],["vec3f","vec3<f32>"],["vec4f","vec4<f32>"],["vec2i","vec2<i32>"],["vec3i","vec3<i32>"],["vec4i","vec4<i32>"],["vec2<bool>"],["vec3<bool>"],["vec4<bool>"],["mat2x2f","mat2x2<f32>"],["mat3x3f","mat3x3<f32>"],["mat4x4f","mat4x4<f32>"],["texture_2d<f32>"],["texture_cube<f32>"],["array<f32>"],["texture_depth_2d"],["texture_depth_cube"],["texture_3d<f32>"],["array<vec2<f32>>"],["array<vec3<f32>>"],["array<vec4<f32>>"],["array<mat4x4<f32>>"],["texture_2d_array<f32>"],["u32"],["vec2u","vec2<u32>"],["vec3u","vec3<u32>"],["vec4u","vec4<u32>"],["array<i32>"],["array<u32>"],["array<bool>"],["array<vec2i>","array<vec2<i32>>"],["array<vec2u>","array<vec2<u32>>"],["array<vec2b>","array<vec2<bool>>"],["array<vec3i>","array<vec3<i32>>"],["array<vec3u>","array<vec3<u32>>"],["array<vec3b>","array<vec3<bool>>"],["array<vec4i>","array<vec4<i32>>"],["array<vec4u>","array<vec4<u32>>"],["array<vec4b>","array<vec4<bool>>"],["texture_2d<i32>"],["texture_2d<u32>"],["texture_cube<i32>"],["texture_cube<u32>"],["texture_3d<i32>"],["texture_3d<u32>"],["texture_2d_array<i32>"],["texture_2d_array<u32>"]],Vx=new Map;zx.forEach((l,e)=>{l.forEach(t=>Vx.set(t,e))});const xd="webgl2",Gx="webgpu",Tv="webgpu:bare",Td="null",rn=1,an=2,G=4,Sb="ldr",mh="ldr_srgb",yb="hdr",Hm=1,Hx=2,Wx=4,Xx=8,Yx=16,jx=32,qx=64,$x=128,xb=255,hc=0,Yc=1,Bo=2,Kx=["view","mesh","mesh_ub"],yf="default",gg="_unused_float_uniform",yo=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Uint16Array],Xl=[1,1,2,2,4,4,4,2],vg=[Uint8Array,Uint16Array,Uint32Array],Tb=[1,2,4],Zx=new Map([["float","f32"],["vec2","vec2f"],["vec3","vec3f"],["vec4","vec4f"],["int","i32"],["ivec2","vec2i"],["ivec3","vec3i"],["ivec4","vec4i"],["uint","u32"],["uvec2","vec2u"],["uvec3","vec3u"],["uvec4","vec4u"]]),Be={};Be[Ie]=0;Be[Cs]=1;Be[ki]=2;Be[Bs]=3;Be[ns]=4;Be[Zs]=5;Be[pn]=6;Be[Uc]=7;Be[zc]=8;Be[Vc]=9;Be[Gc]=10;Be[Hc]=11;Be[Wc]=12;Be[Gi]=13;Be[Vm]=0;Be[Jd]=1;Be[lg]=2;Be[cg]=3;Be[hg]=4;Be[jE]=5;Be[qE]=6;Be[$E]=7;Be[ic]=8;Be[rc]=9;Be[KE]=10;Be[dg]=11;Be[ug]=12;Be[ZE]=13;Be[fg]=14;Be[Io]=15;let wb=0;class xf{slot=-1;scopeId=null;constructor(e,t){this.name=e,this.visibility=t}}class At extends xf{}class q extends xf{format="";constructor(e,t,s=!1){super(e,t),this.readOnly=s}}class No extends xf{constructor(e,t,s=ys,i=ls,r=!0,a=null){super(e,t),this.textureDimension=s,this.sampleType=i,this.hasSampler=r,this.samplerName=a??`${e}_sampler`}}class wd extends xf{constructor(e,t=Re,s=ys,i=!0,r=!1){super(e,G),this.format=t,this.textureDimension=s,this.write=i,this.read=r}}class Ze{uniformBufferFormats=[];textureFormats=[];
2storageTextureFormats=[];storageBufferFormats=[];constructor(e,t){this.id=wb++;let s=0;t.forEach(r=>{r.slot=s++,r instanceof No&&r.hasSampler&&s++,r instanceof At?this.uniformBufferFormats.push(r):r instanceof No?this.textureFormats.push(r):r instanceof wd?this.storageTextureFormats.push(r):r instanceof q&&this.storageBufferFormats.push(r)}),this.device=e;const i=e.scope;this.bufferFormatsMap=new Map,this.uniformBufferFormats.forEach((r,a)=>this.bufferFormatsMap.set(r.name,a)),this.textureFormatsMap=new Map,this.textureFormats.forEach((r,a)=>{this.textureFormatsMap.set(r.name,a),r.scopeId=i.resolve(r.name)}),this.storageTextureFormatsMap=new Map,this.storageTextureFormats.forEach((r,a)=>{this.storageTextureFormatsMap.set(r.name,a),r.scopeId=i.resolve(r.name)}),this.storageBufferFormatsMap=new Map,this.storageBufferFormats.forEach((r,a)=>{this.storageBufferFormatsMap.set(r.name,a),r.scopeId=i.resolve(r.name)}),this.impl=e.createBindGroupFormatImpl(this)}destroy(){this.impl.destroy()}getTexture(e){const t=this.textureFormatsMap.get(e);return t!==void 0?this.textureFormats[t]:null}getStorageTexture(e){const t=this.storageTextureFormatsMap.get(e);return t!==void 0?this.storageTextureFormats[t]:null}loseContext(){}}class Jt{_cache=new Map;get(e,t){return this._cache.has(e)||(this._cache.set(e,t()),e.on("destroy",()=>{this.remove(e)}),e.on("devicelost",()=>{this._cache.get(e)?.loseContext?.(e)})),this._cache.get(e)}remove(e){this._cache.get(e)?.destroy?.(e),this._cache.delete(e)}}class Xt{static calcLevelDimension(e,t){return Math.max(e>>t,1)}static calcMipLevelsCount(e,t,s=1){return 1+Math.floor(Math.log2(Math.max(e,t,s)))}static calcLevelGpuSize(e,t,s,i){const r=fs.get(i),a=fs.get(i)?.size??0;if(a>0)return e*t*s*a;const n=r.blockSize??0;let o=Math.floor((e+3)/4);const c=Math.floor((t+3)/4),h=Math.floor((s+3)/4);return(i===Wo||i===Xo)&&(o=Math.max(Math.floor(o/2),1)),o*c*h*n}static calcGpuSize(e,t,s,i,r,a){let n=0;for(;n+=Xt.calcLevelGpuSize(e,t,s,i),!(!r||e===1&&t===1&&s===1);)e=Math.max(e>>1,1),t=Math.max(t>>1,1),s=Math.max(s>>1,1);return n*(a?6:1)}static calcTextureSize(e,t,s=1){let i=Math.ceil(Math.sqrt(e));return s>1&&(i=H.roundUp(i,s)),t.set(i,Math.ceil(e/i))}}class _n{map=new Map;id=0;get(e){let t=this.map.get(e);return t===void 0&&(t=this.id++,this.map.set(e,t)),t}}const Cb=new _n;class dc{texture;baseMipLevel;mipLevelCount;baseArrayLayer;arrayLayerCount;key;constructor(e,t=0,s=1,i=0,r=1){this.texture=e,this.baseMipLevel=t,this.mipLevelCount=s,this.baseArrayLayer=i,this.arrayLayerCount=r,this.key=Cb.get(`${t}:${s}:${i}:${r}`)}}let Eb=0;class ce{static createDataTexture2D(e,t,s,i,r,a){return new ce(e,{name:t,width:s,height:i,format:r,mipmaps:!1,minFilter:Fe,magFilter:Fe,addressU:ue,addressV:ue,levels:a})}name;_gpuSize=0;releaseSourceAfterUpload=!1;id=Eb++;_invalid=!1;_lockedLevel=-1;_lockedMode=qf;renderVersionDirty=0;_storage=!1;_numLevels=0;_numLevelsRequested;constructor(e,t={}){this.device=e,this.name=t.name??"",this._width=Math.floor(t.width??4),this._height=Math.floor(t.height??4),this._format=t.format??Re,this._compressed=Sd(this._format),this._integerFormat=Qr(this._format),this._integerFormat&&(t.minFilter=Fe,t.magFilter=Fe),this._volume=t.volume??!1,this._depth=Math.floor(t.depth??1),this._arrayLength=Math.floor(t.arrayLength??0),this._storage=t.storage??!1,this._cubemap=t.cubemap??!1,this._flipY=t.flipY??!1,this._premultiplyAlpha=t.premultiplyAlpha??!1,this._mipmaps=t.mipmaps??!0,this._numLevelsRequested=t.numLevels,t.numLevels!==void 0&&(this._numLevels=t.numLevels),this._updateNumLevels(),this._minFilter=t.minFilter??ia,this._magFilter=t.magFilter??It,this._anisotropy=t.anisotropy??1,this._addressU=t.addressU??Ft,this._addressV=t.addressV??Ft,this._addressW=t.addressW??Ft,this._compareOnRead=t.compareOnRead??!1,this._compareFunc=t.compareFunc??Hd,this._type=t.type??Qs,this.projection=ib,this._cubemap?this.projection=Gm:t.projection&&t.projection!==Gm&&(this.projection=t.projection),this._levels=t.levels;const s=!!t.levels;this._levels||this._clearLevels(),this.recreateImpl(s)}destroy(){const e=this.device;e&&(e.onTextureDestroyed(this),this.impl.destroy(e),this.adjustVramSizeTracking(e._vram,-this._gpuSize),this.releaseSourceAfterUpload&&this.releaseImageSources(),this._levels=null,this.device=null)}releaseImageSources(){if(this.releaseSourceAfterUpload=!1,!(typeof ImageBitmap>"u"||!this._levels))for(let e=0;e<this._levels.length;e++){const t=this._levels[e];if(t instanceof ImageBitmap)t.close(),this._levels[e]=null;else if(Array.isArray(t))for(let s=0;s<t.length;s++)t[s]instanceof ImageBitmap&&(t[s].close(),t[s]=null)}}setReleaseSourceAfterUpload(){this.releaseSourceAfterUpload=!0,!this._needsUpload&&!this._needsMipmapsUpload&&this.releaseImageSources()}recreateImpl(e=!0){const{device:t}=this;this.impl?.destroy(t),this.impl=null,this.impl=t.createTextureImpl(this),this.dirtyAll(),e&&this.upload()}_clearLevels(){this._levels=this._cubemap?[[null,null,null,null,null,null]]:[null]}resize(e,t,s=1){if(this.width!==e||this.height!==t||this.depth!==s){const i=this.device;this.adjustVramSizeTracking(i._vram,-this._gpuSize),this._gpuSize=0,this.impl.destroy(i),this._clearLevels(),this._width=Math.floor(e),this._height=Math.floor(t),this._depth=Math.floor(s),this._updateNumLevels(),this.impl=i.createTextureImpl(this),this.dirtyAll()}}loseContext(){this.impl.loseContext(),this.dirtyAll()}adjustVramSizeTracking(e,t){e.tex+=t}propertyChanged(e){this.impl.propertyChanged(e),this.renderVersionDirty=this.device.renderVersion}_updateNumLevels(){const e=this.mipmaps?Xt.calcMipLevelsCount(this.width,this.height):1,t=this._numLevelsRequested;this._numLevels=Math.min(t??e,e),this._mipmaps=this._numLevels>1}get lockedMode(){return this._lockedMode}set minFilter(e){this._minFilter!==e&&(Qr(this._format)||(this._minFilter=e,this.propertyChanged(Hm)))}get minFilter(){return this._minFilter}set magFilter(e){this._magFilter!==e&&(Qr(this._format)||(this._magFilter=e,this.propertyChanged(Hx)))}get magFilter(){return this._magFilter}set addressU(e){this._addressU!==e&&(this._addressU=e,this.propertyChanged(Wx))}get addressU(){return this._addressU}set addressV(e){this._addressV!==e&&(this._addressV=e,this.propertyChanged(Xx))}get addressV(){return this._addressV}set addressW(e){this._volume&&e!==this._addressW&&(this._addressW=e,this.propertyChanged(Yx))}get addressW(){return this._addressW}set compareOnRead(e){this._compareOnRead!==e&&(this._compareOnRead=e,this.propertyChanged(jx))}get compareOnRead(){return this._compareOnRead}set compareFunc(e){this._compareFunc!==e&&(this._compareFunc=e,this.propertyChanged(qx))}get compareFunc(){return this._compareFunc}set anisotropy(e){this._anisotropy!==e&&(this._anisotropy=e,this.propertyChanged($x))}get anisotropy(){return this._anisotropy}set mipmaps(e){if(this._mipmaps!==e&&!this.device.isWebGPU){if(!Qr(this._format)){const t=this._mipmaps,s=this._numLevels;this._mipmaps=e,this._updateNumLevels(),this.array&&this._numLevels!==s?this.recreateImpl():this._mipmaps!==t&&(this.propertyChanged(Hm),this._mipmaps?(this._needsMipmapsUpload=!0,this.device?.texturesToUpload?.add(this)):this._needsMipmapsUpload=!1)}}}get mipmaps(){return this._mipmaps}get numLevels(){return this._numLevels}get storage(){return this._storage}get width(){return this._width}get height(){return this._height}get depth(){return this._depth}get format(){return this._format}get cubemap(){return this._cubemap}get gpuSize(){const e=this.pot&&this._mipmaps&&!(this._compressed&&this._levels.length===1);return Xt.calcGpuSize(this._width,this._height,this._depth,this._format,e,this._cubemap)}get array(){return this._arrayLength>0}get arrayLength(){return this._arrayLength}get volume(){return this._volume}set type(e){this._type!==e&&(this._type=e,this.device._shadersDirty=!0)}get type(){return this._type}set srgb(e){const t=Qd(this.format);if(e!==t)if(e){const s=of(this.format);this._format!==s&&(this._format=s,this.recreateImpl(),this.device._shadersDirty=!0)}else{const s=XE(this.format);this._format!==s&&(this._format=s,this.recreateImpl(),this.device._shadersDirty=!0)}}get srgb(){return Qd(this.format)}set flipY(e){this._flipY!==e&&(this._flipY=e,this.markForUpload())}get flipY(){return this._flipY}set premultiplyAlpha(e){this._premultiplyAlpha!==e&&(this._premultiplyAlpha=e,this.markForUpload())}get premultiplyAlpha(){return this._premultiplyAlpha}get pot(){return H.powerOfTwo(this._width)&&H.powerOfTwo(this._height)}get encoding(){switch(this.type){case wr:return"rgbm";case eu:return"rgbe";case ac:return"rgbp"}return YE(this.format)?"srgb":"linear"}dirtyAll(){this._levelsUpdated=this._cubemap?[[!0,!0,!0,!0,!0,!0]]:[!0],this.markForUpload(),this._needsMipmapsUpload=this._mipmaps,this._mipmapsUploaded=!1,this.propertyChanged(xb)}lock(e={}){e.level??(e.level=0),e.face??(e.face=0),e.mode??(e.mode=Sv),this._lockedMode=e.mode,this._lockedLevel=e.level;const t=this.cubemap?this._levels[e.face]:this._levels;if(!t[e.level]){const s=Math.max(1,this._width>>e.level),i=Math.max(1,this._height>>e.level),r=Math.max(1,this._depth>
2>e.level),a=new ArrayBuffer(Xt.calcLevelGpuSize(s,i,r,this._format));t[e.level]=new(ng(this._format))(a)}return t[e.level]}setSource(e,t=0){if(this.device._isHTMLElementInterface(e)&&(!this.device.supportsHtmlTextures||this._cubemap||this._volume))return;let s=!1,i,r;if(this._cubemap){if(e[0]){i=e[0].width||0,r=e[0].height||0;for(let a=0;a<6;a++){const n=e[a];if(!n||n.width!==i||n.height!==r||!this.device._isBrowserInterface(n)){s=!0;break}}}else s=!0;if(!s)for(let a=0;a<6;a++)this._levels[t][a]!==e[a]&&(this._levelsUpdated[t][a]=!0)}else if(this.device._isBrowserInterface(e)||(s=!0),!s)if(e!==this._levels[t]&&(this._levelsUpdated[t]=!0),e instanceof HTMLVideoElement)i=e.videoWidth,r=e.videoHeight;else if(this.device._isHTMLElementInterface(e)){const a=e.getBoundingClientRect();i=Math.floor(a.width)||1,r=Math.floor(a.height)||1}else i=e.width,r=e.height;if(s)if(this._width=4,this._height=4,this._cubemap)for(let a=0;a<6;a++)this._levels[t][a]=null,this._levelsUpdated[t][a]=!0;else this._levels[t]=null,this._levelsUpdated[t]=!0;else t===0&&(this._width=i,this._height=r),this._levels[t]=e;(this._invalid!==s||!s)&&(this._invalid=s,this.upload())}getSource(e=0){return this._levels[e]}unlock(){this._lockedMode,this._lockedMode===Sv&&this.upload(),this._lockedLevel=-1,this._lockedMode=qf}markForUpload(){this._needsUpload=!0,this.device?.texturesToUpload?.add(this)}upload(){this.markForUpload(),this._needsMipmapsUpload=this._mipmaps,this.impl.uploadImmediate?.(this.device,this)}read(e,t,s,i,r={}){return this.impl.read?.(e,t,s,i,r)}write(e,t,s,i,r){return this.impl.write?.(e,t,s,i,r)}getView(e=0,t=1,s=0,i=1){return new dc(this,e,t,s,i)}}const bb={white:[255,255,255,255],gray:[128,128,128,255],black:[0,0,0,255],normal:[128,128,255,255],pink:[255,128,255,255]};class Ab{map=new Map;destroy(){this.map.forEach(e=>{e.destroy()})}}const Pb=new Jt,Za=(l,e)=>{const t=Pb.get(l,()=>new Ab);if(!t.map.has(e)){const s=new ce(l,{name:`built-in-texture-${e}`,width:1,height:1,format:Re}),i=s.lock(),r=bb[e];i.set(r),s.unlock(),t.map.set(e,s)}return t.map.get(e)};let Ib=0;class Sg{bindGroup;offsets=[]}class jo{renderVersionUpdated=-1;uniformBuffers;uniformBufferOffsets=[];constructor(e,t,s){this.id=Ib++,this.device=e,this.format=t,this.dirty=!0,this.impl=e.createBindGroupImpl(this),this.textures=[],this.storageTextures=[],this.storageBuffers=[],this.uniformBuffers=[],this.defaultUniformBuffer=s,s&&this.setUniformBuffer(yf,s)}destroy(){this.impl.destroy(),this.impl=null,this.format=null,this.defaultUniformBuffer=null}setUniformBuffer(e,t){const s=this.format.bufferFormatsMap.get(e);this.uniformBuffers[s]!==t&&(this.uniformBuffers[s]=t,this.dirty=!0)}setStorageBuffer(e,t){const s=this.format.storageBufferFormatsMap.get(e);this.storageBuffers[s]!==t&&(this.storageBuffers[s]=t,this.dirty=!0)}setTexture(e,t){const s=this.format.textureFormatsMap.get(e),i=t instanceof dc?t.texture:t;this.textures[s]!==t?(this.textures[s]=t,this.dirty=!0):this.renderVersionUpdated<i.renderVersionDirty&&(this.dirty=!0)}setStorageTexture(e,t){const s=this.format.storageTextureFormatsMap.get(e),i=t instanceof dc?t.texture:t;this.storageTextures[s]!==t?(this.storageTextures[s]=t,this.dirty=!0):this.renderVersionUpdated<i.renderVersionDirty&&(this.dirty=!0)}updateUniformBuffers(){for(let e=0;e<this.uniformBuffers.length;e++)this.uniformBuffers[e].update()}update(){const{textureFormats:e,storageTextureFormats:t,storageBufferFormats:s}=this.format;for(let i=0;i<e.length;i++){const r=e[i];let a=r.scopeId.value;a||(r.name==="uSceneDepthMap"&&(a=Za(this.device,"white")),r.name==="uSceneColorMap"&&(a=Za(this.device,"pink")),a||(a=Za(this.device,"pink"))),this.setTexture(r.name,a)}for(let i=0;i<t.length;i++){const r=t[i],a=r.scopeId.value;this.setStorageTexture(r.name,a)}for(let i=0;i<s.length;i++){const r=s[i],a=r.scopeId.value;this.setStorageBuffer(r.name,a)}this.uniformBufferOffsets.length=this.uniformBuffers.length;for(let i=0;i<this.uniformBuffers.length;i++){const r=this.uniformBuffers[i];this.uniformBufferOffsets[i]=r.offset,this.renderVersionUpdated<r.renderVersionDirty&&(this.dirty=!0)}this.dirty&&(this.dirty=!1,this.renderVersionUpdated=this.device.renderVersion,this.impl.update(this))}}const it={set(l,e,t,s=1){return l&~(s<<t)|e<<t},get(l,e,t=1){return l>>e&t},all(l,e,t=1){const s=t<<e;return(l&s)===s},any(l,e,t=1){return(l&t<<e)!==0}},_h=7,Nr=15,wv=0,Cv=3,Ev=7,bv=11,Av=14,Pv=18,Wm=22,Iv=23,Dv=24,Mv=25,Rv=26,Db=15,Mb=Wm;class xt{target0=0;constructor(e=!1,t=vi,s=as,i=Y_,r,a,n,o=!0,c=!0,h=!0,d=!0){this.setColorBlend(t,s,i),this.setAlphaBlend(r??t,a??s,n??i),this.setColorWrite(o,c,h,d),this.blend=e}set blend(e){this.target0=it.set(this.target0,e?1:0,Rv)}get blend(){return it.all(this.target0,Rv)}setColorBlend(e,t,s){this.target0=it.set(this.target0,e,wv,_h),this.target0=it.set(this.target0,t,Cv,Nr),this.target0=it.set(this.target0,s,Ev,Nr)}setAlphaBlend(e,t,s){this.target0=it.set(this.target0,e,bv,_h),this.target0=it.set(this.target0,t,Av,Nr),this.target0=it.set(this.target0,s,Pv,Nr)}setColorWrite(e,t,s,i){this.redWrite=e,this.greenWrite=t,this.blueWrite=s,this.alphaWrite=i}get colorOp(){return it.get(this.target0,wv,_h)}get colorSrcFactor(){return it.get(this.target0,Cv,Nr)}get colorDstFactor(){return it.get(this.target0,Ev,Nr)}get alphaOp(){return it.get(this.target0,bv,_h)}get alphaSrcFactor(){return it.get(this.target0,Av,Nr)}get alphaDstFactor(){return it.get(this.target0,Pv,Nr)}set redWrite(e){this.target0=it.set(this.target0,e?1:0,Wm)}get redWrite(){return it.all(this.target0,Wm)}set greenWrite(e){this.target0=it.set(this.target0,e?1:0,Iv)}get greenWrite(){return it.all(this.target0,Iv)}set blueWrite(e){this.target0=it.set(this.target0,e?1:0,Dv)}get blueWrite(){return it.all(this.target0,Dv)}set alphaWrite(e){this.target0=it.set(this.target0,e?1:0,Mv)}get alphaWrite(){return it.all(this.target0,Mv)}
2get allWrite(){return it.get(this.target0,Mb,Db)}copy(e){return this.target0=e.target0,this}clone(){return new this.constructor().copy(this)}get key(){return this.target0}equals(e){return this.target0===e.target0}static NOBLEND=Object.freeze(new xt);static NOWRITE=Object.freeze(new xt(void 0,void 0,void 0,void 0,void 0,void 0,void 0,!1,!1,!1,!1));static ALPHABLEND=Object.freeze(new xt(!0,vi,j_,q_));static ADDBLEND=Object.freeze(new xt(!0,vi,as,as))}const Rb=new _n,Lv=7,Fv=0,Ov=3;class ds{data=0;_depthBias=0;_depthBiasSlope=0;key=0;constructor(e=Um,t=!0){this.func=e,this.write=t}set test(e){this.func=e?Um:cr,this.updateKey()}get test(){return this.func!==cr}set write(e){this.data=it.set(this.data,e?1:0,Ov),this.updateKey()}get write(){return it.all(this.data,Ov)}set func(e){this.data=it.set(this.data,e,Fv,Lv),this.updateKey()}get func(){return it.get(this.data,Fv,Lv)}set depthBias(e){this._depthBias=e,this.updateKey()}get depthBias(){return this._depthBias}set depthBiasSlope(e){this._depthBiasSlope=e,this.updateKey()}get depthBiasSlope(){return this._depthBiasSlope}copy(e){return this.data=e.data,this._depthBias=e._depthBias,this._depthBiasSlope=e._depthBiasSlope,this.key=e.key,this}clone(){return new this.constructor().copy(this)}updateKey(){const{data:e,_depthBias:t,_depthBiasSlope:s}=this,i=`${e}-${t}-${s}`;this.key=Rb.get(i)}equals(e){return this.key===e.key}static DEFAULT=Object.freeze(new ds);static NODEPTH=Object.freeze(new ds(cr,!1));static WRITEDEPTH=Object.freeze(new ds(cr,!0))}let Lb=0;class la{constructor(e,t,s,i=Ys,r,a){this.device=e,this.format=t,this.numIndices=s,this.usage=i,this.id=Lb++,this.impl=e.createIndexBufferImpl(this,a);const n=Tb[t];this.bytesPerIndex=n,this.numBytes=this.numIndices*n,r?this.setData(r):this.storage=new ArrayBuffer(this.numBytes),this.adjustVramSizeTracking(e._vram,this.numBytes),this.device.buffers.add(this)}destroy(){const e=this.device;e.buffers.delete(this),this.device.indexBuffer===this&&(this.device.indexBuffer=null),this.impl.initialized&&(this.impl.destroy(e),this.adjustVramSizeTracking(e._vram,-this.storage.byteLength))}adjustVramSizeTracking(e,t){e.ib+=t}loseContext(){this.impl.loseContext()}restoreContext(){this.unlock()}getFormat(){return this.format}getNumIndices(){return this.numIndices}lock(){return this.storage}unlock(){this.impl.unlock(this)}setData(e){return e.byteLength!==this.numBytes?!1:(this.storage=e,this.unlock(),!0)}_lockTypedArray(){const e=this.lock();return this.format===ra?new Uint32Array(e):this.format===Ni?new Uint16Array(e):new Uint8Array(e)}writeData(e,t){const s=this._lockTypedArray();if(e.length>t)if(ArrayBuffer.isView(e))e=e.subarray(0,t),s.set(e);else for(let i=0;i<t;i++)s[i]=e[i];else s.set(e);this.unlock()}readData(e){const t=this._lockTypedArray(),s=this.numIndices;if(ArrayBuffer.isView(e))e.set(t);else{e.length=0;for(let i=0;i<s;i++)e[i]=t[i]}return s}}class Qx{globalId=0;revision=0;equals(e){return this.globalId===e.globalId&&this.revision===e.revision}copy(e){this.globalId=e.globalId,this.revision=e.revision}reset(){this.globalId=0,this.revision=0}}let Bv=0;class Fb{constructor(){Bv++,this.version=new Qx,this.version.globalId=Bv}increment(){this.version.revision++}}class Ob{constructor(e){this.name=e,this.value=null,this.versionObject=new Fb}toJSON(e){}setValue(e){this.value=e,this.versionObject.increment()}getValue(){return this.value}}class Bb{constructor(e){this.name=e,this.variables=new Map}resolve(e){return this.variables.has(e)||this.variables.set(e,new Ob(e)),this.variables.get(e)}removeValue(e){for(const t of this.variables.values())t.value===e&&(t.value=null)}}let Nb=0;class Hi{usage=Ys;constructor(e,t,s,i){this.usage=i?.usage??Ys,this.device=e,this.format=t,this.numVertices=s,this.id=Nb++,this.impl=e.createVertexBufferImpl(this,t,i),this.numBytes=t.verticesByteSize?t.verticesByteSize:t.size*s,this.adjustVramSizeTracking(e._vram,this.numBytes);const r=i?.data;r?this.setData(r):this.storage=new ArrayBuffer(this.numBytes),this.device.buffers.add(this)}destroy(){const e=this.device;e.buffers.delete(this),this.impl.initialized&&(this.impl.destroy(e),this.adjustVramSizeTracking(e._vram,-this.storage.byteLength))}adjustVramSizeTracking(e,t){e.vb+=t}loseContext(){this.impl.loseContext()}restoreContext(){this.unlock()}getFormat(){return this.format}getUsage(){return this.usage}getNumVertices(){return this.numVertices}lock(){return this.storage}unlock(){this.impl.unlock(this)}setData(e){return e.byteLength!==this.numBytes?!1:(this.storage=e,this.unlock(),!0)}}function Xs(l){if(l==null)return 0;let e=0;for(let t=0,s=l.length;t<s;t++)e=(e<<5)-e+l.charCodeAt(t),e|=0;return e}function Tf(l){let t=2166136261;for(let s=0;s<l.length;s++)t^=l[s],t*=16777619;return t>>>0}const kb=new _n,Ub=[2,4,8,12,16],zb=new Jt;class Us{constructor(e,t,s){this.device=e,this._elements=[],this.hasUv0=!1,this.hasUv1=!1,this.hasColor=!1,this.hasTangents=!1,this.verticesByteSize=0,this.vertexCount=s,this.interleaved=s===void 0,this.instancing=!1,this.size=t.reduce((a,n)=>a+Math.ceil(n.components*Xl[n.type]/4)*4,0);let i=0,r;for(let a=0,n=t.length;a<n;a++){const o=t[a];
2r=o.components*Xl[o.type],s&&(i=H.roundUp(i,r));const c=o.asInt??!1,h=c?!1:o.normalize??!1,d={name:o.semantic,offset:s?i:o.hasOwnProperty("offset")?o.offset:i,stride:s?r:o.hasOwnProperty("stride")?o.stride:this.size,dataType:o.type,numComponents:o.components,normalize:h,size:r,asInt:c};this._elements.push(d),s?i+=r*s:i+=Math.ceil(r/4)*4,o.semantic===Zs?this.hasUv0=!0:o.semantic===pn?this.hasUv1=!0:o.semantic===ns?this.hasColor=!0:o.semantic===Gi&&(this.hasTangents=!0)}s&&(this.verticesByteSize=i),this._evaluateHash()}get elements(){return this._elements}static getDefaultInstancingFormat(e){return zb.get(e,()=>new Us(e,[{semantic:dg,components:4,type:je},{semantic:ug,components:4,type:je},{semantic:fg,components:4,type:je},{semantic:Io,components:4,type:je}]))}static isElementValid(e,t){const s=t.components*Xl[t.type];return!(e.isWebGPU&&!Ub.includes(s))}update(){this._evaluateHash()}_evaluateHash(){const e=[],t=[],s=this._elements.length;for(let r=0;r<s;r++){const{name:a,dataType:n,numComponents:o,normalize:c,offset:h,stride:d,size:u,asInt:f}=this._elements[r],p=a+n+o+c+f;e.push(p);const m=p+h+d+u;t.push(m)}e.sort();const i=e.join();this.batchingHash=Xs(i),this.shaderProcessingHashString=i,this.renderingHashString=t.join("_"),this.renderingHash=kb.get(this.renderingHashString)}}const Vb=new _n;class $s{_func;_ref;_fail;_zfail;_zpass;_readMask;_writeMask;_dirty=!0;_key;set func(e){this._func=e,this._dirty=!0}get func(){return this._func}set ref(e){this._ref=e,this._dirty=!0}get ref(){return this._ref}set fail(e){this._fail=e,this._dirty=!0}get fail(){return this._fail}set zfail(e){this._zfail=e,this._dirty=!0}get zfail(){return this._zfail}set zpass(e){this._zpass=e,this._dirty=!0}get zpass(){return this._zpass}set readMask(e){this._readMask=e,this._dirty=!0}get readMask(){return this._readMask}set writeMask(e){this._writeMask=e,this._dirty=!0}get writeMask(){return this._writeMask}constructor(e={}){this._func=e.func??cr,this._ref=e.ref??0,this._readMask=e.readMask??255,this._writeMask=e.writeMask??255,this._fail=e.fail??go,this._zfail=e.zfail??go,this._zpass=e.zpass??go,this._evalKey()}_evalKey(){const{_func:e,_ref:t,_fail:s,_zfail:i,_zpass:r,_readMask:a,_writeMask:n}=this,o=`${e},${t},${s},${i},${r},${a},${n}`;this._key=Vb.get(o),this._dirty=!1}get key(){return this._dirty&&this._evalKey(),this._key}copy(e){return this._func=e._func,this._ref=e._ref,this._readMask=e._readMask,this._writeMask=e._writeMask,this._fail=e._fail,this._zfail=e._zfail,this._zpass=e._zpass,this._dirty=e._dirty,this._key=e._key,this}clone(){return new this.constructor().copy(this)}static DEFAULT=Object.freeze(new $s)}let Gb=0;class Se{id=Gb++;constructor(e,t,s=0,i=!0){this.device=e,this.byteSize=t,this.bufferUsage=s;const r=i?$_|s:s;this.impl=e.createBufferImpl(r),this.impl.allocate(e,t),e.buffers.add(this),this.adjustVramSizeTracking(e._vram,this.byteSize)}destroy(){const e=this.device;e.buffers.delete(this),this.impl.destroy(e),this.adjustVramSizeTracking(e._vram,-this.byteSize)}loseContext(){this.impl.loseContext()}restoreContext(){this.impl.allocate(this.device,this.byteSize)}adjustVramSizeTracking(e,t){e.sb+=t}read(e=0,t=this.byteSize,s=null,i=!1){return this.impl.read(this.device,e,t,s,i)}write(e=0,t,s=0,i){this.impl.write(this.device,e,t,s,i)}clear(e=0,t=this.byteSize){this.impl.clear(this.device,e,t)}copy(e,t=0,s=0,i=e.byteSize-t){this.device.getCommandEncoder().copyBufferToBuffer(e.impl.buffer,t,this.impl.buffer,s,i)}}class Je extends ge{canvas;backBuffer=null;backBufferSize=new j;backBufferFormat;backBufferAntialias=!1;isWebGPU=!1;isWebGL2=!1;isNull=!1;isHdr=!1;scope;maxIndirectDrawCount=1024;maxIndirectDispatchCount=256;maxAnisotropy;maxCubeMapSize;maxTextureSize;maxVolumeSize;maxColorAttachments=1;precision;samples;maxSamples=1;supportsStencil;supportsMultiDraw=!0;supportsCompute=!1;supportsStorageTextureRead=!1;supportsSubgroups=!1;supportsSubgroupUniformity=!1;supportsSubgroupId=!1;supportsLinearIndexing=!1;supportsPointerCompositeAccess=!1;supportsPacked4x8IntegerDotProduct=!1;supportsTextureAndSamplerLet=!1;supportsUnrestrictedPointerParameters=!1;maxSubgroupSize=0;minSubgroupSize=0;renderTarget=null;shaders=[];textures=new Set;texturesToUpload=new Set;targets=new Set;renderVersion=0;renderPassIndex;insideRenderPass=!1;supportsUniformBuffers=!1;supportsClipDistances=!1;supportsTextureFormatTier1=!1;supportsTextureFormatTier2=!1;supportsPrimitiveIndex=!1;supportsShaderF16=!1;supportsHtmlTextures=!1;
2textureFloatRenderable;textureHalfFloatRenderable;textureRG11B10Renderable=!1;textureFloatFilterable=!1;quadVertexBuffer;quadIndexBuffer;blendState=new xt;depthState=new ds;stencilEnabled=!1;stencilFront=new $s;stencilBack=new $s;dynamicBuffers;gpuProfiler;_destroyed=!1;defaultClearOptions={color:[0,0,0,1],depth:1,stencil:0,flags:Jl|ec};clientRect={width:0,height:0};_shadersDirty=!1;capsDefines=new Map;mapsToClear=new Set;static EVENT_RESIZE="resizecanvas";constructor(e,t){var s,i,r,a,n,o,c;super(),this.canvas=e,"setAttribute"in e&&e.setAttribute("data-engine",`PlayCanvas ${Ex}`),this.initOptions={...t},(s=this.initOptions).alpha??(s.alpha=!0),(i=this.initOptions).depth??(i.depth=!0),(r=this.initOptions).stencil??(r.stencil=!0),(a=this.initOptions).antialias??(a.antialias=!0),(n=this.initOptions).powerPreference??(n.powerPreference="high-performance"),(o=this.initOptions).displayFormat??(o.displayFormat=Sb),(c=this.initOptions).xrCompatible??(c.xrCompatible=Ce.browser&&!!navigator.xr),this._maxPixelRatio=Ce.browser?Math.min(1,window.devicePixelRatio):1,this.buffers=new Set,this._vram={tex:0,vb:0,ib:0,ub:0,sb:0},this._shaderStats={vsCompiled:0,fsCompiled:0,linked:0,materialShaders:0,compileTime:0},this.initializeContextCaches(),this._drawCallsPerFrame=0,this._shaderSwitchesPerFrame=0,this._primsPerFrame=[];for(let h=lf;h<=qa;h++)this._primsPerFrame[h]=0;this._renderTargetCreationTime=0,this.scope=new Bb("Device"),this.textureBias=this.scope.resolve("textureBias"),this.textureBias.setValue(0)}postInit(){const e=new Us(this,[{semantic:Ie,components:2,type:je}]),t=new Float32Array([-1,-1,1,-1,-1,1,1,1]);this.quadVertexBuffer=new Hi(this,e,4,{data:t});const s=new Uint16Array([0,1,2,2,1,3]);this.quadIndexBuffer=new la(this,Ni,6,Ys,s.buffer)}initCapsDefines(){const{capsDefines:e}=this;e.clear(),this.textureFloatFilterable&&e.set("CAPS_TEXTURE_FLOAT_FILTERABLE",""),this.textureFloatRenderable&&e.set("CAPS_TEXTURE_FLOAT_RENDERABLE",""),this.supportsMultiDraw&&e.set("CAPS_MULTI_DRAW",""),this.supportsPrimitiveIndex&&e.set("CAPS_PRIMITIVE_INDEX",""),this.supportsShaderF16&&e.set("CAPS_SHADER_F16",""),this.supportsSubgroups&&e.set("CAPS_SUBGROUPS",""),this.supportsSubgroupId&&e.set("CAPS_SUBGROUP_ID",""),this.supportsLinearIndexing&&e.set("CAPS_LINEAR_INDEXING",""),this.supportsUnrestrictedPointerParameters&&e.set("CAPS_UNRESTRICTED_POINTER_PARAMETERS",""),this.supportsPointerCompositeAccess&&e.set("CAPS_POINTER_COMPOSITE_ACCESS",""),this.supportsPacked4x8IntegerDotProduct&&e.set("CAPS_PACKED_4X8_INTEGER_DOT_PRODUCT",""),this.supportsTextureAndSamplerLet&&e.set("CAPS_TEXTURE_AND_SAMPLER_LET",""),this.supportsStorageTextureRead&&e.set("CAPS_STORAGE_TEXTURE_READ",""),Ce.desktop&&e.set("PLATFORM_DESKTOP",""),Ce.mobile&&e.set("PLATFORM_MOBILE",""),Ce.android&&e.set("PLATFORM_ANDROID",""),Ce.ios&&e.set("PLATFORM_IOS","")}destroy(){this.fire("destroy"),this.quadVertexBuffer?.destroy(),this.quadVertexBuffer=null,this.quadIndexBuffer?.destroy(),this.quadIndexBuffer=null,this.dynamicBuffers?.destroy(),this.dynamicBuffers=null,this.gpuProfiler?.destroy(),this.gpuProfiler=null,this._destroyed=!0}onDestroyShader(e){this.fire("destroy:shader",e);const t=this.shaders.indexOf(e);t!==-1&&this.shaders.splice(t,1)}onTextureDestroyed(e){this.textures.delete(e),this.texturesToUpload.delete(e),this.scope.removeValue(e)}postDestroy(){this.scope=null,this.canvas=null}loseContext(){this.contextLost=!0,this.backBufferSize.set(-1,-1);for(const e of this.textures)e.loseContext();for(const e of this.buffers)e.loseContext();for(const e of this.targets)e.loseContext();this.gpuProfiler?.loseContext()}restoreContext(){this.contextLost=!1,this.initializeRenderState(),this.initializeContextCaches();for(const e of this.buffers)e.restoreContext();this.gpuProfiler?.restoreContext?.()}toJSON(e){}initializeContextCaches(){this.vertexBuffers=[],this.shader=null,this.shaderValid=void 0,this.shaderAsyncCompile=!1,this.renderTarget=null}initializeRenderState(){this.blendState=new xt,this.depthState=new ds,this.cullMode=tc,this.frontFace=sc,this.vx=this.vy=this.vw=this.vh=0,this.sx=this.sy=this.sw=this.sh=0,this.blendColor=new Q(0,0,0,0)}setStencilState(e,t){}setBlendState(e){}
2setBlendColor(e,t,s,i){}setDepthState(e){}setCullMode(e){}setFrontFace(e){}setDrawStates(e=xt.NOBLEND,t=ds.NODEPTH,s=Yt,i=sc,r,a){this.setBlendState(e),this.setDepthState(t),this.setCullMode(s),this.setFrontFace(i),this.setStencilState(r,a)}setRenderTarget(e){this.renderTarget=e}setVertexBuffer(e){e&&this.vertexBuffers.push(e)}clearVertexBuffer(){this.vertexBuffers.length=0}getIndirectDrawSlot(e=1){return 0}get indirectDrawBuffer(){return null}getIndirectDispatchSlot(e=1){return 0}get indirectDispatchBuffer(){return null}getRenderTarget(){return this.renderTarget}initRenderTarget(e){e.initialized||(e.init(),this.targets.add(e))}draw(e,t,s,i,r=!0,a=!0){}_isBrowserInterface(e){return this._isImageBrowserInterface(e)||this._isImageCanvasInterface(e)||this._isImageVideoInterface(e)||this._isHTMLElementInterface(e)}_isImageBrowserInterface(e){return typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement}_isImageCanvasInterface(e){return typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement}_isImageVideoInterface(e){return typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement}_isHTMLElementInterface(e){return typeof HTMLElement<"u"&&e instanceof HTMLElement&&!(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement)&&!(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement)&&!(typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement)}resizeCanvas(e,t){const s=Math.min(this._maxPixelRatio,Ce.browser?window.devicePixelRatio:1),i=Math.floor(e*s),r=Math.floor(t*s);(i!==this.canvas.width||r!==this.canvas.height)&&this.setResolution(i,r)}setResolution(e,t){this.canvas.width=e,this.canvas.height=t,this.fire(Je.EVENT_RESIZE,e,t)}update(){this.updateClientRect()}updateClientRect(){if(Ce.worker)this.clientRect.width=this.canvas.width,this.clientRect.height=this.canvas.height;else{const e=this.canvas.getBoundingClientRect();this.clientRect.width=e.width,this.clientRect.height=e.height}}get width(){return this.canvas.width}get height(){return this.canvas.height}set fullscreen(e){}get fullscreen(){return!1}set maxPixelRatio(e){this._maxPixelRatio=e}get maxPixelRatio(){return this._maxPixelRatio}get deviceType(){return this._deviceType}startRenderPass(e){}endRenderPass(e){}startComputePass(e){}endComputePass(){}frameStart(){this.renderPassIndex=0,this.renderVersion++}frameEnd(){this.mapsToClear.forEach(e=>e.clear()),this.mapsToClear.clear()}computeDispatch(e,t="Unnamed"){}getRenderableHdrFormat(e=[tn,Ge,mt],t=!0,s=1){for(let i=0;i<e.length;i++){const r=e[i];switch(r){case tn:{if(this.textureRG11B10Renderable)return r;break}case Ge:if(this.textureHalfFloatRenderable)return r;break;case mt:if(this.isWebGPU&&s>1)continue;if(this.textureFloatRenderable&&(!t||this.textureFloatFilterable))return r;break}}}validateAttributes(e,t,s){}}let Hb=0;class St{name;_device;_colorBuffer;_colorBuffers;_depthBuffer;_depth;_stencil;_samples;autoResolve;_face;_mipLevel;_mipmaps;_width;_height;flipY;constructor(e={}){this.id=Hb++;const t=e.colorBuffer?.device??e.colorBuffers?.[0].device??e.depthBuffer?.device??e.graphicsDevice;this._device=t;const{maxSamples:s}=this._device;if(this._samples=Math.min(e.samples??1,s),t.isWebGPU&&(this._samples=this._samples>1?s:1),this._colorBuffer=e.colorBuffer,e.colorBuffer&&(this._colorBuffers=[e.colorBuffer]),this._depthBuffer=e.depthBuffer,this._face=e.face??0,this._depthBuffer){const i=this._depthBuffer._format;i===Oi||i===ja?(this._depth=!0,this._stencil=!1):i===en?(this._depth=!0,this._stencil=!0):i===Ti&&this._depthBuffer.device.isWebGPU&&this._samples>1?(this._depth=!0,this._stencil=!1):(this._depth=!1,this._stencil=!1)}else this._depth=e.depth??!0,this._stencil=e.stencil??!1;e.colorBuffers&&(this._colorBuffers||(this._colorBuffers=[...e.colorBuffers],this._colorBuffer=e.colorBuffers[0])),this.autoResolve=e.autoResolve??!0,this.name=e.name,this.name||(this.name=this._colorBuffer?.name),this.name||(this.name=this._depthBuffer?.name),this.name||(this.name="Untitled"),this.flipY=e.flipY??!1,this._mipLevel=e.mipLevel??0,this._mipLevel>0&&this._depth&&(this._mipLevel=0),this._mipmaps=e.mipLevel===void 0,this.evaluateDimensions(),this.validateMrt(),this.impl=t.createRenderTargetImpl(this)}destroy(){const e=this._device;e&&(e.targets.delete(this),e.renderTarget===this&&e.setRenderTarget(null),this.destroyFrameBuffers())}destroyFrameBuffers(){const e=this._device;e&&this.impl.destroy(e)}destroyTextureBuffers(){this._depthBuffer?.destroy(),this._depthBuffer=null,this._colorBuffers?.forEach(e
2=>{e.destroy()}),this._colorBuffers=null,this._colorBuffer=null}resize(e,t){if(!(this.mipLevel>0)&&(this._depthBuffer?.resize(e,t),this._colorBuffers?.forEach(s=>{s.resize(e,t)}),this._width!==e||this._height!==t)){this.destroyFrameBuffers();const s=this._device;s.renderTarget===this&&s.setRenderTarget(null),this.evaluateDimensions(),this.validateMrt(),this.impl=s.createRenderTargetImpl(this)}}validateMrt(){}evaluateDimensions(){const e=this._colorBuffer??this._depthBuffer;e&&(this._width=e.width,this._height=e.height,this._mipLevel>0&&(this._width=Xt.calcLevelDimension(this._width,this._mipLevel),this._height=Xt.calcLevelDimension(this._height,this._mipLevel)))}init(){this.impl.init(this._device,this)}get initialized(){return this.impl.initialized}get device(){return this._device}loseContext(){this.impl.loseContext()}resolve(e=!0,t=!!this._depthBuffer){this._device&&this._samples>1&&this.impl.resolve(this._device,this,e,t)}copy(e,t,s){if(!this._device)if(e._device)this._device=e._device;else return!1;return this._device.copyRenderTarget(e,this,t,s)}get samples(){return this._samples}get depth(){return this._depth}get stencil(){return this._stencil}get colorBuffer(){return this._colorBuffer}getColorBuffer(e){return this._colorBuffers?.[e]}get depthBuffer(){return this._depthBuffer}get face(){return this._face}get mipLevel(){return this._mipLevel}get mipmaps(){return this._mipmaps}get width(){return this._width??this._device.width}get height(){return this._height??this._device.height}isColorBufferSrgb(e=0){if(this.device.backBuffer===this)return Qd(this.device.backBufferFormat);const t=this.getColorBuffer(e);return t?Qd(t.format):!1}}class Wb{bindGroup;update(e){this.destroy();const t=e.device,s=this.createDescriptor(t,e);this.bindGroup=t.wgpu.createBindGroup(s)}destroy(){this.bindGroup=null}createDescriptor(e,t){const s=[],i=t.format,r=t.format.uniformBufferFormats;t.uniformBuffers.forEach((h,d)=>{const u=r[d].slot,f=h.persistent?h.impl.buffer:h.allocation.gpuBuffer.buffer;s.push({binding:u,resource:{buffer:f,offset:0,size:h.format.byteSize}})});const a=t.format.textureFormats;t.textures.forEach((h,d)=>{const u=h instanceof dc,p=(u?h.texture:h).impl,m=i.textureFormats[d],_=a[d].slot,g=p.getView(e,u?h:void 0);if(s.push({binding:_,resource:g}),m.hasSampler){const v=p.getSampler(e,m.sampleType);s.push({binding:_+1,resource:v})}});const n=t.format.storageTextureFormats;t.storageTextures.forEach((h,d)=>{const u=h instanceof dc,p=(u?h.texture:h).impl,m=n[d].slot,_=p.getView(e,u?h:void 0);s.push({binding:m,resource:_})});const o=t.format.storageBufferFormats;return t.storageBuffers.forEach((h,d)=>{const u=h.impl.buffer,f=o[d].slot;s.push({binding:f,resource:{buffer:u}})}),{layout:t.format.impl.bindGroupLayout,entries:s}}}class $f{static shaderStage(e){let t=0;return e&rn&&(t|=GPUShaderStage.VERTEX),e&an&&(t|=GPUShaderStage.FRAGMENT),e&G&&(t|=GPUShaderStage.COMPUTE),t}}const re=[];re[K_]="";re[Z_]="";re[Du]="";re[Zu]="r8unorm";re[Qu]="rg8unorm";re[Dc]="";re[Mu]="";re[Mc]="";re[Er]="rgba8unorm";re[Re]="rgba8unorm";re[Rc]="bc1-rgba-unorm";re[Ru]="bc2-rgba-unorm";re[Ho]="bc3-rgba-unorm";re[Lc]="";re[Ge]="rgba16float";re[kc]="r16float";re[Ku]="rg16float";re[Lu]="";re[mt]="rgba32float";re[Ti]="r32float";re[ef]="rg32float";re[Oi]="depth32float";re[ja]="depth16unorm";re[en]="depth24plus-stencil8";re[tn]="rg11b10ufloat";re[Fu]="";re[us]="rgba8unorm-srgb";re[Fc]="";re[Ou]="etc2-rgb8unorm";re[Bu]="etc2-rgba8unorm";re[Wo]="";re[Xo]="";re[Oc]="";re[Bc]="";re[Q_]="astc-4x4-unorm";re[J_]="";re[eg]="";re[Nu]="bgra8unorm";re[Ju]="bgra8unorm-srgb";re[ku]="r8sint";re[Uu]="r8uint";re[zu]="r16sint";re[Vu]="r16uint";re[Gu]="r32sint";re[js]="r32uint";re[Hu]="rg8sint";re[tg]="rg8uint";re[Wu]="rg16sint";re[Xu]="rg16uint";re[Yu]="rg32sint";re[Nc]="rg32uint";re[ju]="rgba8sint";re[sg]="rgba8uint";re[qu]="rgba16sint";re[Vi]="rgba16uint";re[$u]="rgba32sint";re[Wt]="rgba32uint";re[ig]="bc6h-rgb-float";re[rg]="bc6h-rgb-ufloat";re[ag]="bc7-rgba-unorm";re[tf]="rgb9e5ufloat";re[sf]="rg8snorm";re[rf]="rgba8snorm";re[af]="rgb10a2unorm";re[nf]="rgb10a2uint";re[Xd]="bc1-rgba-unorm-srgb";re[Yd]="bc2-rgba-unorm-srgb";re[jd]="bc3-rgba-unorm-srgb";re[qd]="etc2-rgb8unorm-srgb";re[$d]="etc2-rgba8unorm-srgb";re[Zd]="bc7-rgba-unorm-srgb";re[Kd]="astc-4x4-unorm-srgb";const qo=[];qo[ls]="filtering";qo[da]="non-filtering";qo[gi]="comparison";qo[aa]="comparison";qo[na]="comparison";const $o=[];$o[ls]="float";$o[da]="unfilterable-float";$o[gi]="depth";$o[aa]="sint";$o[na]="uint";
2const Xb=new _n;class Yb{constructor(e){const t=e.device,{key:s,desc:i}=this.createDescriptor(e);this.key=Xb.get(s),this.bindGroupLayout=t.wgpu.createBindGroupLayout(i)}destroy(){this.bindGroupLayout=null}loseContext(){}createDescriptor(e){const t=[];let s="";return e.uniformBufferFormats.forEach(r=>{const a=$f.shaderStage(r.visibility);s+=`#${r.slot}U:${a}`,t.push({binding:r.slot,visibility:a,buffer:{type:"uniform",hasDynamicOffset:!0}})}),e.textureFormats.forEach(r=>{const a=$f.shaderStage(r.visibility),n=r.sampleType,o=r.textureDimension,c=!1,h=$o[n];if(s+=`#${r.slot}T:${a}-${h}-${o}-${c}`,t.push({binding:r.slot,visibility:a,texture:{sampleType:h,viewDimension:o,multisampled:c}}),r.hasSampler){const d=qo[n];s+=`#${r.slot+1}S:${a}-${d}`,t.push({binding:r.slot+1,visibility:a,sampler:{type:d}})}}),e.storageTextureFormats.forEach(r=>{const{format:a,textureDimension:n}=r,{read:o,write:c}=r;s+=`#${r.slot}ST:${a}-${n}-${o?"r1":"r0"}-${c?"w1":"w0"}`,t.push({binding:r.slot,visibility:GPUShaderStage.COMPUTE,storageTexture:{access:o?c?"read-write":"read-only":"write-only",format:re[a],viewDimension:n}})}),e.storageBufferFormats.forEach(r=>{const a=r.readOnly,n=$f.shaderStage(r.visibility);s+=`#${r.slot}SB:${n}-${a?"ro":"rw"}`,t.push({binding:r.slot,visibility:n,buffer:{type:a?"read-only-storage":"storage"}})}),{key:s,desc:{entries:t}}}}class wf{buffer=null;usageFlags=0;constructor(e=0){this.usageFlags=e}destroy(e){this.buffer&&(e.deferDestroy(this.buffer),this.buffer=null)}get initialized(){return!!this.buffer}loseContext(){this.buffer=null}allocate(e,t){this.buffer=e.wgpu.createBuffer({size:t,usage:this.usageFlags})}unlock(e,t){const s=e.wgpu;if(!this.buffer){const n=t.byteLength+3&-4;this.usageFlags|=GPUBufferUsage.COPY_DST,this.allocate(e,n)}const i=t.byteOffset??0,r=new Uint8Array(t.buffer??t,i,t.byteLength),a=new Uint8Array(this.buffer.size);a.set(r),s.queue.writeBuffer(this.buffer,0,a,0,a.length)}read(e,t,s,i,r){return e.readStorageBuffer(this,t,s,i,r)}write(e,t,s,i,r){e.writeStorageBuffer(this,t,s,i,r)}clear(e,t,s){e.clearStorageBuffer(this,t,s)}}class jb extends wf{format=null;constructor(e,t){super(AE|(t?.storage?$_:0)),this.format=e.format===Ni?"uint16":"uint32"}unlock(e){const t=e.device;super.unlock(t,e.storage)}}const Jx={equals(l,e){if(l.length!==e.length)return!1;for(let t=0;t<l.length;t++)if(l[t]!==e[t])return!1;return!0}},br=[];br[ua]="sint8";br[mr]="uint8";br[fa]="sint16";br[mn]="uint16";br[Yo]="sint32";br[Xc]="uint32";br[je]="float32";br[hf]="float16";const Ar=[];Ar[ua]="snorm8";Ar[mr]="unorm8";Ar[fa]="snorm16";Ar[mn]="unorm16";Ar[Yo]="sint32";Ar[Xc]="uint32";Ar[je]="float32";Ar[hf]="float16";class qb{cache=new Map;get(e,t=null){const s=this.getKey(e,t);let i=this.cache.get(s);return i||(i=this.create(e,t),this.cache.set(s,i)),i}getKey(e,t=null){return`${e?.renderingHashString}-${t?.renderingHashString}`}create(e,t){const s=[],i=r=>{const a=r.interleaved,n=r.instancing?"instance":"vertex";let o=[];const c=r.elements.length;for(let h=0;h<c;h++){const d=r.elements[h],u=Be[d.name],f=d.normalize?Ar:br;o.push({shaderLocation:u,offset:a?d.offset:0,format:`${f[d.dataType]}${d.numComponents>1?`x${d.numComponents}`:""}`}),(!a||h===c-1)&&(s.push({attributes:o,arrayStride:d.stride,stepMode:n}),o=[])}};return e&&i(e),t&&i(t),s}}class eT{constructor(e){this.device=e}getPipelineLayout(e){const t=[];e.forEach(r=>{t.push(r.bindGroupLayout)});const s={bindGroupLayouts:t};return this.device.wgpu.createPipelineLayout(s)}}const $b=["point-list","line-list",void 0,"line-strip","triangle-list","triangle-strip",void 0],Nv=["add","subtract","reverse-subtract","min","max"],gh=["zero","one","src","one-minus-src","dst","one-minus-dst","src-alpha","src-alpha-saturated","one-minus-src-alpha","dst-alpha","one-minus-dst-alpha","constant","one-minus-constant"],Kf=["never","less","equal","less-equal","greater","not-equal","greater-equal","always"],Kb=["none","back","front"],Zb=["ccw","cw"],Pn=["keep","zero","replace","increment-clamp","increment-wrap","decrement-clamp","decrement-wrap","invert"],Qb=["","uint16","uint32"];let Jb=class{pipeline;hashes};class eA extends eT{lookupHashes=new Uint32Array(15);constructor(e){super(e),this.vertexBufferLayout=new qb,this.cache=new Map}get(e,t,s,i,r,a,n,o,c,h,d,u,f,p){const m=e.type;i&&m!==og&&m!==Tr&&(i=void 0);const _=this.lookupHashes;_[0]=m,_[1]=r.id,_[2]=h,_[3]=c.key,_[4]=o.key,_[5]=t?.renderingHash??0,_[6]=s?.renderingHash??0,_[7]=a.impl.key,_[8]=n[0]?.key??0,_[9]=n[1]?.key??0,_[10]=n[2]?.key??0,_[11]=d?u.key:0,_[12]=d?f.key:0,_[13]=i??0,_[14]=p;const g=Tf(_);let v=this.cache.get(g);if(v)for(let w=0;w<v.length;w++){const C=v[w];if(Jx.equals(C.hashes,_))return C.pipeline}const x=$b[m],y=this.getPipelineLayout(n),S=this.vertexBufferLayout.get(t,s),T=new Jb;return T.hashes=new Uint32Array(_),T.pipeline=this.create(x,i,r,a,y,o,c,S,h,d,u,f,p),v?v.push(T):v=[T],this.cache.set(g,v),T.pipeline}getBlend(e){let t;return e.blend&&(t={color:{operation:Nv[e.colorOp],srcFactor:gh[e.colorSrcFactor],dstFactor:gh[e.colorDstFactor]},alpha:{operation:Nv[e.alphaOp],srcFactor:gh[e.alphaSrcFactor],dstFactor:gh[e.alphaDstFactor]}}),t}getDepthStencil(e,t,s,i,r,a){let n;const{depth:o,stencil:c}=t;if(o||c){if(n={format:t.impl.depthAttachment.format},o){n.depthWriteEnabled=e.write,n.depthCompare=Kf[e.func];const h=a==="triangle-list"||a==="triangle-strip";n.depthBias=h?e.depthBias:0,n.depthBiasSlopeScale=h?e.depthBiasSlope:0}else n.depthWriteEnabled=!1,n.depthCompare="always";c&&s&&(n.stencilReadMas=i.readMask,n.stencilWriteMask=i.writeMask,n.stencilFront={compare:Kf[i.func
2],failOp:Pn[i.fail],passOp:Pn[i.zpass],depthFailOp:Pn[i.zfail]},n.stencilBack={compare:Kf[r.func],failOp:Pn[r.fail],passOp:Pn[r.zpass],depthFailOp:Pn[r.zfail]})}return n}create(e,t,s,i,r,a,n,o,c,h,d,u,f){const p=this.device.wgpu,m=s.impl,_={vertex:{module:m.getVertexShaderModule(),entryPoint:m.vertexEntryPoint,buffers:o},primitive:{topology:e,frontFace:Zb[f],cullMode:Kb[c]},depthStencil:this.getDepthStencil(n,i,h,d,u,e),multisample:{count:i.samples},layout:r};t&&(_.primitive.stripIndexFormat=Qb[t]),_.fragment={module:m.getFragmentShaderModule(),entryPoint:m.fragmentEntryPoint,targets:[]};const g=i.impl.colorAttachments;if(g.length>0){let x=0;a.redWrite&&(x|=GPUColorWrite.RED),a.greenWrite&&(x|=GPUColorWrite.GREEN),a.blueWrite&&(x|=GPUColorWrite.BLUE),a.alphaWrite&&(x|=GPUColorWrite.ALPHA);const y=this.getBlend(a);g.forEach(S=>{_.fragment.targets.push({format:S.format,writeMask:x,blend:y})})}return p.createRenderPipeline(_)}}class tA{pipeline=null;hashes=null}class sA extends eT{lookupHashes=new Uint32Array(2);cache=new Map;get(e,t){const s=this.lookupHashes;s[0]=e.impl.computeKey,s[1]=t.impl.key;const i=Tf(s);let r=this.cache.get(i);if(r)for(let o=0;o<r.length;o++){const c=r[o];if(Jx.equals(c.hashes,s))return c.pipeline}const a=this.getPipelineLayout([t.impl]),n=new tA;return n.hashes=new Uint32Array(s),n.pipeline=this.create(e,a),r?r.push(n):r=[n],this.cache.set(i,r),n.pipeline}create(e,t){const s=this.device.wgpu,i=e.impl,r={compute:{module:i.getComputeShaderModule(),entryPoint:i.computeEntryPoint},layout:t};return s.createComputePipeline(r)}}class Cf{_refCount=0;incRefCount(){this._refCount++}decRefCount(){this._refCount--}get refCount(){return this._refCount}}class iA extends Cf{object;constructor(e){super(),this.object=e,this.incRefCount()}}class rA{cache=new Map;destroy(){this.cache.forEach(e=>{e.object?.destroy()}),this.cache.clear()}clear(){this.cache.clear()}get(e){const t=this.cache.get(e);return t?(t.incRefCount(),t.object):null}set(e,t){this.cache.set(e,new iA(t))}release(e){const t=this.cache.get(e);t&&(t.decRefCount(),t.refCount===0&&(this.cache.delete(e),t.object?.destroy()))}}class aA extends rA{loseContext(e){this.clear()}}const nA=new Jt,Yl=l=>nA.get(l,()=>new aA),oA=new _n;class lA{format;multisampledBuffer;destroy(e){e.deferDestroy(this.multisampledBuffer),this.multisampledBuffer=null}}class kv{format;hasStencil;depthTexture=null;depthTextureInternal=!1;multisampledDepthBuffer=null;multisampledDepthBufferKey;constructor(e){this.format=e,this.hasStencil=e==="depth24plus-stencil8"}destroy(e){this.depthTextureInternal&&(e.deferDestroy(this.depthTexture),this.depthTexture=null),this.multisampledDepthBuffer&&(this.multisampledDepthBuffer=null,Yl(e).release(this.multisampledDepthBufferKey))}}class cA{initialized=!1;key;colorAttachments=[];depthAttachment=null;assignedColorTexture=null;renderPassDescriptor={};isBackbuffer=!1;constructor(e){this.renderTarget=e}destroy(e){this.initialized=!1,this.assignedColorTexture=null,this.colorAttachments.forEach(t=>{t.destroy(e)}),this.colorAttachments.length=0,this.depthAttachment?.destroy(e),this.depthAttachment=null}updateKey(){let t=`${this.renderTarget.samples}:${this.depthAttachment?this.depthAttachment.format:"nodepth"}`;this.colorAttachments.forEach(s=>{t+=`:${s.format}`}),this.key=oA.get(t)}assignColorTexture(e,t){this.assignedColorTexture=e;const s=this.renderTarget.device,i=s?.xrColorTextureViewDescriptor,r=i&&e===s.xrColorTexture,a=e.createView(r?i:{format:t}),n=this.renderPassDescriptor.colorAttachments[0];this.renderTarget.samples>1?n.resolveTarget=a:n.view=a,this.setColorAttachment(0,void 0,t),this.updateKey()}setColorAttachment(e,t,s){this.colorAttachments[e]||(this.colorAttachments[e]=new lA),t&&(this.colorAttachments[e].multisampledBuffer=t),s&&(this.colorAttachments[e].format=s)}init(e,t){const s=e.wgpu;this.initDepthStencil(e,s,t),t._colorBuffers&&t._colorBuffers.forEach((r,a)=>{this.setColorAttachment(a,void 0,r.impl.format)}),this.renderPassDescriptor.colorAttachments=[];const i=this.isBackbuffer?1:t._colorBuffers?.length??0;for(let r=0;r<i;++r){const a=this.initColor(e,s,t,r),n=r===0&&this.colorAttachments[0]?.format;(a.view||n)&&this.renderPassDescriptor.colorAttachments.push(a)}this.updateKey(),this.initialized=!0}initDepthStencil(e,t,s){const{samples:i,width:r,height:a,depth:n,depthBuffer:o}=s;
2if(n||o){let c;if(o)if(this.depthAttachment=new kv(o.impl.format),i>1){const h="depth24plus-stencil8";this.depthAttachment.format=h,this.depthAttachment.hasStencil=h==="depth24plus-stencil8";const d=`${o.id}:${r}:${a}:${i}:${h}`,u=Yl(e);let f=u.get(d);if(!f){const p={size:[r,a,1],dimension:"2d",sampleCount:i,format:h,usage:GPUTextureUsage.RENDER_ATTACHMENT|(h!==o.impl.format?GPUTextureUsage.TEXTURE_BINDING:0)};f=t.createTexture(p),u.set(d,f)}this.depthAttachment.multisampledDepthBuffer=f,this.depthAttachment.multisampledDepthBufferKey=d,c=f.createView()}else{const h=o.impl.gpuTexture;this.depthAttachment.depthTexture=h,c=h.createView()}else{this.depthAttachment=new kv("depth24plus-stencil8");const h={size:[r,a,1],dimension:"2d",sampleCount:i,format:this.depthAttachment.format,usage:GPUTextureUsage.RENDER_ATTACHMENT};i>1?h.usage|=GPUTextureUsage.TEXTURE_BINDING:h.usage|=GPUTextureUsage.COPY_SRC;const d=t.createTexture(h);this.depthAttachment.depthTexture=d,this.depthAttachment.depthTextureInternal=!0,c=d.createView()}this.renderPassDescriptor.depthStencilAttachment={view:c}}}initColor(e,t,s,i){const r={},{samples:a,width:n,height:o,mipLevel:c}=s,h=s.getColorBuffer(i);let d=null;if(h&&(h.cubemap?d=h.impl.createView({dimension:"2d",baseArrayLayer:s.face,arrayLayerCount:1,mipLevelCount:1,baseMipLevel:c}):d=h.impl.createView({mipLevelCount:1,baseMipLevel:c})),a>1){const u=this.isBackbuffer?this.colorAttachments[i]?.format??e.backBufferViewFormat:h.impl.format,f={size:[n,o,1],dimension:"2d",sampleCount:a,format:u,usage:GPUTextureUsage.RENDER_ATTACHMENT},p=t.createTexture(f);this.setColorAttachment(i,p,f.format),r.view=p.createView(),r.resolveTarget=d}else r.view=d;return r}setupForRenderPass(e,t){const s=this.renderPassDescriptor.colorAttachments?.length??0;for(let r=0;r<s;++r){const a=this.renderPassDescriptor.colorAttachments[r],n=e.colorArrayOps[r],o=t.isColorBufferSrgb(r);a.clearValue=o?n.clearValueLinear:n.clearValue,a.loadOp=n.clear?"clear":"load",a.storeOp=n.store?"store":"discard"}const i=this.renderPassDescriptor.depthStencilAttachment;i&&(i.depthClearValue=e.depthStencilOps.clearDepthValue,i.depthLoadOp=e.depthStencilOps.clearDepth?"clear":"load",i.depthStoreOp=e.depthStencilOps.storeDepth?"store":"discard",i.depthReadOnly=!1,this.depthAttachment.hasStencil&&(i.stencilClearValue=e.depthStencilOps.clearStencilValue,i.stencilLoadOp=e.depthStencilOps.clearStencil?"clear":"load",i.stencilStoreOp=e.depthStencilOps.storeStencil?"store":"discard",i.stencilReadOnly=!1))}loseContext(){this.initialized=!1}resolve(e,t,s,i){}}const Ot=[];Ot[me]=1;Ot[sn]=2;Ot[hs]=3;Ot[Cr]=4;Ot[_r]=1;Ot[$a]=2;Ot[gr]=3;Ot[Ka]=4;Ot[So]=1;Ot[oc]=2;Ot[lc]=3;Ot[cc]=4;Ot[su]=8;Ot[Do]=12;Ot[Ss]=16;Ot[le]=1;Ot[Mo]=2;Ot[Ro]=3;Ot[oa]=4;class X{name;type;byteSize;offset;scopeId;count;numComponents;get isArrayType(){return this.count>0}constructor(e,t,s=0){if(this.shortName=e,this.name=s?`${e}[0]`:e,this.type=t,this.numComponents=Ot[t],this.updateType=t,s>0)switch(t){case me:this.updateType=df;break;case _r:this.updateType=Lo;break;case le:this.updateType=pf;break;case So:this.updateType=mf;break;case sn:this.updateType=uf;break;case $a:this.updateType=Fo;break;case Mo:this.updateType=_f;break;case oc:this.updateType=gf;break;case hs:this.updateType=ff;break;case gr:this.updateType=Oo;break;case Ro:this.updateType=vf;break;case lc:this.updateType=Sf;break;case Cr:this.updateType=pg;break;case Ka:this.updateType=iu;break;case oa:this.updateType=mg;break;case cc:this.updateType=_g;break;case Ss:this.updateType=Ux;break}this.count=s;let i=this.numComponents;s&&(i=H.roundUp(i,4)),this.byteSize=i*4,s&&(this.byteSize*=s)}calculateOffset(e){let t=this.byteSize<=8?this.byteSize:16;this.count&&(t=16),e=H.roundUp(e,t),this.offset=e/4}}class vt{byteSize=0;map=new Map;constructor(e,t){this.scope=e.scope,this.uniforms=t;let s=0;for(let i=0;i<t.length;i++){const r=t[i];r.calculateOffset(s),s=r.offset*4+r.byteSize,r.scopeId=this.scope.resolve(r.name),this.map.set(r.name,r)}this.byteSize=H.roundUp(s,16)}get(e){return this.map.get(e)}}const Uv=/[ \t]*(\battribute\b|\bvarying\b|\buniform\b)/g,Zf=/(\battribute\b|\bvarying\b|\bout\b|\buniform\b)[ \t]*([^;]+)(;+)/g,Qf="@@@",hA=/([\w-]+)\[(.*?)\]/,dA=new Set(["highp","mediump","lowp"]),uA=new Set(["sampler2DShadow","samplerCubeShadow","sampler2DArrayShadow"]),fA={sampler2D:ys,sampler3D:vo,samplerCube:dr,samplerCubeShadow:dr,sampler2DShadow:ys,sampler2DArray:hr,sampler2DArrayShadow:hr,isampler2D:ys,usampler2D:ys,isampler3D:vo,usampler3D:vo,isamplerCube:dr,usamplerCube:dr,isampler2DArray:hr,usampler2DArray:hr},pA={[ys]:"texture2D",[dr]:"textureCube",[vo]:"texture3D",[hr]:"texture2DArray"};let mA=class{constructor(e,t){this.line=e;const s=e.trim().split(/\s+/);if(dA.has(s[0])&&(this.precision=s.shift()),this.type=s.shift(),e.includes(","),e.includes("[")){const i=s.join(" "),r=hA.exec(i);this.name=r[1],this.arraySize=Number(r[2]),isNaN(this.arraySize)&&(t.failed=!0)}else this.name=s.shift(),this.arraySize=0;
2this.isSampler=this.type.indexOf("sampler")!==-1,this.isSignedInt=this.type.indexOf("isampler")!==-1,this.isUnsignedInt=this.type.indexOf("usampler")!==-1}};class $t{static run(e,t,s){const i=new Map,r=$t.extract(t.vshader),a=$t.extract(t.fshader),n=new Map,o=$t.processAttributes(r.attributes,t.attributes,n,t.processingOptions),c=$t.processVaryings(r.varyings,i,!0),h=$t.processVaryings(a.varyings,i,!1),d=$t.processOuts(a.outs),u=r.uniforms.concat(a.uniforms),p=Array.from(new Set(u)).map(y=>new mA(y,s)),m=$t.processUniforms(e,p,t.processingOptions,s),_=`${o} 3${c} 4${m.code}`,g=r.src.replace(Qf,_),v=`${h} 5${d} 6${m.code}`,x=a.src.replace(Qf,v);return{vshader:g,fshader:x,attributes:n,meshUniformBufferFormat:m.meshUniformBufferFormat,meshBindGroupFormat:m.meshBindGroupFormat}}static extract(e){const t=[],s=[],i=[],r=[];let a=`${Qf} 7`,n;for(;(n=Uv.exec(e))!==null;){const o=n[1];switch(o){case"attribute":case"varying":case"uniform":case"out":{Zf.lastIndex=n.index;const c=Zf.exec(e);o==="attribute"?t.push(c[2]):o==="varying"?s.push(c[2]):o==="out"?i.push(c[2]):o==="uniform"&&r.push(c[2]),e=$t.cutOut(e,n.index,Zf.lastIndex,a),Uv.lastIndex=n.index+a.length,a="";break}}}return{src:e,attributes:t,varyings:s,outs:i,uniforms:r}}static processUniforms(e,t,s,i){const r=[],a=[];t.forEach(u=>{u.isSampler?r.push(u):a.push(u)});const n=[];a.forEach(u=>{if(!s.hasUniform(u.name)){const f=xv.indexOf(u.type),p=new X(u.name,f,u.arraySize);n.push(p)}}),n.length===0&&n.push(new X(gg,me));const o=n.length?new vt(e,n):null,c=[];r.forEach(u=>{if(!s.hasTexture(u.name)){let f=ls;u.isSignedInt?f=aa:u.isUnsignedInt?f=na:(u.precision==="highp"&&(f=da),uA.has(u.type)&&(f=gi));const p=fA[u.type];c.push(new No(u.name,rn|an,p,f))}});const h=new Ze(e,c);let d="";return s.uniformFormats.forEach((u,f)=>{u&&(d+=$t.getUniformShaderDeclaration(u,f,0))}),o&&(d+=$t.getUniformShaderDeclaration(o,Bo,0)),s.bindGroupFormats.forEach((u,f)=>{u&&(d+=$t.getTexturesShaderDeclaration(u,f))}),d+=$t.getTexturesShaderDeclaration(h,Yc),{code:d,meshUniformBufferFormat:o,meshBindGroupFormat:h}}static processVaryings(e,t,s){let i="";const r=s?"out":"in";return e.forEach((a,n)=>{const o=$t.splitToWords(a),c=o.slice(0,-1).join(" "),h=o[o.length-1];s?t.set(h,n):n=t.get(h),i+=`layout(location = ${n}) ${r} ${c} ${h}; 8`}),i}static processOuts(e){let t="";return e.forEach((s,i)=>{t+=`layout(location = ${i}) out ${s}; 9`}),t}static getTypeCount(e){const t=e.substring(e.length-1),s=parseInt(t,10);return isNaN(s)?1:s}static processAttributes(e,t,s,i){let r="";return e.forEach(a=>{const n=$t.splitToWords(a);let o=n[0],c=n[1];if(t.hasOwnProperty(c)){const h=t[c],d=Be[h];s.set(d,c);let u;const f=i.getVertexElement(h);if(f){const p=f.dataType;if(p!==je&&p!==hf&&!f.normalize&&!f.asInt){const m=$t.getTypeCount(o),_=`_private_${c}`;u=`vec${m} ${c} = vec${m}(${_}); 10`,c=_;const g=p===ua||p===fa||p===Yo;m===1?o=g?"int":"uint":o=g?`ivec${m}`:`uvec${m}`}}r+=`layout(location = ${d}) in ${o} ${c}; 11`,u&&(r+=u)}}),r}static splitToWords(e){return e=e.replace(/\s+/g," ").trim(),e.split(" ")}static cutOut(e,t,s,i){return e.substring(0,t)+i+e.substring(s)}static getUniformShaderDeclaration(e,t,s){const i=Kx[t];let r=`layout(set = ${t}, binding = ${s}, std140) uniform ub_${i} { 12`;
12return e.uniforms.forEach(a=>{const n=xv[a.type];r+=` ${n} ${a.shortName}${a.count?`[${a.count}]`:""}; 13`}),`${r}}; 14`}static getTexturesShaderDeclaration(e,t){let s="";return e.textureFormats.forEach(i=>{let r=pA[i.textureDimension];const a=r==="texture2DArray",n=i.sampleType===na?"u":i.sampleType===aa?"i":"";r=`${n}${r}`;let o="",c="";a&&(o="_texture",c=`#define ${i.name} ${n}sampler2DArray(${i.name}${o}, ${i.name}_sampler) 15`),s+=`layout(set = ${t}, binding = ${i.slot}) uniform ${r} ${i.name}${o}; 16`,i.hasSampler&&(s+=`layout(set = ${t}, binding = ${i.slot+1}) uniform sampler ${i.name}_sampler; 17`),s+=c}),s}}const zv=/^[ \t]*(attribute|varying|uniform)[\t ]+/gm,Jf=/^[ \t]*(attribute|varying|uniform)[ \t]*([^;]+)(;+)/gm,ep=/^[ \t]*var\s*(?:(<storage,[^>]*>)\s*([\w\d_]+)\s*:\s*(.*?)\s*;|(<(?!storage,)[^>]*>)?\s*([\w\d_]+)\s*:\s*(texture_.*|storage_texture_.*|storage\w.*|external_texture|sampler(?:_comparison)?)\s*;)\s*$/gm,_A=/(?:@interpolate\([^)]*\)\s*)?([\w]+)\s*:\s*([\w<>]+)/,tp="@@@",sp=/(@vertex|@fragment)\s*fn\s+\w+\s*\(\s*(\w+)\s*:[\s\S]*?\{/,Vv=[{wgslName:"position",wgslType:"vec4f",wgslBuiltin:"position",pcName:"pcPosition",isFallback:!0},{wgslName:"frontFacing",wgslType:"bool",wgslBuiltin:"front_facing",pcName:"pcFrontFacing"},{wgslName:"sampleIndex",wgslType:"u32",wgslBuiltin:"sample_index",pcName:"pcSampleIndex"},{wgslName:"primitiveIndex",wgslType:"u32",wgslBuiltin:"primitive_index",pcName:"pcPrimitiveIndex",requiresFeature:"supportsPrimitiveIndex"}],Gv=[{wgslName:"vertexIndex",wgslType:"u32",wgslBuiltin:"vertex_index",pcName:"pcVertexIndex",isFallback:!0},{wgslName:"instanceIndex",wgslType:"u32",wgslBuiltin:"instance_index",pcName:"pcInstanceIndex"}],Hv=(l,e,t,s)=>l.filter(i=>i.requiresFeature&&!s[i.requiresFeature]?!1:new RegExp(`\\b(?:${i.pcName}|${t}\\.${i.wgslName})\\b`).test(e)),Wv=(l,e,t,s)=>{if(l.length===0&&!s){const i=e.find(r=>r.isFallback&&(!r.requiresFeature||t[r.requiresFeature]));if(i)return[i]}return l},Xv=l=>l.map(e=>` @builtin(${e.wgslBuiltin}) ${e.wgslName} : ${e.wgslType}, 18`).join(""),Yv=l=>l.map(e=>` var<private> ${e.pcName}: ${e.wgslType}; 19`).join(""),jv=l=>l.map(e=>` ${e.pcName} = input.${e.wgslName}; 20`).join(""),gA={texture_1d:{viewDimension:kx,baseSampleType:ls},texture_2d:{viewDimension:ys,baseSampleType:ls},texture_2d_array:{viewDimension:hr,baseSampleType:ls},texture_3d:{viewDimension:vo,baseSampleType:ls},texture_cube:{viewDimension:dr,baseSampleType:ls},texture_cube_array:{viewDimension:tu,baseSampleType:ls},texture_multisampled_2d:{viewDimension:ys,baseSampleType:ls},texture_depth_2d:{viewDimension:ys,baseSampleType:gi},texture_depth_2d_array:{viewDimension:hr,baseSampleType:gi},texture_depth_cube:{viewDimension:dr,baseSampleType:gi},texture_depth_cube_array:{viewDimension:tu,baseSampleType:gi},texture_external:{viewDimension:ys,baseSampleType:da}},vA=(l,e)=>{const t=gA[l];let s=t.baseSampleType;if(t.baseSampleType===ls&&l!=="texture_multisampled_2d")switch(e){case"u32":s=na;break;case"i32":s=aa;break;case"f32":s=ls;break;case"uff":s=da;break}return{viewDimension:t.viewDimension,sampleType:s}},SA=(l,e)=>{if(e===gi)switch(l){case ys:return"texture_depth_2d";case hr:return"texture_depth_2d_array";case dr:return"texture_depth_cube";case tu:return"texture_depth_cube_array"}let t;switch(l){case kx:t="texture_1d";break;case ys:t="texture_2d";break;case hr:t="texture_2d_array";break;case vo:t="texture_3d";break;case dr:t="texture_cube";break;case tu:t="texture_cube_array";break}let s;switch(e){case ls:case da:s="f32";break;case na:s="u32";break;case aa:s="i32";break}return`${t}<${s}>`},qv={f32:"WrappedF32",i32:"WrappedI32",u32:"WrappedU32",vec2f:"WrappedVec2F",vec2i:"WrappedVec2I",vec2u:"WrappedVec2U"},tT=l=>(l=l.replace(/\s+/g," ").trim(),l.split(/[\s:]+/)),yA=/array<([^,]+),\s*([^>]+)>/;class xA{ubName=null;arraySize=0;constructor(e,t){this.line=e;const s=tT(e);if(s.length<2){t.failed=!0;return}if(this.name=s[0],this.type=s.slice(1).join(" "),this.type.includes("array<")){const i=yA.exec(this.type);this.type=i[1].trim(),this.arraySize=Number(i[2]),isNaN(this.arraySize)&&(t.failed=!0)}}}const TA=/^\s*var\s+(\w+)\s*:\s*(texture_\w+)(?:<(\w+)>)?;\s*$/,wA=/^\s*var\s+([\w\d_]+)\s*:\s*(texture_storage_2d|texture_storage_2d_array)<([\w\d_]+),\s*(\w+)>\s*;\s*$/,CA=/^\s*var\s*<storage,\s*(read|write)?>\s*([\w\d_]+)\s*:\s*(.*)\s*;\s*$/,EA=/^\s*var\s+([\w\d_]+)\s*:\s*texture_external;\s*$/,bA=/^\s*var\s+([\w\d_]+)\s*:\s*(sampler|sampler_comparison)\s*;\s*$/;class $v{constructor(e,t){this.originalLine=e,this.line=e,this.isTexture=!1,this.isSampler=!1,this.isStorageTexture=!1,this.isStorageBuffer=!1,this.isExternalTexture=!1,this.type="",this.matchedElements=[];const s=this.line.match(TA);if(s){this.name=s[1],this.type=s[2],this.textureFormat=s[3],this.isTexture=!0,this.matchedElements.push(...s);
20const o=vA(this.type,this.textureFormat);this.textureDimension=o.viewDimension,this.sampleType=o.sampleType}const i=this.line.match(wA);i&&(this.isStorageTexture=!0,this.name=i[1],this.textureType=i[2],this.format=i[3],this.access=i[4],this.matchedElements.push(...i));const r=this.line.match(CA);r&&(this.isStorageBuffer=!0,this.accessMode=r[1]||"none",this.name=r[2],this.type=r[3],this.matchedElements.push(...r));const a=this.line.match(EA);a&&(this.name=a[1],this.isExternalTexture=!0,this.matchedElements.push(...r));const n=this.line.match(bA);n&&(this.name=n[1],this.samplerType=n[2],this.isSampler=!0,this.matchedElements.push(...n)),this.matchedElements.length===0&&(t.failed=!0)}equals(e){return!(this.name!==e.name||this.type!==e.type||this.isTexture!==e.isTexture||this.isSampler!==e.isSampler||this.isStorageTexture!==e.isStorageTexture||this.isStorageBuffer!==e.isStorageBuffer||this.isExternalTexture!==e.isExternalTexture||this.textureFormat!==e.textureFormat||this.textureDimension!==e.textureDimension||this.sampleType!==e.sampleType||this.textureType!==e.textureType||this.format!==e.format||this.access!==e.access||this.accessMode!==e.accessMode||this.samplerType!==e.samplerType)}}class bt{static run(e,t,s){const i=new Map,r=bt.extract(t.vshader),a=bt.extract(t.fshader),n=r.src.match(sp)?.[2]??"",o=a.src.match(sp)?.[2]??"",c=new Map,h=bt.processAttributes(r.attributes,t.attributes,c,t.processingOptions,s,e,r.src,n),d=bt.processVaryings(r.varyings,i,!0,e),u=bt.processVaryings(a.varyings,i,!1,e,a.src,o),f=r.uniforms.concat(a.uniforms),m=Array.from(new Set(f)).map(C=>new xA(C,s)),_=bt.processUniforms(e,m,t.processingOptions,s);r.src=bt.renameUniformAccess(r.src,m),a.src=bt.renameUniformAccess(a.src,m);const g=bt.mergeResources(r.resources,a.resources,s),v=bt.processResources(e,g,t.processingOptions,s),x=bt.generateFragmentOutputStruct(a.src,e.maxColorAttachments);r.src=bt.copyInputs(r.src,s),a.src=bt.copyInputs(a.src,s);const y=`${h} 21${d} 22${_.code} 23${v.code} 24`,S=r.src.replace(tp,y),T=`${u} 25${x} 26${_.code} 27${v.code} 28`,w=a.src.replace(tp,T);return{vshader:S,fshader:w,attributes:c,meshUniformBufferFormat:_.meshUniformBufferFormat,meshBindGroupFormat:v.meshBindGroupFormat}}static extract(e){const t=[],s=[],i=[],r=[];let a=`${tp} 29`,n;for(;(n=zv.exec(e))!==null;){const o=n[1];Jf.lastIndex=n.index;const c=Jf.exec(e);o==="attribute"?t.push(c[2]):o==="varying"?s.push(c[2]):o==="uniform"&&i.push(c[2]),e=bt.cutOut(e,n.index,Jf.lastIndex,a),zv.lastIndex=n.index+a.length,a=""}for(;(n=ep.exec(e))!==null;)r.push(n[0]),e=bt.cutOut(e,n.index,ep.lastIndex,a),ep.lastIndex=n.index+a.length,a="";return{src:e,attributes:t,varyings:s,uniforms:i,resources:r}}static processUniforms(e,t,s,i){const r=[];t.forEach(o=>{if(s.hasUniform(o.name))o.ubName="ub_view";else{o.ubName="ub_mesh_ub";const c=Vx.get(o.type),h=new X(o.name,c,o.arraySize);r.push(h)}}),r.length===0&&r.push(new X(gg,me));const a=new vt(e,r);let n="";return s.uniformFormats.forEach((o,c)=>{o&&(n+=bt.getUniformShaderDeclaration(o,c,0))}),a&&(n+=bt.getUniformShaderDeclaration(a,Bo,0)),{code:n,meshUniformBufferFormat:a}}static renameUniformAccess(e,t){return t.forEach(s=>{const i=`uniform.${s.name}`,r=`${s.ubName}.${s.name}`,a=new RegExp(`\\b${i}\\b`,"g");e=e.replace(a,r)}),e}static mergeResources(e,t,s){const i=e.map(a=>
29new $v(a,s));return t.map(a=>new $v(a,s)).forEach(a=>{const n=i.find(o=>o.name===a.name);n?n.equals(a)||(s.failed=!0):i.push(a)}),i}static processResources(e,t,s,i){const r=[];for(let o=0;o<t.length;o++){const c=t[o];if(c.isTexture){const h=t[o+1],d=h?.isSampler,u=c.sampleType,f=c.textureDimension;r.push(new No(c.name,rn|an,f,u,d,d?h.name:null)),d&&o++}if(c.isStorageBuffer){const h=c.accessMode!=="read_write",d=new q(c.name,rn|an,h);d.format=c.type,r.push(d)}}const a=new Ze(e,r);let n="";return s.bindGroupFormats.forEach((o,c)=>{o&&(n+=bt.getTextureShaderDeclaration(o,c))}),n+=bt.getTextureShaderDeclaration(a,Yc),{code:n,meshBindGroupFormat:a}}static getUniformShaderDeclaration(e,t,s){const i=Kx[t],r=`struct_ub_${i}`;let a=`struct ${r} { 30`;return e.uniforms.forEach(n=>{let o=zx[n.type][0];n.count>0?(qv.hasOwnProperty(o)&&(o=qv[o]),a+=` ${n.shortName}: array<${o}, ${n.count}>, 31`):a+=` ${n.shortName}: ${o}, 32`}),a+=`}; 33`,a+=`@group(${t}) @binding(${s}) var<uniform> ub_${i} : ${r}; 34 35`,a}static getTextureShaderDeclaration(e,t){let s="";return e.textureFormats.forEach(i=>{const r=SA(i.textureDimension,i.sampleType);if(s+=`@group(${t}) @binding(${i.slot}) var ${i.name}: ${r}; 36`,i.hasSampler){const a=i.sampleType===gi?"sampler_comparison":"sampler";s+=`@group(${t}) @binding(${i.slot+1}) var ${i.samplerName}: ${a}; 37`}}),e.storageBufferFormats.forEach(i=>{const r=i.readOnly?"read":"read_write";s+=`@group(${t}) @binding(${i.slot}) var<storage, ${r}> ${i.name} : ${i.format}; 38`}),s}static processVaryings(e,t,s,i,r="",a=""){let n="",o="",c="";if(e.forEach((d,u)=>{const f=d.match(_A);if(f){const p=f[1],m=f[2];s?t.set(p,u):u=t.get(p),n+=` @location(${u}) ${d}, 39`,s||(o+=` var<private> ${p}: ${m}; 40`,c+=` ${p} = input.${p}; 41`)}}),s)return n+=` @builtin(position) position : vec4f, 42`,` 43 struct VertexOutput { 44 ${n} 45 }; 46 `;const h=Wv(Hv(Vv,r,a,i),Vv,i,n.length>0);return n+=Xv(h),` 47 struct FragmentInput { 48 ${n} 49 }; 50 51 ${Yv(h)} 52 ${o} 53 54 // function to copy inputs (varyings) to private global variables 55 fn _pcCopyInputs(input: FragmentInput) { 56 ${c} 57 ${jv(h)} 58 } 59 `}static generateFragmentOutputStruct(e,t){let s=`struct FragmentOutput { 60`;const i=a=>`color${a>0?a:""}`;for(let a=0;a<t;a++){const n=i(a);e.search(new RegExp(`\\.${n}\\s*=`))!==-1&&(s+=` @location(${a}) ${n} : pcOutType${a}, 61`)}return e.search(/\.fragDepth\s*=/)!==-1&&(s+=` @builtin(frag_depth) fragDepth : f32 62`),`${s}}; 63`}static floatAttributeToInt(e,t){const i={f32:"f32","vec2<f32>":"vec2f","vec3<f32>":"vec3f","vec4<f32>":"vec4f"}[e]||e;return{f32:t?"i32":"u32",vec2f:t?"vec2i":"vec2u",vec3f:t?"vec3i":"vec3u",vec4f:t?"vec4i":"vec4u"}[i]||null}static processAttributes(e,t={},s,i,r,a,n="",o=""){let c="",h="",d="";e.forEach(f=>{const p=tT(f),m=p[0];let _=p[1];const g=_;if(t.hasOwnProperty(m)){const v=t[m],x=Be[v];s.set(x,m);const y=i.getVertexElement(v);if(y){const S=y.dataType;if(S!==je&&S!==hf&&!y.normalize&&!y.asInt){const T=S===ua||S===fa||S===Yo;_=bt.floatAttributeToInt(_,T)}}c+=` @location(${x}) ${m}: ${_}, 64`,h+=` var<private> ${f}; 65`,d+=` ${m} = ${g}(input.${m}); 66`}});const u=Wv(Hv(Gv,n,o,a),Gv,a,c.length>0);return` 67 struct VertexInput { 68 ${c} 69 ${Xv(u)} 70 }; 71 72 ${h} 73 ${Yv(u)} 74 75 fn _pcCopyInputs(input: VertexInput) { 76 ${d} 77 ${jv(u)} 78 } 79 `}static copyInputs(e,t){const s=e.match(sp);if(!s||!s[2])return e;const i=s[2],r=s.index+s[0].length-1,a=e.slice(0,r+1),n=e.slice(r+1),o=` 80 _pcCopyInputs(${i});`;return a+o+n}static cutOut(e,t,s,i){return e.substring(0,t)+i+e.substring(s)}}const AA=new _n;class PA{_vertexCode=null;_fragmentCode=null;_computeCode=null;_computeKey;vertexEntryPoint="main";fragmentEntryPoint="main";computeEntryPoint="main";constructor(e){this.shader=e;const t=e.definition;t.shaderLanguage===de?(t.cshader?(this._computeCode=t.cshader??null,this.computeUniformBufferFormats=t.computeUniformBufferFormats,this.computeBindGroupFormat=t.computeBindGroupFormat,t.computeEntryPoint&&(this.computeEntryPoint=t.computeEntryPoint)):(this.vertexEntryPoint="vertexMain",this.fragmentEntryPoint="fragmentMain",t.processingOptions?this.processWGSL():(this._vertexCode=t.vshader??null,this._fragmentCode=t.fshader??null,e.meshUniformBufferFormat=t.meshUniformBufferFormat,e.meshBindGroupFormat=t.meshBindGroupFormat)),e.ready=!0):t.processingOptions&&this.processGLSL()}destroy(e){this._vertexCode=null,this._fragmentCode=null}createShaderModule(e,t){return this.shader.device.wgpu.createShaderModule({code:e})}getVertexShaderModule(){return this.createShaderModule(this._vertexCode,"Vertex")}getFragmentShaderModule(){return this.createShaderModule(this._fragmentCode,"Fragment")}getComputeShaderModule(){return this.createShaderModule(this._computeCode,"Compute")}processGLSL(){const e=this.shader,t=$t.run(e.device,e.definition,e);this._vertexCode=this.transpile(t.vshader,"vertex",e.definition.vshader),this._fragmentCode=this.transpile(t.fshader,"fragment",e.definition.fshader),this._vertexCode&&this._fragmentCode?e.ready=!0:e.failed=!0,e.meshUniformBufferFormat=t.meshUniformBufferFormat,e.meshBindGroupFormat=t.meshBindGroupFormat,e.attributes=t.attributes}processWGSL(){const e=this.shader,t=bt.run(e.device,e.definition,e);this._vertexCode=t.vshader,this._fragmentCode=t.fshader,e.meshUniformBufferFormat=t.meshUniformBufferFormat,e.meshBindGroupFormat=t.meshBindGroupFormat,e.attributes=t.attributes}transpile(e,t,s){const i=this.shader.device;if(!i.glslang||!i.twgsl)return console.error(`Cannot transpile shader [${this.shader.label}] - shader transpilers (glslang/twgsl) are not available. Make sure to provide glslangUrl and twgslUrl when creating the device.`,{shader:this.shader}),null;try{const r=i.glslang.compileGLSL(e,t);return i.twgsl.convertSpirV2WGSL(r)}catch(r){console.error(`Failed to transpile webgl ${t} shader [${this.shader.label}] to WebGPU while rendering undefined, error: 81 [${r.stack}]`,{processed:e,original:s,shader:this.shader,error:r,stack:r.stack})}}get vertexCode(){return this._vertexCode}get fragmentCode(){return this._fragmentCode}
81get computeKey(){if(this._computeKey===void 0){const e=`${this._computeCode}|${this.computeEntryPoint}`;this._computeKey=AA.get(e)}return this._computeKey}loseContext(){}restoreContext(e,t){}}const xo=[];xo[Ft]="repeat";xo[ue]="clamp-to-edge";xo[Iu]="mirror-repeat";const vr=[];vr[Fe]={level:"nearest",mip:"nearest"};vr[It]={level:"linear",mip:"nearest"};vr[Ac]={level:"nearest",mip:"nearest"};vr[Pc]={level:"nearest",mip:"linear"};vr[Ic]={level:"linear",mip:"nearest"};vr[ia]={level:"linear",mip:"linear"};const IA=l=>{};class DA{gpuTexture;view;samplers=[];desc;format;viewCache=new Map;constructor(e){this.texture=e,this.format=re[e.format],this.create(e.device)}create(e){const t=this.texture,s=e.wgpu,i=t.numLevels;Sd(t.format)&&(t.width%4!==0||t.height%4!==0)&&(t._width=H.roundUp(t.width,4),t._height=H.roundUp(t.height,4)),this.desc={size:{width:t.width,height:t.height,depthOrArrayLayers:t.cubemap?6:t.array?t.arrayLength:1},format:this.format,mipLevelCount:i,sampleCount:1,dimension:t.volume?"3d":"2d",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC|(Sd(t.format)?0:GPUTextureUsage.RENDER_ATTACHMENT)|(t.storage?GPUTextureUsage.STORAGE_BINDING:0)},this.gpuTexture=s.createTexture(this.desc);let r;this.texture.format===en&&(r={format:"depth24plus",aspect:"depth-only"}),this.view=this.createView(r),this.viewCache.clear()}destroy(e){e.deferDestroy(this.gpuTexture),this.gpuTexture=null,this.view=null,this.viewCache.clear(),this.samplers.length=0}propertyChanged(e){this.samplers.length=0}getView(e,t){if(this.uploadImmediate(e,this.texture),t){let s=this.viewCache.get(t.key);return s||(s=this.createView({baseMipLevel:t.baseMipLevel,mipLevelCount:t.mipLevelCount,baseArrayLayer:t.baseArrayLayer,arrayLayerCount:t.arrayLayerCount}),this.viewCache.set(t.key,s)),s}return this.view}createView(e){const t=e??{},s=this.desc,i=this.texture,r=()=>i.cubemap?"cube":i.volume?"3d":i.array?"2d-array":"2d",a={format:t.format??s.format,dimension:t.dimension??r(),aspect:t.aspect??"all",baseMipLevel:t.baseMipLevel??0,mipLevelCount:t.mipLevelCount??s.mipLevelCount,baseArrayLayer:t.baseArrayLayer??0,arrayLayerCount:t.arrayLayerCount??s.depthOrArrayLayers};return this.gpuTexture.createView(a)}getSampler(e,t){let s=this.samplers[t];if(!s){const i=this.texture,r={addressModeU:xo[i.addressU],addressModeV:xo[i.addressV],addressModeW:xo[i.addressW]};!t&&i.compareOnRead&&(t=gi),t===gi||t===aa||t===na?(r.compare="less",r.magFilter="linear",r.minFilter="linear"):t===da||!e.textureFloatFilterable&&(i.format===mt||i.format===Ge)||this.texture.format===en||Qr(this.texture.format)?(r.magFilter="nearest",r.minFilter="nearest",r.mipmapFilter="nearest"):(r.magFilter=vr[i.magFilter].level,r.minFilter=vr[i.minFilter].level,r.mipmapFilter=vr[i.minFilter].mip);const a=r.minFilter==="linear"&&r.magFilter==="linear"&&r.mipmapFilter==="linear";r.maxAnisotropy=a?H.clamp(Math.round(i._anisotropy),1,e.maxTextureAnisotropy):1,s=e.wgpu.createSampler(r),this.samplers[t]=s}return s}loseContext(){}uploadImmediate(e,t){(t._needsUpload||t._needsMipmapsUpload)&&(this.uploadData(e),t._needsUpload=!1,t._needsMipmapsUpload=!1)}uploadData(e){const t=this.texture;if(this.desc&&(this.desc.size.width!==t.width||this.desc.size.height!==t.height)&&(e.deferDestroy(this.gpuTexture),this.create(e),t.renderVersionDirty=e.renderVersion),t._levels){let s=!1,i=!1;const r=t.numLevels;for(let a=0;a<r;a++){const n=t._levels[a];if(n){if(t.cubemap)for(let o=0;o<6;o++){const c=n[o];c?this.isExternalImage(c)?(this.uploadExternalImage(e,c,a,o),s=!0):ArrayBuffer.isView(c)&&(this.uploadTypedArrayData(e,c,a,o),s=!0):i=!0}else if(!t._volume)if(t.array)if(t.arrayLength===n.length)for(let o=0;o<t._arrayLength;o++){const c=n[o];this.isExternalImage(c)?(this.uploadExternalImage(e,c,a,o),s=!0):ArrayBuffer.isView(c)&&(this.uploadTypedArrayData(e,c,a,o),s=!0)}else i=!0;else e._isHTMLElementInterface(n)&&e.supportsHtmlTextures?(this.uploadElementImage(e,n,a,0),s=!0):this.isExternalImage(n)?(this.uploadExternalImage(e,n,a,0),s=!0):ArrayBuffer.isView(n)&&(this.uploadTypedArrayData(e,n,a,0),s=!0)}else i=!0}s&&i&&t.mipmaps&&!Sd(t.format)&&!Qr(t.format)&&e.mipmapRenderer.generate(this),t._gpuSize&&t.adjustVramSizeTracking(e._vram,-t._gpuSize),t._gpuSize=t.gpuSize,t.adjustVramSizeTracking(e._vram,t._gpuSize),t.releaseSourceAfterUpload&&t.releaseImageSources()}}isExternalImage(e){return typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas}uploadExternalImage(e,t,s,i){const r={source:t,origin:[0,0],flipY:!1},a={texture:this.gpuTexture,mipLevel:s,origin:[0,0,i],aspect:"all",premultipliedAlpha:this.texture._premultiplyAlpha},n={width:this.desc.size.width,height:this.desc.size.height,depthOrArrayLayers:1};e.submit(),IA(t instanceof HTMLCanvasElement&&t.getContext("2d")),e.wgpu.queue.copyExternalImageToTexture(r,a,n)}uploadElementImage(e,t,s,i){const r={texture:this.gpuTexture,mipLevel:s,origin:[0,0,i],aspect:"all",premultipliedAlpha:this.texture._premultiplyAlpha},a=Xt.calcLevelDimension(this.texture.width,s),n=Xt.calcLevelDimension(this.texture.height,s);e.submit();const o={source:t},c={destination:r,width:a,height:n};e.wgpu.queue.copyElementImageToTexture(o,c)}uploadTypedArrayData(e,t,s,i){const r=this.texture,a=e.wgpu,n={texture:this.gpuTexture,origin:[0,0,i],mipLevel:s},o=Xt.calcLevelDimension(r.width,s),c=Xt.calcLevelDimension(r.height,s);Xt.calcLevelGpuSize(o,c,1,r.format);const h=fs.get(r.format);let d,u;if(h.size)d={offset:0,bytesPerRow:h.size*o,rowsPerImage:c},u={width:o,height:c};else if(h.blockSize){const f=p=>Math.floor((p+3)/4);d={offset:0,bytesPerRow:h.blockSize*f(o),rowsPerImage:f(c)},u={width:Math.max(4,o),height:Math.max(4,c)}}e.submit(),a.queue.writeTexture(n,t,d,u)}read(e,t,s,i,r){const a=r.mipLevel??0,n=r.face??0,o=r.data??null,c=r.immediate??!1,h=this.texture,d=fs.get(h.format),u=s*d.size,f=H.roun
81dUp(u,256),p=f*i,m=h.device,_=m.createBufferImpl(Ox|ct);_.allocate(m,p);const g={texture:this.gpuTexture,mipLevel:a,origin:[e,t,n]},v={buffer:_.buffer,offset:0,bytesPerRow:f},x={width:s,height:i,depthOrArrayLayers:1};return m.getCommandEncoder().copyTextureToBuffer(g,v,x),m.readBuffer(_,p,null,c).then(S=>{const T=ng(h.format),w=o?.buffer??new ArrayBuffer(i*u),C=new Uint8Array(w,o?.byteOffset??0,i*u);for(let b=0;b<i;b++){const I=b*f,P=b*u;C.set(S.subarray(I,I+u),P)}return o??new T(w)})}}class MA extends wf{constructor(e){super(IE)}unlock(e){const t=e.device;super.unlock(t,e.storageInt32.buffer)}}class RA extends wf{constructor(e,t,s){super(PE|(s?.storage?$_:0))}unlock(e){const t=e.device;super.unlock(t,e.storage)}}const ai=/[ \t]*#(ifn?def|if|endif|else|elif|define|undef|extension|include)/g,ip=/define[ \t]+([^\n]+)\r?(?:\n|$)/g,Kv=/extension[ \t]+([\w-]+)[ \t]*:[ \t]*(enable|require)/g,rp=/undef[ \t]+([^\n]+)\r?(?:\n|$)/g,ap=/(ifdef|ifndef|if)[ \t]*([^\r\n]+)\r?\n/g,np=/(endif|else|elif)(?:[ \t]+([^\r\n]*))?\r?\n?/g,Zv=/\{?[\w-]+\}?/,LA=/(!|\s)?defined\(([\w-]+)\)/,FA=/!?defined\s*\([^)]*\)/g,OA=/!?defined\s*$/,BA=/([a-z_]\w
81*)\s*(==|!=|<|<=|>|>=)\s*([\w"']+)/i,NA=/[+\-]/g,op=/include[ \t]+"([\w-]+)(?:\s*,\s*([\w-]+))?"/g,kA=/\{i\}/g,Qv=/(pcFragColor[1-8])\b/g,UA=/^\d+(?:\.\d+)?$/;class Vt{static sourceName;static run(e,t=new Map,s={}){Vt.sourceName=s.sourceName,e=this.stripComments(e),e=e.split(/\r?\n/).map(n=>n.trimEnd()).join(` 82`);const i=new Map,r=new Map;if(e=this._preprocess(e,i,r,t,s.stripDefines),e===null)return null;const a=new Map;return i.forEach((n,o)=>{Number.isInteger(parseFloat(n))&&!n.includes(".")&&a.set(o,n)}),e=this.stripComments(e),e=this.stripUnusedColorAttachments(e,s),e=this.RemoveEmptyLines(e),e=this.processArraySize(e,a),e=this.injectDefines(e,r),e}static stripUnusedColorAttachments(e,t){if(t.stripUnusedColorAttachments){const s=new Map;if(e.match(Qv)?.forEach(a=>{const n=parseInt(a.charAt(a.length-1),10);s.set(n,(s.get(n)??0)+1)}),Array.from(s.values()).some(a=>a===1)){const a=e.split(` 83`),n=[];for(let o=0;o<a.length;o++){const c=a[o].match(Qv);if(c){const h=parseInt(c[0].charAt(c[0].length-1),10);if(h>0&&s.get(h)===1)continue}n.push(a[o])}e=n.join(` 84`)}}return e}static stripComments(e){return e.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm,"$1")}static processArraySize(e,t){return e!==null&&t.forEach((s,i)=>{e=e.replace(new RegExp(`\\[${i}\\]`,"g"),`[${s}]`)}),e}static injectDefines(e,t){if(e!==null&&t.size>0){const s=e.split(` 85`);t.forEach((i,r)=>{const a=new RegExp(r,"g");for(let n=0;n<s.length;n++)s[n].includes("#")||(s[n]=s[n].replace(a,i))}),e=s.join(` 86`)}return e}static RemoveEmptyLines(e){return e!==null&&(e=e.split(/\r?\n/).map(t=>t.trim()===""?"":t).join(` 87`),e=e.replace(/(\n\n){3,}/g,` 88 89`)),e}static _preprocess(e,t=new Map,s,i,r){const a=e,n=[];let o=!1,c;for(;(c=ai.exec(e))!==null&&!o;){const h=c[1];switch(h){case"define":{ip.lastIndex=c.index;const d=ip.exec(e);o||(o=d===null);const u=d[1];Zv.lastIndex=d.index;const p=Zv.exec(u)[0];let m=u.substring(p.length).trim();m===""&&(m="true");const _=Vt._keep(n);let g=r;if(_){const v=p.startsWith("{")&&p.endsWith("}");v&&(g=!0),v?s.set(p,m):t.set(p,m),g&&(e=e.substring(0,d.index-1)+e.substring(ip.lastIndex),ai.lastIndex=d.index-1)}g||(ai.lastIndex=d.index+d[0].length);break}case"undef":{rp.lastIndex=c.index;const d=rp.exec(e),u=d[1].trim();Vt._keep(n)&&(t.delete(u),r&&(e=e.substring(0,d.index-1)+e.substring(rp.lastIndex),ai.lastIndex=d.index-1)),r||(ai.lastIndex=d.index+d[0].length);break}case"extension":{Kv.lastIndex=c.index;const d=Kv.exec(e);if(o||(o=d===null),d){const u=d[1];Vt._keep(n)&&t.set(u,"true")}ai.lastIndex=d.index+d[0].length;break}case"ifdef":case"ifndef":case"if":{ap.lastIndex=c.index;const d=ap.exec(e),u=d[2],f=Vt.evaluate(u,t);o||(o=f.error);let p=f.result;h==="ifndef"&&(p=!p),n.push({anyKeep:p,keep:p,start:c.index,end:ap.lastIndex}),ai.lastIndex=d.index+d[0].length;break}case"endif":case"else":case"elif":{np.lastIndex=c.index;const d=np.exec(e),u=n.pop();if(!u){console.error(`Shader preprocessing encountered "#${d[1]}" without a preceding #if #ifdef #ifndef while preprocessing ${Vt.sourceName} on line: 90 ${e.substring(c.index,c.index+100)}...`,{source:a}),o=!0;continue}const f=u.keep?e.substring(u.end,c.index):"";e=e.substring(0,u.start)+f+e.substring(np.lastIndex),ai.lastIndex=u.start+f.length;const p=d[1];if(p==="else"||p==="elif"){let m=!1;if(!u.anyKeep)if(p==="else")m=!u.keep;else{const _=Vt.evaluate(d[2],t);m=_.result,o||(o=_.error)}n.push({anyKeep:u.anyKeep||m,keep:m,start:ai.lastIndex,end:ai.lastIndex})}break}case"include":{op.lastIndex=c.index;const d=op.exec(e);if(o||(o=d===null),!d){o=!0;continue}const u=d[1].trim(),f=d[2]?.trim();if(Vt._keep(n)){let m=i?.get(u);if(m!==void 0){if(m=this.stripComments(m),f){const _=t.get(f),g=parseFloat(_);if(Number.isInteger(g)){let v="";for(let x=0;x<g;x++)v+=m.replace(kA,String(x));m=v}else console.error(`Include Count identifier "${f}" not resolved while preprocessing ${Vt.sourceName} on line: 91 ${e.substring(c.index,c.index+100)}...`,{originalSource:a,source:e}),o=!0}e=e.substring(0,d.index-1)+m+e.substring(op.lastIndex),ai.lastIndex=d.index-1}else{console.error(`Include "${u}" not resolved while preprocessing ${Vt.sourceName}`,{originalSource:a,source:e}),o=!0;continue}}break}}}return n.length>0&&(console.error(`Shader preprocessing reached the end of the file without encountering the necessary #endif to close a preceding #if, #ifdef, or #ifndef block. ${Vt.sourceName}`),o=!0),o?(console.error("Failed to preprocess shader: ",{source:a}),null):e}static _keep(e){for(let t=0;t<e.length;t++)if(!e[t].keep)return!1;return!0}static evaluateAtomicExpression(e,t){let s=!1;e=e.trim();let i=!1;if(e==="true")return{result:!0,error:s};if(e==="false")return{result:!1,error:s};if(UA.test(e))return{result:parseFloat(e)!==0,error:s};const r=LA.exec(e);if(r){i=r[1]==="!",e=r[2].trim();const o=t.has(e);return{result:i?!o:o,error:s}}const a=BA.exec(e);if(a){const o=t.get(a[1].trim())??a[1].trim(),c=t.get(a[3].trim())??a[3].trim(),h=a[2].trim();let d=!1;switch(h){case"==":d=o===c;break;case"!=":d=o!==c;break;case"<":d=o<c;break;case"<=":d=o<=c;break;case">":d=o>c;break;case">=":d=o>=c;break;default:s=!0}
91return{result:d,error:s}}return{result:t.has(e),error:s}}static processParentheses(e,t){let s=!1,i=e.trim();for(;i.startsWith("(")&&i.endsWith(")");){let r=0,a=!0;for(let n=0;n<i.length-1;n++)if(i[n]==="(")r++;else if(i[n]===")"&&(r--,r===0)){a=!1;break}if(a)i=i.slice(1,-1).trim();else break}for(;;){let r=!1,a=0,n=0,o=-1,c=-1,h=0;for(let p=0;p<i.length;p++)if(i[p]==="("){const m=i.substring(0,p);OA.test(m)?h++:h===0&&(a++,a>n&&(n=a,o=p),r=!0)}else i[p]===")"&&(h>0?h--:a>0&&(a===n&&o!==-1&&(c=p),a--));if(!r||o===-1||c===-1)break;const d=i.substring(o+1,c),{result:u,error:f}=Vt.evaluate(d,t);s=s||f,i=i.substring(0,o)+(u?"true":"false")+i.substring(c+1)}return{expression:i,error:s}}static evaluate(e,t){const s=NA.exec(e)===null;let i=e,r=!1;if(e.replace(FA,"").indexOf("(")!==-1){const o=Vt.processParentheses(e,t);i=o.expression,r=o.error}if(r)return{result:!1,error:!0};const n=i.split("||");for(const o of n){const c=o.split("&&");let h=!0;for(const d of c){const{result:u,error:f}=Vt.evaluateAtomicExpression(d.trim(),t);if(!u||f){h=!1;break}}if(h)return{result:!0,error:!s}}return{result:!1,error:!s}}}var sT=` 92#ifndef outType_0 93#define outType_0 vec4 94#endif 95layout(location = 0) out highp outType_0 pcFragColor0; 96#if COLOR_ATTACHMENT_1 97layout(location = 1) out highp outType_1 pcFragColor1; 98#endif 99#if COLOR_ATTACHMENT_2 100layout(location = 2) out highp outType_2 pcFragColor2; 101#endif 102#if COLOR_ATTACHMENT_3 103layout(location = 3) out highp outType_3 pcFragColor3; 104#endif 105#if COLOR_ATTACHMENT_4 106layout(location = 4) out highp outType_4 pcFragColor4; 107#endif 108#if COLOR_ATTACHMENT_5 109layout(location = 5) out highp outType_5 pcFragColor5; 110#endif 111#if COLOR_ATTACHMENT_6 112layout(location = 6) out highp outType_6 pcFragColor6; 113#endif 114#if COLOR_ATTACHMENT_7 115layout(location = 7) out highp outType_7 pcFragColor7; 116#endif 117#define gl_FragColor pcFragColor0 118#define varying in 119#define texture2D texture 120#define texture2DBias texture 121#define textureCube texture 122#define texture2DProj textureProj 123#define texture2DLod textureLod 124#define texture2DProjLod textureProjLod 125#define textureCubeLod textureLod 126#define texture2DGrad textureGrad 127#define texture2DProjGrad textureProjGrad 128#define textureCubeGrad textureGrad 129#define utexture2D texture 130#define itexture2D texture 131#define texture2DLodEXT texture2DLodEXT_is_no_longer_supported_use_texture2DLod_instead 132#define texture2DProjLodEXT texture2DProjLodEXT_is_no_longer_supported_use_texture2DProjLod 133#define textureCubeLodEXT textureCubeLodEXT_is_no_longer_supported_use_textureCubeLod_instead 134#define texture2DGradEXT texture2DGradEXT_is_no_longer_supported_use_texture2DGrad_instead 135#define texture2DProjGradEXT texture2DProjGradEXT_is_no_longer_supported_use_texture2DProjGrad_instead 136#define textureCubeGradEXT textureCubeGradEXT_is_no_longer_supported_use_textureCubeGrad_instead 137#define textureShadow(res, uv) textureGrad(res, uv, vec2(1, 1), vec2(1, 1)) 138#define SHADOWMAP_PASS(name) name 139#define SHADOWMAP_ACCEPT(name) sampler2DShadow name 140#define TEXTURE_PASS(name) name 141#define TEXTURE_ACCEPT(name) sampler2D name 142#define TEXTURE_ACCEPT_HIGHP(name) highp sampler2D name 143#define GL2 144`,iT=` 145#extension GL_ANGLE_multi_draw : enable 146#define attribute in 147#define varying out 148#define texture2D texture 149#define utexture2D texture 150#define itexture2D texture 151#define GL2 152#define VERTEXSHADER 153#define TEXTURE_PASS(name) name 154#define TEXTURE_ACCEPT(name) sampler2D name 155#define TEXTURE_ACCEPT_HIGHP(name) highp sampler2D name 156`,rT=` 157#extension GL_EXT_samplerless_texture_functions : require 158#ifndef outType_0 159#define outType_0 vec4 160#endif 161#ifndef outType_1 162#define outType_1 vec4 163#endif 164#ifndef outType_2 165#define outType_2 vec4 166#endif 167#ifndef outType_3 168#define outType_3 vec4 169#endif 170#ifndef outType_4 171#define outType_4 vec4 172#endif 173#ifndef outType_5 174#define outType_5 vec4 175#endif 176#ifndef outType_6 177#define outType_6 vec4 178#endif 179#ifndef outType_7 180#define outType_7 vec4 181#endif 182layout(location = 0) out highp outType_0 pcFragColor0; 183layout(location = 1) out highp outType_1 pcFragColor1; 184layout(location = 2) out highp outType_2 pcFragColor2; 185layout(location = 3) out highp outType_3 pcFragColor3; 186layout(location = 4) out highp outType_4 pcFragColor4; 187layout(location = 5) out highp outType_5 pcFragColor5; 188layout(location = 6) out highp outType_6 pcFragColor6; 189layout(location = 7) out highp outType_7 pcFragColor7; 190#define gl_FragColor pcFragColor0 191#define texture2D(res, uv) texture(sampler2D(res, res ## _sampler), uv) 192#define texture2DBias(res, uv, bias) texture(sampler2D(res, res ## _sampler), uv, bias) 193#define texture2DLod(res, uv, lod) textureLod(sampler2D(res, res ## _sampler), uv, lod) 194#define textureCube(res, uv) texture(samplerCube(res, res ## _sampler), uv) 195#define textureCubeLod(res, uv, lod) textureLod(samplerCube(res, res ## _sampler), uv, lod) 196#define textureShadow(res, uv) textureLod(sampler2DShadow(res, res ## _sampler), uv, 0.0) 197#define itexture2D(res, uv) texture(isampler2D(res, res ## _sampler), uv) 198#define utexture2D(res, uv) texture(usampler2D(res, res ## _sampler), uv) 199#define texture2DLodEXT texture2DLodEXT_is_no_longer_supported_use_texture2DLod_instead 200#define texture2DProjLodEXT texture2DProjLodEXT_is_no_longer_supported_use_texture2DProjLod 201#define textureCubeLodEXT textureCubeLodEXT_is_no_longer_supported_use_textureCubeLod_instead 202#define texture2DGradEXT texture2DGradEXT_is_no_longer_supported_use_texture2DGrad_instead 203#define texture2DProjGradEXT texture2DProjGradEXT_is_no_longer_supported_use_texture2DProjGrad_instead 204#define textureCubeGradEXT textureCubeGradEXT_is_no_longer_supported_use_textureCubeGrad_instead 205#define SHADOWMAP_PASS(name) name, name ## _sampler 206#define SHADOWMAP_ACCEPT(name) texture2D name, sampler name ## _sampler 207#define TEXTURE_PASS(name) name, name ## _sampler 208#define TEXTURE_ACCEPT(name) texture2D name, sampler name ## _sampler 209#define TEXTURE_ACCEPT_HIGHP TEXTURE_ACCEPT 210#define GL2 211#define WEBGPU 212`,aT=` 213#extension GL_EXT_samplerless_texture_functions : require 214#define texture2D(res, uv) texture(sampler2D(res, res ## _sampler), uv) 215#define itexture2D(res, uv) texture(isampler2D(res, res ## _sampler), uv) 216#define utexture2D(res, uv) texture(usampler2D(res, res ## _sampler), uv) 217#define TEXTURE_PASS(name) name, name ## _sampler 218#define TEXTURE_ACCEPT(name) texture2D name, sampler name ## _sampler 219#define TEXTURE_ACCEPT_HIGHP TEXTURE_ACCEPT 220#define GL2 221#define WEBGPU 222#define VERTEXSHADER 223#define gl_VertexID gl_VertexIndex 224#define gl_InstanceID gl_InstanceIndex 225`,nT=` 226`,oT=` 227#define VERTEXSHADER 228`,Jv=` 229vec2 getGrabScreenPos(vec4 clipPos) { 230 vec2 uv = (clipPos.xy / clipPos.w) * 0.5 + 0.5; 231 #ifdef WEBGPU 232 uv.y = 1.0 - uv.y; 233 #endif 234 return uv; 235}
236vec2 getImageEffectUV(vec2 uv) { 237 #ifdef WEBGPU 238 uv.y = 1.0 - uv.y; 239 #endif 240 return uv; 241} 242`,eS=` 243#define WEBGPU 244fn getGrabScreenPos(clipPos: vec4<f32>) -> vec2<f32> { 245 var uv: vec2<f32> = (clipPos.xy / clipPos.w) * 0.5 + vec2<f32>(0.5); 246 uv.y = 1.0 - uv.y; 247 return uv; 248} 249fn getImageEffectUV(uv: vec2<f32>) -> vec2<f32> { 250 var modifiedUV: vec2<f32> = uv; 251 modifiedUV.y = 1.0 - modifiedUV.y; 252 return modifiedUV; 253} 254struct WrappedF32 { @size(16) element: f32 } 255struct WrappedI32 { @size(16) element: i32 } 256struct WrappedU32 { @size(16) element: u32 } 257struct WrappedVec2F { @size(16) element: vec2f } 258struct WrappedVec2I { @size(16) element: vec2i } 259struct WrappedVec2U { @size(16) element: vec2u } 260`,Xm=` 261#ifdef CAPS_SHADER_F16 262 alias half = f16; 263 alias half2 = vec2<f16>; 264 alias half3 = vec3<f16>; 265 alias half4 = vec4<f16>; 266 alias half2x2 = mat2x2<f16>; 267 alias half3x3 = mat3x3<f16>; 268 alias half4x4 = mat4x4<f16>; 269#else 270 alias half = f32; 271 alias half2 = vec2f; 272 alias half3 = vec3f; 273 alias half4 = vec4f; 274 alias half2x2 = mat2x2f; 275 alias half3x3 = mat3x3f; 276 alias half4x4 = mat4x4f; 277#endif 278`;const zA={vertex_position:Ie,vertex_normal:Cs,vertex_tangent:Gi,vertex_texCoord0:Zs,vertex_texCoord1:pn,vertex_texCoord2:Uc,vertex_texCoord3:zc,vertex_texCoord4:Vc,vertex_texCoord5:Gc,vertex_texCoord6:Hc,vertex_texCoord7:Wc,vertex_color:ns,vertex_boneIndices:Bs,vertex_boneWeights:ki};class Ht{static createDefinition(e,t){const s=u=>{let f=u.fragmentOutputTypes??"vec4";return Array.isArray(f)||(f=[f]),f},i=(u,f,p,m)=>{const _=e.isWebGPU?u:f;let g="";if(!p){const v=s(m);for(let x=0;x<e.maxColorAttachments;x++){g+=`#define COLOR_ATTACHMENT_${x} 279`;const y=v[x]??"vec4";g+=`#define outType_${x} ${y} 280`}}return g+_},r=(u,f)=>{let p=Ht.getWGSLEnables(e,u?"vertex":"fragment");if(!u){const m=s(f);for(let _=0;_<e.maxColorAttachments;_++){const g=m[_]??"vec4",v=Zx.get(g);p+=`alias pcOutType${_} = ${v}; 281`}}return p},a=t.name??"Untitled";let n,o;const c=Ht.getDefinesCode(e,t.vertexDefines),h=Ht.getDefinesCode(e,t.fragmentDefines);return t.shaderLanguage===de?(n=` 282 ${r(!0,t)} 283 ${c} 284 ${Xm} 285 ${oT} 286 ${eS} 287 ${t.vertexCode} 288 `,o=` 289 ${r(!1,t)} 290 ${h} 291 ${Xm} 292 ${nT} 293 ${eS} 294 ${t.fragmentCode} 295 `):(n=`${Ht.versionCode(e)+i(aT,iT,!0,t)+c+Ht.precisionCode(e)} 296 ${Jv} 297 ${Ht.getShaderNameCode(a)} 298 ${t.vertexCode}`,o=`${(t.fragmentPreamble||"")+Ht.versionCode(e)+i(rT,sT,!1,t)+h+Ht.precisionCode(e)} 299 ${Jv} 300 ${Ht.getShaderNameCode(a)} 301 ${t.fragmentCode}`),{name:a,shaderLanguage:t.shaderLanguage??ze,attributes:t.attributes,vshader:n,vincludes:t.vertexIncludes,fincludes:t.fragmentIncludes,fshader:o,feedbackVaryings:t.feedbackVaryings,useTransformFeedback:t.useTransformFeedback,meshUniformBufferFormat:t.meshUniformBufferFormat,meshBindGroupFormat:t.meshBindGroupFormat}}static getWGSLEnables(e,t){let s="";return e.supportsShaderF16&&(s+=`enable f16; 302`),t==="fragment"&&e.supportsPrimitiveIndex&&(s+=`enable primitive_index; 303`),e.supportsSubgroups&&(s+=`enable subgroups; 304`),e.supportsSubgroupId&&(s+=`requires subgroup_id; 305`),t==="compute"&&e.supportsLinearIndexing&&(s+=`requires linear_indexing; 306`),e.supportsUnrestrictedPointerParameters&&(s+=`requires unrestricted_pointer_parameters; 307`),e.supportsPointerCompositeAccess&&(s+=`requires pointer_composite_access; 308`),e.supportsPacked4x8IntegerDotProduct&&(s+=`requires packed_4x8_integer_dot_product; 309`),e.supportsTextureAndSamplerLet&&(s+=`requires texture_and_sampler_let; 310`),s}static getDefinesCode(e,t){let s="";return e.capsDefines.forEach((i,r)=>{s+=`#define ${r} ${i} 311`}),s+=` 312`,t?.forEach((i,r)=>{s+=`#define ${r} ${i} 313`}),s+=` 314`,s}static getShaderNameCode(e){return`#define SHADER_NAME ${e} 315`}static versionCode(e){return e.isWebGPU?`#version 450 316`:`#version 300 es 317`}static precisionCode(e,t){t&&t!=="highp"&&t!=="mediump"&&t!=="lowp"&&(t=null),t&&(t==="highp"&&e.maxPrecision!=="highp"&&(t="mediump"),t==="mediump"&&e.maxPrecision==="lowp"&&(t="lowp"));const s=t||e.precision;return` 318 precision ${s} float; 319 precision ${s} int; 320 precision ${s} usampler2D; 321 precision ${s} isampler2D; 322 precision ${s} sampler2DShadow; 323 precision ${s} samplerCubeShadow; 324 precision ${s} sampler2DArray; 325 `}static collectAttributes(e){const t={};let s=0,i=e.indexOf("attribute");for(;i>=0&&!(i>0&&e[i-1]==="/");){let r=!1;if(i>0){let a=e.lastIndexOf(` 326`,i);a=a!==-1?a+1:0,e.substring(a,i).includes("#")&&(r=!0)}if(!r){const a=e.indexOf(";",i),n=e.lastIndexOf(" ",a),o=e.substring(n+1,a);if(!t[o]){const c=zA[o];c!==void 0?t[o]=c:(t[o]=`ATTR${s}`,s++)}}i=e.indexOf("attribute",i+1)}return t}}let VA=0;class tt{meshUniformBufferFormat;meshBindGroupFormat;attributes=new Map;constructor(e,t){if(this.id=VA++,this.device=e,this.definition=t,this.name=t.name||"Untitled",this.init(),t.cshader){const s=Ht.getWGSLEnables(e,"compute"),i=Ht.getDefinesCode(e,t.cdefines),r=s+i+t.cshader,a=t.cincludes??new Map;a.has("halfTypesCS")||a.set("halfTypesCS",Xm),t.cshader=Vt.run(r,a,{sourceName:`compute shader for ${this.label}`,stripDefines:!0})}else{const s=t.shaderLanguage===de;t.vshader=Vt.run(t.vshader,t.vincludes,{sourceName:`vertex shader for ${this.label}`,stripDefines:s}),t.shaderLanguage===ze&&(t.attributes??(t.attributes=Ht.collectAttributes(t.vshader)));const i=e.isWebGL2&&(Ce.name==="osx"||Ce.name==="ios");if(t.fshader=Vt.run(t.fshader,t.fincludes,{stripUnusedColorAttachments:i,stripDefines:s,sourceName:`fragment shader for ${this.label}`}),!t.vshader||!t.fshader){this.failed=!0;return}}this.impl=e.createShaderImpl(this)}init(){this.ready=!1,this.failed=!1}get label(){return`Shader Id ${this.id} (${this.definition.shaderLanguage===de?"WGSL":"GLSL"}) ${this.name}`}destroy(){this.device.onDestroyShader(this),this.impl.destroy(this)}loseContext(){this.init(),this.impl.loseContext()}restoreContext(){this.impl.restoreContext(this.device,this)}}class GA{gpuBuffer;stagingBuffer;offset;size}class HA{storage;gpuBuffer;offset}class WA{bufferSize;gpuBuffers=[];stagingBuffers=[];usedBuffers=[];activeBuffer=null;constructor(e,t,s){this.device=e,this.bufferSize=t,this.bufferAlignment=s}
326destroy(){this.gpuBuffers.forEach(e=>{e.destroy(this.device)}),this.gpuBuffers=null,this.stagingBuffers.forEach(e=>{e.destroy(this.device)}),this.stagingBuffers=null,this.usedBuffers=null,this.activeBuffer=null}alloc(e,t){if(this.activeBuffer){const r=H.roundUp(this.activeBuffer.size,this.bufferAlignment);this.bufferSize-r<t&&this.scheduleSubmit()}if(!this.activeBuffer){let r=this.gpuBuffers.pop();r||(r=this.createBuffer(this.device,this.bufferSize,!1));let a=this.stagingBuffers.pop();a||(a=this.createBuffer(this.device,this.bufferSize,!0)),this.activeBuffer=new GA,this.activeBuffer.stagingBuffer=a,this.activeBuffer.gpuBuffer=r,this.activeBuffer.offset=0,this.activeBuffer.size=0}const s=this.activeBuffer,i=H.roundUp(s.size,this.bufferAlignment);e.gpuBuffer=s.gpuBuffer,e.offset=i,e.storage=s.stagingBuffer.alloc(i,t),s.size=i+t}scheduleSubmit(){this.activeBuffer&&(this.usedBuffers.push(this.activeBuffer),this.activeBuffer=null)}submit(){this.scheduleSubmit()}}const qe=[];qe[me]=function(l,e,t){const s=l.storageFloat32;s[t]=e};qe[sn]=(l,e,t)=>{const s=l.storageFloat32;s[t]=e[0],s[t+1]=e[1]};qe[hs]=(l,e,t)=>{const s=l.storageFloat32;s[t]=e[0],s[t+1]=e[1],s[t+2]=e[2]};qe[Cr]=(l,e,t)=>{const s=l.storageFloat32;s[t]=e[0],s[t+1]=e[1],s[t+2]=e[2],s[t+3]=e[3]};qe[_r]=function(l,e,t){const s=l.storageInt32;s[t]=e};qe[$a]=function(l,e,t){const s=l.storageInt32;s[t]=e[0],s[t+1]=e[1]};qe[gr]=function(l,e,t){const s=l.storageInt32;s[t]=e[0],s[t+1]=e[1],s[t+2]=e[2]};qe[Ka]=function(l,e,t){const s=l.storageInt32;s[t]=e[0],s[t+1]=e[1],s[t+2]=e[2],s[t+3]=e[3]};qe[su]=(l,e,t)=>{const s=l.storageFloat32;s[t]=e[0],s[t+1]=e[1],s[t+4]=e[2],s[t+5]=e[3],s[t+8]=e[4],s[t+9]=e[5]};qe[Do]=(l,e,t)=>{const s=l.storageFloat32;s[t]=e[0],s[t+1]=e[1],s[t+2]=e[2],s[t+4]=e[3],s[t+5]=e[4],s[t+6]=e[5],s[t+8]=e[6],s[t+9]=e[7],s[t+10]=e[8]};qe[df]=function(l,e,t,s){const i=l.storageFloat32;for(let r=0;r<s;r++)i[t+r*4]=e[r]};qe[uf]=(l,e,t,s)=>{const i=l.storageFloat32;for(let r=0;r<s;r++)i[t+r*4]=e[r*2],i[t+r*4+1]=e[r*2+1]};qe[ff]=(l,e,t,s)=>{const i=l.storageFloat32;for(let r=0;r<s;r++)i[t+r*4]=e[r*3],i[t+r*4+1]=e[r*3+1],i[t+r*4+2]=e[r*3+2]};qe[le]=(l,e,t,s)=>{const i=l.storageUint32;i[t]=e};qe[Mo]=(l,e,t,s)=>{const i=l.storageUint32;i[t]=e[0],i[t+1]=e[1]};qe[Ro]=(l,e,t,s)=>{const i=l.storageUint32;i[t]=e[0],i[t+1]=e[1],i[t+2]=e[2]};qe[oa]=(l,e,t,s)=>{const i=l.storageUint32;i[t]=e[0],i[t+1]=e[1],i[t+2]=e[2],i[t+3]=e[3]};qe[Lo]=function(l,e,t,s){const i=l.storageInt32;for(let r=0;r<s;r++)i[t+r*4]=e[r]};qe[mf]=qe[Lo];qe[pf]=function(l,e,t,s){const i=l.storageUint32;for(let r=0;r<s;r++)i[t+r*4]=e[r]};qe[Fo]=(l,e,t,s)=>{const i=l.storageInt32;for(let r=0;r<s;r++)i[t+r*4]=e[r*2],i[t+r*4+1]=e[r*2+1]};qe[gf]=qe[Fo];qe[_f]=(l,e,t,s)=>{const i=l.storageUint32;for(let r=0;r<s;r++)i[t+r*4]=e[r*2],i[t+r*4+1]=e[r*2+1]};qe[Oo]=(l,e,t,s)=>{const i=l.storageInt32;for(let r=0;r<s;r++)i[t+r*4]=e[r*3],i[t+r*4+1]=e[r*3+1],i[t+r*4+2]=e[r*3+2]};qe[Sf]=qe[Oo];qe[vf]=(l,e,t,s)=>{const i=l.storageUint32;for(let r=0;r<s;r++)i[t+r*4]=e[r*3],i[t+r*4+1]=e[r*3+1],i[t+r*4+2]=e[r*3+2]};class jc{device;persistent;allocation;storageFloat32;storageInt32;storageUint32;renderVersionDirty=0;constructor(e,t,s=!0){if(this.device=e,this.format=t,this.persistent=s,s){this.impl=e.createUniformBufferImpl(this);const i=new ArrayBuffer(t.byteSize);this.assignStorage(new Int32Array(i)),e._vram.ub+=this.format.byteSize}else this.allocation=new HA}destroy(){if(this.persistent){const e=this.device;this.impl.destroy(e),e._vram.ub-=this.format.byteSize}}get offset(){return this.persistent?0:this.allocation.offset}assignStorage(e){this.storageInt32=e,this.storageUint32=new Uint32Array(e.buffer,e.byteOffset,e.byteLength/4),this.storageFloat32=new Float32Array(e.buffer,e.byteOffset,e.byteLength/4)}loseContext(){this.impl?.loseContext()}setUniform(e,t){const s=e.offset;if(t!=null){const i=qe[e.updateType];i?i(this,t,s,e.count):this.storageFloat32.set(t,s)}}set(e,t){const s=this.format.map.get(e);s&&this.setUniform(s,t)}startUpdate(e){if(!this.persistent){const t=this.allocation,s=t.gpuBuffer;this.device.dynamicBuffers.alloc(t,this.format.byteSize),this.assignStorage(t.storage),e&&(e.bindGroup=t.gpuBuffer.getBindGroup(this),e.offsets[0]=t.offset),s!==t.gpuBuffer&&(this.renderVersionDirty=this.device.renderVersion)}}endUpdate(){this.persistent?this.impl.unlock(this):(this.storageFloat32=null,this.storageInt32=null)}
326update(e){this.startUpdate(e);const t=this.format.uniforms;for(let s=0;s<t.length;s++){const i=t[s].scopeId.value;this.setUniform(t[s],i)}this.endUpdate()}}const XA={type:Tr,base:0,baseVertex:0,count:4,indexed:!1};class YA{constructor(e){const t=` 327 328 struct ub_mesh { 329 color : vec4f, 330 depth: f32 331 } 332 333 @group(2) @binding(0) var<uniform> ubMesh : ub_mesh; 334 335 var<private> pos : array<vec2f, 4> = array<vec2f, 4>( 336 vec2(-1.0, 1.0), vec2(1.0, 1.0), 337 vec2(-1.0, -1.0), vec2(1.0, -1.0) 338 ); 339 340 struct VertexOutput { 341 @builtin(position) position : vec4f 342 } 343 344 @vertex 345 fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput { 346 var output : VertexOutput; 347 output.position = vec4(pos[vertexIndex], ubMesh.depth, 1.0); 348 return output; 349 } 350 351 @fragment 352 fn fragmentMain() -> @location(0) vec4f { 353 return ubMesh.color; 354 } 355 `;this.shader=new tt(e,{name:"WebGPUClearRendererShader",shaderLanguage:de,vshader:t,fshader:t}),this.uniformBuffer=new jc(e,new vt(e,[new X("color",Cr),new X("depth",me)]),!1),this.dynamicBindGroup=new Sg,this.colorData=new Float32Array(4)}destroy(){this.shader.destroy(),this.shader=null,this.uniformBuffer.destroy(),this.uniformBuffer=null}clear(e,t,s,i){s=s||i;const r=s.flags??i.flags;if(r!==0){const{uniformBuffer:a,dynamicBindGroup:n}=this;a.startUpdate(n),e.setBindGroup(Bo,n.bindGroup,n.offsets),e.setBindGroup(Yc,e.emptyBindGroup);let o;if(r&Jl&&(t.colorBuffer||t.impl.assignedColorTexture)){const h=s.color??i.color;this.colorData.set(h),o=xt.NOBLEND}else o=xt.NOWRITE;a.set("color",this.colorData);let c;if(r&ec&&t.depth){const h=s.depth??i.depth;a.set("depth",h),c=ds.WRITEDEPTH}else a.set("depth",1),c=ds.NODEPTH;r&Gd&&t.stencil,a.endUpdate(),e.setDrawStates(o,c),e.setShader(this.shader),e.draw(XA)}}}class jA{device;pipelineCache=new Map;constructor(e){this.device=e;const t=` 356 357 var<private> pos : array<vec2f, 4> = array<vec2f, 4>( 358 vec2(-1.0, 1.0), vec2(1.0, 1.0), 359 vec2(-1.0, -1.0), vec2(1.0, -1.0) 360 ); 361 362 struct VertexOutput { 363 @builtin(position) position : vec4f, 364 @location(0) texCoord : vec2f 365 }; 366 367 @vertex 368 fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput { 369 var output : VertexOutput; 370 output.texCoord = pos[vertexIndex] * vec2f(0.5, -0.5) + vec2f(0.5); 371 output.position = vec4f(pos[vertexIndex], 0, 1); 372 return output; 373 } 374 375 @group(0) @binding(0) var imgSampler : sampler; 376 @group(0) @binding(1) var img : texture_2d<f32>; 377 378 @fragment 379 fn fragmentMain(@location(0) texCoord : vec2f) -> @location(0) vec4f { 380 return textureSample(img, imgSampler, texCoord); 381 } 382 `;this.shader=new tt(e,{name:"WebGPUMipmapRendererShader",shaderLanguage:de,vshader:t,fshader:t}),this.minSampler=e.wgpu.createSampler({minFilter:"linear"})}destroy(){this.shader.destroy(),this.shader=null,this.pipelineCache.clear()}generate(e){const t=e.desc;if(t.mipLevelCount<=1||e.texture.volume)return;const s=this.device,i=s.wgpu,r=t.format;let a=this.pipelineCache.get(r);if(!a){const d=this.shader.impl;a=i.createRenderPipeline({layout:"auto",vertex:{module:d.getVertexShaderModule(),entryPoint:d.vertexEntryPoint},fragment:{module:d.getFragmentShaderModule(),entryPoint:d.fragmentEntryPoint,targets:[{format:r}]},primitive:{topology:"triangle-strip"}}),this.pipelineCache.set(r,a)}const n=e.texture,o=n.cubemap?6:n.array?n.arrayLength:1,c=[];for(let d=0;d<o;d++)c.push(e.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:d}));const h=s.getCommandEncoder();for(let d=1;d<t.mipLevelCount;d++)for(let u=0;u<o;u++){const f=e.createView({dimension:"2d",baseMipLevel:d,mipLevelCount:1,baseArrayLayer:u}),p=h.beginRenderPass({colorAttachments:[{view:f,loadOp:"clear",storeOp:"store"}]}),m=i.createBindGroup({layout:a.getBindGroupLayout(0),entries:[{binding:0,resource:this.minSampler},{binding:1,resource:c[u]}]});p.setPipeline(a),p.setBindGroup(0,m),p.draw(4),p.end(),c[u]=f}s.pipeline=null}}class qA{device;bindGroupCache=new Map;constructor(e){this.device=e,this.bindGroupFormat=new Ze(this.device,[new At(yf,rn|an)])}getBindGroup(e){const t=e.format.byteSize;let s=this.bindGroupCache.get(t);return s||(s=new jo(this.device,this.bindGroupFormat,e),s.update(),this.bindGroupCache.set(t,s)),s}}class $A extends qA{buffer=null;mappedRange=null;constructor(e,t,s){super(e),this.buffer=e.wgpu.createBuffer({size:t,usage:s?GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC:GP
382UBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,mappedAtCreation:s}),s&&this.onAvailable(),e._vram.ub+=t}destroy(e){e._vram.ub-=this.buffer.size,this.buffer.destroy(),this.buffer=null}onAvailable(){this.mappedRange=this.buffer.getMappedRange()}alloc(e,t){return new Int32Array(this.mappedRange,e,t/4)}}class KA extends WA{pendingStagingBuffers=[];createBuffer(e,t,s){return new $A(e,t,s)}submit(){super.submit();const e=this.usedBuffers.length;if(e){const t=this.device,s=this.gpuBuffers,i=t.wgpu.createCommandEncoder();for(let a=e-1;a>=0;a--){const n=this.usedBuffers[a],{stagingBuffer:o,gpuBuffer:c,offset:h,size:d}=n,u=o.buffer;u.unmap(),i.copyBufferToBuffer(u,h,c.buffer,h,d),s.push(c)}const r=i.finish();t.addCommandBuffer(r,!0);for(let a=0;a<e;a++){const n=this.usedBuffers[a].stagingBuffer;this.pendingStagingBuffers.push(n)}this.usedBuffers.length=0}}onCommandBuffersSubmitted(){const e=this.pendingStagingBuffers.length;if(e){for(let t=0;t<e;t++){const s=this.pendingStagingBuffers[t];s.buffer.mapAsync(GPUMapMode.WRITE).then(()=>{this.stagingBuffers&&(s.onAvailable(),this.stagingBuffers.push(s))})}this.pendingStagingBuffers.length=0}}}class lT{frameAllocations=[];pastFrameAllocations=new Map;_enabled=!1;_enableRequest=!1;_frameTime=0;_passTimings=new Map;_nameCache=new Map;maxCount=9999;loseContext(){this.pastFrameAllocations.clear()}set enabled(e){this._enableRequest=e}get enabled(){return this._enableRequest}get passTimings(){return this._passTimings}processEnableRequest(){this._enableRequest!==this._enabled&&(this._enabled=this._enableRequest,this._enabled||(this._frameTime=0))}request(e){this.pastFrameAllocations.set(e,this.frameAllocations),this.frameAllocations=[]}_parsePassName(e){let t=this._nameCache.get(e);return t===void 0&&(e.startsWith("RenderPass")?t=e.substring(10):t=e,this._nameCache.set(e,t)),t}report(e,t){if(t){const s=this.pastFrameAllocations.get(e);if(!s)return;t.length>0&&(this._frameTime=t.reduce((i,r)=>i+r,0)),this._passTimings.clear();for(let i=0;i<s.length;++i){const r=s[i],a=t[i],n=this._parsePassName(r);this._passTimings.set(n,(this._passTimings.get(n)||0)+a)}if(G_.get(QC)){let i=0;for(let r=0;r<s.length;++r)s[r],i+=t[r]}}this.pastFrameAllocations.delete(e)}getSlot(e){if(this.frameAllocations.length>=this.maxCount)return-1;const t=this.frameAllocations.length;return this.frameAllocations.push(e),t}get slotCount(){return this.frameAllocations.length}}class ZA{querySet;stagingBuffers=[];activeStagingBuffer=null;bytesPerSlot;constructor(e,t,s){this.device=e,this.capacity=s,this.bytesPerSlot=t?8:4;const i=e.wgpu;this.querySet=i.createQuerySet({type:t?"timestamp":"occlusion",count:s}),this.queryBuffer=i.createBuffer({size:this.bytesPerSlot*s,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST})}destroy(){this.device.deferDestroy(this.querySet),this.querySet=null,this.device.deferDestroy(this.queryBuffer),this.queryBuffer=null,this.activeStagingBuffer=null,this.stagingBuffers.forEach(e=>{e.destroy()}),this.stagingBuffers=null}getStagingBuffer(){let e=this.stagingBuffers.pop();return e||(e=this.device.wgpu.createBuffer({size:this.queryBuffer.size,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})),e}resolve(e){const s=this.device.getCommandEncoder();s.resolveQuerySet(this.querySet,0,e,this.queryBuffer,0);const i=this.getStagingBuffer();this.activeStagingBuffer=i,s.copyBufferToBuffer(this.queryBuffer,0,i,0,this.bytesPerSlot*e)}request(e,t){const s=this.activeStagingBuffer;return this.activeStagingBuffer=null,s.mapAsync(GPUMapMode.READ).then(()=>{const i=new BigInt64Array(s.getMappedRange()),r=[];for(let a=0;a<e;a++)r.push(Number(i[a*2+1]-i[a*2])*1e-6);return s.unmap(),this.stagingBuffers?.push(s),{renderVersion:t,timings:r}})}}class QA extends lT{device;frameGPUMarkerSlot;constructor(e){super(),this.device=e,this.maxCount=1024,this.timestampQueriesSet=e.supportsTimestampQuery?new ZA(e,!0,2*this.maxCount):null}destroy(){this.timestampQueriesSet?.destroy(),this.timestampQueriesSet=null}frameStart(){this.processEnableRequest()}frameEnd(){this._enabled&&this.timestampQueriesSet?.resolve(this.slotCount*2)}request(){if(this._enabled){const e=this.device.renderVersion;this.timestampQueriesSet?.request(this.slotCount,e).then(t=>{this.report(t.renderVersion,t.timings)}),super.request(e)}}}class JA{device;pipelineCache=new Map;constructor(e){this.device=e;const t=` 383 384 var<private> pos : array<vec2f, 4> = array<vec2f, 4>( 385 vec2(-1.0, 1.0), vec2(1.0, 1.0), vec2(-1.0, -1.0), vec2(1.0, -1.0) 386 ); 387 388 struct VertexOutput { 389 @builtin(position) position : vec4f, 390 }; 391 392 @vertex 393 fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput { 394 var output : VertexOutput; 395 output.position = vec4f(pos[vertexIndex], 0, 1); 396 return output; 397 } 398 399 @group(0) @binding(0) var img : texture_depth_multisampled_2d; 400 401 @fragment 402 fn fragmentMain(@builtin(position) fragColor: vec4f) -> @location(0) vec4f { 403 // load th depth value from sample index 0 404 var depth = textureLoad(img, vec2i(fragColor.xy), 0u); 405 return vec4f(depth, 0.0, 0.0, 0.0); 406 } 407 `;this.shader=new tt(e,{name:"WebGPUResolverDepthShader",shaderLanguage:de,vshader:t,fshader:t})}destroy(){this.shader.destroy(),this.shader=null,this.pipelineCache=null}getPipeline(e){let t=this.pipelineCache.get(e);return t||(t=this.createPipeline(e),this.pipelineCache.set(e,t)),t}createPipeline(e){const t=this.shader.impl;return this.device.wgpu.createRenderPipeline({layout:"auto",vertex:{module:t.getVertexShaderModule(),entryPoint:t.vertexEntryPoint},fragment:{module:t.getFragmentShaderModule(),entryPoint:t.fragmentEntryPoint,targets:[{format:e}]}
407,primitive:{topology:"triangle-strip"}})}resolveDepth(e,t,s){const i=this.device,r=i.wgpu,a=this.getPipeline(s.format),n=t.depthOrArrayLayers;for(let o=0;o<n;o++){const c=t.createView({dimension:"2d",aspect:"depth-only",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:o}),h=s.createView({dimension:"2d",baseMipLevel:0,mipLevelCount:1,baseArrayLayer:o}),d=e.beginRenderPass({colorAttachments:[{view:h,loadOp:"clear",storeOp:"store"}]}),u=r.createBindGroup({layout:a.getBindGroupLayout(0),entries:[{binding:0,resource:c}]});d.setPipeline(a),d.setBindGroup(0,u),d.draw(4),d.end()}i.pipeline=null}}const eP=12;class tP{uniformBuffers=[];bindGroup=null;constructor(e){this.compute=e;const{device:t,shader:s}=e,{computeBindGroupFormat:i,computeUniformBufferFormats:r}=s.impl;if(this.bindGroup=new jo(t,i),r){for(const a in r)if(r.hasOwnProperty(a)){const n=new jc(t,r[a],!0);this.uniformBuffers.push(n),this.bindGroup.setUniformBuffer(a,n)}}this.pipeline=t.computePipeline.get(s,i)}destroy(){this.uniformBuffers.forEach(e=>e.destroy()),this.uniformBuffers.length=0,this.bindGroup.destroy(),this.bindGroup=null}updateBindGroup(){const{bindGroup:e}=this;e.updateUniformBuffers(),e.update()}dispatch(e,t,s){const i=this.compute.device;i.setBindGroup(0,this.bindGroup);const r=i.passEncoder;r.setPipeline(this.pipeline);const{indirectSlotIndex:a,indirectBuffer:n,indirectFrameStamp:o}=this.compute;if(a>=0){let c;n?c=n.impl.buffer:c=i.indirectDispatchBuffer.impl.buffer;const h=a*eP;r.dispatchWorkgroupsIndirect(c,h)}else r.dispatchWorkgroups(e,t,s)}}class sP{device;gpuIndirect=null;gpuIndirectSigned=null;storage=null;constructor(e){this.device=e}allocate(e){this.gpuIndirect&&this.gpuIndirect.length===5*e||(this.storage?.destroy(),this.gpuIndirect=new Uint32Array(5*e),this.gpuIndirectSigned=new Int32Array(this.gpuIndirect.buffer),this.storage=new Se(this.device,this.gpuIndirect.byteLength,Po|ct))}add(e,t,s,i,r=0,a=0){const n=e*5;this.gpuIndirect[n+0]=t,this.gpuIndirect[n+1]=s,this.gpuIndirect[n+2]=i,this.gpuIndirectSigned[n+3]=r,this.gpuIndirect[n+4]=a}update(e){if(this.storage&&e>0){const s=e*5;this.storage.write(0,this.gpuIndirect,0,s)}return 0}destroy(){this.storage?.destroy(),this.storage=null}}class iP{availableStagingBuffers=[];pendingStagingBuffers=[];_destroyed=!1;_lastUploadSubmitVersion=-1;constructor(e){this.uploadStream=e,this.useSingleBuffer=e.useSingleBuffer}_onDeviceLost(){}destroy(){this._destroyed=!0,this.availableStagingBuffers.forEach(e=>e.destroy()),this.pendingStagingBuffers.forEach(e=>e.destroy())}update(e){const t=this.pendingStagingBuffers;for(let i=0;i<t.length;i++){const r=t[i];r.mapAsync(GPUMapMode.WRITE).then(()=>{this._destroyed?r.destroy():this.availableStagingBuffers.push(r)})}t.length=0;const s=this.availableStagingBuffers;for(let i=s.length-1;i>=0;i--)s[i].size<e&&(s[i].destroy(),s.splice(i,1))}upload(e,t,s,i){this.useSingleBuffer?this.uploadDirect(e,t,s,i):this.uploadStaging(e,t,s,i)}uploadDirect(e,t,s,i){const r=s*e.BYTES_PER_ELEMENT;i*e.BYTES_PER_ELEMENT,t.write(r,e,0,i)}uploadStaging(e,t,s,i){const r=this.uploadStream.device,a=s*e.BYTES_PER_ELEMENT,n=i*e.BYTES_PER_ELEMENT;this.pendingStagingBuffers.length>0,this.update(n);const o=this.availableStagingBuffers.pop()??this.uploadStream.device.wgpu.createBuffer({size:n,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC,mappedAtCreation:!0}),c=o.getMappedRange();new Uint8Array(c).set(new Uint8Array(e.buffer,e.byteOffset,n)),o.unmap(),r.getCommandEncoder().copyBufferToBuffer(o,0,t.impl.buffer,a,n),this.pendingStagingBuffers.push(o),this._lastUploadSubmitVersion=r.submitVersion}}class rP{_binding=null;_layer=null;_cachedFramebufferSize=new j;constructor(e){this.xrBridge=e}destroy(e){this._binding=null,this._layer=null,this._cachedFramebufferSize.set(0,0),e._clearXrState()}beginFrame(e,t){const s=this.xrBridge.device;if(s._clearXrState(),!this._binding||!this._layer||!t)return;const i=e.getViewerPose(t);if(!i||!i.views?.length)return;const r=s.xrSubImages;for(let n=0;n<i.views.length;n++){let o;try{o=this._binding.getViewSubImage(this._layer,i.views[n])}catch(d){this.xrBridge._onBindingError?.(d);return}const c=o?.colorTexture;if(!c)continue;let h=null;if(typeof o.getViewDescriptor=="function")try{const d=o.getViewDescriptor();d&&(h={...d})}catch{}r.push({colorTexture:c,viewDescriptor:h,viewport:o.viewport,viewFormat:h?.format??c.format})}const a=r[0];a&&(s.xrColorTexture=a.colorTexture,s.xrColorTextureViewFormat=a.viewFormat,this._cachedFramebufferSize.set(a.colorTexture.width,a.colorTexture.height))}endFrame(){this.xrBridge.device?._clearXrState()}get presentationLayer(){return this._layer}get graphicsBinding(){return this._binding}getFramebufferSize(e,t){const s=this._layer;if(s){const i=s.textureWidth??s.width,r=s.textureHeight??s.height;if(i>0&&r>0){t.set(i,r);return}}if(this._cachedFramebufferSize.x>0&&this._cachedFramebufferSize.y>0){t.copy(this._cachedFramebufferSize);return}t.set(0,0)}getViewport(e,t){if(this._binding&&this._layer)try{const s=this._binding.getViewSubImage(this._layer,t);if(s?.viewport)return s.viewport}catch{}return{x:0,y:0,width:0,height:0}}attachPresentation(e,t){const s=globalThis.XRGPUBinding;if(typeof s>"u"){this.xrBridge._onBindingError?.(new Error("XRGPUBinding is not available in this browser."));return}const r=this.xrBridge.device.wgpu;try{this._binding=new s(e,r)}catch(o){this.xrBridge._onBindingError?.(o);return}const n={colorFormat:this._binding.getPreferredColorFormat(),scaleFactor:t.framebufferScaleFactor};try{this._layer=this._binding.createProjectionLayer({...n,textureType:"texture-array"})}catch{this._layer=this._binding.createProjectionLayer({...n,textureType:"texture"})}e.updateRenderState({layers:[this._layer],depthNear:t.depthNear,depthFar:t.depthFar})}syncCameraColorTexture(e,t){if(!this._binding?.getCameraImage)return;const s=this._binding.getCameraImage(e);if(!s)return;const i=t.impl?.gpuTexture;if(!i)return;const a=this.xrBridge.device.getCommandEncoder(),n=e.width,o=e.height;a.copyTextureToTexture({texture:s},{texture:i},[n,o,1])}syncCameraDepthTexture(e,t,s){e?.texture}releasePresentation(){this._binding=null}onGraphicsDeviceLost(){const e=this.xrBridge,t=e._session;if(!t)return;
407const s=t.renderState,i=e.device;this._binding=null,this._layer=null,this._cachedFramebufferSize.set(0,0),i._clearXrState(),t.updateRenderState({layers:[],depthNear:s.depthNear,depthFar:s.depthFar})}onGraphicsDeviceRestored(){const e=this.xrBridge;if(!e._session)return;const t=e.eventHandler;setTimeout(()=>{if(e._session)try{const s=e._session.renderState;e.attachPresentation(e._session,{framebufferScaleFactor:e._framebufferScaleFactor,depthNear:s.depthNear,depthFar:s.depthFar,onBindingError:e._onBindingError})}catch(s){t.fire("error",s)}},0)}}const lp=new Map,tS=20,aP=12;class nP extends Je{_deferredDestroys=[];renderPipeline=new eA(this);computePipeline=new sA(this);_indirectDrawBuffer=null;_indirectDrawBufferCount=0;_indirectDrawNextIndex=0;_indirectDispatchBuffer=null;_indirectDispatchBufferCount=0;_indirectDispatchNextIndex=0;clearRenderer;mipmapRenderer;pipeline=null;bindGroupFormats=[];emptyBindGroup;submitVersion=0;xrColorTexture=null;xrColorTextureViewFormat=null;xrColorTextureViewDescriptor=null;xrSubImages=[];xrCurrentViewIndex=-1;externalBackbuffer=null;commandEncoder=null;commandBuffers=[];limits;glslang=null;twgsl=null;constructor(e,t={}){super(e,t),t=this.initOptions,t.alpha=t.alpha??!0,this.backBufferAntialias=t.antialias??!1,this.isWebGPU=!0,this._deviceType=Gx,this.featureLevel=t.featureLevel,this.scope.resolve(gg).setValue(0)}destroy(){this.clearRenderer.destroy(),this.clearRenderer=null,this.mipmapRenderer.destroy(),this.mipmapRenderer=null,this.resolver.destroy(),this.resolver=null,this._clearXrState(),this.externalBackbuffer=null,super.destroy()}_clearXrState(){this.xrColorTexture=null,this.xrColorTextureViewFormat=null,this.xrColorTextureViewDescriptor=null,this.xrSubImages.length=0,this.xrCurrentViewIndex=-1}initDeviceCaps(){const e=this.wgpu?.limits;this.limits=e,this.precision="highp",this.maxPrecision="highp",this.maxSamples=4,this.maxTextures=16,this.maxTextureSize=e.maxTextureDimension2D,this.maxCubeMapSize=e.maxTextureDimension2D,this.maxVolumeSize=e.maxTextureDimension3D,this.maxColorAttachments=e.maxColorAttachments,this.maxPixelRatio=1,this.maxAnisotropy=16,this.fragmentUniformsCount=e.maxUniformBufferBindingSize/16,this.vertexUniformsCount=e.maxUniformBufferBindingSize/16,this.supportsUniformBuffers=!0,this.supportsAreaLights=!0,this.supportsGpuParticles=!0,this.supportsCompute=!0,this.textureFloatRenderable=!0,this.textureHalfFloatRenderable=!0,this.supportsImageBitmap=!0,this.samples=this.backBufferAntialias?4:1;const t=window.navigator.gpu.wgslLanguageFeatures;this.supportsStorageTextureRead=t?.has("readonly_and_readwrite_storage_textures"),this.supportsSubgroupUniformity=t?.has("subgroup_uniformity"),this.supportsSubgroupId=t?.has("subgroup_id"),this.supportsLinearIndexing=t?.has("linear_indexing"),this.supportsUnrestrictedPointerParameters=t?.has("unrestricted_pointer_parameters"),this.supportsPointerCompositeAccess=t?.has("pointer_composite_access"),this.supportsPacked4x8IntegerDotProduct=t?.has("packed_4x8_integer_dot_product"),this.supportsTextureAndSamplerLet=t?.has("texture_and_sampler_let"),this.initCapsDefines()}async initWebGpu(e,t){if(!window.navigator.gpu)throw new Error("Unable to retrieve GPU. Ensure you are using a browser that supports WebGPU rendering.");if(e&&t){const s=window.document?.baseURI??window.location.href,i=c=>new URL(c,s).toString(),r=i(t),a=i(t.replace(".js",".wasm")),n=i(e),o=await Promise.all([hv(()=>import(`${r}`),[]).then(()=>twgsl(a)),hv(()=>import(`${n}`),[]).then(c=>c.default())]);this.twgsl=o[0],this.glslang=o[1]}return this.createDevice()}async createDevice(){const e={powerPreference:this.initOptions.powerPreference!=="default"?this.initOptions.powerPreference:void 0,xrCompatible:!!this.initOptions.xrCompatible};this.gpuAdapter=await window.navigator.gpu.requestAdapter(e);const s=this.initOptions.featureLevel==="bare",i=[],r=s?()=>!1:d=>{const u=this.gpuAdapter.features.has(d);return u&&i.push(d),u};this.textureFloatFilterable=r("float32-filterable"),this.textureFloatBlendable=r("float32-blendable"),this.extCompressedTextureS3TC=r("texture-compression-bc"),this.extCompressedTextureS3TCSliced3D=r("texture-compression-bc-sliced-3d"),this.extCompressedTextureETC=r("texture-compression-etc2"),this.extCompressedTextureASTC=r("texture-compression-astc"),this.extCompressedTextureASTCSliced3D=r("texture-compression-astc-sliced-3d"),this.supportsTimestampQuery=r("timestamp-query"),this.supportsDepthClip=r("depth-clip-control"),this.supportsDepth32Stencil=r("depth32float-stencil8"),this.supportsIndirectFirstInstance=r("indirect-first-instance"),this.supportsShaderF16=r("shader-f16"),this.supportsStorageRGBA8=r("bgra8unorm-storage"),this.textureRG11B10Renderable=r("rg11b10ufloat-renderable"),this.supportsClipDistances=r("clip-distances"),this.supportsTextureFormatTier1=r("texture-format-tier1"),this.supportsTextureFormatTier2=r("texture-format-tier2"),this.supportsTextureFormatTier1||(this.supportsTextureFormatTier1=this.supportsTextureFormatTier2),this.supportsPrimitiveIndex=r("primitive-index"),this.supportsSubgroups=r("subgroups"),this.maxSubgroupSize=this.supportsSubgroups?this.gpuAdapter?.info?.subgroupMaxSize??0:0,this.minSubgroupSize=this.supportsSubgroups?this.gpuAdapter?.info?.subgroupMinSize??0:0,window.navigator.gpu.wgslLanguageFeatures&&Array.from(window.navigator.gpu.wgslLanguageFeatures);const a={};if(!s){const d=this.gpuAdapter?.limits;if(d)for(const u in d)u==="minSubgroupSize"||u==="maxSubgroupSize"||(a[u]=d[u])}const n={requiredFeatures:i,requiredLimits:a,defaultQueue:{label:"Default Queue"}};this.wgpu=await this.gpuAdapter.requestDevice(n),this.supportsHtmlTextures=typeof this.wgpu.queue?.copyElementImageToTexture=="function",this.wgpu.lost?.then(this.handleDeviceLost.bind(this)),this.wgpu.addEventListener?.("uncapturederror",d=>{d.error}),this.initDeviceCaps(),this.gpuContext=this.canvas.getContext("webgpu");
407let o="standard",c=window.navigator.gpu.getPreferredCanvasFormat();const h=this.initOptions.displayFormat;return this.backBufferFormat=c==="rgba8unorm"?h===mh?us:Re:h===mh?Ju:Nu,this.backBufferViewFormat=h===mh?`${c}-srgb`:c,h===yb&&this.textureFloatFilterable&&window.matchMedia("(dynamic-range: high)")?.matches&&(this.backBufferFormat=Ge,this.backBufferViewFormat="rgba16float",c="rgba16float",this.isHdr=!0,o="extended"),this.canvasConfig={device:this.wgpu,colorSpace:"srgb",alphaMode:this.initOptions.alpha?"premultiplied":"opaque",format:c,toneMapping:{mode:o},usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC|GPUTextureUsage.COPY_DST,viewFormats:h===mh?[this.backBufferViewFormat]:[]},this.gpuContext?.configure(this.canvasConfig),this.createBackbuffer(),this.clearRenderer=new YA(this),this.mipmapRenderer=new jA(this),this.resolver=new JA(this),this.postInit(),this}async handleDeviceLost(e){e.reason!=="destroyed"&&(super.loseContext(),this.fire("devicelost"),await this.createDevice(),super.restoreContext(),this.fire("devicerestored"))}postInit(){super.postInit(),this.initializeRenderState(),this.setupPassEncoderDefaults(),this.gpuProfiler=new QA(this),this.dynamicBuffers=new KA(this,100*1024,this.limits.minUniformBufferOffsetAlignment),this.emptyBindGroup=new jo(this,new Ze(this,[])),this.emptyBindGroup.update()}createBackbuffer(){this.supportsStencil=this.initOptions.stencil,this.backBuffer=new St({name:"WebgpuFramebuffer",graphicsDevice:this,depth:this.initOptions.depth,stencil:this.supportsStencil,samples:this.samples}),this.backBuffer.impl.isBackbuffer=!0}frameStart(){super.frameStart(),this.gpuProfiler.frameStart(),this.submit();const e=this.xrColorTexture??this.gpuContext?.getCurrentTexture?.()??this.externalBackbuffer?.impl.gpuTexture;(this.backBufferSize.x!==e.width||this.backBufferSize.y!==e.height)&&(this.backBufferSize.set(e.width,e.height),this.backBuffer.destroy(),this.backBuffer=null,this.createBackbuffer());const t=this.backBuffer,s=t.impl,i=e===this.xrColorTexture&&this.xrColorTextureViewFormat?this.xrColorTextureViewFormat:this.backBufferViewFormat;s.setColorAttachment(0,void 0,i),t._width=e.width,t._height=e.height,this.initRenderTarget(t),s.assignColorTexture(e,i)}frameEnd(){super.frameEnd(),this.gpuProfiler.frameEnd(),this.submit(),this.contextLost||this.gpuProfiler.request(),this._indirectDrawNextIndex=0,this._indirectDispatchNextIndex=0}createBufferImpl(e){return new wf(e)}createUniformBufferImpl(e){return new MA(e)}createVertexBufferImpl(e,t,s){return new RA(e,t,s)}createIndexBufferImpl(e,t){return new jb(e,t)}createShaderImpl(e){return new PA(e)}createDrawCommandImpl(e){return new sP(this)}createTextureImpl(e){return this.textures.add(e),new DA(e)}createXrBridgeImpl(e){return new rP(e)}createRenderTargetImpl(e){return new cA(e)}createUploadStreamImpl(e){return new iP(e)}createBindGroupFormatImpl(e){return new Yb(e)}createBindGroupImpl(e){return new Wb}createComputeImpl(e){return new tP(e)}get indirectDrawBuffer(){return this.allocateIndirectDrawBuffer(),this._indirectDrawBuffer}allocateIndirectDrawBuffer(){this._indirectDrawNextIndex===0&&this._indirectDrawBufferCount<this.maxIndirectDrawCount&&(this._indirectDrawBuffer?.destroy(),this._indirectDrawBuffer=null),this._indirectDrawBuffer===null&&(this._indirectDrawBuffer=new Se(this,this.maxIndirectDrawCount*tS,Po|ct),this._indirectDrawBufferCount=this.maxIndirectDrawCount)}getIndirectDrawSlot(e=1){this.allocateIndirectDrawBuffer();const t=this._indirectDrawNextIndex,s=this._indirectDrawNextIndex+e;return this._indirectDrawNextIndex=s,t}get indirectDispatchBuffer(){return this.allocateIndirectDispatchBuffer(),this._indirectDispatchBuffer}allocateIndirectDispatchBuffer(){this._indirectDispatchNextIndex===0&&this._indirectDispatchBufferCount<this.maxIndirectDispatchCount&&(this._indirectDispatchBuffer?.destroy(),this._indirectDispatchBuffer=null),this._indirectDispatchBuffer===null&&(this._indirectDispatchBuffer=new Se(this,this.maxIndirectDispatchCount*aP,Po|ct),this._indirectDispatchBufferCount=this.maxIndirectDispatchCount)}getIndirectDispatchSlot(e=1){this.allocateIndirectDispatchBuffer();const t=this._indirectDispatchNextIndex,s=this._indirectDispatchNextIndex+e;return this._indirectDispatchNextIndex=s,t}setBindGroup(e,t,s){this.passEncoder&&(this.passEncoder.setBindGroup(e,t.impl.bindGroup,s??t.uniformBufferOffsets),this.bindGroupFormats[e]=t.format.impl)}submitVertexBuffer(e,t){const s=e.format,{interleaved:i,elements:r}=s,a=r.length,n=e.impl.buffer;if(i)return this.passEncoder.setVertexBuffer(t,n),1;for(let o=0;o<a;o++)this.passEncoder.setVertexBuffer(t+o,n,r[o].offset);return a}validateVBLocations(e,t){const s=i=>{const{elements:r}=i.format;for(let a=0;a<r.length;a++){const n=r[a].name,o=Be[n];lp.has(o),lp.set(o,n)}};s(e),s(t),lp.clear()}draw(e,t,s=1,i,r=!0,a=!0){if(this.shader.ready&&!this.shader.failed){const n=this.passEncoder;let o=this.pipeline;const c=this.vertexBuffers[0],h=this.vertexBuffers[1];if(r){if(c){const d=this.submitVertexBuffer(c,0);h&&this.submitVertexBuffer(h,d)}o=this.renderPipeline.get(e,c?.format,h?.format,t?.format,this.shader,this.renderTarget,this.bindGroupFormats,this.blendState,this.depthState,this.cullMode,this.stencilEnabled,this.stencilFront,this.stencilBack,this.frontFace),this.pipeline!==o&&(this.pipeline=o,n.setPipeline(o))}if(t&&n.setIndexBuffer(t.impl.buffer,t.impl.format),i){const u=(i.impl?.
407storage??this.indirectDrawBuffer).impl.buffer,f=i.count;for(let p=0;p<f;p++){const m=(i.slotIndex+p)*tS;t?n.drawIndexedIndirect(u,m):n.drawIndirect(u,m)}}else t?n.drawIndexed(e.count,s,e.base,e.baseVertex??0,0):n.draw(e.count,s,e.base,0);this._drawCallsPerFrame++}a&&(this.clearVertexBuffer(),this.pipeline=null)}setShader(e,t=!1){e!==this.shader&&(this.shader=e)}setBlendState(e){this.blendState.copy(e)}setDepthState(e){this.depthState.copy(e)}setStencilState(e,t){if(e||t){this.stencilEnabled=!0,this.stencilFront.copy(e??$s.DEFAULT),this.stencilBack.copy(t??$s.DEFAULT);const s=this.stencilFront.ref;this.stencilRef!==s&&(this.stencilRef=s,this.passEncoder.setStencilReference(s))}else this.stencilEnabled=!1}setBlendColor(e,t,s,i){const r=this.blendColor;(e!==r.r||t!==r.g||s!==r.b||i!==r.a)&&(r.set(e,t,s,i),this.passEncoder.setBlendConstant(r))}setCullMode(e){this.cullMode=e}setFrontFace(e){this.frontFace=e}setAlphaToCoverage(e){}initializeContextCaches(){super.initializeContextCaches()}setupPassEncoderDefaults(){this.pipeline=null,this.stencilRef=0,this.blendColor.set(0,0,0,0)}_uploadDirtyTextures(){this.texturesToUpload.forEach(e=>{(e._needsUpload||e._needsMipmapsUpload)&&e.upload()}),this.texturesToUpload.clear()}setupTimeStampWrites(e,t){if(this.gpuProfiler._enabled&&this.gpuProfiler.timestampQueriesSet){const s=this.gpuProfiler.getSlot(t);s===-1||(e=e??{},e.timestampWrites={querySet:this.gpuProfiler.timestampQueriesSet.querySet,beginningOfPassWriteIndex:s*2,endOfPassWriteIndex:s*2+1})}return e}startRenderPass(e){this._uploadDirtyTextures();const t=e.renderTarget||this.backBuffer;this.renderTarget=t;const s=t.impl;t!==this.backBuffer&&this.initRenderTarget(t),s.setupForRenderPass(e,t);const i=s.renderPassDescriptor;this.setupTimeStampWrites(i,e.name);const r=this.getCommandEncoder();this.passEncoder=r.beginRenderPass(i),this.passEncoder.label=`${e.name}-PassEncoder RT:${t.name}`,this.setupPassEncoderDefaults();const{width:a,height:n}=t;this.setViewport(0,0,a,n),this.setScissor(0,0,a,n),this.insideRenderPass=!0}endRenderPass(e){this.passEncoder.end(),this.passEncoder=null,this.insideRenderPass=!1,this.bindGroupFormats.length=0;const t=this.renderTarget;if(t&&t.depthBuffer&&e.depthStencilOps.resolveDepth&&e.samples>1&&t.autoResolve){const s=t.impl.depthAttachment,i=t.depthBuffer.impl.gpuTexture;s&&i&&this.resolver.resolveDepth(this.commandEncoder,s.multisampledDepthBuffer,i)}for(let s=0;s<e.colorArrayOps.length;s++)e.colorArrayOps[s].genMipmaps&&this.mipmapRenderer.generate(e.renderTarget._colorBuffers[s].impl)}startComputePass(e){this._uploadDirtyTextures(),this.pipeline=null;const t=this.setupTimeStampWrites(void 0,e),s=this.getCommandEncoder();this.passEncoder=s.beginComputePass(t),this.insideRenderPass=!0}endComputePass(){this.passEncoder.end(),this.passEncoder=null,this.insideRenderPass=!1,this.bindGroupFormats.length=0}computeDispatch(e,t="Unnamed"){this.startComputePass(t);for(let s=0;s<e.length;s++){const i=e[s];i.applyParameters(),i.impl.updateBindGroup()}for(let s=0;s<e.length;s++){const i=e[s];i.impl.dispatch(i.countX,i.countY,i.countZ)}this.endComputePass()}getCommandEncoder(){let e=this.commandEncoder;return e||(e=this.wgpu.createCommandEncoder(),this.commandEncoder=e),e}endCommandEncoder(){const{commandEncoder:e}=this;if(e){const t=e.finish();this.addCommandBuffer(t),this.commandEncoder=null}}addCommandBuffer(e,t=!1){t?this.commandBuffers.unshift(e):this.commandBuffers.push(e)}submit(){this.endCommandEncoder(),this.commandBuffers.length>0&&(this.dynamicBuffers.submit(),this.wgpu.queue.submit(this.commandBuffers),this.commandBuffers.length=0,this.submitVersion++,this.dynamicBuffers.onCommandBuffersSubmitted());const e=this._deferredDestroys;if(e.length>0){for(let t=0;t<e.length;t++)e[t].destroy();e.length=0}}deferDestroy(e){e&&this._deferredDestroys.push(e)}clear(e){e.flags&&this.clearRenderer.clear(this,this.renderTarget,e,this.defaultClearOptions)}setViewport(e,t,s,i){if(this.passEncoder){if(this.xrColorTexture)return;this.renderTarget.flipY||(t=this.renderTarget.height-t-i),this.vx=e,this.vy=t,this.vw=s,this.vh=i,this.passEncoder.setViewport(e,t,s,i,0,1)}}setScissor(e,t,s,i){if(this.passEncoder){if(this.xrColorTexture)return;this.renderTarget.flipY||(t=this.renderTarget.height-t-i),this.sx=e,this.sy=t,this.sw=s,this.sh=i,this.passEncoder.setScissorRect
407(e,t,s,i)}}clearStorageBuffer(e,t=0,s=e.byteSize){this.getCommandEncoder().clearBuffer(e.buffer,t,s)}readStorageBuffer(e,t=0,s=e.byteSize-t,i=null,r=!1){const a=this.createBufferImpl(Ox|ct);a.allocate(this,s);const n=a.buffer;return this.getCommandEncoder().copyBufferToBuffer(e.buffer,t,n,0,s),this.readBuffer(a,s,i,r)}readBuffer(e,t,s=null,i=!1){const r=e.buffer;return new Promise((a,n)=>{const o=()=>{r?.mapAsync(GPUMapMode.READ).then(()=>{s??(s=new Uint8Array(t));const c=r.getMappedRange(0,t),h=s.constructor;s.set(new h(c)),r.unmap(),e.destroy(this),a(s)})};i?(this.submit(),o()):setTimeout(()=>{o()})})}writeStorageBuffer(e,t=0,s,i=0,r){this.wgpu.queue.writeBuffer(e.buffer,t,s,i,r)}copyRenderTarget(e,t,s,i){const r={width:e?e.width:t.width,height:e?e.height:t.height,depthOrArrayLayers:1},a=this.getCommandEncoder();if(s){const n={texture:e?e.colorBuffer.impl.gpuTexture:this.backBuffer.impl.assignedColorTexture,mipLevel:e?e.mipLevel:0},o={texture:t?t.colorBuffer.impl.gpuTexture:this.backBuffer.impl.assignedColorTexture,mipLevel:t?t.mipLevel:0};a.copyTextureToTexture(n,o,r)}if(i){const n=e||this.renderTarget,o=n.impl.depthAttachment.depthTexture,c=n.mipLevel;if(e.samples>1){const h=t.colorBuffer.impl.gpuTexture;this.resolver.resolveDepth(a,o,h)}else{const h=t?t.depthBuffer.impl.gpuTexture:this.renderTarget.impl.depthAttachment.depthTexture,d=t?t.mipLevel:this.renderTarget.mipLevel,u={texture:o,mipLevel:c},f={texture:h,mipLevel:d};a.copyTextureToTexture(u,f,r)}}return!0}get hasTranspilers(){return this.glslang&&this.twgsl}}class cT{bufferId=null;destroy(e){this.bufferId&&(e.gl.deleteBuffer(this.bufferId),this.bufferId=null)}get initialized(){return!!this.bufferId}loseContext(){this.bufferId=null}unlock(e,t,s,i){const r=e.gl;if(this.bufferId)r.bindBuffer(s,this.bufferId),r.bufferSubData(s,0,i);else{let a;switch(t){case Ys:a=r.STATIC_DRAW;break;case Vd:a=r.DYNAMIC_DRAW;break;case DE:a=r.STREAM_DRAW;break;case ME:a=r.DYNAMIC_COPY;break}this.bufferId=r.createBuffer(),r.bindBuffer(s,this.bufferId),r.bufferData(s,i,a)}}}class oP extends cT{vao=null;destroy(e){super.destroy(e),e.unbindVertexArray()}loseContext(){super.loseContext(),this.vao=null}unlock(e){const t=e.device;super.unlock(t,e.usage,t.gl.ARRAY_BUFFER,e.storage)}}class lP extends cT{constructor(e){super();const t=e.device.gl,s=e.format;s===zm?this.glFormat=t.UNSIGNED_BYTE:s===Ni?this.glFormat=t.UNSIGNED_SHORT:s===ra&&(this.glFormat=t.UNSIGNED_INT)}unlock(e){const t=e.device;super.unlock(t,e.usage,t.gl.ELEMENT_ARRAY_BUFFER,e.storage)}}class cP{constructor(e,t,s,i){if(this.locationId=i,this.scopeId=e.scope.resolve(t),this.version=new Qx,t.substring(t.length-3)==="[0]")switch(s){case me:s=df;break;case _r:s=Lo;break;case le:s=pf;break;case So:s=mf;break;case sn:s=uf;break;case $a:s=Fo;break;case Mo:s=_f;break;case oc:s=gf;break;case hs:s=ff;break;case gr:s=Oo;break;case Ro:s=vf;break;case lc:s=Sf;break;case Cr:s=pg;break;case Ka:s=iu;break;case oa:s=mg;break;case cc:s=_g;break}this.dataType=s,this.value=[null,null,null,null],this.array=[]}}const sS=new Set(["gl_VertexID","gl_InstanceID","gl_DrawID","gl_BaseVertex","gl_BaseInstance"]);class hP{map=new Map;destroy(e){this.map.forEach(t=>{e.gl.deleteShader(t)})}loseContext(e){this.map.clear()}}const dP=new Jt,uP=new Jt;class fP{compileDuration=0;constructor(e){this.init(),this.compile(e.device,e),this.link(e.device,e),e.device.shaders.push(e)}destroy(e){this.glProgram&&(e.device.gl.deleteProgram(this.glProgram),this.glProgram=null)}init(){this.uniforms=[],this.samplers=[],this.attributes=[],this.glProgram=null,this.glVertexShader=null,this.glFragmentShader=null}loseContext(){this.init()}restoreContext(e,t){this.compile(e,t),this.link(e,t)}compile(e,t){const s=t.definition;this.glVertexShader=this._compileShaderSource(e,s.vshader,!0),this.glFragmentShader=this._compileShaderSource(e,s.fshader,!1)}link(e,t){if(this.glProgram)return;const s=e.gl;if(s.isContextLost())return;const i=s.createProgram();this.glProgram=i,s.attachShader(i,this.glVertexShader),s.attachShader(i,this.glFragmentShader);const r=t.definition,a=r.attributes;if(r.useTransformFeedback){let n=r.feedbackVaryings;if(!n){n=[];for(const o in a)a.hasOwnProperty(o)&&n.push(`out_${o}`)}s.transformFeedbackVaryings(i,n,s.INTERLEAVED_ATTRIBS)}for(const n in a)if(a.hasOwnProperty(n)){const o=a[n],c=Be[o];s.bindAttribLocation(i,c,n)}s.linkProgram(i)}_compileShaderSource(e,t,s){const i=e.gl;if(i.isContextLost())return null;const a=(s?dP:uP).get(e,()=>new hP);let n=a.map.get(t);return n||(n=i.createShader(s?i.VERTEX_SHADER:i.FRAGMENT_SHADER),i.shaderSource(n,t),i.compileShader(n),a.map.set(t,n)),n}finalize(e,t){const s=e.gl;if(s.isContextLost())return!0;const i=this.glProgram,r=t.definition;
407if(!s.getProgramParameter(i,s.LINK_STATUS)){if(!this._isCompiled(e,t,this.glVertexShader,r.vshader,"vertex")||!this._isCompiled(e,t,this.glFragmentShader,r.fshader,"fragment"))return!1;const h=`Failed to link shader program. Error: ${s.getProgramInfoLog(i)}`;return console.error(h),!1}const n=s.getProgramParameter(i,s.ACTIVE_ATTRIBUTES);t.attributes.clear();for(let h=0;h<n;h++){const d=s.getActiveAttrib(i,h),u=s.getAttribLocation(i,d.name);sS.has(d.name)||(r.attributes[d.name]===void 0?(console.error(`Vertex shader attribute "${d.name}" is not mapped to a semantic in shader definition, shader [${t.label}]`,t),t.failed=!0):t.attributes.set(u,d.name))}const o=e._samplerTypes,c=s.getProgramParameter(i,s.ACTIVE_UNIFORMS);for(let h=0;h<c;h++){const d=s.getActiveUniform(i,h),u=s.getUniformLocation(i,d.name);if(sS.has(d.name))continue;const f=new cP(e,d.name,e.pcUniformType[d.type],u);o.has(d.type)?this.samplers.push(f):this.uniforms.push(f)}return t.ready=!0,!0}_isCompiled(e,t,s,i,r){const a=e.gl;if(!a.getShaderParameter(s,a.COMPILE_STATUS)){const n=a.getShaderInfoLog(s),[o,c]=this._processError(i,n),h=`Failed to compile ${r} shader: 408 409${n} 410${o} while rendering undefined`;return console.error(h),!1}return!0}isLinked(e){const{extParallelShaderCompile:t}=e;return t?e.gl.getProgramParameter(this.glProgram,t.COMPLETION_STATUS_KHR):!0}_processError(e,t){const s={};let i="";if(e){const r=e.split(` 411`);let a=0,n=r.length;if(t&&t.startsWith("ERROR:")){const o=t.match(/^ERROR:\s(\d+):(\d+):\s*(.+)/);o&&(s.message=o[3],s.line=parseInt(o[2],10),a=Math.max(0,s.line-6),n=Math.min(r.length,s.line+5))}for(let o=a;o<n;o++){const c=o+1===s.line?"> ":" ";i+=`${c}${o+1}: ${r[o]} 412`}s.source=e}return[i,s]}}class pP{indexSizeBytes;glCounts=null;glOffsetsBytes=null;glInstanceCounts=null;constructor(e){this.indexSizeBytes=e}allocate(e){this.glCounts&&this.glCounts.length===e||(this.glCounts=new Int32Array(e),this.glOffsetsBytes=new Int32Array(e),this.glInstanceCounts=new Int32Array(e))}add(e,t,s,i){this.glCounts[e]=t,this.glOffsetsBytes[e]=i*this.indexSizeBytes,this.glInstanceCounts[e]=s}update(e){return 0}}function iS(l,e){const t=l.width,s=l.height;if(t>e||s>e){const i=e/Math.max(t,s),r=Math.floor(t*i),a=Math.floor(s*i),n=document.createElement("canvas");return n.width=r,n.height=a,n.getContext("2d").drawImage(l,0,0,t,s,0,0,r,a),n}return l}class mP{_glTexture=null;_glTarget;_glFormat;_glInternalFormat;_glPixelType;_glCreated;dirtyParameterFlags=0;constructor(e){this.texture=e}destroy(e){if(this._glTexture){for(let t=0;t<e.textureUnits.length;t++){const s=e.textureUnits[t];for(let i=0;i<s.length;i++)s[i]===this._glTexture&&(s[i]=null)}e.gl.deleteTexture(this._glTexture),this._glTexture=null}}loseContext(){this._glTexture=null}propertyChanged(e){this.dirtyParameterFlags|=e}initialize(e,t){const s=e.gl;switch(this._glTexture=s.createTexture(),this._glTarget=t._cubemap?s.TEXTURE_CUBE_MAP:t._volume?s.TEXTURE_3D:t.array?s.TEXTURE_2D_ARRAY:s.TEXTURE_2D,t._format){case K_:this._glFormat=s.ALPHA,this._glInternalFormat=s.ALPHA,this._glPixelType=s.UNSIGNED_BYTE;break;case Z_:this._glFormat=s.LUMINANCE,this._glInternalFormat=s.LUMINANCE,this._glPixelType=s.UNSIGNED_BYTE;break;case Du:this._glFormat=s.LUMINANCE_ALPHA,this._glInternalFormat=s.LUMINANCE_ALPHA,this._glPixelType=s.UNSIGNED_BYTE;break;case Zu:this._glFormat=s.RED,this._glInternalFormat=s.R8,this._glPixelType=s.UNSIGNED_BYTE;break;case Qu:this._glFormat=s.RG,this._glInternalFormat=s.RG8,this._glPixelType=s.UNSIGNED_BYTE;break;case Dc:this._glFormat=s.RGB,this._glInternalFormat=s.RGB565,this._glPixelType=s.UNSIGNED_SHORT_5_6_5;break;case Mu:this._glFormat=s.RGBA,this._glInternalFormat=s.RGB5_A1,this._glPixelType=s.UNSIGNED_SHORT_5_5_5_1;break;case Mc:this._glFormat=s.RGBA,this._glInternalFormat=s.RGBA4,this._glPixelType=s.UNSIGNED_SHORT_4_4_4_4;break;case Er:this._glFormat=s.RGB,this._glInternalFormat=s.RGB8,this._glPixelType=s.UNSIGNED_BYTE;break;case Re:this._glFormat=s.RGBA,this._glInternalFormat=s.RGBA8,this._glPixelType=s.UNSIGNED_BYTE;break;case Nu:case Ju:break;case ef:break;case tf:this._glFormat=s.RGB,this._glInternalFormat=s.RGB9_E5,this._glPixelType=s.UNSIGNED_INT_5_9_9_9_REV;break;case sf:this._glFormat=s.RG,this._glInternalFormat=s.RG8_SNORM,this._glPixelType=s.BYTE;break;case rf:this._glFormat=s.RGBA,this._glInternalFormat=s.RGBA8_SNORM,this._glPixelType=s.BYTE;break;case af:this._glFormat=s.RGBA,this._glInternalFormat=s.RGB10_A2,this._glPixelType=s.UNSIGNED_INT_2_10_10_10_REV;break;case nf:this._glFormat=s.RGBA_INTEGER,this._glInternalFormat=s.RGB10_A2UI,this._glPixelType=s.UNSIGNED_INT_2_10_10_10_REV;break;case Rc:this._glFormat=s.RGB,this._glInternalFormat=e.extCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;break;case Ru:this._glFormat=s.RGBA,this._glInternalFormat=e.extCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;break;case Ho:this._glFormat=s.RGBA,this._glInternalFormat=e.extCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;break;case Fc:this._glFormat=s.RGB,this._glInternalFormat=e.extCompressedTextureETC1.COMPRESSED_RGB_ETC1_WEBGL;break;case Wo:this._glFormat=s.RGB,this._glInternalFormat=e.extCompressedTexturePVRTC.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;break;case Xo:this._glFormat=s.RGBA,this._glInternalFormat=e.extCompressedTexturePVRTC.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;break;case Oc:this._glFormat=s.RGB,this._glInternalFormat=e.extCompressedTexturePVRTC.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;break;case Bc:this._glFormat=s.RGBA,this._glInternalFormat=e.extCompressedTexturePVRTC.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;break;case Ou:this._glFormat=s.RGB,this._glInternalFormat=e.extCompressedTextureETC.COMPRESSED_RGB8_ETC2;break;
412case Bu:this._glFormat=s.RGBA,this._glInternalFormat=e.extCompressedTextureETC.COMPRESSED_RGBA8_ETC2_EAC;break;case Q_:this._glFormat=s.RGBA,this._glInternalFormat=e.extCompressedTextureASTC.COMPRESSED_RGBA_ASTC_4x4_KHR;break;case J_:this._glFormat=s.RGB,this._glInternalFormat=e.extCompressedTextureATC.COMPRESSED_RGB_ATC_WEBGL;break;case eg:this._glFormat=s.RGBA,this._glInternalFormat=e.extCompressedTextureATC.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL;break;case ig:this._glFormat=s.RGB,this._glInternalFormat=e.extTextureCompressionBPTC.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;break;case rg:this._glFormat=s.RGB,this._glInternalFormat=e.extTextureCompressionBPTC.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;break;case ag:this._glFormat=s.RGBA,this._glInternalFormat=e.extTextureCompressionBPTC.COMPRESSED_RGBA_BPTC_UNORM_EXT;break;case Xd:this._glFormat=s.SRGB,this._glInternalFormat=e.extCompressedTextureS3TC_SRGB.COMPRESSED_SRGB_S3TC_DXT1_EXT;break;case Yd:this._glFormat=s.SRGB_ALPHA,this._glInternalFormat=e.extCompressedTextureS3TC_SRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;break;case jd:this._glFormat=s.SRGB_ALPHA,this._glInternalFormat=e.extCompressedTextureS3TC_SRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;break;case qd:this._glFormat=s.SRGB,this._glInternalFormat=e.extCompressedTextureETC.COMPRESSED_SRGB8_ETC2;break;case $d:this._glFormat=s.SRGB_ALPHA,this._glInternalFormat=e.extCompressedTextureETC.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;break;case Kd:this._glFormat=s.SRGB_ALPHA,this._glInternalFormat=e.extCompressedTextureASTC.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case Zd:this._glFormat=s.RGBA,this._glInternalFormat=e.extTextureCompressionBPTC.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case kc:this._glFormat=s.RED,this._glInternalFormat=s.R16F,this._glPixelType=s.HALF_FLOAT;break;case Ku:this._glFormat=s.RG,this._glInternalFormat=s.RG16F,this._glPixelType=s.HALF_FLOAT;break;case Lc:this._glFormat=s.RGB,this._glInternalFormat=s.RGB16F,this._glPixelType=s.HALF_FLOAT;break;case Ge:this._glFormat=s.RGBA,this._glInternalFormat=s.RGBA16F,this._glPixelType=s.HALF_FLOAT;break;case Lu:this._glFormat=s.RGB,this._glInternalFormat=s.RGB32F,this._glPixelType=s.FLOAT;break;case mt:this._glFormat=s.RGBA,this._glInternalFormat=s.RGBA32F,this._glPixelType=s.FLOAT;break;case Ti:this._glFormat=s.RED,this._glInternalFormat=s.R32F,this._glPixelType=s.FLOAT;break;case Oi:this._glFormat=s.DEPTH_COMPONENT,this._glInternalFormat=s.DEPTH_COMPONENT32F,this._glPixelType=s.FLOAT;break;case ja:this._glFormat=s.DEPTH_COMPONENT,this._glInternalFormat=s.DEPTH_COMPONENT16,this._glPixelType=s.UNSIGNED_SHORT;break;case en:this._glFormat=s.DEPTH_STENCIL,this._glInternalFormat=s.DEPTH24_STENCIL8,this._glPixelType=s.UNSIGNED_INT_24_8;break;case tn:this._glFormat=s.RGB,this._glInternalFormat=s.R11F_G11F_B10F,this._glPixelType=s.UNSIGNED_INT_10F_11F_11F_REV;break;case Fu:this._glFormat=s.RGB,this._glInternalFormat=s.SRGB8,this._glPixelType=s.UNSIGNED_BYTE;break;case us:this._glFormat=s.RGBA,this._glInternalFormat=s.SRGB8_ALPHA8,this._glPixelType=s.UNSIGNED_BYTE;break;case ku:this._glFormat=s.RED_INTEGER,this._glInternalFormat=s.R8I,this._glPixelType=s.BYTE;break;case Uu:this._glFormat=s.RED_INTEGER,this._glInternalFormat=s.R8UI,this._glPixelType=s.UNSIGNED_BYTE;break;case zu:this._glFormat=s.RED_INTEGER,this._glInternalFormat=s.R16I,this._glPixelType=s.SHORT;break;case Vu:this._glFormat=s.RED_INTEGER,this._glInternalFormat=s.R16UI,this._glPixelType=s.UNSIGNED_SHORT;break;case Gu:this._glFormat=s.RED_INTEGER,this._glInternalFormat=s.R32I,this._glPixelType=s.INT;break;case js:this._glFormat=s.RED_INTEGER,this._glInternalFormat=s.R32UI,this._glPixelType=s.UNSIGNED_INT;break;case Hu:this._glFormat=s.RG_INTEGER,this._glInternalFormat=s.RG8I,this._glPixelType=s.BYTE;break;case tg:this._glFormat=s.RG_INTEGER,this._glInternalFormat=s.RG8UI,this._glPixelType=s.UNSIGNED_BYTE;break;case Wu:this._glFormat=s.RG_INTEGER,this._glInternalFormat=s.RG16I,this._glPixelType=s.SHORT;break;case Xu:this._glFormat=s.RG_INTEGER,this._glInternalFormat=s.RG16UI,this._glPixelType=s.UNSIGNED_SHORT;break;case Yu:this._glFormat=s.RG_INTEGER,this._glInternalFormat=s.RG32I,this._glPixelType=s.INT;break;case Nc:this._glFormat=s.RG_INTEGER,this._glInternalFormat=s.RG32UI,this._glPixelType=s.UNSIGNED_INT;break;case ju:this._glFormat=s.RGBA_INTEGER,this._glInternalFormat=s.RGBA8I,this._glPixelType=s.BYTE;break;case sg:this._glFormat=s.RGBA_INTEGER,this._glInternalFormat=s.RGBA8UI,this._glPixelType=s.UNSIGNED_BYTE;break;case qu:this._glFormat=s.RGBA_INTEGER,this._glInternalFormat=s.RGBA16I,this._glPixelType=s.SHORT;break;case Vi:this._glFormat=s.RGBA_INTEGER,this._glInternalFormat=s.RGBA16UI,this._glPixelType=s.UNSIGNED_SHORT;break;case $u:this._glFormat=s.RGBA_INTEGER,this._glInternalFormat=s.RGBA32I,this._glPixelType=s.INT;break;case Wt:this._glFormat=s.RGBA_INTEGER,this._glInternalFormat=s.RGBA32UI,this._glPixelType=s.UNSIGNED_INT;break}this._glCreated=!1}upload(e,t){const s=e.gl;if(!t._needsUpload&&(t._needsMipmapsUpload&&t._mipmapsUploaded||!t.pot))return;let i=0,r,a;const n=t.numLevels;for(t.array&&!this._glCreated&&s.texStorage3D(s.TEXTURE_2D_ARRAY,n,this._glInternalFormat,t._width,t._height,t._arrayLength);t._levels[i]||i===0;){if(!t._needsUpload&&i===0){i++;continue}else if(i&&(!t._needsMipmapsUpload||!t._mipmaps))break;if(r=t._levels[i],a=1/Math.pow(2,i),i===1&&!t._compressed&&!t._integerFormat&&t._levels.length<n&&(s.generateMipmap(this._glTarget),t._mipmapsUploaded=!0),t._cubemap){let o;if(e._isBrowserInterface(r[0]))for(o=0;o<6;o++){if(!t._levelsUpdated[0][o])continue;let c=r[o];e._isImageBrowserInterface(c)&&(c.width>e.maxCubeMapSize||c.height>e.maxCubeMapSize)&&(c=iS(c,e.maxCubeMapSize),i===0&&(t._width=c.width,t._height=c.height)),e.setUnpackFlipY(!1),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),this._glCreated?s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+o,i,0,0,this._glFormat,this._glPixelType,c):s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+o,i,this._glInternalFormat,this._glFormat,this._glPixelType,c)}else for(a=1/Math.pow(2,i),o=0;o<6;o++){if(!t._levelsUpdated[0][o])continue;const c=r[o];t._compressed?this._glCreated&&c?s.compressedTexSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+o,i,0,0,Math.max(t._width*a,1),Math.max(t._height*a,1),this._glInternalFormat,c):s.compressedTexImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+o,i,this._glInternalFormat,Math.max(t._width*a,1),Math.max(t._height*a,1),0,c):(e.setUnpackFlipY(!1),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),e.setUnpackAlignment(1),this._glCreated&&c?s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+o,i,0,0,Math.max(t._width*a,1),Math.max(t._height*a,1),this._glFormat,this._glPixelType,c):s.texImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+o,i,this._glInternalFormat,Math.max(t._width*a,1),Math.max(t._height*a,1),0,this._glFormat,this._glPixelType,c))}}else if(t._volume)t._compressed?s.compressedTexImage3D(s.TEXTURE_3D,i,this._glInternalFormat,Math.max(t._width*a,1),Math.max(t._height*a,1),Math.max(t._depth*a,1),0,r):(e.setUnpackFlipY(!1),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),e.setUnpackAlignment(1),s.texImage3D(s.TEXTURE_3D,i,this._glInternalFormat,Math.max(t._width*a,1),Math.max(t._height*a,1),Math.max(t._depth*a,1),0,this._glFormat,this._glPixelType,r));else if(t.array){if(Array.isArray(r)&&t._arrayLength===r.length)if(t._compressed)for(let o=0;o<t._arrayLength;o++)s.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,i,0,0,o,Math.max(Math.floor(t._width*a),1),Math.max(Math.floor(t._height*a),1),1,this._glInternalFormat,r[o]);else{e.setUnpackAlignment(1);for(let o=0;o<t._arrayLength;o++)s.texSubImage3D(s.TEXTURE_2D_ARRAY,i,0,0,o,Math.max(Math.floor(t._width*a),1),Math.max(Math.floor(t._height*a),1),1,this._glFormat,this._glPixelType,r[o])}}else{if(e._isBrowserInterface(r))if(e._isHTMLElementInterface(r)&&e.supportsHtmlTextures){e.setUnpackFlipY(t._flipY),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha);const o=r.getBoundingClientRect(),c=Math.floor(o.width)||t._width,h=Math.floor(o.height)||t._height;s.texElementImage2D(s.TEXTURE_2D,this._glInternalFormat,r),i===0&&(t._width=c,t._height=h)}else{e._isImageBrowserInterface(r)&&(r.width>e.maxTextureSize||r.height>e.maxTextureSize)&&(r=iS(r,e.maxTextureSize),i===0&&(t._width=r.width,t._height=r.height));const o=r.width||r.videoWidth,c=r.height||r.videoHeight;e.setUnpackFlipY(t._flipY),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),this._glCreated&&t._width===o&&t._height===c&&!e._isImageVideoInterface(r)?s.texSubImage2D(s.TEXTURE_2D,i,0,0,this._glFormat,this._glPixelType,r):(s.texImage2D(s.TEXTURE_2D,i,this._glInternalFormat,this._glFormat,this._glPixelType,r),i===0&&(t._width=o,t._height=c))}else a=1/Math.pow(2,i),t._compressed?this._glCreated&&r?s.compressedTexSubImage2D(s.TEXTURE_2D,i,0,0,Math.max(Math.floor(t._width*a),1),Math.max(Math.floor(t._height*a),1),this._glInternalFormat,r):s.compressedTexImage2D(s.TEXTURE_2D,i,this._glInternalFormat,Math.max(Math.floor(t._width*a),1),Math.max(Math.floor(t._height*a),1),0,r):(e.setUnpackFlipY(!1),e.setUnpackPremultiplyAlpha(t._premultiplyAlpha),e.setUnpackAlignment(1),this._glCreated&&r?s.texSubImage2D(s.TEXTURE_2D,i,0,0,Math.max(t._width*a,1),Math.max(t._height*a,1),this._glFormat,this._glPixelType,r):s.texImage2D(s.TEXTURE_2D,i,this._glInternalFormat,Math.max(t._width*a,1),Math.max(t._height*a,1),0,this._glFormat,this._glPixelType,r));i===0?t._mipmapsUploaded=!1:t._mipmapsUploaded=!0}i++}if(t._needsUpload)if(t._cubemap)for(let o=0;o<6;o++)t._levelsUpdated[0][o]=!1;else t._levelsUpdated[0]=!1;!t._compressed&&!t._integerFormat&&t._mipmaps&&t._needsMipmapsUpload&&t._levels.length===1&&(s.generateMipmap(this._glTarget),t._mipmapsUploaded=!0),t._gpuSize&&t.adjustVramSizeTracking(e._vram,-t._gpuSize),t._gpuSize=t.gpuSize,t.adjustVramSizeTracking(e._vram,t._gpuSize),t.releaseSourceAfterUpload&&t.releaseImageSources(),this._glCreated=!0}uploadImmediate(e,t){(t._needsUpload||t._needsMipmapsUpload)&&(e.setTexture(t,0),t._needsUpload=!1,t._needsMipmapsUpload=!1)}read(e,t,s,i,r){const a=this.texture;return a.device.readTextureAsync(a,e,t,s,i,r)}write(e,t,s,i,r){const{texture:a}=this,{device:n}=a;return n.setTexture(a,0),n.writeTextureAsync(a,e,t,s,i,r)}}const _P=new Jt;class gP{msaaFB;resolveFB;constructor(e,t){this.msaaFB=e,this.resolveFB=t}destroy(e){this.msaaFB&&(e.deleteRenderbuffer(this.msaaFB),this.msaaFB=null),this.resolveFB&&(e.deleteRenderbuffer(this.resolveFB),this.resolveFB=null)}}class vP{_glFrameBuffer=null;_glDepthBuffer=null;_glResolveFrameBuffer=null;colorMrtFramebuffers=null;_glMsaaColorBuffers=[];_glMsaaDepthBuffer=null;msaaDepthBufferKey;suppliedColorFramebuffer;_isInitialized=!1;destroy(e){const t=e.gl;this._isInitialized=!1,this._glFrameBuffer&&(this._glFrameBuffer!==this.suppliedColorFramebuffer&&t.deleteFramebuffer(this._glFrameBuffer),this._glFrameBuffer=null),this._glDepthBuffer&&(t.deleteRenderbuffer(this._glDepthBuffer),this._glDepthBuffer=null),this._glResolveFrameBuffer&&(this._glResolveFrameBuffer!==this.suppliedColorFramebuffer&&t.deleteFramebuffer(this._glResolveFrameBuffer),this._glResolveFrameBuffer=null),this._glMsaaColorBuffers.forEac
412h(s=>{t.deleteRenderbuffer(s)}),this._glMsaaColorBuffers.length=0,this.colorMrtFramebuffers?.forEach(s=>{s.destroy(t)}),this.colorMrtFramebuffers=null,this._glMsaaDepthBuffer&&(this._glMsaaDepthBuffer=null,this.msaaDepthBufferKey&&Yl(e).release(this.msaaDepthBufferKey)),this.suppliedColorFramebuffer=void 0}get initialized(){return this._isInitialized}init(e,t){const s=e.gl;this._isInitialized=!0;const i=[];if(this.suppliedColorFramebuffer!==void 0)this._glFrameBuffer=this.suppliedColorFramebuffer;else{this._glFrameBuffer=s.createFramebuffer(),e.setFramebuffer(this._glFrameBuffer);const r=t._colorBuffers?.length??0,a=s.COLOR_ATTACHMENT0;for(let o=0;o<r;++o){const c=t.getColorBuffer(o);c&&(c.impl._glTexture||(c._width=Math.min(c.width,e.maxRenderBufferSize),c._height=Math.min(c.height,e.maxRenderBufferSize),e.setTexture(c,0)),s.framebufferTexture2D(s.FRAMEBUFFER,a+o,c._cubemap?s.TEXTURE_CUBE_MAP_POSITIVE_X+t._face:s.TEXTURE_2D,c.impl._glTexture,t.mipLevel),i.push(a+o))}s.drawBuffers(i);const n=t._depthBuffer;if(n||t._depth){const o=t._stencil?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT;if(n)n.impl._glTexture||(n._width=Math.min(n.width,e.maxRenderBufferSize),n._height=Math.min(n.height,e.maxRenderBufferSize),e.setTexture(n,0)),s.framebufferTexture2D(s.FRAMEBUFFER,o,n._cubemap?s.TEXTURE_CUBE_MAP_POSITIVE_X+t._face:s.TEXTURE_2D,t._depthBuffer.impl._glTexture,t.mipLevel);else if(!(t._samples>1)){this._glDepthBuffer||(this._glDepthBuffer=s.createRenderbuffer());const h=t._stencil?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT32F;s.bindRenderbuffer(s.RENDERBUFFER,this._glDepthBuffer),s.renderbufferStorage(s.RENDERBUFFER,h,t.width,t.height),s.framebufferRenderbuffer(s.FRAMEBUFFER,o,s.RENDERBUFFER,this._glDepthBuffer),s.bindRenderbuffer(s.RENDERBUFFER,null)}}}if(t._samples>1){this._glResolveFrameBuffer=this._glFrameBuffer,this._glFrameBuffer=s.createFramebuffer(),e.setFramebuffer(this._glFrameBuffer);const r=t._colorBuffers?.length??0;if(this.suppliedColorFramebuffer!==void 0){const a=s.createRenderbuffer();this._glMsaaColorBuffers.push(a);const n=e.backBufferFormat===Re?s.RGBA8:s.RGB8;s.bindRenderbuffer(s.RENDERBUFFER,a),s.renderbufferStorageMultisample(s.RENDERBUFFER,t._samples,n,t.width,t.height),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.RENDERBUFFER,a)}else for(let a=0;a<r;++a){const n=t.getColorBuffer(a);if(n){const o=s.createRenderbuffer();this._glMsaaColorBuffers.push(o),s.bindRenderbuffer(s.RENDERBUFFER,o),s.renderbufferStorageMultisample(s.RENDERBUFFER,t._samples,n.impl._glInternalFormat,t.width,t.height),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+a,s.RENDERBUFFER,o)}}if(t._depth){const a=t._stencil?s.DEPTH24_STENCIL8:s.DEPTH_COMPONENT32F,n=t._stencil?s.DEPTH_STENCIL_ATTACHMENT:s.DEPTH_ATTACHMENT;let o;const c=t._depthBuffer;c&&(o=`${c.id}:${t.width}:${t.height}:${t._samples}:${a}:${n}`,this._glMsaaDepthBuffer=Yl(e).get(o)),this._glMsaaDepthBuffer||(this._glMsaaDepthBuffer=s.createRenderbuffer(),s.bindRenderbuffer(s.RENDERBUFFER,this._glMsaaDepthBuffer),s.renderbufferStorageMultisample(s.RENDERBUFFER,t._samples,a,t.width,t.height),this._glMsaaDepthBuffer.destroy=function(){s.deleteRenderbuffer(this)},c&&Yl(e).set(o,this._glMsaaDepthBuffer)),this.msaaDepthBufferKey=o,s.framebufferRenderbuffer(s.FRAMEBUFFER,n,s.RENDERBUFFER,this._glMsaaDepthBuffer)}r>1&&(this._createMsaaMrtFramebuffers(e,t,r),e.setFramebuffer(this._glFrameBuffer),s.drawBuffers(i))}}_createMsaaMrtFramebuffers(e,t,s){const i=e.gl;this.colorMrtFramebuffers=[];for(let r=0;r<s;++r){const a=t.getColorBuffer(r),n=i.createFramebuffer();e.setFramebuffer(n);const o=this._glMsaaColorBuffers[r];i.bindRenderbuffer(i.RENDERBUFFER,o),i.renderbufferStorageMultisample(i.RENDERBUFFER,t._samples,a.impl._glInternalFormat,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,o),i.drawBuffers([i.COLOR_ATTACHMENT0]);const c=i.createFramebuffer();e.setFramebuffer(c),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,a._cubemap?i.TEXTURE_CUBE_MAP_POSITIVE_X+t._face:i.TEXTURE_2D,a.impl._glTexture,0),this.colorMrtFramebuffers[r]=new gP(n,c)}}_checkFbo(e,t,s=""){const i=t._colorBuffers?.map(h=>h?.format??-1).join(",")??"",r=t._depth?t._depthBuffer?`dt${t._depthBuffer.format}`:t._stencil?"ds":"d":"",a=`${s}:${i}:${r}:${t._samples}`,n=_P.get(e,()=>{const h=new Set;return h.loseContext=()=>h.clear(),h});if(n.has(a))return;const o=e.gl,c=o.checkFramebufferStatus(o.FRAMEBUFFER);switch(c){case o.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:break;case o.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:break;case o.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:break;case o.FRAMEBUFFER_UNSUPPORTED:break}c===o.FRAMEBUFFER_COMPLETE&&n.add(a)}loseContext(){this._glFrameBuffer=null,this._glDepthBuffer=null,this._glResolveFrameBuffer=null,this._glMsaaColorBuffers.length=0,this._glMsaaDepthBuffer=null,this.msaaDepthBufferKey=void 0,this.colorMrtFramebuffers=null,this.suppliedColorFramebuffer=void 0,this._isInitialized=!1}internalResolve(e,t,s,i,r){e.setScissor(0,0,i.width,i.height);const a=e.gl;a.bindFramebuffer(a.READ_FRAMEBUFFER,t),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,s),a.blitFramebuffer(0,0,i.width,i.height,0,0,i.width,i.height,r,a.NEAREST)}resolve(e,t,s,i){const r=e.gl;if(this.colorMrtFramebuffers){if(s)for(let a=0;a<this.colorMrtFramebuffers.length;a++){const n=this.colorMrtFramebuffers[a];this.internalResolve(e,n.msaaFB,n.resolveFB,t,r.COLOR_BUFFER_BIT)}i&&this.internalResolve(e,this._glFrameBuffer,this._glResolveFrameBuffer,t,r.DEPTH_BUFFER_BIT)}else{const a=!!e.defaultFramebuffer&&this._glResolveFrameBuffer===e.defaultFramebuffer;s&&a&&Ce.visionos&&(e.resolveMsaaColorToXrFramebufferViaQuads(this._glFrameBuffer,this._glResolveFrameBuffer,t.width,t.height),s=!1),(s||i)&&this.internalResolve(e,this._glFrameBuffer,this._glResolveFrameBuffer,t,(s?r.COLOR_BUFFER_BIT:0)|(i?r.DEPTH_BUFFER_BIT:0))}r.bindFramebuffer(r.FRAMEBUFFER,this._glFrameBuffer)}}class SP{availablePBOs=[];pendingPBOs=[];constructor(e){this.uploadStream=e,this.useSingleBuffer=e.useSingleBuffer}destroy(){const e=this.uploadStream.device.gl;
412this.availablePBOs.forEach(t=>e.deleteBuffer(t.pbo)),this.pendingPBOs.forEach(t=>{t.sync&&e.deleteSync(t.sync),e.deleteBuffer(t.pbo)})}_onDeviceLost(){this.availablePBOs.length=0,this.pendingPBOs.length=0}update(e){const t=this.uploadStream.device.gl,s=this.pendingPBOs;for(let r=s.length-1;r>=0;r--){const a=s[r],n=t.clientWaitSync(a.sync,0,0);(n===t.CONDITION_SATISFIED||n===t.ALREADY_SIGNALED)&&(t.deleteSync(a.sync),this.availablePBOs.push({pbo:a.pbo,size:a.size}),s.splice(r,1))}const i=this.availablePBOs;for(let r=i.length-1;r>=0;r--)i[r].size<e&&(t.deleteBuffer(i[r].pbo),i.splice(r,1))}upload(e,t,s,i){this.useSingleBuffer?this.uploadDirect(e,t,s,i):this.uploadPBO(e,t,s,i)}uploadDirect(e,t,s,i){const r=this.uploadStream.device,a=r.gl,n=t.impl;r.setTexture(t,0),r.activeTexture(0),r.bindTexture(t),r.setUnpackFlipY(!1),r.setUnpackPremultiplyAlpha(!1),r.setUnpackAlignment(e.BYTES_PER_ELEMENT);let o=e;if(n._glPixelType===a.UNSIGNED_BYTE&&e.BYTES_PER_ELEMENT!==1){const c=i*e.BYTES_PER_ELEMENT;o=new Uint8Array(e.buffer,e.byteOffset,c)}a.texImage2D(a.TEXTURE_2D,0,n._glInternalFormat,t.width,t.height,0,n._glFormat,n._glPixelType,o),n._glCreated=!0}uploadPBO(e,t,s,i){const r=this.uploadStream.device,a=r.gl,n=t.width,o=i*e.BYTES_PER_ELEMENT;this.update(o);const c=s/n,h=i/n,d=this.availablePBOs.pop()??{pbo:a.createBuffer(),size:o};a.bindBuffer(a.PIXEL_UNPACK_BUFFER,d.pbo),a.bufferData(a.PIXEL_UNPACK_BUFFER,o,a.STREAM_DRAW),a.bufferSubData(a.PIXEL_UNPACK_BUFFER,0,new Uint8Array(e.buffer,e.byteOffset,o)),a.bindBuffer(a.PIXEL_UNPACK_BUFFER,null),r.setTexture(t,0),r.activeTexture(0),r.bindTexture(t),a.bindBuffer(a.PIXEL_UNPACK_BUFFER,d.pbo),r.setUnpackFlipY(!1),r.setUnpackPremultiplyAlpha(!1),r.setUnpackAlignment(e.BYTES_PER_ELEMENT),a.pixelStorei(a.UNPACK_ROW_LENGTH,0),a.pixelStorei(a.UNPACK_SKIP_ROWS,0),a.pixelStorei(a.UNPACK_SKIP_PIXELS,0);const u=t.impl;a.texSubImage2D(a.TEXTURE_2D,0,0,c,n,h,u._glFormat,u._glPixelType,0),a.bindBuffer(a.PIXEL_UNPACK_BUFFER,null);const f=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);this.pendingPBOs.push({pbo:d.pbo,size:o,sync:f}),a.flush()}}class yP{_presentationLayer=null;_graphicsBinding=null;_cameraFbSource=null;_cameraFbDest=null;constructor(e){this.xrBridge=e}destroy(e){this._graphicsBinding=null,this._presentationLayer=null,this._deleteCameraFramebuffers(e)}_deleteCameraFramebuffers(e){if(this._cameraFbSource){const t=e.gl;t.deleteFramebuffer(this._cameraFbSource),this._cameraFbSource=null,t.deleteFramebuffer(this._cameraFbDest),this._cameraFbDest=null}}beginFrame(e,t){const s=e.session.renderState.baseLayer;this.xrBridge.device.defaultFramebuffer=s?s.framebuffer:null}endFrame(){this.xrBridge.device.defaultFramebuffer=null}get presentationLayer(){return this._presentationLayer}get graphicsBinding(){return this._graphicsBinding}getFramebufferSize(e,t){const s=e.session.renderState.baseLayer;if(!s){t.set(0,0);return}t.set(s.framebufferWidth,s.framebufferHeight)}getViewport(e,t){const s=e.session.renderState.baseLayer;return s?s.getViewport(t):{x:0,y:0,width:0,height:0}}attachPresentation(e,t){const s=this.xrBridge.device;if(this._presentationLayer=new XRWebGLLayer(e,s.gl,{alpha:!0,depth:!0,stencil:!0,framebufferScaleFactor:t.framebufferScaleFactor,antialias:!1}),window.XRWebGLBinding)try{this._graphicsBinding=new XRWebGLBinding(e,s.gl)}catch(i){this.xrBridge._onBindingError?.(i)}e.updateRenderState({baseLayer:this._presentationLayer,depthNear:t.depthNear,depthFar:t.depthFar})}releasePresentation(){this._graphicsBinding=null}syncCameraColorTexture(e,t){if(!this._graphicsBinding)return;const s=this.xrBridge.device,i=s.gl,r=this._graphicsBinding.getCameraImage(e);if(!r)return;this._cameraFbSource||(this._cameraFbSource=i.createFramebuffer(),this._cameraFbDest=i.createFramebuffer());const a=e.width,n=e.height;s.setFramebuffer(this._cameraFbSource),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,r,0),s.setFramebuffer(this._cameraFbDest),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,t.impl._glTexture,0),i.bindFramebuffer(i.READ_FRAMEBUFFER,this._cameraFbSource),i.bindFramebuffer(i.DRAW_FRAMEBUFFER,this._cameraFbDest),i.blitFramebuffer(0,n,a,0,0,0,a,n,i.COLOR_BUFFER_BIT,i.NEAREST),s.setFramebuffer(s.defaultFramebuffer)}syncCameraDepthTexture(e,t,s){if(!e?.texture)return;const i=this.xrBridge.device.gl;switch(t.impl._glTexture=e.texture,e.textureType==="texture-array"?t.impl._glTarget=i.TEXTURE_2D_ARRAY:t.impl._glTarget=i.TEXTURE_2D,s){case Ti:t.impl._glInternalFormat=i.R32F,t.impl._glPixelType=i.FLOAT,t.impl._glFormat=i.RED;break;
412case Oi:t.impl._glInternalFormat=i.DEPTH_COMPONENT16,t.impl._glPixelType=i.UNSIGNED_SHORT,t.impl._glFormat=i.DEPTH_COMPONENT;break}t.impl._glCreated=!0}onGraphicsDeviceLost(){const e=this.xrBridge._session;if(!e)return;const t=e.renderState;this._graphicsBinding=null,this._presentationLayer=null,this._cameraFbSource=null,this._cameraFbDest=null,e.updateRenderState({baseLayer:this._presentationLayer,depthNear:t.depthNear,depthFar:t.depthFar})}onGraphicsDeviceRestored(){const e=this.xrBridge;if(!e._session)return;const t=e.device,s=e.eventHandler;setTimeout(()=>{e._session&&t.gl.makeXRCompatible().then(()=>{if(!e._session)return;const i=e._session.renderState;e.attachPresentation(e._session,{framebufferScaleFactor:e._framebufferScaleFactor,depthNear:i.depthNear,depthFar:i.depthFar,onBindingError:e._onBindingError})}).catch(i=>{s.fire("error",i)})},0)}}const xP={type:qs,base:0,count:6,indexed:!0},TP=` 413 attribute vec2 vertex_position; 414 varying vec2 pcTexCoord; 415 void main() { 416 gl_Position = vec4(vertex_position, 0.0, 1.0); 417 pcTexCoord = vertex_position * 0.5 + 0.5; 418 } 419`,wP=` 420 uniform sampler2D pcSource; 421 varying vec2 pcTexCoord; 422 void main() { 423 gl_FragColor = texture2D(pcSource, pcTexCoord); 424 } 425`;class CP{_device;_shader=null;_scratchTex=null;_scratchRt=null;_sourceId=null;constructor(e){this._device=e}_getShader(){if(!this._shader){const e=this._device;this._shader=new tt(e,Ht.createDefinition(e,{name:"XrMsaaCopy",attributes:{vertex_position:Ie},vertexCode:TP,fragmentCode:wP})),this._sourceId=e.scope.resolve("pcSource")}return this._shader}_ensureScratch(e,t){const s=this._device;this._scratchTex&&(this._scratchTex.width!==e||this._scratchTex.height!==t)&&(this._scratchRt.destroy(),this._scratchRt=null,this._scratchTex.destroy(),this._scratchTex=null),this._scratchTex||(this._scratchTex=ce.createDataTexture2D(s,"XrMsaaScratch",e,t,s.backBufferFormat),this._scratchRt=new St({colorBuffer:this._scratchTex,depth:!1,stencil:!1})),this._scratchRt.impl.initialized||this._scratchRt.impl.init(s,this._scratchRt)}copy(e,t,s,i){this._ensureScratch(s,i);const r=this._device,a=r.gl;a.bindFramebuffer(a.READ_FRAMEBUFFER,e),a.bindFramebuffer(a.DRAW_FRAMEBUFFER,this._scratchRt.impl._glFrameBuffer),a.blitFramebuffer(0,0,s,i,0,0,s,i,a.COLOR_BUFFER_BIT,a.NEAREST),r.setDrawStates(xt.NOBLEND,ds.NODEPTH),r.setFramebuffer(t),r.setShader(this._getShader()),r.clearVertexBuffer(),r.setVertexBuffer(r.quadVertexBuffer),this._sourceId.setValue(this._scratchTex);const{vx:n,vy:o,vw:c,vh:h,sx:d,sy:u,sw:f,sh:p}=r;r.setViewport(0,0,s,i),r.setScissor(0,0,s,i),r.draw(xP,r.quadIndexBuffer),r.setViewport(n,o,c,h),r.setScissor(d,u,f,p),r.setFramebuffer(e)}destroy(){this._shader?.destroy(),this._shader=null,this._scratchRt?.destroy(),this._scratchRt=null,this._scratchTex?.destroy(),this._scratchTex=null,this._sourceId=null}}class EP{renderVersion;queries=[];destroy(e){this.queries.forEach(t=>e.deleteQuery(t)),this.queries=null}}class bP extends lT{device;freeQueries=[];frameQueries=[];previousFrameQueries=[];timings=[];constructor(e){super(),this.device=e,this.ext=e.extDisjointTimerQuery}destroy(){this.freeQueries.forEach(e=>this.device.gl.deleteQuery(e)),this.frameQueries.forEach(e=>this.device.gl.deleteQuery(e)),this.previousFrameQueries.forEach(e=>e.destroy(this.device.gl)),this.freeQueries=null,this.frameQueries=null,this.previousFrameQueries=null}loseContext(){super.loseContext(),this.freeQueries=[],this.frameQueries=[],this.previousFrameQueries=[]}restoreContext(){this.ext=this.device.extDisjointTimerQuery}getQuery(){return this.freeQueries.pop()??this.device.gl.createQuery()}start(e){if(this.ext){const t=this.getSlot(e),s=this.getQuery();return this.frameQueries[t]=s,this.device.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,s),t}}end(e){e!==void 0&&this.device.gl.endQuery(this.ext.TIME_ELAPSED_EXT)}frameStart(){this.processEnableRequest(),this._enabled&&(this.frameGPUMarkerSlot=this.start("GpuFrame"))}frameEnd(){this._enabled&&this.end(this.frameGPUMarkerSlot)}request(){if(this._enabled){const e=this.ext,t=this.device.gl,s=this.device.renderVersion,i=this.frameQueries;if(i.length>0){this.frameQueries=[];const r=new EP;r.queries=i,r.renderVersion=s,this.previousFrameQueries.push(r)}if(this.previousFrameQueries.length>0){const r=this.previousFrameQueries[0],a=r.queries,n=a[a.length-1],o=t.getQueryParameter(n,t.QUERY_RESULT_AVAILABLE),c=t.getParameter(e.GPU_DISJOINT_EXT);if(o&&!c){this.previousFrameQueries.shift();const h=this.timings;h.length=0;for(let d=0;d<a.length;d++){const u=a[d],f=t.getQueryParameter(u,t.QUERY_RESULT);h[d]=f*1e-6,this.freeQueries.push(u)}this.report(r.renderVersion,h)}
425c&&(this.previousFrameQueries.forEach(h=>{this.report(h.renderVersion,null),h.destroy(t)}),this.previousFrameQueries.length=0)}super.request(s)}}}const AP=l=>{switch(l){case Zu:return 1;case Qu:return 2;default:return 0}},In=[];class hT extends Je{gl;_defaultFramebuffer=null;_defaultFramebufferChanged=!1;_xrMsaaCopy=null;constructor(e,t={}){super(e,t),t=this.initOptions,this.updateClientRect(),this.initTextureUnits(),this.contextLost=!1,this._contextLostHandler=f=>{f.preventDefault(),this.loseContext()},this._contextRestoredHandler=()=>{this.restoreContext()};const s=typeof navigator<"u"&&navigator.userAgent;if(this.forceDisableMultisampling=s&&s.includes("AppleWebKit")&&(s.includes("15.4")||s.includes("15_4")),this.forceDisableMultisampling&&(t.antialias=!1),Ce.browserName==="firefox"){const p=(typeof navigator<"u"?navigator.userAgent:"").match(/Firefox\/(\d+(\.\d+)*)/),m=p?p[1]:null;if(m){const _=parseFloat(m);(Ce.name==="windows"&&(_>=120||_===115)||Ce.name==="android"&&_>=132)&&(t.antialias=!1)}}this.backBufferAntialias=t.antialias??!1,t.antialias=!1;const i=t.gl??e.getContext("webgl2",t);if(!i)throw new Error("WebGL not supported");this.gl=i,this.isWebGL2=!0,this._deviceType=xd,this.updateBackbufferFormat(null);const r=Ce.browserName==="chrome",a=Ce.browserName==="safari",n=Ce.browser&&navigator.appVersion.indexOf("Mac")!==-1;this._tempEnableSafariTextureUnitWorkaround=a,this._tempMacChromeBlitFramebufferWorkaround=n&&r&&!t.alpha,e.addEventListener("webglcontextlost",this._contextLostHandler,!1),e.addEventListener("webglcontextrestored",this._contextRestoredHandler,!1),this.initializeExtensions(),this.initializeCapabilities(),this.initializeRenderState(),this.initializeContextCaches(),this.createBackbuffer(null),this.supportsImageBitmap=!a&&typeof ImageBitmap<"u",this._samplerTypes=new Set([i.SAMPLER_2D,i.SAMPLER_CUBE,i.UNSIGNED_INT_SAMPLER_2D,i.INT_SAMPLER_2D,i.SAMPLER_2D_SHADOW,i.SAMPLER_CUBE_SHADOW,i.SAMPLER_3D,i.INT_SAMPLER_3D,i.UNSIGNED_INT_SAMPLER_3D,i.SAMPLER_2D_ARRAY,i.INT_SAMPLER_2D_ARRAY,i.UNSIGNED_INT_SAMPLER_2D_ARRAY]),this.glAddress=[i.REPEAT,i.CLAMP_TO_EDGE,i.MIRRORED_REPEAT],this.glBlendEquation=[i.FUNC_ADD,i.FUNC_SUBTRACT,i.FUNC_REVERSE_SUBTRACT,i.MIN,i.MAX],this.glBlendFunctionColor=[i.ZERO,i.ONE,i.SRC_COLOR,i.ONE_MINUS_SRC_COLOR,i.DST_COLOR,i.ONE_MINUS_DST_COLOR,i.SRC_ALPHA,i.SRC_ALPHA_SATURATE,i.ONE_MINUS_SRC_ALPHA,i.DST_ALPHA,i.ONE_MINUS_DST_ALPHA,i.CONSTANT_COLOR,i.ONE_MINUS_CONSTANT_COLOR],this.glBlendFunctionAlpha=[i.ZERO,i.ONE,i.SRC_COLOR,i.ONE_MINUS_SRC_COLOR,i.DST_COLOR,i.ONE_MINUS_DST_COLOR,i.SRC_ALPHA,i.SRC_ALPHA_SATURATE,i.ONE_MINUS_SRC_ALPHA,i.DST_ALPHA,i.ONE_MINUS_DST_ALPHA,i.CONSTANT_ALPHA,i.ONE_MINUS_CONSTANT_ALPHA],this.glComparison=[i.NEVER,i.LESS,i.EQUAL,i.LEQUAL,i.GREATER,i.NOTEQUAL,i.GEQUAL,i.ALWAYS],this.glStencilOp=[i.KEEP,i.ZERO,i.REPLACE,i.INCR,i.INCR_WRAP,i.DECR,i.DECR_WRAP,i.INVERT],this.glClearFlag=[0,i.COLOR_BUFFER_BIT,i.DEPTH_BUFFER_BIT,i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT,i.STENCIL_BUFFER_BIT,i.STENCIL_BUFFER_BIT|i.COLOR_BUFFER_BIT,i.STENCIL_BUFFER_BIT|i.DEPTH_BUFFER_BIT,i.STENCIL_BUFFER_BIT|i.COLOR_BUFFER_BIT|i.DEPTH_BUFFER_BIT],this.glCull=[0,i.BACK,i.FRONT,i.FRONT_AND_BACK],this.glFrontFace=[i.CCW,i.CW],this.glFilter=[i.NEAREST,i.LINEAR,i.NEAREST_MIPMAP_NEAREST,i.NEAREST_MIPMAP_LINEAR,i.LINEAR_MIPMAP_NEAREST,i.LINEAR_MIPMAP_LINEAR],this.glPrimitive=[i.POINTS,i.LINES,i.LINE_LOOP,i.LINE_STRIP,i.TRIANGLES,i.TRIANGLE_STRIP,i.TRIANGLE_FAN],this.glType=[i.BYTE,i.UNSIGNED_BYTE,i.SHORT,i.UNSIGNED_SHORT,i.INT,i.UNSIGNED_INT,i.FLOAT,i.HALF_FLOAT],this.pcUniformType={},this.pcUniformType[i.BOOL]=So,this.pcUniformType[i.INT]=_r,this.pcUniformType[i.FLOAT]=me,this.pcUniformType[i.FLOAT_VEC2]=sn,this.pcUniformType[i.FLOAT_VEC3]=hs,this.pcUniformType[i.FLOAT_VEC4]=Cr,this.pcUniformType[i.INT_VEC2]=$a,this.pcUniformType[i.INT_VEC3]=gr,this.pcUniformType[i.INT_VEC4]=Ka,this.pcUniformType[i.BOOL_VEC2]=oc,this.pcUniformType[i.BOOL_VEC3]=lc,this.pcUniformType[i.BOOL_VEC4]=cc,this.pcUniformType[i.FLOAT_MAT2]=su,this.pcUniformType[i.FLOAT_MAT3]=Do,this.pcUniformType[i.FLOAT_MAT4]=Ss,this.pcUniformType[i.SAMPLER_2D]=ab,this.pcUniformType[i.SAMPLER_CUBE]=nb,this.pcUniformType[i.UNSIGNED_INT]=le,this.pcUniformType[i.UNSIGNED_INT_VEC2]=Mo,this.pcUniformType[i.UNSIGNED_INT_VEC3]=Ro,this.pcUniformType[i.UNSIGNED_INT_VEC4]=oa,this.pcUniformType[i.SAMPLER_2D_SHADOW]=ob,this.pcUniformType[i.SAMPLER_CUBE_SHADOW]=lb,this.pcUniformType[i.SAMPLER_2D_ARRAY]=hb,this.pcUniformType[i.SAMPLER_3D]=cb,this.pcUniformType[i.INT_SAMPLER_2D]=db,this.pcUniformType[i.UNSIGNED_INT_SAMPLER_2D]=ub,this.pcUniformType[i.INT_SAMPLER_CUBE]=fb,this.pcUniformType[i.UNSIGNED_INT_SAMPLER_2D]=pb,this.pcUniformType[i.INT_SAMPLER_3D]=mb,this.pcUniformType[i.UNSIGNED_INT_SAMPLER_3D]=_b,this.pcUniformType[i.INT_SAMPLER_2D_ARRAY]=gb,this.pcUniformType[i.UNSIGNED_INT_SAMPLER_2D_ARRAY]=vb,this.targetToSlot={},this.targetToSlot[i.TEXTURE_2D]=0,this.targetToSlot[i.TEXTURE_CUBE_MAP]=1,this.targetToSlot[i.TEXTURE_3D]=2;let o,c,h,d,u;this.commitFunction=[],this.commitFunction[So]=function(f,p){f.value!==p&&(i.uniform1i(f.locationId,p),f.value=p)},this.commitFunction[_r]=this.commitFunction[So],this.commitFunction[me]=function(f,p){f.value!==p&&(i.uniform1f(f.locationId,p),f.value=p)},this.commitFunction[sn]=function(f,p){u=f.value,o=p[0],c=p[1],(u[0]!==o||u[1]!==c)&&(i.uniform2fv(f.locationId,p),u[0]=o,u[1]=c)},this.commitFunction[hs]=function(f,p){u=f.value,o=p[0],c=p[1],h=p[2],(u[0]!==o||u[1]!==c||u[2]!==h)&&(i.uniform3fv(f.locationId,p),u[0]=o,u[1]=c,u[2]=h)},this.commitFunction[Cr]=function(f,p){u=f.value,o=p[0],c=p[1],h=p[2],d=p[3],(u[0]!==o||u[1]!==c||u[2]!==h||u[3]!==d)&&(i.uniform4fv(f.locationId,p),u[0]=o,u[1]=c,u[2]=h,u[3]=d)},this.commitFunction[$a]=function(f,p){u=f.value,o=p[0],c=p[1],(u[0]!==o||u[1]!==c)&&(i.uniform2iv(f.locationId,p),u[0]=o,u[1]=c)},this.commitFunction[oc]=this.commitFunction[$a],this.commitFunction[gr]=function(f,p){u=f.value,o=p[0],c=p[1],h=p[2],(u[0]!==o||u[1]!==c||u[2]!==h)&&(i.uniform3iv(f.locationId,p),u[0]=o,u[1]=c,u[2]=h)},this.commitFunction[lc]=this.commitFunction[gr],this.commitFunction[Ka]=function(f,p){u=f.value,o=p[0],c=p[1],h=p[2],d=p[3],(u[0]!==o||u[1]!==c||u[2]!==h||u[3]!==d)&&(i.uniform4iv(f.locationId,p),u[0]=o,u[1]=c,u[2]=h,u[3]=d)},this.commitFunction[cc]=this.commitFunction[Ka],this.commitFunction[su]=function(f,p){i.uniformMatrix2fv(f.locationId,!1,p)},this.commitFunction[Do]=function(f,p){i.uniformMatrix3fv(f.locationId,!1,p)},this.commitFunction[Ss]=function(f,p){i.uniformMatrix4fv(f.locationId,!1,p)},this.commitFunction[df]=function(f,p){i.uniform1fv(f.locationId,p)},this.commitFunction[uf]=function(f,p){i.uniform2fv(f.locationId,p)},this.commitFunction[ff]=function(f,p){i.uniform3fv(f.locationId,p)},this.commitFunction[pg]=function(f,p){i.uniform4fv(f.locationId,p)},this.commitFunction[le]=function(f,p){f.value!==p&&(i.uniform1ui(f.locationId,p),f.value=p)},this.commitFunction[Mo]=function(f,p){u=f.value,o=p[0],c=p[1],(u[0]!==o||u[1]!==c)&&(i.uniform2uiv(f.locationId,p),u[0]=o,u[1]=c)},this.commitFunction[Ro]=function(f,p){u=f.value,o=p[0],c=p[1],h=p[2],(u[0]!==o||u[1]!==c||u[2]!==h)&&(i.uniform3uiv(f.locationId,p),u[0]=o,u[1]=c,u[2]=h)},this.commitFunction[oa]=function(f,p){u=f.value,o=p[0],c=p[1],h=p[2],d=p[3],(u[0]!==o||u[1]!==c||u[2]!==h||u[3]!==d)&&(i.uniform4uiv(f.locationId,p),u[0]=o,u[1]=c,u[2]=h,u[3]=d)},this.commitFunction[Lo]=function(f,p){i.uniform1iv(f.locationId,p)},this.commitFunction[pf]=function(f,p){i.uniform1uiv(f.locationId,p)},this.commitFunction[mf]=this.commitFunction[Lo],this.commitFunction[Fo]=function(f,p){i.uniform2iv(f.locationId,p)},this.commitFunction[_f]=function(f,p){i.uniform2uiv(f.locationId,p)},this.commitFunction[gf]=this.commitFunction[Fo],this.commitFunction[Oo]=function(f,p){i.uniform3iv(f.locationId,p)},this.commitFunction[vf]=function(f,p){i.uniform3uiv(f.locationId,p)},this.commitFunction[Sf]=this.commitFunction[Oo],this.commitFunction[iu]=function(f,p){i.uniform4iv(f.locationId,p)},this.commitFunction[mg]=function(f,p){i.uniform4uiv(f.locationId,p)},this.commitFunction[_g]=this.commitFunction[iu],this.commitFunction[Ux]=function(f,p){i.uniformMatrix4fv(f.locationId,!1,p)},this.constantTexSource=this.scope.resolve("source"),this.postInit()}postInit(){super.postInit(),this.gpuProfiler=new bP(this)}destroy(){super.destroy();const e=this.gl;this.feedback&&e.deleteTransformFeedback(this.feedback),this.clearVertexArrayObjectCache(),this._xrMsaaCopy?.destroy(),this._xrMsaaCopy=null,this.canvas.removeEventListener("webglcontextlost",this._contextLostHandler,!1),this.canvas.removeEventListener("webglcontextrestored",this._contextRestoredHandler,!1),this._contextLostHandler=null,this._contextRestoredHandler=null,this.gl=null,super.postDestroy()}createBackbuffer(e){this.supportsStencil=this.initOptions.stencil,this.backBuffer=new St({name:"WebglFramebuffer",graphicsDevice:this,depth:this.initOptions.depth,stencil:this.supportsStencil,samples:this.samples}),this.backBuffer.impl.suppliedColorFramebuffer=e}updateBackbufferFormat(e){const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,e);const s=this.gl.getParameter(this.gl.ALPHA_BITS);this.backBufferFormat=s?Re:Er}updateBackbuffer(){const e=this.canvas.width!==this.backBufferSize.x||this.canvas.height!==this.backBufferSize.y;(this._defaultFramebufferChanged||e)&&(this._defaultFramebufferChanged&&this.updateBackbufferFormat(this._defaultFramebuffer),this._defaultFramebufferChanged=!1,this.backBufferSize.set(this.canvas.width,this.canvas.height),this.backBuffer.destroy(),this.createBackbuffer(this._defaultFramebuffer))}createVertexBufferImpl(e,t){return new oP}createIndexBufferImpl(e){return new lP(e)}createShaderImpl(e){return new fP(e)}createDrawCommandImpl(e){return new pP(e.indexSizeBytes)}createTextureImpl(e){return this.textures.add(e),new mP(e)}createXrBridgeImpl(e){return new yP(e)}createRenderTargetImpl(e){return new vP}createUploadStreamImpl(e){return new SP(e)}getPrecision(){const e=this.gl;let t="highp";if(e.getShaderPrecisionFormat){const s=e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT),i=e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT),r=e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT),a=e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT);if(s&&i&&r&&a){const n=s.precision>0&&r.precision>0,o=i.precision>0&&a.precision>0;n||(o?t="mediump":t="lowp")}}return t}getExtension(){for(let e=0;e<arguments.length;e++)if(this.supportedExtensions.indexOf(arguments[e])!==-1)return this.gl.getExtension(arguments[e]);return null}get extDisjointTimerQuery(){return this._extDisjointTimerQuery||(this._extDisjointTimerQuery=this.getExtension("EXT_disjoint_timer_query_webgl2","EXT_disjoint_timer_query")),this._extDisjointTimerQuery}initializeExtensions(){const e=this.gl;
425this.supportedExtensions=e.getSupportedExtensions()??[],this._extDisjointTimerQuery=null,this.textureRG11B10Renderable=!0,this.extColorBufferFloat=this.getExtension("EXT_color_buffer_float"),this.textureFloatRenderable=!!this.extColorBufferFloat,this.extColorBufferHalfFloat=this.getExtension("EXT_color_buffer_half_float"),this.textureHalfFloatRenderable=!!this.extColorBufferHalfFloat||!!this.extColorBufferFloat,this.extDebugRendererInfo=this.getExtension("WEBGL_debug_renderer_info"),this.extTextureFloatLinear=this.getExtension("OES_texture_float_linear"),this.textureFloatFilterable=!!this.extTextureFloatLinear,this.extFloatBlend=this.getExtension("EXT_float_blend"),this.extTextureFilterAnisotropic=this.getExtension("EXT_texture_filter_anisotropic","WEBKIT_EXT_texture_filter_anisotropic"),this.extParallelShaderCompile=this.getExtension("KHR_parallel_shader_compile"),this.extMultiDraw=this.getExtension("WEBGL_multi_draw"),this.supportsMultiDraw=!!this.extMultiDraw,this.extCompressedTextureETC1=this.getExtension("WEBGL_compressed_texture_etc1"),this.extCompressedTextureETC=this.getExtension("WEBGL_compressed_texture_etc"),this.extCompressedTexturePVRTC=this.getExtension("WEBGL_compressed_texture_pvrtc","WEBKIT_WEBGL_compressed_texture_pvrtc"),this.extCompressedTextureS3TC=this.getExtension("WEBGL_compressed_texture_s3tc","WEBKIT_WEBGL_compressed_texture_s3tc"),this.extCompressedTextureS3TC_SRGB=this.getExtension("WEBGL_compressed_texture_s3tc_srgb"),this.extCompressedTextureATC=this.getExtension("WEBGL_compressed_texture_atc"),this.extCompressedTextureASTC=this.getExtension("WEBGL_compressed_texture_astc"),this.extTextureCompressionBPTC=this.getExtension("EXT_texture_compression_bptc"),this.supportsHtmlTextures=typeof e.texElementImage2D=="function"}initializeCapabilities(){const e=this.gl;let t;const s=typeof navigator<"u"?navigator.userAgent:"";this.maxPrecision=this.precision=this.getPrecision();const i=e.getContextAttributes();this.supportsMsaa=i?.antialias??!1,this.supportsStencil=i?.stencil??!1,this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.maxCubeMapSize=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),this.maxRenderBufferSize=e.getParameter(e.MAX_RENDERBUFFER_SIZE),this.maxTextures=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),this.maxCombinedTextures=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),this.maxVertexTextures=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),this.vertexUniformsCount=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),this.fragmentUniformsCount=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),this.maxColorAttachments=e.getParameter(e.MAX_COLOR_ATTACHMENTS),this.maxVolumeSize=e.getParameter(e.MAX_3D_TEXTURE_SIZE),t=this.extDebugRendererInfo,this.unmaskedRenderer=t?e.getParameter(t.UNMASKED_RENDERER_WEBGL):"",this.unmaskedVendor=t?e.getParameter(t.UNMASKED_VENDOR_WEBGL):"";const r=/\bMali-G52+/,a=/SM-[a-zA-Z0-9]+/;this.supportsGpuParticles=!(this.unmaskedVendor==="ARM"&&s.match(a))&&!this.unmaskedRenderer.match(r),t=this.extTextureFilterAnisotropic,this.maxAnisotropy=t?e.getParameter(t.MAX_TEXTURE_MAX_ANISOTROPY_EXT):1;const n=!this.forceDisableMultisampling;this.maxSamples=n?e.getParameter(e.MAX_SAMPLES):1,this.maxSamples=Math.min(this.maxSamples,4),this.samples=n&&this.backBufferAntialias?this.maxSamples:1,this.supportsAreaLights=!Ce.android,this.maxTextures<=8&&(this.supportsAreaLights=!1),this.initCapsDefines()}initializeRenderState(){super.initializeRenderState();const e=this.gl;e.disable(e.BLEND),e.blendFunc(e.ONE,e.ZERO),e.blendEquation(e.FUNC_ADD),e.colorMask(!0,!0,!0,!0),e.blendColor(0,0,0,0),e.enable(e.CULL_FACE),this.cullFace=e.BACK,e.cullFace(e.BACK),e.enable(e.DEPTH_TEST),e.depthFunc(e.LEQUAL),e.depthMask(!0),this.stencil=!1,e.disable(e.STENCIL_TEST),this.stencilFuncFront=this.stencilFuncBack=cr,this.stencilRefFront=this.stencilRefBack=0,this.stencilMaskFront=this.stencilMaskBack=255,e.stencilFunc(e.ALWAYS,0,255),this.stencilFailFront=this.stencilFailBack=go,this.stencilZfailFront=this.stencilZfailBack=go,this.stencilZpassFront=this.stencilZpassBack=go,this.stencilWriteMaskFront=255,this.stencilWriteMaskBack=255,e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.stencilMask(255),this.alphaToCoverage=!1,this.raster=!0,e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.disable(e.RASTERIZER_DISCARD),this.depthBiasEnabled=!1,e.disable(e.POLYGON_OFFSET_FILL),this.clearDepth=1,e.clearDepth(1),this.clearColor=new Q(0,0,0,0),e.clearColor(0,0,0,0),this.clearStencil=0,e.clearStencil(0),e.hint(e.FRAGMENT_SHADER_DERIVATIVE_HINT,e.NICEST),e.enable(e.SCISSOR_TEST),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.NONE),this.unpackFlipY=!1,e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!1),this.unpackPremultiplyAlpha=!1,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),this.unpackAlignment=1,e.pixelStorei(e.UNPACK_ALIGNMENT,1)}initTextureUnits(e=16){this.textureUnits=[];for(let t=0;t<e;t++)this.textureUnits.push([null,null,null])}initializeContextCaches(){super.initializeContextCaches(),this._vaoMap=new Map,this.boundVao=null,this.activeFramebuffer=null,this.feedback=null,this.transformFeedbackBuffer=null,this.textureUnit=0,this.initTextureUnits(this.maxCombinedTextures)}loseContext(){super.loseContext();for(const e of this.shaders)e.loseContext();this.fire("devicelost")}restoreContext(){this.initializeExtensions(),this.initializeCapabilities(),super.restoreContext();for(const e of this.shaders)e.restoreContext();this.fire("devicerestored")}setViewport(e,t,s,i){(this.vx!==e||this.vy!==t||this.vw!==s||this.vh!==i)&&(this.gl.viewport(e,t,s,i),this.vx=e,this.vy=t,this.vw=s,this.vh=i)}setScissor(e,t,s,i){(this.sx!==e||this.sy!==t||this.sw!==s||this.sh!==i)&&(this.gl.scissor(e,t,s,i),this.sx=e,this.sy=t,this.sw=s,this.sh=i)}setFramebuffer(e){if(this.activeFramebuffer!==e){const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,e),this.activeFramebuffer=e}}resolveMsaaColorToXrFramebufferViaQuads(e,t,s,i){this._xrMsaaCopy??(this._xrMsaaCopy=new CP(this)),this._xrMsaaCopy.copy(e,t,s,i)}copyRenderTarget(e,t,s,i){const r=this.gl;
425if(e===this.backBuffer&&(e=null),s){if(t){if(e&&(!e._colorBuffer||!t._colorBuffer||e._colorBuffer._format!==t._colorBuffer._format))return!1}else if(!e._colorBuffer)return!1}if(i&&e&&!e._depth&&(!e._depthBuffer||!t._depthBuffer||e._depthBuffer._format!==t._depthBuffer._format))return!1;const a=this.renderTarget;this.renderTarget=t,this.updateBegin();const n=e?e.impl._glFrameBuffer:this.backBuffer?.impl._glFrameBuffer,o=t?t.impl._glFrameBuffer:this.backBuffer?.impl._glFrameBuffer;r.bindFramebuffer(r.READ_FRAMEBUFFER,n),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,o);const c=e?e.width:t?t.width:this.width,h=e?e.height:t?t.height:this.height;return r.blitFramebuffer(0,0,c,h,0,0,c,h,(s?r.COLOR_BUFFER_BIT:0)|(i?r.DEPTH_BUFFER_BIT:0),r.NEAREST),this.renderTarget=a,r.bindFramebuffer(r.FRAMEBUFFER,a?a.impl._glFrameBuffer:null),!0}frameStart(){super.frameStart(),this.updateBackbuffer(),this.gpuProfiler.frameStart()}frameEnd(){super.frameEnd(),this.gpuProfiler.frameEnd(),this.gpuProfiler.request()}startRenderPass(e){const t=e.renderTarget??this.backBuffer;this.renderTarget=t,this.updateBegin();const{width:s,height:i}=t;this.setViewport(0,0,s,i),this.setScissor(0,0,s,i);const r=e.colorOps,a=e.depthStencilOps;if(r?.clear||a.clearDepth||a.clearStencil){let n=0;const o={};r?.clear&&(n|=Jl,o.color=[r.clearValue.r,r.clearValue.g,r.clearValue.b,r.clearValue.a]),a.clearDepth&&(n|=ec,o.depth=a.clearDepthValue),a.clearStencil&&(n|=Gd,o.stencil=a.clearStencilValue),o.flags=n,this.clear(o)}this.insideRenderPass=!0}endRenderPass(e){this.unbindVertexArray();const t=this.renderTarget,s=e.colorArrayOps.length;if(t){In.length=0;const i=this.gl;for(let r=0;r<s;r++){const a=e.colorArrayOps[r];a.store||a.resolve||In.push(i.COLOR_ATTACHMENT0+r)}t!==this.backBuffer&&(e.depthStencilOps.storeDepth||In.push(i.DEPTH_ATTACHMENT),e.depthStencilOps.storeStencil||In.push(i.STENCIL_ATTACHMENT)),In.length>0&&e.fullSizeClearRect&&i.invalidateFramebuffer(i.DRAW_FRAMEBUFFER,In),s&&e.colorOps?.resolve&&e.samples>1&&t.autoResolve&&t.resolve(!0,!1),t.depthBuffer&&e.depthStencilOps.resolveDepth&&e.samples>1&&t.autoResolve&&t.resolve(!1,!0);for(let r=0;r<s;r++)if(e.colorArrayOps[r].genMipmaps){const n=t._colorBuffers[r];n&&n.impl._glTexture&&n.mipmaps&&(this.activeTexture(this.maxCombinedTextures-1),this.bindTexture(n),this.gl.generateMipmap(n.impl._glTarget))}}this.insideRenderPass=!1}set defaultFramebuffer(e){this._defaultFramebuffer!==e&&(this._defaultFramebuffer=e,this._defaultFramebufferChanged=!0)}get defaultFramebuffer(){return this._defaultFramebuffer}updateBegin(){if(this.boundVao=null,this._tempEnableSafariTextureUnitWorkaround)for(let s=0;s<this.textureUnits.length;++s)for(let i=0;i<3;++i)this.textureUnits[s][i]=null;const e=this.renderTarget??this.backBuffer,t=e.impl;t.initialized||this.initRenderTarget(e),this.setFramebuffer(t._glFrameBuffer)}updateEnd(){this.unbindVertexArray();const e=this.renderTarget;if(e&&e!==this.backBuffer){e._samples>1&&e.autoResolve&&e.resolve();const t=e._colorBuffer;t&&t.impl._glTexture&&t.mipmaps&&(this.activeTexture(this.maxCombinedTextures-1),this.bindTexture(t),this.gl.generateMipmap(t.impl._glTarget))}}setUnpackFlipY(e){if(this.unpackFlipY!==e){this.unpackFlipY=e;const t=this.gl;t.pixelStorei(t.UNPACK_FLIP_Y_WEBGL,e)}}setUnpackPremultiplyAlpha(e){if(this.unpackPremultiplyAlpha!==e){this.unpackPremultiplyAlpha=e;const t=this.gl;t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e)}}setUnpackAlignment(e){this.unpackAlignment!==e&&(this.unpackAlignment=e,this.gl.pixelStorei(this.gl.UNPACK_ALIGNMENT,e))}activeTexture(e){this.textureUnit!==e&&(this.gl.activeTexture(this.gl.TEXTURE0+e),this.textureUnit=e)}bindTexture(e){const t=e.impl,s=t._glTarget,i=t._glTexture,r=this.textureUnit,a=this.targetToSlot[s];this.textureUnits[r][a]!==i&&(this.gl.bindTexture(s,i),this.textureUnits[r][a]=i)}bindTextureOnUnit(e,t){const s=e.impl,i=s._glTarget,r=s._glTexture,a=this.targetToSlot[i];this.textureUnits[t][a]!==r&&(this.activeTexture(t),this.gl.bindTexture(i,r),this.textureUnits[t][a]=r)}setTextureParameters(e){const t=this.gl,s=e.impl.dirtyParameterFlags,i=e.impl._glTarget;if(s&Hm){let r=e._minFilter;(!e._mipmaps||e._compressed&&e._levels.length===1)&&(r===Ac||r===Pc?r=Fe:(r===Ic||r===ia)&&(r=It)),t.texParameteri(i,t.TEXTURE_MIN_FILTER,this.glFilter[r])}if(s&Hx&&t.texParameteri(i,t.TEXTURE_MAG_FILTER,this.glFilter[e._magFilter]),s&Wx&&t.texParameteri(i,t.TEXTURE_WRAP_S,this.glAddress[e._addressU]),s&Xx&&t.texParameteri(i,t.TEXTURE_WRAP_T,this.glAddress[e._addressV]),s&Yx&&t.texParameteri(i,t.TEXTURE_WRAP_R,this.glAddress[e._addressW]),s&jx&&t.texParameteri(i,t.TEXTURE_COMPARE_MODE,e._compareOnRead?t.COMPARE_REF_TO_TEXTURE:t.NONE),s&qx&&t.texParameteri(i,t.TEXTURE_COMPARE_FUNC,this.glComparison[e._compareFunc]),s&$x){const r=this.extTextureFilterAnisotropic;r&&t.texParameterf(i,r.TEXTURE_MAX_ANISOTROPY_EXT,H.clamp(Math.round(e._anisotropy),1,this.maxAnisotropy))}}setTexture(e,t){const s=e.impl;s._glTexture||s.initialize(this,e),s.dirtyParameterFlags>0||e._needsUpload||e._needsMipmapsUpload?(this.activeTexture(t),this.bindTexture(e),s.dirtyParameterFlags&&(this.setTextureParameters(e),s.dirtyParameterFlags=0),(e._needsUpload||e._needsMipmapsUpload)&&(s.upload(this,e),e._needsUpload=!1,e._needsMipmapsUpload=!1)):this.bindTextureOnUnit(e,t)}createVertexArray(e){let t,s;const i=e.length>1;if(i){t="";for(let r=0;r<e.length;r++){const a=e[r];t+=a.id+a.format.renderingHash}s=this._vaoMap.get(t)}if(!s){const r=this.gl;s=r.createVertexArray(),r.bindVertexArray(s),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,null);for(let a=0;a<e.length;a++){const n=e[a];r.bindBuffer(r.ARRAY_BUFFER,n.impl.bufferId);const o=n.format.elements;for(let c=0;c<o.length;c++){const h=o[c],d=Be[h.name];h.asInt?r.vertexAttribIPointer(d,h.numComponents,this.glType[h.dataType],h.stride,h.offset):r.vertexAttribPointer(d,h.numComponents,this.glType[h.dataType],h.normalize,h.stride,h.offset),r.enableVertexAttribArray(d),n.format.instancing&&r.vertexAttribDivisor(d,1)}}r.bindVertexArray(null),r.bindBuffer(r.ARRAY_BUFFER,null),i&&this._vaoMap.set(t,s)}return s}unbindVertexArray(){this.boundVao&&(this.boundVao=null,this.gl.bindVertexArray(null))}setBuffers(e){const t=this.gl;let s;if(this.vertexBuffers.length===1){const r=this.vertexBuffers[0];r.impl.vao||(r.impl.vao=this.createVertexArray(this.vertexBuffers)),s=r.impl.vao}else s=this.createVertexArray(this.vertexBuffers);this.boundVao!==s&&(this.boundVao=s,t.bindVertexArray(s));const i=e?e.impl.bufferId:null;t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,i)}_multiDrawLoopFallback(e,t,s,i,r){const a=this.gl;if(t.indexed){const n=s.impl.glFormat,{glCounts:o,glOffsetsBytes:c,glInstanceCounts:h,count:d}=r.impl;if(i>0)for(let u=0;u<d;u++)a.drawElementsInstanced(e,o[u],n,c[u],h[u]);else for(let u=0;u<d;u++)a.drawElements(e,o[u],n,c[u])}
425else{const{glCounts:n,glOffsetsBytes:o,glInstanceCounts:c,count:h}=r.impl;if(i>0)for(let d=0;d<h;d++)a.drawArraysInstanced(e,o[d],n[d],c[d]);else for(let d=0;d<h;d++)a.drawArrays(e,o[d],n[d])}}draw(e,t,s,i,r=!0,a=!0){const n=this.shader;if(n&&(this.activateShader(),this.shaderValid)){const o=this.gl;r&&this.setBuffers(t);let c=0;const h=n.impl.samplers;for(let p=0,m=h.length;p<m;p++){const _=h[p];let g=_.scopeId.value;if(!g){const v=_.scopeId.name;v==="uSceneDepthMap"&&(g=Za(this,"white")),v==="uSceneColorMap"&&(g=Za(this,"pink")),g||(g=Za(this,"pink"))}if(g instanceof ce){const v=g;this.setTexture(v,c),_.slot!==c&&(o.uniform1i(_.locationId,c),_.slot=c),c++}else{_.array.length=0;const v=g.length;for(let x=0;x<v;x++){const y=g[x];this.setTexture(y,c),_.array[x]=c,c++}o.uniform1iv(_.locationId,_.array)}}const d=n.impl.uniforms;for(let p=0,m=d.length;p<m;p++){const _=d[p],g=_.scopeId,v=_.version,x=g.versionObject.version;if(v.globalId!==x.globalId||v.revision!==x.revision){v.globalId=x.globalId,v.revision=x.revision;const y=g.value;y!=null&&this.commitFunction[_.dataType](_,y)}}this.transformFeedbackBuffer&&(o.bindBufferBase(o.TRANSFORM_FEEDBACK_BUFFER,0,this.transformFeedbackBuffer.impl.bufferId),o.beginTransformFeedback(o.POINTS));const u=this.glPrimitive[e.type],f=e.count;if(i)if(this.extMultiDraw){const p=i.impl;if(e.indexed){const m=t.impl.glFormat;s>0?this.extMultiDraw.multiDrawElementsInstancedWEBGL(u,p.glCounts,0,m,p.glOffsetsBytes,0,p.glInstanceCounts,0,i.count):this.extMultiDraw.multiDrawElementsWEBGL(u,p.glCounts,0,m,p.glOffsetsBytes,0,i.count)}
425else s>0?this.extMultiDraw.multiDrawArraysInstancedWEBGL(u,p.glOffsetsBytes,0,p.glCounts,0,p.glInstanceCounts,0,i.count):this.extMultiDraw.multiDrawArraysWEBGL(u,p.glOffsetsBytes,0,p.glCounts,0,i.count)}else this._multiDrawLoopFallback(u,e,t,s,i);else if(e.indexed){const p=t.impl.glFormat,m=e.base*t.bytesPerIndex;s>0?o.drawElementsInstanced(u,f,p,m,s):o.drawElements(u,f,p,m)}else{const p=e.base;s>0?o.drawArraysInstanced(u,p,f,s):o.drawArrays(u,p,f)}this.transformFeedbackBuffer&&(o.endTransformFeedback(),o.bindBufferBase(o.TRANSFORM_FEEDBACK_BUFFER,0,null)),this._drawCallsPerFrame++}a&&this.clearVertexBuffer()}clear(e){const t=this.defaultClearOptions;e=e||t;const s=e.flags??t.flags;if(s!==0){const i=this.gl;if(s&Jl){const r=e.color??t.color,a=r[0],n=r[1],o=r[2],c=r[3],h=this.clearColor;(a!==h.r||n!==h.g||o!==h.b||c!==h.a)&&(this.gl.clearColor(a,n,o,c),this.clearColor.set(a,n,o,c)),this.setBlendState(xt.NOBLEND)}if(s&ec){const r=e.depth??t.depth;r!==this.clearDepth&&(this.gl.clearDepth(r),this.clearDepth=r),this.setDepthState(ds.WRITEDEPTH)}if(s&Gd){const r=e.stencil??t.stencil;r!==this.clearStencil&&(this.gl.clearStencil(r),this.clearStencil=r),i.stencilMask(255),this.stencilWriteMaskFront=255,this.stencilWriteMaskBack=255}i.clear(this.glClearFlag[s])}}submit(){this.gl.flush()}readPixels(e,t,s,i,r){const a=this.gl;a.readPixels(e,t,s,i,a.RGBA,a.UNSIGNED_BYTE,r)}clientWaitAsync(e,t){const s=this.gl,i=s.fenceSync(s.SYNC_GPU_COMMANDS_COMPLETE,0);return this.submit(),new Promise((r,a)=>{function n(){const o=s.clientWaitSync(i,e,0);o===s.TIMEOUT_EXPIRED?setTimeout(n,t):(s.deleteSync(i),o===s.WAIT_FAILED?a(new Error("webgl clientWaitSync sync failed")):r())}n()})}async readPixelsAsync(e,t,s,i,r,a=!1){const n=this.gl;let o,c;if(a)o=n.RGBA,c=n.UNSIGNED_BYTE;else{const d=this.renderTarget.colorBuffer?.impl;o=d?._glFormat??n.RGBA,c=d?._glPixelType??n.UNSIGNED_BYTE}const h=n.createBuffer();return n.bindBuffer(n.PIXEL_PACK_BUFFER,h),n.bufferData(n.PIXEL_PACK_BUFFER,r.byteLength,n.STREAM_READ),n.readPixels(e,t,s,i,o,c,0),n.bindBuffer(n.PIXEL_PACK_BUFFER,null),await this.clientWaitAsync(0,16),n.bindBuffer(n.PIXEL_PACK_BUFFER,h),n.getBufferSubData(n.PIXEL_PACK_BUFFER,0,r),n.bindBuffer(n.PIXEL_PACK_BUFFER,null),n.deleteBuffer(h),r}readTextureAsync(e,t,s,i,r,a){const n=a.face??0,o=a.mipLevel??0,c=a.renderTarget??new St({colorBuffer:e,depth:!1,face:n,mipLevel:o}),h=AP(e._format),d=h>0,u=ng(e._format),f=a.data??new u(Xt.calcLevelGpuSize(i,r,1,e._format)/u.BYTES_PER_ELEMENT),p=d?new Uint8Array(i*r*4):f;return this.setRenderTarget(c),this.initRenderTarget(c),this.setFramebuffer(c.impl._glFrameBuffer),a.immediate&&this.gl.flush(),new Promise((m,_)=>{this.readPixelsAsync(t,s,i,r,p,d).then(v=>{if(!this._destroyed)if(a.renderTarget||c.destroy(),d){const x=i*r;for(let y=0;y<x;y++)for(let S=0;S<h;S++)f[y*h+S]=v[y*4+S];m(f)}else m(v)}).catch(_)})}async writeTextureAsync(e,t,s,i,r,a){const n=this.gl,o=e.impl,c=o?._glFormat??n.RGBA,h=o?._glPixelType??n.UNSIGNED_BYTE,d=n.createBuffer();n.bindBuffer(n.PIXEL_UNPACK_BUFFER,d),n.bufferData(n.PIXEL_UNPACK_BUFFER,a,n.STREAM_DRAW),n.bindTexture(n.TEXTURE_2D,o._glTexture),n.texSubImage2D(n.TEXTURE_2D,0,t,s,i,r,c,h,0),n.bindBuffer(n.PIXEL_UNPACK_BUFFER,null),e._needsUpload=!1,e._mipmapsUploaded=!1,await this.clientWaitAsync(0,16)}setAlphaToCoverage(e){this.alphaToCoverage!==e&&(this.alphaToCoverage=e,e?this.gl.enable(this.gl.SAMPLE_ALPHA_TO_COVERAGE):this.gl.disable(this.gl.SAMPLE_ALPHA_TO_COVERAGE))}setTransformFeedbackBuffer(e){if(this.transformFeedbackBuffer!==e){this.transformFeedbackBuffer=e;const t=this.gl;e?(this.feedback||(this.feedback=t.createTransformFeedback()),t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,this.feedback)):t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,null)}}setRaster(e){this.raster!==e&&(this.raster=e,e?this.gl.disable(this.gl.RASTERIZER_DISCARD):this.gl.enable(this.gl.RASTERIZER_DISCARD))}setStencilTest(e){if(this.stencil!==e){const t=this.gl;e?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.stencil=e}}setStencilFunc(e,t,s){(this.stencilFuncFront!==e||this.stencilRefFront!==t||this.stencilMaskFront!==s||this.stencilFuncBack!==e||this.stencilRefBack!==t||this.stencilMaskBack!==s)&&(this.gl.stencilFunc(this.glComparison[e],t,s),this.stencilFuncFront=this.stencilFuncBack=e,this.stencilRefFront=this.stencilRefBack=t,this.stencilMaskFront=this.stencilMaskBack=s)}
425setStencilFuncFront(e,t,s){if(this.stencilFuncFront!==e||this.stencilRefFront!==t||this.stencilMaskFront!==s){const i=this.gl;i.stencilFuncSeparate(i.FRONT,this.glComparison[e],t,s),this.stencilFuncFront=e,this.stencilRefFront=t,this.stencilMaskFront=s}}setStencilFuncBack(e,t,s){if(this.stencilFuncBack!==e||this.stencilRefBack!==t||this.stencilMaskBack!==s){const i=this.gl;i.stencilFuncSeparate(i.BACK,this.glComparison[e],t,s),this.stencilFuncBack=e,this.stencilRefBack=t,this.stencilMaskBack=s}}setStencilOperation(e,t,s,i){(this.stencilFailFront!==e||this.stencilZfailFront!==t||this.stencilZpassFront!==s||this.stencilFailBack!==e||this.stencilZfailBack!==t||this.stencilZpassBack!==s)&&(this.gl.stencilOp(this.glStencilOp[e],this.glStencilOp[t],this.glStencilOp[s]),this.stencilFailFront=this.stencilFailBack=e,this.stencilZfailFront=this.stencilZfailBack=t,this.stencilZpassFront=this.stencilZpassBack=s),(this.stencilWriteMaskFront!==i||this.stencilWriteMaskBack!==i)&&(this.gl.stencilMask(i),this.stencilWriteMaskFront=i,this.stencilWriteMaskBack=i)}setStencilOperationFront(e,t,s,i){(this.stencilFailFront!==e||this.stencilZfailFront!==t||this.stencilZpassFront!==s)&&(this.gl.stencilOpSeparate(this.gl.FRONT,this.glStencilOp[e],this.glStencilOp[t],this.glStencilOp[s]),this.stencilFailFront=e,this.stencilZfailFront=t,this.stencilZpassFront=s),this.stencilWriteMaskFront!==i&&(this.gl.stencilMaskSeparate(this.gl.FRONT,i),this.stencilWriteMaskFront=i)}setStencilOperationBack(e,t,s,i){(this.stencilFailBack!==e||this.stencilZfailBack!==t||this.stencilZpassBack!==s)&&(this.gl.stencilOpSeparate(this.gl.BACK,this.glStencilOp[e],this.glStencilOp[t],this.glStencilOp[s]),this.stencilFailBack=e,this.stencilZfailBack=t,this.stencilZpassBack=s),this.stencilWriteMaskBack!==i&&(this.gl.stencilMaskSeparate(this.gl.BACK,i),this.stencilWriteMaskBack=i)}setBlendState(e){const t=this.blendState;if(!t.equals(e)){const s=this.gl,{blend:i,colorOp:r,alphaOp:a,colorSrcFactor:n,colorDstFactor:o,alphaSrcFactor:c,alphaDstFactor:h}=e;if(t.blend!==i&&(i?s.enable(s.BLEND):s.disable(s.BLEND)),t.colorOp!==r||t.alphaOp!==a){const d=this.glBlendEquation;s.blendEquationSeparate(d[r],d[a])}(t.colorSrcFactor!==n||t.colorDstFactor!==o||t.alphaSrcFactor!==c||t.alphaDstFactor!==h)&&s.blendFuncSeparate(this.glBlendFunctionColor[n],this.glBlendFunctionColor[o],this.glBlendFunctionAlpha[c],this.glBlendFunctionAlpha[h]),t.allWrite!==e.allWrite&&this.gl.colorMask(e.redWrite,e.greenWrite,e.blueWrite,e.alphaWrite),t.copy(e)}}setBlendColor(e,t,s,i){const r=this.blendColor;(e!==r.r||t!==r.g||s!==r.b||i!==r.a)&&(this.gl.blendColor(e,t,s,i),r.set(e,t,s,i))}setStencilState(e,t){e||t?(this.setStencilTest(!0),e===t?(this.setStencilFunc(e.func,e.ref,e.readMask),this.setStencilOperation(e.fail,e.zfail,e.zpass,e.writeMask)):(e??(e=$s.DEFAULT),this.setStencilFuncFront(e.func,e.ref,e.readMask),this.setStencilOperationFront(e.fail,e.zfail,e.zpass,e.writeMask),t??(t=$s.DEFAULT),this.setStencilFuncBack(t.func,t.ref,t.readMask),this.setStencilOperationBack(t.fail,t.zfail,t.zpass,t.writeMask))):this.setStencilTest(!1)}setDepthState(e){const t=this.depthState;if(!t.equals(e)){const s=this.gl,i=e.write;t.write!==i&&s.depthMask(i);let{func:r,test:a}=e;!a&&i&&(a=!0,r=cr),t.func!==r&&s.depthFunc(this.glComparison[r]),t.test!==a&&(a?s.enable(s.DEPTH_TEST):s.disable(s.DEPTH_TEST));const{depthBias:n,depthBiasSlope:o}=e;n||o?(this.depthBiasEnabled||(this.depthBiasEnabled=!0,this.gl.enable(this.gl.POLYGON_OFFSET_FILL)),s.polygonOffset(o,n)):this.depthBiasEnabled&&(this.depthBiasEnabled=!1,this.gl.disable(this.gl.POLYGON_OFFSET_FILL)),t.copy(e)}}setCullMode(e){if(this.cullMode!==e){if(e===Yt)this.gl.disable(this.gl.CULL_FACE);else{this.cullMode===Yt&&this.gl.enable(this.gl.CULL_FACE);const t=this.glCull[e];this.cullFace!==t&&(this.gl.cullFace(t),this.cullFace=t)}this.cullMode=e}}setFrontFace(e){if(this.frontFace!==e){const t=this.glFrontFace[e];this.gl.frontFace(t),this.frontFace=e}}setShader(e,t=!1){e!==this.shader&&(this.shader=e,this.shaderAsyncCompile=t,this.shaderValid=void 0)}activateShader(){const{shader:e}=this,{impl:t}=e;this.shaderValid===void 0&&(e.failed?this.shaderValid=!1:e.ready||(this.shaderAsyncCompile?t.isLinked(this)?t.finalize(this,e)||(e.failed=!0,this.shaderValid=!1):this.shaderValid=!1:t.finalize(this,e)||(e.failed=!0,this.shaderValid=!1))),this.shaderValid===void 0&&(this.gl.useProgram(t.glProgram),this.shaderValid=!0)}clearVertexArrayObjectCache(){const e=this.gl;
425this._vaoMap.forEach((t,s,i)=>{e.deleteVertexArray(t)}),this._vaoMap.clear()}set fullscreen(e){e?this.gl.canvas.requestFullscreen():document.exitFullscreen()}get fullscreen(){return!!document.fullscreenElement}}class PP{unlock(e){}}class IP{destroy(e){}init(e,t){}loseContext(){}resolve(e,t,s,i){}}class DP{destroy(e){}loseContext(){}restoreContext(e,t){}}class MP{destroy(e){}propertyChanged(e){}loseContext(){}}class RP{destroy(e){}unlock(e){}}class LP{add(e,t,s,i){}}class FP extends Je{constructor(e,t={}){super(e,t),t=this.initOptions,this.isNull=!0,this._deviceType=Td,this.samples=1,this.backBuffer=new St({name:"Framebuffer",graphicsDevice:this,depth:this.initOptions.depth,stencil:this.supportsStencil,samples:this.samples}),this.initDeviceCaps()}destroy(){super.destroy()}initDeviceCaps(){this.disableParticleSystem=!0,this.precision="highp",this.maxPrecision="highp",this.maxSamples=4,this.maxTextures=16,this.maxTextureSize=4096,this.maxCubeMapSize=4096,this.maxVolumeSize=4096,this.maxColorAttachments=8,this.maxPixelRatio=1,this.maxAnisotropy=16,this.supportsUniformBuffers=!1,this.supportsAreaLights=!0,this.supportsGpuParticles=!1,this.textureFloatRenderable=!0,this.textureHalfFloatRenderable=!0,this.supportsImageBitmap=!1}postInit(){super.postInit()}frameStart(){super.frameStart()}frameEnd(){super.frameEnd()}updateBegin(){}updateEnd(){}readPixels(e,t,s,i,r){}createVertexBufferImpl(e,t){return new RP(e,t)}createIndexBufferImpl(e){return new PP(e)}createShaderImpl(e){return new DP(e)}createTextureImpl(e){return new MP(e)}createRenderTargetImpl(e){return new IP(e)}createDrawCommandImpl(e){return new LP}createUploadStreamImpl(e){return null}draw(e,t,s,i,r=!0,a=!0){}setShader(e,t=!1){}setBlendState(e){}setDepthState(e){}setStencilState(e,t){}setBlendColor(e,t,s,i){}setCullMode(e){}setFrontFace(e){}setAlphaToCoverage(e){}initializeContextCaches(){super.initializeContextCaches()}clear(e){}setViewport(e,t,s,i){}setScissor(e,t,s,i){}copyRenderTarget(e,t,s,i){return!0}}function OP(l,e={}){const t=e.deviceTypes??[];t.includes(xd)||t.push(xd),t.includes(Td)||t.push(Td);const s=[];for(let i=0;i<t.length;i++){const r=t[i];if((r===Gx||r===Tv)&&window?.navigator?.gpu){const a=r===Tv?"bare":void 0;s.push(()=>new nP(l,{...e,featureLevel:a}).initWebGpu(e.glslangUrl,e.twgslUrl))}r===xd&&s.push(()=>new hT(l,e)),r===Td&&s.push(()=>new FP(l,e))}return new Promise((i,r)=>{let a=0;const n=()=>{a>=s.length?r(new Error("Failed to create a graphics device")):Promise.resolve(s[a++]()).then(o=>{o?i(o):n()}).catch(o=>{console.log(o),n()})};n()})}class BP{value;scopeId=null}class Qe{shader=null;name;parameters=new Map;countX=1;countY;countZ;indirectSlotIndex=-1;indirectBuffer=null;indirectFrameStamp=0;constructor(e,t,s="Unnamed"){this.device=e,this.shader=t,this.name=s,e.supportsCompute&&(this.impl=e.createComputeImpl(this))}setParameter(e,t){let s=this.parameters.get(e);s||(s=new BP,s.scopeId=this.device.scope.resolve(e),this.parameters.set(e,s)),s.value=t}getParameter(e){return this.parameters.get(e)?.value}deleteParameter(e){this.parameters.delete(e)}destroy(){this.impl?.destroy(),this.impl=null}applyParameters(){for(const[,e]of this.parameters)e.scopeId.setValue(e.value)}setupDispatch(e,t,s){this.countX=e,this.countY=t,this.countZ=s,this.indirectSlotIndex=-1,this.indirectBuffer=null}setupIndirectDispatch(e,t=null){this.indirectSlotIndex=e,this.indirectBuffer=t,this.indirectFrameStamp=this.device.renderVersion}static calcDispatchSize(e,t,s=65535){if(e<=s)return t.set(e,1);const i=Math.ceil(e/s);return t.set(Math.ceil(e/i),i)}}class rS{device;indexSizeBytes;_maxCount=0;get maxCount(){return this._maxCount}impl=null;_count=1;get count(){return this._count}slotIndex=0;primitiveCount=0;constructor(e,t=0){this.device=e,this.indexSizeBytes=t,this.impl=e.createDrawCommandImpl(this)}destroy(){this.impl?.destroy?.(),this.impl=null}allocate(e){this._maxCount=e,this.impl.allocate?.(e)}add(e,t,s,i,r=0,a=0){this.impl.add(e,t,s,i,r,a)}update(e){this._count=e,this.primitiveCount=this.impl.update?.(e)??0}}class gn{_name;device;_enabled=!0;_skipStart=!1;_skipEnd=!1;executeEnabled=!0;requiresCubemaps=!1;beforePasses=[];
425afterPasses=[];constructor(e){this.device=e}set name(e){this._name=e}get name(){return this._name||(this._name=this.constructor.name),this._name}set enabled(e){this._enabled!==e&&(this._enabled=e,e?this.onEnable():this.onDisable())}get enabled(){return this._enabled}onEnable(){}onDisable(){}frameUpdate(){}before(){}execute(){}after(){}destroy(){}render(){this.enabled&&(this.before(),this.executeEnabled&&this.execute(),this.after(),this.device.renderPassIndex++)}}class NP{clearValue=new Q(0,0,0,1);clearValueLinear=new Q(0,0,0,1);clear=!1;store=!1;resolve=!0;genMipmaps=!1}class kP{clearDepthValue=1;clearStencilValue=0;clearDepth=!1;clearStencil=!1;storeDepth=!1;resolveDepth=!1;storeStencil=!1}class Pr extends gn{renderTarget;_options;samples=0;colorArrayOps=[];get colorOps(){return this.colorArrayOps[0]}depthStencilOps;requiresCubemaps=!0;fullSizeClearRect=!0;set scaleX(e){this._options.scaleX=e}get scaleX(){return this._options.scaleX}set scaleY(e){this._options.scaleY=e}get scaleY(){return this._options.scaleY}set options(e){this._options=e,e&&(this.scaleX=this.scaleX??1,this.scaleY=this.scaleY??1)}get options(){return this._options}init(e=null,t){this.options=t,this.renderTarget=e,this.samples=Math.max(this.renderTarget?this.renderTarget.samples:this.device.samples,1),this.allocateAttachments(),this.postInit()}allocateAttachments(){const e=this.renderTarget;this.depthStencilOps=new kP,e?.depthBuffer&&(this.depthStencilOps.storeDepth=!0);const t=e?e._colorBuffers?.length??0:1;this.colorArrayOps.length=0;for(let s=0;s<t;s++){const i=new NP;this.colorArrayOps[s]=i,this.samples===1&&(i.store=!0,i.resolve=!1);const r=this.renderTarget?._colorBuffers?.[s];if(this.renderTarget?.mipmaps&&r?.mipmaps){const a=Qr(r._format);i.genMipmaps=!a}}}postInit(){}frameUpdate(){if(this._options&&this.renderTarget){const e=this._options.resizeSource??this.device.backBuffer,t=Math.floor(e.width*this.scaleX),s=Math.floor(e.height*this.scaleY);this.renderTarget.resize(t,s)}}setClearColor(e){const t=this.colorArrayOps.length;for(let s=0;s<t;s++){const i=this.colorArrayOps[s];e&&(i.clearValue.copy(e),i.clearValueLinear.linear(e)),i.clear=!!e}}setClearDepth(e){e!==void 0&&(this.depthStencilOps.clearDepthValue=e),this.depthStencilOps.clearDepth=e!==void 0}setClearStencil(e){e!==void 0&&(this.depthStencilOps.clearStencilValue=e),this.depthStencilOps.clearStencil=e!==void 0}render(){if(this.enabled){const e=this.device,t=this.renderTarget!==void 0;this.before(),this.executeEnabled&&(t&&!this._skipStart&&e.startRenderPass(this),this.execute(),t&&!this._skipEnd&&e.endRenderPass(this)),this.after(),e.renderPassIndex++}}}function UP(l){this.array[this.index]=l}function zP(l,e){this.array[this.index]=l,this.array[this.index+1]=e}function VP(l,e,t){this.array[this.index]=l,this.array[this.index+1]=e,this.array[this.index+2]=t}function GP(l,e,t,s){this.array[this.index]=l,this.array[this.index+1]=e,this.array[this.index+2]=t,this.array[this.index+3]=s}function HP(l,e,t){this.array[l]=e[t]}function WP(l,e,t){this.array[l]=e[t],this.array[l+1]=e[t+1]}function XP(l,e,t){this.array[l]=e[t],this.array[l+1]=e[t+1],this.array[l+2]=e[t+2]}function YP(l,e,t){this.array[l]=e[t],this.array[l+1]=e[t+1],this.array[l+2]=e[t+2],this.array[l+3]=e[t+3]}function jP(l,e,t){e[t]=this.array[l]}function qP(l,e,t){e[t]=this.array[l],e[t+1]=this.array[l+1]}function $P(l,e,t){e[t]=this.array[l],e[t+1]=this.array[l+1],e[t+2]=this.array[l+2]}function KP(l,e,t){e[t]=this.array[l],e[t+1]=this.array[l+1],e[t+2]=this.array[l+2],e[t+3]=this.array[l+3]}class ZP{constructor(e,t,s){switch(this.index=0,this.numComponents=t.numComponents,s.interleaved?this.array=new yo[t.dataType](e,t.offset):this.array=new yo[t.dataType](e,t.offset,s.vertexCount*t.numComponents),this.stride=t.stride/this.array.constructor.BYTES_PER_ELEMENT,t.numComponents){case 1:this.set=UP,this.getToArray=jP,this.setFromArray=HP;break;case 2:this.set=zP,this.getToArray=qP,this.setFromArray=WP;break;case 3:this.set=VP,this.getToArray=$P,this.setFromArray=XP;break;case 4:this.set=GP,this.getToArray=KP,this.setFromArray=YP;break}}get(e){return this.array[this.index+e]}
425set(e,t,s,i){}getToArray(e,t,s){}setFromArray(e,t,s){}}class jl{constructor(e){this.vertexBuffer=e,this.vertexFormatSize=e.getFormat().size,this.buffer=this.vertexBuffer.lock(),this.accessors=[],this.element={};const t=this.vertexBuffer.getFormat();for(let s=0;s<t.elements.length;s++){const i=t.elements[s];this.accessors[s]=new ZP(this.buffer,i,t),this.element[i.name]=this.accessors[s]}}next(e=1){let t=0;const s=this.accessors,i=this.accessors.length;for(;t<i;){const r=s[t++];r.index+=e*r.stride}}end(){this.vertexBuffer.unlock()}writeData(e,t,s){const i=this.element[e];if(i){s>this.vertexBuffer.numVertices&&(s=this.vertexBuffer.numVertices);const r=i.numComponents;if(this.vertexBuffer.getFormat().interleaved){let a=0;for(let n=0;n<s;n++)i.setFromArray(a,t,n*r),a+=i.stride}else if(t.length>s*r){const a=s*r;if(ArrayBuffer.isView(t))t=t.subarray(0,a),i.array.set(t);else for(let n=0;n<a;n++)i.array[n]=t[n]}else i.array.set(t)}}readData(e,t){const s=this.element[e];let i=0;if(s){i=this.vertexBuffer.numVertices;let r;const a=s.numComponents;if(this.vertexBuffer.getFormat().interleaved){Array.isArray(t)&&(t.length=0),s.index=0;let n=0;for(r=0;r<i;r++)s.getToArray(n,t,r*a),n+=s.stride}else if(ArrayBuffer.isView(t))t.set(s.array);else{t.length=0;const n=i*a;for(r=0;r<n;r++)t[r]=s.array[r]}}return i}}const QP=-1;class JP{key=null;element=null;event=null;constructor(e,t){t&&(this.key=t.keyCode,this.element=t.target,this.event=t)}}const vh=new JP;function cp(l){return vh.key=l.keyCode,vh.element=l.target,vh.event=l,vh}function Sh(l){return typeof l=="string"?l.toUpperCase().charCodeAt(0):l}const eI={9:"Tab",13:"Enter",16:"Shift",17:"Control",18:"Alt",27:"Escape",37:"Left",38:"Up",39:"Right",40:"Down",46:"Delete",91:"Win"};class tI extends ge{static EVENT_KEYDOWN="keydown";static EVENT_KEYUP="keyup";_element=null;_keymap={};_lastmap={};_keyDownHandler;_keyUpHandler;_keyPressHandler;_visibilityChangeHandler;_windowBlurHandler;preventDefault;stopPropagation;constructor(e,t={}){super(),this._keyDownHandler=this._handleKeyDown.bind(this),this._keyUpHandler=this._handleKeyUp.bind(this),this._keyPressHandler=this._handleKeyPress.bind(this),this._visibilityChangeHandler=this._handleVisibilityChange.bind(this),this._windowBlurHandler=this._handleWindowBlur.bind(this),e&&this.attach(e),this.preventDefault=t.preventDefault||!1,this.stopPropagation=t.stopPropagation||!1}attach(e){this._element&&this.detach(),this._element=e,this._element.addEventListener("keydown",this._keyDownHandler,!1),this._element.addEventListener("keypress",this._keyPressHandler,!1),this._element.addEventListener("keyup",this._keyUpHandler,!1),document.addEventListener("visibilitychange",this._visibilityChangeHandler,!1),window.addEventListener("blur",this._windowBlurHandler,!1)}detach(){this._element&&(this._element.removeEventListener("keydown",this._keyDownHandler),this._element.removeEventListener("keypress",this._keyPressHandler),this._element.removeEventListener("keyup",this._keyUpHandler),this._element=null,document.removeEventListener("visibilitychange",this._visibilityChangeHandler,!1),window.removeEventListener("blur",this._windowBlurHandler,!1))}toKeyIdentifier(e){e=Sh(e);const t=eI[e.toString()];if(t)return t;let s=e.toString(16).toUpperCase();const i=s.length;for(let r=0;r<4-i;r++)s=`0${s}`;return`U+${s}`}_handleKeyDown(e){const t=e.keyCode||e.charCode;if(t===void 0)return;const s=this.toKeyIdentifier(t);this._keymap[s]=!0,this.fire("keydown",cp(e)),this.preventDefault&&e.preventDefault(),this.stopPropagation&&e.stopPropagation()}_handleKeyUp(e){const t=e.keyCode||e.charCode;if(t===void 0)return;const s=this.toKeyIdentifier(t);delete this._keymap[s],this.fire("keyup",cp(e)),this.preventDefault&&e.preventDefault(),this.stopPropagation&&e.stopPropagation()}_handleKeyPress(e){this.fire("keypress",cp(e)),this.preventDefault&&e.preventDefault(),this.stopPropagation&&e.stopPropagation()}_handleVisibilityChange(){document.visibilityState==="hidden"&&this._handleWindowBlur()}_handleWindowBlur(){this._keymap={},this._lastmap={}}update(){for(const e in this._lastmap)delete this._lastmap[e];for(const e in this._keymap)this._keymap.hasOwnProperty(e)&&(this._lastmap[e]=this._keymap[e])}isPressed(e){const t=Sh(e),s=this.toKeyIdentifier(t);return!!this._keymap[s]}wasPressed(e){const t=Sh(e),s=this.toKeyIdentifier(t);return!!this._keymap[s]&&!this._lastmap[s]}wasReleased(e){const t=Sh(e),s=this.toKeyIdentifier(t);return!this._keymap[s]&&!!this._lastmap[s]}}function Ym(){return!!(document.pointerLockElement||document.mozPointerLockElement||document.webkitPointerLockElement)}class Ga{x=0;y=0;dx=0;dy=0;button=QP;buttons;wheelDelta=0;element;ctrlKey=!1;altKey=!1;shiftKey=!1;metaKey=!1;event;constructor(e,t){let s={x:0,y:0};if(t){if(t instanceof Ga)throw Error("Expected MouseEvent");s=e._getTargetCoords(t)}else t={};if(s)this.x=s.x,this.y=s.y;else if(Ym())this.x=0,this.y=0;else return;t.type==="wheel"&&(t.deltaY>0?this.wheelDelta=1:t.deltaY<0&&(this.wheelDelta=-1)),Ym()?(this.dx=t.movementX||t.webkitMovementX||t.mozMovementX||0,this.dy=t.movementY||t.webkitMovementY||t.mozMovementY||0):(this.dx=this.x-e._lastX,this.dy=this.y-e._lastY),(t.type==="mousedown"||t.type==="mouseup")&&(this.button=t.button),this.buttons=e._buttons.slice(0),this.element=t.target,this.ctrlKey=t.ctrlKey??!1,this.altKey=t.altKey??!1,this.shiftKey=t.shiftKey??!1,this.metaKey=t.metaKey??!1,this.event=t}}class sI extends ge{static EVENT_MOUSEMOVE="mousemove";static EVENT_MOUSEDOWN="mousedown";static EVENT_MOUSEUP="mouseup";static EVENT_MOUSEWHEEL="mousewheel";_lastX=0;_lastY=0;
425_buttons=[!1,!1,!1];_lastbuttons=[!1,!1,!1];_target=null;_attached=!1;_upHandler;_downHandler;_moveHandler;_wheelHandler;_contextMenuHandler;constructor(e){super(),this._upHandler=this._handleUp.bind(this),this._downHandler=this._handleDown.bind(this),this._moveHandler=this._handleMove.bind(this),this._wheelHandler=this._handleWheel.bind(this),this._contextMenuHandler=t=>{t.preventDefault()},this.attach(e)}static isPointerLocked(){return Ym()}attach(e){if(this._target=e,this._attached)return;this._attached=!0;const t={passive:!1},s=Ce.passiveEvents?t:!1;window.addEventListener("mouseup",this._upHandler,s),window.addEventListener("mousedown",this._downHandler,s),window.addEventListener("mousemove",this._moveHandler,s),window.addEventListener("wheel",this._wheelHandler,s)}detach(){if(!this._attached)return;this._attached=!1,this._target=null;const e={passive:!1},t=Ce.passiveEvents?e:!1;window.removeEventListener("mouseup",this._upHandler,t),window.removeEventListener("mousedown",this._downHandler,t),window.removeEventListener("mousemove",this._moveHandler,t),window.removeEventListener("wheel",this._wheelHandler,t)}disableContextMenu(){this._target&&this._target.addEventListener("contextmenu",this._contextMenuHandler)}enableContextMenu(){this._target&&this._target.removeEventListener("contextmenu",this._contextMenuHandler)}enablePointerLock(e,t){if(!document.body.requestPointerLock){t&&t();return}const s=()=>{e(),document.removeEventListener("pointerlockchange",s)},i=()=>{t(),document.removeEventListener("pointerlockerror",i)};e&&document.addEventListener("pointerlockchange",s,!1),t&&document.addEventListener("pointerlockerror",i,!1),document.body.requestPointerLock()}disablePointerLock(e){if(!document.exitPointerLock)return;const t=()=>{e(),document.removeEventListener("pointerlockchange",t)};e&&document.addEventListener("pointerlockchange",t,!1),document.exitPointerLock()}update(){this._lastbuttons[0]=this._buttons[0],this._lastbuttons[1]=this._buttons[1],this._lastbuttons[2]=this._buttons[2]}isPressed(e){return this._buttons[e]}wasPressed(e){return this._buttons[e]&&!this._lastbuttons[e]}wasReleased(e){return!this._buttons[e]&&this._lastbuttons[e]}_handleUp(e){this._buttons[e.button]=!1;const t=new Ga(this,e);t.event&&this.fire("mouseup",t)}_handleDown(e){this._buttons[e.button]=!0;const t=new Ga(this,e);t.event&&this.fire("mousedown",t)}_handleMove(e){const t=new Ga(this,e);t.event&&(this.fire("mousemove",t),this._lastX=t.x,this._lastY=t.y)}_handleWheel(e){const t=new Ga(this,e);t.event&&this.fire("mousewheel",t)}_getTargetCoords(e){const t=this._target.getBoundingClientRect(),s=Math.floor(t.left),i=Math.floor(t.top);return e.clientX<s||e.clientX>=s+this._target.clientWidth||e.clientY<i||e.clientY>=i+this._target.clientHeight?null:{x:e.clientX-s,y:e.clientY-i}}}function iI(l){let e=0,t=0,s=l.target;for(;!(s instanceof HTMLElement)&&s;)s=s.parentNode;for(;s;)e+=s.offsetLeft-s.scrollLeft,t+=s.offsetTop-s.scrollTop,s=s.offsetParent;return{x:l.pageX-e,y:l.pageY-t}}class aS{id;x;y;target;touch;constructor(e){const t=iI(e);this.id=e.identifier,this.x=t.x,this.y=t.y,this.target=e.target,this.touch=e}}class yh{element;event;touches=[];changedTouches=[];constructor(e,t){this.element=t.target,this.event=t,this.touches=Array.from(t.touches).map(s=>new aS(s)),this.changedTouches=Array.from(t.changedTouches).map(s=>new aS(s))}getTouchById(e,t){return t.find(s=>s.id===e)||null}}class rI extends ge{static EVENT_TOUCHSTART="touchstart";static EVENT_TOUCHEND="touchend";static EVENT_TOUCHMOVE="touchmove";static EVENT_TOUCHCANCEL="touchcancel";_element=null;_startHandler;_endHandler;_moveHandler;_cancelHandler;constructor(e){super(),this._startHandler=this._handleTouchStart.bind(this),this._endHandler=this._handleTouchEnd.bind(this),this._moveHandler=this._handleTouchMove.bind(this),this._cancelHandler=this._handleTouchCancel.bind(this),this.attach(e)}attach(e){this._element&&this.detach(),this._element=e,this._element.addEventListener("touchstart",this._startHandler,!1),this._element.addEventListener("touchend",this._endHandler,!1),this._element.addEventListener("touchmove",this._moveHandler,!1),this._element.addEventListener("touchcancel",this._cancelHandler,!1)}detach(){this._element&&(this._element.removeEventListener("touchstart",this._startHandler,!1),this._element.removeEventListener("touchend",this._endHandler,!1),this._element.removeEventListener("touchmove",this._moveHandler,!1),this._element.removeEventListener("touchcancel",this._cancelHandler,!1)),this._element=null}_handleTouchStart(e){this.fire("touchstart",new yh(this,e))}_handleTouchEnd(e){this.fire("touchend",new yh(this,e))}_handleTouchMove(e){e.preventDefault(),this.fire("touchmove",new yh(this,e))}_handleTouchCancel(e){this.fire("touchcancel",new yh(this,e))}}class De{static ContentType={AAC:"audio/aac",BASIS:"image/basis",BIN:"application/octet-stream",DDS:"image/dds",FORM_URLENCODED:"application/x-www-form-urlencoded",GIF:"image/gif",GLB:"model/gltf-binary",JPEG:"image/jpeg",JSON:"application/json",MP3:"audio/mpeg",MP4:"audio/mp4",OGG:"audio/ogg",OPUS:'audio/ogg; codecs="opus"',PNG:"image/png",TEXT:"text/plain",WAV:"audio/x-wav",XML:"application/xml"};static ResponseType={TEXT:"text",ARRAY_BUFFER:"arraybuffer",BLOB:"blob",DOCUMENT:"document",JSON:"json"};static binaryExtensions=[".model",".wav",".ogg",".mp3",".mp4",".m4a",".aac",".dds",".basis",".glb",".opus"];static retryDelay=100;get(e,t,s){typeof t=="function"&&(s=t,t={});const i=this.request("GET",e,t,s),{progress:r}=t;if(r){const a=o=>{o.lengthComputable&&r.fire("progress",o.loaded,o.total)},n=o=>{a(o),i.removeEventListener("loadstart",a),i.removeEventListener("progress",a),i.removeEventListener("loadend",n)};i.addEventListener("loadstart",a),i.addEventListener("progress",a),i.addEventListener("loadend",n)}return i}post(e,t,s,i){return typeof s=="function"&&(i=s,s={}),s.postdata=t,this.request("POST",e,s,i)}put(e,t,s,i){return typeof s=="function"&&(i=s,s={}),s.postdata=t,this.request("PUT",e,s,i)}del(e,t,s){return typeof t=="function"&&(s=t,t={}),this.request("DELETE",e,t,s)}request(e,t,s,i){let r,a,n,o=!1;if(typeof s=="function"&&(i=s,s={}),s.retry&&(s=Object.assign({retries:0,maxRetries:5},s)),s.callback=i,s.async==null&&(s.async=!0),s.headers==null&&(s.headers={}),s.postdata!=null)if(s.postdata instanceof Document)n=s.postdata;else if(s.postdata instanceof FormData)n=s.postdata;else if(s.postdata instanceof Object){let h=s.headers["Content-Type"];switch(h===void 0&&(s.headers["Content-Type"]=De.ContentType.FORM_URLENCODED,h=s.headers["Content-Type"]),h){case De.ContentType.FORM_URLENCODED:{n="";let d=!0;for(const u in s.postdata)if(s.postdata.hasOwnProperty(u)){d?d=!1:n+="&";const f=encodeURIComponent(u),p=encodeURIComponent(s.postdata[u]);n+=`${f}=${p}`}break}default:case De.ContentType.JSON:h==null&&(s.headers["Content-Type"]=De.ContentType.JSON),n=JSON.stringify(s.postdata);break}}else n=s.postdata;if(s.cache===!1){const h=Gt();r=new jf(t),r.query?r.query=`${r.query}&ts=${h}`:r.query=`ts=${h}`,t=r.toString()}s.query&&(r=new jf(t),a=Ud(r.getQuery(),s.query),r.setQuery(a),t=r.toString());const c=new XMLHttpRequest;c.open(e,t,s.async),c.withCredentials=s.withCredentials!==void 0?s.withCredentials:!1,c.responseType=s.responseType||this._guessResponseType(t);for(const h in s.headers)s.headers.hasOwnProperty(h)&&c.setRequestHeader(h,s.headers[h]);c.onreadystatechange=()=>{this._onReadyStateChange(e,t,s,c)},c.onerror=()=>{this._onError(e,t,s,c),o=!0};try{c.send(n)}catch(h){o||s.error(c.status,c,h)}return c}_guessResponseType(e){const t=new jf(e),s=ve.getExtension(t.path).toLowerCase();return De.binaryExtensions.indexOf(s)>=0?De.ResponseType.ARRAY_BUFFER:s===".json"?De.ResponseType.JSON:s===".xml"?De.ResponseType.DOCUMENT:De.ResponseType.TEXT}_isBinaryContentType(e){return[De.ContentType.BASIS,De.ContentType.BIN,De.ContentType.DDS,De.ContentType.GLB,De.ContentType.MP3,De.ContentType.MP4,De.ContentType.OGG,De.ContentType.OPUS,De.ContentType.WAV].indexOf(e)>=0}_isBinaryResponseType(e){return e===De.ResponseType.ARRAY_BUFFER||e===De.ResponseType.BLOB||e===De.ResponseType.JSON}_onReadyStateChange(e,t,s,i){if(i.readyState===4)switch(i.status){case 0:{i.responseURL&&i.responseURL.startsWith("file:///")?this._onSuccess(e,t,s,i):this._onError(e,t,s,i);break}case 200:case 201:case 206:case 304:{this._onSuccess(e,t,s,i);break}default:{this._onError(e,t,s,i);break}}}_onSuccess(e,t,s,i){let r,a;const n=i.getResponseHeader("Content-Type");
425n&&(a=n.split(";")[0].trim());try{this._isBinaryContentType(a)||this._isBinaryResponseType(i.responseType)?r=i.response:a===De.ContentType.JSON||t.split("?")[0].endsWith(".json")?r=JSON.parse(i.responseText):i.responseType===De.ResponseType.DOCUMENT||a===De.ContentType.XML?r=i.responseXML:r=i.responseText,s.callback(null,r)}catch(o){s.callback(o)}}_onError(e,t,s,i){if(!s.retrying)if(s.retry&&s.retries<s.maxRetries){s.retries++,s.retrying=!0;const r=H.clamp(Math.pow(2,s.retries)*De.retryDelay,0,s.maxRetryDelay||5e3);console.log(`${e}: ${t} - Error ${i.status}. Retrying in ${r} ms`),setTimeout(()=>{s.retrying=!1,this.request(e,t,s,s.callback)},r)}else s.callback(i.status===0?"Network error":i.status,null)}}const ht=new De,jm="linear";class aI{_manager;position=new E;orientation=new Z;constructor(e){this._manager=e}getPosition(){return this.position}setPosition(e){this.position.copy(e);const t=this.listener;t&&("positionX"in t?(t.positionX.value=e.x,t.positionY.value=e.y,t.positionZ.value=e.z):t.setPosition&&t.setPosition(e.x,e.y,e.z))}setOrientation(e){this.orientation.copy(e);const t=this.listener;if(t){const s=e.data;"forwardX"in t?(t.forwardX.value=-s[8],t.forwardY.value=-s[9],t.forwardZ.value=-s[10],t.upX.value=s[4],t.upY.value=s[5],t.upZ.value=s[6]):t.setOrientation&&t.setOrientation(-s[8],-s[9],-s[10],s[4],s[5],s[6])}}getOrientation(){return this.orientation}get listener(){const e=this._manager.context;return e?e.listener:null}}const xh="running",nS=["click","touchstart","mousedown"];class nI extends ge{_context=null;_unlockHandlerFunc;_userSuspended=!1;listener;_volume=1;constructor(){super(),this._unlockHandlerFunc=this._unlockHandler.bind(this),this.listener=new aI(this)}set volume(e){e=H.clamp(e,0,1),this._volume=e,this.fire("volumechange",e)}get volume(){return this._volume}get suspended(){return this._userSuspended}get context(){if(!this._context){const e=typeof AudioContext<"u"&&AudioContext||typeof webkitAudioContext<"u"&&webkitAudioContext;if(!e)return null;this._context=new e,this._context.state!==xh&&this._registerUnlockListeners()}return this._context}suspend(){this._userSuspended||(this._userSuspended=!0,this._context&&this._context.state===xh&&this._suspend())}resume(){this._userSuspended&&(this._userSuspended=!1,this._context&&this._context.state!==xh&&this._resume())}destroy(){this.fire("destroy");const e=this._context;e&&(this._removeUnlockListeners(),e.close(),this._context=null)}_resume(){const e=this._context;e&&e.resume().then(()=>{const t=e.createBufferSource();t.buffer=e.createBuffer(1,1,e.sampleRate),t.connect(e.destination),t.start(0),t.onended=s=>{t.disconnect(0),this.fire("resume")}},t=>{}).catch(t=>{})}_suspend(){const e=this._context;e&&e.suspend().then(()=>{this.fire("suspend")},t=>{}).catch(t=>{})}_unlockHandler(){this._removeUnlockListeners(),!this._userSuspended&&this._context&&this._context.state!==xh&&this._resume()}_registerUnlockListeners(){nS.forEach(e=>{window.addEventListener(e,this._unlockHandlerFunc,!1)})}_removeUnlockListeners(){nS.forEach(e=>{window.removeEventListener(e,this._unlockHandlerFunc,!1)})}}class oI{buffer;constructor(e){this.buffer=e}get duration(){return this.buffer&&this.buffer.duration||0}}const ni=0,Th=1,Ca=2;function kr(l,e){return l%e||0}class dT extends ge{static EVENT_PLAY="play";static EVENT_PAUSE="pause";static EVENT_RESUME="resume";static EVENT_STOP="stop";static EVENT_END="end";source=null;constructor(e,t,s){super(),this._manager=e,this._volume=s.volume!==void 0?H.clamp(Number(s.volume)||0,0,1):1,this._pitch=s.pitch!==void 0?Math.max(.01,Number(s.pitch)||0):1,this._loop=!!(s.loop!==void 0&&s.loop),this._sound=t,this._state=Ca,this._suspended=!1,this._suspendEndEvent=0,this._suspendInstanceEvents=!1,this._playWhenLoaded=!0,this._startTime=Math.max(0,Number(s.startTime)||0),this._duration=Math.max(0,Number(s.duration)||0),this._startOffset=null,this._onPlayCallback=s.onPlay,this._onPauseCallback=s.onPause,this._onResumeCallback=s.onResume,this._onStopCallback=s.onStop,this._onEndCallback=s.onEnd,this._startedAt=0,this._currentTime=0,this._currentOffset=0,this._inputNode=null,this._connectorNode=null,this._firstNode=null,this._lastNode=null,this._waitingContextSuspension=!1,this._manager.context&&(this._initializeNodes(),this._endedHandler=this._onEnded.bind(this))}set currentTime(e){if(!(e<0))if(this._state===ni){const t=this._suspendInstanceEvents;this._suspendInstanceEvents=!0,this.stop(),this._startOffset=e,this.play(),this._suspendInstanceEvents=t}else this._startOffset=e,this._currentTime=e}get currentTime(){return this._startOffset!==null?this._startOffset:this._state===Th?this._currentTime:this._state===Ca||!this.source?0:(this._updateCurrentTime(),this._currentTime)}set duration(e){this._duration=Math.max(0,Number(e)||0);const t=this._state===ni;this.stop(),t&&this.play()}get duration(){return this._sound?this._duration?kr(this._duration,this._sound.duration):this._sound.duration:0}get isPaused(){return this._state===Th}get isPlaying(){return this._state===ni}get isStopped(){return this._state===Ca}get isSuspended(){return this._suspended}set loop(e){this._loop=!!e,this.source&&(this.source.loop=this._loop)}get loop(){return this._loop}set pitch(e){this._manager.context&&(this._currentOffset=this.currentTime,this._startedAt=this._manager.context.currentTime),this._pitch=Math.max(Number(e)||0,.01),this.source&&(this.source.playbackRate.value=this._pitch)}get pitch(){return this._pitch}set sound(e){this._sound=e,this._state!==Ca?this.stop():this._createSource()}get sound(){return this._sound}set startTime(e){this._startTime=Math.max(0,Number(e)||0);const t=this._state===ni;this.stop(),t&&this.play()}get startTime(){return this._startTime}set volume(e){e=H.clamp(e,0,1),this._volume=e,this.gain&&(this.gain.gain.value=e*this._manager.volume)}get volume(){return this._volume}_onPlay(){this.fire("play"),this._onPlayCallback&&this._onPlayCallback(this)}_onPause(){this.fire("pause"),this._onPauseCallback&&this._onPauseCallback(this)}_onResume(){this.fire("resume"),this._onResumeCallback&&this._onResumeCallback(this)}_onStop(){this.fire("stop"),this._onStopCallback&&this._onStopCallback(this)}_onEnded(){if(this._suspendEndEvent>0){this._suspendEndEvent--;return}this.fire("end"),this._onEndCallback&&this._onEndCallback(this),this.stop()}_onManagerVolumeChange(){this.volume=this._volume}_onManagerSuspend(){this._state===ni&&!this._suspended&&(this._suspended=!0,this.pause())}_onManagerResume(){this._suspended&&(this._suspended=!1,this.resume())}_initializeNodes(){this.gain=this._manager.context.createGain(),this._inputNode=this.gain,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination)}play(){return!this._manager.context||(this._state!==Ca&&this.stop(),this._state=ni,this._playWhenLoaded=!1,this._waitingContextSuspension)?!1:this._manager.suspended?(this._manager.once("resume",this._playAudioImmediate,this),this._waitingContextSuspension=!0,!1):(this._playAudioImmediate(),!0)}_playAudioImmediate(){if(this._waitingContextSuspension=!1,this._state!==ni)return;this.source||this._createSource();let e=kr(this._startOffset,this.duration);e=kr(this._startTime+e,this._sound.duration),this._startOffset=null,this._duration?this.source.start(0,e,this._duration):this.source.start(0,e),this._startedAt=this._manager.context.currentTime,this._currentTime=0,this._currentOffset=e,this.volume=this._volume,this.loop=this._loop,this.pitch=this._pitch,this._manager.on("volumechange",this._onManagerVolumeChange,this),this._manager.on("suspend",this._onManagerSuspend,this),this._manager.on("resume",this._onManagerResume,this),this._manager.on("destroy",this._onManagerDestroy,this),this._suspendInstanceEvents||this._onPlay()}pause(){return this._playWhenLoaded=!1,this._state!==ni?!1:(this._state=Th,this._waitingContextSuspension||(this._updateCurrentTime(),this._suspendEndEvent++,this.source.stop(0),this.source=null,this._startOffset=null,this._suspendInstanceEvents||this._onPause()),!0)}resume(){if(this._state!==Th)return!1;let e=this.currentTime;return this._state=ni,this._waitingContextSuspension||(this.source||this._createSource(),this._startOffset!==null&&(e=kr(this._startOffset,this.duration),e=kr(this._startTime+e,this._sound.duration),this._startOffset=null),this._duration?this.source.start(0,e,this._duration):this.source.start(0,e),this._startedAt=this._manager.context.currentTime,this._currentOffset=e,this.volume=this._volume,this.loop=this._loop,this.pitch=this._pitch,this._playWhenLoaded=!1,this._suspendInstanceEvents||this._onResume()),!0}stop(){if(this._playWhenLoaded=!1,this._state===Ca)return!1;const e=this._state===ni;return this._state=Ca,this._waitingContextSuspension||(this._manager.off("volumechange",this._onManagerVolumeChange,this),this._manager.off("suspend",this._onManagerSuspend,this),this._manager.off("resume",this._onManagerResume,this),this._manager.off("destroy",this._onManagerDestroy,this),this._startedAt=0,this._currentTime=0,this._currentOffset=0,this._startOffset=null,this._suspendEndEvent++,e&&this.source&&this.source.stop(0),this.source=null,this._suspendInstanceEvents||this._onStop()),!0}setExternalNodes(e,t){if(!e){console.error("The firstNode must be a valid Audio Node");return}if(!this._connectorNode)return;t||(t=e);const s=this._manager.context.destination;this._firstNode!==e&&(this._firstNode?this._connectorNode.disconnect(this._firstNode):this._connectorNode.disconnect(s),this._firstNode=e,this._connectorNode.connect(e)),this._lastNode!==t&&(this._lastNode&&this._lastNode.disconnect(s),this._lastNode=t,this._lastNode.connect(s))}clearExternalNodes(){if(!this._connectorNode)return;const e=this._manager.context.destination;this._firstNode&&(this._connectorNode.disconnect(this._firstNode),this._firstNode=null),this._lastNode&&(this._lastNode.disconnect(e),this._lastNode=null),this._connectorNode.connect(e)}getExternalNodes(){return[this._firstNode,this._lastNode]}
425_createSource(){if(!this._sound)return null;const e=this._manager.context;return e?(this._sound.buffer&&(this.source=e.createBufferSource(),this.source.buffer=this._sound.buffer,this.source.connect(this._inputNode),this.source.onended=this._endedHandler,this.source.loopStart=kr(this._startTime,this.source.buffer.duration),this._duration&&(this.source.loopEnd=Math.max(this.source.loopStart,kr(this._startTime+this._duration,this.source.buffer.duration)))),this.source):null}_updateCurrentTime(){this._currentTime=kr((this._manager.context.currentTime-this._startedAt)*this._pitch+this._currentOffset,this.duration)}_onManagerDestroy(){this.source&&this._state===ni&&(this.source.stop(0),this.source=null)}}const lI=1e4;class cI extends dT{_position=new E;_velocity=new E;constructor(e,t,s={}){super(e,t,s),e.context&&(s.position&&(this.position=s.position),this.maxDistance=s.maxDistance!==void 0?Number(s.maxDistance):lI,this.refDistance=s.refDistance!==void 0?Number(s.refDistance):1,this.rollOffFactor=s.rollOffFactor!==void 0?Number(s.rollOffFactor):1,this.distanceModel=s.distanceModel!==void 0?s.distanceModel:jm)}_initializeNodes(){this.gain=this._manager.context.createGain(),this.panner=this._manager.context.createPanner(),this.panner.connect(this.gain),this._inputNode=this.panner,this._connectorNode=this.gain,this._connectorNode.connect(this._manager.context.destination)}set position(e){this._position.copy(e);const t=this.panner;t&&("positionX"in t?(t.positionX.value=e.x,t.positionY.value=e.y,t.positionZ.value=e.z):t.setPosition&&t.setPosition(e.x,e.y,e.z))}get position(){return this._position}set velocity(e){this._velocity.copy(e)}get velocity(){return this._velocity}set maxDistance(e){this.panner&&(this.panner.maxDistance=e)}get maxDistance(){return this.panner?this.panner.maxDistance:0}set refDistance(e){this.panner&&(this.panner.refDistance=e)}get refDistance(){return this.panner?this.panner.refDistance:0}set rollOffFactor(e){this.panner&&(this.panner.rolloffFactor=e)}get rollOffFactor(){return this.panner?this.panner.rolloffFactor:0}set distanceModel(e){this.panner&&(this.panner.distanceModel=e)}get distanceModel(){return this.panner?this.panner.distanceModel:jm}}const yg=0,nn=1,Wi=2,Ns=3,Ui=4,xg=5,Tg=6,wg=7,Cg=8,Eg=9,bg=10,uT={[yg]:"SUBTRACTIVE",[nn]:"ADDITIVE",[Wi]:"NORMAL",[Ns]:"NONE",[Ui]:"PREMULTIPLIED",[xg]:"MULTIPLICATIVE",[Tg]:"ADDITIVEALPHA",[wg]:"MULTIPLICATIVE2X",[Cg]:"SCREEN",[Eg]:"MIN",[bg]:"MAX"},vn="none",hI="linear",dI=0,Ag=2,uI={[dI]:"NONE",[Ag]:"SCHLICK"},fI=0,fT=15,Ir=0,ks=1,Pg=2,Ig=3,Ef=4,Te=0,ot=1,nt=2,oS={[Te]:"DIRECTIONAL",[ot]:"OMNI",[nt]:"SPOT"},Cd=100,Sr=0,pT=1,mT=2,_T=3,pI={[Sr]:"PUNCTUAL",[pT]:"RECT",[mT]:"DISK",[_T]:"SPHERE"},gT=0,vT=1,mI={[gT]:"LINEAR",[vT]:"INVERSESQUARED"},Li=0,qm=2,Dg=3,_I=4,ST=5,uc=6,yT=7,xT=8,gI=9,yr=new Map([[ST,{name:"PCF1_32F",kind:"PCF1",format:Oi,pcf:!0}],[Li,{name:"PCF3_32F",kind:"PCF3",format:Oi,pcf:!0}],[_I,{name:"PCF5_32F",kind:"PCF5",format:Oi,pcf:!0}],[yT,{name:"PCF1_16F",kind:"PCF1",format:ja,pcf:!0}],[xT,{name:"PCF3_16F",kind:"PCF3",format:ja,pcf:!0}],[gI,{name:"PCF5_16F",kind:"PCF5",format:ja,pcf:!0}],[qm,{name:"VSM_16F",kind:"VSM",format:Ge,vsm:!0}],[Dg,{name:"VSM_32F",kind:"VSM",format:mt,vsm:!0}],[uc,{name:"PCSS_32F",kind:"PCSS",format:Ti,pcss:!0}]]),vI=255,TT=1,$m=0,wT=0,Ri=0,SI=1,ru=0,yI=1,mi=0,Sn=1,co=0,Na=1,wh=2,Mg=0,CT=1,xI={[Mg]:"NONE",[CT]:"BOX"},lS="mul",qc=0,Ol=1,TI={[qc]:"NONE",[Ol]:"SRGB"},bf=0,wI=1,CI=3,EI=5,Rg=6,ET=["LINEAR","FILMIC","HEJL","ACES","ACES2","NEUTRAL","NONE"],bT=0,Af=1,AT=2,bI={[bT]:"NONE",[Af]:"AO",[AT]:"GLOSSDEPENDENT"},Jr="none",au="envAtlas",nu="envAtlasHQ",ou="cubeMap",PT="sphereMap",AI={[Jr]:"NONE",[au]:"ENVATLAS",[nu]:"ENVATLASHQ",[ou]:"CUBEMAP",[PT]:"SPHEREMAP"},Lg="ambientSH",Fg="envAtlas",Og="constant",PI={[Lg]:"AMBIENTSH",[Fg]:"ENVALATLAS",[Og]:"CONSTANT"},lu=1,fc=2,Bg=4,IT=8,DT=16,pc=32,Km=64,MT=128,cu=256,Ng=512,mc=1024,_c=2048,RT=4096,gc=8192,Ed=16384,Ks=0,ea=1,LT=2,Js=1,ur=2,fr=4,Ko=0,Pf=1,FT=2,If=3,II=4,Fi=0,kt=1,Ut=2,DI={[Fi]:"SIMPLE",[kt]:"SLICED",[Ut]:"TILED"},bd=1,Ch=0,Ad=0,MI=1,cS=2,hp=3,RI=4,LI=5,hu=0,Zm=1,Me=0,rt=1,no="infinite",FI="box",OI="dome",on="none",BI="bayer8",NI="bluenoise",kI="ignnoise",OT={[on]:"NONE",[BI]:"BAYER8",[NI]:"BLUENOISE",[kI]:"IGNNOISE"},UI="prerender",zI="postrender",VI="prerender:layer",GI="postrender:layer",BT="precull",NT="postcull",HI="cull:end",xs=1,ho=2,kg="pcShadowCamera",Qm=0,WI=1,XI=2,YI=0,dp=1,up="compact",hS=0,To=1,uo=2,Pd=3,ol=0,Bl=1,Jm=2,e_=3,dS=4,uS=5,fS=0,jI=1,pS=2;class Df{uniformFormats=[];bindGroupFormats=[];vertexFormat;constructor(e,t,s){this.uniformFormats[hc]=e,this.bindGroupFormats[hc]=t,this.vertexFormat=s}hasUniform(e){for(let t=0;t<this.uniformFormats.length;t++)if(this.uniformFormats[t]?.get(e))return!0;return!1}hasTexture(e){for(let t=0;t<this.bindGroupFormats.length;t++)if(this.bindGroupFormats[t]?.getTexture(e))return!0;return!1}getVertexElement(e){return this.vertexFormat?.elements.find(t=>t.name===e)}generateKey(e){let t=JSON.stringify(this.uniformFormats)+JSON.stringify(this.bindGroupFormats);return e.isWebGPU&&(t+=this.vertexFormat?.shaderProcessingHashString),t}}const kT=new Jt;function ko(l){return kT.get(l)}function qI(l,e){kT.get(l,()=>e)}class ln{static definesHash(e){const t=Array.from(e).sort((s,i)=>s[0]>i[0]?1:-1);return Xs(JSON.stringify(t))}}const $I=new Jt;class KI{index;name;defines=new Map;constructor(e,t,s={}){this.name=e,this.index=t,Object.assign(this,s),this.buildShaderDefines()}buildShaderDefines(){let e;this.isShadow?e="SHADOW":this.isForward?e="FORWARD":this.index===If?e="PICK":this.index===II&&(e="PICK",this.defines.set("DEPTH_PICK_PASS","")),this.defines.set(`${e}_PASS`,""),this.defines.set(`${this.name.toUpperCase()}_PASS`,"")}}class zi{passesNamed=new Map;passesIndexed=[];nextIndex=0;constructor(){const e=(t,s,i)=>{this.allocate(t,i)};e("forward",Ko,{isForward:!0}),e("prepass"),e("shadow"),e("pick"),e("depth_pick")}static get(e){return $I.get(e,()=>new zi)}allocate(e,t){let s=this.passesNamed.get(e);return s===void 0&&(s=new KI(e,this.nextIndex,t),this.passesNamed.set(s.name,s),this.passesIndexed[s.index]=s,this.nextIndex++),s}getByIndex(e){return this.passesIndexed[e]}getByName(e){return this.passesNamed.get(e)}}class mS extends Map{_validations;_keyDirty=!1;_key="";
425constructor(e){super(),this._validations=e}set(e,t){return(!this.has(e)||this.get(e)!==t)&&this.markDirty(),super.set(e,t)}add(e,t=!0){for(const[s,i]of Object.entries(e))(t||!this.has(s))&&this.set(s,i);return this}delete(e){const t=this.has(e),s=super.delete(e);return t&&s&&this.markDirty(),s}clear(){this.size>0&&this.markDirty(),super.clear()}markDirty(){this._dirty=!0,this._keyDirty=!0}isDirty(){return this._dirty}resetDirty(){this._dirty=!1}get key(){return this._keyDirty&&(this._keyDirty=!1,this._key=Array.from(this.entries()).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>`${e}=${Xs(t)}`).join(",")),this._key}copy(e){for(const t of this.keys())e.has(t)||this.delete(t);for(const[t,s]of e)this.set(t,s);return this}}const ZI=new Jt;class be{static _validations=new Map;glsl=new mS(be._validations);wgsl=new mS(be._validations);static get(e,t=ze){const s=ZI.get(e,()=>new be);return t===ze?s.glsl:s.wgsl}static registerValidation(e,t){}version="";get useWGSL(){return this.glsl.size===0||this.wgsl.size>0}get key(){return`GLSL:${this.glsl.key}|WGSL:${this.wgsl.key}|API:${this.version}`}isDirty(){return this.glsl.isDirty()||this.wgsl.isDirty()}resetDirty(){this.glsl.resetDirty(),this.wgsl.resetDirty()}copy(e){return this.version=e.version,this.glsl.copy(e.glsl),this.wgsl.copy(e.wgsl),this}}class du{static merge(...e){const t=new Map(e[0]??[]);for(let s=1;s<e.length;s++){const i=e[s];if(i)for(const[r,a]of i)t.set(r,a)}return t}}class QI extends ln{constructor(e,t){super(),this.key=e,this.shaderDefinition=t}generateKey(e){return this.key}createShaderDefinition(e,t){return this.shaderDefinition}}class Qt{static createShader(e,t){const s=ko(e);let i=s.getCachedShader(t.uniqueName);if(!i){const r=e.isWebGPU&&(!!t.vertexWGSL||!!t.vertexChunk)&&(!!t.fragmentWGSL||!!t.fragmentChunk),a=be.get(e,r?de:ze),n=t.vertexChunk?a.get(t.vertexChunk):r?t.vertexWGSL:t.vertexGLSL,o=t.fragmentChunk?a.get(t.fragmentChunk):r?t.fragmentWGSL:t.fragmentGLSL,c=du.merge(a,t.fragmentIncludes),h=du.merge(a,t.vertexIncludes);i=new tt(e,Ht.createDefinition(e,{name:t.uniqueName,shaderLanguage:r?de:ze,attributes:t.attributes,vertexCode:n,fragmentCode:o,useTransformFeedback:t.useTransformFeedback,vertexIncludes:h,vertexDefines:t.vertexDefines,fragmentIncludes:c,fragmentDefines:t.fragmentDefines,fragmentOutputTypes:t.fragmentOutputTypes})),s.setCachedShader(t.uniqueName,i)}return i}static getCoreDefines(e,t){const s=new Map(e.defines);return t.cameraShaderParams.defines.forEach((r,a)=>s.set(a,r)),zi.get(t.device).getByIndex(t.pass).defines.forEach((r,a)=>s.set(a,r)),s}static processShader(e,t){const s=e.definition,r=`${s.name??"shader"}-id-${e.id}`,a=new QI(r,s),n="shader",o=ko(e.device);o.register(n,a);const c=o.getProgram(n,{},t);return o.unregister(n),c}static addScreenDepthChunkDefines(e,t,s){t.sceneDepthMapLinear&&s.set("SCENE_DEPTHMAP_LINEAR",""),e.textureFloatRenderable&&s.set("SCENE_DEPTHMAP_FLOAT","")}}const JI={type:qs,base:0,count:6,indexed:!0},ll=new ie,cl=new ie,fp=new Sg;class Uo{uniformBuffer;bindGroup;constructor(e){const t=e.device;if(this.shader=e,t.supportsUniformBuffers){const s=new Df;this.shader=Qt.processShader(e,s);const i=this.shader.meshUniformBufferFormat;i&&(this.uniformBuffer=new jc(t,i,!1));const r=this.shader.meshBindGroupFormat;this.bindGroup=new jo(t,r)}}destroy(){this.uniformBuffer?.destroy(),this.uniformBuffer=null,this.bindGroup?.destroy(),this.bindGroup=null}render(e,t,s){const i=this.shader.device;e&&(ll.set(i.vx,i.vy,i.vw,i.vh),cl.set(i.sx,i.sy,i.sw,i.sh),t=t??e,i.setViewport(e.x,e.y,e.z,e.w),i.setScissor(t.x,t.y,t.z,t.w)),i.setVertexBuffer(i.quadVertexBuffer);const r=this.shader;if(i.setShader(r),i.supportsUniformBuffers){i.setBindGroup(hc,i.emptyBindGroup);const a=this.bindGroup;a.update(),i.setBindGroup(Yc,a);const n=this.uniformBuffer;n?(n.update(fp),i.setBindGroup(Bo,fp.bindGroup,fp.offsets)):i.setBindGroup(Bo,i.emptyBindGroup)}i.draw(JI,i.quadIndexBuffer,s),e&&(i.setViewport(ll.x,ll.y,ll.z,ll.w),i.setScissor(cl.x,cl.y,cl.z,cl.w))}}class UT extends Pr{constructor(e,t,s,i){super(e),this.quad=t,this.rect=s,this.scissorRect=i}execute(){const{device:e}=this;e.setDrawStates(e.blendState),this.quad.render(this.rect,this.scissorRect)}}const e1=new ie;
425function cn(l,e,t,s,i){const r=new Uo(t);s||(s=e1,s.x=0,s.y=0,s.z=e?e.width:l.width,s.w=e?e.height:l.height);const a=new UT(l,r,s,i);a.init(e),a.colorOps.clear=!1,a.depthStencilOps.clearDepth=!1,l.isWebGPU&&e===null&&l.samples>1&&(a.colorOps.store=!0),a.render(),r.destroy()}class _S{_aabb=new Le;origMeshInstances;meshInstance=null;dynamic;batchGroupId;constructor(e,t,s){this.origMeshInstances=e,this.dynamic=t,this.batchGroupId=s}destroy(e,t){this.meshInstance&&(this.removeFromLayers(e,t),this.meshInstance.destroy(),this.meshInstance=null)}addToLayers(e,t){for(let s=0;s<t.length;s++){const i=e.layers.getLayerById(t[s]);i&&i.addMeshInstances([this.meshInstance])}}removeFromLayers(e,t){for(let s=0;s<t.length;s++){const i=e.layers.getLayerById(t[s]);i&&i.removeMeshInstances([this.meshInstance])}}updateBoundingBox(){this._aabb.copy(this.origMeshInstances[0].aabb);for(let e=1;e<this.origMeshInstances.length;e++)this._aabb.add(this.origMeshInstances[e].aabb);this.meshInstance.aabb=this._aabb,this.meshInstance._aabbVer=0}get model(){}}class Zt{_ui=!1;_sprite=!1;_obj={model:[],element:[],sprite:[],render:[]};id;name;dynamic;maxAabbSize;layers;constructor(e,t,s,i,r=[Ir]){this.id=e,this.name=t,this.dynamic=s,this.maxAabbSize=i,this.layers=r}static MODEL="model";static ELEMENT="element";static SPRITE="sprite";static RENDER="render"}const gS=new Z;class $c{bones;constructor(e){this._dirty=!0,this._rootBone=null,this._skinUpdateIndex=-1,this._updateBeforeCull=!0,e&&this.initSkin(e)}set rootBone(e){this._rootBone=e}get rootBone(){return this._rootBone}init(e,t){const s=t*3;let i=Math.ceil(Math.sqrt(s));i=H.roundUp(i,3);const r=Math.ceil(s/i);this.boneTexture=new ce(e,{width:i,height:r,format:mt,mipmaps:!1,minFilter:Fe,magFilter:Fe,name:"skin"}),this.matrixPalette=this.boneTexture.lock({mode:sb}),this.boneTexture.unlock()}destroy(){this.boneTexture&&(this.boneTexture.destroy(),this.boneTexture=null)}resolve(e,t){this.rootBone=e;const s=this.skin,i=[];for(let r=0;r<s.boneNames.length;r++){const a=s.boneNames[r];let n=e.findByName(a);n||(n=t),i.push(n)}this.bones=i}initSkin(e){this.skin=e,this.bones=[];const t=e.inverseBindPose.length;this.init(e.device,t),this.matrices=[];for(let s=0;s<t;s++)this.matrices[s]=new Z}uploadBones(e){this.boneTexture.upload()}_updateMatrices(e,t){if(this._skinUpdateIndex!==t){this._skinUpdateIndex=t,gS.copy(e.getWorldTransform()).invert();for(let s=this.bones.length-1;s>=0;s--)this.matrices[s].mulAffine2(gS,this.bones[s].getWorldTransform()),this.matrices[s].mulAffine2(this.matrices[s],this.skin.inverseBindPose[s])}}updateMatrices(e,t){this._updateBeforeCull&&this._updateMatrices(e,t)}updateMatrixPalette(e,t){this._updateMatrices(e,t);const s=this.matrixPalette,i=this.bones.length;for(let r=0;r<i;r++){const a=this.matrices[r].data,n=r*12;s[n]=a[0],s[n+1]=a[4],s[n+2]=a[8],s[n+3]=a[12],s[n+4]=a[1],s[n+5]=a[5],s[n+6]=a[9],s[n+7]=a[13],s[n+8]=a[2],s[n+9]=a[6],s[n+10]=a[10],s[n+11]=a[14]}this.uploadBones(this.skin.device)}}class vS extends $c{constructor(e,t,s){super();const i=t.length;this.init(e,i),this.device=e,this.rootNode=s,this.bones=t}updateMatrices(e,t){}updateMatrixPalette(e,t){const s=this.matrixPalette,i=this.bones.length;for(let r=0;r<i;r++){const a=this.bones[r].getWorldTransform().data,n=r*12;s[n]=a[0],s[n+1]=a[4],s[n+2]=a[8],s[n+3]=a[12],s[n+4]=a[1],s[n+5]=a[5],s[n+6]=a[9],s[n+7]=a[13],s[n+8]=a[2],s[n+9]=a[6],s[n+10]=a[10],s[n+11]=a[14]}this.uploadBones(this.device)}}let t1=0;class Dn{constructor(){this.initDefaults()}initDefaults(){this.recreate=!1,this.verticesUsage=Ys,this.indicesUsage=Ys,this.maxVertices=0,this.maxIndices=0,this.vertexCount=0,this.indexCount=0,this.vertexStream
425sUpdated=!1,this.indexStreamUpdated=!1,this.vertexStreamDictionary={},this.indices=null}_changeVertexCount(e,t){this.vertexCount||(this.vertexCount=e)}static DEFAULT_COMPONENTS_POSITION=3;static DEFAULT_COMPONENTS_NORMAL=3;static DEFAULT_COMPONENTS_UV=2;static DEFAULT_COMPONENTS_COLORS=4}class s1{constructor(e,t,s,i,r){this.data=e,this.componentCount=t,this.dataType=s,this.dataTypeNormalize=i,this.asInt=r}}class at extends Cf{indexBuffer=[null];vertexBuffer=null;primitive=[{type:0,base:0,baseVertex:0,count:0}];skin=null;boneAabb=null;_aabbVer=0;_aabb=new Le;_geometryData=null;_morph=null;_storageIndex=!1;_storageVertex=!1;constructor(e,t){super(),this.id=t1++,this.device=e,this._storageIndex=t?.storageIndex||!1,this._storageVertex=t?.storageVertex||!1}static fromGeometry(e,t,s={}){const i=new at(e,s),{positions:r,normals:a,tangents:n,colors:o,uvs:c,uvs1:h,blendIndices:d,blendWeights:u,indices:f}=t;return r&&i.setPositions(r),a&&i.setNormals(a),n&&i.setVertexStream(Gi,n,4),o&&i.setColors32(o),c&&i.setUvs(0,c),h&&i.setUvs(1,h),d&&i.setVertexStream(Bs,d,4,d.length/4,mr),u&&i.setVertexStream(ki,u,4),f&&i.setIndices(f),i.update(),i}set morph(e){e!==this._morph&&(this._morph&&this._morph.decRefCount(),this._morph=e,e&&e.incRefCount())}get morph(){return this._morph}set aabb(e){this._aabb=e,this._aabbVer++}get aabb(){return this._aabb}destroy(){const e=this.morph;e&&(this.morph=null,e.refCount<1&&e.destroy()),this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=null);for(let t=0;t<this.indexBuffer.length;t++)this._destroyIndexBuffer(t);this.indexBuffer.length=0,this._geometryData=null}_destroyIndexBuffer(e){this.indexBuffer[e]&&(this.indexBuffer[e].destroy(),this.indexBuffer[e]=null)}_initBoneAabbs(e){this.boneAabb=[],this.boneUsed=[];let t,s,i,r,a;const n=[],o=[],c=this.boneUsed,h=this.skin.boneNames.length;let d,u,f;for(let y=0;y<h;y++)n[y]=new E(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),o[y]=new E(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);const p=new jl(this.vertexBuffer),m=p.element[Ie],_=p.element[ki],g=p.element[Bs],v=this.vertexBuffer.numVertices;for(let y=0;y<v;y++){for(let S=0;S<4;S++)if(_.array[_.index+S]>0){const w=g.array[g.index+S];if(c[w]=!0,t=m.array[m.index],s=m.array[m.index+1],i=m.array[m.index+2],r=o[w],a=n[w],a.x>t&&(a.x=t),a.y>s&&(a.y=s),a.z>i&&(a.z=i),r.x<t&&(r.x=t),r.y<s&&(r.y=s),r.z<i&&(r.z=i),e){let C=d=t,b=u=s,I=f=i;for(let P=0;P<e.length;P++){const L=e[P],O=L.deltaPositions[y*3],D=L.deltaPositions[y*3+1],N=L.deltaPositions[y*3+2];O<0?C+=O:d+=O,D<0?b+=D:u+=D,N<0?I+=N:f+=N}a.x>C&&(a.x=C),a.y>b&&(a.y=b),a.z>I&&(a.z=I),r.x<d&&(r.x=d),r.y<u&&(r.y=u),r.z<f&&(r.z=f)}}p.next()}const x=this.vertexBuffer.getFormat().elements.find(y=>y.name===Ie);if(x&&x.normalize){const y=(()=>{switch(x.dataType){case ua:return S=>Math.max(S/127,-1);case mr:return S=>S/255;case fa:return S=>Math.max(S/32767,-1);case mn:return S=>S/65535;default:return S=>S}})();for(let S=0;S<h;S++)if(c[S]){const T=n[S],w=o[S];T.set(y(T.x),y(T.y),y(T.z)),w.set(y(w.x),y(w.y),y(w.z))}}for(let y=0;y<h;y++){const S=new Le;S.setMinMax(n[y],o[y]),this.boneAabb.push(S)}}_initGeometryData(){this._geometryData||(this._geometryData=new Dn,this.vertexBuffer&&(this._geometryData.vertexCount=this.vertexBuffer.numVertices,this._geometryData.maxVertices=this.vertexBuffer.numVertices),this.indexBuffer.length>0&&this.indexBuffer[0]&&(this._geometryData.indexCount=this.indexBuffer[0].numIndices,this._geometryData.maxIndices=this.indexBuffer[0].numIndices))}clear(e,t,s=0,i=0){this._initGeometryData(),this._geometryData.initDefaults(),this._geometryData.recreate=!0,this._geometryData.maxVertices=s,this._geometryData.maxIndices=i,this._geometryData.verticesUsage=e?Ys:Vd,this._geometryData.indicesUsage=t?Ys:Vd}setVertexStream(e,t,s,i,r=je,a=!1,n=!1){this._initGeometryData();const o=i||t.length/s;this._geometryData._changeVertexCount(o,e),this._geometryData.vertexStream
425sUpdated=!0,this._geometryData.vertexStreamDictionary[e]=new s1(t,s,r,a,n)}getVertexStream(e,t){let s=0,i=!1;if(this._geometryData){const r=this._geometryData.vertexStreamDictionary[e];r&&(i=!0,s=this._geometryData.vertexCount,ArrayBuffer.isView(t)?t.set(r.data):(t.length=0,t.push(r.data)))}return i||this.vertexBuffer&&(s=new jl(this.vertexBuffer).readData(e,t)),s}setPositions(e,t=Dn.DEFAULT_COMPONENTS_POSITION,s){this.setVertexStream(Ie,e,t,s,je,!1)}setNormals(e,t=Dn.DEFAULT_COMPONENTS_NORMAL,s){this.setVertexStream(Cs,e,t,s,je,!1)}setUvs(e,t,s=Dn.DEFAULT_COMPONENTS_UV,i){this.setVertexStream(vv+e,t,s,i,je,!1)}setColors(e,t=Dn.DEFAULT_COMPONENTS_COLORS,s){this.setVertexStream(ns,e,t,s,je,!1)}setColors32(e,t){this.setVertexStream(ns,e,Dn.DEFAULT_COMPONENTS_COLORS,t,mr,!0)}setIndices(e,t){this._initGeometryData(),this._geometryData.indexStreamUpdated=!0,this._geometryData.indices=e,this._geometryData.indexCount=t||e.length}getPositions(e){return this.getVertexStream(Ie,e)}getNormals(e){return this.getVertexStream(Cs,e)}getUvs(e,t){return this.getVertexStream(vv+e,t)}getColors(e){return this.getVertexStream(ns,e)}getIndices(e){let t=0;if(this._geometryData&&this._geometryData.indices){const s=this._geometryData.indices;if(t=this._geometryData.indexCount,ArrayBuffer.isView(e))e.set(s);else{e.length=0;for(let i=0,r=s.length;i<r;i++)e.push(s[i])}}else this.indexBuffer.length>0&&this.indexBuffer[0]&&(t=this.indexBuffer[0].readData(e));return t}update(e=qs,t=!0){if(this._geometryData){if(t){const r=this._geometryData.vertexStreamDictionary[Ie];r&&r.componentCount===3&&(this._aabb.compute(r.data,this._geometryData.vertexCount),this._aabbVer++)}let s=this._geometryData.recreate;this._geometryData.vertexCount>this._geometryData.maxVertices&&(s=!0,this._geometryData.maxVertices=this._geometryData.vertexCount),s&&this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBuffer=null);let i=this._geometryData.recreate;this._geometryData.indexCount>this._geometryData.maxIndices&&(i=!0,this._geometryData.maxIndices=this._geometryData.indexCount),i&&this.indexBuffer.length>0&&this.indexBuffer[0]&&(this.indexBuffer[0].destroy(),this.indexBuffer[0]=null),this._geometryData.vertexStream
425sUpdated&&this._updateVertexBuffer(),this._geometryData.indexStreamUpdated&&this._updateIndexBuffer(),this.primitive[0].type=e,this.indexBuffer.length>0&&this.indexBuffer[0]?this._geometryData.indexStreamUpdated&&(this.primitive[0].count=this._geometryData.indexCount,this.primitive[0].indexed=!0):this._geometryData.vertexStreamsUpdated&&(this.primitive[0].count=this._geometryData.vertexCount,this.primitive[0].indexed=!1),this._geometryData.vertexCount=0,this._geometryData.indexCount=0,this._geometryData.vertexStreamsUpdated=!1,this._geometryData.indexStreamUpdated=!1,this._geometryData.recreate=!1,this.updateRenderStates()}}_buildVertexFormat(e){const t=[];for(const s in this._geometryData.vertexStreamDictionary){const i=this._geometryData.vertexStreamDictionary[s];t.push({semantic:s,components:i.componentCount,type:i.dataType,normalize:i.dataTypeNormalize,asInt:i.asInt})}return new Us(this.device,t,e)}_updateVertexBuffer(){if(!this.vertexBuffer){const s=this._geometryData.maxVertices,i=this._buildVertexFormat(s);this.vertexBuffer=new Hi(this.device,i,s,{usage:this._geometryData.verticesUsage,storage:this._storageVertex})}const e=new jl(this.vertexBuffer),t=this._geometryData.vertexCount;for(const s in this._geometryData.vertexStreamDictionary){const i=this._geometryData.vertexStreamDictionary[s];e.writeData(s,i.data,t),delete this._geometryData.vertexStreamDictionary[s]}e.end()}_updateIndexBuffer(){if(this.indexBuffer.length<=0||!this.indexBuffer[0]){const t=this._geometryData.maxVertices,s=t>65535||t===0?ra:Ni,i=this._storageIndex?{storage:!0}:void 0;this.indexBuffer[0]=new la(this.device,s,this._geometryData.maxIndices,this._geometryData.indicesUsage,void 0,i)}const e=this._geometryData.indices;e&&(this.indexBuffer[0].writeData(e,this._geometryData.indexCount),this._geometryData.indices=null)}prepareRenderState(e){e===Na?this.generateWireframe():e===wh&&(this.primitive[wh]={type:lf,base:0,baseVertex:0,count:this.vertexBuffer?this.vertexBuffer.numVertices:0,indexed:!1})}updateRenderStates(){this.primitive[wh]&&this.prepareRenderState(wh),this.primitive[Na]&&this.prepareRenderState(Na)}generateWireframe(){this._destroyIndexBuffer(Na);const e=this.vertexBuffer.numVertices;let t,s;if(this.indexBuffer.length>0&&this.indexBuffer[0]){const r=[[0,1],[1,2],[2,0]],a=this.primitive[co].base,n=this.primitive[co].count,o=this.primitive[co].baseVertex||0,c=this.indexBuffer[co],h=vg[c.format],d=new h(c.storage),u=new h(n*2),f=new Set;let p=0;for(let m=a;m<a+n;m+=3)for(let _=0;_<3;_++){const g=d[m+r[_][0]]+o,v=d[m+r[_][1]]+o,x=g>v?v*e+g:g*e+v;f.has(x)||(f.add(x),u[p++]=g,u[p++]=v)}f.clear(),s=c.format,t=u.slice(0,p)}else{const r=e-e%3,a=r/3*6;s=a>65535?ra:Ni,t=a>65535?new Uint32Array(a):new Uint16Array(a);let n=0;for(let o=0;o<r;o+=3)t[n++]=o,t[n++]=o+1,t[n++]=o+1,t[n++]=o+2,t[n++]=o+2,t[n++]=o}const i=new la(this.vertexBuffer.device,s,t.length,Ys,t.buffer);this.primitive[Na]={type:cf,base:0,baseVertex:0,count:t.length,indexed:!0},this.indexBuffer[Na]=i}}const SS=new Z,pp=new E,yS=new ae,mp=new ae,xS=new E,TS=new E,i1=new Z,r1=new ae,Is=new E,hl=new Z,Ds=new ae,Mn=new ae,wS=new Z,_p=new E,Eh=new E;function CS(l,e){return l instanceof Function?l:t=>{let s=t[l];return s instanceof Function&&(s=s()),s===e}}function zT(l,e){if(e(l))return l;const t=l._children,s=t.length;for(let i=0;i<s;++i){const r=zT(t[i],e);if(r)return r}return null}class He extends ge{name;tags=new Mx(this);localPosition=new E;localRotation=new ae;localScale=new E(1,1,1);localEulerAngles=new E;position=new E;rotation=new ae;eulerAngles=new E;_scale=null;localTransform=new Z;_dirtyLocal=!1;_aabbVer=0;_frozen=!1;worldTransform=new Z;_dirtyWorld=!1;_worldScaleSign=0;_normalMatrix=new xi;_dirtyNormal=!0;_right=null;_up=null;_forward=null;_parent=null;_children=[];_graphDepth=0;_enabled=!0;_enabledInHierarchy=!1;scaleCompensation=!1;constructor(e="Untitled"){super(),this.name=e}get right(){return this._right||(this._right=new E),this.getWorldTransform().getX(this._right).normalize()}get up(){return this._up||(this._up=new E),this.getWorldTransform().getY(this._up).normalize()}get forward(){return this._forward||(this._forward=new E),this.getWorldTransform().getZ(this._forward).normalize().mulScalar(-1)}get normalMatrix(){const e=this._normalMatrix;return this._dirtyNormal&&(e.invertMat4(this.getWorldTransform()).transpose(),this._dirtyNormal=!1),e}set enabled(e){this._enabled!==e&&(this._enabled=e,(e&&this._parent?.enabled||!e)&&this._notifyHierarchyStateChanged(this,e))}get enabled(){return this._enabled&&this._enabledInHierarchy}get parent(){return this._parent}get path(){let e=this._parent;if(!e)return"";let t=this.name;for(;e&&e._parent;)t=`${e.name}/${t}`,e=e._parent;return t}get root(){let e=this;for(;e._parent;)e=e._parent;return e}get children(){return this._children}get graphDepth(){return this._graphDepth}_notifyHierarchyStateChanged(e,t){e._onHierarchyStateChanged(t);const s=e._children;for(let i=0,r=s.length;i<r;i++)s[i]._enabled&&this._notifyHierarchyStateChanged(s[i],t)}_onHierarchyStateChanged(e){this._enabledInHierarchy=e,e&&!this._frozen&&this._unfreezeParentToRoot()}_cloneInternal(e){e.name=this.name;const t=this.tags._list;e.tags.clear();for(let s=0;s<t.length;s++)e.tags.add(t[s]);e.localPosition.copy(this.localPosition),e.localRotation.copy(this.localRotation),e.localScale.copy(this.localScale),e.localEulerAngles.copy(this.localEulerAngles),e.position.copy(this.position),e.rotation.copy(this.rotation),e.eulerAngles.copy(this.eulerAngles),e.localTransform.copy(this.localTransform),e._dirtyLocal=this._dirtyLocal,e.worldTransform.copy(this.worldTransform),e._dirtyWorld=this._dirtyWorld,e._dirtyNormal=this._dirtyNormal,e._aabbVer=this._aabbVer+1,e._enabled=this._enabled,e.scaleCompensation=this.scaleCompensation,e._enabledInHierarchy=!1}clone(){const e=new this.constructor;return this._cloneInternal(e),e}copy(e){return e._cloneInternal(this),this}destroy(){this.remove();const e=this._children;for(;e.length;){const t=e.pop();t._parent=null,t.destroy()}this.fire("destroy",this),this.off()}find(e,t){const s=[],i=CS(e,t);return this.forEach(r=>{i(r)&&s.push(r)}),s}findOne(e,t){const s=CS(e,t);return zT(this,s)}findByTag(...e){const t=[],s=(i,r)=>{r&&i.tags.has(...e)&&t.push(i);for(let a=0;a<i._children.length;a++)s(i._children[a],!0)};return s(this,!1),t}findByName(e){return this.findOne("name",e)}findByPath(e){const t=Array.isArray(e)?e:e.split("/");let s=this;for(let i=0,r=t.length;i<r;++i)if(s=s.children.find(a=>a.name===t[i]),!s)return null;return s}forEach(e,t){e.call(t,this);const s=this._children,i=s.length;for(let r=0;r<i;++r)s[r].forEach(e,t)}isDescendantOf(e){let t=this._parent;for(;t;){if(t===e)return!0;t=t._parent}return!1}isAncestorOf(e){return e.isDescendantOf(this)}getEulerAngles(){return this.getWorldTransform().getEulerAngles(this.eulerAngles),this.eulerAngles}getLocalEulerAngles(){return this.localRotation.getEulerAngles(this.localEulerAngles),this.localEulerAngles}getLocalPosition(){return this.localPosition}getLocalRotation(){return this.localRotation}getLocalScale(){return this.localScale}getLocalTransform(){return this._dirtyLocal&&(this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale),this._dirtyLocal=!1),this.localTransform}getPosition(){return this.getWorldTransform().getTranslation(this.position),this.position}getRotation(){return this.rotation.setFromMat4(this.getWorldTransform()),this.rotation}getScale(){return this._scale||(this._scale=new E),this.getWorldTransform().getScale(this._scale)}
425getWorldTransform(){return!this._dirtyLocal&&!this._dirtyWorld?this.worldTransform:(this._parent&&this._parent.getWorldTransform(),this._sync(),this.worldTransform)}get worldScaleSign(){return this._worldScaleSign===0&&(this._worldScaleSign=this.getWorldTransform().scaleSign),this._worldScaleSign}remove(){this._parent?.removeChild(this)}reparent(e,t){this.remove(),e&&(t>=0?e.insertChild(this,t):e.addChild(this))}setLocalEulerAngles(e,t,s){this.localRotation.setFromEulerAngles(e,t,s),this._dirtyLocal||this._dirtifyLocal()}setLocalPosition(e,t,s){e instanceof E?this.localPosition.copy(e):this.localPosition.set(e,t,s),this._dirtyLocal||this._dirtifyLocal()}setLocalRotation(e,t,s,i){e instanceof ae?this.localRotation.copy(e):this.localRotation.set(e,t,s,i),this._dirtyLocal||this._dirtifyLocal()}setLocalScale(e,t,s){e instanceof E?this.localScale.copy(e):this.localScale.set(e,t,s),this._dirtyLocal||this._dirtifyLocal()}_dirtifyLocal(){this._dirtyLocal||(this._dirtyLocal=!0,this._dirtyWorld||this._dirtifyWorld())}_unfreezeParentToRoot(){let e=this._parent;for(;e;)e._frozen=!1,e=e._parent}_dirtifyWorld(){this._dirtyWorld||this._unfreezeParentToRoot(),this._dirtifyWorldInternal()}_dirtifyWorldInternal(){if(!this._dirtyWorld){this._frozen=!1,this._dirtyWorld=!0;for(let e=0;e<this._children.length;e++)this._children[e]._dirtyWorld||this._children[e]._dirtifyWorldInternal()}this._dirtyNormal=!0,this._worldScaleSign=0,this._aabbVer++}setPosition(e,t,s){e instanceof E?Is.copy(e):Is.set(e,t,s),this._parent===null?this.localPosition.copy(Is):(hl.copy(this._parent.getWorldTransform()).invert(),hl.transformPoint(Is,this.localPosition)),this._dirtyLocal||this._dirtifyLocal()}setRotation(e,t,s,i){if(e instanceof ae?Ds.copy(e):Ds.set(e,t,s,i),this._parent===null)this.localRotation.copy(Ds);else{const r=this._parent.getRotation();Mn.copy(r).invert(),this.localRotation.copy(Mn).mul(Ds)}this._dirtyLocal||this._dirtifyLocal()}setPositionAndRotation(e,t){if(this._parent===null)this.localPosition.copy(e),this.localRotation.copy(t);else{const s=this._parent.getWorldTransform();hl.copy(s).invert(),hl.transformPoint(e,this.localPosition),this.localRotation.setFromMat4(hl).mul(t)}this._dirtyLocal||this._dirtifyLocal()}setEulerAngles(e,t,s){if(this.localRotation.setFromEulerAngles(e,t,s),this._parent!==null){const i=this._parent.getRotation();Mn.copy(i).invert(),this.localRotation.mul2(Mn,this.localRotation)}this._dirtyLocal||this._dirtifyLocal()}addChild(e){this._prepareInsertChild(e),this._children.push(e),this._onInsertChild(e)}addChildAndSaveTransform(e){const t=e.getPosition(),s=e.getRotation();this._prepareInsertChild(e),e.setPosition(i1.copy(this.worldTransform).invert().transformPoint(t)),e.setRotation(r1.copy(this.getRotation()).invert().mul(s)),this._children.push(e),this._onInsertChild(e)}insertChild(e,t){this._prepareInsertChild(e),this._children.splice(t,0,e),this._onInsertChild(e)}_prepareInsertChild(e){e.remove()}_fireOnHierarchy(e,t,s){this.fire(e,s);for(let i=0;i<this._children.length;i++)this._children[i]._fireOnHierarchy(t,t,s)}_onInsertChild(e){e._parent=this;const t=e._enabled&&this.enabled;e._enabledInHierarchy!==t&&(e._enabledInHierarchy=t,e._notifyHierarchyStateChanged(e,t)),e._updateGraphDepth(),e._dirtifyWorld(),this._frozen&&e._unfreezeParentToRoot(),e._fireOnHierarchy("insert","inserthierarchy",this),this.fire&&this.fire("childinsert",e)}_updateGraphDepth(){this._graphDepth=this._parent?this._parent._graphDepth+1:0;for(let e=0,t=this._children.length;e<t;e++)this._children[e]._updateGraphDepth()}removeChild(e){const t=this._children.indexOf(e);t!==-1&&(this._children.splice(t,1),e._parent=null,e._fireOnHierarchy("remove","removehierarchy",this),this.fire("childremove",e))}_sync(){if(this._dirtyLocal&&(this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale),this._dirtyLocal=!1),this._dirtyWorld){if(this._parent===null)this.worldTransform.copy(this.localTransform);else if(this.scaleCompensation){let e;const t=this._parent;let s=this.localScale,i=t;if(i){for(;i&&i.scaleCompensation;)i=i._parent;i&&(i=i._parent,i&&(e=i.worldTransform.getScale(),xS.mul2(e,this.localScale),s=xS))}mp.setFromMat4(t.worldTransform),yS.mul2(mp,this.localRotation);let r=t.worldTransform;
425t.scaleCompensation&&(TS.mul2(e,t.getLocalScale()),SS.setTRS(t.worldTransform.getTranslation(pp),mp,TS),r=SS),r.transformPoint(this.localPosition,pp),this.worldTransform.setTRS(pp,yS,s)}else this.worldTransform.mulAffine2(this._parent.worldTransform,this.localTransform);this._dirtyWorld=!1}}syncHierarchy(){if(!this._enabled||this._frozen)return;this._frozen=!0,(this._dirtyLocal||this._dirtyWorld)&&this._sync();const e=this._children;for(let t=0,s=e.length;t<s;t++)e[t].syncHierarchy()}lookAt(e,t,s,i=0,r=1,a=0){if(e instanceof E)_p.copy(e),t instanceof E?Eh.copy(t):Eh.copy(E.UP);else{if(s===void 0)return;_p.set(e,t,s),Eh.set(i,r,a)}wS.setLookAt(this.getPosition(),_p,Eh),Ds.setFromMat4(wS),this.setRotation(Ds)}translate(e,t,s){e instanceof E?Is.copy(e):Is.set(e,t,s),Is.add(this.getPosition()),this.setPosition(Is)}translateLocal(e,t,s){e instanceof E?Is.copy(e):Is.set(e,t,s),this.localRotation.transformVector(Is,Is),this.localPosition.add(Is),this._dirtyLocal||this._dirtifyLocal()}rotate(e,t,s){if(Ds.setFromEulerAngles(e,t,s),this._parent===null)this.localRotation.mul2(Ds,this.localRotation);else{const i=this.getRotation(),r=this._parent.getRotation();Mn.copy(r).invert(),Ds.mul2(Mn,Ds),this.localRotation.mul2(Ds,i)}this._dirtyLocal||this._dirtifyLocal()}rotateLocal(e,t,s){Ds.setFromEulerAngles(e,t,s),this.localRotation.mul(Ds),this._dirtyLocal||this._dirtifyLocal()}}const VT=new Jt;function Zo(l){return VT.get(l)}function a1(l,e){VT.get(l,()=>e)}class n1{cache=new Map;destroy(){this.cache.forEach((e,t)=>{t.destroy()}),this.cache.clear()}incRef(e){const t=(this.cache.get(e)||0)+1;this.cache.set(e,t)}decRef(e){if(e){let t=this.cache.get(e);t&&(t--,t===0?(this.cache.delete(e),e.destroy()):this.cache.set(e,t))}}}class qr{static cache=new n1;static incRef(e){this.cache.incRef(e)}static decRef(e){this.cache.decRef(e)}static destroy(){this.cache.destroy()}}class GT{_counter=0;get(){return this._counter++}}const HT=new GT,o1=new Le,bh=new Le,gp=new W_,vp=new Set,Rn=new Uint32Array(4);class ES{vertexBuffer=null;_destroyVertexBuffer=!1;constructor(e){this.count=e}destroy(){this._destroyVertexBuffer&&this.vertexBuffer?.destroy(),this.vertexBuffer=null}}class l1{shader;bindGroup=null;uniformBuffer=null;hashes;getBindGroup(e){if(!this.bindGroup){const s=this.shader.meshBindGroupFormat;this.bindGroup=new jo(e,s)}return this.bindGroup}getUniformBuffer(e){if(!this.uniformBuffer){const s=this.shader.meshUniformBufferFormat;this.uniformBuffer=new jc(e,s,!1)}return this.uniformBuffer}destroy(){this.bindGroup?.destroy(),this.bindGroup=null,this.uniformBuffer?.destroy(),this.uniformBuffer=null}}class Ne{castShadow=!1;shadowCascadeMask=vI;cull=!0;drawOrder=0;_drawBucket=127;node;visible=!0;visibleThisFrame=!1;flipFacesFactor=1;gsplatInstance=null;id=HT.get();isVisibleFunc=null;instancingData=null;indirectData=null;drawCommands=null;meshMetaData=null;parameters={};pick=!0;stencilFront=null;stencilBack=null;transparent=!1;_aabb=new Le;_aabbVer=-1;_aabbMeshVer=-1;_customAabb=null;_updateAabb=!0;_updateAabbFunc=null;_sortKeyShadow=0;_sortKeyForward=0;_sortKeyDynamic=0;_layer=fT;_material=null;_skinInstance=null;_morphInstance=null;_receiveShadow=!0;_renderStyle=co;_screenSpace=!1;_shaderCache=new Map;_shaderDefs=Js<<16;_calculateSortDistance=null;constructor(e,t,s=null){if(this.node=s,this._mesh=e,e.incRefCount(),this.material=t,e.vertexBuffer){const i=e.vertexBuffer.format;this._shaderDefs|=i.hasUv0?Bg:0,this._shaderDefs|=i.hasUv1?IT:0,this._shaderDefs|=i.hasColor?DT:0,this._shaderDefs|=i.hasTangents?Ng:0}this.updateKey()}set drawBucket(e){this._drawBucket=Math.floor(e)&255,this.updateKey()}get drawBucket(){return this._drawBucket}set renderStyle(e){this._renderStyle=e,this.mesh.prepareRenderState(e)}get renderStyle(){return this._renderStyle}set mesh(e){e!==this._mesh&&(this._mesh&&this._mesh.decRefCount(),this._mesh=e,e&&e.incRefCount())}get mesh(){return this._mesh}set aabb(e){this._aabb=e}get aabb(){if(!this._updateAabb)return this._aabb;if(this._updateAabbFunc)return this._updateAabbFunc(this._aabb);let e=this._customAabb,t=!!e;if(!e){if(e=o1,this.skinInstance){if(!this.mesh.boneAabb){const r=this._morphInstance?this._morphInstance.morph._targets:null;this.mesh._initBoneAabbs(r)}const s=this.mesh.boneUsed;let i=!0;for(let r=0;r<this.mesh.boneAabb.length;r++)s[r]&&(bh.setFromTransformedAabb(this.mesh.boneAabb[r],this.skinInstance.matrices[r]),i?(i=!1,e.center.copy(bh.center),e.halfExtents.copy(bh.halfExtents)):e.add(bh));t=!0}else if(this.node._aabbVer!==this._aabbVer||this.mesh._aabbVer!==this._aabbMeshVer){if(this.mesh?(e.center.copy(this.mesh.aabb.center),e.halfExtents.copy(this.mesh.aabb.halfExtents)):(e.center.set(0,0,0),e.halfExtents.set(0,0,0)),this.mesh&&this.mesh.morph){const s=this.mesh.morph.aabb;e._expand(s.getMin(),s.getMax())}t=!0,this._aabbVer=this.node._aabbVer,this._aabbMeshVer=this.mesh._aabbVer}}return t&&this._aabb.setFromTransformedAabb(e,this.node.getWorldTransform()),this._aabb}
425clearShaders(){this._shaderCache.forEach(e=>{e.destroy()}),this._shaderCache.clear()}getShaderInstance(e,t,s,i,r,a,n){const o=this._shaderDefs;Rn[0]=e,Rn[1]=t,Rn[2]=o,Rn[3]=i.hash;const c=Tf(Rn);let h=this._shaderCache.get(c);if(!h){const d=this._material;if(h=new l1,h.shader=d.variants.get(c),h.hashes=new Uint32Array(Rn),!h.shader){const u=d.getShaderVariant({device:this.mesh.device,scene:s,objDefs:o,cameraShaderParams:i,pass:e,sortedLights:n,viewUniformFormat:r,viewBindGroupFormat:a,vertexFormat:this.mesh.vertexBuffer?.format});d.variants.set(c,u),h.shader=u}this._shaderCache.set(c,h)}return h}set material(e){this.clearShaders();const t=this._material;t&&t.removeMeshInstanceRef(this),this._material=e,e&&(e.addMeshInstanceRef(this),this.transparent=e.transparent,this.updateKey())}get material(){return this._material}_updateShaderDefs(e){e!==this._shaderDefs&&(this._shaderDefs=e,this.clearShaders())}set calculateSortDistance(e){this._calculateSortDistance=e}get calculateSortDistance(){return this._calculateSortDistance}set receiveShadow(e){this._receiveShadow!==e&&(this._receiveShadow=e,this._updateShaderDefs(e?this._shaderDefs&~lu:this._shaderDefs|lu))}get receiveShadow(){return this._receiveShadow}set batching(e){this._updateShaderDefs(e?this._shaderDefs|Ed:this._shaderDefs&~Ed)}get batching(){return(this._shaderDefs&Ed)!==0}set skinInstance(e){this._skinInstance=e,this._updateShaderDefs(e?this._shaderDefs|fc:this._shaderDefs&~fc),this._setupSkinUpdate()}get skinInstance(){return this._skinInstance}set morphInstance(e){this._morphInstance?.destroy(),this._morphInstance=e;let t=this._shaderDefs;t=e&&e.morph.morphPositions?t|mc:t&~mc,t=e&&e.morph.morphNormals?t|_c:t&~_c,t=e&&e.morph.intRenderFormat?t|gc:t&~gc,this._updateShaderDefs(t)}get morphInstance(){return this._morphInstance}set screenSpace(e){this._screenSpace!==e&&(this._screenSpace=e,this._updateShaderDefs(e?this._shaderDefs|cu:this._shaderDefs&~cu))}get screenSpace(){return this._screenSpace}set key(e){this._sortKeyForward=e}get key(){return this._sortKeyForward}set mask(e){const t=this._shaderDefs&65535;this._updateShaderDefs(t|e<<16)}get mask(){return this._shaderDefs>>16}set instancingCount(e){this.instancingData&&(this.instancingData.count=e)}get instancingCount(){return this.instancingData?this.instancingData.count:0}destroy(){const e=this.mesh;e&&(this.mesh=null,e.refCount<1&&e.destroy()),this.setRealtimeLightmap(Ne.lightmapParamNames[0],null),this.setRealtimeLightmap(Ne.lightmapParamNames[1],null),this._skinInstance?.destroy(),this._skinInstance=null,this.morphInstance?.destroy(),this.morphInstance=null,this.clearShaders(),this.material=null,this.instancingData?.destroy(),this.destroyDrawCommands()}destroyDrawCommands(){if(this.drawCommands){for(const e of this.drawCommands.values())e?.destroy();this.drawCommands=null}}static lightmapParamNames=["texture_lightMap","texture_dirLightMap"];static _prepareRenderStyleForArray(e,t){if(e){for(let s=0;s<e.length;s++){e[s]._renderStyle=t;const i=e[s].mesh;vp.has(i)||(vp.add(i),i.prepareRenderState(t))}vp.clear()}}_isVisible(e){return this.visible?this.isVisibleFunc?this.isVisibleFunc(e):(gp.center=this.aabb.center,gp.radius=this._aabb.halfExtents.length(),e.frustum.containsSphere(gp)>0):!1}updateKey(){const{material:e}=this;this._sortKeyForward=this._drawBucket<<23|(e.alphaToCoverage||e.alphaTest?4194304:0)|e.id&4194303}setInstancing(e,t=!1){e?(e===!0?this.instancingData=new ES(0):(this.instancingData=new ES(e.numVertices),this.instancingData.vertexBuffer=e,e.format.instancing=!0),this.cull=t):(this.instancingData=null,this.cull=!0),this._updateShaderDefs(e instanceof Hi?this._shaderDefs|pc:this._shaderDefs&~pc)}setIndirect(e,t,s=1){const i=e?.camera??null;if(t===-1)this._deleteDrawCommandsKey(i);else{this.drawCommands??(this.drawCommands=new Map);const r=this.drawCommands.get(i)??new rS(this.mesh.device);r.slotIndex=t,r.update(s),this.drawCommands.set(i,r),this.mesh.device.mapsToClear.add(this.drawCommands)}}setMultiDraw(e,t=1){const s=e?.camera??null;let i;if(t===0)this._deleteDrawCommandsKey(s);else{if(this.drawCommands??(this.drawCommands=new Map),i=this.drawCommands.get(s),!i){const a=this.mesh.indexBuffer?.[0]?.format,n=a!==void 0?kE[a]:0;
425i=new rS(this.mesh.device,n),this.drawCommands.set(s,i)}i.allocate(t)}return i}_deleteDrawCommandsKey(e){const t=this.drawCommands;t&&(t.get(e)?.destroy(),t.delete(e),t.size===0&&this.destroyDrawCommands())}getDrawCommands(e){const t=this.drawCommands;if(t)return t.get(e)??t.get(null)}getIndirectMetaData(){const e=this.mesh?.primitive[this.renderStyle],t=this.meshMetaData??(this.meshMetaData=new Int32Array(4));return t[0]=e.count,t[1]=e.base,t[2]=e.baseVertex,t}ensureMaterial(e){this.material||(this.material=Zo(e))}clearParameters(){this.parameters={}}getParameters(){return this.parameters}getParameter(e){return this.parameters[e]}setParameter(e,t,s=4294967295){const i=this.parameters[e];i?(i.data=t,i.passFlags=s):this.parameters[e]={scopeId:null,data:t,passFlags:s}}setRealtimeLightmap(e,t){const s=this.getParameter(e);s!==t&&(s&&qr.decRef(s.data),t?(qr.incRef(t),this.setParameter(e,t)):this.deleteParameter(e))}deleteParameter(e){this.parameters[e]&&delete this.parameters[e]}setParameters(e,t){const s=this.parameters;for(const i in s){const r=s[i];r.passFlags&t&&(r.scopeId||(r.scopeId=e.scope.resolve(i)),r.scopeId.setValue(r.data))}}setLightmapped(e){e?this.mask=(this.mask|ur)&-6:(this.setRealtimeLightmap(Ne.lightmapParamNames[0],null),this.setRealtimeLightmap(Ne.lightmapParamNames[1],null),this._shaderDefs&=-4289,this.mask=(this.mask|Js)&-7)}setCustomAabb(e){e?this._customAabb?this._customAabb.copy(e):this._customAabb=e.clone():(this._customAabb=null,this._aabbVer=-1),this._setupSkinUpdate()}_setupSkinUpdate(){this._skinInstance&&(this._skinInstance._updateBeforeCull=!this._customAabb)}}const c1=[0,1,3,2,3,1],h1=[0,1,3,0,3,2],bS=new xi;function AS(l,e){if(l&&!e||!l&&e)return!1;if(l=l.data,e=e.data,l===e)return!0;if(l instanceof Float32Array&&e instanceof Float32Array){if(l.length!==e.length)return!1;for(let t=0;t<l.length;t++)if(l[t]!==e[t])return!1;return!0}return!1}function d1(l,e){for(const t in l)if(l.hasOwnProperty(t)&&!AS(l[t],e[t]))return!1;for(const t in e)if(e.hasOwnProperty(t)&&!AS(e[t],l[t]))return!1;return!0}function Sp(l){return l.node.worldTransform.scaleSign}class u1{constructor(e,t,s){this.device=e,this.rootNode=t,this.scene=s,this._init=!1,this._batchGroups={},this._batchGroupCounter=0,this._batchList=[],this._dirtyGroups=[]}destroy(){this.device=null,this.rootNode=null,this.scene=null,this._batchGroups={},this._batchList=[],this._dirtyGroups=[]}addGroup(e,t,s,i,r){if(i===void 0&&(i=this._batchGroupCounter,this._batchGroupCounter++),this._batchGroups[i])return;const a=new Zt(i,e,t,s,r);return this._batchGroups[i]=a,a}removeGroup(e){if(!this._batchGroups[e])return;const t=[];for(let s=0;s<this._batchList.length;s++)this._batchList[s].batchGroupId===e?this.destroyBatch(this._batchList[s]):t.push(this._batchList[s]);this._batchList=t,this._removeModelsFromBatchGroup(this.rootNode,e),delete this._batchGroups[e]}markGroupDirty(e){this._dirtyGroups.indexOf(e)<0&&this._dirtyGroups.push(e)}getGroupByName(e){const t=this._batchGroups;for(const s in t)if(t.hasOwnProperty(s)&&t[s].name===e)return t[s];return null}getGroupById(e){return this._batchGroups[e]??null}getBatches(e){const t=[],s=this._batchList.length;for(let i=0;i<s;i++){const r=this._batchList[i];r.batchGroupId===e&&t.push(r)}return t}_removeModelsFromBatchGroup(e,t){if(e.enabled){e.model&&e.model.batchGroupId===t&&(e.model.batchGroupId=-1),e.render&&e.render.batchGroupId===t&&(e.render.batchGroupId=-1),e.element&&e.element.batchGroupId===t&&(e.element.batchGroupId=-1),e.sprite&&e.sprite.batchGroupId===t&&(e.sprite.batchGroupId=-1);for(let s=0;s<e._children.length;s++)this._removeModelsFromBatchGroup(e._children[s],t)}}insert(e,t,s){const i=this._batchGroups[t];i&&i._obj[e].indexOf(s)<0&&(i._obj[e].push(s),this.markGroupDirty(t))}remove(e,t,s){const i=this._batchGroups[t];if(i){const r=i._obj[e].indexOf(s);r>=0&&(i._obj[e].splice(r,1),this.markGroupDirty(t))}}_filterBatchableInstances(e,t){let s=!1;for(let i=0;i<e.length;i++)(e[i].skinInstance||e[i].morphInstance)&&(s=!0);return s?null:e}_extractRender(e,t,s,i){if(e.render){const r=this._filterBatchableInstances(e.render.meshInstances,e.name);r&&(t=i[e.render.batchGroupId]=t.concat(r),e.render.removeFromLayers())}return t}_extractModel(e,t,s,i){if(e.model&&e.model.model){const r=this._filterBatchableInstances(e.model.meshInstances,e.name);r&&(t=i[e.model.batchGroupId]=t.concat(r),e.model.removeModelFromLayers())}return t}_extractElement(e,t,s){if(!e.element)return;let i=!1;e.element._text&&e.element._text._model.meshInstances.length>0?(t.push(e.element._text._model.meshInstances[0]),e.element.removeModelFromLayers(e.element._text._model),i=!0):e.element._image&&(t.push(e.element._image._renderable.meshInstance),e.element.removeModelFromLayers(e.element._image._renderable.model),e.element._image._renderable.unmaskMeshInstance&&(t.push(e.element._image._renderable.unmaskMeshInstance),(!e.element._image._renderable.unmaskMeshInstance.stencilFront||!e.element._image._renderable.unmaskMeshInstance.stencilBack)&&(e.element._dirtifyMask(),e.element._onPrerender())),i=!0),i&&(s._ui=!0)}_collectAndRemoveMeshInstances(e,t){for(let s=0;s<t.length;s++){const i=t[s],r=this._batchGroups[i];if(!r)continue;let a=e[i];a||(a=e[i]=[]);for(let n=0;n<r._obj.model.length;n++)a=this._extractModel(r._obj.model[n],a,r,e);for(let n=0;n<r._obj.render.length;n++)a=this._extractRender(r._obj.render[n],a,r,e);for(let n=0;n<r._obj.element.length;n++)this._extractElement(r._obj.element[n],a,r);for(let n=0;n<r._obj.sprite.length;n++){const o=r._obj.sprite[n];o.sprite&&o.sprite._meshInstance&&(r.dynamic||o.sprite.sprite._renderMode===Fi)&&(a.push(o.sprite._meshInstance),o.sprite.removeFromLayers(),r._sprite=!0)}}}generate(e){const t={};e||(e=Object.keys(this._batchGroups));const s=[];for(let o=0;o<this._batchList.length;o++){if(e.indexOf(this._batchList[o].batchGroupId)<0){s.push(this._batchList[o]);continue}this.destroyBatch(this._batchList[o])}if(this._batchList=s,this._collectAndRemoveMeshInstances(t,e),e===this._dirtyGroups)this._dirtyGroups.length=0;else{const o=[];for(let c=0;c<this._dirtyGroups.length;c++)e.indexOf(this._dirtyGroups[c])<0&&o.push(this._dirtyGroups[c]);this._dirtyGroups=o}let i,r,a,n;for(const o in t)if(t.hasOwnProperty(o)&&(i=t[o],a=this._batchGroups[o],!!a)){r=this.prepare(i,a.dynamic,a.maxAabbSize,a._ui||a._sprite);for(let c=0;c<r.length;c++)n=this.create(r[c],a.dynamic,parseInt(o,10)),n&&n.addToLayers(this.scene,a.layers)}}prepare(e,t,s=Number.POSITIVE_INFINITY,i){if(e.length===0)return[];const r=s*.5,a=1024,n=4294967295,o=new Le,c=new Le;let h=null,d;const u=[];let f=0;i&&e.sort((g,v)=>g.drawOrder-v.drawOrder);let p=e,m;const _=i?function(g){h?h.add(g.aabb):h=g.aabb.clone(),m.push(g)}:function(g){m.push(g)};for(;p.length>0;){u[f]=[p[0]],m=[];const g=p[0].material,v=p[0].layer,x=p[0]._shaderDefs,y=p[0].parameters,S=p[0].stencilFront;let T=p[0].mesh.vertexBuffer.getNumVertices();const w=p[0].drawOrder;o.copy(p[0].aabb);
425const C=Sp(p[0]),b=p[0].mesh.vertexBuffer.format.batchingHash,I=p[0].mesh.primitive[0].indexed,P=p[0].castShadow,L=p[0].shadowCascadeMask;h=null;for(let O=1;O<p.length;O++){const D=p[O];if(t&&u[f].length>=a){m=m.concat(p.slice(O));break}if(g!==D.material||v!==D.layer||b!==D.mesh.vertexBuffer.format.batchingHash||I!==D.mesh.primitive[0].indexed||x!==D._shaderDefs||T+D.mesh.vertexBuffer.getNumVertices()>n){_(D);continue}if(c.copy(o),c.add(D.aabb),c.halfExtents.x>r||c.halfExtents.y>r||c.halfExtents.z>r){_(D);continue}if(S&&(!(d=D.stencilFront)||S.func!==d.func||S.zpass!==d.zpass)){_(D);continue}if(C!==Sp(D)){_(D);continue}if(P!==D.castShadow||L!==D.shadowCascadeMask){_(D);continue}if(!d1(y,D.parameters)){_(D);continue}if(i&&h&&h.intersects(D.aabb)&&D.drawOrder!==w){_(D);continue}o.add(D.aabb),T+=D.mesh.vertexBuffer.getNumVertices(),u[f].push(D)}f++,p=m}return u}collectBatchedMeshData(e,t){let s=null,i=0,r=0,a=null;for(let n=0;n<e.length;n++)if(e[n].visible){const o=e[n].mesh,c=o.vertexBuffer.numVertices;if(i+=c,o.primitive[0].indexed)r+=o.primitive[0].count;else{const h=o.primitive[0].type;(h===qa||h===Tr)&&o.primitive[0].count===4&&(r+=6)}if(!s){a=e[n].material,s={};const h=o.vertexBuffer.format.elements;for(let d=0;d<h.length;d++){const u=h[d].name;s[u]={numComponents:h[d].numComponents,dataType:h[d].dataType,normalize:h[d].normalize,count:0}}t&&(s[Bs]={numComponents:1,dataType:je,normalize:!1,count:0})}}return{streams:s,batchNumVerts:i,batchNumIndices:r,material:a}}
425create(e,t,s){this._init||(this.vertexFormats={},this._init=!0);let i=null,r,a,n,o=null;const c=this.collectBatchedMeshData(e,t);if(c.streams){const h=c.streams;let d=c.material;const u=c.batchNumVerts,f=c.batchNumIndices;o=new _S(e,t,s),this._batchList.push(o);let p,m,_,g,v=0,x=0,y;const S=u<=65535?Uint16Array:Uint32Array,T=new S(f);for(r in h)i=h[r],i.typeArrayType=yo[i.dataType],i.elementByteSize=Xl[i.dataType],i.buffer=new i.typeArrayType(u*i.numComponents);for(let b=0;b<e.length;b++)if(e[b].visible){a=e[b].mesh,n=a.vertexBuffer.numVertices,t||(y=e[b].node.getWorldTransform());for(r in h)if(r!==Bs){i=h[r];const I=new i.typeArrayType(i.buffer.buffer,i.elementByteSize*i.count),P=a.getVertexStream(r,I)*i.numComponents;if(i.count+=P,!t&&i.numComponents>=3){if(r===Ie){const L=y.data,O=L[0],D=L[1],N=L[2],k=L[4],A=L[5],M=L[6],R=L[8],F=L[9],U=L[10],B=L[12],z=L[13],$=L[14];let K,Y,te;for(let J=0;J<P;J+=i.numComponents)K=I[J],Y=I[J+1],te=I[J+2],I[J]=K*O+Y*k+te*R+B,I[J+1]=K*D+Y*A+te*F+z,I[J+2]=K*N+Y*M+te*U+$}else if(r===Cs||r===Gi){bS.invertMat4(y).transpose();const[L,O,D,N,k,A,M,R,F]=bS.data;let U,B,z;for(let $=0;$<P;$+=i.numComponents)U=I[$],B=I[$+1],z=I[$+2],I[$]=U*L+B*N+z*M,I[$+1]=U*O+B*k+z*R,I[$+2]=U*D+B*A+z*F}}}if(t){i=h[Bs];for(let I=0;I<n;I++)i.buffer[i.count++]=b}if(a.primitive[0].indexed){p=a.primitive[0].base,m=a.primitive[0].baseVertex||0,_=a.primitive[0].count;const I=a.indexBuffer[0].getFormat();g=new vg[I](a.indexBuffer[0].storage)}else{m=0;const I=a.primitive[0].type;if(I===qa||I===Tr)if(a.primitive[0].count===4)p=0,_=6,g=I===qa?c1:h1;else{_=0;continue}}for(let I=0;I<_;I++)T[I+x]=g[p+I]+m+v;x+=_,v+=n}a=new at(this.device);for(r in h)i=h[r],a.setVertexStream(r,i.buffer,i.numComponents,void 0,i.dataType,i.normalize);T.length>0&&a.setIndices(T),a.update(qs,!1),t&&(d=d.clone(),d.update());const w=new Ne(a,d,this.rootNode);w.castShadow=o.origMeshInstances[0].castShadow,w.parameters=o.origMeshInstances[0].parameters,w.layer=o.origMeshInstances[0].layer,w._shaderDefs=o.origMeshInstances[0]._shaderDefs,w.batching=!0,w.cull=o.origMeshInstances[0].cull;const C=this._batchGroups[s];if(C&&C._ui&&(w.cull=!1),t){const b=[];for(let I=0;I<o.origMeshInstances.length;I++)b.push(o.origMeshInstances[I].node);w.skinInstance=new vS(this.device,b,this.rootNode)}w._updateAabb=!1,w.drawOrder=o.origMeshInstances[0].drawOrder,w.stencilFront=o.origMeshInstances[0].stencilFront,w.stencilBack=o.origMeshInstances[0].stencilBack,w.flipFacesFactor=Sp(o.origMeshInstances[0]),w.castShadow=o.origMeshInstances[0].castShadow,o.meshInstance=w,o.updateBoundingBox()}return o}updateAll(){this._dirtyGroups.length>0&&this.generate(this._dirtyGroups);for(let e=0;e<this._batchList.length;e++)this._batchList[e].dynamic&&this._batchList[e].updateBoundingBox()}clone(e,t){const s=new _S(t,e.dynamic,e.batchGroupId);this._batchList.push(s);const i=[];for(let r=0;r<t.length;r++)i.push(t[r].node);return s.meshInstance=new Ne(e.meshInstance.mesh,e.meshInstance.material,e.meshInstance.node),s.meshInstance._updateAabb=!1,s.meshInstance.parameters=t[0].parameters,s.meshInstance.cull=t[0].cull,s.meshInstance.layer=t[0].layer,e.dynamic&&(s.meshInstance.skinInstance=new vS(this.device,i,this.rootNode)),s.meshInstance.castShadow=e.meshInstance.castShadow,s}destroyBatch(e){e.destroy(this.scene,this._batchGroups[e.batchGroupId].layers)}}const PS="uSceneColorMap";class f1 extends gn{colorRenderTarget=null;source=null;destroy(){super.destroy(),this.releaseRenderTarget(this.colorRenderTarget)}shouldReallocate(e,t,s){if(e?.colorBuffer.format!==s)return!0;const r=t?.width||this.device.width,a=t?.height||this.device.height;return!e||r!==e.width||a!==e.height}allocateRenderTarget(e,t,s,i){const r=new ce(s,{name:PS,format:i,width:t?t.colorBuffer.width:s.width,height:t?t.colorBuffer.height:s.height,mipmaps:!0,minFilter:ia,magFilter:It,addressU:ue,addressV:ue});return e?(e.destroyFrameBuffers(),e._colorBuffer=r,e._colorBuffers=[r],e.evaluateDimensions()):e=new St({name:"ColorGrabRT",colorBuffer:r,depth:!1,stencil:!1,autoResolve:!1}),e}releaseRenderTarget(e){e&&(e.destroyTextureBuffers(),e.destroy())}frameUpdate(){const e=this.device,t=this.source,s=t?.colorBuffer.format??this.device.backBufferFormat;
425this.shouldReallocate(this.colorRenderTarget,t?.colorBuffer,s)&&(this.releaseRenderTarget(this.colorRenderTarget),this.colorRenderTarget=this.allocateRenderTarget(this.colorRenderTarget,t,e,s));const i=this.colorRenderTarget.colorBuffer;e.scope.resolve(PS).setValue(i)}execute(){const e=this.device,t=this.source,s=this.colorRenderTarget.colorBuffer;e.isWebGPU?(e.copyRenderTarget(t,this.colorRenderTarget,!0,!1),e.mipmapRenderer.generate(this.colorRenderTarget.colorBuffer.impl)):(e.copyRenderTarget(t,this.colorRenderTarget,!0,!1),e.activeTexture(e.maxCombinedTextures-1),e.bindTexture(s),e.gl.generateMipmap(s.impl._glTarget))}}const IS="uSceneDepthMap";class p1 extends gn{depthRenderTarget=null;camera=null;constructor(e,t){super(e),this.camera=t}destroy(){super.destroy(),this.releaseRenderTarget(this.depthRenderTarget)}shouldReallocate(e,t){const s=t?.width||this.device.width,i=t?.height||this.device.height;return!e||s!==e.width||i!==e.height}allocateRenderTarget(e,t,s,i,r){const a=ce.createDataTexture2D(s,IS,t?t.colorBuffer.width:s.width,t?t.colorBuffer.height:s.height,i);return e?(e.destroyFrameBuffers(),r?e._depthBuffer=a:(e._colorBuffer=a,e._colorBuffers=[a]),e.evaluateDimensions()):e=new St({name:"DepthGrabRT",colorBuffer:r?null:a,depthBuffer:r?a:null,depth:!r,stencil:s.supportsStencil,autoResolve:!1}),e}releaseRenderTarget(e){e&&(e.destroyTextureBuffers(),e.destroy())}before(){const e=this.camera,t=this.device,s=e?.renderTarget??t.backBuffer;let i=!0,r=s.stencil?en:Oi;t.isWebGPU&&s.samples>1&&(r=Ti,i=!1);const a=e.renderTarget?.depthBuffer??e.renderTarget?.colorBuffer;this.shouldReallocate(this.depthRenderTarget,a)&&(this.releaseRenderTarget(this.depthRenderTarget),this.depthRenderTarget=this.allocateRenderTarget(this.depthRenderTarget,e.renderTarget,t,r,i));const n=i?this.depthRenderTarget.depthBuffer:this.depthRenderTarget.colorBuffer;t.scope.resolve(IS).setValue(n)}execute(){const e=this.device;if(e.isWebGL2&&e.renderTarget.samples>1){const t=e.renderTarget.impl._glFrameBuffer,s=this.depthRenderTarget;e.renderTarget=s,e.updateBegin(),this.depthRenderTarget.impl.internalResolve(e,t,s.impl._glFrameBuffer,this.depthRenderTarget,e.gl.DEPTH_BUFFER_BIT)}else e.copyRenderTarget(e.renderTarget,this.depthRenderTarget,!1,!0)}}class WT{_gammaCorrection=Ol;_toneMapping=bf;_srgbRenderTarget=!1;_ssaoEnabled=!1;_fog=vn;_sceneDepthMapLinear=!1;_hash;_defines=new Map;_definesDirty=!0;get hash(){if(this._hash===void 0){const e=`${this.gammaCorrection}_${this.toneMapping}_${this.srgbRenderTarget}_${this.fog}_${this.ssaoEnabled}_${this.sceneDepthMapLinear}`;this._hash=Xs(e)}return this._hash}get defines(){const e=this._defines;return this._definesDirty&&(this._definesDirty=!1,e.clear(),this._sceneDepthMapLinear&&e.set("SCENE_DEPTHMAP_LINEAR",""),this.shaderOutputGamma===Ol&&e.set("SCENE_COLORMAP_GAMMA",""),e.set("FOG",this._fog.toUpperCase()),e.set("TONEMAP",ET[this._toneMapping]),e.set("GAMMA",TI[this.shaderOutputGamma])),e}markDirty(){this._hash=void 0,this._definesDirty=!0}set fog(e){this._fog!==e&&(this._fog=e,this.markDirty())}get fog(){return this._fog}set ssaoEnabled(e){this._ssaoEnabled!==e&&(this._ssaoEnabled=e,this.markDirty())}get ssaoEnabled(){return this._ssaoEnabled}set gammaCorrection(e){this._gammaCorrectionAssigned=!0,this._gammaCorrection!==e&&(this._gammaCorrection=e,this.markDirty())}get gammaCorrection(){return this._gammaCorrection}set toneMapping(e){this._toneMapping!==e&&(this._toneMapping=e,this.markDirty())}get toneMapping(){return this._toneMapping}set srgbRenderTarget(e){this._srgbRenderTarget!==e&&(this._srgbRenderTarget=e,this.markDirty())}get srgbRenderTarget(){return this._srgbRenderTarget}set sceneDepthMapLinear(e){this._sceneDepthMapLinear!==e&&(this._sceneDepthMapLinear=e,this.markDirty())}get sceneDepthMapLinear(){return this._sceneDepthMapLinear}get shaderOutputGamma(){return this._gammaCorrection===Ol&&!this._srgbRenderTarget?Ol:qc}}const Ln=new E,dl=new E,DS=new E,MS=new Z,m1=[new E,new E,new E,new E,new E,new E,new E,new E];class cs{static _flipYProjectionMatrix=new Z().setScale(1,-1,1);static _webGpuDepthRangeMatrix=new Z().set([1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1]);static _applyShaderProjectionScratch=new Z;static applyShaderProjectionTransform(e,t,s,i){if(!s&&!i)return t.copy(e),t;if(s&&i){const r=cs._applyShaderProjectionScratch;return r.mul2(cs._flipYProjectionMatrix,e),t.mul2(cs._webGpuDepthRangeMatrix,r),t}return s?(t.mul2(cs._flipYProjectionMatrix,e),t):(t.mul2(cs._webGpuDepthRangeMatrix,e),t)}shaderPassInfo=null;renderPassColorGrab=null;renderPassDepthGrab=null;fogParams=null;shaderParams=new WT;framePasses=[];beforePasses=[];jitter=0;device;constructor(e){this.device=e,this._aspectRatio=16/9,this._aspectRatioMode=hu,this._calculateProjection=null,this._calculateTransform=null,this._clearColor=new Q(.75,.75,.75,1),this._clearColorBuffer=!0,this._clearDepth=1,this._clearDepthBuffer=!0,this._clearStencil=0,this._clearStencilBuffer=!0,this._cullFaces=!0,this._farClip=1e3,this._flipFaces=!1,this._fov=45,this._frustumCulling=!0,this._horizontalFov=!1,this._layers=[Ir,ks,Pg,Ef,Ig],this._layersSet=new Set(this._layers),this._nearClip=.1,this._node=null,this._orthoHeight=10,this._projection=mi,this._rect=new ie(0,0,1,1),this._renderTarget=null,this._scissorRect=new ie(0,0,1,1),this._scissorRectClear=!1,this._aperture=16,this._shutter=1/1e3,this._sensitivity=1e3,this._projMat=new Z,this._projMatDirty=!0,this._projMatSkybox=new Z,this._viewMat=new Z,this._viewMatDirty=!0,this._viewProjMat=new Z,this._viewProjMatDirty=!0,this._shaderMatricesVersion=0,this._viewProjInverse=new Z,this._viewProjCurrent=null,this._viewProjPrevious=new Z,this._jitters=[0,0,0,0],this.frustum=new X_,this._xr=null,this._xrProperties={horizontalFov:this._horizontalFov,fov:this._fov,aspectRatio:this._aspectRatio,farClip:this._farClip,nearClip:this._nearClip}}destroy(){this.renderPassColorGrab?.destroy(),this.renderPassColorGrab=null,this.renderPassDepthGrab?.destroy(),this.renderPassDepthGrab=null,this.framePasses.length=0}_storeShaderMatrices(e,t,s,i){this._shaderMatricesVersion!==i&&(this._shaderMatricesVersion=i,this._viewProjPrevious.copy(this._viewProjCurrent??e),this._viewProjCurrent??(this._viewProjCurrent=ne
425w Z),this._viewProjCurrent.copy(e),this._viewProjInverse.invert(e),this._jitters[2]=this._jitters[0],this._jitters[3]=this._jitters[1],this._jitters[0]=t,this._jitters[1]=s)}get fullSizeClearRect(){const e=this._scissorRectClear?this.scissorRect:this._rect;return e.x===0&&e.y===0&&e.z===1&&e.w===1}set aspectRatio(e){this._aspectRatio!==e&&(this._aspectRatio=e,this._projMatDirty=!0)}get aspectRatio(){if(this.xr?.active)return this._xrProperties.aspectRatio;if(this._aspectRatioMode===hu){const e=this.calculateAspectRatio();this._aspectRatio!==e&&(this._aspectRatio=e,this._projMatDirty=!0)}return this._aspectRatio}set aspectRatioMode(e){this._aspectRatioMode!==e&&(this._aspectRatioMode=e,this._projMatDirty=!0)}get aspectRatioMode(){return this._aspectRatioMode}set calculateProjection(e){this._calculateProjection=e,this._projMatDirty=!0}get calculateProjection(){return this._calculateProjection}set calculateTransform(e){this._calculateTransform=e}get calculateTransform(){return this._calculateTransform}set clearColor(e){this._clearColor.copy(e)}get clearColor(){return this._clearColor}set clearColorBuffer(e){this._clearColorBuffer=e}get clearColorBuffer(){return this._clearColorBuffer}set clearDepth(e){this._clearDepth=e}get clearDepth(){return this._clearDepth}set clearDepthBuffer(e){this._clearDepthBuffer=e}get clearDepthBuffer(){return this._clearDepthBuffer}set clearStencil(e){this._clearStencil=e}get clearStencil(){return this._clearStencil}set clearStencilBuffer(e){this._clearStencilBuffer=e}get clearStencilBuffer(){return this._clearStencilBuffer}set cullFaces(e){this._cullFaces=e}get cullFaces(){return this._cullFaces}set farClip(e){this._farClip!==e&&(this._farClip=e,this._projMatDirty=!0)}get farClip(){return this.xr?.active?this._xrProperties.farClip:this._farClip}set flipFaces(e){this._flipFaces=e}get flipFaces(){return this._flipFaces}set fov(e){this._fov!==e&&(this._fov=e,this._projMatDirty=!0)}get fov(){return this.xr?.active?this._xrProperties.fov:this._fov}set frustumCulling(e){this._frustumCulling=e}get frustumCulling(){return this._frustumCulling}set horizontalFov(e){this._horizontalFov!==e&&(this._horizontalFov=e,this._projMatDirty=!0)}get horizontalFov(){return this.xr?.active?this._xrProperties.horizontalFov:this._horizontalFov}set layers(e){this._layers=e.slice(0),this._layersSet=new Set(this._layers)}get layers(){return this._layers}get layersSet(){return this._layersSet}set nearClip(e){this._nearClip!==e&&(this._nearClip=e,this._projMatDirty=!0)}get nearClip(){return this.xr?.active?this._xrProperties.nearClip:this._nearClip}set node(e){this._node=e}get node(){return this._node}set orthoHeight(e){this._orthoHeight!==e&&(this._orthoHeight=e,this._projMatDirty=!0)}get orthoHeight(){return this._orthoHeight}set projection(e){this._projection!==e&&(this._projection=e,this._projMatDirty=!0)}get projection(){return this._projection}get projectionMatrix(){return this._evaluateProjectionMatrix(),this._projMat}set rect(e){this._rect.copy(e),this._projMatDirty=!0}get rect(){return this._rect}set renderTarget(e){this._renderTarget=e,this._projMatDirty=!0}get renderTarget(){return this._renderTarget}set scissorRect(e){this._scissorRect.copy(e)}get scissorRect(){return this._scissorRect}get viewMatrix(){if(this._viewMatDirty){const e=this._node.getWorldTransform();this._viewMat.copy(e).invert(),this._viewMatDirty=!1}return this._viewMat}set aperture(e){this._aperture=e}get aperture(){return this._aperture}set sensitivity(e){this._sensitivity=e}get sensitivity(){return this._sensitivity}set shutter(e){this._shutter=e}get shutter(){return this._shutter}set xr(e){this._xr!==e&&(this._xr=e,this._projMatDirty=!0)}get xr(){return this._xr}calculateAspectRatio(e){const t=e??this._renderTarget,s=t?t.width:this.device.width,i=t?t.height:this.device.height;return s*this._rect.z/(i*this._rect.w)}clone(){return new cs(this.device).copy(this)}copy(e){return this._aspectRatio=e._aspectRatio,this._farClip=e._farClip,this._fov=e._fov,this._horizontalFov=e._horizontalFov,this._nearClip=e._nearClip,this._xrProperties.aspectRatio=e._xrProperties.aspectRatio,this._xrProperties.farClip=e._xrProperties.farClip,this._xrProperties.fov=e._xrProperties.fov,this._xrProperties.horizontalFov=e._xrProperties.horizontalFov,this._xrProperties.nearClip=e._xrProperties.nearClip,this.aspectRatioMode=e.aspectRatioMode,this.calculateProjection=e.calculateProjection,this.calculateTransform=e.calculateTransform,this.clearColor=e.clearColor,this.clearColorBuffer=e.clearColorBuffer,this.clearDepth=e.clearDepth,this.clearDepthBuffer=e.clearDepthBuffer,this.clearStencil=e.clearStencil,this.clearStencilBuffer=e.clearStencilBuffer,this.cullFaces=e.cullFaces,this.flipFaces=e.flipFaces,this.frustumCulling=e.frustumCulling,this.layers=e.layers,this.orthoHeight=e.orthoHeight,this.projection=e.projection,this.rect=e.rect,this.renderTarget=e.renderTarget,this.scissorRect=e.scissorRect,this.aperture=e.aperture,this.shutter=e.shutter,this.sensitivity=e.sensitivity,this.shaderPassInfo=e.shaderPassInfo,this.jitter=e.jitter,this._projMatDirty=!0,this}_enableRenderPassColorGrab(e,t){t?this.renderPassColorGrab||(this.renderPassColorGrab=new f1(e)):(this.renderPassColorGrab?.destroy(),this.renderPassColorGrab=null)}
425_enableRenderPassDepthGrab(e,t,s){s?this.renderPassDepthGrab||(this.renderPassDepthGrab=new p1(e,this)):(this.renderPassDepthGrab?.destroy(),this.renderPassDepthGrab=null)}_updateViewProjMat(){(this._projMatDirty||this._viewMatDirty||this._viewProjMatDirty)&&(this._viewProjMat.mul2(this.projectionMatrix,this.viewMatrix),this._viewProjMatDirty=!1)}worldToScreen(e,t,s,i=new E){this._updateViewProjMat(),this._viewProjMat.transformPoint(e,i);const r=this._viewProjMat.data,a=e.x*r[3]+e.y*r[7]+e.z*r[11]+1*r[15];i.x=(i.x/a+1)*.5,i.y=(1-i.y/a)*.5;const{x:n,y:o,z:c,w:h}=this._rect;return i.x=i.x*c*t+n*t,i.y=i.y*h*s+(1-o-h)*s,i}screenToWorld(e,t,s,i,r,a=new E){const{x:n,y:o,z:c,w:h}=this._rect,d=this.farClip-this.nearClip;if(Ln.set((e-n*i)/(c*i),1-(t-(1-o-h)*r)/(h*r),s/d),Ln.mulScalar(2),Ln.sub(E.ONE),this._projection===mi){Z._getPerspectiveHalfSize(dl,this.fov,this.aspectRatio,this.nearClip,this.horizontalFov),dl.x*=Ln.x,dl.y*=Ln.y;const u=this._node.getWorldTransform();dl.z=-this.nearClip,u.transformPoint(dl,DS);const f=this._node.getPosition();a.sub2(DS,f),a.normalize(),a.mulScalar(s),a.add(f)}else this._updateViewProjMat(),MS.copy(this._viewProjMat).invert(),MS.transformPoint(Ln,a);return a}_evaluateProjectionMatrix(){const e=this.aspectRatio;if(this._projMatDirty){if(this._projection===mi)this._projMat.setPerspective(this.fov,e,this.nearClip,this.farClip,this.horizontalFov),this._projMatSkybox.copy(this._projMat);else{const t=this._orthoHeight,s=t*e;this._projMat.setOrtho(-s,s,-t,t,this.nearClip,this.farClip),this._projMatSkybox.setPerspective(this.fov,e,this.nearClip,this.farClip)}this._projMatDirty=!1}}getProjectionMatrixSkybox(){return this._evaluateProjectionMatrix(),this._projMatSkybox}getExposure(){const e=Math.log2(this._aperture*this._aperture/this._shutter*100/this._sensitivity);return 1/(Math.pow(2,e)*1.2)}getScreenSize(e){if(this._projection===mi){const t=this._node.getPosition().distance(e.center);if(t<e.radius)return 1;const s=Math.asin(e.radius/t),i=Math.tan(s),r=Math.tan(this.fov/2*H.DEG_TO_RAD);return Math.min(i/r,1)}return H.clamp(e.radius/this._orthoHeight,0,1)}getFrustumCorners(e=this.nearClip,t=this.farClip){const s=this.fov*H.DEG_TO_RAD;let i,r;this.projection===mi?this.horizontalFov?(i=e*Math.tan(s/2),r=i/this.aspectRatio):(r=e*Math.tan(s/2),i=r*this.aspectRatio):(r=this._orthoHeight,i=r*this.aspectRatio);const a=m1;return a[0].x=i,a[0].y=-r,a[0].z=-e,a[1].x=i,a[1].y=r,a[1].z=-e,a[2].x=-i,a[2].y=r,a[2].z=-e,a[3].x=-i,a[3].y=-r,a[3].z=-e,this._projection===mi&&(this.horizontalFov?(i=t*Math.tan(s/2),r=i/this.aspectRatio):(r=t*Math.tan(s/2),i=r*this.aspectRatio)),a[4].x=i,a[4].y=-r,a[4].z=-t,a[5].x=i,a[5].y=r,a[5].z=-t,a[6].x=-i,a[6].y=r,a[6].z=-t,a[7].x=-i,a[7].y=-r,a[7].z=-t,a}setXrProperties(e){Object.assign(this._xrProperties,e),this._projMatDirty=!0}fillShaderParams(e){const t=this._farClip;return e[0]=1/t,e[1]=t,e[2]=this._nearClip,e[3]=this._projection===Sn?1:0,e}}const RS=new Z,LS=new Z,FS=new Z;class pr{static pointLightRotations=[new ae().setFromEulerAngles(0,90,180),new ae().setFromEulerAngles(0,-90,180),new ae().setFromEulerAngles(90,0,0),new ae().setFromEulerAngles(-90,0,0),new ae().setFromEulerAngles(0,180,180),new ae().setFromEulerAngles(0,0,180)];static create(e,t,s,i){const r=new cs(e);switch(r.node=new He(t),r.aspectRatio=1,r.aspectRatioMode=Zm,r._scissorRectClear=!0,s){case ot:r.node.setRotation(pr.pointLightRotations[i]),r.fov=90,r.projection=mi;break;case nt:r.projection=mi;break;case Te:r.projection=Sn;break}return r}static _spotCookieCamera=null;static evalSpotCookieMatrix(e){let t=pr._spotCookieCamera;t||(t=pr.create(e.device,"SpotCookieCamera",nt),pr._spotCookieCamera=t),t.fov=e._outerConeAngle*2;const s=t._node;s.setPosition(e._node.getPosition()),s.setRotation(e._node.getRotation()),s.rotateLocal(-90,0,0),RS.setTRS(s.getPosition(),s.getRotation(),E.ONE).invert(),LS.mul2(t.projectionMatrix,RS);const i=e.cookieMatrix,r=e.atlasViewport;return FS.setViewport(r.x,r.y,r.z,r.w),i.mul2(FS,LS),i}}const zs=new E,Ea=new Float32Array(6),_1=new E(-.5,0,0),g1=new E(0,0,.5),gt={POSITION_RANGE:0,DIRECTION_FLAGS:1,COLOR_ANGLES_BIAS:2,PROJ_MAT_0:3,ATLAS_VIEWPORT:3,PROJ_MAT_1:4,PROJ_MAT_2:5,PROJ_MAT_3:6,AREA_DATA_WIDTH:7,AREA_DATA_HEIGHT:8,COUNT:9},v1={LIGHTSHAPE_PUNCTUAL:`${Sr}u`,LIGHTSHAPE_RECT:`${pT}u`,LIGHTSHAPE_DISK:`${mT}u`,LIGHTSHAPE_SPHERE:`${_T}u`,LIGHT_COLOR_DIVIDER:`${Cd}.0`},OS=(l,e)=>Object.keys(l).map(t=>`#define {${e}${t}} ${l[t]}`).join(` 426`),BS=` 427 428 ${OS(gt,"CLUSTER_TEXTURE_")} 429 ${OS(v1,"")} 430`;class S1{areaLightsEnabled=!1;constructor(e){this.device=e,be.get(e,ze).set("lightBufferDefinesPS",BS),be.get(e,de).set("lightBufferDefinesPS",BS),this.cookiesEnabled=!1,this.shadowsEnabled=!1,this.areaLightsEnabled=!1,this.maxLights=255;const t=gt.COUNT;this.lightsFloat=new Float32Array(4*t*this.maxLights),this.lightsUint=new Uint32Array(this.lightsFloat.buffer),this.lightsTexture=this.createTexture(this.device,t,this.maxLights,mt,"LightsTexture"),this._lightsTextureId=this.device.scope.resolve("lightsTexture"),this.invMaxColorValue=0,this.invMaxAttenuation=0,this.boundsMin=new E,this.boundsDelta=new E}destroy(){this.lightsTexture?.destroy(),this.lightsTexture=null}createTexture(e,t,s,i,r){return new ce(e,{name:r,width:t,height:s,mipmaps:!1,format:i,addressU:ue,addressV:ue,type:Qs,magFilter:Fe,minFilter:Fe,anisotropy:1})}setBounds(e,t){this.boundsMin.copy(e),this.boundsDelta.copy(t)}uploadTextures(){this.lightsTexture.lock().set(this.lightsFloat),this.lightsTexture.unlock()}updateUniforms(){this._lightsTextureId.setValue(this.lightsTexture)}getSpotDirection(e,t){t._node.getWorldTransform().getY(e).mulScalar(-1),e.normalize()}getLightAreaSizes(e){const t=e._node.getWorldTransform();return t.transformVector(_1,zs),Ea[0]=zs.x,Ea[1]=zs.y,Ea[2]=zs.z,t.transformVector(g1,zs),Ea[3]=zs.x,Ea[4]=zs.y,Ea[5]=zs.z,Ea}addLightData(e,t){const s=e._type===nt,i=e.atlasViewportAllocated,r=this.cookiesEnabled&&!!e._cookie&&i,a=this.areaLightsEnabled&&e.shape!==Sr,n=this.shadowsEnabled&&e.castShadows&&i,o=e._node.getPosition();let c=null,h=null;s?n?c=e.getRenderData(null,0).shadowMatrix:r&&(c=pr.evalSpotCookieMatrix(e)):(n||r)&&(h=e.atlasViewport);const d=this.lightsFloat,u=this.lightsUint,f=t*this.lightsTexture.width*4;d[f+4*gt.POSITION_RANGE+0]=o.x,d[f+4*gt.POSITION_RANGE+1]=o.y,d[f+4*gt.POSITION_RANGE+2]=o.z,d[f+4*gt.POSITION_RANGE+3]=e.attenuationEnd;const p=e.clusteredData;if(u[f+4*gt.COLOR_ANGLES_BIAS+0]=p[0],u[f+4*gt.COLOR_ANGLES_BIAS+1]=p[1],u[f+4*gt.COLOR_ANGLES_BIAS+2]=p[2],e.castShadows){const m=e.getRenderData(null,0),_=e._getUniformBiasValues(m),g=Ja.float2Half(_.bias),v=Ja.float2Half(_.normalBias);u[f+4*gt.COLOR_ANGLES_BIAS+3]=g|v<<16}if(s&&(this.getSpotDirection(zs,e),d[f+4*gt.DIRECTION_FLAGS+0]=zs.x,d[f+4*gt.DIRECTION_FLAGS+1]=zs.y,d[f+4*gt.DIRECTION_FLAGS+2]=zs.z),u[f+4*gt.DIRECTION_FLAGS+3]=e.getClusteredFlags(n,r),c){const m=c.data;for(let _=0;_<16;_++)d[f+4*gt.PROJ_MAT_0+_]=m[_]}if(h&&(d[f+4*gt.ATLAS_VIEWPORT+0]=h.x,d[f+4*gt.ATLAS_VIEWPORT+1]=h.y,d[f+4*gt.ATLAS_VIEWPORT+2]=h.z/3),a){const m=this.getLightAreaSizes(e);d[f+4*gt.AREA_DATA_WIDTH+0]=m[0],d[f+4*gt.AREA_DATA_WIDTH+1]=m[1],d[f+4*gt.AREA_DATA_WIDTH+2]=m[2],d[f+4*gt.AREA_DATA_HEIGHT+0]=m[3],d[f+4*gt.AREA_DATA_HEIGHT+1]=m[4],d[f+4*gt.AREA_DATA_HEIGHT+2]=m[5]}}}const y1=new j,Ah=new E,Ph=new E,Ih=new E,yp=new Le;class NS{constructor(){this.light=null,this.min=new E,this.max=new E}}class t_{clusterTexture;constructor(e){this.device=e,this.name="Untitled",this.reportCount=0,this.boundsMin=new E,this.boundsMax=new E,this.boundsDelta=new E,this._cells=new E(1,1,1),this._cellsLimit=new E,this.cells=this._cells,this.maxCellLightCount=4,this._usedLights=[],this._usedLights.push(new NS),this.lightsBuffer=new S1(e),this.registerUniforms(e)}set maxCellLightCount(e){e!==this._maxCellLightCount&&(this._maxCellLightCount=e,this._cellsDirt
430y=!0)}get maxCellLightCount(){return this._maxCellLightCount}set cells(e){Ah.copy(e).floor(),this._cells.equals(Ah)||(this._cells.copy(Ah),this._cellsLimit.copy(Ah).sub(E.ONE),this._cellsDirty=!0)}get cells(){return this._cells}destroy(){this.lightsBuffer.destroy(),this.releaseClusterTexture()}releaseClusterTexture(){this.clusterTexture&&(this.clusterTexture.destroy(),this.clusterTexture=null)}registerUniforms(e){this._numClusteredLightsId=e.scope.resolve("numClusteredLights"),this._clusterMaxCellsId=e.scope.resolve("clusterMaxCells"),this._clusterWorldTextureId=e.scope.resolve("clusterWorldTexture"),this._clusterBoundsMinId=e.scope.resolve("clusterBoundsMin"),this._clusterBoundsMinData=new Float32Array(3),this._clusterBoundsDeltaId=e.scope.resolve("clusterBoundsDelta"),this._clusterBoundsDeltaData=new Float32Array(3),this._clusterCellsCountByBoundsSizeId=e.scope.resolve("clusterCellsCountByBoundsSize"),this._clusterCellsCountByBoundsSizeData=new Float32Array(3),this._clusterCellsDotId=e.scope.resolve("clusterCellsDot"),this._clusterCellsDotData=new Int32Array(3),this._clusterCellsMaxId=e.scope.resolve("clusterCellsMax"),this._clusterCellsMaxData=new Int32Array(3),this._clusterTextureWidthId=e.scope.resolve("clusterTextureWidth")}updateParams(e){e&&(this.cells=e.cells,this.maxCellLightCount=e.maxLightsPerCell,this.lightsBuffer.cookiesEnabled=e.cookiesEnabled,this.lightsBuffer.shadowsEnabled=e.shadowsEnabled,this.lightsBuffer.areaLightsEnabled=e.areaLightsEnabled)}updateCells(){if(this._cellsDirty){this._cellsDirty=!1;const e=this._cells.x,t=this._cells.y,s=this._cells.z,i=e*t*s,r=this.maxCellLightCount*i,{x:a,y:n}=Xt.calcTextureSize(r,y1,this.maxCellLightCount);this._clusterCellsMaxData[0]=e,this._clusterCellsMaxData[1]=t,this._clusterCellsMaxData[2]=s,this._clusterCellsDotData[0]=this.maxCellLightCount,this._clusterCellsDotData[1]=e*s*this.maxCellLightCount,this._clusterCellsDotData[2]=e*this.maxCellLightCount,this.clusters=new Uint8ClampedArray(r),this.counts=new Int32Array(i),this.releaseClusterTexture(),this.clusterTexture=this.lightsBuffer.createTexture(this.device,a,n,Uu,"ClusterTexture")}}
430uploadTextures(){this.clusterTexture.lock().set(this.clusters),this.clusterTexture.unlock(),this.lightsBuffer.uploadTextures()}updateUniforms(){this._numClusteredLightsId.setValue(this._usedLights.length),this.lightsBuffer.updateUniforms(),this._clusterWorldTextureId.setValue(this.clusterTexture),this._clusterMaxCellsId.setValue(this.maxCellLightCount);const e=this.boundsDelta;this._clusterCellsCountByBoundsSizeData[0]=this._cells.x/e.x,this._clusterCellsCountByBoundsSizeData[1]=this._cells.y/e.y,this._clusterCellsCountByBoundsSizeData[2]=this._cells.z/e.z,this._clusterCellsCountByBoundsSizeId.setValue(this._clusterCellsCountByBoundsSizeData),this._clusterBoundsMinData[0]=this.boundsMin.x,this._clusterBoundsMinData[1]=this.boundsMin.y,this._clusterBoundsMinData[2]=this.boundsMin.z,this._clusterBoundsDeltaData[0]=e.x,this._clusterBoundsDeltaData[1]=e.y,this._clusterBoundsDeltaData[2]=e.z,this._clusterBoundsMinId.setValue(this._clusterBoundsMinData),this._clusterBoundsDeltaId.setValue(this._clusterBoundsDeltaData),this._clusterCellsDotId.setValue(this._clusterCellsDotData),this._clusterCellsMaxId.setValue(this._clusterCellsMaxData),this._clusterTextureWidthId.setValue(this.clusterTexture.width)}evalLightCellMinMax(e,t,s){t.copy(e.min),t.sub(this.boundsMin),t.div(this.boundsDelta),t.mul2(t,this.cells),t.floor(),s.copy(e.max),s.sub(this.boundsMin),s.div(this.boundsDelta),s.mul2(s,this.cells),s.ceil(),t.max(E.ZERO),s.min(this._cellsLimit)}collectLights(e){const t=this.lightsBuffer.maxLights,s=this._usedLights;let i=1;e.forEach(r=>{const a=!!(r.mask&(Js|ur)),n=r.type===nt&&r._outerConeAngle===0;if(r.enabled&&r.type!==Te&&r.visibleThisFrame&&r.intensity>0&&a&&!n&&i<t){let o;i<s.length?o=s[i]:(o=new NS,s.push(o)),o.light=r,r.getBoundingBox(yp),o.min.copy(yp.getMin()),o.max.copy(yp.getMax()),i++}}),s.length=i}evaluateBounds(){const e=this._usedLights,t=this.boundsMin,s=this.boundsMax;if(e.length>1){t.copy(e[1].min),s.copy(e[1].max);for(let i=2;i<e.length;i++)t.min(e[i].min),s.max(e[i].max)}else t.set(0,0,0),s.set(1,1,1);this.boundsDelta.sub2(s,t),this.lightsBuffer.setBounds(t,this.boundsDelta)}updateClusters(e){this.counts.fill(0),this.clusters.fill(0),this.lightsBuffer.areaLightsEnabled=e?e.areaLightsEnabled:!1;const t=this._cells.x,s=this._cells.z,i=this.counts,r=this._maxCellLightCount,a=this.cluster
430s,n=this.maxCellLightCount,o=this._usedLights;for(let c=1;c<o.length;c++){const h=o[c],d=h.light;this.lightsBuffer.addLightData(d,c),this.evalLightCellMinMax(h,Ph,Ih);const u=Ph.x,f=Ih.x,p=Ph.y,m=Ih.y,_=Ph.z,g=Ih.z;for(let v=u;v<=f;v++)for(let x=_;x<=g;x++)for(let y=p;y<=m;y++){const S=v+t*(x+y*s),T=i[S];T<r&&(a[n*S+T]=c,i[S]=T+1)}}}update(e,t=null){this.updateParams(t),this.updateCells(),this.collectLights(e),this.evaluateBounds(),this.updateClusters(t),this.uploadTextures()}activate(){this.updateUniforms()}}const x1="muPIHORMLNDCz4DxVR/ZvYfAUVEFR47KRIC4nwAAAAAP7WxlhD6Ci+2HCe7BF8jRAPZwdH2UPpI5PdLCJdkvG4UTaNDJ/0crAzne71GCrb4kbdMjjCEGzdX6fNxDMLJq5xkeoIVTdfiZkodEeArmZmp/FQzFjD4x8iOW7Dg64n+3mWqyEwLxXT8zoJXfbw8QJKDCaarUYyTlMzNFHbgUe9IQV7g4YOgtSKpIFZJ0qERm7u4PpmiF89ktHWCywaGmD6h+hfh2/Zd8KYlKqqo4Cem4T42bT/Z9FpCQF1hhSjfBzZ5XFn/y3jegWC6u86KuELRundQS/1Rp+XuKKGIgRv3CvP5y749yqLlFO495JOT3+f2CXgd71npU0/KjjpkZucbJ5m78IVyuSrSozc9jgBUhDrz0hFsyb7LFUH9//wJbBgLdNWJZObfKxrNt8TliLA9w9sXFv6g26iXpf6r/BqcAusj/QzGBZuoUGeEtw8BCXCZ3jUiw4hvM18ZVqlUD3C40LAFXW6FRjuAZGRNstb0/qVk4skwyT+MHrvRorI4rKHVMWZmKyAkzL/78u/9pMQuX14pZN50b2PHn6fRxeaCQLsfT4dpvIkWWFuFVENZIh+8xgR6lU+85W0PPdAu1j99kcCG40JBQa4JMyRzq6qriOBLtqF87vpCJan0WEduVr/mOYkS00urVA0mA6M3031+GmGmW48PaJDYOEIb3bIXWPaLoAOEinX1TN3+/vwhG6nqJu0TdHpedS7QsGZIoxH3nQYYjQP1jmbahlbNngw5ogsGk1y50XZyUmQBY+/JBJ3Unu4dApm+WmPwHPU9gLb+4mHh4BiY6M86pq+WeTyWdI3s0CXPEtHGXZ8zMZgUoyRomBi1VdazzuN+WOmQ9Pa0Z0tlNopUi8AJ4x2Xn4mmOKEbXLxlbVsWu8XhuDGYFOGCRVdSqDPXrHU5SDdUlti3k5///SBwzTMwK3L4a1H7w4lnpEas6////AfX8asyIBfeFXVJ3tgvxQ/blZuUKyIODIfr/UzdWNu7pciLBpdZRZ4pIfZ1R6szq+XNxkGG///8EZFpu7VHAhFWqHEOrB9unw+YQa5o8/9IR/V5/zq+986rJSyfgJKt2u9hxU1wzyQWPjJGvzG9+eWWxGFOHVKqI4jBQALwZZswesnvZ2UmmkEXdiRpz8B+oWE7PY70ZTMndisYSXg2TqoI+3y9BxbnY2Y4EfbdcRhAvG59NqDENNYbxKvK5HJfPG5M+Wi2AcpLVJrD6caiEOzgSoVNSgQK8fm2M3zGcF4xtClv/8Hs9oD7C3jitTATYNQxmKqKf1LhIxzf1bmfiNn7UKFmcJu4sLqVLwxGSue3taBEyknkw5hXTsUCvqmmL/f8n/w0giR7Hu/9EHvpkz3yuu64TioMkzdTJ30i0+hFnQqW1+v9mMwq+z9qGX0UFu9MomvVG2xod6vc12AAAAACq7sGa5qptFR0jF3nQt/D+7PibKYahaxP3hEixPbGi9nwNf2LAa7LkEZRKxzXeCD64Xpii5n+8Kpg8eHIv7AWXZltgMoGltmoJ0XGdOCL8WkzphvR9N2o3ARSZ42l5e5Pe4B58MCRlP3EKv+mcloknH+fto5BWsmEutW6KvjOVsznFCktkSczVk4aGvj9VXlRcLeDoKG8RkBgdcNG2bf8HUL4MT2DM+ar7NImJhKpxakX4Vk0CnP+/XNhl5UsP0lXgeZXPoDBMSW5An+DXlTCO5FQGwSPYwHLKYVIimEdAoVe49rQLaaNcye5LxU2/c5TijTgJtD5eQQIe1snxauj5jZsxJBUJdoP/zqpjqv8qBruoPsVsP8N44PCUW5Dd0DzqjSS/Dl5mI9cn1w2ndN/0KAEm1QAAAACwu6KM/083IBbH5bPa/9oHUwcU8I9v3j6/v18QYammrf+P6VL///8BrpuM3fOLCxaLNOFNF1zPbPYTP65ni6njft4eVcyrVXRQFrs52tr35StiSp55edVDCBC0H5rIfac6nzUwxQSt7y15QoKb+5zebEQUmVbrPjXuUa19Ey7sqXMiSUKHaw72PJKDdrutJoQr3u6lEYJ8K0MakWKj9zjTFi4X94TsKYco0GrLeB60M6D8M/80rhXUW8iMequg8y5F838WI0+gp3GBN5Kj/xIOxTWQuUaPV/LwvARr1VH93BFgGZR1MFW0Ua30GbYmdnAgo9VWy8SQtpDUgGE2r2zq2eTEMCL7sMKmE1hchVhuF/TCq9iXKEm86kzOf3Rp9ZnCxbpDUj+FKNxVyXe6pVZkRXv/m95SnB/EB8aME29N85MtAcDoXWlor8De2Q5Dg1tar+8wgiZufbMam81j//ASUohoR/zSh2KG4bvT6mkIPz6C5/98DC3LaWlaEZ1zA5JORZRu6J/a0GY285sEYzw71YqOT1ihAG0z5SDt1xNiDQWZdFpndArp6xWhqSDkRb4kSJEHb9liPvw7uLV/6i5MVf//A9Qjr8xkAEUh+KDI+zdtJ68d6MBOktg1iyp/SCq8O9f5pbamn1VVVQPRTWqNBvhQKa07s6P0lc9Luu/3gw4HeyOUfz8MxMwV4UQhua+t9cr4bz/nIB2wnDSK1K7I94M+s6C84htaX/CNlMQUSs2KJO+yaebfTbkNX5yWcqEJevo0vbKUiETuFXiL019A3E+lmsyZMwXrXLLiQAZ5t9+jI3JobhJTMiDH5ZOQ+8Jau5555NMjHSscP9qCVaa40doh+1a3Ukf6jqBmLddgh79/fwTfCyqiuldNkUoy+nUp+4nerwg0OjtGv2x485PJOJvUEokNhYIdWjpx7BWk0VZGWOp3jSFTJ2bnu6KCduZtG/UcBC9RZ3W/jMSfSMw4Etr/DoD/XYP2V5Ovw+YoM3F5g2dGLdvuG6ZkVGLE6Dk5Zr+sdSyGliJP1y2OFf/KFO0RWO+3gsGhesTnfZVpTd8/HwgO216gwaqo+vY3TljfJWowY+i0p0Os4SLn/1wLqDHMlszggmT/D8MRFzs+pLv6LNJSsNZ/r41mWi/rF6ZcKp/yzJdK0VU44hskq3RGpgO6mIpJDsf/mZkFrz0yYOMLbuaj/wp1v7JMFM5eqvBhmTd7U8frQAtHtys4zgpjZmzUhOVTfNNLifElGXADlqHGKrkBT/nYwX8ZRm3RjvyPvjKyEqEGKUpVnvOGx+NKPHiWM//ZDpDVGvvrjmk8RPF/wiYZD3+Us8YCXjrVOfjdd1UPAfjLp8jgSn4me7DPTpz1Ggy9XL80guFO7ECT10AvILKfD18Qx+KY/f8aRqu0oOO8hfKRFZa9PUJwCsp6VdZz6LFkm2b9Pl2LIifCwzRy7TpdG2uAtOxP2OemY26bJMa9ZGSLIRlMsgpDpnDJwd0oa5pQ13x1hrHf52HpulUWonGWsfXZbSQYKu9bnEN76ciQih0opN3deDVrbrxorfVlnCmL1R9zq3ePGWIv21c7pW8kEiFTM5JX8dAw867s/60cf79/BH+MDFCZBHlz1L+qGOJf/1txhhmrf3//As+RIJwevDb+fgNXVeHw67QptZegayhrEwr5Gy+EPo1RLaMtPbqOZYoVzXzwzjMFWZxyUG9YUIf6/
430///AQWy84iAygLk9COtXt92+0mT/xg0zMzMBeLkb8y9SL2TDXgSX422hDgpGNLJyuPioA+YJ91G8znrpNqHkwYyscaJDEc9Vc+j4cXle3hvcd2JqDQH2lBZxDn6mUTs0b75raMvbs727codX01Anj8f3wir9P2xQaQ22v/TxCMglKDFoTjaP01XTLgxnTvPv02JgEUrW6UDgOnobFpLdvKdlypgIzPcq14fgXU5tvVW0FEs7VRlsG1IyA69fN4n+awHhT34cE+xUvdj86C8LgAsFheTjI9Ht9EyYAAAAAAVBVKRx2wLgUTI0/2QfyJo2riRw3JDqzEShmx/Lifo6mRkQVbS7X53t+EvKxcXogtdts31e9MRHdcHgsA8rt4/mt2unlzQ/wsU8Gu7+W6Oj7eD8EQdDp5XlCsVaS/AV/t5ZpPOHR3rGpyAJe9IPV+xMrBL1Oz/8MQhFs31h0N1cVnq371uqIJYHyafKH1jteAK3VpMXBcuC+yt0ZeKyRUY4QhdrJJ4tJ1wg3Hu6kDsbovxupTMkGdRrm8oZSoYPbJ+PwH/xotgTdkA1205vUEfnqkI04T/fnnd1fiZW5AwNcggd7fi4j5zasmcntZexIxqFZQMzMJpfndmI5jn17cgn5EV5t9XN0C///8Q9wlJpMGXdoiaMTG2sVyHQsn8mWRISCLNG777S0OuDRP2GlLcJ2UeOg7Fo8hTNPeJ//iTJhyqxhKRUntdXOihq2wfKfH///8B0GGrwT+fSOQRdctKxjjGCSS11d6BlQ9BDfE0J6Z25FaNTKGpFKNCMr2G/041KpWwBLVe1k08vncseQbKZdXi8x1t9XA45U/Wd43D9wAh3Tal0aiLVzGPusOZ1F+W3TWoqlX/A95+dNef11TsuGful+ctGssldk3fqpfqh+43XTxL42+leSHoF/dWHYGX6maqUEuLX7UB+r/6Llr4LKocbVIeu+hB9QTPfz9fCP8RyWmX4SmbhMFsNtCijV7lVcwejLKlvl0GfCndnWV7/39VBrtTRuUx92oke3GBgKkC5fdGK0YvNK+xenKaDmsHDjNFUM3NMz3ZiXXFuLgojosPVCDEl2W5BjX3Ms+j0GSqACHmh0+RPWyuNm/Qe8vFf9AW7N1uRaxWirrUytqEJnJ4/Flm8hSoiZ2NQBsS6w/yQlC4gCaFo8q4nyY6AFdo4hiwhBXzbNKKvZvktCjSCukRR/BbYVbNwZi2Yh3hGodEacLW8qijiWJODf0P2bhfaiPspPT4lYJBgi/KfcFwCfvyUIgkJOv///8CG/JEepRBLaMFE+2TgrqsJXOVOWHt6g/bFwVLLMVBsMR50dis/39/AlBX+/rMTJkUQrnlxpR2iu0Tp8tATkRYGmDIrcAiRP8PjoWIlb7/0ecTdSCE9Y58+a+n/FovJQTVF4F2jAxMZhTgrM/KVS5BQu6bVbkWY5HXnxRshks3urDdW4RkWp4M4TeLmFK5KF/uHkkiO5Kv96RioH984v/CSDBnG+BwlnU9B+o7Y+0X0Nob+0pLsStxjvPXMy2eCpzhOWV4XbObBHN4UE2sLQ/DIqXhOzxVf38GlTi6aG7EnePO7TRJm9yOfUUcqq1I2iQHrVDqn3TUNRi/lMw8KbMW/3/nqCz/Ef8PoW5Qxcz2yHR/f78EPB2Stbd+ZFmfNTUYILzsb9YNhpaHcaymYrBiNHmFE3Y4ccYJ25Prqm7zHobGHED8/93ZNlWro9vcKivGZs31UiK1k5zjUhexUgbqJb+fUTjxce/7Zly8a5KMC1fX5nfjPgibdvzbXV1jRT2asXvmSAusaLdq1TSIJ8fXINk5AtT34EWPAsfP9IFQqM5K11O6saoHJA==";let or=null;const XT=()=>{if(!or){const l=atob(x1);or=Uint8Array.from(l,e=>e.charCodeAt(0))}},T1=()=>(XT(),or);class w1{seed=0;constructor(e=0){this.seed=e*4,XT()}_next(){this.seed=(this.seed+4)%or.length}value(){return this._next(),or[this.seed]/255}vec4(e=new ie){return this._next(),e.set(or[this.seed],or[this.seed+1],or[this.seed+2],or[this.seed+3]).mulScalar(1/255)}}const C1=[new E(-1,0,0),new E(1,0,0),new E(0,-1,0),new E(0,1,0),new E(0,0,-1),new E(0,0,1)];class E1{colors=new Float32Array(18);update(e,t){const s=this.colors,{r:i,g:r,b:a}=e;for(let n=0;n<6;n++)s[n*3]=i,s[n*3+1]=r,s[n*3+2]=a;for(let n=0;n<t.length;n++){const o=t[n];if(o._type===Te)for(let c=0;c<6;c++){const h=Math.max(C1[c].dot(o._direction),0)*o._intensity,d=o._color;s[c*3]+=d.r*h,s[c*3+1]+=d.g*h,s[c*3+2]+=d.b*h}}}}const b1=(l,e,t,s)=>{const i=new ce(l,{name:`${e}${t}`,width:t,height:t,format:Re,addressU:Ft,addressV:Ft,type:Qs,magFilter:Fe,minFilter:Fe,anisotropy:1,mipmaps:!1});return i.lock().set(s),i.unlock(),i},A1=new Jt,P1=l=>A1.get(l,()=>{const e=T1(),t=Math.sqrt(e.length/4);return b1(l,"BlueNoise",t,e)});class hn{constructor(e,t){this.texture=e,this.cached=!1,this.renderTargets=t}destroy(){this.texture&&(this.texture.destroy(),this.texture=null);const e=this.renderTargets;for(let t=0;t<e.length;t++)e[t].destroy();this.renderTargets.length=0}static create(e,t){let s=null;return t._type===ot?s=this.createCubemap(e,t._shadowResolution,t._shadowType):s=this.create2dMap(e,t._shadowResolution,t._shadowType),s}static createAtlas(e,t,s){const i=this.create2dMap(e,t,s),r=i.renderTargets,a=r[0];for(let n=0;n<5;n++)r.push(a);return i}static create2dMap(e,t,s){const i=yr.get(s);let r=i.format;r===Ti&&!e.textureFloatRenderable&&e.textureHalfFloatRenderable&&(r=kc);const a=fs.get(r)?.name;let n=It;s===Dg&&(n=e.extTextureFloatLinear?It:Fe),s===uc&&(n=Fe);const o=new ce(e,{format:r,width:t,height:t,mipmaps:!1,minFilter:n,magFilter:n,addressU:ue,addressV:ue,name:`ShadowMap2D_${a}`});let c=null;return i?.pcf?(o.compareOnRead=!0,o.compareFunc=Hd,c=new St({depthBuffer:o})):c=new St({colorBuffer:o,depth:!0}),e.isWebGPU&&(c.flipY=!0),new hn(o,[c])}static createCubemap(e,t,s){const i=yr.get(s),r=fs.get(i.format)?.name,a=s===uc,n=a?Fe:It,o=new ce(e,{format:i?.format,width:t,height:t,cubemap:!0,mipmaps:!1,minFilter:n,magFilter:n,addressU:ue,addressV:ue,name:`ShadowMapCube_${r}`});a||(o.compareOnRead=!0,o.compareFunc=Hd);const c=[];for(let h=0;h<6;h++)a?c.push(new St({colorBuffer:o,face:h,depth:!0})):c.push(new St({depthBuffer:o,face:h}));return new hn(o,c)}}
430const I1=[],D1=[],ji=new ie,xp=new ie;class Tp{constructor(e){this.size=Math.floor(e.w*1024),this.used=!1,this.lightId=-1,this.rect=e}}class M1{constructor(e){this.device=e,this.version=1,this.shadowAtlasResolution=2048,this.shadowAtlas=null,this.shadowEdgePixels=3,this.cookieAtlasResolution=4,this.cookieAtlas=ce.createDataTexture2D(this.device,"CookieAtlas",this.cookieAtlasResolution,this.cookieAtlasResolution,us),this.cookieRenderTarget=new St({colorBuffer:this.cookieAtlas,depth:!1,flipY:!0}),this.slots=[],this.atlasSplit=[],this.cubeSlotsOffsets=[new j(0,0),new j(0,1),new j(1,0),new j(1,1),new j(2,0),new j(2,1)],this.scissorVec=new ie,this.allocateShadowAtlas(1),this.allocateCookieAtlas(1),this.allocateUniforms()}destroy(){this.destroyShadowAtlas(),this.destroyCookieAtlas()}destroyShadowAtlas(){this.shadowAtlas?.destroy(),this.shadowAtlas=null}destroyCookieAtlas(){this.cookieAtlas?.destroy(),this.cookieAtlas=null,this.cookieRenderTarget?.destroy(),this.cookieRenderTarget=null}allocateShadowAtlas(e,t=Li){const s=this.shadowAtlas?.texture.format,i=yr.get(t).format;if(!this.shadowAtlas||this.shadowAtlas.texture.width!==e||s!==i){this.version++,this.destroyShadowAtlas(),this.shadowAtlas=hn.createAtlas(this.device,e,t),this.shadowAtlas.cached=!0;const r=4/this.shadowAtlasResolution;this.scissorVec.set(r,r,-2*r,-2*r)}}allocateCookieAtlas(e){this.cookieAtlas.width!==e&&(this.cookieRenderTarget.resize(e,e),this.version++)}allocateUniforms(){this._shadowAtlasTextureId=this.device.scope.resolve("shadowAtlasTexture"),this._shadowAtlasParamsId=this.device.scope.resolve("shadowAtlasParams"),this._shadowAtlasParams=new Float32Array(2),this._cookieAtlasTextureId=this.device.scope.resolve("cookieAtlasTexture")}updateUniforms(){const t=this.shadowAtlas.renderTargets[0].depthBuffer;this._shadowAtlasTextureId.setValue(t),this._shadowAtlasParams[0]=this.shadowAtlasResolution,this._shadowAtlasParams[1]=this.shadowEdgePixels,this._shadowAtlasParamsId.setValue(this._shadowAtlasParams),this._cookieAtlasTextureId.setValue(this.cookieAtlas)}subdivide(e,t){let s=t.atlasSplit;if(!s){const r=Math.ceil(Math.sqrt(e));s=D1,s[0]=r,s.length=1}if(!((r,a)=>r.length===a.length&&r.every((n,o)=>n===a[o]))(s,this.atlasSplit)){this.version++,this.slots.length=0,this.atlasSplit.length=0,this.atlasSplit.push(...s);const r=this.atlasSplit[0];if(r>1){const a=1/r;for(let n=0;n<r;n++)for(let o=0;o<r;o++){const c=new ie(n*a,o*a,a,a),h=this.atlasSplit[1+n*r+o];if(h>1)for(let d=0;d<h;d++)for(let u=0;u<h;u++){const f=a/h,p=new ie(c.x+d*f,c.y+u*f,f,f);this.slots.push(new Tp(p))}else this.slots.push(new Tp(c))}}else this.slots.push(new Tp(new ie(0,0,1,1)));this.slots.sort((a,n)=>n.size-a.size)}}collectLights(e,t){const s=t.cookiesEnabled,i=t.shadowsEnabled;let r=!1,a=!1;const n=I1;return n.length=0,(s||i)&&(c=>{for(let h=0;h<c.length;h++){const d=c[h];if(d.visibleThisFrame){const u=i&&d.castShadows,f=s&&!!d.cookie;r||(r=u),a||(a=f),(u||f)&&n.push(d)}}})(e),n.sort((c,h)=>h.maxScreenSize-c.maxScreenSize),r&&this.allocateShadowAtlas(this.shadowAtlasResolution,t.shadowType),a&&this.allocateCookieAtlas(this.cookieAtlasResolution),(r||a)&&this.subdivide(n.length,t),n}setupSlot(e,t){e.atlasViewport.copy(t);const s=e.numShadowFaces;for(let i=0;i<s;i++)if(e.castShadows||e._cookie){if(ji.copy(t),xp.copy(t),e._type===nt&&ji.add(this.scissorVec),e._type===ot){const r=ji.z/3,a=this.cubeSlotsOffsets[i];ji.x+=r*a.x,ji.y+=r*a.y,ji.z=r,ji.w=r,xp.copy(ji)}if(e.castShadows){const r=e.getRenderData(null,i);r.shadowViewport.copy(ji),r.shadowScissor.copy(xp)}}}assignSlot(e,t,s){e.atlasViewportAllocated=!0;const i=this.slots[t];i.lightId=e.id,i.used=!0,s&&(e.atlasSlotUpdated=!0,e.atlasVersion=this.version,e.atlasSlotIndex=t)}update(e,t){this.shadowAtlasResolution=t.shadowAtlasResolution,this.cookieAtlasResolution=t.cookieAtlasResolution;const s=this.collectLights(e,t);if(s.length>0){const i=this.slots;for(let n=0;n<i.length;n++)i[n].used=!1;const r=Math.min(s.length,i.length);for(let n=0;n<r;n++){const o=s[n];o.castShadows&&(o._shadowMap=this.shadowAtlas);const c=i[o.atlasSlotIndex];if(o.atlasVersion===this.version&&o.id===c?.lightId){const h=i[o.atlasSlotIndex];h.size===i[n].size&&!h.used&&this.assignSlot(o,o.atlasSlotIndex,!1)}}let a=0;for(let n=0;n<r;n++){for(;a<i.length&&i[a].used;)a++;const o=s[n];o.atlasViewportAllocated||this.assignSlot(o,a,!0);const c=i[o.atlasSlotIndex];this.setupSlot(o,c.rect)}}this.updateUniforms()}}const ws=[];ws[yg]={src:as,dst:as,op:CE};ws[Ns]={src:as,dst:Y_,op:vi};ws[Wi]={src:j_,dst:q_,op:vi,alphaSrc:as};ws[Ui]={src:as,dst:q_,op:vi};ws[nn]={src:as,dst:as,op:vi};ws[Tg]={src:j_,dst:as,op:vi};ws[wg]={src:Fx,dst:TE,op:vi};ws[Cg]={src:wE,dst:as,op:vi};ws[xg]={src:Fx,dst:Y_,op:vi};ws[Eg]={src:as,dst:as,op:EE};ws[bg]={src:as,dst:as,op:bE};let R1=0;class yn{meshInstances=new Set;name="Untitled";userId="";id=R1++;variants=new Map;defines=new Map;_definesDirty=!1;parameters={};alphaTest=0;alphaToCoverage=!1;_blendState=new xt;_depthState=new ds;cull=tc;frontFace=sc;stencilFront=null;stencilBack=null;_shaderChunks=null;_oldChunks={};_dirtyShader=!0;constructor(){}get hasShaderChunks(){return this._shaderChunks!=null}get shaderChunks(){return this._shaderChunks||(this._shaderChunks=new be),this._shaderChunks}getShaderChunks(e=ze){const t=this.shaderChunks;return e===ze?t.glsl:t.wgsl}set shaderChunksVersion(e){this.shaderChunks.version=e}get shaderChunksVersion(){return this.shaderChunks.version}set chunks(e){this._oldChunks=e}get chunks(){return Object.assign(this._oldChunks,Object.fromEntries(this.shaderChunks.glsl)),this._oldChunks}set depthBias(e){this._depthState.depthBias=e}get depthBias(){return this._depthState.depthBias}set slopeDepthBias(e){this._depthState.depthBiasSlope=e}get slopeDepthBias(){return this._depthState.depthBiasSlope}_shaderVersion=0;_scene=null;dirty=!0;set redWrite(e){this._blendState.redWrite=e}get redWrite(){return this._blendState.redWrite}set greenWrite(e){this._blendState.greenWrite=e}get greenWrite(){return this._blendState.greenWrite}set blueWrite(e){this._blendState.blueWrite=e}get blueWrite(){return this._blendState.blueWrite}set alphaWrite(e){this._blendState.alphaWrite=e}get alphaWrite(){return this._blendState.alphaWrite}
430get transparent(){return this._blendState.blend}_updateTransparency(){for(const e of this.meshInstances)e.transparent=this.transparent}set blendState(e){this._blendState.copy(e),this._updateTransparency()}get blendState(){return this._blendState}set blendType(e){const t=ws[e];this._blendState.setColorBlend(t.op,t.src,t.dst),this._blendState.setAlphaBlend(t.alphaOp??t.op,t.alphaSrc??t.src,t.alphaDst??t.dst);const s=e!==Ns;this._blendState.blend!==s&&(this._blendState.blend=s,this._updateTransparency()),this._updateMeshInstanceKeys()}get blendType(){if(!this.transparent)return Ns;const{colorOp:e,colorSrcFactor:t,colorDstFactor:s,alphaOp:i,alphaSrcFactor:r,alphaDstFactor:a}=this._blendState;for(let n=0;n<ws.length;n++){const o=ws[n];if(o.src===t&&o.dst===s&&o.op===e&&o.src===r&&o.dst===a&&o.op===i)return n}return Wi}set depthState(e){this._depthState.copy(e)}get depthState(){return this._depthState}set depthTest(e){this._depthState.test=e}get depthTest(){return this._depthState.test}set depthFunc(e){this._depthState.func=e}get depthFunc(){return this._depthState.func}set depthWrite(e){this._depthState.write=e}get depthWrite(){return this._depthState.write}copy(e){this.name=e.name,this.alphaTest=e.alphaTest,this.alphaToCoverage=e.alphaToCoverage,this._blendState.copy(e._blendState),this._depthState.copy(e._depthState),this.cull=e.cull,this.frontFace=e.frontFace,this.stencilFront=e.stencilFront?.clone(),e.stencilBack&&(this.stencilBack=e.stencilFront===e.stencilBack?this.stencilFront:e.stencilBack.clone()),this.clearParameters();for(const t in e.parameters)e.parameters.hasOwnProperty(t)&&this._setParameterSimple(t,e.parameters[t].data);return this.defines.clear(),e.defines.forEach((t,s)=>this.defines.set(s,t)),this._shaderChunks=e.hasShaderChunks?new be:null,this._shaderChunks?.copy(e._shaderChunks),this}clone(){return new this.constructor().copy(this)}_updateMeshInstanceKeys(){for(const e of this.meshInstances)e.updateKey()}updateUniforms(e,t){this._dirtyShader&&(this.clearVariants(),this._dirtyShader=!1)}getShaderVariant(e){}update(){if(Object.keys(this._oldChunks).length>0)for(const[e,t]of Object.entries(this._oldChunks))this.shaderChunks.glsl.set(e,t),delete this._oldChunks[e];(this._definesDirty||this._shaderChunks?.isDirty())&&(this._definesDirty=!1,this._shaderChunks?.resetDirty(),this.clearVariants()),this.dirty=!0}clearParameters(){this.parameters={}}getParameters(){return this.parameters}clearVariants(){this.variants.clear();for(const e of this.meshInstances)e.clearShaders()}getParameter(e){return this.parameters[e]}_setParameterSimple(e,t){const s=this.parameters[e];s?s.data=t:this.parameters[e]={scopeId:null,data:t}}setParameter(e,t){if(t===void 0&&typeof e=="object"){const s=e;if(s.length){for(let i=0;i<s.length;i++)this.setParameter(s[i]);return}e=s.name,t=s.value}this._setParameterSimple(e,t)}deleteParameter(e){this.parameters[e]&&delete this.parameters[e]}setParameters(e,t){const s=this.parameters;t===void 0&&(t=s);for(const i in t){const r=s[i];r&&(r.scopeId||(r.scopeId=e.scope.resolve(i)),r.scopeId.setValue(r.data))}}setDefine(e,t){let s=!1;const{defines:i}=this;t!==void 0&&t!==!1?(s=!i.has(e)||i.get(e)!==t,i.set(e,t)):(s=i.has(e),i.delete(e)),this._definesDirty||(this._definesDirty=s)}getDefine(e){return this.defines.has(e)}destroy(){this.variants.clear();for(const e of this.meshInstances)if(e.clearShaders(),e._material=null,e.mesh){const t=Zo(e.mesh.device);this!==t&&(e.material=t)}this.meshInstances.clear()}addMeshInstanceRef(e){this.meshInstances.add(e)}removeMeshInstanceRef(e){this.meshInstances.delete(e)}}class L1{constructor(){this.cache=new Map}destroy(){this.clear(),this.cache=null}clear(){this.cache.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.cache.clear()}getKey(e){const t=e._type===ot,s=e._shadowType,i=e._shadowResolution;return`${t}-${s}-${i}`}get(e,t){const s=this.getKey(t),i=this.cache.get(s);if(i&&i.length)return i.pop();const r=hn.create(e,t);return r.cached=!0,r}add(e,t){const s=this.getKey(e),i=this.cache.get(s);i?i.push(t):this.cache.set(s,[t])}}class YT extends Pr{constructor(e,t,s,i,r){super(e),this.requiresCubemaps=!1,this.shadowRenderer=t,this.light=s,this.face=i,this.applyVsm=r,this.shadowCamera=t.prepareFace(s,null,i),t.setupRenderPass(this,this.shadowCamera,!0)}execute(){this.shadowRenderer.renderFace(this.light,null,this.face,!1)}after(){this.applyVsm&&this.shadowRenderer.renderVsm(this.light,this.shadowCamera)}}class F1{shadowLights=[];renderer;shadowRenderer;device;constructor(e,t){this.renderer=e,this.shadowRenderer=t,this.device=e.device}cull(e,t,s=null){const i=this.renderer.scene.clusteredLightingEnabled;e.visibleThisFrame=!0,i||e._shadowMap||(e._shadowMap=hn.create(this.device,e));const r=e._type,a=r===nt?1:6;for(let n=0;n<a;n++){const o=e.getRenderData(null,n),c=o.shadowCamera;c.nearClip=e.attenuationEnd/1e3,c.farClip=e.attenuationEnd;const h=c._node,d=e._node;if(h.setPosition(d.getPosition()),r===nt)c.fov=e._outerConeAngle*2,h.setRotation(d.getRotation()),h.rotateLocal(-90,0,0);else if(r===ot)if(i){const p=2/(this.shadowRenderer.lightTextureAtlas.shadowAtlasResolution*e.atlasViewport.z/3)*this.shadowRenderer.lightTextureAtlas.shadowEdgePixels;c.fov=Math.atan(1+p)*H.RAD_TO_DEG*2}else c.fov=90;this.renderer.updateCameraFrustum(c),this.shadowRenderer.cullShadowCasters(t,e,o.visibleCasters,c,s)}}prepareLights(e,t){let s;for(let i=0;i<t.length;i++){const r=t[i];if(this.shadowRenderer.needsShadowRendering(r)&&r.atlasViewportAllocated){e.push(r);for(let a=0;a<r.numShadowFaces;a++)s=this.shadowRenderer.prepareFace(r,null,a)}}return s}buildNonClusteredRenderPasses(e,t){for(let s=0;s<t.length;s++){const i=t[s];if(this.shadowRenderer.needsShadowRendering(i)){const r=i._type===nt,a=i.numShadowFaces;for(let n=0;n<a;n++){const o=new YT(this.device,this.shadowRenderer,i,n,r);e.addRenderPass(o)}}}}}class O1 extends Pr{constructor(e,t,s,i,r){super(e),this.shadowRenderer=t,this.light=s,this.camera=i,this.allCascadesRendering=r}execute(){const{light:e,camera:t,shadowRenderer:s,allCascadesRendering:i}=this,r=e.numShadowFaces,a=e.shadowUpdateOverrides;for(let n=0;n<r;n++)a?.[n]!==Ks&&s.renderFace(e,t,n,!i),a?.[n]===ea&&(a[n]=Ks)}after(){this.shadowRenderer.renderVsm(this.light,this.camera)}}const Dh=new Le,qi=new E,kS=new Z,st=[new E,new E,new E,new E,new E,new E,new E,new E],wp={min:0,max:0};function B1(l,e,t){st[0].x=st[1].x=st[2].x=st[3].x=e.x,st[1].y=st[3].y=st[7].y=st[5].y=e.y,st[2].z=st[3].z=st[6].z=st[7].z=e.z,st[4].x=st[5].x=st[6].x=st[7].x=t.x,st[0].y=st[2].y=st[4].y=st[6].y=t.y,st[0].z=st[1].z=st[4].z=st[5].z=t.z;let s=9999999999,i=-9999999999;for(let r=0;r<8;++r){l.transformPoint(st[r],st[r]);const a=st[r].z;a<s&&(s=a),a>i&&(i=a)}return wp.min=s,wp.max=i,wp}class N1{renderer;shadowRenderer;device;constructor(e,t){this.renderer=e,this.shadowRenderer=t,this.device=e.device}cull(e,t,s,i=null){e.visibleThisFrame=!0,e._shadowMap||(e._shadowMap=hn.create(this.device,e));const r=s._nearClip;this.generateSplitDistances(e,r,Math.min(s._farClip,e.shadowDistance));const a=e.shadowUpdateOverrides;for(let n=0;n<e.numCascades&&a?.[n]!==Ks;n++){const o=e.getRenderData(s,n),c=o.shadowCamera;c.renderTarget=e._shadowMap.renderTargets[0],o.shadowViewport.copy(e.cascades[n]),o.shadowScissor.copy(e.cascades[n]);const h=c._node,d=e._node;h.setPosition(d.getPosition()),h.setRotation(d.getRotation()),h.rotateLocal(-90,0,0);const u=n===0?r:e._shadowCascadeDistances[n-1],f=e._shadowCascadeDistances[n],p=s.getFrustumCorners(u,f);qi.set(0,0,0);const m=s.node.getWorldTransform();for(let k=0;k<8;k++)m.transformPoint(p[k],p[k]),qi.add(p[k]);qi.mulScalar(1/8);let _=0;for(let k=0;k<8;k++){const A=p[k].sub(qi).length();A>_&&(_=A)}const g=h.right,v=h.up,x=h.forward,y=.25*e._shadowResolution/_,S=Math.ceil(qi.dot(v)*y)/y,T=Math.ceil(qi.dot(g)*y)/y,w=v.mulScalar(S),C=g.mulScalar(T),b=qi.dot(x),I=x.mulScalar(b);qi.add2(w,C).add(I),h.setPosition(qi),h.translateLocal(0,0,1e6),c.nearClip=.01,c.farClip=2e6,c.orthoHeight=_,this.renderer.updateCameraFrustum(c),this.shadowRenderer.cullShadowCasters(t,e,o.visibleCasters,c,i);const P=1<<n,L=o.visibleCasters,O=L.length;let D=0;for(let k=0;k<O;k++){const A=L[k];A.shadowCascadeMask&P&&(L[D++]=A,D===1?Dh.copy(A.aabb):Dh.add(A.aabb))}O!==D&&(L.length=D),kS.copy(h.getWorldTransform()).invert();const N=B1(kS,Dh.getMin(),Dh.getMax());h.translateLocal(0,0,N.max+.1),c.farClip=N.max-N.min+.2,o.projectionCompensation=_}}generateSplitDistances(e,t,s){e._shadowCascadeDistances.fill(s);for(let i=1;i<e.numCascades;i++){const r=i/e.numCascades,a=t+(s-t)*r,n=t*(s/t)**r,o=H.lerp(a,n,e.cascadeDistribution);e._shadowCascadeDistances[i-1]=o}}getLightRenderPass(e,t){let s=null;if(this.shadowRenderer.needsShadowRendering(e)){const i=e.numShadowFaces,r=e.shadowUpdateOverrides;let a=!0,n;for(let o=0;o<i;o++)r?.[o]===Ks&&(a=!1),n=this.shadowRenderer.prepareFace(e,t,o);s=new O1(this.device,this.shadowRenderer,e,t,a),this.shadowRenderer.setupRenderPass(s,n,a)}return s}}const Cp=new Set,US=new Z,zS=new Z,ba=new Float32Array(2),ul=new ie(1,1,0,0),VS=new Z;function k1(l,e){return Math.exp(-(l*l)/(2*e*e))}function U1(l){const e=(l-1)/6,t=(l-1)*.5,s=new Array(l);let i=0;for(let r=0;r<l;++r)s[r]=k1(r-t,e),i+=s[r];for(let r=0;r<l;++r)s[r]/=i;return s}class jT{shadowPassCache=[];constructor(e,t){this.device=e.device,this.renderer=e,this.lightTextureAtlas=t;const s=this.device.scope;this.sourceId=s.resolve("source"),this.pixelOffsetId=s.resolve("pixelOffset"),this.weightId=s.resolve("weight[0]"),this.blurVsmShader=[{},{}],this.blurVsmWeights={},this.shadowMapLightRadiusId=s.resolve("light_radius"),this.viewUniformFormat=null,this.viewBindGroupFormat=null,this.blendStateWrite=new xt,this.blendStateNoWrite=new xt,this.blendStateNoWrite.setColorWrite(!1,!1,!1,!1)}static createShadowCamera(e,t,s,i){const r=pr.create(e,kg,s,i),a=yr.get(t),n=a?.vsm??!1,o=a?.pcf??!1;return n?r.clearColor=new Q(0,0,0,0):r.clearColor=new Q(1,1,1,1),r.clearDepthBuffer=!0,r.clearStencilBuffer=!1,r.clearColorBuffer=!o,r}_cullShadowCastersInternal(e,t,s){const i=e.length;for(let r=0;r<i;r++){const a=e[r];a.castShadow&&(!a.cull||a._isVisible(s))&&(a.visibleThisFrame=!0,t.push(a))}}cullShadowCasters(e,t,s,i,r){if(this.renderer.scene?.fire(BT,i),s.length=0,r)this._cullShadowCastersInternal(r,s,i);else{const a=e.layerList,n=a.length;for(let o=0;o<n;o++){const c=a[o];c._lightsSet.has(t)&&(Cp.has(c)||(Cp.add(c),this._cullShadowCastersInternal(c.shadowCasters,s,i)))}Cp.clear()}s.sort(this.sortCompareShader),this.renderer.scene?.fire(NT,i)}sortCompareShader(e,t){const s=e._sortKeyShadow,i=t._sortKeyShadow;return s===i?t.mesh.id-e.mesh.id:i-s}setupRenderState(e,t){const i=this.renderer.scene.clusteredLightingEnabled?t._isPcf:t._isPcf&&t._type!==ot;e.setBlendState(i?this.blendStateNoWrite:this.blendStateWrite),e.setDepthState(t.shadowDepthState),e.setStencilState(null,null)}
430dispatchUniforms(e,t,s,i){const r=t._node;e._type!==Te&&(this.renderer.dispatchViewPos(r.getPosition()),this.shadowMapLightRadiusId.setValue(e.attenuationEnd)),US.setTRS(r.getPosition(),r.getRotation(),E.ONE).invert(),zS.mul2(t.projectionMatrix,US);const a=s.shadowViewport;t.rect=a,t.scissorRect=s.shadowScissor,VS.setViewport(a.x,a.y,a.z,a.w),s.shadowMatrix.mul2(VS,zS),e._type===Te&&e._shadowMatrixPalette.set(s.shadowMatrix.data,i*16)}getShadowPass(e){const t=e._type,s=e._shadowType;let i=this.shadowPassCache[t]?.[s];if(!i){const r=`ShadowPass_${t}_${s}`;i=zi.get(this.device).allocate(r,{isShadow:!0,lightType:t,shadowType:s}),this.shadowPassCache[t]||(this.shadowPassCache[t]=[]),this.shadowPassCache[t][s]=i}return i.index}submitCasters(e,t,s){const i=this.device,r=this.renderer,a=r.scene,n=1<<FT,o=this.getShadowPass(t),c=s.shaderParams,h=s.renderTarget.flipY?-1:1,d=e.length;for(let u=0;u<d;u++){const f=e[u],p=f.mesh,m=f.instancingData;if(m&&m.count<=0)continue;f.ensureMaterial(i);const _=f.material;r.setBaseConstants(i,_),r.setSkinning(i,f),_.dirty&&(_.updateUniforms(i,a),_.dirty=!1),r.setupCullModeAndFrontFace(!0,h,f),_.setParameters(i),f.setParameters(i,n);const g=f.getShaderInstance(o,0,a,c,this.viewUniformFormat,this.viewBindGroupFormat),v=g.shader;if(v.failed)continue;f._sortKeyShadow=v.id,i.setShader(v),r.setVertexBuffers(i,p),r.setMorphing(i,f.morphInstance),m&&i.setVertexBuffer(m.vertexBuffer),r.setMeshInstanceMatrices(f),r.setupMeshUniformBuffers(g);const x=f.renderStyle,y=f.getDrawCommands(s);i.draw(p.primitive[x],p.indexBuffer[x],m?.count,y),r._shadowDrawCalls++,m&&r._instancedDrawCalls++}
430}needsShadowRendering(e){const t=e.enabled&&e.castShadows&&e.shadowUpdateMode!==Ks&&e.visibleThisFrame;return e.shadowUpdateMode===ea&&(e.shadowUpdateMode=Ks),t&&(this.renderer._shadowMapUpdates+=e.numShadowFaces),t}getLightRenderData(e,t,s){return e.getRenderData(e._type===Te?t:null,s)}setupRenderPass(e,t,s){const i=t.renderTarget;e.init(i),e.depthStencilOps.clearDepthValue=1,e.depthStencilOps.clearDepth=s,i.depthBuffer?e.depthStencilOps.storeDepth=!0:(e.colorOps.clearValue.copy(t.clearColor),e.colorOps.clear=s,e.depthStencilOps.storeDepth=!1),e.requiresCubemaps=!1}prepareFace(e,t,s){const i=e._type,a=this.getLightRenderData(e,t,s).shadowCamera,n=i===Te?0:s;return a.renderTarget=e._shadowMap.renderTargets[n],a}renderFace(e,t,s,i){const r=this.device,a=this.getLightRenderData(e,t,s),n=a.shadowCamera;this.dispatchUniforms(e,n,a,s);const o=n.renderTarget,c=this.renderer;c.setCameraUniforms(n,o),r.supportsUniformBuffers&&c.setupViewUniformBuffers(a.viewBindGroups,this.viewUniformFormat,this.viewBindGroupFormat,null),c.setupViewport(n,o),i&&c.clear(n),this.setupRenderState(r,e),this.submitCasters(a.visibleCasters,e,n)}renderVsm(e,t){e._isVsm&&e._vsmBlurSize>1&&(!this.renderer.scene.clusteredLightingEnabled||e._type===Te)&&this.applyVsmBlur(e,t)}getVsmBlurShader(e,t){const s=this.blurVsmShader;let i=s[e][t];if(!i){this.blurVsmWeights[t]=U1(t);const r=new Map;r.set("{SAMPLES}",t),e===1&&r.set("GAUSS",""),i=Qt.createShader(this.device,{uniqueName:`blurVsm${e}${t}`,attributes:{vertex_position:Ie},vertexChunk:"fullscreenQuadVS",fragmentChunk:"blurVSMPS",fragmentDefines:r}),s[e][t]=i}return i}applyVsmBlur(e,t){const s=this.device;s.setBlendState(xt.NOBLEND);const a=e.getRenderData(e._type===Te?t:null,0).shadowCamera.renderTarget,n=this.renderer.shadowMapCache.get(s,e),o=n.renderTargets[0],c=e.vsmBlurMode,h=e._vsmBlurSize,d=this.getVsmBlurShader(c,h);ul.z=e._shadowResolution-2,ul.w=ul.z,this.sourceId.setValue(a.colorBuffer),ba[0]=1/e._shadowResolution,ba[1]=0,this.pixelOffsetId.setValue(ba),c===TT&&this.weightId.setValue(this.blurVsmWeights[h]),cn(s,o,d,null,ul),this.sourceId.setValue(o.colorBuffer),ba[1]=ba[0],ba[0]=0,this.pixelOffsetId.setValue(ba),cn(s,a,d,null,ul),this.renderer.shadowMapCache.add(e,n)}initViewBindGroupFormat(){this.device.supportsUniformBuffers&&!this.viewUniformFormat&&(this.viewUniformFormat=new vt(this.device,[new X("matrix_viewProjection",Ss)]),this.viewBindGroupFormat=new Ze(this.device,[new At(yf,rn|an)]))}frameUpdate(){this.initViewBindGroupFormat()}}class s_ extends gn{children=[];constructor(e){super(e),this.name="FramePassMultiView"}addChild(e){this.children.push(e)}render(){if(!this.enabled)return;const e=this.device,t=e.xrSubImages,s=t?.length??0,i=this.children,r=i.length;if(s===0){for(let h=0;h<r;h++)i[h].render();return}const a=e.backBuffer?.impl,n=e.xrColorTexture,o=a?.assignedColorTexture??null,c=a?.colorAttachments?.[0]?.format??null;for(let h=0;h<s;h++){const d=t[h];e.xrCurrentViewIndex=h,e.xrColorTexture=d.colorTexture,e.xrColorTextureViewDescriptor=d.viewDescriptor,a?.assignColorTexture?.(d.colorTexture,d.viewFormat);for(let u=0;u<r;u++)i[u].render()}e.xrCurrentViewIndex=-1,e.xrColorTextureViewDescriptor=null,e.xrColorTexture=n??null,a&&o&&c&&a.assignedColorTexture!==o&&a.assignColorTexture(o,c)}}const Mh=[];class z1{_empty=null;_allocated=[];_clusters=new Map;constructor(e){this.device=e}destroy(){this._empty&&(this._empty.destroy(),this._empty=null),this._allocated.forEach(e=>{e.destroy()}),this._allocated.length=0}get count(){return this._allocated.length}get empty(){if(!this._empty){const e=new t_(this.device);e.name="ClusterEmpty",e.update([]),this._empty=e}return this._empty}_assignClustersForPass(e){const t=e.renderActions;if(!t)return;const s=t.length;for(let i=0;i<s;i++){const r=t[i];r.lightClusters=null;const a=r.layer;if(a.hasClusteredLights&&a.meshInstances.length){const n=a.getLightIdHash();let c=this._clusters.get(n)?.lightClusters;c||(c=Mh.pop()??new t_(this.device),this._allocated.push(c),this._clusters.set(n,r)),r.lightClusters=c}r.lightClusters||(r.lightClusters=this.empty)}}assign(e){Mh.push(...this._allocated),this._allocated.length=0,this._cluster
430s.clear();const t=e.length;for(let s=0;s<t;s++){const i=e[s];if(i instanceof s_){const r=i.children;for(let a=0;a<r.length;a++)this._assignClustersForPass(r[a])}else this._assignClustersForPass(i)}Mh.forEach(s=>s.destroy()),Mh.length=0}update(e,t){this.assign(e),this._clusters.forEach(s=>{const i=s.layer;s.lightClusters.update(i.clusteredLightsSet,t)})}}const Ur=new ie,Ep=[];class Ug extends Pr{_quadRenderer2D=null;_quadRendererCube=null;_filteredLights=[];_forceCopy=!1;_evtDeviceRestored=null;constructor(e,t){super(e),this._cubeSlotsOffsets=t,this.requiresCubemaps=!1,this.blitTextureId=e.scope.resolve("blitTexture"),this.invViewProjId=e.scope.resolve("invViewProj"),this._evtDeviceRestored=e.on("devicerestored",this.onDeviceRestored,this)}destroy(){this._quadRenderer2D?.destroy(),this._quadRenderer2D=null,this._quadRendererCube?.destroy(),this._quadRendererCube=null,this._evtDeviceRestored?.off(),this._evtDeviceRestored=null}static create(e,t){const s=new Ug(e.device,t);return s.init(e),s.colorOps.clear=!1,s.depthStencilOps.clearDepth=!1,s}onDeviceRestored(){this._forceCopy=!0}update(e){const t=this._filteredLights;this.filter(e,t),this.executeEnabled=t.length>0}filter(e,t){for(let s=0;s<e.length;s++){const i=e[s];i._type!==Te&&i.atlasViewportAllocated&&(!i.atlasSlotUpdated&&!this._forceCopy||i.enabled&&i.cookie&&i.visibleThisFrame&&t.push(i))}this._forceCopy=!1}initInvViewProjMatrices(){if(!Ep.length)for(let e=0;e<6;e++){const t=pr.create(this.device,null,ot,e),s=t.projectionMatrix,i=t.node.getLocalTransform().clone().invert();Ep[e]=new Z().mul2(s,i).invert()}}get quadRenderer2D(){if(!this._quadRenderer2D){const e=Qt.createShader(this.device,{uniqueName:"cookieRenderer2d",attributes:{vertex_position:Ie},vertexChunk:"cookieBlitVS",fragmentChunk:"cookieBlit2DPS"});this._quadRenderer2D=new Uo(e)}return this._quadRenderer2D}get quadRendererCube(){if(!this._quadRendererCube){const e=Qt.createShader(this.device,{uniqueName:"cookieRendererCube",attributes:{vertex_position:Ie},vertexChunk:"cookieBlitVS",fragmentChunk:"cookieBlitCubePS"});this._quadRendererCube=new Uo(e)}return this._quadRendererCube}execute(){this.device.setDrawStates();const t=this.renderTarget.colorBuffer.width,s=this._cubeSlotsOffsets,i=this._filteredLights;for(let r=0;r<i.length;r++){const a=i[r],n=a.numShadowFaces,o=n>1?this.quadRendererCube:this.quadRenderer2D;n>1&&this.initInvViewProjMatrices(),this.blitTextureId.setValue(a.cookie);for(let c=0;c<n;c++){if(Ur.copy(a.atlasViewport),n>1){const h=Ur.z/3,d=s[c];Ur.x+=h*d.x,Ur.y+=h*d.y,Ur.z=h,Ur.w=h,this.invViewProjId.setValue(Ep[c].data)}Ur.mulScalar(t),o.render(Ur)}}i.length=0}}class qT extends Pr{constructor(e,t,s){super(e),this.requiresCubemaps=!1,this.shadowRenderer=t,this.shadowRendererLocal=s}update(e){const t=this.shadowRendererLocal.shadowLights,s=this.shadowRendererLocal.prepareLights(t,e),i=t.length;this.enabled=i>0,i&&this.shadowRenderer.setupRenderPass(this,s,!1)}execute(){const e=this.shadowRendererLocal.shadowLights,t=e.length;for(let s=0;s<t;s++){const i=e[s];for(let r=0;r<i.numShadowFaces;r++)this.shadowRenderer.renderFace(i,null,r,!0)}e.length=0}}class V1 extends gn{constructor(e,t,s,i,r){super(e),this.renderer=t,this.frameGraph=null,this.cookiesRenderPass=Ug.create(r.cookieRenderTarget,r.cubeSlotsOffsets),this.beforePasses.push(this.cookiesRenderPass),this.shadowRenderPass=new qT(e,s,i),this.beforePasses.push(this.shadowRenderPass)}update(e,t,s,i,r){this.frameGraph=e,this.cookiesRenderPass.enabled=s,s&&this.cookiesRenderPass.update(i),this.shadowRenderPass.enabled=t,t&&this.shadowRenderPass.update(r)}destroy(){this.cookiesRenderPass.destroy(),this.cookiesRenderPass=null}execute(){const{renderer:e}=this,{scene:t}=e;e.worldClustersAllocator.update(this.frameGraph.renderPasses,t.lighting)}}let bp=0;const Ii=new Z,zr=new Z,Fn=new Z,GS=new xi,Ap=new W_,HS=new X_,Pp=new Set,Ip=new Set,Dp=new Sg,Nl=[0,0,0,1],Rh={color:Nl,depth:1,stencil:0,flags:0},WS=[new j(.5,.333333),new j(.25,.666667),new j(.75,.111111),new j(.125,.444444),new j(.625,.777778),new j(.375,.222222),new j(.875,.555556),new j(.0625,.888889),new j(.5625,.037037),new j(.3125,.37037),new j(.8125,.703704),new j(.187
4305,.148148),new j(.6875,.481481),new j(.4375,.814815),new j(.9375,.259259),new j(.03125,.592593)],G1=new Z,H1=new Z,W1=new Z,X1=new Z,On=new Set,Mp=[],Rp=[];class Y1{clustersDebugRendered=!1;scene;processingMeshInstances=new Set;worldClustersAllocator;lights=[];localLights=[];cameraDirShadowLights=new Map;dirLightShadows=new Map;blueNoise=new w1(123);gsplatDirector=null;constructor(e,t){this.device=e,this.scene=t,this.worldClustersAllocator=new z1(e),this.lightTextureAtlas=new M1(e),this.shadowMapCache=new L1,this.shadowRenderer=new jT(this,this.lightTextureAtlas),this._shadowRendererLocal=new F1(this,this.shadowRenderer),this._shadowRendererDirectional=new N1(this,this.shadowRenderer),this.scene.clusteredLightingEnabled&&(this._renderPassUpdateClustered=new V1(this.device,this,this.shadowRenderer,this._shadowRendererLocal,this.lightTextureAtlas)),this.viewUniformFormat=null,this.viewBindGroupFormat=null,this._skinTime=0,this._morphTime=0,this._cullTime=0,this._shadowMapTime=0,this._lightClustersTime=0,this._layerCompositionUpdateTime=0,this._shadowDrawCalls=0,this._skinDrawCalls=0,this._instancedDrawCalls=0,this._shadowMapUpdates=0,this._numDrawCallsCulled=0,this._camerasRendered=0,this._lightClusters=0,this._gsplatCount=0;const s=e.scope;this.boneTextureId=s.resolve("texture_poseMap"),this.modelMatrixId=s.resolve("matrix_model"),this.normalMatrixId=s.resolve("matrix_normal"),this.viewInvId=s.resolve("matrix_viewInverse"),this.viewPos=new Float32Array(3),this.viewPosId=s.resolve("view_position"),this.projId=s.resolve("matrix_projection"),this.projSkyboxId=s.resolve("matrix_projectionSkybox"),this.viewId=s.resolve("matrix_view"),this.viewId3=s.resolve("matrix_view3"),this.viewProjId=s.resolve("matrix_viewProjection"),this.flipYId=s.resolve("projectionFlipY"),this.tbnBasis=s.resolve("tbnBasis"),this.cameraParams=new Float32Array(4),this.cameraParamsId=s.resolve("camera_params"),this.viewportSize=new Float32Array(4),this.viewportSizeId=s.resolve("viewport_size"),this.viewIndexId=s.resolve("view_index"),this.viewIndexId.setValue(0),this.blueNoiseJitterVersion=0,this.blueNoiseJitterVec=new ie,this.blueNoiseJitterData=new Float32Array(4),this.blueNoiseJitterId=s.resolve("blueNoiseJitter"),this.blueNoiseTextureId=s.resolve("blueNoiseTex32"),this.alphaTestId=s.resolve("alpha_ref"),this.opacityMapId=s.resolve("texture_opacityMap"),this.exposureId=s.resolve("exposure"),this.morphPositionTex=s.resolve("morphPositionTex"),this.morphNormalTex=s.resolve("morphNormalTex"),this.morphTexParams=s.resolve("morph_tex_params"),this.lightCube=new E1,this.constantLightCube=s.resolve("lightCube[0]")}destroy(){this.shadowRenderer=null,this._shadowRendererLocal=null,this._shadowRendererDirectional=null,this.shadowMapCache.destroy(),this.shadowMapCache=null,this._renderPassUpdateClustered?.destroy(),this._renderPassUpdateClustered=null,this.lightTextureAtlas.destroy(),this.lightTextureAtlas=null,this.gsplatDirector?.destroy(),this.gsplatDirector=null}setupViewport(e,t){const s=this.device,i=t?t.width:s.width,r=t?t.height:s.height,a=e.rect;let n=Math.floor(a.x*i),o=Math.floor(a.y*r),c=Math.floor(a.z*i),h=Math.floor(a.w*r);if(s.setViewport(n,o,c,h),e._scissorRectClear){const d=e.scissorRect;n=Math.floor(d.x*i),o=Math.floor(d.y*r),c=Math.floor(d.z*i),h=Math.floor(d.w*r)}s.setScissor(n,o,c,h)}setCameraUniforms(e,t){const s=t?.flipY;let i=null;if(e.xr&&e.xr.session){const o=e._node?.parent?.getWorldTransform()||null;i=e.xr.views.list;for(let h=0;h<i.length;h++)i[h].updateTransforms(o)}else{let o=e.projectionMatrix;e.calculateProjection&&e.calculateProjection(o,Ch);let c=e.getProjectionMatrixSkybox();const h=this.device.isWebGPU;o=cs.applyShaderProjectionTransform(o,G1,s,h),c=cs.applyShaderProjectionTransform(c,H1,s,h);const{jitter:d}=e;let u=0,f=0;if(d>0){const m=t?t.width:this.device.width,_=t?t.height:this.device.height,g=WS[this.device.renderVersion%WS.length];u=d*(g.x*2-1)/m,f=d*(g.y*2-1)/_,o=W1.copy(o),o.data[8]=u,o.data[9]=f,c=X1.copy(c),c.data[8]=u,c.data[9]=f,this.blueNoiseJitterVersion!==this.device.renderVersion&&(this.blueNoiseJitterVersion=this.device.renderVersion,this.blueNoise.vec4(this.blueNoiseJitterVec))}const p=d>0?this.blueNoiseJitterVec:ie.ZERO;if(this.blueNoiseJitterData[0]=p.x,this.blueNoiseJitterData[1]=p.y,this.blueNoiseJitterData[2]=p.z,this.blueNoiseJitterData[3]=p.w,this.blueNoiseJitterId.setValue(this.blueNoiseJitterData),this.projId.setValue(o.data),this.projSkyboxId.setValue(c.data),e.calculateTransform)e.calculateTransform(zr,Ch);else{const m=e._node.getPosition(),_=e._node.getRotation();zr.setTRS(m,_,E.ONE)}this.viewInvId.setValue(zr.data),Fn.copy(zr).invert(),this.viewId.setValue(Fn.data),GS.setFromMat4(Fn),this.viewId3.setValue(GS.data),Ii.mul2(o,Fn),this.viewProjId.setValue(Ii.data),e._storeShaderMatrices(Ii,u,f,this.device.renderVersion),this.flipYId.setValue(s?-1:1),this.dispatchViewPos(e._node.getPosition()),e.frustum.setFromMat4(Ii)}this.tbnBasis.setValue(s?-1:1),this.cameraParamsId.setValue(e.fillShaderParams(this.cameraParams));const r=e.xr?.session?e.xr.views.list[0]:null;let a=r?r.viewport.z:t?t.width:this.device.width,n=r?r.viewport.w:t?t.height:this.device.height;return a*=e.rect.z,n*=e.rect.w,this.viewportSize[0]=a,this.viewportSize[1]=n,this.viewportSize[2]=1/a,this.viewportSize[3]=1/n,this.viewportSizeId.setValue(this.viewportSize),this.exposureId.setValue(this.scene.physicalUnits?e.getExposure():this.scene.exposure),i}clear(e,t,s,i){const r=(t??e._clearColorBuffer?Jl:0)|(s??e._clearDepthBuffer?ec:0)|(i??e._clearStencilBuffer?Gd:0);if(r){const a=this.device,n=e._clearColor;Nl[0]=n.r,Nl[1]=n.g,Nl[2]=n.b,Nl[3]=n.a,Rh.depth=e._clearDepth,Rh.stencil=e._clearStencil,Rh.flags=r,a.clear(Rh)}}setupCullModeAndFrontFace(e,t,s){const i=s.material,r=t*s.flipFacesFactor*s.node.worldScaleSign;let a=i.frontFace;r<0&&(a=a===sc?LE:sc),this.device.setCullMode(e?i.cull:Yt),this.device.setFrontFace(a
430)}setupCullMode(e,t,s){this.setupCullModeAndFrontFace(e,t,s)}updateCameraFrustum(e){if(e.xr&&e.xr.views.list.length){const s=e.xr.views.list;Ii.mul2(s[0].projMat,s[0].viewOffMat),e.frustum.setFromMat4(Ii);for(let i=1;i<s.length;i++)Ii.mul2(s[i].projMat,s[i].viewOffMat),HS.setFromMat4(Ii),e.frustum.add(HS);return}const t=e.projectionMatrix;if(e.calculateProjection&&e.calculateProjection(t,Ch),e.calculateTransform)e.calculateTransform(zr,Ch);else{const s=e._node.getPosition(),i=e._node.getRotation();zr.setTRS(s,i,E.ONE),this.viewInvId.setValue(zr.data)}Fn.copy(zr).invert(),Ii.mul2(t,Fn),e.frustum.setFromMat4(Ii)}setBaseConstants(e,t){e.setCullMode(t.cull),e.setFrontFace(t.frontFace),t.opacityMap&&this.opacityMapId.setValue(t.opacityMap),(t.opacityMap||t.alphaTest>0)&&this.alphaTestId.setValue(t.alphaTest)}updateCpuSkinMatrices(e){bp++;const t=e.length;if(t!==0)for(let s=0;s<t;s++){const i=e[s].skinInstance;i&&(i.updateMatrices(e[s].node,bp),i._dirty=!0)}}updateGpuSkinMatrices(e){for(const t of e){const s=t.skinInstance;s&&s._dirty&&(s.updateMatrixPalette(t.node,bp),s._dirty=!1)}}updateMorphing(e){for(const t of e){const s=t.morphInstance;s&&s._dirty&&s.update()}}updateGSplats(e){for(const t of e)t.gsplatInstance?.update()}gpuUpdate(e){this.updateGpuSkinMatrices(e),this.updateMorphing(e),this.updateGSplats(e)}setVertexBuffers(e,t){e.setVertexBuffer(t.vertexBuffer)}setMorphing(e,t){t&&(t.prepareRendering(e),e.setVertexBuffer(t.morph.vertexBufferIds),this.morphPositionTex.setValue(t.texturePositions),this.morphNormalTex.setValue(t.textureNormals),this.morphTexParams.setValue(t._textureParams))}setSkinning(e,t){const s=t.skinInstance;if(s){this._skinDrawCalls++;const i=s.boneTexture;this.boneTextureId.setValue(i)}}dispatchViewPos(e){const t=this.viewPos;t[0]=e.x,t[1]=e.y,t[2]=e.z,this.viewPosId.setValue(t)}initViewBindGroupFormat(e){if(this.device.supportsUniformBuffers&&!this.viewUniformFormat){const t=[new X("matrix_view",Ss),new X("matrix_viewInverse",Ss),new X("matrix_projection",Ss),new X("matrix_projectionSkybox",Ss),new X("matrix_viewProjection",Ss),new X("matrix_view3",Do),new X("cubeMapRotationMatrix",Do),new X("view_position",hs),new X("viewport_size",Cr),new X("skyboxIntensity",me),new X("exposure",me),new X("textureBias",me),new X("view_index",me)];e&&t.push(new X("clusterCellsCountByBoundsSize",hs),new X("clusterBoundsMin",hs),new X("clusterBoundsDelta",hs),new X("clusterCellsDot",gr),new X("clusterCellsMax",gr),new X("shadowAtlasParams",sn),new X("clusterMaxCells",_r),new X("numClusteredLights",_r),new X("clusterTextureWidth",_r)),this.viewUniformFormat=new vt(this.device,t);const s=[new At(yf,rn|an)];this.viewBindGroupFormat=new Ze(this.device,s)}}setupViewUniforms(e,t){this.projId.setValue(e.projMat.data),this.projSkyboxId.setValue(e.projMat.data),this.viewId.setValue(e.viewOffMat.data),this.viewInvId.setValue(e.viewInvOffMat.data),this.viewId3.setValue(e.viewMat3.data),this.viewProjId.setValue(e.projViewOffMat.data),this.viewPosId.setValue(e.positionData),this.viewIndexId.setValue(t)}setupViewUniformBuffers(e,t,s,i){const{device:r}=this,a=i?.length??1;for(;e.length<a;){const n=new jc(r,t,!1),o=new jo(r,s,n);e.push(o)}if(i)for(let n=0;n<a;n++){const o=i[n];this.setupViewUniforms(o,n);const c=e[n];c.defaultUniformBuffer.update(),c.update()}else{const n=e[0];n.defaultUniformBuffer.update(),n.update()}i||r.setBindGroup(hc,e[0])}setupMeshUniformBuffers(e){const t=this.device;if(t.supportsUniformBuffers){const s=e.getBindGroup(t);s.update(),t.setBindGroup(Yc,s),e.getUniformBuffer(t).update(Dp),t.setBindGroup(Bo,Dp.bindGroup,Dp.offsets)}}setMeshInstanceMatrices(e,t=!1){const s=e.node.worldTransform;this.modelMatrixId.setValue(s.data),t&&this.normalMatrixId.setValue(e.node.normalMatrix.data)}cull(e,t,s){const i=s.opaque;i.length=0;const r=s.transparent;r.length=0;const a=e.frustumCulling,n=t.length;for(let o=0;o<n;o++){const c=t[o];c.visible&&(!a||!c.cull||c._isVisible(e))&&(c.visibleThisFrame=!0,(c.transparent?r
430:i).push(c),(c.skinInstance||c.morphInstance||c.gsplatInstance)&&(this.processingMeshInstances.add(c),c.gsplatInstance&&c.gsplatInstance.cameras.push(e)))}}collectLights(e){this.lights.length=0,this.localLights.length=0;const t=this.scene._stats,s=e.layerList.length;for(let i=0;i<s;i++){const r=e.layerList[i];if(!Ip.has(r)){Ip.add(r);const a=r._lights;for(let n=0;n<a.length;n++){const o=a[n];Pp.has(o)||(Pp.add(o),this.lights.push(o),o._type!==Te&&this.localLights.push(o))}}}t.lights=this.lights.length,Pp.clear(),Ip.clear()}cullLights(e,t){const s=this.scene.clusteredLightingEnabled,i=this.scene.physicalUnits;for(let r=0;r<t.length;r++){const a=t[r];if(a.enabled)if(a._type!==Te)if(a.getBoundingSphere(Ap),e.frustum.containsSphere(Ap)){a.visibleThisFrame=!0,a.usePhysicalUnits=i;const n=e.getScreenSize(Ap);a.maxScreenSize=Math.max(a.maxScreenSize,n)}else s||a.castShadows&&!a.shadowMap&&(a.visibleThisFrame=!0);else a.usePhysicalUnits=this.scene.physicalUnits}}cullShadowmaps(e){const t=this.scene.clusteredLightingEnabled;for(let i=0;i<this.localLights.length;i++){const r=this.localLights[i];r._type!==Te&&(t?r.atlasSlotUpdated&&r.shadowUpdateMode===Ks&&(r.shadowUpdateMode=ea):r.shadowUpdateMode===Ks&&r.castShadows&&(r.getRenderData(null,0).shadowCamera.renderTarget||(r.shadowUpdateMode=ea)),r.visibleThisFrame&&r.castShadows&&r.shadowUpdateMode!==Ks&&this._shadowRendererLocal.cull(r,e))}this.cameraDirShadowLights.clear();const s=e.cameras;for(let i=0;i<s.length;i++){const r=s[i];if(r.enabled){const a=r.camera;let n;const o=a.layers;for(let c=0;c<o.length;c++){const h=e.getLayerById(o[c]);if(h){const d=h.splitLights[Te];for(let u=0;u<d.length;u++){const f=d[u];f.castShadows&&!On.has(f)&&(On.add(f),n=n??[],n.push(f),this._shadowRendererDirectional.cull(f,e,a))}}}n&&this.cameraDirShadowLights.set(a,n),On.clear()}}}cullComposition(e){const{scene:t}=this;this.processingMeshInstances.clear();const s=e.cameras.length;this._camerasRendered+=s;for(let i=0;i<s;i++){const r=e.cameras[i],a=r.renderTarget;r.frameUpdate(a),this.updateCameraFrustum(r.camera),t?.fire(BT,r);const n=r.layers;for(let o=0;o<n.length;o++){const c=e.getLayerById(n[o]);if(c&&c.enabled){this.cullLights(r.camera,c._lights);const h=c.getCulledInstances(r.camera);this.cull(r.camera,c.meshInstances,h)}}t?.fire(NT,r)}t.clusteredLightingEnabled&&this.updateLightTextureAtlas(),this.cullShadowmaps(e),t?.fire(HI)}updateShaders(e,t){const s=e.length;for(let i=0;i<s;i++){const r=e[i].material;if(r&&!On.has(r)&&(On.add(r),r.getShaderVariant!==yn.prototype.getShaderVariant)){if(t&&(!r.useLighting||r.emitter&&!r.emitter.lighting))continue;r.clearVariants()}}On.clear()}updateFrameUniforms(){this.blueNoiseTextureId.setValue(P1(this.device))}beginFrame(e){const t=this.scene,s=t.updateShaders||this.device._shadersDirty,i=e.layerList,r=i.length;for(let o=0;o<r;o++){const h=i[o].meshInstances,d=h.length;for(let u=0;u<d;u++){const f=h[u];f.visibleThisFrame=!1,s&&Mp.push(f),f.skinInstance&&Rp.push(f)}}if(s){const o=!t.updateShaders||!this.device._shadersDirty;this.updateShaders(Mp,o),t.updateShaders=!1,this.device._shadersDirty=!1,t._shaderVersion++}this.updateFrameUniforms(),this.updateCpuSkinMatrices(Rp),Mp.length=0,Rp.length=0;const a=this.lights,n=a.length;for(let o=0;o<n;o++)a[o].beginFrame()}updateLightTextureAtlas(){this.lightTextureAtlas.update(this.localLights,this.scene.lighting)}updateLayerComposition(e){const t=e.layerList.length,i=this.scene._shaderVersion;for(let r=0;r<t;r++){const a=e.layerList[r];a._shaderVersion=i}e._update()}frameUpdate(){this.clustersDebugRendered=!1,this.initViewBindGroupFormat(this.scene.clusteredLightingEnabled),this.dirLightShadows.clear()}}class $T{camera=null;constructor(){this.layer=null,this.transparent=!1,this.renderTarget=null,this.lightClusters=null,this.clearColor=!1,this.clearDepth=!1,this.clearStencil=!1,this.triggerPostprocess=!1,this.firstCameraUse=!1,this.lastCameraUse=!1,this.viewBindGroups=[],this.useCameraPasses=!1}destroy(){this.viewBindGroups.forEach(e=>{e.defaultUniformBuffer.destroy(),e.destroy()}),this.viewBindGroups.length=0}setupClears(e,t){this.clearColor=e?.clearColorBuffer||t.clearColorBuffer,this.clearDepth=e?.clearDepthBuffer||t.clearDepthBuffer,this.clearStencil=e?.clearStencilBuffer||t.clearStencilBuffer}}class j1 extends Pr{layerComposition;scene;renderer;renderActions=[];gammaCorrection;toneMapping;noDepthClear=!1;constructor(e,t,s,i){super(e),this.layerComposition=t,this.scene=s,this.renderer=i}get rendersAnything(){return this.renderActions.length>0}addRenderAction(e){this.renderActions.push(e)}addLayer(e,t,s,i=!0){const r=new $T;if(r.renderTarget=this.renderTarget,r.camera=e,r.layer=t,r.transparent=s,i){const a=this.renderActions.length===0;r.setupClears(a?e:void 0,t)}this.addRenderAction(r)}addLayers(e,t,s,i,r,a=!0){const{layerList:n,subLayerList:o}=e;let c=i,h=s;for(;h<n.length;){const d=n[h],u=o[h];if(t.camera.layersSet.has(d.id)&&(this.addLayer(t,d,u,c),c=!1),h++,d.id===r&&u===a)break}return h}updateCameraBeforePasses(){for(let e=0;e<this.renderActions.length;e++){const t=this.renderActions[e];if(t.firstCameraUse){const s=t.camera?.camera;if(s){const{beforePasses:i}=s;for(let r=0;r<i.length;r++)this.beforePasses.push(i[r])}}}}updateDirectionalShadows(){const{renderer:e,renderActions:t}=this;for(let s=0;s<t.length;s++){const a=t[s].camera.camera,n=this.renderer.cameraDirShadowLights.get(a);if(n)for(let o=0;o<n.length;o++){const c=n[o];if(e.dirLightShadows.get(c)!==a){e.dirLightShadows.set(c,a);const h=e._shadowRendererDirectional.getLightRenderPass(c,a);h&&this.beforePasses.push(h)}}}}updateClears(){const e=this.renderActions[0];if(e){const s=e.camera.camera,i=s.fullSizeClearRect;this.setClearColor(i&&e.clearColor?s.clearColor:void 0),this.setClearDepth(i&&e.clearDepth&&!this.noDepthClear?s.clearDepth:void 0),this.setClearStencil(i&&e.clearStencil?s.clearStencil:void 0)}}frameUpdate(){super.frameUpdate(),this.updateCameraBeforePasses(),this.updateDirectionalShadows(),this.updateClears()}before(){const{renderActions:e}=this;for(let t=0;t<e.length;t++){const s=e[t];s.firstCameraUse&&this.scene.fire(UI,s.camera)}}execute(){const{layerComposition:e,renderActions:t}=this;for(let s=0;s<t.length;s++){const i=t[s],r=i.layer;e.isEnabled(r,i.transparent)&&this.renderRenderAction(i,s===0)}}after(){for(let e=0;e<this.renderActions.length;e++){const t=this.renderActions[e];t.lastCameraUse&&this.scene.fire(zI,t.camera)}this.beforePasses.length=0}renderRenderAction(e,t){const{renderer:s,scene:i}
430=this,r=s.device,{layer:a,transparent:n,camera:o}=e;if(o){const c=o.gammaCorrection,h=o.toneMapping;this.gammaCorrection!==void 0&&(o.gammaCorrection=this.gammaCorrection),this.toneMapping!==void 0&&(o.toneMapping=this.toneMapping),i.fire(VI,o,a,n);const d={lightClusters:e.lightClusters},u=o.camera.shaderPassInfo?.index??Ko;(!t||!o.camera.fullSizeClearRect)&&(d.clearColor=e.clearColor,d.clearDepth=e.clearDepth,d.clearStencil=e.clearStencil);const f=e.renderTarget??r.backBuffer;s.renderForwardLayer(o.camera,f,a,n,u,e.viewBindGroups,d),r.setBlendState(xt.NOBLEND),r.setStencilState(null,null),r.setAlphaToCoverage(!1),i.fire(GI,o,a,n),this.gammaCorrection!==void 0&&(o.gammaCorrection=c),this.toneMapping!==void 0&&(o.toneMapping=h)}}}class q1 extends gn{constructor(e,t,s){super(e),this.renderer=t,this.renderAction=s}execute(){this.renderAction.camera.onPostprocessing()}}const $1=[[],[],[]],Vr=new Q,Aa={drawCalls:[],shaderInstances:[],isNewMaterial:[],lightMaskChanged:[],clear:function(){this.drawCalls.length=0,this.shaderInstances.length=0,this.isNewMaterial.length=0,this.lightMaskChanged.length=0}};function K1(l){const e=[];for(let t=0;t<l;++t){const s=Math.sqrt(t+.5)/Math.sqrt(l);e.push(s)}return e}function Z1(l){const e=[];for(let t=0;t<l;t++){const s=t/l,i=Math.sqrt(s*s);e.push(i)}return e}class KT extends Y1{constructor(e,t){super(e,t);const s=this.device;this._forwardDrawCalls=0,this._materialSwitches=0,this._depthMapTime=0,this._forwardTime=0,this._sortTime=0;const i=s.scope;this.fogColorId=i.resolve("fog_color"),this.fogStartId=i.resolve("fog_start"),this.fogEndId=i.resolve("fog_end"),this.fogDensityId=i.resolve("fog_density"),this.ambientId=i.resolve("light_globalAmbient"),this.skyboxIntensityId=i.resolve("skyboxIntensity"),this.cubeMapRotationMatrixId=i.resolve("cubeMapRotationMatrix"),this.pcssDiskSamplesId=i.resolve("pcssDiskSamples[0]"),this.pcssSphereSamplesId=i.resolve("pcssSphereSamples[0]"),this.lightColorId=[],this.lightDir=[],this.lightDirId=[],this.lightShadowMapId=[],this.lightShadowMatrixId=[],this.lightShadowParamsId=[],this.lightShadowIntensity=[],this.lightRadiusId=[],this.lightPos=[],this.lightPosId=[],this.lightWidth=[],this.lightWidthId=[],this.lightHeight=[],this.lightHeightId=[],this.lightInAngleId=[],this.lightOutAngleId=[],this.lightCookieId=[],this.lightCookieIntId=[],this.lightCookieMatrixId=[],this.lightCookieOffsetId=[],this.lightShadowSearchAreaId=[],this.lightCameraParamsId=[],this.lightSoftShadowParamsId=[],this.shadowMatrixPaletteId=[],this.shadowCascadeDistancesId=[],this.shadowCascadeCountId=[],this.shadowCascadeBlendId=[],this.screenSizeId=i.resolve("uScreenSize"),this._screenSize=new Float32Array(4),this.fogColor=new Float32Array(3),this.ambientColor=new Float32Array(3),this.pcssDiskSamples=K1(16),this.pcssSphereSamples=Z1(16)}destroy(){super.destroy()}dispatchGlobalLights(e){const t=this.ambientColor;if(Vr.linear(e.ambientLight),t[0]=Vr.r,t[1]=Vr.g,t[2]=Vr.b,e.physicalUnits)for(let s=0;s<3;s++)t[s]*=e.ambientLuminance;this.ambientId.setValue(t),this.skyboxIntensityId.setValue(e.physicalUnits?e.skyboxLuminance:e.skyboxIntensity),this.cubeMapRotationMatrixId.setValue(e._skyboxRotationMat3.data)}_resolveLight(e,t){const s=`light${t}`;this.lightColorId[t]=e.resolve(`${s}_color`),this.lightDir[t]=new Float32Array(3),this.lightDirId[t]=e.resolve(`${s}_direction`),this.lightShadowMapId[t]=e.resolve(`${s}_shadowMap`),this.lightShadowMatrixId[t]=e.resolve(`${s}_shadowMatrix`),this.lightShadowParamsId[t]=e.resolve(`${s}_shadowParams`),this.lightShadowIntensity[t]=e.resolve(`${s}_shadowIntensity`),this.lightShadowSearchAreaId[t]=e.resolve(`${s}_shadowSearchArea`),this.lightRadiusId[t]=e.resolve(`${s}_radius`),this.lightPos[t]=new Float32Array(3),this.lightPosId[t]=e.resolve(`${s}_position`),this.lightWidth[t]=new Float32Array(3),this.lightWidthId[t]=e.resolve(`${s}_halfWidth`),this.lightHeight[t]=new Float32Array(3),this.lightHeightId[t]=e.resolve(`${s}_halfHeight`),this.lightInAngleId[t]=e.resolve(`${s}_innerConeAngle`),this.lightOutAngleId[t]=e.resolve(`${s}_outerConeAngle`),this.lightCookieId[t]=e.resolve(`${s}_cookie`),this.lightCookieIntId[t]=e.resolve(`${s}_cookieIntensity`),this.lightCookieMatrixId[t]=e.resolve(`${s}_cookieMatrix`),this.lightCookieOffsetId[t]=e.resolve(`${s}_cookieOffset`),this.lightCameraParamsId[t]=e.resolve(`${s}_cameraParams`),this.lightSoftShadowParamsId[t]=e.resolve(`${s}_softShadowParams`),this.shadowMatrixPaletteId[t]=e.resolve(`${s}_shadowMatrixPalette[0]`),this.shadowCascadeDistancesId[t]=e.resolve(`${s}_shadowCascadeDistances`),this.shadowCascadeCountId[t]=e.resolve(`${s}_shadowCascadeCount`),this.shadowCascadeBlendId[t]=e.resolve(`${s}_shadowCascadeBlend`)}setLTCDirectionalLight(e,t,s,i,r){this.lightPos[t][0]=i.x-s.x*r,this.lightPos[t][1]=i.y-s.y*r,this.lightPos[t][2]=i.z-s.z*r,this.lightPosId[t].setValue(this.lightPos[t]);const a=e.transformVector(new E(-.5,0,0));this.lightWidth[t][0]=a.x*r,this.lightWidth[t][1]=a.y*r,this.lightWidth[t][2]=a.z*r,this.lightWidthId[t].setValue(this.lightWidth[t]);const n=e.transformVector(new E(0,0,.5));this.lightHeight[t][0]=n.x*r,this.lightHeight[t][1]=n.y*r,this.lightHeight[t][2]=n.z*r,this.lightHeightId[t].setValue(this.lightHeight[t])}dispatchDirectLights(e,t,s){let i=0;const r=this.device.scope;for(let a=0;a<e.length;a++){if(!(e[a].mask&t))continue;const n=e[a],o=n._node.getWorldTransform();if(this.lightColorId[i]||this._resolveLight(r,i),this.lightColorId[i].setValue(n._c
430olorLinear),o.getY(n._direction).mulScalar(-1),n._direction.normalize(),this.lightDir[i][0]=n._direction.x,this.lightDir[i][1]=n._direction.y,this.lightDir[i][2]=n._direction.z,this.lightDirId[i].setValue(this.lightDir[i]),n.shape!==Sr&&this.setLTCDirectionalLight(o,i,n._direction,s._node.getPosition(),s.farClip),n.castShadows){const c=n.getRenderData(s,0),h=n._getUniformBiasValues(c);this.lightShadowMapId[i].setValue(c.shadowBuffer),this.lightShadowMatrixId[i].setValue(c.shadowMatrix.data),this.shadowMatrixPaletteId[i].setValue(n._shadowMatrixPalette),this.shadowCascadeDistancesId[i].setValue(n._shadowCascadeDistances),this.shadowCascadeCountId[i].setValue(n.numCascades),this.shadowCascadeBlendId[i].setValue(1-n.cascadeBlend),this.lightShadowIntensity[i].setValue(n.shadowIntensity),this.lightSoftShadowParamsId[i].setValue(n._softShadowParams),c.shadowCamera.renderTarget&&this.lightShadowSearchAreaId[i].setValue(n.penumbraSize/c.shadowCamera.renderTarget.width*c.projectionCompensation);const u=n._shadowCameraParams;u.length=4,u[0]=0,u[1]=c.shadowCamera._farClip,u[2]=c.shadowCamera._nearClip,u[3]=1,this.lightCameraParamsId[i].setValue(u);const f=n._shadowRenderParams;f.length=4,f[0]=n._shadowResolution,f[1]=h.normalBias,f[2]=h.bias,f[3]=0,this.lightShadowParamsId[i].setValue(f)}i++}return i}setLTCPositionalLight(e,t){const s=e.transformVector(new E(-.5,0,0));this.lightWidth[t][0]=s.x,this.lightWidth[t][1]=s.y,this.lightWidth[t][2]=s.z,this.lightWidthId[t].setValue(this.lightWidth[t]);const i=e.transformVector(new E(0,0,.5));this.lightHeight[t][0]=i.x,this.lightHeight[t][1]=i.y,this.lightHeight[t][2]=i.z,this.lightHeightId[t].setValue(this.lightHeight[t])}dispatchOmniLight(e,t,s){const i=t._node.getWorldTransform();if(this.lightColorId[s]||this._resolveLight(e,s),this.lightRadiusId[s].setValue(t.attenuationEnd),this.lightColorId[s].setValue(t._colorLinear),i.getTranslation(t._position),this.lightPos[s][0]=t._position.x,this.lightPos[s][1]=t._position.y,this.lightPos[s][2]=t._position.z,this.lightPosId[s].setValue(this.lightPos[s]),t.shape!==Sr&&this.setLTCPositionalLight(i,s),t.castShadows){const r=t.getRenderData(null,0);this.lightShadowMapId[s].setValue(r.shadowBuffer);const a=t._getUniformBiasValues(r),n=t._shadowRenderParams;n.length=4,n[0]=t._shadowResolution,n[1]=a.normalBias,n[2]=a.bias,n[3]=1/t.attenuationEnd,this.lightShadowParamsId[s].setValue(n),this.lightShadowIntensity[s].setValue(t.shadowIntensity);const o=t.penumbraSize/r.shadowCamera.renderTarget.width;this.lightShadowSearchAreaId[s].setValue(o);const c=t._shadowCameraParams;c.length=4,c[0]=0,c[1]=r.shadowCamera._farClip,c[2]=r.shadowCamera._nearClip,c[3]=0,this.lightCameraParamsId[s].setValue(c)}t._cookie&&(this.lightCookieId[s].setValue(t._cookie),this.lightShadowMatrixId[s].setValue(i.data),this.lightCookieIntId[s].setValue(t.cookieIntensity))}dispatchSpotLight(e,t,s){const i=t._node.getWorldTransform();if(this.lightColorId[s]||this._resolveLight(e,s),this.lightInAngleId[s].setValue(t._innerConeAngleCos),this.lightOutAngleId[s].setValue(t._outerConeAngleCos),this.lightRadiusId[s].setValue(t.attenuationEnd),this.lightColorId[s].setValue(t._colorLinear),i.getTranslation(t._position),this.lightPos[s][0]=t._position.x,this.lightPos[s][1]=t._position.y,this.lightPos[s][2]=t._position.z,this.lightPosId[s].setValue(this.lightPos[s]),t.shape!==Sr&&this.setLTCPositionalLight(i,s),i.getY(t._direction).mulScalar(-1),t._direction.normalize(),this.lightDir[s][0]=t._direction.x,this.lightDir[s][1]=t._direction.y,this.lightDir[s][2]=t._direction.z,this.lightDirId[s].setValue(this.lightDir[s]),t.castShadows){const r=t.getRenderData(null,0);this.lightShadowMapId[s].setValue(r.shadowBuffer),this.lightShadowMatrixId[s].setValue(r.shadowMatrix.data);const a=t._getUniformBiasValues(r),n=t._shadowRenderParams;n.length=4,n[0]=t._shadowResolution,n[1]=a.normalBias,n[2]=a.bias,n[3]=1/t.attenuationEnd,this.lightShadowParamsId[s].setValue(n),this.lightShadowIntensity[s].setValue(t.shadowIntensity);const o=t.penumbraSize/r.shadowCamera.renderTarget.width,c=r.shadowCamera._fov*H.DEG_TO_RAD,h=1/Math.tan(c/2);this.lightShadowSearchAreaId[s].setValue(o*h);const d=t._shadowCameraParams;d.length=4,d[0]=0,d[1]=r.shadowCamera._farClip,d[2]=r.shadowCamera._nearClip,d[3]=0,this.lightCameraParamsId[s].setValue(d)}if(t._cookie){if(!t.castShadows){const r=pr.evalSpotCookieMatrix(t);this.lightShadowMatrixId[s].setValue(r.data)}this.lightCookieId[s].setValue(t._cookie),this.lightCookieIntId[s].setValue(t.cookieIntensity),t._cookieTransform&&(t._cookieTransformUniform[0]=t._cookieTransform.x,t._cookieTransformUniform[1]=t._cookieTransform.y,t._cookieTransformUniform[2]=t._cookieTransform.z,t._cookieTransformUniform[3]=t._cookieTransform.w,this.lightCookieMatrixId[s].setValue(t._cookieTransformUniform),t._cookieOffsetUniform[0]=t._cookieOffset.x,t._cookieOffsetUniform[1]=t._cookieOffset.y,this.lightCookieOffsetId[s].setValue(t._cookieOffsetUniform))}}dispatchLocalLights(e,t,s){let i=s;const r=this.device.scope,a=e[ot],n=a.length;for(let h=0;h<n;h++){const d=a[h];d.mask&t&&(this.dispatchOmniLight(r,d,i),i++)}const o=e[nt],c=o.length;for(let h=0;h<c;h++){const d=o[h];d.mask&t&&(this.dispatchSpotLight(r,d,i),i++)}}renderForwardPrepareMaterials(e,t,s,i,r,a){const n=e.fogParams??this.scene.fog,o=e.shaderParams;o.fog=n.type,o.srgbRenderTarget=t?.isColorBufferSrgb(0)??!1;const c=(v,x,y,S)=>{Aa.drawCalls.push(v),Aa.shaderInstances.push(x),Aa.isNewMaterial.push(y),Aa.lightMaskChanged.push(S)};Aa.clear();const h=this.device,d=this.scene,u=d.clusteredLightingEnabled,f=r?.getLightHash(u)??0;let p=null,m,_;
430const g=s.length;for(let v=0;v<g;v++){const x=s[v],y=x.instancingData;if(y&&y.count<=0)continue;x.ensureMaterial(h);const S=x.material,T=x._shaderDefs,w=x.mask;S&&S===p&&T!==m&&(p=null),S!==p&&(this._materialSwitches++,S._scene=d,S.dirty&&(S.updateUniforms(h,d),S.dirty=!1));const C=x.getShaderInstance(a,f,d,o,this.viewUniformFormat,this.viewBindGroupFormat,i);c(x,C,S!==p,!p||w!==_),p=S,m=T,_=w}return Aa}renderForwardInternal(e,t,s,i,r,a,n){const o=this.device,c=this.scene,h=1<<i,d=a?-1:1,u=c.clusteredLightingEnabled,f=e.xr?.session&&e.xr.views.list.length?e.xr.views.list:null,p=o.xrCurrentViewIndex??-1,m=f&&p>=0?p:0,_=f&&p>=0?p+1:f?f.length:0,g=t.drawCalls.length;for(let v=0;v<g;v++){const x=t.drawCalls[v],y=t.isNewMaterial[v],S=t.lightMaskChanged[v],T=t.shaderInstances[v],w=x.material,C=x.mask;if(T.shader.failed)continue;if(y){if(o.setShader(T.shader,!1),w.setParameters(o),S){const A=this.dispatchDirectLights(s[Te],C,e);u||this.dispatchLocalLights(s,C,A)}this.alphaTestId.setValue(w.alphaTest),o.setBlendState(w.blendState),o.setDepthState(w.depthState),o.setAlphaToCoverage(w.alphaToCoverage)}this.setupCullModeAndFrontFace(e._cullFaces,d,x);const b=x.stencilFront??w.stencilFront,I=x.stencilBack??w.stencilBack;o.setStencilState(b,I),x.setParameters(o,h),o.scope.resolve("meshInstanceId").setValue(x.id);const P=x.mesh;this.setVertexBuffers(o,P),this.setMorphing(o,x.morphInstance),this.setSkinning(o,x);const L=x.instancingData;L&&o.setVertexBuffer(L.vertexBuffer),this.setMeshInstanceMatrices(x,!0),this.setupMeshUniformBuffers(T);const O=x.renderStyle,D=P.indexBuffer[O];r?.(x,v);const N=x.getDrawCommands(e);if(f)for(let k=m;k<_;k++){const A=f[k];if(o.setViewport(A.viewport.x,A.viewport.y,A.viewport.z,A.viewport.w),o.supportsUniformBuffers){const F=n[k];o.setBindGroup(hc,F)}else this.setupViewUniforms(A,k);const M=k===m,R=k===_-1;o.draw(P.primitive[O],D,L?.count,N,M,R),this._forwardDrawCalls++,x.instancingData&&this._instancedDrawCalls++}
430else o.draw(P.primitive[O],D,L?.count,N),this._forwardDrawCalls++,x.instancingData&&this._instancedDrawCalls++;v<g-1&&!t.isNewMaterial[v+1]&&w.setParameters(o,x.parameters)}}renderForward(e,t,s,i,r,a,n,o,c){const h=this.renderForwardPrepareMaterials(e,t,s,i,n,r);this.renderForwardInternal(e,h,i,r,a,o,c),Aa.clear()}renderForwardLayer(e,t,s,i,r,a,n={}){const{scene:o,device:c}=this,h=o.clusteredLightingEnabled;this.setupViewport(e,t);let d,u;if(s){s.sortVisible(e,i);const y=s.getCulledInstances(e);d=i?y.transparent:y.opaque,o.immediate.onPreRenderLayer(s,d,i),s.requiresLightCube&&(this.lightCube.update(o.ambientLight,s._lights),this.constantLightCube.setValue(this.lightCube.colors)),u=s.splitLights}else d=n.meshInstances,u=n.splitLights??$1;h&&((n.lightClusters??this.worldClustersAllocator.empty).activate(),s&&!this.clustersDebugRendered&&o.lighting.debugLayer===s.id&&(this.clustersDebugRendered=!0)),o._activeCamera=e;const f=e.fogParams??this.scene.fog;this.setFogConstants(f);const p=this.setCameraUniforms(e,t);c.supportsUniformBuffers&&this.setupViewUniformBuffers(a,this.viewUniformFormat,this.viewBindGroupFormat,p);const m=n.clearColor??!1,_=n.clearDepth??!1,g=n.clearStencil??!1;(m||_||g)&&this.clear(e,m,_,g);const v=!!(e._flipFaces^t?.flipY),x=this._forwardDrawCalls;this.renderForward(e,t,d,u,r,null,s,v,a),s&&(s._forwardDrawCalls+=this._forwardDrawCalls-x)}setFogConstants(e){if(e.type!==vn){Vr.linear(e.color);const t=this.fogColor;t[0]=Vr.r,t[1]=Vr.g,t[2]=Vr.b,this.fogColorId.setValue(t),e.type===hI?(this.fogStartId.setValue(e.start),this.fogEndId.setValue(e.end)):this.fogDensityId.setValue(e.density)}}setSceneConstants(){const e=this.scene;this.dispatchGlobalLights(e);const t=this.device;this._screenSize[0]=t.width,this._screenSize[1]=t.height,this._screenSize[2]=1/t.width,this._screenSize[3]=1/t.height,this.screenSizeId.setValue(this._screenSize),this.pcssDiskSamplesId.setValue(this.pcssDiskSamples),this.pcssSphereSamplesId.setValue(this.pcssSphereSamples)}buildFrameGraph(e,t){const s=this.scene;if(e.reset(),s.clusteredLightingEnabled){const{shadowsEnabled:o,cookiesEnabled:c}=s.lighting;this._renderPassUpdateClustered.update(e,o,c,this.lights,this.localLights),e.addRenderPass(this._renderPassUpdateClustered)}else this._shadowRendererLocal.buildNonClusteredRenderPasses(e,this.localLights);let i=0,r=!0,a=null;const n=t._renderActions;for(let o=i;o<n.length;o++){const c=n[o],{layer:h,camera:d}=c,u=this._isMultiview(d);if(c.useCameraPasses)u&&e.beginMultiView(this.device),d.camera.framePasses.forEach(f=>{e.addRenderPass(f)}),u&&e.endMultiView();else{const f=h.id===ks,p=f&&(d.renderSceneColorMap||d.renderSceneDepthMap);r&&(r=!1,i=o,a=c.renderTarget);const m=n[o+1],g=(m?!m.useCameraPasses&&m.layer.id===ks:!1)&&(d.renderSceneColorMap||d.renderSceneDepthMap),v=m?m.firstCameraUse&&this.cameraDirShadowLights.has(m.camera.camera):!1;if(!m||m.renderTarget!==a||m.camera!==d||v||g||p){const x=f&&i===o;if(u&&(d.renderSceneColorMap||d.renderSceneDepthMap||c.triggerPostprocess&&d?.onPostprocessing),u&&e.beginMultiView(this.device),x||this.addMainRenderPass(e,t,a,i,o),f){if(d.renderSceneColorMap){const y=d.camera.renderPassColorGrab;y.source=d.renderTarget,e.addRenderPass(y)}d.renderSceneDepthMap&&e.addRenderPass(d.camera.renderPassDepthGrab)}if(c.triggerPostprocess&&d?.onPostprocessing){const y=new q1(this.device,this,c);e.addRenderPass(y)}u&&e.endMultiView(),r=!0}}}}_isMultiview(e){const t=e.camera?.xr;return this.device.isWebGPU&&!!t?.session&&t.views.list.length>=2}addMainRenderPass(e,t,s,i,r){const a=new j1(this.device,t,this.scene,this);a.init(s);const n=t._renderActions;for(let o=i;o<=r;o++)a.addRenderAction(n[o]);e.addRenderPass(a)}update(e){this.frameUpdate(),this.shadowRenderer.frameUpdate(),this.scene._updateSkyMesh(),this.updateLayerComposition(e),this.collectLights(e),this.beginFrame(e),this.setSceneConstants(),this.gsplatDirector?.update(e),this.cullComposition(e),this.gpuUpdate(this.processingMeshInstances)}}let Lp=0;const fl=[],Lh=new Set;function Q1(l,e){return l.drawOrder-e.drawOrder}function J1(l,e){const t=l._sortKeyForward,s=e._sortKeyForward;return t===s?e.mesh.id-l.mesh.id:s-t}function eD(l,e){return e._sortKeyDynamic-l._sortKeyDynamic}function tD(l,e){return l._sortKeyDynamic-e._sortKeyDynamic}const sD=[null,Q1,J1,eD,tD];class iD{opaque=[];transparent=[]}class Kt{id;name;_enabled=!0;_refCounter=1;opaqueSortMode=cS;transparentSortMode=hp;customSortCallback=null;customCalculateSortValues=null;_clearColorBuffer=!1;_clearDepthBuffer=!1;_clearStencilBuffer=!1;onEnable;onDisable;meshInstances=[];meshInstancesSet=new Set;shadowCasters=[];shadowCastersSet=new Set;_visibleInstances=new WeakMap;_lights=[];_lightsSet=new Set;_clusteredLightsSet=new Set;_splitLights=[[],[],[]];
430_splitLightsDirty=!0;_lightHash=0;_lightHashDirty=!1;_lightIdHash=0;_lightIdHashDirty=!1;requiresLightCube=!1;cameras=[];camerasSet=new Set;gsplatPlacements=[];gsplatPlacementsSet=new Set;gsplatShadowCasters=[];gsplatShadowCastersSet=new Set;gsplatPlacementsDirty=!0;_dirtyComposition=!1;_shaderVersion=-1;constructor(e={}){e.id!==void 0?(this.id=e.id,Lp=Math.max(this.id+1,Lp)):this.id=Lp++,this.name=e.name,this._enabled=e.enabled??!0,this._refCounter=this._enabled?1:0,this.opaqueSortMode=e.opaqueSortMode??cS,this.transparentSortMode=e.transparentSortMode??hp,this._clearColorBuffer=!!e.clearColorBuffer,this._clearDepthBuffer=!!e.clearDepthBuffer,this._clearStencilBuffer=!!e.clearStencilBuffer,this.onEnable=e.onEnable,this.onDisable=e.onDisable,this._enabled&&this.onEnable&&this.onEnable()}set enabled(e){e!==this._enabled&&(this._dirtyComposition=!0,this.gsplatPlacementsDirty=!0,this._enabled=e,e?(this.incrementCounter(),this.onEnable&&this.onEnable()):(this.decrementCounter(),this.onDisable&&this.onDisable()))}get enabled(){return this._enabled}set clearColorBuffer(e){this._clearColorBuffer=e,this._dirtyComposition=!0}get clearColorBuffer(){return this._clearColorBuffer}set clearDepthBuffer(e){this._clearDepthBuffer=e,this._dirtyComposition=!0}get clearDepthBuffer(){return this._clearDepthBuffer}set clearStencilBuffer(e){this._clearStencilBuffer=e,this._dirtyComposition=!0}get clearStencilBuffer(){return this._clearStencilBuffer}get hasClusteredLights(){return this._clusteredLightsSet.size>0}get clusteredLightsSet(){return this._clusteredLightsSet}incrementCounter(){this._refCounter===0&&(this._enabled=!0,this.onEnable&&this.onEnable()),this._refCounter++}decrementCounter(){if(this._refCounter===1)this._enabled=!1,this.onDisable&&this.onDisable();else if(this._refCounter===0)return;this._refCounter--}addGSplatPlacement(e){this.gsplatPlacementsSet.has(e)||(this.gsplatPlacements.push(e),this.gsplatPlacementsSet.add(e),this.gsplatPlacementsDirty=!0)}removeGSplatPlacement(e){const t=this.gsplatPlacements.indexOf(e);t>=0&&(this.gsplatPlacements.splice(t,1),this.gsplatPlacementsSet.delete(e),this.gsplatPlacementsDirty=!0)}addGSplatShadowCaster(e){this.gsplatShadowCastersSet.has(e)||(this.gsplatShadowCasters.push(e),this.gsplatShadowCastersSet.add(e),this.gsplatPlacementsDirty=!0)}removeGSplatShadowCaster(e){const t=this.gsplatShadowCasters.indexOf(e);t>=0&&(this.gsplatShadowCasters.splice(t,1),this.gsplatShadowCastersSet.delete(e),this.gsplatPlacementsDirty=!0)}addMeshInstances(e,t){const s=this.meshInstances,i=this.meshInstancesSet;for(let r=0;r<e.length;r++){const a=e[r];i.has(a)||(s.push(a),i.add(a),Lh.add(a.material))}if(t||this.addShadowCasters(e),Lh.size>0){const r=this._shaderVersion;Lh.forEach(a=>{r>=0&&a._shaderVersion!==r&&(a.getShaderVariant!==yn.prototype.getShaderVariant&&a.clearVariants(),a._shaderVersion=r)}),Lh.clear()}}removeMeshInstances(e,t){const s=this.meshInstances,i=this.meshInstancesSet;for(let r=0;r<e.length;r++){const a=e[r];if(i.has(a)){i.delete(a);const n=s.indexOf(a);n>=0&&s.splice(n,1)}}t||this.removeShadowCasters(e)}addShadowCasters(e){const t=this.shadowCasters,s=this.shadowCastersSet;for(let i=0;i<e.length;i++){const r=e[i];r.castShadow&&!s.has(r)&&(s.add(r),t.push(r))}}removeShadowCasters(e){const t=this.shadowCasters,s=this.shadowCastersSet;for(let i=0;i<e.length;i++){const r=e[i];if(s.has(r)){s.delete(r);const a=t.indexOf(r);a>=0&&t.splice(a,1)}}}clearMeshInstances(e=!1){this.meshInstances.length=0,this.meshInstancesSet.clear(),e||(this.shadowCasters.length=0,this.shadowCastersSet.clear())}markLightsDirty(){this._lightHashDirty=!0,this._lightIdHashDirty=!0,this._splitLightsDirty=!0}hasLight(e){return this._lightsSet.has(e)}addLight(e){const t=e.light;this._lightsSet.has(t)||(this._lightsSet.add(t),this._lights.push(t),this.markLightsDirty()),t.type!==Te&&this._clusteredLightsSet.add(t)}removeLight(e){const t=e.light;this._lightsSet.has(t)&&(this._lightsSet.delete(t),this._lights.splice(this._lights.indexOf(t),1),this.markLightsDirty()),t.type!==Te&&this._clusteredLightsSet.delete(t)}
430clearLights(){this._lightsSet.forEach(e=>e.removeLayer(this)),this._lightsSet.clear(),this._clusteredLightsSet.clear(),this._lights.length=0,this.markLightsDirty()}get splitLights(){if(this._splitLightsDirty){this._splitLightsDirty=!1;const e=this._splitLights;for(let s=0;s<e.length;s++)e[s].length=0;const t=this._lights;for(let s=0;s<t.length;s++){const i=t[s];i.enabled&&e[i._type].push(i)}for(let s=0;s<e.length;s++)e[s].sort((i,r)=>i.key-r.key)}return this._splitLights}evaluateLightHash(e,t,s){let i=0;const r=this._lights;for(let a=0;a<r.length;a++){const n=r[a].type!==Te;(e&&n||t&&!n)&&fl.push(s?r[a].id:r[a].key)}return fl.length>0&&(fl.sort(),i=Tf(fl),fl.length=0),i}getLightHash(e){return this._lightHashDirty&&(this._lightHashDirty=!1,this._lightHash=this.evaluateLightHash(!e,!0,!1)),this._lightHash}getLightIdHash(){return this._lightIdHashDirty&&(this._lightIdHashDirty=!1,this._lightIdHash=this.evaluateLightHash(!0,!1,!0)),this._lightIdHash}addCamera(e){this.camerasSet.has(e.camera)||(this.camerasSet.add(e.camera),this.cameras.push(e),this._dirtyComposition=!0)}removeCamera(e){if(this.camerasSet.has(e.camera)){this.camerasSet.delete(e.camera);const t=this.cameras.indexOf(e);this.cameras.splice(t,1),this._dirtyComposition=!0}}clearCameras(){this.cameras.length=0,this.camerasSet.clear(),this._dirtyComposition=!0}_calculateSortDistances(e,t,s){const i=e.length,{x:r,y:a,z:n}=t,{x:o,y:c,z:h}=s;for(let d=0;d<i;d++){const u=e[d];let f;if(u.calculateSortDistance)f=u.calculateSortDistance(u,t,s);else{const m=u.aabb.center;f=(m.x-r)*o+(m.y-a)*c+(m.z-n)*h}const p=u._drawBucket*1e9;u._sortKeyDynamic=p+f}}getCulledInstances(e){let t=this._visibleInstances.get(e);return t||(t=new iD,this._visibleInstances.set(e,t)),t}sortVisible(e,t){const s=t?this.transparentSortMode:this.opaqueSortMode;if(s===Ad)return;const i=this.getCulledInstances(e),r=t?i.transparent:i.opaque,a=e.node;if(s===LI){const n=a.getPosition(),o=a.forward;this.customCalculateSortValues&&this.customCalculateSortValues(r,r.length,n,o),this.customSortCallback&&r.sort(this.customSortCallback)}else{if(s===hp||s===RI){const n=a.getPosition(),o=a.forward;this._calculateSortDistances(r,n,o)}r.sort(sD[s])}}}const rD=(l,e)=>l.priority-e.priority,vc=l=>l.sort(rD);class i_ extends ge{layerList=[];layerIdMap=new Map;layerNameMap=new Map;layerOpaqueIndexMap=new Map;layerTransparentIndexMap=new Map;subLayerList=[];subLayerEnabled=[];cameras=[];camerasSet=new Set;_renderActions=[];_dirty=!1;constructor(e="Untitled"){super(),this.name=e,this._opaqueOrder={},this._transparentOrder={}}destroy(){this.destroyRenderActions()}destroyRenderActions(){this._renderActions.forEach(e=>e.destroy()),this._renderActions.length=0}markDirty(){this._dirty=!0}_update(){const e=this.layerList.length;if(!this._dirty){for(let t=0;t<e;t++)if(this.layerList[t]._dirtyComposition){this._dirty=!0;break}}if(this._dirty){this._dirty=!1,this.cameras.length=0,this.camerasSet.clear();for(let s=0;s<e;s++){const i=this.layerList[s];i._dirtyComposition=!1;for(let r=0;r<i.cameras.length;r++){const a=i.cameras[r];this.camerasSet.has(a.camera)||(this.camerasSet.add(a.camera),this.cameras.push(a))}}this.cameras.length>1&&vc(this.cameras);let t=0;this.destroyRenderActions();for(let s=0;s<this.cameras.length;s++){const i=this.cameras[s];if(i.camera.framePasses.length>0){this.addDummyRenderAction(t,i),t++;continue}let r=!0;const a=t;let n=null,o=!1;for(let c=0;c<e;c++){const h=this.layerList[c];if(h.enabled&&this.subLayerEnabled[c]&&h.cameras.length>0&&i.layers.indexOf(h.id)>=0){!o&&h.id===i.disablePostEffectsLayer&&(o=!0,n&&(n.triggerPostprocess=!0));const u=this.subLayerList[c];n=this.addRenderAction(t,h,u,i,r,o),t++,r=!1}}a<t&&(n.lastCameraUse=!0),!o&&n&&(n.triggerPostprocess=!0),i.renderTarget&&i.postEffectsEnabled&&this.propagateRenderTarget(a-1,i)}this._logRenderActions()}}getNextRenderAction(e){const t=new $T;return this._renderActions.push(t),t}addDummyRenderAction(e,t){const s=this.getNextRenderAction(e);s.camera=t,s.useCameraPasses=!0}addRenderAction(e,t,s,i,r,a){let n=t.id!==ks?i.renderTarget:null,o=!1;const c=this._renderActions;for(let f=e-1;f>=0;f--)if(c[f].camera===i&&c[f].renderTarget===n){o=!0;break}
430a&&i.postEffectsEnabled&&(n=null);const h=this.getNextRenderAction(e);h.triggerPostprocess=!1,h.layer=t,h.transparent=s,h.camera=i,h.renderTarget=n,h.firstCameraUse=r,h.lastCameraUse=!1;const d=r||!o,u=t.clearColorBuffer||t.clearDepthBuffer||t.clearStencilBuffer;return(d||u)&&h.setupClears(d?i:void 0,t),h}propagateRenderTarget(e,t){for(let s=e;s>=0;s--){const i=this._renderActions[s],r=i.layer;if(i.renderTarget&&r.id!==ks)break;if(r.id===ks)continue;if(i.useCameraPasses)break;const a=i?.camera.camera;if(a&&(!t.camera.rect.equals(a.rect)||!t.camera.scissorRect.equals(a.scissorRect)))break;i.renderTarget=t.renderTarget}}_logRenderActions(){}_isLayerAdded(e){return this.layerIdMap.get(e.id)===e}_isSublayerAdded(e,t){return(t?this.layerTransparentIndexMap:this.layerOpaqueIndexMap).get(e)!==void 0}push(e){this._isLayerAdded(e)||(this.layerList.push(e),this.layerList.push(e),this._opaqueOrder[e.id]=this.subLayerList.push(!1)-1,this._transparentOrder[e.id]=this.subLayerList.push(!0)-1,this.subLayerEnabled.push(!0),this.subLayerEnabled.push(!0),this._updateLayerMaps(),this._dirty=!0,this.fire("add",e))}insert(e,t){if(this._isLayerAdded(e))return;this.layerList.splice(t,0,e,e),this.subLayerList.splice(t,0,!1,!0);const s=this.layerList.length;this._updateOpaqueOrder(t,s-1),this._updateTransparentOrder(t,s-1),this.subLayerEnabled.splice(t,0,!0,!0),this._updateLayerMaps(),this._dirty=!0,this.fire("add",e)}remove(e){let t=this.layerList.indexOf(e);for(delete this._opaqueOrder[t],delete this._transparentOrder[t];t>=0;)this.layerList.splice(t,1),this.subLayerList.splice(t,1),this.subLayerEnabled.splice(t,1),t=this.layerList.indexOf(e),this._dirty=!0,this.fire("remove",e);const s=this.layerList.length;this._updateOpaqueOrder(0,s-1),this._updateTransparentOrder(0,s-1),this._updateLayerMaps()}pushOpaque(e){this._isSublayerAdded(e,!1)||(this.layerList.push(e),this._opaqueOrder[e.id]=this.subLayerList.push(!1)-1,this.subLayerEnabled.push(!0),this._updateLayerMaps(),this._dirty=!0,this.fire("add",e))}insertOpaque(e,t){if(this._isSublayerAdded(e,!1))return;this.layerList.splice(t,0,e),this.subLayerList.splice(t,0,!1);const s=this.subLayerList.length;this._updateOpaqueOrder(t,s-1),this.subLayerEnabled.splice(t,0,!0),this._updateLayerMaps(),this._dirty=!0,this.fire("add",e)}removeOpaque(e){for(let t=0,s=this.layerList.length;t<s;t++)if(this.layerList[t]===e&&!this.subLayerList[t]){this.layerList.splice(t,1),this.subLayerList.splice(t,1),s--,this._updateOpaqueOrder(t,s-1),this.subLayerEnabled.splice(t,1),this._dirty=!0,this.layerList.indexOf(e)<0&&this.fire("remove",e);break}this._updateLayerMaps()}pushTransparent(e){this._isSublayerAdded(e,!0)||(this.layerList.push(e),this._transparentOrder[e.id]=this.subLayerList.push(!0)-1,this.subLayerEnabled.push(!0),this._updateLayerMaps(),this._dirty=!0,this.fire("add",e))}
430insertTransparent(e,t){if(this._isSublayerAdded(e,!0))return;this.layerList.splice(t,0,e),this.subLayerList.splice(t,0,!0);const s=this.subLayerList.length;this._updateTransparentOrder(t,s-1),this.subLayerEnabled.splice(t,0,!0),this._updateLayerMaps(),this._dirty=!0,this.fire("add",e)}removeTransparent(e){for(let t=0,s=this.layerList.length;t<s;t++)if(this.layerList[t]===e&&this.subLayerList[t]){this.layerList.splice(t,1),this.subLayerList.splice(t,1),s--,this._updateTransparentOrder(t,s-1),this.subLayerEnabled.splice(t,1),this._dirty=!0,this.layerList.indexOf(e)<0&&this.fire("remove",e);break}this._updateLayerMaps()}getOpaqueIndex(e){return this.layerOpaqueIndexMap.get(e)??-1}getTransparentIndex(e){return this.layerTransparentIndexMap.get(e)??-1}isEnabled(e,t){if(e.enabled){const s=t?this.getTransparentIndex(e):this.getOpaqueIndex(e);if(s>=0)return this.subLayerEnabled[s]}return!1}_updateLayerMaps(){this.layerIdMap.clear(),this.layerNameMap.clear(),this.layerOpaqueIndexMap.clear(),this.layerTransparentIndexMap.clear();for(let e=0;e<this.layerList.length;e++){const t=this.layerList[e];this.layerIdMap.set(t.id,t),this.layerNameMap.set(t.name,t),(this.subLayerList[e]?this.layerTransparentIndexMap:this.layerOpaqueIndexMap).set(t,e)}}getLayerById(e){return this.layerIdMap.get(e)??null}getLayerByName(e){return this.layerNameMap.get(e)??null}_updateOpaqueOrder(e,t){for(let s=e;s<=t;s++)this.subLayerList[s]===!1&&(this._opaqueOrder[this.layerList[s].id]=s)}_updateTransparentOrder(e,t){for(let s=e;s<=t;s++)this.subLayerList[s]===!0&&(this._transparentOrder[this.layerList[s].id]=s)}_sortLayersDescending(e,t,s){let i=-1,r=-1;for(let a=0,n=e.length;a<n;a++){const o=e[a];s.hasOwnProperty(o)&&(i=Math.max(i,s[o]))}for(let a=0,n=t.length;a<n;a++){const o=t[a];s.hasOwnProperty(o)&&(r=Math.max(r,s[o]))}return i===-1&&r!==-1?1:r===-1&&i!==-1?-1:r-i}sortTransparentLayers(e,t){return this._sortLayersDescending(e,t,this._transparentOrder)}sortOpaqueLayers(e,t){return this._sortLayersDescending(e,t,this._opaqueOrder)}}const Fh=new E,$i={bias:0,normalBias:0},pl=new Q,Fp={r:0,g:1,b:2,a:3},ZT={directional:Te,omni:ot,point:ot,spot:nt},aD=[[new ie(0,0,1,1)],[new ie(0,0,.5,.5),new ie(0,.5,.5,.5)],[new ie(0,0,.5,.5),new ie(0,.5,.5,.5),new ie(.5,0,.5,.5)],[new ie(0,0,.5,.5),new ie(0,.5,.5,.5),new ie(.5,0,.5,.5),new ie(.5,.5,.5,.5)]],nD={rrr:1,ggg:2,bbb:4,aaa:8,rgb:7};let oD=0;class lD{constructor(e,t,s){this.light=s,this.camera=e,this.shadowCamera=jT.createShadowCamera(s.device,s._shadowType,s._type,t),this.shadowMatrix=new Z,this.shadowViewport=new ie(0,0,1,1),this.shadowScissor=new ie(0,0,1,1),this.projectionCompensation=0,this.face=t,this.visibleCasters=[],this.viewBindGroups=[]}destroy(){this.viewBindGroups.forEach(e=>{e.defaultUniformBuffer.destroy(),e.destroy()}),this.viewBindGroups.length=0}get shadowBuffer(){const e=this.shadowCamera.renderTarget;return e?this.light._isPcf?e.depthBuffer:e.colorBuffer:null}}class Sc{layers=new Set;clusteredLighting;shadowDepthState=ds.DEFAULT.clone();clusteredFlags=0;clusteredData=new Uint32Array(3);clusteredData16=new Uint16Array(this.clusteredData.buffer);_evtDeviceRestored=null;constructor(e,t){this.device=e,this.clusteredLighting=t,this.id=oD++,this._evtDeviceRestored=e.on("devicerestored",this.onDeviceRestored,this),this._type=Te,this._color=new Q(.8,.8,.8),this._intensity=1,this._affectSpecularity=!0,this._luminance=0,this._castShadows=!1,this._enabled=!1,this._mask=Js,this.isStatic=!1,this.key=0,this.bakeDir=!0,this.bakeNumSamples=1,this.bakeArea=0,this.attenuationStart=10,this.attenuationEnd=10,this._falloffMode=gT,this._shadowType=Li,this._vsmBlurSize=11,this.vsmBlurMode=TT,this.vsmBias=.01*.25,this._cookie=null,this.cookieIntensity=1,this._cookieFalloff=!0,this._cookieChannel="rgb",this._cookieTransform=null,this._cookieTransformUniform=new Float32Array(4),this._cookieOffset=null,this._cookieOffsetUniform=new Float32Array(2),this._cookieTransformSet=!1,this._cookieOffsetSet=!1,this._innerConeAngle=40,this._outerConeAngle=45,this.cascades=null,this._shadowMatrixPalette=null,this._shadowCascadeDistances=null,this.numCascades=1,this._cascadeBlend=0,this.cascadeDistribution=.5,this._shape=Sr,this._colorLinear=new Float32Array(3),this._updateLinearColor(),this._position=new E(0,0,0),this._direction=new E(0,0,0),this._innerConeAngleCos=Math.cos(this._innerConeAngle*H.DEG_TO_RAD),this._updateOuterAngle(this._outerConeAngle),this._usePhysicalUnits=void 0,this._shadowMap=null,this._shadowRenderParams=[],this._shadowCameraParams=[],this.shadowDistance=40,this._shadowResolution=1024,this._shadowBias=-5e-4,this._shadowIntensity=1,this._normalOffsetBias=0,this.shadowUpdateMode=LT,this.shadowUpdateOverrides=null,this._isVsm=!1,this._isPcf=!0,this._softShadowParams=new Float32Array(4),this.shadowSamples=16,this.shadowBlockerSamples=16,this.penumbraSize=1,this.penumbraFalloff=1,this._cookieMatrix=null,this._atlasViewport=null,this.atlasViewportAllocated=!1,this.atlasVersion=0,this.atlasSlotIndex=0,this.atlasSlotUpdated=!1,this._node=null,this._renderData=[],this.visibleThisFrame=!1,this.maxScreenSize=0,this._updateShadowBias()}destroy(){this._evtDeviceRestored?.off(),this._evtDeviceRestored=null,this._destroyShadowMap(),this.releaseRenderData(),this._renderData=null}onDeviceRestored(){this.shadowUpdateMode===Ks&&(this.shadowUpdateMode=ea)}releaseRenderData(){if(this._renderData){for(let e=0;e<this._renderData.length;e++)this._renderData[e].destroy();this._renderData.length=0}}addLayer(e){this.layers.add(e)}removeLayer(e){this.layers.delete(e)}set shadowSamples(e){this._softShadowParams[0]=e}get shadowSamples(){return this._softShadowParams[0]}set shadowBlockerSamples(e){this._softShadowParams[1]=e}get shadowBlockerSamples(){return this._softShadowParams[1]}set shadowBias(e){this._shadowBias!==e&&(this._shadowBias=e,this._updateShadowBias())}get shadowBias(){return this._shadowBias}set numCascades(e){(!this.cascades||this.numCascades!==e)&&(this.cascades=aD[e-1],this._shadowMatrixPalette=new Float32Array(64),this._shadowCascadeDistances=new Float32Array(4),this._destroyShadowMap(),this.updateKey())}get numCascades(){return this.cascades.length}set cascadeBlend(e){this._cascadeBlend!==e&&(this._cascadeBlend=e,this.updateKey())}get cascadeBlend(){return this._cascadeBlend}set shadowMap(e){this._shadowMap!==e&&(this._destroyShadowMap(),this._shadowMap=e)}get shadowMap(){return this._shadowMap}set mask(e){this._mask!==e&&(this._mask=e,this.updateKey(),this.updateClusteredFlags())}get mask(){return this._mask}get numShadowFaces(){const e=this._type;return e===Te?this.numCascades:e===ot?6:1}set type(e){if(this._type===e)return;this._type=e,this._destroyShadowMap(),this._updateShadowBias(),this.updateKey(),this.updateClusteredFlags();const t=this._shadowType;this._shadowType=null,this.shadowUpdateOverrides=null,this.shadowType=t}get type(){return this._type}set shape(e){if(this._shape===e)return;this._shape=e,this._destroyShadowMap(),this.updateKey(),this.updateClusteredFlags();const t=this._shadowType;this._shadowType=null,this.shadowType=t}get shape(){return this._shape}set usePhysicalUnits(e){this._usePhysicalUnits!==e&&(this._usePhysicalUnits=e,this._updateLinearColor())}get usePhysicalUnits(){return this._usePhysicalUnits}set shadowType(e){if(this._shadowType===e)return;let t=yr.get(e);t||(e=Li);const s=this.device;
430e===uc&&(!s.textureFloatRenderable||!s.textureFloatFilterable)&&(e=Li),this._type===ot&&e!==ST&&e!==Li&&e!==yT&&e!==xT&&e!==uc&&(e=Li),e===Dg&&(!s.textureFloatRenderable||!s.textureFloatFilterable)&&(e=qm),e===qm&&!s.textureHalfFloatRenderable&&(e=Li),t=yr.get(e),this._isVsm=t?.vsm??!1,this._isPcf=t?.pcf??!1,this._shadowType=e,this._destroyShadowMap(),this.updateKey()}get shadowType(){return this._shadowType}set enabled(e){this._enabled!==e&&(this._enabled=e,this.layersDirty())}get enabled(){return this._enabled}set castShadows(e){this._castShadows!==e&&(this._castShadows=e,this._destroyShadowMap(),this.layersDirty(),this.updateKey())}get castShadows(){return this._castShadows&&this._mask!==fr&&this._mask!==0}set shadowIntensity(e){this._shadowIntensity!==e&&(this._shadowIntensity=e,this.updateKey())}get shadowIntensity(){return this._shadowIntensity}get bakeShadows(){return this._castShadows&&this._mask===fr}set shadowResolution(e){this._shadowResolution!==e&&(this._type===ot?e=Math.min(e,this.device.maxCubeMapSize):e=Math.min(e,this.device.maxTextureSize),this._shadowResolution=e,this._destroyShadowMap())}get shadowResolution(){return this._shadowResolution}set vsmBlurSize(e){this._vsmBlurSize!==e&&(e%2===0&&e++,this._vsmBlurSize=e)}get vsmBlurSize(){return this._vsmBlurSize}set normalOffsetBias(e){if(this._normalOffsetBias!==e){const t=!this._normalOffsetBias&&e||this._normalOffsetBias&&!e;this._normalOffsetBias=e,t&&this.updateKey()}}get normalOffsetBias(){return this._normalOffsetBias}set falloffMode(e){this._falloffMode!==e&&(this._falloffMode=e,this.updateKey(),this.updateClusteredFlags())}get falloffMode(){return this._falloffMode}set innerConeAngle(e){this._innerConeAngle!==e&&(this._innerConeAngle=e,this._innerConeAngleCos=Math.cos(e*H.DEG_TO_RAD),this.updateClusterData(!1,!0),this._usePhysicalUnits&&this._updateLinearColor())}get innerConeAngle(){return this._innerConeAngle}set outerConeAngle(e){this._outerConeAngle!==e&&(this._outerConeAngle=e,this._updateOuterAngle(e),this._usePhysicalUnits&&this._updateLinearColor())}get outerConeAngle(){return this._outerConeAngle}set penumbraSize(e){this._penumbraSize=e,this._softShadowParams[2]=e}get penumbraSize(){return this._penumbraSize}set penumbraFalloff(e){this._softShadowParams[3]=e}get penumbraFalloff(){return this._softShadowParams[3]}_updateOuterAngle(e){const t=e*H.DEG_TO_RAD;this._outerConeAngleCos=Math.cos(t),this._outerConeAngleSin=Math.sin(t),this.updateClusterData(!1,!0)}set intensity(e){this._intensity!==e&&(this._intensity=e,this._updateLinearColor())}get intensity(){return this._intensity}set affectSpecularity(e){this._type===Te&&(this._affectSpecularity=e,this.updateKey())}get affectSpecularity(){return this._affectSpecularity}set luminance(e){this._luminance!==e&&(this._luminance=e,this._updateLinearColor())}get luminance(){return this._luminance}get cookieMatrix(){return this._cookieMatrix||(this._cookieMatrix=new Z),this._cookieMatrix}get atlasViewport(){return this._atlasViewport||(this._atlasViewport=new ie(0,0,1,1)),this._atlasViewport}set cookie(e){this._cookie!==e&&(this._cookie=e,this.updateKey())}get cookie(){return this._cookie}set cookieFalloff(e){this._cookieFalloff!==e&&(this._cookieFalloff=e,this.updateKey())}get cookieFalloff(){return this._cookieFalloff}set cookieChannel(e){if(this._cookieChannel!==e){if(e.length<3){const t=e.charAt(e.length-1),s=3-e.length;for(let i=0;i<s;i++)e+=t}this._cookieChannel=e,this.updateKey(),this.updateClusteredFlags()}}get cookieChannel(){return this._cookieChannel}set cookieTransform(e){this._cookieTransform!==e&&(this._cookieTransform=e,this._cookieTransformSet=!!e,e&&!this._cookieOffset&&(this.cookieOffset=new j,this._cookieOffsetSet=!1),this.updateKey())}get cookieTransform(){return this._cookieTransform}set cookieOffset(e){if(this._cookieOffset===e)return;!!(this._cookieTransformSet||e)&&!e&&this._cookieOffset?this._cookieOffset.set(0,0):this._cookieOffset=e,this._cookieOffsetSet=!!e,e&&!this._cookieTransform&&(this.cookieTransform=new ie(1,1,0,0),this._cookieTransformSet=!1),this.updateKey()}get cookieOffset(){return this._cookieOffset}beginFrame(){this.visibleThisFrame=this._type===Te&&this._enabled,this.maxScreenSize=0,this.atlasViewportAllocated=!1,this.atlasSlotUpdated=!1}_destroyShadowMap(){if(this.releaseRenderData(),this._shadowMap&&(this._shadowMap.cached||this._shadowMap.destroy(),this._shadowMap=null),this.shadowUpdateMode===Ks&&(this.shadowUpdateMode=ea),this.shadowUpdateOverrides)for(let e=0;e<this.shadowUpdateOverrides.length;e++)this.shadowUpdateOverrides[e]===Ks&&(this.shadowUpdateOverrides[e]=ea)}getRenderData(e,t){for(let i=0;i<this._renderData.length;i++){const r=this._renderData[i];if(r.camera===e&&r.face===t)return r}const s=new lD(e,t,this);return this._renderData.push(s),s}clone(){const e=new Sc(this.device,this.clusteredLighting);return e.type=this._type,e.setColor(this._color),e.intensity=this._intensity,e.affectSpecularity=this._affectSpecularity,e.luminance=this._luminance,e.castShadows=this.castShadows,e._enabled=this._enabled,e.attenuationStart=this.attenuationStart,e.attenuationEnd=this.attenuationEnd,e.falloffMode=this._falloffMode,e.shadowType=this._shadowType,e.vsmBlurSize=this._vsmBlurSize,e.vsmBlurMode=this.vsmBlurMode,e.vsmBias=this.vsmBias,e.shadowUpdateMode=this.shadowUpdateMode,e.mask=this.mask,this.shadowUpdateOverrides&&(e.shadowUpdateOverrides=this.shadowUpdateOverrides.slice()),e.innerConeAngle=this._innerConeAngle,e.outerConeAngle=this._outerConeAngle,e.numCascades=this.numCascades,e.cascadeDistribution=this.cascadeDistribution,e.cascadeBlend=this._cascadeBlend,e.shape=this._shape,e.shadowDepthState.copy(this.shadowDepthState),e.shadowBias=this.shadowBias,e.normalOffsetBias=this._normalOffsetBias,e.shadowResolution=this._shadowResolution,e.shadowDistance=this.shadowDistance,e.shadowIntensity=this.shadowIntensity,e.shadowSamples=this.shadowSamples,e.shadowBlockerSamples=this.shadowBlockerSamples,e.penumbraSize=this.penumbraSize,e.penumbraFalloff=this.penumbraFalloff,e}static getLightUnitConversion(e,t=Math.PI/4,s=0){switch(e){case nt:{const i=Math.cos(t),r=Math.cos(s);return 2*Math.PI*(1-r+(r-i)/2)}case ot:return 4*Math.PI;case Te:return 1}}_getUniformBiasValues(e){const t=e.shadowCamera._farClip;switch(this._type){case ot:$i.bias=this.shadowBias,$i.normalBias=this._normalOffsetBias;break;case nt:this._isVsm?$i.bias=-1e-5*20:$i.bias=this.shadowBias*20,$i.normalBias=this._isVsm?this.vsmBias/(this.attenuationEnd/7):this._normalOffsetBias;break;case Te:this._isVsm?$i.bias=-1e-5*20:$i.bias=this.shadowBias/t*100,$i.normalBias=this._isVsm?this.vsmBias/(t/7):this._normalOffsetBias;break}return $i}getColor(){return this._color}getBoundingSphere(e){if(this._type===nt){const t=this.attenuationEnd,s=this._outerConeAngle,i=this._outerConeAngleCos,r=this._node;Fh.copy(r.up),s>
43045?(e.radius=t*this._outerConeAngleSin,Fh.mulScalar(-t*i)):(e.radius=t/(2*i),Fh.mulScalar(-e.radius)),e.center.add2(r.getPosition(),Fh)}else this._type===ot&&(e.center=this._node.getPosition(),e.radius=this.attenuationEnd)}getBoundingBox(e){if(this._type===nt){const t=this.attenuationEnd,s=this._outerConeAngle,i=this._node,r=Math.abs(Math.sin(s*H.DEG_TO_RAD)*t);e.center.set(0,-t*.5,0),e.halfExtents.set(r,t*.5,r),e.setFromTransformedAabb(e,i.getWorldTransform(),!0)}else this._type===ot&&(e.center.copy(this._node.getPosition()),e.halfExtents.set(this.attenuationEnd,this.attenuationEnd,this.attenuationEnd))}_updateShadowBias(){if(this._type===ot&&!this.clusteredLighting)this.shadowDepthState.depthBias=0,this.shadowDepthState.depthBiasSlope=0;else{const e=this.shadowBias*-1e3;this.shadowDepthState.depthBias=e,this.shadowDepthState.depthBiasSlope=e}}_updateLinearColor(){let e=this._intensity;this._usePhysicalUnits&&(e=this._luminance/Sc.getLightUnitConversion(this._type,this._outerConeAngle*H.DEG_TO_RAD,this._innerConeAngle*H.DEG_TO_RAD));const t=this._color,s=this._colorLinear;e>=1?pl.linear(t).mulScalar(e):pl.copy(t).mulScalar(e).linear(),s[0]=pl.r,s[1]=pl.g,s[2]=pl.b,this.updateClusterData(!0)}setColor(){arguments.length===1?this._color.set(arguments[0].r,arguments[0].g,arguments[0].b):arguments.length===3&&this._color.set(arguments[0],arguments[1],arguments[2]),this._updateLinearColor()}layersDirty(){this.layers.forEach(e=>{e.hasLight(this)&&e.markLightsDirty()})}updateKey(){let e=this._type<<29|this._shadowType<<25|this._falloffMode<<23|(this._normalOffsetBias!==0?1:0)<<22|(this._cookie?1:0)<<21|(this._cookieFalloff?1:0)<<20|Fp[this._cookieChannel.charAt(0)]<<18|(this._cookieTransform?1:0)<<12|this._shape<<10|(this.numCascades>0?1:0)<<9|(this._cascadeBlend>0?1:0)<<8|(this.affectSpecularity?1:0)<<7|this.mask<<6|(this._castShadows?1:0)<<3;this._cookieChannel.length===3&&(e|=Fp[this._cookieChannel.charAt(1)]<<16,e|=Fp[this._cookieChannel.charAt(2)]<<14),e!==this.key&&this.layersDirty(),this.key=e}updateClusteredFlags(){const e=!!(this.mask&Js),t=!!(this.mask&ur);this.clusteredFlags=(this.type===nt?1:0)<<30|(this._shape&3)<<28|(this._falloffMode&1)<<27|(nD[this._cookieChannel]??0)<<23|(e?1:0)<<22|(t?1:0)<<21}getClusteredFlags(e,t){return this.clusteredFlags|((e?Math.floor(this.shadowIntensity*255):0)&255)<<0|((t?Math.floor(this.cookieIntensity*255):0)&255)<<8}updateClusterData(e,t){const{clusteredData16:s}=this,i=Ja.float2Half;if(e&&(s[0]=i(H.clamp(this._colorLinear[0]/Cd,0,65504)),s[1]=i(H.clamp(this._colorLinear[1]/Cd,0,65504)),s[2]=i(H.clamp(this._colorLinear[2]/Cd,0,65504))),t){let a=0;const n=.99;let o=Math.cos(this._innerConeAngle*n*H.DEG_TO_RAD);o>.5&&(o=1-o,a|=1);let c=Math.cos(this._outerConeAngle*n*H.DEG_TO_RAD);c>.5&&(c=1-c,a|=2),s[3]=a,s[4]=i(o),s[5]=i(c)}}}class QT{_areaLightsEnabled=!1;_cells=new E(10,3,10);_maxLightsPerCell=255;_shadowsEnabled=!0;_shadowType=Li;_shadowAtlasResolution=2048;_cookiesEnabled=!1;_cookieAtlasResolution=2048;debugLayer;atlasSplit=null;constructor(e,t,s){this._supportsAreaLights=e,this._maxTextureSize=t,this._dirtyLightsFnc=s}applySettings(e){this.shadowsEnabled=e.lightingShadowsEnabled??this.shadowsEnabled,this.cookiesEnabled=e.lightingCookiesEnabled??this.cookiesEnabled,this.areaLightsEnabled=e.lightingAreaLightsEnabled??this.areaLightsEnabled,this.shadowAtlasResolution=e.lightingShadowAtlasResolution??this.shadowAtlasResolution,this.cookieAtlasResolution=e.lightingCookieAtlasResolution??this.cookieAtlasResolution,this.maxLightsPerCell=e.lightingMaxLightsPerCell??this.maxLightsPerCell,this.shadowType=e.lightingShadowType??this.shadowType,e.lightingCells&&(this.cells=new E(e.lightingCells))}set cells(e){this._cells.copy(e)}get cells(){return this._cells}set maxLightsPerCell(e){this._maxLightsPerCell=H.clamp(e,1,255)}get maxLightsPerCell(){return this._maxLightsPerCell}set cookieAtlasResolution(e){this._cookieAtlasResolution=H.clamp(e,32,this._maxTextureSize)}get cookieAtlasResolution(){return this._cookieAtlasResolution}set shadowAtlasResolution(e){this._shadowAtlasResolution=H.clamp(e,32,this._maxTextureSize)}get shadowAtlasResolution(){return this._shadowAtlasResolution}set shadowType(e){this._shadowType!==e&&(this._shadowType=e,this._dirtyLightsFnc())}get shadowType(){return this._shadowType}set cookiesEnabled(e){this._cookiesEnabled!==e&&(this._cookiesEnabled=e,this._dirtyLightsFnc())}get cookiesEnabled(){return this._cookiesEnabled}set areaLightsEnabled(e){this._supportsAreaLights&&this._areaLightsEnabled!==e&&(this._areaLightsEnabled=e,this._dirtyLightsFnc())}get areaLightsEnabled(){return this._areaLightsEnabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this._dirtyLightsFnc())}get shadowsEnabled(){return this._shadowsEnabled}}class dn{constructor(e){this.morph=e,e.incRefCount(),this.device=e.device;const t=e._targets.length;this.shader=this._createShader(t),this._weights=[],this._weightMap=new Map;for(let a=0;a<e._targets.length;a++){const n=e._targets[a];n.name&&this._weightMap.set(n.name,a),this.setWeight(a,n.defaultWeight)}this._shaderMorphWeights=new Float32Array(t),this._shaderMorphIndex=new Uint32Array(t);const s=(a,n)=>(this[n]=e._createTexture(a,e._renderTextureFormat),new St({colorBuffer:this[n],depth:!1}
430));e.morphPositions&&(this.rtPositions=s("MorphRTPos","texturePositions")),e.morphNormals&&(this.rtNormals=s("MorphRTNrm","textureNormals")),this._textureParams=new Float32Array([e.morphTextureWidth,e.morphTextureHeight]);const i=e.aabb.halfExtents;this._aabbSize=new Float32Array([i.x*4,i.y*4,i.z*4]);const r=e.aabb.getMin();this._aabbMin=new Float32Array([r.x*2,r.y*2,r.z*2]),this._aabbNrmSize=new Float32Array([2,2,2]),this._aabbNrmMin=new Float32Array([-1,-1,-1]),this.aabbSizeId=this.device.scope.resolve("aabbSize"),this.aabbMinId=this.device.scope.resolve("aabbMin"),this.morphTextureId=this.device.scope.resolve("morphTexture"),this.morphFactor=this.device.scope.resolve("morphFactor[0]"),this.morphIndex=this.device.scope.resolve("morphIndex[0]"),this.countId=this.device.scope.resolve("count"),this.zeroTextures=!1}destroy(){this.shader=null;const e=this.morph;e&&(this.morph=null,e.decRefCount(),e.refCount<1&&e.destroy()),this.rtPositions?.destroy(),this.rtPositions=null,this.texturePositions?.destroy(),this.texturePositions=null,this.rtNormals?.destroy(),this.rtNormals=null,this.textureNormals?.destroy(),this.textureNormals=null}clone(){return new dn(this.morph)}_getWeightIndex(e){return typeof e=="string"?this._weightMap.get(e):e}getWeight(e){const t=this._getWeightIndex(e);return this._weights[t]}setWeight(e,t){const s=this._getWeightIndex(e);this._weights[s]=t,this._dirty=!0}_createShader(e){const t=new Map;t.set("{MORPH_TEXTURE_MAX_COUNT}",e),this.morph.intRenderFormat&&t.set("MORPH_INT","");const s=this.morph.intRenderFormat?"uvec4":"vec4";return Qt.createShader(this.device,{uniqueName:`TextureMorphShader_${e}-${this.morph.intRenderFormat?"int":"float"}`,attributes:{vertex_position:Ie},vertexChunk:"morphVS",fragmentChunk:"morphPS",fragmentDefines:t,fragmentOutputTypes:[s]})}_updateTextureRenderTarget(e,t,s){const{morph:i,device:r}=this;this.setAabbUniforms(s),this.morphTextureId.setValue(s?i.targetsTexturePositions:i.targetsTextureNormals),r.setBlendState(xt.NOBLEND),this.countId.setValue(t),this.morphFactor.setValue(this._shaderMorphWeights),this.morphIndex.setValue(this._shaderMorphIndex),cn(r,e,this.shader)}_updateTextureMorph(e){this.device,(e>0||!this.zeroTextures)&&(this.rtPositions&&this._updateTextureRenderTarget(this.rtPositions,e,!0),this.rtNormals&&this._updateTextureRenderTarget(this.rtNormals,e,!1),this.zeroTextures=e===0)}setAabbUniforms(e=!0){this.aabbSizeId.setValue(e?this._aabbSize:this._aabbNrmSize),this.aabbMinId.setValue(e?this._aabbMin:this._aabbNrmMin)}prepareRendering(e){this.setAabbUniforms()}update(){this._dirty=!1;const e=this.morph._targets,t=1e-5,s=this._shaderMorphWeights,i=this._shaderMorphIndex;let r=0;for(let a=0;a<e.length;a++)Math.abs(this.getWeight(a))>t&&(s[r]=this.getWeight(a),i[r]=a,r++);this._updateTextureMorph(r)}}class pa{graph=null;meshInstances=[];skinInstances=[];morphInstances=[];constructor(){this.cameras=[],this.lights=[],this._shadersVersion=0,this._immutable=!1}getGraph(){return this.graph}setGraph(e){this.graph=e}getCameras(){return this.cameras}setCameras(e){this.cameras=e}getLights(){return this.lights}setLights(e){this.lights=e}getMaterials(){const e=[];for(let t=0;t<this.meshInstances.length;t++){const s=this.meshInstances[t];e.indexOf(s.material)===-1&&e.push(s.material)}return e}clone(){const e=[],t=[],s=function(c){const h=c.clone();e.push(c),t.push(h);for(let d=0;d<c._children.length;d++)h.addChild(s(c._children[d]));return h},i=s(this.graph),r=[],a=[],n=[];for(let c=0;c<this.skinInstances.length;c++){const h=this.skinInstances[c].skin,d=new $c(h),u=[];for(let f=0;f<h.boneNames.length;f++){const p=h.boneNames[f],m=i.findByName(p);u.push(m)}d.bones=u,a.push(d)}for(let c=0;c<this.morphInstances.length;c++){const h=this.morphInstances[c].morph,d=new dn(h);n.push(d)}for(let c=0;c<this.meshInstances.length;c++){const h=this.meshInstances[c],d=e.indexOf(h.node),u=new Ne(h.mesh,h.material,t[d]);if(h.skinInstance){const f=this.skinInstances.indexOf(h.skinInstance);u.skinInstance=a[f]}if(h.morphInstance){const f=this.morphInstances.indexOf(h.morphInstance);u.morphInstance=n[f]}r.push(u)}const o=new pa;return o.graph=i,o.meshInstances=r,o.skinInstances=a,o.morphInstances=n,o.getGraph().syncHierarchy(),o}destroy(){const e=this.meshInstances;for(let t=0;t<e.length;t++)e[t].destroy();this.meshInstances.length=0}generateWireframe(){Ne._prepareRenderStyleForArray(this.meshInstances,Na)}}class zg extends Cf{_aabb;preferHighPrecision;constructor(e,t,{preferHighPrecision:s=!1}={}){super(),this.device=t;const i=t;this.preferHighPrecision=s,this._targets=e.slice();
430const r=i.textureHalfFloatRenderable?Ge:void 0,a=i.textureFloatRenderable?mt:void 0;this._renderTextureFormat=this.preferHighPrecision?a??r:r??a,this._renderTextureFormat=this._renderTextureFormat??Vi,this.intRenderFormat=Qr(this._renderTextureFormat),this._textureFormat=this.preferHighPrecision?mt:Ge,this._init(),this._updateMorphFlags()}destroy(){this.vertexBufferIds?.destroy(),this.vertexBufferIds=null,this.targetsTexturePositions?.destroy(),this.targetsTexturePositions=null,this.targetsTextureNormals?.destroy(),this.targetsTextureNormals=null}get aabb(){if(!this._aabb){const e=new E,t=new E;for(let s=0;s<this._targets.length;s++){const i=this._targets[s].aabb;e.min(i.getMin()),t.max(i.getMax())}this._aabb=new Le,this._aabb.setMinMax(e,t)}return this._aabb}get morphPositions(){return this._morphPositions}get morphNormals(){return this._morphNormals}_init(){this._initTextureBased();for(let e=0;e<this._targets.length;e++)this._targets[e]._postInit()}_findSparseSet(e,t,s){let i=1;const r=e[0].length;for(let a=0;a<r;a+=3){let n=!1;for(let o=0;o<e.length;o++){const c=e[o];if(c[a]!==0||c[a+1]!==0||c[a+2]!==0){n=!0;break}}n?(t.push(i),s.push(a/3),i++):t.push(0)}return i}_initTextureBased(){const e=[],t=[],s=this._targets;for(let _=0;_<s.length;_++){const g=s[_];g.options.deltaPositions&&(e.push(g.options.deltaPositions),t.push(!0)),g.options.deltaNormals&&(e.push(g.options.deltaNormals),t.push(!1))}const i=[],r=[],a=this._findSparseSet(e,i,r),n=this.device.maxTextureSize;let o=Math.ceil(Math.sqrt(a));o=Math.min(o,n);const c=Math.ceil(a/o);if(c>n)return;this.morphTextureWidth=o,this.morphTextureHeight=c;let h=!1;const d=Ja.float2Half;this._textureFormat===Ge&&(h=!0);const u=[],f=[],p=o*c*4;for(let _=0;_<e.length;_++){const g=e[_],v=this._textureFormat===Ge?new Uint16Array(p):new Float32Array(p);if((t[_]?u:f).push(v),h)for(let x=0;x<r.length;x++){const y=r[x]*3,S=x*4+4;v[S]=d(g[y]),v[S+1]=d(g[y+1]),v[S+2]=d(g[y+2])}else for(let x=0;x<r.length;x++){const y=r[x]*3,S=x*4+4;v[S]=g[y],v[S+1]=g[y+1],v[S+2]=g[y+2]}}u.length>0&&(this.targetsTexturePositions=this._createTexture("MorphPositionsTexture",this._textureFormat,s.length,[u])),f.length>0&&(this.targetsTextureNormals=this._createTexture("MorphNormalsTexture",this._textureFormat,s.length,[f]));const m=[{semantic:Io,components:1,type:Xc,asInt:!0}];return this.vertexBufferIds=new Hi(this.device,new Us(this.device,m,i.length),i.length,{data:new Uint32Array(i)}),!0}get targets(){return this._targets}_updateMorphFlags(){this._morphPositions=!1,this._morphNormals=!1;for(let e=0;e<this._targets.length;e++){const t=this._targets[e];t.morphPositions&&(this._morphPositions=!0),t.morphNormals&&(this._morphNormals=!0)}}_createTexture(e,t,s,i){return new ce(this.device,{levels:i,arrayLength:s,width:this.morphTextureWidth,height:this.morphTextureHeight,format:t,cubemap:!1,mipmaps:!1,minFilter:Fe,magFilter:Fe,addressU:ue,addressV:ue,name:e})}}class Mf{used=!1;constructor(e){this.options=e,this._name=e.name,this._defaultWeight=e.defaultWeight||0,this._aabb=e.aabb,this.deltaPositions=e.deltaPositions,this.morphPositions=!!e.deltaPositions,this.morphNormals=!!e.deltaNormals}get name(){return this._name}get defaultWeight(){return this._defaultWeight}get aabb(){return this._aabb||(this._aabb=new Le,this.deltaPositions&&this._aabb.compute(this.deltaPositions)),this._aabb}clone(){return new Mf(this.options)}_postInit(){this.options.preserveData||(this.options=null),this.used=!0}}let Ki,XS=1;const ne=4,Op=new Z,Bp=new Z,Di=new E,ut=new E,oi=new E,Bn=new E,Ms=new E,Dt=new E,Nn=new E,kn=new E,ml=new E,YS=new E,is=new E,Oh=new E,Pa=new E;function fo(l){return l-Math.floor(l)}function cD(l){return Math.max(Math.min(l,1),0)}function Np(l,e){return l-e*Math.floor(l/e)}function hD(l){let e=fo(l),t=fo(255*l),s=fo(65025*l),i=fo(160581375*l);return e-=t/255,t-=s/255,s-=i/255,i-=i/255,[e,t,s,i]}function Bh(l){let e=fo(l),t=fo(255*l);return e-=t/255,t-=t/255,[e,t]}class dD{constructor(e){this._emitter=e}calcSpawnPosition(e,t,s,i,r){const a=this._emitter,n=Math.random(),o=Math.random(),c=Math.random(),h=Math.random();if(a.useCpu&&(e[r*ne+0+a.numParticlesPot*2*ne]=n,e[r*ne+1+a.numParticlesPot*2*ne]=o,e[r*ne+2+a.numParticlesPot*2*ne]=c),ut.x=n-.5,ut.y=o-.5,ut.z=c-.5,a.emitterShape===Ri){const f=Math.max(Math.abs(ut.x),Math.max(Math.abs(ut.y),Math.abs(ut.z))),p=f+(.5-f)*s[0],m=f+(.5-f)*s[1],_=f+(.5-f)*s[2];ut.x=p*(f===Math.abs(ut.x)?Math.sign(ut.x):2*ut.x),ut.y=m*(f===Math.abs(ut.y)?Math.sign(ut.y):2*ut.y),ut.z=_*(f===Math.abs(ut.z)?Math.sign(ut.z):2*ut.z),a.localSpace?Di.copy(t.transformPoint(ut)):Di.copy(i).add(t.transformPoint(ut))}else{ut.normalize();const f=a.emitterRadius===0?0:a.emitterRadiusInner/a.emitterRadius,p=
430h*(1-f)+f;a.localSpace?Di.copy(ut.mulScalar(p*a.emitterRadius)):Di.copy(i).add(ut.mulScalar(p*a.emitterRadius))}let u=-H.lerp(a.rate,a.rate2,n)*r;if(a.pack8){const f=(Di.x-a.worldBounds.center.x)/a.worldBoundsSize.x+.5,p=(Di.y-a.worldBounds.center.y)/a.worldBoundsSize.y+.5,m=(Di.z-a.worldBounds.center.z)/a.worldBoundsSize.z+.5;let _=H.lerp(a.startAngle*H.DEG_TO_RAD,a.startAngle2*H.DEG_TO_RAD,n);_=_%(Math.PI*2)/(Math.PI*2);const g=Bh(f);e[r*ne]=g[0],e[r*ne+1]=g[1];const v=Bh(p);e[r*ne+2]=v[0],e[r*ne+3]=v[1];const x=Bh(m);e[r*ne+0+a.numParticlesPot*ne]=x[0],e[r*ne+1+a.numParticlesPot*ne]=x[1];const y=Bh(_);e[r*ne+2+a.numParticlesPot*ne]=y[0],e[r*ne+3+a.numParticlesPot*ne]=y[1];const S=1;e[r*ne+3+a.numParticlesPot*ne*2]=S;const T=Math.max(a.lifetime,a.numParticles*Math.max(a.rate,a.rate2)),w=a.lifetime+1;u=(u+T)/(T+w);const C=hD(u);e[r*ne+0+a.numParticlesPot*ne*3]=C[0],e[r*ne+1+a.numParticlesPot*ne*3]=C[1],e[r*ne+2+a.numParticlesPot*ne*3]=C[2],e[r*ne+3+a.numParticlesPot*ne*3]=C[3]}else e[r*ne]=Di.x,e[r*ne+1]=Di.y,e[r*ne+2]=Di.z,e[r*ne+3]=H.lerp(a.startAngle*H.DEG_TO_RAD,a.startAngle2*H.DEG_TO_RAD,n),e[r*ne+3+a.numParticlesPot*ne]=u}update(e,t,s,i,r,a,n,o){let c,h,d;const u=this._emitter;if(u.meshInstance.node){const b=u.meshInstance.node.worldTransform;for(let I=0;I<12;I++)Op.data[I]=b.data[I];Bp.copy(Op),Bp.invert(),Ki=u.meshInstance.node.localScale,XS=Math.max(Math.max(Ki.x,Ki.y),Ki.z)}a=u.meshInstance.node===null||u.localSpace?E.ZERO:u.meshInstance.node.getPosition();const f=u.camera?u.camera._node.getPosition():E.ZERO,p=u.useMesh?17:15;let m,_,g,v,x,y,S,T,w;const C=u.precision-1;for(let b=0;b<u.numParticles;b++){const I=Math.floor(u.vbCPU[b*u.numParticleVerts*(u.useMesh?6:4)+3]),P=s[I*ne+0+u.numParticlesPot*2*ne];oi.x=P,oi.y=s[I*ne+1+u.numParticlesPot*2*ne],oi.z=s[I*ne+2+u.numParticlesPot*2*ne];const L=u.rate+(u.rate2-u.rate)*P,O=u.lifetime;let D=s[I*ne+3+u.numParticlesPot*ne]+n;const N=cD(D/O);let k=0,A=0;const M=0;(D-n<=0||D>=O)&&this.calcSpawnPosition(s,i,r,a,I);let F=D>0&&D<O;F&&(d=N*C,m=Math.floor(d),_=Math.ceil(d),d%=1,c=u.qRotSpeed[m],h=u.qRotSpeed[_],g=c+(h-c)*d,c=u.qRotSpeed2[m],h=u.qRotSpeed2[_],v=c+(h-c)*d,c=u.qScale[m],h=u.qScale[_],k=c+(h-c)*d,c=u.qScale2[m],h=u.qScale2[_],x=c+(h-c)*d,c=u.qAlpha[m],h=u.qAlpha[_],y=c+(h-c)*d,c=u.qAlpha2[m],h=u.qAlpha2[_],S=c+(h-c)*d,c=u.qRadialSpeed[m],h=u.qRadialSpeed[_],T=c+(h-c)*d,c=u.qRadialSpeed2[m],h=u.qRadialSpeed2[_],w=c+(h-c)*d,T+=(w-T)*(P*100%1),Bn.x=s[I*ne],Bn.y=s[I*ne+1],Bn.z=s[I*ne+2],u.localSpace?ml.copy(Bn):ml.copy(Bn).sub(a),ml.normalize().mulScalar(T),m*=3,_*=3,c=u.qLocalVelocity[m],h=u.qLocalVelocity[_],Dt.x=c+(h-c)*d,c=u.qLocalVelocity[m+1],h=u.qLocalVelocity[_+1],Dt.y=c+(h-c)*d,c=u.qLocalVelocity[m+2],h=u.qLocalVelocity[_+2],Dt.z=c+(h-c)*d,c=u.qLocalVelocity2[m],h=u.qLocalVelocity2[_],kn.x=c+(h-c)*d,c=u.qLocalVelocity2[m+1],h=u.qLocalVelocity2[_+1],kn.y=c+(h-c)*d,c=u.qLocalVelocity2[m+2],h=u.qLocalVelocity2[_+2],kn.z=c+(h-c)*d,c=u.qVelocity[m],h=u.qVelocity[_],Ms.x=c+(h-c)*d,c=u.qVelocity[m+1],h=u.qVelocity[_+1],Ms.y=c+(h-c)*d,c=u.qVelocity[m+2],h=u.qVelocity[_+2],Ms.z=c+(h-c)*d,c=u.qVelocity2[m],h=u.qVelocity2[_],Nn.x=c+(h-c)*d,c=u.qVelocity2[m+1],h=u.qVelocity2[_+1],Nn.y=c+(h-c)*d,c=u.qVelocity2[m+2],h=u.qVelocity2[_+2],Nn.z=c+(h-c)*d,Dt.x+=(kn.x-Dt.x)*oi.x,Dt.y+=(kn.y-Dt.y)*oi.y,Dt.z+=(kn.z-Dt.z)*oi.z,u.initialVelocity>0&&(u.emitterShape===SI?(ut.copy(oi).mulScalar(2).sub(E.ONE).normalize(),Dt.add(ut.mulScalar(u.initialVelocity))):Dt.add(E.FORWARD.mulScalar(u.initialVelocity))),Ms.x+=(Nn.x-Ms.x)*oi.x,Ms.y+=(Nn.y-Ms.y)*oi.y,Ms.z+=(Nn.z-Ms.z)*oi.z,g+=(v-g)*oi.y,k=(k+(x-k)*(P*1e4%1))*XS,A=(S-y)*(P*1e3%1),u.meshInstance.node&&(u.localSpace?(Dt.x/=Ki.x,Dt.y/=Ki.y,Dt.z/=Ki.z):Op.transformPoint(Dt,Dt)),u.localSpace?(Bp.transformPoint(Ms,Ms),Dt.add(Ms).add(ml)):(Dt.add(Ms.mul(Ki)),Dt.add(ml.mul(Ki))),Oh.copy(Dt),YS.copy(Bn).add(Dt.mulScalar(n)),is.copy(YS),s[I*ne]=is.x,s[I*ne+1]=is.y,s[I*ne+2]=is.z,s[I*ne+3]+=g*n,u.wrap&&u.wrapBounds&&(u.localSpace||is.sub(a),is.x=Np(is.x,u.wrapBounds.x)-u.wrapBounds.x*.5,is.y=Np(is.y,u.wrapBounds.y)-u.wrapBounds.y*.5,is.z=Np(is.z,u.wrapBounds.z)-u.wrapBounds.z*.5,u.localSpace||is.add(a)),u.sort>0&&(u.sort===1?(Pa.copy(is).sub(f),u.particleDistance[I]=-(Pa.x*Pa.x+Pa.y*Pa.y+Pa.z*Pa.z)):u.sort===2?u.particleDistance[I]=D:u.sort===3&&(u.particleDistance[I]=-D))),o?D<0&&(s[I*ne+3+u.numParticlesPot*2*ne]=-1):(D>=O&&(D-=Math.max(O,u.numParticles*L),s[I*ne+3+u.numParticlesPot*2*ne]=u.loop?1:-1),D<0&&u.loop&&(s[I*ne+3+u.numParticlesPot*2*ne]=1)),s[I*ne+3+u.numParticlesPot*2*ne]<0&&(F=!1),s[I*ne+3+u.numParticlesPot*ne]=D;for(let U=0;U<u.numParticleVerts;U++){const B=(b*u.numParticleVerts+U)*(u.useMesh?6:4);let z=u.vbCPU[B],$=u.vbCPU[B+1],K=u.vbCPU[B+2];F||(z=$=K=0);const Y=b*u.numParticleVerts*p+U*p;e[Y]=is.x,e[Y+1]=is.y,e[Y+2]=is.z,e[Y+3]=N,e[Y+4]=u.alignToMotion?M:s[I*ne+3],e[Y+5]=k,e[Y+6]=A,e[Y+7]=Oh.x,e[Y+8]=z,e[Y+9]=$,e[Y+10]=K,e[Y+11]=Oh.y,e[Y+12]=I,e[Y+13]=Oh.z,e[Y+14]=u.vbCPU[B+3],u.useMesh&&(e[Y+15]=u.vbCPU[B+4],e[Y+16]=u.vbCPU[B+5])}}if(u.sort>
430$m&&u.camera){const b=u.useMesh?6:4,I=u.particleDistance;for(let P=0;P<u.numParticles;P++)t[P][0]=P,t[P][1]=I[Math.floor(u.vbCPU[P*u.numParticleVerts*b+3])];u.vbOld.set(u.vbCPU),t.sort((P,L)=>P[1]-L[1]);for(let P=0;P<u.numParticles;P++){const L=t[P][0]*u.numParticleVerts*b,O=P*u.numParticleVerts*b;for(let D=0;D<u.numParticleVerts*b;D++)u.vbCPU[O+D]=u.vbOld[L+D]}}}}const jS=new xi,qS=new xi,$S=new xi;class uD{constructor(e,t){this._emitter=e,this.frameRandomUniform=new Float32Array(3),this.emitterPosUniform=new Float32Array(3),this.emitterScaleUniform=new Float32Array([1,1,1]),this.worldBoundsMulUniform=new Float32Array(3),this.worldBoundsAddUniform=new Float32Array(3),this.inBoundsSizeUniform=new Float32Array(3),this.inBoundsCenterUniform=new Float32Array(3),this.constantParticleTexIN=t.scope.resolve("particleTexIN"),this.constantParticleTexOUT=t.scope.resolve("particleTexOUT"),this.constantEmitterPos=t.scope.resolve("emitterPos"),this.constantEmitterScale=t.scope.resolve("emitterScale"),this.constantSpawnBounds=t.scope.resolve("spawnBounds"),this.constantSpawnPosInnerRatio=t.scope.resolve("spawnPosInnerRatio"),this.constantSpawnBoundsSphere=t.scope.resolve("spawnBoundsSphere"),this.constantSpawnBoundsSphereInnerRatio=t.scope.resolve("spawnBoundsSphereInnerRatio"),this.constantInitialVelocity=t.scope.resolve("initialVelocity"),this.constantFrameRandom=t.scope.resolve("frameRandom"),this.constantDelta=t.scope.resolve("delta"),this.constantRate=t.scope.resolve("rate"),this.constantRateDiv=t.scope.resolve("rateDiv"),this.constantLifetime=t.scope.resolve("lifetime"),this.constantGraphSampleSize=t.scope.resolve("graphSampleSize"),this.constantGraphNumSamples=t.scope.resolve("graphNumSamples"),this.constantInternalTex0=t.scope.resolve("internalTex0"),this.constantInternalTex1=t.scope.resolve("internalTex1"),this.constantInternalTex2=t.scope.resolve("internalTex2"),this.constantInternalTex3=t.scope.resolve("internalTex3"),this.constantEmitterMatrix=t.scope.resolve("emitterMatrix"),this.constantEmitterMatrixInv=t.scope.resolve("emitterMatrixInv"),this.constantNumParticles=t.scope.resolve("numParticles"),this.constantNumParticlesPot=t.scope.resolve("numParticlesPot"),this.constantLocalVelocityDivMult=t.scope.resolve("localVelocityDivMult"),this.constantVelocityDivMult=t.scope.resolve("velocityDivMult"),this.constantRotSpeedDivMult=t.scope.resolve("rotSpeedDivMult"),this.constantSeed=t.scope.resolve("seed"),this.constantStartAngle=t.scope.resolve("startAngle"),this.constantStartAngle2=t.scope.resolve("startAngle2"),this.constantOutBoundsMul=t.scope.resolve("outBoundsMul"),this.constantOutBoundsAdd=t.scope.resolve("outBoundsAdd"),this.constantInBoundsSize=t.scope.resolve("inBoundsSize"),this.constantInBoundsCenter=t.scope.resolve("inBoundsCenter"),this.constantMaxVel=t.scope.resolve("maxVel"),this.constantFaceTangent=t.scope.resolve("faceTangent"),this.constantFaceBinorm=t.scope.resolve("faceBinorm"),this.constantRadialSpeedDivMult=t.scope.resolve("radialSpeedDivMult")}_setInputBounds(){this.inBoundsSizeUniform[0]=this._emitter.prevWorldBoundsSize.x,this.inBoundsSizeUniform[1]=this._emitter.prevWorldBoundsSize.y,this.inBoundsSizeUniform[2]=this._emitter.prevWorldBoundsSize.z,this.constantInBoundsSize.setValue(this.inBoundsSizeUniform),this.inBoundsCenterUniform[0]=this._emitter.prevWorldBoundsCenter.x,this.inBoundsCenterUniform[1]=this._emitter.prevWorldBoundsCenter.y,this.inBoundsCenterUniform[2]=this._emitter.prevWorldBoundsCenter.z,this.constantInBoundsCenter.setValue(this.inBoundsCenterUniform)}randomize(){this.frameRandomUniform[0]=Math.random(),this.frameRandomUniform[1]=Math.random(),this.frameRandomUniform[2]=Math.random()}update(e,t,s,i,r){const a=this._emitter;e.setDrawStates(),this.randomize(),this.constantRadialSpeedDivMult.setValue(a.material.getParameter("radialSpeedDivMult").data),this.constantGraphSampleSize.setValue(1/a.precision),this.constantGraphNumSamples.setValue(a.precision),this.constantNumParticles.setValue(a.numParticles),this.constantNumParticlesPot.setValue(a.numParticlesPot),this.constantInternalTex0.setValue(a.internalTex0),this.constantInternalTex1.setValue(a.internalTex1),this.constantInternalTex2.setValue(a.internalTex2),this.constantInternalTex3.setValue(a.internalTex3);const n=a.meshInstance.node,o=n===null?E.ONE:n.localScale;if(a.pack8){this.worldBoundsMulUniform[0]=a.worldBoundsMul.x,this.worldBoundsMulUniform[1]=a.worldBoundsMul.y,this.worldBoundsMulUniform[2]=a.worldBoundsMul.z,this.constantOutBoundsMul.setValue(this.worldBoundsMulUniform),this.worldBoundsAddUniform[0]=a.worldBoundsAdd.x,this.worldBoundsAddUniform[1]=a.worldBoundsAdd.y,this.worldBoundsAddUniform[2]=a.worldBoundsAdd.z,this.constantOutBoundsAdd.setValue(this.worldBoundsAddUniform),this._setInputBounds();let f=a.maxVel*Math.max(Math.max(o.x,o.y),o.z);
430f=Math.max(f,1),this.constantMaxVel.setValue(f)}const c=n===null||a.localSpace?E.ZERO:n.getPosition(),h=n===null?Z.IDENTITY:n.getWorldTransform();a.emitterShape===Ri?(jS.setFromMat4(t),this.constantSpawnBounds.setValue(jS.data),this.constantSpawnPosInnerRatio.setValue(s)):(this.constantSpawnBoundsSphere.setValue(a.emitterRadius),this.constantSpawnBoundsSphereInnerRatio.setValue(a.emitterRadius===0?0:a.emitterRadiusInner/a.emitterRadius)),this.constantInitialVelocity.setValue(a.initialVelocity),qS.setFromMat4(h),$S.invertMat4(h),this.emitterPosUniform[0]=c.x,this.emitterPosUniform[1]=c.y,this.emitterPosUniform[2]=c.z,this.constantEmitterPos.setValue(this.emitterPosUniform),this.constantFrameRandom.setValue(this.frameRandomUniform),this.constantDelta.setValue(i),this.constantRate.setValue(a.rate),this.constantRateDiv.setValue(a.rate2-a.rate),this.constantStartAngle.setValue(a.startAngle*H.DEG_TO_RAD),this.constantStartAngle2.setValue(a.startAngle2*H.DEG_TO_RAD),this.constantSeed.setValue(a.seed),this.constantLifetime.setValue(a.lifetime),this.emitterScaleUniform[0]=o.x,this.emitterScaleUniform[1]=o.y,this.emitterScaleUniform[2]=o.z,this.constantEmitterScale.setValue(this.emitterScaleUniform),this.constantEmitterMatrix.setValue(qS.data),this.constantEmitterMatrixInv.setValue($S.data),this.constantLocalVelocityDivMult.setValue(a.localVelocityUMax),this.constantVelocityDivMult.setValue(a.velocityUMax),this.constantRotSpeedDivMult.setValue(a.rotSpeedUMax[0]);let d=a.swapTex?a.particleTexOUT:a.particleTexIN;d=a.beenReset?a.particleTexStart:d;const u=a.swapTex?a.particleTexIN:a.particleTexOUT;this.constantParticleTexIN.setValue(d),cn(e,a.swapTex?a.rtParticleTexIN:a.rtParticleTexOUT,r?a.shaderParticleUpdateOnStop:a.loop?a.shaderParticleUpdateRespawn:a.shaderParticleUpdateNoRespawn),a.material.setParameter("particleTexOUT",d),a.material.setParameter("particleTexIN",u),a.beenReset=!1,a.swapTex=!a.swapTex,a.prevWorldBoundsSize.copy(a.worldBoundsSize),a.prevWorldBoundsCenter.copy(a.worldBounds.center),a.pack8&&this._setInputBounds()}}const KS=["NONE","VERTEX","MAP"];class fD extends ln{generateKey(e){let s=`particle_${ln.definesHash(e.defines)}_`;for(const i in e)e.hasOwnProperty(i)&&(s+=e[i]);return s}createVertexDefines(e,t){const s=new Map(e.defines);return e.mesh&&s.set("USE_MESH",""),e.meshUv&&s.set("USE_MESH_UV",""),e.localSpace&&s.set("LOCAL_SPACE",""),e.screenSpace&&s.set("SCREEN_SPACE",""),e.animTex&&s.set("ANIMTEX",""),e.soft>0&&s.set("SOFT",""),e.stretch>0&&s.set("STRETCH",""),e.customFace&&s.set("CUSTOM_FACE",""),e.pack8&&s.set("PACK8",""),e.localSpace&&s.set("LOCAL_SPACE",""),e.animTexLoop&&s.set("ANIMTEX_LOOP",""),e.wrap&&s.set("WRAP",""),e.alignToMotion&&s.set("ALIGN_TO_MOTION",""),s.set("NORMAL",KS[e.normal]),t.particle_vertexData=Ie,e.mesh&&e.meshUv&&(t.particle_uv=Zs),e.useCpu&&(t.particle_vertexData2=Jd,t.particle_vertexData3=lg,t.particle_vertexData4=cg,t.particle_vertexData5=hg),s}createFragmentDefines(e){const t=new Map(e.defines);return e.soft>0&&t.set("SOFT",""),e.halflambert&&t.set("HALF_LAMBERT",""),t.set("NORMAL",KS[e.normal]),t.set("BLEND",uT[e.blend]),t}createShaderDefinition(e,t){const s=e.isWebGPU?de:ze,i=be.get(e,s),r={},a=this.createVertexDefines(t,r),n=this.createFragmentDefines(t),o=`PARTICLE_${t.useCpu?"CPU":"GPU"} 431`;a.set(o,""),n.set(o,"");const c=new Map(i);return Ht.createDefinition(e,{name:"ParticleShader",shaderLanguage:s,attributes:r,vertexCode:i.get("particle_shaderVS"),fragmentCode:i.get("particle_shaderPS"),fragmentDefines:n,fragmentIncludes:c,vertexIncludes:c,vertexDefines:a})}}const pD=new fD;class mD extends yn{emitter=null;constructor(e){super(),this.emitter=e}getShaderVariant(e){const{device:t,scene:s,cameraShaderParams:i,objDefs:r}=e,{emitter:a}=this,n={defines:Qt.getCoreDefines(this,e),pass:Ko,useCpu:this.emitter.useCpu,normal:a.lighting?a.normalMap!==null?2:1:0,halflambert:this.emitter.halfLambert,stretch:this.emitter.stretch,alignToMotion:this.emitter.alignToMotion,soft:this.emitter.depthSoftening,mesh:this.emitter.useMesh,meshUv:r&Bg,gamma:i?.shaderOutputGamma??qc,toneMap:i?.toneMapping??bf,fog:s&&!this.emitter.noFog?s.fog.type:"none",wrap:this.emitter.wrap&&this.emitter.wrapBounds,localSpace
431:this.emitter.localSpace,screenSpace:a.inTools?!1:this.emitter.screenSpace,blend:this.emitter.blendType,animTex:this.emitter._isAnimated(),animTexLoop:this.emitter.animLoop,pack8:this.emitter.pack8,customFace:this.emitter.orientation!==ru},o=new Df(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),c=ko(t);return c.register("particle",pD),c.getProgram("particle",n,o,this.userId)}}const ZS=[[-1,-1],[1,-1],[1,1],[-1,1]];function Vs(l,e,t,s,i=mt,r,a){let n=Fe;a&&(i===Re||i===us)&&(n=It);const o=new ce(l,{width:e,height:t,format:i,cubemap:!1,mipmaps:!1,minFilter:n,magFilter:n,addressU:ue,addressV:ue,name:"ParticleSystemTexture"}),c=o.lock();if(i===Re||i===us){const h=new Uint8Array(s.length);for(let d=0;d<s.length;d++)h[d]=s[d]*r*255;s=h}return c.set(s),o.unlock(),o}function QS(l){return Math.max(Math.min(l,1),0)}const JS=new _i([0,0,1,0]),ey=new _i([0,1,1,1]),ty=new Ya([0,0,1,0],[0,0,1,0],[0,0,1,0]),_D=new Ya([0,1,1,1],[0,1,1,1],[0,1,1,1]);let Zi=2;const Nh=4,Qi=new Float32Array(3),Ia=new Z,sy=new E,kh=new E,Uh=new E;let uu,ql;function oe(l,e){ql[l]!==void 0&&ql[l]!==null?uu[l]=ql[l]:uu[l]=e}function JT(l,e,t){return(l*255<<16|e*255<<8|t*255)/(1<<24)}function iy(l,e){const t=l.length/3,s=new Array(t*4);for(let i=0;i<t;i++)s[i*4]=l[i*3],s[i*4+1]=l[i*3+1],s[i*4+2]=l[i*3+2],s[i*4+3]=JT(e[i*3],e[i*3+1],e[i*3+2]);return s}function gD(l,e){const t=new Array(e.length*4);for(let s=0;s<e.length;s++)t[s*4]=l[s*3],t[s*4+1]=l[s*3+1],t[s*4+2]=l[s*3+2],t[s*4+3]=e[s];return t}function vD(l,e,t,s,i){const r=new Array(l.length*4);for(let a=0;a<l.length;a++)r[a*4]=l[a],r[a*4+1]=e[a],r[a*4+2]=0,r[a*4+3]=JT(t[a],s[a],i[a]);return r}function SD(l,e){const t=new Array(l.length*4);for(let s=0;s<l.length;s++)t[s*4]=l[s],t[s*4+1]=e[s],t[s*4+2]=0,t[s*4+3]=0;return t}function yD(l){const e=Math.max(l.rate,l.rate2)*l.numParticles+l.lifetime;return Date.now()+e*1e3}function xD(l,e){const t=new Float32Array(l.length);for(let s=0;s<l.length;s++)t[s]=l[s]-e[s];return t}function ka(l,e){const t=e.length,s=l.length/t;for(let i=0;i<s;i++)for(let r=0;r<t;r++){const a=Math.abs(l[i*t+r]);e[r]=Math.max(e[r],a)}}function TD(l,e){const t=e.length,s=l.length/t;for(let i=0;i<s;i++)for(let r=0;r<t;r++)l[i*t+r]/=e[r]===0?1:e[r],l[i*t+r]*=.5,l[i*t+r]+=.5}function Da(l,e,t){const s=xD(e,l);return ka(s,t),TD(s,t),s}const wD=new Jt;class CD{material=null;internalTex0=null;internalTex1=null;internalTex2=null;colorParam=null;constructor(e,t){this.graphicsDevice=e;const s=e,i=32;this.precision=i,this._addTimeTime=0,uu=this,ql=t,oe("numParticles",1),this.numParticles>e.maxTextureSize&&(this.numParticles=e.maxTextureSize),oe("rate",1),oe("rate2",this.rate),oe("lifetime",50),oe("emitterExtents",new E(0,0,0)),oe("emitterExtentsInner",new E(0,0,0)),oe("emitterRadius",0),oe("emitterRadiusInner",0),oe("emitterShape",Ri),oe("initialVelocity",1),oe("wrap",!1),oe("localSpace",!1),oe("screenSpace",!1),oe("wrapBounds",null),oe("colorMap",this.defaultParamTexture),oe("normalMap",null),oe("loop",!0),oe("preWarm",!1),oe("sort",$m),oe("mode",wT),oe("scene",null),oe("lighting",!1),oe("halfLambert",!1),oe("intensity",1),oe("stretch",0),oe("alignToMotion",!1),oe("depthSoftening",0),oe("mesh",null),oe("particleNormal",new E(0,1,0)),oe("orientation",ru),oe("depthWrite",!1),oe("noFog",!1),oe("blendType",Wi),oe("node",null),oe("startAngle",0),oe("startAngle2",this.startAngle),oe("animTilesX",1),oe("animTilesY",1),oe("animStartFrame",0),oe("animNumFrames",1),oe("animNumAnimations",1),oe("animIndex",0),oe("randomizeAnimIndex",!1),oe("animSpeed",1),oe("animLoop",!0),this._gpuUpdater=new uD(this,s),this._cpuUpdater=new dD(this),this.emitterPosUniform=new Float32Array(3),this.wrapBoundsUniform=new Float32Array(3),this.emitterScaleUniform=new Float32Array([1,1,1]),oe("colorGraph",_D),oe("colorGraph2",this.colorGraph),oe("scaleGraph",ey),oe("scaleGraph2",this.scaleGraph),oe("alphaGraph",ey),oe("alphaGraph2",this.alphaGraph),oe("localVelocityGraph",ty),oe("localVelocityGraph2",this.localVelocityGraph),oe("velocityGraph",ty),oe("velocityGraph2",this.velocityGraph),oe("rotationSpeedGraph",JS),oe("rotationSpeedGraph2",this.rotationSpeedGraph),oe("radialSpeedGraph",JS),oe("radialSpeedGraph2",this.radialSpeedGraph),uu=null,ql=null,this.animTilesParams=new Float32Array(2),this.animParams=new Float32Array(4),this.animIndexParams=new Float32Array(2),this.vbToSort=null,this.vbOld=null,this.particleDistance=null,this.camera=null,this.swapTex=!1,this.useMesh=!0,this.useCpu=!e.supportsGpuParticles,this.pack8=!0,this.localBounds=new Le,this.worldBoundsNoTrail=new Le,this.worldBoundsTrail=[new Le,new Le],this.worldBounds=new Le,this.worldBoundsSize=new E,this.prevWorldBoundsSize=new E,this.prevWorldBoundsCenter=new E,this.prevEmitterExtents=this.emitterExtents,this.prevEmitterRadius=this.emitterRadius,this.worldBoundsMul=new E,this.worldBoundsAdd=new E,this.timeToSwitchBounds=0,this.shaderParticleUpdateRespawn=null,this.shaderParticleUpdateNoRespawn=null,this.shaderParticleUpdateOnStop=null,this.numParticleVerts=0,this.numParticleIndices=0,this.material=null,this.meshInstance=null,this.drawOrder=0,this.seed=Math.random(),this.fixedTimeStep=1/60,this.maxSubSteps=10,this.simTime=0,this.simTimeTotal=0,this.beenReset=!1,this._layer=null,this.rebuild()}get defaultParamTexture(){return wD.get(this.graphicsDevice,()=>{const s=new Float32Array(1024);for(let r=0;r<16;r++)for(let a=0;a<16;a++){const n=a+1-8.5,o=r+1-8.5,c=QS(1-QS(Math.sqrt(n*n+o*o)/16)-.5),h=r*16+a;s[h*4]=1,s[h*4+1]=1,s[h*4+2]=1,s[h*4+3]=c}const i=Vs(this.graphicsDevice,16,16,s,us,1,!0);return i.minFilter=It,i.magFilter=It,i})}onChangeCamera(){this.resetMaterial()}calculateBoundsMad(){this.worldBoundsMul.x=1/this.worldBoundsSize.x,this.worldBoundsMul.y=1/this.worldBoundsSize.y,this.worldBoundsMul.z=1/this.worldBoundsSize.z,this.worldBoundsAdd.copy(this.worldBounds.center).mul(this.worldBoundsMul).mulScalar(-1),this.worldBoundsAdd.x+=.5,this.worldBoundsAdd.y+=.5,this.worldBoundsAdd.z+=.5}calculateWorldBounds(){if(!this.node)return;if(this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),
431!this.useCpu){let s=!1;this.emitterShape===Ri?s=!this.emitterExtents.equals(this.prevEmitterExtents):s=this.emitterRadius!==this.prevEmitterRadius,s&&this.calculateLocalBounds()}const e=this.node.getWorldTransform();this.localSpace?this.worldBoundsNoTrail.copy(this.localBounds):this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,e),this.worldBoundsTrail[0].add(this.worldBoundsNoTrail),this.worldBoundsTrail[1].add(this.worldBoundsNoTrail);const t=this.simTimeTotal;t>=this.timeToSwitchBounds&&(this.worldBoundsTrail[0].copy(this.worldBoundsTrail[1]),this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.timeToSwitchBounds=t+this.lifetime),this.worldBounds.copy(this.worldBoundsTrail[0]),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.localSpace?(this.meshInstance.aabb.setFromTransformedAabb(this.worldBounds,e),this.meshInstance.mesh.aabb.setFromTransformedAabb(this.worldBounds,e)):(this.meshInstance.aabb.copy(this.worldBounds),this.meshInstance.mesh.aabb.copy(this.worldBounds)),this.meshInstance._aabbVer=1-this.meshInstance._aabbVer,this.pack8&&this.calculateBoundsMad()}resetWorldBounds(){this.node&&(this.worldBoundsNoTrail.setFromTransformedAabb(this.localBounds,this.localSpace?Z.IDENTITY:this.node.getWorldTransform()),this.worldBoundsTrail[0].copy(this.worldBoundsNoTrail),this.worldBoundsTrail[1].copy(this.worldBoundsNoTrail),this.worldBounds.copy(this.worldBoundsTrail[0]),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),this.simTimeTotal=0,this.timeToSwitchBounds=0)}calculateLocalBounds(){let e=Number.MAX_VALUE,t=Number.MAX_VALUE,s=Number.MAX_VALUE,i=-Number.MAX_VALUE,r=-Number.MAX_VALUE,a=-Number.MAX_VALUE,n=0,o=0;const c=this.lifetime/this.precision,h=[this.qVelocity,this.qVelocity2],d=[this.qLocalVelocity,this.qLocalVelocity2],u=[0,0],f=[0,0],p=[0,0],m=[0,0],_=[0,0];let g,v,x;for(let S=0;S<this.precision+1;S++){const T=Math.min(S,this.precision-1);for(let w=0;w<2;w++)g=d[w][T*3+0]*c+u[w],v=d[w][T*3+1]*c+f[w],x=d[w][T*3+2]*c+p[w],e=Math.min(g,e),t=Math.min(v,t),s=Math.min(x,s),i=Math.max(g,i),r=Math.max(v,r),a=Math.max(x,a),u[w]=g,f[w]=v,p[w]=x;for(let w=0;w<2;w++)_[w]+=c*Math.sqrt(h[w][T*3+0]*h[w][T*3+0]+h[w][T*3+1]*h[w][T*3+1]+h[w][T*3+2]*h[w][T*3+2]);m[0]+=this.qRadialSpeed[T]*c,m[1]+=this.qRadialSpeed2[T]*c,n=Math.max(n,Math.max(Math.abs(m[0]),Math.abs(m[1]))),o=Math.max(o,this.qScale[T])}this.emitterShape===Ri?(g=this.emitterExtents.x*.5,v=this.emitterExtents.y*.5,x=this.emitterExtents.z*.5):(g=this.emitterRadius,v=this.emitterRadius,x=this.emitterRadius);const y=Math.max(_[0],_[1]);kh.x=e-o-g-n-y,kh.y=t-o-v-n-y,kh.z=s-o-x-n-y,Uh.x=i+o+g+n+y,Uh.y=r+o+v+n+y,Uh.z=a+o+x+n+y,this.localBounds.setMinMax(kh,Uh)}rebuild(){const e=this.graphicsDevice;this.colorMap===null&&(this.colorMap=this.defaultParamTexture),this.spawnBounds=this.emitterShape===Ri?this.emitterExtents:this.emitterRadius,this.useCpu=this.useCpu||this.sort>$m||e.maxVertexTextures<=1||e.fragmentUniformsCount<64||e.forceCpuParticles;const t=this._destroyResources();this.pack8=(this.pack8||!e.textureFloatRenderable)&&!this.useCpu,Zi=this.useCpu||this.pack8?4:2,this.useMesh=!!this.mesh,this.numParticlesPot=H.nextPowerOfTwo(this.numParticles),this.rebuildGraphs(),this.calculateLocalBounds(),this.resetWorldBounds(),this.node&&(this.worldBounds.setFromTransformedAabb(this.localBounds,this.localSpace?Z.IDENTITY:this.node.getWorldTransform()),this.worldBoundsTrail[0].copy(this.worldBounds),this.worldBoundsTrail[1].copy(this.worldBounds),this.worldBoundsSize.copy(this.worldBounds.halfExtents).mulScalar(2),this.prevWorldBoundsSize.copy(this.worldBoundsSize),this.prevWorldBoundsCenter.copy(this.worldBounds.center),this.pack8&&this.calculateBoundsMad()),this.vbToSort=new Array(this.numParticles);for(let o=0;o<this.numParticles;o++)this.vbToSort[o]=[0,0];this.particleDistance=new Float32Array(this.numParticles),this._gpuUpdater.randomize(),this.particleTex=new Float32Array(this.numParticlesPot*Zi*Nh);const s=this.node===null||this.localSpace?E.ZERO:this.node.getPosition();this.emitterShape===Ri&&(this.node===null||this.localSpace?Ia.setTRS(E.ZERO,ae.IDENTITY,this.spawnBounds):Ia.setTRS(E.ZERO,this.node.getRotation(),sy.copy(this.spawnBounds).mul(this.node.localScale)),Qi[0]=this.emitterExtents.x!==0?this.emitterExtentsInner.x/this.emitterExtents.x:0,Qi[1]=this.emitterExtents.y!==0?this.emitterExtentsInner.y/this.emitterExtents.y:0,Qi[2]=this.emitterExtents.z!==0?this.emitterExtentsInner.z/this.emitterExtents.z:0);for(let o=0;o<this.numParticles;o++)this._cpuUpdater.calcSpawnPosition(this.particleTex,Ia,Qi,s,o),this.useCpu&&(this.particleTex[o*Nh+3+this.numParticlesPot*2*Nh]=1);this.particleTexStart=new Float32Array(this.numParticlesPot*Zi*Nh);for(let o=0;o<this.particleTexStart.length;o++)this.particleTexStart[o]=this.particleTex[o];this.useCpu||(this.pack8?(this.particleTexIN=Vs(e,this.numParticlesPot,Zi,this.particleTex,Re,1,!1),this.particleTexOUT=Vs(e,this.numParticlesPot,Zi,this.particleTex,Re,1,!1),this.particleTexStart=Vs(e,this.numParticlesPot,Zi,this.particleTexStart,Re,1,!1)):(this.particleTexIN=Vs(e,this.numParticlesPot,Zi,this.particleTex),this.particleTexOUT=Vs(e,this.numParticlesPot,Zi,this.particleTex),this.particleTexStart=Vs(e,this.numParticlesPot,Zi,this.particleTexStart)),this.rtParticleTexIN=new St({colorBuffer:this.particleTexIN,depth:!1}
431),this.rtParticleTexOUT=new St({colorBuffer:this.particleTexOUT,depth:!1}),this.swapTex=!1);const i=new Map;this.localSpace&&i.set("LOCAL_SPACE",""),this.pack8&&i.set("PACK8",""),this.emitterShape===Ri&&i.set("EMITTERSHAPE_BOX","");const r=`Shape:${this.emitterShape}-Pack:${this.pack8}-Local:${this.localSpace}`,a={attributes:{vertex_position:Ie},vertexChunk:"fullscreenQuadVS",fragmentChunk:"particle_simulationPS",fragmentDefines:i};a.uniqueName=`ParticleUpdateRespawn-${r}`,i.set("RESPAWN",""),this.shaderParticleUpdateRespawn=Qt.createShader(e,a),i.delete("RESPAWN"),a.uniqueName=`ParticleUpdateNoRespawn-${r}`,i.set("NO_RESPAWN",""),this.shaderParticleUpdateNoRespawn=Qt.createShader(e,a),i.delete("NO_RESPAWN"),a.uniqueName=`ParticleUpdateStop-${r}`,i.set("ON_STOP",""),this.shaderParticleUpdateOnStop=Qt.createShader(e,a),this.numParticleVerts=this.useMesh?this.mesh.vertexBuffer.numVertices:4,this.numParticleIndices=this.useMesh?this.mesh.indexBuffer[0].numIndices:6,this._allocate(this.numParticles);const n=new at(e);n.vertexBuffer=this.vertexBuffer,n.indexBuffer[0]=this.indexBuffer,n.primitive[0].type=qs,n.primitive[0].base=0,n.primitive[0].count=this.numParticles*this.numParticleIndices,n.primitive[0].indexed=!0,this.material=this._createMaterial(),this.resetMaterial(),this.meshInstance=new Ne(n,this.material,this.node),this.meshInstance.pick=!1,this.meshInstance.updateKey(),this.meshInstance.cull=!0,this.localSpace?this.meshInstance.aabb.setFromTransformedAabb(this.worldBounds,this.node.getWorldTransform()):this.meshInstance.aabb.copy(this.worldBounds),this.meshInstance._updateAabb=!1,this.meshInstance.visible=t,this._setMaterialTextures(),this.resetTime(),this.addTime(0,!1),this.preWarm&&this.prewarm(this.lifetime)}_isAnimated(){return this.animNumFrames>=1&&(this.animTilesX>1||this.animTilesY>1)&&(this.colorMap&&this.colorMap!==this.defaultParamTexture||this.normalMap)}rebuildGraphs(){const e=this.precision,t=this.graphicsDevice;this.qLocalVelocity=this.localVelocityGraph.quantize(e),this.qVelocity=this.velocityGraph.quantize(e),this.qColor=this.colorGraph.quantizeClamped(e,0,1),this.qRotSpeed=this.rotationSpeedGraph.quantize(e),this.qScale=this.scaleGraph.quantize(e),this.qAlpha=this.alphaGraph.quantize(e),this.qRadialSpeed=this.radialSpeedGraph.quantize(e),this.qLocalVelocity2=this.localVelocityGraph2.quantize(e),this.qVelocity2=this.velocityGraph2.quantize(e),this.qColor2=this.colorGraph2.quantizeClamped(e,0,1),this.qRotSpeed2=this.rotationSpeedGraph2.quantize(e),this.qScale2=this.scaleGraph2.quantize(e),this.qAlpha2=this.alphaGraph2.quantize(e),this.qRadialSpeed2=this.radialSpeedGraph2.quantize(e);for(let s=0;s<e;s++)this.qRotSpeed[s]*=H.DEG_TO_RAD,this.qRotSpeed2[s]*=H.DEG_TO_RAD;if(this.localVelocityUMax=new Float32Array(3),this.velocityUMax=new Float32Array(3),this.colorUMax=new Float32Array(3),this.rotSpeedUMax=[0],this.scaleUMax=[0],this.alphaUMax=[0],this.radialSpeedUMax=[0],this.qLocalVelocityDiv=Da(this.qLocalVelocity,this.qLocalVelocity2,this.localVelocityUMax),this.qVelocityDiv=Da(this.qVelocity,this.qVelocity2,this.velocityUMax),this.qColorDiv=Da(this.qColor,this.qColor2,this.colorUMax),this.qRotSpeedDiv=Da(this.qRotSpeed,this.qRotSpeed2,this.rotSpeedUMax),this.qScaleDiv=Da(this.qScale,this.qScale2,this.scaleUMax),this.qAlphaDiv=Da(this.qAlpha,this.qAlpha2,this.alphaUMax),this.qRadialSpeedDiv=Da(this.qRadialSpeed,this.qRadialSpeed2,this.radialSpeedUMax),this.pack8){const s=[0,0,0];ka(this.qVelocity,s);const i=[0,0,0];ka(this.qVelocity2,i);const r=[0,0,0];ka(this.qLocalVelocity,r);const a=[0,0,0];ka(this.qLocalVelocity2,a);const n=[0];ka(this.qRadialSpeed,n);const o=[0];ka(this.qRadialSpeed2,o);let c=Math.max(s[0],i[0]);c=Math.max(c,s[1]),c=Math.max(c,i[1]),c=Math.max(c,s[2]),c=Math.max(c,i[2]);let h=Math.max(r[0],a[0]);h=Math.max(h,r[1]),h=Math.max(h,a[1]),h=Math.max(h,r[2]),h=Math.max(h,a[2]);const d=Math.max(n[0],o[0]);this.maxVel=c+h+d}this.useCpu||(this.internalTex0=Vs(t,e,1,iy(this.qLocalVelocity,this.qLocalVelocityDiv)),this.internalTex1=Vs(t,e,1,iy(this.qVelocity,this.qVelocityDiv)),this.internalTex2=Vs(t,e,1,vD(this.qRotSpeed,this.qScale,this.qScaleDiv,this.qRotSpeedDiv,this.qAlphaDiv)),this.internalTex3=Vs(t,e,1,SD(this.qRadialSpeed,this.qRadialSpeedDiv))),this.colorParam=Vs(t,e,1,gD(this.qColor,this.qAlpha),us,1,!0)}_setMaterialTextures(){this.colorMap&&(this.material.setParameter("colorMap",this.colorMap),this.lighting&&this.normalMap&&this.material.setParameter("normalMap",this.normalMap))}_createMaterial(){const e=new mD(this);return e.name=`EmitterMaterial:${this.node.name}`,e.cull=Yt,e.alphaWrite=!1,e.blendType=this.blendType,e.depthWrite=this.depthWrite,e}resetMaterial(){const e=this.material;e.setParameter("stretch",this.stretch),this._isAnimated()&&(e.setParameter("animTexTilesParams",this.animTilesParams),e.setParameter("animTexParams",this.animParams),e.setParameter("animTexIndexParams",this.animIndexParams)),e.setParameter("colorMult",this.intensity),this.useCpu||(e.setParameter("internalTex0",this.internalTex0),e.setParameter("internalTex1",this.internalTex1),e.setParameter("internalTex2",this.internalTex2),e.setParameter("internalTex3",this.internalTex3)),e.setParameter("colorParam",this.colorParam),e.setParameter("numParticles",this.numParticles),e.setParameter("numParticlesPot",this.numParticlesPot),e.setParameter("lifetime",this.lifetime),e.setParameter("rate",this.rate),e.setParameter("rateDiv",this.rate2-this.rate),e.setParameter("seed",this.seed),e.setParameter("scaleDivMult",this.scaleUMax[0]),e.setParameter("alphaDivMult",this.alphaUMax[0]),e.setParameter("radialSpeedDivMult",this.radialSpeedUMax[0]),e.setParameter("graphNumSamples",this.precision),e.setParameter("graphSampleSize",1/this.precision),e.setParameter("emitterScale",new Float32Array([1,1,1])),this.pack8&&(this._gpuUpdater._setInputBounds(),e.setParameter("inBoundsSize",this._gpuUpdater.inBoundsSizeUniform),e.setParameter("inBoundsCenter",this._gpuUpdater.inBoundsCenterUniform),e.setParameter("maxVel",this.maxVel)),this.wrap&&this.wrapBounds&&(this.wrapBoundsUniform[0]=this.wrapBounds.x,this.wrapBoundsUniform[1]=this.wrapBounds.y,this.wrapBoundsUniform[2]=this.wrapBounds.z,e.setParameter("wrapBounds",this.wrapBoundsUniform)),this._setMaterialTextures(),this.depthSoftening>0&&e.setParameter("softening",1/(this.depthSoftening*this.depthSoftening*100)),this.stretch>0&&(e.cull=Yt),this._compParticleFaceParams()}_compParticleFaceParams(){let e,t;if(this.orientation===ru)e=new Float32Array([1,0,0]),t=new Float32Array([0,0,1]);else{let s;this.orientation===yI?s=this.particleNormal.normalize():s=(this.node===null?Z.IDENTITY:this.node.getWorldTransform()).transformVector(this.particleNormal).normalize();const i=new E(1,0,0);Math.abs(i.dot(s))===1&&i.set(0,0,1);const r=new E().cross(s,i).normalize();i.cross(r,s).normalize(),e=new Float32Array([i.x,i.y,i.z]),t=new Float32Array([r.x,r.y,r.z])}this.material.setParameter("faceTangent",e),this.material.setParameter("faceBinorm",t)}getVertexInfo(){const e=[];return this.useCpu?e.push({semantic:Vm,components:4,type:je},{semantic:Jd,components:4,type:je},{semantic:lg,components:4,type:je},{semantic:cg,components:1,type:je},{semantic:hg,components:this.useMesh?4:2,type:je}):(e.push({semantic:Vm,components:4,type:je}),this.useMesh&&e.push({semantic:Jd,components:2,type:je})),e}_allocate(e){const t=e*this.numParticleVerts,s=e*this.numParticleIndices;if(this.vertexBuffer===void 0||this.vertexBuffer.getNumVertices()!==t){const i=this.getVertexInfo(),r=new
431Us(this.graphicsDevice,i);this.vertexBuffer=new Hi(this.graphicsDevice,r,t,{usage:Vd}),this.indexBuffer=new la(this.graphicsDevice,ra,s);const a=new Float32Array(this.vertexBuffer.lock());let n,o,c;if(this.useMesh){n=new Float32Array(this.mesh.vertexBuffer.lock()),o=n.length/this.mesh.vertexBuffer.numVertices;for(let u=0;u<this.mesh.vertexBuffer.format.elements.length;u++)if(this.mesh.vertexBuffer.format.elements[u].name===Zs){c=this.mesh.vertexBuffer.format.elements[u].offset/4;break}}for(let u=0;u<t;u++){const f=Math.floor(u/this.numParticleVerts);if(this.useMesh){const p=u%this.numParticleVerts;a[u*6]=n[p*o],a[u*6+1]=n[p*o+1],a[u*6+2]=n[p*o+2],a[u*6+3]=f,a[u*6+4]=n[p*o+c+0],a[u*6+5]=1-n[p*o+c+1]}else{const p=u%4;a[u*4]=ZS[p][0],a[u*4+1]=ZS[p][1],a[u*4+2]=0,a[u*4+3]=f}}this.useCpu&&(this.vbCPU=new Float32Array(a),this.vbOld=new Float32Array(this.vbCPU.length)),this.vertexBuffer.unlock(),this.useMesh&&this.mesh.vertexBuffer.unlock();let h=0;const d=new Uint32Array(this.indexBuffer.lock());if(this.useMesh){const u=this.mesh.indexBuffer[0];n=new vg[u.format](u.lock())}for(let u=0;u<e;u++)if(this.useMesh)for(let f=0;f<this.numParticleIndices;f++)d[u*this.numParticleIndices+f]=n[f]+u*this.numParticleVerts;else{const f=u*4;d[h++]=f,d[h++]=f+1,d[h++]=f+2,d[h++]=f,d[h++]=f+2,d[h++]=f+3}this.indexBuffer.unlock(),this.useMesh&&this.mesh.indexBuffer[0].unlock()}}reset(){if(this.beenReset=!0,this.seed=Math.random(),this.material.setParameter("seed",this.seed),this.useCpu)for(let t=0;t<this.particleTexStart.length;t++)this.particleTex[t]=this.particleTexStart[t];else this._setMaterialTextures();this.resetWorldBounds(),this.resetTime();const e=this.loop;this.loop=!0,this.addTime(0,!1),this.loop=e,this.preWarm&&this.prewarm(this.lifetime)}prewarm(e){const t=e/this.lifetime,s=Math.min(Math.floor(t*this.precision),this.precision),i=e/s;for(let r=0;r<s;r++)this.addTime(i,!1)}resetTime(){this.endTime=yD(this)}finishFrame(){this.useCpu&&this.vertexBuffer.unlock()}addTime(e,t){const s=this.graphicsDevice;if(this.simTimeTotal+=e,this.calculateWorldBounds(),this._isAnimated()){const a=this.animTilesParams;a[0]=1/this.animTilesX,a[1]=1/this.animTilesY;const n=this.animParams;n[0]=this.animStartFrame,n[1]=this.animNumFrames*this.animSpeed,n[2]=this.animNumFrames-1,n[3]=this.animNumAnimations-1;const o=this.animIndexParams;o[0]=this.animIndex,o[1]=this.randomizeAnimIndex}this.scene&&this.camera!==this.scene._activeCamera&&(this.camera=this.scene._activeCamera,this.onChangeCamera()),this.emitterShape===Ri&&(Qi[0]=this.emitterExtents.x!==0?this.emitterExtentsInner.x/this.emitterExtents.x:0,Qi[1]=this.emitterExtents.y!==0?this.emitterExtentsInner.y/this.emitterExtents.y:0,Qi[2]=this.emitterExtents.z!==0?this.emitterExtentsInner.z/this.emitterExtents.z:0,this.meshInstance.node===null?Ia.setTRS(E.ZERO,ae.IDENTITY,this.emitterExtents):Ia.setTRS(E.ZERO,this.meshInstance.node.getRotation(),sy.copy(this.emitterExtents).mul(this.meshInstance.node.localScale)));let i;const r=this.meshInstance.node===null?E.ONE:this.meshInstance.node.localScale;if(this.emitterScaleUniform[0]=r.x,this.emitterScaleUniform[1]=r.y,this.emitterScaleUniform[2]=r.z,this.material.setParameter("emitterScale",this.emitterScaleUniform),this.localSpace&&this.meshInstance.node&&(i=this.meshInstance.node.getPosition(),this.emitterPosUniform[0]=i.x,this.emitterPosUniform[1]=i.y,this.emitterPosUniform[2]=i.z,this.material.setParameter("emitterPos",this.emitterPosUniform)),this._compParticleFaceParams(),!this.useCpu)this._gpuUpdater.update(s,Ia,Qi,e,t);else{const a=new Float32Array(this.vertexBuffer.lock());this._cpuUpdater.update(a,this.vbToSort,this.particleTex,Ia,Qi,i,e,t)}this.loop||Date.now()>this.endTime&&(this.onFinished&&this.onFinished(),this.meshInstance.visible=!1),this.meshInstance&&(this.meshInstance.drawOrder=this.drawOrder)}_destroyResources(){this.particleTexIN?.destroy(),this.particleTexIN=null,this.particleTexOUT?.destroy(),this.particleTexOUT=null,this.particleTexStart&&this.particleTexStart.destroy&&(this.particleTexStart.destroy(),this.particleTexStart=null),this.rtParticleTexIN?.destroy(),this.rtParticleTexIN=null,this.rtParticleTexOUT?.destroy(),this.rtParticleTexOUT=null,this.internalTex0?.destroy(),this.internalTex0=null,this.internalTex1?.destroy(),this.internalTex1=null,this.internalTex2?.destroy(),this.internalTex2=null,this.internalTex3?.destroy(),this.internalTex3=null,this.colorParam?.destroy(),this.colorParam=null,this.vertexBuffer=void 0,this.indexBuffer=void 0;const e=this.meshInstance?.visible??!0;return this.meshInstance?.destroy(),this.meshInstance=null,this.material?.destroy(),this.material=null,e}destroy(){this.camera=null,this._destroyResources()}}class ED extends ln{generateKey(e){const t=e.shaderDesc,s=t.vertexGLSL?Xs(t.vertexGLSL):0,i=t.fragmentGLSL?Xs(t.fragmentGLSL):0,r=t.vertexWGSL?Xs(t.vertexWGSL):0,a=t.fragmentWGSL?Xs(t.fragmentWGSL):0,n=ln.definesHash(e.defines),o=e.shaderChunks?.key??"";let c=`${t.uniqueName}_${n}_${s}_${i}_${r}_${a}_${o}`;return e.skin&&(c+="_skin"),e.useInstancing&&(c+="_inst"),e.useMorphPosition&&(c+="_morphp"),e.useMorphNormal&&(c+="_morphn"),e.useMorphTextureBasedInt&&(c+="_morphi"),c}createAttributesDefinition(e,t){const s=t.shaderDesc.attributes,i=s?{...s}:void 0;t.skin&&(i.vertex_boneWeights=ki,i.vertex_boneIndices=Bs),(t.useMorphPosition||t.useMorphNormal)&&(i.morph_vertex_id=Io),e.attributes=i}createVertexDefinition(e,t,s,i){const r=t.shaderDesc,a=new Map(s);a.set("transformInstancingVS","");const n=new Map(t.defines);t.skin&&n.set("SKIN",!0),t.useInstancing&&n.set("INSTANCING",!0),(t.useMorphPosition||t.useMorphNormal)&&(n.set("MORPHING",!0),t.useMorphTextureBasedInt&&n.set("MORPHING_INT",!0),t.useMorphPosition&&n.set("MORPHING_POSITION",!0),t.useMorphNormal&&n.set("MORPHING_NORMAL",!0)),e.vertexCode=i?r.vertexWGSL:r.vertexGLSL,e.vertexIncludes=a,e.vertexDefines=n}createFragmentDefinition(e,t,s,i){const r=t.shaderDesc,a=new Map(s),n=new Map(t.defines);e.fragmentCode=i?r.fragmentWGSL:r.fragmentGLSL,e.fragmentIncludes=a,e.fragmentDefines=n}createShaderDefinition(e,t){const s=t.shaderDesc,i=e.isWebGPU&&!!s.vertexWGSL&&!!s.fragmentWGSL&&(t.shaderChunks?.useWGSL??!0),r={name:`ShaderMaterial-${s.uniqueName}`,shaderLanguage:i?de:ze,fragmentOutputTypes:s.fragmentOutputTypes,meshUniformBufferFormat:s.meshUniformBufferFormat,meshBindGroupFormat:s.meshBindGroupFormat},a=i?de:ze,n=du.merge(be.get(e,a),t.shaderChunks[a]);return this.createAttributesDefinition(r,t),this.createVertexDefinition(r,t,n,i),this.createFragmentDefinition(r,t,n,i),Ht.createDefinition(e,r)}}const bD=new ED;class ei extends yn{_shaderDesc;constructor(e){super(),this.shaderDesc=e}set shaderDesc(e){if(this._shaderDesc=void 0,e&&(this._shaderDesc={uniqueName:e.uniqueName,attributes:e.attributes,fragmentOutputTypes:e.fragmentOutputTypes,vertexGLSL:e.vertexGLSL,fragmentGLSL:e.fragmentGLSL,vertexWGSL:e.vertexWGSL,fragmentWGSL:e.fragmentWGSL},e.vertexCode||e.fragmentCode||e.shaderLanguage)){const t=e.shaderLanguage??ze;t===ze?(this._shaderDesc.vertexGLSL=e.vertexCode,this._shaderDesc.fragmentGLSL=e.fragmentCode):t===de&&(this._shaderDesc.vertexWGSL=e.vertexCode,this._shaderDesc.fragmentWGSL=e.fragmentCode)}this.clearVariants()}get shaderDesc(){return this._shaderDesc}copy(e){return super.copy(e),this.shaderDesc=e.shaderDesc,this}getShaderVariant(e){const{objDefs:t}=e,s={defines:Qt.getCoreDefines(this,e),skin:(t&fc)!==0,useInstancing:(t&pc)!==0,useMorphPosition:(t&mc)!==0,useMorphNormal:(t&_c)!==0,useMorphTextureBasedInt:(t&gc)!==0,pass:e.pass,gamma:e.cameraShaderParams.shaderOutputGamma,toneMapping:e.cameraShaderParams.toneMapping,fog:e.cameraShaderParams.fog,shaderDesc:this.shaderDesc,shaderChunks:this.shaderChunks},i=new Df(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),r=ko(e.device);return r.register("shader-material",bD),r.getProgram("shader-material",s,i,this.userId)}}var AD=` 432uniform highp {sampler} {name}; 433{returnType} load{funcName}() { return texelFetch({name}, splat.uv, 0); } 434{returnType} load{funcName}WithIndex(uint index) { return texelFetch({name}, ivec2(index % splatTextureSize, index / splatTextureSize), 0); } 435`,PD=` 436var {name}: {textureType}; 437fn load{funcName}() -> {returnType} { return textureLoad({name}, splat.uv, 0); } 438fn load{funcName}WithIndex(index: u32) -> {returnType} { return textureLoad({name}, vec2i(i32(index % uniform.splatTextureSize), i32(index / uniform.splatTextureSize)), 0); } 439`,ID=` 440@group(0) @binding({binding}) var {name}: {textureType}; 441fn load{funcName}() -> {returnType} { return textureLoad({name}, splat.uv, 0); } 442fn load{funcName}WithIndex(index: u32) -> {returnType} { return textureLoad({name}, vec2i(i32(index % uniforms.splatTextureSize), i32(index / uniforms.splatTextureSize)), 0); } 443`,ry=` 444void write{funcName}({returnType} value) { 445#if {defineGuard} 446 pcFragColor{index} = value; 447#endif 448} 449`,ay=` 450fn write{funcName}(value: {returnType}) { 451#if {defineGuard} 452 processOutput.{colorSlot} = value; 453#endif 454} 455`,ew=` 456vec3 getCenter() { return loadDataCenter().xyz; } 457vec4 getColor() { return loadDataColor(); } 458vec3 getScale() { return loadDataScale().xyz; } 459vec4 getRotation() { return loadDataRotation(); } 460`,tw=` 461fn getCenter() -> vec3f { return loadDataCenter().xyz; } 462fn getColor() -> vec4f { return loadDataColor(); } 463fn getScale() -> vec3f { return loadDataScale().xyz; } 464fn getRotation() -> vec4f { return loadDataRotation(); } 465`,DD=` 466 vec3 getCenter() { return loadDataCenter().xyz; } 467 vec4 getColor() { return loadDataColor(); } 468 vec3 getScale() { return vec3(loadDataCenter().w); } 469 vec4 getRotation() { return vec4(0.0, 0.0, 0.0, 1.0); } 470`,MD=` 471 fn getCenter() -> vec3f { return loadDataCenter().xyz; } 472 fn getColor() -> vec4f { return loadDataColor(); } 473 fn getScale() -> vec3f { return vec3f(loadDataCenter().w); } 474 fn getRotation() -> vec4f { return vec4f(0.0, 0.0, 0.0, 1.0); } 475`;const ny=l=>l.map(e=>`${e.name}:${e.format}:${e.storage}`).join(","),oy=/\{name\}/g,RD=/\{sampler\}/g,ly=/\{textureType\}/g,zh=/\{returnType\}/g,Vh=/\{funcName\}/g,LD=/\{binding\}/g,FD=/\{index\}/g,OD=/\{colorSlot\}/g,cy=/\{defineGuard\}/g;class ca{_device;streams;_read;allowStreamRemoval=!1;_extraStreams=[];_streamNames=new Set;_extraStreamsVersion=0;_hash;_resourceStreams=null;_instanceStreams=null;constructor(e,t,s){this._device=e,this.streams=[...t],this._streamNames=new Set(this.streams.map(r=>r.name));const i=e.isWebGPU;
475this._read=i?s.readWGSL:s.readGLSL}get hash(){if(this._hash===void 0){const e=ny(this.streams),t=ny(this._extraStreams);this._hash=Xs(e+t+this._read)}return this._hash}get extraStreamsVersion(){return this._extraStreamsVersion}get extraStreams(){return this._extraStreams}get resourceStreams(){return this._resourceStreams===null&&(this._resourceStreams=[...this.streams.filter(e=>e.storage!==dp),...this._extraStreams.filter(e=>e.storage!==dp)]),this._resourceStreams}get instanceStreams(){return this._instanceStreams===null&&(this._instanceStreams=this._extraStreams.filter(e=>e.storage===dp)),this._instanceStreams}addExtraStreams(e){if(!e||e.length===0)return;let t=!1;for(const s of e)this._streamNames.has(s.name)||(this._extraStreams.push({name:s.name,format:s.format,storage:s.storage??YI}),this._streamNames.add(s.name),t=!0);t&&(this._extraStreamsVersion++,this._invalidateCaches())}removeExtraStreams(e){if(!this.allowStreamRemoval)return;let t=!1;for(const s of e){const i=this._extraStreams.findIndex(r=>r.name===s);i!==-1&&(this._extraStreams.splice(i,1),this._streamNames.delete(s),t=!0)}t&&(this._extraStreamsVersion++,this._invalidateCaches())}getInputDeclarations(e){const t=this._device.isWebGPU,s=t?PD:AD,i=t?ph:yd,r=[];let a=[...this.streams,...this._extraStreams];e&&(a=a.filter(n=>e.includes(n.name)));for(const n of a){const o=i(n.format),c=n.name.charAt(0).toUpperCase()+n.name.slice(1);let h=o.textureType??"";t&&n.format===mt&&(h="texture_2d<uff>");const d=s.replace(oy,n.name).replace(RD,o.sampler??"").replace(ly,h).replace(zh,o.returnType).replace(Vh,c);r.push(d)}return r.join(` 476`)}getReadCode(){return this._read}getComputeInputDeclarations(e,t){const s=[];let i=[...this.streams,...this._extraStreams];t&&(i=i.filter(r=>t.includes(r.name)));for(let r=0;r<i.length;r++){const a=i[r],n=ph(a.format),o=a.name.charAt(0).toUpperCase()+a.name.slice(1);let c=n.textureType??"";a.format===mt&&(c="texture_2d<uff>");const h=ID.replace(LD,String(e+r)).replace(oy,a.name).replace(ly,c).replace(zh,n.returnType).replace(Vh,o);s.push(h)}return s.join(` 477`)}getComputeBindFormats(e){let t=[...this.streams,...this._extraStreams];return e&&(t=t.filter(s=>e.includes(s.name))),t.map(s=>{const i=fs.get(s.format);let r=ls;return i?.isUint?r=na:i?.isInt&&(r=aa),new No(s.name,G,void 0,r,!1)})}setWriteCode(e,t){this._write=this._device.isWebGPU?t:e}getWriteCode(){return this._write}getOutputDeclarations(e){const t=this._device.isWebGPU,s=[],i=t?ay:ry,r=t?ph:yd;for(let a=0;a<e.length;a++){const n=e[a],o=r(n.format),c=n.name.charAt(0).toUpperCase()+n.name.slice(1),h=a===0?"color":`color${a}`,d=i.replace(Vh,c).replace(zh,o.returnType).replace(FD,String(a)).replace(OD,h).replace(cy,"1");s.push(d)}return s.join(` 478`)}getOutputStubs(e){const t=this._device.isWebGPU,s=[],i=t?ay:ry,r=t?ph:yd;for(const a of e){const n=r(a.format),o=a.name.charAt(0).toUpperCase()+a.name.slice(1),c=i.replace(Vh,o).replace(zh,n.returnType).replace(cy,"0");s.push(c)}return s.join(` 479`)}getStream(e){let t=this.streams.find(s=>s.name===e);return t||(t=this._extraStreams.find(s=>s.name===e)),t}
479_invalidateCaches(){this._hash=void 0,this._resourceStreams=null,this._instanceStreams=null}static createDefaultFormat(e){return new ca(e,[{name:"dataColor",format:Ge},{name:"dataCenter",format:mt},{name:"dataScale",format:Ge},{name:"dataRotation",format:Ge}],{readGLSL:ew,readWGSL:tw})}static createSimpleFormat(e){return new ca(e,[{name:"dataCenter",format:mt},{name:"dataColor",format:Ge}],{readGLSL:DD,readWGSL:MD})}}var BD=` 480uvec4 cachedTransformA; 481vec3 getCenter() { 482 cachedTransformA = loadDataTransformA(); 483 return vec3(uintBitsToFloat(cachedTransformA.r), uintBitsToFloat(cachedTransformA.g), uintBitsToFloat(cachedTransformA.b)); 484} 485float getOpacity() { 486 return float(cachedTransformA.a >> 24u) / 255.0; 487} 488vec3 getColor() { 489 uint data = loadDataColor().x; 490 float r = float(data & 0x7FFu) * (4.0 / 2047.0); 491 float g = float((data >> 11u) & 0x7FFu) * (4.0 / 2047.0); 492 float b = float((data >> 22u) & 0x3FFu) * (4.0 / 1023.0); 493 return vec3(r, g, b); 494} 495vec4 getRotation() { 496 uint data = loadDataTransformB().x; 497 vec3 p = vec3( 498 float(data & 0x7FFu) / 2047.0 * 2.0 - 1.0, 499 float((data >> 11u) & 0x7FFu) / 2047.0 * 2.0 - 1.0, 500 float((data >> 22u) & 0x3FFu) / 1023.0 * 2.0 - 1.0 501 ); 502 float d = dot(p, p); 503 return vec4(1.0 - d, sqrt(max(0.0, 2.0 - d)) * p); 504} 505vec3 getScale() { 506 uint data = cachedTransformA.a; 507 float sx = float(data & 0xFFu); 508 float sy = float((data >> 8u) & 0xFFu); 509 float sz = float((data >> 16u) & 0xFFu); 510 const float logRange = 21.0 / 255.0; 511 const float logMin = -12.0; 512 return vec3( 513 sx == 0.0 ? 0.0 : exp(sx * logRange + logMin), 514 sy == 0.0 ? 0.0 : exp(sy * logRange + logMin), 515 sz == 0.0 ? 0.0 : exp(sz * logRange + logMin) 516 ); 517} 518`,ND=` 519void writeSplat(vec3 center, vec4 rotation, vec3 scale, vec4 color) { 520 vec3 rgb = clamp(color.rgb, 0.0, 4.0); 521 uint rBits = uint(rgb.r * (2047.0 / 4.0) + 0.5); 522 uint gBits = uint(rgb.g * (2047.0 / 4.0) + 0.5); 523 uint bBits = uint(rgb.b * (1023.0 / 4.0) + 0.5); 524 writeDataColor(uvec4(rBits | (gBits << 11u) | (bBits << 22u), 0u, 0u, 0u)); 525 #ifndef GSPLAT_COLOR_ONLY 526 vec4 q = rotation; 527 if (q.w < 0.0) q = -q; 528 vec3 p = q.xyz * inversesqrt(1.0 + q.w); 529 uint aBitsQ = uint(clamp((p.x * 0.5 + 0.5) * 2047.0 + 0.5, 0.0, 2047.0)); 530 uint bBitsQ = uint(clamp((p.y * 0.5 + 0.5) * 2047.0 + 0.5, 0.0, 2047.0)); 531 uint cBitsQ = uint(clamp((p.z * 0.5 + 0.5) * 1023.0 + 0.5, 0.0, 1023.0)); 532 uint packedQuat = aBitsQ | (bBitsQ << 11u) | (cBitsQ << 22u); 533 const float invLogRange = 255.0 / 21.0; 534 const float logMin = -12.0; 535 uint sxBits = scale.x < 1e-10 ? 0u : uint(clamp((log(scale.x) - logMin) * invLogRange + 0.5, 1.0, 255.0)); 536 uint syBits = scale.y < 1e-10 ? 0u : uint(clamp((log(scale.y) - logMin) * invLogRange + 0.5, 1.0, 255.0)); 537 uint szBits = scale.z < 1e-10 ? 0u : uint(clamp((log(scale.z) - logMin) * invLogRange + 0.5, 1.0, 255.0)); 538 uint alphaBits = uint(clamp(color.a, 0.0, 1.0) * 255.0 + 0.5); 539 uint packedScaleAlpha = sxBits | (syBits << 8u) | (szBits << 16u) | (alphaBits << 24u); 540 writeDataTransformA(uvec4(floatBitsToUint(center.x), floatBitsToUint(center.y), floatBitsToUint(center.z), packedScaleAlpha)); 541 writeDataTransformB(uvec4(packedQuat, 0u, 0u, 0u)); 542 #endif 543} 544`,kD=` 545uvec4 cachedTransformA; 546uvec2 cachedTransformB; 547vec4 cachedColor; 548vec3 getCenter() { 549 cachedTransformA = loadDataTransformA(); 550 cachedTransformB = loadDataTransformB().xy; 551 return vec3(uintBitsToFloat(cachedTransformA.r), uintBitsToFloat(cachedTransformA.g), uintBitsToFloat(cachedTransformA.b)); 552} 553float getOpacity() { 554 #ifdef GSPLAT_COLOR_FLOAT 555 cachedColor = loadDataColor(); 556 #else 557 uvec4 packedColor = loadDataColor(); 558 uint packed_rg = packedColor.r | (packedColor.g << 16u); 559 uint packed_ba = packedColor.b | (packedColor.a << 16u); 560 cachedColor = vec4(unpackHalf2x16(packed_rg), unpackHalf2x16(packed_ba)); 561 #endif 562 return cachedColor.a; 563} 564vec3 getColor() { 565 return cachedColor.rgb; 566} 567vec4 getRotation() { 568 vec2 rotXY = unpackHalf2x16(cachedTransformA.a); 569 vec2 rotZscaleX = unpackHalf2x16(cachedTransformB.x); 570 vec3 rotXYZ = vec3(rotXY, rotZscaleX.x); 571 return vec4(rotXYZ, sqrt(max(0.0, 1.0 - dot(rotXYZ, rotXYZ)))).wxyz; 572} 573vec3 getScale() { 574 vec2 rotZscaleX = unpackHalf2x16(cachedTransformB.x); 575 vec2 scaleYZ = unpackHalf2x16(cachedTransformB.y); 576 return vec3(rotZscaleX.y, scaleYZ); 577} 578`,UD=` 579void writeSplat(vec3 center, vec4 rotation, vec3 scale, vec4 color) { 580 #ifdef GSPLAT_COLOR_UINT 581 uint packed_rg = packHalf2x16(color.rg); 582 uint packed_ba = packHalf2x16(color.ba); 583 writeDataColor(uvec4( 584 packed_rg & 0xFFFFu, 585 packed_rg >> 16u, 586 packed_ba & 0xFFFFu, 587 packed_ba >> 16u 588 )); 589 #else 590 writeDataColor(color); 591 #endif 592 #ifndef GSPLAT_COLOR_ONLY 593 writeDataTransformA(uvec4(floatBitsToUint(center.x), floatBitsToUint(center.y), floatBitsToUint(center.z), packHalf2x16(rotation.xy))); 594 writeDataTransformB(uvec4(packHalf2x16(vec2(rotation.z, scale.x)), packHalf2x16(scale.yz), 0u, 0u)); 595 #endif 596} 597`,zD=` 598var<private> cachedTransformA: vec4u; 599fn getCenter() -> vec3f { 600 cachedTransformA = loadDataTransformA(); 601 return vec3f(bitcast<f32>(cachedTransformA.r), bitcast<f32>(cachedTransformA.g), bitcast<f32>(cachedTransformA.b)); 602} 603fn getOpacity() -> f32 { 604 return f32(cachedTransformA.a >> 24u) / 255.0; 605} 606fn getColor() -> vec3f { 607 let data = loadDataColor().x; 608 let r = f32(data & 0x7FFu) * (4.0 / 2047.0); 609 let g = f32((data >> 11u) & 0x7FFu) * (4.0 / 2047.0); 610 let b = f32((data >>
610 22u) & 0x3FFu) * (4.0 / 1023.0); 611 return vec3f(r, g, b); 612} 613fn getRotation() -> vec4f { 614 let data = loadDataTransformB().x; 615 let p = vec3f( 616 f32(data & 0x7FFu) / 2047.0 * 2.0 - 1.0, 617 f32((data >> 11u) & 0x7FFu) / 2047.0 * 2.0 - 1.0, 618 f32((data >> 22u) & 0x3FFu) / 1023.0 * 2.0 - 1.0 619 ); 620 let d = dot(p, p); 621 return vec4f(1.0 - d, sqrt(max(0.0, 2.0 - d)) * p); 622} 623fn getScale() -> vec3f { 624 let data = cachedTransformA.a; 625 let sx = f32(data & 0xFFu); 626 let sy = f32((data >> 8u) & 0xFFu); 627 let sz = f32((data >> 16u) & 0xFFu); 628 let logRange = 21.0 / 255.0; 629 let logMin = -12.0; 630 return vec3f( 631 select(exp(sx * logRange + logMin), 0.0, sx == 0.0), 632 select(exp(sy * logRange + logMin), 0.0, sy == 0.0), 633 select(exp(sz * logRange + logMin), 0.0, sz == 0.0) 634 ); 635} 636`,VD=` 637fn writeSplat(center: vec3f, rotation: vec4f, scale: vec3f, color: vec4f) { 638 let rgb = clamp(color.rgb, vec3f(0.0), vec3f(4.0)); 639 let rBits = u32(rgb.r * (2047.0 / 4.0) + 0.5); 640 let gBits = u32(rgb.g * (2047.0 / 4.0) + 0.5); 641 let bBits = u32(rgb.b * (1023.0 / 4.0) + 0.5); 642 writeDataColor(vec4u(rBits | (gBits << 11u) | (bBits << 22u), 0u, 0u, 0u)); 643 #ifndef GSPLAT_COLOR_ONLY 644 var q = rotation; 645 if (q.w < 0.0) { q = -q; } 646 let p = q.xyz * inverseSqrt(1.0 + q.w); 647 let aBitsQ = u32(clamp(p.x * 0.5 + 0.5, 0.0, 1.0) * 2047.0 + 0.5); 648 let bBitsQ = u32(clamp(p.y * 0.5 + 0.5, 0.0, 1.0) * 2047.0 + 0.5); 649 let cBitsQ = u32(clamp(p.z * 0.5 + 0.5, 0.0, 1.0) * 1023.0 + 0.5); 650 let packedQuat = aBitsQ | (bBitsQ << 11u) | (cBitsQ << 22u); 651 let invLogRange = 255.0 / 21.0; 652 let logMin = -12.0; 653 let sxBits = select(u32(clamp((log(scale.x) - logMin) * invLogRange + 0.5, 1.0, 255.0)), 0u, scale.x < 1e-10); 654 let syBits = select(u32(clamp((log(scale.y) - logMin) * invLogRange + 0.5, 1.0, 255.0)), 0u, scale.y < 1e-10); 655 let szBits = select(u32(clamp((log(scale.z) - logMin) * invLogRange + 0.5, 1.0, 255.0)), 0u, scale.z < 1e-10); 656 let alphaBits = u32(clamp(color.a, 0.0, 1.0) * 255.0 + 0.5); 657 let packedScaleAlpha = sxBits | (syBits << 8u) | (szBits << 16u) | (alphaBits << 24u); 658 writeDataTransformA(vec4u(bitcast<u32>(center.x), bitcast<u32>(center.y), bitcast<u32>(center.z), packedScaleAlpha)); 659 writeDataTransformB(vec4u(packedQuat, 0u, 0u, 0u)); 660 #endif 661} 662`,GD=` 663var<private> cachedTransformA: vec4u; 664var<private> cachedTransformB: vec2u; 665var<private> cachedColor: vec4f; 666fn getCenter() -> vec3f { 667 cachedTransformA = loadDataTransformA(); 668 cachedTransformB = loadDataTransformB().xy; 669 return vec3f(bitcast<f32>(cachedTransformA.r), bitcast<f32>(cachedTransformA.g), bitcast<f32>(cachedTransformA.b)); 670} 671fn getOpacity() -> f32 { 672 #ifdef GSPLAT_COLOR_FLOAT 673 cachedColor = loadDataColor(); 674 #else 675 let packedColor = loadDataColor(); 676 let packed_rg = packedColor.r | (packedColor.g << 16u); 677 let packed_ba = packedColor.b | (packedColor.a << 16u); 678 cachedColor = vec4f(unpack2x16float(packed_rg), unpack2x16float(packed_ba)); 679 #endif 680 return cachedColor.a; 681} 682fn getColor() -> vec3f { 683 return cachedColor.rgb; 684} 685fn getRotation() -> vec4f { 686 let rotXY = unpack2x16float(cachedTransformA.a); 687 let rotZscaleX = unpack2x16float(cachedTransformB.x); 688 let rotXYZ = vec3f(rotXY, rotZscaleX.x); 689 return vec4f(rotXYZ, sqrt(max(0.0, 1.0 - dot(rotXYZ, rotXYZ)))).wxyz; 690} 691fn getScale() -> vec3f { 692 let rotZscaleX = unpack2x16float(cachedTransformB.x); 693 let scaleYZ = unpack2x16float(cachedTransformB.y); 694 return vec3f(rotZscaleX.y, scaleYZ); 695} 696`,HD=` 697fn writeSplat(center: vec3f, rotation: vec4f, scale: vec3f, color: vec4f) { 698 writeDataColor(color); 699 #ifndef GSPLAT_COLOR_ONLY 700 writeDataTransformA(vec4u(bitcast<u32>(center.x), bitcast<u32>(center.y), bitcast<u32>(center.z), pack2x16float(rotation.xy))); 701 writeDataTransformB(vec4u(pack2x16float(vec2f(rotation.z, scale.x)), pack2x16float(scale.yz), 0u, 0u)); 702 #endif 703} 704`;class WD{_material=new ei;_format;_device;_dataFormat=up;constructor(e){this._device=e,this._format=this._createFormat(up),this._material.setParameter("alphaClip",.3),this._material.setParameter("alphaClipForward",1/255),this._material.setParameter("minPixelSize",2),this._material.setParameter("minContribution",3)}_createFormat(e){let t;
704if(e===up)t=new ca(this._device,[{name:"dataColor",format:js},{name:"dataTransformA",format:Wt},{name:"dataTransformB",format:js}],{readGLSL:BD,readWGSL:zD}),t.setWriteCode(ND,VD);else{const s=this._device.getRenderableHdrFormat([Ge])||Vi;t=new ca(this._device,[{name:"dataColor",format:s},{name:"dataTransformA",format:Wt},{name:"dataTransformB",format:Nc}],{readGLSL:kD,readWGSL:GD}),t.setWriteCode(UD,HD)}return t.allowStreamRemoval=!0,t}radialSorting=!1;_renderer=hS;_currentRenderer=To;set renderer(e){this._renderer!==e&&(this._renderer=e,e===hS?this._currentRenderer=To:(e===Pd||e===uo)&&!this._device.isWebGPU?this._currentRenderer=To:this._currentRenderer=e)}get renderer(){return this._renderer}get currentRenderer(){return this._currentRenderer}dirty=!1;_debug=ol;set debug(e){if(this._debug!==e){const t=this._debug;this._debug=e,(e===Bl||t===Bl||e===e_||t===e_)&&(this.dirty=!0)}}get debug(){return this._debug}set colorizeLod(e){this.debug=e?Bl:ol}get colorizeLod(){return this._debug===Bl}set debugAabbs(e){this.debug=e?dS:ol}get debugAabbs(){return this._debug===dS}set debugNodeAabbs(e){this.debug=e?uS:ol}get debugNodeAabbs(){return this._debug===uS}_enableIds=!1;set enableIds(e){e&&!this._enableIds?(this._enableIds=!0,this._format.getStream("pcId")||this._format.addExtraStreams([{name:"pcId",format:js}])):!e&&this._enableIds&&(this._enableIds=!1,this._format.removeExtraStreams(["pcId"]))}get enableIds(){return this._enableIds}lodUpdateDistance=1;lodUpdateAngle=0;_lodBehindPenalty=1;set lodBehindPenalty(e){this._lodBehindPenalty!==e&&(this._lodBehindPenalty=e,this.dirty=!0)}get lodBehindPenalty(){return this._lodBehindPenalty}_lodRangeMin=0;set lodRangeMin(e){this._lodRangeMin!==e&&(this._lodRangeMin=e,this.dirty=!0)}get lodRangeMin(){return this._lodRangeMin}_lodRangeMax=10;set lodRangeMax(e){this._lodRangeMax!==e&&(this._lodRangeMax=e,this.dirty=!0)}get lodRangeMax(){return this._lodRangeMax}_lodUnderfillLimit=0;set lodUnderfillLimit(e){this._lodUnderfillLimit!==e&&(this._lodUnderfillLimit=e,this.dirty=!0)}get lodUnderfillLimit(){return this._lodUnderfillLimit}_splatBudget=0;set splatBudget(e){this._splatBudget!==e&&(this._splatBudget=e,this.dirty=!0)}get splatBudget(){return this._splatBudget}_colorRamp=null;set colorRamp(e){this._colorRamp!==e&&(this._colorRamp=e,this.dirty=!0)}get colorRamp(){return this._colorRamp}colorRampIntensity=1;useFog=!0;set colorizeColorUpdate(e){this.debug=e?Jm:ol}get colorizeColorUpdate(){return this._debug===Jm}colorUpdateAngle=10;set colorUpdateDistance(e){}get colorUpdateDistance(){return 0}set colorUpdateDistanceLodScale(e){}get colorUpdateDistanceLodScale(){return 0}set colorUpdateAngleLodScale(e){}get colorUpdateAngleLodScale(){return 0}set alphaClip(e){this._material.setParameter("alphaClip",e),this._material.update()}get alphaClip(){return this._material.getParameter("alphaClip")?.data??.3}set alphaClipForward(e){this._material.setParameter("alphaClipForward",e),this._material.update()}get alphaClipForward(){return this._material.getParameter("alphaClipForward")?.data??1/255}set minPixelSize(e){this._material.setParameter("minPixelSize",e),this._material.update()}get minPixelSize(){return this._material.getParameter("minPixelSize")?.data??2}set minContribution(e){this._material.setParameter("minContribution",e),this._material.update()}get minContribution(){return this._material.getParameter("minContribution")?.data??3}set antiAlias(e){this._material.setDefine("GSPLAT_AA",e),this._material.update()}get antiAlias(){return!!this._material.getDefine("GSPLAT_AA")}set twoDimensional(e){this._material.setDefine("GSPLAT_2DGS",e),this._material.update()}get twoDimensional(){return!!this._material.getDefine("GSPLAT_2DGS")}_fisheye=0;set fisheye(e){if(this._fisheye!==e){const t=this._fisheye>0;this._fisheye=e;const s=e>0;t!==s&&(this._material.setDefine("GSPLAT_FISHEYE",s),this._material.update())}}get fisheye(){return this._fisheye}cooldownTicks=100;set dataFormat(e){if(this._dataFormat!==e){this._dataFormat=e;const t=this._format.extraStreams.map(s=>({name:s.name,format:s.format,storage:s.storage}));this._format=this._createFormat(e),t.length>0&&this._format.addExtraStreams(t),this.dirty=!0}}get dataFormat(){return this._dataFormat}get material(){return this._material}get format(){return this._format}frameEnd(){this._material.dirty=!1,this.dirty=!1}}class sw{enabled=!1;k=1;invK=1;cornerScale=1;projMat00=1;projMat11=1;maxTheta=Math.PI;_lastT=-1;_lastFov=-1;_lastP00=0;_lastP11=0;
704update(e,t,s){s.data[15]===1&&(e=0);const i=s.data[0],r=s.data[5];if(e===this._lastT&&t===this._lastFov&&i===this._lastP00&&r===this._lastP11)return;if(this._lastT=e,this._lastFov=t,this._lastP00=i,this._lastP11=r,e<=0){this.enabled=!1,this.k=1,this.invK=1,this.cornerScale=1,this.maxTheta=Math.PI;return}this.enabled=!0;const a=t/180+.15,n=Math.max(1,t/180+.05),o=n*Math.pow(a/n,e);this.k=o,this.invK=1/o,this.cornerScale=1+(Math.SQRT2-1)*e;const c=Math.min(o*Math.PI/2,3.13),h=this.cornerScale,d=Math.atan2(1,i),u=Math.min(d,c-.01);this.projMat00=h/(o*Math.tan(u/o));const f=Math.atan2(1,r),p=Math.min(f,c-.01);this.projMat11=h/(o*Math.tan(p/o)),this.maxTheta=c}}const XD={linear:"decodeLinear",srgb:"decodeGamma",rgbm:"decodeRGBM",rgbe:"decodeRGBE",rgbp:"decodeRGBP",xy:"unpackNormalXY",xyz:"unpackNormalXYZ"},YD={linear:"encodeLinear",srgb:"encodeGamma",rgbm:"encodeRGBM",rgbe:"encodeRGBE",rgbp:"encodeRGBP"};class ta{static decodeFunc(e){return XD[e]??"decodeGamma"}static encodeFunc(e){return YD[e]??"encodeGamma"}}const iw=(l,e)=>{const t=e.length/3,s=l.length/3,i=new E,r=new E,a=new E,n=new E,o=new E,c=new E,h=[];for(let d=0;d<l.length;d++)h[d]=0;for(let d=0;d<t;d++){const u=e[d*3],f=e[d*3+1],p=e[d*3+2];i.set(l[u*3],l[u*3+1],l[u*3+2]),r.set(l[f*3],l[f*3+1],l[f*3+2]),a.set(l[p*3],l[p*3+1],l[p*3+2]),n.sub2(r,i),o.sub2(a,i),c.cross(n,o).normalize(),h[u*3]+=c.x,h[u*3+1]+=c.y,h[u*3+2]+=c.z,h[f*3]+=c.x,h[f*3+1]+=c.y,h[f*3+2]+=c.z,h[p*3]+=c.x,h[p*3+1]+=c.y,h[p*3+2]+=c.z}for(let d=0;d<s;d++){const u=h[d*3],f=h[d*3+1],p=h[d*3+2],m=1/Math.sqrt(u*u+f*f+p*p);h[d*3]*=m,h[d*3+1]*=m,h[d*3+2]*=m}return h},ma=(l,e,t,s)=>{const i=s.length/3,r=l.length/3,a=new E,n=new E,o=new E,c=new j,h=new j,d=new j,u=new E,f=new E,p=new Float32Array(r*3),m=new Float32Array(r*3),_=[];for(let S=0;S<i;S++){const T=s[S*3],w=s[S*3+1],C=s[S*3+2];a.set(l[T*3],l[T*3+1],l[T*3+2]),n.set(l[w*3],l[w*3+1],l[w*3+2]),o.set(l[C*3],l[C*3+1],l[C*3+2]),c.set(t[T*2],t[T*2+1]),h.set(t[w*2],t[w*2+1]),d.set(t[C*2],t[C*2+1]);const b=n.x-a.x,I=o.x-a.x,P=n.y-a.y,L=o.y-a.y,O=n.z-a.z,D=o.z-a.z,N=h.x-c.x,k=d.x-c.x,A=h.y-c.y,M=d.y-c.y,R=N*M-k*A;if(R===0)u.set(0,1,0),f.set(1,0,0);else{const F=1/R;u.set((M*b-A*I)*F,(M*P-A*L)*F,(M*O-A*D)*F),f.set((N*I-k*b)*F,(N*L-k*P)*F,(N*D-k*O)*F)}p[T*3+0]+=u.x,p[T*3+1]+=u.y,p[T*3+2]+=u.z,p[w*3+0]+=u.x,p[w*3+1]+=u.y,p[w*3+2]+=u.z,p[C*3+0]+=u.x,p[C*3+1]+=u.y,p[C*3+2]+=u.z,m[T*3+0]+=f.x,m[T*3+1]+=f.y,m[T*3+2]+=f.z,m[w*3+0]+=f.x,m[w*3+1]+=f.y,m[w*3+2]+=f.z,m[C*3+0]+=f.x,m[C*3+1]+=f.y,m[C*3+2]+=f.z}const g=new E,v=new E,x=new E,y=new E;for(let S=0;S<r;S++){x.set(e[S*3],e[S*3+1],e[S*3+2]),g.set(p[S*3],p[S*3+1],p[S*3+2]),v.set(m[S*3],m[S*3+1],m[S*3+2]);const T=x.dot(g);y.copy(x).mulScalar(T),y.sub2(g,y).normalize(),_[S*4]=y.x,_[S*4+1]=y.y,_[S*4+2]=y.z,y.cross(x,g),_[S*4+3]=y.dot(v)<0?-1:1}return _};class un{positions;normals;colors;uvs;uvs1;blendIndices;blendWeights;tangents;indices;calculateNormals(){this.normals=iw(this.positions,this.indices)}calculateTangents(){this.tangents=ma(this.positions,this.normals,this.uvs,this.indices)}}const r_=8/64,hy=1-r_*2;class a_ extends un{constructor(e={}){super();const t=e.halfExtents??new E(.5,.5,.5),s=e.widthSegments??1,i=e.lengthSegments??1,r=e.heightSegments??1,a=e.yOffset??0,n=-t.y+a,o=t.y+a,c=[new E(-t.x,n,t.z),new E(t.x,n,t.z),new E(t.x,o,t.z),new E(-t.x,o,t.z),new E(t.x,n,-t.z),new E(-t.x,n,-t.z),new E(-t.x,o,-t.z),new E(t.x,o,-t.z)],h=[[0,1,3],[4,5,7],[3,2,6],[1,0,4],[1,4,2],[5,0,6]],d=[[0,0,1],[0,0,-1],[0,1,0],[0,-1,0],[1,0,0],[-1,0,0]],u={FRONT:0,BACK:1,TOP:2,BOTTOM:3,RIGHT:4,LEFT:5},f=[],p=[],m=[],_=[],g=[];let v=0;const x=(y,S,T)=>{const w=new E,C=new E,b=new E,I=new E;for(let P=0;P<=S;P++)for(let L=0;L<=T;L++){w.lerp(c[h[y][0]],c[h[y][1]],P/S),C.lerp(c[h[y][0]],c[h[y][2]],L/T),b.sub2(C,c[h[y][0]]),I.add2(w,b);let O=P/S,D=L/T;f.push(I.x,I.y,I.z),p.push(d[y][0],d[y][1],d[y][2]),m.push(O,1-D),O=O*hy+r_,D=D*hy+r_,O/=3,D/=3,O+=y%3/3,D+=Math.floor(y/3)/3,_.push(O,1-D),P<S&&L<T&&(g.push(v+T+1,v+1,v),g.push(v+T+1,v+T+2,v+1)),v++}};x(u.FRONT,s,r),x(u.BACK,s,r),x(u.TOP,s,i),x(u.BOTTOM,s,i),x(u.RIGHT,i,r),x(u.LEFT,i,r),this.positions=f,this.normals=p,this.uvs=m,this.uvs1=_,this.indices=g,e.calculateTangents&&(this.tangents=ma(f,p,m,g))}}class rw extends un{constructor(e={}){super();
704const t=e.radius??.5,s=e.latitudeBands??16,i=e.longitudeBands??16,r=[],a=[],n=[],o=[];for(let c=0;c<=s;c++){const h=c*Math.PI/s,d=Math.sin(h),u=Math.cos(h);for(let f=0;f<=i;f++){const p=f*2*Math.PI/i-Math.PI/2,m=Math.sin(p),g=Math.cos(p)*d,v=u,x=m*d,y=1-f/i,S=1-c/s;r.push(g*t,v*t,x*t),a.push(g,v,x),n.push(y,1-S)}}for(let c=0;c<s;++c)for(let h=0;h<i;++h){const d=c*(i+1)+h,u=d+i+1;o.push(d+1,u,d),o.push(d+1,u+1,u)}this.positions=r,this.normals=a,this.uvs=n,this.uvs1=n,this.indices=o,e.calculateTangents&&(this.tangents=ma(r,a,n,o))}}class jD extends rw{constructor(e={}){const s=e.latitudeBands??16,i=e.longitudeBands??16;super({radius:.5,latitudeBands:s,longitudeBands:i});const r=.1,a=.95,n=a*a,o=this.positions;for(let c=0;c<o.length;c+=3){const h=o[c]/.5;let d=o[c+1]/.5;const u=o[c+2]/.5;d<0&&(d*=.3,h*h+u*u<n&&(d=-r)),d+=r,d*=.5,o[c+1]=d}}}class $l{static create(e,t){switch(t){case FI:return $l.box(e);case OI:return $l.dome(e)}return $l.infinite(e)}static infinite(e){return at.fromGeometry(e,new a_(e))}static box(e){return at.fromGeometry(e,new a_({yOffset:.5}))}static dome(e){const t=new jD({latitudeBands:50,longitudeBands:50});return t.normals=void 0,t.uvs=void 0,at.fromGeometry(e,t)}}class qD{meshInstance=null;_depthWrite=!1;constructor(e,t,s,i,r){const a=new ei({uniqueName:"SkyMaterial",vertexGLSL:be.get(e,ze).get("skyboxVS"),fragmentGLSL:be.get(e,ze).get("skyboxPS"),vertexWGSL:be.get(e,de).get("skyboxVS"),fragmentWGSL:be.get(e,de).get("skyboxPS"),attributes:{aPosition:Ie}});a.setDefine("{SKYBOX_DECODE_FNC}",ta.decodeFunc(i.encoding)),r!==no&&a.setDefine("SKYMESH",""),i.cubemap&&a.setDefine("SKY_CUBEMAP",""),a.setParameter("skyboxHighlightMultiplier",t.skyboxHighlightMultiplier),i.cubemap?a.setParameter("texture_cubeMap",i):(a.setParameter("texture_envAtlas",i),a.setParameter("mipLevel",t.skyboxMip)),a.cull=Bx,a.depthWrite=this._depthWrite;const n=t.layers.getLayerById(Pg);if(n){const o=$l.create(e,r),c=new Ne(o,a,s);this.meshInstance=c,c.cull=!1,c.pick=!1,n.addMeshInstances([c]),this.skyLayer=n}}destroy(){this.meshInstance&&(this.skyLayer&&this.skyLayer.removeMeshInstances([this.meshInstance]),this.meshInstance.destroy(),this.meshInstance=null)}set depthWrite(e){this._depthWrite=e,this.meshInstance&&(this.meshInstance.material.depthWrite=e)}get depthWrite(){return this._depthWrite}}class $D{_type=no;_center=new E(0,1,0);skyMesh=null;_depthWrite=!1;_fisheye=0;_fisheyeProj=null;node=new He("SkyMeshNode");constructor(e){this.device=e.device,this.scene=e,this.center=new E(0,1,0),this.centerArray=new Float32Array(3),this.projectedSkydomeCenterId=this.device.scope.resolve("projectedSkydomeCenter"),this._preRenderEvt=e.on("prerender",this._onPreRender,this)}destroy(){this._preRenderEvt.off(),this.resetSkyMesh()}applySettings(e){this.type=e.skyType??no,this.node.setLocalPosition(new E(e.skyMeshPosition??[0,0,0])),this.node.setLocalEulerAngles(new E(e.skyMeshRotation??[0,0,0])),this.node.setLocalScale(new E(e.skyMeshScale??[1,1,1])),e.skyCenter&&(this._center=new E(e.skyCenter))}set type(e){this._type!==e&&(this._type=e,this.scene.updateShaders=!0,this.updateSkyMesh())}get type(){return this._type}set center(e){this._center.copy(e)}get center(){return this._center}set depthWrite(e){this._depthWrite!==e&&(this._depthWrite=e,this.skyMesh&&(this.skyMesh.depthWrite=e))}get depthWrite(){return this._depthWrite}set fisheye(e){if(this._fisheye!==e){const t=this._fisheye>0;this._fisheye=e;const s=e>0;t!==s&&(this._fisheyeProj??(this._fisheyeProj=new sw),this._type===no&&this._setFisheyeDefine(s))}}get fisheye(){return this._fisheye}updateSkyMesh(){const e=this.scene._getSkyboxTex();e&&(this.resetSkyMesh(),this.skyMesh=new qD(this.device,this.scene,this.node,e,this.type),this.skyMesh.depthWrite=this._depthWrite,this._fisheye>0&&this.type===no&&this._setFisheyeDefine(!0),this.scene.fire("set:skybox",e))}resetSkyMesh(){this.skyMesh?.destroy(),this.skyMesh=null}update(){if(this.type!==no){const{center:e,centerArray:t}=this,s=new E;this.node.getWorldTransform().transformPoint(e,s),t[0]=s.x,t[1]=s.y,t[2]=s.z,this.projectedSkydomeCenterId.setValue(t)}}_setFisheyeDefine(e){if(this.skyMesh?.meshInstance){const t=this.skyMesh.meshInstance.material;
704t.setDefine("SKY_FISHEYE",e),t.update()}}_onPreRender(e){if(this._fisheye>0&&this._fisheyeProj&&this.skyMesh?.meshInstance){const t=e.camera,s=this._fisheyeProj;s.update(this._fisheye,t.fov,t.projectionMatrix);const i=this.skyMesh.meshInstance.material;i.setParameter("fisheye_k",s.k),i.setParameter("fisheye_invK",s.invK),i.setParameter("fisheye_projMat00",s.projMat00),i.setParameter("fisheye_projMat11",s.projMat11)}}}const fu=new He;fu.worldTransform=Z.IDENTITY;fu._dirtyWorld=fu._dirtyNormal=!1;class KD{constructor(e,t,s){this.material=t,this.layer=s,this.positions=[],this.colors=[],this.mesh=new at(e),this.meshInstance=null}addLines(e,t){const s=this.positions,i=e.length;for(let a=0;a<i;a++){const n=e[a];s.push(n.x,n.y,n.z)}const r=this.colors;if(t.length)for(let a=0;a<i;a++){const n=t[a];r.push(n.r,n.g,n.b,n.a)}else for(let a=0;a<i;a++)r.push(t.r,t.g,t.b,t.a)}addLinesArrays(e,t){const s=this.positions;for(let r=0;r<e.length;r+=3)s.push(e[r],e[r+1],e[r+2]);const i=this.colors;if(t.length)for(let r=0;r<t.length;r+=4)i.push(t[r],t[r+1],t[r+2],t[r+3]);else{const r=e.length/3;for(let a=0;a<r;a++)i.push(t.r,t.g,t.b,t.a)}}onPreRender(e,t){this.positions.length>0&&this.material.transparent===t&&(this.mesh.setPositions(this.positions),this.mesh.setColors(this.colors),this.mesh.update(cf,!1),this.meshInstance||(this.meshInstance=new Ne(this.mesh,this.material,fu)),e.push(this.meshInstance))}clear(){this.positions.length=0,this.colors.length=0}}class ZD{constructor(e){this.device=e,this.map=new Map}getBatch(e,t){let s=this.map.get(e);return s||(s=new KD(this.device,e,t),this.map.set(e,s)),s}onPreRender(e,t){this.map.forEach(s=>{s.onPreRender(e,t)})}clear(){this.map.forEach(e=>e.clear())}}const Gs=[],Un=new E;class QD{shaderDescs=new Map;constructor(e){this.device=e,this.quadMesh=null,this.textureShader=null,this.depthTextureShader=null,this.cubeLocalPos=null,this.cubeWorldPos=null,this.batchesMap=new Map,this.allBatches=new Set,this.updatedLayers=new Set,this._materialDepth=null,this._materialNoDepth=null,this.layerMeshInstances=new Map}createMaterial(e){const t=new ei({uniqueName:"ImmediateLine",vertexGLSL:be.get(this.device,ze).get("immediateLineVS"),fragmentGLSL:be.get(this.device,ze).get("immediateLinePS"),vertexWGSL:be.get(this.device,de).get("immediateLineVS"),fragmentWGSL:be.get(this.device,de).get("immediateLinePS"),attributes:{vertex_position:Ie,vertex_color:ns}});return t.blendType=Wi,t.depthTest=e,t.update(),t}get materialDepth(){return this._materialDepth||(this._materialDepth=this.createMaterial(!0)),this._materialDepth}get materialNoDepth(){return this._materialNoDepth||(this._materialNoDepth=this.createMaterial(!1)),this._materialNoDepth}getBatch(e,t){let s=this.batchesMap.get(e);s||(s=new ZD(this.device),this.batchesMap.set(e,s)),this.allBatches.add(s);const i=t?this.materialDepth:this.materialNoDepth;return s.getBatch(i,e)}getShaderDesc(e,t,s){return this.shaderDescs.has(e)||this.shaderDescs.set(e,{uniqueName:`DebugShader:${e}`,vertexGLSL:` 705 attribute vec2 vertex_position; 706 uniform mat4 matrix_model; 707 varying vec2 uv0; 708 void main(void) { 709 gl_Position = matrix_model * vec4(vertex_position, 0, 1); 710 uv0 = vertex_position.xy + 0.5; 711 } 712 `,vertexWGSL:` 713 attribute vertex_position: vec2f; 714 uniform matrix_model: mat4x4f; 715 varying uv0: vec2f; 716 @vertex fn vertexMain(input: VertexInput) -> VertexOutput { 717 var output: VertexOutput; 718 output.position = uniform.matrix_model * vec4f(input.vertex_position, 0.0, 1.0); 719 output.uv0 = input.vertex_position.xy + vec2f(0.5); 720 return output; 721 } 722 `,fragmentGLSL:t,fragmentWGSL:s,attributes:{vertex_position:Ie}}),this.shaderDescs.get(e)}getTextureShaderDesc(e){const t=ta.decodeFunc(e);return this.getShaderDesc(`textureShader-${e}`,` 723 #include "gammaPS" 724 varying vec2 uv0; 725 uniform sampler2D colorMap; 726 void main (void) { 727 vec3 linearColor = ${t}(texture2D(colorMap, uv0)); 728 gl_FragColor = vec4(gammaCorrectOutput(linearColor), 1); 729 } 730 `,` 731 #include "gammaPS" 732 varying uv0: vec2f; 733 var colorMap: texture_2d<f32>; 734 var colorMapSampler: sampler; 735 @fragment fn fragmentMain(input : FragmentInput) -> FragmentOutput { 736 var output: FragmentOutput; 737 let sampledTex = textureSample(colorMap, colorMapSampler, input.uv0); 738 let linearColor: vec3f = ${t}(sampledTex);
739 output.color = vec4f(gammaCorrectOutput(linearColor), 1.0); 740 return output; 741 } 742 `)}getUnfilterableTextureShaderDesc(){return this.getShaderDesc("textureShaderUnfilterable",` 743 varying vec2 uv0; 744 uniform highp sampler2D colorMap; 745 void main (void) { 746 ivec2 uv = ivec2(uv0 * textureSize(colorMap, 0)); 747 gl_FragColor = vec4(texelFetch(colorMap, uv, 0).xyz, 1); 748 } 749 `,` 750 varying uv0: vec2f; 751 var colorMap: texture_2d<uff>; 752 @fragment fn fragmentMain(input : FragmentInput) -> FragmentOutput { 753 var output: FragmentOutput; 754 let uv : vec2<i32> = vec2<i32>(input.uv0 * vec2f(textureDimensions(colorMap, 0))); 755 let fetchedColor : vec4f = textureLoad(colorMap, uv, 0); 756 output.color = vec4f(fetchedColor.xyz, 1.0); 757 return output; 758 } 759 `)}getDepthTextureShaderDesc(){return this.getShaderDesc("depthTextureShader",` 760 #include "screenDepthPS" 761 #include "gammaPS" 762 varying vec2 uv0; 763 void main() { 764 float depth = getLinearScreenDepth(getImageEffectUV(uv0)) * camera_params.x; 765 gl_FragColor = vec4(gammaCorrectOutput(vec3(depth)), 1.0); 766 } 767 `,` 768 #include "screenDepthPS" 769 #include "gammaPS" 770 varying uv0: vec2f; 771 @fragment fn fragmentMain(input: FragmentInput) -> FragmentOutput { 772 var output: FragmentOutput; 773 let depth: f32 = getLinearScreenDepth(getImageEffectUV(input.uv0)) * uniform.camera_params.x; 774 output.color = vec4f(gammaCorrectOutput(vec3f(depth)), 1.0); 775 return output; 776 } 777 `)}getQuadMesh(){return this.quadMesh||(this.quadMesh=new at(this.device),this.quadMesh.setPositions([-.5,-.5,0,.5,-.5,0,-.5,.5,0,.5,.5,0]),this.quadMesh.update(Tr)),this.quadMesh}drawMesh(e,t,s,i,r){if(!i){const n=this.getGraphNode(t);i=new Ne(s,e,n)}let a=this.layerMeshInstances.get(r);a||(a=[],this.layerMeshInstances.set(r,a)),a.push(i)}drawWireAlignedBox(e,t,s,i,r,a){if(a){const o=(c,h,d)=>{Un.set(c,h,d),a.transformPoint(Un,Un),Gs.push(Un.x,Un.y,Un.z)};o(e.x,e.y,e.z),o(e.x,t.y,e.z),o(e.x,t.y,e.z),o(t.x,t.y,e.z),o(t.x,t.y,e.z),o(t.x,e.y,e.z),o(t.x,e.y,e.z),o(e.x,e.y,e.z),o(e.x,e.y,t.z),o(e.x,t.y,t.z),o(e.x,t.y,t.z),o(t.x,t.y,t.z),o(t.x,t.y,t.z),o(t.x,e.y,t.z),o(t.x,e.y,t.z),o(e.x,e.y,t.z),o(e.x,e.y,e.z),o(e.x,e.y,t.z),o(e.x,t.y,e.z),o(e.x,t.y,t.z),o(t.x,t.y,e.z),o(t.x,t.y,t.z),o(t.x,e.y,e.z),o(t.x,e.y,t.z)}else Gs.push(e.x,e.y,e.z,e.x,t.y,e.z,e.x,t.y,e.z,t.x,t.y,e.z,t.x,t.y,e.z,t.x,e.y,e.z,t.x,e.y,e.z,e.x,e.y,e.z,e.x,e.y,t.z,e.x,t.y,t.z,e.x,t.y,t.z,t.x,t.y,t.z,t.x,t.y,t.z,t.x,e.y,t.z,t.x,e.y,t.z,e.x,e.y,t.z,e.x,e.y,e.z,e.x,e.y,t.z,e.x,t.y,e.z,e.x,t.y,t.z,t.x,t.y,e.z,t.x,t.y,t.z,t.x,e.y,e.z,t.x,e.y,t.z);this.getBatch(r,i).addLinesArrays(Gs,s),Gs.length=0}drawWireSphere(e,t,s,i,r,a){const n=2*Math.PI/i;let o=0;for(let h=0;h<i;h++){const d=Math.sin(o),u=Math.cos(o);o+=n;const f=Math.sin(o),p=Math.cos(o);Gs.push(e.x+t*d,e.y,e.z+t*u),Gs.push(e.x+t*f,e.y,e.z+t*p),Gs.push(e.x+t*d,e.y+t*u,e.z),Gs.push(e.x+t*f,e.y+t*p,e.z),Gs.push(e.x,e.y+t*d,e.z+t*u),Gs.push(e.x,e.y+t*f,e.z+t*p)}this.getBatch(a,r).addLinesArrays(Gs,s),Gs.length=0}getGraphNode(e){const t=new He("ImmediateDebug");return t.worldTransform=e,t._dirtyWorld=t._dirtyNormal=!1,t}onPreRenderLayer(e,t,s){if(this.batchesMap.forEach((i,r)=>{r===e&&i.onPreRender(t,s)}),!this.updatedLayers.has(e)){this.updatedLayers.add(e);const i=this.layerMeshInstances.get(e);if(i){for(let r=0;r<i.length;r++)t.push(i[r]);i.length=0}}}onPostRender(){this.allBatches.forEach(e=>e.clear()),this.allBatches.clear(),this.updatedLayers.clear()}}const dy=2.399963229728653,Kc={circlePoint(l){const e=Math.sqrt(Math.random()),t=Math.random()*2*Math.PI;l.x=e*Math.cos(t),l.y=e*Math.sin(t)},circlePointDeterministic(l,e,t){const s=e*dy,i=Math.sqrt(e/t);l.x=i*Math.cos(s),l.y=i*Math.sin(s)},spherePointDeterministic(l,e,t,s=0,i=1){s=1-2*s,i=1-2*i;const r=H.lerp(s,i,e/t),a=Math.sqrt(1-r*r),n=dy*e;l.x=Math.cos(n)*a,l.y=r,l.z=Math.sin(n)*a},radicalInverse(l){let e=(l<<16|l>>>16)>>>0;return e=((e&1431655765)<<1|(e&2863311530)>>>1)>>>0,e=((e&858993459)<<2|(e&3435973836)>>>2)>>>0,e=((e&252645135)<<4|(e&4042322160)>>>4)>>>0,e=((e&16711935)<<8|(e&4278255360)>>>8)>>>0,e*23283064365386963e-26}},uy=l=>{switch(l){case Gm:return"Cubemap";case rb:return"Octahedral";default:return"Equirect"}},Gh=(l,e,t)=>{if(l<=0)e[t+0]=0,e[t+1]=0,e[t+2]=0,e[t+3]=0;else if(l>=1)e[t+0]=255,e[t+1]=0,e[t+2]=0,e[t+3]=0;else{let s=1*l%1,i=255*l%1,r=65025*l%1;const a=16581375*l%1;s-=i/255,i-=r/255,r-=a/255,e[t+0]=Math.min(255,Math.floor(s*256)),e[t+1]=Math.min(255,Math.floor(i*256)),e[t+2]=Math.min(255,Math.floor(r*256)),e[t+3]=Math.min(255,Math.floor(a*256))}},JD=l=>{const e=l.length,t=Math.min(e,512),s=Math.ceil(e/t),i=new Uint8Array(t*s*4);let r=0;for(let a=0;a<e;a+=4)Gh(l[a+0]*.5+.5,i,r+0),Gh(l[a+1]*.5+.5,i,r+4),Gh(l[a+2]*.5+.5,i,r+8),Gh(l[a+3]/8,i,r+12),r+=16;return{width:t,height:s,data:i}},eM=(l,e,t,s)=>{const i=t*2*Math.PI,r=Math.pow(1-e,1/(s+1)),a=Math.sqrt(1-r*r);l.set(Math.cos(i)*a,Math.sin(i)*a,r).normalize()},tM=(l,e,t)=>{const s=t*2*Math.PI,i=Math.sqrt(1-e),r=Math.sqrt(e);l.set(Math.cos(s)*r,Math.sin(s)*r,i).normalize()},sM=(l,e,t,s)=>{const i=t*2*Math.PI,r=Math.sqrt((1-e)/(1+(s*s-1)*e)),a=Math.sqrt(1-r*r);l.set(Math.cos(i)*a,Math.sin(i)*a,r).normalize()},iM=(l,e)=>{const t=l*e,s=e/(1-l*l+t*t);return s*s*(1/Math.PI)},rM=(l,e)=>{const t=new E,s=[];for(let i=0;i<l;++i)eM(t,i/l,Kc.radicalInverse(i),e),s.push(t.x,t.y,t.z,0);return s},aM=(l,e)=>{const t=e/l,s=new E,i=[];for(let r=0;r<l;++r){tM(s,r/l,Kc.radicalInverse(r));const a=s.z/Math.PI,n=.5*Math.log2(t/a);i.push(s.x,s.y,s.z,n)}return i},nM={16:{2:26,8:20,32:17,128:16,512:16},32:{2:53,8:40,32:34,128:32,512:32},128:{2:214,8:163,32:139,128:130,512:128},1024:{2:1722,8:1310,32:1114,128:1041,512:1025}},oM=(l,e)=>{const t=nM[l];return t&&t[e]||l},lM=(l,e,t)=>{const s=t/l,i=1-Math.log2(e)/11,r=i*i,a=new E,n=new E,o=new E(0,0,1),c=[],h=oM(l,e);for(let d=0;d<h;++d){sM(a,d/h,Kc.radicalInverse(d),r);const u=a.z;if(n.set(a.x,a.y,a.z).mulScalar(2*u).sub(o),n.z>0){const f=iM(Math.min(1,u),r)/4+.001,p=.5*Math.log2(s/f);c.push(n.x,n.y,n.z,p)}}for(;c.length<l*4;)c.push(0,0,0,0);return c},cM=(l,e,t)=>{const s=JD(t);return new ce(l,{name:e,width:s.width,height:s.height,mipmaps:!1,minFilter:Fe,magFilter:Fe,levels:[s.data]})};class aw{constructor(e=!0){this.destroyContent=e}map=new Map;
777destroy(){this.destroyContent&&this.map.forEach((e,t)=>{e.destroy()})}get(e,t){if(!this.map.has(e)){const s=t();return this.map.set(e,s),s}return this.map.get(e)}}const hM=new aw(!1),dM=new Jt,Vg=(l,e,t)=>dM.get(l,()=>new aw).get(e,()=>cM(l,e,hM.get(e,t))),uM=(l,e,t)=>{const s=`lambert-samples-${e}-${t}`;return Vg(l,s,()=>aM(e,t))},fM=(l,e,t)=>{const s=`phong-samples-${e}-${t}`;return Vg(l,s,()=>rM(e,t))},pM=(l,e,t,s)=>{const i=`ggx-samples-${e}-${t}-${s}`;return Vg(l,i,()=>lM(e,t,s))};function Ji(l,e,t={}){const s=t.seamPixels??0,i=(t.rect?.z??e.width)-s*2,r=(t.rect?.w??e.height)-s*2;if(i<1||r<1)return!1;const a={none:"reproject",lambert:"prefilterSamplesUnweighted",phong:"prefilterSamplesUnweighted",ggx:"prefilterSamples"},n=t.hasOwnProperty("specularPower")?t.specularPower:1,o=t.hasOwnProperty("face")?t.face:null,c=t.hasOwnProperty("distribution")?t.distribution:n===1?"none":"phong",h=a[c]||"reproject",d=h.startsWith("prefilterSamples"),u=ta.decodeFunc(l.encoding),f=ta.encodeFunc(e.encoding),p=`sample${uy(l.projection)}`,m=`getDirection${uy(e.projection)}`,_=t.hasOwnProperty("numSamples")?t.numSamples:1024,g=`ReprojectShader:${h}_${u}_${f}_${p}_${m}_${_}`,v=l.device;let x=ko(v).getCachedShader(g);if(!x){const C=new Map;d&&C.set("USE_SAMPLES_TEX",""),l.cubemap&&C.set("CUBEMAP_SOURCE",""),C.set("{PROCESS_FUNC}",h),C.set("{DECODE_FUNC}",u),C.set("{ENCODE_FUNC}",f),C.set("{SOURCE_FUNC}",p),C.set("{TARGET_FUNC}",m),C.set("{NUM_SAMPLES}",_),C.set("{NUM_SAMPLES_SQRT}",Math.round(Math.sqrt(_)).toFixed(1)),x=Qt.createShader(v,{uniqueName:g,attributes:{vertex_position:Ie},vertexChunk:"reprojectVS",fragmentChunk:"reprojectPS",fragmentDefines:C})}v.setBlendState(xt.NOBLEND),v.scope.resolve(l.cubemap?"sourceCube":"sourceTex").setValue(l);const S=v.scope.resolve("params"),T=v.scope.resolve("uvMod");s>0?T.setValue([(i+s*2)/i,(r+s*2)/r,-s/i,-s/r]):T.setValue([1,1,0,0]);const w=[0,e.width*e.height*(e.cubemap?6:1),l.width*l.height*(l.cubemap?6:1)];if(d){const C=l.width*l.height*(l.cubemap?6:1),b=c==="ggx"?pM(v,_,n,C):c==="lambert"?uM(v,_,C):fM(v,_,n);v.scope.resolve("samplesTex").setValue(b),v.scope.resolve("samplesTexInverseSize").setValue([1/b.width,1/b.height])}for(let C=0;C<(e.cubemap?6:1);C++)if(o===null||C===o){const b=new St({colorBuffer:e,face:C,depth:!1,flipY:v.isWebGPU});w[0]=C,S.setValue(w),cn(v,b,x,t?.rect),b.destroy()}return!0}const kp=(l,e=0)=>1+Math.floor(Math.log2(Math.max(l,e))),mM=l=>l.textureHalfFloatRenderable,_M=l=>l.textureFloatRenderable,gM=l=>mM(l)?Ge:_M(l)?mt:Re,vM=l=>Re,SM=(l,e,t,s)=>new ce(l,{name:`lighting-${e}`,cubemap:!0,width:e,height:e,format:t,type:ac,addressU:ue,addressV:ue,mipmaps:!1});class nw{static generateSkyboxCubemap(e,t){const s=e.device,i=SM(s,t||(e.cubemap?e.width:e.width/4),Re);return Ji(e,i,{numSamples:1024}),i}static generateLightingSource(e,t){const s=e.device,i=gM(s),r=t?.target||new ce(s,{name:"lighting-source",cubemap:!0,width:t?.size||128,height:t?.size||128,format:i,type:i===Re?ac:Qs,addressU:ue,addressV:ue,mipmaps:!0});return Ji(e,r,{numSamples:e.mipmaps?1:1024}),r}static generateAtlas(e,t){const s=e.device,i=vM(),r=t?.target||new ce(s,{name:"envAtlas",width:t?.size||512,height:t?.size||512,format:i,type:ac,projection:yv,addressU:ue,addressV:ue,mipmaps:!1}),a=r.width/512,n=new ie(0,0,512*a,256*a),o=kp(256)-kp(4);for(let c=0;c<o;++c)Ji(e,r,{numSamples:1,rect:n,seamPixels:a}),n.x+=n.w,n.y+=n.w,n.z=Math.max(1,Math.floor(n.z*.5)),n.w=Math.max(1,Math.floor(n.w*.5));n.set(0,256*a,256*a,128*a);for(let c=1;c<7;++c)Ji(e,r,{numSamples:t?.numReflectionSamples||1024,distribution:t?.distribution||"ggx",specularPower:Math.max(1,2048>>c*2),rect:n,seamPixels:a}),n.y+=n.w,n.z=Math.max(1,Math.floor(n.z*.5)),n.w=Math.max(1,Math.floor(n.w*.5));return n.set(128*a,384*a,64*a,32*a),Ji(e,r,{numSamples:t?.numAmbientSamples||2048,distribution:"lambert",rect:n,seamPixels:a}),r}static generatePrefilteredAtlas(e,t){const s=e[0].device,i=e[0].format,r=e[0].type,a=t?.target||new ce(s,{name:"envPrefilteredAtlas",width:t?.size||512,height:t?.size||512,format:i,type:r,projection:yv,addressU:ue,addressV:ue,mipmaps:!1}),n=a.width/512,o=new ie(0,0,512*n,256*n),c=kp(512);for(let h=0;h<c;++h)Ji(e[0],a,{numSamples:1,rect:o,seamPixels:n}
777),o.x+=o.w,o.y+=o.w,o.z=Math.max(1,Math.floor(o.z*.5)),o.w=Math.max(1,Math.floor(o.w*.5));o.set(0,256*n,256*n,128*n);for(let h=1;h<e.length;++h)Ji(e[h],a,{numSamples:1,rect:o,seamPixels:n}),o.y+=o.w,o.z=Math.max(1,Math.floor(o.z*.5)),o.w=Math.max(1,Math.floor(o.w*.5));return o.set(128*n,384*n,64*n,32*n),t?.legacyAmbient?Ji(e[5],a,{numSamples:1,rect:o,seamPixels:n}):Ji(e[0],a,{numSamples:t?.numSamples||2048,distribution:"lambert",rect:o,seamPixels:n}),a}}class yM{type=vn;color=new Q(0,0,0);density=0;start=1;end=1e3}class ti extends ge{static EVENT_SETLAYERS="set:layers";static EVENT_SETSKYBOX="set:skybox";static EVENT_PRERENDER="prerender";static EVENT_POSTRENDER="postrender";static EVENT_PRERENDER_LAYER="prerender:layer";static EVENT_POSTRENDER_LAYER="postrender:layer";static EVENT_PRECULL="precull";static EVENT_POSTCULL="postcull";ambientBake=!1;ambientBakeOcclusionBrightness=0;ambientBakeOcclusionContrast=0;ambientLight=new Q(0,0,0);ambientLuminance=0;exposure=1;lightmapSizeMultiplier=1;lightmapMaxResolution=2048;lightmapMode=bd;lightmapFilterEnabled=!1;lightmapHDR=!1;root=null;physicalUnits=!1;_envAtlas=null;_skyboxCubeMap=null;_fogParams=new yM;forcePassThroughSpecular=!1;constructor(e){super(),this.device=e,this._gravity=new E(0,-9.8,0),this._layers=null,this._prefilteredCubemaps=[],this._internalEnvAtlas=null,this._skyboxIntensity=1,this._skyboxLuminance=0,this._skyboxMip=0,this._skyboxHighlightMultiplier=1,this._skyboxRotationShaderInclude=!1,this._skyboxRotation=new ae,this._skyboxRotationMat3=new xi,this._skyboxRotationMat4=new Z,this._ambientBakeNumSamples=1,this._ambientBakeSpherePart=.4,this._lightmapFilterRange=10,this._lightmapFilterSmoothness=.2,this._clusteredLightingEnabled=!0,this._lightingParams=new QT(this.device.supportsAreaLights,this.device.maxTextureSize,()=>{this.updateShaders=!0}),this.gsplatCentersEnabled=!0,this._gsplatParams=new WD(this.device),this._sky=new $D(this),this._stats={meshInstances:0,lights:0,dynamicLights:0,bakedLights:0,updateShadersTime:0},this.updateShaders=!0,this._shaderVersion=0,this.immediate=new QD(this.device)}get defaultDrawLayer(){return this.layers.getLayerById(Ig)}set ambientBakeNumSamples(e){this._ambientBakeNumSamples=H.clamp(Math.floor(e),1,255)}get ambientBakeNumSamples(){return this._ambientBakeNumSamples}set ambientBakeSpherePart(e){this._ambientBakeSpherePart=H.clamp(e,.001,1)}get ambientBakeSpherePart(){return this._ambientBakeSpherePart}set clusteredLightingEnabled(e){if(!(this.device.isWebGPU&&!e)){if(!this._clusteredLightingEnabled&&e){console.error("Turning on disabled clustered lighting is not currently supported");return}this._clusteredLightingEnabled=e}}get clusteredLightingEnabled(){return this._clusteredLightingEnabled}set envAtlas(e){e!==this._envAtlas&&(this._envAtlas=e,e&&(e.addressU=ue,e.addressV=ue,e.minFilter=It,e.magFilter=It,e.mipmaps=!1),this._prefilteredCubemaps=[],this._internalEnvAtlas&&(this._internalEnvAtlas.destroy(),this._internalEnvAtlas=null),this._resetSkyMesh())}get envAtlas(){return this._envAtlas}set layers(e){const t=this._layers;this._layers=e,this.fire("set:layers",t,e)}get layers(){return this._layers}get sky(){return this._sky}get lighting(){return this._lightingParams}get gsplat(){return this._gsplatParams}get fog(){return this._fogParams}set lightmapFilterRange(e){this._lightmapFilterRange=Math.max(e,.001)}get lightmapFilterRange(){return this._lightmapFilterRange}set lightmapFilterSmoothness(e){this._lightmapFilterSmoothness=Math.max(e,.001)}get lightmapFilterSmoothness(){return this._lightmapFilterSmoothness}set prefilteredCubemaps(e){e=e||[];const t=this._prefilteredCubemaps;(t.length!==e.length||t.some((i,r)=>i!==e[r]))&&(e.length===6&&e.every(r=>!!r)?(this._internalEnvAtlas=nw.generatePrefilteredAtlas(e,{target:this._internalEnvAtlas}),this._envAtlas=this._internalEnvAtlas):(this._internalEnvAtlas&&(this._internalEnvAtlas.destroy(),this._internalEnvAtlas=null),this._envAtlas=null),this._prefilteredCubemaps=e.slice(),this._resetSkyMesh())}get prefilteredCubemaps(){return this._prefilteredCubemaps}set skybox(e){e!==this._skyboxCubeMap&&(this._skyboxCubeMap=e,this._resetSkyMesh())}get skybox(){return this._skyboxCubeMap}set skyboxIntensity(e){e!==this._skyboxIntensity&&(this._skyboxIntensity=e,this._resetSkyMesh())}get skyboxIntensity(){return this._skyboxIntensity}set skyboxLuminance(e){e!==this._skyboxLuminance&&(this._skyboxLuminance=e,this._resetSkyMesh())}get skyboxLuminance(){return this._skyboxLuminance}set skyboxMip(e){e!==this._skyboxMip&&(this._skyboxMip=e,this._resetSkyMesh())}get skyboxMip(){return this._skyboxMip}set skyboxHighlightMultiplier(e){e!==this._skyboxHighlightMultiplier&&(this._skyboxHighlightMultiplier=e,this._resetSkyMesh())}get skyboxHighlightMultiplier(){return this._skyboxHighlightMultiplier}set skyboxRotation(e){if(!this._skyboxRotation.equals(e)){const t=e.equals(ae.IDENTITY);this._skyboxRotation.copy(e),t?this._skyboxRotationMat3.setIdentity():(this._skyboxRotationMat4.setTRS(E.ZERO,e,E.ONE),this._skyboxRotationMat3.invertMat4(this._skyboxRotationMat4)),!this._skyboxRotationShaderInclude&&!t&&(this._skyboxRotationShaderInclude=!0,this._resetSkyMesh())}}get skyboxRotation(){return this._skyboxRotation}destroy(){this._sky.destroy(),this.root=null,this.off()}drawLine(e,t,s=Q.WHITE,i=!0,r=this.defaultDrawLayer){this.immediate.getBatch(r,i).addLines([e,t],[s,s])}drawLines(e,t,s=!0,i=this.defaultDrawLayer){this.immediate.getBatch(i,s).addLines(e,t)}drawLineArrays(e,t,s=!0,i=this.defaultDrawLayer){this.immediate.getBatch(i,s).addLinesArrays(e,t)}applySettings(e){const t=e.physics,s=e.render;this._gravity.set(t.gravity[0],t.gravity[1],t.gravity[2]),this.ambientLight.set(s.global_ambient[0],s.global_ambient[1],s.global_ambient[2]),this.ambientLuminance=s.ambientLuminance,this.fog.type=s.fog,this.fog.color.set(s.fog_color[0],s.fog_color[1],s.fog_color[2]),this.fog.start=s.fog_start,this.fog.end=s.fog_end,this.fog.density=s.fog_density,this.lightmapSizeMultiplier=s.lightmapSizeMultiplier,this.lightmapMaxResolution=s.lightmapMaxResolution,this.lightmapMode=s.lightmapMode,this.exposure=s.exposure,this._skyboxIntensity=s.skyboxIntensity??1,this._skyboxLuminance=s.skyboxLuminance??2e4,this._skyboxMip=s.skyboxMip??0,s.skyboxRotation&&(this.skyboxRotation=new ae().setFromEulerAngles(s.skyboxRotation[0],s.skyboxRotation[1],s.skyboxRotation[2])),this.sky.applySettings(s),this.clusteredLightingEnabled=s.clusteredLightingEnabled??!1,this.lighting.applySettings(s),["lightmapFilterEnabled","lightmapFilterRange","lightmapFilterSmoothness","ambientBake","ambientBakeNumSamples","ambientBakeSpherePart","ambientBakeOcclusionBrightness","ambientBakeOcclusionContrast"].forEach(i=>
777{s.hasOwnProperty(i)&&(this[i]=s[i])}),this._resetSkyMesh()}_getSkyboxTex(){const e=this._prefilteredCubemaps;return this._skyboxMip?e[[0,1,3,4,5,6][this._skyboxMip]]||this._envAtlas||e[0]||this._skyboxCubeMap:this._skyboxCubeMap||e[0]||this._envAtlas}_updateSkyMesh(){this.sky.skyMesh||this.sky.updateSkyMesh(),this.sky.update()}_resetSkyMesh(){this.sky.resetSkyMesh(),this.updateShaders=!0}setSkybox(e){e?(this.skybox=e[0]||null,e[1]&&!e[1].cubemap?this.envAtlas=e[1]:this.prefilteredCubemaps=e.slice(1)):(this.skybox=null,this.envAtlas=null)}get lightmapPixelFormat(){return this.lightmapHDR&&this.device.getRenderableHdrFormat()||Re}}class ow{constructor(e,t,s){this.device=e,this.inverseBindPose=t,this.boneNames=s}}const xM=[0,0,1,0,0,1,0,0,1,0,0,1],TM=[0,1,3,2,3,1];class wM extends ge{constructor(e,t){super(),this._device=e,this._pixelsPerUnit=t&&t.pixelsPerUnit!==void 0?t.pixelsPerUnit:1,this._renderMode=t&&t.renderMode!==void 0?t.renderMode:Fi,this._atlas=t&&t.atlas!==void 0?t.atlas:null,this._frameKeys=t&&t.frameKeys!==void 0?t.frameKeys:null,this._meshes=[],this._updatingProperties=!1,this._meshesDirty=!1,this._atlas&&this._frameKeys&&this._createMeshes()}set frameKeys(e){this._frameKeys=e,this._atlas&&this._frameKeys&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes()),this.fire("set:frameKeys",e)}get frameKeys(){return this._frameKeys}set atlas(e){e!==this._atlas&&(this._atlas&&(this._atlas.off("set:frames",this._onSetFrames,this),this._atlas.off("set:frame",this._onFrameChanged,this),this._atlas.off("remove:frame",this._onFrameRemoved,this)),this._atlas=e,this._atlas&&this._frameKeys&&(this._atlas.on("set:frames",this._onSetFrames,this),this._atlas.on("set:frame",this._onFrameChanged,this),this._atlas.on("remove:frame",this._onFrameRemoved,this),this._updatingProperties?this._meshesDirty=!0:this._createMeshes()),this.fire("set:atlas",e))}get atlas(){return this._atlas}set pixelsPerUnit(e){this._pixelsPerUnit!==e&&(this._pixelsPerUnit=e,this.fire("set:pixelsPerUnit",e),this._atlas&&this._frameKeys&&this.renderMode===Fi&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes()))}get pixelsPerUnit(){return this._pixelsPerUnit}set renderMode(e){if(this._renderMode===e)return;const t=this._renderMode;this._renderMode=e,this.fire("set:renderMode",e),(t===Fi||e===Fi)&&this._atlas&&this._frameKeys&&(this._updatingProperties?this._meshesDirty=!0:this._createMeshes())}get renderMode(){return this._renderMode}get meshes(){return this._meshes}_createMeshes(){const e=this._meshes.length;for(let i=0;i<e;i++){const r=this._meshes[i];r&&r.destroy()}const t=this._frameKeys.length;this._meshes=new Array(t);const s=this.renderMode===kt||this._renderMode===Ut?this._create9SliceMesh:this._createSimpleMesh;for(let i=0;i<t;i++){const r=this._atlas.frames[this._frameKeys[i]];this._meshes[i]=r?s.call(this,r):null}this.fire("set:meshes")}_createSimpleMesh(e){const t=e.rect,s=this._atlas.texture.width,i=this._atlas.texture.height,r=t.z/this._pixelsPerUnit,a=t.w/this._pixelsPerUnit,n=e.pivot.x,o=e.pivot.y,c=[-n*r,-o*a,0,(1-n)*r,-o*a,0,(1-n)*r,(1-o)*a,0,-n*r,(1-o)*a,0],h=t.x/s,d=1-t.y/i,u=(t.x+t.z)/s,f=1-(t.y+t.w)/i,p=[h,d,u,d,u,f,h,f],m=new un;return m.positions=c,m.normals=xM,m.uvs=p,m.indices=TM,at.fromGeometry(this._device,m)}_create9SliceMesh(){const e=j.ONE,t=3,s=3,i=[],r=[],a=[],n=[];let o=0;for(let h=0;h<=t;h++){const d=h===0||h===t?0:1;for(let u=0;u<=s;u++){const f=-e.x+2*e.x*(h<=1?0:3)/t,p=0,m=-(-e.y+2*e.y*(u<=1?0:3)/s),_=u===0||u===s?0:1;i.push(-f,p,m),r.push(0,1,0),a.push(d,_),h<t&&u<s&&(n.push(o+s+1,o+1,o),n.push(o+s+1,o+s+2,o+1)),o++}}const c=new un;return c.positions=i,c.normals=r,c.uvs=a,c.indices=n,at.fromGeometry(this._device,c)}_onSetFrames(e){this._updatingProperties?this._meshesDirty=!0:this._createMeshes()}_onFrameChanged(e,t){const s=this._frameKeys.indexOf(e);s<0||(t?this.renderMode===Fi&&(this._meshes[s]=this._createSimpleMesh(t)):this._meshes[s]=null,this.fire("set:meshes"))}_onFrameRemoved(e){const t=this._frameKeys.indexOf(e);t<0||(this._meshes[t]=null,this.fire("set:meshes"))}startUpdate(){this._updatingProperties=!0,this._meshesDirty=!1}endUpdate(){this._updatingProperties=!1,this._meshesDirty&&this._atlas&&this._frameKeys&&this._createMeshes(),this._meshesDirty=!1}destroy(){for(const e of this._meshes)e&&e.destroy();this._meshes.length=0}}class CM extends ge{constructor(){super(),this._texture=null,this._frames=null}set texture(e){this._texture=e,this.fire("set:texture",e)}get texture(){return this._texture}set frames(e){this._frames=e,this.fire("set:frames",e)}get frames(){return this._frames}setFrame(e,t){let s=this._frames[e];s?(s.rect.copy(t.rect),s.pivot.copy(t.pivot),s.border.copy(t.border)):(s={rect:t.rect.clone(),pivot:t.pivot.clone(),border:t.border.clone()},this._frames[e]=s),this.fire("set:frame",e.toString(),s)}removeFrame(e){const t=this._frames[e];t&&(delete this._frames[e],this.fire("remove:frame",e.toString(),t))}destroy(){this._texture&&this._texture.destroy()}}class fy{constructor(e,t,s,i){this.time=e,this.position=t,this.rotation=s,this.scale=i}}class py{constructor(){this._name="",this._keys=[]}}class my{name="";duration=0;constructor(){this._nodes=[],this._nodeDict={}}getNode(e){return this._nodeDict[e]}addNode(e){this._nodes.push(e),this._nodeDict[e._name]=e}get nodes(){return this._nodes}}class EM{constructor(){this._written=!1,this._name="",this._keyFrames=[],this._quat=new ae,this._pos=new E,this._scale=new E,this._targetNode=null}getTarget(){return this._targetNode}setTarget(e){this._targetNode=e}}class Up{looping=!0;constructor(e){this._animation=null,this._time=0,this._interpolatedKeys=[],this._interpolatedKeyDict={},this._currKeyIndices={},this.graph=null;const t=s=>{const i=new EM;i._name=s.name,this._interpolatedKeys.push(i),this._interpolatedKeyDict[s.name]=i,this._currKeyIndices[s.name]=0;for(let r=0;r<s._children.length;r++)t(s._children[r])};t(e)}set animation(e){this._animation=e,this.currentTime=0}get animation(){return this._animation}set currentTime(e){this._time=e;const t=this._interpolatedKeys.length;for(let s=0;s<t;s++){const r=this._interpolatedKeys[s]._name;this._currKeyIndices[r]=0}this.addTime(0),this.updateGraph()}get currentTime(){return this._time}get numNodes(){return this._interpolatedKeys.length}addTime(e){if(this._animation!==null){const t=this._animation._nodes,s=this._animation.duration;if(this._time===s&&!this.looping)return;if(this._time+=e,this._time>s){this._time=this.looping?0:s;for(let r=0;r<t.length;r++){const n=t[r]._name;this._currKeyIndices[n]=0}}else if(this._time<0){this._time=this.looping?s:0;for(let r=0;r<t.length;r++){const a=t[r],n=a._name;this._currKeyIndices[n]=a._keys.length-2}}const i=e>=0?1:-1;for(let r=0;r<t.length;r++){const a=t[r],n=a._name,o=a._keys,c=this._interpolatedKeyDict[n];if(c===void 0)continue;let h=!1;if(o.length!==1)for(let d=this._currKeyIndices[n];d<o.length-1&&d>=0;d+=i){const u=o[d],f=o[d+1];if(u.time<=this._time&&f.time>=this._time){const p=(this._time-u.time)/(f.time-u.time);c._pos.lerp(u.position,f.position,p),c._quat.slerp(u.rotation,f.rotation,p),c._scale.lerp(u.scale,f.scale,p),c._written=!0,this._currKeyIndices[n]=d,h=!0;break}}(o.length===1||!h&&this._time===0&&this.looping)&&(c._pos.copy(o[0].position),c._quat.copy(o[0].rotation),c._scale.copy(o[0].scale),c._written=!0)}}}blend(e,t,s){const i=this._interpolatedKeys.length;for(let r=0;r<i;r++){const a=e._interpolatedKeys[r],n=t._interpolatedKeys[r],o=this._interpolatedKeys[r];a._written&&n._written?(o._quat.slerp(a._quat,t._interpolatedKeys[r]._quat,s),o._pos.lerp(a._pos,t._interpolatedKeys[r]._pos,s),o._scale.lerp(a._scale,n._scale,s),o._written=!0):a._written?(o._quat.copy(a._quat),o._pos.copy(a._pos),o._scale.copy(a._scale),o._written=!0):n._written&&(o._quat.copy(n._quat),o._pos.copy(n._pos),o._scale.copy(n._scale),o._written=!0)}}setGraph(e){if(this.graph=e,e)for(let t=0;t<this._interpolatedKeys.length;t++){const s=this._interpolatedKeys[t],i=e.findByName(s._name);this._interpolatedKeys[t].setTarget(i)}else for(let t=0;t<this._interpolatedKeys.length;t++)this._interpolatedKeys[t].setTarget(null)}updateGraph(){if(this.graph)for(let e=0;e<this._interpolatedKeys.length;e++){const t=this._interpolatedKeys[e];if(t._written){const s=t.getTarget();s.localPosition.copy(t._pos),s.localRotation.copy(t._quat),s.localScale.copy(t._scale),s._dirtyLocal||s._dirtifyLocal(),t._written=!1}}}}const bM=` 778@group(0) @binding(0) var<storage, read_write> items: array<u32>; 779@group(0) @binding(1) var<storage, read_write> blockSums: array<u32>; 780struct PrefixSumUniforms { 781 elementCount: u32 782}; 783@group(0) @binding(2) var<uniform> uniforms: PrefixSumUniforms; 784const WORKGROUP_SIZE_X: u32 = {WORKGROUP_SIZE_X}u; 785const WORKGROUP_SIZE_Y: u32 = {WORKGROUP_SIZE_Y}u; 786const THREADS_PER_WORKGROUP: u32 = {THREADS_PER_WORKGROUP}u; 787const ITEMS_PER_WORKGROUP: u32 = {ITEMS_PER_WORKGROUP}u; 788var<workgroup> temp: array<u32, ITEMS_PER_WORKGROUP * 2>; 789@compute @workgroup_size(WORKGROUP_SIZE_X, WORKGROUP_SIZE_Y, 1) 790fn reduce_downsweep( 791 @builtin(workgroup_id) w_id: vec3<u32>, 792 @builtin(num_workgroups) w_dim: vec3<u32>, 793 @builtin(local_invocation_index) TID: u32, 794) { 795 let WORKGROUP_ID = w_id.x + w_id.y * w_dim.x; 796 let WID = WORKGROUP_ID * THREADS_PER_WORKGROUP; 797 let GID = WID + TID; 798 799 let ELM_TID = TID * 2; 800 let ELM_GID = GID * 2; 801 802 temp[ELM_TID] = select(items[ELM_GID], 0u, ELM_GID >= uniforms.elementCount); 803 temp[ELM_TID + 1u] = select(items[ELM_GID + 1u], 0u, ELM_GID + 1u >= uniforms.elementCount); 804 var offset: u32 = 1u;
805 for (var d: u32 = ITEMS_PER_WORKGROUP >> 1u; d > 0u; d >>= 1u) { 806 workgroupBarrier(); 807 if (TID < d) { 808 var ai: u32 = offset * (ELM_TID + 1u) - 1u; 809 var bi: u32 = offset * (ELM_TID + 2u) - 1u; 810 temp[bi] += temp[ai]; 811 } 812 offset *= 2u; 813 } 814 if (TID == 0u) { 815 let last_offset = ITEMS_PER_WORKGROUP - 1u; 816 blockSums[WORKGROUP_ID] = temp[last_offset]; 817 temp[last_offset] = 0u; 818 } 819 for (var d: u32 = 1u; d < ITEMS_PER_WORKGROUP; d *= 2u) { 820 offset >>= 1u; 821 workgroupBarrier(); 822 if (TID < d) { 823 var ai: u32 = offset * (ELM_TID + 1u) - 1u; 824 var bi: u32 = offset * (ELM_TID + 2u) - 1u; 825 let t: u32 = temp[ai]; 826 temp[ai] = temp[bi]; 827 temp[bi] += t; 828 } 829 } 830 workgroupBarrier(); 831 if (ELM_GID < uniforms.elementCount) { 832 items[ELM_GID] = temp[ELM_TID]; 833 } 834 if (ELM_GID + 1u < uniforms.elementCount) { 835 items[ELM_GID + 1u] = temp[ELM_TID + 1u]; 836 } 837} 838@compute @workgroup_size(WORKGROUP_SIZE_X, WORKGROUP_SIZE_Y, 1) 839fn add_block_sums( 840 @builtin(workgroup_id) w_id: vec3<u32>, 841 @builtin(num_workgroups) w_dim: vec3<u32>, 842 @builtin(local_invocation_index) TID: u32, 843) { 844 let WORKGROUP_ID = w_id.x + w_id.y * w_dim.x; 845 let WID = WORKGROUP_ID * THREADS_PER_WORKGROUP; 846 let GID = WID + TID; 847 let ELM_ID = GID * 2u; 848 if (ELM_ID >= uniforms.elementCount) { 849 return; 850 } 851 let blockSum = blockSums[WORKGROUP_ID]; 852 items[ELM_ID] += blockSum; 853 if (ELM_ID + 1u >= uniforms.elementCount) { 854 return; 855 } 856 items[ELM_ID + 1u] += blockSum; 857} 858`,lw=16,cw=16,hw=lw*cw,Hh=2*hw;class Gg{device;passes=[];_uniformBufferFormat=null;_bindGroupFormat=null;_scanShader=null;_addBlockShader=null;constructor(e){this.device=e,this._createFormatsAndShaders()}destroy(){this.destroyPasses(),this._scanShader?.destroy(),this._addBlockShader?.destroy(),this._bindGroupFormat?.destroy(),this._scanShader=null,this._addBlockShader=null,this._bindGroupFormat=null,this._uniformBufferFormat=null}_createFormatsAndShaders(){this._uniformBufferFormat=new vt(this.device,[new X("elementCount",le)]),this._bindGroupFormat=new Ze(this.device,[new q("items",G,!1),new q("blockSums",G,!1),new At("uniforms",G)]),this._scanShader=this._createShader("PrefixSumScan","reduce_downsweep"),this._addBlockShader=this._createShader("PrefixSumAddBlock","add_block_sums")}createPassesRecursive(e,t){const s=Math.ceil(t/Hh),{x:i,y:r}=this.findOptimalDispatchSize(s),a=new Se(this.device,s*4),n=new Qe(this.device,this._scanShader,"PrefixSumScan");n.setParameter("items",e),n.setParameter("blockSums",a);const o={scanCompute:n,addBlockCompute:null,blockSumBuffer:a,dispatchX:i,dispatchY:r,count:t,allocatedCount:t};if(this.passes.push(o),s>1){this.createPassesRecursive(a,s);const c=new Qe(this.device,this._addBlockShader,"PrefixSumAddBlock");c.setParameter("items",e),c.setParameter("blockSums",a),o.addBlockCompute=c}}_createShader(e,t){const s=new Map;return s.set("{WORKGROUP_SIZE_X}",lw),s.set("{WORKGROUP_SIZE_Y}",cw),s.set("{THREADS_PER_WORKGROUP}",hw),s.set("{ITEMS_PER_WORKGROUP}",Hh),new tt(this.device,{name:e,shaderLanguage:de,cshader:bM,cdefines:s,computeEntryPoint:t,computeBindGroupFormat:this._bindGroupFormat,computeUniformBufferFormats:{uniforms:this._uniformBufferFormat}})}findOptimalDispatchSize(e){const t=this.device.limits.maxComputeWorkgroupsPerDimension||65535;if(e<=t)return{x:e,y:1};const s=Math.floor(Math.sqrt(e)),i=Math.ceil(e/s);return{x:s,y:i}}resize(e,t){const s=this._countPassesNeeded(t),i=this.passes.length;if(s>i){this.destroyPasses(),this.createPassesRecursive(e,t);return}let r=t;for(let a=0;a<this.passes.length;a++){const n=Math.ceil(r/Hh),{x:o,y:c}=this.findOptimalDispatchSize(n);if(this.passes[a].count=r,this.passes[a].dispatchX=o,this.passes[a].dispatchY=c,r=n,n<=1)break}}destroyPasses(){for(const e of this.passes)e.blockSumBuffer?.destroy();this.passes.length=0}_countPassesNeeded(e){let t=0,s=e;for(;s>0;){t++;const i=Math.ceil(s/Hh);if(i<=1)break;s=i}return t}dispatch(e){for(let t=0;t<this.passes.length;t++){const s=this.passes[t];s.scanCompute.setParameter("elementCount",s.count),s.scanCompute.setupDispatch(s.dispatchX,s.dispatchY,1),e.computeDispatch([s.scanCompute],"PrefixSumScan")}for(let t=this.passes.length-1;t>=0;t--){const s=this.passes[t];s.addBlockCompute&&(s.addBlockCompute.setParameter("elementCount",s.count),s.addBlockCompute.setupDispatch(s.dispatchX,s.dispatchY,1),e.computeDispatch([s.addBlockCompute],"PrefixSumAddBlock"))}}}const AM=` 859@group(0) @binding(0) var<storage, read> input: array<u32>; 860@group(0) @binding(1) var<storage, read_write> block_sums: array<u32>; 861struct RadixSortUniforms { 862 workgroupCount: u32, 863 elementCount: u32 864}; 865@group(0) @binding(2) var<uniform> uniforms: RadixSortUniforms; 866#ifdef USE_INDIRECT_SORT 867 @group(0) @binding(3) var<storage, read> sortElementCount: array<u32>; 868#endif 869const THREADS_PER_WORKGROUP: u32 = {THREADS_PER_WORKGROUP}u; 870const WORKGROUP_SIZE_X: u32 = {WORKGROUP_SIZE_X}u; 871const WORKGROUP_SIZE_Y: u32 = {WORKGROUP_SIZE_Y}u; 872const CURRENT_BIT: u32 = {CURRENT_BIT}u; 873const ELEMENTS_PER_THREAD: u32 = {ELEMENTS_PER_THREAD}u; 874const ELEMENTS_PER_WORKGROUP: u32 = THREADS_PER_WORKGROUP * ELEMENTS_PER_THREAD; 875var<workgroup> histogram: array<atomic<u32>, 16>; 876@compute @workgroup_size(WORKGROUP_SIZE_X, WORKGROUP_SIZE_Y, 1) 877fn main( 878 @builtin(workgroup_id) w_id: vec3<u32>, 879 @builtin(num_workgroups) w_dim: vec3<u32>, 880 @builtin(local_invocation_index) TID: u32, 881) { 882 let WORKGROUP_ID = w_id.x + w_id.y * w_dim.x; 883 let WID = WORKGROUP_ID * ELEMENTS_PER_WORKGROUP; 884 if (TID < 16u) { 885 atomicStore(&histogram[TID], 0u); 886 } 887 workgroupBarrier(); 888 #ifdef USE_INDIRECT_SORT 889 let elementCount = sortElementCount[0]; 890 #else 891 let elementCount = uniforms.elementCount; 892 #endif 893 for (var r = 0u; r < ELEMENTS_PER_THREAD; r++) { 894 let GID = WID + r * THREADS_PER_WORKGROUP + TID; 895 let is_valid = GID < elementCount && WORKGROUP_ID < uniforms.workgroupCount; 896 if (is_valid) { 897 let elm = input[GID]; 898 let digit = (elm >> CURRENT_BIT) & 0xFu;
899 atomicAdd(&histogram[digit], 1u); 900 } 901 } 902 workgroupBarrier(); 903 if (TID < 16u && WORKGROUP_ID < uniforms.workgroupCount) { 904 block_sums[TID * uniforms.workgroupCount + WORKGROUP_ID] = atomicLoad(&histogram[TID]); 905 } 906} 907`,PM=` 908@group(0) @binding(0) var<storage, read> inputKeys: array<u32>; 909@group(0) @binding(1) var<storage, read_write> outputKeys: array<u32>; 910@group(0) @binding(2) var<storage, read> prefix_block_sum: array<u32>; 911@group(0) @binding(3) var<storage, read> inputValues: array<u32>; 912@group(0) @binding(4) var<storage, read_write> outputValues: array<u32>; 913struct RadixSortUniforms { 914 workgroupCount: u32, 915 elementCount: u32 916}; 917@group(0) @binding(5) var<uniform> uniforms: RadixSortUniforms; 918#ifdef USE_INDIRECT_SORT 919 @group(0) @binding(6) var<storage, read> sortElementCount: array<u32>; 920#endif 921const THREADS_PER_WORKGROUP: u32 = {THREADS_PER_WORKGROUP}u; 922const WORKGROUP_SIZE_X: u32 = {WORKGROUP_SIZE_X}u; 923const WORKGROUP_SIZE_Y: u32 = {WORKGROUP_SIZE_Y}u; 924const CURRENT_BIT: u32 = {CURRENT_BIT}u; 925const IS_FIRST_PASS: u32 = {IS_FIRST_PASS}u; 926const IS_LAST_PASS: u32 = {IS_LAST_PASS}u; 927const ELEMENTS_PER_THREAD: u32 = {ELEMENTS_PER_THREAD}u; 928const ELEMENTS_PER_WORKGROUP: u32 = THREADS_PER_WORKGROUP * ELEMENTS_PER_THREAD; 929var<workgroup> digit_masks: array<atomic<u32>, 128>; 930var<workgroup> digit_offsets: array<u32, 16>;
931@compute @workgroup_size(WORKGROUP_SIZE_X, WORKGROUP_SIZE_Y, 1) 932fn main( 933 @builtin(workgroup_id) w_id: vec3<u32>, 934 @builtin(num_workgroups) w_dim: vec3<u32>, 935 @builtin(local_invocation_index) TID: u32, 936) { 937 let WORKGROUP_ID = w_id.x + w_id.y * w_dim.x; 938 let WID = WORKGROUP_ID * ELEMENTS_PER_WORKGROUP; 939 let word_idx = TID >> 5u; 940 let bit_idx = TID & 31u; 941 if (TID < 16u) { 942 digit_offsets[TID] = 0u; 943 } 944 if (TID < 128u) { 945 atomicStore(&digit_masks[TID], 0u); 946 } 947 workgroupBarrier(); 948 #ifdef USE_INDIRECT_SORT 949 let elementCount = sortElementCount[0]; 950 #else 951 let elementCount = uniforms.elementCount; 952 #endif 953 for (var round = 0u; round < ELEMENTS_PER_THREAD; round++) { 954 let GID = WID + round * THREADS_PER_WORKGROUP + TID; 955 let is_valid = GID < elementCount; 956 let k = select(0u, inputKeys[GID], is_valid); 957 let digit = select(16u, (k >> CURRENT_BIT) & 0xFu, is_valid); 958 let v = select(0u, select(inputValues[GID], GID, IS_FIRST_PASS == 1u), is_valid); 959 if (is_valid) { 960 atomicOr(&digit_masks[digit * 8u + word_idx], 1u << bit_idx); 961 } 962 workgroupBarrier(); 963 if (is_valid) { 964 let base = digit * 8u; 965 var local_prefix = digit_offsets[digit]; 966 for (var w = 0u; w < word_idx; w++) { 967 local_prefix += countOneBits(atomicLoad(&digit_masks[base + w])); 968 } 969 local_prefix += countOneBits(atomicLoad(&digit_masks[base + word_idx]) & ((1u << bit_idx) - 1u)); 970 let pid = digit * uniforms.workgroupCount + WORKGROUP_ID; 971 let sorted_position = prefix_block_sum[pid] + local_prefix; 972 if (IS_LAST_PASS == 0u) { 973 outputKeys[sorted_position] = k; 974 } 975 outputValues[sorted_position] = v; 976 } 977 if (round < ELEMENTS_PER_THREAD - 1u) { 978 workgroupBarrier(); 979 if (TID < 16u) { 980 var count = 0u; 981 for (var w = 0u; w < 8u; w++) { 982 let idx = TID * 8u + w; 983 count += countOneBits(atomicLoad(&digit_masks[idx])); 984 atomicStore(&digit_masks[idx], 0u); 985 } 986 digit_offsets[TID] += count; 987 } 988 workgroupBarrier(); 989 } 990 } 991} 992`;class dw{device;_indirect=!1;constructor(e,t=!1){this.device=e,this._indirect=t}capacity=0;_elementCount=0;_numBits=0;_hasInitialValues=!1;_skipLastPassKeyWrite=!1;_destructiveKeys=!1;_keys0=null;_keys1=null;_values0=null;_values1=null;_indirectInfo=new Uint32Array(4);get sortedIndices(){return this._values0?this._numBits/this.radixBits%2===1?this._values1:this._values0:null}get sortedKeys(){if(!this._keys0)return null;const e=this.radixBits;return this._numBits/e%2===0?this._keys1:this._keys0}get radixBits(){return 0}sort(e,t,s,i,r,a){return null}sortIndirect(e,t,s,i,r,a,n,o){return null}prepareIndirect(){return this._indirectInfo}_allocatePingPongElementBuffers(e){const t=e*4,s=Si|ct,i=this.device;this._keys0=new Se(i,t,s),this._destructiveKeys||(this._keys1=new Se(i,t,s)),this._values0=new Se(i,t,s),this._values1=new Se(i,t,s)}_destroyPingPongBuffers(){this._keys0?.destroy(),this._destructiveKeys||this._keys1?.destroy(),this._values0?.destroy(),this._values1?.destroy(),this._keys0=null,this._keys1=null,this._values0=null,this._values1=null}destroy(){}}const uw=16,fw=16,pw=uw*fw,mw=8,zp=pw*mw,Wh=4,_y=16;class IM extends dw{_workgroupCount=0;_allocatedWorkgroupCount=0;_blockSums=null;_prefixSumKernel=null;
992_dispatchSize=new j(1,1);_histogramBindGroupFormat=null;_reorderBindGroupFormat=null;_uniformBufferFormat=null;_passes=[];constructor(e,t=!1){super(e,t);const s=this._indirectInfo;s[0]=1,s[1]=zp,this._uniformBufferFormat=new vt(e,[new X("workgroupCount",le),new X("elementCount",le)]);const i=[new q("input",G,!0),new q("block_sums",G,!1),new At("uniforms",G)],r=[new q("inputKeys",G,!0),new q("outputKeys",G,!1),new q("prefix_block_sum",G,!0),new q("inputValues",G,!0),new q("outputValues",G,!1),new At("uniforms",G)];t&&(i.push(new q("sortElementCount",G,!0)),r.push(new q("sortElementCount",G,!0))),this._histogramBindGroupFormat=new Ze(e,i),this._reorderBindGroupFormat=new Ze(e,r)}destroy(){this._destroyBuffers(),this._destroyPasses(),this._histogramBindGroupFormat?.destroy(),this._reorderBindGroupFormat?.destroy(),this._histogramBindGroupFormat=null,this._reorderBindGroupFormat=null,this._uniformBufferFormat=null,super.destroy()}_destroyPasses(){for(const e of this._passes)e.histogramCompute.shader?.destroy(),e.reorderCompute.shader?.destroy();this._passes.length=0,this._numBits=0}_destroyBuffers(){this._destroyPingPongBuffers(),this._blockSums?.destroy(),this._prefixSumKernel?.destroy(),this._blockSums=null,this._prefixSumKernel=null,this._workgroupCount=0,this._allocatedWorkgroupCount=0}get radixBits(){return Wh}_createPasses(e,t,s){this._destroyPasses(),this._numBits=e,this._hasInitialValues=t,this._skipLastPassKeyWrite=s;const i=e/Wh,r=this._indirect?"-Indirect":"";for(let a=0;a<i;a++){const n=a*Wh,o=a===0&&!t,c=s&&a===i-1,h=this._createShader(`RadixSort4bit-Histogram${r}-${n}`,AM,n,!1,!1,this._histogramBindGroupFormat),d=this._createShader(`RadixSort4bit-Reorder${r}-${n}`,PM,n,o,c,this._reorderBindGroupFormat),u=new Qe(this.device,h,`RadixSort4bit-Histogram${r}-${n}`),f=new Qe(this.device,d,`RadixSort4bit-Reorder${r}-${n}`);this._passes.push({histogramCompute:u,reorderCompute:f})}}_allocateBuffers(e,t,s,i,r=!1){const a=Math.max(e,this.capacity),n=Math.ceil(a/zp),o=Math.max(1,Math.ceil(e/zp)),c=r||n!==this._allocatedWorkgroupCount||!this._keys0,h=t!==this._numBits||s!==this._hasInitialValues||i!==this._skipLastPassKeyWrite;if(c){this._destroyBuffers(),this._allocatedWorkgroupCount=n,this.capacity=a;const d=_y*n*4;this._allocatePingPongElementBuffers(a),this._blockSums=new Se(this.device,d,Si|ct),this._prefixSumKernel=new Gg(this.device)}this._workgroupCount=o,Qe.calcDispatchSize(o,this._dispatchSize,this.device.limits.maxComputeWorkgroupsPerDimension||65535),this._prefixSumKernel.resize(this._blockSums,_y*o),h&&this._createPasses(t,s,i)}_createShader(e,t,s,i,r,a){const n=new Map;return n.set("{WORKGROUP_SIZE_X}",uw),n.set("{WORKGROUP_SIZE_Y}",fw),n.set("{THREADS_PER_WORKGROUP}",pw),n.set("{ELEMENTS_PER_THREAD}",mw),n.set("{CURRENT_BIT}",s),n.set("{IS_FIRST_PASS}",i?1:0),n.set("{IS_LAST_PASS}",r?1:0),this._indirect&&n.set("USE_INDIRECT_SORT",""),new tt(this.device,{name:e,shaderLanguage:de,cshader:t,cdefines:n,computeBindGroupFormat:a,computeUniformBufferFormats:{uniforms:this._uniformBufferFormat}})}sort(e,t,s=16,i,r=!1,a=!1){return this._execute(e,t,s,-1,null,i,r,a)}sortIndirect(e,t,s,i,r,a,n=!1,o=!1){return this._execute(e,t,s,i,r,a,n,o)}_execute(e,t,s,i,r,a,n=!1,o=!1){this._elementCount=t;const c=!!a,h=this._destructiveKeys;this._destructiveKeys=o,this._allocateBuffers(t,s,c,n,o!==h),o&&(this._keys1=e);const d=this.device,u=s/Wh,f=this._indirect?"-Indirect":"";let p=e,m=a??this._values0,_=this._keys0,g=this._values1;for(let v=0;v<u;v++){const{histogramCompute:x,reorderCompute:y}=this._passes[v],S=v===u-1;if(this._indirect&&this._blockSums.clear(),x.setParameter("input",p),x.setParameter("block_sums",this._blockSums),x.setParameter("workgroupCount",this._workgroupCount),x.setParameter("elementCount",t),this._indirect?(x.setParameter("sortElementCount",r),x.setupIndirectDispatch(i)):x.setupDispatch(this._dispatchSize.x,this._dispatchSize.y,1),d.computeDispatch([x],`RadixSort4bit-Histogram${f}`),this._prefixSumKernel.dispatch(d),y.setParameter("inputKeys",p),y.setParameter("outputKeys",_),y.setParameter("prefix_block_sum",this._blockSums),y.setParameter("inputValues",m),y.setParameter("outputValues",g),y.setParameter("workgroupCount",this._workgroupCount),y.setParameter("elementCount",t),this._indirect?(y.setParameter("sortElementCount",r),y.setupIndirectDispatch(i)):y.setupDispatch(this._dispatchSize.x,this._dispatchSize.y,1),d.computeDispatch([y],`RadixSort4bit-Reorder${f}`),!S){p=_,_=p===this._keys0?this._keys1:this._keys0;const T=m;m=g,g=T}}return this.sortedIndices}}const DM=` 993@group(0) @binding(0) var<storage, read> b_sort: array<vec4<u32>>; 994@group(0) @binding(1) var<storage, read_write> b_globalHist: array<atomic<u32>>; 995struct OneSweepUniforms { 996 numKeys: u32, 997 threadBlocks: u32, 998 numPasses: u32, 999 _pad: u32 1000}; 1001@group(0) @binding(2) var<uniform> uniforms: OneSweepUniforms; 1002#ifdef USE_INDIRECT_SORT 1003@group(0) @binding(3) var<storage, read> b_sortElementCount: array<u32>; 1004#endif 1005const RADIX: u32 = 256u; 1006const MAX_PASSES: u32 = 4u; 1007const G_HIST_DIM: u32 = {G_HIST_DIM}u; 1008const G_HIST_PART_SIZE: u32 = {G_HIST_PART_SIZE}u; 1009const G_HIST_PART_SIZE_VEC: u32 = G_HIST_PART_SIZE / 4u; 1010const SHARED_HIST_SIZE: u32 = 2u * MAX_PASSES * RADIX; 1011var<workgroup> g_gHist: array<atomic<u32>, SHARED_HIST_SIZE>; 1012fn histOffset(row: u32, pass_: u32) -> u32 { 1013 return row * RADIX + pass_ * 2u * RADIX; 1014} 1015@compute @workgroup_size(G_HIST_DIM, 1, 1) 1016fn main( 1017 @builtin(local_invocation_index) gtid: u32, 1018 @builtin(workgroup_id) gid: vec3<u32>, 1019 @builtin(num_workgroups) nwg: vec3<u32>, 1020) { 1021 let flatGid = gid.x + gid.y * nwg.x; 1022 let numPasses = uniforms.numPasses; 1023 #ifdef USE_INDIRECT_SORT
1024 let numKeys = b_sortElementCount[0]; 1025 #else 1026 let numKeys = uniforms.numKeys; 1027 #endif 1028 let sharedEnd = 2u * numPasses * RADIX; 1029 for (var i = gtid; i < sharedEnd; i = i + G_HIST_DIM) { 1030 atomicStore(&g_gHist[i], 0u); 1031 } 1032 workgroupBarrier(); 1033 let row = gtid / 64u; 1034 let numKeysVecFull = numKeys >> 2u; 1035 let partitionStartVec = flatGid * G_HIST_PART_SIZE_VEC; 1036 let partitionEndVec = min(partitionStartVec + G_HIST_PART_SIZE_VEC, numKeysVecFull); 1037 for (var i = partitionStartVec + gtid; i < partitionEndVec; i = i + G_HIST_DIM) { 1038 let q = b_sort[i]; 1039 if (numPasses >= 1u) { 1040 let off = histOffset(row, 0u); 1041 atomicAdd(&g_gHist[(q.x & 0xFFu) + off], 1u); 1042 atomicAdd(&g_gHist[(q.y & 0xFFu) + off], 1u); 1043 atomicAdd(&g_gHist[(q.z & 0xFFu) + off], 1u); 1044 atomicAdd(&g_gHist[(q.w & 0xFFu) + off], 1u); 1045 } 1046 if (numPasses >= 2u) { 1047 let off = histOffset(row, 1u); 1048 atomicAdd(&g_gHist[((q.x >> 8u) & 0xFFu) + off], 1u); 1049 atomicAdd(&g_gHist[((q.y >> 8u) & 0xFFu) + off], 1u); 1050 atomicAdd(&g_gHist[((q.z >> 8u) & 0xFFu) + off], 1u); 1051 atomicAdd(&g_gHist[((q.w >> 8u) & 0xFFu) + off], 1u); 1052 } 1053 if (numPasses >= 3u) { 1054 let off = histOffset(row, 2u); 1055 atomicAdd(&g_gHist[((q.x >> 16u) & 0xFFu) + off], 1u); 1056 atomicAdd(&g_gHist[((q.y >> 16u) & 0xFFu) + off], 1u); 1057 atomicAdd(&g_gHist[((q.z >> 16u) & 0xFFu) + off], 1u); 1058 atomicAdd(&g_gHist[((q.w >> 16u) & 0xFFu) + off], 1u); 1059 } 1060 if (numPasses >= 4u) { 1061 let off = histOffset(row, 3u); 1062 atomicAdd(&g_gHist[((q.x >> 24u) & 0xFFu) + off], 1u); 1063 atomicAdd(&g_gHist[((q.y >> 24u) & 0xFFu) + off], 1u); 1064 atomicAdd(&g_gHist[((q.z >> 24u) & 0xFFu) + off], 1u); 1065 atomicAdd(&g_gHist[((q.w >> 24u) & 0xFFu) + off], 1u); 1066 } 1067 } 1068 let tailIdx = numKeysVecFull; 1069 if ((numKeys & 3u) != 0u && 1070 tailIdx >= partitionStartVec && 1071 tailIdx < partitionStartVec + G_HIST_PART_SIZE_VEC && 1072 (tailIdx - partitionStartVec) % G_HIST_DIM == gtid) { 1073 let q = b_sort[tailIdx]; 1074 let base = tailIdx << 2u; 1075 if (numPasses >= 1u) { 1076 let off = histOffset(row, 0u); 1077 if (base + 0u < numKeys) { atomicAdd(&g_gHist[(q.x & 0xFFu) + off], 1u); } 1078 if (base + 1u < numKeys) { atomicAdd(&g_gHist[(q.y & 0xFFu) + off], 1u); } 1079 if (base + 2u < numKeys) { atomicAdd(&g_gHist[(q.z & 0xFFu) + off], 1u); } 1080 } 1081 if (numPasses >= 2u) { 1082 let off = histOffset(row, 1u); 1083 if (base + 0u < numKeys) { atomicAdd(&g_gHist[((q.x >> 8u) & 0xFFu) + off], 1u); } 1084 if (base + 1u < numKeys) { atomicAdd(&g_gHist[((q.y >> 8u) & 0xFFu) + off], 1u); } 1085 if (base + 2u < numKeys) { atomicAdd(&g_gHist[((q.z >> 8u) & 0xFFu) + off], 1u); } 1086 } 1087 if (numPasses >= 3u) { 1088 let off = histOffset(row, 2u); 1089 if (base + 0u < numKeys) { atomicAdd(&g_gHist[((q.x >> 16u) & 0xFFu) + off], 1u); } 1090 if (base + 1u < numKeys) { atomicAdd(&g_gHist[((q.y >> 16u) & 0xFFu) + off], 1u); } 1091 if (base + 2u < numKeys) { atomicAdd(&g_gHist[((q.z >> 16u) & 0xFFu) + off], 1u); } 1092 } 1093 if (numPasses >= 4u) { 1094 let off = histOffset(row, 3u); 1095 if (base + 0u < numKeys) { atomicAdd(&g_gHist[((q.x >> 24u) & 0xFFu) + off], 1u); } 1096 if (base + 1u < numKeys) { atomicAdd(&g_gHist[((q.y >> 24u) & 0xFFu) + off], 1u); } 1097 if (base + 2u < numKeys) { atomicAdd(&g_gHist[((q.z >> 24u) & 0xFFu) + off], 1u); } 1098 } 1099 } 1100 workgroupBarrier(); 1101 for (var i = gtid; i < RADIX; i = i + G_HIST_DIM) { 1102 for (var p = 0u; p < numPasses; p = p + 1u) { 1103 let row0 = atomicLoad(&g_gHist[i + histOffset(0u, p)]); 1104 let row1 = atomicLoad(&g_gHist[i + histOffset(1u, p)]); 1105 let total = row0 + row1; 1106 if (total != 0u) { 1107 atomicAdd(&b_globalHist[i + p * RADIX], total); 1108 } 1109 } 1110 } 1111} 1112`,MM=` 1113@group(0) @binding(0) var<storage, read> b_globalHist: array<u32>; 1114@group(0) @binding(1) var<storage, read_write> b_passHist: array<atomic<u32>>; 1115struct OneSweepScanUniforms { 1116 threadBlocks: u32, 1117 _pad0: u32, 1118 _pad1: u32, 1119 _pad2: u32 1120}; 1121@group(0) @binding(2) var<uniform> uniforms: OneSweepScanUniforms; 1122#ifdef USE_INDIRECT_SORT 1123@group(0) @binding(3) var<storage, read> b_sortElementCount: array<u32>; 1124#endif 1125const RADIX: u32 = 256u; 1126const FLAG_INCLUSIVE: u32 = 2u; 1127const PART_SIZE: u32 = {PART_SIZE}u; 1128const MAX_SUBGROUPS: u32 = {MAX_SUBGROUPS}u; 1129var<workgroup> g_scan: array<u32, RADIX>; 1130var<workgroup> sg_totals: array<u32, MAX_SUBGROUPS>; 1131@compute @workgroup_size(RADIX, 1, 1) 1132fn main( 1133 @builtin(local_invocation_index) gtid: u32, 1134 @builtin(workgroup_id) gid: vec3<u32>, 1135 @builtin(subgroup_invocation_id) sgInvId: u32, 1136 @builtin(subgroup_size) sgSize: u32, 1137) { 1138 let pass_ = gid.x; 1139 #ifdef USE_INDIRECT_SORT
1140 let numKeys = b_sortElementCount[0]; 1141 let threadBlocks = (numKeys + PART_SIZE - 1u) / PART_SIZE; 1142 #else 1143 let threadBlocks = uniforms.threadBlocks; 1144 #endif 1145 let waveIndex = gtid / sgSize; 1146 let t = b_globalHist[gtid + pass_ * RADIX]; 1147 let sgExcl = subgroupExclusiveAdd(t); 1148 let sgTotal = subgroupAdd(t); 1149 if (sgInvId == 0u) { 1150 sg_totals[waveIndex] = sgTotal; 1151 } 1152 workgroupBarrier(); 1153 if (gtid == 0u) { 1154 var acc: u32 = 0u; 1155 for (var i = 0u; i < MAX_SUBGROUPS; i = i + 1u) { 1156 let v = sg_totals[i]; 1157 sg_totals[i] = acc; 1158 acc = acc + v; 1159 } 1160 } 1161 workgroupBarrier(); 1162 let excl = sgExcl + sg_totals[waveIndex]; 1163 g_scan[gtid] = excl; 1164 let dst = pass_ * threadBlocks * RADIX + gtid; 1165 atomicStore(&b_passHist[dst], (excl << 2u) | FLAG_INCLUSIVE); 1166} 1167`,RM=` 1168@group(0) @binding(0) var<storage, read> inputKeys: array<u32>; 1169@group(0) @binding(1) var<storage, read_write> outputKeys: array<u32>; 1170@group(0) @binding(2) var<storage, read> inputValues: array<u32>; 1171@group(0) @binding(3) var<storage, read_write> outputValues: array<u32>; 1172@group(0) @binding(4) var<storage, read_write> b_passHist: array<atomic<u32>>; 1173@group(0) @binding(5) var<storage, read_write> b_index: array<atomic<u32>>; 1174struct OneSweepBinningUniforms { 1175 numKeys: u32, 1176 threadBlocks: u32, 1177 pass_: u32, 1178 flags: u32 1179}; 1180@group(0) @binding(6) var<uniform> uniforms: OneSweepBinningUniforms; 1181#ifdef USE_INDIRECT_SORT 1182@group(0) @binding(7) var<storage, read> b_sortElementCount: array<u32>; 1183#endif 1184const RADIX: u32 = 256u; 1185const RADIX_MASK: u32 = 255u; 1186const RADIX_LOG: u32 = 8u; 1187const D_DIM: u32 = {D_DIM}u; 1188const KEYS_PER_THREAD: u32 = {KEYS_PER_THREAD}u; 1189const PART_SIZE: u32 = D_DIM * KEYS_PER_THREAD; 1190const MAX_SUBGROUPS: u32 = {MAX_SUBGROUPS}u; 1191const WAVE_HISTS_SIZE: u32 = MAX_SUBGROUPS * RADIX; 1192const G_D_SIZE: u32 = max(PART_SIZE, WAVE_HISTS_SIZE); 1193const FLAG_NOT_READY: u32 = 0u; 1194const FLAG_REDUCTION: u32 = 1u; 1195const FLAG_INCLUSIVE: u32 = 2u; 1196const FLAG_MASK: u32 = 3u; 1197var<workgroup> g_d: array<atomic<u32>, G_D_SIZE>; 1198var<workgroup> digit_base: array<u32, RADIX>; 1199var<workgroup> sg_totals: array<u32, MAX_SUBGROUPS>; 1200var<workgroup> wg_partIndex: u32; 1201fn passHistOffset(tb: u32, pass_: u32, partitionIdx: u32) -> u32 { 1202 return pass_ * tb * RADIX + partitionIdx * RADIX; 1203} 1204@compute @workgroup_size(D_DIM, 1, 1) 1205fn main( 1206 @builtin(local_invocation_index) TID: u32, 1207 @builtin(subgroup_invocation_id) sgInvId: u32, 1208 @builtin(subgroup_size) sgSize: u32, 1209) { 1210 let waveIndex = TID / sgSize; 1211 let ltMask = (1u << sgInvId) - 1u; 1212 let activeMask = select(0xFFFFFFFFu, (1u << sgSize) - 1u, sgSize < 32u); 1213 let pass_ = uniforms.pass_; 1214 let currentBit = pass_ << 3u; 1215 #ifdef USE_INDIRECT_SORT 1216 let numKeys = b_sortElementCount[0]; 1217 let threadBlocks = (numKeys + PART_SIZE - 1u) / PART_SIZE; 1218 #else 1219 let numKeys = uniforms.numKeys; 1220 let threadBlocks = uniforms.threadBlocks; 1221 #endif 1222 let isFirstPass = (uniforms.flags & 1u) != 0u; 1223 let isLastPass = (uniforms.flags & 2u) != 0u; 1224 if (TID == 0u) { 1225 wg_partIndex = atomicAdd(&b_index[pass_], 1u); 1226 } 1227 let partitionIndex = workgroupUniformLoad(&wg_partIndex); 1228 for (var i = TID; i < WAVE_HISTS_SIZE; i = i + D_DIM) { 1229 atomicStore(&g_d[i], 0u); 1230 } 1231 workgroupBarrier(); 1232 let tileStart = partitionIndex * PART_SIZE; 1233 let validInBlock = select( 1234 0u, 1235 min(PART_SIZE, numKeys - tileStart), 1236 tileStart < numKeys 1237 ); 1238 let subPartSize = sgSize * KEYS_PER_THREAD; 1239 let waveBase = tileStart + waveIndex * subPartSize; 1240 var keys: array<u32, {KEYS_PER_THREAD}>; 1241 var values: array<u32, {KEYS_PER_THREAD}>; 1242 var validMask: u32 = 0u; 1243 for (var i = 0u; i < KEYS_PER_THREAD; i = i + 1u) { 1244 let gid = waveBase + sgInvId + i * sgSize; 1245 let is_valid = gid < numKeys; 1246 keys[i] = select(0xFFFFFFFFu, inputKeys[gid], is_valid); 1247 values[i] = select( 1248 select(0u, inputValues[gid], is_valid), 1249 gid, 1250 isFirstPass 1251 ); 1252 if (is_valid) { 1253 validMask = validMask | (1u << i); 1254 } 1255 } 1256 var offsets: array<u32, {KEYS_PER_THREAD}>; 1257 for (var i = 0u; i < KEYS_PER_THREAD; i = i + 1u) { 1258 let k = keys[i]; 1259 let isValid = ((validMask >> i) & 1u) == 1u; 1260 let digit = (k >> currentBit) & RADIX_MASK; 1261 var waveFlag: u32 = activeMask; 1262 for (var b = 0u; b < 8u; b = b + 1u) { 1263 let t = ((digit >> b) & 1u) == 1u; 1264 let ballot = subgroupBallot(t).x; 1265 waveFlag = waveFlag & select(~ballot, ballot, t); 1266 } 1267 let validBallot = subgroupBallot(isValid).x; 1268 waveFlag = waveFlag & validBallot; 1269 let peerBits = countOneBits(waveFlag & ltMask); 1270 let totalBits = countOneBits(waveFlag); 1271 let lowestRankPeer = firstTrailingBit(waveFlag); 1272 var preIncrementVal: u32 = 0u; 1273 if (isValid && peerBits == 0u) { 1274 preIncrementVal = atomicAdd(&g_d[waveIndex * RADIX + digit], totalBits); 1275 } 1276 offsets[i] = subgroupShuffle(preIncrementVal, lowestRankPeer) + peerBits; 1277 workgroupBarrier(); 1278 } 1279 var myHistRed: u32 = 0u; 1280 { 1281 var histReduction = atomicLoad(&g_d[TID]); 1282 for (var w = 1u; w < MAX_SUBGROUPS; w = w + 1u) { 1283 let idx = TID + w * RADIX; 1284 let cnt = atomicLoad(&g_d[idx]); 1285 histReduction = histReduction + cnt; 1286 atomicStore(&g_d[idx], histReduction - cnt); 1287 } 1288 myHistRed = histReduction; 1289 } 1290 if (partitionIndex + 1u < threadBlocks) { 1291 let dst = passHistOffset(threadBlocks, pass_, partitionIndex + 1u) + TID; 1292 atomicAdd(&b_passHist[dst], FLAG_REDUCTION | (myHistRed << 2u)); 1293 } 1294 let warpExcl = subgroupExclusiveAdd(myHistRed); 1295 let warpTotal = subgroupAdd(myHistRed); 1296 if (sgInvId == 0u) { 1297 sg_totals[waveIndex] = warpTotal; 1298 } 1299 workgroupBarrier(); 1300 if (TID == 0u) { 1301 var acc: u32 = 0u; 1302 for (var w = 0u; w < MAX_SUBGROUPS; w = w + 1u) { 1303 let t = sg_totals[w]; 1304 sg_totals[w] = acc; 1305 acc = acc + t; 1306 } 1307 } 1308 workgroupBarrier(); 1309 let myDigitBase = warpExcl + sg_totals[waveIndex]; 1310 var scatterPos: array<u32, {KEYS_PER_THREAD}>; 1311 for (var i = 0u; i < KEYS_PER_THREAD; i = i + 1u) { 1312 let k = keys[i]; 1313 let digit = (k >> currentBit) & RADIX_MASK; 1314 let warpBase = select(0u, atomicLoad(&g_d[waveIndex * RADIX + digit]), waveIndex > 0u); 1315 scatterPos[i] = offsets[i] + warpBase; 1316 } 1317 digit_base[TID] = myDigitBase; 1318 workgroupBarrier(); 1319 for (var i = 0u; i < KEYS_PER_THREAD; i = i + 1u) { 1320 let k = keys[i]; 1321 let digit = (k >> currentBit) & RADIX_MASK; 1322 scatterPos[i] = scatterPos[i] + digit_base[digit]; 1323 } 1324 workgroupBarrier(); 1325 if (TID < RADIX) { 1326 var lookbackReduction: u32 = 0u; 1327 var k: u32 = partitionIndex; 1328 var done: bool = false;
1329 loop { 1330 if (done) { break; } 1331 let flagPayload = atomicLoad(&b_passHist[passHistOffset(threadBlocks, pass_, k) + TID]); 1332 let flag = flagPayload & FLAG_MASK; 1333 if (flag == FLAG_INCLUSIVE) { 1334 lookbackReduction = lookbackReduction + (flagPayload >> 2u); 1335 if (partitionIndex + 1u < threadBlocks) { 1336 let dst = passHistOffset(threadBlocks, pass_, partitionIndex + 1u) + TID; 1337 atomicAdd(&b_passHist[dst], 1u | (lookbackReduction << 2u)); 1338 } 1339 digit_base[TID] = lookbackReduction - myDigitBase; 1340 done = true; 1341 } else if (flag == FLAG_REDUCTION) { 1342 lookbackReduction = lookbackReduction + (flagPayload >> 2u); 1343 if (k == 0u) { done = true; } 1344 else { k = k - 1u; } 1345 } 1346 } 1347 } 1348 for (var i = 0u; i < KEYS_PER_THREAD; i = i + 1u) { 1349 if (((validMask >> i) & 1u) == 1u) { 1350 atomicStore(&g_d[scatterPos[i]], keys[i]); 1351 } 1352 } 1353 workgroupBarrier(); 1354 var linearDigits: array<u32, {KEYS_PER_THREAD}>; 1355 for (var r = 0u; r < KEYS_PER_THREAD; r = r + 1u) { 1356 let linearIdx = TID + r * D_DIM; 1357 if (linearIdx < validInBlock) { 1358 let k = atomicLoad(&g_d[linearIdx]); 1359 let digit = (k >> currentBit) & RADIX_MASK; 1360 linearDigits[r] = digit; 1361 let globalPos = digit_base[digit] + linearIdx; 1362 if (!isLastPass) { 1363 outputKeys[globalPos] = k; 1364 } 1365 } 1366 } 1367 workgroupBarrier(); 1368 for (var i = 0u; i < KEYS_PER_THREAD; i = i + 1u) { 1369 if (((validMask >> i) & 1u) == 1u) { 1370 atomicStore(&g_d[scatterPos[i]], values[i]); 1371 } 1372 } 1373 workgroupBarrier(); 1374 for (var r = 0u; r < KEYS_PER_THREAD; r = r + 1u) { 1375 let linearIdx = TID + r * D_DIM; 1376 if (linearIdx < validInBlock) { 1377 let v = atomicLoad(&g_d[linearIdx]); 1378 let digit = linearDigits[r]; 1379 let globalPos = digit_base[digit] + linearIdx; 1380 outputValues[globalPos] = v; 1381 } 1382 } 1383} 1384`,_w=256,gw=15,Xh=_w*gw,LM=128,Vp=32768,Yh=256,_l=4;class FM extends dw{_threadBlocks=0;_allocatedThreadBlocks=0;_globalHist=null;_passHist=null;_index=null;
1384_binningDispatchSize=new j(1,1);_globalHistDispatchSize=new j(1,1);_globalHistBindGroupFormat=null;_scanBindGroupFormat=null;_binningBindGroupFormat=null;_globalHistUniformFormat=null;_scanUniformFormat=null;_binningUniformFormat=null;_globalHistShader=null;_scanShader=null;_binningShader=null;_globalHistCompute=null;_scanCompute=null;_binningComputes=[];constructor(e,t=!1){super(e,t);const s=this._indirectInfo;s[0]=2,s[1]=Xh,s[2]=Vp,this._globalHistUniformFormat=new vt(e,[new X("numKeys",le),new X("threadBlocks",le),new X("numPasses",le),new X("_pad",le)]),this._scanUniformFormat=new vt(e,[new X("threadBlocks",le),new X("_pad0",le),new X("_pad1",le),new X("_pad2",le)]),this._binningUniformFormat=new vt(e,[new X("numKeys",le),new X("threadBlocks",le),new X("pass_",le),new X("flags",le)]);const i=e.minSubgroupSize||e.maxSubgroupSize||32,r=Math.max(1,Math.ceil(256/i)),a=t?"Indirect":"",n=[new q("b_sort",G,!0),new q("b_globalHist",G,!1),new At("uniforms",G)],o=[new q("b_globalHist",G,!0),new q("b_passHist",G,!1),new At("uniforms",G)],c=[new q("inputKeys",G,!0),new q("outputKeys",G,!1),new q("inputValues",G,!0),new q("outputValues",G,!1),new q("b_passHist",G,!1),new q("b_index",G,!1),new At("uniforms",G)];t&&(n.push(new q("b_sortElementCount",G,!0)),o.push(new q("b_sortElementCount",G,!0)),c.push(new q("b_sortElementCount",G,!0))),this._globalHistBindGroupFormat=new Ze(e,n),this._scanBindGroupFormat=new Ze(e,o),this._binningBindGroupFormat=new Ze(e,c);const h=new Map;h.set("{G_HIST_DIM}",LM),h.set("{G_HIST_PART_SIZE}",Vp),t&&h.set("USE_INDIRECT_SORT",""),this._globalHistShader=new tt(e,{name:`OneSweepGlobalHist${a}`,shaderLanguage:de,cshader:DM,cdefines:h,computeBindGroupFormat:this._globalHistBindGroupFormat,computeUniformBufferFormats:{uniforms:this._globalHistUniformFormat}});const d=new Map;d.set("{MAX_SUBGROUPS}",r),d.set("{PART_SIZE}",Xh),t&&d.set("USE_INDIRECT_SORT",""),this._scanShader=new tt(e,{name:`OneSweepScan${a}`,shaderLanguage:de,cshader:MM,cdefines:d,computeBindGroupFormat:this._scanBindGroupFormat,computeUniformBufferFormats:{uniforms:this._scanUniformFormat}});const u=new Map;u.set("{D_DIM}",_w),u.set("{KEYS_PER_THREAD}",gw),u.set("{MAX_SUBGROUPS}",r),t&&u.set("USE_INDIRECT_SORT",""),this._binningShader=new tt(e,{name:`OneSweepBinning${a}`,shaderLanguage:de,cshader:RM,cdefines:u,computeBindGroupFormat:this._binningBindGroupFormat,computeUniformBufferFormats:{uniforms:this._binningUniformFormat}}),this._globalHistCompute=new Qe(e,this._globalHistShader,this._globalHistShader.name),this._scanCompute=new Qe(e,this._scanShader,this._scanShader.name)}destroy(){this._destroyBuffers(),this._globalHistShader?.destroy(),this._scanShader?.destroy(),this._binningShader?.destroy(),this._globalHistBindGroupFormat?.destroy(),this._scanBindGroupFormat?.destroy(),this._binningBindGroupFormat?.destroy(),this._globalHistShader=null,this._scanShader=null,this._binningShader=null,this._globalHistCompute=null,this._scanCompute=null,this._binningComputes.length=0,this._globalHistBindGroupFormat=null,this._scanBindGroupFormat=null,this._binningBindGroupFormat=null,this._globalHistUniformFormat=null,this._scanUniformFormat=null,this._binningUniformFormat=null,super.destroy()}_destroyBuffers(){this._destroyPingPongBuffers(),this._globalHist?.destroy(),this._passHist?.destroy(),this._index?.destroy(),this._globalHist=null,this._passHist=null,this._index=null,this._allocatedThreadBlocks=0,this._threadBlocks=0}get radixBits(){return 8}_ensureBinningComputes(e){for(;this._binningComputes.length<e;)this._binningComputes.push(new Qe(this.device,this._binningShader,`OneSweepBinning-${this._binningComputes.length}`))}_allocateBuffers(e,t=!1){const s=Math.max(e,this.capacity),i=Math.max(1,Math.ceil(s/Xh)),r=Math.max(1,Math.ceil(e/Xh));if(t||i!==this._allocatedThreadBlocks||!this._keys0){this._destroyBuffers(),this._allocatedThreadBlocks=i,this.capacity=s;const c=this.device;this._allocatePingPongElementBuffers(s),this._globalHist=new Se(c,_l*Yh*4,ct),this._passHist=new Se(c,_l*i*Yh*4,ct),this._index=new Se(c,_l*4,ct)}this._threadBlocks=r;const n=this.device.limits.maxComputeWorkgroupsPerDimension||65535;
1384Qe.calcDispatchSize(r,this._binningDispatchSize,n);const o=Math.max(1,Math.ceil(e/Vp));Qe.calcDispatchSize(o,this._globalHistDispatchSize,n)}sort(e,t,s=16,i,r=!1,a=!1){const n=s/8,o=!!i;this._elementCount=t,this._numBits=s,this._hasInitialValues=o,this._skipLastPassKeyWrite=r;const c=this._destructiveKeys;this._destructiveKeys=a,this._allocateBuffers(t,a!==c),this._ensureBinningComputes(n),a&&(this._keys1=e);const h=this.device;this._globalHist.clear(),this._passHist.clear(0,_l*this._threadBlocks*Yh*4),this._index.clear();const d=this._globalHistCompute;d.setParameter("b_sort",e),d.setParameter("b_globalHist",this._globalHist),d.setParameter("numKeys",t),d.setParameter("threadBlocks",this._threadBlocks),d.setParameter("numPasses",n),d.setParameter("_pad",0),d.setupDispatch(this._globalHistDispatchSize.x,this._globalHistDispatchSize.y,1),h.computeDispatch([d],"OneSweep-GlobalHist");const u=this._scanCompute;u.setParameter("b_globalHist",this._globalHist),u.setParameter("b_passHist",this._passHist),u.setParameter("threadBlocks",this._threadBlocks),u.setParameter("_pad0",0),u.setParameter("_pad1",0),u.setParameter("_pad2",0),u.setupDispatch(n,1,1),h.computeDispatch([u],"OneSweep-Scan");let f=e,p=i??this._values0,m=this._keys0,_=this._values1;for(let g=0;g<n;g++){const v=g===0&&!o,x=g===n-1,y=(v?1:0)|(x&&r?2:0),S=this._binningComputes[g];if(S.setParameter("inputKeys",f),S.setParameter("outputKeys",m),S.setParameter("inputValues",p),S.setParameter("outputValues",_),S.setParameter("b_passHist",this._passHist),S.setParameter("b_index",this._index),S.setParameter("numKeys",t),S.setParameter("threadBlocks",this._threadBlocks),S.setParameter("pass_",g),S.setParameter("flags",y),S.setupDispatch(this._binningDispatchSize.x,this._binningDispatchSize.y,1),h.computeDispatch([S],`OneSweep-Binning-${g}`),!x){f=m,m=f===this._keys0?this._keys1:this._keys0;const T=p;p=_,_=T}}return this.sortedIndices}sortIndirect(e,t,s,i,r,a,n=!1,o=!1){const c=s/8,h=!!a;this._elementCount=t,this._numBits=s,this._hasInitialValues=h,this._skipLastPassKeyWrite=n;const d=this._destructiveKeys;this._destructiveKeys=o,this._allocateBuffers(t,o!==d),this._ensureBinningComputes(c),o&&(this._keys1=e);const u=this.device;this._globalHist.clear(),this._passHist.clear(0,_l*this._allocatedThreadBlocks*Yh*4),this._index.clear();const f=this._globalHistCompute;f.setParameter("b_sort",e),f.setParameter("b_globalHist",this._globalHist),f.setParameter("b_sortElementCount",r),f.setParameter("numKeys",0),f.setParameter("threadBlocks",0),f.setParameter("numPasses",c),f.setParameter("_pad",0),f.setupIndirectDispatch(i+1),u.computeDispatch([f],"OneSweep-GlobalHistIndirect");const p=this._scanCompute;p.setParameter("b_globalHist",this._globalHist),p.setParameter("b_passHist",this._passHist),p.setParameter("b_sortElementCount",r),p.setParameter("threadBlocks",0),p.setParameter("_pad0",0),p.setParameter("_pad1",0),p.setParameter("_pad2",0),p.setupDispatch(c,1,1),u.computeDispatch([p],"OneSweep-ScanIndirect");let m=e,_=a??this._values0,g=this._keys0,v=this._values1;for(let x=0;x<c;x++){const y=x===0&&!h,S=x===c-1,T=(y?1:0)|(S&&n?2:0),w=this._binningComputes[x];if(w.setParameter("inputKeys",m),w.setParameter("outputKeys",g),w.setParameter("inputValues",_),w.setParameter("outputValues",v),w.setParameter("b_passHist",this._passHist),w.setParameter("b_index",this._index),w.setParameter("b_sortElementCount",r),w.setParameter("numKeys",0),w.setParameter("threadBlocks",0),w.setParameter("pass_",x),w.setParameter("flags",T),w.setupIndirectDispatch(i),u.computeDispatch([w],`OneSweep-BinningIndirect-${x}`),!S){m=g,g=m===this._keys0?this._keys1:this._keys0;const C=_;_=v,v=C}}return this.sortedIndices}}class OM{_impl;constructor(e,t={}){const s=t.kind??fS,i=t.indirect??!1;let r=s;s===fS&&(r=this._canUseOneSweep(e)?pS:jI),r===pS?(this._canUseOneSweep(e),this._impl=new FM(e,i)):this._impl=new IM(e,i)}_canUseOneSweep(e){return!(!e.supportsCompute||!e.supportsSubgroups||e.gpuAdapter?.info?.vendor?.toLowerCase?.()!=="nvidia"||e.minSubgroupSize>32)}get sortedIndices(){return this._impl.sortedIndices}get sortedKeys(){return this._impl.sortedKeys}get radixBits(){return this._impl.radixBits}set capacity(e){this._impl.capacity=e}get capacity(){return this._impl.capacity}sort(e,t,s=16,i,r,a=!1){return this._impl.sort(e,t,s,i,r,a)}sortIndirect(e,t,s,i,r,a,n,o=!1){return this._impl.sortIndirect(e,t,s,i,r,a,n,o)}prepareIndirect(){return this._impl.prepareIndirect()}destroy(){this._impl.destroy()}}class vw{hasTangents=!1;shaderChunks=null;pass=0;alphaTest=!1;blendType=Ns;separateAmbient=!1;screenSpace=!1;skin=!1;batch=!1;useInstancing=!1;useMorphPosition=!1;useMorphNormal=!1;useMorphTextureBasedInt=!1;nineSlicedMode=0;clusteredLightingEnabled=!0;clusteredLightingCookiesEnabled=!1;clusteredLightingShadowsEnabled=!1;clusteredLightingShadowType=0;clusteredLightingAreaLightsEnabled=!1;vertexColors=!1;useVertexColorGamma=!1;lightMapEnabled=!1;dirLightMapEnabled=!1;useHeights=!1;useNormals=!1;useClearCoatNormals=!1;useAo=!1;diffuseMapEnabled=!1;pixelSnap=!1;ambientSH=!1;ssao=!1;
1384twoSidedLighting=!1;occludeDirect=!1;occludeSpecular=0;occludeSpecularFloat=!1;useMsdf=!1;msdfTextAttribute=!1;alphaToCoverage=!1;opacityFadesSpecular=!1;opacityDither=on;opacityShadowDither=on;cubeMapProjection=0;useSpecular=!1;useSpecularityFactor=!1;enableGGXSpecular=!1;fresnelModel=0;useRefraction=!1;useClearCoat=!1;useSheen=!1;useIridescence=!1;useMetalness=!1;useDynamicRefraction=!1;dispersion=!1;fog=vn;gamma=qc;toneMap=-1;reflectionSource=Jr;reflectionEncoding=null;reflectionCubemapEncoding=null;ambientSource="constant";ambientEncoding=null;skyboxIntensity=1;useCubeMapRotation=!1;lightMapWithoutAmbient=!1;lights=[];noShadow=!1;lightMaskDynamic=0;userAttributes={};linearDepth=!1;shadowCatcher=!1}class ui{static update(e,t,s,i,r,a,n){ui.updateSharedOptions(e,t,s,r,a),ui.updateMaterialOptions(e,t),ui.updateEnvOptions(e,t,s,i),ui.updateLightingOptions(e,t,s,r,n)}static updateSharedOptions(e,t,s,i,r){e.shaderChunks=t.shaderChunks,e.pass=r,e.alphaTest=t.alphaTest>0,e.blendType=t.blendType,e.screenSpace=i&&(i&cu)!==0,e.skin=i&&(i&fc)!==0,e.useInstancing=i&&(i&pc)!==0,e.useMorphPosition=i&&(i&mc)!==0,e.useMorphNormal=i&&(i&_c)!==0,e.useMorphTextureBasedInt=i&&(i&gc)!==0,e.hasTangents=i&&(i&Ng)!==0,e.nineSlicedMode=t.nineSlicedMode||Fi,t.useLighting&&s.clusteredLightingEnabled?(e.clusteredLightingEnabled=!0,e.clusteredLightingCookiesEnabled=s.lighting.cookiesEnabled,e.clusteredLightingShadowsEnabled=s.lighting.shadowsEnabled,e.clusteredLightingShadowType=s.lighting.shadowType,e.clusteredLightingAreaLightsEnabled=s.lighting.areaLightsEnabled):(e.clusteredLightingEnabled=!1,e.clusteredLightingCookiesEnabled=!1,e.clusteredLightingShadowsEnabled=!1,e.clusteredLightingAreaLightsEnabled=!1)}static updateMaterialOptions(e,t){e.separateAmbient=!1,e.pixelSnap=t.pixelSnap,e.ambientSH=t.ambientSH,e.twoSidedLighting=t.twoSidedLighting,e.occludeDirect=t.occludeDirect,e.occludeSpecular=t.occludeSpecular,e.occludeSpecularFloat=t.occludeSpecularIntensity!==1,e.useMsdf=!1,e.msdfTextAttribute=!1,e.alphaToCoverage=t.alphaToCoverage,e.opacityFadesSpecular=t.opacityFadesSpecular,e.opacityDither=t.opacityDither,e.cubeMapProjection=Mg,e.useSpecular=t.hasSpecular,e.useSpecularityFactor=t.hasSpecularityFactor,e.enableGGXSpecular=t.ggxSpecular,e.useAnisotropy=!1,e.fresnelModel=t.fresnelModel,e.useRefraction=t.hasRefraction,e.useClearCoat=t.hasClearCoat,e.useSheen=t.hasSheen,e.useIridescence=t.hasIrridescence,e.useMetalness=t.hasMetalness,e.useDynamicRefraction=t.dynamicRefraction,e.dispersion=t.dispersion>0,e.vertexColors=!1,e.lightMapEnabled=t.hasLighting,e.dirLightMapEnabled=t.dirLightMap,e.useHeights=t.hasHeights,e.useNormals=t.hasNormals,e.useClearCoatNormals=t.hasClearCoatNormals,e.useAo=t.hasAo,e.diffuseMapEnabled=t.hasDiffuseMap}static updateEnvOptions(e,t,s,i){e.fog=t.useFog?i.fog:vn,e.gamma=i.shaderOutputGamma,e.toneMap=t.useTonemap?i.toneMapping:Rg,t.useSkybox&&s.envAtlas&&s.skybox?(e.reflectionSource=nu,e.reflectionEncoding=s.envAtlas.encoding,e.reflectionCubemapEncoding=s.skybox.encoding):t.useSkybox&&s.envAtlas?(e.reflectionSource=au,e.reflectionEncoding=s.envAtlas.encoding):t.useSkybox&&s.skybox?(e.reflectionSource=ou,e.reflectionEncoding=s.skybox.encoding):(e.reflectionSource=Jr,e.reflectionEncoding=null),t.ambientSH?(e.ambientSource=Lg,e.ambientEncoding=null):e.reflectionSource!==Jr&&s.envAtlas?(e.ambientSource=Fg,e.ambientEncoding=s.envAtlas.encoding):(e.ambientSource=Og,e.ambientEncoding=null);const r=e.reflectionSource!==Jr;e.skyboxIntensity=r,e.useCubeMapRotation=r&&s._skyboxRotationShaderInclude}static updateLightingOptions(e,t,s,i,r){if(e.lightMapWithoutAmbient=!1,t.useLighting){const a=[],n=i?i>>16:Js;e.lightMaskDynamic=!!(n&Js),e.lightMapWithoutAmbient=!1,r&&(ui.collectLights(Te,r[Te],a,n),s.clusteredLightingEnabled||(ui.collectLights(ot,r[ot],a,n),ui.collectLights(nt,r[nt],a,n))),e.lights=a}else e.lights=[];(e.lights.length===0&&!s.clusteredLightingEnabled||(i&lu)!==0)&&(e.noShadow=!0)}static collectLights(e,t,s,i){for(let r=0;r<t.length;r++){const a=t[r];a.enabled&&a.mask&i&&s.push(a)}}}const Gp={vertex_normal:Cs,vertex_tangent:Gi,vertex_texCoord0:Zs,vertex_texCoord1:pn,vertex_color:ns,vertex_boneWeights:ki,vertex_boneIndices:Bs};class BM{varyingsCode="";device;options;shaderLanguage;vDefines=new Map;fDefines=new Map;includes=new Map;chunks=null;constructor(e,t,s=!0){this.device=e,this.options=t;const i=t.shaderChunks;if(this.shaderLanguage=e.isWebGPU&&s&&(!i||i.useWGSL)?de:ze,e.isWebGPU&&this.shaderLanguage===ze&&e.hasTranspilers,this.attributes={vertex_position:Ie},t.userAttributes)for(const[a,n]of Object.entries(t.userAttributes))this.attributes[n]=a;const r=be.get(e,this.shaderLanguage);this.chunks=new Map(r),i&&(this.shaderLanguage===ze?i.glsl:i.wgsl).forEach((n,o)=>{for(const c in Gp)Gp.hasOwnProperty(c)&&n.indexOf(c)>=0&&(this.attributes[c]=Gp[c]);this.chunks.set(o,n)}),this.shaderPassInfo=zi.get(this.device).getByIndex(t.pass),this.shadowPass=this.shaderPassInfo.isShadow,this.lighting=t.lights.length>0||t.dirLightMapEnabled||t.clusteredLightingEnabled,this.reflections=t.reflectionSource!==Jr,this.needsNormal=this.lighting||this.reflections||t.useSpecular||t.ambientSH||t.useHeights||t.enableGGXSpecular||t.clusteredLightingEnabled&&!this.shadowPass||t.useClearCoatNormals,this.needsNormal=this.needsNormal&&!this.shadowPass,this.needsSceneColor=t.useDynamicRefraction,this.needsScreenSize=t.useDynamicRefraction,this.needsTransforms=t.useDynamicRefraction,this.vshader=null,this.fshader=null}fDefineSet(e,t,s=""){e&&this.fDefines.set(t,s)}generateVertexShader(e,t,s){const{options:i,vDefines:r,attributes:a}=this,n=new Map;if(n.set("vPositionW","vec3"),(i.nineSlicedMode===kt||i.nineSlicedMode===Ut)&&r.set("NINESLICED",!0),this.options.linearDepth&&(r.set("LINEAR_DEPTH",!0),n.set("vLinearDepth","float")),this.needsNormal&&r.set("NORMALS",!0),this.options.useInstancing){const d=be.get(this.device,this.shaderLanguage);this.chunks.get("transformInstancingVS")===d.get("transformInstancingVS")&&(a.instance_line1=dg,a.instance_line2=ug,a.instance_line3=fg,a.instance_line4=Io)}this.needsNormal&&(a.vertex_normal=Cs,n.set("vNormalW","vec3"),i.hasTangents&&(i.useHeights||i.useNormals||i.useClearCoatNormals||i.enableGGXSpecular)?(r.set("TANGENTS",!0),a.vertex_tangent=Gi,n.set("vTangentW","vec3"),n.set("vBinormalW","vec3")):i.enableGGXSpecular&&(r.set("GGX_SPECULAR",!0),n.set("vObjectSpaceUpW","vec3")));const o=2;for(let d=0;d<o;d++)e[d]&&(r.set(`UV${d}`,!0),a[`vertex_texCoord${d}`]=`TEXCOORD${d}`),t[d]&&(r.set(`UV${d}_UNMODIFIED`,!0),n.set(`vUv${d}`,"vec2"));let c=0;const h=new Set;
1384s.forEach(d=>{const{id:u,uv:f,name:p}=d,m=u+f*100;if(!h.has(m)){h.add(m),n.set(`vUV${f}_${u}`,"vec2");const _=`texture_${p}MapTransform`;r.set(`{TRANSFORM_NAME_${c}}`,_),r.set(`{TRANSFORM_UV_${c}}`,f),r.set(`{TRANSFORM_ID_${c}}`,u),c++}}),r.set("UV_TRANSFORMS_COUNT",c),i.vertexColors&&(a.vertex_color=ns,r.set("VERTEX_COLOR",!0),n.set("vVertexColor","vec4"),i.useVertexColorGamma&&r.set("STD_VERTEX_COLOR_GAMMA","")),i.useMsdf&&i.msdfTextAttribute&&(a.vertex_outlineParameters=ic,a.vertex_shadowParameters=rc,r.set("MSDF",!0)),(i.useMorphPosition||i.useMorphNormal)&&(r.set("MORPHING",!0),i.useMorphTextureBasedInt&&r.set("MORPHING_INT",!0),i.useMorphPosition&&r.set("MORPHING_POSITION",!0),i.useMorphNormal&&r.set("MORPHING_NORMAL",!0),a.morph_vertex_id=Io),i.skin&&(a.vertex_boneIndices=Bs,i.batch?r.set("BATCH",!0):(a.vertex_boneWeights=ki,r.set("SKIN",!0))),i.useInstancing&&r.set("INSTANCING",!0),i.screenSpace&&r.set("SCREENSPACE",!0),i.pixelSnap&&r.set("PIXELSNAP",!0),n.forEach((d,u)=>{this.varyingsCode+=`#define VARYING_${u.toUpperCase()} 1385`,this.varyingsCode+=this.shaderLanguage===de?`varying ${u}: ${Zx.get(d)}; 1386`:`varying ${d} ${u}; 1387`}),this.includes.set("varyingsVS",this.varyingsCode),this.includes.set("varyingsPS",this.varyingsCode),this.vshader=` 1388 #include "litMainVS" 1389 `}_setupLightingDefines(e,t){const s=this.fDefines,i=this.options;if(this.fDefines.set("LIGHT_COUNT",i.lights.length),e&&s.set("AREA_LIGHTS",!0),t&&this.lighting&&(s.set("LIT_CLUSTERED_LIGHTS",!0),i.clusteredLightingCookiesEnabled&&s.set("CLUSTER_COOKIES",!0),i.clusteredLightingAreaLightsEnabled&&s.set("CLUSTER_AREALIGHTS",!0),i.lightMaskDynamic&&s.set("CLUSTER_MESH_DYNAMIC_LIGHTS",!0),i.clusteredLightingShadowsEnabled&&!i.noShadow)){const r=yr.get(i.clusteredLightingShadowType);s.set("CLUSTER_SHADOWS",!0),s.set(`SHADOW_KIND_${r.kind}`,!0),s.set(`CLUSTER_SHADOW_TYPE_${r.kind}`,!0)}for(let r=0;r<i.lights.length;r++){const a=i.lights[r],n=a._type;if(t&&n!==Te)continue;const o=e&&a._shape?a._shape:Sr,c=a._shadowType,h=a.castShadows&&!i.noShadow,d=yr.get(c);s.set(`LIGHT${r}`,!0),s.set(`LIGHT${r}TYPE`,`${oS[n]}`),s.set(`LIGHT${r}SHADOWTYPE`,`${d.name}`),s.set(`LIGHT${r}SHAPE`,`${pI[o]}`),s.set(`LIGHT${r}FALLOFF`,`${mI[a._falloffMode]}`),a.affectSpecularity&&s.set(`LIGHT${r}AFFECT_SPECULARITY`,!0),a._cookie&&(n===nt&&!a._cookie._cubemap||n===ot&&a._cookie._cubemap)&&(s.set(`LIGHT${r}COOKIE`,!0),s.set(`{LIGHT${r}COOKIE_CHANNEL}`,a._cookieChannel),n===nt&&(a._cookieTransform&&s.set(`LIGHT${r}COOKIE_TRANSFORM`,!0),a._cookieFalloff&&s.set(`LIGHT${r}COOKIE_FALLOFF`,!0))),h&&(s.set(`LIGHT${r}CASTSHADOW`,!0),d.pcf&&s.set(`LIGHT${r}SHADOW_PCF`,!0),a._normalOffsetBias&&!a._isVsm&&s.set(`LIGHT${r}_SHADOW_SAMPLE_NORMAL_OFFSET`,!0),n===Te&&(s.set(`LIGHT${r}_SHADOW_SAMPLE_ORTHO`,!0),a.cascadeBlend>0&&s.set(`LIGHT${r}_SHADOW_CASCADE_BLEND`,!0),a.numCascades>1&&s.set(`LIGHT${r}_SHADOW_CASCADES`,!0)),(d.pcf||d.pcss||this.device.isWebGPU)&&s.set(`LIGHT${r}_SHADOW_SAMPLE_SOURCE_ZBUFFER`,!0),n===ot&&s.set(`LIGHT${r}_SHADOW_SAMPLE_POINT`,!0)),h&&(s.set(`SHADOW_KIND_${d.kind}`,!0),n===Te&&s.set("SHADOW_DIRECTIONAL",!0))}}prepareForwardPass(e){const{options:t}=this,i=t.clusteredLightingEnabled&&t.clusteredLightingAreaLightsEnabled||t.lights.some(n=>n._shape&&n._shape!==Sr),r=!t.lightMapEnabled||t.lightMapWithoutAmbient,a=this.needsNormal&&(t.useNormals||t.useClearCoatNormals||t.enableGGXSpecular&&!t.useHeights);t.useSpecular&&(this.fDefineSet(!0,"LIT_SPECULAR"),this.fDefineSet(this.reflections,"LIT_REFLECTIONS"),this.fDefineSet(t.useClearCoat,"LIT_CLEARCOAT"),this.fDefineSet(t.fresnelModel>0,"LIT_SPECULAR_FRESNEL"),this.fDefineSet(t.useSheen,"LIT_SHEEN"),this.fDefineSet(t.useIridescence,"LIT_IRIDESCENCE")),this.fDefineSet(this.lighting&&t.useSpecular||this.reflections,"LIT_SPECULAR_OR_REFLECTION"),this.fDefineSet(this.needsSceneColor,"LIT_SCENE_COLOR"),this.fDefineSet(this.needsScreenSize,"LIT_SCREEN_SIZE"),this.fDefineSet(this.needsTransforms,"LIT_TRANSFORMS"),this.fDefineSet(this.needsNormal,"LIT_NEEDS_NORMAL"),this.fDefineSet(this.lighting,"LIT_LIGHTING"),this.fDefineSet(t.useMetalness,"LIT_METALNESS"),this.fDefineSet(t.enableGGXSpecular,"LIT_GGX_SPECULAR"),this.fDefineSet(t.useAnisotropy,"LIT_ANISOTROPY"),this.fDefineSet(t.useSpecularityFactor,"LIT_SPECULARITY_FACTOR"),this.fDefineSet(t.useCubeMapRotation,"CUBEMAP_ROTATION"),this.fDefineSet(t.occludeSpecularFloat,"LIT_OCCLUDE_SPECULAR_FLOAT"),this.fDefineSet(t.separateAmbient,"LIT_SEPARATE_AMBIENT"),this.fDefineSet(t.twoSidedLighting,"LIT_TWO_SIDED_LIGHTING"),this.fDefineSet(t.lightMapEnabled,"LIT_LIGHTMAP"),this.fDefineSet(t.dirLightMapEnabled,"LIT_DIR_LIGHTMAP"),this.fDefineSet(t.skyboxIntensity>0,"LIT_SKYBOX_INTENSITY"),this.fDefineSet(t.clusteredLightingShadowsEnabled,"LIT_CLUSTERED_SHADOWS"),this.fDefineSet(t.clusteredLightingAreaLightsEnabled,"LIT_CLUSTERED_AREA_LIGHTS"),this.fDefineSet(a,"LIT_TBN"),this.fDefineSet(r,"LIT_ADD_AMBIENT"),this.fDefineSet(t.hasTangents,"LIT_TANGENTS"),this.fDefineSet(t.useNormals,"LIT_USE_NORMALS"),this.fDefineSet(t.useClearCoatNormals,"LIT_USE_CLEARCOAT_NORMALS"),this.fDefineSet(t.useRefraction,"LIT_REFRACTION"),this.fDefineSet(t.useDynamicRefraction,"LIT_DYNAMIC_REFRACTION"),this.fDefineSet(t.dispersion,"LIT_DISPERSION"),this.fDefineSet(t.useHeights,"LIT_HEIGHTS"),this.fDefineSet(t.opacityFadesSpecular,"LIT_OPACITY_FADES_SPECULAR"),this.fDefineSet(t.alphaToCoverage,"LIT_ALPHA_TO_COVERAGE"),this.fDefineSet(t.alphaTest,"LIT_ALPHA_TEST"),this.fDefineSet(t.useMsdf,"LIT_MSDF"),this.fDefineSet(t.ssao,"LIT_SSAO"),this.fDefineSet(t.useAo,"LIT_AO"),this.fDefineSet(t.occludeDirect,"LIT_OCCLUDE_DIRECT"),this.fDefineSet(t.msdfTextAttribute,"LIT_MSDF_TEXT_ATTRIBUTE"),this.fDefineSet(t.diffuseMapEnabled,"LIT_DIFFUSE_MAP"),this.fDefineSet(t.shadowCatcher,"LIT_SHADOW_CATCHER"),this.fDefineSet(!0,"LIT_FRESNEL_MODEL",uI[t.fresnelModel]),this.fDefineSet(!0,"LIT_NONE_SLICE_MODE",DI[t.nineSlicedMode]),this.fDefineSet(!0,"LIT_BLEND_TYPE",uT[t.blendType]),this.fDefineSet(!0,"LIT_CUBEMAP_PROJECTION",xI[t.cubeMapProjection]),this.fDefineSet(!0,"LIT_OCCLUDE_SPECULAR",bI[t.occludeSpecular]),this.fDefineSet(!0,"LIT_REFLECTION_SOURCE",AI[t.reflectionSource]),this.fDefineSet(!0,"LIT_AMBIENT_SOURCE",PI[t.ambientSource]),this.fDefineSet(!0,"{lightingUv}",e??""),this.fDefineSet(!0,"{reflectionDecode}",ta.decodeFunc(t.reflectionEncoding)),this.fDefineSet(!0,"{reflectionCubemapDecode}",ta.decodeFunc(t.reflectionCubemapEncoding)),this.fDefineSet(!0,"{ambientDecode}",ta.decodeFunc(t.ambientEncoding)),this._setupLightingDefines(i,t.clusteredLightingEnabled)}preparePrepassPass(){const{options:e}=this;this.fDefineSet(e.alphaTest,"LIT_ALPHA_TEST"),this.fDefineSet(!0,"STD_OPACITY_DITHER",OT[e.opacitySh
1389adowDither])}prepareShadowPass(){const{options:e}=this,t=this.shaderPassInfo.lightType,s=this.shaderPassInfo.shadowType,i=yr.get(s),r=t===Te||!i.vsm&&t===nt;this.fDefineSet(r,"PERSPECTIVE_DEPTH"),this.fDefineSet(!0,"LIGHT_TYPE",`${oS[t]}`),this.fDefineSet(!0,"SHADOW_TYPE",`${i.name}`),this.fDefineSet(e.alphaTest,"LIT_ALPHA_TEST")}generateFragmentShader(e,t,s){const i=this.options;this.includes.set("frontendDeclPS",e??""),this.includes.set("frontendCodePS",t??""),i.pass===If||(i.pass===Pf?this.preparePrepassPass():this.shadowPass?this.prepareShadowPass():this.prepareForwardPass(s)),this.fshader=` 1390 #include "litMainPS" 1391 `}}const Sw={generateKey(l){return`lit${Object.keys(l).sort().map(e=>e==="shaderChunks"?l.shaderChunks?.key??"":e==="lights"?Sw.generateLightsKey(l):e+l[e]).join(` 1392`)}`},generateLightsKey(l){return`lights:${l.lights.map(e=>!l.clusteredLightingEnabled||e._type===Te?`${e.key},`:"").join("")}`}};class yc{defines=new Map;forceUv1=!1;specularTint=!1;metalnessTint=!1;glossTint=!1;emissiveEncoding="linear";lightMapEncoding="linear";vertexColorGamma=!1;packedNormal=!1;normalDetailPackedNormal=!1;clearCoatPackedNormal=!1;glossInvert=!1;sheenGlossInvert=!1;clearCoatGlossInvert=!1;useAO=!1;litOptions=new vw;get pass(){return this.litOptions.pass}}const wo=[],Hp=l=>Object.keys(l).filter(e=>e!=="litOptions").sort();class NM extends ln{optionsContext=new yc;optionsContextMin=new yc;generateKey(e){let t;return e===this.optionsContextMin?(this.propsMin||(this.propsMin=Hp(e)),t=this.propsMin):e===this.optionsContext?(this.props||(this.props=Hp(e)),t=this.props):t=Hp(e),`standard: 1393${ln.definesHash(e.defines)} 1394${t.map(r=>r+e[r]).join(` 1395`)}${Sw.generateKey(e.litOptions)}`}_getUvSourceExpression(e,t,s){const i=s[e],r=s[t],a=s.litOptions.pass===Ko;let n;return a&&s.litOptions.nineSlicedMode===kt||a&&s.litOptions.nineSlicedMode===Ut?n="nineSlicedUv":(i===0?n=`vUv${r}`:n=`vUV${r}_${i}`,s.heightMap&&e!=="heightMapTransform"&&(n+=" + dUvOffset")),n}_validateMapChunk(e,t,s,i){}_addMapDefines(e,t,s,i,r,a,n=null){const o=`${t}Map`,c=t.toUpperCase(),h=`${o}Uv`,d=`${o}Identifier`,u=`${o}Transform`,f=`${o}Channel`,p=`${t}VertexColorChannel`,m=`${t}Tint`,_=`${t}VertexColor`,g=`${t}Mode`,v=`${t}Invert`,x=i[m],y=i[_],S=i[o],T=i[d],w=i[g],C=r.get(s);if(S){e.set(`STD_${c}_TEXTURE`,"");const b=this._getUvSourceExpression(u,h,i);e.set(`{STD_${c}_TEXTURE_UV}`,b),e.set(`{STD_${c}_TEXTURE_CHANNEL}`,i[f]);const I=`{STD_${c}_TEXTURE_NAME}`;if(C.includes(I)){let P=`texture_${o}`;const L=a[T];L?P=L:(a[T]=P,e.set(`STD_${c}_TEXTURE_ALLOCATE`,"")),e.set(I,P)}if(n){const P=i[f]==="aaa"?"passThrough":ta.decodeFunc(n);e.set(`{STD_${c}_TEXTURE_DECODE}`,P)}}y&&(e.set(`STD_${c}_VERTEX`,""),e.set(`{STD_${c}_VERTEX_CHANNEL}`,i[p])),w&&e.set(`{STD_${c}_DETAILMODE}`,w),x&&e.set(`STD_${c}_CONSTANT`,""),i[v]&&e.set(`STD_${c}_INVERT`,"")}_correctChannel(e,t,s){if(s[e]>0){if(s[e]<t.length)return t.substring(0,s[e]);if(s[e]>t.length){let i=t;const r=i.charAt(i.length-1),a=s[e]-i.length;for(let n=0;n<a;n++)i+=r;return i}return t}}createVertexShader(e,t){const s=[],i=[],r=[];for(const n in wo){const o=`${n}Map`;if(t[`${n}VertexColor`]){const c=`${n}VertexColorChannel`;t[c]=this._correctChannel(n,t[c],wo)}if(t[o]){const c=`${o}Channel`,h=`${o}Transform`,d=`${o}Uv`;t[d]=Math.min(t[d],1),t[c]=this._correctChannel(n,t[c],wo);const u=t[d];s[u]=!0,i[u]=i[u]||t[o]&&!t[h],t[h]&&r.push({name:n,id:t[h],uv:t[d]})}}t.forceUv1&&(s[1]=!0,i[1]=i[1]!==void 0?i[1]:!0),e.generateVertexShader(s,i,r)}prepareFragmentDefines(e,t,s){const i=(r,a,n="")=>{r&&t.set(a,n)};i(e.lightMap,"STD_LIGHTMAP",""),i(e.lightVertexColor,"STD_LIGHT_VERTEX_COLOR",""),i(e.dirLightMap&&e.litOptions.useSpecular,"STD_LIGHTMAP_DIR",""),i(e.heightMap,"STD_HEIGHT_MAP",""),i(e.useSpecularColor,"STD_SPECULAR_COLOR",""),i(e.aoMap||e.aoVertexColor||e.useAO,"STD_AO",""),i(!0,"STD_OPACITY_DITHER",OT[s.isForward?e.litOptions.opacityDither:e.litOptions.opacityShadowDither])}createShaderDefinition(e,t){const s=zi.get(e).getByIndex(t.litOptions.pass),i=s.isForward,r=new BM(e,t.litOptions);this.createVertexShader(r,t);const a={};t.litOptions.fresnelModel=t.litOptions.fresnelModel===0?Ag:t.litOptions.fresnelModel;const n=r.fDefines;this.prepareFragmentDefines(t,n,s);let o="";if(i){if(t.heightMap&&this._addMapDefines(n,"height","parallaxPS",t,r.chunks,a),(t.litOptions.blendType!==Ns||t.litOptions.alphaTest||t.litOptions.alphaToCoverage||t.litOptions.opacityDither!==on)&&this._addMapDefines(n,"opacity","opacityPS",t,r.chunks,a),r.needsNormal){if((t.normalMap||t.clearCoatNormalMap)&&!t.litOptions.hasTangents){const u=t.
1395normalMap?"normalMap":"clearCoatNormalMap";o=this._getUvSourceExpression(`${u}Transform`,`${u}Uv`,t)}this._addMapDefines(n,"normalDetail","normalMapPS",t,r.chunks,a,t.normalDetailPackedNormal?"xy":"xyz"),this._addMapDefines(n,"normal","normalMapPS",t,r.chunks,a,t.packedNormal?"xy":"xyz")}t.diffuseDetail&&this._addMapDefines(n,"diffuseDetail","diffusePS",t,r.chunks,a,t.diffuseDetailEncoding),this._addMapDefines(n,"diffuse","diffusePS",t,r.chunks,a,t.diffuseEncoding),t.litOptions.useRefraction&&(this._addMapDefines(n,"refraction","transmissionPS",t,r.chunks,a),this._addMapDefines(n,"thickness","thicknessPS",t,r.chunks,a)),t.litOptions.useIridescence&&(this._addMapDefines(n,"iridescence","iridescencePS",t,r.chunks,a),this._addMapDefines(n,"iridescenceThickness","iridescenceThicknessPS",t,r.chunks,a)),(r.lighting&&t.litOptions.useSpecular||r.reflections)&&(t.litOptions.useSheen&&(this._addMapDefines(n,"sheen","sheenPS",t,r.chunks,a,t.sheenEncoding),this._addMapDefines(n,"sheenGloss","sheenGlossPS",t,r.chunks,a)),t.litOptions.useMetalness&&(this._addMapDefines(n,"metalness","metalnessPS",t,r.chunks,a),this._addMapDefines(n,"ior","iorPS",t,r.chunks,a)),t.litOptions.useSpecularityFactor&&this._addMapDefines(n,"specularityFactor","specularityFactorPS",t,r.chunks,a),t.useSpecularColor&&this._addMapDefines(n,"specular","specularPS",t,r.chunks,a,t.specularEncoding),this._addMapDefines(n,"gloss","glossPS",t,r.chunks,a)),t.aoDetail&&this._addMapDefines(n,"aoDetail","aoPS",t,r.chunks,a),(t.aoMap||t.aoVertexColor||t.useAO)&&this._addMapDefines(n,"ao","aoPS",t,r.chunks,a),this._addMapDefines(n,"emissive","emissivePS",t,r.chunks,a,t.emissiveEncoding),t.litOptions.useClearCoat&&(this._addMapDefines(n,"clearCoat","clearCoatPS",t,r.chunks,a),this._addMapDefines(n,"clearCoatGloss","clearCoatGlossPS",t,r.chunks,a),this._addMapDefines(n,"clearCoatNormal","clearCoatNormalPS",t,r.chunks,a,t.clearCoatPackedNormal?"xy":"xyz")),t.litOptions.enableGGXSpecular&&this._addMapDefines(n,"anisotropy","anisotropyPS",t,r.chunks,a),(t.lightMap||t.lightVertexColor)&&this._addMapDefines(n,"light","lightmapPS",t,r.chunks,a,t.lightMapEncoding)}else{const u=t.litOptions.opacityShadowDither;(t.litOptions.alphaTest||u)&&this._addMapDefines(n,"opacity","opacityPS",t,r.chunks,a)}r.generateFragmentShader(r.chunks.get("stdDeclarationPS"),r.chunks.get("stdFrontEndPS"),o);const c=du.merge(r.chunks,r.includes),h=r.vDefines;t.defines.forEach((u,f)=>h.set(f,u)),t.defines.forEach((u,f)=>n.set(f,u));const d=Ht.createDefinition(e,{name:"StandardShader",attributes:r.attributes,shaderLanguage:r.shaderLanguage,vertexCode:r.vshader,fragmentCode:r.fshader,vertexIncludes:c,fragmentIncludes:c,fragmentDefines:n,vertexDefines:h});return r.shaderPassInfo.isForward&&(d.tag=QE),d}}const Wp=new NM,gy=(l,e)=>{if(l.length!==e.length)return!1;for(let t=0;t<l.length;++t)if(l[t]!==e[t])return!1;return!0},kM=l=>l.r!==1||l.g!==1||l.b!==1,UM=l=>l.r!==0||l.g!==0||l.b!==0;class zM{constructor(){this._mapXForms=null}updateMinRef(e,t,s,i,r,a){this._updateSharedOptions(e,t,s,i,r),this._updateMinOptions(e,s,r),this._updateUVOptions(e,s,i,!0)}updateRef(e,t,s,i,r,a,n){this._updateSharedOptions(e,t,i,r,a),this._updateEnvOptions(e,i,t,s),this._updateMaterialOptions(e,i,t),e.litOptions.hasTangents=r&&(r&Ng)!==0,this._updateLightOptions(e,t,i,r,n),this._updateUVOptions(e,i,r,!1,s)}_updateSharedOptions(e,t,s,i,r){e.forceUv1=s.forceUv1,s.userAttributes&&(e.litOptions.userAttributes=Object.fromEntries(s.userAttributes.entries())),e.litOptions.shaderChunks=s.shaderChunks,e.litOptions.pass=r,e.litOptions.alphaTest=s.alphaTest>0,e.litOptions.blendType=s.blendType,e.litOptions.screenSpace=i&&(i&cu)!==0,e.litOptions.skin=i&&(i&fc)!==0,e.litOptions.batch=i&&(i&Ed)!==0,e.litOptions.useInstancing=i&&(i&pc)!==0,e.litOptions.useMorphPosition=i&&(i&mc)!==0,e.litOptions.useMorphNormal=i&&(i&_c)!==0,e.litOptions.useMorphTextureBasedInt=i&&(i&gc)!==0,e.litOptions.nineSlicedMode=s.nineSlicedMode||0,t.clusteredLightingEnabled&&s.useLighting?(e.litOptions.clusteredLightingEnabled=!0,e.litOptions.clusteredLightingCookiesEnabled=t.lighting.cookiesEnabled,e.litOptions.clusteredLightingShadowsEnabled=t.lighting.shadowsEnabled,e.litOptions.clusteredLightingShadowType=t.lighting.shadowType,e.litOptions.clusteredLightingAreaLightsEnabled=t.lighting.areaLightsEnabled):(e.litOptions.clusteredLightingEnabled=!1,e.litOptions.clusteredLightingCookiesEnabled=!1,e.litOptions.clusteredLightingShadowsEnabled=!1,e.litOptions.clusteredLightingAreaLightsEnabled=!1)}_updateUVOptions(e,t,s,i,r){let a=!1,n=!1,o=!1;s&&(a=(s&Bg)!==0,n=(s&IT)!==0,o=(s&DT)!==0),e.litOptions.vertexColors=!1,this._mapXForms=[];const c={};for(const h in wo)this._updateTexOptions(e,t,h,a,n,o,i,c);this._mapXForms=null,e.litOptions.ssao=r?.ssaoEnabled,e.useAO=e.litOptions.ssao,e.litOptions.lightMapEnabled=e.lightMap,e.litOptions.dirLightMapEnabled=e.dirLightMap,e.litOptions.useHeights=e.heightMap,e.litOptions.useNormals=e.normalMap,e.litOptions.useClearCoatNormals=e.clearCoatNormalMap,e.litOptions.useAo=e.aoMap||e.aoVertexColor||e.litOptions.ssao,e.litOptions.diffuseMapEnabled=e.diffuseMap}_updateTexOptions(e,t,s,i,r,a,n,o){const c=s==="opacity";if(!n||c){const h=`${s}Map`,d=`${s}VertexColor`,u=`${s}VertexColorChannel`,f=`${h}Channel`,p=`${h}Transform`,m=`${h}Uv`,_=`${h}Identifier`;if(s!=="light"&&(e[h]=!1,e[_]=void 0,e[f]="",e[p]=0,e[m]=0),e[d]=!1,e[u]="",c&&t.blendType===Ns&&t.alphaTest===0&&!t.alphaToCoverage&&t.opacityDither===on)return;if(s!=="height"&&t[d]&&a&&(e[d]=t[d],e[u]=t[u],e.litOptions.vertexColors=!0),t[h]){let g=!0;if(t[m]===0&&!i&&(g=!1),t[m]===1&&!r&&(g=!1),g){const v=t[h].id;let x=o[v];x===void 0&&(o[v]=s,x=s),e[h]=!!t[h],e[_]=x,e[p]=this._getMapTransformID(t.getUniform(p),t[m]),e[f]=t[f],e[m]=t[m]}}}}_updateMinOptions(e,t,s){const i=s===Pf;
1395e.litOptions.opacityShadowDither=i?t.opacityDither:t.opacityShadowDither,e.litOptions.linearDepth=i,e.litOptions.lights=[]}_updateMaterialOptions(e,t,s){const i=!!(t.useMetalness||t.specularMap||t.sphereMap||t.cubeMap||UM(t.specular)||t.specularityFactor>0&&t.useMetalness||t.enableGGXSpecular||t.clearCoat>0),r=!t.useMetalness||t.useMetalnessSpecularColor,a=i&&(t.specularTint||kM(t.specular)),n=i&&t.useMetalnessSpecularColor&&(t.specularityFactorTint||t.specularityFactor!==1),o=h=>h?h.format===Ho||h.type===nc:!1,c=(h,d)=>Math.abs(h-d)<1e-4;e.specularTint=a,e.specularityFactorTint=n,e.metalnessTint=t.useMetalness&&t.metalness<1,e.glossTint=!0,e.diffuseEncoding=t.diffuseMap?.encoding,e.diffuseDetailEncoding=t.diffuseDetailMap?.encoding,e.emissiveEncoding=t.emissiveMap?.encoding,e.lightMapEncoding=t.lightMap?.encoding,e.packedNormal=o(t.normalMap),e.refractionTint=!c(t.refraction,1),e.refractionIndexTint=!c(t.refractionIndex,1/1.5),e.thicknessTint=t.useDynamicRefraction&&t.thickness!==1,e.specularEncoding=t.specularMap?.encoding,e.sheenEncoding=t.sheenMap?.encoding,e.aoMapUv=t.aoUvSet,e.aoDetail=!!t.aoDetailMap,e.diffuseDetail=!!t.diffuseDetailMap,e.normalDetail=!!t.normalMap,e.normalDetailPackedNormal=o(t.normalDetailMap),e.diffuseDetailMode=t.diffuseDetailMode,e.aoDetailMode=t.aoDetailMode,e.clearCoatGloss=!!t.clearCoatGloss,e.clearCoatPackedNormal=o(t.clearCoatNormalMap),e.iorTint=!c(t.refractionIndex,1/1.5),s.forcePassThroughSpecular&&(e.specularEncoding="linear",e.sheenEncoding="linear"),e.iridescenceTint=t.iridescence!==1,e.glossInvert=t.glossInvert,e.sheenGlossInvert=t.sheenGlossInvert,e.clearCoatGlossInvert=t.clearCoatGlossInvert,e.useSpecularColor=r,e.litOptions.separateAmbient=!1,e.litOptions.pixelSnap=t.pixelSnap,e.litOptions.ambientSH=!!t.ambientSH,e.litOptions.twoSidedLighting=t.twoSidedLighting,e.litOptions.occludeSpecular=t.occludeSpecular,e.litOptions.occludeSpecularFloat=t.occludeSpecularIntensity!==1,e.litOptions.useMsdf=!!t.msdfMap,e.litOptions.msdfTextAttribute=!!t.msdfTextAttribute,e.litOptions.alphaToCoverage=t.alphaToCoverage,e.litOptions.opacityFadesSpecular=t.opacityFadesSpecular,e.litOptions.opacityDither=t.opacityDither,e.litOptions.cubeMapProjection=t.cubeMapProjection,e.litOptions.occludeDirect=t.occludeDirect,e.litOptions.useSpecular=i,e.litOptions.useSpecularityFactor=(n||!!t.specularityFactorMap)&&t.useMetalnessSpecularColor,e.litOptions.enableGGXSpecular=t.enableGGXSpecular,e.litOptions.useAnisotropy=t.enableGGXSpecular&&(t.anisotropyIntensity>0||!!t.anisotropyMap),e.litOptions.fresnelModel=t.fresnelModel,e.litOptions.useRefraction=(t.refraction||!!t.refractionMap)&&(t.useDynamicRefraction||e.litOptions.reflectionSource!==Jr),e.litOptions.useClearCoat=!!t.clearCoat,e.litOptions.useSheen=t.useSheen,e.litOptions.useIridescence=t.useIridescence&&t.iridescence!==0,e.litOptions.useMetalness=t.useMetalness,e.litOptions.useDynamicRefraction=t.useDynamicRefraction,e.litOptions.dispersion=t.dispersion>0,e.litOptions.shadowCatcher=t.shadowCatcher,e.litOptions.useVertexColorGamma=t.vertexColorGamma}_updateEnvOptions(e,t,s,i){e.litOptions.fog=t.useFog?i.fog:vn,e.litOptions.gamma=i.shaderOutputGamma,e.litOptions.toneMap=t.useTonemap?i.toneMapping:Rg;let r=!1;if(t.envAtlas&&t.cubeMap?(e.litOptions.reflectionSource=nu,e.litOptions.reflectionEncoding=t.envAtlas.encoding,e.litOptions.reflectionCubemapEncoding=t.cubeMap.encoding):t.envAtlas?(e.litOptions.reflectionSource=au,e.litOptions.reflectionEncoding=t.envAtlas.encoding):t.cubeMap?(e.litOptions.reflectionSource=ou,e.litOptions.reflectionEncoding=t.cubeMap.encoding):t.sphereMap?(e.litOptions.reflectionSource=PT,e.litOptions.reflectionEncoding=t.sphereMap.encoding):t.useSkybox&&s.envAtlas&&s.skybox?(e.litOptions.reflectionSource=nu,e.litOptions.reflectionEncoding=s.envAtlas.encoding,e.litOptions.reflectionCubemapEncoding=s.skybox.encoding,r=!0):t.useSkybox&&s.envAtlas?(e.litOptions.reflectionSource=au,e.litOptions.reflectionEncoding=s.envAtlas.encoding,r=!0):t.useSkybox&&s.skybox?(e.litOptions.reflectionSource=ou,e.litOptions.reflectionEncoding=s.skybox.encoding,r=!0):(e.litOptions.reflectionSource=Jr,e.litOptions.reflectionEncoding=null),t.ambientSH)e.litOptions.ambientSource=Lg,e.litOptions.ambientEncoding=null;else{const a=t.envAtlas||(t.useSkybox&&s.envAtlas?s.envAtlas:null);a&&!t.sphereMap?(e.litOptions.ambientSource=Fg,e.litOptions.ambientEncoding=a.encoding):(e.litOptions.ambientSource=Og,e.litOptions.ambientEncoding=null)}e.litOptions.skyboxIntensity=r,e.litOptions.useCubeMapRotation=r&&s._skyboxRotationShaderInclude}_updateLightOptions(e,t,s,i,r){if(e.lightMap=!1,e.lightMapChannel="",e.lightMapUv=0,e.lightMapTransform=0,e.litOptions.lightMapWithoutAmbient=!1,e.dirLightMap=!1,i&&(e.litOptions.noShadow=(i&lu)!==0,(i&Km)!==0&&(e.lightMapEncoding=t.lightmapPixelFormat===Re?"rgbm":"linear",e.lightMap=!0,e.lightMapChannel="rgb",e.lightMapUv=1,e.lightMapTransform=0,e.litOptions.lightMapWithoutAmbient=!s.lightMap,(i&MT)!==0&&(e.dirLightMap=!0),(i&RT)!==0&&(e.litOptions.lightMapWithoutAmbient=!1))),s.useLighting){const a=[],n=i?i>>16:Js;e.litOptions.lightMaskDynamic=!!(n&Js),r&&(ui.collectLights(Te,r[Te],a,n),t.clusteredLightingEnabled||(ui.collectLights(ot,r[ot],a,n),ui.collectLights(nt,r[nt],a,n))),e.litOptions.lights=a}else e.litOptions.lights=[];e.litOptions.lights.length===0&&!t.clusteredLightingEnabled&&(e.litOptions.noShadow=!0)}_getMapTransformID(e,t){if(!e)return 0;let s=this._mapXForms[t];s||(s=[],this._mapXForms[t]=s);for(let i=0;i<s.length;i++)if(gy(s[i][0].value,e[0].value)&&gy(s[i][1].value,e[1].value))return i+1;return s.push(e)}}function _t(l,e=!0,t=!0){const s={};return s[`${l}Map`]="texture",s[`${l}MapTiling`]="vec2",s[`${l}MapOffset`]="vec2",s[`${l}MapRotation`]="number",s[`${l}MapUv`]="number",e&&(s[`${l}MapChannel`]="string",t&&(s[`${l}VertexColor`]="boolean",s[`${l}VertexColorChannel`]="string")),s}const zo={name:"string",chunks:"chunks",mappingFormat:"string",_engine:"boolean",ambient:"rgb",..._t("ao"),..._t("aoDetail",!0,!1),aoDetailMode:"string",aoIntensity:"number",diffuse:"rgb",..._t("diffuse"),..._t("diffuseDetail",!0,!1),diffuseDetailMode:"string",vertexColorGamma:"boolean",specular:"rgb",specularTint:"boolean",..._t("specular"),occludeSpecular:"enum:occludeSpecular",specularityFactor:"number",specularityFactorTint:"boolean",..._t("specularityFactor"),useMetalness:"boolean",metalness:"number",enableGGXSpecular:"boolean",metalnessTint:"boolean",..._t("metalness"),useMetalnessSpecularColor:"boolean",anisotropyIntensity:"number",anisotropyRotation:"number",..._t("anisotropy"),shininess:"number",gloss:"number",glossInvert:"boolean",..._t("gloss"),clearCoat:"number",..._t("clearCoat"),clearCoatGloss:"number",clearCoatGlossInvert:"boolean",..._t("clearCoatGloss"),clearCoatBumpiness:"number",..._t("clearCoatNormal",!1),useSheen:"boolean",sheen:"rgb",..._t("sheen"),sheenGloss:"number",sheenGlossInvert:"boolean",..._t("sheenGloss"),fresnelModel:"number",emissive:"rgb",..._t("emissive"),emissiveIntensity:"number",..._t("normal",!1),bumpiness:"number",..._t("normalDetail",!1),normalDetailMapBumpine
1395ss:"number",..._t("height",!0,!1),heightMapFactor:"number",alphaToCoverage:"boolean",alphaTest:"number",alphaFade:"number",alphaDither:"number",opacity:"number",..._t("opacity"),opacityFadesSpecular:"boolean",opacityDither:"string",opacityShadowDither:"string",reflectivity:"number",refraction:"number",refractionTint:"boolean",..._t("refraction"),refractionIndex:"number",dispersion:"number",thickness:"number",thicknessTint:"boolean",..._t("thickness"),attenuation:"rgb",attenuationDistance:"number",useDynamicRefraction:"boolean",sphereMap:"texture",cubeMap:"cubemap",cubeMapProjection:"number",cubeMapProjectionBox:"boundingbox",useIridescence:"boolean",iridescence:"number",iridescenceTint:"boolean",..._t("iridescence"),iridescenceThicknessTint:"boolean",iridescenceThicknessMin:"number",iridescenceThicknessMax:"number",iridescenceRefractionIndex:"number",..._t("iridescenceThickness"),..._t("light"),depthTest:"boolean",depthFunc:"enum:depthFunc",depthWrite:"boolean",depthBias:"number",slopeDepthBias:"number",cull:"enum:cull",blendType:"enum:blendType",useFog:"boolean",useLighting:"boolean",useSkybox:"boolean",useTonemap:"boolean",envAtlas:"texture",twoSidedLighting:"boolean",shadowCatcher:"boolean"},Rf=[];for(const l in zo)zo[l]==="texture"&&Rf.push(l);const Hg=[];for(const l in zo)zo[l]==="cubemap"&&Hg.push(l);const VM={aoMapVertexColor:"boolean",diffuseMapTint:"boolean",diffuseMapVertexColor:"boolean",emissiveMapTint:"boolean",emissiveMapVertexColor:"boolean",glossMapVertexColor:"boolean",metalnessMapVertexColor:"boolean",opacityMapVertexColor:"boolean",specularAntialias:"boolean",specularMapTint:"boolean",specularMapVertexColor:"boolean",ambientTint:"boolean",emissiveTint:"boolean",diffuseTint:"boolean",sheenTint:"boolean",conserveEnergy:"boolean",useGamma:"boolean",useGammaTonemap:"boolean",sheenGlossTint:"boolean",anisotropy:"boolean"},Id={},yw={};let gl=new Set;const jh=new Q;class Es extends yn{static TEXTURE_PARAMETERS=Rf;static CUBEMAP_PARAMETERS=Hg;userAttributes=new Map;onUpdateShader;constructor(){super(),this._assetReferences={},this._activeParams=new Set,this._activeLightingParams=new Set,this.shaderOptBuilder=new zM,this.reset()}reset(){Object.keys(Id).forEach(e=>{this[`_${e}`]=Id[e].value()}),this._uniformCache={}}copy(e){return super.copy(e),Object.keys(Id).forEach(t=>{this[t]=e[t]}),this._alphaDither=e._alphaDither,this.userAttributes=new Map(e.userAttributes),this}setAttribute(e,t){this.userAttributes.set(t,e)}_setParameter(e,t){gl.add(e),this.setParameter(e,t)}_setParameters(e){e.forEach(t=>{this._setParameter(t.name,t.value)})}_processParameters(e){const t=this[e];t.forEach(s=>{gl.has(s)||delete this.parameters[s]}),this[e]=gl,gl=t,gl.clear()}_updateMap(e){const t=`${e}Map`,s=this[t];if(s){this._setParameter(`texture_${t}`,s);const i=`${t}Transform`,r=this.getUniform(i);r&&this._setParameters(r)}}_allocUniform(e,t){let s=this._uniformCache[e];return s||(s=t(),this._uniformCache[e]=s),s}getUniform(e,t,s){return yw[e](this,t,s)}updateUniforms(e,t){const s=n=>this.getUniform(n,e,t);this._setParameter("material_ambient",s("ambient")),this._setParameter("material_diffuse",s("diffuse")),this._setParameter("material_aoIntensity",this.aoIntensity);const i=this.specular.r!==1||this.specular.g!==1||this.specular.b!==1,r=!this.specularMap||this.specularTint||i;this.useMetalness?((!this.metalnessMap||this.metalness<1)&&this._setParameter("material_metalness",this.metalness),r&&this._setParameter("material_specular",s("specular")),(!this.specularityFactorMap||this.specularityFactorTint||this.specularityFactor!==1)&&this._setParameter("material_specularityFactor",this.specularityFactor),this._setParameter("material_sheen",s("sheen")),this._setParameter("material_sheenGloss",this.sheenGloss),this._setParameter("material_refractionIndex",this.refractionIndex)):r&&this._setParameter("material_specular",s("specular")),this.enableGGXSpecular&&(this._setParameter("material_anisotropyIntensity",this.anisotropyIntensity),this._setParameter("material_anisotropyRotation",[Math.cos(this.anisotropyRotation*H.DEG_TO_RAD),Math.sin(this.anisotropyRotation*H.DEG_TO_RAD)])),this.clearCoat>0&&(this._setParameter("material_clearCoat",this.clearCoat),this._setParameter("material_clearCoatGloss",this.clearCoatGloss),this._setParameter("material_clearCoatBumpiness",this.clearCoatBumpiness)),this._setParameter("material_gloss",this.gloss),this._setParameter("material_emissive",s("emissive")),this._setParameter("material_emissiveIntensity",this.emissiveIntensity),this.refraction>0&&this._setParameter("material_refraction",this.refraction),this.dispersion>0&&this._setParameter("material_dispersion",this.dispersion),this.useDynamicRefraction&&(this._setParameter("material_thickness",this.thickness),this._setParameter("material_attenuation",s("attenuation")),this._setParameter("material_invAttenuationDistance",this.attenuationDistance===0?0:1/this.attenuationDistance)),this.useIridescence&&(this._setParameter("material_iridescence",this.iridescence),this._setParameter("material_iridescenceRefractionIndex",this.iridescenceRefractionIndex),this._setParameter("material_iridescenceThicknessMin",this.iridescenceThicknessMin),this._setParameter("material_iridescenceThicknessMax",this.iridescenceThicknessMax)),this._setParameter("material_opacity",this.opacity);const a=this._opacity>0?this.alphaDither/this._opacity:1;this._setParameter("material_alphaDitherScale",a),this.opacityFadesSpecular===!1&&this._setParameter("material_alphaFade",this.alphaFade),this.occludeSpecular&&this._setParameter("material_occludeSpecularIntensity",this.occludeSpecularIntensity),this.cubeMapProjection===CT&&this._setParameter(s("cubeMapProjectionBox"));for(const n in wo)this._updateMap(n);this.ambientSH&&this._setParameter("ambientSH[0]",this.ambientSH),this.normalMap&&this._setParameter("material_bumpiness",this.bumpiness),this.normalMap&&this.normalDetailMap&&this._setParameter("material_normalDetailMapBumpine
1395ss",this.normalDetailMapBumpiness),this.heightMap&&this._setParameter("material_heightMapFactor",s("heightMapFactor")),this.envAtlas&&this.cubeMap?(this._setParameter("texture_envAtlas",this.envAtlas),this._setParameter("texture_cubeMap",this.cubeMap)):this.envAtlas?this._setParameter("texture_envAtlas",this.envAtlas):this.cubeMap?this._setParameter("texture_cubeMap",this.cubeMap):this.sphereMap&&this._setParameter("texture_sphereMap",this.sphereMap),this._setParameter("material_reflectivity",this.reflectivity),this._processParameters("_activeParams"),super.updateUniforms(e,t)}updateEnvUniforms(e,t){!(this.envAtlas||this.cubeMap||this.sphereMap)&&this.useSkybox&&(t.envAtlas&&t.skybox?(this._setParameter("texture_envAtlas",t.envAtlas),this._setParameter("texture_cubeMap",t.skybox)):t.envAtlas?this._setParameter("texture_envAtlas",t.envAtlas):t.skybox&&this._setParameter("texture_cubeMap",t.skybox)),this._processParameters("_activeLightingParams")}getShaderVariant(e){const{device:t,scene:s,pass:i,objDefs:r,sortedLights:a,cameraShaderParams:n}=e;this.updateEnvUniforms(t,s);const o=zi.get(t).getByIndex(i),c=i===If||i===Pf||o.isShadow;let h=c?Wp.optionsContextMin:Wp.optionsContext;h.defines=Qt.getCoreDefines(this,e),c?this.shaderOptBuilder.updateMinRef(h,s,this,r,i,a):this.shaderOptBuilder.updateRef(h,s,n,this,r,i,a),this.useFog||h.defines.set("FOG","NONE"),h.defines.set("TONEMAP",ET[h.litOptions.toneMap]),this.onUpdateShader&&(h=this.onUpdateShader(h));const d=new Df(e.viewUniformFormat,e.viewBindGroupFormat,e.vertexFormat),u=ko(t);return u.register("standard",Wp),u.getProgram("standard",h,d,this.userId)}destroy(){for(const e in this._assetReferences)this._assetReferences[e]._unbind();this._assetReferences=null,super.destroy()}}const Lf=(l,e)=>{yw[l]=e},Wg=(l,e,t,s)=>{Object.defineProperty(Es.prototype,l,{get:s||function(){return this[`_${l}`]},set:t}),Id[l]={value:e}},GM=l=>{const e=`_${l.name}`,t=l.dirtyShaderFunc||(()=>!0),s=function(i){const r=this[e];r!==i&&(this._dirtyShader=this._dirtyShader||t(r,i),this[e]=i)};Wg(l.name,()=>l.defaultValue,s,l.getterFunc)},HM=l=>{const e=`_${l.name}`,t=l.dirtyShaderFunc||(()=>!0),s=function(i){const r=this[e];r.equals(i)||(this._dirtyShader=this._dirtyShader||t(r,i),this[e]=r.copy(i))};Wg(l.name,()=>l.defaultValue.clone(),s,l.getterFunc)},Os=l=>l.defaultValue&&l.defaultValue.clone?HM(l):GM(l);function ft(l,e="rgb",t=!0,s=0){wo[l]=e.length||-1,Os({name:`${l}Map`,defaultValue:null,dirtyShaderFunc:(o,c)=>!!o!=!!c||o&&(o.type!==c.type||o.format!==c.format)}),Os({name:`${l}MapTiling`,defaultValue:new j(1,1)}),Os({name:`${l}MapOffset`,defaultValue:new j(0,0)}),Os({name:`${l}MapRotation`,defaultValue:0}),Os({name:`${l}MapUv`,defaultValue:s}),e&&(Os({name:`${l}MapChannel`,defaultValue:e}),t&&(Os({name:`${l}VertexColor`,defaultValue:!1}),Os({name:`${l}VertexColorChannel`,defaultValue:e})));const i=`${l}MapTiling`,r=`${l}MapOffset`,a=`${l}MapRotation`,n=`${l}MapTransform`;Lf(n,(o,c,h)=>{const d=o[i],u=o[r],f=o[a];if(d.x===1&&d.y===1&&u.x===0&&u.y===0&&f===0)return null;const p=o._allocUniform(n,()=>[{name:`texture_${n}0`,value:new Float32Array(3)},{name:`texture_${n}1`,value:new Float32Array(3)}]),m=Math.cos(f*H.DEG_TO_RAD),_=Math.sin(f*H.DEG_TO_RAD),g=p[0].value;g[0]=m*d.x,g[1]=-_*d.y,g[2]=u.x;const v=p[1].value;return v[0]=_*d.x,v[1]=m*d.y,v[2]=1-d.y-u.y,p})}function zn(l,e){Os({name:l,defaultValue:e,getterFunc:function(){return this._dirtyShader=!0,this[`_${l}`]}}),Lf(l,(t,s,i)=>{const r=t._allocUniform(l,()=>new Float32Array(3)),a=t[l];return jh.linear(a),r[0]=jh.r,r[1]=jh.g,r[2]=jh.b,r})}function Ke(l,e,t){Os({name:l,defaultValue:e,dirtyShaderFunc:(s,i)=>(s===0||s===1)!=(i===0||i===1)}),Lf(l,t)}function vl(l,e){Os({name:l,defaultValue:null,dirtyShaderFunc:(t,s)=>!!t==!!s}),Lf(l,e)}function Xe(l,e){Os({name:l,defaultValue:e})}function WM(){zn("ambient",new Q(1,1,1)),zn("diffuse",new Q(1,1,1)),zn("specular",new Q(0,0,0)),zn("emissive",new Q(0,0,0)),zn("sheen",new Q(1,1,1)),zn("attenuation",new Q(1,1,1)),Ke("emissiveIntensity",1),Ke("specularityFactor",1),Ke("sheenGloss",0),Ke("gloss",.25),Ke("aoIntensity",1),Ke("heightMapFactor",1,(s,i,r)=>
1395s.heightMapFactor*.025),Ke("opacity",1),Ke("alphaFade",1),Os({name:"alphaDither",defaultValue:null,dirtyShaderFunc:()=>!1,getterFunc:function(){return this._alphaDither??this._opacity}}),Ke("alphaTest",0),Ke("bumpiness",1),Ke("normalDetailMapBumpiness",1),Ke("reflectivity",1),Ke("occludeSpecularIntensity",1),Ke("refraction",0),Ke("refractionIndex",1/1.5,(s,i,r)=>Math.max(.001,s.refractionIndex)),Ke("dispersion",0),Ke("thickness",0),Ke("attenuationDistance",0),Ke("metalness",1),Ke("anisotropyIntensity",0),Ke("anisotropyRotation",0),Ke("clearCoat",0),Ke("clearCoatGloss",1),Ke("clearCoatBumpiness",1),Ke("aoUvSet",0,null),Ke("iridescence",0),Ke("iridescenceRefractionIndex",1/1.5),Ke("iridescenceThicknessMin",0),Ke("iridescenceThicknessMax",0),vl("ambientSH"),vl("cubeMapProjectionBox",(s,i,r)=>{const a=s._allocUniform("cubeMapProjectionBox",()=>[{name:"envBoxMin",value:new Float32Array(3)},{name:"envBoxMax",value:new Float32Array(3)}]),n=s.cubeMapProjectionBox.getMin(),o=a[0].value;o[0]=n.x,o[1]=n.y,o[2]=n.z;const c=s.cubeMapProjectionBox.getMax(),h=a[1].value;return h[0]=c.x,h[1]=c.y,h[2]=c.z,a}),Xe("specularTint",!1),Xe("specularityFactorTint",!1),Xe("useMetalness",!1),Xe("useMetalnessSpecularColor",!1),Xe("useSheen",!1),Xe("enableGGXSpecular",!1),Xe("occludeDirect",!1),Xe("opacityFadesSpecular",!0),Xe("occludeSpecular",Af),Xe("fresnelModel",Ag),Xe("useDynamicRefraction",!1),Xe("cubeMapProjection",Mg),Xe("useFog",!0),Xe("useLighting",!0),Xe("useTonemap",!0),Xe("useSkybox",!0),Xe("forceUv1",!1),Xe("pixelSnap",!1),Xe("twoSidedLighting",!1),Xe("nineSlicedMode",void 0),Xe("msdfTextAttribute",!1),Xe("useIridescence",!1),Xe("glossInvert",!1),Xe("sheenGlossInvert",!1),Xe("clearCoatGlossInvert",!1),Xe("opacityDither",on),Xe("opacityShadowDither",on),Xe("shadowCatcher",!1),Xe("vertexColorGamma",!1),ft("diffuse"),ft("specular"),ft("emissive"),ft("thickness","g"),ft("specularityFactor","g"),ft("normal",""),ft("metalness","g"),ft("gloss","g"),ft("opacity","a"),ft("refraction","g"),ft("height","g",!1),ft("ao","g"),ft("light","rgb",!0,1),ft("msdf",""),ft("diffuseDetail","rgb",!1),ft("normalDetail",""),ft("aoDetail","g",!1),ft("clearCoat","g"),ft("clearCoatGloss","g"),ft("clearCoatNormal",""),ft("sheen","rgb"),ft("sheenGloss","g"),ft("iridescence","g"),ft("iridescenceThickness","g"),ft("anisotropy",""),Xe("diffuseDetailMode",lS),Xe("aoDetailMode",lS),vl("cubeMap"),vl("sphereMap"),vl("envAtlas");const l=function(){return this._prefilteredCubemaps},e=function(s){const i=this._prefilteredCubemaps;s=s||[];let r=!1,a=!0;for(let n=0;n<6;++n){const o=s[n]||null;i[n]!==o&&(i[n]=o,r=!0),a=a&&!!i[n]}r&&(a?this.envAtlas=nw.generatePrefilteredAtlas(i,{target:this.envAtlas}):this.envAtlas&&(this.envAtlas.destroy(),this.envAtlas=null),this._dirtyShader=!0)},t=[null,null,null,null,null,null];Wg("prefilteredCubemaps",()=>t.slice(),e,l)}WM();const di=8/64,Mi=1-di*2;class Xg extends un{constructor(e,t,s,i,r,a){super();const n=new E,o=new E,c=new E,h=new E,d=new E,u=new E,f=[],p=[],m=[],_=[],g=[];let v;if(s>0)for(let x=0;x<=i;x++)for(let y=0;y<=r;y++){const S=y/r*2*Math.PI-Math.PI,T=Math.sin(S),w=Math.cos(S);d.set(T*e,-s/2,w*e),h.set(T*t,s/2,w*t),n.lerp(d,h,x/i),o.sub2(h,d).normalize(),u.set(w,0,-T),c.cross(u,o).normalize(),f.push(n.x,n.y,n.z),p.push(c.x,c.y,c.z);let C=y/r,b=x/i;m.push(C,1-b);const I=b;if(b=C,C=I,C=C*Mi+di,b=b*Mi+di,C/=3,_.push(C,1-b),x<i&&y<r){const P=x*(r+1)+y,L=x*(r+1)+(y+1),O=(x+1)*(r+1)+y,D=(x+1)*(r+1)+(y+1);g.push(P,L,O),g.push(L,D,O)}}if(a){const x=Math.floor(r/2),y=r,S=s/2;for(let T=0;T<=x;T++){const w=T*Math.PI*.5/x,C=Math.sin(w),b=Math.cos(w);for(let I=0;I<=y;I++){const P=I*2*Math.PI/y-Math.PI/2,L=Math.sin(P),D=Math.cos(P)*C,N=b,k=L*C;let A=1-I/y,M=1-T/x;f.push(D*t,N*t+S,k*t),p.push(D,N,k),m.push(A,1-M),A=A*Mi+di,M=M*Mi+di,A/=3,M/=3,A+=1/3,_.push(A,1-M)}}v=(i+1)*(r+1);for(let T=0;T<x;++T)for(let w=0;w<y;++w){const C=T*(y+1)+w,b=C+y+1;g.push(v+C+1,v+b,v+C),g.push(v+C+1,v+b+1,v+b)}for(let T=0;T<=x;T++){const w=Math.PI*.5+T*Math.PI*.5/x,C=Math.sin(w),b=Math.cos(w);for(let I=0;I<=y;I++){const P=I*2*Math.PI/y-Math.PI/2,L=Math.sin(P),D=Math.cos(P)*C,N=b,k=L*C;let A=1-I/y,M=1-T/x;f.push(D*t,N*t-S,k*t),p.push(D,N,k),m.push(A,1-M),A=A*Mi+di,M=M*Mi+di,A/=3,M/=3,A+=2/3,_.push(A,1-M)}}v=(i+1)*(r+1)+(y+1)*(x+1);for(let T=0;T<x;++T)for(let w=0;w<y;++w){const C=T*(y+1)+w,b=C+y+1;g.push(v+C+1,v+b,v+C),g.push(v+C+1,v+b+1,v+b)}}else{if(v=(i+1)*(r+1),e>0)for(let x=0;x<r;x++){const y=x/r*2*Math.PI,S=Math.sin(y),T=-s/2,w=Math.cos(y);let C=1-(S+1)/2,b=(w+1)/2;
1395f.push(S*e,T,w*e),p.push(0,-1,0),m.push(C,1-b),C=C*Mi+di,b=b*Mi+di,C/=3,b/=3,C+=1/3,_.push(C,1-b),x>1&&g.push(v,v+x,v+x-1)}if(v+=r,t>0)for(let x=0;x<r;x++){const y=x/r*2*Math.PI,S=Math.sin(y),T=s/2,w=Math.cos(y);let C=1-(S+1)/2,b=(w+1)/2;f.push(S*t,T,w*t),p.push(0,1,0),m.push(C,1-b),C=C*Mi+di,b=b*Mi+di,C/=3,b/=3,C+=2/3,_.push(C,1-b),x>1&&g.push(v,v+x-1,v+x)}}this.positions=f,this.normals=p,this.uvs=m,this.uvs1=_,this.indices=g}}class XM extends Xg{constructor(e={}){const t=e.radius??.3,s=e.height??1,i=e.heightSegments??1,r=e.sides??20;super(t,t,s-2*t,i,r,!0),e.calculateTangents&&(this.tangents=ma(this.positions,this.normals,this.uvs,this.indices))}}class YM extends Xg{constructor(e={}){const t=e.baseRadius??.5,s=e.peakRadius??0,i=e.height??1,r=e.heightSegments??5,a=e.capSegments??18;super(t,s,i,r,a,!1),e.calculateTangents&&(this.tangents=ma(this.positions,this.normals,this.uvs,this.indices))}}class jM extends Xg{constructor(e={}){const t=e.radius??.5,s=e.height??1,i=e.heightSegments??5,r=e.capSegments??20;super(t,t,s,i,r,!1),e.calculateTangents&&(this.tangents=ma(this.positions,this.normals,this.uvs,this.indices))}}class qM extends un{constructor(e={}){super();const t=e.halfExtents??new j(.5,.5),s=e.widthSegments??5,i=e.lengthSegments??5,r=[],a=[],n=[],o=[];let c=0;for(let h=0;h<=s;h++)for(let d=0;d<=i;d++){const u=-t.x+2*t.x*h/s,f=0,p=-(-t.y+2*t.y*d/i),m=h/s,_=d/i;r.push(u,f,p),a.push(0,1,0),n.push(m,1-_),h<s&&d<i&&(o.push(c+i+1,c+1,c),o.push(c+i+1,c+i+2,c+1)),c++}this.positions=r,this.normals=a,this.uvs=n,this.uvs1=n,this.indices=o,e.calculateTangents&&(this.tangents=ma(r,a,n,o))}}class $M extends un{constructor(e={}){super();const t=e.tubeRadius??.2,s=e.ringRadius??.3,i=(e.sectorAngle??360)*H.DEG_TO_RAD,r=e.segments??30,a=e.sides??20,n=[],o=[],c=[],h=[];for(let d=0;d<=a;d++)for(let u=0;u<=r;u++){const f=Math.cos(i*u/r)*(s+t*Math.cos(2*Math.PI*d/a)),p=Math.sin(2*Math.PI*d/a)*t,m=Math.sin(i*u/r)*(s+t*Math.cos(2*Math.PI*d/a)),_=Math.cos(i*u/r)*Math.cos(2*Math.PI*d/a),g=Math.sin(2*Math.PI*d/a),v=Math.sin(i*u/r)*Math.cos(2*Math.PI*d/a),x=d/a,y=1-u/r;if(n.push(f,p,m),o.push(_,g,v),c.push(x,1-y),d<a&&u<r){const S=d*(r+1)+u,T=(d+1)*(r+1)+u,w=d*(r+1)+(u+1),C=(d+1)*(r+1)+(u+1);h.push(S,T,w),h.push(T,C,w)}}this.positions=n,this.normals=o,this.uvs=c,this.uvs1=c,this.indices=h,e.calculateTangents&&(this.tangents=ma(n,o,c,h))}}class KM{processedCache=new Map;definitionsCache=new Map;_generators=new Map;constructor(e,t){this._device=e,this._isClearingCache=!1,this._precached=!1,this._programsCollection=[],this._defaultStdMatOption=new yc,this._defaultStdMatOptionMin=new yc;const s=new WT;t.shaderOptBuilder.updateRef(this._defaultStdMatOption,{},s,t,null,[],Ko,null),t.shaderOptBuilder.updateMinRef(this._defaultStdMatOptionMin,{},t,null,FT,null),e.on("destroy:shader",i=>{this.removeFromCache(i)})}destroy(){this.clearCache()}register(e,t){this._generators.has(e)||this._generators.set(e,t)}unregister(e){this._generators.has(e)&&this._generators.delete(e)}isRegistered(e){return this._generators.has(e)}generateShaderDefinition(e,t,s,i){let r=this.definitionsCache.get(s);if(!r){let a;i.litOptions?.lights&&(a=i.litOptions.lights,i.litOptions.lights=a.map(o=>{const c=o.clone?o.clone():o;return c.key=o.key,c})),this.storeNewProgram(t,i),i.litOptions?.lights&&(i.litOptions.lights=a),this._precached;const n=this._device;r=e.createShaderDefinition(n,i),r.name=r.name??(i.pass?`${t}-pass:${i.pass}`:t),this.definitionsCache.set(s,r)}return r}getCachedShader(e){return this.processedCache.get(e)}setCachedShader(e,t){this.processedCache.set(e,t)}getProgram(e,t,s,i){const r=this._generators.get(e);if(!r)return null;const a=r.generateKey(t),n=Xs(a),o=s.generateKey(this._device),c=Xs(o),h=`${n}#${c}`;let d=this.getCachedShader(h);if(!d){const u=this.generateShaderDefinition(r,e,n,t);let f="",p;t.pass!==void 0&&(p=zi.get(this._device).getByIndex(t.pass),f=`-${p.name}`),this._device.fire("shader:generate",{userMaterialId:i,shaderPassInfo:p,definition:u});const m={name:`${u.name}${f}-proc`,attributes:u.attributes,vshader:u.vshader,vincludes:u.vincludes,fincludes:u.fincludes,fshader:u.fshader,processingOptions:s,shaderLanguage:u.shaderLanguage,meshUniformBufferFormat:u.meshUniformBufferFormat,meshBindGroupFormat:u.meshBindGroupFormat};d=new tt(this._device,m),this.setCachedShader(h,d)}return d}storeNewProgram(e,t){let s={};if(e==="standard"){const i=this._getDefaultStdMatOptions(t.pass);for(const r in t)(t.hasOwnProperty(r)&&i[r]!==t[r]||r==="pass")&&(s[r]=t[r]);for(const r in t.litOptions)s[r]=t.litOptions[r]}else s=t;this._programsCollection.push(JSON.stringify({name:e,options:s}))}dumpPrograms(){let e=`let device = pc.app ? pc.app.graphicsDevice : pc.Application.getApplication().graphicsDevice; 1396`;e+="let shaders = [",this._programsCollection[0]&&(e+=` 1397 ${this._programsCollection[0]}`);for(let s=1;s<this._programsCollection.length;++s)e+=`, 1398 ${this._programsCollection[s]}`;e+=` 1399];
1400`,e+=`pc.getProgramLibrary(device).precompile(shaders); 1401`,e+=`if (pc.version != "${Ex}" || pc.revision != "${JC}") 1402`,e+=' console.warn("precompile-shaders.js: engine version mismatch, rebuild shaders lib with current engine");';const t=document.createElement("a");t.setAttribute("href",`data:text/plain;charset=utf-8,${encodeURIComponent(e)}`),t.setAttribute("download","precompile-shaders.js"),t.style.display="none",document.body.appendChild(t),t.click(),document.body.removeChild(t)}clearCache(){this._isClearingCache=!0,this.processedCache.forEach(e=>{e.destroy()}),this.processedCache.clear(),this._isClearingCache=!1}removeFromCache(e){this._isClearingCache||this.processedCache.forEach((t,s)=>{e===t&&this.processedCache.delete(s)})}_getDefaultStdMatOptions(e){const t=zi.get(this._device).getByIndex(e);return e===If||e===Pf||t.isShadow?this._defaultStdMatOptionMin:this._defaultStdMatOption}precompile(e){if(e){const t=new Array(e.length);for(let s=0;s<e.length;s++){if(e[s].name==="standard"){const i=e[s].options,r=this._getDefaultStdMatOptions(i.pass);for(const a in r)r.hasOwnProperty(a)&&i[a]===void 0&&(i[a]=r[a])}t[s]=this.getProgram(e[s].name,e[s].options)}}this._precached=!0}}class xw{_deviceLostEvent=null;constructor(e,t=!1){this.device=e,this.useSingleBuffer=t,this.impl=e.createUploadStreamImpl(this),this._deviceLostEvent=this.device.on("devicelost",this._onDeviceLost,this)}destroy(){this._deviceLostEvent?.off(),this._deviceLostEvent=null,this.impl?.destroy(),this.impl=null}upload(e,t,s=0,i=e.length){this.impl?.upload(e,t,s,i)}_onDeviceLost(){this.impl?._onDeviceLost?.()}}var ZM=` 1403#define GSPLAT_CENTER_NOPROJ 1404#include "gsplatHelpersVS" 1405#include "gsplatFormatVS" 1406#include "gsplatStructsVS" 1407#include "gsplatDeclarationsVS" 1408#include "gsplatCenterVS" 1409#include "gsplatEvalSHVS" 1410#include "gsplatQuatToMat3VS" 1411#include "gsplatReadVS" 1412#include "gsplatWorkBufferOutputVS" 1413#include "gsplatWriteVS" 1414#include "gsplatModifyVS" 1415flat varying ivec4 vSubDraw; 1416uniform vec3 uColorMultiply; 1417uniform vec3 model_scale; 1418uniform vec4 model_rotation; 1419#ifdef GSPLAT_ID 1420 uniform uint uId; 1421#endif 1422void main(void) { 1423 int localRow = int(gl_FragCoord.y) - vSubDraw.w; 1424 int localCol = int(gl_FragCoord.x) - vSubDraw.y; 1425 uint originalIndex = uint(vSubDraw.x + localRow * vSubDraw.z + localCol); 1426 setSplat(originalIndex); 1427 vec3 modelCenter = getCenter(); 1428 vec3 worldCenter = (matrix_model * vec4(modelCenter, 1.0)).xyz; 1429 SplatCenter center; 1430 initCenter(modelCenter, center); 1431 vec4 srcRotation = getRotation().yzwx; 1432 vec3 srcScale = getScale(); 1433 vec4 worldRotation = quatMul(model_rotation, srcRotation); 1434 if (worldRotation.w < 0.0) { 1435 worldRotation = -worldRotation; 1436 } 1437 vec3 worldScale = model_scale * srcScale; 1438 vec3 originalCenter = worldCenter; 1439 modifySplatCenter(worldCenter); 1440 modifySplatRotationScale(originalCenter, worldCenter, worldRotation, worldScale); 1441 vec4 color = getColor(); 1442 #if SH_BANDS > 0 1443 vec3 dir = normalize(center.view * mat3(center.modelView)); 1444 vec3 sh[SH_COEFFS]; 1445 float scale; 1446 readSHData(sh, scale); 1447 color.xyz += evalSH(sh, dir) * scale; 1448 #endif 1449 modifySplatColor(worldCenter, color); 1450 color.xyz *= uColorMultiply; 1451 writeSplat(worldCenter, worldRotation, worldScale, color); 1452 #ifdef GSPLAT_ID 1453 writePcId(uvec4(uId, 0u, 0u, 0u)); 1454 #endif 1455} 1456`,QM=` 1457#define GSPLAT_CENTER_NOPROJ 1458#include "gsplatHelpersVS" 1459#include "gsplatFormatVS" 1460#include "gsplatStructsVS" 1461#include "gsplatDeclarationsVS" 1462#include "gsplatCenterVS" 1463#include "gsplatEvalSHVS" 1464#include "gsplatQuatToMat3VS" 1465#include "gsplatReadVS" 1466var<private> processOutput: FragmentOutput; 1467#include "gsplatWorkBufferOutputVS" 1468#include "gsplatWriteVS" 1469#include "gsplatModifyVS" 1470varying @interpolate(flat) vSubDraw: vec4i; 1471uniform uColorMultiply: vec3f; 1472uniform model_scale: vec3f; 1473uniform model_rotation: vec4f; 1474#ifdef GSPLAT_ID 1475 uniform uId: u32; 1476#endif 1477@fragment 1478fn fragmentMain(input: FragmentInput) -> FragmentOutput { 1479 let localRow = i32(input.position.y) - input.vSubDraw.w; 1480 let localCol = i32(input.position.x) - input.vSubDraw.y; 1481 let originalIndex = u32(input.vSubDraw.x + localRow * input.vSubDraw.z + localCol); 1482 setSplat(originalIndex); 1483 var modelCenter = getCenter(); 1484 var worldCenter = (uniform.matrix_model * vec4f(modelCenter, 1.0)).xyz; 1485 var center: SplatCenter; 1486 initCenter(modelCenter, ¢er); 1487 let srcRotation = getRotation().yzwx; 1488 let srcScale = getScale(); 1489 var worldRotation = vec4f(quatMul(half4(uniform.model_rotation), half4(srcRotation))); 1490 if (worldRotation.w < 0.0) { 1491 worldRotation = -worldRotation; 1492 } 1493 var worldScale = uniform.model_scale * srcScale; 1494 let originalCenter = worldCenter; 1495 modifySplatCenter(&worldCenter); 1496 modifySplatRotationScale(originalCenter, worldCenter, &worldRotation, &worldScale); 1497 var color = getColor(); 1498 #if SH_BANDS > 0 1499 let dir = normalize(center.view * mat3x3f(center.modelView[0].xyz, center.modelView[1].xyz, center.modelView[2].xyz)); 1500 var sh: array<half3, SH_COEFFS>; 1501 var scale: f32; 1502 readSHData(&sh, &scale); 1503 color = vec4f(color.xyz + vec3f(evalSH(&sh, dir) * half(scale)), color.w); 1504 #endif 1505 modifySplatColor(worldCenter, &color); 1506 color = vec4f(color.xyz * uniform.uColorMultiply, color.w); 1507 writeSplat(worldCenter, worldRotation, worldScale, color); 1508 #ifdef GSPLAT_ID 1509 writePcId(vec4u(uniform.uId, 0u, 0u, 0u)); 1510 #endif 1511 return processOutput; 1512} 1513`,JM=` 1514attribute vec2 vertex_position; 1515precision highp usampler2D; 1516uniform usampler2D uSubDrawData; 1517uniform ivec2 uTextureSize; 1518uniform int uSubDrawBase; 1519flat varying ivec4 vSubDraw; 1520void main(void) {
1521 int subDrawWidth = textureSize(uSubDrawData, 0).x; 1522 int idx = gl_InstanceID + uSubDrawBase; 1523 uvec4 data = texelFetch(uSubDrawData, ivec2(idx % subDrawWidth, idx / subDrawWidth), 0); 1524 int rowStart = int(data.r & 0xFFFFu); 1525 int numRows = int(data.r >> 16u); 1526 int colStart = int(data.g); 1527 int colEnd = int(data.b); 1528 int sourceBase = int(data.a); 1529 float u = float(gl_VertexID & 1); 1530 float v = float(gl_VertexID >> 1); 1531 vec4 ndc = vec4(colStart, colEnd, rowStart, rowStart + numRows) / vec4(uTextureSize.x, uTextureSize.x, uTextureSize.y, uTextureSize.y) * 2.0 - 1.0; 1532 gl_Position = vec4(mix(ndc.x, ndc.y, u), mix(ndc.z, ndc.w, v), 0.5, 1.0); 1533 vSubDraw = ivec4(sourceBase, colStart, colEnd - colStart, rowStart); 1534} 1535`,eR=` 1536attribute vertex_position: vec2f; 1537var uSubDrawData: texture_2d<u32>; 1538uniform uTextureSize: vec2i; 1539uniform uSubDrawBase: i32; 1540varying @interpolate(flat) vSubDraw: vec4i; 1541@vertex 1542fn vertexMain(input: VertexInput) -> VertexOutput { 1543 var output: VertexOutput; 1544 let subDrawWidth = i32(textureDimensions(uSubDrawData, 0).x); 1545 let instIdx = i32(input.instanceIndex) + uniform.uSubDrawBase; 1546 let data = textureLoad(uSubDrawData, vec2i(instIdx % subDrawWidth, instIdx / subDrawWidth), 0); 1547 let rowStart = i32(data.r & 0xFFFFu); 1548 let numRows = i32(data.r >> 16u); 1549 let colStart = i32(data.g); 1550 let colEnd = i32(data.b); 1551 let sourceBase = i32(data.a); 1552 let u = f32(i32(input.vertexIndex) & 1); 1553 let v = f32(i32(input.vertexIndex) >> 1u); 1554 let ndc = vec4f(f32(colStart), f32(colEnd), f32(rowStart), f32(rowStart + numRows)) / vec4f(f32(uniform.uTextureSize.x), f32(uniform.uTextureSize.x), f32(uniform.uTextureSize.y), f32(uniform.uTextureSize.y)) * 2.0 - 1.0; 1555 output.position = vec4f(mix(ndc.x, ndc.y, u), mix(-ndc.z, -ndc.w, v), 0.5, 1.0); 1556 output.vSubDraw = vec4i(sourceBase, colStart, colEnd - colStart, rowStart); 1557 return output; 1558} 1559`;const vy=new Z,Sy=new X_,Xp=8;class tR{device;boundsBuffer=null;totalBoundsEntries=0;_allocatedBoundsEntries=0;_boundsFloatView=null;_boundsUintView=null;_tmpSpheres=null;transformsBuffer=null;_allocatedTransformCount=0;_transformsData=null;frustumPlanes=new Float32Array(24);fisheyeCameraPos=new Float32Array(3);fisheyeCameraForward=new Float32Array(3);fisheyeMaxTheta=Math.PI;constructor(e){this.device=e}destroy(){this.boundsBuffer?.destroy(),this.transformsBuffer?.destroy()}updateBoundsData(e){let t=0;for(let a=0;a<e.length;a++)t+=e[a].numBoundsEntries;if(this.totalBoundsEntries=t,t===0)return;if(t>this._allocatedBoundsEntries){this.boundsBuffer?.destroy(),this._allocatedBoundsEntries=t,this.boundsBuffer=new Se(this.device,t*Xp*4,ct);const a=new ArrayBuffer(t*Xp*4);this._boundsFloatView=new Float32Array(a),this._boundsUintView=new Uint32Array(a),this._tmpSpheres=new Float32Array(t*4)}const s=this._boundsFloatView,i=this._boundsUintView,r=this._tmpSpheres;for(let a=0;a<e.length;a++){const n=e[a],o=n.boundsBaseIndex,c=n.numBoundsEntries;n.splat.writeBoundsSpheres(r,o*4);for(let h=0;h<c;h++){const d=(o+h)*4,u=(o+h)*Xp;s[u+0]=r[d+0],s[u+1]=r[d+1],s[u+2]=r[d+2],s[u+3]=r[d+3],i[u+4]=a}}this.boundsBuffer.write(0,s)}updateTransformsData(e){const t=e.length;if(t===0)return;t>this._allocatedTransformCount&&(this.transformsBuffer?.destroy(),this._allocatedTransformCount=t,this.transformsBuffer=new Se(this.device,t*12*4,ct),this._transformsData=new Float32Array(t*12));const s=this._transformsData;let i=0;for(let r=0;r<e.length;r++){const a=e[r].splat.node.getWorldTransform().data;s[i++]=a[0],s[i++]=a[4],s[i++]=a[8],s[i++]=a[12],s[i++]=a[1],s[i++]=a[5],s[i++]=a[9],s[i++]=a[13],s[i++]=a[2],s[i++]=a[6],s[i++]=a[10],s[i++]=a[14]}this.transformsBuffer.write(0,s)}computeFrustumPlanes(e,t){vy.mul2(e,t),Sy.setFromMat4(vy);const s=this.frustumPlanes;for(let i=0;i<6;i++){const r=Sy.planes[i];s[i*4+0]=r.normal.x,s[i*4+1]=r.normal.y,s[i*4+2]=r.normal.z,s[i*4+3]=r.distance}}setFisheyeData(e,t,s){this.fisheyeCameraPos[0]=e.x,this.fisheyeCameraPos[1]=e.y,this.fisheyeCameraPos[2]=e.z,this.fisheyeCameraForward[0]=t.x,this.fisheyeCameraForward[1]=t.y,this.fisheyeCameraForward[2]=t.z,this.fisheyeMaxTheta=s}}const sR=new Z,qh=new E,Ma=new ae,Yp=new j,iR=[1,1,1];class yy extends Pr{splats=[];colorsByLod=void 0;cameraNode=null;workBuffer;colorOnly;_modelScaleData=new Float32Array(3);_modelRotationData=new Float32Array(4);_textureSize=new Int32Array(2);_subDrawTexture;_partialData=[];constructor(e,t,s=!1){super(e),this.workBuffer=t,this.colorOnly=s,this._subDrawTexture=ce.createDataTexture2D(e,"GsplatSubDrawData",1,1,Wt)}destroy(){this.splats.length=0,this._subDrawTexture.destroy(),super.destroy()}init(e){super.init(e),this.colorOps.clear=!1,this.depthStencilOps.clearDepth=!1}
1559update(e,t,s,i=null){this.splats.length=0,this._partialData.length=0,this.colorsByLod=s;const r=this.workBuffer.textureSize;if(i){const a=i.size*3;this._subDrawTexture.width*this._subDrawTexture.height<a&&(Xt.calcTextureSize(a,Yp),this._subDrawTexture.resize(Yp.x,Yp.y));const n=this._subDrawTexture.lock();let o=0;for(let c=0;c<e.length;c++){const h=e[c];if(h.activeSplats<=0)continue;const d=h.intervals,u=d.length/2;if(u===0)i.has(h.allocId)&&(this.splats.push(h),this._partialData.push(0,0));else{const f=o,p=h.intervalAllocIds;for(let _=0;_<u;_++)i.has(p[_])&&(o=h.appendSubDraws(n,o,d[_*2],d[_*2+1]-d[_*2],h.intervalOffsets[_],r));const m=o-f;m>0&&(this.splats.push(h),this._partialData.push(f,m))}}this._subDrawTexture.unlock()}else for(let a=0;a<e.length;a++){const n=e[a];n.activeSplats>0&&(this.splats.push(n),this._partialData.push(0,0))}for(let a=0;a<this.splats.length;a++)this._partialData[a*2+1]===0&&this.splats[a].ensureSubDrawTexture(r);return this.cameraNode=t,this.splats.length>0}execute(){const{device:e,splats:t,cameraNode:s,_partialData:i}=this;e.setDrawStates();const r=s.getWorldTransform(),a=sR.copy(r).invert();e.scope.resolve("matrix_view").setValue(a.data);for(let n=0;n<t.length;n++){const o=i[n*2+1];o>0?this.renderSplat(t[n],this._subDrawTexture,o,i[n*2]):this.renderSplat(t[n])}}renderSplat(e,t,s,i=0){const{device:r,resource:a}=e,n=r.scope,o=t??e.subDrawTexture,c=s??e.subDrawCount,h=e.getWorkBufferModifier?.()??null,d=a.format.hash,u=a.format.getInputDeclarations(),f=a.getWorkBufferRenderInfo(this.colorOnly,h,d,u,this.workBuffer.format);f.material.setParameters(r);const p=this.colorsByLod?.[e.lodIndex]??this.colorsByLod?.[0]??iR;n.resolve("uColorMultiply").setValue(p);const m=e.node.getWorldTransform();if(m.getScale(qh),Ma.setFromMat4(m),Ma.w<0&&Ma.mulScalar(-1),this._modelScaleData[0]=qh.x,this._modelScaleData[1]=qh.y,this._modelScaleData[2]=qh.z,this._modelRotationData[0]=Ma.x,this._modelRotationData[1]=Ma.y,this._modelRotationData[2]=Ma.z,this._modelRotationData[3]=Ma.w,n.resolve("matrix_model").setValue(m.data),n.resolve("model_scale").setValue(this._modelScaleData),n.resolve("model_rotation").setValue(this._modelRotationData),n.resolve("uId").setValue(e.placementId),e.parameters)for(const v of e.parameters.values())v.scopeId.setValue(v.data);const _=e.getInstanceStreams?.();if(_){_.syncWithFormat(e.resource.format);for(const[v,x]of _.textures)n.resolve(v).setValue(x)}n.resolve("uSubDrawData").setValue(o),n.resolve("uSubDrawBase").setValue(i);const g=this.workBuffer.textureSize;this._textureSize[0]=g,this._textureSize[1]=g,n.resolve("uTextureSize").setValue(this._textureSize),f.quadRender.render(void 0,void 0,c)}}class pu{device;format=null;textures=new Map;_textureDimensions=new j;_isInstance=!1;_formatVersion=-1;get textureDimensions(){return this._textureDimensions}constructor(e,t=!1){this.device=e,this._isInstance=t}destroy(){for(const e of this.textures.values())e.destroy();this.textures.clear()}init(e,t){this.format=e,this._textureDimensions=Xt.calcTextureSize(t,new j);const s=this._isInstance?e.instanceStreams:e.resourceStreams;for(const i of s){const r=this.createTexture(i.name,i.format,this._textureDimensions);this.textures.set(i.name,r)}this._formatVersion=e.extraStreamsVersion}getTexture(e){return this.syncWithFormat(this.format),this.textures.get(e)}getTexturesInOrder(){const e=[];if(this.format){const t=this._isInstance?this.format.instanceStreams:this.format.resourceStreams;for(const s of t){const i=this.textures.get(s.name);i&&e.push(i)}}return e}syncWithFormat(e){if(e){if(this.format===e&&this._formatVersion===e.extraStreamsVersion)return;this.format=e;const t=this._isInstance?e.instanceStreams:e.resourceStreams;for(const s of t)if(!this.textures.has(s.name)){const i=this.createTexture(s.name,s.format,this._textureDimensions);this.textures.set(s.name,i)}this._formatVersion=e.extraStreamsVersion}}resize(e,t){this._textureDimensions.set(e,t);for(const s of this.textures.values())s.resize(e,t)}createTexture(e,t,s,i){return ce.createDataTexture2D(this.device,e,s.x,s.y,t,i?[i]:void 0)}}let rR=0;class aR{material;quadRender;constructor(e,t,s,i,r){this.material=s;const a=new Map(s.defines),n=r.getStream("dataColor");n.format===Vi&&a.set("GSPLAT_COLOR_UINT",""),i&&a.set("GSPLAT_COLOR_ONLY",""),r.getStream("pcId")&&a.set("GSPLAT_ID","");const o=s.hasShaderChunks?e.isWebGPU?s.shaderChunks.wgsl:s.shaderChunks.glsl:void 0,c=i?[n]:[...r.streams,...r.extraStreams],h=[];
1559for(const p of c){const m=yd(p.format);h.push(m.returnType)}const d=a.has("GSPLAT_LOD"),u={uniqueName:`SplatCopyToWorkBuffer:${t}`,attributes:{vertex_position:Ie},vertexDefines:a,fragmentDefines:a,fragmentGLSL:ZM,fragmentWGSL:QM,fragmentIncludes:o,fragmentOutputTypes:h};d?(u.vertexGLSL=JM,u.vertexWGSL=eR):u.vertexChunk="fullscreenQuadVS";const f=Qt.createShader(e,u);this.quadRender=new Uo(f)}destroy(){this.material?.destroy(),this.quadRender?.destroy()}}class xy{device;format;id=rR++;streams;renderTarget;colorRenderTarget;orderTexture;orderBuffer;uploadStream;renderPass;colorRenderPass;frustumCuller;constructor(e,t){this.device=e,this.format=t,this.frustumCuller=new tR(e),this.streams=new pu(e),this.streams.init(t,1),this._createRenderTargets(),this.uploadStream=new xw(e,!e.isWebGPU),e.isWebGPU?this.orderBuffer=new Se(e,4,ct):this.orderTexture=new ce(e,{name:"SplatGlobalOrder",width:1,height:1,format:js,mipmaps:!1,addressU:ue,addressV:ue}),this.renderPass=new yy(e,this),this.renderPass.init(this.renderTarget),this.colorRenderPass=new yy(e,this,!0),this.colorRenderPass.init(this.colorRenderTarget)}_createRenderTargets(){this.renderTarget?.destroy(),this.colorRenderTarget?.destroy();const e=this.streams.getTexturesInOrder();this.renderTarget=new St({name:`GsplatWorkBuffer-MRT-${this.id}`,colorBuffers:e,depth:!1,flipY:!0});const t=this.streams.getTexture("dataColor");this.colorRenderTarget=new St({name:`GsplatWorkBuffer-Color-${this.id}`,colorBuffer:t,depth:!1,flipY:!0}),this.renderPass?.init(this.renderTarget),this.colorRenderPass?.init(this.colorRenderTarget)}syncWithFormat(){const e=this.streams._formatVersion;this.streams.syncWithFormat(this.format),e!==this.streams._formatVersion&&this._createRenderTargets()}getTexture(e){return this.streams.getTexture(e)}destroy(){this.renderPass?.destroy(),this.colorRenderPass?.destroy(),this.streams.destroy(),this.orderTexture?.destroy(),this.orderBuffer?.destroy(),this.renderTarget?.destroy(),this.colorRenderTarget?.destroy(),this.uploadStream.destroy(),this.frustumCuller.destroy()}get textureSize(){return this.streams.textureDimensions.x}setOrderData(e){this.textureSize,this.device.isWebGPU?this.uploadStream.upload(e,this.orderBuffer,0,e.length):this.uploadStream.upload(e,this.orderTexture,0,e.length)}resize(e){if(this.renderTarget.resize(e,e),this.colorRenderTarget.resize(e,e),this.streams.resize(e,e),this.device.isWebGPU){const t=e*e*4;this.orderBuffer.byteSize<t&&(this.orderBuffer.destroy(),this.orderBuffer=new Se(this.device,t,ct))}else this.orderTexture.resize(e,e)}render(e,t,s,i=null){this.renderPass.update(e,t,s,i)&&this.renderPass.render()}renderColor(e,t,s,i=null){this.colorRenderPass.update(e,t,s,i)&&this.colorRenderPass.render()}}class xc{static _cache=new Jt;_pendingDestroy=new Set;static queueDestroy(e,t){this._cache.get(e,()=>new xc)._pendingDestroy.add(t)}static process(e){const t=this._cache.get(e,()=>new xc)._pendingDestroy;for(const s of t)s.refCount===0&&(s._actualDestroy(),t.delete(s))}destroy(){this._pendingDestroy.clear()}}let nR=0;const Vn=new Map;class Rt{device;gsplatData;set centers(e){this._centers=e}get centers(){return this._centers}get hasCenters(){return this._centers!=null}_centers=null;centersVersion=0;aabb;mesh=null;id=nR++;workBufferRenderInfos=new Map;_format=null;streams;parameters=new Map;_refCount=0;_meshRefCount=0;constructor(e,t,s={}){this.device=e,this.gsplatData=t,this.streams=new pu(e),s.prepareCenters!==!1?this._centers=t.getCenters():this._centers=null,this.aabb=new Le,t.calcAabb(this.aabb)}destroy(){if(this.refCount>0){xc.queueDestroy(this.device,this);return}this._actualDestroy()}_actualDestroy(){this.streams.destroy(),this.mesh?.destroy(),this.workBufferRenderInfos.forEach(e=>e.destroy()),this.workBufferRenderInfos.clear()}incRefCount(){this._refCount++}decRefCount(){this._refCount--}get refCount(){return this._refCount}ensureMesh(){this.mesh||(this.mesh=Rt.createMesh(this.device),this.mesh.aabb.copy(this.aabb)),this._meshRefCount++}releaseMesh(){this._meshRefCount--,this._meshRefCount<1&&(this.mesh=null)}getWorkBufferRenderInfo(e,t,s,i,r){this.configureMaterialDefines(Vn),Vn.set("GSPLAT_LOD",""),e&&Vn.set("GSPLAT_COLOR_ONLY","");let a="";for(const[c,h]of Vn)a&&(a+=";"),a+=`${c}=${h}`;
1559const n=`${s};${r.hash};${t?.hash??0};${a}`;let o=this.workBufferRenderInfos.get(n);if(!o){const c=new ei;this.configureMaterial(c,t,i);const h=this.device.isWebGPU?c.shaderChunks.wgsl:c.shaderChunks.glsl,d=e?[r.getStream("dataColor")]:[...r.streams,...r.extraStreams];let u=r.getOutputDeclarations(d);e&&r.extraStreams.length>0&&(u+=` 1560${r.getOutputStubs(r.extraStreams)}`),h.set("gsplatWorkBufferOutputVS",u);const f=r.getWriteCode();f&&h.set("gsplatWriteVS",f),Vn.forEach((p,m)=>c.setDefine(m,p)),o=new aR(this.device,n,c,e,r),this.workBufferRenderInfos.set(n,o)}return Vn.clear(),o}static createMesh(e){const t=Rt.instanceSize,s=new Float32Array(12*t),i=new Uint32Array(6*t);for(let a=0;a<t;++a){s.set([-1,-1,a,1,-1,a,1,1,a,-1,1,a],a*12);const n=a*4;i.set([0+n,1+n,2+n,0+n,2+n,3+n],a*6)}const r=new at(e);return r.setPositions(s,3),r.setIndices(i),r.update(),r}static get instanceSize(){return 128}get numSplats(){return this.gsplatData.numSplats}get format(){return this._format}getTexture(e){return this.streams.getTexture(e)??null}get textureDimensions(){return this.streams.textureDimensions}configureMaterial(e,t,s){this.configureMaterialDefines(e.defines),this.streams.syncWithFormat(this.format);const i=this.device.isWebGPU?e.shaderChunks.wgsl:e.shaderChunks.glsl;i.set("gsplatDeclarationsVS",s),i.set("gsplatReadVS",this.format.getReadCode()),t?.code&&i.set("gsplatModifyVS",t.code);for(const[r,a]of this.streams.textures)e.setParameter(r,a);for(const[r,a]of this.parameters)e.setParameter(r,a);this.textureDimensions.x>0&&e.setParameter("splatTextureSize",this.textureDimensions.x)}configureMaterialDefines(e){}instantiate(){}}const Gn=new Z,Ty=new ae,jp=new Le,wy=new Le,oR=new Q(1,1,0,.4),qp=.28209479177387814;class lR{constructor(e,t,s,i,r){const a=e.getProp("x"),n=e.getProp("y"),o=e.getProp("z"),c=e.getProp("rot_1"),h=e.getProp("rot_2"),d=e.getProp("rot_3"),u=e.getProp("rot_0"),f=e.getProp("scale_0"),p=e.getProp("scale_1"),m=e.getProp("scale_2"),_=e.getProp("f_dc_0"),g=e.getProp("f_dc_1"),v=e.getProp("f_dc_2"),x=e.getProp("opacity"),y=S=>{if(S>0)return 1/(1+Math.exp(-S));const T=Math.exp(S);return T/(1+T)};this.read=S=>{t&&(t.x=a[S],t.y=n[S],t.z=o[S]),s&&s.set(c[S],h[S],d[S],u[S]),i&&i.set(Math.exp(f[S]),Math.exp(p[S]),Math.exp(m[S])),r&&r.set(.5+_[S]*qp,.5+g[S]*qp,.5+v[S]*qp,y(x[S]))}}}const Cy=(l,e,t)=>{Ty.set(t.x,t.y,t.z,t.w).normalize(),l.setTRS(e,Ty,E.ONE)};class ha{elements;numSplats;comments;constructor(e,t=[]){this.elements=e,this.numSplats=this.getElement("vertex").count,this.comments=t}static calcSplatAabb(e,t,s,i){Cy(Gn,t,s),jp.center.set(0,0,0),jp.halfExtents.set(i.x*2,i.y*2,i.z*2),e.setFromTransformedAabb(jp,Gn)}getProp(e,t="vertex"){return this.getElement(t)?.properties.find(s=>s.name===e)?.storage}getElement(e){return this.elements.find(t=>t.name===e)}addProp(e,t){this.getElement("vertex").properties.push({type:"float",name:e,storage:t,byteSize:4})}createIter(e,t,s,i){return new lR(this,e,t,s,i)}calcAabb(e,t){let s,i,r,a,n,o,c=!0;const h=this.getProp("x"),d=this.getProp("y"),u=this.getProp("z"),f=this.getProp("scale_0"),p=this.getProp("scale_1"),m=this.getProp("scale_2");for(let _=0;_<this.numSplats;++_){if(t&&!t(_))continue;const g=h[_],v=d[_],x=u[_],y=Math.max(f[_],p[_],m[_]);if(!isFinite(g)||!isFinite(v)||!isFinite(x)||!isFinite(y))continue;const S=2*Math.exp(y);c?(c=!1,s=g-S,i=v-S,r=x-S,a=g+S,n=v+S,o=x+S):(s=Math.min(s,g-S),i=Math.min(i,v-S),r=Math.min(r,x-S),a=Math.max(a,g+S),n=Math.max(n,v+S),o=Math.max(o,x+S))}return c||(e.center.set((s+a)*.5,(i+n)*.5,(r+o)*.5),e.halfExtents.set((a-s)*.5,(n-i)*.5,(o-r)*.5)),!c}calcAabbExact(e,t){const s=new E,i=new ae,r=new E,a=this.createIter(s,i,r);let n=!0;for(let o=0;o<this.numSplats;++o)t&&!t(o)||(a.read(o),n?(n=!1,ha.calcSplatAabb(e,s,i,r)):(ha.calcSplatAabb(wy,s,i,r),e.add(wy)));return!n}getCenters(){const e=this.getProp("x"),t=this.getProp("y"),s=this.getProp("z"),i=new Float32Array(this.numSplats*3);for(let r=0;r<this.numSplats;++r)i[r*3+0]=e[r],i[r*3+1]=t[r],i[r*3+2]=s[r];return i}calcFocalPoint(e,t){const s=this.getProp("x"),i=this.getProp("y"),r=this.getProp("z"),a=this.getProp("scale_0"),n=this.getProp("scale_1"),o=this.getProp("scale_2");e.x=0,e.y=0,e.z=0;let c=0;for(let h=0;h<this.numSplats;++h){if(t&&!t(h))continue;const d=s[h],u=i[h],f=r[h];if(!isFinite(d)||!isFinite(u)||!isFinite(f))continue;const p=1/(1+Math.exp(Math.max(a[h],n[h],o[h])));e.x+=d*p,e.y+=u*p,e.z+=f*p,c+=p}e.mulScalar(1/c)}renderWireframeBounds(e,t){const s=new E,i=new ae,r=new E,a=new E,n=new E,o=this.createIter(s,i,r);for(let c=0;c<this.numSplats;++c)o.read(c),Cy(Gn,s,i),Gn.mul2(t,Gn),a.set(r.x*-2,r.y*-2,r.z*-2),n.set(r.x*2,r.y*2,r.z*2),e.immediate.drawWireAlignedBox(a,n,oR,!0,e.defaultDrawLayer,Gn)}get isCompressed(){return!1}get shBands(){return{9:1,24:2,45:3}[(()=>{for(let s=0;s<45;++s)if(!this.getProp(`f_rest_${s}`))return s;return 45})()]??0}calcMortonOrder(){const e=x=>{let y=x[0],S=x[0];for(let T=1;T<x.length;T++)x[T]<y&&(y=x[T]),x[T]>S&&(S=x[T]);return{min:y,max:S}},t=(x,y,S)=>{const T=w=>(w&=1023,w=(w^w<<16)&4278190335,w=(w^w<<8)&50393103,w=(w^w<<4)&51130563,w=(w^w<<2)&153391689,w);return(T(S)<<2)+(T(y)<<1)+T(x)},s=this.getProp("x"),i=this.getProp("y"),r=this.getProp("z"),{min:a,max:n}=e(s),{min:o,max:c}
1560=e(i),{min:h,max:d}=e(r),u=a===n?0:1024/(n-a),f=o===c?0:1024/(c-o),p=h===d?0:1024/(d-h),m=new Map;for(let x=0;x<this.numSplats;x++){const y=Math.min(1023,Math.floor((s[x]-a)*u)),S=Math.min(1023,Math.floor((i[x]-o)*f)),T=Math.min(1023,Math.floor((r[x]-h)*p)),w=t(y,S,T),C=m.get(w);C?C.push(x):m.set(w,[x])}const _=Array.from(m.keys()).sort((x,y)=>x-y),g=new Uint32Array(this.numSplats);let v=0;for(let x=0;x<_.length;++x){const y=m.get(_[x]);for(let S=0;S<y.length;++S)g[v++]=y[S]}return g}reorder(e){const t=new Map,s=a=>{if(t.has(a)){const n=t.get(a);return t.delete(a),n}return new ArrayBuffer(a)},i=a=>{t.set(a.byteLength,a)},r=a=>{const n=new a.constructor(s(a.byteLength));for(let o=0;o<e.length;o++)n[o]=a[e[o]];return i(a.buffer),n};this.elements.forEach(a=>{a.properties.forEach(n=>{n.storage&&(n.storage=r(n.storage))})})}reorderData(){this.reorder(this.calcMortonOrder())}}const cR=` 1561 attribute vec2 vertex_position; 1562 void main(void) { 1563 gl_Position = vec4(vertex_position, 0.0, 1.0); 1564 } 1565`,hR=` 1566 #include "gsplatEvalSHVS" 1567 vec4 packRgb(vec3 v) { 1568 uvec3 vb = uvec3(clamp(v, vec3(0.0), vec3(1.0)) * vec3(2047.0, 2047.0, 1023.0)); 1569 uint bits = (vb.x << 21) | (vb.y << 10) | vb.z; 1570 return vec4((uvec4(bits) >> uvec4(24, 16, 8, 0)) & uvec4(0xff)) / vec4(255.0); 1571 } 1572 uniform mediump vec3 dir; 1573 uniform mediump sampler2D centroids; 1574 uniform mediump float shN_mins; 1575 uniform mediump float shN_maxs; 1576 void main(void) { 1577 ivec2 uv = ivec2(gl_FragCoord.xy) * ivec2(SH_COEFFS, 1); 1578 mediump vec3 coefficients[SH_COEFFS]; 1579 for (int i = 0; i < SH_COEFFS; i++) { 1580 vec3 s = texelFetch(centroids, ivec2(uv.x + i, uv.y), 0).xyz; 1581 coefficients[i] = mix(vec3(shN_mins), vec3(shN_maxs), s); 1582 } 1583 gl_FragColor = packRgb(evalSH(coefficients, dir) * 0.25 + 0.5); 1584 } 1585`,dR=` 1586 attribute vertex_position: vec2f; 1587 @vertex 1588 fn vertexMain(input: VertexInput) -> VertexOutput { 1589 var output: VertexOutput; 1590 output.position = vec4f(vertex_position, 0.0, 1.0); 1591 return output; 1592 } 1593`,uR=` 1594 #include "gsplatEvalSHVS" 1595 fn packRgb(v: vec3f) -> vec4f { 1596 let vb = vec3u(clamp(v, vec3f(0.0), vec3f(1.0)) * vec3f(2047.0, 2047.0, 1023.0)); 1597 let bits = dot(vb, vec3u(1 << 21, 1 << 10, 1)); 1598 return vec4f((vec4u(bits) >> vec4u(24, 16, 8, 0)) & vec4u(0xff)) / vec4f(255.0); 1599 } 1600 uniform dir: vec3f; 1601 uniform shN_mins: f32; 1602 uniform shN_maxs: f32; 1603 var centroids: texture_2d<f32>; 1604 @fragment 1605 fn fragmentMain(input: FragmentInput) -> FragmentOutput { 1606 var output: FragmentOutput; 1607 var uv = vec2i(input.position.xy) * vec2i(SH_COEFFS, 1); 1608 var coefficients: array<vec3f, SH_COEFFS>; 1609 for (var i: i32 = 0; i < SH_COEFFS; i++) { 1610 let s: vec3f = textureLoad(centroids, vec2i(uv.x + i, uv.y), 0).xyz; 1611 coefficients[i] = mix(vec3f(uniform.shN_mins), vec3f(uniform.shN_maxs), s); 1612 } 1613 output.color = packRgb(evalSH(&coefficients, uniform.dir) * 0.25 + 0.5); 1614 return output; 1615 } 1616`,fR=` 1617 uniform mediump sampler2D sh0; 1618 uniform highp sampler2D sh_labels; 1619 uniform mediump sampler2D sh_result; 1620 uniform vec4 sh0_mins; 1621 uniform vec4 sh0_maxs; 1622 float SH_C0 = 0.28209479177387814; 1623 vec3 unpackRgb(vec4 v) { 1624 uvec4 uv = uvec4(v * 255.0); 1625 uint bits = (uv.x << 24) | (uv.y << 16) | (uv.z << 8) | uv.w; 1626 uvec3 vb = (uvec3(bits) >> uvec3(21, 10, 0)) & uvec3(0x7ffu, 0x7ffu, 0x3ffu); 1627 return vec3(vb) / vec3(2047.0, 2047.0, 1023.0); 1628 } 1629 vec4 getColor(in SplatSource source) { 1630 vec4 baseSample = mix(sh0_mins, sh0_maxs, texelFetch(sh0, source.uv, 0)); 1631 vec4 base = vec4(vec3(0.5) + baseSample.xyz * SH_C0, 1.0 / (1.0 + exp(-baseSample.w))); 1632 ivec2 labelSample = ivec2(texelFetch(sh_labels, source.uv, 0).xy * 255.0); 1633 int n = labelSample.x + labelSample.y * 256; 1634 vec4 shSample = texelFetch(sh_result, ivec2(n % 64, n / 64), 0); 1635 vec3 sh = (unpackRgb(shSample) - vec3(0.5)) * 4.0; 1636 return vec4(base.xyz + sh, base.w); 1637 } 1638`,pR=` 1639 var sh0: texture_2d<f32>; 1640 var sh_labels: texture_2d<f32>; 1641 var sh_result: texture_2d<f32>; 1642 uniform sh0_mins: vec4f; 1643 uniform sh0_maxs: vec4f; 1644 const SH_C0: f32 = 0.28209479177387814; 1645 fn unpackRgb(v: vec4f) -> vec3f { 1646 let bits = dot(vec4u(v * 255.0), vec4u(1u << 24, 1u << 16, 1u << 8, 1u)); 1647 let vb = (vec3u(bits) >> vec3u(21, 10, 0)) & vec3u(0x7ffu, 0x7ffu, 0x3ffu); 1648 return vec3f(vb) / vec3f(2047.0, 2047.0, 1023.0); 1649 } 1650 fn getColor(source: ptr<function, SplatSource>) -> vec4f { 1651 let baseSample: vec4f = mix(uniform.sh0_mins, uniform.sh0_maxs, textureLoad(sh0, source.uv, 0)); 1652 let base = vec4f(vec3f(0.5) + baseSample.xyz * SH_C0, 1.0 / (1.0 + exp(-baseSample.w))); 1653 let labelSample: vec2i = vec2i(textureLoad(sh_labels, source.uv, 0).xy * 255.0); 1654 let n = labelSample.x + labelSample.y * 256; 1655 let shSample: vec4f = textureLoad(sh_result, vec2i(n % 64, n / 64), 0); 1656 let sh: vec3f = (unpackRgb(shSample) - vec3f(0.5)) * 4.0; 1657 return vec4f(base.xyz + sh, base.w); 1658 } 1659`,mR=(l,e)=>{for(const t in e)l.resolve(t).setValue(e[t])};class _R extends Pr{executeCallback=null;execute(){this.executeCallback?.()}}const Ey=new Z,Sl=new E;class gR{prevDir=new E;updateMode="enable";constructor(e,t){this.device=e,this.gsplatInstance=t;const{resource:s}=t;this.shader=Qt.createShader(e,{uniqueName:"gsplatResolveSH",vertexGLSL:cR,fragmentGLSL:hR,vertexWGSL:dR,fragmentWGSL:uR,fragmentDefines:new Map([["SH_BANDS",s.gsplatData.shBands.toString()]]),attributes:{vertex_position:Ie}}),this.texture=s.streams.createTexture("centroids",Re,new j(64,1024)),this.renderTarget=new St({colorBuffer:this.texture,depth:!1}
1659),this.renderPass=new _R(e),this.renderPass.init(this.renderTarget,{}),this.renderPass.colorOps.clear=!0,this.quadRender=new Uo(this.shader);const{material:i}=t;i.setDefine("SH_BANDS","0");const{shaderChunks:r}=i;r.glsl.set("gsplatSogColorVS",fR),r.wgsl.set("gsplatSogColorVS",pR),i.update(),e.scope.resolve("sh_result").setValue(this.texture)}destroy(){const{gsplatInstance:e}=this,{material:t}=e;t.setDefine("SH_BANDS",e.resource.gsplatData.shBands.toString());const{shaderChunks:s}=t;s.glsl.delete("gsplatSogColorVS"),s.wgsl.delete("gsplatSogColorVS"),t.update(),this.quadRender.destroy(),this.renderPass.destroy(),this.renderTarget.destroy(),this.texture.destroy(),this.shader.destroy()}render(e,t){const{prevDir:s,updateMode:i}=this;if(i==="disable"||(Ey.invert(t),Ey.transformVector(e.forward,Sl),Sl.normalize(),i==="enable"&&Sl.equalsApprox(s,.001)))return;s.copy(Sl);const r=()=>{const{device:a}=this,{sh_centroids:n,meta:o}=this.gsplatInstance.resource.gsplatData;mR(a.scope,{dir:Sl.toArray(),centroids:n,shN_mins:o.shN.mins,shN_maxs:o.shN.maxs}),a.setDrawStates(),this.quadRender.render()};this.renderPass.executeCallback=r,this.renderPass.render()}}function vR(){const l=typeof self<"u"&&self||require("node:worker_threads").parentPort;let e,t,s,i,r,a,n=!1;const o={x:0,y:0,z:0},c={x:0,y:0,z:0},h={x:0,y:0,z:0},d={x:0,y:0,z:0};let u,f;const p=32,m=new Array(p).fill(0),_=new Array(p).fill(0),g=new Array(p).fill(0),v=(y,S,T)=>{for(;y<=S;){const w=S+y>>1,C=T(w);if(C>0)y=w+1;else if(C<0)S=w-1;else return w}return~y},x=()=>{if(!e||!t||t.length===0||!r||!a)return;const y=performance.now(),S=r.x,T=r.y,w=r.z,C=a.x,b=a.y,I=a.z,P=.001;if(!n&&Math.abs(S-o.x)<P&&Math.abs(T-o.y)<P&&Math.abs(w-o.z)<P&&Math.abs(C-c.x)<P&&Math.abs(b-c.y)<P&&Math.abs(I-c.z)<P)return;n=!1,o.x=S,o.y=T,o.z=w,c.x=C,c.y=b,c.z=I;let L,O;for(let B=0;B<8;++B){const z=B&1?h.x:d.x,$=B&2?h.y:d.y,K=B&4?h.z:d.z,Y=z*C+$*b+K*I;B===0?L=O=Y:(L=Math.min(L,Y),O=Math.max(O,Y))}const D=t.length/3,k=2**Math.max(10,Math.min(20,Math.round(Math.log2(D/4))))+1;u?.length!==D&&(u=new Uint32Array(D)),!f||f.length!==k?f=new Uint32Array(k):f.fill(0);const A=O-L;if(A<1e-6)for(let B=0;B<D;++B)u[B]=0,f[0]++;else{const B=s.length/4;m.fill(0);for(let Y=0;Y<B;++Y){const te=s[Y*4+0],J=s[Y*4+1],_e=s[Y*4+2],Ae=s[Y*4+3],we=te*C+J*b+_e*I-L,$e=Math.max(0,Math.floor((we-Ae)*p/A)),Ye=Math.min(p,Math.ceil((we+Ae)*p/A));for(let Ee=$e;Ee<Ye;++Ee)m[Ee]++}const z=m.reduce((Y,te)=>Y+te,0);for(let Y=0;Y<p;++Y)g[Y]=m[Y]/z*k>>>0;for(let Y=0;Y<p;++Y)_[Y]=Y===0?0:_[Y-1]+g[Y-1];const $=A/p;let K=0;for(let Y=0;Y<D;++Y){const te=t[K++],J=t[K++],_e=t[K++],Ae=(te*C+J*b+_e*I-L)/$,we=Ae>>>0,$e=_[we]+g[we]*(Ae-we)>>>0;u[Y]=$e,f[$e]++}}for(let B=1;B<k;B++)f[B]+=f[B-1];for(let B=0;B<D;B++){const z=u[B],$=--f[z];e[$]=B}const M=S*C+T*b+w*I,R=B=>{let z=e[B]*3;return t[z++]*C+t[z++]*b+t[z]*I-M},F=()=>{const B=v(0,D-1,z=>-R(z));return Math.min(D,Math.abs(B))},U=R(D-1)>=0?F():D;if(i)for(let B=0;B<D;++B)e[B]=i[e[B]];l.postMessage({order:e.buffer,count:U,sortTime:performance.now()-y},[e.buffer]),e=null};l.addEventListener("message",y=>{const S=y.data??y;if(S.order&&(e=new Uint32Array(S.order)),S.centers)if(t=new Float32Array(S.centers),n=!0,S.chunks){const T=new Float32Array(S.chunks);s=new Float32Array(S.chunks,0,T.length*4/6),h.x=T[0],h.y=T[1],h.z=T[2],d.x=T[3],d.y=T[4],d.z=T[5];for(let w=0;w<T.length/6;++w){const C=T[w*6+0],b=T[w*6+1],I=T[w*6+2],P=T[w*6+3],L=T[w*6+4],O=T[w*6+5];s[w*4+0]=(C+P)*.5,s[w*4+1]=(b+L)*.5,s[w*4+2]=(I+O)*.5,s[w*4+3]=Math.sqrt((P-C)**2+(L-b)**2+(O-I)**2)*.5,C<h.x&&(h.x=C),b<h.y&&(h.y=b),I<h.z&&(h.z=I),P>d.x&&(d.x=P),L>d.y&&(d.y=L),O>d.z&&(d.z=O)}}else{const T=t.length/3,w=Math.ceil(T/256);s=new Float32Array(w*4),h.x=h.y=h.z=1/0,d.x=d.y=d.z=-1/0;let C,b,I,P,L,O;for(let D=0;D<w;++D){C=b=I=1/0,P=L=O=-1/0;const N=D*256,k=Math.min(T,(D+1)*256);for(let A=N;A<k;++A){const M=t[A*3+0],R=t[A*3+1],F=t[A*3+2],U=Number.isFinite(M),B=Number.isFinite(R),z=Number.isFinite(F);U||(t[A*3+0]=0),B||(t[A*3+1]=0),z||(t[A*3+2]=0),!(!U||!B||!z)&&(M<C?C=M:M>P&&(P=M),R<b?b=R:R>L&&(L=R),F<I?I=F:F>O&&(O=F),M<h.x?h.x=M:M>d.x&&(d.x=M),R<h.y?h.y=R:R>d.y&&(d.y=R),F<h.z?h.z=F:F>d.z&&(d.z=F))}s[D*4+0]=(C+P)*.5,s[D*4+1]=(b+L)*.5,s[D*4+2]=(I+O)*.5,s[D*4+3]=Math.sqrt((P-C)**2+(L-b)**2+(O-I)**2)*.5}}S.hasOwnProperty("mapping")&&(i=S.mapping?new Uint32Array(S.mapping):null,n=!0),S.cameraPosition&&(r=S.cameraPosition),S.cameraDirection&&(a=S.cameraDirection),x()})}class SR extends ge{worker;target;orderData;centers;scene;uploadStream;pendingSorted=null;constructor(e,t){super(),this.scene=t??null,this.uploadStream=new xw(e,!e.isWebGPU);const s=r=>{const a=r.data??r;this.scene&&a.sortTime!==void 0&&this.scene.fire("gsplat:sorted",a.sortTime);const n=a.order,o=this.orderData;this.worker.postMessage({order:o},[o]),this.orderData=n,this.pendingSorted={count:a.count,data:new Uint32Array(n)},this.fire("updated")},i=`(${vR.toString()})()`;Ce.environment==="node"?(this.worker=new Worker(i,{eval:!0}),this.worker.on("message",s)):(this.worker=new Worker(URL.createObjectURL(new Blob([i],{type:"application/javascript"}))),this.worker.addEventListener("message",s))}destroy(){this.worker.terminate(),this.worker=null,this.uploadStream.destroy(),this.uploadStream=null}init(e,t,s,i){this.target=e,this.centers=s.slice();
1659const r=new Uint32Array(t);for(let o=0;o<t;++o)r[o]=o;this.orderData=new ArrayBuffer(t*4);const a={order:r.buffer,centers:s.buffer,chunks:i?.buffer},n=[r.buffer,s.buffer].concat(i?[i.buffer]:[]);this.worker.postMessage(a,n)}applyPendingSorted(){if(this.pendingSorted){const{count:e,data:t}=this.pendingSorted;return this.pendingSorted=null,this.uploadStream.upload(t,this.target),e}return-1}setMapping(e){if(e){const t=new Float32Array(e.length*3);for(let s=0;s<e.length;++s){const i=e[s]*3,r=s*3;t[r+0]=this.centers[i+0],t[r+1]=this.centers[i+1],t[r+2]=this.centers[i+2]}this.worker.postMessage({centers:t.buffer,mapping:e.buffer},[t.buffer,e.buffer])}else{const t=this.centers.slice();this.worker.postMessage({centers:t.buffer,mapping:null},[t.buffer])}}setCamera(e,t){this.worker.postMessage({cameraPosition:{x:e.x,y:e.y,z:e.z},cameraDirection:{x:t.x,y:t.y,z:t.z}})}}var yR=` 1660#include "gsplatPackingPS" 1661uniform highp sampler2D means_l; 1662uniform highp sampler2D means_u; 1663uniform highp uint numSplats; 1664uniform highp vec3 means_mins; 1665uniform highp vec3 means_maxs; 1666void main(void) { 1667 int w = int(textureSize(means_l, 0).x); 1668 ivec2 uv = ivec2(gl_FragCoord.xy); 1669 if (uint(uv.x + uv.y * w) >= numSplats) { 1670 discard; 1671 } 1672 vec3 l = texelFetch(means_l, uv, 0).xyz; 1673 vec3 u = texelFetch(means_u, uv, 0).xyz; 1674 vec3 n = (l + u * 256.0) / 257.0; 1675 vec3 v = mix(means_mins, means_maxs, n); 1676 vec3 center = sign(v) * (exp(abs(v)) - 1.0); 1677 pcFragColor0 = uvec4(floatBitsToUint(center), 0u); 1678} 1679`,xR=` 1680var means_l: texture_2d<f32>; 1681var means_u: texture_2d<f32>; 1682uniform numSplats: u32; 1683uniform means_mins: vec3f; 1684uniform means_maxs: vec3f; 1685@fragment 1686fn fragmentMain(input: FragmentInput) -> FragmentOutput { 1687 var output: FragmentOutput; 1688 let w: u32 = textureDimensions(means_l, 0).x; 1689 let uv: vec2<i32> = vec2<i32>(input.position.xy); 1690 if (u32(uv.x + uv.y * i32(w)) >= uniform.numSplats) { 1691 discard; 1692 return output; 1693 } 1694 let l: vec3f = textureLoad(means_l, uv, 0).xyz; 1695 let u: vec3f = textureLoad(means_u, uv, 0).xyz; 1696 let n: vec3f = (l + u * 256.0) / 257.0; 1697 let v: vec3f = mix(uniform.means_mins, uniform.means_maxs, n); 1698 let center: vec3f = sign(v) * (exp(abs(v)) - 1.0); 1699 let packed: vec4<u32> = bitcast<vec4<u32>>(vec4f(center, 0.0)); 1700 output.color = packed; 1701 return output; 1702} 1703`;const lr=.28209479177387814,Gr=l=>l.device.isNull?new Promise(e=>{e(new Uint8Array(l.width*l.height*4))}):l.read(0,0,l.width,l.height,{mipLevel:0,face:0,immediate:!0}),TR=(l,e)=>{for(const t in e)l.resolve(t).setValue(e[t])};class wR{constructor(e,t,s,i,r,a){const n=(w,C,b)=>w*(1-b)+C*b,{meta:o,shBands:c}=e,{means:h,scales:d,sh0:u,shN:f}=o,p=t&&e.means_l._levels[0],m=t&&e.means_u._levels[0],_=s&&e.quats._levels[0],g=i&&e.scales._levels[0],v=r&&e.sh0._levels[0],x=a&&e.sh_labels._levels[0],y=a&&e.sh_centroids._levels[0],S=Math.SQRT2,T={1:3,2:8,3:15}[c]??0;this.read=w=>{if(t){const C=n(h.mins[0],h.maxs[0],((m[w*4+0]<<8)+p[w*4+0])/65535),b=n(h.mins[1],h.maxs[1],((m[w*4+1]<<8)+p[w*4+1])/65535),I=n(h.mins[2],h.maxs[2],((m[w*4+2]<<8)+p[w*4+2])/65535);t.x=Math.sign(C)*(Math.exp(Math.abs(C))-1),t.y=Math.sign(b)*(Math.exp(Math.abs(b))-1),t.z=Math.sign(I)*(Math.exp(Math.abs(I))-1)}if(s){const C=(_[w*4+0]/255-.5)*S,b=(_[w*4+1]/255-.5)*S,I=(_[w*4+2]/255-.5)*S,P=Math.sqrt(Math.max(0,1-(C*C+b*b+I*I)));switch(_[w*4+3]-252){case 0:s.set(C,b,I,P);break;case 1:s.set(P,b,I,C);break;case 2:s.set(b,P,I,C);break;case 3:s.set(b,I,P,C);break}}if(i)if(o.version===2){const C=d.codebook[g[w*4+0]],b=d.codebook[g[w*4+1]],I=d.codebook[g[w*4+2]];i.set(C,b,I)}else{const C=n(d.mins[0],d.maxs[0],g[w*4+0]/255),b=n(d.mins[1],d.maxs[1],g[w*4+1]/255),I=n(d.mins[2],d.maxs[2],g[w*4+2]/255);i.set(C,b,I)}if(r)if(o.version===2){const C=u.codebook[v[w*4+0]],b=u.codebook[v[w*4+1]],I=u.codebook[v[w*4+2]],P=v[w*4+3]/255;r.set(.5+C*lr,.5+b*lr,.5+I*lr,P)}else{const C=n(u.mins[0],u.maxs[0],v[w*4+0]/255),b=n(u.mins[1],u.maxs[1],v[w*4+1]/255),I=n(u.mins[2],u.maxs[2],v[w*4+2]/255),P=n(u.mins[3],u.maxs[3],v[w*4+3]/255);r.set(.5+C*lr,.5+b*lr,.5+I*lr,1/(1+Math.exp(-P)))}if(a){const C=x[w*4+0]+(x[w*4+1]<<8),b=C%64*T,I=Math.floor(C/64);if(o.version===2)for(let P=0;P<3;++P)for(let L=0;L<T;++L)a[P*15+L]=f.codebook[y[(b+L)*4+P+I*e.sh_centroids.width*4]];else for(let P=0;P<3;++P)for(let L=0;L<T;++L)a[P*15+L]=n(f.mins,f.maxs,y[(b+L)*4+P+I*e.sh_centroids.width*4]/255)}}}}class Tc{meta;numSplats;means_l;means_u;quats;scales;sh0;sh_centroids;sh_labels;codebookTexture=null;url="";_centers=null;destroyed=!1;shBands=0;_destroyGpuResources(){this.means_l?.destroy(),this.means_u?.destroy(),this.quats?.destroy(),this.scales?.destroy(),this.sh0?.destroy(),this.sh_centroids?.destroy(),this.sh_labels?.destroy(),this.codebookTexture?.destroy(),this.codebookTexture=null}static calcBands(e){return{192:1,512:2,960:3}[e]??0}destroy(){this.destroyed=!0,this._destroyGpuResources()}createIter(e,t,s,i,r){return new wR(this,e,t,s,i,r)}calcAabb(e){const{mins:t,maxs:s}=this.meta.means,i=r=>Math.sign(r)*(Math.exp(Math.abs(r))-1);e.center.set((i(t[0])+i(s[0]))*.5,(i(t[1])+i(s[1]))*.5,(i(t[2])+i(s[2]))*.5),e.halfExtents.set((i(s[0])-i(t[0]))*.5,(i(s[1])-i(t[1]))*.5,(i(s[2])-i(t[2]))*.5)}getCenters(){const e=this._centers;return this._centers=null,e}calcFocalPoint(e,t){const{mins:s,maxs:i}=this.meta.means,r=a=>
1703Math.sign(a)*(Math.exp(Math.abs(a))-1);e.set((r(s[0])+r(i[0]))*.5,(r(s[1])+r(i[1]))*.5,(r(s[2])+r(i[2]))*.5)}get isSog(){return!0}async decompress(){const e=["x","y","z","f_dc_0","f_dc_1","f_dc_2","opacity","scale_0","scale_1","scale_2","rot_0","rot_1","rot_2","rot_3"];this._patchCodebooks();const{shBands:t}=this,{means_l:s,means_u:i,quats:r,scales:a,sh0:n,sh_labels:o,sh_centroids:c}=this;if(s._levels[0]=await Gr(s),i._levels[0]=await Gr(i),r._levels[0]=await Gr(r),a._levels[0]=await Gr(a),n._levels[0]=await Gr(n),t>0){o._levels[0]=await Gr(o),c._levels[0]=await Gr(c);const g=[];for(let v=0;v<45;++v)g.push(`f_rest_${v}`);e.splice(e.indexOf("f_dc_0")+1,0,...g)}const h={};e.forEach(g=>{h[g]=new Float32Array(this.numSplats)});const d=new E,u=new ae,f=new E,p=new ie,m=t>0?new Float32Array(45):null,_=this.createIter(d,u,f,p,m);for(let g=0;g<this.numSplats;++g)if(_.read(g),h.x[g]=d.x,h.y[g]=d.y,h.z[g]=d.z,h.rot_1[g]=u.x,h.rot_2[g]=u.y,h.rot_3[g]=u.z,h.rot_0[g]=u.w,h.scale_0[g]=f.x,h.scale_1[g]=f.y,h.scale_2[g]=f.z,h.f_dc_0[g]=(p.x-.5)/lr,h.f_dc_1[g]=(p.y-.5)/lr,h.f_dc_2[g]=(p.z-.5)/lr,h.opacity[g]=p.w<=0?-40:p.w>=1?40:-Math.log(1/p.w-1),m)for(let v=0;v<45;++v)h[`f_rest_${v}`][g]=m[v];return new ha([{name:"vertex",count:this.numSplats,properties:e.map(g=>({name:g,type:"float",byteSize:4,storage:h[g]}))}])}async generateCenters(){const{device:e,width:t,height:s}=this.means_l,{scope:i}=e,r=new ce(e,{name:"sogCentersTexture",width:t,height:s,format:Wt,mipmaps:!1}),a=Qt.createShader(e,{uniqueName:"GsplatSogCentersShader",attributes:{vertex_position:Ie},vertexChunk:"fullscreenQuadVS",fragmentGLSL:yR,fragmentWGSL:xR,fragmentOutputTypes:["uvec4"]}),n=new St({colorBuffer:r,depth:!1,mipLevel:0});TR(i,{means_l:this.means_l,means_u:this.means_u,numSplats:this.numSplats,means_mins:this.meta.means.mins,means_maxs:this.meta.means.maxs});const o=new Uo(a),c=new UT(e,o);c.name="SogGenerateCenters",c.init(n),c.colorOps.clear=!1,c.depthStencilOps.clearDepth=!1,c.render(),o.destroy(),n.destroy();const h=await Gr(r);if(this.destroyed||e._destroyed){r.destroy();return}const d=new Float32Array(h.buffer),u=new Float32Array(this.numSplats*3);for(let f=0;f<this.numSplats;f++){const p=f*4;u[f*3+0]=d[p+0],u[f*3+1]=d[p+1],u[f*3+2]=d[p+2]}this._centers=u,r.destroy()}_createCodebookTexture(){const e=this.means_l.device,{scales:t,sh0:s,shN:i}=this.meta,r=t.codebook,a=s.codebook,n=i?.codebook,o=new Float32Array(256*4);for(let h=0;h<256;h++)o[h*4]=r[h];for(let h=0;h<256;h++)o[h*4+1]=a[h];if(n)for(let h=0;h<256;h++)o[h*4+2]=n[h];const c=this.url?`_${this.url}`:"";this.codebookTexture=new ce(e,{name:`sogCodebook${c}`,width:256,height:1,format:mt,mipmaps:!1,minFilter:Fe,magFilter:Fe,addressU:ue,addressV:ue,levels:[o]})}_patchCodebooks(){["scales","sh0","shN"].forEach(e=>{const t=this.meta[e]?.codebook;t?.[0]===null&&(t[0]=t[1]+(t[1]-t[255])/255)})}prepareCodebook(){const e=this.means_l?.device;this.destroyed||!e||e._destroyed||(this._patchCodebooks(),this.meta.version===2&&this._createCodebookTexture())}async prepareGpuData(){const e=this.means_l?.device;this.destroyed||!e||e._destroyed||await this.generateCenters()}}const CR=new Z,Hn=new E,Wn=new E;class ER{resource;orderTexture;orderBuffer;_material;meshInstance;options={};sorter=null;lastCameraPosition=new E;lastCameraDirection=new E;resolveSH=null;cameras=[];constructor(e,t={}){this.resource=e;const s=e.device,i=e.streams.textureDimensions,r=i.x*i.y;if(s.isWebGPU?this.orderBuffer=new Se(s,r*4,ct):this.orderTexture=e.streams.createTexture("splatOrder",js,i),t.material?(this._material=t.material,this._material.setDefine("{GSPLAT_INSTANCE_SIZE}",String(Rt.instanceSize)),this.setMaterialOrderData(this._material),this._material.setParameter("alphaClipForward",1/255)):(this._material=new ei({uniqueName:"SplatMaterial",vertexGLSL:'#include "gsplatVS"',fragmentGLSL:'#include "gsplatPS"',vertexWGSL:'#include "gsplatVS"',fragmentWGSL:'#include "gsplatPS"',attributes:{vertex_position:Ie}}),this.configureMaterial(this._material),this._material.update()),e.ensureMesh(),this.meshInstance=new Ne(e.mesh,this._material),this.meshInstance.setInstancing(!0,!0),this.meshInstance.gsplatInstance=this,this.meshInstance.instancingCount=0,e.hasCenters){const a=e.centers.slice(),n=e.chunks?.slice(),o=this.orderBuffer??this.orderTexture;
1703this.sorter=new SR(s,t.scene),this.sorter.init(o,r,a,n)}this.setHighQualitySH(t.highQualitySH??!1)}destroy(){this.resource?.releaseMesh(),this.orderTexture?.destroy(),this.orderBuffer?.destroy(),this.resolveSH?.destroy(),this.material?.destroy(),this.meshInstance?.destroy(),this.sorter?.destroy()}setMaterialOrderData(e){this.orderBuffer?e.setParameter("splatOrder",this.orderBuffer):(e.setParameter("splatOrder",this.orderTexture),e.setParameter("splatTextureSize",this.orderTexture.width))}set material(e){this._material!==e&&(this._material=e,this._material.setDefine("{GSPLAT_INSTANCE_SIZE}",String(Rt.instanceSize)),this.setMaterialOrderData(this._material),this._material.setParameter("alphaClipForward",1/255),this.meshInstance&&(this.meshInstance.material=e))}get material(){return this._material}configureMaterial(e,t={}){this.resource.configureMaterial(e,null,this.resource.format.getInputDeclarations()),e.setDefine("{GSPLAT_INSTANCE_SIZE}",Rt.instanceSize),e.setParameter("numSplats",0),this.setMaterialOrderData(e),e.setParameter("alphaClip",.3),e.setParameter("alphaClipForward",1/255),e.setParameter("minPixelSize",2),e.setDefine(`DITHER_${t.dither?"BLUENOISE":"NONE"}`,""),e.cull=Yt,e.blendType=t.dither?Ns:Ui,e.depthWrite=!!t.dither}sort(e){if(this.sorter){const t=e.getWorldTransform();t.getTranslation(Hn),t.getZ(Wn);const s=this.meshInstance.node.getWorldTransform(),i=CR.invert(s);i.transformPoint(Hn,Hn),i.transformVector(Wn,Wn),(!Hn.equalsApprox(this.lastCameraPosition)||!Wn.equalsApprox(this.lastCameraDirection))&&(this.lastCameraPosition.copy(Hn),this.lastCameraDirection.copy(Wn),this.sorter.setCamera(Hn,Wn
1703))}}update(){const e=this.sorter?.applyPendingSorted()??-1;if(e>=0&&(this.meshInstance.instancingCount=Math.ceil(e/Rt.instanceSize),this.material.setParameter("numSplats",e)),this.cameras.length>0){const t=this.cameras[0];this.sort(t._node),this.resolveSH?.render(t._node,this.meshInstance.node.getWorldTransform()),this.cameras.length=0}}setHighQualitySH(e){const{resource:t}=this,{gsplatData:s}=t;s instanceof Tc&&s.shBands>0&&e===!!this.resolveSH&&(this.resolveSH?(this.resolveSH.destroy(),this.resolveSH=null):this.resolveSH=new gR(t.device,this))}}const bR=(l,e)=>{const t=[];for(let s=0;s<e;++s)t.push(l.getProp(`f_rest_${s}`));return t};class Ff extends Rt{shBands;constructor(e,t,s={}){super(e,t,s);const i=t.numSplats;this.shBands=t.shBands;const r=[{name:"splatColor",format:Ge},{name:"transformA",format:Wt},{name:"transformB",format:Ge}];this.shBands>0&&(r.push({name:"splatSH_1to3",format:Wt}),this.shBands>1&&(r.push({name:"splatSH_4to7",format:Wt}),this.shBands>2?(r.push({name:"splatSH_8to11",format:Wt}),r.push({name:"splatSH_12to15",format:Wt})):r.push({name:"splatSH_8to11",format:js}))),this._format=new ca(e,r,{readGLSL:'#include "gsplatUncompressedVS"',readWGSL:'#include "gsplatUncompressedVS"'}),this.streams.init(this.format,i),this.updateColorData(t),this.updateTransformData(t),this.shBands>0&&this.updateSHData(t)}configureMaterialDefines(e){e.set("SH_BANDS",this.shBands)}updateColorData(e){const t=this.streams.getTexture("splatColor");if(!t)return;const s=Ja.float2Half,i=t.lock(),r=e.getProp("f_dc_0"),a=e.getProp("f_dc_1"),n=e.getProp("f_dc_2"),o=e.getProp("opacity"),c=.28209479177387814;for(let h=0;h<this.numSplats;++h){const d=r[h]*c+.5,u=a[h]*c+.5,f=n[h]*c+.5,p=1/(1+Math.exp(-o[h]));i[h*4+0]=s(d),i[h*4+1]=s(u),i[h*4+2]=s(f),i[h*4+3]=s(p)}t.unlock()}updateTransformData(e){const t=Ja.float2Half,s=this.streams.getTexture("transformA"),i=this.streams.getTexture("transformB");if(!s)return;const r=s.lock(),a=new Float32Array(r.buffer),n=i.lock(),o=new E,c=new ae,h=new E,d=e.createIter(o,c,h);for(let u=0;u<this.numSplats;u++)d.read(u),c.normalize(),c.w<0&&c.mulScalar(-1),a[u*4+0]=o.x,a[u*4+1]=o.y,a[u*4+2]=o.z,r[u*4+3]=t(c.x)|t(c.y)<<16,n[u*4+0]=t(h.x),n[u*4+1]=t(h.y),n[u*4+2]=t(h.z),n[u*4+3]=t(c.z);s.unlock(),i.unlock()}updateSHData(e){const t=this.streams.getTexture("splatSH_1to3"),s=this.streams.getTexture("splatSH_4to7"),i=this.streams.getTexture("splatSH_8to11"),r=this.streams.getTexture("splatSH_12to15"),a=t.lock(),n=s?.lock(),o=i?.lock(),c=r?.lock(),h={1:3,2:8,3:15}[this.shBands],d=bR(e,h*3),u=2047,f=1023,p=new Float32Array(1),m=new Uint32Array(p.buffer),_=new Array(h*3).fill(0);for(let g=0;g<e.numSplats;++g){for(let x=0;x<h;++x)_[x*3]=d[x][g],_[x*3+1]=d[x+h][g],_[x*3+2]=d[x+h*2][g];let v=_[0];for(let x=1;x<h*3;++x)v=Math.max(v,Math.abs(_[x]));if(v!==0){for(let x=0;x<h;++x)_[x*3+0]=Math.max(0,Math.min(u,Math.floor((_[x*3+0]/v*.5+.5)*u+.5))),_[x*3+1]=Math.max(0,Math.min(f,Math.floor((_[x*3+1]/v*.5+.5)*f+.5))),_[x*3+2]=Math.max(0,Math.min(u,Math.floor((_[x*3+2]/v*.5+.5)*u+.5)));p[0]=v,a[g*4+0]=m[0],a[g*4+1]=_[0]<<21|_[1]<<11|_[2],a[g*4+2]=_[3]<<21|_[4]<<11|_[5],a[g*4+3]=_[6]<<21|_[7]<<11|_[8],this.shBands>1&&(n[g*4+0]=_[9]<<21|_[10]<<11|_[11],n[g*4+1]=_[12]<<21|_[13]<<11|_[14],n[g*4+2]=_[15]<<21|_[16]<<11|_[17],n[g*4+3]=_[18]<<21|_[19]<<11|_[20],this.shBands>2?(o[g*4+0]=_[21]<<21|_[22]<<11|_[23],o[g*4+1]=_[24]<<21|_[25]<<11|_[26],o[g*4+2]=_[27]<<21|_[28]<<11|_[29],o[g*4+3]=_[30]<<21|_[31]<<11|_[32],c[g*4+0]=_[33]<<21|_[34]<<11|_[35],c[g*4+1]=_[36]<<21|_[37]<<11|_[38],c[g*4+2]=_[39]<<21|_[40]<<11|_[41],c[g*4+3]=_[42]<<21|_[43]<<11|_[44]):o[g]=_[21]<<21|_[22]<<11|_[23])}}t.unlock(),s?.unlock(),i?.unlock(),r?.unlock()}}class Tw extends Rt{constructor(e,t,s={}){super(e,t,s);const{meta:i,means_l:r}=t,a=i.version===2,n=t.shBands>0;r&&this.streams.textureDimensions.set(r.width,r.height),this.streams.textures.set("means_l",t.means_l),this.streams.textures.set("means_u",t.means_u),this.streams.textures.set("quats",t.quats),this.streams.textures.set("scales",t.scales),this.streams.textures.set("sh0",t.sh0),n&&(this.streams.textures.set("sh_labels",t.sh_labels),this.streams.textures.set("sh_centroids",t.sh_centroids)),a&&this.streams.textures.set("sogCodebook",t.codebookTexture);const o=[{name:"means_l",format:Re},{name:"means_u",format:Re},{name:"quats",format:Re},{name:"scales",format:Re},{name:"sh0",format:Re}];n&&(o.push({name:"sh_labels",format:Re}),o.push({name:"sh_centroids",format:Re}
1703)),a&&o.push({name:"sogCodebook",format:mt}),this._format=new ca(e,o,{readGLSL:'#include "gsplatSogVS"',readWGSL:'#include "gsplatSogVS"'}),this._populateParameters()}releaseTextureSources(){const e=this.gsplatData;e.means_l?.setReleaseSourceAfterUpload(),e.means_u?.setReleaseSourceAfterUpload(),e.quats?.setReleaseSourceAfterUpload(),e.scales?.setReleaseSourceAfterUpload(),e.sh0?.setReleaseSourceAfterUpload(),e.sh_centroids?.setReleaseSourceAfterUpload(),e.sh_labels?.setReleaseSourceAfterUpload()}_actualDestroy(){this.streams.textures.delete("means_l"),this.streams.textures.delete("means_u"),this.streams.textures.delete("quats"),this.streams.textures.delete("scales"),this.streams.textures.delete("sh0"),this.streams.textures.delete("sh_labels"),this.streams.textures.delete("sh_centroids"),this.streams.textures.delete("sogCodebook"),this.gsplatData.destroy(),super._actualDestroy()}_populateParameters(){const{meta:e}=this.gsplatData;e.means&&(this.parameters.set("means_mins",e.means.mins),this.parameters.set("means_maxs",e.means.maxs)),e.version!==2&&(e.scales&&(this.parameters.set("scales_mins",e.scales.mins),this.parameters.set("scales_maxs",e.scales.maxs)),e.sh0&&(this.parameters.set("sh0_mins",e.sh0.mins),this.parameters.set("sh0_maxs",e.sh0.maxs)),e.shN&&(this.parameters.set("shN_mins",e.shN.mins),this.parameters.set("shN_maxs",e.shN.maxs)))}configureMaterialDefines(e){const t=this.gsplatData;e.set("SH_BANDS",t.shBands),t.meta.version===2&&e.set("SOG_V2","")}}const AR="NONE",PR="FILL_WINDOW",by="KEEP_ASPECT",n_="AUTO",IR="FIXED";let ww;function yi(){return ww}function $p(l){ww=l}class DR{renderPasses=[];renderTargetMap=new Map;multiview=null;beginMultiView(e){this.multiview=new s_(e)}endMultiView(){const e=this.multiview;this.multiview=null,e?.children.length&&this.renderPasses.push(e)}addRenderPass(e){e.frameUpdate();const t=e.beforePasses;for(let i=0;i<t.length;i++){const r=t[i];r.enabled&&this.addRenderPass(r)}e.enabled&&(this.multiview?this.multiview.addChild(e):this.renderPasses.push(e));const s=e.afterPasses;for(let i=0;i<s.length;i++){const r=s[i];r.enabled&&this.addRenderPass(r)}}reset(){this.renderPasses.length=0}compile(){this._compilePasses(this.renderPasses);for(let e=0;e<this.renderPasses.length;e++){const t=this.renderPasses[e];t instanceof s_&&this._compilePasses(t.children)}}_compilePasses(e){const t=this.renderTargetMap;for(let r=0;r<e.length;r++){const a=e[r];a._skipStart=!1,a._skipEnd=!1;const n=a.renderTarget;if(n!==void 0){const o=t.get(n);if(o){const c=a.colorArrayOps.length;for(let h=0;h<c;h++)a.colorArrayOps[h].clear||(o.colorArrayOps[h].store=!0);a.depthStencilOps.clearDepth||(o.depthStencilOps.storeDepth=!0),a.depthStencilOps.clearStencil||(o.depthStencilOps.storeStencil=!0)}t.set(n,a)}}for(let r=0;r<e.length-1;r++){const a=e[r],n=a.renderTarget,o=e[r+1],c=o.renderTarget;n!==c||n===void 0||o.depthStencilOps.clearDepth||o.depthStencilOps.clearStencil||o.colorArrayOps.some(h=>h.clear)||a.afterPasses.length>0||o.beforePasses.length>0||(a._skipEnd=!0,o._skipStart=!0)}let s=null,i=null;for(let r=0;r<e.length;r++){const a=e[r],n=a.renderTarget,o=n?.colorBuffer;if(o?.cubemap){if(s===o){const c=i.colorArrayOps.length;for(let h=0;h<c;h++)i.colorArrayOps[h].mipmaps=!1}s=n.colorBuffer,i=a}else a.requiresCubemaps&&(s=null,i=null)}t.clear()}render(e){this.compile();const t=this.renderPasses;for(let s=0;s<t.length;s++)t[s].render()}}class MR{constructor(e,t){this.texture0=e,this.texture1=t}destroy(){this.texture0?.destroy(),this.texture1?.destroy()}}const Ay=new Jt;class Ha{static createTexture(e,t,s,i=""){return new ce(e,{name:`AreaLightLUT${i}`,width:s,height:s,format:t,addressU:ue,addressV:ue,type:Qs,magFilter:It,minFilter:Fe,anisotropy:1,mipmaps:!1})}static applyTextures(e,t,s){Ay.remove(e),Ay.get(e,()=>new MR(t,t===s?null:s)),e.scope.resolve("areaLightsLutTex1").setValue(t),e.scope.resolve("areaLightsLutTex2").setValue(s)}static createPlaceholder(e){const t=Ha.createTexture(e,Ge,2,"placeholder");t.lock().fill(0),t.unlock(),Ha.applyTextures(e,t,t)}static set(e,t,s){function i(u,f,p){const m=Ha.createTexture(u,p,64);return m.lock().set(f),m.unlock(),m}function r(u){const f=u.length,p=new Uint16Array(f),m=Ja.float2Half;for(let _=0;_<f;_++)p[_]=m(u[_]);return p}const a=t,n=s,o=r(a),c=r(n),h=i(e,o,Ge),d=i(e,c,Ge);Ha.applyTextures(e,h,d)}}const mu="en-US",_u={en:"en-US",es:"en-ES",zh:"zh-CN","zh-HK":"zh-TW","zh-TW":"zh-HK","zh-MO":"zh-HK",fr:"fr-FR",de:"de-DE",it:"it-IT",ru:"ru-RU",ja:"ja-JP"},Yg={};function _a(l,e){for(let t=0,s=l.length;t<s;t++)Yg[l[t]]=e}function ar(l){const e=l.indexOf("-");return e!==-1?l.substring(0,e):l}function RR(l,e){const t=l.indexOf("-");return t!==-1?e+l.substring(t):e}function Cw(l,e){if(e[l])return l;let t=_u[l];if(t&&e[t])return t;const s=ar(l);return t=_u[s],e[t]?t:e[s]?s:mu}_a(["ja","ko","th","vi","zh","id"],l=>0);_a(["fa","hi"],l=>l>=0&&l<=1?0:1);_a(["fr","pt"],l=>l>=0&&l<2?0:1);_a(["da"],l=>l===1||!Number.isInteger(l)&&l>=0&&l<=1?0:1);_a(["de","en","it","el","es","tr","fi","sv","nb","no","ur"],l=>l===1?0:1);_a(["ru","uk"],l=>{if(Number.isInteger(l)){const e=l%10,t=l%100;if(e===1&&t!==11)return 0;if(e>=2&&e<=4&&(t<12||t>14))return 1;if(e===0||e>=5&&e<=9||t>=11&&t<=14)return 2}return 3});_a(["pl"],l=>{if(Number.isInteger(l)){if(l===1)return 0;const e=l%10,t=l%100;if(e>=2&&e<=4&&(t<12||t>14))return 1;if(e>=0&&e<=1||e>=5&&e<=9||t>=12&&t<=14)return 2}return 3});_a(["ar"],l=>{if(l===0)return 0;if(l===1)return 1;if(l===2)return 2;if(Number.isInteger(l)){const e=l%100;if(e>=3&&e<=10)return 3;if(e>=11&&e<=99)return 4}return 5});const LR=Yg[ar(mu)];function Kp(l){return Yg[l]||LR}
1703const Vo=new RegExp("^\\s*(?:(?:[a-z]+[a-z0-9\\-+.]*:)?//|data:|blob:)","i");class FR{constructor(e="",t="",s=null,i=null,r=null,a=null){this.url=e,this.filename=t,this.hash=s,this.size=i,this.opt=r,this.contents=a}equals(e){return this.url===e.url&&this.filename===e.filename&&this.hash===e.hash&&this.size===e.size&&this.opt===e.opt&&this.contents===e.contents}}let OR=-1;const BR={pvr:"extCompressedTexturePVRTC",dxt:"extCompressedTextureS3TC",etc2:"extCompressedTextureETC",etc1:"extCompressedTextureETC1",basis:"canvas"},Py=["pvr","dxt","etc2","etc1","basis"];class pe extends ge{static EVENT_LOAD="load";static EVENT_UNLOAD="unload";static EVENT_REMOVE="remove";static EVENT_ERROR="error";static EVENT_CHANGE="change";static EVENT_PROGRESS="progress";static EVENT_ADDLOCALIZED="add:localized";static EVENT_REMOVELOCALIZED="remove:localized";_file=null;_i18n={};_preload=!1;_resources=[];id=OR--;loaded=!1;loading=!1;options={};registry=null;tags=new Mx(this);type;urlObject=null;constructor(e,t,s,i={},r={}){super(),this._name=e||"",this.type=t,this._data=i||{},this.options=r||{},s&&(this.file=s)}set name(e){if(this._name===e)return;const t=this._name;this._name=e,this.fire("name",this,this._name,t)}get name(){return this._name}set file(e){if(e&&e.variants&&["texture","textureatlas","bundle"].indexOf(this.type)!==-1){const i=this.registry?._loader?._app||yi(),r=i?.graphicsDevice;if(r)for(let a=0,n=Py.length;a<n;a++){const o=Py[a];if(e.variants[o]&&r[BR[o]]){e=e.variants[o];break}if(i.enableBundles){const c=i.bundles.listBundlesForAsset(this);if(c&&c.find(h=>h?.file?.variants[o]))break}}}const t=this._file,s=e?new FR(e.url,e.filename,e.hash,e.size,e.opt,e.contents):null;(!!s!=!!t||s&&!s.equals(t))&&(this._file=s,this.fire("change",this,"file",s,t),this.reload())}get file(){return this._file}set data(e){const t=this._data;this._data=e,e!==t&&(this.fire("change",this,"data",e,t),this.loaded&&this.registry._loader.patch(this,this.registry))}get data(){return this._data}set resource(e){const t=this._resources[0];this._resources[0]=e,this.fire("change",this,"resource",e,t)}get resource(){return this._resources[0]}set resources(e){const t=this._resources;this._resources=e,this.fire("change",this,"resources",e,t)}get resources(){return this._resources}set preload(e){e=!!e,this._preload!==e&&(this._preload=e,this._preload&&!this.loaded&&!this.loading&&this.registry&&this.registry.load(this))}get preload(){return this._preload}set loadFaces(e){e=!!e,(!this.hasOwnProperty("_loadFaces")||e!==this._loadFaces)&&(this._loadFaces=e,this.loaded&&this.registry._loader.patch(this,this.registry))}get loadFaces(){return this._loadFaces}getFileUrl(){const e=this.file;if(!e||!e.url)return null;let t=e.url;if(this.registry&&this.registry.prefix&&!Vo.test(t)&&(t=this.registry.prefix+t),this.type!=="script"&&e.hash){const s=t.indexOf("?")!==-1?"&":"?";t+=`${s}t=${e.hash}`}return t}getAbsoluteUrl(e){if(e.startsWith("blob:")||e.startsWith("data:"))return e;const t=ve.getDirectory(this.file.url);return ve.join(t,e)}getLocalizedAssetId(e){return e=Cw(e,this._i18n),this._i18n[e]||null}addLocalizedAssetId(e,t){this._i18n[e]=t,this.fire("add:localized",e,t)}removeLocalizedAssetId(e){const t=this._i18n[e];t&&(delete this._i18n[e],this.fire("remove:localized",e,t))}ready(e,t){t=t||this,this.loaded?e.call(t,this):this.once("load",s=>{e.call(t,s)})}reload(){this.loaded&&(this.loaded=!1,this.registry.load(this))}unload(){if(!this.loaded&&this._resources.length===0)return;this.fire("unload",this),this.registry.fire(`unload:${this.id}`,this);const e=this._resources;this.urlObject&&(URL.revokeObjectURL(this.urlObject),this.urlObject=null),this.resources=[],this.loaded=!1,this.file&&this.registry._loader.clearCache(this.getFileUrl(),this.type);for(let t=0;t<e.length;++t)e[t]?.destroy?.()}static fetchArrayBuffer(e,t,s,i=0){s?.file?.contents?setTimeout(()=>{t(null,s.file.contents)}):ht.get(e,{cache:!0,responseType:"arraybuffer",retry:i>0,maxRetries:i,progress:s},t)}}class NR{_index={};_key;constructor(e=null){this._key=e}addItem(e){const t=e.tags._list;for(const s of t)this.add(s,e)}removeItem(e){const t=e.tags._list;for(const s of t)this.remove(s,e)}add(e,t){this._index[e]&&this._index[e].list.indexOf(t)!==-1||(this._index[e]||(this._index[e]={list:[]},this._key&&(this._index[e].keys={})),this._index[e].list.push(t),this._key&&(this._index[e].keys[t[this._key]]=t))}remove(e,t){if(!this._index[e]||this._key&&!this._index[e].keys[t[this._key]])return;const s=this._index[e].list.indexOf(t);s!==-1&&(this._index[e].list.splice(s,1),this._key&&delete this._index[e].keys[t[this._key]],this._index[e].list.length===0&&delete this._index[e])}find(e){const t={},s=[];let i,r,a,n,o;const c=(h,d)=>this._index[h].list.length-this._index[d].list.length;for(let h=0;h<e.length;h++){if(r=e[h],r instanceof Array){if(r.length===0)continue;if(r.length===1)r=r[0];else{o=!1;for(let d=0;d<r.length;d++)if(!this._index[r[d]]){o=!0;break}if(o)continue;a=r.slice(0).sort(c),n=a.slice(1),n.length===1&&(n=n[0]);for(let d=0;d<this._index[a[0]].list.length;d++)i=this._index[a[0]].list[d],(this._key?!t[i[this._key]]:s.indexOf(i)===-1)&&i.tags.has(n)&&(this._key&&(t[i[this._key]]=!0),s.push(i));continue}}if(r&&typeof r=="string"&&this._index[r])for(let d=0;d<this._index[r].list.length;d++)i=this._index[r].list[d],this._key?t[i[this._key]]||(t[i[this._key]]=!0,s.push(i)):s.indexOf(i)===-1&&s.push(i)}return s}}class Ew extends ge{static EVENT_LOAD="load";static EVENT_ADD="add";static EVENT_REMOVE="remove";static EVENT_ERROR="error";_assets=new Set;_loader;_idToAsset=new Map;_urlToAsset=new Map;_nameToAsset=new Map;_tags=new NR("id");prefix=null;bundles=null;constructor(e){super(),this._loader=e}get loader(){return this._loader}list(e={}){const t=Array.from(this._assets);return e.preload!==void 0?t.filter(s=>s.preload===e.preload):t}add(e){this._assets.has(e)||(this._assets.add(e),this._idToAsset.set(e.id,e),e.file?.url&&this._urlToAsset.set(e.file.url,e),this._nameToAsset.has(e.name)||this._nameToAsset.set(e.name,new Set),this._nameToAsset.get(e.n
1703ame).add(e),e.on("name",this._onNameChange,this),e.registry=this,this._tags.addItem(e),e.tags.on("add",this._onTagAdd,this),e.tags.on("remove",this._onTagRemove,this),this.fire("add",e),this.fire(`add:${e.id}`,e),e.file?.url&&this.fire(`add:url:${e.file.url}`,e),e.preload&&this.load(e))}remove(e){if(!this._assets.has(e))return!1;if(this._assets.delete(e),this._idToAsset.delete(e.id),e.file?.url&&this._urlToAsset.delete(e.file.url),e.off("name",this._onNameChange,this),this._nameToAsset.has(e.name)){const t=this._nameToAsset.get(e.name);t.delete(e),t.size===0&&this._nameToAsset.delete(e.name)}return this._tags.removeItem(e),e.tags.off("add",this._onTagAdd,this),e.tags.off("remove",this._onTagRemove,this),e.fire("remove",e),this.fire("remove",e),this.fire(`remove:${e.id}`,e),e.file?.url&&this.fire(`remove:url:${e.file.url}`,e),!0}get(e){return this._idToAsset.get(Number(e))}getByUrl(e){return this._urlToAsset.get(e)}load(e,t){if((e.loading||e.loaded)&&!t?.force)return;const s=e.file,i=()=>{this.fire("load",e),this.fire(`load:${e.id}`,e),s&&s.url&&this.fire(`load:url:${s.url}`,e),e.fire("load",e)},r=n=>{if(n instanceof Array?e.resources=n:e.resource=n,this._loader.patch(e,this),e.type==="bundle"){const o=e.data.assets;for(let c=0;c<o.length;c++){const h=this._idToAsset.get(o[c]);h&&!h.loaded&&this.load(h,{force:!0})}e.resource.loaded?i():(this.fire("load:start",e),this.fire(`load:start:${e.id}`,e),s&&s.url&&this.fire(`load:start:url:${s.url}`,e),e.fire("load:start",e),e.resource.on("load",i))}else i()},a=(n,o,c)=>{if(e.loaded=!0,e.loading=!1,n)this.fire("error",n,e),this.fire(`error:${e.id}`,n,e),e.fire("error",n,e);else{if(e.type==="script"){const h=this._loader.getHandler("script");h._cache[e.id]&&h._cache[e.id].parentNode===document.head&&document.head.removeChild(h._cache[e.id]),c&&(h._cache[e.id]=c)}r(o)}};if(s||e.type==="cubemap"){this.fire("load:start",e),this.fire(`load:${e.id}:start`,e),e.loading=!0;const n=e.getFileUrl();if(e.type==="bundle"){const o=e.data.assets;for(let c=0;c<o.length;c++){const h=this._idToAsset.get(o[c]);h&&(h.loaded||h.resource||h.loading||(h.loading=!0))}}this._loader.load(n,e.type,a,e,t)}else{const n=this._loader.open(e.type,e.data);e.loaded=!0,r(n)}}loadFromUrl(e,t,s){this.loadFromUrlAndFilename(e,null,t,s)}loadFromUrlAndFilename(e,t,s,i){const r=ve.getBasename(t||e),a={filename:t||r,url:e};let n=this.getByUrl(e);if(!n)n=new pe(r,s,a),this.add(n);else if(n.loaded){i(n.loadFromUrlError||null,n);return}const o=c=>{c.once("load",h=>{s==="material"?this._loadTextures(h,(d,u)=>{i(d,h)}):i(null,h)}),c.once("error",h=>{h&&(this.loadFromUrlError=h),i(h,c)}),this.load(c)};n.resource?i(null,n):s==="model"?this._loadModel(n,o):o(n)}_loadModel(e,t){const s=e.getFileUrl(),i=ve.getExtension(s);if(i===".json"||i===".glb"){const r=ve.getDirectory(s),a=ve.getBasename(s),n=ve.join(r,a.replace(i,".mapping.json"));this._loader.load(n,"json",(o,c)=>{o?(e.data={mapping:[]},t(e)):this._loadMaterials(e,c,(h,d)=>{e.data=c,t(e)})})}else t(e)}_loadMaterials(e,t,s){const i=[];let r=0;const a=(n,o)=>{this._loadTextures(o,(c,h)=>{i.push(o),i.length===r&&s(null,i)})};for(let n=0;n<t.mapping.length;n++){const o=t.mapping[n].path;if(o){r++;const c=e.getAbsoluteUrl(o);this.loadFromUrl(c,"material",a)}}r===0&&s(null,i)}_loadTextures(e,t){const s=[];let i=0;const r=e.data;if(r.mappingFormat!=="path"){t(null,s);return}const a=(o,c)=>{o&&console.error(`Failed to load material texture for "${e.name}": ${o?.message??o}`,o),s.push(c),s.length===i&&t(null,s)},n=Rf;for(let o=0;o<n.length;o++){const c=r[n[o]];if(c&&typeof c=="string"){i++;const h=e.getAbsoluteUrl(c);this.loadFromUrl(h,"texture",a)}}i===0&&t(null,s)}_onTagAdd(e,t){this._tags.add(e,t)}_onTagRemove(e,t){this._tags.remove(e,t)}_onNameChange(e,t,s){if(this._nameToAsset.has(s)){const i=this._nameToAsset.get(s);i.delete(e),i.size===0&&this._nameToAsset.delete(s)}this._nameToAsset.has(e.name)||this._nameToAsset.set(e.name,new Set),this._nameToAsset.get(e.name).add(e)}findByTag(...e){return this._tags.find(e)}filter(e){return Array.from(this._assets).filter(t=>e(t))}find(e,t){const s=this._nameToAsset.get(e);if(!s)return null;for(const i of s)if(!t||i.type===t)return i;return null}findAll(e,t){const s=this._nameToAsset.get(e);if(!s)return[];const i=Array.from(s);return t?i.filter(r=>r.type===t):i}log(){}}class kR{_idToBundle=new Map;_assetToBundles=new Map;_urlsToBundles=new Map;_fileRequests=new Map;constructor(e){this._assets=e,this._assets.bundles=this,this._assets.on("add",this._onAssetAdd,this),this._assets.on("remove",this._onAssetRemove,this)}_onAssetAdd(e){if(e.type==="bundle"){this._idToBundle.set(e.id,e),this._assets.on(`load:start:${e.id}`,this._onBundleLoadStart,this),this._assets.on(`load:${e.id}`,this._onBundleLoad,this),this._assets.on(`error:${e.id}`,this._onBundleError,this);const t=e.data.assets;for(let s=0;s<t.length;s++)this._indexAssetInBundle(t[s],e)}else this._assetToBundles.has(e.id)&&this._indexAssetFileUrls(e)}_unbindAssetEvents(e){this._assets.off(`load:start:${e}`,this._onBundleLoadStart,this),this._assets.off(`load:${e}`,this._onBundleLoad,this),this._assets.off(`error:${e}`,this._onBundleError,this)}_indexAssetInBundle(e,t){let s=this._assetToBundles.get(e);s||(s=new Set,this._assetToBundles.set(e,s)),s.add(t);const i=this._assets.get(e);i&&this._indexAssetFileUrls(i)}_indexAssetFileUrls(e){const t=this._getAssetFileUrls(e);if(t)for(let s=0;s<t.length;s++){const i=this._assetToBundles.get(e.id);i&&this._urlsToBundles.set(t[s],i)}}_getAssetFileUrls(e){let t=e.getFileUrl();if(!t)return null;t=t.split("?")[0];const s=[t];if(e.type==="font"){const i=e.data.info.maps.length;for(let r=1;r<i;r++)s.push(t.replace(".png",`${r}.png`))}return s}_onAssetRemove(e){if(e.type==="bundle"){this._idToBundle.delete(e.id),this._unbindAssetEvents(e.id);const t=e.data.assets;for(let s=0;s<t.length;s++){const i=this._assetToBundles.get(t[s]);if(i&&(i.delete(e),i.size===0)){this._assetToBundles.delete(t[s]);for(const[r,a]of this._urlsToBundles)a===i&&this._urlsToBundles.delete(r)}}
1703this._onBundleError(`Bundle ${e.id} was removed`)}else{if(!this._assetToBundles.get(e.id))return;this._assetToBundles.delete(e.id);const s=this._getAssetFileUrls(e);if(!s)return;for(let i=0;i<s.length;i++)this._urlsToBundles.delete(s[i])}}_onBundleLoadStart(e){e.resource.on("add",(t,s)=>{const i=this._fileRequests.get(t);if(i){for(let r=0;r<i.length;r++)i[r](null,s);this._fileRequests.delete(t)}})}_onBundleLoad(e){if(!e.resource){this._onBundleError(`Bundle ${e.id} failed to load`);return}if(this._fileRequests)for(const[t,s]of this._fileRequests){const i=this._urlsToBundles.get(t);if(!i||!i.has(e))continue;const r=decodeURIComponent(t);let a,n;if(e.resource.has(r))n=e.resource.get(r);else if(e.resource.loaded)a=`Bundle ${e.id} does not contain URL ${t}`;else continue;for(let o=0;o<s.length;o++)s[o](a,a||n);this._fileRequests.delete(t)}}_onBundleError(e){for(const[t,s]of this._fileRequests)if(!this._findLoadedOrLoadingBundleForUrl(t)){for(let r=0;r<s.length;r++)s[r](e);this._fileRequests.delete(t)}}_findLoadedOrLoadingBundleForUrl(e){const t=this._urlsToBundles.get(e);if(!t)return null;let s=null;for(const i of t){if(i.loaded&&i.resource)return i;i.loading&&(s=i)}return s}listBundlesForAsset(e){const t=this._assetToBundles.get(e.id);return t?Array.from(t):null}list(){return Array.from(this._idToBundle.values())}hasUrl(e){return this._urlsToBundles.has(e)}urlIsLoadedOrLoading(e){return!!this._findLoadedOrLoadingBundleForUrl(e)}loadUrl(e,t){const s=this._findLoadedOrLoadingBundleForUrl(e);if(!s){t(`URL ${e} not found in any bundles`);return}if(s.loaded){const r=decodeURIComponent(e);if(s.resource.has(r)){t(null,s.resource.get(r));return}else if(s.resource.loaded){t(`Bundle ${s.id} does not contain URL ${e}`);return}}let i=this._fileRequests.get(e);i||(i=[],this._fileRequests.set(e,i)),i.push(t)}destroy(){this._assets.off("add",this._onAssetAdd,this),this._assets.off("remove",this._onAssetRemove,this);for(const e of this._idToBundle.keys())this._unbindAssetEvents(e);this._assets=null,this._idToBundle.clear(),this._idToBundle=null,this._assetToBundles.clear(),this._assetToBundles=null,this._urlsToBundles.clear(),this._urlsToBundles=null,this._fileRequests.clear(),this._fileRequests=null}}class UR extends ge{anim;animation;audiolistener;button;camera;collision;element;gsplat;joint;layoutchild;layoutgroup;light;model;particlesystem;render;rigidbody;screen;script;scrollbar;scrollview;sound;sprite;zone;constructor(){super(),this.list=[]}add(e){const t=e.id;if(this[t])throw new Error(`ComponentSystem name '${t}' already registered or not allowed`);this[t]=e,this.list.push(e)}remove(e){const t=e.id;if(!this[t])throw new Error(`No ComponentSystem named '${t}' registered`);delete this[t];const s=this.list.indexOf(this[t]);s!==-1&&this.list.splice(s,1)}destroy(){this.off();for(let e=0;e<this.list.length;e++)this.list[e].destroy()}}class zR extends ge{_index=new Map;_loaded=!1;static EVENT_ADD="add";static EVENT_LOAD="load";addFile(e,t){this._index.has(e)||(this._index.set(e,t),this.fire("add",e,t))}has(e){return this._index.has(e)}get(e){return this._index.get(e)||null}destroy(){this._index.clear()}set loaded(e){!e||this._loaded||(this._loaded=!0,this.fire("load"))}get loaded(){return this._loaded}}class VR extends ge{headerSize=512;paddingSize=512;bytesRead=0;bytesReceived=0;headerRead=!1;reader=null;data=new Uint8Array(0);decoder=null;prefix="";fileName="";fileSize=0;fileType="";ustarFormat="";constructor(e,t=""){super(),this.prefix=t||"",this.reader=e.body.getReader(),this.reader.read().then(s=>{this.pump(s.done,s.value)}).catch(s=>{this.fire("error",s)})}pump(e,t){if(e)return this.fire("done"),null;this.bytesReceived+=t.byteLength;const s=new Uint8Array(this.data.length+t.length);for(s.set(this.data),s.set(t,this.data.length),this.data=s;this.readFile(););return this.reader.read().then(i=>{this.pump(i.done,i.value)}).catch(i=>{this.fire("error",i)})}readFile(){if(!this.headerRead&&this.bytesReceived>this.bytesRead+this.headerSize){this.headerRead=!0;const e=new DataView(this.data.buffer,this.bytesRead,this.headerSize);this.decoder??(this.decoder=new TextDecoder("windows-1252"));const t=this.decoder.decode(e);if(this.fileName=t.substring(0,100).replace(/\0/g,""),this.fileSize=parseInt(t.substring(124,136),8),this.fileType=t.substring(156,157),this.ustarFormat=t.substring(257,263),this.ustarFormat.indexOf("ustar")!==-1){const s=t.substring(345,500).replace(/\0/g,"");
1703s.length>0&&(this.fileName=s.trim()+this.fileName.trim())}this.bytesRead+=512}if(this.headerRead){if(this.bytesReceived<this.bytesRead+this.fileSize)return!1;if(this.fileType===""||this.fileType==="0"){const t=new DataView(this.data.buffer,this.bytesRead,this.fileSize),s={name:this.prefix+this.fileName,size:this.fileSize,data:t};this.fire("file",s)}this.bytesRead+=this.fileSize,this.headerRead=!1;const e=this.bytesRead%this.paddingSize;return e!==0&&(this.bytesRead+=this.paddingSize-e),!0}return!1}}class dt{handlerType="";_app;_maxRetries=0;constructor(e,t){this._app=e,this.handlerType=t}set maxRetries(e){this._maxRetries=e}get maxRetries(){return this._maxRetries}load(e,t,s){}open(e,t,s){return t}patch(e,t){}}class GR extends dt{constructor(e){super(e,"bundle"),this._assets=e.assets}_fetchRetries(e,t,s=0){return new Promise((i,r)=>{const a=()=>{fetch(e,t).then(i).catch(n=>{s++,s<this.maxRetries?a():r(n)})};a()})}load(e,t){typeof e=="string"&&(e={load:e,original:e}),this._fetchRetries(e.load,{mode:"cors"},this.maxRetries).then(s=>{const i=new zR;t(null,i);const r=new VR(s,this._assets.prefix);r.on("file",a=>{i.addFile(a.name,a.data)}),r.on("done",()=>{i.loaded=!0}),r.on("error",a=>{t(a)})}).catch(s=>{t(s)})}open(e,t){return t}}class Co{constructor(e){this._handlers={},this._requests={},this._cache={},this._app=e}addHandler(e,t){this._handlers[e]=t,t._loader=this}removeHandler(e){delete this._handlers[e]}getHandler(e){return this._handlers[e]}static makeKey(e,t){return`${e}-${t}`}load(e,t,s,i,r){const a=this._handlers[t];if(!a){const o=`No resource handler for asset type: '${t}' when loading [${e}]`;s(o);return}if(!e){this._loadNull(a,s,i);return}const n=Co.makeKey(e,t);if(this._cache[n]!==void 0)s(null,this._cache[n]);else if(this._requests[n])this._requests[n].push(s);else{this._requests[n]=[s];const o=this,c=function(d,u){if(d){o._onFailure(n,d);return}if(u.load instanceof DataView){if(a.openBinary){if(!o._requests[n])return;try{const f=a.openBinary(u.load);o._onSuccess(n,f)}catch(f){o._onFailure(n,f)}return}u.load=URL.createObjectURL(new Blob([u.load])),i&&(i.urlObject&&URL.revokeObjectURL(i.urlObject),i.urlObject=u.load)}a.load(u,(f,p,m)=>{if(o._requests[n]){if(f){o._onFailure(n,f);return}try{o._onSuccess(n,a.open(u.original,p,i),m)}catch(_){o._onFailure(n,_)}}},i)},h=e.split("?")[0];if(this._app.enableBundles&&this._app.bundles.hasUrl(h)&&!(r&&r.bundlesIgnore)){if(!this._app.bundles.urlIsLoadedOrLoading(h)){const d=this._app.bundles.listBundlesForAsset(i);let u;r&&r.bundlesFilter&&(u=r.bundlesFilter(d)),u||(d?.sort((f,p)=>f.file.size-p.file.size),u=d?.[0]),u&&this._app.assets?.load(u)}this._app.bundles.loadUrl(h,(d,u)=>{c(d,{load:u,original:h})})}else c(null,{load:e,original:i&&i.file.filename||e})}}_loadNull(e,t,s){const i=function(r,a,n){if(r)t(r);else try{t(null,e.open(null,a,s),n)}catch(o){t(o)}};e.load(null,i,s)}_onSuccess(e,t,s){t!==null?this._cache[e]=t:delete this._cache[e];for(let i=0;i<this._requests[e].length;i++)this._requests[e][i](null,t,s);delete this._requests[e]}_onFailure(e,t){if(console.error(`Failed to load resource [${e}]: ${t?.message??t}`,t),this._requests[e]){for(let s=0;s<this._requests[e].length;s++)this._requests[e][s](t);delete this._requests[e]}}open(e,t){const s=this._handlers[e];return s?s.open(null,t):(console.warn(`No resource handler found for: ${e}`),t)}patch(e,t){const s=this._handlers[e.type];if(!s){console.warn(`No resource handler found for: ${e.type}`);return}s.patch&&s.patch(e,t)}clearCache(e,t){const s=Co.makeKey(e,t);delete this._cache[s]}getFromCache(e,t){const s=Co.makeKey(e,t);if(this._cache[s])return this._cache[s]}enableRetry(e=5){e=Math.max(0,Math.floor(e))||0;for(const t in this._handlers)this._handlers[t].maxRetries=e}disableRetry(){for(const e in this._handlers)this._handlers[e].maxRetries=0}destroy(){this._handlers={},this._requests={},this._cache={}}}class HR{_validate(e){if(!e.header)throw new Error('pc.I18n#addData: Missing "header" field');if(!e.header.version)throw new Error('pc.I18n#addData: Missing "header.version" field');if(e.header.version!==1)throw new Error('pc.I18n#addData: Invalid "header.version" field');if(e.data){if(!Array.isArray(e.data))throw new Error('pc.I18n#addData: "data" field must be an array')}else throw new Error('pc.I18n#addData: Missing "data" field');for(let t=0,s=e.data.length;t<s;t++){const i=e.data[t];if(!i.info)throw new Error(`pc.I18n#addData: missing "data[${t}].info" field`);if(!i.info.locale)throw new Error(`pc.I18n#addData: missing "data[${t}].info.locale" field`);if(typeof i.info.locale!="string")throw new Error(`pc.I18n#addData: "data[${t}].info.locale" must be a string`);if(!i.messages)throw new Error(`pc.I18n#addData: missing "data[${t}].messages" field`)}}parse(e){return e.data}}class fn extends ge{static EVENT_CHANGE="change";constructor(e){super(),this.locale=mu,this._translations={},this._availableLangs={},this._app=e,this._assets=[],this._parser=new HR}set assets(e){const t={};for(let i=0,r=e.length;i<r;i++){const a=e[i]instanceof pe?e[i].id:e[i];t[a]=!0}let s=this._assets.length;for(;s--;){const i=this._assets[s];if(!t[i]){this._app.assets.off(`add:${i}`,this._onAssetAdd,this);const r=this._app.assets.get(i);r&&this._onAssetRemove(r),this._assets.splice(s,1)}}for(const i in t){const r=parseInt(i,10);if(this._assets.indexOf(r)!==-1)continue;this._assets.push(r);const a=this._app.assets.get(r);a?this._onAssetAdd(a):this._app.assets.once(`add:${r}`,this._onAssetAdd,this)}}get assets(){return this._assets}set locale(e){if(this._locale===e)return;let t=ar(e);if(t==="in"&&(t="id",e=RR(e,t),this._locale===e))return;const s=this._locale;this._locale=e,this._lang=t,this._pluralFn=Kp(this._lang),this.fire(fn.EVENT_CHANGE,e,s)}get locale(){return this._locale}static findAvailableLocale(e,t){return Cw(e,t)}findAvailableLocale(e){if(this._translations[e])return e;const t=ar(e);return this._findFallbackLocale(e,t)}getText(e,t){let s=e,i;t||(t=this._locale,i=this._lang);let r=this._translations[t];return r||(i||(i=ar(t)),t=this._findFallbackLocale(t,i),r=this._translations[t]),r&&r.hasOwnProperty(e)&&(s=r[e],Array.isArray(s)&&(s=s[0]),s==null&&(s=e)),s}
1703getPluralText(e,t,s){let i=e,r,a;s?(r=ar(s),a=Kp(r)):(s=this._locale,r=this._lang,a=this._pluralFn);let n=this._translations[s];if(n||(s=this._findFallbackLocale(s,r),r=ar(s),a=Kp(r),n=this._translations[s]),n&&n[e]&&a){const o=a(t);i=n[e][o],i==null&&(i=e)}return i}addData(e){let t;try{t=this._parser.parse(e)}catch(s){console.error(`I18n.addData: failed to parse localization data: ${s?.message??s}`,s);return}for(let s=0,i=t.length;s<i;s++){const r=t[s],a=r.info.locale,n=r.messages;if(!this._translations[a]){this._translations[a]={};const o=ar(a);this._availableLangs[o]||(this._availableLangs[o]=a)}Object.assign(this._translations[a],n),this.fire("data:add",a,n)}}removeData(e){let t;try{t=this._parser.parse(e)}catch(s){console.error(`I18n.removeData: failed to parse localization data: ${s?.message??s}`,s);return}for(let s=0,i=t.length;s<i;s++){const r=t[s],a=r.info.locale,n=this._translations[a];if(!n)continue;const o=r.messages;for(const c in o)delete n[c];Object.keys(n).length===0&&(delete this._translations[a],delete this._availableLangs[ar(a)]),this.fire("data:remove",a,o)}}destroy(){this._translations=null,this._availableLangs=null,this._assets=null,this._parser=null,this.off()}_findFallbackLocale(e,t){let s=_u[e];return s&&this._translations[s]||(s=_u[t],s&&this._translations[s])||(s=this._availableLangs[t],s&&this._translations[s])?s:mu}_onAssetAdd(e){e.on("load",this._onAssetLoad,this),e.on("change",this._onAssetChange,this),e.on("remove",this._onAssetRemove,this),e.on("unload",this._onAssetUnload,this),e.resource&&this._onAssetLoad(e)}_onAssetLoad(e){this.addData(e.resource)}_onAssetChange(e){e.resource&&this.addData(e.resource)}_onAssetRemove(e){e.off("load",this._onAssetLoad,this),e.off("change",this._onAssetChange,this),e.off("remove",this._onAssetRemove,this),e.off("unload",this._onAssetUnload,this),e.resource&&this.removeData(e.resource),this._app.assets.once(`add:${e.id}`,this._onAssetAdd,this)}_onAssetUnload(e){e.resource&&this.removeData(e.resource)}}class WR extends ge{_scripts={};_list=[];_scriptSchemas=new Map;constructor(e){super(),this.app=e}destroy(){this.app=null,this.off()}addSchema(e,t){t&&this._scriptSchemas.set(e,t)}getSchema(e){return this._scriptSchemas.get(e)}add(e){const t=e.__name;return this._scripts.hasOwnProperty(t)?(setTimeout(()=>{if(e.prototype.swap){const s=this._scripts[t],i=this._list.indexOf(s);this._list[i]=e,this._scripts[t]=e,this.fire("swap",t,e),this.fire(`swap:${t}`,e)}else console.warn(`script registry already has '${t}' script, define 'swap' method for new script type to enable code hot swapping`)}),!1):(this._scripts[t]=e,this._list.push(e),this.fire("add",t,e),this.fire(`add:${t}`,e),setTimeout(()=>{if(!this._scripts.hasOwnProperty(t)||!this.app||!this.app.systems||!this.app.systems.script)return;const s=this.app.systems.script._components;let i;const r=[],a=[];for(s.loopIndex=0;s.loopIndex<s.length;s.loopIndex++){const n=s.items[s.loopIndex];if(n._scriptsIndex[t]&&n._scriptsIndex[t].awaiting){n._scriptsData&&n._scriptsData[t]&&(i=n._scriptsData[t].attributes);const o=n.create(t,{preloading:!0,ind:n._scriptsIndex[t].ind,attributes:i});o&&r.push(o);for(const c of n.scripts)n.initializeAttributes(c)}}for(let n=0;n<r.length;n++)r[n].enabled&&(r[n]._initialized=!0,a.push(r[n]),r[n].initialize&&r[n].initialize());for(let n=0;n<a.length;n++)!a[n].enabled||a[n]._postInitialized||(a[n]._postInitialized=!0,a[n].postInitialize&&a[n].postInitialize())}),!0)}remove(e){let t=e,s=e;if(typeof s!="string"?s=t.__name:t=this.get(s),this.get(s)!==t)return!1;delete this._scripts[s];const i=this._list.indexOf(t);return this._list.splice(i,1),this.fire("remove",s,t),this.fire(`remove:${s}`,t),!0}get(e){return this._scripts[e]||null}has(e){if(typeof e=="string")return this._scripts.hasOwnProperty(e);if(!e)return!1;const t=e.__name;return this._scripts[t]===e}list(){return this._list}}const XR=(l,e)=>l.constructor.order-e.constructor.order,YR=l=>l.sort(XR),yl=[],bw=[],jR=()=>bw.pop()??[],Iy=l=>{l.length=0,bw.push(l)};class lt extends He{static EVENT_DESTROY="destroy";anim;animation;audiolistener;button;camera;collision;element;gsplat;layoutchild;layoutgroup;light;model;particlesystem;render;rigidbody;screen;script;scrollbar;scrollview;sound;sprite;c={};_app;_destroying=!1;_guid=null;_template=!1;constructor(e,t=yi()){super(e),this._app=t}addComponent(e,t){const s=this._app.systems[e];return!s||this.c[e]?null:s.addComponent(this,t)}
1703removeComponent(e){const t=this._app.systems[e];t&&this.c[e]&&t.removeComponent(this)}findComponent(e){const t=this.findOne(s=>s.c?.[e]);return t&&t.c[e]}findComponents(e){return this.find(t=>t.c?.[e]).map(t=>t.c[e])}findScript(e){return this.findOne(s=>s.c?.script?.has(e))?.c.script.get(e)}findScripts(e){return this.find(s=>s.c?.script?.has(e)).map(s=>s.c.script.get(e))}set guid(e){const t=this._app._entityIndex;this._guid&&delete t[this._guid],this._guid=e,t[this._guid]=this}get guid(){return this._guid||(this.guid=eE.create()),this._guid}getGuid(){return this.guid}setGuid(e){this.guid=e}_notifyHierarchyStateChanged(e,t){let s=!1;e===this&&yl.length===0&&(s=!0),e._beingEnabled=!0,e._onHierarchyStateChanged(t),e._onHierarchyStatePostChanged&&yl.push(e);const i=e._children;for(let r=0,a=i.length;r<a;r++)i[r]._enabled&&this._notifyHierarchyStateChanged(i[r],t);if(e._beingEnabled=!1,s){for(let r=0;r<yl.length;r++)yl[r]._onHierarchyStatePostChanged();yl.length=0}}_onHierarchyStateChanged(e){super._onHierarchyStateChanged(e);const t=this._getSortedComponents();for(let s=0;s<t.length;s++){const i=t[s];i.enabled&&(e?i.onEnable():i.onDisable())}Iy(t)}_onHierarchyStatePostChanged(){const e=this._getSortedComponents();for(let t=0;t<e.length;t++)e[t].onPostStateChange();Iy(e)}findByGuid(e){if(this._guid===e)return this;const t=this._app._entityIndex[e];return t&&(t===this||t.isDescendantOf(this))?t:null}destroy(){this._destroying=!0;for(const e in this.c)this.c[e].enabled=!1;for(const e in this.c)this.c[e].system.removeComponent(this);super.destroy(),this._guid&&delete this._app._entityIndex[this._guid],this._destroying=!1}clone(){const e={},t=this._cloneRecursively(e);return e[this.guid]=t,Aw(this,this,t,e),t}_getSortedComponents(){const e=this.c,t=jR();let s=0;for(const i in e)if(e.hasOwnProperty(i)){const r=e[i];s|=r.constructor.order!==0,t.push(r)}return s&&t.length>1&&YR(t),t}_cloneRecursively(e){const t=new this.constructor(void 0,this._app);super._cloneInternal(t);for(const s in this.c)this.c[s].system.cloneComponent(this,t);for(let s=0;s<this._children.length;s++){const i=this._children[s];if(i instanceof lt){const r=i._cloneRecursively(e);t.addChild(r),e[i.guid]=r}}return t}}function Aw(l,e,t,s){if(e instanceof lt){const i=e.c;for(const n in i){const o=i[n],c=o.system.getPropertiesOfType("entity");for(let h=0,d=c.length;h<d;h++){const f=c[h].name,p=o[f];if(!!l.findByGuid(p)){const _=s[p].guid;_&&(t.c[n][f]=_)}}}i.script&&t.script.resolveDuplicatedEntityReferenceProperties(i.script,s),i.render&&t.render.resolveDuplicatedEntityReferenceProperties(i.render,s),i.button&&t.button.resolveDuplicatedEntityReferenceProperties(i.button,s),i.scrollview&&t.scrollview.resolveDuplicatedEntityReferenceProperties(i.scrollview,s),i.scrollbar&&t.scrollbar.resolveDuplicatedEntityReferenceProperties(i.scrollbar,s),i.anim&&t.anim.resolveDuplicatedEntityReferenceProperties(i.anim,s);const r=e.children.filter(n=>n instanceof lt),a=t.children.filter(n=>n instanceof lt);for(let n=0,o=r.length;n<o;n++)Aw(l,r[n],a[n],s)}}class Dy{name;url;data=null;_loading=!1;_onLoadedCallbacks=[];constructor(e,t){this.name=e,this.url=t}get loaded(){return!!this.data}get loading(){return this._loading}}class qR{_app;_list=[];_index={};_urlIndex={};constructor(e){this._app=e}destroy(){this._app=null}list(){return this._list}add(e,t){if(this._index.hasOwnProperty(e))return!1;const s=new Dy(e,t),i=this._list.push(s);return this._index[s.name]=i-1,this._urlIndex[s.url]=i-1,!0}find(e){return this._index.hasOwnProperty(e)?this._list[this._index[e]]:null}findByUrl(e){return this._urlIndex.hasOwnProperty(e)?this._list[this._urlIndex[e]]:null}remove(e){if(this._index.hasOwnProperty(e)){const t=this._index[e];let s=this._list[t];delete this._urlIndex[s.url],delete this._index[e],this._list.splice(t,1);for(let i=0;i<this._list.length;i++)s=this._list[i],this._index[s.name]=i,this._urlIndex[s.url]=i}}_loadSceneData(e,t,s){const i=this._app;let r=e;if(typeof e=="string"&&(e=this.findByUrl(r)||this.find(r)||new Dy("Untitled",r)),r=e.url,!r){s("Cannot find scene to load");return}if(e.loaded){s(null,e);return}i.assets&&i.assets.prefix&&!Vo.test(r)&&(r=ve.join(i.assets.prefix,r)),e._onLoadedCallbacks.push(s),e._loading||i.loader.getHandler("hierarchy").load(r,(n,o)=>{e.data=o,e._loading=!1;for(let c=0;c<e._onLoadedCallbacks.length;c++)e._onLoadedCallbacks[c](n,e);t||(e.data=null),e._onLoadedCallbacks.length=0}),e._loading=!0}loadSceneData(e,t){this._loadSceneData(e,!0,t)}unloadSceneData(e){typeof e=="string"&&(e=this.findByUrl(e)),e&&(e.data=null)}_loadSceneHierarchy(e,t,s){this._loadSceneData(e,!1,(i,r)=>{if(i){s&&s(i);return}t&&t(r);const a=this._app,n=()=>{const o=a.loader.getHandler("hierarchy");a.systems.script.preloading=!0;const c=o.open(r.url,r.data);a.systems.script.preloading=!1,a.loader.clearCache(r.url,"hierarchy"),a.root.addChild(c),a.systems.fire("initialize",c),a.systems.fire("postInitialize",c),a.systems.fire("postPostInitialize",c),s&&s(null,c)};a._preloadScripts(r.data,n)})}loadSceneHierarchy(e,t){this._loadSceneHierarchy(e,null,t)}loadSceneSettings(e,t){this._loadSceneData(e,!1,(s,i)=>{s?t&&t(s):(this._app.applySceneSettings(i.data.settings),t&&t(null))})}changeScene(e,t){const s=this._app,i=r=>{const{children:a}=s.root;for(;a.length;)a[0].destroy();s.applySceneSettings(r.data.settings)};this._loadSceneHierarchy(e,i,t)}loadScene(e,t){const s=this._app,i=s.loader.getHandler("scene");s.assets&&s.assets.prefix&&!Vo.test(e)&&(e=ve.join(s.assets.prefix,e)),i.load(e,(r,a)=>{if(r)t&&t(r);else{const n=()=>{s.systems.script.preloading=!0;const o=i.open(e,a),c=this.findByUrl(e);c&&!c.loaded&&(c.data=a),s.systems.script.preloading=!1,s.loader.clearCache(e,"scene"),s.loader.patch({resource:o,type:"scene"},s.assets),s.root.addChild(o.root),s.systems.rigidbody&&typeof Ammo<"u"&&s.systems.rigidbody.gravity.set(o._gravity.x,o._gravity.y,o._gravity.z),t&&t(null,o)};s._preloadScripts(a,n)}})}}class $R{constructor(e){this.frame={fps:0,ms:0,dt:0,updateStart:0,updateTime:0,renderStart:0,renderTime:0,physicsStart:0,physicsTime:0,scriptUpdateStart:0,scriptUpdate:0,scriptPostUpdateStart:0,scriptPostUpdate:0,animUpdateStart:0,animUpdate:0,cullTime:0,sortTime:0,skinTime:0,morphTime:0,instancingTime:0,triangles:0,gsplats:0,gsplatSort:0,gsplatBufferCopy:0,otherPrimitives:0,shaders:0,materials:0,cameras:0,shadowMapUpdates:0,shadowMapTime:0,depthMapTime:0,forwardTime:0,lightCluster
1703sTime:0,lightClusters:0,_timeToCountFrames:0,_fpsAccum:0},this.drawCalls={forward:0,depth:0,shadow:0,immediate:0,misc:0,total:0,skinned:0,instanced:0,removedByInstancing:0},this.misc={renderTargetCreationTime:0},this.particles={updatesPerFrame:0,_updatesPerFrame:0,frameTime:0,_frameTime:0},this.shaders=e._shaderStats,this.vram=e._vram,this.gpu=e.gpuProfiler?.passTimings??new Map,Object.defineProperty(this.vram,"totalUsed",{get:function(){return this.tex+this.vb+this.ib+this.ub+this.sb}}),Object.defineProperty(this.vram,"geom",{get:function(){return this.vb+this.ib}}),Object.defineProperty(this.vram,"buffers",{get:function(){return this.ub+this.sb}})}get scene(){return yi().scene._stats}get lightmapper(){return yi().lightmapper?.stats}get batcher(){const e=yi()._batcher;return e?e._stats:null}updateBasic(e,t,s,i,r){const a=this.frame;a.dt=t,a.ms=s,e>a._timeToCountFrames?(a.fps=a._fpsAccum,a._fpsAccum=0,a._timeToCountFrames=e+1e3):a._fpsAccum++,this.drawCalls.total=r._drawCallsPerFrame,r._drawCallsPerFrame=0,a.gsplats=i._gsplatCount,a.gsplatBufferCopy=i._gsplatBufferCopy??0}updateDetailed(e,t){let s=this.frame;s.cameras=e._camerasRendered,s.materials=e._materialSwitches,s.shaders=t._shaderSwitchesPerFrame,s.shadowMapUpdates=e._shadowMapUpdates,s.shadowMapTime=e._shadowMapTime,s.depthMapTime=e._depthMapTime,s.forwardTime=e._forwardTime;const i=t._primsPerFrame;s.triangles=i[qs]/3+Math.max(i[Tr]-2,0)+Math.max(i[qa]-2,0),s.cullTime=e._cullTime,s.sortTime=e._sortTime,s.skinTime=e._skinTime,s.morphTime=e._morphTime,s.lightClusters=e._lightClusters,s.lightClustersTime=e._lightClustersTime,s.otherPrimitives=0;for(let r=0;r<i.length;r++)r<qs&&(s.otherPrimitives+=i[r]),i[r]=0;e._camerasRendered=0,e._materialSwitches=0,e._shadowMapUpdates=0,t._shaderSwitchesPerFrame=0,e._cullTime=0,e._layerCompositionUpdateTime=0,e._lightClustersTime=0,e._sortTime=0,e._skinTime=0,e._morphTime=0,e._shadowMapTime=0,e._depthMapTime=0,e._forwardTime=0,s=this.drawCalls,s.forward=e._forwardDrawCalls,s.culled=e._numDrawCallsCulled,s.depth=0,s.shadow=e._shadowDrawCalls,s.skinned=e._skinDrawCalls,s.immediate=0,s.instanced=0,s.removedByInstancing=0,s.misc=s.total-(s.forward+s.shadow),e._depthDrawCalls=0,e._shadowDrawCalls=0,e._forwardDrawCalls=0,e._numDrawCallsCulled=0,e._skinDrawCalls=0,e._immediateRendered=0,e._instancedDrawCalls=0,this.misc.renderTargetCreationTime=t.renderTargetCreationTime,s=this.particles,s.updatesPerFrame=s._updatesPerFrame,s.frameTime=s._frameTime,s._updatesPerFrame=0,s._frameTime=0}frameEnd(){this.frame.gsplatSort=0}}var KR=` 1704uniform float alpha_ref; 1705void alphaTest(float a) { 1706 if (a < alpha_ref) discard; 1707} 1708`,ZR=` 1709#ifdef LIT_AMBIENT_SOURCE == AMBIENTSH 1710 uniform vec3 ambientSH[9]; 1711#endif 1712#if LIT_AMBIENT_SOURCE == ENVALATLAS 1713 #include "envAtlasPS" 1714 #ifndef ENV_ATLAS 1715 #define ENV_ATLAS 1716 uniform sampler2D texture_envAtlas; 1717 #endif 1718#endif 1719void addAmbient(vec3 worldNormal) { 1720 #ifdef LIT_AMBIENT_SOURCE == AMBIENTSH 1721 vec3 n = cubeMapRotate(worldNormal); 1722 vec3 color = 1723 ambientSH[0] + 1724 ambientSH[1] * n.x + 1725 ambientSH[2] * n.y + 1726 ambientSH[3] * n.z + 1727 ambientSH[4] * n.x * n.z + 1728 ambientSH[5] * n.z * n.y + 1729 ambientSH[6] * n.y * n.x + 1730 ambientSH[7] * (3.0 * n.z * n.z - 1.0) + 1731 ambientSH[8] * (n.x * n.x - n.y * n.y); 1732 dDiffuseLight += processEnvironment(max(color, vec3(0.0))); 1733 #endif 1734 #if LIT_AMBIENT_SOURCE == ENVALATLAS 1735 vec3 dir = normalize(cubeMapRotate(worldNormal) * vec3(-1.0, 1.0, 1.0)); 1736 vec2 uv = mapUv(toSphericalUv(dir), vec4(128.0, 256.0 + 128.0, 64.0, 32.0) / atlasSize); 1737 vec4 raw = texture2D(texture_envAtlas, uv); 1738 vec3 linear = {ambientDecode}(raw); 1739 dDiffuseLight += processEnvironment(linear); 1740 #endif 1741 #if LIT_AMBIENT_SOURCE == CONSTANT 1742 dDiffuseLight += light_globalAmbient; 1743 #endif 1744} 1745`,QR=` 1746#ifdef LIT_GGX_SPECULAR 1747 uniform float material_anisotropyIntensity; 1748 uniform vec2 material_anisotropyRotation; 1749#endif 1750void getAnisotropy() { 1751 dAnisotropy = 0.0; 1752 dAnisotropyRotation = vec2(1.0, 0.0); 1753#ifdef LIT_GGX_SPECULAR 1754 dAnisotropy = material_anisotropyIntensity; 1755 dAnisotropyRotation = material_anisotropyRotation; 1756#endif 1757 #ifdef STD_ANISOTROPY_TEXTURE 1758 vec3 anisotropyTex = texture2DBias({STD_ANISOTROPY_TEXTURE_NAME}, {STD_ANISOTROPY_TEXTURE_UV}, textureBias).rgb; 1759 dAnisotropy *= anisotropyTex.b;
1760 vec2 anisotropyRotationFromTex = anisotropyTex.rg * 2.0 - vec2(1.0); 1761 mat2 rotationMatrix = mat2(dAnisotropyRotation.x, dAnisotropyRotation.y, -dAnisotropyRotation.y, dAnisotropyRotation.x); 1762 dAnisotropyRotation = rotationMatrix * anisotropyRotationFromTex; 1763 #endif 1764 1765 dAnisotropy = clamp(dAnisotropy, 0.0, 1.0); 1766} 1767`,JR=` 1768#if defined(STD_AO_TEXTURE) || defined(STD_AO_VERTEX) 1769 uniform float material_aoIntensity; 1770#endif 1771#ifdef STD_AODETAIL_TEXTURE 1772 #include "detailModesPS" 1773#endif 1774void getAO() { 1775 dAo = 1.0; 1776 #ifdef STD_AO_TEXTURE 1777 float aoBase = texture2DBias({STD_AO_TEXTURE_NAME}, {STD_AO_TEXTURE_UV}, textureBias).{STD_AO_TEXTURE_CHANNEL}; 1778 #ifdef STD_AODETAIL_TEXTURE 1779 float aoDetail = texture2DBias({STD_AODETAIL_TEXTURE_NAME}, {STD_AODETAIL_TEXTURE_UV}, textureBias).{STD_AODETAIL_TEXTURE_CHANNEL}; 1780 aoBase = detailMode_{STD_AODETAIL_DETAILMODE}(vec3(aoBase), vec3(aoDetail)).r; 1781 #endif 1782 dAo *= aoBase; 1783 #endif 1784 #ifdef STD_AO_VERTEX 1785 dAo *= saturate(vVertexColor.{STD_AO_VERTEX_CHANNEL}); 1786 #endif 1787 #if defined(STD_AO_TEXTURE) || defined(STD_AO_VERTEX) 1788 dAo = mix(1.0, dAo, material_aoIntensity); 1789 #endif 1790} 1791`,e2=` 1792void occludeDiffuse(float ao) { 1793 dDiffuseLight *= ao; 1794} 1795`,t2=` 1796#if LIT_OCCLUDE_SPECULAR != NONE 1797 #ifdef LIT_OCCLUDE_SPECULAR_FLOAT 1798 uniform float material_occludeSpecularIntensity; 1799 #endif 1800#endif 1801void occludeSpecular(float gloss, float ao, vec3 worldNormal, vec3 viewDir) { 1802 #if LIT_OCCLUDE_SPECULAR == AO 1803 #ifdef LIT_OCCLUDE_SPECULAR_FLOAT 1804 float specOcc = mix(1.0, ao, material_occludeSpecularIntensity); 1805 #else 1806 float specOcc = ao; 1807 #endif 1808 #endif 1809 #if LIT_OCCLUDE_SPECULAR == GLOSSDEPENDENT 1810 float specPow = exp2(gloss * 11.0); 1811 float specOcc = saturate(pow(dot(worldNormal, viewDir) + ao, 0.01 * specPow) - 1.0 + ao); 1812 #ifdef LIT_OCCLUDE_SPECULAR_FLOAT 1813 specOcc = mix(1.0, specOcc, material_occludeSpecularIntensity); 1814 #endif 1815 #endif 1816 #if LIT_OCCLUDE_SPECULAR != NONE 1817 dSpecularLight *= specOcc; 1818 dReflection *= specOcc; 1819 #ifdef LIT_SHEEN 1820 sSpecularLight *= specOcc; 1821 sReflection *= specOcc; 1822 #endif 1823 #endif 1824} 1825`,s2=` 1826 vec4 dirLm = texture2D(texture_dirLightMap, vUv1); 1827 if (bakeDir > 0.5) { 1828 if (dAtten > 0.00001) { 1829 dirLm.xyz = dirLm.xyz * 2.0 - vec3(1.0); 1830 dAtten = saturate(dAtten); 1831 gl_FragColor.rgb = normalize(dLightDirNormW.xyz*dAtten + dirLm.xyz*dirLm.w) * 0.5 + vec3(0.5); 1832 gl_FragColor.a = dirLm.w + dAtten; 1833 gl_FragColor.a = max(gl_FragColor.a, 1.0 / 255.0); 1834 } else { 1835 gl_FragColor = dirLm; 1836 } 1837 } else { 1838 gl_FragColor.rgb = dirLm.xyz; 1839 gl_FragColor.a = max(dirLm.w, dAtten > 0.00001 ? (1.0/255.0) : 0.0); 1840 } 1841`,i2=` 1842#ifdef LIT_LIGHTMAP_BAKING_ADD_AMBIENT 1843 dDiffuseLight = ((dDiffuseLight - 0.5) * max(ambientBakeOcclusionContrast + 1.0, 0.0)) + 0.5; 1844 dDiffuseLight += vec3(ambientBakeOcclusionBrightness); 1845 dDiffuseLight = saturate(dDiffuseLight); 1846 dDiffuseLight *= dAmbientLight; 1847#endif 1848#ifdef LIGHTMAP_RGBM 1849 gl_FragColor.rgb = dDiffuseLight; 1850 gl_FragColor.rgb = pow(gl_FragColor.rgb, vec3(0.5)); 1851 gl_FragColor.rgb /= 8.0; 1852 gl_FragColor.a = clamp( max( max( gl_FragColor.r, gl_FragColor.g ), max( gl_FragColor.b, 1.0 / 255.0 ) ), 0.0,1.0 ); 1853 gl_FragColor.a = ceil(gl_FragColor.a * 255.0) / 255.0; 1854 gl_FragColor.rgb /= gl_FragColor.a; 1855#else 1856 gl_FragColor = vec4(dDiffuseLight, 1.0); 1857#endif 1858`,r2=` 1859uniform vec3 view_position; 1860uniform vec3 light_globalAmbient; 1861float square(float x) { 1862 return x*x; 1863} 1864float saturate(float x) { 1865 return clamp(x, 0.0, 1.0); 1866} 1867vec3 saturate(vec3 x) { 1868 return clamp(x, vec3(0.0), vec3(1.0)); 1869} 1870`,a2=` 1871#define NINESLICED 1872varying vec2 vMask; 1873varying vec2 vTiledUv; 1874uniform mediump vec4 innerOffset; 1875uniform mediump vec2 outerScale; 1876uniform mediump vec4 atlasRect; 1877vec2 nineSlicedUv; 1878`,n2=` 1879#define NINESLICED 1880#define NINESLICETILED 1881varying vec2 vMask; 1882varying vec2 vTiledUv; 1883uniform mediump vec4 innerOffset; 1884uniform mediump vec2 outerScale; 1885uniform mediump vec4 atlasRect; 1886vec2 nineSlicedUv; 1887`,o2=` 1888float bayer2(vec2 p) { 1889 return mod(2.0 * p.y + p.x + 1.0, 4.0); 1890} 1891float bayer4(vec2 p) { 1892 vec2 p1 = mod(p, 2.0); 1893 vec2 p2 = floor(0.5 * mod(p, 4.0)); 1894 return 4.0 * bayer2(p1) + bayer2(p2); 1895} 1896float bayer8(vec2 p) { 1897 vec2 p1 = mod(p, 2.0); 1898 vec2 p2 = floor(0.5 * mod(p, 4.0));
1899 vec2 p4 = floor(0.25 * mod(p, 8.0)); 1900 return 4.0 * (4.0 * bayer2(p1) + bayer2(p2)) + bayer2(p4); 1901} 1902`,l2=` 1903varying vec2 vUv0; 1904uniform sampler2D source; 1905uniform vec2 pixelOffset; 1906#ifdef GAUSS 1907 uniform float weight[{SAMPLES}]; 1908#endif 1909void main(void) { 1910 vec3 moments = vec3(0.0); 1911 vec2 uv = vUv0 - pixelOffset * (float({SAMPLES}) * 0.5); 1912 for (int i = 0; i < {SAMPLES}; i++) { 1913 vec4 c = texture2D(source, uv + pixelOffset * float(i)); 1914 #ifdef GAUSS 1915 moments += c.xyz * weight[i]; 1916 #else 1917 moments += c.xyz; 1918 #endif 1919 } 1920 #ifndef GAUSS 1921 moments *= 1.0 / float({SAMPLES}); 1922 #endif 1923 gl_FragColor = vec4(moments.x, moments.y, moments.z, 1.0); 1924} 1925`,c2=` 1926uniform float material_clearCoat; 1927void getClearCoat() { 1928 ccSpecularity = material_clearCoat; 1929 #ifdef STD_CLEARCOAT_TEXTURE 1930 ccSpecularity *= texture2DBias({STD_CLEARCOAT_TEXTURE_NAME}, {STD_CLEARCOAT_TEXTURE_UV}, textureBias).{STD_CLEARCOAT_TEXTURE_CHANNEL}; 1931 #endif 1932 #ifdef STD_CLEARCOAT_VERTEX 1933 ccSpecularity *= saturate(vVertexColor.{STD_CLEARCOAT_VERTEX_CHANNEL}); 1934 #endif 1935} 1936`,h2=` 1937uniform float material_clearCoatGloss; 1938void getClearCoatGlossiness() { 1939 ccGlossiness = material_clearCoatGloss; 1940 #ifdef STD_CLEARCOATGLOSS_TEXTURE 1941 ccGlossiness *= texture2DBias({STD_CLEARCOATGLOSS_TEXTURE_NAME}, {STD_CLEARCOATGLOSS_TEXTURE_UV}, textureBias).{STD_CLEARCOATGLOSS_TEXTURE_CHANNEL}; 1942 #endif 1943 #ifdef STD_CLEARCOATGLOSS_VERTEX 1944 ccGlossiness *= saturate(vVertexColor.{STD_CLEARCOATGLOSS_VERTEX_CHANNEL}); 1945 #endif 1946 #ifdef STD_CLEARCOATGLOSS_INVERT 1947 ccGlossiness = 1.0 - ccGlossiness; 1948 #endif 1949 ccGlossiness += 0.0000001; 1950} 1951`,d2=` 1952#ifdef STD_CLEARCOATNORMAL_TEXTURE 1953uniform float material_clearCoatBumpiness; 1954#endif 1955void getClearCoatNormal() { 1956#ifdef STD_CLEARCOATNORMAL_TEXTURE 1957 vec3 normalMap = {STD_CLEARCOATNORMAL_TEXTURE_DECODE}(texture2DBias({STD_CLEARCOATNORMAL_TEXTURE_NAME}, {STD_CLEARCOATNORMAL_TEXTURE_UV}, textureBias)); 1958 normalMap = mix(vec3(0.0, 0.0, 1.0), normalMap, material_clearCoatBumpiness); 1959 ccNormalW = normalize(dTBN * normalMap); 1960#else 1961 ccNormalW = dVertexNormalW; 1962#endif 1963} 1964`,u2=` 1965vec2 getCubemapFaceCoordinates(const vec3 dir, out float faceIndex, out vec2 tileOffset) 1966{ 1967 vec3 vAbs = abs(dir); 1968 float ma; 1969 vec2 uv; 1970 if (vAbs.z >= vAbs.x && vAbs.z >= vAbs.y) { 1971 faceIndex = dir.z < 0.0 ? 5.0 : 4.0; 1972 ma = 0.5 / vAbs.z; 1973 uv = vec2(dir.z < 0.0 ? -dir.x : dir.x, -dir.y); 1974 tileOffset.x = 2.0; 1975 tileOffset.y = dir.z < 0.0 ? 1.0 : 0.0; 1976 } else if(vAbs.y >= vAbs.x) { 1977 faceIndex = dir.y < 0.0 ? 3.0 : 2.0; 1978 ma = 0.5 / vAbs.y; 1979 uv = vec2(dir.x, dir.y < 0.0 ? -dir.z : dir.z); 1980 tileOffset.x = 1.0; 1981 tileOffset.y = dir.y < 0.0 ? 1.0 : 0.0; 1982 } else { 1983 faceIndex = dir.x < 0.0 ? 1.0 : 0.0; 1984 ma = 0.5 / vAbs.x; 1985 uv = vec2(dir.x < 0.0 ? dir.z : -dir.z, -dir.y); 1986 tileOffset.x = 0.0; 1987 tileOffset.y = dir.x < 0.0 ? 1.0 : 0.0; 1988 } 1989 return uv * ma + 0.5; 1990} 1991vec2 getCubemapAtlasCoordinates(const vec3 omniAtlasViewport, float shadowEdgePixels, float shadowTextureResolution, const vec3 dir) { 1992 float faceIndex; 1993 vec2 tileOffset; 1994 vec2 uv = getCubemapFaceCoordinates(dir, faceIndex, tileOffset); 1995 float atlasFaceSize = omniAtlasViewport.z; 1996 float tileSize = shadowTextureResolution * atlasFaceSize; 1997 float offset = shadowEdgePixels / tileSize; 1998 uv = uv * vec2(1.0 - offset * 2.0) + vec2(offset * 1.0); 1999 uv *= atlasFaceSize; 2000 uv += tileOffset * atlasFaceSize; 2001 uv += omniAtlasViewport.xy; 2002 return uv; 2003} 2004`,f2=` 2005vec3 _getCookieClustered(TEXTURE_ACCEPT(tex), vec2 uv, float intensity, vec4 cookieChannel) { 2006 vec4 pixel = mix(vec4(1.0), texture2DLod(tex, uv, 0.0), intensity); 2007 bool isRgb = dot(cookieChannel.rgb, vec3(1.0)) == 3.0; 2008 return isRgb ? pixel.rgb : vec3(dot(pixel, cookieChannel)); 2009} 2010vec3 getCookie2DClustered(TEXTURE_ACCEPT(tex), mat4 transform, vec3 worldPosition, float intensity, vec4 cookieChannel) {
2011 vec4 projPos = transform * vec4(worldPosition, 1.0); 2012 return _getCookieClustered(TEXTURE_PASS(tex), projPos.xy / projPos.w, intensity, cookieChannel); 2013} 2014vec3 getCookieCubeClustered(TEXTURE_ACCEPT(tex), vec3 dir, float intensity, vec4 cookieChannel, float shadowTextureResolution, float shadowEdgePixels, vec3 omniAtlasViewport) { 2015 vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir); 2016 return _getCookieClustered(TEXTURE_PASS(tex), uv, intensity, cookieChannel); 2017} 2018`,p2=` 2019vec3 _getShadowCoordPerspZbuffer(mat4 shadowMatrix, vec4 shadowParams, vec3 wPos) { 2020 vec4 projPos = shadowMatrix * vec4(wPos, 1.0); 2021 projPos.xyz /= projPos.w; 2022 return projPos.xyz; 2023} 2024vec3 getShadowCoordPerspZbufferNormalOffset(mat4 shadowMatrix, vec4 shadowParams, vec3 normal) { 2025 vec3 wPos = vPositionW + normal * shadowParams.y; 2026 return _getShadowCoordPerspZbuffer(shadowMatrix, shadowParams, wPos); 2027} 2028vec3 normalOffsetPointShadow(vec4 shadowParams, vec3 lightPos, vec3 lightDir, vec3 lightDirNorm, vec3 normal) { 2029 float distScale = length(lightDir); 2030 vec3 wPos = vPositionW + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale; 2031 vec3 dir = wPos - lightPos; 2032 return dir; 2033} 2034#if defined(CLUSTER_SHADOW_TYPE_PCF1) 2035float getShadowOmniClusteredPCF1(SHADOWMAP_ACCEPT(shadowMap), vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) { 2036 float shadowTextureResolution = shadowParams.x; 2037 vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir); 2038 float shadowZ = length(lightDir) * shadowParams.w + shadowParams.z; 2039 return textureShadow(shadowMap, vec3(uv, shadowZ)); 2040} 2041#endif 2042#if defined(CLUSTER_SHADOW_TYPE_PCF3) 2043float getShadowOmniClusteredPCF3(SHADOWMAP_ACCEPT(shadowMap), vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) { 2044 float shadowTextureResolution = shadowParams.x; 2045 vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir); 2046 float shadowZ = length(lightDir) * shadowParams.w + shadowParams.z; 2047 vec3 shadowCoord = vec3(uv, shadowZ); 2048 return getShadowPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams); 2049} 2050#endif 2051#if defined(CLUSTER_SHADOW_TYPE_PCF5) 2052float getShadowOmniClusteredPCF5(SHADOWMAP_ACCEPT(shadowMap), vec4 shadowParams, vec3 omniAtlasViewport, float shadowEdgePixels, vec3 lightDir) { 2053 float shadowTextureResolution = shadowParams.x; 2054 vec2 uv = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir); 2055 float shadowZ = length(lightDir) * shadowParams.w + shadowParams.z; 2056 vec3 shadowCoord = vec3(uv, shadowZ); 2057 return getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams); 2058} 2059#endif 2060#if defined(CLUSTER_SHADOW_TYPE_PCF1) 2061float getShadowSpotClusteredPCF1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) { 2062 return textureShadow(shadowMap, shadowCoord); 2063} 2064#endif 2065#if defined(CLUSTER_SHADOW_TYPE_PCF3) 2066float getShadowSpotClusteredPCF3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) { 2067 return getShadowSpotPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams); 2068} 2069#endif 2070#if defined(CLUSTER_SHADOW_TYPE_PCF5) 2071float getShadowSpotClusteredPCF5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) { 2072 return getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams); 2073} 2074#endif 2075`,m2=` 2076#include "lightBufferDefinesPS" 2077#include "clusteredLightUtilsPS" 2078#ifdef CLUSTER_COOKIES 2079 #include "clusteredLightCookiesPS" 2080#endif 2081#ifdef CLUSTER_SHADOWS 2082 #include "clusteredLightShadowsPS" 2083#endif 2084uniform highp usampler2D clusterWorldTexture; 2085uniform highp sampler2D lightsTexture; 2086#ifdef CLUSTER_SHADOWS 2087 uniform sampler2DShadow shadowAtlasTexture; 2088#endif 2089#ifdef CLUSTER_COOKIES 2090 uniform sampler2D cookieAtlasTexture; 2091#endif 2092uniform int clusterMaxCells; 2093uniform int numClusteredLights; 2094uniform int clusterTextureWidth; 2095uniform vec3 clusterCellsCountByBoundsSize; 2096uniform vec3 clusterBoundsMin; 2097uniform vec3 clusterBoundsDelta; 2098uniform ivec3 clusterCellsDot; 2099uniform ivec3 clusterCellsMax; 2100uniform vec2 shadowAtlasParams; 2101struct ClusterLightData { 2102 vec3 position; 2103 int lightIndex; 2104 vec3 direction; 2105 uint shape; 2106 vec3 color; 2107 float shadowIntensity; 2108 float range; 2109 float biasesData; 2110 float cookieIntensity; 2111 bool isSpot; 2112 bool falloffModeLinear; 2113 bool isDynamic; 2114 bool isLightmapped; 2115}; 2116struct ClusterLightSpotData { 2117 float innerConeAngleCos; 2118 float outerConeAngleCos; 2119}; 2120struct ClusterLightAreaData { 2121 vec3 halfWidth; 2122 vec3 halfHeight; 2123}; 2124struct ClusterLightShadowData { 2125 float shadowBias; 2126 float shadowNormalBias; 2127}; 2128mat4 lightProjectionMatrix; 2129uint clusterLightData_flags; 2130float clusterLightData_anglesData; 2131uint clusterLightData_colorBFlagsData; 2132vec4 sampleLightTextureF(int lightIndex, int index) { 2133 return texelFetch(lightsTexture, ivec2(index, lightIndex), 0); 2134}
2135ClusterLightData decodeClusterLightCore(int lightIndex) { 2136 ClusterLightData clusterLightData; 2137 clusterLightData.lightIndex = lightIndex; 2138 vec4 halfData = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_COLOR_ANGLES_BIAS}); 2139 clusterLightData_anglesData = halfData.z; 2140 clusterLightData.biasesData = halfData.w; 2141 clusterLightData_colorBFlagsData = floatBitsToUint(halfData.y); 2142 vec2 colorRG = unpackHalf2x16(floatBitsToUint(halfData.x)); 2143 vec2 colorB_flags = unpackHalf2x16(clusterLightData_colorBFlagsData); 2144 clusterLightData.color = vec3(colorRG, colorB_flags.x) * {LIGHT_COLOR_DIVIDER}; 2145 vec4 lightPosRange = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_POSITION_RANGE}); 2146 clusterLightData.position = lightPosRange.xyz; 2147 clusterLightData.range = lightPosRange.w; 2148 vec4 lightDir_Flags = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_DIRECTION_FLAGS}); 2149 clusterLightData.direction = lightDir_Flags.xyz; 2150 clusterLightData_flags = floatBitsToUint(lightDir_Flags.w); 2151 clusterLightData.isSpot = (clusterLightData_flags & (1u << 30u)) != 0u; 2152 clusterLightData.shape = (clusterLightData_flags >> 28u) & 0x3u; 2153 clusterLightData.falloffModeLinear = (clusterLightData_flags & (1u << 27u)) == 0u; 2154 clusterLightData.shadowIntensity = float((clusterLightData_flags >> 0u) & 0xFFu) / 255.0; 2155 clusterLightData.cookieIntensity = float((clusterLightData_flags >> 8u) & 0xFFu) / 255.0; 2156 clusterLightData.isDynamic = (clusterLightData_flags & (1u << 22u)) != 0u; 2157 clusterLightData.isLightmapped = (clusterLightData_flags & (1u << 21u)) != 0u; 2158 return clusterLightData; 2159} 2160ClusterLightSpotData decodeClusterLightSpot() { 2161 uint angleFlags = (clusterLightData_colorBFlagsData >> 16u) & 0xFFFFu; 2162 vec2 angleValues = unpackHalf2x16(floatBitsToUint(clusterLightData_anglesData)); 2163 float innerVal = angleValues.x; 2164 float outerVal = angleValues.y; 2165 float innerIsVersine = float(angleFlags & 1u); 2166 float outerIsVersine = float((angleFlags >> 1u) & 1u); 2167 return ClusterLightSpotData( 2168 mix(innerVal, 1.0 - innerVal, innerIsVersine), 2169 mix(outerVal, 1.0 - outerVal, outerIsVersine) 2170 ); 2171} 2172vec3 decodeClusterLightOmniAtlasViewport(int lightIndex) { 2173 return sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_0}).xyz; 2174} 2175ClusterLightAreaData decodeClusterLightAreaData(int lightIndex) { 2176 return ClusterLightAreaData( 2177 sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_AREA_DATA_WIDTH}).xyz, 2178 sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_AREA_DATA_HEIGHT}).xyz 2179 ); 2180} 2181mat4 decodeClusterLightProjectionMatrixData(int lightIndex) { 2182 vec4 m0 = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_0}); 2183 vec4 m1 = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_1}); 2184 vec4 m2 = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_2}); 2185 vec4 m3 = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_3}); 2186 return mat4(m0, m1, m2, m3); 2187} 2188ClusterLightShadowData decodeClusterLightShadowData(float biasesData) { 2189 vec2 biases = unpackHalf2x16(floatBitsToUint(biasesData)); 2190 return ClusterLightShadowData(biases.x, biases.y); 2191} 2192vec4 decodeClusterLightCookieData() { 2193 uint cookieFlags = (clusterLightData_flags >> 23u) & 0x0Fu; 2194 vec4 mask = vec4(uvec4(cookieFlags) & uvec4(1u, 2u, 4u, 8u)); 2195 return step(1.0, mask); 2196} 2197void evaluateLight( 2198 ClusterLightData light, 2199 vec3 worldNormal, 2200 vec3 viewDir, 2201 vec3 reflectionDir, 2202#if defined(LIT_CLEARCOAT) 2203 vec3 clearcoatReflectionDir, 2204#endif 2205 float gloss, 2206 vec3 specularity, 2207 vec3 geometricNormal, 2208 mat3 tbn, 2209#if defined(LIT_IRIDESCENCE) 2210 vec3 iridescenceFresnel, 2211#endif 2212 vec3 clearcoat_worldNormal, 2213 float clearcoat_gloss, 2214 float sheen_gloss, 2215 float iridescence_intensity 2216) { 2217 vec3 cookieAttenuation = vec3(1.0); 2218 float diffuseAttenuation = 1.0; 2219 float falloffAttenuation = 1.0; 2220 vec3 lightDirW = evalOmniLight(light.position); 2221 vec3 lightDirNormW = normalize(lightDirW); 2222 #ifdef CLUSTER_AREALIGHTS 2223 if (light.shape != {LIGHTSHAPE_PUNCTUAL}) { 2224 ClusterLightAreaData areaData = decodeClusterLightAreaData(light.lightIndex); 2225 if (light.shape == {LIGHTSHAPE_RECT}) { 2226 calcRectLightValues(light.position, areaData.halfWidth, areaData.halfHeight); 2227 } else if (light.shape == {LIGHTSHAPE_DISK}) { 2228 calcDiskLightValues(light.position, areaData.halfWidth, areaData.halfHeight); 2229 } else { 2230 calcSphereLightValues(light.position, areaData.halfWidth, areaData.halfHeight); 2231 } 2232 falloffAttenuation = getFalloffWindow(light.range, lightDirW); 2233 } else 2234 #endif 2235 { 2236 if (light.falloffModeLinear) 2237 falloffAttenuation = getFalloffLinear(light.range, lightDirW); 2238 else 2239 falloffAttenuation = getFalloffInvSquared(light.range, lightDirW); 2240 } 2241 if (falloffAttenuation > 0.00001) { 2242 #ifdef CLUSTER_AREALIGHTS 2243 if (light.shape != {LIGHTSHAPE_PUNCTUAL}) { 2244 if (light.shape == {LIGHTSHAPE_RECT}) { 2245 diffuseAttenuation = getRectLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0; 2246 } else if (light.shape == {LIGHTSHAPE_DISK}) { 2247 diffuseAttenuation = getDiskLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0; 2248 } else { 2249 diffuseAttenuation = getSphereLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0; 2250 } 2251 } else 2252 #endif 2253 { 2254 falloffAttenuation *= getLightDiffuse(worldNormal, viewDir, lightDirNormW); 2255 } 2256 if (light.isSpot) { 2257 ClusterLightSpotData spotData = decodeClusterLightSpot(); 2258 falloffAttenuation *= getSpotEffect(light.direction, spotData.innerConeAngleCos, spotData.outerConeAngleCos, lightDirNormW); 2259 } 2260 #if defined(CLUSTER_COOKIES) || defined(CLUSTER_SHADOWS) 2261 if (falloffAttenuation > 0.00001) { 2262 if (light.shadowIntensity > 0.0 || light.cookieIntensity > 0.0) {
2263 vec3 omniAtlasViewport = vec3(0.0); 2264 if (light.isSpot) { 2265 lightProjectionMatrix = decodeClusterLightProjectionMatrixData(light.lightIndex); 2266 } else { 2267 omniAtlasViewport = decodeClusterLightOmniAtlasViewport(light.lightIndex); 2268 } 2269 float shadowTextureResolution = shadowAtlasParams.x; 2270 float shadowEdgePixels = shadowAtlasParams.y; 2271 #ifdef CLUSTER_COOKIES 2272 if (light.cookieIntensity > 0.0) { 2273 vec4 cookieChannelMask = decodeClusterLightCookieData(); 2274 if (light.isSpot) { 2275 cookieAttenuation = getCookie2DClustered(TEXTURE_PASS(cookieAtlasTexture), lightProjectionMatrix, vPositionW, light.cookieIntensity, cookieChannelMask); 2276 } else { 2277 cookieAttenuation = getCookieCubeClustered(TEXTURE_PASS(cookieAtlasTexture), lightDirW, light.cookieIntensity, cookieChannelMask, shadowTextureResolution, shadowEdgePixels, omniAtlasViewport); 2278 } 2279 } 2280 #endif 2281 #ifdef CLUSTER_SHADOWS 2282 if (light.shadowIntensity > 0.0) { 2283 ClusterLightShadowData shadowData = decodeClusterLightShadowData(light.biasesData); 2284 vec4 shadowParams = vec4(shadowTextureResolution, shadowData.shadowNormalBias, shadowData.shadowBias, 1.0 / light.range); 2285 if (light.isSpot) { 2286 vec3 shadowCoord = getShadowCoordPerspZbufferNormalOffset(lightProjectionMatrix, shadowParams, geometricNormal); 2287 2288 #if defined(CLUSTER_SHADOW_TYPE_PCF1) 2289 float shadow = getShadowSpotClusteredPCF1(SHADOWMAP_PASS(shadowAtlasTexture), shadowCoord, shadowParams); 2290 #elif defined(CLUSTER_SHADOW_TYPE_PCF3) 2291 float shadow = getShadowSpotClusteredPCF3(SHADOWMAP_PASS(shadowAtlasTexture), shadowCoord, shadowParams); 2292 #elif defined(CLUSTER_SHADOW_TYPE_PCF5) 2293 float shadow = getShadowSpotClusteredPCF5(SHADOWMAP_PASS(shadowAtlasTexture), shadowCoord, shadowParams); 2294 #elif defined(CLUSTER_SHADOW_TYPE_PCSS) 2295 float shadow = getShadowSpotClusteredPCSS(SHADOWMAP_PASS(shadowAtlasTexture), shadowCoord, shadowParams); 2296 #endif 2297 falloffAttenuation *= mix(1.0, shadow, light.shadowIntensity); 2298 } else { 2299 vec3 dir = normalOffsetPointShadow(shadowParams, light.position, lightDirW, lightDirNormW, geometricNormal); 2300 #if defined(CLUSTER_SHADOW_TYPE_PCF1) 2301 float shadow = getShadowOmniClusteredPCF1(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, omniAtlasViewport, shadowEdgePixels, dir); 2302 #elif defined(CLUSTER_SHADOW_TYPE_PCF3) 2303 float shadow = getShadowOmniClusteredPCF3(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, omniAtlasViewport, shadowEdgePixels, dir); 2304 #elif defined(CLUSTER_SHADOW_TYPE_PCF5) 2305 float shadow = getShadowOmniClusteredPCF5(SHADOWMAP_PASS(shadowAtlasTexture), shadowParams, omniAtlasViewport, shadowEdgePixels, dir); 2306 #endif 2307 falloffAttenuation *= mix(1.0, shadow, light.shadowIntensity); 2308 } 2309 } 2310 #endif 2311 } 2312 } 2313 #endif 2314 #ifdef CLUSTER_AREALIGHTS 2315 if (light.shape != {LIGHTSHAPE_PUNCTUAL}) { 2316 { 2317 vec3 areaDiffuse = (diffuseAttenuation * falloffAttenuation) * light.color * cookieAttenuation; 2318 #if defined(LIT_SPECULAR) 2319 areaDiffuse = mix(areaDiffuse, vec3(0), dLTCSpecFres); 2320 #endif 2321 dDiffuseLight += areaDiffuse; 2322 } 2323 #ifdef LIT_SPECULAR 2324 float areaLightSpecular; 2325 if (light.shape == {LIGHTSHAPE_RECT}) { 2326 areaLightSpecular = getRectLightSpecular(worldNormal, viewDir); 2327 } else if (light.shape == {LIGHTSHAPE_DISK}) { 2328 areaLightSpecular = getDiskLightSpecular(worldNormal, viewDir); 2329 } else { 2330 areaLightSpecular = getSphereLightSpecular(worldNormal, viewDir); 2331 } 2332 dSpecularLight += dLTCSpecFres * areaLightSpecular * falloffAttenuation * light.color * cookieAttenuation; 2333 #ifdef LIT_CLEARCOAT 2334 float areaLightSpecularCC; 2335 if (light.shape == {LIGHTSHAPE_RECT}) { 2336 areaLightSpecularCC = getRectLightSpecular(clearcoat_worldNormal, viewDir); 2337 } else if (light.shape == {LIGHTSHAPE_DISK}) { 2338 areaLightSpecularCC = getDiskLightSpecular(clearcoat_worldNormal, viewDir); 2339 } else { 2340 areaLightSpecularCC = getSphereLightSpecular(clearcoat_worldNormal, viewDir); 2341 } 2342 ccSpecularLight += ccLTCSpecFres * areaLightSpecularCC * falloffAttenuation * light.color * cookieAttenuation; 2343 #endif 2344 #endif 2345 } else 2346 #endif 2347 { 2348 { 2349 vec3 punctualDiffuse = falloffAttenuation * light.color * cookieAttenuation; 2350 #if defined(CLUSTER_AREALIGHTS) 2351 #if defined(LIT_SPECULAR) 2352 punctualDiffuse = mix(punctualDiffuse, vec3(0), specularity); 2353 #endif 2354 #endif 2355 dDiffuseLight += punctualDiffuse; 2356 } 2357 2358 #ifdef LIT_SPECULAR 2359 vec3 halfDir = normalize(-lightDirNormW + viewDir); 2360 2361 #ifdef LIT_SPECULAR_FRESNEL 2362 dSpecularLight += 2363 getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, lightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * 2364 getFresnel( 2365 dot(viewDir, halfDir), 2366 gloss, 2367 specularity 2368 #if defined(LIT_IRIDESCENCE) 2369 , iridescenceFresnel, 2370 iridescence_intensity 2371 #endif 2372 ); 2373 #else 2374 dSpecularLight += getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, lightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * specularity; 2375 #endif 2376 #ifdef LIT_CLEARCOAT 2377 #ifdef LIT_SPECULAR_FRESNEL 2378 ccSpecularLight += getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat_worldNormal, viewDir, lightDirNormW, clearcoat_gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * getFresnelCC(dot(viewDir, halfDir)); 2379 #else 2380 ccSpecularLight += getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat_worldNormal, viewDir, lightDirNormW, clearcoat_gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation; 2381 #endif 2382 #endif 2383 #ifdef LIT_SHEEN 2384 sSpecularLight += getLightSpecularSheen(halfDir, worldNormal, viewDir, lightDirNormW, sheen_gloss) * falloffAttenuation * light.color * cookieAttenuation; 2385 #endif 2386 #endif 2387 } 2388 } 2389 dAtten = falloffAttenuation; 2390 dLightDirNormW = lightDirNormW; 2391} 2392void evaluateClusterLight( 2393 int lightIndex, 2394 vec3 worldNormal, 2395 vec3 viewDir, 2396 vec3 reflectionDir, 2397#if defined(LIT_CLEARCOAT) 2398 vec3 clearcoatReflectionDir, 2399#endif 2400 float gloss, 2401 vec3 specularity, 2402 vec3 geometricNormal, 2403 mat3 tbn, 2404#if defined(LIT_IRIDESCENCE) 2405 vec3 iridescenceFresnel, 2406#endif 2407 vec3 clearcoat_worldNormal, 2408 float clearcoat_gloss, 2409 float sheen_gloss, 2410 float iridescence_intensity 2411) { 2412 ClusterLightData clusterLightData = decodeClusterLightCore(lightIndex); 2413 #ifdef CLUSTER_MESH_DYNAMIC_LIGHTS 2414 bool acceptLightMask = clusterLightData.isDynamic; 2415 #else 2416 bool acceptLightMask = clusterLightData.isLightmapped; 2417 #endif 2418 if (acceptLightMask) 2419 evaluateLight( 2420 clusterLightData, 2421 worldNormal, 2422 viewDir, 2423 reflectionDir, 2424#if defined(LIT_CLEARCOAT) 2425 clearcoatReflectionDir, 2426#endif 2427 gloss, 2428 specularity, 2429 geometricNormal, 2430 tbn, 2431#if defined(LIT_IRIDESCENCE) 2432 iridescenceFresnel, 2433#endif 2434 clearcoat_worldNormal, 2435 clearcoat_gloss, 2436 sheen_gloss, 2437 iridescence_intensity 2438 ); 2439} 2440void addClusteredLights( 2441 vec3 worldNormal, 2442 vec3 viewDir, 2443 vec3 reflectionDir, 2444#if defined(LIT_CLEARCOAT) 2445 vec3 clearcoatReflectionDir, 2446#endif 2447 float gloss, 2448 vec3 specularity, 2449 vec3 geometricNormal, 2450 mat3 tbn, 2451#if defined(LIT_IRIDESCENCE) 2452 vec3 iridescenceFresnel, 2453#endif 2454 vec3 clearcoat_worldNormal, 2455 float clearcoat_gloss, 2456 float sheen_gloss, 2457 float iridescence_intensity 2458) { 2459 if (numClusteredLights <= 1) 2460 return;
2461 ivec3 cellCoords = ivec3(floor((vPositionW - clusterBoundsMin) * clusterCellsCountByBoundsSize)); 2462 if (!(any(lessThan(cellCoords, ivec3(0))) || any(greaterThanEqual(cellCoords, clusterCellsMax)))) { 2463 int cellIndex = cellCoords.x * clusterCellsDot.x + cellCoords.y * clusterCellsDot.y + cellCoords.z * clusterCellsDot.z; 2464 int clusterV = cellIndex / clusterTextureWidth; 2465 int clusterU = cellIndex - clusterV * clusterTextureWidth; 2466 for (int lightCellIndex = 0; lightCellIndex < clusterMaxCells; lightCellIndex++) { 2467 uint lightIndex = texelFetch(clusterWorldTexture, ivec2(clusterU + lightCellIndex, clusterV), 0).x; 2468 if (lightIndex == 0u) 2469 break; 2470 evaluateClusterLight( 2471 int(lightIndex), 2472 worldNormal, 2473 viewDir, 2474 reflectionDir, 2475#if defined(LIT_CLEARCOAT) 2476 clearcoatReflectionDir, 2477#endif 2478 gloss, 2479 specularity, 2480 geometricNormal, 2481 tbn, 2482#if defined(LIT_IRIDESCENCE) 2483 iridescenceFresnel, 2484#endif 2485 clearcoat_worldNormal, 2486 clearcoat_gloss, 2487 sheen_gloss, 2488 iridescence_intensity 2489 ); 2490 } 2491 } 2492} 2493`,_2=` 2494vec3 combineColor(vec3 albedo, vec3 sheenSpecularity, float clearcoatSpecularity) { 2495 vec3 ret = vec3(0); 2496#ifdef LIT_OLD_AMBIENT 2497 ret += (dDiffuseLight - light_globalAmbient) * albedo + material_ambient * light_globalAmbient; 2498#else 2499 ret += albedo * dDiffuseLight; 2500#endif 2501#ifdef LIT_SPECULAR 2502 ret += dSpecularLight; 2503#endif 2504#ifdef LIT_REFLECTIONS 2505 ret += dReflection.rgb * dReflection.a; 2506#endif 2507#ifdef LIT_SHEEN 2508 float sheenScaling = 1.0 - max(max(sheenSpecularity.r, sheenSpecularity.g), sheenSpecularity.b) * 0.157; 2509 ret = ret * sheenScaling + (sSpecularLight + sReflection.rgb) * sheenSpecularity; 2510#endif 2511#ifdef LIT_CLEARCOAT 2512 float clearCoatScaling = 1.0 - ccFresnel * clearcoatSpecularity; 2513 ret = ret * clearCoatScaling + (ccSpecularLight + ccReflection) * clearcoatSpecularity; 2514#endif 2515 return ret; 2516} 2517`,g2=` 2518 varying vec2 uv0; 2519 uniform sampler2D blitTexture; 2520 void main(void) { 2521 gl_FragColor = texture2D(blitTexture, uv0); 2522 } 2523`,v2=` 2524 varying vec2 uv0; 2525 uniform samplerCube blitTexture; 2526 uniform mat4 invViewProj; 2527 void main(void) { 2528 vec4 projPos = vec4(uv0 * 2.0 - 1.0, 0.5, 1.0); 2529 vec4 worldPos = invViewProj * projPos; 2530 gl_FragColor = textureCube(blitTexture, worldPos.xyz); 2531 } 2532`,S2=` 2533 attribute vec2 vertex_position; 2534 varying vec2 uv0; 2535 void main(void) { 2536 gl_Position = vec4(vertex_position, 0.5, 1.0); 2537 uv0 = vertex_position.xy * 0.5 + 0.5; 2538 #ifndef WEBGPU 2539 uv0.y = 1.0 - uv0.y; 2540 #endif 2541 } 2542`,y2=` 2543vec4 getCookie2D(sampler2D tex, mat4 transform, float intensity) { 2544 vec4 projPos = transform * vec4(vPositionW, 1.0); 2545 projPos.xy /= projPos.w; 2546 return mix(vec4(1.0), texture2D(tex, projPos.xy), intensity); 2547} 2548vec4 getCookie2DClip(sampler2D tex, mat4 transform, float intensity) { 2549 vec4 projPos = transform * vec4(vPositionW, 1.0); 2550 projPos.xy /= projPos.w; 2551 if (projPos.x < 0.0 || projPos.x > 1.0 || projPos.y < 0.0 || projPos.y > 1.0 || projPos.z < 0.0) return vec4(0.0); 2552 return mix(vec4(1.0), texture2D(tex, projPos.xy), intensity); 2553} 2554vec4 getCookie2DXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) { 2555 vec4 projPos = transform * vec4(vPositionW, 1.0); 2556 projPos.xy /= projPos.w; 2557 projPos.xy += cookieOffset; 2558 vec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5); 2559 return mix(vec4(1.0), texture2D(tex, uv), intensity); 2560} 2561vec4 getCookie2DClipXform(sampler2D tex, mat4 transform, float intensity, vec4 cookieMatrix, vec2 cookieOffset) { 2562 vec4 projPos = transform * vec4(vPositionW, 1.0); 2563 projPos.xy /= projPos.w; 2564 projPos.xy += cookieOffset; 2565 if (projPos.x < 0.0 || projPos.x > 1.0 || projPos.y < 0.0 || projPos.y > 1.0 || projPos.z < 0.0) return vec4(0.0); 2566 vec2 uv = mat2(cookieMatrix) * (projPos.xy-vec2(0.5)) + vec2(0.5); 2567 return mix(vec4(1.0), texture2D(tex, uv), intensity); 2568} 2569vec4 getCookieCube(samplerCube tex, mat4 transform, float intensity) { 2570 return mix(vec4(1.0), textureCube(tex, dLightDirNormW * mat3(transform)), intensity); 2571} 2572`,x2=` 2573#if LIT_CUBEMAP_PROJECTION == BOX 2574 uniform vec3 envBoxMin; 2575 uniform vec3 envBoxMax; 2576#endif 2577vec3 cubeMapProject(vec3 nrdir) { 2578 #if LIT_CUBEMAP_PROJECTION == NONE 2579 return cubeMapRotate(nrdir); 2580 #endif 2581 #if LIT_CUBEMAP_PROJECTION == BOX 2582 nrdir = cubeMapRotate(nrdir);
2583 vec3 rbmax = (envBoxMax - vPositionW) / nrdir; 2584 vec3 rbmin = (envBoxMin - vPositionW) / nrdir; 2585 vec3 rbminmax = mix(rbmin, rbmax, vec3(greaterThan(nrdir, vec3(0.0)))); 2586 float fa = min(min(rbminmax.x, rbminmax.y), rbminmax.z); 2587 vec3 posonbox = vPositionW + nrdir * fa; 2588 vec3 envBoxPos = (envBoxMin + envBoxMax) * 0.5; 2589 return normalize(posonbox - envBoxPos); 2590 #endif 2591} 2592`,T2=` 2593#ifdef CUBEMAP_ROTATION 2594uniform mat3 cubeMapRotationMatrix; 2595#endif 2596vec3 cubeMapRotate(vec3 refDir) { 2597#ifdef CUBEMAP_ROTATION 2598 return refDir * cubeMapRotationMatrix; 2599#else 2600 return refDir; 2601#endif 2602} 2603`,w2=` 2604#ifdef DEBUG_ALBEDO_PASS 2605gl_FragColor = vec4(gammaCorrectOutput(dAlbedo), 1.0); 2606#endif 2607#ifdef DEBUG_UV0_PASS 2608gl_FragColor = vec4(litArgs_albedo , 1.0); 2609#endif 2610#ifdef DEBUG_WORLD_NORMAL_PASS 2611gl_FragColor = vec4(litArgs_worldNormal * 0.5 + 0.5, 1.0); 2612#endif 2613#ifdef DEBUG_OPACITY_PASS 2614gl_FragColor = vec4(vec3(litArgs_opacity) , 1.0); 2615#endif 2616#ifdef DEBUG_SPECULARITY_PASS 2617gl_FragColor = vec4(litArgs_specularity, 1.0); 2618#endif 2619#ifdef DEBUG_GLOSS_PASS 2620gl_FragColor = vec4(vec3(litArgs_gloss) , 1.0); 2621#endif 2622#ifdef DEBUG_METALNESS_PASS 2623gl_FragColor = vec4(vec3(litArgs_metalness) , 1.0); 2624#endif 2625#ifdef DEBUG_AO_PASS 2626gl_FragColor = vec4(vec3(litArgs_ao) , 1.0); 2627#endif 2628#ifdef DEBUG_EMISSION_PASS 2629gl_FragColor = vec4(gammaCorrectOutput(litArgs_emission), 1.0); 2630#endif 2631`,C2=` 2632#ifdef DEBUG_LIGHTING_PASS 2633litArgs_albedo = vec3(0.5); 2634#endif 2635#ifdef DEBUG_UV0_PASS 2636#ifdef VARYING_VUV0 2637litArgs_albedo = vec3(vUv0, 0); 2638#else 2639litArgs_albedo = vec3(0); 2640#endif 2641#endif 2642`,E2=` 2643#ifndef _DECODE_INCLUDED_ 2644#define _DECODE_INCLUDED_ 2645vec3 decodeLinear(vec4 raw) { 2646 return raw.rgb; 2647} 2648float decodeGamma(float raw) { 2649 return pow(raw, 2.2); 2650} 2651vec3 decodeGamma(vec3 raw) { 2652 return pow(raw, vec3(2.2)); 2653} 2654vec3 decodeGamma(vec4 raw) { 2655 return pow(raw.xyz, vec3(2.2)); 2656} 2657vec3 decodeRGBM(vec4 raw) { 2658 vec3 color = (8.0 * raw.a) * raw.rgb; 2659 return color * color; 2660} 2661vec3 decodeRGBP(vec4 raw) { 2662 vec3 color = raw.rgb * (-raw.a * 7.0 + 8.0); 2663 return color * color; 2664} 2665vec3 decodeRGBE(vec4 raw) { 2666 if (raw.a == 0.0) { 2667 return vec3(0.0, 0.0, 0.0); 2668 } else { 2669 return raw.xyz * pow(2.0, raw.w * 255.0 - 128.0); 2670 } 2671} 2672vec4 passThrough(vec4 raw) { 2673 return raw; 2674} 2675vec3 unpackNormalXYZ(vec4 nmap) { 2676 return nmap.xyz * 2.0 - 1.0; 2677} 2678vec3 unpackNormalXY(vec4 nmap) { 2679 vec3 normal; 2680 normal.xy = nmap.wy * 2.0 - 1.0; 2681 normal.z = sqrt(1.0 - clamp(dot(normal.xy, normal.xy), 0.0, 1.0)); 2682 return normal; 2683} 2684#endif 2685`,b2=` 2686#ifndef _DETAILMODES_INCLUDED_ 2687#define _DETAILMODES_INCLUDED_
2688vec3 detailMode_mul(vec3 c1, vec3 c2) { 2689 return c1 * c2; 2690} 2691vec3 detailMode_add(vec3 c1, vec3 c2) { 2692 return c1 + c2; 2693} 2694vec3 detailMode_screen(vec3 c1, vec3 c2) { 2695 return 1.0 - (1.0 - c1)*(1.0 - c2); 2696} 2697vec3 detailMode_overlay(vec3 c1, vec3 c2) { 2698 return mix(1.0 - 2.0 * (1.0 - c1)*(1.0 - c2), 2.0 * c1 * c2, step(c1, vec3(0.5))); 2699} 2700vec3 detailMode_min(vec3 c1, vec3 c2) { 2701 return min(c1, c2); 2702} 2703vec3 detailMode_max(vec3 c1, vec3 c2) { 2704 return max(c1, c2); 2705} 2706#endif 2707`,A2=` 2708uniform vec3 material_diffuse; 2709#ifdef STD_DIFFUSEDETAIL_TEXTURE 2710 #include "detailModesPS" 2711#endif 2712void getAlbedo() { 2713 dAlbedo = material_diffuse.rgb; 2714 #ifdef STD_DIFFUSE_TEXTURE 2715 vec3 albedoTexture = {STD_DIFFUSE_TEXTURE_DECODE}(texture2DBias({STD_DIFFUSE_TEXTURE_NAME}, {STD_DIFFUSE_TEXTURE_UV}, textureBias)).{STD_DIFFUSE_TEXTURE_CHANNEL}; 2716 #ifdef STD_DIFFUSEDETAIL_TEXTURE 2717 vec3 albedoDetail = {STD_DIFFUSEDETAIL_TEXTURE_DECODE}(texture2DBias({STD_DIFFUSEDETAIL_TEXTURE_NAME}, {STD_DIFFUSEDETAIL_TEXTURE_UV}, textureBias)).{STD_DIFFUSEDETAIL_TEXTURE_CHANNEL}; 2718 albedoTexture = detailMode_{STD_DIFFUSEDETAIL_DETAILMODE}(albedoTexture, albedoDetail); 2719 #endif 2720 dAlbedo *= albedoTexture; 2721 #endif 2722 #ifdef STD_DIFFUSE_VERTEX 2723 dAlbedo *= saturate(vVertexColor.{STD_DIFFUSE_VERTEX_CHANNEL}); 2724 #endif 2725} 2726`,P2=` 2727uniform vec3 material_emissive; 2728uniform float material_emissiveIntensity; 2729void getEmission() { 2730 dEmission = material_emissive * material_emissiveIntensity; 2731 #ifdef STD_EMISSIVE_TEXTURE 2732 dEmission *= {STD_EMISSIVE_TEXTURE_DECODE}(texture2DBias({STD_EMISSIVE_TEXTURE_NAME}, {STD_EMISSIVE_TEXTURE_UV}, textureBias)).{STD_EMISSIVE_TEXTURE_CHANNEL}; 2733 #endif 2734 #ifdef STD_EMISSIVE_VERTEX 2735 dEmission *= saturate(vVertexColor.{STD_EMISSIVE_VERTEX_CHANNEL}); 2736 #endif 2737} 2738`,I2=` 2739vec4 encodeLinear(vec3 source) { 2740 return vec4(source, 1.0); 2741} 2742vec4 encodeGamma(vec3 source) { 2743 return vec4(pow(source + 0.0000001, vec3(1.0 / 2.2)), 1.0); 2744} 2745vec4 encodeRGBM(vec3 source) { 2746 vec4 result; 2747 result.rgb = pow(source.rgb, vec3(0.5)); 2748 result.rgb *= 1.0 / 8.0; 2749 result.a = saturate( max( max( result.r, result.g ), max( result.b, 1.0 / 255.0 ) ) ); 2750 result.a = ceil(result.a * 255.0) / 255.0; 2751 result.rgb /= result.a; 2752 return result; 2753} 2754vec4 encodeRGBP(vec3 source) { 2755 vec3 gamma = pow(source, vec3(0.5)); 2756 float maxVal = min(8.0, max(1.0, max(gamma.x, max(gamma.y, gamma.z)))); 2757 float v = 1.0 - ((maxVal - 1.0) / 7.0); 2758 v = ceil(v * 255.0) / 255.0; 2759 return vec4(gamma / (-v * 7.0 + 8.0), v); 2760} 2761vec4 encodeRGBE(vec3 source) { 2762 float maxVal = max(source.x, max(source.y, source.z)); 2763 if (maxVal < 1e-32) { 2764 return vec4(0, 0, 0, 0); 2765 } else { 2766 float e = ceil(log2(maxVal)); 2767 return vec4(source / pow(2.0, e), (e + 128.0) / 255.0); 2768 } 2769} 2770`,D2=` 2771 gl_FragColor.rgb = combineColor(litArgs_albedo, litArgs_sheen_specularity, litArgs_clearcoat_specularity); 2772 gl_FragColor.rgb += litArgs_emission; 2773 gl_FragColor.rgb = addFog(gl_FragColor.rgb); 2774 gl_FragColor.rgb = toneMap(gl_FragColor.rgb); 2775 gl_FragColor.rgb = gammaCorrectOutput(gl_FragColor.rgb); 2776`,M2=` 2777#ifndef _ENVATLAS_INCLUDED_ 2778#define _ENVATLAS_INCLUDED_ 2779const float atlasSize = 512.0; 2780const float seamSize = 1.0 / atlasSize; 2781vec2 mapUv(vec2 uv, vec4 rect) { 2782 return vec2(mix(rect.x + seamSize, rect.x + rect.z - seamSize, uv.x), 2783 mix(rect.y + seamSize, rect.y + rect.w - seamSize, uv.y)); 2784} 2785vec2 mapRoughnessUv(vec2 uv, float level) { 2786 float t = 1.0 / exp2(level); 2787 return mapUv(uv, vec4(0, 1.0 - t, t, t * 0.5)); 2788} 2789vec2 mapShinyUv(vec2 uv, float level) { 2790 float t = 1.0 / exp2(level); 2791 return mapUv(uv, vec4(1.0 - t, 1.0 - t, t, t * 0.5)); 2792} 2793#endif 2794`,R2=` 2795#ifdef LIT_SKYBOX_INTENSITY 2796 uniform float skyboxIntensity; 2797#endif 2798vec3 processEnvironment(vec3 color) { 2799 #ifdef LIT_SKYBOX_INTENSITY 2800 return color * skyboxIntensity; 2801 #else 2802 return color; 2803 #endif 2804} 2805`,L2=` 2806float getFalloffWindow(float lightRadius, vec3 lightDir) { 2807 float sqrDist = dot(lightDir, lightDir); 2808 float invRadius = 1.0 / lightRadius; 2809 return square(saturate(1.0 - square(sqrDist * square(invRadius)))); 2810} 2811float getFalloffInvSquared(float lightRadius, vec3 lightDir) { 2812 float sqrDist = dot(lightDir, lightDir); 2813 float falloff = 1.0 / (sqrDist + 1.0); 2814 float invRadius = 1.0 / lightRadius; 2815 falloff *= 16.0;
2816 falloff *= square(saturate(1.0 - square(sqrDist * square(invRadius)))); 2817 return falloff; 2818} 2819`,F2=` 2820float getFalloffLinear(float lightRadius, vec3 lightDir) { 2821 float d = length(lightDir); 2822 return max(((lightRadius - d) / lightRadius), 0.0); 2823} 2824`,O2=` 2825#ifndef FLOAT_AS_UINT 2826#define FLOAT_AS_UINT 2827vec4 float2uint(float value) { 2828 uint intBits = floatBitsToUint(value); 2829 return vec4( 2830 float((intBits >> 24u) & 0xFFu) / 255.0, 2831 float((intBits >> 16u) & 0xFFu) / 255.0, 2832 float((intBits >> 8u) & 0xFFu) / 255.0, 2833 float(intBits & 0xFFu) / 255.0 2834 ); 2835} 2836float uint2float(vec4 value) { 2837 uint intBits = 2838 (uint(value.r * 255.0) << 24u) | 2839 (uint(value.g * 255.0) << 16u) | 2840 (uint(value.b * 255.0) << 8u) | 2841 uint(value.a * 255.0); 2842 return uintBitsToFloat(intBits); 2843} 2844vec4 float2vec4(float value) { 2845 #if defined(CAPS_TEXTURE_FLOAT_RENDERABLE) 2846 return vec4(value, 1.0, 1.0, 1.0); 2847 #else 2848 return float2uint(value); 2849 #endif 2850} 2851#endif 2852`,B2=` 2853float dBlendModeFogFactor = 1.0; 2854#if (FOG != NONE) 2855 uniform vec3 fog_color; 2856 #if (FOG == LINEAR) 2857 uniform float fog_start; 2858 uniform float fog_end; 2859 #else 2860 uniform float fog_density; 2861 #endif 2862#endif 2863#ifdef VERTEXSHADER 2864 float getFogFactor(float depth) { 2865#else 2866 float getFogFactor() { 2867 float depth = gl_FragCoord.z / gl_FragCoord.w; 2868#endif 2869 float fogFactor = 0.0; 2870 #if (FOG == LINEAR) 2871 fogFactor = (fog_end - depth) / (fog_end - fog_start); 2872 #elif (FOG == EXP) 2873 fogFactor = exp(-depth * fog_density); 2874 #elif (FOG == EXP2) 2875 fogFactor = exp(-depth * depth * fog_density * fog_density); 2876 #endif 2877 return clamp(fogFactor, 0.0, 1.0); 2878} 2879#ifdef VERTEXSHADER 2880 vec3 addFog(vec3 color, float depth) { 2881 #if (FOG != NONE) 2882 return mix(fog_color * dBlendModeFogFactor, color, getFogFactor(depth)); 2883 #endif 2884 return color; 2885 } 2886#else 2887 vec3 addFog(vec3 color) { 2888 #if (FOG != NONE) 2889 return mix(fog_color * dBlendModeFogFactor, color, getFogFactor()); 2890 #endif 2891 return color; 2892 } 2893#endif 2894`,N2=` 2895float pow5(float x) { 2896 float x2 = x * x; 2897 return x2 * x2 * x; 2898} 2899vec3 getFresnel( 2900 float cosTheta, 2901 float gloss, 2902 vec3 specularity 2903#if defined(LIT_IRIDESCENCE) 2904 , vec3 iridescenceFresnel, 2905 float iridescenceIntensity 2906#endif 2907 ) { 2908 float fresnel = pow5(1.0 - saturate(cosTheta)); 2909 float glossSq = gloss * gloss; 2910 float specIntensity = max(specularity.r, max(specularity.g, specularity.b)); 2911 vec3 ret = specularity + (max(vec3(glossSq * specIntensity), specularity) - specularity) * fresnel; 2912#if defined(LIT_IRIDESCENCE) 2913 return mix(ret, iridescenceFresnel, iridescenceIntensity); 2914#else 2915 return ret; 2916#endif 2917} 2918float getFresnelCC(float cosTheta) { 2919 float fresnel = pow5(1.0 - saturate(cosTheta)); 2920 return 0.04 + (1.0 - 0.04) * fresnel; 2921} 2922`,k2=` 2923attribute vec2 vertex_position; 2924varying vec2 vUv0; 2925void main(void) 2926{ 2927 gl_Position = vec4(vertex_position, 0.5, 1.0); 2928 vUv0 = vertex_position.xy * 0.5 + 0.5; 2929} 2930`,U2=` 2931#include "decodePS" 2932#if (GAMMA == SRGB) 2933 float gammaCorrectInput(float color) { 2934 return decodeGamma(color); 2935 } 2936 vec3 gammaCorrectInput(vec3 color) { 2937 return decodeGamma(color); 2938 } 2939 vec4 gammaCorrectInput(vec4 color) { 2940 return vec4(decodeGamma(color.xyz), color.w); 2941 } 2942 vec3 gammaCorrectOutput(vec3 color) { 2943 return pow(color + 0.0000001, vec3(1.0 / 2.2)); 2944 } 2945#else 2946 float gammaCorrectInput(float color) { 2947 return color; 2948 } 2949 vec3 gammaCorrectInput(vec3 color) { 2950 return color; 2951 } 2952 vec4 gammaCorrectInput(vec4 color) { 2953 return color; 2954 } 2955 vec3 gammaCorrectOutput(vec3 color) { 2956 return color; 2957 } 2958#endif 2959`,z2=` 2960#ifdef STD_GLOSS_CONSTANT 2961uniform float material_gloss; 2962#endif 2963void getGlossiness() { 2964 dGlossiness = 1.0; 2965 #ifdef STD_GLOSS_CONSTANT 2966 dGlossiness *= material_gloss; 2967 #endif 2968 #ifdef STD_GLOSS_TEXTURE 2969 dGlossiness *= texture2DBias({STD_GLOSS_TEXTURE_NAME}, {STD_GLOSS_TEXTURE_UV}, textureBias).{STD_GLOSS_TEXTURE_CHANNEL}; 2970 #endif 2971 #ifdef STD_GLOSS_VERTEX 2972 dGlossiness *= saturate(vVertexColor.{STD_GLOSS_VERTEX_CHANNEL}); 2973 #endif 2974 #ifdef STD_GLOSS_INVERT 2975 dGlossiness = 1.0 - dGlossiness; 2976 #endif 2977 dGlossiness += 0.0000001; 2978} 2979`,V2=` 2980 attribute vec2 aPosition; 2981 varying vec2 uv0; 2982 void main(void) 2983 { 2984 gl_Position = vec4(aPosition, 0.0, 1.0);
2985 uv0 = getImageEffectUV((aPosition.xy + 1.0) * 0.5); 2986 } 2987`,G2=` 2988 #include "gammaPS" 2989 varying vec4 color; 2990 void main(void) { 2991 gl_FragColor = vec4(gammaCorrectOutput(decodeGamma(color.rgb)), color.a); 2992 } 2993`,H2=` 2994 attribute vec4 vertex_position; 2995 attribute vec4 vertex_color; 2996 uniform mat4 matrix_model; 2997 uniform mat4 matrix_viewProjection; 2998 varying vec4 color; 2999 void main(void) { 3000 color = vertex_color; 3001 gl_Position = matrix_viewProjection * matrix_model * vertex_position; 3002 } 3003`,W2=` 3004uniform float material_iridescenceRefractionIndex; 3005float iridescence_iorToFresnel(float transmittedIor, float incidentIor) { 3006 return pow((transmittedIor - incidentIor) / (transmittedIor + incidentIor), 2.0); 3007} 3008vec3 iridescence_iorToFresnel(vec3 transmittedIor, float incidentIor) { 3009 return pow((transmittedIor - vec3(incidentIor)) / (transmittedIor + vec3(incidentIor)), vec3(2.0)); 3010} 3011vec3 iridescence_fresnelToIor(vec3 f0) { 3012 vec3 sqrtF0 = sqrt(f0); 3013 return (vec3(1.0) + sqrtF0) / (vec3(1.0) - sqrtF0); 3014} 3015vec3 iridescence_sensitivity(float opd, vec3 shift) { 3016 float PI = 3.141592653589793; 3017 float phase = 2.0 * PI * opd * 1.0e-9; 3018 const vec3 val = vec3(5.4856e-13, 4.4201e-13, 5.2481e-13); 3019 const vec3 pos = vec3(1.6810e+06, 1.7953e+06, 2.2084e+06); 3020 const vec3 var = vec3(4.3278e+09, 9.3046e+09, 6.6121e+09); 3021 vec3 xyz = val * sqrt(2.0 * PI * var) * cos(pos * phase + shift) * exp(-pow(phase, 2.0) * var); 3022 xyz.x += 9.7470e-14 * sqrt(2.0 * PI * 4.5282e+09) * cos(2.2399e+06 * phase + shift[0]) * exp(-4.5282e+09 * pow(phase, 2.0)); 3023 xyz /= vec3(1.0685e-07); 3024 const mat3 XYZ_TO_REC709 = mat3( 3025 3.2404542, -0.9692660, 0.0556434, 3026 -1.5371385, 1.8760108, -0.2040259, 3027 -0.4985314, 0.0415560, 1.0572252 3028 ); 3029 return XYZ_TO_REC709 * xyz; 3030} 3031float iridescence_fresnel(float cosTheta, float f0) { 3032 float x = clamp(1.0 - cosTheta, 0.0, 1.0); 3033 float x2 = x * x; 3034 float x5 = x * x2 * x2; 3035 return f0 + (1.0 - f0) * x5; 3036} 3037vec3 iridescence_fresnel(float cosTheta, vec3 f0) { 3038 float x = clamp(1.0 - cosTheta, 0.0, 1.0); 3039 float x2 = x * x; 3040 float x5 = x * x2 * x2; 3041 return f0 + (vec3(1.0) - f0) * x5; 3042} 3043vec3 calcIridescence(float outsideIor, float cosTheta, vec3 base_f0, float iridescenceThickness) { 3044 float PI = 3.141592653589793; 3045 float iridescenceIor = mix(outsideIor, material_iridescenceRefractionIndex, smoothstep(0.0, 0.03, iridescenceThickness)); 3046 float sinTheta2Sq = pow(outsideIor / iridescenceIor, 2.0) * (1.0 - pow(cosTheta, 2.0)); 3047 float cosTheta2Sq = 1.0 - sinTheta2Sq; 3048 if (cosTheta2Sq < 0.0) { 3049 return vec3(1.0); 3050 } 3051 float cosTheta2 = sqrt(cosTheta2Sq); 3052 float r0 = iridescence_iorToFresnel(iridescenceIor, outsideIor); 3053 float r12 = iridescence_fresnel(cosTheta, r0); 3054 float r21 = r12; 3055 float t121 = 1.0 - r12; 3056 float phi12 = iridescenceIor < outsideIor ? PI : 0.0; 3057 float phi21 = PI - phi12; 3058 vec3 baseIor = iridescence_fresnelToIor(base_f0 + vec3(0.0001)); 3059 vec3 r1 = iridescence_iorToFresnel(baseIor, iridescenceIor); 3060 vec3 r23 = iridescence_fresnel(cosTheta2, r1); 3061 vec3 phi23 = vec3(0.0); 3062 if (baseIor[0] < iridescenceIor) phi23[0] = PI; 3063 if (baseIor[1] < iridescenceIor) phi23[1] = PI; 3064 if (baseIor[2] < iridescenceIor) phi23[2] = PI; 3065 float opd = 2.0 * iridescenceIor * iridescenceThickness * cosTheta2; 3066 vec3 phi = vec3(phi21) + phi23; 3067 vec3 r123Sq = clamp(r12 * r23, 1e-5, 0.9999); 3068 vec3 r123 = sqrt(r123Sq); 3069 vec3 rs = pow(t121, 2.0) * r23 / (1.0 - r123Sq); 3070 vec3 c0 = r12 + rs; 3071 vec3 i = c0; 3072 vec3 cm = rs - t121; 3073 for (int m = 1; m <= 2; m++) { 3074 cm *= r123; 3075 vec3 sm = 2.0 * iridescence_sensitivity(float(m) * opd, float(m) * phi); 3076 i += cm * sm; 3077 } 3078 return max(i, vec3(0.0)); 3079} 3080vec3 getIridescence(float cosTheta, vec3 specularity, float iridescenceThickness) { 3081 return calcIridescence(1.0, cosTheta, specularity, iridescenceThickness); 3082} 3083`,X2=` 3084#ifdef STD_IRIDESCENCE_CONSTANT 3085uniform float material_iridescence; 3086#endif 3087void getIridescence() { 3088 float iridescence = 1.0; 3089 #ifdef STD_IRIDESCENCE_CONSTANT 3090 iridescence *= material_iridescence; 3091 #endif 3092 #ifdef STD_IRIDESCENCE_TEXTURE 3093 iridescence *= texture2DBias({STD_IRIDESCENCE_TEXTURE_NAME}, {STD_IRIDESCENCE_TEXTURE_UV}, textureBias).{STD_IRIDESCENCE_TEXTURE_CHANNEL}; 3094 #endif 3095 dIridescence = iridescence; 3096} 3097`,Y2=` 3098uniform float material_iridescenceThicknessMax; 3099#ifdef STD_IRIDESCENCETHICKNESS_TEXTURE 3100uniform float material_iridescenceThicknessMin; 3101#endif 3102void getIridescenceThickness() { 3103 #ifdef STD_IRIDESCENCETHICKNESS_TEXTURE 3104 float blend = texture2DBias({STD_IRIDESCENCETHICKNESS_TEXTURE_NAME}, {STD_IRIDESCENCETHICKNESS_TEXTURE_UV}, textureBias).{STD_IRIDESCENCETHICKNESS_TEXTURE_CHANNEL}; 3105 float iridescenceThickness = mix(material_iridescenceThicknessMin, material_iridescenceThicknessMax, blend); 3106 #else 3107 float iridescenceThickness = material_iridescenceThicknessMax; 3108 #endif 3109 dIridescenceThickness = iridescenceThickness; 3110} 3111`,j2=` 3112#ifdef STD_IOR_CONSTANT 3113uniform float material_refractionIndex; 3114#endif 3115void getIor() { 3116#ifdef STD_IOR_CONSTANT 3117 dIor = material_refractionIndex; 3118#else 3119 dIor = 1.0 / 1.5; 3120#endif 3121} 3122`,q2=` 3123#if defined(LIGHT{i}) 3124 uniform vec3 light{i}_color; 3125 #if LIGHT{i}TYPE == DIRECTIONAL 3126 uniform vec3 light{i}_direction; 3127 #else 3128 #define LIT_CODE_LIGHTS_POINT 3129 uniform vec3 light{i}_position; 3130 uniform float light{i}_radius; 3131 #if LIGHT{i}TYPE == SPOT 3132 #define LIT_CODE_LIGHTS_SPOT 3133 uniform vec3 light{i}_direction; 3134 uniform float light{i}_innerConeAngle; 3135 uniform float light{i}_outerConeAngle; 3136 #endif 3137 #endif 3138 #if LIGHT{i}SHAPE != PUNCTUAL 3139 #define LIT_CODE_FALLOFF_SQUARED 3140 #if LIGHT{i}TYPE == DIRECTIONAL 3141 uniform vec3 light{i}_position; 3142 #endif 3143 uniform vec3 light{i}_halfWidth; 3144 uniform vec3 light{i}_halfHeight; 3145 #else 3146 #if LIGHT{i}FALLOFF == LINEAR 3147 #define LIT_CODE_FALLOFF_LINEAR 3148 #endif 3149 #if LIGHT{i}FALLOFF == INVERSESQUARED 3150 #define LIT_CODE_FALLOFF_SQUARED 3151 #endif 3152 #endif 3153 #if defined(LIGHT{i}
3153CASTSHADOW) 3154 #if LIGHT{i}TYPE != OMNI 3155 uniform mat4 light{i}_shadowMatrix; 3156 #endif 3157 uniform float light{i}_shadowIntensity; 3158 uniform vec4 light{i}_shadowParams; 3159 #if LIGHT{i}SHADOWTYPE == PCSS_32F 3160 uniform float light{i}_shadowSearchArea; 3161 uniform vec4 light{i}_cameraParams; 3162 #if LIGHT{i}TYPE == DIRECTIONAL 3163 uniform vec4 light{i}_softShadowParams; 3164 #endif 3165 #endif 3166 #if LIGHT{i}TYPE == DIRECTIONAL 3167 uniform mat4 light{i}_shadowMatrixPalette[4]; 3168 uniform vec4 light{i}_shadowCascadeDistances; 3169 uniform int light{i}_shadowCascadeCount; 3170 uniform float light{i}_shadowCascadeBlend; 3171 #endif 3172 #if LIGHT{i}TYPE == OMNI 3173 #if defined(LIGHT{i}SHADOW_PCF) 3174 uniform samplerCubeShadow light{i}_shadowMap; 3175 #else 3176 uniform samplerCube light{i}_shadowMap; 3177 #endif 3178 #else 3179 #if defined(LIGHT{i}SHADOW_PCF) 3180 uniform sampler2DShadow light{i}_shadowMap; 3181 #else 3182 uniform sampler2D light{i}_shadowMap; 3183 #endif 3184 #endif 3185 #endif 3186 #if defined(LIGHT{i}COOKIE) 3187 #define LIT_CODE_COOKIE 3188 #if LIGHT{i}TYPE == OMNI 3189 uniform samplerCube light{i}_cookie; 3190 uniform float light{i}_cookieIntensity; 3191 uniform mat4 light{i}_shadowMatrix; 3192 #endif 3193 #if LIGHT{i}TYPE == SPOT 3194 uniform sampler2D light{i}_cookie; 3195 uniform float light{i}_cookieIntensity; 3196 #if !defined(LIGHT{i}CASTSHADOW) 3197 uniform mat4 light{i}_shadowMatrix; 3198 #endif 3199 #if defined(LIGHT{i}COOKIE_TRANSFORM) 3200 uniform vec4 light{i}_cookieMatrix; 3201 uniform vec2 light{i}_cookieOffset; 3202 #endif 3203 #endif 3204 #endif 3205#endif 3206`,$2=` 3207float getLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm) { 3208 return max(dot(worldNormal, -lightDirNorm), 0.0); 3209} 3210`,K2=` 3211vec3 evalOmniLight(vec3 lightPosW) { 3212 return vPositionW - lightPosW; 3213} 3214`,Z2=` 3215#if defined(LIGHT{i}) 3216 evaluateLight{i}( 3217 #if defined(LIT_IRIDESCENCE) 3218 iridescenceFresnel 3219 #endif 3220 ); 3221#endif 3222`,Q2=` 3223#if defined(LIGHT{i}) 3224void evaluateLight{i}( 3225 #if defined(LIT_IRIDESCENCE) 3226 vec3 iridescenceFresnel 3227 #endif 3228) { 3229 vec3 lightColor = light{i}_color; 3230 #if LIGHT{i}TYPE == DIRECTIONAL && !defined(LIT_SHADOW_CATCHER) 3231 if (all(equal(lightColor, vec3(0.0)))) { 3232 return; 3233 } 3234 #endif 3235 #if LIGHT{i}TYPE == DIRECTIONAL 3236 dLightDirNormW = light{i}_direction; 3237 dAtten = 1.0; 3238 #else 3239 3240 vec3 lightDirW = evalOmniLight(light{i}_position); 3241 dLightDirNormW = normalize(lightDirW); 3242 #if defined(LIGHT{i}COOKIE) 3243 #if LIGHT{i}TYPE == SPOT 3244 #ifdef LIGHT{i}COOKIE_FALLOFF 3245 #ifdef LIGHT{i}COOKIE_TRANSFORM 3246 vec3 cookieAttenuation = getCookie2DXform(light{i}_cookie, light{i}_shadowMatrix, light{i}_cookieIntensity, light{i}_cookieMatrix, light{i}_cookieOffset).{LIGHT{i}COOKIE_CHANNEL}; 3247 #else 3248 vec3 cookieAttenuation = getCookie2D(light{i}_cookie, light{i}_shadowMatrix, light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL}; 3249 #endif 3250 #else 3251 #ifdef LIGHT{i}COOKIE_TRANSFORM 3252 vec3 cookieAttenuation = getCookie2DClipXform(light{i}_cookie, light{i}_shadowMatrix, light{i}_cookieIntensity, light{i}_cookieMatrix, light{i}_cookieOffset).{LIGHT{i}COOKIE_CHANNEL}; 3253 #else 3254 vec3 cookieAttenuation = getCookie2DClip(light{i}_cookie, light{i}_shadowMatrix, light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL}; 3255 #endif 3256 #endif 3257 #endif 3258 #if LIGHT{i}TYPE == OMNI 3259 vec3 cookieAttenuation = getCookieCube(light{i}_cookie, light{i}_shadowMatrix, light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL}; 3260 #endif 3261 lightColor *= cookieAttenuation; 3262 #endif 3263 #if LIGHT{i}SHAPE == PUNCTUAL 3264 #if LIGHT{i}FALLOFF == LINEAR 3265 dAtten = getFalloffLinear(light{i}_radius, lightDirW); 3266 #else 3267 dAtten = getFalloffInvSquared(light{i}_radius, lightDirW); 3268 #endif 3269 #else 3270 dAtten = getFalloffWindow(light{i}_radius, lightDirW); 3271 #endif 3272 #if LIGHT{i}TYPE == SPOT 3273 #if !defined(LIGHT{i}COOKIE) || defined(LIGHT{i}COOKIE_FALLOFF) 3274 dAtten *= getSpotEffect(light{i}_direction, light{i}_innerConeAngle, light{i}_outerConeAngle, dLightDirNormW); 3275 #endif 3276 #endif 3277 #endif 3278 if (dAtten < 0.00001) { 3279 return; 3280 } 3281 #if LIGHT{i}SHAPE != PUNCTUAL 3282 #if LIGHT{i}SHAPE == RECT 3283 calcRectLightValues(light{i}_position, light{i}_halfWidth, light{i}_halfHeight); 3284 #elif LIGHT{i}SHAPE == DISK 3285 calcDiskLightValues(light{i}_position, light{i}_halfWidth, light{i}_halfHeight); 3286 #elif LIGHT{i}SHAPE == SPHERE 3287 calcSphereLightValues(light{i}_position, light{i}_halfWidth, light{i}_halfHeight); 3288 #endif 3289 #endif 3290 #if LIGHT{i}SHAPE != PUNCTUAL 3291 #if LIGHT{i}TYPE == DIRECTIONAL 3292 float attenDiffuse = getLightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirNormW); 3293 #else 3294 #if LIGHT{i}SHAPE == RECT 3295 float attenDiffuse = getRectLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0; 3296 #elif LIGHT{i}SHAPE == DISK 3297 float attenDiffuse = getDiskLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0; 3298 #elif LIGHT{i}SHAPE == SPHERE 3299 float attenDiffuse = getSphereLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0; 3300 #endif 3301 #endif 3302 #else 3303 dAtten *= getLightDiffuse(litArgs_worldNormal, vec3(0.0), dLightDirNormW); 3304 #endif 3305 #ifdef LIGHT{i}
3305CASTSHADOW 3306 #if LIGHT{i}TYPE == DIRECTIONAL 3307 float shadow = getShadow{i}(vec3(0.0)); 3308 #else 3309 float shadow = getShadow{i}(lightDirW); 3310 #endif 3311 shadow = mix(1.0, shadow, light{i}_shadowIntensity); 3312 dAtten *= shadow; 3313 #if defined(LIT_SHADOW_CATCHER) && LIGHT{i}TYPE == DIRECTIONAL 3314 dShadowCatcher *= shadow; 3315 #endif 3316 #endif 3317 #if LIGHT{i}SHAPE != PUNCTUAL 3318 #ifdef LIT_SPECULAR 3319 dDiffuseLight += ((attenDiffuse * dAtten) * lightColor) * (1.0 - dLTCSpecFres); 3320 #else 3321 dDiffuseLight += (attenDiffuse * dAtten) * lightColor; 3322 #endif 3323 #else 3324 #if defined(AREA_LIGHTS) && defined(LIT_SPECULAR) 3325 dDiffuseLight += (dAtten * lightColor) * (1.0 - litArgs_specularity); 3326 #else 3327 dDiffuseLight += dAtten * lightColor; 3328 #endif 3329 #endif 3330 #ifdef LIGHT{i}AFFECT_SPECULARITY 3331 #if LIGHT{i}SHAPE != PUNCTUAL 3332 #ifdef LIT_CLEARCOAT 3333 #if LIGHT{i}SHAPE == RECT 3334 ccSpecularLight += ccLTCSpecFres * getRectLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor; 3335 #elif LIGHT{i}SHAPE == DISK 3336 ccSpecularLight += ccLTCSpecFres * getDiskLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor; 3337 #elif LIGHT{i}SHAPE == SPHERE 3338 ccSpecularLight += ccLTCSpecFres * getSphereLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor; 3339 #endif 3340 #endif 3341 #ifdef LIT_SPECULAR 3342 #if LIGHT{i}SHAPE == RECT 3343 dSpecularLight += dLTCSpecFres * getRectLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor; 3344 #elif LIGHT{i}SHAPE == DISK 3345 dSpecularLight += dLTCSpecFres * getDiskLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor; 3346 #elif LIGHT{i}SHAPE == SPHERE 3347 dSpecularLight += dLTCSpecFres * getSphereLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor; 3348 #endif 3349 #endif 3350 #else 3351 #if LIGHT{i}TYPE == DIRECTIONAL && LIT_FRESNEL_MODEL != NONE 3352 #define LIGHT{i}FRESNEL 3353 #endif 3354 #ifdef LIT_SPECULAR 3355 vec3 halfDirW = normalize(-dLightDirNormW + dViewDirW); 3356 #endif 3357 #ifdef LIT_CLEARCOAT 3358 vec3 lightspecularCC = getLightSpecular(halfDirW, ccReflDirW, litArgs_clearcoat_worldNormal, dViewDirW, dLightDirNormW, litArgs_clearcoat_gloss, dTBN) * dAtten * lightColor; 3359 #ifdef LIGHT{i}FRESNEL 3360 lightspecularCC *= getFresnelCC(dot(dViewDirW, halfDirW)); 3361 #endif 3362 ccSpecularLight += lightspecularCC; 3363 #endif 3364 #ifdef LIT_SHEEN 3365 sSpecularLight += getLightSpecularSheen(halfDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_sheen_gloss) * dAtten * lightColor; 3366 #endif 3367 #ifdef LIT_SPECULAR 3368 vec3 lightSpecular = getLightSpecular(halfDirW, dReflDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_gloss, dTBN) * dAtten * lightColor; 3369 #ifdef LIGHT{i}FRESNEL 3370 #if defined(LIT_IRIDESCENCE)
3371 lightSpecular *= getFresnel(dot(dViewDirW, halfDirW), litArgs_gloss, litArgs_specularity, iridescenceFresnel, litArgs_iridescence_intensity); 3372 #else 3373 lightSpecular *= getFresnel(dot(dViewDirW, halfDirW), litArgs_gloss, litArgs_specularity); 3374 #endif 3375 #else 3376 lightSpecular *= litArgs_specularity; 3377 #endif 3378 3379 dSpecularLight += lightSpecular; 3380 #endif 3381 #endif 3382 #endif 3383} 3384#endif 3385`,J2=` 3386#ifdef LIGHT{i}CASTSHADOW 3387 #ifdef LIGHT{i}_SHADOW_SAMPLE_POINT 3388 vec3 getShadowSampleCoordOmni{i}(vec4 shadowParams, vec3 worldPosition, vec3 lightPos, inout vec3 lightDir, vec3 lightDirNorm, vec3 normal) { 3389 #ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET 3390 float distScale = length(lightDir); 3391 vec3 surfacePosition = worldPosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale; 3392 lightDir = surfacePosition - lightPos; 3393 #endif 3394 return lightDir; 3395 } 3396 #endif 3397 #ifndef LIGHT{i}_SHADOW_SAMPLE_POINT 3398 vec3 getShadowSampleCoord{i}(mat4 shadowTransform, vec4 shadowParams, vec3 worldPosition, vec3 lightPos, inout vec3 lightDir, vec3 lightDirNorm, vec3 normal) { 3399 vec3 surfacePosition = worldPosition; 3400 #ifdef LIGHT{i}_SHADOW_SAMPLE_SOURCE_ZBUFFER 3401 #ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET 3402 surfacePosition = surfacePosition + normal * shadowParams.y; 3403 #endif 3404 #else 3405 #ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET 3406 #ifdef LIGHT{i}_SHADOW_SAMPLE_ORTHO 3407 float distScale = 1.0; 3408 #else 3409 float distScale = abs(dot(vPositionW - lightPos, lightDirNorm)); 3410 #endif 3411 surfacePosition = surfacePosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale; 3412 #endif 3413 #endif 3414 vec4 positionInShadowSpace = shadowTransform * vec4(surfacePosition, 1.0
3414); 3415 #ifdef LIGHT{i}_SHADOW_SAMPLE_ORTHO 3416 positionInShadowSpace.z = saturate(positionInShadowSpace.z) - 0.0001; 3417 #else 3418 #ifdef LIGHT{i}_SHADOW_SAMPLE_SOURCE_ZBUFFER 3419 positionInShadowSpace.xyz /= positionInShadowSpace.w; 3420 #else 3421 positionInShadowSpace.xy /= positionInShadowSpace.w; 3422 positionInShadowSpace.z = length(lightDir) * shadowParams.w; 3423 #endif 3424 #endif 3425 return positionInShadowSpace.xyz; 3426 } 3427 #endif 3428 float getShadow{i}(vec3 lightDirW) { 3429 #if LIGHT{i}TYPE == OMNI 3430 vec3 shadowCoord = getShadowSampleCoordOmni{i}(light{i}_shadowParams, vPositionW, light{i}_position, lightDirW, dLightDirNormW, dVertexNormalW); 3431 #else 3432 #ifdef LIGHT{i}_SHADOW_CASCADES 3433 int cascadeIndex = getShadowCascadeIndex(light{i}_shadowCascadeDistances, light{i}_shadowCascadeCount); 3434 #ifdef LIGHT{i}_SHADOW_CASCADE_BLEND 3435 cascadeIndex = ditherShadowCascadeIndex(cascadeIndex, light{i}_shadowCascadeDistances, light{i}_shadowCascadeCount, light{i}_shadowCascadeBlend); 3436 #endif 3437 mat4 shadowMatrix = light{i}_shadowMatrixPalette[cascadeIndex]; 3438 #else 3439 mat4 shadowMatrix = light{i}_shadowMatrix; 3440 #endif 3441 #if LIGHT{i}TYPE == DIRECTIONAL 3442 vec3 shadowCoord = getShadowSampleCoord{i}(shadowMatrix, light{i}_shadowParams, vPositionW, vec3(0.0), lightDirW, dLightDirNormW, dVertexNormalW); 3443 #else 3444 vec3 shadowCoord = getShadowSampleCoord{i}(shadowMatrix, light{i}_shadowParams, vPositionW, light{i}_position, lightDirW, dLightDirNormW, dVertexNormalW); 3445 #endif 3446 #endif 3447 #if LIGHT{i}TYPE == DIRECTIONAL 3448 shadowCoord = fadeShadow(shadowCoord, light{i}_shadowCascadeDistances); 3449 #endif 3450 #if LIGHT{i}TYPE == DIRECTIONAL 3451 #if LIGHT{i}SHADOWTYPE == VSM_16F 3452 return getShadowVSM16(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, 5.54); 3453 #endif 3454 #if LIGHT{i}SHADOWTYPE == VSM_32F 3455 return getShadowVSM32(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, 15.0); 3456 #endif 3457 #if LIGHT{i}SHADOWTYPE == PCSS_32F 3458 #if LIGHT{i}SHAPE != PUNCTUAL 3459 vec2 shadowSearchArea = vec2(length(light{i}_halfWidth), length(light{i}_halfHeight)) * light{i}_shadowSearchArea; 3460 return getShadowPCSS(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, light{i}_cameraParams, shadowSearchArea, lightDirW); 3461 #else 3462 return getShadowPCSS(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, light{i}_cameraParams, light{i}_softShadowParams, lightDirW); 3463 #endif 3464 #endif 3465 #if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F 3466 return getShadowPCF1x1(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams); 3467 #endif 3468 #if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F 3469 return getShadowPCF3x3(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams); 3470 #endif 3471 #if LIGHT{i}SHADOWTYPE == PCF5_16F || LIGHT{i}SHADOWTYPE == PCF5_32F 3472 return getShadowPCF5x5(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams); 3473 #endif 3474 #endif 3475 #if LIGHT{i}TYPE == SPOT 3476 #if LIGHT{i}SHADOWTYPE == VSM_16F 3477 return getShadowSpotVSM16(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, 5.54, lightDirW); 3478 #endif 3479 #if LIGHT{i}SHADOWTYPE == VSM_32F 3480 return getShadowSpotVSM32(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, 15.0, lightDirW); 3481 #endif 3482 #if LIGHT{i}SHADOWTYPE == PCSS_32F 3483 #if LIGHT{i}SHAPE != PUNCTUAL 3484 vec2 shadowSearchArea = vec2(length(light{i}_halfWidth), length(light{i}_halfHeight)) * light{i}_shadowSearchArea; 3485 #else 3486 vec2 shadowSearchArea = vec2(light{i}_shadowSearchArea); 3487 #endif 3488 return getShadowSpotPCSS(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, light{i}_cameraParams, shadowSearchArea, lightDirW); 3489 #endif 3490 #if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F 3491 return getShadowSpotPCF1x1(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams); 3492 #endif 3493 #if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F 3494 return getShadowSpotPCF3x3(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams); 3495 #endif 3496 #if LIGHT{i}SHADOWTYPE == PCF5_16F || LIGHT{i}SHADOWTYPE == PCF5_32F 3497 return getShadowSpotPCF5x5(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams); 3498 #endif 3499 #endif 3500 #if LIGHT{i}TYPE == OMNI 3501 #if LIGHT{i}SHADOWTYPE == PCSS_32F 3502 #if LIGHT{i}SHAPE != PUNCTUAL 3503 vec2 shadowSearchArea = vec2(length(light{i}_halfWidth), length(light{i}_halfHeight)) * light{i}_shadowSearchArea; 3504 #else 3505 vec2 shadowSearchArea = vec2(light{i}_shadowSearchArea); 3506 #endif 3507 return getShadowOmniPCSS(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, light{i}_cameraParams, shadowSearchArea, lightDirW); 3508 #endif 3509 #if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F 3510 return getShadowOmniPCF1x1(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, lightDirW); 3511 #endif 3512 #if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F 3513 return getShadowOmniPCF3x3(SHADOWMAP_PASS(light{i}_shadowMap), shadowCoord, light{i}_shadowParams, lightDirW); 3514 #endif 3515 #endif 3516 } 3517#endif 3518`,eL=` 3519#ifdef LIT_CLUSTERED_LIGHTS 3520 #define LIT_CODE_FALLOFF_LINEAR 3521 #define LIT_CODE_FALLOFF_SQUARED 3522 #define LIT_CODE_LIGHTS_POINT 3523 #define LIT_CODE_LIGHTS_SPOT 3524#endif 3525#ifdef AREA_LIGHTS 3526 uniform highp sampler2D areaLightsLutTex1; 3527 uniform highp sampler2D areaLightsLutTex2; 3528#endif 3529#ifdef LIT_LIGHTING 3530 #include "lightDiffuseLambertPS" 3531 #if defined(AREA_LIGHTS) || defined(LIT_CLUSTERED_AREA_LIGHTS) 3532 #include "ltcPS" 3533 #endif 3534#endif 3535#ifdef SHADOW_DIRECTIONAL 3536 #include "shadowCascadesPS" 3537#endif 3538#if defined(SHADOW_KIND_PCF1) 3539 #include "shadowPCF1PS" 3540#endif 3541#if defined(SHADOW_KIND_PCF3) 3542 #include "shadowPCF3PS" 3543#endif 3544#if defined(SHADOW_KIND_PCF5) 3545 #include "shadowPCF5PS" 3546#endif 3547#if defined(SHADOW_KIND_PCSS) 3548 #include "linearizeDepthPS" 3549 #include "shadowPCSSPS" 3550 #include "shadowSoftPS" 3551#endif 3552#if defined(SHADOW_KIND_VSM) 3553 #include "shadowEVSMPS" 3554#endif 3555#ifdef LIT_CODE_FALLOFF_LINEAR 3556 #include "falloffLinearPS" 3557#endif 3558#ifdef LIT_CODE_FALLOFF_SQUARED 3559 #include "falloffInvSquaredPS" 3560#endif 3561#ifdef LIT_CODE_LIGHTS_POINT 3562 #include "lightDirPointPS" 3563#endif 3564#ifdef LIT_CODE_LIGHTS_SPOT 3565 #include "spotPS" 3566#endif 3567#ifdef LIT_CODE_COOKIE 3568 #include "cookiePS" 3569#endif 3570#ifdef LIT_CLUSTERED_LIGHTS 3571 #include "clusteredLightPS" 3572#endif 3573#ifdef LIGHT_COUNT > 0 3574 #include "lightFunctionShadowPS, LIGHT_COUNT" 3575 #include "lightFunctionLightPS, LIGHT_COUNT" 3576#endif
3577`,tL=` 3578void addLightMap( 3579 vec3 lightmap, 3580 vec3 dir, 3581 vec3 worldNormal, 3582 vec3 viewDir, 3583 vec3 reflectionDir, 3584 float gloss, 3585 vec3 specularity, 3586 vec3 vertexNormal, 3587 mat3 tbn 3588#if defined(LIT_IRIDESCENCE) 3589 vec3 iridescenceFresnel, 3590 float iridescenceIntensity 3591#endif 3592) { 3593 #if defined(LIT_SPECULAR) && defined(LIT_DIR_LIGHTMAP) 3594 if (dot(dir, dir) < 0.0001) { 3595 dDiffuseLight += lightmap; 3596 } else { 3597 float vlight = saturate(dot(dir, -vertexNormal)); 3598 float flight = saturate(dot(dir, -worldNormal)); 3599 float nlight = (flight / max(vlight, 0.01)) * 0.5; 3600 dDiffuseLight += lightmap * nlight * 2.0; 3601 vec3 halfDir = normalize(-dir + viewDir); 3602 vec3 specularLight = lightmap * getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, dir, gloss, tbn); 3603 #ifdef LIT_SPECULAR_FRESNEL 3604 specularLight *= 3605 getFresnel(dot(viewDir, halfDir), 3606 gloss, 3607 specularity 3608 #if defined(LIT_IRIDESCENCE) 3609 , iridescenceFresnel, 3610 iridescenceIntensity 3611 #endif 3612 ); 3613 #endif 3614 dSpecularLight += specularLight; 3615 } 3616 #else 3617 dDiffuseLight += lightmap; 3618 #endif 3619} 3620`,sL=` 3621#ifdef STD_LIGHTMAP_DIR 3622 vec3 dLightmapDir; 3623 uniform sampler2D texture_dirLightMap; 3624#endif 3625void getLightMap() { 3626 dLightmap = vec3(1.0); 3627 #ifdef STD_LIGHT_TEXTURE 3628 dLightmap *= {STD_LIGHT_TEXTURE_DECODE}(texture2DBias({STD_LIGHT_TEXTURE_NAME}, {STD_LIGHT_TEXTURE_UV}, textureBias)).{STD_LIGHT_TEXTURE_CHANNEL}; 3629 #ifdef STD_LIGHTMAP_DIR 3630 vec3 dir = texture2DBias(texture_dirLightMap, {STD_LIGHT_TEXTURE_UV}, textureBias).xyz * 2.0 - 1.0; 3631 float dirDot = dot(dir, dir); 3632 dLightmapDir = (dirDot > 0.001) ? dir / sqrt(dirDot) : vec3(0.0); 3633 #endif 3634 #endif 3635 #ifdef STD_LIGHT_VERTEX 3636 dLightmap *= saturate(vVertexColor.{STD_LIGHT_VERTEX_CHANNEL}); 3637 #endif 3638} 3639`,iL=` 3640float calcLightSpecular(float gloss, vec3 worldNormal, vec3 viewDir, vec3 h, vec3 lightDirNorm, mat3 tbn) { 3641 float PI = 3.141592653589793; 3642 float roughness = max((1.0 - gloss) * (1.0 - gloss), 0.001); 3643 float alphaRoughness = roughness * roughness; 3644 float anisotropy = dAnisotropy; 3645 vec2 direction = dAnisotropyRotation; 3646 float at = mix(alphaRoughness, 1.0, anisotropy * anisotropy); 3647 float ab = clamp(alphaRoughness, 0.001, 1.0); 3648 vec3 anisotropicT = normalize(tbn * vec3(direction, 0.0)); 3649 vec3 anisotropicB = normalize(cross(tbn[2], anisotropicT)); 3650 float NoH = dot(worldNormal, h); 3651 float ToH = dot(anisotropicT, h); 3652 float BoH = dot(anisotropicB, h); 3653 float a2 = at * ab; 3654 vec3 v = vec3(ab * ToH, at * BoH, a2 * NoH); 3655 float v2 = dot(v, v); 3656 float w2 = a2 / v2; 3657 float D = a2 * w2 * w2 * (1.0 / PI); 3658 float ToV = dot(anisotropicT, viewDir); 3659 float BoV = dot(anisotropicB, viewDir); 3660 float ToL = dot(anisotropicT, -lightDirNorm); 3661 float BoL = dot(anisotropicB, -lightDirNorm); 3662 float NoV = dot(worldNormal, viewDir); 3663 float NoL = dot(worldNormal, -lightDirNorm); 3664 float lambdaV = NoL * length(vec3(at * ToV, ab * BoV, NoV)); 3665 float lambdaL = NoV * length(vec3(at * ToL, ab * BoL, NoL)); 3666 float G = 0.5 / (lambdaV + lambdaL); 3667 return D * G; 3668} 3669float getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) { 3670 return calcLightSpecular(gloss, worldNormal, viewDir, h, lightDirNorm, tbn); 3671} 3672`,rL=` 3673float calcLightSpecular(float gloss, vec3 worldNormal, vec3 viewDir, vec3 h, vec3 lightDirNorm) { 3674 const float PI = 3.141592653589793; 3675 float roughness = max((1.0 - gloss) * (1.0 - gloss), 0.001); 3676 float alpha = roughness * roughness; 3677 float NoH = max(dot(worldNormal, h), 0.0); 3678 float NoV = max(dot(worldNormal, viewDir), 0.0); 3679 float NoL = max(dot(worldNormal, -lightDirNorm), 0.0); 3680 float NoH2 = NoH * NoH; 3681 float denom = NoH2 * (alpha - 1.0) + 1.0; 3682 float D = alpha / (PI * denom * denom); 3683 float alpha2 = alpha * alpha; 3684 float lambdaV = NoL * sqrt(NoV * NoV * (1.0 - alpha2) + alpha2); 3685 float lambdaL = NoV * sqrt(NoL * NoL * (1.0 - alpha2) + alpha2); 3686 float G = 0.5 / max(lambdaV + lambdaL, 0.00001); 3687 return D * G; 3688} 3689float getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) { 3690 return calcLightSpecular(gloss, worldNormal, viewDir, h, lightDirNorm); 3691} 3692`,aL=` 3693float calcLightSpecular(float gloss, vec3 worldNormal, vec3 h) { 3694 float nh = max( dot( h, worldNormal ), 0.0 ); 3695 float specPow = exp2(gloss * 11.0); 3696 specPow = max(specPow, 0.0001); 3697 return pow(nh, specPow) * (specPow + 2.0) / 8.0; 3698} 3699float getLightSpecular(vec3 h, vec3 reflDir, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float gloss, mat3 tbn) { 3700 return calcLightSpecular(gloss, worldNormal, h); 3701} 3702`,nL=` 3703float sheenD(vec3 normal, vec3 h, float roughness) { 3704 const float PI = 3.141592653589793; 3705 float invR = 1.0 / (roughness * roughness); 3706 float cos2h = max(dot(normal, h), 0.0); 3707 cos2h *= cos2h; 3708 float sin2h = max(1.0 - cos2h, 0.0078125); 3709 return (2.0 + invR) * pow(sin2h, invR * 0.5) / (2.0 * PI); 3710} 3711float sheenV(vec3 normal, vec3 viewDir, vec3 light) { 3712 float NoV = max(dot(normal, viewDir), 0.000001); 3713 float NoL = max(dot(normal, light), 0.000001); 3714 return 1.0 / (4.0 * (NoL + NoV - NoL * NoV)); 3715} 3716float getLightSpecularSheen(vec3 h, vec3 worldNormal, vec3 viewDir, vec3 lightDirNorm, float sheenGloss) { 3717 float D = sheenD(worldNormal, h, sheenGloss); 3718 float V = sheenV(worldNormal, viewDir, -lightDirNorm); 3719 return D * V; 3720} 3721`,oL=` 3722#ifndef LINEARIZE_DEPTH 3723#define LINEARIZE_DEPTH 3724float linearizeDepthWithParams(float z, vec4 cameraParams) { 3725 if (cameraParams.w == 0.0) 3726 return (cameraParams.z * cameraParams.y) / (cameraParams.y + z * (cameraParams.z - cameraParams.y)); 3727 else 3728 return cameraParams.z + z * (cameraParams.y - cameraParams.z); 3729} 3730#ifndef CAMERAPLANES 3731 #define CAMERAPLANES 3732 uniform vec4 camera_params; 3733#endif 3734float linearizeDepth(float z) { 3735 return linearizeDepthWithParams(z, camera_params); 3736} 3737#endif 3738`,lL=` 3739void evaluateBackend() { 3740 #ifdef LIT_SSAO 3741 litArgs_ao *= texture2DLod(ssaoTexture, gl_FragCoord.xy * ssaoTextureSizeInv, 0.0).r; 3742 #endif 3743 #ifdef LIT_NEEDS_NORMAL 3744 #ifdef LIT_SPECULAR 3745 getReflDir(litArgs_worldNormal, dViewDirW, litArgs_gloss, dTBN); 3746 #endif 3747 #ifdef LIT_CLEARCOAT 3748 ccReflDirW = normalize(-reflect(dViewDirW, litArgs_clearcoat_worldNormal)); 3749 #endif 3750 #endif 3751 #ifdef LIT_SPECULAR_OR_REFLECTION 3752 #ifdef LIT_METALNESS 3753 float f0 = 1.0 / litArgs_ior; 3754 f0 = (f0 - 1.0) / (f0 + 1.0); 3755 f0 *= f0; 3756 #ifdef LIT_SPECULARITY_FACTOR 3757 litArgs_specularity = getSpecularModulate(litArgs_specularity, litArgs_albedo, litArgs_metalness, f0, litArgs_specularityFactor); 3758 #else 3759 litArgs_specularity = getSpecularModulate(litArgs_specularity, litArgs_albedo, litArgs_metalness, f0, 1.0); 3760 #endif 3761 litArgs_albedo = getAlbedoModulate(litArgs_albedo, litArgs_metalness); 3762 #endif 3763 #ifdef LIT_IRIDESCENCE 3764 vec3 iridescenceFresnel = getIridescence(saturate(dot(dViewDirW, litArgs_worldNormal)), litArgs_specularity, litArgs_iridescence_thickness); 3765 #endif 3766 #endif 3767 #ifdef LIT_ADD_AMBIENT 3768 addAmbient(litArgs_worldNormal); 3769 #ifdef LIT_SPECULAR 3770 dDiffuseLight = dDiffuseLight * (1.0 - litArgs_specularity); 3771 #endif 3772 #ifdef LIT_SEPARATE_AMBIENT 3773 vec3 dAmbientLight = dDiffuseLight; 3774 dDiffuseLight = vec3(0); 3775 #endif 3776 #endif 3777 #ifndef LIT_OLD_AMBIENT 3778 dDiffuseLight *= material_ambient; 3779 #endif 3780 #ifdef LIT_AO 3781 #ifndef LIT_OCCLUDE_DIRECT 3782 occludeDiffuse(litArgs_ao); 3783 #endif 3784 #endif 3785 #ifdef LIT_LIGHTMAP 3786 addLightMap( 3787 litArgs_lightmap, 3788 litArgs_lightmapDir, 3789 litArgs_worldNormal, 3790 dViewDirW, 3791 dReflDirW, 3792 litArgs_gloss, 3793 litArgs_specularity, 3794 dVertexNormalW, 3795 dTBN 3796 #if defined(LIT_IRIDESCENCE) 3797 , iridescenceFresnel, 3798 litArgs_iridescence_intensity 3799 #endif 3800 ); 3801 #endif 3802 #ifdef LIT_LIGHTING || LIT_REFLECTIONS 3803 #ifdef LIT_REFLECTIONS 3804 #ifdef LIT_CLEARCOAT 3805 addReflectionCC(ccReflDirW, litArgs_clearcoat_gloss); 3806 3807 #ifdef LIT_SPECULAR_FRESNEL 3808 ccFresnel = getFresnelCC(dot(dViewDirW, litArgs_clearcoat_worldNormal)); 3809 ccReflection *= ccFresnel; 3810 #else 3811 ccFresnel = 0.0; 3812 #endif 3813 #endif 3814 #ifdef LIT_SPECULARITY_FACTOR 3815 ccReflection *= litArgs_specularityFactor; 3816 #endif 3817 #ifdef LIT_SHEEN 3818 addReflectionSheen(litArgs_worldNormal, dViewDirW, litArgs_sheen_gloss); 3819 #endif 3820 addReflection(dReflDirW, litArgs_gloss); 3821 #ifdef LIT_FRESNEL_MODEL 3822 dReflection.rgb *= getFresnel( 3823 dot(dViewDirW, litArgs_worldNormal), 3824 litArgs_gloss, 3825 litArgs_specularity 3826 #if defined(LIT_IRIDESCENCE) 3827 , iridescenceFresnel, 3828 litArgs_iridescence_intensity 3829 #endif 3830 ); 3831 #else 3832 dReflection.rgb *= litArgs_specularity; 3833 #endif 3834 #endif 3835 #ifdef AREA_LIGHTS 3836 dSpecularLight *= litArgs_specularity; 3837 #ifdef LIT_SPECULAR 3838 calcLTCLightValues(litArgs_gloss, litArgs_worldNormal, dViewDirW, litArgs_specularity, litArgs_clearcoat_gloss, litArgs_clearcoat_worldNormal, litArgs_clearcoat_specularity); 3839 #endif 3840 #endif 3841 3842 #ifdef LIGHT_COUNT > 0 3843 #include "lightEvaluationPS, LIGHT_COUNT" 3844 #endif 3845 #ifdef LIT_CLUSTERED_LIGHTS 3846 addClusteredLights(litArgs_worldNormal, dViewDirW, dReflDirW, 3847 #if defined(LIT_CLEARCOAT) 3848 ccReflDirW, 3849 #endif 3850 litArgs_gloss, litArgs_specularity, dVertexNormalW, dTBN, 3851 #if defined(LIT_IRIDESCENCE) 3852 iridescenceFresnel, 3853 #endif 3854 litArgs_clearcoat_worldNormal, litArgs_clearcoat_gloss, litArgs_sheen_gloss, litArgs_iridescence_intensity 3855 ); 3856 #endif 3857 #ifdef AREA_LIGHTS 3858 #ifdef LIT_CLEARCOAT 3859 litArgs_clearcoat_specularity = 1.0; 3860 #endif 3861 #ifdef LIT_SPECULAR 3862 litArgs_specularity = vec3(1); 3863 #endif 3864 #endif 3865 #ifdef LIT_REFRACTION 3866 addRefraction( 3867 litArgs_worldNormal, 3868 dViewDirW, 3869 litArgs_thickness, 3870 litArgs_gloss, 3871 litArgs_specularity, 3872 litArgs_albedo, 3873 litArgs_transmission,
3874 litArgs_ior, 3875 litArgs_dispersion 3876 #if defined(LIT_IRIDESCENCE) 3877 , iridescenceFresnel, 3878 litArgs_iridescence_intensity 3879 #endif 3880 ); 3881 #endif 3882 #endif 3883 #ifdef LIT_AO 3884 #ifdef LIT_OCCLUDE_DIRECT 3885 occludeDiffuse(litArgs_ao); 3886 #endif 3887 #if LIT_OCCLUDE_SPECULAR != NONE 3888 occludeSpecular(litArgs_gloss, litArgs_ao, litArgs_worldNormal, dViewDirW); 3889 #endif 3890 #endif 3891 #if !defined(LIT_OPACITY_FADES_SPECULAR) 3892 #if LIT_BLEND_TYPE == NORMAL || LIT_BLEND_TYPE == PREMULTIPLIED 3893 float specLum = dot((dSpecularLight + dReflection.rgb * dReflection.a), vec3( 0.2126, 0.7152, 0.0722 )); 3894 #ifdef LIT_CLEARCOAT 3895 specLum += dot(ccSpecularLight * litArgs_clearcoat_specularity + ccReflection * litArgs_clearcoat_specularity, vec3( 0.2126, 0.7152, 0.0722 )); 3896 #endif 3897 litArgs_opacity = clamp(litArgs_opacity + gammaCorrectInput(specLum), 0.0, 1.0); 3898 #endif 3899 litArgs_opacity *= material_alphaFade; 3900 #endif 3901 #ifdef LIT_LIGHTMAP_BAKING 3902 #ifdef LIT_LIGHTMAP_BAKING_COLOR 3903 #include "bakeLmEndPS" 3904 #endif 3905 #ifdef LIT_LIGHTMAP_BAKING_DIR 3906 #include "bakeDirLmEndPS" 3907 #endif 3908 #else 3909 #include "endPS" 3910 #include "outputAlphaPS" 3911 #endif 3912 #ifdef LIT_MSDF 3913 gl_FragColor = applyMsdf(gl_FragColor); 3914 #endif 3915 #include "outputPS" 3916 #include "debugOutputPS" 3917 #ifdef LIT_SHADOW_CATCHER 3918 gl_FragColor.rgb = vec3(dShadowCatcher); 3919 #endif 3920} 3921`,cL=` 3922vec3 sReflection; 3923vec3 dVertexNormalW; 3924vec3 dTangentW; 3925vec3 dBinormalW; 3926vec3 dViewDirW; 3927vec3 dReflDirW; 3928vec3 ccReflDirW; 3929vec3 dLightDirNormW; 3930float dAtten; 3931mat3 dTBN; 3932vec4 dReflection; 3933vec3 dDiffuseLight; 3934vec3 dSpecularLight; 3935float ccFresnel; 3936vec3 ccReflection; 3937vec3 ccSpecularLight; 3938float ccSpecularityNoFres; 3939vec3 sSpecularLight; 3940#ifdef LIT_DISPERSION 3941 uniform float material_dispersion; 3942#endif 3943#ifndef LIT_OPACITY_FADES_SPECULAR 3944 uniform float material_alphaFade; 3945#endif 3946#ifdef LIT_SSAO 3947 uniform sampler2D ssaoTexture; 3948 uniform vec2 ssaoTextureSizeInv; 3949#endif 3950#ifdef LIT_SHADOW_CATCHER 3951 float dShadowCatcher = 1.0; 3952#endif 3953#if LIGHT_COUNT > 0 3954 #include "lightDeclarationPS, LIGHT_COUNT" 3955#endif 3956#ifdef LIT_SPECULAR 3957 #if LIT_FRESNEL_MODEL == NONE && !defined(LIT_REFLECTIONS) && !defined(LIT_DIFFUSE_MAP) 3958 #define LIT_OLD_AMBIENT 3959 #endif 3960#endif 3961#ifdef STD_LIGHTMAP_DIR 3962 uniform float bakeDir; 3963#endif 3964#ifdef LIT_LIGHTMAP_BAKING_ADD_AMBIENT 3965 uniform float ambientBakeOcclusionContrast; 3966 uniform float ambientBakeOcclusionBrightness; 3967#endif 3968`,hL=` 3969void main(void) { 3970 #include "litUserMainStartPS" 3971 dReflection = vec4(0); 3972 #ifdef LIT_CLEARCOAT 3973 ccSpecularLight = vec3(0); 3974 ccReflection = vec3(0); 3975 #endif 3976 #if LIT_NONE_SLICE_MODE == SLICED 3977 #include "startNineSlicedPS" 3978 #elif LIT_NONE_SLICE_MODE == TILED 3979 #include "startNineSlicedTiledPS" 3980 #endif 3981 #ifdef LIT_NEEDS_NORMAL 3982 dVertexNormalW = normalize(vNormalW); 3983 #ifdef LIT_TANGENTS 3984 #if defined(LIT_HEIGHTS) || defined(LIT_USE_NORMALS) || defined(LIT_USE_CLEARCOAT_NORMALS) || defined(LIT_GGX_SPECULAR) 3985 dTangentW = vTangentW; 3986 dBinormalW = vBinormalW; 3987 #endif 3988 #endif 3989 getViewDir(); 3990 #ifdef LIT_TBN 3991 getTBN(dTangentW, dBinormalW, dVertexNormalW); 3992 #ifdef LIT_TWO_SIDED_LIGHTING 3993 handleTwoSidedLighting(); 3994 #endif 3995 #endif 3996 #endif 3997 evaluateFrontend(); 3998 #include "debugProcessFrontendPS" 3999 evaluateBackend(); 4000 #include "litUserMainEndPS" 4001} 4002`,dL=` 4003#ifdef LIT_NEEDS_NORMAL 4004 #include "cubeMapRotatePS" 4005 #include "cubeMapProjectPS" 4006 #include "envProcPS" 4007#endif 4008#ifdef LIT_SPECULAR_OR_REFLECTION 4009 #ifdef LIT_METALNESS 4010 #include "metalnessModulatePS" 4011 #endif 4012 #ifdef LIT_IRIDESCENCE 4013 #include "iridescenceDiffractionPS" 4014 #endif 4015#endif 4016#if defined(LIT_SPECULAR_OR_REFLECTION) || defined(LIT_REFRACTION) 4017 #if LIT_FRESNEL_MODEL == SCHLICK 4018 #include "fresnelSchlickPS" 4019 #endif 4020#endif 4021#ifdef LIT_AO 4022 #include "aoDiffuseOccPS" 4023 #include "aoSpecOccPS" 4024#endif 4025#if LIT_REFLECTION_SOURCE == ENVATLASHQ 4026 #include "envAtlasPS" 4027 #include "reflectionEnvHQPS" 4028#elif LIT_REFLECTION_SOURCE == ENVATLAS 4029 #include "envAtlasPS" 4030 #include "reflectionEnvPS" 4031#elif LIT_REFLECTION_SOURCE == CUBEMAP 4032 #include "reflectionCubePS" 4033#elif LIT_REFLECTION_SOURCE == SPHEREMAP 4034 #include "reflectionSpherePS" 4035#endif 4036#ifdef LIT_REFLECTIONS 4037 #ifdef LIT_CLEARCOAT 4038 #include "reflectionCCPS" 4039 #endif 4040 #ifdef LIT_SHEEN 4041 #include "reflectionSheenPS" 4042 #endif 4043#endif 4044#ifdef LIT_REFRACTION 4045 #if defined(LIT_DYNAMIC_REFRACTION) 4046 #include "refractionDynamicPS" 4047 #elif defined(LIT_REFLECTIONS) 4048 #include "refractionCubePS" 4049 #endif 4050#endif 4051#ifdef LIT_SHEEN 4052 #include "lightSheenPS" 4053#endif 4054uniform vec3 material_ambient; 4055#ifdef LIT_SPECULAR 4056 #ifdef LIT_LIGHTING 4057 #ifdef LIT_GGX_SPECULAR 4058 #ifdef LIT_ANISOTROPY 4059 #include "lightSpecularAnisoGGXPS" 4060 #else 4061 #include "lightSpecularGGXPS" 4062 #endif 4063 #else 4064 #include "lightSpecularBlinnPS"
4065 #endif 4066 #endif 4067#endif 4068#include "combinePS" 4069#ifdef LIT_LIGHTMAP 4070 #include "lightmapAddPS" 4071#endif 4072#ifdef LIT_ADD_AMBIENT 4073 #include "ambientPS" 4074#endif 4075#ifdef LIT_MSDF 4076 #include "msdfPS" 4077#endif 4078#ifdef LIT_NEEDS_NORMAL 4079 #include "viewDirPS" 4080 #ifdef LIT_SPECULAR 4081 #ifdef LIT_ANISOTROPY 4082 #include "reflDirAnisoPS" 4083 #else 4084 #include "reflDirPS" 4085 #endif 4086 #endif 4087#endif 4088#include "lightingPS" 4089`,uL=` 4090#include "basePS" 4091#include "sphericalPS" 4092#include "decodePS" 4093#include "gammaPS" 4094#include "tonemappingPS" 4095#include "fogPS" 4096#if LIT_NONE_SLICE_MODE == SLICED 4097 #include "baseNineSlicedPS" 4098#elif LIT_NONE_SLICE_MODE == TILED 4099 #include "baseNineSlicedTiledPS" 4100#endif 4101#ifdef LIT_TBN 4102 #include "TBNPS" 4103 #ifdef LIT_TWO_SIDED_LIGHTING 4104 #include "twoSidedLightingPS" 4105 #endif 4106#endif 4107`,fL=` 4108#include "varyingsPS" 4109#include "litUserDeclarationPS" 4110#include "frontendDeclPS" 4111#if defined(PICK_PASS) || defined(PREPASS_PASS) 4112 #include "frontendCodePS" 4113 #include "litUserCodePS" 4114 #include "litOtherMainPS" 4115#elif defined(SHADOW_PASS) 4116 #include "frontendCodePS" 4117 #include "litUserCodePS" 4118 #include "litShadowMainPS" 4119#else 4120 #include "litForwardDeclarationPS" 4121 #include "litForwardPreCodePS" 4122 #include "frontendCodePS" 4123 #include "litForwardPostCodePS" 4124 #include "litForwardBackendPS" 4125 #include "litUserCodePS" 4126 #include "litForwardMainPS" 4127#endif 4128`,pL=` 4129#include "varyingsVS" 4130#include "litUserDeclarationVS" 4131#ifdef VERTEX_COLOR 4132 attribute vec4 vertex_color; 4133#endif 4134#ifdef NINESLICED 4135 varying vec2 vMask; 4136 varying vec2 vTiledUv; 4137 uniform mediump vec4 innerOffset; 4138 uniform mediump vec2 outerScale; 4139 uniform mediump vec4 atlasRect; 4140#endif 4141vec3 dPositionW; 4142mat4 dModelMatrix; 4143#include "transformCoreVS" 4144#ifdef UV0 4145 attribute vec2 vertex_texCoord0; 4146 #include "uv0VS" 4147#endif 4148#ifdef UV1 4149 attribute vec2 vertex_texCoord1; 4150 #include "uv1VS" 4151#endif 4152#ifdef LINEAR_DEPTH 4153 #ifndef VIEWMATRIX 4154 #define VIEWMATRIX 4155 uniform mat4 matrix_view; 4156 #endif 4157#endif 4158#include "transformVS" 4159#ifdef NORMALS 4160 #include "normalCoreVS" 4161 #include "normalVS" 4162#endif 4163#ifdef TANGENTS 4164 attribute vec4 vertex_tangent; 4165#endif 4166#include "uvTransformUniformsPS, UV_TRANSFORMS_COUNT" 4167#ifdef MSDF 4168 #include "msdfVS" 4169#endif 4170#include "litUserCodeVS" 4171#ifdef VERTEX_COLOR 4172 vec3 decodeGamma(vec3 raw) { 4173 return pow(raw, vec3(2.2)); 4174 } 4175 vec4 gammaCorrectInput(vec4 color) { 4176 return vec4(decodeGamma(color.xyz), color.w); 4177 } 4178#endif 4179void main(void) { 4180 #include "litUserMainStartVS" 4181 gl_PointSize = 1.0; 4182 gl_Position = getPosition(); 4183 vPositionW = getWorldPosition(); 4184 #ifdef NORMALS 4185 vNormalW = getNormal(); 4186 #endif 4187 #ifdef TANGENTS 4188 vTangentW = normalize(dNormalMatrix * vertex_tangent.xyz); 4189 vBinormalW = cross(vNormalW, vTangentW) * vertex_tangent.w; 4190 #elif defined(GGX_SPECULAR) 4191 vObjectSpaceUpW = normalize(dNormalMatrix * vec3(0, 1, 0)); 4192 #endif 4193 #ifdef UV0 4194 vec2 uv0 = getUv0(); 4195 #ifdef UV0_UNMODIFIED 4196 vUv0 = uv0; 4197 #endif 4198 #endif 4199 #ifdef UV1 4200 vec2 uv1 = getUv1(); 4201 #ifdef UV1_UNMODIFIED 4202 vUv1 = uv1; 4203 #endif 4204 #endif 4205 #include "uvTransformVS, UV_TRANSFORMS_COUNT" 4206 #ifdef VERTEX_COLOR 4207 #ifdef STD_VERTEX_COLOR_GAMMA 4208 vVertexColor = gammaCorrectInput(vertex_color); 4209 #else 4210 vVertexColor = vertex_color; 4211 #endif 4212 #endif 4213 #ifdef LINEAR_DEPTH 4214 vLinearDepth = -(matrix_view * vec4(vPositionW, 1.0)).z; 4215 #endif 4216 #ifdef MSDF 4217 unpackMsdfParams(); 4218 #endif 4219 #include "litUserMainEndVS" 4220} 4221`,mL=` 4222#ifdef PICK_PASS 4223 #include "pickPS" 4224#endif 4225#ifdef PREPASS_PASS 4226 #include "floatAsUintPS" 4227#endif 4228void main(void) { 4229 #include "litUserMainStartPS" 4230 evaluateFrontend(); 4231 #ifdef PICK_PASS 4232 pcFragColor0 = getPickOutput(); 4233 #ifdef DEPTH_PICK_PASS 4234 pcFragColor1 = getPickDepth(); 4235 #endif 4236 #endif 4237 #ifdef PREPASS_PASS 4238 gl_FragColor = float2vec4(vLinearDepth); 4239 #endif 4240 #include "litUserMainEndPS" 4241} 4242`,_L=` 4243vec3 litArgs_albedo; 4244float litArgs_opacity; 4245vec3 litArgs_emission; 4246vec3 litArgs_worldNormal; 4247float litArgs_ao; 4248vec3 litArgs_lightmap; 4249vec3 litArgs_lightmapDir; 4250float litArgs_metalness; 4251vec3 litArgs_specularity; 4252float litArgs_specularityFactor; 4253float litArgs_gloss; 4254float litArgs_sheen_gloss; 4255vec3 litArgs_sheen_specularity; 4256float litArgs_transmission; 4257float litArgs_thickness; 4258float litArgs_ior;
4259float litArgs_dispersion; 4260float litArgs_iridescence_intensity; 4261float litArgs_iridescence_thickness; 4262vec3 litArgs_clearcoat_worldNormal; 4263float litArgs_clearcoat_specularity; 4264float litArgs_clearcoat_gloss; 4265`,gL=` 4266 #if LIT_NONE_SLICE_MODE == TILED 4267 const float textureBias = -1000.0; 4268 #else 4269 uniform float textureBias; 4270 #endif 4271 #include "litShaderArgsPS" 4272`,vL=` 4273#if LIGHT_TYPE != DIRECTIONAL 4274 uniform vec3 view_position; 4275 uniform float light_radius; 4276#endif 4277#if SHADOW_TYPE == PCSS_32F 4278 #include "linearizeDepthPS" 4279#endif 4280void main(void) { 4281 #include "litUserMainStartPS" 4282 evaluateFrontend(); 4283 #ifdef PERSPECTIVE_DEPTH 4284 float depth = gl_FragCoord.z; 4285 #if SHADOW_TYPE == PCSS_32F 4286 #if LIGHT_TYPE != DIRECTIONAL 4287 depth = linearizeDepthWithParams(depth, camera_params); 4288 #endif 4289 #endif 4290 #else 4291 float depth = min(distance(view_position, vPositionW) / light_radius, 0.99999); 4292 #define MODIFIED_DEPTH 4293 #endif 4294 #if SHADOW_TYPE == VSM_16F || SHADOW_TYPE == VSM_32F 4295 #if SHADOW_TYPE == VSM_32F 4296 float exponent = 15.0; 4297 #else 4298 float exponent = 5.54; 4299 #endif 4300 depth = 2.0 * depth - 1.0; 4301 depth = exp(exponent * depth); 4302 gl_FragColor = vec4(depth, depth*depth, 1.0, 1.0); 4303 #else 4304 #if SHADOW_TYPE == PCSS_32F 4305 gl_FragColor.r = depth; 4306 #else 4307 #ifdef MODIFIED_DEPTH 4308 gl_FragDepth = depth; 4309 #endif 4310 gl_FragColor = vec4(1.0); 4311 #endif 4312 #endif 4313 #include "litUserMainEndPS" 4314} 4315`,SL=` 4316mat3 transposeMat3( const in mat3 m ) { 4317 mat3 tmp; 4318 tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x ); 4319 tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y ); 4320 tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z ); 4321 return tmp; 4322} 4323vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { 4324 const float LUT_SIZE = 64.0; 4325 const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; 4326 const float LUT_BIAS = 0.5 / LUT_SIZE; 4327 float dotNV = saturate( dot( N, V ) ); 4328 vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); 4329 uv = uv * LUT_SCALE + LUT_BIAS; 4330 return uv; 4331} 4332float LTC_ClippedSphereFormFactor( const in vec3 f ) { 4333 float l = length( f ); 4334 return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); 4335} 4336vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { 4337 float x = dot( v1, v2 ); 4338 float y = abs( x ); 4339 float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; 4340 float b = 3.4175940 + ( 4.1616724 + y ) * y; 4341 float v = a / b; 4342 float theta_sintheta = ( x >
4342 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; 4343 return cross( v1, v2 ) * theta_sintheta; 4344} 4345struct Coords { 4346 vec3 coord0; 4347 vec3 coord1; 4348 vec3 coord2; 4349 vec3 coord3; 4350}; 4351float LTC_EvaluateRect( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in Coords rectCoords) { 4352 vec3 v1 = rectCoords.coord1 - rectCoords.coord0; 4353 vec3 v2 = rectCoords.coord3 - rectCoords.coord0; 4354 4355 vec3 lightNormal = cross( v1, v2 ); 4356 float factor = sign(-dot( lightNormal, P - rectCoords.coord0 )); 4357 vec3 T1, T2; 4358 T1 = normalize( V - N * dot( V, N ) ); 4359 T2 = factor * cross( N, T1 ); 4360 mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) ); 4361 vec3 coords[ 4 ]; 4362 coords[ 0 ] = mat * ( rectCoords.coord0 - P ); 4363 coords[ 1 ] = mat * ( rectCoords.coord1 - P ); 4364 coords[ 2 ] = mat * ( rectCoords.coord2 - P ); 4365 coords[ 3 ] = mat * ( rectCoords.coord3 - P ); 4366 coords[ 0 ] = normalize( coords[ 0 ] ); 4367 coords[ 1 ] = normalize( coords[ 1 ] ); 4368 coords[ 2 ] = normalize( coords[ 2 ] ); 4369 coords[ 3 ] = normalize( coords[ 3 ] ); 4370 vec3 vectorFormFactor = vec3( 0.0 ); 4371 vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); 4372 vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); 4373 vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); 4374 vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); 4375 float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); 4376 return result; 4377} 4378Coords dLTCCoords; 4379Coords getLTCLightCoords(vec3 lightPos, vec3 halfWidth, vec3 halfHeight){ 4380 Coords coords; 4381 coords.coord0 = lightPos + halfWidth - halfHeight; 4382 coords.coord1 = lightPos - halfWidth - halfHeight; 4383 coords.coord2 = lightPos - halfWidth + halfHeight; 4384 coords.coord3 = lightPos + halfWidth + halfHeight; 4385 return coords; 4386} 4387float dSphereRadius; 4388Coords getSphereLightCoords(vec3 lightPos, vec3 halfWidth, vec3 halfHeight){ 4389 dSphereRadius = max(length(halfWidth), length(halfHeight)); 4390 vec3 f = reflect(normalize(lightPos - view_position), vNormalW); 4391 vec3 w = normalize(cross(f, halfHeight)); 4392 vec3 h = normalize(cross(f, w)); 4393 return getLTCLightCoords(lightPos, w * dSphereRadius, h * dSphereRadius); 4394} 4395vec2 dLTCUV; 4396#ifdef LIT_CLEARCOAT 4397 vec2 ccLTCUV; 4398#endif 4399vec2 getLTCLightUV(float gloss, vec3 worldNormal, vec3 viewDir) 4400{ 4401 float roughness = max((1.0 - gloss) * (1.0 - gloss), 0.001); 4402 return LTC_Uv( worldNormal, viewDir, roughness ); 4403} 4404vec3 dLTCSpecFres; 4405#ifdef LIT_CLEARCOAT 4406 vec3 ccLTCSpecFres; 4407#endif 4408vec3 getLTCLightSpecFres(vec2 uv, vec3 specularity) 4409{ 4410 vec4 t2 = texture2DLod(areaLightsLutTex2, uv, 0.0); 4411 return specularity * t2.x + ( vec3( 1.0 ) - specularity) * t2.y; 4412} 4413void calcLTCLightValues(float gloss, vec3 worldNormal, vec3 viewDir, vec3 specularity, float clearcoatGloss, vec3 clearcoatWorldNormal, float clearcoatSpecularity) 4414{ 4415 dLTCUV = getLTCLightUV(gloss, worldNormal, viewDir); 4416 dLTCSpecFres = getLTCLightSpecFres(dLTCUV, specularity); 4417#ifdef LIT_CLEARCOAT 4418 ccLTCUV = getLTCLightUV(clearcoatGloss, clearcoatWorldNormal, viewDir); 4419 ccLTCSpecFres = getLTCLightSpecFres(ccLTCUV, vec3(clearcoatSpecularity)); 4420#endif 4421} 4422void calcRectLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight) { 4423 dLTCCoords = getLTCLightCoords(lightPos, halfWidth, halfHeight); 4424} 4425void calcDiskLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight) { 4426 calcRectLightValues(lightPos, halfWidth, halfHeight); 4427} 4428void calcSphereLightValues(vec3 lightPos, vec3 halfWidth, vec3 halfHeight) { 4429 dLTCCoords = getSphereLightCoords(lightPos, halfWidth, halfHeight); 4430} 4431vec3 SolveCubic(vec4 Coefficient) 4432{ 4433 float pi = 3.14159; 4434 Coefficient.xyz /= Coefficient.w; 4435 Coefficient.yz /= 3.0; 4436 float A = Coefficient.w; 4437 float B = Coefficient.z; 4438 float C = Coefficient.y; 4439 float D = Coefficient.x; 4440 vec3 Delta = vec3( 4441 -Coefficient.z * Coefficient.z + Coefficient.y, 4442 -Coefficient.y * Coefficient.z + Coefficient.x, 4443 dot(vec2(Coefficient.z, -Coefficient.y), Coefficient.xy) 4444 ); 4445 float Discriminant = dot(vec2(4.0 * Delta.x, -Delta.y), Delta.zy); 4446 vec2 xlc, xsc; 4447 { 4448 float A_a = 1.0; 4449 float C_a = Delta.x; 4450 float D_a = -2.0 * B * Delta.x + Delta.y; 4451 float Theta = atan(sqrt(Discriminant), -D_a) / 3.0; 4452 float x_1a = 2.0 * sqrt(-C_a) * cos(Theta); 4453 float x_3a = 2.0 * sqrt(-C_a) * cos(Theta + (2.0 / 3.0) * pi); 4454 float xl; 4455 if ((x_1a + x_3a) > 2.0 * B) 4456 xl = x_1a; 4457 else 4458 xl = x_3a; 4459 xlc = vec2(xl - B, A); 4460 } 4461 { 4462 float A_d = D; 4463 float C_d = Delta.z; 4464 float D_d = -D * Delta.y + 2.0 * C * Delta.z; 4465 float Theta = atan(D * sqrt(Discriminant), -D_d) / 3.0; 4466 float x_1d = 2.0 * sqrt(-C_d) * cos(Theta); 4467 float x_3d = 2.0 * sqrt(-C_d) * cos(Theta + (2.0 / 3.0) * pi); 4468 float xs; 4469 if (x_1d + x_3d < 2.0 * C) 4470 xs = x_1d; 4471 else 4472 xs = x_3d; 4473 xsc = vec2(-D, xs + C); 4474 } 4475 float E = xlc.y * xsc.y; 4476 float F = -xlc.x * xsc.y - xlc.y * xsc.x; 4477 float G = xlc.x * xsc.x; 4478 vec2 xmc = vec2(C * F - B * G, -B * F + C * E); 4479 vec3 Root = vec3(xsc.x / xsc.y, xmc.x / xmc.y, xlc.x / xlc.y); 4480 if (Root.x < Root.y && Root.x < Root.z) 4481 Root.xyz = Root.yxz; 4482 else if (Root.z < Root.x && Root.z < Root.y) 4483 Root.xyz = Root.xzy; 4484 return Root; 4485} 4486float LTC_EvaluateDisk(vec3 N, vec3 V, vec3 P, mat3 Minv, Coords points) 4487{ 4488 vec3 T1 = normalize(V - N * dot(V, N)); 4489 vec3 T2 = cross(N, T1); 4490 mat3 R = transposeMat3( mat3( T1, T2, N ) ); 4491 vec3 L_[ 3 ]; 4492 L_[ 0 ] = R * ( points.coord0 - P ); 4493 L_[ 1 ] = R * ( points.coord1 - P ); 4494 L_[ 2 ] = R * ( points.coord2 - P ); 4495 vec3 C = 0.5 * (L_[0] + L_[2]); 4496 vec3 V1 = 0.5 * (L_[1] - L_[2]); 4497 vec3 V2 = 0.5 * (L_[1] - L_[0]); 4498 C = Minv * C; 4499 V1 = Minv * V1; 4500 V2 = Minv * V2; 4501 float a, b; 4502 float d11 = dot(V1, V1); 4503 float d22 = dot(V2, V2); 4504 float d12 = dot(V1, V2);
4505 if (abs(d12) / sqrt(d11 * d22) > 0.0001) 4506 { 4507 float tr = d11 + d22; 4508 float det = -d12 * d12 + d11 * d22; 4509 det = sqrt(det); 4510 float u = 0.5 * sqrt(tr - 2.0 * det); 4511 float v = 0.5 * sqrt(tr + 2.0 * det); 4512 float e_max = (u + v) * (u + v); 4513 float e_min = (u - v) * (u - v); 4514 vec3 V1_, V2_; 4515 if (d11 > d22) 4516 { 4517 V1_ = d12 * V1 + (e_max - d11) * V2; 4518 V2_ = d12 * V1 + (e_min - d11) * V2; 4519 } 4520 else 4521 { 4522 V1_ = d12*V2 + (e_max - d22)*V1; 4523 V2_ = d12*V2 + (e_min - d22)*V1; 4524 } 4525 a = 1.0 / e_max; 4526 b = 1.0 / e_min; 4527 V1 = normalize(V1_); 4528 V2 = normalize(V2_); 4529 } 4530 else 4531 { 4532 a = 1.0 / dot(V1, V1); 4533 b = 1.0 / dot(V2, V2); 4534 V1 *= sqrt(a); 4535 V2 *= sqrt(b); 4536 } 4537 vec3 V3 = normalize(cross(V1, V2)); 4538 if (dot(C, V3) < 0.0) 4539 V3 *= -1.0; 4540 float L = dot(V3, C); 4541 float x0 = dot(V1, C) / L; 4542 float y0 = dot(V2, C) / L; 4543 float E1 = inversesqrt(a); 4544 float E2 = inversesqrt(b); 4545 a *= L * L; 4546 b *= L * L; 4547 float c0 = a * b; 4548 float c1 = a * b * (1.0 + x0 * x0 + y0 * y0) - a - b; 4549 float c2 = 1.0 - a * (1.0 + x0 * x0) - b * (1.0 + y0 * y0); 4550 float c3 = 1.0; 4551 vec3 roots = SolveCubic(vec4(c0, c1, c2, c3)); 4552 float e1 = roots.x; 4553 float e2 = roots.y; 4554 float e3 = roots.z; 4555 vec3 avgDir = vec3(a * x0 / (a - e2), b * y0 / (b - e2), 1.0); 4556 mat3 rotate = mat3(V1, V2, V3); 4557 avgDir = rotate * avgDir; 4558 avgDir = normalize(avgDir); 4559 float L1 = sqrt(-e2 / e3); 4560 float L2 = sqrt(-e2 / e1); 4561 float formFactor = max(0.0, L1 * L2 * inversesqrt((1.0 + L1 * L1) * (1.0 + L2 * L2))); 4562 4563 const float LUT_SIZE = 64.0; 4564 const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; 4565 const float LUT_BIAS = 0.5 / LUT_SIZE; 4566 vec2 uv = vec2(avgDir.z * 0.5 + 0.5, formFactor); 4567 uv = uv*LUT_SCALE + LUT_BIAS; 4568 float scale = texture2DLod(areaLightsLutTex2, uv, 0.0).w; 4569 return formFactor*scale; 4570} 4571float FixNan(float value) { 4572 #ifdef WEBGPU 4573 return value != value ? 0.0 : value; 4574 #else 4575 return isnan(value) ? 0.0 : value; 4576 #endif 4577} 4578float getRectLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) { 4579 return LTC_EvaluateRect( worldNormal, viewDir, vPositionW, mat3( 1.0 ), dLTCCoords ); 4580} 4581float getDiskLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) { 4582 return FixNan(LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, mat3( 1.0 ), dLTCCoords )); 4583} 4584float getSphereLightDiffuse(vec3 worldNormal, vec3 viewDir, vec3 lightDir, vec3 lightDirNorm) { 4585 float falloff = dSphereRadius / (dot(lightDir, lightDir) + dSphereRadius); 4586 return FixNan(getLightDiffuse(worldNormal, viewDir, lightDirNorm) * falloff); 4587} 4588mat3 getLTCLightInvMat(vec2 uv) 4589{ 4590 vec4 t1 = texture2DLod(areaLightsLutTex1, uv, 0.0); 4591 return mat3( 4592 vec3( t1.x, 0, t1.y ), 4593 vec3( 0, 1, 0 ), 4594 vec3( t1.z, 0, t1.w ) 4595 ); 4596} 4597float calcRectLightSpecular(vec3 worldNormal, vec3 viewDir, vec2 uv) { 4598 mat3 mInv = getLTCLightInvMat(uv); 4599 return LTC_EvaluateRect( worldNormal, viewDir, vPositionW, mInv, dLTCCoords ); 4600} 4601float getRectLightSpecular(vec3 worldNormal, vec3 viewDir) { 4602 return calcRectLightSpecular(worldNormal, viewDir, dLTCUV); 4603} 4604float calcDiskLightSpecular(vec3 worldNormal, vec3 viewDir, vec2 uv) { 4605 mat3 mInv = getLTCLightInvMat(uv); 4606 return LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, mInv, dLTCCoords ); 4607} 4608float getDiskLightSpecular(vec3 worldNormal, vec3 viewDir) { 4609 return calcDiskLightSpecular(worldNormal, viewDir, dLTCUV); 4610} 4611float getSphereLightSpecular(vec3 worldNormal, vec3 viewDir) { 4612 return calcDiskLightSpecular(worldNormal, viewDir, dLTCUV); 4613} 4614`,yL=` 4615#ifdef STD_METALNESS_CONSTANT 4616uniform float material_metalness; 4617#endif 4618void getMetalness() { 4619 float metalness = 1.0; 4620 #ifdef STD_METALNESS_CONSTANT 4621 metalness *= material_metalness; 4622 #endif 4623 #ifdef STD_METALNESS_TEXTURE 4624 metalness *= texture2DBias({STD_METALNESS_TEXTURE_NAME}, {STD_METALNESS_TEXTURE_UV}, textureBias).{STD_METALNESS_TEXTURE_CHANNEL}; 4625 #endif 4626 #ifdef STD_METALNESS_VERTEX 4627 metalness *= saturate(vVertexColor.{STD_METALNESS_VERTEX_CHANNEL}); 4628 #endif 4629 dMetalness = metalness; 4630} 4631`,xL=` 4632uniform sampler2D texture_msdfMap; 4633float median(float r, float g, float b) { 4634 return max(min(r, g), min(max(r, g), b)); 4635} 4636float map (float min, float max, float v) { 4637 return (v - min) / (max - min); 4638} 4639uniform float font_sdfIntensity; 4640uniform float font_pxrange; 4641uniform float font_textureWidth; 4642#ifndef LIT_MSDF_TEXT_ATTRIBUTE 4643 uniform vec4 outline_color; 4644 uniform float outline_thickness; 4645 uniform vec4 shadow_color; 4646 uniform vec2 shadow_offset; 4647#else 4648 varying vec4 outline_color; 4649 varying float outline_thickness; 4650 varying vec4 shadow_color; 4651 varying vec2 shadow_offset; 4652#endif 4653vec4 applyMsdf(vec4 color) { 4654 color.rgb = gammaCorrectInput(color.rgb); 4655 vec3 tsample = texture2D(texture_msdfMap, vUv0).rgb; 4656 vec2 uvShdw = vUv0 - shadow_offset; 4657 vec3 ssample = texture2D(texture_msdfMap, uvShdw).rgb; 4658 float sigDist = median(tsample.r, tsample.g, tsample.b); 4659 float sigDistShdw = median(ssample.r, ssample.g, ssample.b); 4660 float smoothingMax = 0.2; 4661 vec2 w = fwidth(vUv0); 4662 float smoothing = clamp(w.x * font_textureWidth / font_pxrange, 0.0, smoothingMax); 4663 float mapMin = 0.05; 4664 float mapMax = clamp(1.0 - font_sdfIntensity, mapMin, 1.0); 4665 float sigDistInner = map(mapMin, mapMax, sigDist); 4666 float sigDistOutline = map(mapMin, mapMax, sigDist + outline_thickness); 4667 sigDistShdw = map(mapMin, mapMax, sigDistShdw + outline_thickness); 4668 float center = 0.5; 4669 float inside = smoothstep(center-smoothing, center+smoothing, sigDistInner); 4670 float outline = smoothstep(center-smoothing, center+smoothing, sigDistOutline); 4671 float shadow = smoothstep(center-smoothing, center+smoothing, sigDistShdw); 4672 vec4 tcolor = (outline > inside) ? outline * vec4(outline_color.a * outline_color.rgb, outline_color.a) : vec4(0.0); 4673 tcolor = mix(tcolor, color, inside); 4674 vec4 scolor = (shadow > outline) ? shadow * vec4(shadow_color.a * shadow_color.rgb, shadow_color.a) : tcolor; 4675 tcolor = mix(scolor, tcolor, outline); 4676 tcolor.rgb = gammaCorrectOutput(tcolor.rgb); 4677 4678 return tcolor; 4679} 4680`,TL=` 4681vec3 getSpecularModulate(in vec3 specularity, in vec3 albedo, in float metalness, in float f0, in float specularityFactor) { 4682 vec3 dielectricF0 = f0 * specularity * specularityFactor; 4683 return mix(dielectricF0, albedo, metalness); 4684} 4685vec3 getAlbedoModulate(in vec3 albedo, in float metalness) { 4686 return albedo * (1.0 - metalness); 4687} 4688`,wL=` 4689 varying vec2 uv0; 4690 uniform sampler2DArray morphTexture; 4691 uniform highp float morphFactor[{MORPH_TEXTURE_MAX_COUNT}]; 4692 uniform highp uint morphIndex[{MORPH_TEXTURE_MAX_COUNT}]; 4693 uniform int count; 4694 #ifdef MORPH_INT 4695 uniform vec3 aabbSize; 4696 uniform vec3 aabbMin; 4697 #endif 4698 void main (void) { 4699 highp vec3 color = vec3(0, 0, 0);
4700 ivec2 pixelCoords = ivec2(uv0 * vec2(textureSize(morphTexture, 0).xy)); 4701 4702 for (int i = 0; i < count; i++) { 4703 uint textureIndex = morphIndex[i]; 4704 vec3 delta = texelFetch(morphTexture, ivec3(pixelCoords, int(textureIndex)), 0).xyz; 4705 color += morphFactor[i] * delta; 4706 } 4707 #ifdef MORPH_INT 4708 color = (color - aabbMin) / aabbSize * 65535.0; 4709 gl_FragColor = uvec4(color, 1u); 4710 #else 4711 gl_FragColor = vec4(color, 1.0); 4712 #endif 4713 } 4714`,CL=` 4715 attribute vec2 vertex_position; 4716 varying vec2 uv0; 4717 void main(void) { 4718 gl_Position = vec4(vertex_position, 0.5, 1.0); 4719 uv0 = vertex_position.xy * 0.5 + 0.5; 4720 } 4721`,EL=` 4722attribute vec3 vertex_outlineParameters; 4723attribute vec3 vertex_shadowParameters; 4724varying vec4 outline_color; 4725varying float outline_thickness; 4726varying vec4 shadow_color; 4727varying vec2 shadow_offset; 4728void unpackMsdfParams() { 4729 vec3 little = mod(vertex_outlineParameters, 256.); 4730 vec3 big = (vertex_outlineParameters - little) / 256.; 4731 outline_color.rb = little.xy / 255.; 4732 outline_color.ga = big.xy / 255.; 4733 outline_thickness = little.z / 255. * 0.2; 4734 little = mod(vertex_shadowParameters, 256.); 4735 big = (vertex_shadowParameters - little) / 256.; 4736 shadow_color.rb = little.xy / 255.; 4737 shadow_color.ga = big.xy / 255.; 4738 shadow_offset = (vec2(little.z, big.z) / 127. - 1.) * 0.005; 4739} 4740`,bL=` 4741mat3 dNormalMatrix; 4742vec3 getNormal() { 4743 dNormalMatrix = getNormalMatrix(dModelMatrix); 4744 vec3 localNormal = getLocalNormal(vertex_normal); 4745 return normalize(dNormalMatrix * localNormal); 4746} 4747`,AL=` 4748attribute vec3 vertex_normal; 4749uniform mat3 matrix_normal; 4750#ifdef MORPHING_NORMAL 4751 #ifdef MORPHING_INT 4752 uniform highp usampler2D morphNormalTex; 4753 #else 4754 uniform highp sampler2D morphNormalTex; 4755 #endif 4756#endif 4757vec3 getLocalNormal(vec3 vertexNormal) { 4758 vec3 localNormal = vertex_normal; 4759 #ifdef MORPHING_NORMAL 4760 ivec2 morphUV = getTextureMorphCoords(); 4761 #ifdef MORPHING_INT 4762 vec3 morphNormal = vec3(texelFetch(morphNormalTex, ivec2(morphUV), 0).xyz) / 65535.0 * 2.0 - 1.0; 4763 #else 4764 vec3 morphNormal = texelFetch(morphNormalTex, ivec2(morphUV), 0).xyz; 4765 #endif 4766 localNormal += morphNormal; 4767 #endif 4768 return localNormal; 4769} 4770#if defined(SKIN) || defined(BATCH) 4771 mat3 getNormalMatrix(mat4 modelMatrix) { 4772 return mat3(modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz); 4773 } 4774#elif defined(INSTANCING) 4775 mat3 getNormalMatrix(mat4 modelMatrix) { 4776 return mat3(modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz); 4777 } 4778#else 4779 mat3 getNormalMatrix(mat4 modelMatrix) { 4780 return matrix_normal; 4781 } 4782#endif 4783`,PL=` 4784#ifdef STD_NORMAL_TEXTURE 4785 uniform float material_bumpiness; 4786#endif 4787#ifdef STD_NORMALDETAIL_TEXTURE 4788 uniform float material_normalDetailMapBumpiness; 4789 vec3 blendNormals(vec3 n1, vec3 n2) { 4790 n1 += vec3(0, 0, 1); 4791 n2 *= vec3(-1, -1, 1); 4792 return n1 * dot(n1, n2) / n1.z - n2; 4793 } 4794#endif 4795void getNormal() { 4796#ifdef STD_NORMAL_TEXTURE 4797 vec3 normalMap = {STD_NORMAL_TEXTURE_DECODE}(texture2DBias({STD_NORMAL_TEXTURE_NAME}, {STD_NORMAL_TEXTURE_UV}, textureBias)); 4798 normalMap = mix(vec3(0.0, 0.0, 1.0), normalMap, material_bumpiness); 4799 #ifdef STD_NORMALDETAIL_TEXTURE 4800 vec3 normalDetailMap = {STD_NORMALDETAIL_TEXTURE_DECODE}(texture2DBias({STD_NORMALDETAIL_TEXTURE_NAME}, {STD_NORMALDETAIL_TEXTURE_UV}, textureBias)); 4801 normalDetailMap = mix(vec3(0.0, 0.0, 1.0), normalDetailMap, material_normalDetailMapBumpiness); 4802 normalMap = blendNormals(normalMap, normalDetailMap); 4803 #endif 4804 dNormalW = normalize(dTBN * normalMap); 4805#else 4806 dNormalW = dVertexNormalW; 4807#endif 4808} 4809`,IL=` 4810uniform float material_opacity; 4811uniform float material_alphaDitherScale; 4812void getOpacity() { 4813 dAlpha = material_opacity; 4814 #ifdef STD_OPACITY_TEXTURE 4815 dAlpha *= texture2DBias({STD_OPACITY_TEXTURE_NAME}, {STD_OPACITY_TEXTURE_UV}, textureBias).{STD_OPACITY_TEXTURE_CHANNEL}; 4816 #endif 4817 #ifdef STD_OPACITY_VERTEX 4818 dAlpha *= clamp(vVertexColor.{STD_OPACITY_VERTEX_CHANNEL}, 0.0, 1.0); 4819 #endif 4820} 4821`,DL=` 4822#if STD_OPACITY_DITHER == BAYER8 4823 #include "bayerPS" 4824#endif 4825uniform vec4 blueNoiseJitter; 4826#if STD_OPACITY_DITHER == BLUENOISE 4827 uniform sampler2D blueNoiseTex32; 4828#endif 4829void opacityDither(float alpha, float id) { 4830 if (alpha <= 0.0) 4831 discard; 4832 if (alpha >= 1.0) 4833 return; 4834 #if STD_OPACITY_DITHER == BAYER8 4835 float noise = bayer8(floor(mod(gl_FragCoord.xy + blueNoiseJitter.xy + id, 8.0)
4835)) / 64.0; 4836 #else 4837 #if STD_OPACITY_DITHER == BLUENOISE 4838 vec2 uv = fract(gl_FragCoord.xy / 32.0 + blueNoiseJitter.xy + id); 4839 float noise = texture2DLod(blueNoiseTex32, uv, 0.0).y; 4840 #endif 4841 #if STD_OPACITY_DITHER == IGNNOISE 4842 vec3 magic = vec3(0.06711056, 0.00583715, 52.9829189); 4843 float noise = fract(magic.z * fract(dot(gl_FragCoord.xy + blueNoiseJitter.xy + id, magic.xy))); 4844 #endif 4845 #endif 4846 noise = pow(noise, 2.2); 4847 if (alpha < noise) 4848 discard; 4849} 4850`,ML=` 4851`,RL=` 4852#if LIT_BLEND_TYPE == NORMAL || LIT_BLEND_TYPE == ADDITIVEALPHA || defined(LIT_ALPHA_TO_COVERAGE) 4853 gl_FragColor.a = litArgs_opacity; 4854#elif LIT_BLEND_TYPE == PREMULTIPLIED 4855 gl_FragColor.rgb *= litArgs_opacity; 4856 gl_FragColor.a = litArgs_opacity; 4857#else 4858 gl_FragColor.a = 1.0; 4859#endif 4860`,LL=` 4861varying vec2 vUv0; 4862uniform sampler2D source; 4863void main(void) { 4864 gl_FragColor = texture2D(source, vUv0); 4865} 4866`,FL=` 4867uniform vec3 material_sheen; 4868void getSheen() { 4869 vec3 sheenColor = material_sheen; 4870 #ifdef STD_SHEEN_TEXTURE 4871 sheenColor *= {STD_SHEEN_TEXTURE_DECODE}(texture2DBias({STD_SHEEN_TEXTURE_NAME}, {STD_SHEEN_TEXTURE_UV}, textureBias)).{STD_SHEEN_TEXTURE_CHANNEL}; 4872 #endif 4873 #ifdef STD_SHEEN_VERTEX 4874 sheenColor *= saturate(vVertexColor.{STD_SHEEN_VERTEX_CHANNEL}); 4875 #endif 4876 sSpecularity = sheenColor; 4877} 4878`,OL=` 4879uniform float material_sheenGloss; 4880void getSheenGlossiness() { 4881 float sheenGlossiness = material_sheenGloss; 4882 #ifdef STD_SHEENGLOSS_TEXTURE 4883 sheenGlossiness *= texture2DBias({STD_SHEENGLOSS_TEXTURE_NAME}, {STD_SHEENGLOSS_TEXTURE_UV}, textureBias).{STD_SHEENGLOSS_TEXTURE_CHANNEL}; 4884 #endif 4885 #ifdef STD_SHEENGLOSS_VERTEX 4886 sheenGlossiness *= saturate(vVertexColor.{STD_SHEENGLOSS_VERTEX_CHANNEL}); 4887 #endif 4888 #ifdef STD_SHEENGLOSS_INVERT 4889 sheenGlossiness = 1.0 - sheenGlossiness; 4890 #endif 4891 sGlossiness = sheenGlossiness + 0.0000001; 4892} 4893`,BL=` 4894uniform float material_heightMapFactor; 4895void getParallax() { 4896 float parallaxScale = material_heightMapFactor; 4897 float height = texture2DBias({STD_HEIGHT_TEXTURE_NAME}, {STD_HEIGHT_TEXTURE_UV}, textureBias).{STD_HEIGHT_TEXTURE_CHANNEL}; 4898 height = height * parallaxScale - parallaxScale * 0.5; 4899 vec3 viewDirT = dViewDirW * dTBN; 4900 viewDirT.z += 0.42; 4901 dUvOffset = height * (viewDirT.xy / viewDirT.z); 4902} 4903`,NL=` 4904vec4 encodePickOutput(uint id) { 4905 const vec4 inv = vec4(1.0 / 255.0); 4906 const uvec4 shifts = uvec4(16, 8, 0, 24); 4907 uvec4 col = (uvec4(id) >> shifts) & uvec4(0xff); 4908 return vec4(col) * inv; 4909} 4910#ifndef PICK_CUSTOM_ID 4911 uniform uint meshInstanceId; 4912 vec4 getPickOutput() { 4913 return encodePickOutput(meshInstanceId); 4914 } 4915#endif 4916#ifdef DEPTH_PICK_PASS 4917 #include "floatAsUintPS" 4918 #ifndef CAMERAPLANES 4919 #define CAMERAPLANES 4920 uniform vec4 camera_params; 4921 #endif 4922 vec4 getPickDepth() { 4923 float linearDepth; 4924 if (camera_params.w > 0.5) { 4925 linearDepth = gl_FragCoord.z; 4926 } else { 4927 float viewDist = 1.0 / gl_FragCoord.w; 4928 linearDepth = (viewDist - camera_params.z) / (camera_params.y - camera_params.z); 4929 } 4930 return float2uint(linearDepth); 4931 } 4932#endif 4933`,kL=` 4934void getReflDir(vec3 worldNormal, vec3 viewDir, float gloss, mat3 tbn) { 4935 dReflDirW = normalize(-reflect(viewDir, worldNormal)); 4936} 4937`,UL=` 4938void getReflDir(vec3 worldNormal, vec3 viewDir, float gloss, mat3 tbn) { 4939 float roughness = sqrt(1.0 - min(gloss, 1.0)); 4940 vec2 direction = dAnisotropyRotation; 4941 vec3 anisotropicT = normalize(tbn * vec3(direction, 0.0)); 4942 vec3 anisotropicB = normalize(cross(tbn[2], anisotropicT)); 4943 float anisotropy = dAnisotropy; 4944 vec3 anisotropicDirection = anisotropicB; 4945 vec3 anisotropicTangent = cross(anisotropicDirection, viewDir); 4946 vec3 anisotropicNormal = cross(anisotropicTangent, anisotropicDirection); 4947 float bendFactor = 1.0 - anisotropy * (1.0 - roughness); 4948 float bendFactor4 = bendFactor * bendFactor * bendFactor * bendFactor; 4949 vec3 bentNormal = normalize(mix(normalize(anisotropicNormal), normalize(worldNormal), bendFactor4)); 4950 dReflDirW = reflect(-viewDir, bentNormal); 4951} 4952`,zL=` 4953#ifdef LIT_CLEARCOAT 4954void addReflectionCC(vec3 reflDir, float gloss) { 4955 ccReflection += calcReflection(reflDir, gloss); 4956} 4957#endif 4958`,VL=` 4959uniform samplerCube texture_cubeMap; 4960uniform float material_reflectivity; 4961vec3 calcReflection(vec3 reflDir, float gloss) { 4962 vec3 lookupVec = cubeMapProject(reflDir); 4963 lookupVec.x *= -1.0; 4964 return {reflectionDecode}(textureCube(texture_cubeMap, lookupVec)); 4965} 4966void addReflection(vec3 reflDir, float gloss) { 4967 dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity); 4968} 4969`,GL=` 4970#ifndef ENV_ATLAS 4971 #define ENV_ATLAS 4972 uniform sampler2D texture_envAtlas; 4973#endif 4974uniform samplerCube texture_cubeMap; 4975uniform float material_reflectivity; 4976vec3 calcReflection(vec3 reflDir, float gloss) { 4977 vec3 dir = cubeMapProject(reflDir) * vec3(-1.0, 1.0, 1.0); 4978 vec2 uv = toSphericalUv(dir);
4979 float level = saturate(1.0 - gloss) * 5.0; 4980 float ilevel = floor(level); 4981 float flevel = level - ilevel; 4982 vec3 sharp = {reflectionCubemapDecode}(textureCube(texture_cubeMap, dir)); 4983 vec3 roughA = {reflectionDecode}(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel))); 4984 vec3 roughB = {reflectionDecode}(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel + 1.0))); 4985 return processEnvironment(mix(sharp, mix(roughA, roughB, flevel), min(level, 1.0))); 4986} 4987void addReflection(vec3 reflDir, float gloss) { 4988 dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity); 4989} 4990`,HL=` 4991#ifndef ENV_ATLAS 4992#define ENV_ATLAS 4993 uniform sampler2D texture_envAtlas; 4994#endif 4995uniform float material_reflectivity; 4996float shinyMipLevel(vec2 uv) { 4997 vec2 dx = dFdx(uv); 4998 vec2 dy = dFdy(uv); 4999 vec2 uv2 = vec2(fract(uv.x + 0.5), uv.y); 5000 vec2 dx2 = dFdx(uv2); 5001 vec2 dy2 = dFdy(uv2); 5002 float maxd = min(max(dot(dx, dx), dot(dy, dy)), max(dot(dx2, dx2), dot(dy2, dy2))); 5003 return clamp(0.5 * log2(maxd) - 1.0 + textureBias, 0.0, 5.0); 5004} 5005vec3 calcReflection(vec3 reflDir, float gloss) { 5006 vec3 dir = cubeMapProject(reflDir) * vec3(-1.0, 1.0, 1.0); 5007 vec2 uv = toSphericalUv(dir); 5008 float level = saturate(1.0 - gloss) * 5.0; 5009 float ilevel = floor(level); 5010 float level2 = shinyMipLevel(uv * atlasSize); 5011 float ilevel2 = floor(level2); 5012 vec2 uv0, uv1; 5013 float weight; 5014 if (ilevel == 0.0) { 5015 uv0 = mapShinyUv(uv, ilevel2); 5016 uv1 = mapShinyUv(uv, ilevel2 + 1.0); 5017 weight = level2 - ilevel2; 5018 } else { 5019 uv0 = uv1 = mapRoughnessUv(uv, ilevel); 5020 weight = 0.0; 5021 } 5022 vec3 linearA = {reflectionDecode}(texture2D(texture_envAtlas, uv0)); 5023 vec3 linearB = {reflectionDecode}(texture2D(texture_envAtlas, uv1)); 5024 vec3 linear0 = mix(linearA, linearB, weight); 5025 vec3 linear1 = {reflectionDecode}(texture2D(texture_envAtlas, mapRoughnessUv(uv, ilevel + 1.0))); 5026 return processEnvironment(mix(linear0, linear1, level - ilevel)); 5027} 5028void addReflection(vec3 reflDir, float gloss) { 5029 dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity); 5030} 5031`,WL=` 5032#ifndef VIEWMATRIX 5033 #define VIEWMATRIX 5034 uniform mat4 matrix_view; 5035#endif 5036uniform sampler2D texture_sphereMap; 5037uniform float material_reflectivity; 5038vec3 calcReflection(vec3 reflDir, float gloss) { 5039 vec3 reflDirV = (mat3(matrix_view) * reflDir); 5040 float m = 2.0 * sqrt(dot(reflDirV.xy, reflDirV.xy) + (reflDirV.z + 1.0) * (reflDirV.z + 1.0)); 5041 vec2 sphereMapUv = reflDirV.xy / m + 0.5; 5042 return {reflectionDecode}(texture2D(texture_sphereMap, sphereMapUv)); 5043} 5044void addReflection(vec3 reflDir, float gloss) { 5045 dReflection += vec4(calcReflection(reflDir, gloss), material_reflectivity); 5046} 5047`,XL=` 5048void addReflectionSheen(vec3 worldNormal, vec3 viewDir, float gloss) { 5049 float NoV = dot(worldNormal, viewDir); 5050 float alphaG = gloss * gloss; 5051 float a = gloss < 0.25 ? -339.2 * alphaG + 161.4 * gloss - 25.9 : -8.48 * alphaG + 14.3 * gloss - 9.95; 5052 float b = gloss < 0.25 ? 44.0 * alphaG - 23.7 * gloss + 3.26 : 1.97 * alphaG - 3.27 * gloss + 0.72; 5053 float DG = exp( a * NoV + b ) + ( gloss < 0.25 ? 0.0 : 0.1 * ( gloss - 0.25 ) ); 5054 sReflection += calcReflection(worldNormal, 0.0) * saturate(DG); 5055} 5056`,YL=` 5057vec3 refract2(vec3 viewVec, vec3 normal, float IOR) { 5058 float vn = dot(viewVec, normal); 5059 float k = 1.0 - IOR * IOR * (1.0 - vn * vn); 5060 vec3 refrVec = IOR * viewVec - (IOR * vn + sqrt(k)) * normal; 5061 return refrVec; 5062} 5063void addRefraction( 5064 vec3 worldNormal, 5065 vec3 viewDir, 5066 float thickness, 5067 float gloss, 5068 vec3 specularity, 5069 vec3 albedo, 5070 float transmission, 5071 float refractionIndex, 5072 float dispersion 5073#if defined(LIT_IRIDESCENCE) 5074 , vec3 iridescenceFresnel, 5075 float iridescenceIntensity 5076#endif 5077) { 5078 vec4 tmpRefl = dReflection; 5079 vec3 reflectionDir = refract2(-viewDir, worldNormal, refractionIndex); 5080 dReflection = vec4(0); 5081 addReflection(reflectionDir, gloss); 5082 dDiffuseLight = mix(dDiffuseLight, dReflection.rgb * albedo, transmission); 5083 dReflection = tmpRefl; 5084} 5085`,jL=` 5086uniform float material_invAttenuationDistance; 5087uniform vec3 material_attenuation; 5088vec3 evalRefractionColor(vec3 refractionVector, float gloss, float refractionIndex) { 5089 vec4 pointOfRefraction = vec4(vPositionW + refractionVector, 1.0); 5090 vec4 projectionPoint = matrix_viewProjection * pointOfRefraction; 5091 vec2 uv = getGrabScreenPos(projectionPoint); 5092 float iorToRoughness = (1.0 - gloss) * clamp((1.0 / refractionIndex) * 2.0 - 2.0, 0.0, 1.0); 5093 float refractionLod = log2(uScreenSize.x) * iorToRoughness; 5094 vec3 refraction = texture2DLod(uSceneColorMap, uv, refractionLod).rgb; 5095 #ifdef SCENE_COLORMAP_GAMMA 5096 refraction = decodeGamma(refraction); 5097 #endif 5098 return refraction; 5099} 5100void addRefraction( 5101 vec3 worldNormal, 5102 vec3 viewDir, 5103 float thickness, 5104 float gloss, 5105 vec3 specularity, 5106 vec3 albedo, 5107 float transmission,
5108 float refractionIndex, 5109 float dispersion 5110#if defined(LIT_IRIDESCENCE) 5111 , vec3 iridescenceFresnel, 5112 float iridescenceIntensity 5113#endif 5114) { 5115 vec3 modelScale; 5116 modelScale.x = length(vec3(matrix_model[0].xyz)); 5117 modelScale.y = length(vec3(matrix_model[1].xyz)); 5118 modelScale.z = length(vec3(matrix_model[2].xyz)); 5119 vec3 scale = thickness * modelScale; 5120 vec3 refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndex)) * scale; 5121 vec3 refraction = evalRefractionColor(refractionVector, gloss, refractionIndex); 5122 #ifdef LIT_DISPERSION 5123 float halfSpread = (1.0 / refractionIndex - 1.0) * 0.025 * dispersion; 5124 float refractionIndexR = refractionIndex - halfSpread; 5125 refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndexR)) * scale; 5126 refraction.r = evalRefractionColor(refractionVector, gloss, refractionIndexR).r; 5127 float refractionIndexB = refractionIndex + halfSpread; 5128 refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndexB)) * scale; 5129 refraction.b = evalRefractionColor(refractionVector, gloss, refractionIndexB).b; 5130 #endif 5131 vec3 transmittance; 5132 if (material_invAttenuationDistance != 0.0) 5133 { 5134 vec3 attenuation = -log(material_attenuation) * material_invAttenuationDistance; 5135 transmittance = exp(-attenuation * length(refractionVector)); 5136 } 5137 else 5138 { 5139 transmittance = vec3(1.0); 5140 } 5141 vec3 fresnel = vec3(1.0) - 5142 getFresnel( 5143 dot(viewDir, worldNormal), 5144 gloss, 5145 specularity 5146 #if defined(LIT_IRIDESCENCE) 5147 , iridescenceFresnel, 5148 iridescenceIntensity 5149 #endif 5150 ); 5151 dDiffuseLight = mix(dDiffuseLight, refraction * transmittance * fresnel, transmission); 5152} 5153`,qL=` 5154varying vec2 vUv0; 5155#ifdef CUBEMAP_SOURCE 5156 uniform samplerCube sourceCube; 5157#else 5158 uniform sampler2D sourceTex; 5159#endif 5160#ifdef USE_SAMPLES_TEX 5161 uniform sampler2D samplesTex; 5162 uniform vec2 samplesTexInverseSize; 5163#endif 5164uniform vec3 params; 5165float targetFace() { return params.x; } 5166float targetTotalPixels() { return params.y; } 5167float sourceTotalPixels() { return params.z; } 5168float PI = 3.141592653589793; 5169float saturate(float x) { 5170 return clamp(x, 0.0, 1.0); 5171} 5172#include "decodePS" 5173#include "encodePS" 5174vec3 modifySeams(vec3 dir, float scale) { 5175 vec3 adir = abs(dir); 5176 float M = max(max(adir.x, adir.y), adir.z); 5177 return dir / M * vec3( 5178 adir.x == M ? 1.0 : scale, 5179 adir.y == M ? 1.0 : scale, 5180 adir.z == M ? 1.0 : scale 5181 ); 5182} 5183vec2 toSpherical(vec3 dir) { 5184 return vec2(dir.xz == vec2(0.0) ? 0.0 : atan(dir.x, dir.z), asin(dir.y)); 5185} 5186vec3 fromSpherical(vec2 uv) { 5187 return vec3(cos(uv.y) * sin(uv.x), 5188 sin(uv.y), 5189 cos(uv.y) * cos(uv.x)); 5190} 5191vec3 getDirectionEquirect() { 5192 return fromSpherical((vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0) * vec2(PI, PI * 0.5)); 5193} 5194float signNotZero(float k){ 5195 return(k >= 0.0) ? 1.0 : -1.0; 5196} 5197vec2 signNotZero(vec2 v) { 5198 return vec2(signNotZero(v.x), signNotZero(v.y)); 5199} 5200vec3 octDecode(vec2 o) { 5201 vec3 v = vec3(o.x, 1.0 - abs(o.x) - abs(o.y), o.y); 5202 if (v.y < 0.0) { 5203 v.xz = (1.0 - abs(v.zx)) * signNotZero(v.xz); 5204 } 5205 return normalize(v); 5206} 5207vec3 getDirectionOctahedral() { 5208 return octDecode(vec2(vUv0.x, 1.0 - vUv0.y) * 2.0 - 1.0); 5209} 5210vec2 octEncode(in vec3 v) { 5211 float l1norm = abs(v.x) + abs(v.y) + abs(v.z); 5212 vec2 result = v.xz * (1.0 / l1norm); 5213 if (v.y < 0.0) { 5214 result = (1.0 - abs(result.yx)) * signNotZero(result.xy); 5215 } 5216 return result; 5217} 5218#ifdef CUBEMAP_SOURCE 5219 vec4 sampleCubemap(vec3 dir) { 5220 return textureCube(sourceCube, modifySeams(dir, 1.0)); 5221 } 5222 vec4 sampleCubemap(vec2 sph) { 5223 return sampleCubemap(fromSpherical(sph)); 5224 } 5225 vec4 sampleCubemap(vec3 dir, float mipLevel) { 5226 return textureCubeLod(sourceCube, modifySeams(dir, 1.0), mipLevel); 5227 } 5228 vec4 sampleCubemap(vec2 sph, float mipLevel) { 5229 return sampleCubemap(fromSpherical(sph), mipLevel); 5230 } 5231#else 5232 vec4 sampleEquirect(vec2 sph) { 5233 vec2 uv = sph / vec2(PI * 2.0, PI) + 0.5; 5234 return texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y)); 5235 } 5236 vec4 sampleEquirect(vec3 dir) { 5237 return sampleEquirect(toSpherical(dir)); 5238 } 5239 vec4 sampleEquirect(vec2 sph, float mipLevel) { 5240 vec2 uv = sph / vec2(PI * 2.0, PI) + 0.5; 5241 return texture2DLod(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel); 5242 } 5243 vec4 sampleEquirect(vec3 dir, float mipLevel) { 5244 return sampleEquirect(toSpherical(dir), mipLevel); 5245 } 5246 vec4 sampleOctahedral(vec3 dir) { 5247 vec2 uv = octEncode(dir) * 0.5 + 0.5; 5248 return texture2D(sourceTex, vec2(uv.x, 1.0 - uv.y)); 5249 } 5250 vec4 sampleOctahedral(vec2 sph) { 5251 return sampleOctahedral(fromSpherical(sph)); 5252 } 5253 vec4 sampleOctahedral(vec3 dir, float mipLevel) { 5254 vec2 uv = octEncode(dir) * 0.5 + 0.5; 5255 return texture2DLod(sourceTex, vec2(uv.x, 1.0 - uv.y), mipLevel); 5256 } 5257 vec4 sampleOctahedral(vec2 sph, float mipLevel) { 5258 return sampleOctahedral(fromSpherical(sph), mipLevel); 5259 } 5260#endif 5261vec3 getDirectionCubemap() { 5262 vec2 st = vUv0 * 2.0 - 1.0; 5263 float face = targetFace(); 5264 vec3 vec; 5265 if (face == 0.0) { 5266 vec = vec3(1, -st.y, -st.x); 5267 } else if (face == 1.0) { 5268 vec = vec3(-1, -st.y, st.x); 5269 } else if (face == 2.0) { 5270 vec = vec3(st.x, 1, st.y); 5271 } else if (face == 3.0) { 5272 vec = vec3(st.x, -1, -st.y); 5273 } else if (face == 4.0) { 5274 vec = vec3(st.x, -st.y, 1); 5275 } else { 5276 vec = vec3(-st.x, -st.y, -1); 5277 } 5278 return normalize(modifySeams(vec, 1.0)); 5279} 5280mat3 matrixFromVector(vec3 n) { 5281 float a = 1.0 / (1.0 + n.z); 5282 float b = -n.x * n.y * a; 5283 vec3 b1 = vec3(1.0 - n.x * n.x * a, b, -n.x); 5284 vec3 b2 = vec3(b, 1.0 - n.y * n.y * a, -n.y); 5285 return mat3(b1, b2, n); 5286} 5287mat3 matrixFromVectorSlow(vec3 n) { 5288 vec3 up = (1.0 - abs(n.y) <= 0.0000001) ? vec3(0.0, 0.0, n.y > 0.0 ? 1.0 : -1.0) : vec3(0.0, 1.0, 0.0); 5289 vec3 x = normalize(cross(up, n)); 5290 vec3 y = cross(n, x); 5291 return mat3(x, y, n); 5292} 5293vec4 reproject() { 5294 if ({NUM_SAMPLES} <= 1) { 5295 return {ENCODE_FUNC}({DECODE_FUNC}({SOURCE_FUNC}({TARGET_FUNC}()))); 5296 } else { 5297 vec3 t = {TARGET_FUNC}(); 5298 vec3 tu = dFdx(t); 5299 vec3 tv = dFdy(t); 5300 vec3 result = vec3(0.0); 5301 for (float u = 0.0; u < {NUM_SAMPLES_SQRT}; ++u) { 5302 for (float v = 0.0; v < {NUM_SAMPLES_SQRT}; ++v) { 5303 result += {DECODE_FUNC}({SOURCE_FUNC}(normalize(t + 5304 tu * (u / {NUM_SAMPLES_SQRT} - 0.5) + 5305 tv * (v / {NUM_SAMPLES_SQRT} - 0.5)))); 5306 } 5307 } 5308 return {ENCODE_FUNC}(result / ({NUM_SAMPLES_SQRT} * {NUM_SAMPLES_SQRT})); 5309 } 5310} 5311vec4 unpackFloat = vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0); 5312#ifdef USE_SAMPLES_TEX 5313 void unpackSample(int i, out vec3 L, out float mipLevel) { 5314 float u = (float(i * 4) + 0.5) * samplesTexInverseSize.x; 5315 float v = (floor(u) + 0.5) * samplesTexInverseSize.y; 5316 vec4 raw; 5317 raw.x = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x;
5318 raw.y = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x; 5319 raw.z = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); u += samplesTexInverseSize.x; 5320 raw.w = dot(texture2D(samplesTex, vec2(u, v)), unpackFloat); 5321 L.xyz = raw.xyz * 2.0 - 1.0; 5322 mipLevel = raw.w * 8.0; 5323 } 5324 vec4 prefilterSamples() { 5325 mat3 vecSpace = matrixFromVectorSlow({TARGET_FUNC}()); 5326 vec3 L; 5327 float mipLevel; 5328 vec3 result = vec3(0.0); 5329 float totalWeight = 0.0; 5330 for (int i = 0; i < {NUM_SAMPLES}; ++i) { 5331 unpackSample(i, L, mipLevel); 5332 result += {DECODE_FUNC}({SOURCE_FUNC}(vecSpace * L, mipLevel)) * L.z; 5333 totalWeight += L.z; 5334 } 5335 return {ENCODE_FUNC}(result / totalWeight); 5336 } 5337 vec4 prefilterSamplesUnweighted() { 5338 mat3 vecSpace = matrixFromVectorSlow({TARGET_FUNC}()); 5339 vec3 L; 5340 float mipLevel; 5341 vec3 result = vec3(0.0); 5342 float totalWeight = 0.0; 5343 for (int i = 0; i < {NUM_SAMPLES}; ++i) { 5344 unpackSample(i, L, mipLevel); 5345 result += {DECODE_FUNC}({SOURCE_FUNC}(vecSpace * L, mipLevel)); 5346 } 5347 return {ENCODE_FUNC}(result / float({NUM_SAMPLES})); 5348 } 5349#endif 5350void main(void) { 5351 gl_FragColor = {PROCESS_FUNC}(); 5352} 5353`,$L=` 5354attribute vec2 vertex_position; 5355uniform vec4 uvMod; 5356varying vec2 vUv0; 5357void main(void) { 5358 gl_Position = vec4(vertex_position, 0.5, 1.0); 5359 vUv0 = getImageEffectUV((vertex_position.xy * 0.5 + 0.5) * uvMod.xy + uvMod.zw); 5360} 5361`,KL=` 5362uniform highp sampler2D uSceneDepthMap; 5363#ifndef SCREENSIZE 5364 #define SCREENSIZE 5365 uniform vec4 uScreenSize; 5366#endif 5367#ifndef VIEWMATRIX 5368 #define VIEWMATRIX 5369 uniform mat4 matrix_view; 5370#endif 5371#ifndef LINEARIZE_DEPTH 5372 #define LINEARIZE_DEPTH 5373 5374 #ifndef CAMERAPLANES 5375 #define CAMERAPLANES 5376 uniform vec4 camera_params; 5377 #endif 5378 float linearizeDepth(float z) { 5379 if (camera_params.w == 0.0) 5380 return (camera_params.z * camera_params.y) / (camera_params.y + z * (camera_params.z - camera_params.y)); 5381 else 5382 return camera_params.z + z * (camera_params.y - camera_params.z); 5383 } 5384#endif 5385float delinearizeDepth(float linearDepth) { 5386 if (camera_params.w == 0.0) { 5387 return (camera_params.y * (camera_params.z - linearDepth)) / (linearDepth * (camera_params.z - camera_params.y)); 5388 } else { 5389 return (linearDepth - camera_params.z) / (camera_params.y - camera_params.z); 5390 } 5391} 5392float getLinearScreenDepth(vec2 uv) { 5393 #ifdef SCENE_DEPTHMAP_LINEAR 5394 #ifdef SCENE_DEPTHMAP_FLOAT 5395 return texture2D(uSceneDepthMap, uv).r; 5396 #else 5397 ivec2 textureSize = textureSize(uSceneDepthMap, 0); 5398 ivec2 texel = ivec2(uv * vec2(textureSize)); 5399 vec4 data = texelFetch(uSceneDepthMap, texel, 0); 5400 uint intBits = 5401 (uint(data.r * 255.0) << 24u) | 5402 (uint(data.g * 255.0) << 16u) | 5403 (uint(data.b * 255.0) << 8u) | 5404 uint(data.a * 255.0); 5405 return uintBitsToFloat(intBits); 5406 #endif 5407 #else 5408 return linearizeDepth(texture2D(uSceneDepthMap, uv).r); 5409 #endif 5410} 5411#ifndef VERTEXSHADER 5412 float getLinearScreenDepth() { 5413 vec2 uv = gl_FragCoord.xy * uScreenSize.zw; 5414 return getLinearScreenDepth(uv); 5415 } 5416#endif 5417float getLinearDepth(vec3 pos) { 5418 return -(matrix_view * vec4(pos, 1.0)).z; 5419} 5420`,ZL=` 5421int getShadowCascadeIndex(vec4 shadowCascadeDistances, int shadowCascadeCount) { 5422 float depth = 1.0 / gl_FragCoord.w; 5423 vec4 comparisons = step(shadowCascadeDistances, vec4(depth)); 5424 int cascadeIndex = int(dot(comparisons, vec4(1.0))); 5425 return min(cascadeIndex, shadowCascadeCount - 1); 5426} 5427int ditherShadowCascadeIndex(int cascadeIndex, vec4 shadowCascadeDistances, int shadowCascadeCount, float blendFactor) { 5428 5429 if (cascadeIndex < shadowCascadeCount - 1) { 5430 float currentRangeEnd = shadowCascadeDistances[cascadeIndex]; 5431 float transitionStart = blendFactor * currentRangeEnd; 5432 float depth = 1.0 / gl_FragCoord.w; 5433 if (depth > transitionStart) { 5434 float transitionFactor = smoothstep(transitionStart, currentRangeEnd, depth); 5435 float dither = fract(sin(dot(gl_FragCoord.xy, vec2(12.9898, 78.233))) * 43758.5453); 5436 if (dither < transitionFactor) { 5437 cascadeIndex += 1; 5438 } 5439 } 5440 } 5441 return cascadeIndex; 5442} 5443vec3 fadeShadow(vec3 shadowCoord, vec4 shadowCascadeDistances) { 5444 float depth = 1.0 / gl_FragCoord.w; 5445 if (depth > shadowCascadeDistances.w) { 5446 shadowCoord.z = -9999999.0; 5447 } 5448 return shadowCoord; 5449} 5450`,QL=` 5451float linstep(float a, float b, float v) { 5452 return saturate((v - a) / (b - a)); 5453} 5454float reduceLightBleeding(float pMax, float amount) { 5455 return linstep(amount, 1.0, pMax); 5456} 5457float chebyshevUpperBound(vec2 moments, float mean, float minVariance, float lightBleedingReduction) { 5458 float variance = moments.y - (moments.x * moments.x); 5459 variance = max(variance, minVariance); 5460 float d = mean - moments.x; 5461 float pMax = variance / (variance + (d * d)); 5462 pMax = reduceLightBleeding(pMax, lightBleedingReduction); 5463 return (mean <= moments.x ? 1.0 : pMax); 5464} 5465float calculateEVSM(vec3 moments, float Z, float vsmBias, float exponent) { 5466 Z = 2.0 * Z - 1.0; 5467 float warpedDepth = exp(exponent * Z); 5468 moments.xy += vec2(warpedDepth, warpedDepth*warpedDepth) * (1.0 - moments.z); 5469 float VSMBias = vsmBias; 5470 float depthScale = VSMBias * exponent * warpedDepth; 5471 float minVariance1 = depthScale * depthScale; 5472 return chebyshevUpperBound(moments.xy, warpedDepth, minVariance1, 0.1); 5473} 5474float VSM16(TEXTURE_ACCEPT(tex), vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) {
5475 vec3 moments = texture2DLod(tex, texCoords, 0.0).xyz; 5476 return calculateEVSM(moments, Z, vsmBias, exponent); 5477} 5478float getShadowVSM16(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent) { 5479 return VSM16(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent); 5480} 5481float getShadowSpotVSM16(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) { 5482 return VSM16(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, length(lightDir) * shadowParams.w + shadowParams.z, shadowParams.y, exponent); 5483} 5484float VSM32(TEXTURE_ACCEPT(tex), vec2 texCoords, float resolution, float Z, float vsmBias, float exponent) { 5485 #ifdef CAPS_TEXTURE_FLOAT_FILTERABLE 5486 vec3 moments = texture2DLod(tex, texCoords, 0.0).xyz; 5487 #else 5488 float pixelSize = 1.0 / resolution; 5489 texCoords -= vec2(pixelSize); 5490 vec3 s00 = texture2DLod(tex, texCoords, 0.0).xyz; 5491 vec3 s10 = texture2DLod(tex, texCoords + vec2(pixelSize, 0), 0.0).xyz; 5492 vec3 s01 = texture2DLod(tex, texCoords + vec2(0, pixelSize), 0.0).xyz; 5493 vec3 s11 = texture2DLod(tex, texCoords + vec2(pixelSize), 0.0).xyz; 5494 vec2 fr = fract(texCoords * resolution); 5495 vec3 h0 = mix(s00, s10, fr.x); 5496 vec3 h1 = mix(s01, s11, fr.x); 5497 vec3 moments = mix(h0, h1, fr.y); 5498 #endif 5499 return calculateEVSM(moments, Z, vsmBias, exponent); 5500} 5501float getShadowVSM32(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent) { 5502 return VSM32(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent); 5503} 5504float getShadowSpotVSM32(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, float exponent, vec3 lightDir) { 5505 float Z = length(lightDir) * shadowParams.w + shadowParams.z; 5506 return VSM32(TEXTURE_PASS(shadowMap), shadowCoord.xy, shadowParams.x, Z, shadowParams.y, exponent); 5507} 5508`,JL=` 5509float getShadowPCF1x1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) { 5510 return textureShadow(shadowMap, shadowCoord); 5511} 5512float getShadowSpotPCF1x1(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) { 5513 return textureShadow(shadowMap, shadowCoord); 5514} 5515#ifndef WEBGPU 5516float getShadowOmniPCF1x1(samplerCubeShadow shadowMap, vec3 shadowCoord, vec4 shadowParams, vec3 lightDir) { 5517 float shadowZ = length(lightDir) * shadowParams.w + shadowParams.z; 5518 return texture(shadowMap, vec4(lightDir, shadowZ)); 5519} 5520#endif 5521`,e3=` 5522float _getShadowPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec3 shadowParams) { 5523 float z = shadowCoord.z; 5524 vec2 uv = shadowCoord.xy * shadowParams.x; 5525 float shadowMapSizeInv = 1.0 / shadowParams.x; 5526 vec2 base_uv = floor(uv + 0.5); 5527 float s = (uv.x + 0.5 - base_uv.x); 5528 float t = (uv.y + 0.5 - base_uv.y); 5529 base_uv -= vec2(0.5); 5530 base_uv *= shadowMapSizeInv; 5531 float sum = 0.0; 5532 float uw0 = (3.0 - 2.0 * s); 5533 float uw1 = (1.0 + 2.0 * s); 5534 float u0 = (2.0 - s) / uw0 - 1.0; 5535 float u1 = s / uw1 + 1.0; 5536 float vw0 = (3.0 - 2.0 * t); 5537 float vw1 = (1.0 + 2.0 * t); 5538 float v0 = (2.0 - t) / vw0 - 1.0; 5539 float v1 = t / vw1 + 1.0; 5540 u0 = u0 * shadowMapSizeInv + base_uv.x; 5541 v0 = v0 * shadowMapSizeInv + base_uv.y; 5542 u1 = u1 * shadowMapSizeInv + base_uv.x; 5543 v1 = v1 * shadowMapSizeInv + base_uv.y; 5544 sum += uw0 * vw0 * textureShadow(shadowMap, vec3(u0, v0, z)); 5545 sum += uw1 * vw0 * textureShadow(shadowMap, vec3(u1, v0, z)); 5546 sum += uw0 * vw1 * textureShadow(shadowMap, vec3(u0, v1, z)); 5547 sum += uw1 * vw1 * textureShadow(shadowMap, vec3(u1, v1, z)); 5548 sum *= 1.0f / 16.0; 5549 return sum; 5550} 5551float getShadowPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) { 5552 return _getShadowPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz); 5553} 5554float getShadowSpotPCF3x3(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) { 5555 return _getShadowPCF3x3(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz); 5556} 5557#ifndef WEBGPU 5558float getShadowOmniPCF3x3(samplerCubeShadow shadowMap, vec4 shadowParams, vec3 dir) { 5559 5560 float shadowZ = length(dir) * shadowParams.w + shadowParams.z; 5561 float z = 1.0 / float(textureSize(shadowMap, 0)); 5562 vec3 tc = normalize(dir); 5563 mediump vec4 shadows; 5564 shadows.x = texture(shadowMap, vec4(tc + vec3( z, z, z), shadowZ)); 5565 shadows.y = texture(shadowMap, vec4(tc + vec3(-z,-z, z), shadowZ)); 5566 shadows.z = texture(shadowMap, vec4(tc + vec3(-z, z,-z), shadowZ)); 5567 shadows.w = texture(shadowMap, vec4(tc + vec3( z,-z,-z), shadowZ)); 5568 return dot(shadows, vec4(0.25)); 5569} 5570float getShadowOmniPCF3x3(samplerCubeShadow shadowMap, vec3 shadowCoord, vec4 shadowParams, vec3 lightDir) { 5571 return getShadowOmniPCF3x3(shadowMap, shadowParams, lightDir); 5572} 5573#endif 5574`,t3=` 5575float _getShadowPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec3 shadowParams) { 5576 float z = shadowCoord.z; 5577 vec2 uv = shadowCoord.xy * shadowParams.x; 5578 float shadowMapSizeInv = 1.0 / shadowParams.x; 5579 vec2 base_uv = floor(uv + 0.5); 5580 float s = (uv.x + 0.5 - base_uv.x); 5581 float t = (uv.y + 0.5 - base_uv.y); 5582 base_uv -= vec2(0.5); 5583 base_uv *= shadowMapSizeInv; 5584 float uw0 = (4.0 - 3.0 * s); 5585 float uw1 = 7.0; 5586 float uw2 = (1.0 + 3.0 * s); 5587 float u0 = (3.0 - 2.0 * s) / uw0 - 2.0; 5588 float u1 = (3.0 + s) / uw1; 5589 float u2 = s / uw2 + 2.0; 5590 float vw0 = (4.0 - 3.0 * t); 5591 float vw1 = 7.0; 5592 float vw2 = (1.0 + 3.0 * t); 5593 float v0 = (3.0 - 2.0 * t) / vw0 - 2.0; 5594 float v1 = (3.0 + t) / vw1; 5595 float v2 = t / vw2 + 2.0; 5596 float sum = 0.0; 5597 u0 = u0 * shadowMapSizeInv + base_uv.x; 5598 v0 = v0 * shadowMapSizeInv + base_uv.y; 5599 u1 = u1 * shadowMapSizeInv + base_uv.x; 5600 v1 = v1 * shadowMapSizeInv + base_uv.y; 5601 u2 = u2 * shadowMapSizeInv + base_uv.x; 5602 v2 = v2 * shadowMapSizeInv + base_uv.y; 5603 sum += uw0 * vw0 * textureShadow(shadowMap, vec3(u0, v0, z)); 5604 sum += uw1 * vw0 * textureShadow(shadowMap, vec3(u1, v0, z)); 5605 sum += uw2 * vw0 * textureShadow(shadowMap, vec3(u2, v0, z)); 5606 sum += uw0 * vw1 * textureShadow(shadowMap, vec3(u0, v1, z)); 5607 sum += uw1 * vw1 * textureShadow(shadowMap, vec3(u1, v1, z)); 5608 sum += uw2 * vw1 * textureShadow(shadowMap, vec3(u2, v1, z)); 5609 sum += uw0 * vw2 * textureShadow(shadowMap, vec3(u0, v2, z)); 5610 sum += uw1 * vw2 * textureShadow(shadowMap, vec3(u1, v2, z)); 5611 sum += uw2 * vw2 * textureShadow(shadowMap, vec3(u2, v2, z)); 5612 sum *= 1.0f / 144.0; 5613 sum = saturate(sum); 5614 return sum; 5615} 5616float getShadowPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) { 5617 return _getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz); 5618} 5619float getShadowSpotPCF5x5(SHADOWMAP_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams) { 5620 return _getShadowPCF5x5(SHADOWMAP_PASS(shadowMap), shadowCoord, shadowParams.xyz); 5621} 5622`,s3=` 5623#define PCSS_SAMPLE_COUNT 16 5624uniform float pcssDiskSamples[PCSS_SAMPLE_COUNT]; 5625uniform float pcssSphereSamples[PCSS_SAMPLE_COUNT]; 5626vec2 vogelDisk(int sampleIndex, float count, float phi, float r) { 5627 const float GoldenAngle = 2.4; 5628 float theta = float(sampleIndex) * GoldenAngle + phi; 5629 float sine = sin(theta); 5630 float cosine = cos(theta); 5631 return vec2(r * cosine, r * sine); 5632} 5633vec3 vogelSphere(int sampleIndex, float count, float phi, float r) { 5634 const float GoldenAngle = 2.4; 5635 float theta = float(sampleIndex) * GoldenAngle + phi; 5636 float weight = float(sampleIndex) / count; 5637 return vec3(cos(theta) * r, weight, sin(theta) * r); 5638} 5639float noise(vec2 screenPos) { 5640 const float PHI = 1.61803398874989484820459; 5641 return fract(sin(dot(screenPos * PHI, screenPos)) * screenPos.x); 5642} 5643float viewSpaceDepth(float depth, mat4 invProjection) { 5644 float z = depth * 2.0 - 1.0; 5645 vec4 clipSpace = vec4(0.0, 0.0, z, 1.0); 5646 vec4 viewSpace = invProjection * clipSpace; 5647 return viewSpace.z; 5648} 5649float PCSSBlockerDistance(TEXTURE_ACCEPT(shadowMap), vec2 sampleCoords[PCSS_SAMPLE_COUNT], vec2 shadowCoords, vec2 searchSize, float z, vec4 cameraParams) { 5650 float blockers = 0.0; 5651 float averageBlocker = 0.0; 5652 for (int i = 0; i < PCSS_SAMPLE_COUNT; i++) {
5653 vec2 offset = sampleCoords[i] * searchSize; 5654 vec2 sampleUV = shadowCoords + offset; 5655 float blocker = texture2DLod(shadowMap, sampleUV, 0.0).r; 5656 float isBlocking = step(blocker, z); 5657 blockers += isBlocking; 5658 averageBlocker += blocker * isBlocking; 5659 } 5660 if (blockers > 0.0) 5661 return averageBlocker / blockers; 5662 return -1.0; 5663} 5664float PCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoords, vec4 cameraParams, vec2 shadowSearchArea) { 5665 float receiverDepth = linearizeDepthWithParams(shadowCoords.z, cameraParams); 5666 vec2 samplePoints[PCSS_SAMPLE_COUNT]; 5667 const float PI = 3.141592653589793; 5668 float noise = noise( gl_FragCoord.xy ) * 2.0 * PI; 5669 for (int i = 0; i < PCSS_SAMPLE_COUNT; i++) { 5670 float pcssPresample = pcssDiskSamples[i]; 5671 samplePoints[i] = vogelDisk(i, float(PCSS_SAMPLE_COUNT), noise, pcssPresample); 5672 } 5673 float averageBlocker = PCSSBlockerDistance(TEXTURE_PASS(shadowMap), samplePoints, shadowCoords.xy, shadowSearchArea, receiverDepth, cameraParams); 5674 if (averageBlocker == -1.0) { 5675 return 1.0; 5676 } else { 5677 float depthDifference = (receiverDepth - averageBlocker) / 3.0; 5678 vec2 filterRadius = depthDifference * shadowSearchArea; 5679 float shadow = 0.0; 5680 for (int i = 0; i < PCSS_SAMPLE_COUNT; i ++) 5681 { 5682 vec2 sampleUV = samplePoints[i] * filterRadius; 5683 sampleUV = shadowCoords.xy + sampleUV; 5684 float depth = texture2DLod(shadowMap, sampleUV, 0.0).r; 5685 shadow += step(receiverDepth, depth); 5686 } 5687 return shadow / float(PCSS_SAMPLE_COUNT); 5688 } 5689} 5690#ifndef WEBGPU 5691float PCSSCubeBlockerDistance(samplerCube shadowMap, vec3 lightDirNorm, vec3 samplePoints[PCSS_SAMPLE_COUNT], float z, float shadowSearchArea) { 5692 float blockers = 0.0; 5693 float averageBlocker = 0.0; 5694 for (int i = 0; i < PCSS_SAMPLE_COUNT; i++) { 5695 vec3 sampleDir = lightDirNorm + samplePoints[i] * shadowSearchArea; 5696 sampleDir = normalize(sampleDir); 5697 float blocker = textureCubeLod(shadowMap, sampleDir, 0.0).r; 5698 float isBlocking = step(blocker, z); 5699 blockers += isBlocking; 5700 averageBlocker += blocker * isBlocking; 5701 } 5702 if (blockers > 0.0) 5703 return averageBlocker / blockers; 5704 return -1.0; 5705} 5706float PCSSCube(samplerCube shadowMap, vec4 shadowParams, vec3 shadowCoords, vec4 cameraParams, float shadowSearchArea, vec3 lightDir) { 5707 5708 vec3 samplePoints[PCSS_SAMPLE_COUNT]; 5709 const float PI = 3.141592653589793; 5710 float noise = noise( gl_FragCoord.xy ) * 2.0 * PI; 5711 for (int i = 0; i < PCSS_SAMPLE_COUNT; i++) { 5712 float r = pcssSphereSamples[i]; 5713 samplePoints[i] = vogelSphere(i, float(PCSS_SAMPLE_COUNT), noise, r); 5714 } 5715 float receiverDepth = length(lightDir) * shadowParams.w + shadowParams.z; 5716 vec3 lightDirNorm = normalize(lightDir); 5717 5718 float averageBlocker = PCSSCubeBlockerDistance(shadowMap, lightDirNorm, samplePoints, receiverDepth, shadowSearchArea); 5719 if (averageBlocker == -1.0) { 5720 return 1.0; 5721 } else { 5722 float filterRadius = ((receiverDepth - averageBlocker) / averageBlocker) * shadowSearchArea; 5723 float shadow = 0.0; 5724 for (int i = 0; i < PCSS_SAMPLE_COUNT; i++) 5725 { 5726 vec3 offset = samplePoints[i] * filterRadius; 5727 vec3 sampleDir = lightDirNorm + offset; 5728 sampleDir = normalize(sampleDir); 5729 float depth = textureCubeLod(shadowMap, sampleDir, 0.0).r; 5730 shadow += step(receiverDepth, depth); 5731 } 5732 return shadow / float(PCSS_SAMPLE_COUNT); 5733 } 5734} 5735float getShadowOmniPCSS(samplerCube shadowMap, vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec2 shadowSearchArea, vec3 lightDir) { 5736 return PCSSCube(shadowMap, shadowParams, shadowCoord, cameraParams, shadowSearchArea.x, lightDir); 5737} 5738#endif 5739float getShadowSpotPCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec2 shadowSearchArea, vec3 lightDir) { 5740 return PCSS(TEXTURE_PASS(shadowMap), shadowCoord, cameraParams, shadowSearchArea); 5741} 5742`,i3=` 5743highp float fractSinRand(const in vec2 uv) { 5744 const float PI = 3.141592653589793; 5745 const highp float a = 12.9898, b = 78.233, c = 43758.5453; 5746 highp float dt = dot(uv.xy, vec2(a, b)), sn = mod(dt, PI); 5747 return fract(sin(sn) * c); 5748} 5749struct VogelDiskData { 5750 float invNumSamples; 5751 float initialAngle; 5752 float currentPointId; 5753}; 5754void prepareDiskConstants(out VogelDiskData data, int sampleCount, float randomSeed) { 5755 const float pi2 = 6.28318530718; 5756 data.invNumSamples = 1.0 / float(sampleCount); 5757 data.initialAngle = randomSeed * pi2; 5758 data.currentPointId = 0.0; 5759} 5760vec2 generateDiskSample(inout VogelDiskData data) { 5761 const float GOLDEN_ANGLE = 2.399963; 5762 float r = sqrt((data.currentPointId + 0.5) * data.invNumSamples); 5763 float theta = data.currentPointId * GOLDEN_ANGLE + data.initialAngle; 5764 vec2 offset = vec2(cos(theta), sin(theta)) * pow(r, 1.33); 5765 data.currentPointId += 1.0; 5766 return offset; 5767} 5768void PCSSFindBlocker(TEXTURE_ACCEPT(shadowMap), out float avgBlockerDepth, out int numBlockers, 5769 vec2 shadowCoords, float z, int shadowBlockerSamples, float penumbraSize, float invShadowMapSize, float randomSeed) { 5770 VogelDiskData diskData; 5771 prepareDiskConstants(diskData, shadowBlockerSamples, randomSeed); 5772 float searchWidth = penumbraSize * invShadowMapSize; 5773 float blockerSum = 0.0; 5774 numBlockers = 0; 5775 for( int i = 0; i < shadowBlockerSamples; ++i ) { 5776 vec2 diskUV = generateDiskSample(diskData); 5777 vec2 sampleUV = shadowCoords + diskUV * searchWidth;
5778 float shadowMapDepth = texture2DLod(shadowMap, sampleUV, 0.0).r; 5779 if ( shadowMapDepth < z ) { 5780 blockerSum += shadowMapDepth; 5781 numBlockers++; 5782 } 5783 } 5784 avgBlockerDepth = blockerSum / float(numBlockers); 5785} 5786float PCSSFilter(TEXTURE_ACCEPT(shadowMap), vec2 uv, float receiverDepth, int shadowSamples, float filterRadius, float randomSeed) { 5787 VogelDiskData diskData; 5788 prepareDiskConstants(diskData, shadowSamples, randomSeed); 5789 float sum = 0.0; 5790 for (int i = 0; i < shadowSamples; i++) { 5791 vec2 offsetUV = generateDiskSample(diskData) * filterRadius; 5792 float depth = texture2DLod(shadowMap, uv + offsetUV, 0.0).r; 5793 sum += step(receiverDepth, depth); 5794 } 5795 return sum / float(shadowSamples); 5796} 5797float getPenumbra(float dblocker, float dreceiver, float penumbraSize, float penumbraFalloff) { 5798 float dist = dreceiver - dblocker; 5799 float penumbra = 1.0 - pow(1.0 - dist, penumbraFalloff); 5800 return penumbra * penumbraSize; 5801} 5802float PCSSDirectional(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoords, vec4 cameraParams, vec4 softShadowParams) { 5803 float receiverDepth = shadowCoords.z; 5804 float randomSeed = fractSinRand(gl_FragCoord.xy); 5805 int shadowSamples = int(softShadowParams.x); 5806 int shadowBlockerSamples = int(softShadowParams.y); 5807 float penumbraSize = softShadowParams.z; 5808 float penumbraFalloff = softShadowParams.w; 5809 int shadowMapSize = textureSize(shadowMap, 0).x; 5810 float invShadowMapSize = 1.0 / float(shadowMapSize); 5811 invShadowMapSize *= float(shadowMapSize) / 2048.0; 5812 float penumbra; 5813 if (shadowBlockerSamples > 0) { 5814 float avgBlockerDepth = 0.0; 5815 int numBlockers = 0; 5816 PCSSFindBlocker(TEXTURE_PASS(shadowMap), avgBlockerDepth, numBlockers, shadowCoords.xy, receiverDepth, shadowBlockerSamples, penumbraSize, invShadowMapSize, randomSeed); 5817 if (numBlockers < 1) 5818 return 1.0f; 5819 penumbra = getPenumbra(avgBlockerDepth, shadowCoords.z, penumbraSize, penumbraFalloff); 5820 } else { 5821 penumbra = penumbraSize; 5822 } 5823 float filterRadius = penumbra * invShadowMapSize; 5824 return PCSSFilter(TEXTURE_PASS(shadowMap), shadowCoords.xy, receiverDepth, shadowSamples, filterRadius, randomSeed); 5825} 5826float getShadowPCSS(TEXTURE_ACCEPT(shadowMap), vec3 shadowCoord, vec4 shadowParams, vec4 cameraParams, vec4 softShadowParams, vec3 lightDir) { 5827 return PCSSDirectional(TEXTURE_PASS(shadowMap), shadowCoord, cameraParams, softShadowParams); 5828} 5829`,r3=` 5830attribute float vertex_boneIndices; 5831uniform highp sampler2D texture_poseMap; 5832mat4 getBoneMatrix(const in float indexFloat) { 5833 int width = textureSize(texture_poseMap, 0).x; 5834 int index = int(indexFloat + 0.5) * 3; 5835 int iy = index / width; 5836 int ix = index % width; 5837 vec4 v1 = texelFetch(texture_poseMap, ivec2(ix + 0, iy), 0); 5838 vec4 v2 = texelFetch(texture_poseMap, ivec2(ix + 1, iy), 0); 5839 vec4 v3 = texelFetch(texture_poseMap, ivec2(ix + 2, iy), 0); 5840 return mat4( 5841 v1.x, v2.x, v3.x, 0, 5842 v1.y, v2.y, v3.y, 0, 5843 v1.z, v2.z, v3.z, 0, 5844 v1.w, v2.w, v3.w, 1 5845 ); 5846} 5847`,a3=` 5848attribute vec4 vertex_boneWeights; 5849attribute vec4 vertex_boneIndices; 5850uniform highp sampler2D texture_poseMap; 5851void getBoneMatrix(const in int width, const in int index, out vec4 v1, out vec4 v2, out vec4 v3) { 5852 int v = index / width; 5853 int u = index % width; 5854 v1 = texelFetch(texture_poseMap, ivec2(u + 0, v), 0); 5855 v2 = texelFetch(texture_poseMap, ivec2(u + 1, v), 0); 5856 v3 = texelFetch(texture_poseMap, ivec2(u + 2, v), 0); 5857} 5858mat4 getSkinMatrix(const in vec4 indicesFloat, const in vec4 weights) { 5859 int width = textureSize(texture_poseMap, 0).x; 5860 ivec4 indices = ivec4(indicesFloat + 0.5) * 3; 5861 vec4 a1, a2, a3; 5862 getBoneMatrix(width, indices.x, a1, a2, a3); 5863 vec4 b1, b2, b3; 5864 getBoneMatrix(width, indices.y, b1, b2, b3); 5865 vec4 c1, c2, c3; 5866 getBoneMatrix(width, indices.z, c1, c2, c3); 5867 vec4 d1, d2, d3; 5868 getBoneMatrix(width, indices.w, d1, d2, d3); 5869 vec4 v1 = a1 * weights.x + b1 * weights.y + c1 * weights.z + d1 * weights.w; 5870 vec4 v2 = a2 * weights.x + b2 * weights.y + c2 * weights.z + d2 * weights.w; 5871 vec4 v3 = a3 * weights.x + b3 * weights.y + c3 * weights.z + d3 * weights.w; 5872 float one = dot(weights, vec4(1.0)); 5873 return mat4( 5874 v1.x, v2.x, v3.x, 0, 5875 v1.y, v2.y, v3.y, 0, 5876 v1.z, v2.z, v3.z, 0, 5877 v1.w, v2.w, v3.w, one 5878 ); 5879} 5880`,n3=` 5881 #define LIT_SKYBOX_INTENSITY 5882 #include "envProcPS" 5883 #include "gammaPS" 5884 #include "tonemappingPS" 5885 #ifdef PREPASS_PASS 5886 varying float vLinearDepth; 5887 #include "floatAsUintPS" 5888 #endif 5889 varying vec3 vViewDir; 5890 uniform float skyboxHighlightMultiplier;
5891 #if defined(SKY_FISHEYE) && !defined(SKYMESH) 5892 uniform float fisheye_k; 5893 uniform float fisheye_invK; 5894 uniform float fisheye_projMat00; 5895 uniform float fisheye_projMat11; 5896 uniform mat4 matrix_view; 5897 uniform mat3 cubeMapRotationMatrix; 5898 varying vec3 vClipXYW; 5899 #endif 5900 #ifdef SKY_CUBEMAP 5901 uniform samplerCube texture_cubeMap; 5902 #ifdef SKYMESH 5903 varying vec3 vWorldPos; 5904 uniform mat3 cubeMapRotationMatrix; 5905 uniform vec3 projectedSkydomeCenter; 5906 #endif 5907 #else 5908 #include "sphericalPS" 5909 #include "envAtlasPS" 5910 uniform sampler2D texture_envAtlas; 5911 uniform float mipLevel; 5912 #endif 5913 void main(void) { 5914 #ifdef PREPASS_PASS 5915 gl_FragColor = float2vec4(vLinearDepth); 5916 #else 5917 #if defined(SKY_FISHEYE) && !defined(SKYMESH) 5918 vec2 ndc = vClipXYW.xy / vClipXYW.z; 5919 float px = ndc.x / fisheye_projMat00; 5920 float py = ndc.y / fisheye_projMat11; 5921 float r = sqrt(px * px + py * py); 5922 float theta = fisheye_k * atan(r * fisheye_invK); 5923 float sinT = sin(theta); 5924 float cosT = cos(theta); 5925 vec3 camDir = (r > 1e-6) 5926 ? vec3(px / r * sinT, py / r * sinT, -cosT) 5927 : vec3(0.0, 0.0, -1.0); 5928 vec3 dir = transpose(mat3(matrix_view)) * camDir; 5929 dir = dir * cubeMapRotationMatrix; 5930 #elif defined(SKY_CUBEMAP) && defined(SKYMESH) 5931 vec3 envDir = normalize(vWorldPos - projectedSkydomeCenter); 5932 vec3 dir = envDir * cubeMapRotationMatrix; 5933 #else 5934 vec3 dir = vViewDir; 5935 #endif 5936 #ifdef SKY_CUBEMAP 5937 dir.x *= -1.0; 5938 vec3 linear = {SKYBOX_DECODE_FNC}(textureCube(texture_cubeMap, dir)); 5939 #else 5940 dir *= vec3(-1.0, 1.0, 1.0); 5941 vec2 uv = toSphericalUv(normalize(dir)); 5942 vec3 linear = {SKYBOX_DECODE_FNC}(texture2D(texture_envAtlas, mapRoughnessUv(uv, mipLevel))); 5943 #endif 5944 if (any(greaterThanEqual(linear, vec3(64.0)))) { 5945 linear *= skyboxHighlightMultiplier; 5946 } 5947 gl_FragColor = vec4(gammaCorrectOutput(toneMap(processEnvironment(linear))), 1.0); 5948 #endif 5949 } 5950`,o3=` 5951attribute vec4 aPosition; 5952uniform mat4 matrix_view; 5953uniform mat4 matrix_projectionSkybox; 5954uniform mat3 cubeMapRotationMatrix; 5955varying vec3 vViewDir; 5956#ifdef SKY_FISHEYE 5957 varying vec3 vClipXYW; 5958#endif 5959#ifdef PREPASS_PASS 5960 varying float vLinearDepth; 5961#endif 5962#ifdef SKYMESH 5963 uniform mat4 matrix_model; 5964 varying vec3 vWorldPos; 5965#endif 5966void main(void) { 5967 mat4 view = matrix_view; 5968 #ifdef SKYMESH 5969 vec4 worldPos = matrix_model * aPosition; 5970 vWorldPos = worldPos.xyz; 5971 gl_Position = matrix_projectionSkybox * (view * worldPos); 5972 #ifdef PREPASS_PASS 5973 vLinearDepth = -(matrix_view * vec4(vWorldPos, 1.0)).z; 5974 #endif 5975 #else 5976 view[3][0] = view[3][1] = view[3][2] = 0.0; 5977 vViewDir = aPosition.xyz * cubeMapRotationMatrix; 5978 #ifdef SKY_FISHEYE 5979 vec4 viewPos = view * aPosition; 5980 gl_Position = vec4(viewPos.xy, 0.0, -viewPos.z); 5981 vClipXYW = vec3(gl_Position.xy, gl_Position.w); 5982 #else 5983 gl_Position = matrix_projectionSkybox * (view * aPosition); 5984 #endif 5985 #ifdef PREPASS_PASS 5986 vLinearDepth = -gl_Position.w; 5987 #endif 5988 #endif 5989 gl_Position.z = gl_Position.w - 1.0e-7; 5990} 5991`,l3=` 5992#ifdef STD_SPECULAR_CONSTANT 5993uniform vec3 material_specular; 5994#endif 5995void getSpecularity() { 5996 vec3 specularColor = vec3(1,1,1); 5997 #ifdef STD_SPECULAR_CONSTANT 5998 specularColor *= material_specular; 5999 #endif 6000 #ifdef STD_SPECULAR_TEXTURE 6001 specularColor *= {STD_SPECULAR_TEXTURE_DECODE}(texture2DBias({STD_SPECULAR_TEXTURE_NAME}, {STD_SPECULAR_TEXTURE_UV}, textureBias)).{STD_SPECULAR_TEXTURE_CHANNEL}; 6002 #endif 6003 #ifdef STD_SPECULAR_VERTEX 6004 specularColor *= saturate(vVertexColor.{STD_SPECULAR_VERTEX_CHANNEL}); 6005 #endif 6006 dSpecularity = specularColor; 6007} 6008`,c3=` 6009vec2 toSpherical(vec3 dir) { 6010 return vec2(dir.xz == vec2(0.0) ? 0.0 : atan(dir.x, dir.z), asin(dir.y)); 6011} 6012vec2 toSphericalUv(vec3 dir) { 6013 const float PI = 3.141592653589793; 6014 vec2 uv = toSpherical(dir) / vec2(PI * 2.0, PI) + 0.5; 6015 return vec2(uv.x, 1.0 - uv.y); 6016} 6017`,h3=` 6018#ifdef STD_SPECULARITYFACTOR_CONSTANT 6019uniform float material_specularityFactor; 6020#endif 6021void getSpecularityFactor() { 6022 float specularityFactor = 1.0; 6023 #ifdef STD_SPECULARITYFACTOR_CONSTANT 6024 specularityFactor *= material_specularityFactor; 6025 #endif 6026 #ifdef STD_SPECULARITYFACTOR_TEXTURE 6027 specularityFactor *= texture2DBias({STD_SPECULARITYFACTOR_TEXTURE_NAME}, {STD_SPECULARITYFACTOR_TEXTURE_UV}, textureBias).{STD_SPECULARITYFACTOR_TEXTURE_CHANNEL}; 6028 #endif 6029 #ifdef STD_SPECULARITYFACTOR_VERTEX 6030 specularityFactor *= saturate(vVertexColor.{STD_SPECULARITYFACTOR_VERTEX_CHANNEL}); 6031 #endif 6032 dSpecularityFactor = specularityFactor; 6033} 6034`,d3=` 6035float getSpotEffect(vec3 lightSpotDir, float lightInnerConeAngle, float lightOuterConeAngle, vec3 lightDirNorm) { 6036 float cosAngle = dot(lightDirNorm, lightSpotDir); 6037 return smoothstep(lightOuterConeAngle, lightInnerConeAngle, cosAngle); 6038} 6039`,u3=` 6040 nineSlicedUv = vec2(vUv0.x, 1.0 - vUv0.y); 6041`,f3=` 6042 vec2 tileMask = step(vMask, vec2(0.99999)); 6043 vec2 tileSize = 0.5 * (innerOffset.xy + innerOffset.zw); 6044 vec2 tileScale = vec2(1.0) / (vec2(1.0) - tileSize); 6045 vec2 clampedUv = mix(innerOffset.xy * 0.5, vec2(1.0) - innerOffset.zw * 0.5, fract((vTiledUv - tileSize) * tileScale)); 6046 clampedUv = clampedUv * atlasRect.zw + atlasRect.xy; 6047 nineSlicedUv = vUv0 * tileMask + clampedUv * (vec2(1.0) - tileMask); 6048 nineSlicedUv.y = 1.0 - nineSlicedUv.y; 6049 6050`,p3=` 6051 float dAlpha = 1.0; 6052 #if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE 6053 #ifdef STD_OPACITY_TEXTURE_ALLOCATE 6054 uniform sampler2D texture_opacityMap; 6055 #endif 6056 #endif 6057 #ifdef FORWARD_PASS 6058 vec3 dAlbedo; 6059 vec3 dNormalW; 6060 vec3 dSpecularity = vec3(0.0); 6061 float dGlossiness = 0.0; 6062 #ifdef LIT_REFRACTION 6063 float dTransmission; 6064 float dThickness; 6065 #endif 6066 #ifdef LIT_SCENE_COLOR 6067 uniform sampler2D uSceneColorMap; 6068 #endif 6069 #ifdef LIT_SCREEN_SIZE 6070 uniform vec4 uScreenSize; 6071 #endif 6072 #ifdef LIT_TRANSFORMS 6073 uniform mat4 matrix_viewProjection; 6074 uniform mat4 matrix_model; 6075 #endif 6076 #ifdef STD_HEIGHT_MAP 6077 vec2 dUvOffset; 6078 #ifdef STD_HEIGHT_TEXTURE_ALLOCATE 6079 uniform sampler2D texture_heightMap; 6080 #endif 6081 #endif 6082 #ifdef STD_DIFFUSE_TEXTURE_ALLOCATE 6083 uniform sampler2D texture_diffuseMap; 6084 #endif 6085 #ifdef STD_DIFFUSEDETAIL_TEXTURE_ALLOCATE 6086 uniform sampler2D texture_diffuseDetailMap; 6087 #endif 6088 #ifdef STD_NORMAL_TEXTURE_ALLOCATE 6089 uniform sampler2D texture_normalMap; 6090 #endif 6091 #ifdef STD_NORMALDETAIL_TEXTURE_ALLOCATE 6092 uniform sampler2D texture_normalDetailMap; 6093 #endif 6094 #ifdef STD_THICKNESS_TEXTURE_ALLOCATE 6095 uniform sampler2D texture_thicknessMap; 6096 #endif 6097 #ifdef STD_REFRACTION_TEXTURE_ALLOCATE 6098 uniform sampler2D texture_refractionMap; 6099 #endif 6100 #ifdef LIT_IRIDESCENCE 6101 float dIridescence; 6102 float dIridescenceThickness; 6103 #ifdef STD_IRIDESCENCE_THICKNESS_TEXTURE_ALLOCATE 6104 uniform sampler2D texture_iridescenceThicknessMap; 6105 #endif 6106 #ifdef STD_IRIDESCENCE_TEXTURE_ALLOCATE 6107 uniform sampler2D texture_iridescenceMap; 6108 #endif 6109 #endif 6110 #ifdef LIT_CLEARCOAT 6111 float ccSpecularity; 6112 float ccGlossiness; 6113 vec3 ccNormalW; 6114 #endif 6115 #ifdef LIT_GGX_SPECULAR 6116 float dAnisotropy; 6117 vec2 dAnisotropyRotation; 6118 #endif 6119 #ifdef LIT_SPECULAR_OR_REFLECTION 6120 #ifdef LIT_SHEEN 6121 vec3 sSpecularity; 6122 float sGlossiness; 6123 #ifdef STD_SHEEN_TEXTURE_ALLOCATE 6124 uniform sampler2D texture_sheenMap; 6125 #endif 6126 #ifdef STD_SHEENGLOSS_TEXTURE_ALLOCATE 6127 uniform sampler2D texture_sheenGlossMap; 6128 #endif 6129 #endif 6130 #ifdef LIT_METALNESS 6131 float dMetalness; 6132 float dIor; 6133 #ifdef STD_METALNESS_TEXTURE_ALLOCATE 6134 uniform sampler2D texture_metalnessMap; 6135 #endif 6136 #endif 6137 #ifdef LIT_SPECULARITY_FACTOR 6138 float dSpecularityFactor; 6139 #ifdef STD_SPECULARITYFACTOR_TEXTURE_ALLOCATE 6140 uniform sampler2D texture_specularityFactorMap; 6141 #endif 6142 #endif 6143 #ifdef STD_SPECULAR_COLOR 6144 #ifdef STD_SPECULAR_TEXTURE_ALLOCATE 6145 uniform sampler2D texture_specularMap; 6146 #endif 6147 #endif 6148 #ifdef STD_GLOSS_TEXTURE_ALLOCATE 6149 uniform sampler2D texture_glossMap; 6150 #endif 6151 #endif 6152 #ifdef STD_AO 6153 float dAo; 6154 #ifdef STD_AO_TEXTURE_ALLOCATE 6155 uniform sampler2D texture_aoMap; 6156 #endif 6157 #ifdef STD_AODETAIL_TEXTURE_ALLOCATE 6158 uniform sampler2D texture_aoDetailMap; 6159 #endif 6160 #endif 6161 vec3 dEmission; 6162 #ifdef STD_EMISSIVE_TEXTURE_ALLOCATE 6163 uniform sampler2D texture_emissiveMap; 6164 #endif 6165 #ifdef LIT_CLEARCOAT 6166 #ifdef STD_CLEARCOAT_TEXTURE_ALLOCATE 6167 uniform sampler2D texture_clearCoatMap; 6168 #endif 6169 #ifdef STD_CLEARCOATGLOSS_TEXTURE_ALLOCATE 6170 uniform sampler2D texture_clearCoatGlossMap; 6171 #endif 6172 #ifdef STD_CLEARCOATNORMAL_TEXTURE_ALLOCATE 6173 uniform sampler2D texture_clearCoatNormalMap; 6174 #endif 6175 #endif 6176 6177 #ifdef LIT_GGX_SPECULAR 6178 #ifdef STD_ANISOTROPY_TEXTURE_ALLOCATE 6179 uniform sampler2D texture_anisotropyMap; 6180 #endif 6181 #endif 6182 #if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR) 6183 vec3 dLightmap;
6184 #ifdef STD_LIGHT_TEXTURE_ALLOCATE 6185 uniform sampler2D texture_lightMap; 6186 #endif 6187 #endif 6188 #endif 6189 #include "litShaderCorePS" 6190`,m3=` 6191 #if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE 6192 #include "opacityPS" 6193 #if defined(LIT_ALPHA_TEST) 6194 #include "alphaTestPS" 6195 #endif 6196 #if STD_OPACITY_DITHER != NONE 6197 #include "opacityDitherPS" 6198 #endif 6199 #endif 6200 #ifdef FORWARD_PASS 6201 #ifdef STD_HEIGHT_MAP 6202 #include "parallaxPS" 6203 #endif 6204 #include "diffusePS" 6205 #ifdef LIT_NEEDS_NORMAL 6206 #include "normalMapPS" 6207 #endif 6208 #ifdef LIT_REFRACTION 6209 #include "transmissionPS" 6210 #include "thicknessPS" 6211 #endif 6212 #ifdef LIT_IRIDESCENCE 6213 #include "iridescencePS" 6214 #include "iridescenceThicknessPS" 6215 #endif 6216 #ifdef LIT_SPECULAR_OR_REFLECTION 6217 #ifdef LIT_SHEEN 6218 #include "sheenPS" 6219 #include "sheenGlossPS" 6220 #endif 6221 #ifdef LIT_METALNESS 6222 #include "metalnessPS" 6223 #include "iorPS" 6224 #endif 6225 #ifdef LIT_SPECULARITY_FACTOR 6226 #include "specularityFactorPS" 6227 #endif 6228 #ifdef STD_SPECULAR_COLOR 6229 #include "specularPS" 6230 #else 6231 void getSpecularity() { 6232 dSpecularity = vec3(1); 6233 } 6234 #endif 6235 #include "glossPS" 6236 #endif 6237 #ifdef STD_AO 6238 #include "aoPS" 6239 #endif 6240 #include "emissivePS" 6241 #ifdef LIT_CLEARCOAT 6242 #include "clearCoatPS" 6243 #include "clearCoatGlossPS" 6244 #include "clearCoatNormalPS" 6245 #endif 6246 #if defined(LIT_SPECULAR) && defined(LIT_LIGHTING) && defined(LIT_GGX_SPECULAR) 6247 #include "anisotropyPS" 6248 #endif 6249 #if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR) 6250 #include "lightmapPS" 6251 #endif 6252 #endif 6253 void evaluateFrontend() { 6254 #if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE 6255 getOpacity(); 6256 #if defined(LIT_ALPHA_TEST) 6257 alphaTest(dAlpha); 6258 #endif 6259 #if STD_OPACITY_DITHER != NONE 6260 opacityDither(dAlpha * material_alphaDitherScale, 0.0); 6261 #endif 6262 litArgs_opacity = dAlpha; 6263 #endif 6264 #ifdef FORWARD_PASS 6265 #ifdef STD_HEIGHT_MAP 6266 getParallax(); 6267 #endif 6268 getAlbedo(); 6269 litArgs_albedo = dAlbedo; 6270 #ifdef LIT_NEEDS_NORMAL 6271 getNormal(); 6272 litArgs_worldNormal = dNormalW; 6273 #endif 6274 #ifdef LIT_REFRACTION 6275 getRefraction(); 6276 litArgs_transmission = dTransmission; 6277 getThickness(); 6278 litArgs_thickness = dThickness; 6279 #ifdef LIT_DISPERSION 6280 litArgs_dispersion = material_dispersion; 6281 #endif 6282 #endif 6283 #ifdef LIT_IRIDESCENCE 6284 getIridescence(); 6285 getIridescenceThickness(); 6286 litArgs_iridescence_intensity = dIridescence; 6287 litArgs_iridescence_thickness = dIridescenceThickness; 6288 #endif 6289 #ifdef LIT_SPECULAR_OR_REFLECTION 6290 #ifdef LIT_SHEEN 6291 getSheen(); 6292 litArgs_sheen_specularity = sSpecularity; 6293 getSheenGlossiness(); 6294 litArgs_sheen_gloss = sGlossiness; 6295 #endif 6296 #ifdef LIT_METALNESS 6297 getMetalness(); 6298 litArgs_metalness = dMetalness; 6299 getIor(); 6300 litArgs_ior = dIor; 6301 #endif 6302 #ifdef LIT_SPECULARITY_FACTOR 6303 getSpecularityFactor(); 6304 litArgs_specularityFactor = dSpecularityFactor; 6305 #endif 6306 getGlossiness(); 6307 getSpecularity(); 6308 litArgs_specularity = dSpecularity; 6309 litArgs_gloss = dGlossiness; 6310 #endif 6311 #ifdef STD_AO 6312 getAO(); 6313 litArgs_ao = dAo; 6314 #endif 6315 getEmission(); 6316 litArgs_emission = dEmission; 6317 #ifdef LIT_CLEARCOAT 6318 getClearCoat(); 6319 getClearCoatGlossiness(); 6320 getClearCoatNormal(); 6321 litArgs_clearcoat_specularity = ccSpecularity; 6322 litArgs_clearcoat_gloss = ccGlossiness; 6323 litArgs_clearcoat_worldNormal = ccNormalW; 6324 #endif 6325 #if defined(LIT_SPECULAR) && defined(LIT_LIGHTING) && defined(LIT_GGX_SPECULAR) 6326 getAnisotropy(); 6327 #endif 6328 #if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR) 6329 getLightMap(); 6330 litArgs_lightmap = dLightmap; 6331 #ifdef STD_LIGHTMAP_DIR 6332 litArgs_lightmapDir = dLightmapDir; 6333 #endif 6334 #endif 6335 #endif 6336 } 6337`,_3=` 6338#ifdef LIT_TANGENTS 6339 #define TBN_TANGENTS 6340#else 6341 #if defined(LIT_USE_NORMALS) || defined(LIT_USE_CLEARCOAT_NORMALS) 6342 #define TBN_DERIVATIVES 6343 #endif 6344#endif 6345#if defined(TBN_DERIVATIVES) 6346 uniform float tbnBasis; 6347#endif 6348void getTBN(vec3 tangent, vec3 binormal, vec3 normal) { 6349 #ifdef TBN_TANGENTS 6350 dTBN = mat3(normalize(tangent), normalize(binormal), normalize(normal)); 6351 #elif defined(TBN_DERIVATIVES) 6352 vec2 uv = {lightingUv}; 6353 vec3 dp1 = dFdx( vPositionW ); 6354 vec3 dp2 = dFdy( vPositionW ); 6355 vec2 duv1 = dFdx( uv ); 6356 vec2 duv2 = dFdy( uv ); 6357 vec3 dp2perp = cross( dp2, normal ); 6358 vec3 dp1perp = cross( normal, dp1 ); 6359 vec3 T = dp2perp * duv1.x + dp1perp * duv2.x; 6360 vec3 B = dp2perp * duv1.y + dp1perp * duv2.y; 6361 float denom = max( dot(T,T), dot(B,B) ); 6362 float invmax = (denom == 0.0) ? 0.0 : tbnBasis / sqrt( denom ); 6363 dTBN = mat3(T * invmax, -B * invmax, normal ); 6364 #else 6365 vec3 B = cross(normal, vObjectSpaceUpW); 6366 vec3 T = cross(normal, B); 6367 if (dot(B,B)==0.0) 6368 { 6369 float major=max(max(normal.x, normal.y), normal.z); 6370 if (normal.x == major) 6371 { 6372 B = cross(normal, vec3(0,1,0)); 6373 T = cross(normal, B); 6374 } 6375 else if (normal.y == major) 6376 { 6377 B = cross(normal, vec3(0,0,1)); 6378 T = cross(normal, B); 6379 } 6380 else if (normal.z == major) 6381 { 6382 B = cross(normal, vec3(1,0,0)); 6383 T = cross(normal, B); 6384 } 6385 } 6386 dTBN = mat3(normalize(T), normalize(B), normalize(normal)); 6387 #endif 6388} 6389`,g3=` 6390#ifdef STD_THICKNESS_CONSTANT 6391uniform float material_thickness; 6392#endif 6393void getThickness() { 6394 dThickness = 1.0; 6395 #ifdef STD_THICKNESS_CONSTANT 6396 dThickness *= material_thickness; 6397 #endif 6398 #ifdef STD_THICKNESS_TEXTURE 6399 dThickness *= texture2DBias({STD_THICKNESS_TEXTURE_NAME}, {STD_THICKNESS_TEXTURE_UV}, textureBias).{STD_THICKNESS_TEXTURE_CHANNEL}; 6400 #endif 6401 #ifdef STD_THICKNESS_VERTEX 6402 dThickness *= saturate(vVertexColor.{STD_THICKNESS_VERTEX_CHANNEL}); 6403 #endif 6404} 6405`,v3=` 6406#ifndef TONEMAP_NO_EXPOSURE_UNIFORM 6407 #if TONEMAP != NONE 6408 uniform float exposure; 6409 float getExposure() { return exposure; } 6410 #else 6411 float getExposure() { return 1.0; } 6412 #endif 6413#endif 6414#if (TONEMAP == NONE) 6415 #include "tonemappingNonePS" 6416#elif TONEMAP == FILMIC 6417 #include "tonemappingFilmicPS" 6418#elif TONEMAP == LINEAR 6419 #include "tonemappingLinearPS" 6420#elif TONEMAP == HEJL 6421 #include "tonemappingHejlPS" 6422#elif TONEMAP == ACES 6423 #include "tonemappingAcesPS" 6424#elif TONEMAP == ACES2 6425 #include "tonemappingAces2PS" 6426#elif TONEMAP == NEUTRAL 6427 #include "tonemappingNeutralPS" 6428#endif 6429`,S3=` 6430vec3 toneMap(vec3 color) { 6431 float tA = 2.51; 6432 float tB = 0.03; 6433 float tC = 2.43; 6434 float tD = 0.59; 6435 float tE = 0.14; 6436 vec3 x = color * getExposure(); 6437 return (x*(tA*x+tB))/(x*(tC*x+tD)+tE); 6438} 6439`,y3=` 6440const mat3 ACESInputMat = mat3( 6441 0.59719, 0.35458, 0.04823, 6442 0.07600, 0.90834, 0.01566, 6443 0.02840, 0.13383, 0.83777 6444); 6445const mat3 ACESOutputMat = mat3( 6446 1.60475, -0.53108, -0.07367, 6447 -0.10208, 1.10813, -0.00605, 6448 -0.00327, -0.07276, 1.07602 6449); 6450vec3 RRTAndODTFit(vec3 v) { 6451 vec3 a = v * (v + 0.0245786) - 0.000090537; 6452 vec3 b = v * (0.983729 * v + 0.4329510) + 0.238081; 6453 return a / b; 6454} 6455vec3 toneMap(vec3 color) { 6456 color *= getExposure() / 0.6; 6457 color = color * ACESInputMat; 6458 color = RRTAndODTFit(color); 6459 color = color * ACESOutputMat; 6460 color = clamp(color, 0.0, 1.0); 6461 return color; 6462} 6463`,x3=` 6464const float A = 0.15; 6465const float B = 0.50; 6466const float C = 0.10; 6467const float D = 0.20; 6468const float E = 0.02; 6469const float F = 0.30; 6470const float W = 11.2; 6471vec3 uncharted2Tonemap(vec3 x) { 6472 return ((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F; 6473} 6474vec3 toneMap(vec3 color) { 6475 color = uncharted2Tonemap(color * getExposure()); 6476 vec3 whiteScale = 1.0 / uncharted2Tonemap(vec3(W,W,W)); 6477 color = color * whiteScale; 6478 return color; 6479} 6480`,T3=` 6481vec3 toneMap(vec3 color) { 6482 color *= getExposure(); 6483 const float A = 0.22, B = 0.3, C = .1, D = 0.2, E = .01, F = 0.3; 6484 const float Scl = 1.25; 6485 vec3 h = max( vec3(0.0), color - vec3(0.004) ); 6486 return (h*((Scl*A)*h+Scl*vec3(C*B,C*B,C*B))+Scl*vec3(D*E,D*E,D*E)) / (h*(A*h+vec3(B,B,B))+vec3(D*F,D*F,D*F)) - Scl*vec3(E/F,E/F,E/F); 6487} 6488`,w3=` 6489vec3 toneMap(vec3 color) { 6490 return color * getExposure(); 6491} 6492`,C3=` 6493vec3 toneMap(vec3 color) { 6494 color *= getExposure(); 6495 float startCompression = 0.8 - 0.04; 6496 float desaturation = 0.15; 6497 float x = min(color.r, min(color.g, color.b)); 6498 float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; 6499 color -= offset; 6500 float peak = max(color.r, max(color.g, color.b)); 6501 if (peak < startCompression) return color; 6502 float d = 1. - startCompression; 6503 float newPeak = 1. - d * d / (peak + d - startCompression); 6504 color *= newPeak / peak; 6505 float g = 1. - 1. / (desaturation * (peak - newPeak) + 1.); 6506 return mix(color, newPeak * vec3(1, 1, 1), g); 6507} 6508`,E3=` 6509vec3 toneMap(vec3 color) { 6510 return color; 6511} 6512`,b3=` 6513#ifdef PIXELSNAP 6514uniform vec4 uScreenSize; 6515#endif 6516#ifdef SCREENSPACE 6517uniform float projectionFlipY; 6518#endif 6519vec4 evalWorldPosition(vec3 vertexPosition, mat4 modelMatrix) { 6520 vec3 localPos = getLocalPosition(vertexPosition); 6521 #ifdef NINESLICED 6522 localPos.xz *= outerScale; 6523 vec2 positiveUnitOffset = clamp(vertexPosition.xz, vec2(0.0), vec2(1.0)); 6524 vec2 negativeUnitOffset = clamp(-vertexPosition.xz, vec2(0.0), vec2(1.0)); 6525 localPos.xz += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy; 6526 vTiledUv = (localPos.xz - outerScale + innerOffset.xy) * -0.5 + 1.0; 6527 localPos.xz *= -0.5; 6528 localPos = localPos.xzy; 6529 #endif 6530 vec4 posW = modelMatrix * vec4(localPos, 1.0); 6531 #ifdef SCREENSPACE 6532 posW.zw = vec2(0.0, 1.0); 6533 #endif 6534 return posW; 6535} 6536vec4 getPosition() { 6537 dModelMatrix = getModelMatrix(); 6538 vec4 posW = evalWorldPosition(vertex_position.xyz, dModelMatrix); 6539 dPositionW = posW.xyz; 6540 vec4 screenPos; 6541 #ifdef UV1LAYOUT 6542 screenPos = vec4(vertex_texCoord1.xy * 2.0 - 1.0, 0.5, 1); 6543 #ifdef WEBGPU
6544 screenPos.y *= -1.0; 6545 #endif 6546 #else 6547 #ifdef SCREENSPACE 6548 screenPos = posW; 6549 screenPos.y *= projectionFlipY; 6550 #else 6551 screenPos = matrix_viewProjection * posW; 6552 #endif 6553 #ifdef PIXELSNAP 6554 screenPos.xy = (screenPos.xy * 0.5) + 0.5; 6555 screenPos.xy *= uScreenSize.xy; 6556 screenPos.xy = floor(screenPos.xy); 6557 screenPos.xy *= uScreenSize.zw; 6558 screenPos.xy = (screenPos.xy * 2.0) - 1.0; 6559 #endif 6560 #endif 6561 return screenPos; 6562} 6563vec3 getWorldPosition() { 6564 return dPositionW; 6565} 6566`,A3=` 6567attribute vec4 vertex_position; 6568uniform mat4 matrix_viewProjection; 6569uniform mat4 matrix_model; 6570#ifdef MORPHING 6571 uniform vec2 morph_tex_params; 6572 attribute uint morph_vertex_id; 6573 ivec2 getTextureMorphCoords() { 6574 ivec2 textureSize = ivec2(morph_tex_params); 6575 int morphGridV = int(morph_vertex_id) / textureSize.x; 6576 int morphGridU = int(morph_vertex_id) - (morphGridV * textureSize.x); 6577 #ifdef WEBGPU 6578 morphGridV = textureSize.y - morphGridV - 1; 6579 #endif 6580 return ivec2(morphGridU, morphGridV); 6581 } 6582 #ifdef MORPHING_POSITION 6583 #ifdef MORPHING_INT 6584 uniform vec3 aabbSize; 6585 uniform vec3 aabbMin; 6586 uniform usampler2D morphPositionTex; 6587 #else 6588 uniform highp sampler2D morphPositionTex; 6589 #endif 6590 #endif 6591#endif 6592#ifdef defined(BATCH) 6593 #include "skinBatchVS" 6594 mat4 getModelMatrix() { 6595 return getBoneMatrix(vertex_boneIndices); 6596 } 6597#elif defined(SKIN) 6598 #include "skinVS" 6599 mat4 getModelMatrix() { 6600 return matrix_model * getSkinMatrix(vertex_boneIndices, vertex_boneWeights); 6601 } 6602#elif defined(INSTANCING) 6603 #include "transformInstancingVS" 6604#else 6605 mat4 getModelMatrix() { 6606 return matrix_model; 6607 } 6608#endif 6609vec3 getLocalPosition(vec3 vertexPosition) { 6610 vec3 localPos = vertexPosition; 6611 #ifdef MORPHING_POSITION 6612 ivec2 morphUV = getTextureMorphCoords(); 6613 #ifdef MORPHING_INT 6614 vec3 morphPos = vec3(texelFetch(morphPositionTex, ivec2(morphUV), 0).xyz) / 65535.0 * aabbSize + aabbMin; 6615 #else 6616 vec3 morphPos = texelFetch(morphPositionTex, ivec2(morphUV), 0).xyz; 6617 #endif 6618 localPos += morphPos; 6619 #endif 6620 return localPos; 6621} 6622`,P3=` 6623attribute vec4 instance_line1; 6624attribute vec4 instance_line2; 6625attribute vec4 instance_line3; 6626attribute vec4 instance_line4; 6627mat4 getModelMatrix() { 6628 return matrix_model * mat4(instance_line1, instance_line2, instance_line3, instance_line4); 6629} 6630`,I3=` 6631#ifdef STD_REFRACTION_CONSTANT 6632uniform float material_refraction; 6633#endif 6634void getRefraction() { 6635 float refraction = 1.0; 6636 #ifdef STD_REFRACTION_CONSTANT 6637 refraction = material_refraction; 6638 #endif 6639 #ifdef STD_REFRACTION_TEXTURE 6640 refraction *= texture2DBias({STD_REFRACTION_TEXTURE_NAME}, {STD_REFRACTION_TEXTURE_UV}, textureBias).{STD_REFRACTION_TEXTURE_CHANNEL}; 6641 #endif 6642 #ifdef STD_REFRACTION_VERTEX 6643 refraction *= saturate(vVertexColor.{STD_REFRACTION_VERTEX_CHANNEL}); 6644 #endif 6645 dTransmission = refraction; 6646} 6647`,D3=` 6648void handleTwoSidedLighting() { 6649 if (!gl_FrontFacing) dTBN[2] = -dTBN[2]; 6650} 6651`,M3=` 6652#ifdef NINESLICED 6653 vec2 getUv0() { 6654 vec2 uv = vertex_position.xz; 6655 vec2 positiveUnitOffset = clamp(vertex_position.xz, vec2(0.0), vec2(1.0)); 6656 vec2 negativeUnitOffset = clamp(-vertex_position.xz, vec2(0.0), vec2(1.0)); 6657 uv += (-positiveUnitOffset * innerOffset.xy + negativeUnitOffset * innerOffset.zw) * vertex_texCoord0.xy; 6658 uv = uv * -0.5 + 0.5; 6659 uv = uv * atlasRect.zw + atlasRect.xy; 6660 vMask = vertex_texCoord0.xy; 6661 return uv; 6662 } 6663#else 6664 vec2 getUv0() { 6665 return vertex_texCoord0; 6666 } 6667#endif 6668`,R3=` 6669vec2 getUv1() { 6670 return vertex_texCoord1; 6671} 6672`,L3=` 6673vUV{TRANSFORM_UV_{i}}_{TRANSFORM_ID_{i}} = vec2( 6674 dot(vec3(uv{TRANSFORM_UV_{i}}, 1), {TRANSFORM_NAME_{i}}0), 6675 dot(vec3(uv{TRANSFORM_UV_{i}}, 1), {TRANSFORM_NAME_{i}}1) 6676); 6677`,F3=` 6678 uniform vec3 {TRANSFORM_NAME_{i}}0; 6679 uniform vec3 {TRANSFORM_NAME_{i}}1; 6680`,O3=` 6681void getViewDir() { 6682 dViewDirW = normalize(view_position - vPositionW); 6683} 6684`;const B3={alphaTestPS:KR,ambientPS:ZR,anisotropyPS:QR,aoPS:JR,aoDiffuseOccPS:e2,aoSpecOccPS:t2,bakeDirLmEndPS:s2,bakeLmEndPS:i2,basePS:r2,baseNineSlicedPS:a2,baseNineSlicedTiledPS:n2,bayerPS:o2,blurVSMPS:l2,clearCoatPS:c2,clearCoatGlossPS:h2,clearCoatNormalPS:d2,clusteredLightCookiesPS:f2,clusteredLightShadowsPS:p2,clusteredLightUtilsPS:u2,clusteredLightPS:m2,combinePS:_2,cookieBlit2DPS:g2,cookieBlitCubePS:v2,cookieBlitVS:S2,cookiePS:y2,cubeMapProjectP
6684S:x2,cubeMapRotatePS:T2,debugOutputPS:w2,debugProcessFrontendPS:C2,detailModesPS:b2,diffusePS:A2,decodePS:E2,emissivePS:P2,encodePS:I2,endPS:D2,envAtlasPS:M2,envProcPS:R2,falloffInvSquaredPS:L2,falloffLinearPS:F2,floatAsUintPS:O2,fogPS:B2,fresnelSchlickPS:N2,frontendCodePS:"",frontendDeclPS:"",fullscreenQuadVS:k2,gammaPS:U2,gles3PS:sT,gles3VS:iT,glossPS:z2,quadVS:V2,immediateLinePS:G2,immediateLineVS:H2,iridescenceDiffractionPS:W2,iridescencePS:X2,iridescenceThicknessPS:Y2,iorPS:j2,lightDeclarationPS:q2,lightDiffuseLambertPS:$2,lightDirPointPS:K2,lightEvaluationPS:Z2,lightFunctionLightPS:Q2,lightFunctionShadowPS:J2,lightingPS:eL,lightmapAddPS:tL,lightmapPS:sL,lightSpecularAnisoGGXPS:iL,lightSpecularGGXPS:rL,lightSpecularBlinnPS:aL,lightSheenPS:nL,linearizeDepthPS:oL,litForwardBackendPS:lL,litForwardDeclarationPS:cL,litForwardMainPS:hL,litForwardPostCodePS:dL,litForwardPreCodePS:uL,litMainPS:fL,litMainVS:pL,litOtherMainPS:mL,litShaderArgsPS:_L,litShaderCorePS:gL,litShadowMainPS:vL,litUserDeclarationPS:"",litUserDeclarationVS:"",litUserCodePS:"",litUserCodeVS:"",litUserMainStartPS:"",litUserMainStartVS:"",litUserMainEndPS:"",litUserMainEndVS:"",ltcPS:SL,metalnessPS:yL,metalnessModulatePS:TL,morphPS:wL,morphVS:CL,msdfPS:xL,msdfVS:EL,normalVS:bL,normalCoreVS:AL,normalMapPS:PL,opacityPS:IL,opacityDitherPS:DL,outputPS:ML,outputAlphaPS:RL,outputTex2DPS:LL,sheenPS:FL,sheenGlossPS:OL,parallaxPS:BL,pickPS:NL,reflDirPS:kL,reflDirAnisoPS:UL,reflectionCCPS:zL,reflectionCubePS:VL,reflectionEnvHQPS:GL,reflectionEnvPS:HL,reflectionSpherePS:WL,reflectionSheenPS:XL,refractionCubePS:YL,refractionDynamicPS:jL,reprojectPS:qL,reprojectVS:$L,screenDepthPS:KL,shadowCascadesPS:ZL,shadowEVSMPS:QL,shadowPCF1PS:JL,shadowPCF3PS:e3,shadowPCF5PS:t3,shadowPCSSPS:s3,shadowSoftPS:i3,skinBatchVS:r3,skinVS:a3,skyboxPS:n3,skyboxVS:o3,specularPS:l3,sphericalPS:c3,specularityFactorPS:h3,spotPS:d3,startNineSlicedPS:u3,startNineSlicedTiledPS:f3,stdDeclarationPS:p3,stdFrontEndPS:m3,TBNPS:_3,thicknessPS:g3,tonemappingPS:v3,tonemappingAcesPS:S3,tonemappingAces2PS:y3,tonemappingFilmicPS:x3,tonemappingHejlPS:T3,tonemappingLinearPS:w3,tonemappingNeutralPS:C3,tonemappingNonePS:E3,transformVS:b3,transformCoreVS:A3,transformInstancingVS:P3,transmissionPS:I3,twoSidedLightingPS:D3,uv0VS:M3,uv1VS:R3,uvTransformVS:L3,uvTransformUniformsPS:F3,viewDirPS:O3,webgpuPS:rT,webgpuVS:aT};var N3=` 6685uniform alpha_ref: f32; 6686fn alphaTest(a: f32) { 6687 if (a < uniform.alpha_ref) { 6688 discard; 6689 } 6690} 6691`,k3=` 6692#if LIT_AMBIENT_SOURCE == AMBIENTSH 6693 uniform ambientSH: array<vec3f, 9>; 6694#endif 6695#if LIT_AMBIENT_SOURCE == ENVALATLAS 6696 #include "envAtlasPS" 6697 #ifndef ENV_ATLAS 6698 #define ENV_ATLAS 6699 var texture_envAtlas: texture_2d<f32>; 6700 var texture_envAtlasSampler: sampler; 6701 #endif 6702#endif 6703fn addAmbient(worldNormal: vec3f) { 6704 #ifdef LIT_AMBIENT_SOURCE == AMBIENTSH 6705 let n: vec3f = cubeMapRotate(worldNormal); 6706 let color: vec3f = 6707 uniform.ambientSH[0] + 6708 uniform.ambientSH[1] * n.x + 6709 uniform.ambientSH[2] * n.y + 6710 uniform.ambientSH[3] * n.z + 6711 uniform.ambientSH[4] * n.x * n.z + 6712 uniform.ambientSH[5] * n.z * n.y + 6713 uniform.ambientSH[6] * n.y * n.x + 6714 uniform.ambientSH[7] * (3.0 * n.z * n.z - 1.0) + 6715 uniform.ambientSH[8] * (n.x * n.x - n.y * n.y); 6716 dDiffuseLight += processEnvironment(max(color, vec3f(0.0))); 6717 #endif 6718 #if LIT_AMBIENT_SOURCE == ENVALATLAS 6719 let dir: vec3f = normalize(cubeMapRotate(worldNormal) * vec3f(-1.0, 1.0, 1.0)); 6720 let uv: vec2f = mapUv(toSphericalUv(dir), vec4f(128.0, 256.0 + 128.0, 64.0, 32.0) / atlasSize); 6721 let raw: vec4f = textureSample(texture_envAtlas, texture_envAtlasSampler, uv); 6722 let linear: vec3f = {ambientDecode}(raw); 6723 dDiffuseLight += processEnvironment(linear); 6724 #endif 6725 #if LIT_AMBIENT_SOURCE == CONSTANT 6726 dDiffuseLight += uniform.light_globalAmbient; 6727 #endif 6728} 6729`,U3=` 6730#ifdef LIT_GGX_SPECULAR 6731 uniform material_anisotropyIntensity: f32; 6732 uniform material_anisotropyRotation: vec2f; 6733#endif 6734fn getAnisotropy() { 6735 dAnisotropy = 0.0; 6736 dAnisotropyRotation = vec2f(1.0, 0.0); 6737#ifdef LIT_GGX_SPECULAR 6738 dAnisotropy = uniform.material_anisotropyIntensity; 6739 dAnisotropyRotation = uniform.material_anisotropyRotation; 6740#endif 6741#ifdef STD_ANISOTROPY_TEXTURE 6742 let anisotropyTex: vec3f = textureSampleBias({STD_ANISOTROPY_TEXTURE_NAME}, {STD_ANISOTROPY_TEXTURE_NAME}Sampler, {STD_ANISOTROPY_TEXTURE_UV}, uniform.textureBias).rgb; 6743 dAnisotropy *= anisotropyTex.b;
6744 let anisotropyRotationFromTex: vec2f = anisotropyTex.rg * 2.0 - vec2f(1.0); 6745 let rotationMatrix: mat2x2f = mat2x2f(dAnisotropyRotation.x, dAnisotropyRotation.y, -dAnisotropyRotation.y, dAnisotropyRotation.x); 6746 dAnisotropyRotation = rotationMatrix * anisotropyRotationFromTex; 6747#endif 6748 dAnisotropy = clamp(dAnisotropy, 0.0, 1.0); 6749} 6750`,z3=` 6751#if defined(STD_AO_TEXTURE) || defined(STD_AO_VERTEX) 6752 uniform material_aoIntensity: f32; 6753#endif 6754#ifdef STD_AODETAIL_TEXTURE 6755 #include "detailModesPS" 6756#endif 6757fn getAO() { 6758 dAo = 1.0; 6759 #ifdef STD_AO_TEXTURE 6760 var aoBase: f32 = textureSampleBias({STD_AO_TEXTURE_NAME}, {STD_AO_TEXTURE_NAME}Sampler, {STD_AO_TEXTURE_UV}, uniform.textureBias).{STD_AO_TEXTURE_CHANNEL}; 6761 #ifdef STD_AODETAIL_TEXTURE 6762 var aoDetail: f32 = textureSampleBias({STD_AODETAIL_TEXTURE_NAME}, {STD_AODETAIL_TEXTURE_NAME}Sampler, {STD_AODETAIL_TEXTURE_UV}, uniform.textureBias).{STD_AODETAIL_TEXTURE_CHANNEL}; 6763 aoBase = detailMode_{STD_AODETAIL_DETAILMODE}(vec3f(aoBase), vec3f(aoDetail)).r; 6764 #endif 6765 dAo = dAo * aoBase; 6766 #endif 6767 #ifdef STD_AO_VERTEX 6768 dAo = dAo * saturate(vVertexColor.{STD_AO_VERTEX_CHANNEL}); 6769 #endif 6770 #if defined(STD_AO_TEXTURE) || defined(STD_AO_VERTEX) 6771 dAo = mix(1.0, dAo, uniform.material_aoIntensity); 6772 #endif 6773} 6774`,V3=` 6775fn occludeDiffuse(ao: f32) { 6776 dDiffuseLight = dDiffuseLight * ao; 6777} 6778`,G3=` 6779#if LIT_OCCLUDE_SPECULAR != NONE 6780 #ifdef LIT_OCCLUDE_SPECULAR_FLOAT 6781 uniform material_occludeSpecularIntensity: f32; 6782 #endif 6783#endif 6784fn occludeSpecular(gloss: f32, ao: f32, worldNormal: vec3f, viewDir: vec3f) { 6785 #if LIT_OCCLUDE_SPECULAR == AO 6786 #ifdef LIT_OCCLUDE_SPECULAR_FLOAT 6787 var specOcc: f32 = mix(1.0, ao, uniform.material_occludeSpecularIntensity); 6788 #else 6789 var specOcc: f32 = ao; 6790 #endif 6791 #endif 6792 #if LIT_OCCLUDE_SPECULAR == GLOSSDEPENDENT 6793 var specPow: f32 = exp2(gloss * 11.0); 6794 var specOcc: f32 = saturate(pow(dot(worldNormal, viewDir) + ao, 0.01 * specPow) - 1.0 + ao); 6795 #ifdef LIT_OCCLUDE_SPECULAR_FLOAT 6796 specOcc = mix(1.0, specOcc, uniform.material_occludeSpecularIntensity); 6797 #endif 6798 #endif 6799 #if LIT_OCCLUDE_SPECULAR != NONE 6800 dSpecularLight = dSpecularLight * specOcc; 6801 dReflection = dReflection * specOcc; 6802 #ifdef LIT_SHEEN 6803 sSpecularLight = sSpecularLight * specOcc; 6804 sReflection = sReflection * specOcc; 6805 #endif 6806 #endif 6807} 6808`,H3=` 6809 let dirLm = textureSample(texture_dirLightMap, texture_dirLightMapSampler, vUv1); 6810 if (uniform.bakeDir > 0.5) { 6811 if (dAtten > 0.00001) { 6812 let unpacked_dir = dirLm.xyz * 2.0 - vec3f(1.0); 6813 dAtten = clamp(dAtten, 0.0, 1.0); 6814 let combined_dir = dLightDirNormW.xyz * dAtten + unpacked_dir * dirLm.w; 6815 let finalRgb = normalize(combined_dir) * 0.5 + vec3f(0.5); 6816 let finalA = max(dirLm.w + dAtten, 1.0 / 255.0); 6817 output.color = vec4f(finalRgb, finalA); 6818 } else { 6819 output.color = dirLm; 6820 } 6821 } else { 6822 let alpha_min = select(0.0, 1.0 / 255.0, dAtten > 0.00001); 6823 let finalA = max(dirLm.w, alpha_min); 6824 output.color = vec4f(dirLm.rgb, finalA); 6825 } 6826`,W3=` 6827#ifdef LIT_LIGHTMAP_BAKING_ADD_AMBIENT 6828 dDiffuseLight = ((dDiffuseLight - 0.5) * max(uniform.ambientBakeOcclusionContrast + 1.0, 0.0)) + 0.5; 6829 dDiffuseLight = dDiffuseLight + vec3f(uniform.ambientBakeOcclusionBrightness); 6830 dDiffuseLight = saturate3(dDiffuseLight); 6831 dDiffuseLight = dDiffuseLight * dAmbientLight; 6832#endif 6833#ifdef LIGHTMAP_RGBM 6834 var temp_color_rgbm = vec4f(dDiffuseLight, 1.0); 6835 temp_color_rgbm = vec4f(pow(temp_color_rgbm.rgb, vec3f(0.5)), temp_color_rgbm.a); 6836 temp_color_rgbm = vec4f(temp_color_rgbm.rgb / 8.0, temp_color_rgbm.a); 6837 let max_g_b = max(temp_color_rgbm.g, max(temp_color_rgbm.b, 1.0 / 255.0)); 6838 let max_rgb = max(temp_color_rgbm.r, max_g_b); 6839 temp_color_rgbm.a = clamp(max_rgb, 0.0, 1.0); 6840 temp_color_rgbm.a = ceil(temp_color_rgbm.a * 255.0) / 255.0; 6841 temp_color_rgbm = vec4f(temp_color_rgbm.rgb / temp_color_rgbm.a, temp_color_rgbm.a); 6842 output.color = temp_color_rgbm; 6843#else 6844 output.color = vec4f(dDiffuseLight, 1.0); 6845#endif 6846`,X3=` 6847uniform view_position: vec3f; 6848uniform light_globalAmbient: vec3f; 6849fn square(x: f32) -> f32 { 6850 return x*x; 6851} 6852fn saturate(x: f32) -> f32 { 6853 return clamp(x, 0.0, 1.0); 6854} 6855fn saturate3(x: vec3f) -> vec3f { 6856 return clamp(x, vec3f(0.0), vec3f(1.0)); 6857} 6858`,Y3=` 6859#define NINESLICED 6860varying vMask: vec2f; 6861varying vTiledUv: vec2f; 6862uniform innerOffset: vec4f; 6863uniform outerScale: vec2f; 6864uniform atlasRect: vec4f; 6865var<private>
6865 nineSlicedUv: vec2f; 6866`,j3=` 6867#define NINESLICED 6868#define NINESLICETILED 6869varying vMask: vec2f; 6870varying vTiledUv: vec2f; 6871uniform innerOffset: vec4f; 6872uniform outerScale: vec2f; 6873uniform atlasRect: vec4f; 6874var<private> nineSlicedUv: vec2f; 6875`,q3=` 6876fn bayer2(p: vec2f) -> f32 { 6877 return (2.0 * p.y + p.x + 1.0) % 4.0; 6878} 6879fn bayer4(p: vec2f) -> f32 { 6880 let p1: vec2f = p % vec2f(2.0); 6881 let p2: vec2f = floor(0.5 * (p % vec2f(4.0))); 6882 return 4.0 * bayer2(p1) + bayer2(p2); 6883} 6884fn bayer8(p: vec2f) -> f32 { 6885 let p1: vec2f = p % vec2f(2.0); 6886 let p2: vec2f = floor(0.5 * (p % vec2f(4.0))); 6887 let p4: vec2f = floor(0.25 * (p % vec2f(8.0))); 6888 return 4.0 * (4.0 * bayer2(p1) + bayer2(p2)) + bayer2(p4); 6889} 6890`,$3=` 6891varying vUv0: vec2f; 6892var source: texture_2d<f32>; 6893var sourceSampler: sampler; 6894#ifdef GAUSS 6895 uniform weight: array<f32, {SAMPLES}>; 6896#endif 6897uniform pixelOffset: vec2f; 6898@fragment 6899fn fragmentMain(input: FragmentInput) -> FragmentOutput { 6900 var output: FragmentOutput; 6901 var moments: vec3f = vec3f(0.0); 6902 let uv: vec2f = input.vUv0 - uniform.pixelOffset * (f32({SAMPLES}) * 0.5); 6903 for (var i: i32 = 0; i < {SAMPLES}; i = i + 1) {
6904 let c: vec4f = textureSample(source, sourceSampler, uv + uniform.pixelOffset * f32(i)); 6905 #ifdef GAUSS 6906 moments = moments + c.xyz * uniform.weight[i].element; 6907 #else 6908 moments = moments + c.xyz; 6909 #endif 6910 } 6911 #ifndef GAUSS 6912 moments = moments * (1.0 / f32({SAMPLES})); 6913 #endif 6914 output.color = vec4f(moments, 1.0); 6915 return output; 6916} 6917`,K3=` 6918uniform material_clearCoat: f32; 6919fn getClearCoat() { 6920 ccSpecularity = uniform.material_clearCoat; 6921 #ifdef STD_CLEARCOAT_TEXTURE 6922 ccSpecularity = ccSpecularity * textureSampleBias({STD_CLEARCOAT_TEXTURE_NAME}, {STD_CLEARCOAT_TEXTURE_NAME}Sampler, {STD_CLEARCOAT_TEXTURE_UV}, uniform.textureBias).{STD_CLEARCOAT_TEXTURE_CHANNEL}; 6923 #endif 6924 #ifdef STD_CLEARCOAT_VERTEX 6925 ccSpecularity = ccSpecularity * saturate(vVertexColor.{STD_CLEARCOAT_VERTEX_CHANNEL}); 6926 #endif 6927} 6928`,Z3=` 6929 uniform material_clearCoatGloss: f32; 6930fn getClearCoatGlossiness() { 6931 ccGlossiness = uniform.material_clearCoatGloss; 6932 #ifdef STD_CLEARCOATGLOSS_TEXTURE 6933 ccGlossiness = ccGlossiness * textureSampleBias({STD_CLEARCOATGLOSS_TEXTURE_NAME}, {STD_CLEARCOATGLOSS_TEXTURE_NAME}Sampler, {STD_CLEARCOATGLOSS_TEXTURE_UV}, uniform.textureBias).{STD_CLEARCOATGLOSS_TEXTURE_CHANNEL}; 6934 #endif 6935 #ifdef STD_CLEARCOATGLOSS_VERTEX 6936 ccGlossiness = ccGlossiness * saturate(vVertexColor.{STD_CLEARCOATGLOSS_VERTEX_CHANNEL}); 6937 #endif 6938 #ifdef STD_CLEARCOATGLOSS_INVERT 6939 ccGlossiness = 1.0 - ccGlossiness; 6940 #endif 6941 ccGlossiness += 0.0000001; 6942} 6943`,Q3=` 6944#ifdef STD_CLEARCOATNORMAL_TEXTURE 6945 uniform material_clearCoatBumpiness: f32; 6946#endif 6947fn getClearCoatNormal() { 6948#ifdef STD_CLEARCOATNORMAL_TEXTURE 6949 var normalMap: vec3f = {STD_CLEARCOATNORMAL_TEXTURE_DECODE}(textureSampleBias({STD_CLEARCOATNORMAL_TEXTURE_NAME}, {STD_CLEARCOATNORMAL_TEXTURE_NAME}Sampler, {STD_CLEARCOATNORMAL_TEXTURE_UV}, uniform.textureBias)); 6950 normalMap = mix(vec3f(0.0, 0.0, 1.0), normalMap, uniform.material_clearCoatBumpiness); 6951 ccNormalW = normalize(dTBN * normalMap); 6952#else 6953 ccNormalW = dVertexNormalW; 6954#endif 6955} 6956`,J3=` 6957struct FaceCoords { 6958 uv: vec2f, 6959 faceIndex: f32, 6960 tileOffset: vec2f, 6961} 6962fn getCubemapFaceCoordinates(dir: vec3f) -> FaceCoords { 6963 var faceIndex: f32; 6964 var tileOffset: vec2f; 6965 var uv: vec2f; 6966 let vAbs: vec3f = abs(dir); 6967 var ma: f32; 6968 if (vAbs.z >= vAbs.x && vAbs.z >= vAbs.y) { 6969 let is_neg_z = dir.z < 0.0; 6970 faceIndex = select(4.0, 5.0, is_neg_z); 6971 ma = 0.5 / vAbs.z; 6972 uv = vec2f(select(dir.x, -dir.x, is_neg_z), -dir.y); 6973 tileOffset = vec2f(2.0, select(0.0, 1.0, is_neg_z)); 6974 } else if (vAbs.y >= vAbs.x) { 6975 let is_neg_y = dir.y < 0.0; 6976 faceIndex = select(2.0, 3.0, is_neg_y); 6977 ma = 0.5 / vAbs.y; 6978 uv = vec2f(dir.x, select(dir.z, -dir.z, is_neg_y)); 6979 tileOffset = vec2f(1.0, select(0.0, 1.0, is_neg_y)); 6980 } else { 6981 let is_neg_x = dir.x < 0.0; 6982 faceIndex = select(0.0, 1.0, is_neg_x); 6983 ma = 0.5 / vAbs.x; 6984 uv = vec2f(select(-dir.z, dir.z, is_neg_x), -dir.y); 6985 tileOffset = vec2f(0.0, select(0.0, 1.0, is_neg_x)); 6986 } 6987 uv = uv * ma + 0.5; 6988 return FaceCoords(uv, faceIndex, tileOffset); 6989} 6990fn getCubemapAtlasCoordinates(omniAtlasViewport: vec3f, shadowEdgePixels: f32, shadowTextureResolution: f32, dir: vec3f) -> vec2f { 6991 let faceData: FaceCoords = getCubemapFaceCoordinates(dir); 6992 var uv: vec2f = faceData.uv; 6993 let tileOffset: vec2f = faceData.tileOffset; 6994 let atlasFaceSize: f32 = omniAtlasViewport.z; 6995 let tileSize: f32 = shadowTextureResolution * atlasFaceSize; 6996 var offset: f32 = shadowEdgePixels / tileSize; 6997 uv = uv * (1.0 - offset * 2.0) + offset; 6998 uv = uv * atlasFaceSize; 6999 uv = uv + tileOffset * atlasFaceSize; 7000 uv = uv + omniAtlasViewport.xy; 7001 return uv; 7002} 7003`,eF=` 7004fn _getCookieClustered(tex: texture_2d<f32>, texSampler: sampler, uv: vec2f, intensity: f32, cookieChannel: vec4f) -> vec3f { 7005 let pixel: vec4f = mix(vec4f(1.0), textureSampleLevel(tex, texSampler, uv, 0.0), intensity); 7006 let isRgb: bool = dot(cookieChannel.rgb, vec3f(1.0)) == 3.0; 7007 return select(vec3f(dot(pixel, cookieChannel)), pixel.rgb, isRgb); 7008} 7009fn getCookie2DClustered(tex: texture_2d<f32>, texSampler: sampler, transform: mat4x4f, worldPosition: vec3f, intensity: f32, cookieChannel: vec4f) -> vec3f {
7010 let projPos: vec4f = transform * vec4f(worldPosition, 1.0); 7011 return _getCookieClustered(tex, texSampler, projPos.xy / projPos.w, intensity, cookieChannel); 7012} 7013fn getCookieCubeClustered(tex: texture_2d<f32>, texSampler: sampler, dir: vec3f, intensity: f32, cookieChannel: vec4f, shadowTextureResolution: f32, shadowEdgePixels: f32, omniAtlasViewport: vec3f) -> vec3f { 7014 let uv: vec2f = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, dir); 7015 return _getCookieClustered(tex, texSampler, uv, intensity, cookieChannel); 7016} 7017`,tF=` 7018fn _getShadowCoordPerspZbuffer(shadowMatrix: mat4x4f, shadowParams: vec4f, wPos: vec3f) -> vec3f { 7019 var projPos = shadowMatrix * vec4f(wPos, 1.0); 7020 return projPos.xyz / projPos.w; 7021} 7022fn getShadowCoordPerspZbufferNormalOffset(shadowMatrix: mat4x4f, shadowParams: vec4f, normal: vec3f) -> vec3f { 7023 let wPos: vec3f = vPositionW + normal * shadowParams.y; 7024 return _getShadowCoordPerspZbuffer(shadowMatrix, shadowParams, wPos); 7025} 7026fn normalOffsetPointShadow(shadowParams: vec4f, lightPos: vec3f, lightDir: vec3f, lightDirNorm: vec3f, normal: vec3f) -> vec3f { 7027 let distScale: f32 = length(lightDir); 7028 let wPos: vec3f = vPositionW + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale; 7029 let dir: vec3f = wPos - lightPos; 7030 return dir; 7031} 7032#if defined(CLUSTER_SHADOW_TYPE_PCF1) 7033 fn getShadowOmniClusteredPCF1(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowParams: vec4f, omniAtlasViewport: vec3f, shadowEdgePixels: f32, lightDir: vec3f) -> f32 { 7034 let shadowTextureResolution: f32 = shadowParams.x; 7035 let uv: vec2f = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir); 7036 let shadowZ: f32 = length(lightDir) * shadowParams.w + shadowParams.z; 7037 return textureSampleCompareLevel(shadowMap, shadowMapSampler, uv, shadowZ); 7038 } 7039#endif 7040#if defined(CLUSTER_SHADOW_TYPE_PCF3) 7041 fn getShadowOmniClusteredPCF3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowParams: vec4f, omniAtlasViewport: vec3f, shadowEdgePixels: f32, lightDir: vec3f) -> f32 { 7042 let shadowTextureResolution: f32 = shadowParams.x; 7043 let uv: vec2f = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir); 7044 let shadowZ: f32 = length(lightDir) * shadowParams.w + shadowParams.z; 7045 let shadowCoord: vec3f = vec3f(uv, shadowZ); 7046 return getShadowPCF3x3(shadowMap, shadowMapSampler, shadowCoord, shadowParams); 7047 } 7048#endif 7049#if defined(CLUSTER_SHADOW_TYPE_PCF5) 7050 fn getShadowOmniClusteredPCF5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowParams: vec4f, omniAtlasViewport: vec3f, shadowEdgePixels: f32, lightDir: vec3f) -> f32 { 7051 let shadowTextureResolution: f32 = shadowParams.x; 7052 let uv: vec2f = getCubemapAtlasCoordinates(omniAtlasViewport, shadowEdgePixels, shadowTextureResolution, lightDir); 7053 let shadowZ: f32 = length(lightDir) * shadowParams.w + shadowParams.z; 7054 let shadowCoord: vec3f = vec3f(uv, shadowZ); 7055 return getShadowPCF5x5(shadowMap, shadowMapSampler, shadowCoord, shadowParams); 7056 } 7057#endif 7058#if defined(CLUSTER_SHADOW_TYPE_PCF1) 7059 fn getShadowSpotClusteredPCF1(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 { 7060 return textureSampleCompareLevel(shadowMap, shadowMapSampler, shadowCoord.xy, shadowCoord.z); 7061 } 7062#endif 7063 #if defined(CLUSTER_SHADOW_TYPE_PCF3) 7064 fn getShadowSpotClusteredPCF3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 { 7065 return getShadowSpotPCF3x3(shadowMap, shadowMapSampler, shadowCoord, shadowParams); 7066 } 7067#endif 7068 #if defined(CLUSTER_SHADOW_TYPE_PCF5) 7069 fn getShadowSpotClusteredPCF5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 { 7070 return getShadowPCF5x5(shadowMap, shadowMapSampler, shadowCoord, shadowParams); 7071 } 7072#endif 7073`,sF=` 7074#include "lightBufferDefinesPS" 7075#include "clusteredLightUtilsPS" 7076#ifdef CLUSTER_COOKIES 7077 #include "clusteredLightCookiesPS" 7078#endif 7079#ifdef CLUSTER_SHADOWS 7080 #include "clusteredLightShadowsPS" 7081#endif 7082var clusterWorldTexture: texture_2d<u32>; 7083var lightsTexture: texture_2d<uff>; 7084#ifdef CLUSTER_SHADOWS 7085 var shadowAtlasTexture: texture_depth_2d; 7086 var shadowAtlasTextureSampler: sampler_comparison; 7087#endif 7088#ifdef CLUSTER_COOKIES 7089 var cookieAtlasTexture: texture_2d<f32>; 7090 var cookieAtlasTextureSampler: sampler; 7091#endif
7092uniform clusterMaxCells: i32; 7093uniform numClusteredLights: i32; 7094uniform clusterTextureWidth: i32; 7095uniform clusterCellsCountByBoundsSize: vec3f; 7096uniform clusterBoundsMin: vec3f; 7097uniform clusterBoundsDelta: vec3f; 7098uniform clusterCellsDot: vec3i; 7099uniform clusterCellsMax: vec3i; 7100uniform shadowAtlasParams: vec2f; 7101struct ClusterLightData { 7102 position: vec3f, 7103 lightIndex: i32, 7104 direction: vec3f, 7105 shape: u32, 7106 color: vec3f, 7107 shadowIntensity: f32, 7108 range: f32, 7109 biasesData: f32, 7110 cookieIntensity: f32, 7111 isSpot: bool, 7112 falloffModeLinear: bool, 7113 isDynamic: bool, 7114 isLightmapped: bool 7115} 7116struct ClusterLightSpotData { 7117 innerConeAngleCos: f32, 7118 outerConeAngleCos: f32 7119} 7120struct ClusterLightAreaData { 7121 halfWidth: vec3f, 7122 halfHeight: vec3f 7123} 7124struct ClusterLightShadowData { 7125 shadowBias: f32, 7126 shadowNormalBias: f32 7127} 7128var<private> lightProjectionMatrix: mat4x4f; 7129var<private> clusterLightData_flags: u32; 7130var<private> clusterLightData_anglesData: f32; 7131var<private> clusterLightData_colorBFlagsData: u32; 7132fn sampleLightTextureF(lightIndex: i32, index: i32) -> vec4f { 7133 return textureLoad(lightsTexture, vec2<i32>(index, lightIndex), 0); 7134} 7135fn decodeClusterLightCore(lightIndex: i32) -> ClusterLightData { 7136 var clusterLightData: ClusterLightData; 7137 clusterLightData.lightIndex = lightIndex; 7138 let halfData: vec4f = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_COLOR_ANGLES_BIAS}); 7139 clusterLightData_anglesData = halfData.z; 7140 clusterLightData.biasesData = halfData.w; 7141 clusterLightData_colorBFlagsData = bitcast<u32>(halfData.y); 7142 let colorRG: vec2f = unpack2x16float(bitcast<u32>(halfData.x)); 7143 let colorB_flags: vec2f = unpack2x16float(clusterLightData_colorBFlagsData); 7144 clusterLightData.color = vec3f(colorRG, colorB_flags.x) * {LIGHT_COLOR_DIVIDER}; 7145 let lightPosRange: vec4f = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_POSITION_RANGE}); 7146 clusterLightData.position = lightPosRange.xyz; 7147 clusterLightData.range = lightPosRange.w; 7148 let lightDir_Flags: vec4f = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_DIRECTION_FLAGS}); 7149 clusterLightData.direction = lightDir_Flags.xyz; 7150 clusterLightData_flags = bitcast<u32>(lightDir_Flags.w); 7151 clusterLightData.isSpot = (clusterLightData_flags & (1u << 30u)) != 0u; 7152 clusterLightData.shape = (clusterLightData_flags >> 28u) & 0x3u; 7153 clusterLightData.falloffModeLinear = (clusterLightData_flags & (1u << 27u)) == 0u; 7154 clusterLightData.shadowIntensity = f32((clusterLightData_flags >> 0u) & 0xFFu) / 255.0; 7155 clusterLightData.cookieIntensity = f32((clusterLightData_flags >> 8u) & 0xFFu) / 255.0; 7156 clusterLightData.isDynamic = (clusterLightData_flags & (1u << 22u)) != 0u; 7157 clusterLightData.isLightmapped = (clusterLightData_flags & (1u << 21u)) != 0u; 7158 return clusterLightData; 7159} 7160fn decodeClusterLightSpot() -> ClusterLightSpotData { 7161 let angleFlags: u32 = (clusterLightData_colorBFlagsData >> 16u) & 0xFFFFu; 7162 let angleValues: vec2f = unpack2x16float(bitcast<u32>(clusterLightData_anglesData)); 7163 let innerVal: f32 = angleValues.x; 7164 let outerVal: f32 = angleValues.y; 7165 let innerIsVersine: bool = (angleFlags & 1u) != 0u; 7166 let outerIsVersine: bool = ((angleFlags >> 1u) & 1u) != 0u; 7167 return ClusterLightSpotData( 7168 select(innerVal, 1.0 - innerVal, innerIsVersine), 7169 select(outerVal, 1.0 - outerVal, outerIsVersine) 7170 ); 7171} 7172fn decodeClusterLightOmniAtlasViewport(lightIndex: i32) -> vec3f { 7173 return sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_0}).xyz; 7174} 7175fn decodeClusterLightAreaData(lightIndex: i32) -> ClusterLightAreaData { 7176 return ClusterLightAreaData( 7177 sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_AREA_DATA_WIDTH}).xyz, 7178 sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_AREA_DATA_HEIGHT}).xyz 7179 ); 7180} 7181fn decodeClusterLightProjectionMatrixData(lightIndex: i32) -> mat4x4f { 7182 let m0: vec4f = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_0}); 7183 let m1: vec4f = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_1}); 7184 let m2: vec4f = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_2}); 7185 let m3: vec4f = sampleLightTextureF(lightIndex, {CLUSTER_TEXTURE_PROJ_MAT_3}); 7186 return mat4x4f(m0, m1, m2, m3); 7187} 7188fn decodeClusterLightShadowData(biasesData: f32) -> ClusterLightShadowData { 7189 let biases: vec2f = unpack2x16float(bitcast<u32>(biasesData)); 7190 return ClusterLightShadowData(biases.x, biases.y); 7191} 7192fn decodeClusterLightCookieData() -> vec4f { 7193 let cookieFlags: u32 = (clusterLightData_flags >> 23u) & 0x0Fu; 7194 let mask_uvec: vec4<u32> = vec4<u32>(cookieFlags) & vec4<u32>(1u, 2u, 4u, 8u); 7195 return step(vec4f(1.0), vec4f(mask_uvec)); 7196} 7197fn evaluateLight( 7198 light: ClusterLightData, 7199 worldNormal: vec3f, 7200 viewDir: vec3f, 7201 reflectionDir: vec3f, 7202#if defined(LIT_CLEARCOAT) 7203 clearcoatReflectionDir: vec3f, 7204#endif 7205 gloss: f32, 7206 specularity: vec3f, 7207 geometricNormal: vec3f, 7208 tbn: mat3x3f, 7209#if defined(LIT_IRIDESCENCE) 7210 iridescenceFresnel: vec3f, 7211#endif 7212 clearcoat_worldNormal: vec3f, 7213 clearcoat_gloss: f32, 7214 sheen_gloss: f32, 7215 iridescence_intensity: f32 7216) { 7217 var cookieAttenuation: vec3f = vec3f(1.0); 7218 var diffuseAttenuation: f32 = 1.0; 7219 var falloffAttenuation: f32 = 1.0; 7220 let lightDirW: vec3f = evalOmniLight(light.position); 7221 let lightDirNormW: vec3f = normalize(lightDirW); 7222 #ifdef CLUSTER_AREALIGHTS 7223 if (light.shape != {LIGHTSHAPE_PUNCTUAL}) { 7224 let areaData: ClusterLightAreaData = decodeClusterLightAreaData(light.lightIndex); 7225 if (light.shape == {LIGHTSHAPE_RECT}) { 7226 calcRectLightValues(light.position, areaData.halfWidth, areaData.halfHeight); 7227 } else if (light.shape == {LIGHTSHAPE_DISK}) { 7228 calcDiskLightValues(light.position, areaData.halfWidth, areaData.halfHeight); 7229 } else { 7230 calcSphereLightValues(light.position, areaData.halfWidth, areaData.halfHeight); 7231 } 7232 falloffAttenuation = getFalloffWindow(light.range, lightDirW); 7233 } else 7234 #endif 7235 { 7236 if (light.falloffModeLinear) { 7237 falloffAttenuation = getFalloffLinear(light.range, lightDirW); 7238 } else { 7239 falloffAttenuation = getFalloffInvSquared(light.range, lightDirW); 7240 } 7241 } 7242 if (falloffAttenuation > 0.00001) { 7243 #ifdef CLUSTER_AREALIGHTS 7244 if (light.shape != {LIGHTSHAPE_PUNCTUAL}) { 7245 if (light.shape == {LIGHTSHAPE_RECT}) { 7246 diffuseAttenuation = getRectLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0; 7247 } else if (light.shape == {LIGHTSHAPE_DISK}) { 7248 diffuseAttenuation = getDiskLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0; 7249 } else { 7250 diffuseAttenuation = getSphereLightDiffuse(worldNormal, viewDir, lightDirW, lightDirNormW) * 16.0; 7251 } 7252 } else 7253 #endif 7254 { 7255 falloffAttenuation = falloffAttenuation * getLightDiffuse(worldNormal, viewDir, lightDirNormW); 7256 } 7257 if (light.isSpot) { 7258 let spotData: ClusterLightSpotData = decodeClusterLightSpot(); 7259 falloffAttenuation = falloffAttenuation * getSpotEffect(light.direction, spotData.innerConeAngleCos, spotData.outerConeAngleCos, lightDirNormW); 7260 } 7261 #if defined(CLUSTER_COOKIES) || defined(CLUSTER_SHADOWS) 7262 if (falloffAttenuation > 0.00001) { 7263 if (light.shadowIntensity > 0.0 || light.cookieIntensity > 0.0) { 7264 var omniAtlasViewport: vec3f = vec3f(0.0); 7265 if (light.isSpot) { 7266 lightProjectionMatrix = decodeClusterLightProjectionMatrixData(light.lightIndex); 7267 } else { 7268 omniAtlasViewport = decodeClusterLightOmniAtlasViewport(light.lightIndex); 7269 } 7270 let shadowTextureResolution: f32 = uniform.shadowAtlasParams.x; 7271 let shadowEdgePixels: f32 = uniform.shadowAtlasParams.y; 7272 #ifdef CLUSTER_COOKIES 7273 if (light.cookieIntensity > 0.0) {
7274 let cookieChannelMask: vec4f = decodeClusterLightCookieData(); 7275 if (light.isSpot) { 7276 cookieAttenuation = getCookie2DClustered(cookieAtlasTexture, cookieAtlasTextureSampler, lightProjectionMatrix, vPositionW, light.cookieIntensity, cookieChannelMask); 7277 } else { 7278 cookieAttenuation = getCookieCubeClustered(cookieAtlasTexture, cookieAtlasTextureSampler, lightDirW, light.cookieIntensity, cookieChannelMask, shadowTextureResolution, shadowEdgePixels, omniAtlasViewport); 7279 } 7280 } 7281 #endif 7282 #ifdef CLUSTER_SHADOWS 7283 if (light.shadowIntensity > 0.0) { 7284 let shadowData: ClusterLightShadowData = decodeClusterLightShadowData(light.biasesData); 7285 let shadowParams: vec4f = vec4f(shadowTextureResolution, shadowData.shadowNormalBias, shadowData.shadowBias, 1.0 / light.range); 7286 if (light.isSpot) { 7287 let shadowCoord: vec3f = getShadowCoordPerspZbufferNormalOffset(lightProjectionMatrix, shadowParams, geometricNormal); 7288 #if defined(CLUSTER_SHADOW_TYPE_PCF1) 7289 let shadow: f32 = getShadowSpotClusteredPCF1(shadowAtlasTexture, shadowAtlasTextureSampler, shadowCoord, shadowParams); 7290 #elif defined(CLUSTER_SHADOW_TYPE_PCF3) 7291 let shadow: f32 = getShadowSpotClusteredPCF3(shadowAtlasTexture, shadowAtlasTextureSampler, shadowCoord, shadowParams); 7292 #elif defined(CLUSTER_SHADOW_TYPE_PCF5) 7293 let shadow: f32 = getShadowSpotClusteredPCF5(shadowAtlasTexture, shadowAtlasTextureSampler, shadowCoord, shadowParams); 7294 #elif defined(CLUSTER_SHADOW_TYPE_PCSS) 7295 let shadow: f32 = getShadowSpotClusteredPCSS(shadowAtlasTexture, shadowAtlasTextureSampler, shadowCoord, shadowParams); 7296 #endif 7297 falloffAttenuation = falloffAttenuation * mix(1.0, shadow, light.shadowIntensity); 7298 } else { 7299 let dir: vec3f = normalOffsetPointShadow(shadowParams, light.position, lightDirW, lightDirNormW, geometricNormal); 7300 #if defined(CLUSTER_SHADOW_TYPE_PCF1) 7301 let shadow: f32 = getShadowOmniClusteredPCF1(shadowAtlasTexture, shadowAtlasTextureSampler, shadowParams, omniAtlasViewport, shadowEdgePixels, dir); 7302 #elif defined(CLUSTER_SHADOW_TYPE_PCF3) 7303 let shadow: f32 = getShadowOmniClusteredPCF3(shadowAtlasTexture, shadowAtlasTextureSampler, shadowParams, omniAtlasViewport, shadowEdgePixels, dir); 7304 #elif defined(CLUSTER_SHADOW_TYPE_PCF5) 7305 let shadow: f32 = getShadowOmniClusteredPCF5(shadowAtlasTexture, shadowAtlasTextureSampler, shadowParams, omniAtlasViewport, shadowEdgePixels, dir); 7306 #endif 7307 falloffAttenuation = falloffAttenuation * mix(1.0, shadow, light.shadowIntensity); 7308 } 7309 } 7310 #endif 7311 } 7312 } 7313 #endif 7314 #ifdef CLUSTER_AREALIGHTS 7315 if (light.shape != {LIGHTSHAPE_PUNCTUAL}) { 7316 { 7317 var areaDiffuse: vec3f = (diffuseAttenuation * falloffAttenuation) * light.color * cookieAttenuation; 7318 #if defined(LIT_SPECULAR) 7319 areaDiffuse = mix(areaDiffuse, vec3f(0.0), dLTCSpecFres); 7320 #endif 7321 dDiffuseLight = dDiffuseLight + areaDiffuse; 7322 } 7323 #ifdef LIT_SPECULAR 7324 var areaLightSpecular: f32; 7325 if (light.shape == {LIGHTSHAPE_RECT}) { 7326 areaLightSpecular = getRectLightSpecular(worldNormal, viewDir); 7327 } else if (light.shape == {LIGHTSHAPE_DISK}) { 7328 areaLightSpecular = getDiskLightSpecular(worldNormal, viewDir); 7329 } else { 7330 areaLightSpecular = getSphereLightSpecular(worldNormal, viewDir); 7331 } 7332 dSpecularLight = dSpecularLight + dLTCSpecFres * areaLightSpecular * falloffAttenuation * light.color * cookieAttenuation; 7333 #ifdef LIT_CLEARCOAT 7334 var areaLightSpecularCC: f32; 7335 if (light.shape == {LIGHTSHAPE_RECT}) { 7336 areaLightSpecularCC = getRectLightSpecular(clearcoat_worldNormal, viewDir); 7337 } else if (light.shape == {LIGHTSHAPE_DISK}) { 7338 areaLightSpecularCC = getDiskLightSpecular(clearcoat_worldNormal, viewDir); 7339 } else { 7340 areaLightSpecularCC = getSphereLightSpecular(clearcoat_worldNormal, viewDir); 7341 } 7342 ccSpecularLight = ccSpecularLight + ccLTCSpecFres * areaLightSpecularCC * falloffAttenuation * light.color * cookieAttenuation; 7343 #endif 7344 #endif 7345 } else 7346 #endif 7347 { 7348 { 7349 var punctualDiffuse: vec3f = falloffAttenuation * light.color * cookieAttenuation; 7350 #if defined(CLUSTER_AREALIGHTS) 7351 #if defined(LIT_SPECULAR) 7352 punctualDiffuse = mix(punctualDiffuse, vec3f(0.0), specularity); 7353 #endif 7354 #endif 7355 dDiffuseLight = dDiffuseLight + punctualDiffuse; 7356 } 7357 #ifdef LIT_SPECULAR 7358 let halfDir: vec3f = normalize(-lightDirNormW + viewDir); 7359 #ifdef LIT_SPECULAR_FRESNEL 7360 dSpecularLight = dSpecularLight + 7361 getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, lightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * 7362 getFresnel( 7363 dot(viewDir, halfDir), 7364 gloss, 7365 specularity 7366 #if defined(LIT_IRIDESCENCE) 7367 , iridescenceFresnel, 7368 iridescence_intensity 7369 #endif 7370 ); 7371 #else 7372 dSpecularLight = dSpecularLight + getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, lightDirNormW, gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * specularity; 7373 #endif 7374 #ifdef LIT_CLEARCOAT 7375 #ifdef LIT_SPECULAR_FRESNEL 7376 ccSpecularLight = ccSpecularLight + getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat_worldNormal, viewDir, lightDirNormW, clearcoat_gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation * getFresnelCC(dot(viewDir, halfDir)); 7377 #else 7378 ccSpecularLight = ccSpecularLight + getLightSpecular(halfDir, clearcoatReflectionDir, clearcoat_worldNormal, viewDir, lightDirNormW, clearcoat_gloss, tbn) * falloffAttenuation * light.color * cookieAttenuation; 7379 #endif 7380 #endif 7381 #ifdef LIT_SHEEN 7382 sSpecularLight = sSpecularLight + getLightSpecularSheen(halfDir, worldNormal, viewDir, lightDirNormW, sheen_gloss) * falloffAttenuation * light.color * cookieAttenuation; 7383 #endif 7384 #endif 7385 } 7386 } 7387 dAtten = falloffAttenuation; 7388 dLightDirNormW = lightDirNormW; 7389} 7390fn evaluateClusterLight( 7391 lightIndex: i32, 7392 worldNormal: vec3f, 7393 viewDir: vec3f, 7394 reflectionDir: vec3f, 7395#if defined(LIT_CLEARCOAT) 7396 clearcoatReflectionDir: vec3f, 7397#endif 7398 gloss: f32, 7399 specularity: vec3f, 7400 geometricNormal: vec3f, 7401 tbn: mat3x3f, 7402#if defined(LIT_IRIDESCENCE) 7403 iridescenceFresnel: vec3f, 7404#endif 7405 clearcoat_worldNormal: vec3f, 7406 clearcoat_gloss: f32, 7407 sheen_gloss: f32, 7408 iridescence_intensity: f32 7409) { 7410 let clusterLightData: ClusterLightData = decodeClusterLightCore(lightIndex); 7411 #ifdef CLUSTER_MESH_DYNAMIC_LIGHTS 7412 let acceptLightMask: bool = clusterLightData.isDynamic; 7413 #else 7414 let acceptLightMask: bool = clusterLightData.isLightmapped; 7415 #endif 7416 if (acceptLightMask) { 7417 evaluateLight( 7418 clusterLightData, 7419 worldNormal, 7420 viewDir, 7421 reflectionDir, 7422#if defined(LIT_CLEARCOAT) 7423 clearcoatReflectionDir, 7424#endif 7425 gloss, 7426 specularity, 7427 geometricNormal, 7428 tbn, 7429#if defined(LIT_IRIDESCENCE) 7430 iridescenceFresnel, 7431#endif 7432 clearcoat_worldNormal, 7433 clearcoat_gloss, 7434 sheen_gloss, 7435 iridescence_intensity 7436 ); 7437 } 7438} 7439fn addClusteredLights( 7440 worldNormal: vec3f, 7441 viewDir: vec3f, 7442 reflectionDir: vec3f, 7443#if defined(LIT_CLEARCOAT) 7444 clearcoatReflectionDir: vec3f, 7445#endif 7446 gloss: f32, 7447 specularity: vec3f, 7448 geometricNormal: vec3f, 7449 tbn: mat3x3f, 7450#if defined(LIT_IRIDESCENCE) 7451 iridescenceFresnel: vec3f, 7452#endif 7453 clearcoat_worldNormal: vec3f, 7454 clearcoat_gloss: f32, 7455 sheen_gloss: f32, 7456 iridescence_intensity: f32 7457) { 7458 if (uniform.numClusteredLights <= 1) { 7459 return; 7460 } 7461 let cellCoords: vec3i = vec3i(floor((vPositionW - uniform.clusterBoundsMin) * uniform.clusterCellsCountByBoundsSize)); 7462 if (!(any(cellCoords < vec3i(0)) || any(cellCoords >= uniform.clusterCellsMax))) { 7463 let cellIndex: i32 = cellCoords.x * uniform.clusterCellsDot.x + cellCoords.y * uniform.clusterCellsDot.y + cell
7463Coords.z * uniform.clusterCellsDot.z; 7464 let clusterV: i32 = cellIndex / uniform.clusterTextureWidth; 7465 let clusterU: i32 = cellIndex - clusterV * uniform.clusterTextureWidth; 7466 for (var lightCellIndex: i32 = 0; lightCellIndex < uniform.clusterMaxCells; lightCellIndex = lightCellIndex + 1) { 7467 let lightIndex: u32 = textureLoad(clusterWorldTexture, vec2<i32>(clusterU + lightCellIndex, clusterV), 0).r; 7468 if (lightIndex == 0u) { 7469 break; 7470 } 7471 evaluateClusterLight( 7472 i32(lightIndex), 7473 worldNormal, 7474 viewDir, 7475 reflectionDir, 7476#if defined(LIT_CLEARCOAT) 7477 clearcoatReflectionDir, 7478#endif 7479 gloss, 7480 specularity, 7481 geometricNormal, 7482 tbn, 7483#if defined(LIT_IRIDESCENCE) 7484 iridescenceFresnel, 7485#endif 7486 clearcoat_worldNormal, 7487 clearcoat_gloss, 7488 sheen_gloss, 7489 iridescence_intensity 7490 ); 7491 } 7492 } 7493}`,iF=` 7494fn combineColor(albedo: vec3f, sheenSpecularity: vec3f, clearcoatSpecularity: f32) -> vec3f { 7495 var ret: vec3f = vec3f(0.0); 7496 #ifdef LIT_OLD_AMBIENT 7497 ret = ret + ((dDiffuseLight - uniform.light_globalAmbient) * albedo + uniform.material_ambient * uniform.light_globalAmbient); 7498 #else 7499 ret = ret + (albedo * dDiffuseLight); 7500 #endif 7501 #ifdef LIT_SPECULAR 7502 ret = ret + dSpecularLight; 7503 #endif 7504 #ifdef LIT_REFLECTIONS 7505 ret = ret + (dReflection.rgb * dReflection.a); 7506 #endif 7507 #ifdef LIT_SHEEN 7508 let sheenScaling: f32 = 1.0 - max(max(sheenSpecularity.r, sheenSpecularity.g), sheenSpecularity.b) * 0.157; 7509 ret = ret * sheenScaling + (sSpecularLight + sReflection.rgb) * sheenSpecularity; 7510 #endif 7511 #ifdef LIT_CLEARCOAT 7512 let clearCoatScaling: f32 = 1.0 - ccFresnel * clearcoatSpecularity; 7513 ret = ret * clearCoatScaling + (ccSpecularLight + ccReflection) * clearcoatSpecularity; 7514 #endif 7515 return ret; 7516} 7517`,rF=` 7518 varying uv0: vec2f; 7519 var blitTexture: texture_2d<f32>; 7520 var blitTextureSampler : sampler; 7521 @fragment 7522 fn fragmentMain(input : FragmentInput) -> FragmentOutput { 7523 var output: FragmentOutput; 7524 output.color = textureSample(blitTexture, blitTextureSampler, input.uv0); 7525 return output; 7526 } 7527`,aF=` 7528 varying uv0: vec2f; 7529 uniform invViewProj: mat4x4<f32>; 7530 var blitTexture: texture_cube<f32>; 7531 var blitTextureSampler : sampler; 7532 @fragment 7533 fn fragmentMain(input : FragmentInput) -> FragmentOutput { 7534 var output: FragmentOutput; 7535 var projPos = vec4f(input.uv0 * 2.0 - 1.0, 0.5, 1.0); 7536 var worldPos = uniform.invViewProj * projPos; 7537 output.color = textureSample(blitTexture, blitTextureSampler, worldPos.xyz); 7538 return output; 7539 } 7540`,nF=` 7541 attribute vertex_position: vec2f; 7542 varying uv0: vec2f; 7543 @vertex 7544 fn vertexMain(input: VertexInput) -> VertexOutput { 7545 var output: VertexOutput; 7546 output.position = vec4f(input.vertex_position, 0.5, 1.0); 7547 output.uv0 = input.vertex_position * 0.5 + vec2f(0.5, 0.5); 7548 output.uv0.y = 1.0 - output.uv0.y; 7549 return output; 7550 } 7551`,oF=` 7552#if LIT_CUBEMAP_PROJECTION == BOX 7553 uniform envBoxMin: vec3f; 7554 uniform envBoxMax: vec3f; 7555#endif 7556fn cubeMapProject(nrdir: vec3f) -> vec3f { 7557 #if LIT_CUBEMAP_PROJECTION == NONE 7558 return cubeMapRotate(nrdir); 7559 #endif 7560 #if LIT_CUBEMAP_PROJECTION == BOX 7561 let nrdir_rotated: vec3f = cubeMapRotate(nrdir); 7562 let rbmax: vec3f = (uniform.envBoxMax - vPositionW) / nrdir_rotated; 7563 let rbmin: vec3f = (uniform.envBoxMin - vPositionW) / nrdir_rotated; 7564 let rbminmax: vec3f = select(rbmin, rbmax, nrdir_rotated > vec3f(0.0)); 7565 let fa: f32 = min(min(rbminmax.x, rbminmax.y), rbminmax.z); 7566 let posonbox: vec3f = vPositionW + nrdir_rotated * fa; 7567 let envBoxPos: vec3f = (uniform.envBoxMin + uniform.envBoxMax) * 0.5; 7568 return normalize(posonbox - envBoxPos); 7569 #endif 7570} 7571`,lF=` 7572#ifdef CUBEMAP_ROTATION 7573uniform cubeMapRotationMatrix: mat3x3f; 7574#endif 7575fn cubeMapRotate(refDir: vec3f) -> vec3f { 7576#ifdef CUBEMAP_ROTATION 7577 return refDir * uniform.cubeMapRotationMatrix; 7578#else 7579 return refDir; 7580#endif 7581} 7582`,cF=` 7583#ifdef DEBUG_ALBEDO_PASS 7584output.color = vec4(gammaCorrectOutput(dAlbedo), 1.0); 7585#endif 7586#ifdef DEBUG_UV0_PASS 7587output.color = vec4f(litArgs_albedo , 1.0); 7588#endif 7589#ifdef DEBUG_WORLD_NORMAL_PASS 7590output.color = vec4f(litArgs_worldNormal * 0.5 + 0.5, 1.0); 7591#endif 7592#ifdef DEBUG_OPACITY_PASS 7593output.color = vec4f(vec3f(litArgs_opacity) , 1.0); 7594#endif 7595#ifdef DEBUG_SPECULARITY_PASS 7596output.color = vec4f(litArgs_specularity, 1.0); 7597#endif 7598#ifdef DEBUG_GLOSS_PASS 7599output.color = vec4f(vec3f(litArgs_gloss) , 1.0); 7600#endif 7601#ifdef DEBUG_METALNESS_PASS 7602output.color = vec4f(vec3f(litArgs_metalness) , 1.0); 7603#endif 7604#ifdef DEBUG_AO_PASS 7605output.color = vec4f(vec3f(litArgs_ao) , 1.0); 7606#endif 7607#ifdef DEBUG_EMISSION_PASS 7608output.color = vec4f(gammaCorrectOutput(litArgs_emission), 1.0); 7609#endif 7610`,hF=` 7611#ifdef DEBUG_LIGHTING_PASS 7612 litArgs_albedo = vec3f(0.5); 7613#endif 7614#ifdef DEBUG_UV0_PASS 7615#ifdef VARYING_VUV0 7616 litArgs_albedo = vec3f(vUv0, 0.0); 7617#else 7618 litArgs_albedo = vec3f(0.0); 7619#endif 7620#endif 7621`,dF=` 7622#ifndef _DECODE_INCLUDED_ 7623#define _DECODE_INCLUDED_ 7624fn decodeLinear(raw: vec4f) -> vec3f { 7625 return raw.rgb; 7626} 7627fn decodeGammaFloat(raw: f32) -> f32 { 7628 return pow(raw, 2.2); 7629} 7630fn decodeGamma3(raw: vec3f) -> vec3f { 7631 return pow(raw, vec3f(2.2)); 7632} 7633fn decodeGamma(raw: vec4f) -> vec3f { 7634 return pow(raw.xyz, vec3f(2.2)); 7635} 7636fn decodeRGBM(raw: vec4f) -> vec3f { 7637 let color = (8.0 * raw.a) * raw.rgb; 7638 return color * color; 7639} 7640fn decodeRGBP(raw: vec4f) -> vec3f { 7641 let color = raw.rgb * (-raw.a * 7.0 + 8.0); 7642 return color * color; 7643} 7644fn decodeRGBE(raw: vec4f) -> vec3f { 7645 return select(vec3f(0.0), raw.xyz * pow(2.0, raw.w * 255.0 - 128.0), raw.a != 0.0); 7646} 7647fn passThrough(raw: vec4f) -> vec4f { 7648 return raw; 7649} 7650fn unpackNormalXYZ(nmap: vec4f) -> vec3f { 7651 return nmap.xyz * 2.0 - 1.0; 7652} 7653fn unpackNormalXY(nmap: vec4f) -> vec3f { 7654 var xy = nmap.wy * 2.0 - 1.0; 7655 return vec3f(xy, sqrt(1.0 - clamp(dot(xy, xy), 0.0, 1.0))); 7656} 7657#endif 7658`,uF=` 7659#ifndef _DETAILMODES_INCLUDED_ 7660#define _DETAILMODES_INCLUDED_
7661fn detailMode_mul(c1: vec3f, c2: vec3f) -> vec3f { 7662 return c1 * c2; 7663} 7664fn detailMode_add(c1: vec3f, c2: vec3f) -> vec3f { 7665 return c1 + c2; 7666} 7667fn detailMode_screen(c1: vec3f, c2: vec3f) -> vec3f { 7668 return 1.0 - (1.0 - c1)*(1.0 - c2); 7669} 7670fn detailMode_overlay(c1: vec3f, c2: vec3f) -> vec3f { 7671 return mix(1.0 - 2.0 * (1.0 - c1)*(1.0 - c2), 2.0 * c1 * c2, step(c1, vec3f(0.5))); 7672} 7673fn detailMode_min(c1: vec3f, c2: vec3f) -> vec3f { 7674 return min(c1, c2); 7675} 7676fn detailMode_max(c1: vec3f, c2: vec3f) -> vec3f { 7677 return max(c1, c2); 7678} 7679#endif 7680`,fF=` 7681uniform material_diffuse: vec3f; 7682#ifdef STD_DIFFUSEDETAIL_TEXTURE 7683 #include "detailModesPS" 7684#endif 7685fn getAlbedo() { 7686 dAlbedo = uniform.material_diffuse.rgb; 7687 #ifdef STD_DIFFUSE_TEXTURE 7688 var albedoTexture: vec3f = {STD_DIFFUSE_TEXTURE_DECODE}(textureSampleBias({STD_DIFFUSE_TEXTURE_NAME}, {STD_DIFFUSE_TEXTURE_NAME}Sampler, {STD_DIFFUSE_TEXTURE_UV}, uniform.textureBias)).{STD_DIFFUSE_TEXTURE_CHANNEL}; 7689 #ifdef STD_DIFFUSEDETAIL_TEXTURE 7690 var albedoDetail: vec3f = {STD_DIFFUSEDETAIL_TEXTURE_DECODE}(textureSampleBias({STD_DIFFUSEDETAIL_TEXTURE_NAME}, {STD_DIFFUSEDETAIL_TEXTURE_NAME}Sampler, {STD_DIFFUSEDETAIL_TEXTURE_UV}, uniform.textureBias)).{STD_DIFFUSEDETAIL_TEXTURE_CHANNEL}; 7691 albedoTexture = detailMode_{STD_DIFFUSEDETAIL_DETAILMODE}(albedoTexture, albedoDetail); 7692 #endif 7693 dAlbedo = dAlbedo * albedoTexture; 7694 #endif 7695 #ifdef STD_DIFFUSE_VERTEX 7696 dAlbedo = dAlbedo * saturate3(vVertexColor.{STD_DIFFUSE_VERTEX_CHANNEL}); 7697 #endif 7698} 7699`,pF=` 7700uniform material_emissive: vec3f; 7701uniform material_emissiveIntensity: f32; 7702fn getEmission() { 7703 dEmission = uniform.material_emissive * uniform.material_emissiveIntensity; 7704 #ifdef STD_EMISSIVE_TEXTURE 7705 dEmission *= {STD_EMISSIVE_TEXTURE_DECODE}(textureSampleBias({STD_EMISSIVE_TEXTURE_NAME}, {STD_EMISSIVE_TEXTURE_NAME}Sampler, {STD_EMISSIVE_TEXTURE_UV}, uniform.textureBias)).{STD_EMISSIVE_TEXTURE_CHANNEL}; 7706 #endif 7707 #ifdef STD_EMISSIVE_VERTEX 7708 dEmission = dEmission * saturate3(vVertexColor.{STD_EMISSIVE_VERTEX_CHANNEL}); 7709 #endif 7710} 7711`,mF=` 7712fn encodeLinear(source: vec3f) -> vec4f { 7713 return vec4f(source, 1.0); 7714} 7715fn encodeGamma(source: vec3f) -> vec4f { 7716 return vec4f(pow(source + vec3f(0.0000001), vec3f(1.0 / 2.2)), 1.0); 7717} 7718fn encodeRGBM(source: vec3f) -> vec4f { 7719 var color: vec3f = pow(source, vec3f(0.5)); 7720 color *= 1.0 / 8.0; 7721 var a: f32 = saturate(max(max(color.r, color.g), max(color.b, 1.0 / 255.0))); 7722 a = ceil(a * 255.0) / 255.0; 7723 color /= a; 7724 return vec4f(color, a); 7725} 7726fn encodeRGBP(source: vec3f) -> vec4f { 7727 var gamma: vec3f = pow(source, vec3f(0.5)); 7728 var maxVal: f32 = min(8.0, max(1.0, max(gamma.x, max(gamma.y, gamma.z)))); 7729 var v: f32 = 1.0 - ((maxVal - 1.0) / 7.0); 7730 v = ceil(v * 255.0) / 255.0; 7731 return vec4f(gamma / (-v * 7.0 + 8.0), v); 7732} 7733fn encodeRGBE(source: vec3f) -> vec4f { 7734 var maxVal: f32 = max(source.x, max(source.y, source.z)); 7735 if (maxVal < 1e-32) { 7736 return vec4f(0.0, 0.0, 0.0, 0.0); 7737 } else { 7738 var e: f32 = ceil(log2(maxVal)); 7739 return vec4f(source / pow(2.0, e), (e + 128.0) / 255.0); 7740 } 7741} 7742`,_F=` 7743 var finalRgb: vec3f = combineColor(litArgs_albedo, litArgs_sheen_specularity, litArgs_clearcoat_specularity); 7744 finalRgb = finalRgb + litArgs_emission; 7745 finalRgb = addFog(finalRgb); 7746 finalRgb = toneMap(finalRgb); 7747 finalRgb = gammaCorrectOutput(finalRgb); 7748 output.color = vec4f(finalRgb, output.color.a); 7749`,gF=` 7750#ifndef _ENVATLAS_INCLUDED_ 7751#define _ENVATLAS_INCLUDED_ 7752const atlasSize : f32 = 512.0; 7753const seamSize : f32 = 1.0 / atlasSize; 7754fn mapUv(uv : vec2f, rect : vec4f) -> vec2f { 7755 return vec2f(mix(rect.x + seamSize, rect.x + rect.z - seamSize, uv.x), 7756 mix(rect.y + seamSize, rect.y + rect.w - seamSize, uv.y)); 7757} 7758fn mapRoughnessUv(uv : vec2f, level : f32) -> vec2f { 7759 let t : f32 = 1.0 / exp2(level); 7760 return mapUv(uv, vec4f(0.0, 1.0 - t, t, t * 0.5)); 7761} 7762fn mapShinyUv(uv : vec2f, level : f32) -> vec2f { 7763 let t : f32 = 1.0 / exp2(level); 7764 return mapUv(uv, vec4f(1.0 - t, 1.0 - t, t, t * 0.5)); 7765} 7766#endif 7767`,vF=` 7768#ifdef LIT_SKYBOX_INTENSITY 7769 uniform skyboxIntensity : f32; 7770#endif 7771fn processEnvironment(color : vec3f) -> vec3f { 7772 #ifdef LIT_SKYBOX_INTENSITY 7773 return color * uniform.skyboxIntensity; 7774 #else 7775 return color; 7776 #endif 7777} 7778`,SF=` 7779fn getFalloffWindow(lightRadius: f32, lightDir: vec3f) -> f32 { 7780 let sqrDist: f32 = dot(lightDir, lightDir); 7781 let invRadius: f32 = 1.0 / lightRadius;
7782 return square(saturate(1.0 - square(sqrDist * square(invRadius)))); 7783} 7784fn getFalloffInvSquared(lightRadius: f32, lightDir: vec3f) -> f32 { 7785 let sqrDist: f32 = dot(lightDir, lightDir); 7786 var falloff: f32 = 1.0 / (sqrDist + 1.0); 7787 let invRadius: f32 = 1.0 / lightRadius; 7788 falloff = falloff * 16.0; 7789 falloff = falloff * square(saturate(1.0 - square(sqrDist * square(invRadius)))); 7790 return falloff; 7791} 7792`,yF=` 7793fn getFalloffLinear(lightRadius: f32, lightDir: vec3f) -> f32 { 7794 let d: f32 = length(lightDir); 7795 return max(((lightRadius - d) / lightRadius), 0.0); 7796} 7797`,xF=` 7798#ifndef FLOAT_AS_UINT 7799#define FLOAT_AS_UINT 7800fn float2uint(value: f32) -> vec4f { 7801 let intBits = bitcast<u32>(value); 7802 return vec4f( 7803 f32((intBits >> 24u) & 0xffu), 7804 f32((intBits >> 16u) & 0xffu), 7805 f32((intBits >> 8u) & 0xffu), 7806 f32(intBits & 0xffu) 7807 ) / 255.0; 7808} 7809fn uint2float(value: vec4f) -> f32 { 7810 let rgba_u32 = vec4<u32>(value * 255.0); 7811 let intBits: u32 = 7812 (rgba_u32.r << 24u) | 7813 (rgba_u32.g << 16u) | 7814 (rgba_u32.b << 8u) | 7815 rgba_u32.a; 7816 return bitcast<f32>(intBits); 7817} 7818fn float2vec4(value: f32) -> vec4f { 7819 #if defined(CAPS_TEXTURE_FLOAT_RENDERABLE) 7820 return vec4f(value, 1.0, 1.0, 1.0); 7821 #else 7822 return float2uint(value); 7823 #endif 7824} 7825#endif 7826`,TF=` 7827#include "fogMathPS" 7828var<private> dBlendModeFogFactor : f32 = 1.0; 7829#if (FOG != NONE) 7830 uniform fog_color : vec3f; 7831 7832 #if (FOG == LINEAR) 7833 uniform fog_start : f32; 7834 uniform fog_end : f32; 7835 #else 7836 uniform fog_density : f32; 7837 #endif 7838#endif 7839#ifdef VERTEXSHADER 7840 fn getFogFactor(depth: f32) -> f32 { 7841#else 7842 fn getFogFactor() -> f32 { 7843 let depth = pcPosition.z / pcPosition.w; 7844#endif 7845 #if (FOG == LINEAR) 7846 return evaluateFogFactorLinear(depth, uniform.fog_start, uniform.fog_end); 7847 #elif (FOG == EXP) 7848 return evaluateFogFactorExp(depth, uniform.fog_density); 7849 #elif (FOG == EXP2) 7850 return evaluateFogFactorExp2(depth, uniform.fog_density); 7851 #else 7852 return 1.0; 7853 #endif 7854} 7855#ifdef VERTEXSHADER 7856 fn addFog(color: vec3f, depth: f32) -> vec3f { 7857 #if (FOG != NONE) 7858 return mix(uniform.fog_color * dBlendModeFogFactor, color, getFogFactor(depth)); 7859 #else 7860 return color; 7861 #endif 7862 } 7863#else 7864 fn addFog(color: vec3f) -> vec3f { 7865 #if (FOG != NONE) 7866 return mix(uniform.fog_color * dBlendModeFogFactor, color, getFogFactor()); 7867 #else 7868 return color; 7869 #endif 7870 } 7871#endif 7872`,wF=` 7873fn evaluateFogFactorLinear(depth: f32, fogStart: f32, fogEnd: f32) -> f32 { 7874 return clamp((fogEnd - depth) / (fogEnd - fogStart), 0.0, 1.0); 7875} 7876fn evaluateFogFactorExp(depth: f32, fogDensity: f32) -> f32 { 7877 return clamp(exp(-depth * fogDensity), 0.0, 1.0); 7878} 7879fn evaluateFogFactorExp2(depth: f32, fogDensity: f32) -> f32 { 7880 return clamp(exp(-depth * depth * fogDensity * fogDensity), 0.0, 1.0); 7881} 7882`,CF=` 7883fn pow5(x: f32) -> f32 { 7884 let x2: f32 = x * x; 7885 return x2 * x2 * x; 7886} 7887fn getFresnel( 7888 cosTheta: f32, 7889 gloss: f32, 7890 specularity: vec3f 7891 #if defined(LIT_IRIDESCENCE) 7892 , iridescenceFresnel: vec3f, 7893 iridescenceIntensity: f32 7894 #endif 7895) -> vec3f { 7896 let fresnel: f32 = pow5(1.0 - saturate(cosTheta)); 7897 let glossSq: f32 = gloss * gloss; 7898 let specIntensity: f32 = max(specularity.r, max(specularity.g, specularity.b)); 7899 let ret: vec3f = specularity + (max(vec3f(glossSq * specIntensity), specularity) - specularity) * fresnel; 7900 #if defined(LIT_IRIDESCENCE) 7901 return mix(ret, iridescenceFresnel, iridescenceIntensity); 7902 #else 7903 return ret; 7904 #endif 7905} 7906fn getFresnelCC(cosTheta: f32) -> f32 { 7907 let fresnel: f32 = pow5(1.0 - saturate(cosTheta)); 7908 return 0.04 + (1.0 - 0.04) * fresnel; 7909}`,EF=` 7910attribute vertex_position: vec2f; 7911varying vUv0: vec2f; 7912@vertex 7913fn vertexMain(input: VertexInput) -> VertexOutput { 7914 var output: VertexOutput; 7915 output.position = vec4f(input.vertex_position, 0.5, 1.0); 7916 output.vUv0 = input.vertex_position.xy * 0.5 + vec2f(0.5); 7917 return output; 7918} 7919`,bF=` 7920#include "decodePS" 7921#if (GAMMA == SRGB) 7922 fn gammaCorrectInput(color: f32) -> f32 { 7923 return decodeGammaFloat(color); 7924 } 7925 fn gammaCorrectInputVec3(color: vec3f) -> vec3f { 7926 return decodeGamma3(color); 7927 } 7928 fn gammaCorrectInputVec4(color: vec4f) -> vec4f { 7929 return vec4f(decodeGamma3(color.xyz), color.w); 7930 } 7931 fn gammaCorrectOutput(color: vec3f) -> vec3f { 7932 return pow(color + 0.0000001, vec3f(1.0 / 2.2)); 7933 } 7934#else 7935 fn gammaCorrectInput(color: f32) -> f32 { 7936 return color; 7937 } 7938 fn gammaCorrectInputVec3(color: vec3f) -> vec3f { 7939 return color; 7940 } 7941 fn gammaCorrectInputVec4(color: vec4f) -> vec4f { 7942 return color; 7943 } 7944 fn gammaCorrectOutput(color: vec3f) -> vec3f { 7945 return color; 7946 } 7947#endif 7948`,AF=` 7949#ifdef STD_GLOSS_CONSTANT 7950 uniform material_gloss: f32; 7951#endif 7952fn getGlossiness() { 7953 dGlossiness = 1.0; 7954 #ifdef STD_GLOSS_CONSTANT 7955 dGlossiness = dGlossiness * uniform.material_gloss; 7956 #endif 7957 #ifdef STD_GLOSS_TEXTURE 7958 dGlossiness = dGlossiness * textureSampleBias({STD_GLOSS_TEXTURE_NAME}, {STD_GLOSS_TEXTURE_NAME}Sampler, {STD_GLOSS_TEXTURE_UV}, uniform.textureBias).{STD_GLOSS_TEXTURE_CHANNEL}; 7959 #endif 7960 #ifdef STD_GLOSS_VERTEX 7961 dGlossiness = dGlossiness * saturate(vVertexColor.{STD_GLOSS_VERTEX_CHANNEL}); 7962 #endif 7963 #ifdef STD_GLOSS_INVERT 7964 dGlossiness = 1.0 - dGlossiness; 7965 #endif 7966 dGlossiness = dGlossiness + 0.0000001; 7967} 7968`,PF=` 7969 attribute aPosition: vec2f; 7970 varying uv0: vec2f; 7971 @vertex fn vertexMain(input: VertexInput) -> VertexOutput { 7972 var output: VertexOutput; 7973 output.position = vec4f(input.aPosition, 0.0, 1.0);
7974 output.uv0 = getImageEffectUV((input.aPosition + 1.0) * 0.5); 7975 return output; 7976 } 7977`,Of=` 7978struct DrawIndexedIndirectArgs { 7979 indexCount: u32, 7980 instanceCount: u32, 7981 firstIndex: u32, 7982 baseVertex: i32, 7983 firstInstance: u32 7984}; 7985struct DrawIndirectArgs { 7986 vertexCount: u32, 7987 instanceCount: u32, 7988 firstVertex: u32, 7989 firstInstance: u32, 7990 _pad: u32 7991}; 7992`,IF=` 7993 #include "gammaPS" 7994 varying color: vec4f; 7995 @fragment 7996 fn fragmentMain(input : FragmentInput) -> FragmentOutput { 7997 var output: FragmentOutput; 7998 output.color = vec4f(gammaCorrectOutput(decodeGamma3(input.color.rgb)), input.color.a); 7999 return output; 8000 } 8001`,DF=` 8002 attribute vertex_position: vec4f; 8003 attribute vertex_color: vec4f; 8004 uniform matrix_model: mat4x4f; 8005 uniform matrix_viewProjection: mat4x4f; 8006 varying color: vec4f; 8007 @vertex 8008 fn vertexMain(input : VertexInput) -> VertexOutput { 8009 var output : VertexOutput; 8010 output.color = input.vertex_color; 8011 output.position = uniform.matrix_viewProjection * uniform.matrix_model * input.vertex_position; 8012 return output; 8013 } 8014`,MF=` 8015uniform material_iridescenceRefractionIndex: f32; 8016fn iridescence_iorToFresnelScalar(transmittedIor: f32, incidentIor: f32) -> f32 { 8017 return pow((transmittedIor - incidentIor) / (transmittedIor + incidentIor), 2.0); 8018} 8019fn iridescence_iorToFresnelVec3(transmittedIor: vec3f, incidentIor: f32) -> vec3f { 8020 return pow((transmittedIor - vec3f(incidentIor)) / (transmittedIor + vec3f(incidentIor)), vec3f(2.0)); 8021} 8022fn iridescence_fresnelToIor(f0: vec3f) -> vec3f { 8023 let sqrtF0: vec3f = sqrt(f0); 8024 return (vec3f(1.0) + sqrtF0) / (vec3f(1.0) - sqrtF0); 8025} 8026const XYZ_TO_REC709: mat3x3f = mat3x3f( 8027 vec3f(3.2404542, -1.5371385, -0.4985314), 8028 vec3f(-0.9692660, 1.8760108, 0.0415560), 8029 vec3f(0.0556434, -0.2040259, 1.0572252) 8030); 8031fn iridescence_sensitivity(opd: f32, shift: vec3f) -> vec3f { 8032 let PI: f32 = 3.141592653589793; 8033 let phase: f32 = 2.0 * PI * opd * 1.0e-9; 8034 const val: vec3f = vec3f(5.4856e-13, 4.4201e-13, 5.2481e-13); 8035 const pos: vec3f = vec3f(1.6810e+06, 1.7953e+06, 2.2084e+06); 8036 const var_: vec3f = vec3f(4.3278e+09, 9.3046e+09, 6.6121e+09); 8037 var xyz: vec3f = val * sqrt(2.0 * PI * var_) * cos(pos * phase + shift) * exp(-pow(phase, 2.0) * var_); 8038 xyz.x = xyz.x + 9.7470e-14 * sqrt(2.0 * PI * 4.5282e+09) * cos(2.2399e+06 * phase + shift[0]) * exp(-4.5282e+09 * pow(phase, 2.0)); 8039 xyz = xyz / vec3f(1.0685e-07); 8040 return XYZ_TO_REC709 * xyz; 8041} 8042fn iridescence_fresnelScalar(cosTheta: f32, f0: f32) -> f32 { 8043 let x: f32 = clamp(1.0 - cosTheta, 0.0, 1.0); 8044 let x2: f32 = x * x; 8045 let x5: f32 = x * x2 * x2; 8046 return f0 + (1.0 - f0) * x5; 8047} 8048fn iridescence_fresnelVec3(cosTheta: f32, f0: vec3f) -> vec3f { 8049 let x: f32 = clamp(1.0 - cosTheta, 0.0, 1.0); 8050 let x2: f32 = x * x; 8051 let x5: f32 = x * x2 * x2; 8052 return f0 + (vec3f(1.0) - f0) * x5; 8053} 8054fn calcIridescence(outsideIor: f32, cosTheta: f32, base_f0: vec3f, iridescenceThickness: f32) -> vec3f { 8055 let PI: f32 = 3.141592653589793; 8056 let iridescenceIor: f32 = mix(outsideIor, uniform.material_iridescenceRefractionIndex, smoothstep(0.0, 0.03, iridescenceThickness)); 8057 let sinTheta2Sq: f32 = pow(outsideIor / iridescenceIor, 2.0) * (1.0 - pow(cosTheta, 2.0)); 8058 let cosTheta2Sq: f32 = 1.0 - sinTheta2Sq; 8059 if (cosTheta2Sq < 0.0) { 8060 return vec3f(1.0); 8061 } 8062 let cosTheta2: f32 = sqrt(cosTheta2Sq); 8063 let r0: f32 = iridescence_iorToFresnelScalar(iridescenceIor, outsideIor); 8064 let r12: f32 = iridescence_fresnelScalar(cosTheta, r0); 8065 let r21: f32 = r12; 8066 let t121: f32 = 1.0 - r12; 8067 let phi12: f32 = select(0.0, PI, iridescenceIor < outsideIor); 8068 let phi21: f32 = PI - phi12; 8069 let baseIor: vec3f = iridescence_fresnelToIor(base_f0 + vec3f(0.0001)); 8070 let r1: vec3f = iridescence_iorToFresnelVec3(baseIor, iridescenceIor); 8071 let r23: vec3f = iridescence_fresnelVec3(cosTheta2, r1); 8072 let phi23: vec3f = select(vec3f(0.0), vec3f(PI), baseIor < vec3f(iridescenceIor)); 8073 let opd: f32 = 2.0 * iridescenceIor * iridescenceThickness * cosTheta2; 8074 let phi: vec3f = vec3f(phi21) + phi23; 8075 let r123Sq: vec3f = clamp(vec3f(r12) * r23, vec3f(1e-5), vec3f(0.9999)); 8076 let r123: vec3f = sqrt(r123Sq); 8077 let rs: vec3f = pow(vec3f(t121), vec3f(2.0)) * r23 / (vec3f(1.0) - r123Sq); 8078 let c0: vec3f = vec3f(r12) + rs; 8079 var i_irid: vec3f = c0; 8080 var cm: vec3f = rs - vec3f(t121); 8081 cm = cm * r123; 8082 let sm1: vec3f = 2.0 * iridescence_sensitivity(1.0 * opd, 1.0 * phi); 8083 i_irid = i_irid + cm * sm1; 8084 cm = cm * r123; 8085 let sm2: vec3f = 2.0 * iridescence_sensitivity(2.0 * opd, 2.0 * phi); 8086 i_irid = i_irid + cm * sm2; 8087 return max(i_irid, vec3f(0.0)); 8088} 8089fn getIridescenceDiffraction(cosTheta: f32, specularity: vec3f, iridescenceThickness: f32) -> vec3f { 8090 return calcIridescence(1.0, cosTheta, specularity, iridescenceThickness); 8091} 8092`,RF=` 8093#ifdef STD_IRIDESCENCE_CONSTANT 8094 uniform material_iridescence: f32; 8095#endif 8096fn getIridescence() { 8097 var iridescence = 1.0; 8098 #ifdef STD_IRIDESCENCE_CONSTANT 8099 iridescence = iridescence * uniform.material_iridescence; 8100 #endif 8101 #ifdef STD_IRIDESCENCE_TEXTURE 8102 iridescence = iridescence * textureSampleBias({STD_IRIDESCENCE_TEXTURE_NAME}, {STD_IRIDESCENCE_TEXTURE_NAME}Sampler, {STD_IRIDESCENCE_TEXTURE_UV}, uniform.textureBias).{STD_IRIDESCENCE_TEXTURE_CHANNEL}; 8103 #endif 8104 dIridescence = iridescence; 8105} 8106`,LF=` 8107uniform material_iridescenceThicknessMax: f32; 8108#ifdef STD_IRIDESCENCETHICKNESS_TEXTURE 8109 uniform material_iridescenceThicknessMin: f32; 8110#endif 8111fn getIridescenceThickness() { 8112 #ifdef STD_IRIDESCENCETHICKNESS_TEXTURE 8113 var blend: f32 = textureSampleBias({STD_IRIDESCENCETHICKNESS_TEXTURE_NAME}, {STD_IRIDESCENCETHICKNESS_TEXTURE_NAME}Sampler, {STD_IRIDESCENCETHICKNESS_TEXTURE_UV}, uniform.textureBias).{STD_IRIDESCENCETHICKNESS_TEXTURE_CHANNEL}; 8114 var iridescenceThickness: f32 = mix(uniform.material_iridescenceThicknessMin, uniform.material_iridescenceThicknessMax, blend); 8115 #else 8116 var iridescenceThickness: f32 = uniform.material_iridescenceThicknessMax; 8117 #endif 8118 dIridescenceThickness = iridescenceThickness; 8119} 8120`,FF=` 8121#ifdef STD_IOR_CONSTANT 8122 uniform material_refractionIndex: f32; 8123#endif 8124fn getIor() { 8125#ifdef STD_IOR_CONSTANT 8126 dIor = uniform.material_refractionIndex; 8127#else 8128 dIor = 1.0 / 1.5; 8129#endif 8130} 8131`,OF=` 8132#if defined(LIGHT{i}) 8133 uniform light{i}_color: vec3f; 8134 #if LIGHT{i}TYPE == DIRECTIONAL 8135 uniform light{i}_direction: vec3f; 8136 #else 8137 #define LIT_CODE_LIGHTS_POINT 8138 uniform light{i}_position: vec3f; 8139 uniform light{i}_radius: f32; 8140 #if LIGHT{i}TYPE == SPOT 8141 #define LIT_CODE_LIGHTS_SPOT 8142 uniform light{i}_direction: vec3f; 8143 uniform light{i}_innerConeAngle: f32; 8144 uniform light{i}_outerConeAngle: f32; 8145 #endif 8146 #endif 8147 #if LIGHT{i}SHAPE != PUNCTUAL 8148 #define LIT_CODE_FALLOFF_SQUARED 8149 #if LIGHT{i}TYPE == DIRECTIONAL 8150 uniform light{i}_position: vec3f; 8151 #endif 8152 uniform light{i}_halfWidth: vec3f; 8153 uniform light{i}_halfHeight: vec3f; 8154 #else 8155 #if LIGHT{i}FALLOFF == LINEAR 8156 #define LIT_CODE_FALLOFF_LINEAR 8157 #endif 8158 #if LIGHT{i}FALLOFF == INVERSESQUARED 8159 #define LIT_CODE_FALLOFF_SQUARED 8160 #endif 8161 #endif 8162 #if defined(LIGHT{i}
8162CASTSHADOW) 8163 #if LIGHT{i}TYPE != OMNI 8164 uniform light{i}_shadowMatrix: mat4x4f; 8165 #endif 8166 uniform light{i}_shadowIntensity: f32; 8167 uniform light{i}_shadowParams: vec4f; 8168 #if LIGHT{i}SHADOWTYPE == PCSS_32F 8169 uniform light{i}_shadowSearchArea: f32; 8170 uniform light{i}_cameraParams: vec4f; 8171 #if LIGHT{i}TYPE == DIRECTIONAL 8172 uniform light{i}_softShadowParams: vec4f; 8173 #endif 8174 #endif 8175 #if LIGHT{i}TYPE == DIRECTIONAL 8176 uniform light{i}_shadowMatrixPalette: array<mat4x4f, 4>; 8177 uniform light{i}_shadowCascadeDistances: vec4f; 8178 uniform light{i}_shadowCascadeCount: i32; 8179 uniform light{i}_shadowCascadeBlend: f32; 8180 #endif 8181 #if LIGHT{i}TYPE == OMNI 8182 NOT SUPPORTED 8183 #else 8184 #if defined(LIGHT{i}SHADOW_PCF) 8185 var light{i}_shadowMap: texture_depth_2d; 8186 var light{i}_shadowMapSampler: sampler_comparison; 8187 #else 8188 var light{i}_shadowMap: texture_2d<f32>; 8189 var light{i}_shadowMapSampler: sampler; 8190 #endif 8191 #endif 8192 #endif 8193 #if defined(LIGHT{i}COOKIE) 8194 #define LIT_CODE_COOKIE 8195 #if LIGHT{i}TYPE == OMNI 8196 NOT SUPPORTED 8197 #endif 8198 #if LIGHT{i}TYPE == SPOT 8199 NOT SUPPORTED 8200 #endif 8201 #endif 8202#endif 8203`,BF=` 8204fn getLightDiffuse(worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f) -> f32 { 8205 return max(dot(worldNormal, -lightDirNorm), 0.0); 8206} 8207`,NF=` 8208fn evalOmniLight(lightPosW: vec3f) -> vec3f { 8209 return vPositionW - lightPosW; 8210} 8211`,kF=` 8212#if defined(LIGHT{i}) 8213 evaluateLight{i}( 8214 #if defined(LIT_IRIDESCENCE) 8215 iridescenceFresnel 8216 #endif 8217 ); 8218#endif 8219`,UF=` 8220#if defined(LIGHT{i}) 8221fn evaluateLight{i}( 8222 #if defined(LIT_IRIDESCENCE) 8223 iridescenceFresnel: vec3f 8224 #endif 8225) { 8226 var lightColor: vec3f = uniform.light{i}_color; 8227 #if LIGHT{i}TYPE == DIRECTIONAL && !defined(LIT_SHADOW_CATCHER) 8228 if (all(lightColor == vec3f(0.0, 0.0, 0.0))) { 8229 return; 8230 } 8231 #endif 8232 #if LIGHT{i}TYPE == DIRECTIONAL 8233 dLightDirNormW = uniform.light{i}_direction; 8234 dAtten = 1.0; 8235 #else 8236 var lightDirW: vec3f = evalOmniLight(uniform.light{i}_position); 8237 dLightDirNormW = normalize(lightDirW); 8238 #if defined(LIGHT{i}COOKIE) 8239 #if LIGHT{i}TYPE == SPOT 8240 #ifdef LIGHT{i}COOKIE_FALLOFF 8241 #ifdef LIGHT{i}COOKIE_TRANSFORM 8242 var cookieAttenuation: vec3f = getCookie2DXform(uniform.light{i}_cookie, uniform.light{i}_shadowMatrix, uniform.light{i}_cookieIntensity, uniform.light{i}_cookieMatrix, uniform.light{i}_cookieOffset).{LIGHT{i}COOKIE_CHANNEL}; 8243 #else 8244 var cookieAttenuation: vec3f = getCookie2D(uniform.light{i}_cookie, uniform.light{i}_shadowMatrix, uniform.light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL}; 8245 #endif 8246 #else 8247 #ifdef LIGHT{i}COOKIE_TRANSFORM 8248 var cookieAttenuation: vec3f = getCookie2DClipXform(uniform.light{i}_cookie, uniform.light{i}_shadowMatrix, uniform.light{i}_cookieIntensity, uniform.light{i}_cookieMatrix, uniform.light{i}_cookieOffset).{LIGHT{i}COOKIE_CHANNEL}; 8249 #else 8250 var cookieAttenuation: vec3f = getCookie2DClip(uniform.light{i}_cookie, uniform.light{i}_shadowMatrix, uniform.light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL}; 8251 #endif 8252 #endif 8253 #endif 8254 #if LIGHT{i}TYPE == OMNI 8255 var cookieAttenuation: vec3f = getCookieCube(uniform.light{i}_cookie, uniform.light{i}_shadowMatrix, uniform.light{i}_cookieIntensity).{LIGHT{i}COOKIE_CHANNEL}; 8256 #endif 8257 lightColor = lightColor * cookieAttenuation; 8258 #endif 8259 #if LIGHT{i}SHAPE == PUNCTUAL 8260 #if LIGHT{i}FALLOFF == LINEAR 8261 dAtten = getFalloffLinear(uniform.light{i}_radius, lightDirW); 8262 #else 8263 dAtten = getFalloffInvSquared(uniform.light{i}_radius, lightDirW); 8264 #endif 8265 #else 8266 dAtten = getFalloffWindow(uniform.light{i}_radius, lightDirW); 8267 #endif 8268 #if LIGHT{i}TYPE == SPOT 8269 #if !defined(LIGHT{i}COOKIE) || defined(LIGHT{i}COOKIE_FALLOFF) 8270 dAtten = dAtten * getSpotEffect(uniform.light{i}_direction, uniform.light{i}_innerConeAngle, uniform.light{i}_outerConeAngle, dLightDirNormW); 8271 #endif 8272 #endif 8273 #endif 8274 if (dAtten < 0.00001) { 8275 return; 8276 } 8277 #if LIGHT{i}SHAPE != PUNCTUAL 8278 #if LIGHT{i}SHAPE == RECT 8279 calcRectLightValues(uniform.light{i}_position, uniform.light{i}_halfWidth, uniform.light{i}_halfHeight); 8280 #elif LIGHT{i}SHAPE == DISK 8281 calcDiskLightValues(uniform.light{i}_position, uniform.light{i}_halfWidth, uniform.light{i}_halfHeight); 8282 #elif LIGHT{i}SHAPE == SPHERE 8283 calcSphereLightValues(uniform.light{i}_position, uniform.light{i}_halfWidth, uniform.light{i}_halfHeight); 8284 #endif 8285 #endif 8286 #if LIGHT{i}SHAPE != PUNCTUAL 8287 #if LIGHT{i}TYPE == DIRECTIONAL 8288 var attenDiffuse: f32 = getLightDiffuse(litArgs_worldNormal, dViewDirW, dLightDirNormW); 8289 #else 8290 #if LIGHT{i}SHAPE == RECT 8291 var attenDiffuse: f32 = getRectLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0; 8292 #elif LIGHT{i}SHAPE == DISK 8293 var attenDiffuse: f32 = getDiskLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0; 8294 #elif LIGHT{i}SHAPE == SPHERE 8295 var attenDiffuse: f32 = getSphereLightDiffuse(litArgs_worldNormal, dViewDirW, lightDirW, dLightDirNormW) * 16.0; 8296 #endif 8297 #endif 8298 #else 8299 dAtten = dAtten * getLightDiffuse(litArgs_worldNormal, vec3(0.0), dLightDirNormW); 8300 #endif 8301 #ifdef LIGHT{i}
8301CASTSHADOW 8302 #if LIGHT{i}TYPE == DIRECTIONAL 8303 var shadow: f32 = getShadow{i}(vec3(0.0)); 8304 #else 8305 var shadow: f32 = getShadow{i}(lightDirW); 8306 #endif 8307 shadow = mix(1.0, shadow, uniform.light{i}_shadowIntensity); 8308 dAtten = dAtten * shadow; 8309 #if defined(LIT_SHADOW_CATCHER) && LIGHT{i}TYPE == DIRECTIONAL 8310 dShadowCatcher = dShadowCatcher * shadow; 8311 #endif 8312 #endif 8313 #if LIGHT{i}SHAPE != PUNCTUAL 8314 #ifdef LIT_SPECULAR 8315 dDiffuseLight = dDiffuseLight + (((attenDiffuse * dAtten) * lightColor) * (1.0 - dLTCSpecFres)); 8316 #else 8317 dDiffuseLight = dDiffuseLight + ((attenDiffuse * dAtten) * lightColor); 8318 #endif 8319 #else 8320 #if defined(AREA_LIGHTS) && defined(LIT_SPECULAR) 8321 dDiffuseLight = dDiffuseLight + ((dAtten * lightColor) * (1.0 - litArgs_specularity)); 8322 #else 8323 dDiffuseLight = dDiffuseLight + (dAtten * lightColor); 8324 #endif 8325 #endif 8326 #ifdef LIGHT{i}AFFECT_SPECULARITY 8327 #if LIGHT{i}SHAPE != PUNCTUAL 8328 #ifdef LIT_CLEARCOAT 8329 #if LIGHT{i}SHAPE == RECT 8330 ccSpecularLight = ccSpecularLight + (ccLTCSpecFres * getRectLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor); 8331 #elif LIGHT{i}SHAPE == DISK 8332 ccSpecularLight = ccSpecularLight + (ccLTCSpecFres * getDiskLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor); 8333 #elif LIGHT{i}SHAPE == SPHERE 8334 ccSpecularLight = ccSpecularLight + (ccLTCSpecFres * getSphereLightSpecular(litArgs_clearcoat_worldNormal, dViewDirW) * dAtten * lightColor); 8335 #endif 8336 #endif 8337 #ifdef LIT_SPECULAR 8338 #if LIGHT{i}SHAPE == RECT 8339 dSpecularLight = dSpecularLight + (dLTCSpecFres * getRectLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor); 8340 #elif LIGHT{i}SHAPE == DISK 8341 dSpecularLight = dSpecularLight + (dLTCSpecFres * getDiskLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor); 8342 #elif LIGHT{i}SHAPE == SPHERE 8343 dSpecularLight = dSpecularLight + (dLTCSpecFres * getSphereLightSpecular(litArgs_worldNormal, dViewDirW) * dAtten * lightColor); 8344 #endif 8345 #endif 8346 #else 8347 #if LIGHT{i}TYPE == DIRECTIONAL && LIT_FRESNEL_MODEL != NONE 8348 #define LIGHT{i}FRESNEL 8349 #endif 8350 #ifdef LIT_SPECULAR 8351 var halfDirW: vec3f = normalize(-dLightDirNormW + dViewDirW); 8352 #endif 8353 #ifdef LIT_CLEARCOAT 8354 var lightspecularCC: vec3f = getLightSpecular(halfDirW, ccReflDirW, litArgs_clearcoat_worldNormal, dViewDirW, dLightDirNormW, litArgs_clearcoat_gloss, dTBN) * dAtten * lightColor; 8355 #ifdef LIGHT{i}FRESNEL 8356 lightspecularCC = lightspecularCC * getFresnelCC(dot(dViewDirW, halfDirW)); 8357 #endif 8358 ccSpecularLight = ccSpecularLight + lightspecularCC; 8359 #endif 8360 #ifdef LIT_SHEEN 8361 sSpecularLight = sSpecularLight + (getLightSpecularSheen(halfDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_sheen_gloss) * dAtten * lightColor); 8362 #endif 8363 #ifdef LIT_SPECULAR 8364 var lightSpecular: vec3f = getLightSpecular(halfDirW, dReflDirW, litArgs_worldNormal, dViewDirW, dLightDirNormW, litArgs_gloss, dTBN) * dAtten * lightColor; 8365 #ifdef LIGHT{i}FRESNEL 8366 #if defined(LIT_IRIDESCENCE)
8367 lightSpecular = lightSpecular * getFresnel(dot(dViewDirW, halfDirW), litArgs_gloss, litArgs_specularity, iridescenceFresnel, litArgs_iridescence_intensity); 8368 #else 8369 lightSpecular = lightSpecular * getFresnel(dot(dViewDirW, halfDirW), litArgs_gloss, litArgs_specularity); 8370 #endif 8371 #else 8372 lightSpecular = lightSpecular * litArgs_specularity; 8373 #endif 8374 8375 dSpecularLight = dSpecularLight + lightSpecular; 8376 #endif 8377 #endif 8378 #endif 8379} 8380#endif 8381`,zF=` 8382#ifdef LIGHT{i}CASTSHADOW 8383 #ifdef LIGHT{i}_SHADOW_SAMPLE_POINT 8384 fn getShadowSampleCoordOmni{i}(shadowParams: vec4f, worldPosition: vec3f, lightPos: vec3f, lightDir: ptr<function, vec3f>, lightDirNorm: vec3f, normal: vec3f) -> vec3f { 8385 #ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET 8386 let distScale: f32 = length(*lightDir); 8387 var surfacePosition = worldPosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale; 8388 *lightDir = surfacePosition - lightPos; 8389 #endif 8390 return *lightDir; 8391 } 8392 #endif 8393 #ifndef LIGHT{i}_SHADOW_SAMPLE_POINT 8394 fn getShadowSampleCoord{i}(shadowTransform: mat4x4f, shadowParams: vec4f, worldPosition: vec3f, lightPos: vec3f, lightDir: ptr<function, vec3f>, lightDirNorm: vec3f, normal: vec3f) -> vec3f { 8395 var surfacePosition = worldPosition; 8396 #ifdef LIGHT{i}_SHADOW_SAMPLE_SOURCE_ZBUFFER 8397 #ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET 8398 surfacePosition = surfacePosition + normal * shadowParams.y; 8399 #endif 8400 #else 8401 #ifdef LIGHT{i}_SHADOW_SAMPLE_NORMAL_OFFSET 8402 #ifdef LIGHT{i}_SHADOW_SAMPLE_ORTHO 8403 var distScale: f32 = 1.0; 8404 #else 8405 var distScale: f32 = abs(dot(vPositionW - lightPos, lightDirNorm)); 8406 #endif 8407 surfacePosition = surfacePosition + normal * shadowParams.y * clamp(1.0 - dot(normal, -lightDirNorm), 0.0, 1.0) * distScale; 8408 #endif 8409 #endif 8410 var positionInShadowSpace: vec4f = shadowTransform * vec4f(surfacePosition, 1.0
8410); 8411 #ifdef LIGHT{i}_SHADOW_SAMPLE_ORTHO 8412 positionInShadowSpace.z = saturate(positionInShadowSpace.z) - 0.0001; 8413 #else 8414 #ifdef LIGHT{i}_SHADOW_SAMPLE_SOURCE_ZBUFFER 8415 positionInShadowSpace.xyz = positionInShadowSpace.xyz / positionInShadowSpace.w; 8416 #else 8417 positionInShadowSpace.xy = positionInShadowSpace.xy / positionInShadowSpace.w; 8418 positionInShadowSpace.z = length(*lightDir) * shadowParams.w; 8419 #endif 8420 #endif 8421 return positionInShadowSpace.xyz; 8422 } 8423 #endif 8424 fn getShadow{i}(lightDirW_in: vec3f) -> f32 { 8425 var lightDirArg = lightDirW_in; 8426 #if LIGHT{i}TYPE == OMNI 8427 var shadowCoord: vec3f = getShadowSampleCoordOmni{i}(uniform.light{i}_shadowParams, vPositionW, uniform.light{i}_position, &lightDirArg, dLightDirNormW, dVertexNormalW); 8428 #else 8429 #ifdef LIGHT{i}_SHADOW_CASCADES 8430 var cascadeIndex: i32 = getShadowCascadeIndex(uniform.light{i}_shadowCascadeDistances, uniform.light{i}_shadowCascadeCount); 8431 #ifdef LIGHT{i}_SHADOW_CASCADE_BLEND 8432 cascadeIndex = ditherShadowCascadeIndex(cascadeIndex, uniform.light{i}_shadowCascadeDistances, uniform.light{i}_shadowCascadeCount, uniform.light{i}_shadowCascadeBlend); 8433 #endif 8434 var shadowMatrix: mat4x4f = uniform.light{i}_shadowMatrixPalette[cascadeIndex]; 8435 #else 8436 var shadowMatrix: mat4x4f = uniform.light{i}_shadowMatrix; 8437 #endif 8438 #if LIGHT{i}TYPE == DIRECTIONAL 8439 var shadowCoord: vec3f = getShadowSampleCoord{i}(shadowMatrix, uniform.light{i}_shadowParams, vPositionW, vec3f(0.0), &lightDirArg, dLightDirNormW, dVertexNormalW); 8440 #else 8441 var shadowCoord: vec3f = getShadowSampleCoord{i}(shadowMatrix, uniform.light{i}_shadowParams, vPositionW, uniform.light{i}_position, &lightDirArg, dLightDirNormW, dVertexNormalW); 8442 #endif 8443 #endif 8444 #if LIGHT{i}TYPE == DIRECTIONAL 8445 shadowCoord = fadeShadow(shadowCoord, uniform.light{i}_shadowCascadeDistances); 8446 #endif 8447 #if LIGHT{i}TYPE == DIRECTIONAL 8448 #if LIGHT{i}SHADOWTYPE == VSM_16F 8449 return getShadowVSM16(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, 5.54); 8450 #endif 8451 #if LIGHT{i}SHADOWTYPE == VSM_32F 8452 return getShadowVSM32(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, 15.0); 8453 #endif 8454 #if LIGHT{i}SHADOWTYPE == PCSS_32F 8455 #if LIGHT{i}SHAPE != PUNCTUAL 8456 let shadowSearchArea = vec2f(length(uniform.light{i}_halfWidth), length(uniform.light{i}_halfHeight)) * uniform.light{i}_shadowSearchArea; 8457 return getShadowPCSS(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, uniform.light{i}_cameraParams, shadowSearchArea, lightDirW_in); 8458 #else 8459 return getShadowPCSS(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, uniform.light{i}_cameraParams, uniform.light{i}_softShadowParams, lightDirW_in); 8460 #endif 8461 #endif 8462 #if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F 8463 return getShadowPCF1x1(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams); 8464 #endif 8465 #if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F 8466 return getShadowPCF3x3(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams); 8467 #endif 8468 #if LIGHT{i}SHADOWTYPE == PCF5_16F || LIGHT{i}SHADOWTYPE == PCF5_32F 8469 return getShadowPCF5x5(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams); 8470 #endif 8471 #endif 8472 #if LIGHT{i}TYPE == SPOT 8473 #if LIGHT{i}SHADOWTYPE == VSM_16F 8474 return getShadowSpotVSM16(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, 5.54, lightDirW_in); 8475 #endif 8476 #if LIGHT{i}SHADOWTYPE == VSM_32F 8477 return getShadowSpotVSM32(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, 15.0, lightDirW_in); 8478 #endif 8479 #if LIGHT{i}SHADOWTYPE == PCSS_32F 8480 #if LIGHT{i}SHAPE != PUNCTUAL 8481 var shadowSearchArea: vec2f = vec2f(length(uniform.light{i}_halfWidth), length(uniform.light{i}_halfHeight)) * uniform.light{i}_shadowSearchArea; 8482 #else 8483 var shadowSearchArea: vec2f = vec2f(uniform.light{i}_shadowSearchArea); 8484 #endif 8485 return getShadowSpotPCSS(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, uniform.light{i}_cameraParams, shadowSearchArea, lightDirW_in); 8486 #endif 8487 #if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F 8488 return getShadowSpotPCF1x1(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams); 8489 #endif 8490 #if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F 8491 return getShadowSpotPCF3x3(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams); 8492 #endif 8493 #if LIGHT{i}SHADOWTYPE == PCF5_16F || LIGHT{i}SHADOWTYPE == PCF5_32F 8494 return getShadowSpotPCF5x5(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams); 8495 #endif 8496 #endif 8497 #if LIGHT{i}TYPE == OMNI 8498 #if LIGHT{i}SHADOWTYPE == PCSS_32F 8499 var shadowSearchArea: vec2f; 8500 #if LIGHT{i}SHAPE != PUNCTUAL 8501 var shadowSearchArea: vec2f = vec2f(length(uniform.light{i}_halfWidth), length(uniform.light{i}_halfHeight)) * uniform.light{i}_shadowSearchArea; 8502 #else 8503 var shadowSearchArea: vec2f = vec2f(uniform.light{i}_shadowSearchArea); 8504 #endif 8505 return getShadowOmniPCSS(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, uniform.light{i}_cameraParams, shadowSearchArea, lightDirW_in); 8506 #endif 8507 #if LIGHT{i}SHADOWTYPE == PCF1_16F || LIGHT{i}SHADOWTYPE == PCF1_32F 8508 return getShadowOmniPCF1x1(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, lightDirW_in); 8509 #endif 8510 #if LIGHT{i}SHADOWTYPE == PCF3_16F || LIGHT{i}SHADOWTYPE == PCF3_32F 8511 return getShadowOmniPCF3x3(light{i}_shadowMap, light{i}_shadowMapSampler, shadowCoord, uniform.light{i}_shadowParams, lightDirW_in); 8512 #endif 8513 #endif 8514 } 8515#endif 8516`,VF=` 8517#ifdef LIT_CLUSTERED_LIGHTS 8518 #define LIT_CODE_FALLOFF_LINEAR 8519 #define LIT_CODE_FALLOFF_SQUARED 8520 #define LIT_CODE_LIGHTS_POINT 8521 #define LIT_CODE_LIGHTS_SPOT 8522#endif 8523#ifdef AREA_LIGHTS 8524 var areaLightsLutTex1: texture_2d<f32>; 8525 var areaLightsLutTex1Sampler: sampler; 8526 var areaLightsLutTex2: texture_2d<f32>; 8527 var areaLightsLutTex2Sampler: sampler; 8528#endif 8529#ifdef LIT_LIGHTING 8530 #include "lightDiffuseLambertPS" 8531 #if defined(AREA_LIGHTS) || defined(LIT_CLUSTERED_AREA_LIGHTS) 8532 #include "ltcPS" 8533 #endif 8534#endif 8535#ifdef SHADOW_DIRECTIONAL 8536 #include "shadowCascadesPS" 8537#endif 8538#if defined(SHADOW_KIND_PCF1) 8539 #include "shadowPCF1PS" 8540#endif 8541#if defined(SHADOW_KIND_PCF3) 8542 #include "shadowPCF3PS" 8543#endif 8544#if defined(SHADOW_KIND_PCF5) 8545 #include "shadowPCF5PS" 8546#endif 8547#if defined(SHADOW_KIND_PCSS) 8548 #include "linearizeDepthPS" 8549 #include "shadowSoftPS" 8550#endif 8551#if defined(SHADOW_KIND_VSM) 8552 #include "shadowEVSMPS" 8553#endif 8554#ifdef LIT_CODE_FALLOFF_LINEAR 8555 #include "falloffLinearPS" 8556#endif 8557#ifdef LIT_CODE_FALLOFF_SQUARED 8558 #include "falloffInvSquaredPS" 8559#endif 8560#ifdef LIT_CODE_LIGHTS_POINT 8561 #include "lightDirPointPS" 8562#endif 8563#ifdef LIT_CODE_LIGHTS_SPOT 8564 #include "spotPS" 8565#endif 8566#ifdef LIT_CODE_COOKIE 8567 #include "cookiePS" 8568#endif 8569#ifdef LIT_CLUSTERED_LIGHTS 8570 #include "clusteredLightPS" 8571#endif 8572#ifdef LIGHT_COUNT > 0 8573 #include "lightFunctionShadowPS, LIGHT_COUNT" 8574 #include "lightFunctionLightPS, LIGHT_COUNT" 8575#endif 8576`,GF=` 8577fn addLightMap( 8578 lightmap: vec3f, 8579 dir: vec3f, 8580 worldNormal: vec3f, 8581 viewDir: vec3f, 8582 reflectionDir: vec3f, 8583 gloss: f32, 8584 specularity: vec3f, 8585 vertexNormal: vec3f, 8586 tbn: mat3x3f 8587#if defined(LIT_IRIDESCENCE) 8588 , iridescenceFresnel: vec3f, 8589 iridescenceIntensity: f32 8590#endif 8591) { 8592 #if defined(LIT_SPECULAR) && defined(LIT_DIR_LIGHTMAP) 8593 if (dot(dir, dir) < 0.0001) { 8594 dDiffuseLight = dDiffuseLight + lightmap; 8595 } else { 8596 let vlight: f32 = saturate(dot(dir, -vertexNormal)); 8597 let flight: f32 = saturate(dot(dir, -worldNormal)); 8598 let nlight: f32 = (flight / max(vlight, 0.01)) * 0.5; 8599 dDiffuseLight = dDiffuseLight + lightmap * nlight * 2.0; 8600 let halfDir: vec3f = normalize(-dir + viewDir); 8601 var specularLight: vec3f = lightmap * getLightSpecular(halfDir, reflectionDir, worldNormal, viewDir, dir, gloss, tbn); 8602 #ifdef LIT_SPECULAR_FRESNEL 8603 specularLight = specularLight * 8604 getFresnel(dot(viewDir, halfDir), 8605 gloss, 8606 specularity 8607 #if defined(LIT_IRIDESCENCE) 8608 , iridescenceFresnel, 8609 iridescenceIntensity 8610 #endif 8611 ); 8612 #endif 8613 dSpecularLight = dSpecularLight + specularLight; 8614 } 8615 #else 8616 dDiffuseLight = dDiffuseLight + lightmap; 8617 #endif 8618} 8619`,HF=`
8620#ifdef STD_LIGHTMAP_DIR 8621 var<private> dLightmapDir: vec3f; 8622 var texture_dirLightMap: texture_2d<f32>; 8623 var texture_dirLightMapSampler: sampler; 8624#endif 8625fn getLightMap() { 8626 dLightmap = vec3f(1.0); 8627 #ifdef STD_LIGHT_TEXTURE 8628 dLightmap = dLightmap * {STD_LIGHT_TEXTURE_DECODE}(textureSampleBias({STD_LIGHT_TEXTURE_NAME}, {STD_LIGHT_TEXTURE_NAME}Sampler, {STD_LIGHT_TEXTURE_UV}, uniform.textureBias)).{STD_LIGHT_TEXTURE_CHANNEL}; 8629 #ifdef STD_LIGHTMAP_DIR 8630 var dir: vec3f = textureSampleBias(texture_dirLightMap, texture_dirLightMapSampler, {STD_LIGHT_TEXTURE_UV}, uniform.textureBias).xyz * 2.0 - 1.0; 8631 var dirDot = dot(dir, dir); 8632 dLightmapDir = select(vec3(0.0), dir / sqrt(dirDot), dirDot > 0.001); 8633 #endif 8634 #endif 8635 #ifdef STD_LIGHT_VERTEX 8636 dLightmap = dLightmap * saturate(vVertexColor.{STD_LIGHT_VERTEX_CHANNEL}); 8637 #endif 8638} 8639`,WF=` 8640fn calcLightSpecular(gloss: f32, worldNormal: vec3f, viewDir: vec3f, h: vec3f, lightDirNorm: vec3f, tbn: mat3x3f) -> f32 { 8641 let PI: f32 = 3.141592653589793; 8642 let roughness: f32 = max((1.0 - gloss) * (1.0 - gloss), 0.001); 8643 let alphaRoughness: f32 = roughness * roughness; 8644 let anisotropy: f32 = dAnisotropy; 8645 let direction: vec2f = dAnisotropyRotation; 8646 let at: f32 = mix(alphaRoughness, 1.0, anisotropy * anisotropy); 8647 let ab: f32 = clamp(alphaRoughness, 0.001, 1.0); 8648 let anisotropicT: vec3f = normalize(tbn * vec3f(direction, 0.0)); 8649 let anisotropicB: vec3f = normalize(cross(tbn[2], anisotropicT)); 8650 let NoH: f32 = dot(worldNormal, h); 8651 let ToH: f32 = dot(anisotropicT, h); 8652 let BoH: f32 = dot(anisotropicB, h); 8653 let a2: f32 = at * ab; 8654 let v: vec3f = vec3f(ab * ToH, at * BoH, a2 * NoH); 8655 let v2: f32 = dot(v, v); 8656 let w2: f32 = a2 / v2; 8657 let D: f32 = a2 * w2 * w2 * (1.0 / PI); 8658 let ToV: f32 = dot(anisotropicT, viewDir); 8659 let BoV: f32 = dot(anisotropicB, viewDir); 8660 let ToL: f32 = dot(anisotropicT, -lightDirNorm); 8661 let BoL: f32 = dot(anisotropicB, -lightDirNorm); 8662 let NoV: f32 = dot(worldNormal, viewDir); 8663 let NoL: f32 = dot(worldNormal, -lightDirNorm); 8664 let lambdaV: f32 = NoL * length(vec3f(at * ToV, ab * BoV, NoV)); 8665 let lambdaL: f32 = NoV * length(vec3f(at * ToL, ab * BoL, NoL)); 8666 let G: f32 = 0.5 / (lambdaV + lambdaL); 8667 return D * G; 8668} 8669fn getLightSpecular(h: vec3f, reflDir: vec3f, worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f, gloss: f32, tbn: mat3x3f) -> f32 { 8670 return calcLightSpecular(gloss, worldNormal, viewDir, h, lightDirNorm, tbn); 8671} 8672`,XF=` 8673fn calcLightSpecular(gloss: f32, worldNormal: vec3f, viewDir: vec3f, h: vec3f, lightDirNorm: vec3f) -> f32 { 8674 const PI: f32 = 3.141592653589793; 8675 let roughness: f32 = max((1.0 - gloss) * (1.0 - gloss), 0.001); 8676 let alpha: f32 = roughness * roughness; 8677 let NoH: f32 = max(dot(worldNormal, h), 0.0); 8678 let NoV: f32 = max(dot(worldNormal, viewDir), 0.0); 8679 let NoL: f32 = max(dot(worldNormal, -lightDirNorm), 0.0); 8680 let NoH2: f32 = NoH * NoH; 8681 let denom: f32 = NoH2 * (alpha - 1.0) + 1.0; 8682 let D: f32 = alpha / (PI * denom * denom); 8683 let alpha2: f32 = alpha * alpha; 8684 let lambdaV: f32 = NoL * sqrt(NoV * NoV * (1.0 - alpha2) + alpha2); 8685 let lambdaL: f32 = NoV * sqrt(NoL * NoL * (1.0 - alpha2) + alpha2); 8686 let G: f32 = 0.5 / max(lambdaV + lambdaL, 0.00001); 8687 return D * G; 8688} 8689fn getLightSpecular(h: vec3f, reflDir: vec3f, worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f, gloss: f32, tbn: mat3x3f) -> f32 { 8690 return calcLightSpecular(gloss, worldNormal, viewDir, h, lightDirNorm); 8691} 8692`,YF=` 8693fn calcLightSpecular(gloss: f32, worldNormal: vec3f, h: vec3f) -> f32 { 8694 let nh: f32 = max( dot( h, worldNormal ), 0.0 ); 8695 var specPow: f32 = exp2(gloss * 11.0); 8696 specPow = max(specPow, 0.0001); 8697 return pow(nh, specPow) * (specPow + 2.0) / 8.0; 8698} 8699fn getLightSpecular(h: vec3f, reflDir: vec3f, worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f, gloss: f32, tbn: mat3x3f) -> f32 { 8700 return calcLightSpecular(gloss, worldNormal, h); 8701} 8702`,jF=` 8703fn sheenD(normal: vec3f, h: vec3f, roughness: f32) -> f32 { 8704 let PI: f32 = 3.141592653589793; 8705 let invR: f32 = 1.0 / (roughness * roughness); 8706 var cos2h: f32 = max(dot(normal, h), 0.0); 8707 cos2h = cos2h * cos2h; 8708 let sin2h: f32 = max(1.0 - cos2h, 0.0078125); 8709 return (2.0 + invR) * pow(sin2h, invR * 0.5) / (2.0 * PI); 8710} 8711fn sheenV(normal: vec3f, viewDir: vec3f, light: vec3f) -> f32 { 8712 let NoV: f32 = max(dot(normal, viewDir), 0.000001); 8713 let NoL: f32 = max(dot(normal, light), 0.000001); 8714 return 1.0 / (4.0 * (NoL + NoV - NoL * NoV)); 8715} 8716fn getLightSpecularSheen(h: vec3f, worldNormal: vec3f, viewDir: vec3f, lightDirNorm: vec3f, sheenGloss: f32) -> f32 { 8717 let D: f32 = sheenD(worldNormal, h, sheenGloss); 8718 let V: f32 = sheenV(worldNormal, viewDir, -lightDirNorm); 8719 return D * V; 8720}`,qF=` 8721#ifndef LINEARIZE_DEPTH 8722#define LINEARIZE_DEPTH 8723fn linearizeDepthWithParams(z: f32, cameraParams: vec4f) -> f32 { 8724 if (cameraParams.w == 0.0) { 8725 return (cameraParams.z * cameraParams.y) / (cameraParams.y + z * (cameraParams.z - cameraParams.y)); 8726 } else { 8727 return cameraParams.z + z * (cameraParams.y - cameraParams.z); 8728 } 8729} 8730#ifndef CAMERAPLANES 8731 #define CAMERAPLANES 8732 uniform camera_params: vec4f; 8733#endif 8734fn linearizeDepth(z: f32) -> f32 { 8735 return linearizeDepthWithParams(z, uniform.camera_params); 8736} 8737#endif 8738`,$F=` 8739fn evaluateBackend() -> FragmentOutput { 8740 var output: FragmentOutput; 8741 #ifdef LIT_SSAO 8742 litArgs_ao = litArgs_ao * textureSampleLevel(ssaoTexture, ssaoTextureSampler, pcPosition.xy * uniform.ssaoTextureSizeInv, 0.0).r; 8743 #endif 8744 #ifdef LIT_NEEDS_NORMAL 8745 #ifdef LIT_SPECULAR 8746 getReflDir(litArgs_worldNormal, dViewDirW, litArgs_gloss, dTBN); 8747 #endif 8748 #ifdef LIT_CLEARCOAT 8749 ccReflDirW = normalize(-reflect(dViewDirW, litArgs_clearcoat_worldNormal)); 8750 #endif 8751 #endif 8752 #ifdef LIT_SPECULAR_OR_REFLECTION 8753 #ifdef LIT_METALNESS 8754 var f0: f32 = 1.0 / litArgs_ior; 8755 f0 = (f0 - 1.0) / (f0 + 1.0); 8756 f0 = f0 * f0; 8757 #ifdef LIT_SPECULARITY_FACTOR 8758 litArgs_specularity = getSpecularModulate(litArgs_specularity, litArgs_albedo, litArgs_metalness, f0, litArgs_specularityFactor); 8759 #else 8760 litArgs_specularity = getSpecularModulate(litArgs_specularity, litArgs_albedo, litArgs_metalness, f0, 1.0); 8761 #endif 8762 litArgs_albedo = getAlbedoModulate(litArgs_albedo, litArgs_metalness); 8763 #endif 8764 #ifdef LIT_IRIDESCENCE 8765 var iridescenceFresnel: vec3f = getIridescenceDiffraction(saturate(dot(dViewDirW, litArgs_worldNormal)), litArgs_specularity, litArgs_iridescence_thickness); 8766 #endif 8767 #endif 8768 #ifdef LIT_ADD_AMBIENT 8769 addAmbient(litArgs_worldNormal); 8770 #ifdef LIT_SPECULAR 8771 dDiffuseLight = dDiffuseLight * (1.0 - litArgs_specularity); 8772 #endif 8773 #ifdef LIT_SEPARATE_AMBIENT 8774 var dAmbientLight: vec3f = dDiffuseLight; 8775 dDiffuseLight = vec3(0.0); 8776 #endif 8777 #endif 8778 #ifndef LIT_OLD_AMBIENT 8779 dDiffuseLight = dDiffuseLight * uniform.material_ambient; 8780 #endif 8781 #ifdef LIT_AO 8782 #ifndef LIT_OCCLUDE_DIRECT 8783 occludeDiffuse(litArgs_ao); 8784 #endif 8785 #endif 8786 #ifdef LIT_LIGHTMAP 8787 addLightMap( 8788 litArgs_lightmap, 8789 litArgs_lightmapDir, 8790 litArgs_worldNormal, 8791 dViewDirW, 8792 dReflDirW, 8793 litArgs_gloss, 8794 litArgs_specularity, 8795 dVertexNormalW, 8796 dTBN 8797 #if defined(LIT_IRIDESCENCE) 8798 , iridescenceFresnel, 8799 litArgs_iridescence_intensity 8800 #endif 8801 ); 8802 #endif 8803 #ifdef LIT_LIGHTING || LIT_REFLECTIONS 8804 #ifdef LIT_REFLECTIONS 8805 #ifdef LIT_CLEARCOAT 8806 addReflectionCC(ccReflDirW, litArgs_clearcoat_gloss); 8807 8808 #ifdef LIT_SPECULAR_FRESNEL 8809 ccFresnel = getFresnelCC(dot(dViewDirW, litArgs_clearcoat_worldNormal)); 8810 ccReflection = ccReflection * ccFresnel; 8811 #else 8812 ccFresnel = 0.0; 8813 #endif 8814 #endif 8815 #ifdef LIT_SPECULARITY_FACTOR 8816 ccReflection = ccReflection * litArgs_specularityFactor; 8817 #endif 8818 #ifdef LIT_SHEEN 8819 addReflectionSheen(litArgs_worldNormal, dViewDirW, litArgs_sheen_gloss); 8820 #endif 8821 addReflection(dReflDirW, litArgs_gloss); 8822 #ifdef LIT_FRESNEL_MODEL 8823 dReflection = vec4f( 8824 dReflection.rgb * getFresnel( 8825 dot(dViewDirW, litArgs_worldNormal), 8826 litArgs_gloss, 8827 litArgs_specularity 8828 #if defined(LIT_IRIDESCENCE) 8829 , iridescenceFresnel, 8830 litArgs_iridescence_intensity 8831 #endif 8832 ), 8833 dReflection.a 8834 ); 8835 #else 8836 dReflection = vec4f(dReflection.rgb * litArgs_specularity, dReflection.a); 8837 #endif 8838 #endif 8839 #ifdef AREA_LIGHTS 8840 dSpecularLight = dSpecularLight * litArgs_specularity; 8841 #ifdef LIT_SPECULAR 8842 calcLTCLightValues(litArgs_gloss, litArgs_worldNormal, dViewDirW, litArgs_specularity, litArgs_clearcoat_gloss, litArgs_clearcoat_worldNormal, litArgs_clearcoat_specularity); 8843 #endif 8844 #endif 8845 8846 #ifdef LIGHT_COUNT > 0 8847 #include "lightEvaluationPS, LIGHT_COUNT" 8848 #endif 8849 #ifdef LIT_CLUSTERED_LIGHTS 8850 addClusteredLights(litArgs_worldNormal, dViewDirW, dReflDirW, 8851 #if defined(LIT_CLEARCOAT) 8852 ccReflDirW, 8853 #endif 8854 litArgs_gloss, litArgs_specularity, dVertexNormalW, dTBN, 8855 #if defined(LIT_IRIDESCENCE) 8856 iridescenceFresnel, 8857 #endif 8858 litArgs_clearcoat_worldNormal, litArgs_clearcoat_gloss, litArgs_sheen_gloss, litArgs_iridescence_intensity 8859 ); 8860 #endif 8861 #ifdef AREA_LIGHTS 8862 #ifdef LIT_CLEARCOAT 8863 litArgs_clearcoat_specularity = 1.0; 8864 #endif 8865 #ifdef LIT_SPECULAR 8866 litArgs_specularity = vec3(1.0); 8867 #endif 8868 #endif 8869 #ifdef LIT_REFRACTION 8870 addRefraction( 8871 litArgs_worldNormal, 8872 dViewDirW, 8873 litArgs_thickness, 8874 litArgs_gloss, 8875 litArgs_specularity, 8876 litArgs_albedo, 8877 litArgs_transmission,
8878 litArgs_ior, 8879 litArgs_dispersion 8880 #if defined(LIT_IRIDESCENCE) 8881 , iridescenceFresnel, 8882 litArgs_iridescence_intensity 8883 #endif 8884 ); 8885 #endif 8886 #endif 8887 #ifdef LIT_AO 8888 #ifdef LIT_OCCLUDE_DIRECT 8889 occludeDiffuse(litArgs_ao); 8890 #endif 8891 #if LIT_OCCLUDE_SPECULAR != NONE 8892 occludeSpecular(litArgs_gloss, litArgs_ao, litArgs_worldNormal, dViewDirW); 8893 #endif 8894 #endif 8895 #if !defined(LIT_OPACITY_FADES_SPECULAR) 8896 #if LIT_BLEND_TYPE == NORMAL || LIT_BLEND_TYPE == PREMULTIPLIED 8897 var specLum: f32 = dot((dSpecularLight + dReflection.rgb * dReflection.a), vec3f( 0.2126, 0.7152, 0.0722 )); 8898 #ifdef LIT_CLEARCOAT 8899 specLum = specLum + dot(ccSpecularLight * litArgs_clearcoat_specularity + ccReflection * litArgs_clearcoat_specularity, vec3f( 0.2126, 0.7152, 0.0722 )); 8900 #endif 8901 litArgs_opacity = clamp(litArgs_opacity + gammaCorrectInput(specLum), 0.0, 1.0); 8902 #endif 8903 litArgs_opacity = litArgs_opacity * uniform.material_alphaFade; 8904 #endif 8905 #ifdef LIT_LIGHTMAP_BAKING 8906 #ifdef LIT_LIGHTMAP_BAKING_COLOR 8907 #include "bakeLmEndPS" 8908 #endif 8909 #ifdef LIT_LIGHTMAP_BAKING_DIR 8910 #include "bakeDirLmEndPS" 8911 #endif 8912 #else 8913 #include "endPS" 8914 #include "outputAlphaPS" 8915 #endif 8916 #ifdef LIT_MSDF 8917 output.color = applyMsdf(output.color); 8918 #endif 8919 #include "outputPS" 8920 #include "debugOutputPS" 8921 #ifdef LIT_SHADOW_CATCHER 8922 output.color = vec4f(vec3f(dShadowCatcher), output.color.a); 8923 #endif 8924 return output; 8925} 8926`,KF=` 8927var<private> sReflection: vec3f; 8928var<private> dVertexNormalW: vec3f; 8929var<private> dTangentW: vec3f; 8930var<private> dBinormalW: vec3f; 8931var<private> dViewDirW: vec3f; 8932var<private> dReflDirW: vec3f; 8933var<private> ccReflDirW: vec3f; 8934var<private> dLightDirNormW: vec3f; 8935var<private> dAtten: f32; 8936var<private> dTBN: mat3x3f; 8937var<private> dReflection: vec4f; 8938var<private> dDiffuseLight: vec3f; 8939var<private> dSpecularLight: vec3f; 8940var<private> ccFresnel: f32; 8941var<private> ccReflection: vec3f; 8942var<private> ccSpecularLight: vec3f; 8943var<private> ccSpecularityNoFres: f32; 8944var<private> sSpecularLight: vec3f; 8945#ifdef LIT_DISPERSION 8946 uniform material_dispersion: f32; 8947#endif 8948#ifndef LIT_OPACITY_FADES_SPECULAR 8949 uniform material_alphaFade: f32; 8950#endif 8951#ifdef LIT_SSAO 8952 var ssaoTexture : texture_2d<f32>; 8953 var ssaoTextureSampler : sampler; 8954 uniform ssaoTextureSizeInv: vec2f; 8955#endif 8956#ifdef LIT_SHADOW_CATCHER 8957 var<private> dShadowCatcher: f32 = 1.0; 8958#endif 8959#if LIGHT_COUNT > 0 8960 #include "lightDeclarationPS, LIGHT_COUNT" 8961#endif 8962#ifdef LIT_SPECULAR 8963 #if LIT_FRESNEL_MODEL == NONE && !defined(LIT_REFLECTIONS) && !defined(LIT_DIFFUSE_MAP) 8964 #define LIT_OLD_AMBIENT 8965 #endif 8966#endif 8967#ifdef STD_LIGHTMAP_DIR 8968 uniform bakeDir: f32; 8969#endif 8970#ifdef LIT_LIGHTMAP_BAKING_ADD_AMBIENT 8971 uniform ambientBakeOcclusionContrast: f32; 8972 uniform ambientBakeOcclusionBrightness: f32; 8973#endif 8974`,ZF=` 8975@fragment 8976fn fragmentMain(input: FragmentInput) -> FragmentOutput { 8977 #include "litUserMainStartPS" 8978 dReflection = vec4f(0.0); 8979 #ifdef LIT_CLEARCOAT 8980 ccSpecularLight = vec3f(0.0); 8981 ccReflection = vec3f(0.0); 8982 #endif 8983 #if LIT_NONE_SLICE_MODE == SLICED 8984 #include "startNineSlicedPS" 8985 #elif LIT_NONE_SLICE_MODE == TILED 8986 #include "startNineSlicedTiledPS" 8987 #endif 8988 #ifdef LIT_NEEDS_NORMAL 8989 dVertexNormalW = normalize(vNormalW); 8990 #ifdef LIT_TANGENTS 8991 #if defined(LIT_HEIGHTS) || defined(LIT_USE_NORMALS) || defined(LIT_USE_CLEARCOAT_NORMALS) || defined(LIT_GGX_SPECULAR) 8992 dTangentW = vTangentW; 8993 dBinormalW = vBinormalW; 8994 #endif 8995 #endif 8996 getViewDir(); 8997 #ifdef LIT_TBN 8998 getTBN(dTangentW, dBinormalW, dVertexNormalW); 8999 #ifdef LIT_TWO_SIDED_LIGHTING 9000 handleTwoSidedLighting(); 9001 #endif 9002 #endif 9003 #endif 9004 evaluateFrontend(); 9005 #include "debugProcessFrontendPS" 9006 var output: FragmentOutput = evaluateBackend(); 9007 #include "litUserMainEndPS" 9008 return output; 9009} 9010`,QF=` 9011#ifdef LIT_NEEDS_NORMAL 9012 #include "cubeMapRotatePS" 9013 #include "cubeMapProjectPS" 9014 #include "envProcPS" 9015#endif 9016#ifdef LIT_SPECULAR_OR_REFLECTION 9017 #ifdef LIT_METALNESS 9018 #include "metalnessModulatePS" 9019 #endif 9020 #ifdef LIT_IRIDESCENCE 9021 #include "iridescenceDiffractionPS" 9022 #endif 9023#endif 9024#if defined(LIT_SPECULAR_OR_REFLECTION) || defined(LIT_REFRACTION) 9025 #if LIT_FRESNEL_MODEL == SCHLICK 9026 #include "fresnelSchlickPS" 9027 #endif 9028#endif 9029#ifdef LIT_AO 9030 #include "aoDiffuseOccPS" 9031 #include "aoSpecOccPS" 9032#endif 9033#if LIT_REFLECTION_SOURCE == ENVATLASHQ 9034 #include "envAtlasPS"
9035 #include "reflectionEnvHQPS" 9036#elif LIT_REFLECTION_SOURCE == ENVATLAS 9037 #include "envAtlasPS" 9038 #include "reflectionEnvPS" 9039#elif LIT_REFLECTION_SOURCE == CUBEMAP 9040 #include "reflectionCubePS" 9041#elif LIT_REFLECTION_SOURCE == SPHEREMAP 9042 #include "reflectionSpherePS" 9043#endif 9044#ifdef LIT_REFLECTIONS 9045 #ifdef LIT_CLEARCOAT 9046 #include "reflectionCCPS" 9047 #endif 9048 #ifdef LIT_SHEEN 9049 #include "reflectionSheenPS" 9050 #endif 9051#endif 9052#ifdef LIT_REFRACTION 9053 #if defined(LIT_DYNAMIC_REFRACTION) 9054 #include "refractionDynamicPS" 9055 #elif defined(LIT_REFLECTIONS) 9056 #include "refractionCubePS" 9057 #endif 9058#endif 9059#ifdef LIT_SHEEN 9060 #include "lightSheenPS" 9061#endif 9062uniform material_ambient: vec3f; 9063#ifdef LIT_SPECULAR 9064 #ifdef LIT_LIGHTING 9065 #ifdef LIT_GGX_SPECULAR 9066 #ifdef LIT_ANISOTROPY 9067 #include "lightSpecularAnisoGGXPS" 9068 #else 9069 #include "lightSpecularGGXPS" 9070 #endif 9071 #else 9072 #include "lightSpecularBlinnPS" 9073 #endif 9074 #endif 9075#endif 9076#include "combinePS" 9077#ifdef LIT_LIGHTMAP 9078 #include "lightmapAddPS" 9079#endif 9080#ifdef LIT_ADD_AMBIENT 9081 #include "ambientPS" 9082#endif 9083#ifdef LIT_MSDF 9084 #include "msdfPS" 9085#endif 9086#ifdef LIT_NEEDS_NORMAL 9087 #include "viewDirPS" 9088 #ifdef LIT_SPECULAR 9089 #ifdef LIT_ANISOTROPY 9090 #include "reflDirAnisoPS" 9091 #else 9092 #include "reflDirPS" 9093 #endif 9094 #endif 9095#endif 9096#include "lightingPS" 9097`,JF=` 9098#include "basePS" 9099#include "sphericalPS" 9100#include "decodePS" 9101#include "gammaPS" 9102#include "tonemappingPS" 9103#include "fogPS" 9104#if LIT_NONE_SLICE_MODE == SLICED 9105 #include "baseNineSlicedPS" 9106#elif LIT_NONE_SLICE_MODE == TILED 9107 #include "baseNineSlicedTiledPS" 9108#endif 9109#ifdef LIT_TBN 9110 #include "TBNPS" 9111 #ifdef LIT_TWO_SIDED_LIGHTING 9112 #include "twoSidedLightingPS" 9113 #endif 9114#endif 9115`,eO=` 9116#include "varyingsPS" 9117#include "litUserDeclarationPS" 9118#include "frontendDeclPS" 9119#if defined(PICK_PASS) || defined(PREPASS_PASS) 9120 #include "frontendCodePS" 9121 #include "litUserCodePS" 9122 #include "litOtherMainPS" 9123#elif defined(SHADOW_PASS) 9124 #include "frontendCodePS" 9125 #include "litUserCodePS" 9126 #include "litShadowMainPS" 9127#else 9128 #include "litForwardDeclarationPS" 9129 #include "litForwardPreCodePS" 9130 #include "frontendCodePS" 9131 #include "litForwardPostCodePS" 9132 #include "litForwardBackendPS" 9133 #include "litUserCodePS" 9134 #include "litForwardMainPS" 9135#endif 9136`,tO=` 9137#include "varyingsVS" 9138#include "litUserDeclarationVS" 9139#ifdef VERTEX_COLOR 9140 attribute vertex_color: vec4f; 9141#endif 9142#ifdef NINESLICED 9143 varying vMask: vec2f; 9144 varying vTiledUv: vec2f; 9145 var<private> dMaskGlobal: vec2f; 9146 var<private> dTiledUvGlobal: vec2f; 9147 uniform innerOffset: vec4f; 9148 uniform outerScale: vec2f; 9149 uniform atlasRect: vec4f; 9150#endif 9151var<private> dPositionW: vec3f; 9152var<private> dModelMatrix: mat4x4f; 9153#include "transformCoreVS" 9154#ifdef UV0 9155 attribute vertex_texCoord0: vec2f; 9156 #include "uv0VS" 9157#endif 9158#ifdef UV1 9159 attribute vertex_texCoord1: vec2f; 9160 #include "uv1VS" 9161#endif 9162#ifdef LINEAR_DEPTH 9163 #ifndef VIEWMATRIX 9164 #define VIEWMATRIX 9165 uniform matrix_view: mat4x4f; 9166 #endif 9167#endif 9168#include "transformVS" 9169#ifdef NORMALS 9170 #include "normalCoreVS" 9171 #include "normalVS" 9172#endif 9173#ifdef TANGENTS 9174 attribute vertex_tangent: vec4f; 9175#endif 9176#include "uvTransformUniformsPS, UV_TRANSFORMS_COUNT" 9177#ifdef MSDF 9178 #include "msdfVS" 9179#endif 9180#include "litUserCodeVS" 9181#ifdef VERTEX_COLOR 9182 fn decodeGamma3(raw: vec3f) -> vec3f { 9183 return pow(raw, vec3f(2.2)); 9184 } 9185 fn gammaCorrectInputVec4(color: vec4f) -> vec4f { 9186 return vec4f(decodeGamma3(color.xyz), color.w); 9187 } 9188#endif 9189@vertex 9190fn vertexMain(input : VertexInput) -> VertexOutput { 9191 #include "litUserMainStartVS" 9192 var output : VertexOutput; 9193 output.position = getPosition(); 9194 output.vPositionW = getWorldPosition(); 9195 #ifdef NORMALS 9196 output.vNormalW = getNormal(); 9197 #endif 9198 #ifdef TANGENTS 9199 output.vTangentW = normalize(dNormalMatrix * vertex_tangent.xyz); 9200 output.vBinormalW = cross(output.vNormalW, output.vTangentW) * vertex_tangent.w; 9201 #elif defined(GGX_SPECULAR) 9202 output.vObjectSpaceUpW = normalize(dNormalMatrix * vec3f(0.0, 1.0, 0.0)); 9203 #endif 9204 #ifdef UV0 9205 var uv0: vec2f = getUv0(); 9206 #ifdef UV0_UNMODIFIED 9207 output.vUv0 = uv0; 9208 #endif 9209 #endif 9210 #ifdef UV1 9211 var uv1: vec2f = getUv1(); 9212 #ifdef UV1_UNMODIFIED 9213 output.vUv1 = uv1; 9214 #endif 9215 #endif 9216 #include "uvTransformVS, UV_TRANSFORMS_COUNT" 9217 #ifdef VERTEX_COLOR 9218 #ifdef STD_VERTEX_COLOR_GAMMA 9219 output.vVertexColor = gammaCorrectInputVec4(vertex_color); 9220 #else 9221 output.vVertexColor = vertex_color; 9222 #endif 9223 #endif 9224 #ifdef LINEAR_DEPTH 9225 output.vLinearDepth = -(uniform.matrix_view * vec4f(output.vPositionW, 1.0)).z; 9226 #endif 9227 #ifdef MSDF 9228 unpackMsdfParams(); 9229 output.outline_color = dOutlineColor; 9230 output.outline_thickness = dOutlineThickness; 9231 output.shadow_color = dShadowColor; 9232 output.shadow_offset = dShadowOffset; 9233 #endif 9234 #ifdef NINESLICED 9235 output.vMask = dMaskGlobal; 9236 output.vTiledUv = dTiledUvGlobal; 9237 #endif 9238 #include "litUserMainEndVS" 9239 return output; 9240} 9241`,sO=` 9242#ifdef PICK_PASS 9243 #include "pickPS" 9244#endif 9245#ifdef PREPASS_PASS 9246 #include "floatAsUintPS" 9247#endif 9248@fragment 9249fn fragmentMain(input: FragmentInput) -> FragmentOutput { 9250 #include "litUserMainStartPS" 9251 var output: FragmentOutput; 9252 9253 evaluateFrontend(); 9254 #ifdef PICK_PASS 9255 output.color = getPickOutput(); 9256 #ifdef DEPTH_PICK_PASS 9257 output.color1 = getPickDepth(); 9258 #endif 9259 #endif 9260 #ifdef PREPASS_PASS 9261 output.color = float2vec4(vLinearDepth); 9262 #endif 9263 #include "litUserMainEndPS" 9264 return output; 9265} 9266`,iO=` 9267var<private> litArgs_albedo: vec3f; 9268var<private> litArgs_opacity: f32; 9269var<private> litArgs_emission: vec3f; 9270var<private> litArgs_worldNormal: vec3f; 9271var<private> litArgs_ao: f32; 9272var<private> litArgs_lightmap: vec3f; 9273var<private> litArgs_lightmapDir: vec3f; 9274var<private> litArgs_metalness: f32; 9275var<private> litArgs_specularity: vec3f; 9276var<private> litArgs_specularityFactor: f32; 9277var<private> litArgs_gloss: f32; 9278var<private> litArgs_sheen_gloss: f32; 9279var<private> litArgs_sheen_specularity: vec3f; 9280var<private> litArgs_transmission: f32; 9281var<private> litArgs_thickness: f32; 9282var<private> litArgs_ior: f32; 9283var<private>
9283 litArgs_dispersion: f32; 9284var<private> litArgs_iridescence_intensity: f32; 9285var<private> litArgs_iridescence_thickness: f32; 9286var<private> litArgs_clearcoat_worldNormal: vec3f; 9287var<private> litArgs_clearcoat_specularity: f32; 9288var<private> litArgs_clearcoat_gloss: f32; 9289`,rO=` 9290 #if LIT_NONE_SLICE_MODE == TILED 9291 var<private> textureBias: f32 = -1000.0; 9292 #else 9293 uniform textureBias: f32; 9294 #endif 9295 #include "litShaderArgsPS" 9296`,aO=` 9297#if LIGHT_TYPE != DIRECTIONAL 9298 uniform view_position: vec3f; 9299 uniform light_radius: f32; 9300#endif 9301#if SHADOW_TYPE == PCSS_32F 9302 #include "linearizeDepthPS" 9303#endif 9304@fragment 9305fn fragmentMain(input: FragmentInput) -> FragmentOutput { 9306 #include "litUserMainStartPS" 9307 var output: FragmentOutput; 9308 evaluateFrontend(); 9309 #ifdef PERSPECTIVE_DEPTH 9310 var depth: f32 = input.position.z; 9311 #if SHADOW_TYPE == PCSS_32F 9312 #if LIGHT_TYPE != DIRECTIONAL 9313 depth = linearizeDepthWithParams(depth, camera_params); 9314 #endif 9315 #endif 9316 #else 9317 var depth: f32 = min(distance(uniform.view_position, input.vPositionW) / uniform.light_radius, 0.99999); 9318 #define MODIFIED_DEPTH 9319 #endif 9320 #if SHADOW_TYPE == VSM_16F || SHADOW_TYPE == VSM_32F 9321 #if SHADOW_TYPE == VSM_32F 9322 var exponent: f32 = 15.0; 9323 #else 9324 var exponent: f32 = 5.54; 9325 #endif 9326 var depth_vsm = 2.0 * depth - 1.0; 9327 depth_vsm = exp(exponent * depth_vsm); 9328 output.color = vec4f(depth_vsm, depth_vsm * depth_vsm, 1.0, 1.0); 9329 #else 9330 #if SHADOW_TYPE == PCSS_32F 9331 output.color = vec4f(depth, 0.0, 0.0, 1.0); 9332 #else 9333 #ifdef MODIFIED_DEPTH 9334 output.fragDepth = depth; 9335 #endif 9336 output.color = vec4f(1.0); 9337 #endif 9338 #endif 9339 #include "litUserMainEndPS" 9340 9341 return output; 9342} 9343`,nO=` 9344fn LTC_Uv(N: vec3f, V: vec3f, roughness: f32) -> vec2f { 9345 const LUT_SIZE: f32 = 64.0; 9346 const LUT_SCALE: f32 = (LUT_SIZE - 1.0) / LUT_SIZE; 9347 const LUT_BIAS: f32 = 0.5 / LUT_SIZE; 9348 let dotNV: f32 = saturate(dot( N, V )); 9349 let uv: vec2f = vec2f( roughness, sqrt( 1.0 - dotNV ) ); 9350 return uv * LUT_SCALE + LUT_BIAS; 9351} 9352fn LTC_ClippedSphereFormFactor( f: vec3f ) -> f32 { 9353 let l: f32 = length( f ); 9354 return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); 9355} 9356fn LTC_EdgeVectorFormFactor( v1: vec3f, v2: vec3f ) -> vec3f { 9357 let x: f32 = dot( v1, v2 ); 9358 let y: f32 = abs( x ); 9359 let a: f32 = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; 9360 let b: f32 = 3.4175940 + ( 4.1616724 + y ) * y; 9361 let v: f32 = a / b;
9362 let inv_sqrt_term = inverseSqrt( max( 1.0 - x * x, 1e-7f ) ); 9363 let theta_sintheta: f32 = select( (0.5 * inv_sqrt_term - v), v, x > 0.0 ); 9364 return cross( v1, v2 ) * theta_sintheta; 9365} 9366struct Coords { 9367 coord0: vec3f, 9368 coord1: vec3f, 9369 coord2: vec3f, 9370 coord3: vec3f, 9371} 9372fn LTC_EvaluateRect( N: vec3f, V: vec3f, P: vec3f, mInv: mat3x3f, rectCoords: Coords) -> f32 { 9373 let v1: vec3f = rectCoords.coord1 - rectCoords.coord0; 9374 let v2: vec3f = rectCoords.coord3 - rectCoords.coord0; 9375 let lightNormal: vec3f = cross( v1, v2 ); 9376 let factor: f32 = sign(-dot( lightNormal, P - rectCoords.coord0 )); 9377 let T1: vec3f = normalize( V - N * dot( V, N ) ); 9378 let T2: vec3f = factor * cross( N, T1 ); 9379 let mat: mat3x3f = mInv * transpose( mat3x3f( T1, T2, N ) ); 9380 var coords: array<vec3f, 4>; 9381 coords[0] = mat * ( rectCoords.coord0 - P ); 9382 coords[1] = mat * ( rectCoords.coord1 - P ); 9383 coords[2] = mat * ( rectCoords.coord2 - P ); 9384 coords[3] = mat * ( rectCoords.coord3 - P ); 9385 coords[0] = normalize( coords[0] ); 9386 coords[1] = normalize( coords[1] ); 9387 coords[2] = normalize( coords[2] ); 9388 coords[3] = normalize( coords[3] ); 9389 var vectorFormFactor: vec3f = vec3f( 0.0 ); 9390 vectorFormFactor = vectorFormFactor + LTC_EdgeVectorFormFactor( coords[0], coords[1] ); 9391 vectorFormFactor = vectorFormFactor + LTC_EdgeVectorFormFactor( coords[1], coords[2] ); 9392 vectorFormFactor = vectorFormFactor + LTC_EdgeVectorFormFactor( coords[2], coords[3] ); 9393 vectorFormFactor = vectorFormFactor + LTC_EdgeVectorFormFactor( coords[3], coords[0] ); 9394 let result: f32 = LTC_ClippedSphereFormFactor( vectorFormFactor ); 9395 return result; 9396} 9397var<private> dLTCCoords: Coords; 9398fn getLTCLightCoords(lightPos: vec3f, halfWidth: vec3f, halfHeight: vec3f) -> Coords { 9399 var coords: Coords; 9400 coords.coord0 = lightPos + halfWidth - halfHeight; 9401 coords.coord1 = lightPos - halfWidth - halfHeight; 9402 coords.coord2 = lightPos - halfWidth + halfHeight; 9403 coords.coord3 = lightPos + halfWidth + halfHeight; 9404 return coords; 9405} 9406var<private> dSphereRadius: f32; 9407fn getSphereLightCoords(lightPos: vec3f, halfWidth: vec3f, halfHeight: vec3f) -> Coords { 9408 dSphereRadius = max(length(halfWidth), length(halfHeight)); 9409 let f: vec3f = reflect(normalize(lightPos - uniform.view_position), vNormalW); 9410 let w: vec3f = normalize(cross(f, halfHeight)); 9411 let h: vec3f = normalize(cross(f, w)); 9412 return getLTCLightCoords(lightPos, w * dSphereRadius, h * dSphereRadius); 9413} 9414var<private> dLTCUV: vec2f; 9415#ifdef LIT_CLEARCOAT 9416 var<private> ccLTCUV: vec2f; 9417#endif 9418fn getLTCLightUV(gloss: f32, worldNormal: vec3f, viewDir: vec3f) -> vec2f { 9419 let roughness: f32 = max((1.0 - gloss) * (1.0 - gloss), 0.001); 9420 return LTC_Uv( worldNormal, viewDir, roughness ); 9421} 9422var<private> dLTCSpecFres: vec3f; 9423#ifdef LIT_CLEARCOAT 9424 var<private> ccLTCSpecFres: vec3f; 9425#endif 9426fn getLTCLightSpecFres(uv: vec2f, specularity: vec3f) -> vec3f { 9427 let t2: vec4f = textureSampleLevel(areaLightsLutTex2, areaLightsLutTex2Sampler, uv, 0.0); 9428 return specularity * t2.x + ( vec3f( 1.0 ) - specularity) * t2.y; 9429} 9430fn calcLTCLightValues(gloss: f32, worldNormal: vec3f, viewDir: vec3f, specularity: vec3f, clearcoatGloss: f32, clearcoatWorldNormal: vec3f, clearcoatSpecularity: f32) { 9431 dLTCUV = getLTCLightUV(gloss, worldNormal, viewDir); 9432 dLTCSpecFres = getLTCLightSpecFres(dLTCUV, specularity); 9433 #ifdef LIT_CLEARCOAT 9434 ccLTCUV = getLTCLightUV(clearcoatGloss, clearcoatWorldNormal, viewDir); 9435 ccLTCSpecFres = getLTCLightSpecFres(ccLTCUV, vec3f(clearcoatSpecularity)); 9436 #endif 9437} 9438fn calcRectLightValues(lightPos: vec3f, halfWidth: vec3f, halfHeight: vec3f) { 9439 dLTCCoords = getLTCLightCoords(lightPos, halfWidth, halfHeight); 9440} 9441fn calcDiskLightValues(lightPos: vec3f, halfWidth: vec3f, halfHeight: vec3f) { 9442 calcRectLightValues(lightPos, halfWidth, halfHeight); 9443} 9444fn calcSphereLightValues(lightPos: vec3f, halfWidth: vec3f, halfHeight: vec3f) { 9445 dLTCCoords = getSphereLightCoords(lightPos, halfWidth, halfHeight); 9446} 9447fn SolveCubic(Coefficient_in: vec4f) -> vec3f { 9448 let pi: f32 = 3.14159; 9449 var Coefficient = Coefficient_in; 9450 Coefficient = vec4f(Coefficient.xyz / Coefficient.w, Coefficient.w); 9451 let new_yz: vec2f = Coefficient.yz / 3.0; 9452 Coefficient = vec4f(Coefficient.x, new_yz.x, new_yz.y, Coefficient.w); 9453 9454 let A: f32 = Coefficient.w; 9455 let B: f32 = Coefficient.z; 9456 let C: f32 = Coefficient.y; 9457 let D: f32 = Coefficient.x; 9458 let Delta: vec3f = vec3f( 9459 -Coefficient.z * Coefficient.z + Coefficient.y, 9460 -Coefficient.y * Coefficient.z + Coefficient.x, 9461 dot(vec2f(Coefficient.z, -Coefficient.y), Coefficient.xy) 9462 ); 9463 let Discriminant: f32 = dot(vec2f(4.0 * Delta.x, -Delta.y), Delta.zy); 9464 var xlc: vec2f; 9465 var xsc: vec2f; 9466 { 9467 let A_a: f32 = 1.0; 9468 let C_a: f32 = Delta.x; 9469 let D_a: f32 = -2.0 * B * Delta.x + Delta.y; 9470 let Theta: f32 = atan2(sqrt(Discriminant), -D_a) / 3.0; 9471 let sqrt_neg_Ca = sqrt(-C_a); 9472 let x_1a: f32 = 2.0 * sqrt_neg_Ca * cos(Theta); 9473 let x_3a: f32 = 2.0 * sqrt_neg_Ca * cos(Theta + (2.0 / 3.0) * pi); 9474 let xl: f32 = select(x_3a, x_1a, (x_1a + x_3a) > 2.0 * B); 9475 xlc = vec2f(xl - B, A); 9476 } 9477 { 9478 let A_d: f32 = D; 9479 let C_d: f32 = Delta.z; 9480 let D_d: f32 = -D * Delta.y + 2.0 * C * Delta.z; 9481 let Theta: f32 = atan2(D * sqrt(Discriminant), -D_d) / 3.0; 9482 let sqrt_neg_Cd = sqrt(-C_d); 9483 let x_1d: f32 = 2.0 * sqrt_neg_Cd * cos(Theta); 9484 let x_3d: f32 = 2.0 * sqrt_neg_Cd * cos(Theta + (2.0 / 3.0) * pi); 9485 let xs: f32 = select(x_3d, x_1d, x_1d + x_3d < 2.0 * C); 9486 xsc = vec2f(-D, xs + C); 9487 } 9488 let E: f32 = xlc.y * xsc.y; 9489 let F: f32 = -xlc.x * xsc.y - xlc.y * xsc.x; 9490 let G: f32 = xlc.x * xsc.x; 9491 let xmc: vec2f = vec2f(C * F - B * G, -B * F + C * E); 9492 var Root: vec3f = vec3f(xsc.x / xsc.y, xmc.x / xmc.y, xlc.x / xlc.y); 9493 if (Root.x < Root.y && Root.x < Root.z) { 9494 Root = Root.yxz; 9495 } else if (Root.z < Root.x && Root.z < Root.y) { 9496 Root = Root.xzy; 9497 } 9498 return Root; 9499} 9500fn LTC_EvaluateDisk(N: vec3f, V: vec3f, P: vec3f, Minv: mat3x3f, points: Coords) -> f32 { 9501 let T1: vec3f = normalize(V - N * dot(V, N)); 9502 let T2: vec3f = cross(N, T1); 9503 let R: mat3x3f = transpose( mat3x3f( T1, T2, N ) ); 9504 var L_: array<vec3f, 3>; 9505 L_[0] = R * ( points.coord0 - P ); 9506 L_[1] = R * ( points.coord1 - P ); 9507 L_[2] = R * ( points.coord2 - P ); 9508 let C: vec3f = 0.5 * (L_[0] + L_[2]); 9509 var V1: vec3f = 0.5 * (L_[1] - L_[2]); 9510 var V2: vec3f = 0.5 * (L_[1] - L_[0]); 9511 let C_Minv: vec3f = Minv * C; 9512 let V1_Minv: vec3f = Minv * V1; 9513 let V2_Minv: vec3f = Minv * V2; 9514 var a: f32; 9515 var b: f32; 9516 let d11: f32 = dot(V1_Minv, V1_Minv); 9517 let d22: f32 = dot(V2_Minv, V2_Minv); 9518 let d12: f32 = dot(V1_Minv, V2_Minv);
9519 if (abs(d12) / sqrt(d11 * d22) > 0.0001) { 9520 let tr: f32 = d11 + d22; 9521 let det_inner: f32 = -d12 * d12 + d11 * d22; 9522 let det: f32 = sqrt(det_inner); 9523 let u: f32 = 0.5 * sqrt(tr - 2.0 * det); 9524 let v: f32 = 0.5 * sqrt(tr + 2.0 * det); 9525 let e_max: f32 = (u + v) * (u + v); 9526 let e_min: f32 = (u - v) * (u - v); 9527 var V1_: vec3f; 9528 var V2_: vec3f; 9529 if (d11 > d22) { 9530 V1_ = d12 * V1_Minv + (e_max - d11) * V2_Minv; 9531 V2_ = d12 * V1_Minv + (e_min - d11) * V2_Minv; 9532 } else { 9533 V1_ = d12*V2_Minv + (e_max - d22)*V1_Minv; 9534 V2_ = d12*V2_Minv + (e_min - d22)*V1_Minv; 9535 } 9536 a = 1.0 / e_max; 9537 b = 1.0 / e_min; 9538 V1 = normalize(V1_); 9539 V2 = normalize(V2_); 9540 } else { 9541 a = 1.0 / dot(V1_Minv, V1_Minv); 9542 b = 1.0 / dot(V2_Minv, V2_Minv); 9543 V1 = V1_Minv * sqrt(a); 9544 V2 = V2_Minv * sqrt(b); 9545 } 9546 var V3: vec3f = normalize(cross(V1, V2)); 9547 if (dot(C_Minv, V3) < 0.0) { 9548 V3 = V3 * -1.0; 9549 } 9550 let L: f32 = dot(V3, C_Minv); 9551 let x0: f32 = dot(V1, C_Minv) / L; 9552 let y0: f32 = dot(V2, C_Minv) / L; 9553 let E1: f32 = inverseSqrt(a); 9554 let E2: f32 = inverseSqrt(b); 9555 let a_scaled = a * L * L; 9556 let b_scaled = b * L * L; 9557 let c0: f32 = a_scaled * b_scaled; 9558 let c1: f32 = a_scaled * b_scaled * (1.0 + x0 * x0 + y0 * y0) - a_scaled - b_scaled; 9559 let c2: f32 = 1.0 - a_scaled * (1.0 + x0 * x0) - b_scaled * (1.0 + y0 * y0); 9560 let c3: f32 = 1.0; 9561 let roots: vec3f = SolveCubic(vec4f(c0, c1, c2, c3)); 9562 let e1: f32 = roots.x; 9563 let e2: f32 = roots.y; 9564 let e3: f32 = roots.z; 9565 var avgDir: vec3f = vec3f(a_scaled * x0 / (a_scaled - e2), b_scaled * y0 / (b_scaled - e2), 1.0); 9566 let rotate: mat3x3f = mat3x3f(V1, V2, V3); 9567 avgDir = rotate * avgDir; 9568 avgDir = normalize(avgDir); 9569 let L1: f32 = sqrt(-e2 / e3); 9570 let L2: f32 = sqrt(-e2 / e1); 9571 let formFactor: f32 = max(0.0, L1 * L2 * inverseSqrt((1.0 + L1 * L1) * (1.0 + L2 * L2))); 9572 const LUT_SIZE_disk: f32 = 64.0; 9573 const LUT_SCALE_disk: f32 = ( LUT_SIZE_disk - 1.0 ) / LUT_SIZE_disk; 9574 const LUT_BIAS_disk: f32 = 0.5 / LUT_SIZE_disk; 9575 var uv: vec2f = vec2f(avgDir.z * 0.5 + 0.5, formFactor); 9576 uv = uv * LUT_SCALE_disk + LUT_BIAS_disk; 9577 let scale: f32 = textureSampleLevel(areaLightsLutTex2, areaLightsLutTex2Sampler, uv, 0.0).w; 9578 return formFactor * scale; 9579} 9580fn FixNan(value: f32) -> f32 { 9581 return select(value, 0.0, value != value); 9582} 9583fn getRectLightDiffuse(worldNormal: vec3f, viewDir: vec3f, lightDir: vec3f, lightDirNorm: vec3f) -> f32 { 9584 let identityMat = mat3x3f(vec3f(1.0, 0.0, 0.0), vec3f(0.0, 1.0, 0.0), vec3f(0.0, 0.0, 1.0)); 9585 return LTC_EvaluateRect( worldNormal, viewDir, vPositionW, identityMat, dLTCCoords ); 9586} 9587fn getDiskLightDiffuse(worldNormal: vec3f, viewDir: vec3f, lightDir: vec3f, lightDirNorm: vec3f) -> f32 { 9588 let identityMat = mat3x3f(vec3f(1.0, 0.0, 0.0), vec3f(0.0, 1.0, 0.0), vec3f(0.0, 0.0, 1.0)); 9589 return FixNan(LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, identityMat, dLTCCoords )); 9590} 9591fn getSphereLightDiffuse(worldNormal: vec3f, viewDir: vec3f, lightDir: vec3f, lightDirNorm: vec3f) -> f32 { 9592 let falloff: f32 = dSphereRadius / (dot(lightDir, lightDir) + dSphereRadius); 9593 return FixNan(getLightDiffuse(worldNormal, viewDir, lightDirNorm) * falloff); 9594} 9595fn getLTCLightInvMat(uv: vec2f) -> mat3x3f { 9596 let t1: vec4f = textureSampleLevel(areaLightsLutTex1, areaLightsLutTex1Sampler, uv, 0.0); 9597 return mat3x3f( 9598 vec3f( t1.x, 0.0, t1.y ), 9599 vec3f( 0.0, 1.0, 0.0 ), 9600 vec3f( t1.z, 0.0, t1.w ) 9601 ); 9602} 9603fn calcRectLightSpecular(worldNormal: vec3f, viewDir: vec3f, uv: vec2f) -> f32 { 9604 let mInv: mat3x3f = getLTCLightInvMat(uv); 9605 return LTC_EvaluateRect( worldNormal, viewDir, vPositionW, mInv, dLTCCoords ); 9606} 9607fn getRectLightSpecular(worldNormal: vec3f, viewDir: vec3f) -> f32 { 9608 return calcRectLightSpecular(worldNormal, viewDir, dLTCUV); 9609} 9610fn calcDiskLightSpecular(worldNormal: vec3f, viewDir: vec3f, uv: vec2f) -> f32 { 9611 let mInv: mat3x3f = getLTCLightInvMat(uv); 9612 return LTC_EvaluateDisk( worldNormal, viewDir, vPositionW, mInv, dLTCCoords ); 9613} 9614fn getDiskLightSpecular(worldNormal: vec3f, viewDir: vec3f) -> f32 { 9615 return calcDiskLightSpecular(worldNormal, viewDir, dLTCUV); 9616} 9617fn getSphereLightSpecular(worldNormal: vec3f, viewDir: vec3f) -> f32 { 9618 return calcDiskLightSpecular(worldNormal, viewDir, dLTCUV); 9619} 9620`,oO=` 9621#ifdef STD_METALNESS_CONSTANT 9622uniform material_metalness: f32; 9623#endif 9624fn getMetalness() { 9625 var metalness: f32 = 1.0; 9626 #ifdef STD_METALNESS_CONSTANT 9627 metalness = metalness * uniform.material_metalness; 9628 #endif 9629 #ifdef STD_METALNESS_TEXTURE 9630 metalness = metalness * textureSampleBias({STD_METALNESS_TEXTURE_NAME}, {STD_METALNESS_TEXTURE_NAME}Sampler, {STD_METALNESS_TEXTURE_UV}, uniform.textureBias).{STD_METALNESS_TEXTURE_CHANNEL}; 9631 #endif 9632 #ifdef STD_METALNESS_VERTEX 9633 metalness = metalness * saturate(vVertexColor.{STD_METALNESS_VERTEX_CHANNEL}); 9634 #endif 9635 dMetalness = metalness; 9636} 9637`,lO=` 9638var texture_msdfMap: texture_2d<f32>; 9639var texture_msdfMapSampler: sampler; 9640fn median(r: f32, g: f32, b: f32) -> f32 { 9641 return max(min(r, g), min(max(r, g), b)); 9642} 9643fn map(min: f32, max: f32, v: f32) -> f32 { 9644 return (v - min) / (max - min); 9645} 9646uniform font_sdfIntensity: f32; 9647uniform font_pxrange: f32; 9648uniform font_textureWidth: f32; 9649#ifndef LIT_MSDF_TEXT_ATTRIBUTE 9650 uniform outline_color: vec4f; 9651 uniform outline_thickness: f32; 9652 uniform shadow_color: vec4f; 9653 uniform shadow_offset: vec2f; 9654#else 9655 varying outline_color: vec4f; 9656 varying outline_thickness: f32; 9657 varying shadow_color: vec4f; 9658 varying shadow_offset: vec2f; 9659#endif 9660fn applyMsdf(color_in: vec4f) -> vec4f { 9661 #ifndef LIT_MSDF_TEXT_ATTRIBUTE 9662 var outline_colorValue = uniform.outline_color; 9663 var outline_thicknessValue = uniform.outline_thickness;
9664 var shadow_colorValue = uniform.shadow_color; 9665 var shadow_offsetValue = uniform.shadow_offset; 9666 #else 9667 var outline_colorValue = outline_color; 9668 var outline_thicknessValue = outline_thickness; 9669 var shadow_colorValue = shadow_color; 9670 var shadow_offsetValue = shadow_offset; 9671 #endif 9672 var color = vec4f(gammaCorrectInputVec3(color_in.rgb), color_in.a); 9673 let tsample: vec3f = textureSample(texture_msdfMap, texture_msdfMapSampler, vUv0).rgb; 9674 let uvShdw: vec2f = vUv0 - shadow_offsetValue; 9675 let ssample: vec3f = textureSample(texture_msdfMap, texture_msdfMapSampler, uvShdw).rgb; 9676 let sigDist: f32 = median(tsample.r, tsample.g, tsample.b); 9677 var sigDistShdw: f32 = median(ssample.r, ssample.g, ssample.b); 9678 let smoothingMax: f32 = 0.2; 9679 let w: vec2f = abs(dpdx(vUv0)) + abs(dpdy(vUv0)); 9680 let smoothing: f32 = clamp(w.x * uniform.font_textureWidth / uniform.font_pxrange, 0.0, smoothingMax); 9681 let mapMin: f32 = 0.05; 9682 let mapMax: f32 = clamp(1.0 - uniform.font_sdfIntensity, mapMin, 1.0); 9683 let sigDistInner: f32 = map(mapMin, mapMax, sigDist); 9684 let sigDistOutline: f32 = map(mapMin, mapMax, sigDist + outline_thicknessValue); 9685 sigDistShdw = map(mapMin, mapMax, sigDistShdw + outline_thicknessValue); 9686 let center: f32 = 0.5; 9687 let inside: f32 = smoothstep(center - smoothing, center + smoothing, sigDistInner); 9688 let outline: f32 = smoothstep(center - smoothing, center + smoothing, sigDistOutline); 9689 let shadow: f32 = smoothstep(center - smoothing, center + smoothing, sigDistShdw); 9690 let tcolor_outline: vec4f = outline * vec4f(outline_colorValue.a * outline_colorValue.rgb, outline_colorValue.a); 9691 var tcolor: vec4f = select(vec4f(0.0), tcolor_outline, outline > inside); 9692 tcolor = mix(tcolor, color, inside); 9693 let scolor_shadow: vec4f = shadow * vec4f(shadow_colorValue.a * shadow_colorValue.rgb, shadow_colorValue.a); 9694 let scolor: vec4f = select(tcolor, scolor_shadow, shadow > outline); 9695 tcolor = mix(scolor, tcolor, outline); 9696 tcolor = vec4f(gammaCorrectOutput(tcolor.rgb), tcolor.a); 9697 return tcolor; 9698} 9699`,cO=` 9700fn getSpecularModulate(specularity: vec3f, albedo: vec3f, metalness: f32, f0: f32, specularityFactor: f32) -> vec3f { 9701 let dielectricF0: vec3f = f0 * specularity * specularityFactor; 9702 return mix(dielectricF0, albedo, metalness); 9703} 9704fn getAlbedoModulate(albedo: vec3f, metalness: f32) -> vec3f { 9705 return albedo * (1.0 - metalness); 9706} 9707`,hO=` 9708 varying uv0: vec2f; 9709 var morphTexture: texture_2d_array<f32>; 9710 uniform morphFactor: array<f32, {MORPH_TEXTURE_MAX_COUNT}>; 9711 uniform morphIndex: array<u32, {MORPH_TEXTURE_MAX_COUNT}>; 9712 uniform count: u32; 9713 @fragment 9714 fn fragmentMain(input : FragmentInput) -> FragmentOutput { 9715 var color = vec3f(0, 0, 0); 9716 let textureDims = textureDimensions(morphTexture); 9717 let pixelCoords = vec2i(input.uv0 * vec2f(textureDims)); 9718 9719 for (var i: u32 = 0; i < uniform.count; i = i + 1) { 9720 var textureIndex: u32 = uniform.morphIndex[i].element; 9721 var delta = textureLoad(morphTexture, pixelCoords, textureIndex, 0).xyz; 9722 color += uniform.morphFactor[i].element * delta; 9723 } 9724 var output: FragmentOutput; 9725 output.color = vec4f(color, 1.0); 9726 return output; 9727 } 9728`,dO=` 9729 attribute vertex_position: vec2f; 9730 varying uv0: vec2f; 9731 @vertex 9732 fn vertexMain(input: VertexInput) -> VertexOutput { 9733 var output: VertexOutput; 9734 output.position = vec4f(input.vertex_position, 0.5, 1.0); 9735 output.uv0 = input.vertex_position * 0.5 + vec2f(0.5, 0.5); 9736 return output; 9737 } 9738`,uO=` 9739attribute vertex_outlineParameters: vec3f; 9740attribute vertex_shadowParameters: vec3f; 9741varying outline_color: vec4f; 9742varying outline_thickness: f32; 9743varying shadow_color: vec4f; 9744varying shadow_offset: vec2f; 9745var<private> dOutlineColor: vec4f; 9746var<private> dOutlineThickness: f32; 9747var<private> dShadowColor: vec4f; 9748var<private> dShadowOffset: vec2f; 9749fn unpackMsdfParams() { 9750 let little: vec3f = vertex_outlineParameters % vec3f(256.0); 9751 let big: vec3f = (vertex_outlineParameters - little) / 256.0; 9752 dOutlineColor = vec4f(little.x, big.x, little.y, big.y) / 255.0; 9753 dOutlineThickness = little.z / 255.0 * 0.2; 9754 let little_shadow = vertex_shadowParameters % vec3f(256.0); 9755 let big_shadow = (vertex_shadowParameters - little_shadow) / 256.0; 9756 dShadowColor = vec4f(little_shadow.x, big_shadow.x, little_shadow.y, big_shadow.y) / 255.0; 9757 dShadowOffset = (vec2f(little_shadow.z, big_shadow.z) / 127.0 - 1.0) * 0.005; 9758} 9759`,fO=` 9760var<private> dNormalMatrix: mat3x3f; 9761fn getNormal() -> vec3f { 9762 dNormalMatrix = getNormalMatrix(dModelMatrix); 9763 let localNormal: vec3f = getLocalNormal(vertex_normal); 9764 return normalize(dNormalMatrix * localNormal); 9765}`,pO=` 9766attribute vertex_normal: vec3f; 9767uniform matrix_normal: mat3x3f; 9768#ifdef MORPHING_NORMAL 9769 #ifdef MORPHING_INT 9770 var morphNormalTex: texture_2d<u32>; 9771 var morphNormalTexSampler: sampler; 9772 #else 9773 var morphNormalTex: texture_2d<f32>; 9774 var morphNormalTexSampler: sampler; 9775 #endif 9776#endif 9777fn getLocalNormal(vertexNormal: vec3f) -> vec3f { 9778 var localNormal: vec3f = vertexNormal; 9779 #ifdef MORPHING_NORMAL 9780 let morphUV: vec2i = getTextureMorphCoords(); 9781 #ifdef MORPHING_INT 9782 let morphNormalInt: vec4u = textureLoad(morphNormalTex, morphUV, 0); 9783 let morphNormalF: vec3f = vec3f(morphNormalInt.xyz) / 65535.0 * 2.0 - 1.0; 9784 localNormal = localNormal + morphNormalF; 9785 #else 9786 let morphNormal: vec3f = textureLoad(morphNormalTex, morphUV, 0).xyz; 9787 localNormal = localNormal + morphNormal; 9788 #endif 9789 #endif 9790 return localNormal; 9791} 9792#if defined(SKIN) || defined(BATCH) 9793 fn getNormalMatrix(modelMatrix: mat4x4f) -> mat3x3f { 9794 return mat3x3f(modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz); 9795 } 9796#elif defined(INSTANCING) 9797 fn getNormalMatrix(modelMatrix: mat4x4f) -> mat3x3f { 9798 return mat3x3f(modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz); 9799 } 9800#else 9801 fn getNormalMatrix(modelMatrix: mat4x4f) -> mat3x3f { 9802 return uniform.matrix_normal; 9803 } 9804#endif 9805`,mO=` 9806#ifdef STD_NORMAL_TEXTURE 9807 uniform material_bumpiness: f32; 9808#endif 9809#ifdef STD_NORMALDETAIL_TEXTURE
9810 uniform material_normalDetailMapBumpiness: f32; 9811 fn blendNormals(inN1: vec3f, inN2: vec3f) -> vec3f { 9812 let n1: vec3f = inN1 + vec3f(0.0, 0.0, 1.0); 9813 let n2: vec3f = inN2 * vec3f(-1.0, -1.0, 1.0); 9814 return n1 * dot(n1, n2) / n1.z - n2; 9815 } 9816#endif 9817fn getNormal() { 9818#ifdef STD_NORMAL_TEXTURE 9819 var normalMap: vec3f = {STD_NORMAL_TEXTURE_DECODE}(textureSampleBias({STD_NORMAL_TEXTURE_NAME}, {STD_NORMAL_TEXTURE_NAME}Sampler, {STD_NORMAL_TEXTURE_UV}, uniform.textureBias)); 9820 normalMap = mix(vec3f(0.0, 0.0, 1.0), normalMap, uniform.material_bumpiness); 9821 #ifdef STD_NORMALDETAIL_TEXTURE 9822 var normalDetailMap: vec3f = {STD_NORMALDETAIL_TEXTURE_DECODE}(textureSampleBias({STD_NORMALDETAIL_TEXTURE_NAME}, {STD_NORMALDETAIL_TEXTURE_NAME}Sampler, {STD_NORMALDETAIL_TEXTURE_UV}, uniform.textureBias)); 9823 normalDetailMap = mix(vec3f(0.0, 0.0, 1.0), normalDetailMap, uniform.material_normalDetailMapBumpiness); 9824 normalMap = blendNormals(normalMap, normalDetailMap); 9825 #endif 9826 dNormalW = normalize(dTBN * normalMap); 9827#else 9828 dNormalW = dVertexNormalW; 9829#endif 9830} 9831`,_O=` 9832uniform material_opacity: f32; 9833uniform material_alphaDitherScale: f32; 9834fn getOpacity() { 9835 dAlpha = uniform.material_opacity; 9836 #ifdef STD_OPACITY_TEXTURE 9837 dAlpha = dAlpha * textureSampleBias({STD_OPACITY_TEXTURE_NAME}, {STD_OPACITY_TEXTURE_NAME}Sampler, {STD_OPACITY_TEXTURE_UV}, uniform.textureBias).{STD_OPACITY_TEXTURE_CHANNEL}; 9838 #endif 9839 #ifdef STD_OPACITY_VERTEX 9840 dAlpha = dAlpha * clamp(vVertexColor.{STD_OPACITY_VERTEX_CHANNEL}, 0.0, 1.0); 9841 #endif 9842} 9843`,gO=` 9844#if STD_OPACITY_DITHER == BAYER8 9845 #include "bayerPS" 9846#endif 9847uniform blueNoiseJitter: vec4f; 9848#if STD_OPACITY_DITHER == BLUENOISE 9849 var blueNoiseTex32 : texture_2d<f32>; 9850 var blueNoiseTex32Sampler : sampler; 9851#endif 9852fn opacityDither(alpha: f32, id: f32) { 9853 if (alpha <= 0.0) { 9854 discard; 9855 } 9856 if (alpha >= 1.0) { 9857 return; 9858 } 9859 #if STD_OPACITY_DITHER == BAYER8 9860 var noise: f32 = bayer8(floor((pcPosition.xy + uniform.blueNoiseJitter.xy + id) % vec2f(8.0))) / 64.0; 9861 #else 9862 #if STD_OPACITY_DITHER == BLUENOISE 9863 var uv = fract(pcPosition.xy / 32.0 + uniform.blueNoiseJitter.xy + id); 9864 var noise: f32 = textureSampleLevel(blueNoiseTex32, blueNoiseTex32Sampler, uv, 0.0).y; 9865 #endif 9866 #if STD_OPACITY_DITHER == IGNNOISE 9867 var magic = vec3f(0.06711056, 0.00583715, 52.9829189); 9868 var noise: f32 = fract(magic.z * fract(dot(pcPosition.xy + uniform.blueNoiseJitter.xy + id, magic.xy))); 9869 #endif 9870 #endif 9871 noise = pow(noise, 2.2); 9872 if (alpha < noise) { 9873 discard; 9874 } 9875} 9876`,vO=` 9877`,SO=` 9878#if LIT_BLEND_TYPE == NORMAL || LIT_BLEND_TYPE == ADDITIVEALPHA || defined(LIT_ALPHA_TO_COVERAGE) 9879 output.color = vec4f(output.color.rgb, litArgs_opacity); 9880#elif LIT_BLEND_TYPE == PREMULTIPLIED 9881 output.color = vec4f(output.color.rgb * litArgs_opacity, litArgs_opacity); 9882#else 9883 output.color = vec4f(output.color.rgb, 1.0); 9884#endif 9885`,yO=` 9886varying vUv0: vec2f; 9887var source: texture_2d<f32>; 9888var sourceSampler: sampler; 9889@fragment fn fragmentMain(input : FragmentInput) -> FragmentOutput { 9890 var output: FragmentOutput; 9891 output.color = textureSample(source, sourceSampler, input.vUv0); 9892 return output; 9893} 9894`,xO=` 9895uniform material_sheen: vec3f; 9896fn getSheen() { 9897 var sheenColor = uniform.material_sheen; 9898 #ifdef STD_SHEEN_TEXTURE 9899 sheenColor = sheenColor * {STD_SHEEN_TEXTURE_DECODE}(textureSampleBias({STD_SHEEN_TEXTURE_NAME}, {STD_SHEEN_TEXTURE_NAME}Sampler, {STD_SHEEN_TEXTURE_UV}, uniform.textureBias)).{STD_SHEEN_TEXTURE_CHANNEL}; 9900 #endif 9901 #ifdef STD_SHEEN_VERTEX 9902 sheenColor = sheenColor * saturate3(vVertexColor.{STD_SHEEN_VERTEX_CHANNEL}); 9903 #endif 9904 sSpecularity = sheenColor; 9905} 9906`,TO=` 9907uniform material_sheenGloss: f32; 9908fn getSheenGlossiness() { 9909 var sheenGlossiness = uniform.material_sheenGloss; 9910 #ifdef STD_SHEENGLOSS_TEXTURE 9911 sheenGlossiness = sheenGlossiness * textureSampleBias({STD_SHEENGLOSS_TEXTURE_NAME}, {STD_SHEENGLOSS_TEXTURE_NAME}Sampler, {STD_SHEENGLOSS_TEXTURE_UV}, uniform.textureBias).{STD_SHEENGLOSS_TEXTURE_CHANNEL}; 9912 #endif 9913 #ifdef STD_SHEENGLOSS_VERTEX 9914 sheenGlossiness = sheenGlossiness * saturate(vVertexColor.{STD_SHEENGLOSS_VERTEX_CHANNEL}); 9915 #endif 9916 #ifdef STD_SHEENGLOSS_INVERT 9917 sheenGlossiness = 1.0 - sheenGlossiness; 9918 #endif 9919 sGlossiness = sheenGlossiness + 0.0000001; 9920} 9921`,wO=` 9922uniform material_heightMapFactor: f32; 9923fn getParallax() { 9924 var parallaxScale = uniform.material_heightMapFactor; 9925 var height: f32 = textureSampleBias({STD_HEIGHT_TEXTURE_NAME}, {STD_HEIGHT_TEXTURE_NAME}Sampler, {STD_HEIGHT_TEXTURE_UV}, uniform.textureBias).{STD_HEIGHT_TEXTURE_CHANNEL}; 9926 height = height * parallaxScale - parallaxScale * 0.5; 9927 var viewDirT: vec3f = dViewDirW * dTBN; 9928 viewDirT.z = viewDirT.z + 0.42; 9929 dUvOffset = height * (viewDirT.xy / viewDirT.z); 9930} 9931`,CO=` 9932fn encodePickOutput(id: u32) -> vec4f { 9933 let inv: vec4f = vec4f(1.0 / 255.0); 9934 let shifts: vec4u = vec4u(16u, 8u, 0u, 24u); 9935 let col: vec4u = (vec4u(id) >> shifts) & vec4u(0xffu); 9936 return vec4f(col) * inv; 9937} 9938#ifndef PICK_CUSTOM_ID 9939 uniform meshInstanceId: u32; 9940 fn getPickOutput() -> vec4f { 9941 return encodePickOutput(uniform.meshInstanceId); 9942 } 9943#endif 9944#ifdef DEPTH_PICK_PASS 9945 #include "floatAsUintPS" 9946 #ifndef CAMERAPLANES 9947 #define CAMERAPLANES 9948 uniform camera_params: vec4f; 9949 #endif 9950 fn getPickDepth() -> vec4f { 9951 var linearDepth: f32; 9952 if (uniform.camera_params.w > 0.5) { 9953 linearDepth = pcPosition.z; 9954 } else { 9955 let viewDist = 1.0 / pcPosition.w; 9956 linearDepth = (viewDist - uniform.camera_params.z) / (uniform.camera_params.y - uniform.camera_params.z); 9957 } 9958 return float2uint(linearDepth); 9959 } 9960#endif 9961`,EO=` 9962fn getReflDir(worldNormal: vec3f, viewDir: vec3f, gloss: f32, tbn: mat3x3f) { 9963 dReflDirW = normalize(-reflect(viewDir, worldNormal)); 9964} 9965`,bO=` 9966fn getReflDir(worldNormal: vec3f, viewDir: vec3f, gloss: f32, tbn: mat3x3f) { 9967 let roughness: f32 = sqrt(1.0 - min(gloss, 1.0)); 9968 let direction: vec2f = dAnisotropyRotation; 9969 let anisotropicT: vec3f = normalize(tbn * vec3f(direction, 0.0)); 9970 let anisotropicB: vec3f = normalize(cross(tbn[2], anisotropicT)); 9971 let anisotropy: f32 = dAnisotropy; 9972 let anisotropicDirection: vec3f = anisotropicB; 9973 let anisotropicTangent: vec3f = cross(anisotropicDirection, viewDir); 9974 let anisotropicNormal: vec3f = cross(anisotropicTangent, anisotropicDirection); 9975 let bendFactor: f32 = 1.0 - anisotropy * (1.0 - roughness); 9976 let bendFactor4: f32 = bendFactor * bendFactor * bendFactor * bendFactor; 9977 let bentNormal: vec3f = normalize(mix(normalize(anisotropicNormal), normalize(worldNormal), bendFactor4)); 9978 dReflDirW = reflect(-viewDir, bentNormal); 9979}`,AO=` 9980#ifdef LIT_CLEARCOAT 9981fn addReflectionCC(reflDir: vec3f, gloss: f32) { 9982 ccReflection = ccReflection + calcReflection(reflDir, gloss); 9983} 9984#endif 9985`,PO=` 9986var texture_cubeMap: texture_cube<f32>; 9987var texture_cubeMapSampler: sampler; 9988uniform material_reflectivity: f32; 9989fn calcReflection(reflDir: vec3f, gloss: f32) -> vec3f { 9990 var lookupVec: vec3f = cubeMapProject(reflDir); 9991 lookupVec.x = lookupVec.x * -1.0; 9992 return {reflectionDecode}(textureSample(texture_cubeMap, texture_cubeMapSampler, lookupVec)); 9993} 9994fn addReflection(reflDir: vec3f, gloss: f32) { 9995 dReflection = dReflection + vec4f(calcReflection(reflDir, gloss), uniform.material_reflectivity); 9996} 9997`,IO=` 9998#ifndef ENV_ATLAS 9999 #define ENV_ATLAS 10000 var texture_envAtlas: texture_2d<f32>; 10001 var texture_envAtlasSampler: sampler; 10002#endif 10003var texture_cubeMap: texture_cube<f32>; 10004var texture_cubeMapSampler: sampler; 10005uniform material_reflectivity: f32; 10006fn calcReflection(reflDir: vec3f, gloss: f32) -> vec3f { 10007 let dir: vec3f = cubeMapProject(reflDir) * vec3f(-1.0, 1.0, 1.0); 10008 let uv: vec2f = toSphericalUv(dir);
10009 let level: f32 = saturate(1.0 - gloss) * 5.0; 10010 let ilevel: f32 = floor(level); 10011 let flevel: f32 = level - ilevel; 10012 let sharp: vec3f = {reflectionCubemapDecode}(textureSample(texture_cubeMap, texture_cubeMapSampler, dir)); 10013 let roughA: vec3f = {reflectionDecode}(textureSample(texture_envAtlas, texture_envAtlasSampler, mapRoughnessUv(uv, ilevel))); 10014 let roughB: vec3f = {reflectionDecode}(textureSample(texture_envAtlas, texture_envAtlasSampler, mapRoughnessUv(uv, ilevel + 1.0))); 10015 return processEnvironment(mix(sharp, mix(roughA, roughB, flevel), min(level, 1.0))); 10016} 10017fn addReflection(reflDir: vec3f, gloss: f32) { 10018 dReflection = dReflection + vec4f(calcReflection(reflDir, gloss), uniform.material_reflectivity); 10019} 10020`,DO=` 10021#ifndef ENV_ATLAS 10022#define ENV_ATLAS 10023 var texture_envAtlas: texture_2d<f32>; 10024 var texture_envAtlasSampler: sampler; 10025#endif 10026uniform material_reflectivity: f32; 10027fn shinyMipLevel(uv: vec2f) -> f32 { 10028 let dx: vec2f = dpdx(uv); 10029 let dy: vec2f = dpdy(uv); 10030 let uv2: vec2f = vec2f(fract(uv.x + 0.5), uv.y); 10031 let dx2: vec2f = dpdx(uv2); 10032 let dy2: vec2f = dpdy(uv2); 10033 let maxd: f32 = min(max(dot(dx, dx), dot(dy, dy)), max(dot(dx2, dx2), dot(dy2, dy2))); 10034 return clamp(0.5 * log2(maxd) - 1.0 + uniform.textureBias, 0.0, 5.0); 10035} 10036fn calcReflection(reflDir: vec3f, gloss: f32) -> vec3f { 10037 let dir: vec3f = cubeMapProject(reflDir) * vec3f(-1.0, 1.0, 1.0); 10038 let uv: vec2f = toSphericalUv(dir); 10039 let level: f32 = saturate(1.0 - gloss) * 5.0; 10040 let ilevel: f32 = floor(level); 10041 let level2: f32 = shinyMipLevel(uv * atlasSize); 10042 let ilevel2: f32 = floor(level2); 10043 var uv0: vec2f; 10044 var uv1: vec2f; 10045 var weight: f32; 10046 if (ilevel == 0.0) { 10047 uv0 = mapShinyUv(uv, ilevel2); 10048 uv1 = mapShinyUv(uv, ilevel2 + 1.0); 10049 weight = level2 - ilevel2; 10050 } else { 10051 uv0 = mapRoughnessUv(uv, ilevel); 10052 uv1 = uv0; 10053 weight = 0.0; 10054 } 10055 let linearA: vec3f = {reflectionDecode}(textureSample(texture_envAtlas, texture_envAtlasSampler, uv0)); 10056 let linearB: vec3f = {reflectionDecode}(textureSample(texture_envAtlas, texture_envAtlasSampler, uv1)); 10057 let linear0: vec3f = mix(linearA, linearB, weight); 10058 let linear1: vec3f = {reflectionDecode}(textureSample(texture_envAtlas, texture_envAtlasSampler, mapRoughnessUv(uv, ilevel + 1.0))); 10059 return processEnvironment(mix(linear0, linear1, level - ilevel)); 10060} 10061fn addReflection(reflDir: vec3f, gloss: f32) { 10062 dReflection = dReflection + vec4f(calcReflection(reflDir, gloss), uniform.material_reflectivity); 10063} 10064`,MO=` 10065#ifndef VIEWMATRIX 10066 #define VIEWMATRIX 10067 uniform matrix_view: mat4x4f; 10068#endif 10069var texture_sphereMap: texture_2d<f32>; 10070var texture_sphereMapSampler: sampler; 10071uniform material_reflectivity: f32; 10072fn calcReflection(reflDir: vec3f, gloss: f32) -> vec3f { 10073 let viewRotationMatrix = mat3x3f(uniform.matrix_view[0].xyz, uniform.matrix_view[1].xyz, uniform.matrix_view[2].xyz); 10074 let reflDirV: vec3f = viewRotationMatrix * reflDir; 10075 let m: f32 = 2.0 * sqrt(dot(reflDirV.xy, reflDirV.xy) + (reflDirV.z + 1.0) * (reflDirV.z + 1.0)); 10076 let sphereMapUv: vec2f = reflDirV.xy / m + 0.5; 10077 return {reflectionDecode}(textureSample(texture_sphereMap, texture_sphereMapSampler, sphereMapUv)); 10078} 10079fn addReflection(reflDir: vec3f, gloss: f32) { 10080 dReflection = dReflection + vec4f(calcReflection(reflDir, gloss), uniform.material_reflectivity); 10081} 10082`,RO=` 10083fn addReflectionSheen(worldNormal: vec3f, viewDir: vec3f, gloss: f32) { 10084 let NoV: f32 = dot(worldNormal, viewDir); 10085 let alphaG: f32 = gloss * gloss; 10086 let a: f32 = select( 10087 -8.48 * alphaG + 14.3 * gloss - 9.95, 10088 -339.2 * alphaG + 161.4 * gloss - 25.9, 10089 gloss < 0.25 10090 ); 10091 let b: f32 = select( 10092 1.97 * alphaG - 3.27 * gloss + 0.72, 10093 44.0 * alphaG - 23.7 * gloss + 3.26, 10094 gloss < 0.25 10095 ); 10096 let dg_add: f32 = select( 10097 0.1 * ( gloss - 0.25 ), 10098 0.0, 10099 gloss < 0.25 10100 ); 10101 let dg: f32 = exp( a * NoV + b ) + dg_add; 10102 sReflection = sReflection + (calcReflection(worldNormal, 0.0) * saturate(dg)); 10103}`,LO=` 10104fn refract2(viewVec: vec3f, normal: vec3f, IOR: f32) -> vec3f { 10105 let vn: f32 = dot(viewVec, normal); 10106 let k: f32 = 1.0 - IOR * IOR * (1.0 - vn * vn); 10107 let refrVec: vec3f = IOR * viewVec - (IOR * vn + sqrt(k)) * normal; 10108 return refrVec; 10109} 10110fn addRefraction( 10111 worldNormal: vec3f, 10112 viewDir: vec3f, 10113 thickness: f32, 10114 gloss: f32, 10115 specularity: vec3f, 10116 albedo: vec3f, 10117 transmission: f32, 10118 refractionIndex: f32, 10119 dispersion: f32 10120#if defined(LIT_IRIDESCENCE) 10121 , iridescenceFresnel: vec3f, 10122 iridescenceIntensity: f32 10123#endif 10124) { 10125 let tmpRefl: vec4f = dReflection; 10126 let reflectionDir: vec3f = refract2(-viewDir, worldNormal, refractionIndex); 10127 dReflection = vec4f(0.0); 10128 addReflection(reflectionDir, gloss); 10129 dDiffuseLight = mix(dDiffuseLight, dReflection.rgb * albedo, transmission); 10130 dReflection = tmpRefl; 10131} 10132`,FO=` 10133uniform material_invAttenuationDistance: f32; 10134uniform material_attenuation: vec3f; 10135fn evalRefractionColor(refractionVector: vec3f, gloss: f32, refractionIndex: f32) -> vec3f { 10136 let pointOfRefraction: vec4f = vec4f(vPositionW + refractionVector, 1.0); 10137 let projectionPoint: vec4f = uniform.matrix_viewProjection * pointOfRefraction; 10138 let uv: vec2f = getGrabScreenPos(projectionPoint); 10139 let iorToRoughness: f32 = (1.0 - gloss) * clamp((1.0 / refractionIndex) * 2.0 - 2.0, 0.0, 1.0); 10140 let refractionLod: f32 = log2(uniform.uScreenSize.x) * iorToRoughness; 10141 var refraction: vec3f = textureSampleLevel(uSceneColorMap, uSceneColorMapSampler, uv, refractionLod).rgb; 10142 #ifdef SCENE_COLORMAP_GAMMA 10143 refraction = decodeGamma3(refraction); 10144 #endif 10145 return refraction; 10146} 10147fn addRefraction( 10148 worldNormal: vec3f, 10149 viewDir: vec3f, 10150 thickness: f32, 10151 gloss: f32, 10152 specularity: vec3f, 10153 albedo: vec3f, 10154 transmission: f32, 10155 refractionIndex: f32, 10156 dispersion: f32, 10157#if defined(LIT_IRIDESCENCE) 10158 iridescenceFresnel: vec3f, 10159 iridescenceIntensity: f32 10160#endif 10161) { 10162 var modelScale: vec3f; 10163 modelScale.x = length(uniform.matrix_model[0].xyz); 10164 modelScale.y = length(uniform.matrix_model[1].xyz); 10165 modelScale.z = length(uniform.matrix_model[2].xyz); 10166 let scale: vec3f = thickness * modelScale; 10167 var refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndex)) * scale; 10168 var refraction = evalRefractionColor(refractionVector, gloss, refractionIndex); 10169 #ifdef LIT_DISPERSION 10170 let halfSpread: f32 = (1.0 / refractionIndex - 1.0) * 0.025 * dispersion; 10171 let refractionIndexR: f32 = refractionIndex - halfSpread; 10172 refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndexR)) * scale; 10173 refraction.r = evalRefractionColor(refractionVector, gloss, refractionIndexR).r; 10174 let refractionIndexB: f32 = refractionIndex + halfSpread; 10175 refractionVector = normalize(refract(-viewDir, worldNormal, refractionIndexB)) * scale; 10176 refraction.b = evalRefractionColor(refractionVector, gloss, refractionIndexB).b; 10177 #endif 10178 var transmittance: vec3f; 10179 if (uniform.material_invAttenuationDistance != 0.0) 10180 { 10181 let attenuation: vec3f = -log(uniform.material_attenuation) * uniform.material_invAttenuationDistance; 10182 transmittance = exp(-attenuation * length(refractionVector)); 10183 } 10184 else 10185 { 10186 transmittance = vec3f(1.0); 10187 } 10188 let fresnel: vec3f = vec3f(1.0) - 10189 getFresnel( 10190 dot(viewDir, worldNormal), 10191 gloss, 10192 specularity 10193 #if defined(LIT_IRIDESCENCE) 10194 , iridescenceFresnel, 10195 iridescenceIntensity 10196 #endif 10197 ); 10198 dDiffuseLight = mix(dDiffuseLight, refraction * transmittance * fresnel, transmission); 10199} 10200`,OO=` 10201varying vUv0: vec2f; 10202#ifdef CUBEMAP_SOURCE 10203 var sourceCube: texture_cube<f32>; 10204 var sourceCubeSampler : sampler; 10205#else 10206 var sourceTex: texture_2d<f32>; 10207 var sourceTexSampler : sampler; 10208#endif 10209#ifdef USE_SAMPLES_TEX 10210 var samplesTex: texture_2d<f32>; 10211 var samplesTexSampler : sampler; 10212 uniform samplesTexInverseSize: vec2f; 10213#endif 10214uniform params: vec3f; 10215fn targetFace() -> f32 { return uniform.params.x; } 10216fn targetTotalPixels() -> f32 { return uniform.params.y; } 10217fn sourceTotalPixels() -> f32 { return uniform.params.z; } 10218const PI: f32 = 3.141592653589793; 10219fn saturate(x: f32) -> f32 { 10220 return clamp(x, 0.0, 1.0); 10221} 10222#include "decodePS" 10223#include "encodePS" 10224fn modifySeams(dir: vec3f, scale: f32) -> vec3f { 10225 let adir = abs(dir); 10226 let M = max(max(adir.x, adir.y), adir.z); 10227 return dir / M * vec3f( 10228 select(scale, 1.0, adir.x == M), 10229 select(scale, 1.0, adir.y == M), 10230 select(scale, 1.0, adir.z == M) 10231 ); 10232} 10233fn toSpherical(dir: vec3f) -> vec2f { 10234 let nonZeroXZ = any(dir.xz != vec2f(0.0, 0.0)); 10235 return vec2f(select(0.0, atan2(dir.x, dir.z), nonZeroXZ), asin(dir.y)); 10236} 10237fn fromSpherical(uv: vec2f) -> vec3f { 10238 return vec3f(cos(uv.y) * sin(uv.x), 10239 sin(uv.y), 10240 cos(uv.y) * cos(uv.x)); 10241} 10242fn getDirectionEquirect(uv: vec2f) -> vec3f { 10243 return fromSpherical((vec2f(uv.x, 1.0 - uv.y) * 2.0 - 1.0) * vec2f(PI, PI * 0.5)); 10244} 10245fn signNotZero(k: f32) -> f32 { 10246 return select(-1.0, 1.0, k >= 0.0); 10247} 10248fn signNotZeroVec2(v: vec2f) -> vec2f { 10249 return vec2f(signNotZero(v.x), signNotZero(v.y)); 10250} 10251fn octDecode(o: vec2f) -> vec3f { 10252 var v = vec3f(o.x, 1.0 - abs(o.x) - abs(o.y), o.y); 10253 if (v.y < 0.0) { 10254 var temp: vec2f = (1.0 - abs(v.zx)) * signNotZeroVec2(v.xz); 10255 v = vec3f(temp.x, v.y, temp.y); 10256 } 10257 return normalize(v); 10258}
10259fn getDirectionOctahedral(uv: vec2f) -> vec3f { 10260 return octDecode(vec2f(uv.x, 1.0 - uv.y) * 2.0 - 1.0); 10261} 10262fn octEncode(v: vec3f) -> vec2f { 10263 let l1norm = abs(v.x) + abs(v.y) + abs(v.z); 10264 var result = v.xz * (1.0 / l1norm); 10265 if (v.y < 0.0) { 10266 result = (1.0 - abs(result.yx)) * signNotZeroVec2(result.xy); 10267 } 10268 return result; 10269} 10270#ifdef CUBEMAP_SOURCE 10271 fn sampleCubemapDir(dir: vec3f) -> vec4f { 10272 return textureSample(sourceCube, sourceCubeSampler, modifySeams(dir, 1.0)); 10273 } 10274 fn sampleCubemapSph(sph: vec2f) -> vec4f { 10275 return sampleCubemapDir(fromSpherical(sph)); 10276 } 10277 fn sampleCubemapDirLod(dir: vec3f, mipLevel: f32) -> vec4f { 10278 return textureSampleLevel(sourceCube, sourceCubeSampler, modifySeams(dir, 1.0), mipLevel); 10279 } 10280 fn sampleCubemapSphLod(sph: vec2f, mipLevel: f32) -> vec4f { 10281 return sampleCubemapDirLod(fromSpherical(sph), mipLevel); 10282 } 10283#else 10284 fn sampleEquirectSph(sph: vec2f) -> vec4f { 10285 let uv = sph / vec2f(PI * 2.0, PI) + 0.5; 10286 return textureSample(sourceTex, sourceTexSampler, vec2f(uv.x, 1.0 - uv.y)); 10287 } 10288 fn sampleEquirectDir(dir: vec3f) -> vec4f { 10289 return sampleEquirectSph(toSpherical(dir)); 10290 } 10291 fn sampleEquirectSphLod(sph: vec2f, mipLevel: f32) -> vec4f { 10292 let uv = sph / vec2f(PI * 2.0, PI) + 0.5; 10293 return textureSampleLevel(sourceTex, sourceTexSampler, vec2f(uv.x, 1.0 - uv.y), mipLevel); 10294 } 10295 fn sampleEquirectDirLod(dir: vec3f, mipLevel: f32) -> vec4f { 10296 return sampleEquirectSphLod(toSpherical(dir), mipLevel); 10297 } 10298 fn sampleOctahedralDir(dir: vec3f) -> vec4f { 10299 let uv = octEncode(dir) * 0.5 + 0.5; 10300 return textureSample(sourceTex, sourceTexSampler, vec2f(uv.x, 1.0 - uv.y)); 10301 } 10302 fn sampleOctahedralSph(sph: vec2f) -> vec4f { 10303 return sampleOctahedralDir(fromSpherical(sph)); 10304 } 10305 fn sampleOctahedralDirLod(dir: vec3f, mipLevel: f32) -> vec4f { 10306 let uv = octEncode(dir) * 0.5 + 0.5; 10307 return textureSampleLevel(sourceTex, sourceTexSampler, vec2f(uv.x, 1.0 - uv.y), mipLevel); 10308 } 10309 fn sampleOctahedralSphLod(sph: vec2f, mipLevel: f32) -> vec4f { 10310 return sampleOctahedralDirLod(fromSpherical(sph), mipLevel); 10311 } 10312#endif 10313fn getDirectionCubemap(uv: vec2f) -> vec3f { 10314 let st = uv * 2.0 - 1.0; 10315 let face = targetFace(); 10316 var vec: vec3f; 10317 if (face == 0.0) { 10318 vec = vec3f(1, -st.y, -st.x); 10319 } else if (face == 1.0) { 10320 vec = vec3f(-1, -st.y, st.x); 10321 } else if (face == 2.0) { 10322 vec = vec3f(st.x, 1, st.y); 10323 } else if (face == 3.0) { 10324 vec = vec3f(st.x, -1, -st.y); 10325 } else if (face == 4.0) { 10326 vec = vec3f(st.x, -st.y, 1); 10327 } else { 10328 vec = vec3f(-st.x, -st.y, -1); 10329 } 10330 return normalize(modifySeams(vec, 1.0)); 10331} 10332fn matrixFromVector(n: vec3f) -> mat3x3f { 10333 let a = 1.0 / (1.0 + n.z); 10334 let b = -n.x * n.y * a; 10335 let b1 = vec3f(1.0 - n.x * n.x * a, b, -n.x); 10336 let b2 = vec3f(b, 1.0 - n.y * n.y * a, -n.y); 10337 return mat3x3f(b1, b2, n); 10338} 10339fn matrixFromVectorSlow(n: vec3f) -> mat3x3f { 10340 let up = select(vec3f(0.0, 0.0, select(-1.0, 1.0, n.y > 0.0)), vec3f(0.0, 1.0, 0.0), abs(n.y) > 0.0000001); 10341 let x = normalize(cross(up, n)); 10342 let y = cross(n, x); 10343 return mat3x3f(x, y, n); 10344} 10345fn reproject(uv: vec2f) -> vec4f { 10346 if ({NUM_SAMPLES} <= 1) { 10347 return {ENCODE_FUNC}({DECODE_FUNC}({SOURCE_FUNC}Dir({TARGET_FUNC}(uv)))); 10348 } else { 10349 let t = {TARGET_FUNC}(uv); 10350 let tu = dpdx(t); 10351 let tv = dpdy(t); 10352 var result = vec3f(0.0); 10353 for (var u = 0.0; u < {NUM_SAMPLES_SQRT}; u += 1.0) { 10354 for (var v = 0.0; v < {NUM_SAMPLES_SQRT}; v += 1.0) { 10355 result += {DECODE_FUNC}({SOURCE_FUNC}Dir(normalize(t + 10356 tu * (u / {NUM_SAMPLES_SQRT} - 0.5) + 10357 tv * (v / {NUM_SAMPLES_SQRT} - 0.5)))); 10358 } 10359 } 10360 return {ENCODE_FUNC}(result / ({NUM_SAMPLES_SQRT} * {NUM_SAMPLES_SQRT})); 10361 } 10362} 10363const unpackFloat: vec4f = vec4f(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0); 10364#ifdef USE_SAMPLES_TEX 10365 fn unpackSample(i: i32, L: ptr<function, vec3f>, mipLevel: ptr<function, f32>) { 10366 var u = (f32(i * 4) + 0.5) * uniform.samplesTexInverseSize.x; 10367 var v = (floor(u) + 0.5) * uniform.samplesTexInverseSize.y; 10368 var raw: vec4f; 10369 raw.x = dot(textureSample(samplesTex, samplesTexSampler, vec2f(u, v)), unpackFloat); u += uniform.samplesTexInverseSize.x; 10370 raw.y = dot(textureSample(samplesTex, samplesTexSampler, vec2f(u, v)), unpackFloat); u += uniform.samplesTexInverseSize.x; 10371 raw.z = dot(textureSample(samplesTex, samplesTexSampler, vec2f(u, v)), unpackFloat); u += uniform.samplesTexInverseSize.x;
10372 raw.w = dot(textureSample(samplesTex, samplesTexSampler, vec2f(u, v)), unpackFloat); 10373 *L = raw.xyz * 2.0 - 1.0; 10374 *mipLevel = raw.w * 8.0; 10375 } 10376 fn prefilterSamples(uv: vec2f) -> vec4f { 10377 let vecSpace = matrixFromVectorSlow({TARGET_FUNC}(uv)); 10378 var L: vec3f; 10379 var mipLevel: f32; 10380 var result = vec3f(0.0); 10381 var totalWeight = 0.0; 10382 for (var i = 0; i < {NUM_SAMPLES}; i += 1) { 10383 unpackSample(i, &L, &mipLevel); 10384 result += {DECODE_FUNC}({SOURCE_FUNC}DirLod(vecSpace * L, mipLevel)) * L.z; 10385 totalWeight += L.z; 10386 } 10387 return {ENCODE_FUNC}(result / totalWeight); 10388 } 10389 fn prefilterSamplesUnweighted(uv: vec2f) -> vec4f { 10390 let vecSpace = matrixFromVectorSlow({TARGET_FUNC}(uv)); 10391 var L: vec3f; 10392 var mipLevel: f32; 10393 var result = vec3f(0.0); 10394 for (var i = 0; i < {NUM_SAMPLES}; i += 1) { 10395 unpackSample(i, &L, &mipLevel); 10396 result += {DECODE_FUNC}({SOURCE_FUNC}DirLod(vecSpace * L, mipLevel)); 10397 } 10398 return {ENCODE_FUNC}(result / f32({NUM_SAMPLES})); 10399 } 10400#endif 10401@fragment 10402fn fragmentMain(input : FragmentInput) -> FragmentOutput { 10403 var output: FragmentOutput; 10404 output.color = {PROCESS_FUNC}(input.vUv0); 10405 return output; 10406} 10407`,BO=` 10408attribute vertex_position: vec2f; 10409uniform uvMod: vec4f; 10410varying vUv0: vec2f; 10411@vertex 10412fn vertexMain(input: VertexInput) -> VertexOutput { 10413 var output: VertexOutput; 10414 output.position = vec4f(input.vertex_position, 0.5, 1.0); 10415 output.vUv0 = getImageEffectUV((input.vertex_position * 0.5 + vec2f(0.5, 0.5)) * uniform.uvMod.xy + uniform.uvMod.zw); 10416 return output; 10417} 10418`,NO=` 10419var uSceneDepthMap: texture_2d<uff>; 10420#ifndef SCREENSIZE 10421 #define SCREENSIZE 10422 uniform uScreenSize: vec4f; 10423#endif 10424#ifndef VIEWMATRIX 10425 #define VIEWMATRIX 10426 uniform matrix_view: mat4x4f; 10427#endif 10428#ifndef LINEARIZE_DEPTH 10429 #define LINEARIZE_DEPTH 10430 #ifndef CAMERAPLANES 10431 #define CAMERAPLANES 10432 uniform camera_params: vec4f; 10433 #endif 10434 fn linearizeDepth(z: f32) -> f32 { 10435 if (uniform.camera_params.w == 0.0) { 10436 return (uniform.camera_params.z * uniform.camera_params.y) / (uniform.camera_params.y + z * (uniform.camera_params.z - uniform.camera_params.y)); 10437 } else { 10438 return uniform.camera_params.z + z * (uniform.camera_params.y - uniform.camera_params.z); 10439 } 10440 } 10441#endif 10442fn delinearizeDepth(linearDepth: f32) -> f32 { 10443 if (uniform.camera_params.w == 0.0) { 10444 return (uniform.camera_params.y * (uniform.camera_params.z - linearDepth)) / (linearDepth * (uniform.camera_params.z - uniform.camera_params.y)); 10445 } else { 10446 return (linearDepth - uniform.camera_params.z) / (uniform.camera_params.y - uniform.camera_params.z); 10447 } 10448} 10449fn getLinearScreenDepth(uv: vec2f) -> f32 { 10450 let textureSize = textureDimensions(uSceneDepthMap, 0); 10451 let texel: vec2i = vec2i(uv * vec2f(textureSize)); 10452 #ifdef SCENE_DEPTHMAP_LINEAR 10453 return textureLoad(uSceneDepthMap, texel, 0).r; 10454 #else 10455 return linearizeDepth(textureLoad(uSceneDepthMap, texel, 0).r); 10456 #endif 10457} 10458#ifndef VERTEXSHADER 10459 fn getLinearScreenDepthFrag() -> f32 { 10460 let uv: vec2f = pcPosition.xy * uniform.uScreenSize.zw; 10461 return getLinearScreenDepth(uv); 10462 } 10463#endif 10464fn getLinearDepth(pos: vec3f) -> f32 {
10465 return -(uniform.matrix_view * vec4f(pos, 1.0)).z; 10466} 10467`,kO=` 10468fn getShadowCascadeIndex(shadowCascadeDistances: vec4f, shadowCascadeCount: i32) -> i32 { 10469 let depth: f32 = 1.0 / pcPosition.w; 10470 let comparisons: vec4f = step(shadowCascadeDistances, vec4f(depth)); 10471 let cascadeIndex: i32 = i32(dot(comparisons, vec4f(1.0))); 10472 return min(cascadeIndex, shadowCascadeCount - 1); 10473} 10474fn ditherShadowCascadeIndex(cascadeIndex_in: i32, shadowCascadeDistances: vec4f, shadowCascadeCount: i32, blendFactor: f32) -> i32 { 10475 var cascadeIndex: i32 = cascadeIndex_in; 10476 if (cascadeIndex < shadowCascadeCount - 1) { 10477 let currentRangeEnd: f32 = shadowCascadeDistances[cascadeIndex]; 10478 let transitionStart: f32 = blendFactor * currentRangeEnd; 10479 let depth: f32 = 1.0 / pcPosition.w; 10480 if (depth > transitionStart) { 10481 let transitionFactor: f32 = smoothstep(transitionStart, currentRangeEnd, depth); 10482 let dither: f32 = fract(sin(dot(pcPosition.xy, vec2f(12.9898, 78.233))) * 43758.5453); 10483 if (dither < transitionFactor) { 10484 cascadeIndex = cascadeIndex + 1; 10485 } 10486 } 10487 } 10488 return cascadeIndex; 10489} 10490fn fadeShadow(shadowCoord_in: vec3f, shadowCascadeDistances: vec4f) -> vec3f { 10491 var shadowCoord: vec3f = shadowCoord_in; 10492 let depth: f32 = 1.0 / pcPosition.w; 10493 if (depth > shadowCascadeDistances.w) { 10494 shadowCoord.z = -9999999.0; 10495 } 10496 return shadowCoord; 10497} 10498`,UO=` 10499fn linstep(a: f32, b: f32, v: f32) -> f32 { 10500 return clamp((v - a) / (b - a), 0.0, 1.0); 10501} 10502fn reduceLightBleeding(pMax: f32, amount: f32) -> f32 { 10503 return linstep(amount, 1.0, pMax); 10504} 10505fn chebyshevUpperBound(moments: vec2f, mean: f32, minVariance: f32, lightBleedingReduction: f32) -> f32 { 10506 var variance: f32 = moments.y - (moments.x * moments.x); 10507 variance = max(variance, minVariance); 10508 let d: f32 = mean - moments.x; 10509 var pMax: f32 = variance / (variance + (d * d)); 10510 pMax = reduceLightBleeding(pMax, lightBleedingReduction); 10511 return select(pMax, 1.0, mean <= moments.x); 10512} 10513fn calculateEVSM(moments_in: vec3f, Z_in: f32, vsmBias: f32, exponent: f32) -> f32 { 10514 let Z: f32 = 2.0 * Z_in - 1.0; 10515 let warpedDepth: f32 = exp(exponent * Z); 10516 let moments: vec2f = moments_in.xy + vec2f(warpedDepth, warpedDepth*warpedDepth) * (1.0 - moments_in.z); 10517 let VSMBias: f32 = vsmBias; 10518 let depthScale: f32 = VSMBias * exponent * warpedDepth; 10519 let minVariance1: f32 = depthScale * depthScale; 10520 return chebyshevUpperBound(moments, warpedDepth, minVariance1, 0.1); 10521} 10522fn VSM16(tex: texture_2d<f32>, texSampler: sampler, texCoords: vec2f, resolution: f32, Z: f32, vsmBias: f32, exponent: f32) -> f32 { 10523 let moments: vec3f = textureSampleLevel(tex, texSampler, texCoords, 0.0).xyz; 10524 return calculateEVSM(moments, Z, vsmBias, exponent); 10525}
10526fn getShadowVSM16(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, exponent: f32) -> f32 { 10527 return VSM16(shadowMap, shadowMapSampler, shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent); 10528} 10529fn getShadowSpotVSM16(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, exponent: f32, lightDir: vec3f) -> f32 { 10530 let Z: f32 = length(lightDir) * shadowParams.w + shadowParams.z; 10531 return VSM16(shadowMap, shadowMapSampler, shadowCoord.xy, shadowParams.x, Z, shadowParams.y, exponent); 10532} 10533fn VSM32(tex: texture_2d<f32>, texSampler: sampler, texCoords_in: vec2f, resolution: f32, Z: f32, vsmBias: f32, exponent: f32) -> f32 { 10534 #ifdef CAPS_TEXTURE_FLOAT_FILTERABLE 10535 var moments: vec3f = textureSampleLevel(tex, texSampler, texCoords_in, 0.0).xyz; 10536 #else 10537 var pixelSize : f32 = 1.0 / resolution; 10538 let texCoords: vec2f = texCoords_in - vec2f(pixelSize); 10539 let s00: vec3f = textureSampleLevel(tex, texSampler, texCoords, 0.0).xyz; 10540 let s10: vec3f = textureSampleLevel(tex, texSampler, texCoords + vec2f(pixelSize, 0.0), 0.0).xyz; 10541 let s01: vec3f = textureSampleLevel(tex, texSampler, texCoords + vec2f(0.0, pixelSize), 0.0).xyz; 10542 let s11: vec3f = textureSampleLevel(tex, texSampler, texCoords + vec2f(pixelSize), 0.0).xyz; 10543 let fr: vec2f = fract(texCoords * resolution); 10544 let h0: vec3f = mix(s00, s10, fr.x); 10545 let h1: vec3f = mix(s01, s11, fr.x); 10546 var moments: vec3f = mix(h0, h1, fr.y); 10547 #endif 10548 return calculateEVSM(moments, Z, vsmBias, exponent); 10549} 10550fn getShadowVSM32(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, exponent: f32) -> f32 { 10551 return VSM32(shadowMap, shadowMapSampler, shadowCoord.xy, shadowParams.x, shadowCoord.z, shadowParams.y, exponent); 10552} 10553fn getShadowSpotVSM32(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, exponent: f32, lightDir: vec3f) -> f32 { 10554 let Z: f32 = length(lightDir) * shadowParams.w + shadowParams.z; 10555 return VSM32(shadowMap, shadowMapSampler, shadowCoord.xy, shadowParams.x, Z, shadowParams.y, exponent); 10556} 10557`,zO=` 10558fn getShadowPCF1x1(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 { 10559 return textureSampleCompareLevel(shadowMap, shadowMapSampler, shadowCoord.xy, shadowCoord.z); 10560} 10561fn getShadowSpotPCF1x1(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 { 10562 return textureSampleCompareLevel(shadowMap, shadowMapSampler, shadowCoord.xy, shadowCoord.z); 10563} 10564`,VO=` 10565fn _getShadowPCF3x3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec3f) -> f32 { 10566 let z: f32 = shadowCoord.z; 10567 let uv: vec2f = shadowCoord.xy * shadowParams.x; 10568 let shadowMapSizeInv: f32 = 1.0 / shadowParams.x; 10569 let base_uv_temp: vec2f = floor(uv + 0.5); 10570 let s: f32 = (uv.x + 0.5 - base_uv_temp.x); 10571 let t: f32 = (uv.y + 0.5 - base_uv_temp.y); 10572 let base_uv: vec2f = (base_uv_temp - vec2f(0.5)) * shadowMapSizeInv; 10573 var sum: f32 = 0.0; 10574 let uw0: f32 = (3.0 - 2.0 * s); 10575 let uw1: f32 = (1.0 + 2.0 * s); 10576 let u0_offset: f32 = (2.0 - s) / uw0 - 1.0; 10577 let u1_offset: f32 = s / uw1 + 1.0; 10578 let vw0: f32 = (3.0 - 2.0 * t); 10579 let vw1: f32 = (1.0 + 2.0 * t); 10580 let v0_offset: f32 = (2.0 - t) / vw0 - 1.0; 10581 let v1_offset: f32 = t / vw1 + 1.0; 10582 let u0: f32 = u0_offset * shadowMapSizeInv + base_uv.x; 10583 let v0: f32 = v0_offset * shadowMapSizeInv + base_uv.y; 10584 let u1: f32 = u1_offset * shadowMapSizeInv + base_uv.x; 10585 let v1: f32 = v1_offset * shadowMapSizeInv + base_uv.y; 10586 sum = sum + uw0 * vw0 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u0, v0), z); 10587 sum = sum + uw1 * vw0 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u1, v0), z); 10588 sum = sum + uw0 * vw1 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u0, v1), z); 10589 sum = sum + uw1 * vw1 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u1, v1), z); 10590 sum = sum * (1.0 / 16.0); 10591 return sum; 10592} 10593fn getShadowPCF3x3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 { 10594 return _getShadowPCF3x3(shadowMap, shadowMapSampler, shadowCoord, shadowParams.xyz); 10595} 10596fn getShadowSpotPCF3x3(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 { 10597 return _getShadowPCF3x3(shadowMap, shadowMapSampler, shadowCoord, shadowParams.xyz); 10598} 10599`,GO=` 10600fn _getShadowPCF5x5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec3f) -> f32 { 10601 let z: f32 = shadowCoord.z; 10602 let uv: vec2f = shadowCoord.xy * shadowParams.x; 10603 let shadowMapSizeInv: f32 = 1.0 / shadowParams.x; 10604 let base_uv_temp: vec2f = floor(uv + 0.5); 10605 let s: f32 = (uv.x + 0.5 - base_uv_temp.x); 10606 let t: f32 = (uv.y + 0.5 - base_uv_temp.y); 10607 let base_uv: vec2f = (base_uv_temp - vec2f(0.5)) * shadowMapSizeInv; 10608 let uw0: f32 = (4.0 - 3.0 * s); 10609 let uw1: f32 = 7.0; 10610 let uw2: f32 = (1.0 + 3.0 * s); 10611 let u0_offset: f32 = (3.0 - 2.0 * s) / uw0 - 2.0; 10612 let u1_offset: f32 = (3.0 + s) / uw1; 10613 let u2_offset: f32 = s / uw2 + 2.0; 10614 let vw0: f32 = (4.0 - 3.0 * t); 10615 let vw1: f32 = 7.0; 10616 let vw2: f32 = (1.0 + 3.0 * t); 10617 let v0_offset: f32 = (3.0 - 2.0 * t) / vw0 - 2.0; 10618 let v1_offset: f32 = (3.0 + t) / vw1; 10619 let v2_offset: f32 = t / vw2 + 2.0; 10620 var sum: f32 = 0.0; 10621 let u0: f32 = u0_offset * shadowMapSizeInv + base_uv.x; 10622 let v0: f32 = v0_offset * shadowMapSizeInv + base_uv.y; 10623 let u1: f32 = u1_offset * shadowMapSizeInv + base_uv.x; 10624 let v1: f32 = v1_offset * shadowMapSizeInv + base_uv.y; 10625 let u2: f32 = u2_offset * shadowMapSizeInv + base_uv.x; 10626 let v2: f32 = v2_offset * shadowMapSizeInv + base_uv.y; 10627 sum = sum + uw0 * vw0 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u0, v0), z); 10628 sum = sum + uw1 * vw0 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u1, v0), z); 10629 sum = sum + uw2 * vw0 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u2, v0), z); 10630 sum = sum + uw0 * vw1 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u0, v1), z); 10631 sum = sum + uw1 * vw1 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u1, v1), z); 10632 sum = sum + uw2 * vw1 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u2, v1), z); 10633 sum = sum + uw0 * vw2 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u0, v2), z); 10634 sum = sum + uw1 * vw2 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u1, v2), z); 10635 sum = sum + uw2 * vw2 * textureSampleCompareLevel(shadowMap, shadowMapSampler, vec2f(u2, v2), z); 10636 sum = sum * (1.0 / 144.0); 10637 sum = saturate(sum); 10638 return sum; 10639} 10640fn getShadowPCF5x5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 { 10641 return _getShadowPCF5x5(shadowMap, shadowMapSampler, shadowCoord, shadowParams.xyz); 10642} 10643fn getShadowSpotPCF5x5(shadowMap: texture_depth_2d, shadowMapSampler: sampler_comparison, shadowCoord: vec3f, shadowParams: vec4f) -> f32 { 10644 return _getShadowPCF5x5(shadowMap, shadowMapSampler, shadowCoord, shadowParams.xyz); 10645} 10646`,HO=` 10647fn fractSinRand(uv: vec2f) -> f32 { 10648 let PI: f32 = 3.141592653589793; 10649 let a: f32 = 12.9898; let b: f32 = 78.233; let c: f32 = 43758.5453; 10650 let dt: f32 = dot(uv.xy, vec2f(a, b)); 10651 let sn: f32 = dt % PI; 10652 return fract(sin(sn) * c); 10653} 10654struct VogelDiskData { 10655 invNumSamples: f32, 10656 initialAngle: f32, 10657 currentPointId: f32, 10658} 10659fn prepareDiskConstants(data: ptr<function, VogelDiskData>, sampleCount: i32, randomSeed: f32) { 10660 let pi2: f32 = 6.28318530718; 10661 data.invNumSamples = 1.0 / f32(sampleCount); 10662 data.initialAngle = randomSeed * pi2; 10663 data.currentPointId = 0.0; 10664} 10665fn generateDiskSample(data: ptr<function, VogelDiskData>) -> vec2f { 10666 let GOLDEN_ANGLE: f32 = 2.399963; 10667 let r: f32 = sqrt((data.currentPointId + 0.5) * data.invNumSamples); 10668 let theta: f32 = data.currentPointId * GOLDEN_ANGLE + data.initialAngle; 10669 let offset: vec2f = vec2f(cos(theta), sin(theta)) * pow(r, 1.33); 10670 data.currentPointId = data.currentPointId + 1.0; 10671 return offset; 10672} 10673fn PCSSFindBlocker(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, avgBlockerDepth: ptr<function, f32>, numBlockers: ptr<function, i32>, 10674 shadowCoords: vec2f, z: f32, shadowBlockerSamples: i32, penumbraSize: f32, invShadowMapSize: f32, randomSeed: f32) { 10675 var diskData: VogelDiskData; 10676 prepareDiskConstants(&diskData, shadowBlockerSamples, randomSeed); 10677 let searchWidth: f32 = penumbraSize * invShadowMapSize; 10678 var blockerSum: f32 = 0.0; 10679 var numBlockers_local: i32 = 0; 10680 for( var i: i32 = 0; i < shadowBlockerSamples; i = i + 1 ) { 10681 let diskUV: vec2f = generateDiskSample(&diskData); 10682 let sampleUV: vec2f = shadowCoords + diskUV * searchWidth; 10683 let shadowMapDepth: f32 = textureSampleLevel(shadowMap, shadowMapSampler, sampleUV, 0.0
10683).r; 10684 if ( shadowMapDepth < z ) { 10685 blockerSum = blockerSum + shadowMapDepth; 10686 numBlockers_local = numBlockers_local + 1; 10687 } 10688 } 10689 *avgBlockerDepth = blockerSum / f32(numBlockers_local); 10690 *numBlockers = numBlockers_local; 10691} 10692fn PCSSFilter(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, uv: vec2f, receiverDepth: f32, shadowSamples: i32, filterRadius: f32, randomSeed: f32) -> f32 { 10693 var diskData: VogelDiskData; 10694 prepareDiskConstants(&diskData, shadowSamples, randomSeed); 10695 var sum: f32 = 0.0; 10696 for (var i: i32 = 0; i < shadowSamples; i = i + 1) { 10697 let offsetUV: vec2f = generateDiskSample(&diskData) * filterRadius; 10698 let depth: f32 = textureSampleLevel(shadowMap, shadowMapSampler, uv + offsetUV, 0.0).r; 10699 sum = sum + step(receiverDepth, depth); 10700 } 10701 return sum / f32(shadowSamples); 10702} 10703fn getPenumbra(dblocker: f32, dreceiver: f32, penumbraSize: f32, penumbraFalloff: f32) -> f32 { 10704 let dist: f32 = dreceiver - dblocker; 10705 let penumbra: f32 = 1.0 - pow(1.0 - dist, penumbraFalloff); 10706 return penumbra * penumbraSize; 10707} 10708fn PCSSDirectional(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, shadowCoords: vec3f, cameraParams: vec4f, softShadowParams: vec4f) -> f32 { 10709 let receiverDepth: f32 = shadowCoords.z; 10710 let randomSeed: f32 = fractSinRand(pcPosition.xy); 10711 let shadowSamples: i32 = i32(softShadowParams.x); 10712 let shadowBlockerSamples: i32 = i32(softShadowParams.y); 10713 let penumbraSize: f32 = softShadowParams.z; 10714 let penumbraFalloff: f32 = softShadowParams.w; 10715 let shadowMapSize: i32 = i32(textureDimensions(shadowMap, 0).x); 10716 var invShadowMapSize: f32 = 1.0 / f32(shadowMapSize); 10717 invShadowMapSize = invShadowMapSize * (f32(shadowMapSize) / 2048.0); 10718 var penumbra: f32; 10719 if (shadowBlockerSamples > 0) { 10720 var avgBlockerDepth: f32 = 0.0; 10721 var numBlockers: i32 = 0; 10722 PCSSFindBlocker(shadowMap, shadowMapSampler, &avgBlockerDepth, &numBlockers, shadowCoords.xy, receiverDepth, shadowBlockerSamples, penumbraSize, invShadowMapSize, randomSeed); 10723 if (numBlockers < 1) { 10724 return 1.0; 10725 } 10726 penumbra = getPenumbra(avgBlockerDepth, shadowCoords.z, penumbraSize, penumbraFalloff); 10727 } else { 10728 penumbra = penumbraSize; 10729 } 10730 let filterRadius: f32 = penumbra * invShadowMapSize; 10731 return PCSSFilter(shadowMap, shadowMapSampler, shadowCoords.xy, receiverDepth, shadowSamples, filterRadius, randomSeed); 10732} 10733fn getShadowPCSS(shadowMap: texture_2d<f32>, shadowMapSampler: sampler, shadowCoord: vec3f, shadowParams: vec4f, cameraParams: vec4f, softShadowParams: vec4f, lightDir: vec3f) -> f32 { 10734 return PCSSDirectional(shadowMap, shadowMapSampler, shadowCoord, cameraParams, softShadowParams); 10735} 10736`,WO=` 10737attribute vertex_boneIndices: f32; 10738var texture_poseMap: texture_2d<uff>; 10739fn getBoneMatrix(indexFloat: f32) -> mat4x4f { 10740 let width = i32(textureDimensions(texture_poseMap).x); 10741 let index: i32 = i32(indexFloat + 0.5) * 3; 10742 let iy: i32 = index / width; 10743 let ix: i32 = index % width; 10744 let v1: vec4f = textureLoad(texture_poseMap, vec2i(ix + 0, iy), 0); 10745 let v2: vec4f = textureLoad(texture_poseMap, vec2i(ix + 1, iy), 0); 10746 let v3: vec4f = textureLoad(texture_poseMap, vec2i(ix + 2, iy), 0); 10747 return mat4x4f( 10748 v1.x, v2.x, v3.x, 0, 10749 v1.y, v2.y, v3.y, 0, 10750 v1.z, v2.z, v3.z, 0, 10751 v1.w, v2.w, v3.w, 1.0 10752 ); 10753} 10754`,XO=` 10755attribute vertex_boneWeights: vec4f; 10756attribute vertex_boneIndices: vec4f; 10757var texture_poseMap: texture_2d<uff>; 10758struct BoneMatrix { 10759 v1: vec4f, 10760 v2: vec4f, 10761 v3: vec4f, 10762} 10763fn getBoneMatrix(width: i32, index: i32) -> BoneMatrix { 10764 let v = index / width; 10765 let u = index % width; 10766 var result: BoneMatrix; 10767 result.v1 = textureLoad(texture_poseMap, vec2i(u + 0, v), 0); 10768 result.v2 = textureLoad(texture_poseMap, vec2i(u + 1, v), 0); 10769 result.v3 = textureLoad(texture_poseMap, vec2i(u + 2, v), 0); 10770 return result; 10771} 10772fn getSkinMatrix(indicesFloat: vec4f, weights: vec4f) -> mat4x4f { 10773 let width = i32(textureDimensions(texture_poseMap).x); 10774 var indices = vec4i(indicesFloat + 0.5) * 3; 10775 let boneA = getBoneMatrix(width, indices.x); 10776 let boneB = getBoneMatrix(width, indices.y); 10777 let boneC = getBoneMatrix(width, indices.z); 10778 let boneD = getBoneMatrix(width, indices.w); 10779 let v1 = boneA.v1 * weights.x + boneB.v1 * weights.y + boneC.v1 * weights.z + boneD.v1 * weights.w; 10780 let v2 = boneA.v2 * weights.x + boneB.v2 * weights.y + boneC.v2 * weights.z + boneD.v2 * weights.w; 10781 let v3 = boneA.v3 * weights.x + boneB.v3 * weights.y + boneC.v3 * weights.z + boneD.v3 * weights.w; 10782 let one = dot(weights, vec4f(1.0, 1.0, 1.0, 1.0)); 10783 return mat4x4f( 10784 v1.x, v2.x, v3.x, 0, 10785 v1.y, v2.y, v3.y, 0, 10786 v1.z, v2.z, v3.z, 0, 10787 v1.w, v2.w, v3.w, one 10788 ); 10789} 10790`,YO=` 10791 #define LIT_SKYBOX_INTENSITY 10792 #include "envProcPS" 10793 #include "gammaPS" 10794 #include "tonemappingPS" 10795 #ifdef PREPASS_PASS 10796 varying vLinearDepth: f32; 10797 #include "floatAsUintPS" 10798 #endif 10799 varying vViewDir : vec3f; 10800 uniform skyboxHighlightMultiplier : f32;
10801 #if defined(SKY_FISHEYE) && !defined(SKYMESH) 10802 uniform fisheye_k : f32; 10803 uniform fisheye_invK : f32; 10804 uniform fisheye_projMat00 : f32; 10805 uniform fisheye_projMat11 : f32; 10806 uniform matrix_view : mat4x4f; 10807 uniform cubeMapRotationMatrix : mat3x3f; 10808 varying vClipXYW : vec3f; 10809 #endif 10810 #ifdef SKY_CUBEMAP 10811 var texture_cubeMap : texture_cube<f32>; 10812 var texture_cubeMap_sampler : sampler; 10813 #ifdef SKYMESH 10814 varying vWorldPos : vec3f; 10815 uniform cubeMapRotationMatrix : mat3x3f; 10816 uniform projectedSkydomeCenter : vec3f; 10817 #endif 10818 #else 10819 #include "sphericalPS" 10820 #include "envAtlasPS" 10821 var texture_envAtlas : texture_2d<f32>; 10822 var texture_envAtlas_sampler : sampler; 10823 uniform mipLevel : f32; 10824 #endif 10825 @fragment 10826 fn fragmentMain(input : FragmentInput) -> FragmentOutput { 10827 var output: FragmentOutput; 10828 #ifdef PREPASS_PASS 10829 output.color = float2vec4(vLinearDepth); 10830 #else 10831 var linear : vec3f; 10832 var dir : vec3f; 10833 #if defined(SKY_FISHEYE) && !defined(SKYMESH) 10834 let ndc : vec2f = input.vClipXYW.xy / input.vClipXYW.z; 10835 let px : f32 = ndc.x / uniform.fisheye_projMat00; 10836 let py : f32 = ndc.y / uniform.fisheye_projMat11; 10837 let r : f32 = sqrt(px * px + py * py); 10838 let theta : f32 = uniform.fisheye_k * atan(r * uniform.fisheye_invK); 10839 let sinT : f32 = sin(theta); 10840 let cosT : f32 = cos(theta); 10841 var camDir : vec3f; 10842 if (r > 1e-6) { 10843 camDir = vec3f(px / r * sinT, py / r * sinT, -cosT); 10844 } else { 10845 camDir = vec3f(0.0, 0.0, -1.0); 10846 } 10847 let viewMat3 : mat3x3f = mat3x3f( 10848 uniform.matrix_view[0].xyz, 10849 uniform.matrix_view[1].xyz, 10850 uniform.matrix_view[2].xyz 10851 ); 10852 dir = transpose(viewMat3) * camDir; 10853 dir = dir * uniform.cubeMapRotationMatrix; 10854 #elif defined(SKY_CUBEMAP) && defined(SKYMESH) 10855 var envDir : vec3f = normalize(input.vWorldPos - uniform.projectedSkydomeCenter); 10856 dir = envDir * uniform.cubeMapRotationMatrix; 10857 #else 10858 dir = input.vViewDir; 10859 #endif 10860 #ifdef SKY_CUBEMAP 10861 dir.x *= -1.0; 10862 linear = {SKYBOX_DECODE_FNC}(textureSample(texture_cubeMap, texture_cubeMap_sampler, dir)); 10863 #else 10864 dir *= vec3f(-1.0, 1.0, 1.0); 10865 let uv : vec2f = toSphericalUv(normalize(dir)); 10866 linear = {SKYBOX_DECODE_FNC}(textureSample(texture_envAtlas, texture_envAtlas_sampler, mapRoughnessUv(uv, uniform.mipLevel))); 10867 #endif 10868 if (any(linear >= vec3f(64.0))) { 10869 linear *= uniform.skyboxHighlightMultiplier; 10870 } 10871 10872 output.color = vec4f(gammaCorrectOutput(toneMap(processEnvironment(linear))), 1.0); 10873 #endif 10874 return output; 10875 } 10876`,jO=` 10877 attribute aPosition : vec4f; 10878 uniform matrix_view : mat4x4f; 10879 uniform matrix_projectionSkybox : mat4x4f; 10880 uniform cubeMapRotationMatrix : mat3x3f; 10881 varying vViewDir : vec3f; 10882 #ifdef SKY_FISHEYE 10883 varying vClipXYW : vec3f; 10884 #endif 10885 #ifdef PREPASS_PASS 10886 varying vLinearDepth: f32; 10887 #endif 10888 #ifdef SKYMESH 10889 uniform matrix_model : mat4x4f; 10890 varying vWorldPos : vec3f; 10891 #endif 10892 @vertex 10893 fn vertexMain(input : VertexInput) -> VertexOutput { 10894 var output : VertexOutput; 10895 var view : mat4x4f = uniform.matrix_view; 10896 #ifdef SKYMESH 10897 var worldPos : vec4f = uniform.matrix_model * input.aPosition; 10898 output.vWorldPos = worldPos.xyz; 10899 output.position = uniform.matrix_projectionSkybox * (view * worldPos); 10900 #ifdef PREPASS_PASS 10901 output.vLinearDepth = -(uniform.matrix_view * vec4f(worldPos.xyz, 1.0)).z; 10902 #endif 10903 #else 10904 view[3][0] = 0.0; 10905 view[3][1] = 0.0; 10906 view[3][2] = 0.0; 10907 output.vViewDir = input.aPosition.xyz * uniform.cubeMapRotationMatrix; 10908 #ifdef SKY_FISHEYE 10909 var viewPos : vec4f = view * input.aPosition; 10910 output.position = vec4f(viewPos.xy, 0.0, -viewPos.z); 10911 output.vClipXYW = vec3f(output.position.xy, output.position.w); 10912 #else 10913 output.position = uniform.matrix_projectionSkybox * (view * input.aPosition); 10914 #endif 10915 #ifdef PREPASS_PASS 10916 output.vLinearDepth = -pcPosition.w; 10917 #endif 10918 #endif 10919 output.position.z = output.position.w - 1.0e-7; 10920 return output; 10921 } 10922`,jg=` 10923fn writeSortIndirectArgs( 10924 baseSlot: u32, 10925 count: u32, 10926 slotInfo: vec4<u32> 10927) { 10928 let n = slotInfo.x; 10929 if (n >= 1u) { 10930 let g = slotInfo.y; 10931 let wc = (count + g - 1u) / g; 10932 let off = baseSlot * 3u; 10933 indirectDispatchArgs[off + 0u] = wc; 10934 indirectDispatchArgs[off + 1u] = 1u; 10935 indirectDispatchArgs[off + 2u] = 1u; 10936 }
10937 if (n >= 2u) { 10938 let g = slotInfo.z; 10939 let wc = (count + g - 1u) / g; 10940 let off = (baseSlot + 1u) * 3u; 10941 indirectDispatchArgs[off + 0u] = wc; 10942 indirectDispatchArgs[off + 1u] = 1u; 10943 indirectDispatchArgs[off + 2u] = 1u; 10944 } 10945 if (n >= 3u) { 10946 let g = slotInfo.w; 10947 let wc = (count + g - 1u) / g; 10948 let off = (baseSlot + 2u) * 3u; 10949 indirectDispatchArgs[off + 0u] = wc; 10950 indirectDispatchArgs[off + 1u] = 1u; 10951 indirectDispatchArgs[off + 2u] = 1u; 10952 } 10953} 10954`,qO=` 10955#ifdef STD_SPECULAR_CONSTANT 10956 uniform material_specular: vec3f; 10957#endif 10958fn getSpecularity() { 10959 var specularColor = vec3f(1.0, 1.0, 1.0); 10960 #ifdef STD_SPECULAR_CONSTANT 10961 specularColor = specularColor * uniform.material_specular; 10962 #endif 10963 #ifdef STD_SPECULAR_TEXTURE 10964 specularColor = specularColor * {STD_SPECULAR_TEXTURE_DECODE}(textureSampleBias({STD_SPECULAR_TEXTURE_NAME}, {STD_SPECULAR_TEXTURE_NAME}Sampler, {STD_SPECULAR_TEXTURE_UV}, uniform.textureBias)).{STD_SPECULAR_TEXTURE_CHANNEL}; 10965 #endif 10966 #ifdef STD_SPECULAR_VERTEX 10967 specularColor = specularColor * saturate3(vVertexColor.{STD_SPECULAR_VERTEX_CHANNEL}); 10968 #endif 10969 dSpecularity = specularColor; 10970} 10971`,$O=` 10972fn toSpherical(dir: vec3f) -> vec2f { 10973 let angle_xz = select(0.0, atan2(dir.x, dir.z), any(dir.xz != vec2f(0.0))); 10974 return vec2f(angle_xz, asin(dir.y)); 10975} 10976fn toSphericalUv(dir : vec3f) -> vec2f { 10977 const PI : f32 = 3.141592653589793; 10978 let uv : vec2f = toSpherical(dir) / vec2f(PI * 2.0, PI) + vec2f(0.5, 0.5); 10979 return vec2f(uv.x, 1.0 - uv.y); 10980} 10981`,KO=` 10982#ifdef STD_SPECULARITYFACTOR_CONSTANT 10983 uniform material_specularityFactor: f32; 10984#endif 10985fn getSpecularityFactor() { 10986 var specularityFactor = 1.0; 10987 #ifdef STD_SPECULARITYFACTOR_CONSTANT 10988 specularityFactor = specularityFactor * uniform.material_specularityFactor; 10989 #endif 10990 #ifdef STD_SPECULARITYFACTOR_TEXTURE 10991 specularityFactor = specularityFactor * textureSampleBias({STD_SPECULARITYFACTOR_TEXTURE_NAME}, {STD_SPECULARITYFACTOR_TEXTURE_NAME}Sampler, {STD_SPECULARITYFACTOR_TEXTURE_UV}, uniform.textureBias).{STD_SPECULARITYFACTOR_TEXTURE_CHANNEL}; 10992 #endif 10993 #ifdef STD_SPECULARITYFACTOR_VERTEX 10994 specularityFactor = specularityFactor * saturate(vVertexColor.{STD_SPECULARITYFACTOR_VERTEX_CHANNEL}); 10995 #endif 10996 dSpecularityFactor = specularityFactor; 10997} 10998`,ZO=` 10999fn getSpotEffect(lightSpotDir: vec3f, lightInnerConeAngle: f32, lightOuterConeAngle: f32, lightDirNorm: vec3f) -> f32 { 11000 let cosAngle: f32 = dot(lightDirNorm, lightSpotDir); 11001 return smoothstep(lightOuterConeAngle, lightInnerConeAngle, cosAngle); 11002}`,QO=` 11003 nineSlicedUv = vec2f(vUv0.x, 1.0 - vUv0.y); 11004`,JO=` 11005 let tileMask: vec2f = step(vMask, vec2f(0.99999)); 11006 let tileSize: vec2f = 0.5 * (innerOffset.xy + innerOffset.zw); 11007 let tileScale: vec2f = vec2f(1.0) / (vec2f(1.0) - tileSize); 11008 var clampedUv: vec2f = mix(innerOffset.xy * 0.5, vec2f(1.0) - innerOffset.zw * 0.5, fract((vTiledUv - tileSize) * tileScale)); 11009 clampedUv = clampedUv * atlasRect.zw + atlasRect.xy; 11010 var nineSlicedUv: vec2f = vUv0 * tileMask + clampedUv * (vec2f(1.0) - tileMask); 11011 nineSlicedUv.y = 1.0 - nineSlicedUv.y; 11012`,eB=` 11013 var<private> dAlpha: f32 = 1.0; 11014 #if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE 11015 #ifdef STD_OPACITY_TEXTURE_ALLOCATE 11016 var texture_opacityMap : texture_2d<f32>; 11017 var texture_opacityMapSampler : sampler; 11018 #endif 11019 #endif 11020 #ifdef FORWARD_PASS 11021 var<private> dAlbedo: vec3f; 11022 var<private> dNormalW: vec3f; 11023 var<private> dSpecularity: vec3f = vec3f(0.0, 0.0, 0.0); 11024 var<private> dGlossiness: f32 = 0.0; 11025 #ifdef LIT_REFRACTION 11026 var<private> dTransmission: f32; 11027 var<private> dThickness: f32; 11028 #endif 11029 #ifdef LIT_SCENE_COLOR 11030 var uSceneColorMap : texture_2d<f32>; 11031 var uSceneColorMapSampler : sampler; 11032 #endif 11033 #ifdef LIT_SCREEN_SIZE 11034 uniform uScreenSize: vec4f; 11035 #endif 11036 #ifdef LIT_TRANSFORMS 11037 var<private> matrix_viewProjection: mat4x4f; 11038 var<private> matrix_model: mat4x4f; 11039 #endif 11040 #ifdef STD_HEIGHT_MAP 11041 var<private> dUvOffset: vec2f; 11042 #ifdef STD_HEIGHT_TEXTURE_ALLOCATE 11043 var texture_heightMap : texture_2d<f32>; 11044 var texture_heightMapSampler : sampler; 11045 #endif 11046 #endif 11047 #ifdef STD_DIFFUSE_TEXTURE_ALLOCATE 11048 var texture_diffuseMap : texture_2d<f32>; 11049 var texture_diffuseMapSampler : sampler; 11050 #endif 11051 #ifdef STD_DIFFUSEDETAIL_TEXTURE_ALLOCATE 11052 var texture_diffuseDetailMap : texture_2d<f32>; 11053 var texture_diffuseDetailMapSampler : sampler; 11054 #endif 11055 #ifdef STD_NORMAL_TEXTURE_ALLOCATE 11056 var texture_normalMap : texture_2d<f32>; 11057 var texture_normalMapSampler : sampler; 11058 #endif 11059 #ifdef STD_NORMALDETAIL_TEXTURE_ALLOCATE 11060 var texture_normalDetailMap : texture_2d<f32>; 11061 var texture_normalDetailMapSampler : sampler; 11062 #endif 11063 #ifdef STD_THICKNESS_TEXTURE_ALLOCATE 11064 var texture_thicknessMap : texture_2d<f32>; 11065 var texture_thicknessMapSampler : sampler; 11066 #endif 11067 #ifdef STD_REFRACTION_TEXTURE_ALLOCATE 11068 var texture_refractionMap : texture_2d<f32>; 11069 var texture_refractionMapSampler : sampler; 11070 #endif 11071 #ifdef LIT_IRIDESCENCE 11072 var<private> dIridescence: f32; 11073 var<private> dIridescenceThickness: f32; 11074 #ifdef STD_IRIDESCENCE_THICKNESS_TEXTURE_ALLOCATE 11075 var texture_iridescenceThicknessMap : texture_2d<f32>; 11076 var texture_iridescenceThicknessMapSampler : sampler; 11077 #endif 11078 #ifdef STD_IRIDESCENCE_TEXTURE_ALLOCATE 11079 var texture_iridescenceMap : texture_2d<f32>; 11080 var texture_iridescenceMapSampler : sampler; 11081 #endif 11082 #endif 11083 #ifdef LIT_CLEARCOAT 11084 var<private> ccSpecularity: f32; 11085 var<private> ccGlossiness: f32; 11086 var<private> ccNormalW: vec3f; 11087 #endif 11088 #ifdef LIT_GGX_SPECULAR 11089 var<private> dAnisotropy: f32; 11090 var<private> dAnisotropyRotation: vec2f; 11091 #endif 11092 #ifdef LIT_SPECULAR_OR_REFLECTION 11093 #ifdef LIT_SHEEN 11094 var<private> sSpecularity: vec3f; 11095 var<private> sGlossiness: f32; 11096 #ifdef STD_SHEEN_TEXTURE_ALLOCATE 11097 var texture_sheenMap : texture_2d<f32>; 11098 var texture_sheenMapSampler : sampler; 11099 #endif 11100 #ifdef STD_SHEENGLOSS_TEXTURE_ALLOCATE 11101 var texture_sheenGlossMap : texture_2d<f32>; 11102 var texture_sheenGlossMapSampler : sampler; 11103 #endif 11104 #endif 11105 #ifdef LIT_METALNESS 11106 var<private> dMetalness: f32; 11107 var<private> dIor: f32; 11108 #ifdef STD_METALNESS_TEXTURE_ALLOCATE 11109 var texture_metalnessMap : texture_2d<f32>; 11110 var texture_metalnessMapSampler : sampler; 11111 #endif 11112 #endif 11113 #ifdef LIT_SPECULARITY_FACTOR 11114 var<private> dSpecularityFactor: f32; 11115 #ifdef STD_SPECULARITYFACTOR_TEXTURE_ALLOCATE 11116 var texture_specularityFactorMap : texture_2d<f32>; 11117 var texture_specularityFactorMapSampler : sampler; 11118 #endif 11119 #endif 11120 #ifdef STD_SPECULAR_COLOR 11121 #ifdef STD_SPECULAR_TEXTURE_ALLOCATE 11122 var texture_specularMap : texture_2d<f32>; 11123 var texture_specularMapSampler : sampler; 11124 #endif 11125 #endif 11126 #ifdef STD_GLOSS_TEXTURE_ALLOCATE 11127 var texture_glossMap : texture_2d<f32>; 11128 var texture_glossMapSampler : sampler; 11129 #endif 11130 #endif 11131 #ifdef STD_AO 11132 var <private> dAo: f32; 11133 #ifdef STD_AO_TEXTURE_ALLOCATE 11134 var texture_aoMap : texture_2d<f32>; 11135 var texture_aoMapSampler : sampler; 11136 #endif 11137 #ifdef STD_AODETAIL_TEXTURE_ALLOCATE 11138 var texture_aoDetailMap : texture_2d<f32>; 11139 var texture_aoDetailMapSampler : sampler; 11140 #endif 11141 #endif 11142 var <private> dEmission: vec3f; 11143 #ifdef STD_EMISSIVE_TEXTURE_ALLOCATE 11144 var texture_emissiveMap : texture_2d<f32>; 11145 var texture_emissiveMapSampler : sampler; 11146 #endif 11147 #ifdef LIT_CLEARCOAT 11148 #ifdef STD_CLEARCOAT_TEXTURE_ALLOCATE 11149 var texture_clearCoatMap : texture_2d<f32>; 11150 var texture_clearCoatMapSampler : sampler; 11151 #endif 11152 #ifdef STD_CLEARCOATGLOSS_TEXTURE_ALLOCATE 11153 var texture_clearCoatGlossMap : texture_2d<f32>; 11154 var texture_clearCoatGlossMapSampler : sampler; 11155 #endif 11156 #ifdef STD_CLEARCOATNORMAL_TEXTURE_ALLOCATE 11157 var texture_clearCoatNormalMap : texture_2d<f32>; 11158 var texture_clearCoatNormalMapSampler : sampler; 11159 #endif 11160 #endif 11161 #ifdef LIT_GGX_SPECULAR 11162 #ifdef STD_ANISOTROPY_TEXTURE_ALLOCATE 11163 var texture_anisotropyMap : texture_2d<f32>; 11164 var texture_anisotropyMapSampler : sampler; 11165 #endif 11166 #endif 11167 #if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR) 11168 var<private> dLightmap: vec3f;
11169 #ifdef STD_LIGHT_TEXTURE_ALLOCATE 11170 var texture_lightMap : texture_2d<f32>; 11171 var texture_lightMapSampler : sampler; 11172 #endif 11173 #endif 11174 #endif 11175 #include "litShaderCorePS" 11176`,tB=` 11177 #if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE 11178 #include "opacityPS" 11179 #if defined(LIT_ALPHA_TEST) 11180 #include "alphaTestPS" 11181 #endif 11182 #if STD_OPACITY_DITHER != NONE 11183 #include "opacityDitherPS" 11184 #endif 11185 #endif 11186 #ifdef FORWARD_PASS 11187 #ifdef STD_HEIGHT_MAP 11188 #include "parallaxPS" 11189 #endif 11190 #include "diffusePS" 11191 #ifdef LIT_NEEDS_NORMAL 11192 #include "normalMapPS" 11193 #endif 11194 #ifdef LIT_REFRACTION 11195 #include "transmissionPS" 11196 #include "thicknessPS" 11197 #endif 11198 #ifdef LIT_IRIDESCENCE 11199 #include "iridescencePS" 11200 #include "iridescenceThicknessPS" 11201 #endif 11202 #ifdef LIT_SPECULAR_OR_REFLECTION 11203 #ifdef LIT_SHEEN 11204 #include "sheenPS" 11205 #include "sheenGlossPS" 11206 #endif 11207 #ifdef LIT_METALNESS 11208 #include "metalnessPS" 11209 #include "iorPS" 11210 #endif 11211 #ifdef LIT_SPECULARITY_FACTOR 11212 #include "specularityFactorPS" 11213 #endif 11214 #ifdef STD_SPECULAR_COLOR 11215 #include "specularPS" 11216 #else 11217 fn getSpecularity() { 11218 dSpecularity = vec3f(1.0, 1.0, 1.0); 11219 } 11220 #endif 11221 #include "glossPS" 11222 #endif 11223 #ifdef STD_AO 11224 #include "aoPS" 11225 #endif 11226 #include "emissivePS" 11227 #ifdef LIT_CLEARCOAT 11228 #include "clearCoatPS" 11229 #include "clearCoatGlossPS" 11230 #include "clearCoatNormalPS" 11231 #endif 11232 #if defined(LIT_SPECULAR) && defined(LIT_LIGHTING) && defined(LIT_GGX_SPECULAR) 11233 #include "anisotropyPS" 11234 #endif 11235 #if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR) 11236 #include "lightmapPS" 11237 #endif 11238 #endif 11239 fn evaluateFrontend() { 11240 #if LIT_BLEND_TYPE != NONE || defined(LIT_ALPHA_TEST) || defined(LIT_ALPHA_TO_COVERAGE) || STD_OPACITY_DITHER != NONE 11241 getOpacity(); 11242 #if defined(LIT_ALPHA_TEST) 11243 alphaTest(dAlpha); 11244 #endif 11245 #if STD_OPACITY_DITHER != NONE 11246 opacityDither(dAlpha * uniform.material_alphaDitherScale, 0.0); 11247 #endif 11248 litArgs_opacity = dAlpha; 11249 #endif 11250 #ifdef FORWARD_PASS 11251 #ifdef STD_HEIGHT_MAP 11252 getParallax(); 11253 #endif 11254 getAlbedo(); 11255 litArgs_albedo = dAlbedo; 11256 #ifdef LIT_NEEDS_NORMAL 11257 getNormal(); 11258 litArgs_worldNormal = dNormalW; 11259 #endif 11260 #ifdef LIT_REFRACTION 11261 getRefraction(); 11262 litArgs_transmission = dTransmission; 11263 getThickness(); 11264 litArgs_thickness = dThickness; 11265 #ifdef LIT_DISPERSION 11266 litArgs_dispersion = uniform.material_dispersion; 11267 #endif 11268 #endif 11269 #ifdef LIT_IRIDESCENCE 11270 getIridescence(); 11271 getIridescenceThickness(); 11272 litArgs_iridescence_intensity = dIridescence; 11273 litArgs_iridescence_thickness = dIridescenceThickness; 11274 #endif 11275 #ifdef LIT_SPECULAR_OR_REFLECTION 11276 #ifdef LIT_SHEEN 11277 getSheen(); 11278 litArgs_sheen_specularity = sSpecularity; 11279 getSheenGlossiness(); 11280 litArgs_sheen_gloss = sGlossiness; 11281 #endif 11282 #ifdef LIT_METALNESS 11283 getMetalness(); 11284 litArgs_metalness = dMetalness; 11285 getIor(); 11286 litArgs_ior = dIor; 11287 #endif 11288 #ifdef LIT_SPECULARITY_FACTOR 11289 getSpecularityFactor(); 11290 litArgs_specularityFactor = dSpecularityFactor; 11291 #endif 11292 getGlossiness(); 11293 getSpecularity(); 11294 litArgs_specularity = dSpecularity; 11295 litArgs_gloss = dGlossiness; 11296 #endif 11297 #ifdef STD_AO 11298 getAO(); 11299 litArgs_ao = dAo; 11300 #endif 11301 getEmission(); 11302 litArgs_emission = dEmission; 11303 #ifdef LIT_CLEARCOAT 11304 getClearCoat(); 11305 getClearCoatGlossiness(); 11306 getClearCoatNormal(); 11307 litArgs_clearcoat_specularity = ccSpecularity; 11308 litArgs_clearcoat_gloss = ccGlossiness; 11309 litArgs_clearcoat_worldNormal = ccNormalW; 11310 #endif 11311 #if defined(LIT_SPECULAR) && defined(LIT_LIGHTING) && defined(LIT_GGX_SPECULAR) 11312 getAnisotropy(); 11313 #endif 11314 #if defined(STD_LIGHTMAP) || defined(STD_LIGHT_VERTEX_COLOR) 11315 getLightMap(); 11316 litArgs_lightmap = dLightmap; 11317 #ifdef STD_LIGHTMAP_DIR 11318 litArgs_lightmapDir = dLightmapDir; 11319 #endif 11320 #endif 11321 #endif 11322 } 11323`,sB=` 11324#ifdef LIT_TANGENTS 11325 #define TBN_TANGENTS 11326#else 11327 #if defined(LIT_USE_NORMALS) || defined(LIT_USE_CLEARCOAT_NORMALS) 11328 #define TBN_DERIVATIVES 11329 #endif 11330#endif 11331#if defined(TBN_DERIVATIVES) 11332 uniform tbnBasis: f32; 11333#endif 11334fn getTBN(tangent: vec3f, binormal: vec3f, normal: vec3f) { 11335 #ifdef TBN_TANGENTS 11336 dTBN = mat3x3f(normalize(tangent), normalize(binormal), normalize(normal)); 11337 #elif defined(TBN_DERIVATIVES) 11338 let uv: vec2f = {lightingUv}; 11339 let dp1: vec3f = dpdx( vPositionW ); 11340 let dp2: vec3f = dpdy( vPositionW ); 11341 let duv1: vec2f = dpdx( uv ); 11342 let duv2: vec2f = dpdy( uv ); 11343 let dp2perp: vec3f = cross( dp2, normal );
11344 let dp1perp: vec3f = cross( normal, dp1 ); 11345 let T: vec3f = dp2perp * duv1.x + dp1perp * duv2.x; 11346 let B: vec3f = dp2perp * duv1.y + dp1perp * duv2.y; 11347 let denom: f32 = max( dot(T, T), dot(B, B) ); 11348 let invmax: f32 = select(uniform.tbnBasis / sqrt( denom ), 0.0, denom == 0.0); 11349 dTBN = mat3x3f(T * invmax, -B * invmax, normal ); 11350 #else 11351 var B: vec3f = cross(normal, vObjectSpaceUpW); 11352 var T: vec3f = cross(normal, B); 11353 if (dot(B,B) == 0.0) 11354 { 11355 let major: f32 = max(max(normal.x, normal.y), normal.z); 11356 if (normal.x == major) 11357 { 11358 B = cross(normal, vec3f(0.0, 1.0, 0.0)); 11359 T = cross(normal, B); 11360 } 11361 else if (normal.y == major) 11362 { 11363 B = cross(normal, vec3f(0.0, 0.0, 1.0)); 11364 T = cross(normal, B); 11365 } 11366 else 11367 { 11368 B = cross(normal, vec3f(1.0, 0.0, 0.0)); 11369 T = cross(normal, B); 11370 } 11371 } 11372 dTBN = mat3x3f(normalize(T), normalize(B), normalize(normal)); 11373 #endif 11374}`,iB=` 11375#ifdef STD_THICKNESS_CONSTANT 11376uniform material_thickness: f32; 11377#endif 11378fn getThickness() { 11379 dThickness = 1.0; 11380 #ifdef STD_THICKNESS_CONSTANT 11381 dThickness = dThickness * uniform.material_thickness; 11382 #endif 11383 #ifdef STD_THICKNESS_TEXTURE 11384 dThickness = dThickness * textureSampleBias({STD_THICKNESS_TEXTURE_NAME}, {STD_THICKNESS_TEXTURE_NAME}Sampler, {STD_THICKNESS_TEXTURE_UV}, uniform.textureBias).{STD_THICKNESS_TEXTURE_CHANNEL}; 11385 #endif 11386 #ifdef STD_THICKNESS_VERTEX 11387 dThickness = dThickness * saturate(vVertexColor.{STD_THICKNESS_VERTEX_CHANNEL}); 11388 #endif 11389} 11390`,rB=` 11391#ifndef TONEMAP_NO_EXPOSURE_UNIFORM 11392 #if TONEMAP != NONE 11393 uniform exposure: f32; 11394 fn getExposure() -> f32 { return uniform.exposure; } 11395 #else 11396 fn getExposure() -> f32 { return 1.0; } 11397 #endif 11398#else 11399 #if TONEMAP != NONE 11400 fn getExposure() -> f32 { return uniforms.exposure; } 11401 #else 11402 fn getExposure() -> f32 { return 1.0; } 11403 #endif 11404#endif 11405#if (TONEMAP == NONE) 11406 #include "tonemappingNonePS" 11407#elif TONEMAP == FILMIC 11408 #include "tonemappingFilmicPS" 11409#elif TONEMAP == LINEAR 11410 #include "tonemappingLinearPS" 11411#elif TONEMAP == HEJL 11412 #include "tonemappingHejlPS" 11413#elif TONEMAP == ACES 11414 #include "tonemappingAcesPS" 11415#elif TONEMAP == ACES2 11416 #include "tonemappingAces2PS" 11417#elif TONEMAP == NEUTRAL 11418 #include "tonemappingNeutralPS" 11419#endif 11420`,aB=` 11421fn toneMap(color: vec3f) -> vec3f { 11422 let tA: f32 = 2.51; 11423 let tB: f32 = 0.03; 11424 let tC: f32 = 2.43; 11425 let tD: f32 = 0.59; 11426 let tE: f32 = 0.14; 11427 let x: vec3f = color * getExposure(); 11428 return (x * (tA * x + tB)) / (x * (tC * x + tD) + tE); 11429} 11430`,nB=` 11431const ACESInputMat: mat3x3f = mat3x3f( 11432 vec3f(0.59719, 0.35458, 0.04823), 11433 vec3f(0.07600, 0.90834, 0.01566), 11434 vec3f(0.02840, 0.13383, 0.83777) 11435); 11436const ACESOutputMat: mat3x3f = mat3x3f( 11437 vec3f( 1.60475, -0.53108, -0.07367), 11438 vec3f(-0.10208, 1.10813, -0.00605), 11439 vec3f(-0.00327, -0.07276, 1.07602) 11440); 11441fn RRTAndODTFit(v: vec3f) -> vec3f { 11442 let a: vec3f = v * (v + vec3f(0.0245786)) - vec3f(0.000090537); 11443 let b: vec3f = v * (vec3f(0.983729) * v + vec3f(0.4329510)) + vec3f(0.238081); 11444 return a / b; 11445} 11446fn toneMap(color: vec3f) -> vec3f { 11447 var c: vec3f = color * (getExposure() / 0.6); 11448 c = c * ACESInputMat; 11449 c = RRTAndODTFit(c); 11450 c = c * ACESOutputMat; 11451 return clamp(c, vec3f(0.0), vec3f(1.0)); 11452} 11453`,oB=` 11454const A: f32 = 0.15; 11455const B: f32 = 0.50; 11456const C: f32 = 0.10; 11457const D: f32 = 0.20; 11458const E: f32 = 0.02; 11459const F: f32 = 0.30; 11460const W: f32 = 11.2; 11461fn uncharted2Tonemap(x: vec3f) -> vec3f { 11462 return ((x * (A * x + C * B) + D * E) / (x * (A * x + B) + D * F)) - vec3f(E / F); 11463} 11464fn toneMap(color: vec3f) -> vec3f { 11465 var c: vec3f = uncharted2Tonemap(color * getExposure()); 11466 let whiteScale: vec3f = vec3f(1.0) / uncharted2Tonemap(vec3f(W, W, W)); 11467 c *= whiteScale; 11468 return c; 11469} 11470`,lB=` 11471fn toneMap(color: vec3f) -> vec3f { 11472 let A: f32 = 0.22; 11473 let B: f32 = 0.3; 11474 let C: f32 = 0.1; 11475 let D: f32 = 0.2; 11476 let E: f32 = 0.01; 11477 let F: f32 = 0.3; 11478 let Scl: f32 = 1.25; 11479 let adjusted_color = color * getExposure(); 11480 let h = max(vec3f(0.0), adjusted_color - vec3f(0.004)); 11481 return (h * ((Scl * A) * h + Scl * vec3f(C * B)) + Scl * vec3f(D * E)) / 11482 (h * (A * h + vec3f(B)) + vec3f(D * F)) - 11483 Scl * vec3f(E / F); 11484} 11485`,cB=` 11486fn toneMap(color: vec3f) -> vec3f { 11487 return color * getExposure(); 11488} 11489`,hB=` 11490fn toneMap(col: vec3f) -> vec3f { 11491 var color = col * getExposure(); 11492 let startCompression = 0.8 - 0.04; 11493 let desaturation = 0.15; 11494 let x = min(color.r, min(color.g, color.b)); 11495 let offset = select(0.04, x - 6.25 * x * x, x < 0.08); 11496 color -= vec3f(offset); 11497 let peak = max(color.r, max(color.g, color.b)); 11498 if (peak < startCompression) { 11499 return color; 11500 } 11501 let d = 1.0 - startCompression; 11502 let newPeak = 1.0 - d * d / (peak + d - startCompression); 11503 color *= newPeak / peak; 11504 let g = 1.0 - 1.0 / (desaturation * (peak - newPeak) + 1.0); 11505 return mix(color, vec3f(newPeak), vec3f(g)); 11506} 11507`,dB=` 11508fn toneMap(color: vec3f) -> vec3f { 11509 return color; 11510} 11511`,uB=` 11512#ifdef PIXELSNAP 11513 uniform uScreenSize: vec4f; 11514#endif 11515#ifdef SCREENSPACE 11516 uniform projectionFlipY: f32; 11517#endif 11518fn evalWorldPosition(vertexPosition: vec3f, modelMatrix: mat4x4f) -> vec4f { 11519 var localPos: vec3f = getLocalPosition(vertexPosition); 11520 #ifdef NINESLICED 11521 var localPosXZ: vec2f = localPos.xz; 11522 localPosXZ = localPosXZ * uniform.outerScale; 11523 let positiveUnitOffset: vec2f = clamp(vertexPosition.xz, vec2f(0.0), vec2f(1.0)); 11524 let negativeUnitOffset: vec2f = clamp(-vertexPosition.xz, vec2f(0.0), vec2f(1.0)); 11525 localPosXZ = localPosXZ + (-positiveUnitOffset * uniform.innerOffset.xy + negativeUnitOffset * uniform.innerOffset.zw) * vertex_texCoord0.xy; 11526 dTiledUvGlobal = (localPosXZ - uniform.outerScale + uniform.innerOffset.xy) * -0.5 + 1.0; 11527 localPosXZ = localPosXZ * -0.5; 11528 localPos = vec3f(localPosXZ.x, localPosXZ.y, localPos.y); 11529 #endif 11530 var posW: vec4f = modelMatrix * vec4f(localPos, 1.0); 11531 #ifdef SCREENSPACE 11532 posW = vec4f(posW.xy, 0.0, 1.0); 11533 #endif 11534 return posW; 11535} 11536fn getPosition() -> vec4f { 11537 dModelMatrix = getModelMatrix(); 11538 let posW: vec4f = evalWorldPosition(vertex_position.xyz, dModelMatrix); 11539 dPositionW = posW.xyz; 11540 var screenPos: vec4f; 11541 #ifdef UV1LAYOUT 11542 screenPos = vec4f(vertex_texCoord1.xy * 2.0 - 1.0, 0.5, 1.0);
11543 screenPos.y *= -1.0; 11544 #else 11545 #ifdef SCREENSPACE 11546 screenPos = posW; 11547 screenPos.y *= uniform.projectionFlipY; 11548 #else 11549 screenPos = uniform.matrix_viewProjection * posW; 11550 #endif 11551 #ifdef PIXELSNAP 11552 screenPos.xy = (screenPos.xy * 0.5) + 0.5; 11553 screenPos.xy *= uniforms.uScreenSize.xy; 11554 screenPos.xy = floor(screenPos.xy); 11555 screenPos.xy *= uniforms.uScreenSize.zw; 11556 screenPos.xy = (screenPos.xy * 2.0) - 1.0; 11557 #endif 11558 #endif 11559 return screenPos; 11560} 11561fn getWorldPosition() -> vec3f { 11562 return dPositionW; 11563} 11564`,fB=` 11565 attribute vertex_position: vec4f; 11566 uniform matrix_viewProjection: mat4x4f; 11567 uniform matrix_model: mat4x4f; 11568 11569 #ifdef MORPHING 11570 uniform morph_tex_params: vec2f; 11571 attribute morph_vertex_id: u32; 11572 fn getTextureMorphCoords() -> vec2i { 11573 var textureSize: vec2i = vec2i(uniform.morph_tex_params); 11574 var morphGridV: i32 = i32(morph_vertex_id) / textureSize.x; 11575 var morphGridU: i32 = i32(morph_vertex_id) - (morphGridV * textureSize.x); 11576 morphGridV = textureSize.y - morphGridV - 1; 11577 return vec2i(morphGridU, morphGridV); 11578 } 11579 #ifdef MORPHING_POSITION 11580 #ifdef MORPHING_INT 11581 uniform aabbSize: vec3f; 11582 uniform aabbMin: vec3f; 11583 var morphPositionTex: texture_2d<u32>; 11584 #else 11585 var morphPositionTex: texture_2d<f32>; 11586 #endif 11587 #endif 11588 #endif 11589 #ifdef defined(BATCH) 11590 #include "skinBatchVS" 11591 fn getModelMatrix() -> mat4x4f { 11592 return getBoneMatrix(vertex_boneIndices); 11593 } 11594 #elif defined(SKIN) 11595 #include "skinVS" 11596 fn getModelMatrix() -> mat4x4f { 11597 return uniform.matrix_model * getSkinMatrix(vertex_boneIndices, vertex_boneWeights); 11598 } 11599 #elif defined(INSTANCING) 11600 #include "transformInstancingVS" 11601 #else 11602 fn getModelMatrix() -> mat4x4f { 11603 return uniform.matrix_model; 11604 } 11605 #endif 11606 fn getLocalPosition(vertexPosition: vec3f) -> vec3f { 11607 var localPos: vec3f = vertexPosition; 11608 #ifdef MORPHING_POSITION 11609 var morphUV: vec2i = getTextureMorphCoords(); 11610 #ifdef MORPHING_INT 11611 var morphPos: vec3f = vec3f(textureLoad(morphPositionTex, morphUV, 0).xyz) / 65535.0 * uniform.aabbSize + uniform.aabbMin; 11612 #else 11613 var morphPos: vec3f = textureLoad(morphPositionTex, morphUV, 0).xyz; 11614 #endif 11615 localPos += morphPos; 11616 #endif 11617 return localPos; 11618 } 11619`,pB=` 11620attribute instance_line1: vec4f; 11621attribute instance_line2: vec4f; 11622attribute instance_line3: vec4f; 11623attribute instance_line4: vec4f; 11624fn getModelMatrix() -> mat4x4f { 11625 return uniform.matrix_model * mat4x4f(instance_line1, instance_line2, instance_line3, instance_line4); 11626} 11627`,mB=` 11628#ifdef STD_REFRACTION_CONSTANT 11629 uniform material_refraction: f32; 11630#endif 11631fn getRefraction() { 11632 var refraction: f32 = 1.0; 11633 #ifdef STD_REFRACTION_CONSTANT 11634 refraction = uniform.material_refraction; 11635 #endif 11636 #ifdef STD_REFRACTION_TEXTURE 11637 refraction = refraction * textureSampleBias({STD_REFRACTION_TEXTURE_NAME}, {STD_REFRACTION_TEXTURE_NAME}Sampler, {STD_REFRACTION_TEXTURE_UV}, uniform.textureBias).{STD_REFRACTION_TEXTURE_CHANNEL}; 11638 #endif 11639 #ifdef STD_REFRACTION_VERTEX 11640 refraction = refraction * saturate(vVertexColor.{STD_REFRACTION_VERTEX_CHANNEL}); 11641 #endif 11642 dTransmission = refraction; 11643} 11644`,_B=` 11645fn handleTwoSidedLighting() { 11646 if (!pcFrontFacing) { dTBN[2] = -dTBN[2]; } 11647} 11648`,gB=` 11649#ifdef NINESLICED 11650 fn getUv0() -> vec2f { 11651 var uv = vertex_position.xz; 11652 let positiveUnitOffset = clamp(vertex_position.xz, vec2f(0.0, 0.0), vec2f(1.0, 1.0)); 11653 let negativeUnitOffset = clamp(-vertex_position.xz, vec2f(0.0, 0.0), vec2f(1.0, 1.0)); 11654 uv = uv + ((-positiveUnitOffset * uniform.innerOffset.xy) + (negativeUnitOffset * uniform.innerOffset.zw)) * vertex_texCoord0.xy; 11655 uv = uv * -0.5 + vec2f(0.5, 0.5); 11656 uv = uv * uniform.atlasRect.zw + uniform.atlasRect.xy; 11657 dMaskGlobal = vertex_texCoord0.xy; 11658 return uv; 11659 } 11660#else 11661 fn getUv0() -> vec2f { 11662 return vertex_texCoord0; 11663 } 11664#endif 11665`,vB=` 11666fn getUv1() -> vec2f { 11667 return vertex_texCoord1; 11668} 11669`,SB=` 11670output.vUV{TRANSFORM_UV_{i}}_{TRANSFORM_ID_{i}} = vec2f( 11671 dot(vec3f(uv{TRANSFORM_UV_{i}}, 1), uniform.{TRANSFORM_NAME_{i}}0), 11672 dot(vec3f(uv{TRANSFORM_UV_{i}}, 1), uniform.{TRANSFORM_NAME_{i}}1) 11673); 11674`,yB=` 11675 uniform {TRANSFORM_NAME_{i}}0: vec3f; 11676 uniform {TRANSFORM_NAME_{i}}1: vec3f; 11677`,xB=` 11678fn getViewDir() { 11679 dViewDirW = normalize(uniform.view_position - vPositionW); 11680} 11681`;const Kl={alphaTestPS:N3,ambientPS:k3,anisotropyPS:U3,aoPS:z3,aoDiffuseOccPS:V3,aoSpecOccPS:G3,bakeDirLmEndPS:H3,bakeLmEndPS:W3,basePS:X3,baseNineSlicedPS:Y3,baseNineSlicedTiledPS:j3,bayerPS:q3,blurVSMPS:$3,clearCoatPS:K3,clearCoatGlossPS:Z3,clearCoatNormalPS:Q3,clusteredLightCookiesPS:eF,clusteredLightShadowsPS:tF,clusteredLightUtilsPS:J3,clusteredLightPS:sF,combinePS:iF,cookieBlit2DPS:rF,cookieBlitCubePS:aF,cookieBlitVS:nF,cubeMapProjectP
11681S:oF,cubeMapRotatePS:lF,debugOutputPS:cF,debugProcessFrontendPS:hF,detailModesPS:uF,diffusePS:fF,decodePS:dF,emissivePS:pF,encodePS:mF,endPS:_F,envAtlasPS:gF,envProcPS:vF,falloffInvSquaredPS:SF,falloffLinearPS:yF,floatAsUintPS:xF,fogPS:TF,fogMathPS:wF,fresnelSchlickPS:CF,frontendCodePS:"",frontendDeclPS:"",fullscreenQuadVS:EF,gammaPS:bF,glossPS:AF,quadVS:PF,indirectCoreCS:Of,immediateLinePS:IF,immediateLineVS:DF,iridescenceDiffractionPS:MF,iridescencePS:RF,iridescenceThicknessPS:LF,iorPS:FF,lightDeclarationPS:OF,lightDiffuseLambertPS:BF,lightDirPointPS:NF,lightEvaluationPS:kF,lightFunctionLightPS:UF,lightFunctionShadowPS:zF,lightingPS:VF,lightmapAddPS:GF,lightmapPS:HF,lightSpecularAnisoGGXPS:WF,lightSpecularGGXPS:XF,lightSpecularBlinnPS:YF,lightSheenPS:jF,linearizeDepthPS:qF,litForwardBackendPS:$F,litForwardDeclarationPS:KF,litForwardMainPS:ZF,litForwardPostCodePS:QF,litForwardPreCodePS:JF,litMainPS:eO,litMainVS:tO,litOtherMainPS:sO,litShaderArgsPS:iO,litShaderCorePS:rO,litShadowMainPS:aO,litUserDeclarationPS:"",litUserDeclarationVS:"",litUserCodePS:"",litUserCodeVS:"",litUserMainStartPS:"",litUserMainStartVS:"",litUserMainEndPS:"",litUserMainEndVS:"",ltcPS:nO,metalnessPS:oO,metalnessModulatePS:cO,morphPS:hO,morphVS:dO,msdfPS:lO,msdfVS:uO,normalVS:fO,normalCoreVS:pO,normalMapPS:mO,opacityPS:_O,opacityDitherPS:gO,outputPS:vO,outputAlphaPS:SO,outputTex2DPS:yO,sheenPS:xO,sheenGlossPS:TO,parallaxPS:wO,pickPS:CO,reflDirPS:EO,reflDirAnisoPS:bO,reflectionCCPS:AO,reflectionCubePS:PO,reflectionEnvHQPS:IO,reflectionEnvPS:DO,reflectionSpherePS:MO,reflectionSheenPS:RO,refractionCubePS:LO,refractionDynamicPS:FO,reprojectPS:OO,reprojectVS:BO,screenDepthPS:NO,shadowCascadesPS:kO,shadowEVSMPS:UO,shadowPCF1PS:zO,shadowPCF3PS:VO,shadowPCF5PS:GO,shadowSoftPS:HO,skinBatchVS:WO,skinVS:XO,skyboxPS:YO,skyboxVS:jO,sortIndirectArgsCS:jg,specularPS:qO,sphericalPS:$O,specularityFactorPS:KO,spotPS:ZO,startNineSlicedPS:QO,startNineSlicedTiledPS:JO,stdDeclarationPS:eB,stdFrontEndPS:tB,TBNPS:sB,thicknessPS:iB,tonemappingPS:rB,tonemappingAcesPS:aB,tonemappingAces2PS:nB,tonemappingFilmicPS:oB,tonemappingHejlPS:lB,tonemappingLinearPS:cB,tonemappingNeutralPS:hB,tonemappingNonePS:dB,transformVS:uB,transformCoreVS:fB,transformInstancingVS:pB,transmissionPS:mB,twoSidedLightingPS:_B,uv0VS:gB,uv1VS:vB,uvTransformVS:SB,uvTransformUniformsPS:yB,viewDirPS:xB,webgpuPS:nT,webgpuVS:oT};class Ts extends ge{_batcher=null;_destroyRequested=!1;_inFrameUpdate=!1;_librariesLoaded=!1;_fillMode=by;_resolutionMode=IR;_allowResize=!0;_skyboxAsset=null;_soundManager;_visibilityChangeHandler;_entityIndex={};_inTools=!1;_scriptPrefix="";_time=0;enableBundles=typeof TextDecoder<"u";frameRequestId;tick=(e,t)=>{if(!this.graphicsDevice)return;this.frameRequestId&&(this.xr?.session?.cancelAnimationFrame(this.frameRequestId),cancelAnimationFrame(this.frameRequestId),this.frameRequestId=null),this._inFrameUpdate=!0,$p(this);const s=this._processTimestamp(e)||Gt(),i=s-(this._time||s);let r=i/1e3;if(r=H.clamp(r,0,this.maxDeltaTime),r*=this.timeScale,this._time=s,this.requestAnimationFrame(),this.graphicsDevice.contextLost)return;this.stats.updateBasic(s,r,i,this.renderer,this.graphicsDevice),this.fire("frameupdate",i);let a=!1;t&&(a=!this.xr?.update(t)),a||(this.update(r),this.fire("framerender"),(this.autoRender||this.renderNextFrame)&&(this.render(),this.renderNextFrame=!1),this.fire("frameend"),this.stats.frameEnd()),this._inFrameUpdate=!1,this._destroyRequested&&this.destroy()};timeScale=1;maxDeltaTime=.1;frame=0;frameGraph=new DR;renderer;scriptsOrder=[];stats;autoRender=!0;renderNextFrame=!1;graphicsDevice;root;scene;lightmapper=null;loader=new Co(this);assets;bundles;scenes=new qR(this);scripts=new WR(this);systems=new UR;i18n=new fn(this);keyboard=null;mouse=null;touch=null;gamepads=null;elementInput=null;xr=null;constructor(e){super(),Ts._applications[e.id]=this,$p(this),this.root=new lt,this.root._enabledInHierarchy=!0}init(e){const{assetPrefix:t,batchManager:s,componentSystems:i,elementInput:r,gamepads:a,graphicsDevice:n,keyboard:o,lightmapper:c,mouse:h,resourceHandlers:d,scriptsOrder:u,scriptPrefix:f,soundManager:p,touch:m,xr:_}=e;this.graphicsDevice=n,be.get(n,ze).add(B3),be.get(n,de).add(Kl),this._initDefaultMaterial(),this._initProgramLibrary(),this.stats=new $R(n),this._soundManager=p,this.scene=new ti(n),this._registerSceneImmediate(this.scene),this.assets=new Ew(this.loader),t&&(this.assets.prefix=t),this.bundles=new kR(this.assets),this.scriptsOrder=u||[],this.defaultLayerWorld=new Kt({name:"World",i
11681d:Ir}),this.defaultLayerDepth=new Kt({name:"Depth",id:ks,enabled:!1,opaqueSortMode:Ad}),this.defaultLayerSkybox=new Kt({name:"Skybox",id:Pg,opaqueSortMode:Ad}),this.defaultLayerUi=new Kt({name:"UI",id:Ef,transparentSortMode:MI}),this.defaultLayerImmediate=new Kt({name:"Immediate",id:Ig,opaqueSortMode:Ad});const g=new i_("default");g.pushOpaque(this.defaultLayerWorld),g.pushOpaque(this.defaultLayerDepth),g.pushOpaque(this.defaultLayerSkybox),g.pushTransparent(this.defaultLayerWorld),g.pushOpaque(this.defaultLayerImmediate),g.pushTransparent(this.defaultLayerImmediate),g.pushTransparent(this.defaultLayerUi),this.scene.layers=g,Ha.createPlaceholder(n),this.renderer=new KT(n,this.scene),c&&(this.lightmapper=new c(n,this.root,this.scene,this.renderer,this.assets),this.once("prerender",this._firstBake,this)),s&&(this._batcher=new s(n,this.root,this.scene),this.once("prerender",this._firstBatch,this)),this.keyboard=o||null,this.mouse=h||null,this.touch=m||null,this.gamepads=a||null,r&&(this.elementInput=r,this.elementInput.app=this),this.xr=_?new _(this):null,this.elementInput&&this.elementInput.attachSelectEvents(),this._scriptPrefix=f||"",this.enableBundles&&this.loader.addHandler("bundle",new GR(this)),d.forEach(v=>{const x=new v(this);this.loader.addHandler(x.handlerType,x)}),this.loader.enableRetry(),i.forEach(v=>{this.systems.add(new v(this))}),this._visibilityChangeHandler=this.onVisibilityChange.bind(this),typeof document<"u"&&document.addEventListener("visibilitychange",this._visibilityChangeHandler,!1)}static _applications={};static getApplication(e){return e?Ts._applications[e]:yi()}_initDefaultMaterial(){const e=new Es;e.name="Default Material",a1(this.graphicsDevice,e)}_initProgramLibrary(){const e=new KM(this.graphicsDevice,new Es);qI(this.graphicsDevice,e)}get soundManager(){return this._soundManager}get batcher(){return this._batcher}get fillMode(){return this._fillMode}get resolutionMode(){return this._resolutionMode}configure(e,t){ht.get(e,(s,i)=>{if(s){t(s);return}const r=i.application_properties,a=i.scenes,n=i.assets;this._parseApplicationProperties(r,o=>{this._parseScenes(a),this._parseAssets(n),t(o||null)})})}preload(e){this.fire("preload:start");const t=this.assets.list({preload:!0});if(t.length===0){this.fire("preload:end"),e();return}let s=0;const i=()=>{s++,this.fire("preload:progress",s/t.length),s===t.length&&(this.fire("preload:end"),e())};t.forEach(r=>{r.loaded?i():(r.once("load",i),r.once("error",i),this.assets.load(r))})}_preloadScripts(e,t){t()}_parseApplicationProperties(e,t){if(typeof e.maxAssetRetries=="number"&&e.maxAssetRetries>0&&this.loader.enableRetry(e.maxAssetRetries),e.useDevicePixelRatio||(e.useDevicePixelRatio=e.use_device_pixel_ratio),e.resolutionMode||(e.resolutionMode=e.resolution_mode),e.fillMode||(e.fillMode=e.fill_mode),this._width=e.width,this._height=e.height,e.useDevicePixelRatio&&(this.graphicsDevice.maxPixelRatio=window.devicePixelRatio),this.setCanvasResolution(e.resolutionMode,this._width,this._height),this.setCanvasFillMode(e.fillMode,this._width,this._height),e.layers&&e.layerOrder){const s=new i_("application"),i={};for(const r in e.layers){const a=e.layers[r];a.id=parseInt(r,10),a.enabled=a.id!==ks,i[r]=new Kt(a)}for(let r=0,a=e.layerOrder.length;r<a;r++){const n=e.layerOrder[r],o=i[n.layer];o&&(n.transparent?s.pushTransparent(o):s.pushOpaque(o),s.subLayerEnabled[r]=n.enabled)}this.scene.layers=s}if(e.batchGroups){const s=this.batcher;if(s)for(let i=0,r=e.batchGroups.length;i<r;i++){const a=e.batchGroups[i];s.addGroup(a.name,a.dynamic,a.maxAabbSize,a.id,a.layers)}}e.i18nAssets&&(this.i18n.assets=e.i18nAssets),this._loadLibraries(e.libraries,t)}_loadLibraries(e,t){const s=e.length;let i=s;const r=/^https?:\/\//;if(s){const a=(n,o)=>{i--,n?t(n):i===0&&(this.onLibrariesLoaded(),t(null))};for(let n=0;n<s;++n){let o=e[n];!r.test(o.toLowerCase())&&this._scriptPrefix&&(o=ve.join(this._scriptPrefix,o)),this.loader.load(o,"script",a)}}else this.onLibrariesLoaded(),t(null)}_parseScenes(e){if(e)for(let t=0;t<e.length;t++)this.scenes.add(e[t].name,e[t].url)}_parseAssets(e){const t=[],s={},i={};for(let r=0;r<this.scriptsOrder.length;r++){const a=this.scriptsOrder[r];e[a]&&(s[a]=!0,t.push(e[a]))}if(this.enableBundles)for(const r in e)e[r].type==="bundle"&&(i[r]=!0,t.push(e[r]));for(const r in e)s[r]||i[r]||t.push(e[r]);for(let r=0;r<t.length;
11681r++){const a=t[r],n=new pe(a.name,a.type,a.file,a.data);if(n.id=parseInt(a.id,10),n.preload=a.preload?a.preload:!1,n.loaded=a.type==="script"&&a.data&&a.data.loadingType>0,n.tags.add(a.tags),a.i18n)for(const o in a.i18n)n.addLocalizedAssetId(o,a.i18n[o]);this.assets.add(n)}}start(){this.frame=0,this.fire("start",{timestamp:Gt(),target:this}),this._librariesLoaded||this.onLibrariesLoaded(),this.systems.fire("initialize",this.root),this.fire("initialize"),this.systems.fire("postInitialize",this.root),this.systems.fire("postPostInitialize",this.root),this.fire("postinitialize"),this.requestAnimationFrame()}requestAnimationFrame(){this.xr?.session?this.frameRequestId=this.xr.session.requestAnimationFrame(this.tick):this.frameRequestId=Ce.browser||Ce.worker?requestAnimationFrame(this.tick):null}inputUpdate(e){this.mouse&&this.mouse.update(),this.keyboard&&this.keyboard.update(),this.gamepads&&this.gamepads.update()}update(e){this.frame++,this.graphicsDevice.update(),this.stats.frame.scriptUpdateStart=Gt(),this.systems.fire(this._inTools?"toolsUpdate":"update",e),this.stats.frame.scriptUpdate=Gt()-this.stats.frame.scriptUpdateStart,this.stats.frame.animUpdateStart=Gt(),this.systems.fire("animationUpdate",e),this.stats.frame.animUpdate=Gt()-this.stats.frame.animUpdateStart,this.stats.frame.scriptPostUpdateStart=Gt(),this.systems.fire("postUpdate",e),this.stats.frame.scriptPostUpdate=Gt()-this.stats.frame.scriptPostUpdateStart,this.fire("update",e),this.inputUpdate(e)}render(){this.updateCanvasSize(),this.graphicsDevice.frameStart(),this.fire("prerender"),this.root.syncHierarchy(),this._batcher&&this._batcher.updateAll(),this.renderComposition(this.scene.layers),this.fire("postrender"),this.stats.frame.renderTime=Gt()-this.stats.frame.renderStart,this.graphicsDevice.frameEnd()}renderComposition(e){this.renderer.update(e),this.renderer.buildFrameGraph(this.frameGraph,e),this.frameGraph.render(this.graphicsDevice)}setCanvasFillMode(e,t,s){this._fillMode=e,this.resizeCanvas(t,s)}setCanvasResolution(e,t,s){this._resolutionMode=e,e===n_&&t===void 0&&(t=this.graphicsDevice.canvas.clientWidth,s=this.graphicsDevice.canvas.clientHeight),this.graphicsDevice.resizeCanvas(t,s)}isHidden(){return document.hidden}onVisibilityChange(){this.isHidden()?this._soundManager&&this._soundManager.suspend():this._soundManager&&this._soundManager.resume()}resizeCanvas(e,t){if(!this._allowResize||this.xr&&this.xr.session)return;const s=window.innerWidth,i=window.innerHeight;if(this._fillMode===by){const r=this.graphicsDevice.canvas.width/this.graphicsDevice.canvas.height,a=s/i;r>a?(e=s,t=e/r):(t=i,e=t*r)}else this._fillMode===PR&&(e=s,t=i);return this.graphicsDevice.canvas.style.width=`${e}px`,this.graphicsDevice.canvas.style.height=`${t}px`,this.updateCanvasSize(),{width:e,height:t}}updateCanvasSize(){if(!(!this._allowResize||this.xr?.active)&&this._resolutionMode===n_){const e=this.graphicsDevice.canvas;this.graphicsDevice.resizeCanvas(e.clientWidth,e.clientHeight)}}onLibrariesLoaded(){this._librariesLoaded=!0,this.systems.rigidbody&&this.systems.rigidbody.onLibraryLoaded()}applySceneSettings(e){let t;if(this.systems.rigidbody&&typeof Ammo<"u"){const[s,i,r]=e.physics.gravity;this.systems.rigidbody.gravity.set(s,i,r)}this.scene.applySettings(e),e.render.hasOwnProperty("skybox")&&(e.render.skybox?(t=this.assets.get(e.render.skybox),t?this.setSkybox(t):this.assets.once(`add:${e.render.skybox}`,this.setSkybox,this)):this.setSkybox(null))}setAreaLightLuts(e,t){e&&t&&Ha.set(this.graphicsDevice,e,t)}setSkybox(e){if(e!==this._skyboxAsset){const t=()=>{this.setSkybox(null)},s=()=>{this.scene.setSkybox(this._skyboxAsset?this._skyboxAsset.resources:null)};this._skyboxAsset&&(this.assets.off(`load:${this._skyboxAsset.id}`,s,this),this.assets.off(`remove:${this._skyboxAsset.id}`,t,this),this._skyboxAsset.off("change",s,this)),this._skyboxAsset=e,this._skyboxAsset&&(this.assets.on(`load:${this._skyboxAsset.id}`,s,this),this.assets.once(`remove:${this._skyboxAsset.id}`,t,this),this._skyboxAsset.on("change",s,this),this.scene.skyboxMip===0&&!this._skyboxAsset.loadFaces&&(this._skyboxAsset.loadFaces=!0),this.assets.load(this._skyboxAsset)),s()}}_firstBake(){this.lightmapper?.bake(null,this.scene.lightmapMode)}_firstBatch(){this.batcher?.generate()}_processTimestamp(e){return e}drawLine(e,t,s,i,r){this.scene.drawLine(e,t,s,i,r)}drawLines(e,t,s=!0,i=this.scene.defaultDrawLayer){this.scene.drawLines(e,t,s,i)}drawLineArrays(e,t,s=!0,i=this.scene.defaultDrawLayer){this.scene.drawLineArrays(e,t,s,i)}drawWireSphere(e,t,s=Q.WHITE,i=20,r=!0,a=this.scene.defaultDrawLayer){this.scene.immediate.drawWireSphere(e,t,s,i,r,a)}
11681drawWireAlignedBox(e,t,s=Q.WHITE,i=!0,r=this.scene.defaultDrawLayer,a){this.scene.immediate.drawWireAlignedBox(e,t,s,i,r,a)}drawMeshInstance(e,t=this.scene.defaultDrawLayer){this.scene.immediate.drawMesh(null,null,null,e,t)}drawMesh(e,t,s,i=this.scene.defaultDrawLayer){this.scene.immediate.drawMesh(t,s,e,null,i)}drawQuad(e,t,s=this.scene.defaultDrawLayer){this.scene.immediate.drawMesh(t,e,this.scene.immediate.getQuadMesh(),null,s)}drawTexture(e,t,s,i,r,a,n=this.scene.defaultDrawLayer,o=!0){if(o===!1&&!this.graphicsDevice.isWebGPU)return;const c=new Z;c.setTRS(new E(e,t,0),ae.IDENTITY,new E(s,-i,0)),a||(a=new ei,a.cull=Yt,a.setParameter("colorMap",r),a.shaderDesc=o?this.scene.immediate.getTextureShaderDesc(r.encoding):this.scene.immediate.getUnfilterableTextureShaderDesc(),a.update()),this.drawQuad(c,a,n)}drawDepthTexture(e,t,s,i,r=this.scene.defaultDrawLayer){const a=new ei;a.cull=Yt,a.shaderDesc=this.scene.immediate.getDepthTextureShaderDesc(),a.update(),this.drawTexture(e,t,s,i,null,a,r)}destroy(){if(this._inFrameUpdate){this._destroyRequested=!0;return}const e=this.graphicsDevice.canvas.id;this.fire("destroy",this),this.off("librariesloaded"),this._gsplatSortedEvt?.off(),this._gsplatSortedEvt=null,typeof document<"u"&&document.removeEventListener("visibilitychange",this._visibilityChangeHandler,!1),this._visibilityChangeHandler=null,this.root.destroy(),this.root=null,this.mouse&&(this.mouse.off(),this.mouse.detach(),this.mouse=null),this.keyboard&&(this.keyboard.off(),this.keyboard.detach(),this.keyboard=null),this.touch&&(this.touch.off(),this.touch.detach(),this.touch=null),this.elementInput&&(this.elementInput.detach(),this.elementInput=null),this.gamepads&&(this.gamepads.destroy(),this.gamepads=null),this.systems.destroy(),this.scene.layers&&this.scene.layers.destroy(),this.bundles.destroy(),this.bundles=null,this.i18n.destroy(),this.i18n=null,this.loader.getHandler("script")?.clearCache(),this.loader.destroy(),this.loader=null,this.systems=null,this.context=null,this.scripts.destroy(),this.scripts=null,this.scenes.destroy(),this.scenes=null,this.lightmapper?.destroy(),this.lightmapper=null,this._batcher&&(this._batcher.destroy(),this._batcher=null),this._entityIndex={},this.defaultLayerDepth.onDisable=null,this.defaultLayerDepth.onEnable=null,this.defaultLayerDepth=null,this.defaultLayerWorld=null,this.xr?.end(),this.xr?.destroy(),this.renderer.destroy(),this.renderer=null;const s=this.assets.list();for(let i=0;i<s.length;i++)s[i].unload(),s[i].off();this.assets.off(),this.scene.destroy(),this.scene=null,this.graphicsDevice.destroy(),this.graphicsDevice=null,this.off(),this._soundManager?.destroy(),this._soundManager=null,Ts._applications[e]=null,yi()===this&&$p(null),Ts.cancelTick(this)}static cancelTick(e){e.frameRequestId&&(cancelAnimationFrame(e.frameRequestId),e.frameRequestId=void 0)}getEntityFromIndex(e){return this._entityIndex[e]}_registerSceneImmediate(e){this.on("postrender",e.immediate.onPostRender,e.immediate),this._gsplatSortedEvt=e.on("gsplat:sorted",t=>{this.stats.frame.gsplatSort+=t})}}class TB{elementInput;keyboard;mouse;touch;gamepads;scriptPrefix;assetPrefix;scriptsOrder;soundManager;graphicsDevice;lightmapper;batchManager;xr;componentSystems=[];resourceHandlers=[]}const xl=new W_;class Pw{constructor(e,t,s){this.scene=e,this.light=t,this.store(),t.numCascades=1,this.scene.clusteredLightingEnabled&&!s.shadowsEnabled&&(t.castShadows=!1),t.type!==Te&&(t._node.getWorldTransform(),t.getBoundingSphere(xl),this.lightBounds=new Le,this.lightBounds.center.copy(xl.center),this.lightBounds.halfExtents.set(xl.radius,xl.radius,xl.radius))}store(){this.mask=this.light.mask,this.shadowUpdateMode=this.light.shadowUpdateMode,this.enabled=this.light.enabled,this.intensity=this.light.intensity,this.rotation=this.light._node.getLocalRotation().clone(),this.numCascades=this.light.numCascades,this.castShadows=this.light._castShadows}restore(){const e=this.light;e.mask=this.mask,e.shadowUpdateMode=this.shadowUpdateMode,e.enabled=this.enabled,e.intensity=this.intensity,e._node.setLocalRotation(this.rotation),e.numCascades=this.numCascades,e._castShadows=this.castShadows}startBake(){this.light.enabled=!0,this.light._destroyShadowMap(),this.light.beginFrame()}endBake(e){const t=this.light;t.enabled=!1,t.shadowMap&&(t.shadowMap.cached&&e.add(t,t.shadowMap),t.shadowMap=null)}}const $h=new j;class wB extends Pw{constructor(e,t){super(e.scene,t,e.lightingParams)}get numVirtualLights(){return this.light.type===Te?this.light.bakeNumSamples:1}prepareVirtualLight(e,t){const s=this.light;if(s._node.setLocalRotation(this.rotation),e>0){const a=s.bakeArea;Kc.circlePointDeterministic($h,e,t),$h.mulScalar(a*.5),s._node.rotateLocal($h.x,0,$h.y)}s._node.getWorldTransform();const i=2.2,r=Math.pow(this.intensity,i);s.intensity=Math.pow(r/t,1/i)}}const My=new E;class Ry extends Pw{constructor(e){const t=e.scene,s=new lt("AmbientLight");s.addComponent("light",{type:"directional",affectDynamic:!0,affectLightmapped:!1,bake:!0,bakeNumSamples:t.ambientBakeNumSamples,castShadows:!0,normalOffsetBias:.05,shadowBias:.2,shadowDistance:1,shadowResolution:2048,shadowType:Li,color:Q.WHITE,intensity:1,bakeDir:!1}),super(t,s.light.light,e.lightingParams)}get numVirtualLights(){return this.light.bakeNumSamples}prepareVirtualLight(e,t){Kc.spherePointDeterministic(My,e,t,0,this.scene.ambientBakeSpherePart),this.light._node.lookAt(My.mulScalar(-1)),this.light._node.rotateLocal(90,0,0);const s=2.2,i=2*Math.PI*this.scene.ambientBakeSpherePart,r=Math.pow(i,s);this.light.intensity=Math.pow(r/t,1/s)}}class Kh{constructor(e,t=null){this.node=e,this.component=e.render||e.model,t=t||this.component.meshInstances,this.store(
11681),this.meshInstances=t,this.bounds=null,this.renderTargets=[]}store(){this.castShadows=this.component.castShadows}restore(){this.component.castShadows=this.castShadows}}var CB=` 11682float normpdf3(in vec3 v, in float sigma) { 11683 return 0.39894 * exp(-0.5 * dot(v, v) / (sigma * sigma)) / sigma; 11684} 11685vec3 decodeRGBM(vec4 rgbm) { 11686 vec3 color = (8.0 * rgbm.a) * rgbm.rgb; 11687 return color * color; 11688} 11689float saturate(float x) { 11690 return clamp(x, 0.0, 1.0); 11691} 11692vec4 encodeRGBM(vec3 color) { 11693 vec4 encoded; 11694 encoded.rgb = pow(color.rgb, vec3(0.5)); 11695 encoded.rgb *= 1.0 / 8.0; 11696 encoded.a = saturate( max( max( encoded.r, encoded.g ), max( encoded.b, 1.0 / 255.0 ) ) ); 11697 encoded.a = ceil(encoded.a * 255.0) / 255.0; 11698 encoded.rgb /= encoded.a; 11699 return encoded; 11700} 11701vec3 decode(vec4 pixel) { 11702 #if HDR 11703 return pixel.rgb; 11704 #else 11705 return decodeRGBM(pixel); 11706 #endif 11707} 11708bool isUsed(vec4 pixel) { 11709 #if HDR 11710 return any(greaterThan(pixel.rgb, vec3(0.0))); 11711 #else 11712 return pixel.a > 0.0; 11713 #endif 11714} 11715varying vec2 vUv0; 11716uniform sampler2D source; 11717uniform vec2 pixelOffset; 11718uniform vec2 sigmas; 11719uniform float bZnorm; 11720uniform float kernel[{MSIZE}]; 11721void main(void) { 11722 11723 vec4 pixel = texture2DLod(source, vUv0, 0.0); 11724 if (!isUsed(pixel)) { 11725 gl_FragColor = pixel; 11726 return ; 11727 } 11728 float sigma = sigmas.x; 11729 float bSigma = sigmas.y; 11730 vec3 pixelHdr = decode(pixel); 11731 vec3 accumulatedHdr = vec3(0.0); 11732 float accumulatedFactor = 0.000001; 11733 const int kSize = ({MSIZE} - 1) / 2; 11734 for (int i = -kSize; i <= kSize; ++i) { 11735 for (int j = -kSize; j <= kSize; ++j) { 11736 11737 vec2 coord = vUv0 + vec2(float(i), float(j)) * pixelOffset; 11738 vec4 pix = texture2DLod(source, coord, 0.0); 11739 if (isUsed(pix)) { 11740 vec3 hdr = decode(pix); 11741 float factor = kernel[kSize + j] * kernel[kSize + i]; 11742 factor *= normpdf3(hdr - pixelHdr, bSigma) * bZnorm; 11743 accumulatedHdr += factor * hdr; 11744 accumulatedFactor += factor; 11745 } 11746 } 11747 } 11748 vec3 finalHDR = accumulatedHdr / accumulatedFactor; 11749 #if HDR 11750 gl_FragColor = vec4(finalHDR, 1.0); 11751 #else 11752 gl_FragColor = encodeRGBM(finalHDR); 11753 #endif 11754} 11755`,EB=` 11756varying vec2 vUv0; 11757uniform sampler2D source; 11758uniform vec2 pixelOffset; 11759bool isUsed(vec4 pixel) { 11760 #if HDR 11761 return any(greaterThan(pixel.rgb, vec3(0.0))); 11762 #else 11763 return pixel.a > 0.0; 11764 #endif 11765} 11766void main(void) { 11767 vec4 c = texture2DLod(source, vUv0, 0.0); 11768 c = isUsed(c) ? c : texture2DLod(source, vUv0 - pixelOffset, 0.0); 11769 c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(0, -pixelOffset.y), 0.0); 11770 c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(pixelOffset.x, -pixelOffset.y), 0.0); 11771 c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(-pixelOffset.x, 0), 0.0); 11772 c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(pixelOffset.x, 0), 0.0); 11773 c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(-pixelOffset.x, pixelOffset.y), 0.0); 11774 c = isUsed(c) ? c : texture2DLod(source, vUv0 + vec2(0, pixelOffset.y), 0.0); 11775 c = isUsed(c) ? c : texture2DLod(source, vUv0 + pixelOffset, 0.0); 11776 gl_FragColor = c; 11777} 11778`,bB=` 11779fn normpdf3(v: vec3f, sigma: f32) -> f32 { 11780 return 0.39894 * exp(-0.5 * dot(v, v) / (sigma * sigma)) / sigma; 11781} 11782fn decodeRGBM(rgbm: vec4f) -> vec3f { 11783 let color = (8.0 * rgbm.a) * rgbm.rgb; 11784 return color * color; 11785} 11786fn saturate(x: f32) -> f32 { 11787 return clamp(x, 0.0, 1.0); 11788} 11789fn encodeRGBM(color: vec3f) -> vec4f { 11790 var encoded: vec4f; 11791 let rgb_processed = pow(color.rgb, vec3f(0.5)) * (1.0 / 8.0); 11792 encoded = vec4f(rgb_processed, 0.0); 11793 let max_g_b = max( encoded.g, max( encoded.b, 1.0 / 255.0 ) ); 11794 let max_rgb = max( encoded.r, max_g_b ); 11795 encoded.a = clamp(max_rgb, 0.0, 1.0); 11796 encoded.a = ceil(encoded.a * 255.0) / 255.0; 11797 encoded = vec4f(encoded.rgb / encoded.a, encoded.a); 11798 return encoded; 11799} 11800fn decode(pixel: vec4f) -> vec3f { 11801 #if HDR 11802 return pixel.rgb; 11803 #else 11804 return decodeRGBM(pixel); 11805 #endif 11806} 11807fn isUsed(pixel: vec4f) -> bool { 11808 #if HDR 11809 return any(pixel.rgb > vec3f(0.0)); 11810 #else 11811 return pixel.a > 0.0; 11812 #endif 11813} 11814varying vUv0: vec2f; 11815var source: texture_2d<f32>; 11816var sourceSampler: sampler; 11817uniform kernel: array<f32, {MSIZE}>; 11818uniform pixelOffset: vec2f; 11819uniform sigmas: vec2f; 11820uniform bZnorm: f32; 11821@fragment 11822fn fragmentMain(input: FragmentInput) -> FragmentOutput { 11823 var output: FragmentOutput; 11824 let pixel = textureSampleLevel(source, sourceSampler, input.vUv0, 0.0); 11825 if (!isUsed(pixel)) { 11826 output.color = pixel; 11827 return output; 11828 } 11829 let sigma = uniform.sigmas.x; 11830 let bSigma = uniform.sigmas.y; 11831 let pixelHdr = decode(pixel); 11832 var accumulatedHdr = vec3f(0.0); 11833 var accumulatedFactor = 0.000001; 11834 const kSize = ({MSIZE} - 1) / 2; 11835 for (var i: i32 = -kSize; i <= kSize; i = i + 1) { 11836 for (var j: i32 = -kSize; j <= kSize; j = j + 1) { 11837 let coord = input.vUv0 + vec2f(f32(i), f32(j)) * uniform.pixelOffset; 11838 let pix = textureSampleLevel(source, sourceSampler, coord, 0.0); 11839 if (isUsed(pix)) { 11840 let hdr = decode(pix); 11841 var factor = uniform.kernel[u32(kSize + j)].element * uniform.kernel[u32(kSize + i)].element; 11842 factor = factor * normpdf3(hdr - pixelHdr, bSigma) * uniform.bZnorm; 11843 accumulatedHdr = accumulatedHdr + factor * hdr; 11844 accumulatedFactor = accumulatedFactor + factor; 11845 } 11846 } 11847 } 11848 let finalHDR = accumulatedHdr / accumulatedFactor; 11849 #if HDR 11850 output.color = vec4f(finalHDR, 1.0); 11851 #else 11852 output.color = encodeRGBM(finalHDR); 11853 #endif 11854 return output; 11855} 11856`,AB=` 11857varying vUv0: vec2f; 11858var source: texture_2d<f32>; 11859var sourceSampler: sampler; 11860uniform pixelOffset: vec2f; 11861fn isUsed(pixel: vec4f) -> bool { 11862 #ifdef HDR 11863 return any(pixel.rgb > vec3f(0.0)); 11864 #else 11865 return pixel.a > 0.0; 11866 #endif 11867} 11868@fragment 11869fn fragmentMain(input: FragmentInput) -> FragmentOutput { 11870 var c: vec4f = textureSampleLevel(source, sourceSampler, input.vUv0, 0.0); 11871 c = select(textureSampleLevel(source, sourceSampler, input.vUv0 - uniform.pixelOffset, 0.0), c, isUsed(c)); 11872 c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(0.0, -uniform.pixelOffset.y), 0.0), c, isUsed(c)); 11873 c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(uniform.pixelOffset.x, -uniform.pixelOffset.y), 0.0), c, isUsed(c)); 11874 c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(-uniform.pixelOffset.x, 0.0), 0.0), c, isUsed(c)); 11875 c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(uniform.pixelOffset.x, 0.0), 0.0), c, isUsed(c)); 11876 c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(-uniform.pixelOffset.x, uniform.pixelOffset.y), 0.0), c, isUsed(c)); 11877 c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + vec2f(0.0, uniform.pixelOffset.y), 0.0), c, isUsed(c)); 11878 c = select(textureSampleLevel(source, sourceSampler, input.vUv0 + uniform.pixelOffset, 0.0), c, isUsed(c)); 11879 var output: FragmentOutput; 11880 output.color = c; 11881 return output; 11882} 11883`;
11883const Ly=15,PB={glslBilateralDeNoisePS:CB,glslDilatePS:EB},IB={wgslBilateralDeNoisePS:bB,wgslDilatePS:AB};class DB{shaderDilate=[];shaderDenoise=[];constructor(e){this.device=e,be.get(this.device,ze).add(PB),be.get(this.device,de).add(IB),this.constantTexSource=e.scope.resolve("source"),this.constantPixelOffset=e.scope.resolve("pixelOffset"),this.pixelOffset=new Float32Array(2),this.sigmas=null,this.constantSigmas=null,this.kernel=null}setSourceTexture(e){this.constantTexSource.setValue(e)}prepare(e,t){this.pixelOffset[0]=1/e,this.pixelOffset[1]=1/t,this.constantPixelOffset.setValue(this.pixelOffset)}prepareDenoise(e,t,s){const i=s?0:1;if(!this.shaderDenoise[i]){const r=new Map;r.set("{MSIZE}",15),s&&r.set("HDR",""),this.shaderDenoise[i]=Qt.createShader(this.device,{uniqueName:`lmBilateralDeNoise-${s?"hdr":"rgbm"}`,attributes:{vertex_position:Ie},vertexGLSL:be.get(this.device,ze).get("fullscreenQuadVS"),vertexWGSL:be.get(this.device,de).get("fullscreenQuadVS"),fragmentGLSL:be.get(this.device,ze).get("glslBilateralDeNoisePS"),fragmentWGSL:be.get(this.device,de).get("wgslBilateralDeNoisePS"),fragmentDefines:r}),this.sigmas=new Float32Array(2),this.constantSigmas=this.device.scope.resolve("sigmas"),this.constantKernel=this.device.scope.resolve("kernel[0]"),this.bZnorm=this.device.scope.resolve("bZnorm")}this.sigmas[0]=e,this.sigmas[1]=t,this.constantSigmas.setValue(this.sigmas),this.evaluateDenoiseUniforms(e,t)}getDenoise(e){const t=e?0:1;return this.shaderDenoise[t]}getDilate(e,t){const s=t?0:1;if(!this.shaderDilate[s]){const i=t?`#define HDR 11884`:"";this.shaderDilate[s]=Qt.createShader(e,{uniqueName:`lmDilate-${t?"hdr":"rgbm"}`,attributes:{vertex_position:Ie},vertexGLSL:be.get(this.device,ze).get("fullscreenQuadVS"),vertexWGSL:be.get(this.device,de).get("fullscreenQuadVS"),fragmentGLSL:i+be.get(this.device,ze).get("glslDilatePS"),fragmentWGSL:i+be.get(this.device,de).get("wgslDilatePS")})}return this.shaderDilate[s]}evaluateDenoiseUniforms(e,t){function s(n,o){return .39894*Math.exp(-.5*n*n/(o*o))/o}this.kernel=this.kernel||new Float32Array(Ly);const i=this.kernel,r=Math.floor((Ly-1)/2);for(let n=0;n<=r;++n){const o=s(n,e);i[r+n]=o,i[r-n]=o}this.constantKernel.setValue(this.kernel);const a=1/s(0,t);this.bZnorm.setValue(a)}}class MB extends Pr{viewBindGroups=[];constructor(e,t,s,i,r,a){super(e),this.renderer=t,this.camera=s,this.worldClusters=i,this.receivers=r,this.lightArray=a}destroy(){this.viewBindGroups.forEach(e=>{e.defaultUniformBuffer.destroy(),e.destroy()}),this.viewBindGroups.length=0}execute(){const e=this.device,{renderer:t,camera:s,receivers:i,renderTarget:r,worldClusters:a,lightArray:n}=this;e.supportsUniformBuffers&&!t.viewUniformFormat&&t.initViewBindGroupFormat(t.scene.clusteredLightingEnabled),t.renderForwardLayer(s,r,null,void 0,Ko,this.viewBindGroups,{meshInstances:i,splitLights:n,lightClusters:a})}}const RB=2048,LB=0,FB=1,Zh=new E;class OB{constructor(e,t,s,i,r){this.device=e,this.root=t,this.scene=s,this.renderer=i,this.assets=r,this.shadowMapCache=i.shadowMapCache,this._tempSet=new Set,this._initCalled=!1,this.passMaterials=[],this.ambientAOMaterial=null,this.fog="",this.ambientLight=new Q,this.renderTargets=new Map,this.stats={renderPasses:0,lightmapCount:0,totalRenderTime:0,forwardTime:0,fboTime:0,shadowMapTime:0,compileTime:0,shadersLinked:0}}destroy(){qr.decRef(this.blackTex),this.blackTex=null,qr.destroy(),this.device=null,this.root=null,this.scene=null,this.renderer=null,this.assets=null,this.camera?.destroy(),this.camera=null}initBake(e){if(this.bakeHDR=this.scene.lightmapPixelFormat!==Re,!this._initCalled){this._initCalled=!0,this.lightmapFilters=new DB(e),this.constantBakeDir=e.scope.resolve("bakeDir"),this.materials=[],this.blackTex=new ce(this.device,{width:4,height:4,format:Re,type:wr,name:"lightmapBlack"}),qr.incRef(this.blackTex);const t=new cs(this.device);t.clearColor.set(0,0,0,0),t.clearColorBuffer=!0,t.clearDepthBuffer=!1,t.clearStencilBuffer=!1,t.frustumCulling=!1,t.projection=Sn,t.aspectRatio=1,t.node=new He,this.camera=t,this.camera.shaderParams.gammaCorrection=qc,this.camera.shaderParams.toneMapping=bf}if(this.scene.clusteredLightingEnabled){const t=new QT(e.supportsAreaLights,e.maxTextureSize,()=>{});this.lightingParams=t;const s=this.scene.lighting;t.shadowsEnabled=s.shadowsEnabled,t.shadowAtlasResolution=s.shadowAtlasResolution,t.co
11884okiesEnabled=s.cookiesEnabled,t.cookieAtlasResolution=s.cookieAtlasResolution,t.areaLightsEnabled=s.areaLightsEnabled,t.cells=new E(3,3,3),t.maxLightsPerCell=4,this.worldClusters=new t_(e),this.worldClusters.name="ClusterLightmapper",this.shadowLocalClusteredPass=new qT(e,this.renderer.shadowRenderer,this.renderer._shadowRendererLocal)}}finishBake(e){this.materials=[];function t(s){qr.decRef(s.colorBuffer),s.destroy()}this.renderTargets.forEach(s=>{t(s)}),this.renderTargets.clear(),e.forEach(s=>{s.renderTargets.forEach(i=>{t(i)}),s.renderTargets.length=0}),this.ambientAOMaterial=null,this.worldClusters&&(this.worldClusters.destroy(),this.worldClusters=null)}createMaterialForPass(e,t,s){const i=new Es;return i.name=`lmMaterial-pass:${t}-ambient:${s}`,i.setDefine("UV1LAYOUT",""),i.setDefine("LIT_LIGHTMAP_BAKING",""),t===LB?(i.setDefine("LIT_LIGHTMAP_BAKING_COLOR",""),s?i.setDefine("LIT_LIGHTMAP_BAKING_ADD_AMBIENT",""):i.ambient=new Q(0,0,0),this.bakeHDR||i.setDefine("LIGHTMAP_RGBM",""),i.lightMap=this.blackTex):(i.setDefine("LIT_LIGHTMAP_BAKING_DIR",""),i.setDefine("STD_LIGHTMAP_DIR","")),i.cull=Yt,i.forceUv1=!0,i.update(),i}createMaterials(e,t,s){for(let i=0;i<s;i++)this.passMaterials[i]||(this.passMaterials[i]=this.createMaterialForPass(t,i,!1));this.ambientAOMaterial||(this.ambientAOMaterial=this.createMaterialForPass(t,0,!0),this.ambientAOMaterial.onUpdateShader=function(i){return i.litOptions.lightMapWithoutAmbient=!0,i.litOptions.separateAmbient=!0,i})}createTexture(e,t){return new ce(this.device,{width:e,height:e,format:this.scene.lightmapPixelFormat,mipmaps:!1,type:this.bakeHDR?Qs:wr,minFilter:Fe,magFilter:Fe,addressU:ue,addressV:ue,name:t})}collectModels(e,t,s){if(!e.enabled)return;let i;if(e.model?.model&&e.model?.enabled&&(s&&s.push(new Kh(e)),e.model.lightmapped&&t&&(i=e.model.model.meshInstances)),e.render?.enabled&&(s&&s.push(new Kh(e)),e.render.lightmapped&&t&&(i=e.render.meshInstances)),i){let r=!0;for(let a=0;a<i.length;a++)if(!i[a].mesh.vertexBuffer.format.hasUv1){r=!1;break}if(r){const a=[];for(let n=0;n<i.length;n++){const o=i[n].mesh;this._tempSet.has(o)?t.push(new Kh(e,[i[n]])):a.push(i[n]),this._tempSet.add(o)}this._tempSet.clear(),a.length>0&&t.push(new Kh(e,a))}}for(let r=0;r<e._children.length;r++)this.collectModels(e._children[r],t,s)}prepareShadowCasters(e){const t=[];for(let s=0;s<e.length;s++){const i=e[s].component;if(i.castShadows=i.castShadowsLightmap,i.castShadowsLightmap){const r=e[s].meshInstances;for(let a=0;a<r.length;a++)r[a].visibleThisFrame=!0,t.push(r[a])}}return t}updateTransforms(e){for(let t=0;t<e.length;t++){const s=e[t].meshInstances;for(let i=0;i<s.length;i++)s[i].node.getWorldTransform()}}calculateLightmapSize(e){let t;const s=this.scene.lightmapSizeMultiplier||16,i=Zh;let r,a;e.model?(a=e.model.lightmapSizeMultiplier,e.model.asset?(t=this.assets.get(e.model.asset).data,t.area&&(r=t.area)):e.model._area&&(t=e.model,t._area&&(r=t._area))):e.render&&(a=e.render.lightmapSizeMultiplier,e.render.type!=="asset"&&e.render._area&&(t=e.render,t._area&&(r=t._area)));const n={x:1,y:1,z:1,uv:1};r&&(n.x=r.x,n.y=r.y,n.z=r.z,n.uv=r.uv);const o=a||1;n.x*=o,n.y*=o,n.z*=o;const c=e.render||e.model,h=this.computeNodeBounds(c.meshInstances);i.copy(h.halfExtents);let d=n.x*i.y*i.z+n.y*i.x*i.z+n.z*i.x*i.y;return d/=n.uv,d=Math.sqrt(d),Math.min(H.nextPowerOfTwo(d*s),this.scene.lightmapMaxResolution||RB)}setLightmapping(e,t,s,i){for(let r=0;r<e.length;r++){const a=e[r],n=a.meshInstances;for(let o=0;o<n.length;o++){const c=n[o];if(c.setLightmapped(t),t){i&&(c._shaderDefs|=i),c.mask=ur;for(let h=0;h<s;h++){const d=a.renderTargets[h].colorBuffer;d.minFilter=It,d.magFilter=It,c.setRealtimeLightmap(Ne.lightmapParamNames[h],d)}}}}}bake(e,t=bd){const s=this.device,i=Gt();this.scene._updateSkyMesh(),this.stats.renderPasses=0,this.stats.shadowMapTime=0,this.stats.forwardTime=0;const r=s._shaderStats.linked,a=s._renderTargetCreationTime,n=s._shaderStats.compileTime,o=[],c=[];if(e){for(let d=0;d<e.length;d++)this.collectModels(e[d],o,null);this.collectModels(this.root,null,c)}else this.collectModels(this.root,o,c);if(o.length>0){this.renderer.shadowRenderer.frameUpdate();const d=t===bd?2:1;this.setLightmapping(o,!1,d),this.initBake(s),this.bakeInternal(d,o,c);let u=Km;t===bd&&(u|=MT),this.scene.ambientBake&&(u|=RT),this.setLightmapping(o,!0,d,u),this.finishBake(o)}const h=Gt();this.stats.totalRenderTime=h-i,this.stats.shadersLinked=s._shaderStats.linked-r,this.stats.compileTime=s._shaderStats.compileTime-n,this.stats.fboTime=s._renderTargetCreationTime-a,this.stats.lightmapCount=o.length}allocateTextures(e,t){for(let s=0;s<e.length;s++){const i=e[s],r=this.calculateLightmapSize(i.node);for(let a=0;a<t;a++){const n=this.createTexture(r,`lightmapper_lightmap_${s}`);qr.incRef(n),i.renderTargets[a]=new St({colorBuffer:n,depth:!1}
11884)}if(!this.renderTargets.has(r)){const a=this.createTexture(r,`lightmapper_temp_lightmap_${r}`);qr.incRef(a),this.renderTargets.set(r,new St({colorBuffer:a,depth:!1}))}}}prepareLightsToBake(e,t){if(this.scene.ambientBake){const i=new Ry(this);t.push(i)}const s=this.renderer.lights;for(let i=0;i<s.length;i++){const r=s[i],a=new wB(this,r);e.push(a),r.enabled&&(r.mask&fr)!==0&&(r.mask=fr|ur|Js,r.shadowUpdateMode=r.type===Te?LT:ea,t.push(a))}t.sort()}restoreLights(e){for(let t=0;t<e.length;t++)e[t].restore()}setupScene(){this.ambientLight.copy(this.scene.ambientLight),this.scene.ambientBake||this.scene.ambientLight.set(0,0,0),this.renderer.setSceneConstants(),this.device.scope.resolve("ambientBakeOcclusionContrast").setValue(this.scene.ambientBakeOcclusionContrast),this.device.scope.resolve("ambientBakeOcclusionBrightness").setValue(this.scene.ambientBakeOcclusionBrightness)}restoreScene(){this.scene.ambientLight.copy(this.ambientLight)}computeNodeBounds(e){const t=new Le;if(e.length>0){t.copy(e[0].aabb);for(let s=1;s<e.length;s++)t.add(e[s].aabb)}return t}computeNodesBounds(e){for(let t=0;t<e.length;t++){const s=e[t].meshInstances;e[t].bounds=this.computeNodeBounds(s)}}computeBounds(e){const t=new Le;for(let s=0;s<e.length;s++){t.copy(e[0].aabb);for(let i=1;i<e.length;i++)t.add(e[i].aabb)}return t}backupMaterials(e){for(let t=0;t<e.length;t++)this.materials[t]=e[t].material}restoreMaterials(e){for(let t=0;t<e.length;t++)e[t].material=this.materials[t]}lightCameraPrepare(e,t){const s=t.light;let i;return s.type===nt&&(i=s.getRenderData(null,0).shadowCamera,i._node.setPosition(s._node.getPosition()),i._node.setRotation(s._node.getRotation()),i._node.rotateLocal(-90,0,0),i.projection=mi,i.nearClip=s.attenuationEnd/1e3,i.farClip=s.attenuationEnd,i.aspectRatio=1,i.fov=s._outerConeAngle*2,this.renderer.updateCameraFrustum(i)),i}lightCameraPrepareAndCull(e,t,s,i){const r=e.light;let a=!0;if(r.type===Te){Zh.copy(i.center),Zh.y+=i.halfExtents.y,this.camera.node.setPosition(Zh),this.camera.node.setEulerAngles(-90,0,0),this.camera.nearClip=0,this.camera.farClip=i.halfExtents.y*2;const n=Math.max(i.halfExtents.x,i.halfExtents.z);this.camera.orthoHeight=n}else e.lightBounds.intersects(t.bounds)||(a=!1);if(r.type===nt){let n=!1;const o=t.meshInstances;for(let c=0;c<o.length;c++)if(o[c]._isVisible(s)){n=!0;break}n||(a=!1)}return a}setupLightArray(e,t){e[Te].length=0,e[ot].length=0,e[nt].length=0,e[t.type][0]=t,t.visibleThisFrame=!0}renderShadowMap(e,t,s,i){const r=i.light,a=this.scene.clusteredLightingEnabled,n=r.castShadows&&(!a||this.scene.lighting.shadowsEnabled);if(!t&&n)if(!r.shadowMap&&!a&&(r.shadowMap=this.shadowMapCache.get(this.device,r)),r.type===Te)this.renderer._shadowRendererDirectional.cull(r,e,this.camera,s),this.renderer._shadowRendererDirectional.getLightRenderPass(r,this.camera)?.render();else if(this.renderer._shadowRendererLocal.cull(r,e,s),a)this.shadowLocalClusteredPass.update([r]),this.shadowLocalClusteredPass.enabled&&this.shadowLocalClusteredPass.render();else{const o=r.numShadowFaces,c=r._type===nt;for(let h=0;h<o;h++)new YT(this.device,this.renderer.shadowRenderer,r,h,c).render()}return!0}postprocessTextures(e,t,s){const r=this.lightmapFilters.getDilate(e,this.bakeHDR);let a;const n=this.scene.lightmapFilterEnabled;n&&(this.lightmapFilters.prepareDenoise(this.scene.lightmapFilterRange,this.scene.lightmapFilterSmoothness,this.bakeHDR),a=this.lightmapFilters.getDenoise(this.bakeHDR)),e.setBlendState(xt.NOBLEND),e.setDepthState(ds.NODEPTH),e.setStencilState(null,null);for(let o=0;o<t.length;o++){const c=t[o];for(let h=0;h<s;h++){const d=c.renderTargets[h],u=d.colorBuffer,f=this.renderTargets.get(u.width),p=f.colorBuffer;this.lightmapFilters.prepare(u.width,u.height);for(let m=0;m<1;m++)this.lightmapFilters.setSourceTexture(u),cn(e,f,n&&h===0&&m===0?a:r),this.lightmapFilters.setSourceTexture(p),cn(e,d,r)}}}bakeInternal(e,t,s){const i=this.scene,r=i.layers,a=this.device,n=i.clusteredLightingEnabled;this.createMaterials(a,i,e),this.setupScene(),r._update(),this.computeNodesBounds(t),this.allocateTextures(t,e),this.renderer.collectLights(r);const o=[],c=[];this.prepareLightsToBake(o,c),this.updateTransforms(s);const h=this.prepareShadowCasters(s);this.renderer.updateCpuSkinMatrices(h),this.renderer.gpuUpdate(h);const d=this.computeBounds(h);let u,f,p,m;
11884for(u=0;u<t.length;u++)for(p=t[u].meshInstances,f=0;f<p.length;f++)m=p[f],m.setLightmapped(!1),m.mask=fr,m.setRealtimeLightmap(Ne.lightmapParamNames[0],this.blackTex),m.setRealtimeLightmap(Ne.lightmapParamNames[1],this.blackTex);for(f=0;f<c.length;f++)c[f].light.enabled=!1;const _=[[],[],[]];let g,v,x=!1;for(u=0;u<c.length;u++){const y=c[u],S=y instanceof Ry,T=y.light.type===Te;let w=y.numVirtualLights;e>1&&w>1&&y.light.bakeDir&&(w=1);for(let C=0;C<w;C++){w>1&&y.prepareVirtualLight(C,w),y.startBake();let b=!1;const I=this.lightCameraPrepare(a,y);for(v=0;v<t.length;v++){const P=t[v];if(p=P.meshInstances,!this.lightCameraPrepareAndCull(y,P,I,d))continue;this.setupLightArray(_,y.light);const O=T?[]:[y.light];for(n&&this.renderer.lightTextureAtlas.update(O,this.lightingParams),b=this.renderShadowMap(r,b,h,y),n&&this.worldClusters.update(O,this.lightingParams),this.backupMaterials(p),g=0;g<e&&!(g>0&&C>0||S&&g>0);g++){const D=P.renderTargets[g],N=P.renderTargets[g].colorBuffer.width,k=this.renderTargets.get(N),A=k.colorBuffer;g===0?x=i.updateShaders:x&&(i.updateShaders=!0);let M=this.passMaterials[g];for(S&&C+1===w&&g===0&&(M=this.ambientAOMaterial),f=0;f<p.length;f++)p[f].material=M;this.renderer.updateShaders(p),g===FB&&this.constantBakeDir.setValue(y.light.bakeDir?1:0);const R=new MB(a,this.renderer,this.camera,n?this.worldClusters:null,p,_);for(R.init(k),R.colorOps.clear=!0,R.colorOps.clearValue.copy(this.camera.clearColor),R.render(),R.destroy(),P.renderTargets[g]=k,this.renderTargets.set(N,D),f=0;f<p.length;f++)m=p[f],m.setRealtimeLightmap(Ne.lightmapParamNames[g],A),m._shaderDefs|=Km}this.restoreMaterials(p)}y.endBake(this.shadowMapCache)}}for(this.postprocessTextures(a,t,e),v=0;v<s.length;v++)s[v].restore();this.restoreLights(o),this.restoreScene(),n||this.shadowMapCache.clear()}}class ye extends ge{static order=0;system;entity;constructor(e,t){super(),this.system=e,this.entity=t,this.system.schema&&!this._accessorsBuilt&&this.buildAccessors(this.system.schema),this.on("set",function(s,i,r){this.fire(`set_${s}`,s,i,r)}),this.on("set_enabled",this.onSetEnabled,this)}static _buildAccessors(e,t){t.forEach(s=>{const i=typeof s=="object"?s.name:s;Object.defineProperty(e,i,{get:function(){return this.data[i]},set:function(r){const a=this.data,n=a[i];a[i]=r,this.fire("set",i,n,r)},configurable:!0})}),e._accessorsBuilt=!0}buildAccessors(e){ye._buildAccessors(this,e)}onSetEnabled(e,t,s){t!==s&&this.entity.enabled&&(s?this.onEnable():this.onDisable())}onEnable(){}onDisable(){}onPostStateChange(){}get data(){const e=this.system.store[this.entity.guid];return e?e.data:null}set enabled(e){}get enabled(){return!0}}class Tt extends ge{id;constructor(e){super(),this.app=e,this.store={},this.schema=[]}addComponent(e,t={}){const s=new this.ComponentType(this,e),i=new this.DataType;return this.store[e.guid]={entity:e,data:i},e[this.id]=s,e.c[this.id]=s,this.initializeComponentData(s,t,[]),this.fire("add",e,s),s}removeComponent(e){const t=this.id,s=this.store[e.guid],i=e.c[t];i.fire("beforeremove"),this.fire("beforeremove",e,i),delete this.store[e.guid],e[t]=void 0,delete e.c[t],this.fire("remove",e,s.data)}cloneComponent(e,t){const s=this.store[e.guid];return this.addComponent(t,s.data)}initializeComponentData(e,t={},s){for(let i=0,r=s.length;i<r;i++){const a=s[i];let n,o;typeof a=="object"?(n=a.name,o=a.type):(n=a,o=void 0);let c=t[n];c!==void 0?(o!==void 0&&(c=BB(c,o)),e[n]=c):e[n]=e.data[n]}e.enabled&&e.entity.enabled&&e.onEnable()}getPropertiesOfType(e){const t=[];return(this.schema||[]).forEach(i=>{i&&typeof i=="object"&&i.type===e&&t.push(i)}),t}destroy(){this.off()}}function BB(l,e){if(!l)return l;switch(e){case"rgb":return l instanceof Q?l.clone():new Q(l[0],l[1],l[2]);case"rgba":return l instanceof Q?l.clone():new Q(l[0],l[1],l[2],l[3]);case"vec2":return l instanceof j?l.clone():new j(l[0],l[1]);case"vec3":return l instanceof E?l.clone():new E(l[0],l[1],l[2]);case"vec4":return l instanceof ie?l.clone():new ie(l[0],l[1],l[2],l[3]);case"boolean":case"number":case"string":return l;case"entity":return l;default:throw new Error(`Could not convert unhandled type: ${e}`)}}const Iw=0,o_=1,l_=2;class NB{constructor(){this._left=1/0,this._right=-1/0,this._len=0,this._recip=0,this._p0=0,this._p1=0,this._t=0,this._hermite={valid:!1,p0:0,m0:0,p1:0,m1:0}}update(e,t){if(e<this._left||e>=this._right){const s=t.length;if(!s)this._left=-1/0,this._right=1/0,this._len=0,this._recip=0,this._p0=this._p1=0;else if(e<t[0])this._left=-1/0,this._right=t[0],this._len=0,this._recip=0,this._p0=this._p1=0;else if(e>=t[s-1])this._left=t[s-1],this._right=1/0,this._len=0,this._recip=0,this._p0=this._p1=s-1;else{const i=this._findKey(e,t);this._left=t[i],this._right=t[i+1],this._len=this._right-this._left;const r=1/this._len;this._recip=isFinite(r)?r:0,this._p0=i,this._p1=i+1}}this._t=this._recip===0?0:(e-this._left)*this._recip,this._hermite.valid=!1}_findKey(e,t){let s=0;for(;e>=t[s+1];)s++;return s}eval(e,t,s){const i=s._data,r=s._components,a=this._p0*r;if(t===Iw)for(let n=0;n<r;
11884++n)e[n]=i[a+n];else{const n=this._t,o=this._p1*r;switch(t){case o_:for(let c=0;c<r;++c)e[c]=H.lerp(i[a+c],i[o+c],n);break;case l_:{const c=this._hermite;if(!c.valid){const p=n*n,m=n+n,_=1-n,g=_*_;c.valid=!0,c.p0=(1+m)*g,c.m0=n*g,c.p1=p*(3-m),c.m1=p*(n-1)}const h=(this._p0*3+1)*r,d=(this._p0*3+2)*r,u=(this._p1*3+1)*r,f=(this._p1*3+0)*r;for(let p=0;p<r;++p)e[p]=c.p0*i[h+p]+c.m0*i[d+p]*this._len+c.p1*i[u+p]+c.m1*i[f+p]*this._len;break}}}}}class Fy{constructor(e){this._name=`${e.name}Snapshot`,this._time=-1,this._cache=[],this._results=[];for(let i=0;i<e._inputs.length;++i)this._cache[i]=new NB;const t=e._curves,s=e._outputs;for(let i=0;i<t.length;++i){const r=t[i],a=s[r._output],n=[];for(let o=0;o<a._components;++o)n[o]=0;this._results[i]=n}}}class wc{static eventFrame={start:0,end:0,residual:0};constructor(e,t,s,i,r,a){this._name=e.name,this._track=e,this._snapshot=new Fy(e),this._playing=i,this._time=t,this._speed=s,this._loop=r,this._blendWeight=1,this._blendOrder=0,this._eventHandler=a,this.alignCursorToCurrentTime()}set name(e){this._name=e}get name(){return this._name}set track(e){this._track=e,this._snapshot=new Fy(e)}get track(){return this._track}get snapshot(){return this._snapshot}set time(e){this._time=e,this.alignCursorToCurrentTime()}get time(){return this._time}set speed(e){const t=Math.sign(e)!==Math.sign(this._speed);this._speed=e,t&&this.alignCursorToCurrentTime()}get speed(){return this._speed}set loop(e){this._loop=e}get loop(){return this._loop}set blendWeight(e){this._blendWeight=e}get blendWeight(){return this._blendWeight}set blendOrder(e){this._blendOrder=e}get blendOrder(){return this._blendOrder}set eventCursor(e){this._eventCursor=e}get eventCursor(){return this._eventCursor}get eventCursorEnd(){return this.isReverse?0:this._track.events.length-1}get nextEvent(){return this._track.events[this._eventCursor]}get isReverse(){return this._speed<0}nextEventAheadOfTime(e){return this.nextEvent?this.isReverse?this.nextEvent.time<=e:this.nextEvent.time>=e:!1}nextEventBehindTime(e){return this.nextEvent?e===this.track.duration?this.isReverse?this.nextEvent.time>=e:this.nextEvent.time<=e:this.isReverse?this.nextEvent.time>e:this.nextEvent.time<e:!1}resetEventCursor(){this._eventCursor=this.isReverse?this._track.events.length-1:0}moveEventCursor(){this._eventCursor+=this.isReverse?-1:1,this._eventCursor>=this.track.events.length?this._eventCursor=0:this._eventCursor<0&&(this._eventCursor=this.track.events.length-1)}clipFrameTime(e){const t=wc.eventFrame;t.start=0,t.end=e,t.residual=0,this.isReverse?e<0&&(t.start=this.track.duration,t.end=0,t.residual=e+this.track.duration):e>this.track.duration&&(t.start=0,t.end=this.track.duration,t.residual=e-this.track.duration)}alignCursorToCurrentTime(){for(this.resetEventCursor();this.nextEventBehindTime(this._time)&&this._eventCursor!==this.eventCursorEnd;)this.moveEventCursor()}fireNextEvent(){this._eventHandler.fire(this.nextEvent.name,{track:this.track,...this.nextEvent}),this.moveEventCursor()}fireNextEventInFrame(e,t){return this.nextEventAheadOfTime(e)&&this.nextEventBehindTime(t)?(this.fireNextEvent(),!0):!1}activeEventsForFrame(e,t){const s=wc.eventFrame;this.clipFrameTime(t);const i=this.eventCursor;for(;this.fireNextEventInFrame(e,s.end)&&i!==this.eventCursor;);this.loop&&Math.abs(s.residual)>0&&this.activeEventsForFrame(s.start,s.residual)}progressForTime(e){return e*this._speed/this._track.duration}_update(e){if(this._playing){let t=this._time;const s=this._track.duration,i=this._speed,r=this._loop;this._track.events.length>0&&s>0&&this.activeEventsForFrame(t,t+i*e),t+=i*e,i>=0?t>s&&(r?t=t%s||0:(t=this._track.duration,this.pause())):t<0&&(r?t=s+(t%s||0):(t=0,this.pause())),this._time=t}this._time!==this._snapshot._time&&this._track.eval(this._time,this._snapshot)}play(){this._playing=!0,this._time=0}stop(){this._playing=!1,this._time=0}pause(){this._playing=!1}resume(){this._playing=!0}reset(){this._time=0}}const Dw="NONE",kB="PREV_STATE",UB="NEXT_STATE",zB="PREV_STATE_NEXT_STATE",VB="NEXT_STATE_PREV_STATE",GB="GREATER_THAN",HB="LESS_THAN",WB="GREATER_THAN_EQUAL_TO",XB="LESS_THAN_EQUAL_TO",YB="EQUAL_TO",jB="NOT_EQUAL_TO",Oy="INTEGER",By="FLOAT",Ny="BOOLEAN",Dd="TRIGGER",qB="1D",$B="2D_DIRECTIONAL",KB="2D_CARTESIAN",ZB="DIRECT",kl="START",c_="END",Ua="ANY",gu=[kl,c_,Ua],Mw="OVERWRITE",QB="ADDITIVE";class rs{static dot(e,t){const s=e.length;let i=0;for(let r=0;r<s;++r)i+=e[r]*t[r];return i}static normalize(e){let t=rs.dot(e,e);if(t>0){t=1/Math.sqrt(t);const s=e.length;for(let i=0;i<s;++i)e[i]*=t}}static set(e,t,s){const i=e.length;if(s==="quaternion"){let r=rs.dot(t,t);r>0&&(r=1/Math.sqrt(r));for(let a=0;a<i;++a)e[a]=t[a]*r}else for(let r=0;r<i;++r)e[r]=t[r]}static blendVec(e,t,s,i){const r=i?1:1-s,a=e.length;for(let n=0;n<a;++n)e[n]=e[n]*r+t[n]*s}static blendQuat(e,t,s,i){const r=e.length,a=i?1:1-s;rs.dot(e,t)<0&&(s=-s);for(let n=0;n<r;++n)e[n]=e[n]*a+t[n]*s;i||rs.normalize(e)}static blend(e,t,s,i,r){i==="quaternion"?rs.blendQuat(e,t,s,r):rs.blendVec(e,t,s,r)}static stableSort(e,t){const s=e.length;for(let i=0;i<s-1;++i)for(let r=i+1;r<s;++r)if(t(e[r],e[i])){const a=e[i];e[i]=e[r],e[r]=a}}}class Nt{static TYPE_QUAT="quaternion";static TYPE_VEC3="vector3";static q1=new ae;static q2=new ae;static q3=new ae;static quatArr=[0,0,0,1];static vecArr=[0,0,0];static IDENTITY_QUAT_ARR=[0,0,0,1];constructor(e,t){this._component=e,this.mask=new Int8Array(e.layers.length),this.weights=new Float32Array(e.layers.length),this.totalWeight=0,this.counter=0,this.layerCounter=0,this.valueType=t,this.dirty=!0,this.value=t===Nt.TYPE_QUAT?[0,0,0,1]:[0,0,0],this.baseValue=null,this.setter=null}get _normalizeWeights(){return this._component.normalizeWeights}getWeight(e){return this.dirty&&this.updateWeights(),this._normalizeWeights&&this.totalWeight===0||!this.mask[e]?0:this._normalizeWeights?this.weights[e]/this.totalWeight:H.clamp(this.weights[e],0,1)}_layerBlendType(e){return this._component.layers[e].blendType}setMask(e,t){this.mask[e]=t,this._normalizeWeights&&(this._component.layers[e].blendType===Mw&&(this.mask=this.mask.fill(0,0,e)),this.dirty=!0)}updateWeights(){this.totalWeight=0;for(let e=0;e<this.weights.length;e++)this.weights[e]=this._component.layers[e].weight,this.totalWeight+=this.mask[e]*this.weights[e];this.dirty=!1}updateValue(e,t){if(this.counter===0&&(rs.set(this.value,Nt.IDENTITY_QUAT_ARR,this.valueType),this._normalizeWeights||rs.blend(this.value,this.baseValue,1,this.valueType)),!(!this.mask[e]||this.getWeight(e)===0)){if(this._layerBlendType(e)===QB&&!this._normalizeWeights)if(this.valueType===Nt.TYPE_QUAT){const s=Nt.q1.set(this.value[0],this.value[1],this.value[2],this.value[3]),i=Nt.q2.set(this.baseValue[0],this.baseValue[1],this.baseValue[2],this.baseValue[3]),r=Nt.q3.set(t[0],t[1],t[2],t[3]),a=i.invert().mul(r);a.slerp(ae.IDENTITY,a,this.getWeight(e)),s.mul(a),Nt.quatArr[0]=s.x,Nt.quatArr[1]=s.y,Nt.quatArr[2]=s.z,Nt.quatArr[3]=s.w,rs.set(this.value,Nt.quatArr,this.valueType)}else Nt.vecArr[0]=t[0]-this.baseValue[0],Nt.vecArr[1]=t[1]-this.baseValue[1],Nt.vecArr[2]=t[2]-this.baseValue[2],rs.blend(this.value,Nt.vecArr,this.getWeight(e),this.valueType,!0);else rs.blend(this.value,t,this.getWeight(e),this.valueType);this.setter&&this.setter(this.value)}}unbind(){this.setter&&this.setter(this.baseValue)}}class Rw{constructor(e){this._binder=e,this._clips=[],this._inputs=[],this._outputs=[],this._targets={}}get clips(){return this._clips}
11884addClip(e){const t=this._targets,s=this._binder,i=e.track.curves,r=e.snapshot,a=[],n=[];for(let o=0;o<i.length;++o){const h=i[o].paths;for(let d=0;d<h.length;++d){const u=h[d],f=s.resolve(u);let p=t[f&&f.targetPath||null];if(!p&&f){p={target:f,value:[],curves:0,blendCounter:0};for(let m=0;m<p.target.components;++m)p.value.push(0);if(t[f.targetPath]=p,s.animComponent){if(!s.animComponent.targets[f.targetPath]){let m;f.targetPath.substring(f.targetPath.length-13)==="localRotation"?m=Nt.TYPE_QUAT:m=Nt.TYPE_VEC3,s.animComponent.targets[f.targetPath]=new Nt(s.animComponent,m)}s.animComponent.targets[f.targetPath].layerCounter++,s.animComponent.targets[f.targetPath].setMask(s.layerIndex,1)}}p&&(p.curves++,a.push(r._results[o]),n.push(p))}}this._clips.push(e),this._inputs.push(a),this._outputs.push(n)}removeClip(e){const t=this._targets,s=this._binder,i=this._clips,a=i[e].track.curves;for(let n=0;n<a.length;++n){const c=a[n].paths;for(let h=0;h<c.length;++h){const d=c[h],u=this._binder.resolve(d);u&&(u.curves--,u.curves===0&&(s.unresolve(d),delete t[u.targetPath],s.animComponent&&s.animComponent.targets[u.targetPath].layerCounter--))}}i.splice(e,1),this._inputs.splice(e,1),this._outputs.splice(e,1)}removeClips(){for(;this._clips.length>0;)this.removeClip(0)}updateClipTrack(e,t){this._clips.forEach(s=>{s.name.includes(e)&&(s.track=t)}),this.rebind()}findClip(e){const t=this._clips;for(let s=0;s<t.length;++s){const i=t[s];if(i.name===e)return i}return null}rebind(){this._binder.rebind(),this._targets={};const e=[...this.clips];this.removeClips(),e.forEach(t=>{this.addClip(t)})}assignMask(e){return this._binder.assignMask(e)}update(e,t=!0){const s=this._clips,i=s.map((n,o)=>o);rs.stableSort(i,(n,o)=>s[n].blendOrder<s[o].blendOrder);for(let n=0;n<i.length;++n){const o=i[n],c=s[o],h=this._inputs[o],d=this._outputs[o],u=c.blendWeight;if(u>0&&c._update(e),!t)break;let f,p,m;if(u>=1)for(let _=0;_<h.length;++_)f=h[_],p=d[_],m=p.value,rs.set(m,f,p.target.type),p.blendCounter++;else if(u>0)for(let _=0;_<h.length;++_)f=h[_],p=d[_],m=p.value,p.blendCounter===0?rs.set(m,f,p.target.type):rs.blend(m,f,u,p.target.type),p.blendCounter++}const r=this._targets,a=this._binder;for(const n in r)if(r.hasOwnProperty(n)){const o=r[n];if(a.animComponent&&o.target.usesLayerBlending){const c=a.animComponent.targets[n];c.counter===c.layerCounter&&(c.counter=0),c.path||(c.path=n,c.baseValue=o.target.get(),c.setter=o.target.set),c.updateV
11884alue(a.layerIndex,o.value),c.counter++}else o.target.set(o.value);o.blendCounter=0}this._binder.update(e)}}class Lw{constructor(e){this._events=[...e],this._events.sort((t,s)=>t.time-s.time)}get events(){return this._events}}class Dr{static EMPTY=Object.freeze(new Dr("empty",Number.MAX_VALUE,[],[],[]));constructor(e,t,s,i,r,a=new Lw([])){this._name=e,this._duration=t,this._inputs=s,this._outputs=i,this._curves=r,this._animEvents=a}get name(){return this._name}get duration(){return this._duration}get inputs(){return this._inputs}get outputs(){return this._outputs}get curves(){return this._curves}set events(e){this._animEvents=e}get events(){return this._animEvents.events}eval(e,t){t._time=e;const s=this._inputs,i=this._outputs,r=this._curves,a=t._cache,n=t._results;for(let o=0;o<s.length;++o)a[o].update(e,s[o]._data);for(let o=0;o<r.length;++o){const c=r[o],h=i[c._output],d=n[o];a[c._input].eval(d,c._interpolation,h)}}}class po{static joinPath(e,t){t=t||".";const s=function(i){return i.replace(/\\/g,"\\\\").replace(new RegExp(`\\${t}`,"g"),`\\${t}`)};return e.map(s).join(t)}static splitPath(e,t){t=t||".";const s=[];let i="",r=0;for(;r<e.length;){let a=e[r++];a==="\\"&&r<e.length?(a=e[r++],a==="\\"||a===t?i+=a:i+=`\\${a}`):a===t?(s.push(i),i=""):i+=a}return i.length>0&&s.push(i),s}static encode(e,t,s){return`${Array.isArray(e)?e.join("/"):e}/${t}/${Array.isArray(s)?s.join("/"):s}`}resolve(e){return null}unresolve(e){}update(e){}}class h_{constructor(e,t,s,i){e.set?(this._set=e.set,this._get=e.get):this._set=e,this._type=t,this._components=s,this._targetPath=i,this._isTransform=this._targetPath.substring(this._targetPath.length-13)==="localRotation"||this._targetPath.substring(this._targetPath.length-13)==="localPosition"||this._targetPath.substring(this._targetPath.length-10)==="localScale",this._isWeight=this._targetPath.indexOf("weight.")!==-1}get set(){return this._set}get get(){return this._get}get type(){return this._type}get components(){return this._components}get targetPath(){return this._targetPath}get isTransform(){return this._isTransform}get isWeight(){return this._isWeight}get usesLayerBlending(){return this._isTransform||this._isWeight}}class $r{constructor(e){if(this.graph=e,!e)return;this._mask=null;const t={},s=function(r){t[r.name]=r;for(let a=0;a<r.children.length;++a)s(r.children[a])};s(e),this.nodes=t,this.targetCache={};const i=function(r){let a=r;for(;a&&!(a instanceof lt);)a=a.parent;let n;return a&&(a.render?n=a.render.meshInstances:a.model&&(n=a.model.meshInstances)),n};this.nodeCounts={},this.activeNodes=[],this.handlers={localPosition:function(r){const a=r.localPosition,n=function(o){a.set(...o)};return $r.createAnimTarget(n,"vector",3,r,"localPosition")},localRotation:function(r){const a=r.localRotation,n=function(o){a.set(...o)};return $r.createAnimTarget(n,"quaternion",4,r,"localRotation")},localScale:function(r){const a=r.localScale,n=function(o){a.set(...o)};return $r.createAnimTarget(n,"vector",3,r,"localScale")},weight:function(r,a){a.indexOf("name.")===0?a=a.replace("name.",""):a=Number(a);const n=i(r),o=[];if(n)for(let c=0;c<n.length;++c)n[c].node.name===r.name&&n[c].morphInstance&&o.push(n[c].morphInstance);if(o.length>0){const c={set:h=>{for(let d=0;d<o.length;++d)o[d].setWeight(a,h[0])},get:()=>[o[0].getWeight(a)]};return $r.createAnimTarget(c,"number",1,r,`weight.${a}`)}return null},materialTexture:(r,a)=>{const n=i(r);if(n){let o;for(let c=0;c<n.length;++c)if(n[c].node.name===r.name){o=n[c];break}if(o){const c=h=>
11884{const d=this.animComponent.system.app.assets.get(h[0]);d&&d.resource&&d.type==="texture"&&(o.material[a]=d.resource,o.material.update())};return $r.createAnimTarget(c,"vector",1,r,"materialTexture","material")}}return null}}}_isPathInMask=(e,t)=>{const s=this._mask[e];if(s){if(s.children||t&&s.value!==!1)return!0}else return!1;return!1};_isPathActive(e){if(!this._mask)return!0;const t=[e.entityPath[0],this.graph.name];for(let s=0;s<t.length;++s){let i=t[s];if(this._isPathInMask(i,e.entityPath.length===1))return!0;for(let r=1;r<e.entityPath.length;r++)if(i+=`/${e.entityPath[r]}`,this._isPathInMask(i,r===e.entityPath.length-1))return!0}return!1}findNode(e){if(!this._isPathActive(e))return null;let t;return this.graph&&(t=this.graph.findByPath(e.entityPath),t||(t=this.graph.findByPath(e.entityPath.slice(1)))),t||(t=this.nodes[e.entityPath[e.entityPath.length-1]||""]),t}static createAnimTarget(e,t,s,i,r,a){const n=po.encode(i.path,a||"entity",r);return new h_(e,t,s,n)}resolve(e){const t=po.encode(e.entityPath,e.component,e.propertyPath);let s=this.targetCache[t];if(s)return s;const i=this.findNode(e);if(!i)return null;const r=this.handlers[e.propertyPath];return!r||(s=r(i),!s)?null:(this.targetCache[t]=s,this.nodeCounts[i.path]?this.nodeCounts[i.path]++:(this.activeNodes.push(i),this.nodeCounts[i.path]=1),s)}unresolve(e){if(e.component!=="graph")return;const t=this.nodes[e.entityPath[e.entityPath.length-1]||""];if(this.nodeCounts[t.path]--,this.nodeCounts[t.path]===0){const s=this.activeNodes,i=s.indexOf(t.node),r=s.length;i<r-1&&(s[i]=s[r-1]),s.pop()}}update(e){const t=this.activeNodes;for(let s=0;s<t.length;++s)t[s]._dirtifyLocal()}assignMask(e){return e!==this._mask?(this._mask=e,!0):!1}}class Fw extends ye{_animations={};_assets=[];_loop=!0;animEvaluator=null;model=null;skeleton=null;fromSkel=null;toSkel=null;animationsIndex={};prevAnim=null;currAnim=null;blend=0;blending=!1;blendSpeed=0;activate=!0;speed=1;set animations(e){this._animations=e,this.onSetAnimations()}get animations(){return this._animations}set assets(e){const t=this._assets;if(t&&t.length){for(let i=0;i<t.length;i++)if(t[i]){const r=this.system.app.assets.get(t[i]);if(r){r.off("change",this.onAssetChanged,this),r.off("remove",this.onAssetRemoved,this);const a=this.animationsIndex[r.id];this.currAnim===a&&this._stopCurrentAnimation(),delete this.animations[a],delete this.animationsIndex[r.id]}}}this._assets=e;const s=e.map(i=>i instanceof pe?i.id:i);this.loadAnimationAssets(s)}get assets(){return this._assets}set currentTime(e){if(this.skeleton&&(this.skeleton.currentTime=e,this.skeleton.addTime(0),this.skeleton.updateGraph()),this.animEvaluator){const t=this.animEvaluator.clips;for(let s=0;s<t.length;++s)t[s].time=e}}get currentTime(){if(this.skeleton)return this.skeleton._time;if(this.animEvaluator){const e=this.animEvaluator.clips;if(e.length>0)return e[e.length-1].time}return 0}get duration(){return this.currAnim?this.animations[this.currAnim].duration:0}set loop(e){if(this._loop=e,this.skeleton&&(this.skeleton.looping=e),this.animEvaluator)for(let t=0;t<this.animEvaluator.clips.length;++t)this.animEvaluator.clips[t].loop=e}get loop(){return this._loop}play(e,t=0){if(!(!this.enabled||!this.entity.enabled)&&this.animations[e]){if(this.prevAnim=this.currAnim,this.currAnim=e,this.model){!this.skeleton&&!this.animEvaluator&&this._createAnimationController();const s=this.animations[this.prevAnim],i=this.animations[this.currAnim];if(this.blending=t>0&&!!this.prevAnim,this.blending&&(this.blend=0,this.blendSpeed=1/t),this.skeleton&&(this.blending?(this.fromSkel.animation=s,this.fromSkel.addTime(this.skeleton._time),this.toSkel.animation=i):this.skeleton.animation=i),this.animEvaluator){const r=this.animEvaluator;if(this.blending)for(;r.clips.length>1;)r.removeClip(0);else this.animEvaluator.removeClips();const a=new wc(this.animations[this.currAnim],0,1,!0,this.loop);a.name=this.currAnim,a.blendWeight=this.blending?0:1,a.reset(),this.animEvaluator.addClip(a)}}this.playing=!0}}getAnimation(e){return this.animations[e]}setModel(e){e!==this.model&&(this._resetAnimationController(),this.model=e,this.animations&&this.currAnim&&this.animations[this.currAnim]&&this.play(this.currAnim))}onSetAnimations(){const e=this.entity.model;if(e){const t=e.model;t&&t!==this.model&&this.setModel(t)}if(!this.currAnim&&this.activate&&this.enabled&&this.entity.enabled){const t=Object.keys(this._animations);t.length>0&&this.play(t[0])}}_resetAnimationController(){this.skeleton=null,this.fromSkel=null,this.toSkel=null,this.animEvaluator=null}_createAnimationController(){const e=this.model,t=this.animations;let s=!1,i=!1;for(const a in t)t.hasOwnProperty(a)&&(t[a].constructor===Dr?i=!0:s=!0);const r=e.getGraph();
11884s?(this.fromSkel=new Up(r),this.toSkel=new Up(r),this.skeleton=new Up(r),this.skeleton.looping=this.loop,this.skeleton.setGraph(r)):i&&(this.animEvaluator=new Rw(new $r(this.entity)))}loadAnimationAssets(e){if(!e||!e.length)return;const t=this.system.app.assets,s=r=>{if(r.resources.length>1)for(let a=0;a<r.resources.length;a++)this.animations[r.resources[a].name]=r.resources[a],this.animationsIndex[r.id]=r.resources[a].name;else this.animations[r.name]=r.resource,this.animationsIndex[r.id]=r.name;this.animations=this.animations},i=r=>{r.off("change",this.onAssetChanged,this),r.on("change",this.onAssetChanged,this),r.off("remove",this.onAssetRemoved,this),r.on("remove",this.onAssetRemoved,this),r.resource?s(r):(r.once("load",s,this),this.enabled&&this.entity.enabled&&t.load(r))};for(let r=0,a=e.length;r<a;r++){const n=t.get(e[r]);n?i(n):t.on(`add:${e[r]}`,i)}}onAssetChanged(e,t,s,i){if(t==="resource"||t==="resources")if(t==="resources"&&s&&s.length===0&&(s=null),s){let r=!1;if(s.length>1){if(i&&i.length>1)for(let a=0;a<i.length;a++)delete this.animations[i[a].name];else delete this.animations[e.name];r=!1;for(let a=0;a<s.length;a++)this.animations[s[a].name]=s[a],!r&&this.currAnim===s[a].name&&this.playing&&this.enabled&&this.entity.enabled&&(r=!0,this.play(s[a].name));r||(this._stopCurrentAnimation(),this.onSetAnimations())}else{if(i&&i.length>1)for(let a=0;a<i.length;a++)delete this.animations[i[a].name];this.animations[e.name]=s[0]||s,r=!1,this.currAnim===e.name&&this.playing&&this.enabled&&this.entity.enabled&&(r=!0,this.play(e.name)),r||(this._stopCurrentAnimation(),this.onSetAnimations())}this.animationsIndex[e.id]=e.name}else{if(i.length>1)for(let r=0;r<i.length;r++)delete this.animations[i[r].name],this.currAnim===i[r].name&&this._stopCurrentAnimation();else delete this.animations[e.name],this.currAnim===e.name&&this._stopCurrentAnimation();delete this.animationsIndex[e.id]}}onAssetRemoved(e){if(e.off("remove",this.onAssetRemoved,this),this.animations){if(e.resources.length>1)for(let t=0;t<e.resources.length;t++)delete this.animations[e.resources[t].name],this.currAnim===e.resources[t].name&&this._stopCurrentAnimation();else delete this.animations[e.name],this.currAnim===e.name&&this._stopCurrentAnimation();delete this.animationsIndex[e.id]}}_stopCurrentAnimation(){if(this.currAnim=null,this.playing=!1,this.skeleton&&(this.skeleton.currentTime=0,this.skeleton.animation=null),this.animEvaluator){for(let e=0;e<this.animEvaluator.clips.length;++e)this.animEvaluator.clips[e].stop();this.animEvaluator.update(0),this.animEvaluator.removeClips()}}onEnable(){super.onEnable();const e=this.assets,t=this.system.app.assets;if(e)for(let s=0,i=e.length;s<i;s++){let r=e[s];r instanceof pe||(r=t.get(r)),r&&!r.resource&&t.load(r)}if(this.activate&&!this.currAnim){const s=Object.keys(this.animations);s.length>0&&this.play(s[0])}}onBeforeRemove(){for(let e=0;e<this.assets.length;e++){let t=this.assets[e];typeof t=="number"&&(t=this.system.app.assets.get(t)),t&&(t.off("change",this.onAssetChanged,this),t.off("remove",this.onAssetRemoved,this))}this.skeleton=null,this.fromSkel=null,this.toSkel=null,this.animEvaluator=null}update(e){if(this.blending&&(this.blend+=e*this.blendSpeed,this.blend>=1&&(this.blend=1)),this.playing){const s=this.skeleton;if(s!==null&&this.model!==null){if(this.blending)s.blend(this.fromSkel,this.toSkel,this.blend);else{const i=e*this.speed;s.addTime(i),this.speed>0&&s._time===s.animation.duration&&!this.loop?this.playing=!1:this.speed<0&&s._time===0&&!this.loop&&(this.playing=!1)}this.blending&&this.blend===1&&(s.animation=this.toSkel.animation),s.updateGraph()}}const t=this.animEvaluator;if(t){for(let s=0;s<t.clips.length;++s){const i=t.clips[s];i.speed=this.speed,this.playing?i.resume():i.pause()}this.blending&&t.clips.length>1&&(t.clips[1].blendWeight=this.blend),t.update(e)}this.blending&&this.blend===1&&(this.blending=!1)}}class JB{enabled=!0}const d_=["enabled"];class eN extends Tt{constructor(e){super(e),this.id="animation",this.ComponentType=Fw,this.DataType=JB,this.schema=d_,this.on("beforeremove",this.onBeforeRemove,this),this.app.systems.on("update",this.onUpdate,this)}initializeComponentData(e,t,s){s=["activate","enabled","loop","speed","assets"];for(const i of s)t.hasOwnProperty(i)&&(e[i]=t[i]);super.initializeComponentData(e,t,d_)}cloneComponent(e,t){this.addComponent(t,{}),t.animation.assets=e.animation.assets.slice(),t.animation.speed=e.animation.speed,t.animation.loop=e.animation.loop,t.animation.activate=e.animation.activate,t.animation.enabled=e.animation.enabled;const s={},i=e.animation.animations;for(const n in i)i.hasOwnProperty(n)&&(s[n]=i[n]);t.animation.animations=s;const r={},a=e.animation.animationsIndex;for(const n in a)a.hasOwnProperty(n)&&(r[n]=a[n]);return t.animation.animationsIndex=r,t.animation}onBeforeRemove(e,t){t.onBeforeRemove()}onUpdate(e){const t=this.store;for(const s in t)if(t.hasOwnProperty(s)){const i=t[s];i.data.enabled&&i.entity.enabled&&i.entity.animation.update(e)}}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this)}}ye._buildAccessors(Fw.prototype,d_);class Cc{constructor(e,t,s,i,r=1){this._state=e,this._parent=t,this._name=s,Array.isArray(i)?(this._point=new j(i[0],i[1]),this._pointLength=this._point.length()):(this._point=i,this._pointLength=i),this._speed=r,this._weightedSpeed=1,this._weight=1,this._animTrack=null}get parent(){return this._parent}get name(){return this._name}get path(){return this._parent?`${this._parent.path}.${this._name}`:this._name}get point(){return this._point}get pointLength(){return this._pointLength}set weight(e){this._weight=e}get weight(){return this._parent?this._parent.weight*this._weight:this._weight}get normalizedWeight(){const e=this._state.totalWeight;return e===0?0:this.weight/e}get speed(){return this._weightedSpeed*this._speed}get absoluteSpeed(){return Math.abs(this._speed)}set weightedSpeed(e){this._weightedSpeed=e}get weightedSpeed(){return this._weightedSpeed}set animTrack(e){this._animTrack=e}get animTrack(){return this._animTrack}}class Qo extends Cc{constructor(e,t,s,i,r,a,n,o,c){super(e,t,s,i),this._parameters=r,this._parameterValues=new Array(r.length),this._children=[],this._findParameter=c,this._syncAnimations=n!==!1,this._pointCache={};for(let h=0;h<a.length;h++){const d=a[h];d.children?this._children.push(o(d.type,e,this,d.name,1,d.parameter?[d.parameter]:d.parameters,d.children,d.syncAnimations,o,c)):this._children.push(new Cc(e,this,d.name,d.point,d.speed))}}get weight(){return this.calculateWeights(),this._parent?this._parent.weight*this._weight:this._weight}get syncAnimations(){return this._syncAnimations}getChild(e){for(let t=0;t<this._children.length;t++)if(this._children[t].name===e)return this._children[t];return null}updateParameterValues(){let e=!0;for(let t=0;t<this._parameterValues.length;t++){const s=this._findParameter(this._parameters[t]).value;this._parameterValues[t]!==s&&(this._parameterValues[t]=s,e=!1)}return e}getNodeWeightedDuration(e){return this._children[e].animTrack.duration/this._children[e].speedMultiplier*this._children[e].weight}getNodeCount(){let e=0;for(let t=0;t<this._children.length;t++)this._children[t].constructor===Qo?e+=this._children[t].getNodeCount():e++;return e}}class tN extends Qo{constructor(e,t,s,i,r,a,n,o,c){a.sort((h,d)=>h.point-d.point),super(e,t,s,i,r,a,n,o,c)}calculateWeights(){if(this.updateParameterValues())return;let e=0;this._children[0].weight=0;for(let t=0;t<this._children.length;t++){const s=this._children[t];if(t!==this._children.length-1){const i=this._children[t+1];if(s.point===i.point)s.weight=.5,i.weight=.5;else if(H.between(this._parameterValues[0],s.point,i.point,!0)){const r=Math.abs(s.point-i.point),a=Math.abs(s.point-this._parameterValues[0]),n=(r-a)/r;s.weight=n,i.weight=1-n}else i.weight=0}this._syncAnimations&&(e+=s.animTrack.duration/s.absoluteSpeed*s.weight)}if(this._syncAnimations)for(let t=0;t<this._children.length;t++){const s=this._children[t];s.weightedSpeed=s.animTrack.duration/s.absoluteSpeed/e}}}class za extends Qo{static _p=new j;static _pip=new j;pointDistanceCache(e,t){const s=`${e}${t}`;return this._pointCache[s]||(this._pointCache[s]=this._children[t].point.clone().sub(this._children[e].point)),this._pointCache[s]}calculateWeights(){if(this.updateParameterValues())return;let e,t;za._p.set(...this._parameterValues),e=0,t=0;for(let s=0;s<this._children.length;s++){const i=this._children[s],r=i.point;za._pip.set(za._p.x,za._p.y).sub(r);let a=Number.MAX_VALUE;for(let n=0;n<this._children.length;n++){if(s===n)continue;const o=this.pointDistanceCache(s,n),c=H.clamp(1-za._pip.dot(o)/o.lengthSq(),0,1);c<a&&(a=c)}i.weight=a,e+=a,this._syncAnimations&&(t+=i.animTrack.duration/i.absoluteSpeed*i.weight)}for(let s=0;s<this._children.length;s++){const i=this._children[s];i.weight=i._weight/e,this._syncAnimations&&(i.weightedSpeed=i.animTrack.duration/i.absoluteSpeed/t)}}}class Va extends Qo{static _p=new j;static _pip=new j;pointCache(e,t){const s=`${e}${t}`;return this._pointCache[s]||(this._pointCache[s]=new j((this._children[t].pointLength-this._children[e].pointLength)/((this._children[t].pointLength+this._children[e].pointLength)/2),j.angleRad(this._children[e].point,this._children[t].point)*2)),this._pointCache[s]}calculateWeights(){if(this.updateParameterValues())return;let e,t;Va._p.set(...this._parameterValues);const s=Va._p.length();e=0,t=0;for(let i=0;i<this._children.length;i++){const r=this._children[i],a=r.point,n=r.pointLength;let o=Number.MAX_VALUE;for(let c=0;c<this._children.length;c++){if(i===c)continue;
11884const h=this.pointCache(i,c),d=this._children[c].pointLength;Va._pip.set((s-n)/((d+n)/2),j.angleRad(a,Va._p)*2);const u=H.clamp(1-Math.abs(Va._pip.dot(h)/h.lengthSq()),0,1);u<o&&(o=u)}r.weight=o,e+=o,this._syncAnimations&&(t+=r.animTrack.duration/r.absoluteSpeed*r.weight)}for(let i=0;i<this._children.length;i++){const r=this._children[i];if(r.weight=r._weight/e,this._syncAnimations){const a=r.animTrack.duration/t*e;r.weightedSpeed=r.absoluteSpeed*a}}}}class sN extends Qo{calculateWeights(){if(this.updateParameterValues())return;let e=0,t=0;for(let s=0;s<this._children.length;s++)if(e+=Math.max(this._parameterValues[s],0),this._syncAnimations){const i=this._children[s];t+=i.animTrack.duration/i.absoluteSpeed*i.weight}for(let s=0;s<this._children.length;s++){const i=this._children[s],r=Math.max(this._parameterValues[s],0);e?(i.weight=r/e,this._syncAnimations&&(i.weightedSpeed=i.animTrack.duration/i.absoluteSpeed/t)):(i.weight=0,this._syncAnimations&&(i.weightedSpeed=0))}}}class ky{_animations={};_animationList=[];constructor(e,t,s=1,i=!0,r){this._controller=e,this._name=t,this._speed=s,this._loop=i,this._hasAnimations=!1,r?this._blendTree=this._createTree(r.type,this,null,t,1,r.parameter?[r.parameter]:r.parameters,r.children,r.syncAnimations,this._createTree,this._controller.findParameter):this._blendTree=new Cc(this,null,t,1,s)}_createTree(e,t,s,i,r,a,n,o,c,h){switch(e){case qB:return new tN(t,s,i,r,a,n,o,c,h);case KB:return new za(t,s,i,r,a,n,o,c,h);case $B:return new Va(t,s,i,r,a,n,o,c,h);case ZB:return new sN(t,s,i,r,a,n,o,c,h)}}_getNodeFromPath(e){let t=this._blendTree;for(let s=1;s<e.length;s++)t=t.getChild(e[s]);return t}addAnimation(e,t){const s=e.join("."),i=this._animationList.findIndex(r=>r.path===s);if(i>=0)this._animationList[i].animTrack=t;else{const r=this._getNodeFromPath(e);r.animTrack=t,this._animationList.push(r)}this._updateHasAnimations()}_updateHasAnimations(){this._hasAnimations=this._animationList.length>0&&this._animationList.every(e=>e.animTrack&&e.animTrack!==Dr.EMPTY)}get name(){return this._name}set animations(e){this._animationList=e,this._updateHasAnimations()}get animations(){return this._animationList}get hasAnimations(){return this._hasAnimations}set speed(e){this._speed=e}get speed(){return this._speed}set loop(e){this._loop=e}get loop(){return this._loop}get nodeCount(){return!this._blendTree||this._blendTree.constructor===Cc?1:this._blendTree.getNodeCount()}get playable(){return gu.indexOf(this.name)!==-1||this.animations.length===this.nodeCount}get looping(){if(this.animations.length>0){const e=`${this.name}.${this.animations[0].animTrack.name}`,t=this._controller.animEvaluator.findClip(e);if(t)return t.loop}return!1}get totalWeight(){let e=0;for(let t=0;t<this.animations.length;t++)e+=this.animations[t].weight;return e}get timelineDuration(){let e=0;for(let t=0;t<this.animations.length;t++){const s=this.animations[t];s.animTrack.duration>e&&(e=s.animTrack.duration)}return e}}class vu{constructor({from:e,to:t,time:s=0,priority:i=0,conditions:r=[],exitTime:a=null,transitionOffset:n=null,interruptionSource:o=Dw}){this._from=e,this._to=t,this._time=s,this._priority=i,this._conditions=r,this._exitTime=a,this._transitionOffset=n,this._interruptionSource=o}get from(){return this._from}set to(e){this._to=e}get to(){return this._to}get time(){return this._time}get priority(){return this._priority}get conditions(){return this._conditions}get exitTime(){return this._exitTime}get transitionOffset(){return this._transitionOffset}get interruptionSource(){return this._interruptionSource}get hasExitTime(){return!!this.exitTime}}class iN{_states={};_stateNames=[];_findTransitionsFromStateCache={};_findTransitionsBetweenStatesCache={};_previousStateName=null;_activeStateName=kl;_activeStateDuration=0;_activeStateDurationDirty=!0;_playing=!1;_activate;_transitions;_currTransitionTime=1;_totalTransitionTime=1;_isTransitioning=!1;_transitionInterruptionSource=Dw;_transitionPreviousStates=[];_timeInState=0;_timeInStateBefore=0;constructor(e,t,s,i,r,a,n){this._animEvaluator=e,this._eventHandler=r,this._findParameter=a,this._consumeTrigger=n;for(let o=0;o<t.length;o++)this._states[t[o].name]=new ky(this,t[o].name,t[o].speed,t[o].loop,t[o].blendTree),this._stateNames.push(t[o].name);this._transitions=s.map(o=>new vu({...o})),this._activate=i}get animEvaluator(){return this._animEvaluator}set activeState(e){this._activeStateName=e}get activeState(){return this._findState(this._activeStateName)}get activeStateName(){return this._activeStateName}get activeStateAnimations(){return this.activeState.animations}set previousState(e){this._previousStateName=e}get previousState(){return this._findState(this._previousStateName)}get previousStateName(){return this._previousStateName}get playable(){let e=!0;for(let t=0;t<this._stateNames.length;t++)this._states[this._stateNames[t]].playable||(e=!1);return e}set playing(e){this._playing=e}get playing(){return this._playing}get activeStateProgress(){return this._getActiveStateProgressForTime(this._timeInState)}get activeStateDuration(){if(this._activeStateDurationDirty){let e=0;for(let t=0;t<this.activeStateAnimations.length;t++){const s=this._animEvaluator.findClip(this.activeStateAnimations[t].name);s&&(e=Math.max(e,s.track.duration))}this._activeStateDuration=e,this._activeStateDurationDirty=!1}return this._activeStateDuration}set activeStateCurrentTime(e){this._timeInStateBefore=e,this._timeInState=e;for(let t=0;t<this.activeStateAnimations.length;t++){const s=this.animEvaluator.findClip(this.activeStateAnimations[t].name);s&&(s.time=e)}}get activeStateCurrentTime(){return this._timeInState}get transitioning(){return this._isTransitioning}get transitionProgress(){return this._currTransitionTime/this._totalTransitionTime}get states(){return this._stateNames}assignMask(e){return this._animEvaluator.assignMask(e)}_findState(e){return this._states[e]}_getActiveStateProgressForTime(e){if(this.activeStateName===kl||this.activeStateName===c_||this.activeStateName===Ua)return 1;const t=this._animEvaluator.findClip(this.activeStateAnimations[0].name);return t?t.progressForTime(e):null}_findTransitionsFromState(e){let t=this._findTransitionsFromStateCache[e];return t||(t=this._transitions.filter(s=>s.from===e),vc(t),this._findTransitionsFromStateCache[e]=t),t}_findTransitionsBetweenStates(e,t){let s=this._findTransitionsBetweenStatesCache[`${e}->${t}`];return s||(s=this._transitions.filter(i=>i.from===e&&i.to===t),vc(s),this._findTransitionsBetweenStatesCache[`${e}->${t}`]=s),s}_transitionHasConditionsMet(e){const t=e.conditions;for(let s=0;s<t.length;s++){const i=t[s],r=this._findParameter(i.parameterName);switch(i.predicate){case GB:if(!(r.value>i.value))return!1;break;case HB:if(!(r.value<i.value))return!1;break;case WB:if(!(r.value>=i.value))return!1;break;case XB:if(!(r.value<=i.value))return!1;break;case YB:if(r.value!==i.value)return!1;break;case jB:if(r.value===i.value)return!1;break}}return!0}_findTransition(e,t){let s=[];if(e&&t)s=s.concat(this._findTransitionsBetweenStates(e,t));else if(!this._isTransitioning)s=s.concat(this._findTransitionsFromState(this._activeStateName)),s=s.concat(this._findTransitionsFromState(Ua));else switch(this._transitionInterruptionSource){case kB:s=s.concat(this._findTransitionsFromState(this._previousStateName)),s=s.concat(this._findTransitionsFromState(Ua));break;case UB:s=s.concat(this._findTransitionsFromState(this._activeStateName)),s=s.concat(this._findTransitionsFromState(Ua));break;case zB:s=s.concat(this._findTransitionsFromState(this._previousStateName)),s=s.concat(this._findTransitionsFromState(this._activeStateName)),s=s.concat(this._findTransitionsFromState(Ua));break;case VB:s=s.concat(this._findTransitionsFromState(this._activeStateName)),s=s.concat(this._findTransitionsFromState(this._previousStateName)),s=s.concat(this._findTransitionsFromState(Ua));break}if(s=s.filter(i=>{if(i.to===this.activeStateName)return!1;if(i.hasExitTime){let r=this._getActiveStateProgressForTime(this._timeInStateBefore),a=this._getActiveStateProgressForTime(this._timeInState);if(i.exitTime<1&&this.activeState.loop&&(r-=Math.floor(r),a-=Math.floor(a)),a===r){if(a!==i.exitTime)return null}else if(!(i.exitTime>r&&i.exitTime<=a))return null}return this._transitionHasConditionsMet(i)}),s.length>0){const i=s[0];if(i.to===c_){const r=this._findTransitionsFromState(kl)[0];i.to=r.to}return i}return null}updateStateFromTransition(e){let t,s,i;this.previousState=e.from?this.activeStateName:null,this.activeState=e.to,this._activeStateDurationDirty=!0;for(let c=0;c<e.conditions.length;c++){const h=e.conditions[c];this._findParameter(h.parameterName).type===Dd&&this._consumeTrigger(h.parameterName)}
11884if(this.previousState){this._isTransitioning||(this._transitionPreviousStates=[]),this._transitionPreviousStates.push({name:this._previousStateName,weight:1});const c=Math.min(this._totalTransitionTime!==0?this._currTransitionTime/this._totalTransitionTime:1,1);for(let h=0;h<this._transitionPreviousStates.length;h++){this._isTransitioning?h!==this._transitionPreviousStates.length-1?this._transitionPreviousStates[h].weight*=1-c:this._transitionPreviousStates[h].weight=c:this._transitionPreviousStates[h].weight=1,t=this._findState(this._transitionPreviousStates[h].name);for(let d=0;d<t.animations.length;d++)s=t.animations[d],i=this._animEvaluator.findClip(`${s.name}.previous.${h}`),i||(i=this._animEvaluator.findClip(s.name),i.name=`${s.name}.previous.${h}`),h!==this._transitionPreviousStates.length-1&&i.pause()}}this._isTransitioning=!0,this._totalTransitionTime=e.time,this._currTransitionTime=0,this._transitionInterruptionSource=e.interruptionSource;const r=this.activeState,a=e.transitionOffset&&e.transitionOffset>0&&e.transitionOffset<1;let n=0,o=0;if(a){const c=r.timelineDuration*e.transitionOffset;n=c,o=c}this._timeInState=n,this._timeInStateBefore=o;for(let c=0;c<r.animations.length;c++){if(i=this._animEvaluator.findClip(r.animations[c].name),i)i.reset();else{const h=Number.isFinite(r.animations[c].speed)?r.animations[c].speed:r.speed;i=new wc(r.animations[c].animTrack,this._timeInState,h,!0,r.loop,this._eventHandler),i.name=r.animations[c].name,this._animEvaluator.addClip(i)}if(e.time>0?i.blendWeight=0:i.blendWeight=r.animations[c].normalizedWeight,i.play(),a)i.time=r.timelineDuration*e.transitionOffset;else{const h=r.speed>=0?0:this.activeStateDuration;i.time=h}}}_transitionToState(e){if(!this._findState(e))return;let t=this._findTransition(this._activeStateName,e);t||(this._animEvaluator.removeClips(),t=new vu({from:null,to:e})),this.updateStateFromTransition(t)}assignAnimation(e,t,s,i){const r=e.split(".");let a=this._findState(r[0]);a||(a=new ky(this,r[0],s),this._states[r[0]]=a,this._stateNames.push(r[0])),a.addAnimation(r,t),this._animEvaluator.updateClipTrack(a.name,t),s!==void 0&&(a.speed=s),i!==void 0&&(a.loop=i),!this._playing&&this._activate&&this.playable&&this.play(),this._activeStateDurationDirty=!0}removeNodeAnimations(e){if(gu.indexOf(e)!==-1)return!1;const t=this._findState(e);return t?(t.animations=[],!0):!1}play(e){e&&this._transitionToState(e),this._playing=!0}pause(){this._playing=!1}reset(){this._previousStateName=null,this._activeStateName=kl,this._playing=!1,this._currTransitionTime=1,this._totalTransitionTime=1,this._isTransitioning=!1,this._timeInState=0,this._timeInStateBefore=0,this._animEvaluator.removeClips()}rebind(){this._animEvaluator.rebind()}update(e){if(!this._playing)return;let t,s,i;(this.activeState.loop||this._timeInState<this.activeStateDuration)&&(this._timeInStateBefore=this._timeInState,this._timeInState+=e*this.activeState.speed,!this.activeState.loop&&this._timeInState>this.activeStateDuration&&(this._timeInState=this.activeStateDuration,e=this.activeStateDuration-this._timeInStateBefore));const r=this._findTransition(this._activeStateName);if(r&&this.updateStateFromTransition(r),this._isTransitioning)if(this._currTransitionTime+=e,this._currTransitionTime<=this._totalTransitionTime){const a=this._totalTransitionTime!==0?this._currTransitionTime/this._totalTransitionTime:1;for(let n=0;n<this._transitionPreviousStates.length;n++){t=this._findState(this._transitionPreviousStates[n].name);const o=this._transitionPreviousStates[n].weight;for(let c=0;c<t.animations.length;c++)s=t.animations[c],i=this._animEvaluator.findClip(`${s.name}.previous.${n}`),i&&(i.blendWeight=(1-a)*s.normalizedWeight*o)}t=this.activeState;for(let n=0;n<t.animations.length;n++)s=t.animations[n],this._animEvaluator.findClip(s.name).blendWeight=a*s.normalizedWeight}else{this._isTransitioning=!1;const a=this.activeStateAnimations.length,n=this._animEvaluator.clips.length;for(let o=0;o<n-a;o++)this._animEvaluator.removeClip(0);this._transitionPreviousStates=[],t=this.activeState;for(let o=0;o<t.animations.length;o++)s=t.animations[o],i=this._animEvaluator.findClip(s.name),i&&(i.blendWeight=s.normalizedWeight)}else if(this.activeState._blendTree.constructor!==Cc){t=this.activeState;for(let a=0;a<t.animations.length;a++)s=t.animations[a],i=this._animEvaluator.findClip(s.name),i&&(i.blendWeight=s.normalizedWeight,s.parent.syncAnimations&&(i.speed=s.speed))}this._animEvaluator.update(e,this.activeState.hasAnimations)}findParameter=e=>this._findParameter(e)}const Zp=new j,Qh=new E,Tl=new ie,wl=new Q,Cl=new ae;class nr extends $r{constructor(e,t,s,i,r){super(t),this.animComponent=e,this._mask=i,this.layerName=s,this.layerIndex=r}static _packFloat(e){return e[0]}static _packBoolean(e){return!!e[0]}static _packVec2(e){return Zp.x=e[0],Zp.y=e[1],Zp}static _packVec3(e){return Qh.x=e[0],Qh.y=e[1],Qh.z=e[2],Qh}static _packVec4(e){return Tl.x=e[0],Tl.y=e[1],Tl.z=e[2],Tl.w=e[3],Tl}static _packColor(e){return wl.r=e[0],wl.g=e[1],wl.b=e[2],wl.a=e[3],wl}static _packQuat(e){return Cl.x=e[0],Cl.y=e[1],Cl.z=e[2],Cl.w=e[3],Cl}resolve(e){const t=po.encode(e.entityPath,e.component,e.propertyPath);let s=this.targetCache[t];if(s)return s;let i,r,a;switch(e.component){case"entity":i=this._getEntityFromHierarchy(e.entityPath),a=po.encode(i.path,"entity",e.propertyPath),r=i;break;case"graph":if(r=this.findNode(e),!r)return null;a=po.encode(r.path,"graph",e.propertyPath);break;default:if(i=this._getEntityFromHierarchy(e.entityPath),r=i.findComponent(e.component),!r)return null;a=po.encode(i.path,e.component,e.propertyPath);break}return s=this._createAnimTargetForProperty(r,e.propertyPath,a),this.targetCache[t]=s,s}update(e){const t=this.activeNodes;if(t)for(let s=0;s<t.length;s++)t[s]._dirtifyLocal()}_getEntityFromHierarchy(e){if(!this.animComponent.entity.name===e[0])return null;const t=this.animComponent.entity;return e.length===1?t:t._parent.findByPath(e)}_resolvePath(e,t,s){const i=t.length-(s?0:1);for(let r=0;r<i;r++)e=e[t[r]];return e}_setter(e,t,s){const i=this._resolvePath(e,t),r=t[t.length-1],a=`set${r.substring(0,1).toUpperCase()}${r.substring(1)}`;if(i[a]){let c=i[`get${r.substring(0,1).toUpperCase()}${r.substring(1)}`].bind(i)();c=[c.x,c.y,c.z,c.w];const h=i[a].bind(i);return{set:d=>{h(s(d))},get:()=>c}}const n=i[r];if(typeof n=="object"&&n.hasOwnProperty("copy"))return function(o){n.copy(s(o))};if([j,E,ie,Q,ae].indexOf(i.constructor)!==-1&&t.length>1){const o=t.length>2?this._resolvePath(e,t.slice(0,-1)):e,c=t[t.length-2];return function(h){i[r]=s(h),o[c]=i}}return function(o){i[r]=s(o)}}_createAnimTargetForProperty(e,t,s){if(this.handlers&&t[0].startsWith("weight."))return this.handlers.weight(e,t[0].replace("weight.",""));if(this.handlers&&t[0]==="material"&&t.length===2){const o=t[1];if(o.endsWith("Map"))return this.handlers.materialTexture(e,o)}const i=this._resolvePath(e,t,!0);if(typeof i>"u")return null;let r,a,n;if(typeof i=="number")r=this._setter(e,t,nr._packFloat),a="vector",n=1;else if(typeof i=="boolean")r=this._setter(e,t,nr._packBoolean),a="vector",n=1;else if(typeof i=="object")switch(i.constructor){case j:r=this._setter(e,t,nr._packVec2),a="vector",n=2;break;case E:r=this._setter(e,t,nr._packVec3),a="vector",n=3;break;case ie:r=this._setter(e,t,nr._packVec4),a="vector",n=4;break;case Q:r=this._setter(e,t,nr._packColor),a="vector",n=4;break;case ae:r=this._setter(e,t,nr._packQuat),a="quaternion",n=4;break;default:return null}return t.indexOf("material")!==-1?new h_(o=>
11884{r(o),e.material.update()},a,n,s):new h_(r,a,n,s)}rebind(){this.targetCache={},this.animComponent.rootBone?this.graph=this.animComponent.rootBone:this.graph=this.animComponent.entity;const e={},t=function(s){e[s.name]=s;for(let i=0;i<s.children.length;++i)t(s.children[i])};t(this.graph),this.nodes=e}}class rN{_name;_controller;_component;_weight;_blendType;_mask=null;_blendTime=0;_blendTimeElapsed=0;_startingWeight=0;_targetWeight=0;constructor(e,t,s,i=1,r=Mw){this._name=e,this._controller=t,this._component=s,this._weight=i,this._blendType=r}get name(){return this._name}set playing(e){this._controller.playing=e}get playing(){return this._controller.playing}get playable(){return this._controller.playable}get activeState(){return this._controller.activeStateName}get previousState(){return this._controller.previousStateName}get activeStateProgress(){return this._controller.activeStateProgress}get activeStateDuration(){return this._controller.activeStateDuration}set activeStateCurrentTime(e){const t=this._controller,s=t.playing;t.playing=!0,t.activeStateCurrentTime=e,s||t.update(0),t.playing=s}get activeStateCurrentTime(){return this._controller.activeStateCurrentTime}get transitioning(){return this._controller.transitioning}get transitionProgress(){return this.transitioning?this._controller.transitionProgress:null}get states(){return this._controller.states}set weight(e){this._weight=e,this._component.dirtifyTargets()}get weight(){return this._weight}set blendType(e){e!==this._blendType&&(this._blendType=e,this._controller.normalizeWeights&&this._component.rebind())}get blendType(){return this._blendType}set mask(e){this._controller.assignMask(e)&&this._component.rebind(),this._mask=e}get mask(){return this._mask}play(e){this._controller.play(e)}pause(){this._controller.pause()}reset(){this._controller.reset()}rebind(){this._controller.rebind()}update(e){this._blendTime&&(this._blendTimeElapsed<this._blendTime?(this.weight=H.lerp(this._startingWeight,this._targetWeight,this._blendTimeElapsed/this._blendTime),this._blendTimeElapsed+=e):(this.weight=this._targetWeight,this._blendTime=0,this._blendTimeElapsed=0,this._startingWeight=0,this._targetWeight=0)),this._controller.update(e)}blendToWeight(e,t){this._startingWeight=this.weight,this._targetWeight=e,this._blendTime=Math.max(0,t),this._blendTimeElapsed=0}assignAnimation(e,t,s,i){t instanceof Dr&&(this._controller.assignAnimation(e,t,s,i),this._controller._transitions.length===0&&this._controller._transitions.push(new vu({from:"START",to:e})),this._component.activate&&this._component.playable&&(this._component.playing=!0))}removeNodeAnimations(e){this._controller.removeNodeAnimations(e)&&(this._component.playing=!1)}getAnimationAsset(e){return this._component.animationAssets[`${this.name}:${e}`]}transition(e,t=0,s=null){this._controller.updateStateFromTransition(new vu({from:this._controller.activeStateName,to:e,time:t,transitionOffset:s}))}}class Md{constructor(e){if(this._layers=[],this._parameters={},Array.isArray(e.layers))this._layers=e.layers;else for(const t in e.layers){const s=e.layers[t],i={name:s.name,blendType:s.blendType,weight:s.weight,states:[],transitions:[]};for(let r=0;r<s.states.length;r++)i.states.push(e.states[s.states[r]]);for(let r=0;r<s.transitions.length;r++){const a=e.transitions[s.transitions[r]];if(a.conditions&&!Array.isArray(a.conditions)){const n=Object.keys(a.conditions),o=[];for(let c=0;c<n.length;c++){const h=a.conditions[n[c]];h.parameterName&&o.push(h)}a.conditions=o}Number.isInteger(a.from)&&(a.from=e.states[a.from].name),Number.isInteger(a.to)&&(a.to=e.states[a.to].name),i.transitions.push(a)}this._layers.push(i)}for(const t in e.parameters){const s=e.parameters[t];this._parameters[s.name]={type:s.type,value:s.value}}}get parameters(){return Object.assign({},this._parameters)}get layers(){return this._layers}}class Ow extends ye{_stateGraphAsset=null;_animationAssets={};_speed=1;_activate=!0;_playing=!1;_rootBone=null;_stateGraph=null;_layers=[];_layerIndices={};_parameters={};_targets={};_consumedTriggers=new Set;_normalizeWeights=!1;set stateGraphAsset(e){if(e===null){this.removeStateGraph();return}
11884this._stateGraphAsset&&this.system.app.assets.get(this._stateGraphAsset).off("change",this._onStateGraphAssetChangeEvent,this);let t,s;e instanceof pe?(t=e.id,s=this.system.app.assets.get(t),s||(this.system.app.assets.add(e),s=this.system.app.assets.get(t))):(t=e,s=this.system.app.assets.get(t)),!(!s||this._stateGraphAsset===t)&&(s.resource?(this._stateGraph=s.resource,this.loadStateGraph(this._stateGraph),s.on("change",this._onStateGraphAssetChangeEvent,this)):(s.once("load",i=>{this._stateGraph=i.resource,this.loadStateGraph(this._stateGraph)}),s.on("change",this._onStateGraphAssetChangeEvent,this),this.system.app.assets.load(s)),this._stateGraphAsset=t)}get stateGraphAsset(){return this._stateGraphAsset}set normalizeWeights(e){this._normalizeWeights=e,this.unbind()}get normalizeWeights(){return this._normalizeWeights}set animationAssets(e){this._animationAssets=e,this.loadAnimationAssets()}get animationAssets(){return this._animationAssets}set speed(e){this._speed=e}get speed(){return this._speed}set activate(e){this._activate=e}get activate(){return this._activate}set playing(e){this._playing=e}get playing(){return this._playing}set rootBone(e){if(typeof e=="string"){const t=this.entity.root.findByGuid(e);this._rootBone=t}else e instanceof lt?this._rootBone=e:this._rootBone=null;this.rebind()}get rootBone(){return this._rootBone}set stateGraph(e){this._stateGraph=e}get stateGraph(){return this._stateGraph}get layers(){return this._layers}set layerIndices(e){this._layerIndices=e}get layerIndices(){return this._layerIndices}set parameters(e){this._parameters=e}get parameters(){return this._parameters}set targets(e){this._targets=e}get targets(){return this._targets}get playable(){for(let e=0;e<this._layers.length;e++)if(!this._layers[e].playable)return!1;return!0}get baseLayer(){return this._layers.length>0?this._layers[0]:null}_onStateGraphAssetChangeEvent(e){const t=this.animationAssets,s=this.layers.map(i=>i.mask);this.removeStateGraph(),this._stateGraph=new Md(e._data),this.loadStateGraph(this._stateGraph),this.animationAssets=t,this.loadAnimationAssets(),this.layers.forEach((i,r)=>{i.mask=s[r]}),this.rebind()}dirtifyTargets(){const e=Object.values(this._targets);for(let t=0;t<e.length;t++)e[t].dirty=!0}_addLayer({name:e,states:t,transitions:s,weight:i,mask:r,blendType:a}){let n;this.rootBone?n=this.rootBone:n=this.entity;const o=this._layers.length,c=new nr(this,n,e,r,o),h=new Rw(c),d=new iN(h,t,s,this._activate,this,this.findParameter,this.consumeTrigger);return this._layers.push(new rN(e,d,this,i,a)),this._layerIndices[e]=o,this._layers[o]}addLayer(e,t,s,i){const r=this.findAnimationLayer(e);if(r)return r;const a=[{name:"START",speed:1}],n=[];return this._addLayer({name:e,states:a,transitions:n,weight:t,mask:s,blendType:i})}_assignParameters(e){this._parameters={};const t=Object.keys(e.parameters);for(let s=0;s<t.length;s++){const i=t[s];this._parameters[i]={type:e.parameters[i].type,value:e.parameters[i].value}}}loadStateGraph(e){this._stateGraph=e,this._assignParameters(e),this._layers=[];let t=!1;for(let s=0;s<e.layers.length;s++){const i=e.layers[s];this._addLayer({...i}),i.states.some(r=>r.blendTree)&&(t=!0)}t||this.setupAnimationAssets()}setupAnimationAssets(){for(let e=0;e<this._layers.length;e++){const t=this._layers[e],s=t.name;for(let i=0;i<t.states.length;i++){const r=t.states[i];if(gu.indexOf(r)===-1){const a=`${s}:${r}`;this._animationAssets[a]||(this._animationAssets[a]={asset:null})}}}this.loadAnimationAssets()}loadAnimationAssets(){for(let e=0;e<this._layers.length;e++){const t=this._layers[e];for(let s=0;s<t.states.length;s++){const i=t.states[s];if(gu.indexOf(i)!==-1)continue;const r=this._animationAssets[`${t.name}:${i}`];if(!r||!r.asset){this.findAnimationLayer(t.name).assignAnimation(i,Dr.EMPTY);continue}const a=r.asset,n=this.system.app.assets.get(a);n&&(n.resource?this.onAnimationAssetLoaded(t.name,i,n):(n.once("load",(function(o,c){return(function(h){this.onAnimationAssetLoaded(o,c,h)}).bind(this)}).bind(this)(t.name,i)),this.system.app.assets.load(n)))}}}onAnimationAssetLoaded(e,t,s){this.findAnimationLayer(e).assignAnimation(t,s.resource)}removeStateGraph(){this._stateGraph=null,this._stateGraphAsset=null,this._animationAssets={},this._layers=[],this._layerIndices={},this._parameters={},this._playing=!1,this.unbind(),this._targets={}}reset(){this._assignParameters(this._stateGraph);for(let e=0;e<this._layers.length;e++){const t=this._layers[e].playing;this._layers[e].reset(),this._layers[e].playing=t}}unbind(){this._normalizeWeights||Object.keys(this._targets).forEac
11884h(e=>{this._targets[e].unbind()})}rebind(){this._targets={};for(let e=0;e<this._layers.length;e++)this._layers[e].rebind()}findAnimationLayer(e){const t=this._layerIndices[e];return this._layers[t]||null}addAnimationState(e,t,s=1,i=!0,r="Base"){this._stateGraph||this.loadStateGraph(new Md({layers:[{name:r,states:[{name:"START",speed:1},{name:e,speed:s,loop:i,defaultState:!0}],transitions:[{from:"START",to:e}]}],parameters:{}}));const a=this.findAnimationLayer(r);a?a.assignAnimation(e,t,s,i):this.addLayer(r)?.assignAnimation(e,t,s,i)}assignAnimation(e,t,s,i=1,r=!0){if(!this._stateGraph&&e.indexOf(".")===-1){this.loadStateGraph(new Md({layers:[{name:"Base",states:[{name:"START",speed:1},{name:e,speed:i,loop:r,defaultState:!0}],transitions:[{from:"START",to:e}]}],parameters:{}})),this.baseLayer.assignAnimation(e,t);return}const a=s?this.findAnimationLayer(s):this.baseLayer;a&&a.assignAnimation(e,t,i,r)}removeNodeAnimations(e,t){const s=t?this.findAnimationLayer(t):this.baseLayer;s&&s.removeNodeAnimations(e)}getParameterValue(e,t){const s=this._parameters[e];if(s&&s.type===t)return s.value}setParameterValue(e,t,s){const i=this._parameters[e];if(i&&i.type===t){i.value=s;return}}findParameter=e=>this._parameters[e];consumeTrigger=e=>{this._consumedTriggers.add(e)};getFloat(e){return this.getParameterValue(e,By)}setFloat(e,t){this.setParameterValue(e,By,t)}getInteger(e){return this.getParameterValue(e,Oy)}setInteger(e,t){typeof t=="number"&&t%1===0&&this.setParameterValue(e,Oy,t)}getBoolean(e){return this.getParameterValue(e,Ny)}setBoolean(e,t){this.setParameterValue(e,Ny,!!t)}getTrigger(e){return this.getParameterValue(e,Dd)}setTrigger(e,t=!1){this.setParameterValue(e,Dd,!0),t&&this._consumedTriggers.add(e)}resetTrigger(e){this.setParameterValue(e,Dd,!1)}onBeforeRemove(){Number.isFinite(this._stateGraphAsset)&&this.system.app.assets.get(this._stateGraphAsset).off("change",this._onStateGraphAssetChangeEvent,this)}update(e){for(let t=0;t<this.layers.length;t++)this.layers[t].update(e*this.speed);this._consumedTriggers.forEach(t=>{this.parameters[t].value=!1}),this._consumedTriggers.clear()}resolveDuplicatedEntityReferenceProperties(e,t){e.rootBone&&t[e.rootBone.guid]?this.rootBone=t[e.rootBone.guid]:this.rebind()}}class aN{enabled=!0}const u_=["enabled"];class nN extends Tt{constructor(e){super(e),this.id="anim",this.ComponentType=Ow,this.DataType=aN,this.schema=u_,this.on("beforeremove",this.onBeforeRemove,this),this.app.systems.on("animationUpdate",this.onAnimationUpdate,this)}initializeComponentData(e,t,s){super.initializeComponentData(e,t,u_);const i=["animationAssets","stateGraph","layers","masks"];Object.keys(t).forEach(r=>{i.includes(r)||(e[r]=t[r])}),t.stateGraph&&(e.stateGraph=t.stateGraph,e.loadStateGraph(e.stateGraph)),t.layers&&t.layers.forEach((r,a)=>{r._controller.states.forEach(n=>{r._controller._states[n]._animationList.forEach(o=>{if(!o.animTrack||o.animTrack===Dr.EMPTY){const c=this.app.assets.get(r._component._animationAssets[`${r.name}:${o.name}`].asset);c&&!c.loaded&&c.once("load",()=>{e.layers[a].assignAnimation(o.name,c.resource)})}else e.layers[a].assignAnimation(o.name,o.animTrack)})})}),t.animationAssets&&(e.animationAssets=Object.assign(e.animationAssets,t.animationAssets)),t.masks&&Object.keys(t.masks).forEach(r=>{if(e.layers[r]){const a=t.masks[r].mask,n={};Object.keys(a).forEach(o=>{n[decodeURI(o)]=a[o]}),e.layers[r].mask=n}})}onAnimationUpdate(e){const t=this.store;for(const s in t)if(t.hasOwnProperty(s)){const i=t[s].entity.anim;i.data.enabled&&i.entity.enabled&&i.playing&&i.update(e)}}cloneComponent(e,t){let s;(!e.anim.rootBone||e.anim.rootBone===e)&&(s={},e.anim.layers.forEach((r,a)=>{if(r.mask){const n={};Object.keys(r.mask).forEach(o=>{const c=o.split("/");c.shift();const h=[t.name,...c].join("/");n[h]=r.mask[o]}),s[a]={mask:n}}}));const i={enabled:e.anim.enabled,stateGraphAsset:e.anim.stateGraphAsset,animationAssets:e.anim.animationAssets,speed:e.anim.speed,activate:e.anim.activate,playing:e.anim.playing,rootBone:e.anim.rootBone,stateGraph:e.anim.stateGraph,layers:e.anim.layers,layerIndices:e.anim.layerIndices,parameters:e.anim.parameters,normalizeWeights:e.anim.normalizeWeights,masks:s};return this.addComponent(t,i)}onBeforeRemove(e,t){t.onBeforeRemove()}destroy(){super.destroy(),this.app.systems.off("animationUpdate",this.onAnimationUpdate,this)}}ye._buildAccessors(Ow.prototype,u_);
11884class Bw extends ye{setCurrentListener(){if(this.enabled&&this.entity.audiolistener&&this.entity.enabled){this.system.current=this.entity;const e=this.system.current.getPosition();this.system.manager.listener.setPosition(e)}}onEnable(){this.setCurrentListener()}onDisable(){this.system.current===this.entity&&(this.system.current=null)}}class oN{enabled=!0}const Nw=["enabled"];class lN extends Tt{constructor(e){super(e),this.id="audiolistener",this.ComponentType=Bw,this.DataType=oN,this.schema=Nw,this.manager=e.soundManager,this.current=null,this.app.systems.on("update",this.onUpdate,this)}initializeComponentData(e,t,s){s=["enabled"],super.initializeComponentData(e,t,s)}onUpdate(e){if(this.current){const t=this.current.getPosition();this.manager.listener.setPosition(t);const s=this.current.getWorldTransform();this.manager.listener.setOrientation(s)}}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this)}}ye._buildAccessors(Bw.prototype,Nw);const f_=0,Uy=1,Rd="group",p_="image",kw="text",Ld="stretch",cN="contain",hN="cover",Mt={DEFAULT:"DEFAULT",HOVER:"HOVER",PRESSED:"PRESSED",INACTIVE:"INACTIVE"},Zc={};Zc[Mt.DEFAULT]="_defaultTint";Zc[Mt.HOVER]="hoverTint";Zc[Mt.PRESSED]="pressedTint";Zc[Mt.INACTIVE]="inactiveTint";const Qc={};Qc[Mt.DEFAULT]="_defaultSpriteAsset";Qc[Mt.HOVER]="hoverSpriteAsset";Qc[Mt.PRESSED]="pressedSpriteAsset";Qc[Mt.INACTIVE]="inactiveSpriteAsset";const Jc={};Jc[Mt.DEFAULT]="_defaultSpriteFrame";Jc[Mt.HOVER]="hoverSpriteFrame";Jc[Mt.PRESSED]="pressedSpriteFrame";Jc[Mt.INACTIVE]="inactiveSpriteFrame";class dN extends ye{static EVENT_MOUSEDOWN="mousedown";static EVENT_MOUSEUP="mouseup";static EVENT_MOUSEENTER="mouseenter";static EVENT_MOUSELEAVE="mouseleave";static EVENT_CLICK="click";static EVENT_TOUCHSTART="touchstart";static EVENT_TOUCHEND="touchend";static EVENT_TOUCHCANCEL="touchcancel";static EVENT_TOUCHLEAVE="touchleave";static EVENT_SELECTSTART="selectstart";static EVENT_SELECTEND="selectend";static EVENT_SELECTENTER="selectenter";static EVENT_SELECTLEAVE="selectleave";static EVENT_HOVERSTART="hoverstart";static EVENT_HOVEREND="hoverend";static EVENT_PRESSEDSTART="pressedstart";static EVENT_PRESSEDEND="pressedend";_visualState=Mt.DEFAULT;_isHovering=!1;_hoveringCounter=0;_isPressed=!1;_defaultTint=new Q(1,1,1,1);_defaultSpriteAsset=null;_defaultSpriteFrame=0;_imageEntity=null;_evtElementAdd=null;_evtImageEntityElementAdd=null;_evtImageEntityElementRemove=null;_evtImageEntityElementColor=null;_evtImageEntityElementOpacity=null;_evtImageEntityElementSpriteAsset=null;_evtImageEntityElementSpriteFrame=null;constructor(e,t){super(e,t),this._toggleLifecycleListeners("on",e)}set enabled(e){this._setValue("enabled",e)}get enabled(){return this.data.enabled}set active(e){this._setValue("active",e)}get active(){return this.data.active}set imageEntity(e){if(this._imageEntity!==e){const t=typeof e=="string";if(this._imageEntity&&t&&this._imageEntity.guid===e)return;this._imageEntity&&this._imageEntityUnsubscribe(),e instanceof He?this._imageEntity=e:t?this._imageEntity=this.system.app.getEntityFromIndex(e)||null:this._imageEntity=null,this._imageEntity&&this._imageEntitySubscribe(),this._imageEntity?this.data.imageEntity=this._imageEntity.guid:t&&e&&(this.data.imageEntity=e)}}get imageEntity(){return this._imageEntity}set hitPadding(e){this._setValue("hitPadding",e)}get hitPadding(){return this.data.hitPadding}set transitionMode(e){this._setValue("transitionMode",e)}get transitionMode(){return this.data.transitionMode}set hoverTint(e){this._setValue("hoverTint",e)}get hoverTint(){return this.data.hoverTint}set pressedTint(e){this._setValue("pressedTint",e)}get pressedTint(){return this.data.pressedTint}set inactiveTint(e){this._setValue("inactiveTint",e)}get inactiveTint(){return this.data.inactiveTint}set fadeDuration(e){this._setValue("fadeDuration",e)}get fadeDuration(){return this.data.fadeDuration}set hoverSpriteAsset(e){this._setValue("hoverSpriteAsset",e)}get hoverSpriteAsset(){return this.data.hoverSpriteAsset}set hoverSpriteFrame(e){this._setValue("hoverSpriteFrame",e)}get hoverSpriteFrame(){return this.data.hoverSpriteFrame}set pressedSpriteAsset(e){this._setValue("pressedSpriteAsset",e)}get pressedSpriteAsset(){return this.data.pressedSpriteAsset}set pressedSpriteFrame(e){this._setValue("pressedSpriteFrame",e)}get pressedSpriteFrame(){return this.data.pressedSpriteFrame}set inactiveSpriteAsset(e){this._setValue("inactiveSpriteAsset",e)}get inactiveSpriteAsset(){return this.data.inactiveSpriteAsset}set inactiveSpriteFrame(e){this._setValue("inactiveSpriteFrame",e)}get inactiveSpriteFrame(){return this.data.inactiveSpriteFrame}_setValue(e,t){const s=this.data,i=s[e];s[e]=t,this.fire("set",e,i,t)}_toggleLifecycleListeners(e,t){this[e]("set_active",this._onSetActive,this),this[e]("set_transitionMode",this._onSetTransitionMode,this),this[e]("set_hoverTint",this._onSetTransitionValue,this),this[e]("set_pressedTint",this._onSetTransitionValue,this),this[e]("set_inactiveTint",this._onSetTransitionValue,this),this[e]("set_hoverSpriteAsset",this._onSetTransitionValue,this),this[e]("set_hoverSpriteFrame",this._onSetTransitionValue,this),this[e]("set_pressedSpriteAsset",this._onSetTransitionValue,this),this[e]("set_pressedSpriteFrame",this._onSetTransitionValue,this),this[e]("set_inactiveSpriteAsset",this._onSetTransitionValue,this),this[e]("set_inactiveSpriteFrame",this._onSetTransitionValue,this),e==="on"?this._evtElementAdd=this.entity.on("element:add",this._onElementComponentAdd,this):(this._evtElementAdd?.off(),this._evtElementAdd=null)}_onSetActive(e,t,s){t!==s&&this._updateVisualState()}_onSetTransitionMode(e,t,s){t!==s&&(this._cancelTween(),this._resetToDefaultVisualState(t),this._forceReapplyVisualState())}
11884_onSetTransitionValue(e,t,s){t!==s&&this._forceReapplyVisualState()}_imageEntitySubscribe(){this._evtImageEntityElementAdd=this._imageEntity.on("element:add",this._onImageElementGain,this),this._imageEntity.element&&this._onImageElementGain()}_imageEntityUnsubscribe(){this._evtImageEntityElementAdd?.off(),this._evtImageEntityElementAdd=null,this._imageEntity?.element&&this._onImageElementLose()}_imageEntityElementSubscribe(){const e=this._imageEntity.element;this._evtImageEntityElementRemove=e.once("beforeremove",this._onImageElementLose,this),this._evtImageEntityElementColor=e.on("set:color",this._onSetColor,this),this._evtImageEntityElementOpacity=e.on("set:opacity",this._onSetOpacity,this),this._evtImageEntityElementSpriteAsset=e.on("set:spriteAsset",this._onSetSpriteAsset,this),this._evtImageEntityElementSpriteFrame=e.on("set:spriteFrame",this._onSetSpriteFrame,this)}_imageEntityElementUnsubscribe(){this._evtImageEntityElementRemove?.off(),this._evtImageEntityElementRemove=null,this._evtImageEntityElementColor?.off(),this._evtImageEntityElementColor=null,this._evtImageEntityElementOpacity?.off(),this._evtImageEntityElementOpacity=null,this._evtImageEntityElementSpriteAsset?.off(),this._evtImageEntityElementSpriteAsset=null,this._evtImageEntityElementSpriteFrame?.off(),this._evtImageEntityElementSpriteFrame=null}_onElementComponentRemove(){this._toggleHitElementListeners("off")}_onElementComponentAdd(){this._toggleHitElementListeners("on")}_onImageElementLose(){this._imageEntityElementUnsubscribe(),this._cancelTween(),this._resetToDefaultVisualState(this.transitionMode)}_onImageElementGain(){this._imageEntityElementSubscribe(),this._storeDefaultVisualState(),this._forceReapplyVisualState()}_toggleHitElementListeners(e){if(this.entity.element){const t=e==="on";if(t&&this._hasHitElementListeners)return;this.entity.element[e]("beforeremove",this._onElementComponentRemove,this),this.entity.element[e]("mouseenter",this._onMouseEnter,this),this.entity.element[e]("mouseleave",this._onMouseLeave,this),this.entity.element[e]("mousedown",this._onMouseDown,this),this.entity.element[e]("mouseup",this._onMouseUp,this),this.entity.element[e]("touchstart",this._onTouchStart,this),this.entity.element[e]("touchend",this._onTouchEnd,this),this.entity.element[e]("touchleave",this._onTouchLeave,this),this.entity.element[e]("touchcancel",this._onTouchCancel,this),this.entity.element[e]("selectstart",this._onSelectStart,this),this.entity.element[e]("selectend",this._onSelectEnd,this),this.entity.element[e]("selectenter",this._onSelectEnter,this),this.entity.element[e]("selectleave",this._onSelectLeave,this),this.entity.element[e]("click",this._onClick,this),this._hasHitElementListeners=t}}_storeDefaultVisualState(){const e=this._imageEntity?.element;!e||e.type===Rd||(this._storeDefaultColor(e.color),this._storeDefaultOpacity(e.opacity),this._storeDefaultSpriteAsset(e.spriteAsset),this._storeDefaultSpriteFrame(e.spriteFrame))}_storeDefaultColor(e){this._defaultTint.r=e.r,this._defaultTint.g=e.g,this._defaultTint.b=e.b}_storeDefaultOpacity(e){this._defaultTint.a=e}_storeDefaultSpriteAsset(e){this._defaultSpriteAsset=e}_storeDefaultSpriteFrame(e){this._defaultSpriteFrame=e}_onSetColor(e){this._isApplyingTint||(this._storeDefaultColor(e),this._forceReapplyVisualState())}_onSetOpacity(e){this._isApplyingTint||(this._storeDefaultOpacity(e),this._forceReapplyVisualState())}_onSetSpriteAsset(e){this._isApplyingSprite||(this._storeDefaultSpriteAsset(e),this._forceReapplyVisualState())}_onSetSpriteFrame(e){this._isApplyingSprite||(this._storeDefaultSpriteFrame(e),this._forceReapplyVisualState())}_onMouseEnter(e){this._isHovering=!0,this._updateVisualState(),this._fireIfActive("mouseenter",e)}_onMouseLeave(e){this._isHovering=!1,this._isPressed=!1,this._updateVisualState(),this._fireIfActive("mouseleave",e)}_onMouseDown(e){this._isPressed=!0,this._updateVisualState(),this._fireIfActive("mousedown",e)}_onMouseUp(e){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("mouseup",e)}_onTouchStart(e){this._isPressed=!0,this._updateVisualState(),this._fireIfActive("touchstart",e)}_onTouchEnd(e){e.event.preventDefault(),this._isPressed=!1,this._updateVisualState(),this._fireIfActive("touchend",e)}_onTouchLeave(e){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("touchleave",e)}_onTouchCancel(e){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("touchcancel",e)}_onSelectStart(e){this._isPressed=!0,this._updateVisualState(),this._fireIfActive("selectstart",e)}_onSelectEnd(e){this._isPressed=!1,this._updateVisualState(),this._fireIfActive("selectend",e)}_onSelectEnter(e){this._hoveringCounter++,this._hoveringCounter===1&&(this._isHovering=!0,this._updateVisualState()),this._fireIfActive("selectenter",e)}_onSelectLeave(e){this._hoveringCounter--,this._hoveringCounter===0&&(this._isHovering=!1,this._isPressed=!1,this._updateVisualState()),this._fireIfActive("selectleave",e)}_onClick(e){this._fireIfActive("click",e)}_fireIfActive(e,t){this.data.active&&this.fire(e,t)}_updateVisualState(e){const t=this._visualState,s=this._determineVisualState();if((t!==s||e)&&this.enabled)switch(this._visualState=s,t===Mt.HOVER&&this._fireIfActive("hoverend"),t===Mt.PRESSED&&this._fireIfActive("pressedend"),s===Mt.HOVER&&this._fireIfActive("hoverstart"),s===Mt.PRESSED&&this._fireIfActive("pressedstart"),this.transitionMode){case f_:{const i=Zc[this._visualState],r=this[i];this._applyTint(r);break}case Uy:{const i=Qc[this._visualState],r=Jc[this._visualState],a=this[i],n=this[r];this._applySprite(a,n);break}}}_forceReapplyVisualState(){this._updateVisualState(!0)}_resetToDefaultVisualState(e){if(this._imageEntity?.element)switch(e){case f_:this._cancelTween(),this._applyTintImmediately(this._defaultTint);break;case Uy:this._applySprite(this._defaultSpriteAsset,this._defaultSpriteFrame);break}}_determineVisualState(){if(this.active){if(this._isPressed)return Mt.PRESSED;if(this._isHovering)return Mt.HOVER}else return Mt.INACTIVE;return Mt.DEFAULT}_applySprite(e,t){const s=this._imageEntity?.element;s&&(t=t||0,this._isApplyingSprite=!0,s.spriteAsset!==e&&(s.spriteAsset=e),s.spriteFrame!==t&&(s.spriteFrame=t),this._isApplyingSprite=!1)}_applyTint(e){this._cancelTween(),this.fadeDuration===0?this._applyTintImmediately(e):this._applyTintWithTween(e)}_applyTintImmediately(e){const t=this._imageEntity?.element;if(!e||!t||t.type===Rd)return;const s=zy(e);this._isApplyingTint=!0,s.equals(t.color)||(t.color=s),t.opacity!==e.a&&(t.opacity=e.a),this._isApplyingTint=!1}_applyTintWithTween(e){const t=this._imageEntity?.element;if(!e||!t||t.type===Rd)return;const s=zy(e),i=t.color,r=t.opacity;s.equals(i)&&e.a===r||(this._tweenInfo={startTime:Gt(),from:new Q(i.r,i.g,i.b,r),to:e.clone(),lerpColor:new Q}
11884)}_updateTintTween(){const e=Gt()-this._tweenInfo.startTime;let t=this.fadeDuration===0?1:e/this.fadeDuration;if(t=H.clamp(t,0,1),Math.abs(t-1)>1e-5){const s=this._tweenInfo.lerpColor;s.lerp(this._tweenInfo.from,this._tweenInfo.to,t),this._applyTintImmediately(new Q(s.r,s.g,s.b,s.a))}else this._applyTintImmediately(this._tweenInfo.to),this._cancelTween()}_cancelTween(){delete this._tweenInfo}onUpdate(){this._tweenInfo&&this._updateTintTween()}onEnable(){this._isHovering=!1,this._hoveringCounter=0,this._isPressed=!1,this._toggleHitElementListeners("on"),this._forceReapplyVisualState()}onDisable(){this._toggleHitElementListeners("off"),this._resetToDefaultVisualState(this.transitionMode)}onRemove(){this._imageEntityUnsubscribe(),this._toggleLifecycleListeners("off",this.system),this.onDisable()}resolveDuplicatedEntityReferenceProperties(e,t){e.imageEntity&&(this.imageEntity=t[e.imageEntity.guid])}}function zy(l){return new Q(l.r,l.g,l.b)}class uN{enabled=!0;active=!0;imageEntity=null;hitPadding=new ie;transitionMode=f_;hoverTint=new Q(.75,.75,.75);pressedTint=new Q(.5,.5,.5);inactiveTint=new Q(.25,.25,.25);fadeDuration=0;hoverSpriteAsset=null;hoverSpriteFrame=0;pressedSpriteAsset=null;pressedSpriteFrame=0;inactiveSpriteAsset=null;inactiveSpriteFrame=0}const Vy=["enabled","active",{name:"hitPadding",type:"vec4"},"transitionMode",{name:"hoverTint",type:"rgba"},{name:"pressedTint",type:"rgba"},{name:"inactiveTint",type:"rgba"},"fadeDuration","hoverSpriteAsset","hoverSpriteFrame","pressedSpriteAsset","pressedSpriteFrame","inactiveSpriteAsset","inactiveSpriteFrame"];class fN extends Tt{constructor(e){super(e),this.id="button",this.ComponentType=dN,this.DataType=uN,this.schema=Vy,this.on("beforeremove",this._onRemoveComponent,this),this.app.systems.on("update",this.onUpdate,this)}initializeComponentData(e,t,s){e.imageEntity=t.imageEntity,super.initializeComponentData(e,t,Vy)}onUpdate(e){const t=this.store;for(const s in t){const i=t[s].entity,r=i.button;r.enabled&&i.enabled&&r.onUpdate()}}_onRemoveComponent(e,t){t.onRemove()}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this)}}const Gy=new E,Hy=new ae;class pN extends ye{static EVENT_CONTACT="contact";static EVENT_COLLISIONSTART="collisionstart";static EVENT_COLLISIONEND="collisionend";static EVENT_TRIGGERENTER="triggerenter";static EVENT_TRIGGERLEAVE="triggerleave";_compoundParent=null;_hasOffset=!1;constructor(e,t){super(e,t),this.entity.on("insert",this._onInsert,this),this.on("set_type",this.onSetType,this),this.on("set_convexHull",this.onSetModel,this),this.on("set_halfExtents",this.onSetHalfExtents,this),this.on("set_linearOffset",this.onSetOffset,this),this.on("set_angularOffset",this.onSetOffset,this),this.on("set_radius",this.onSetRadius,this),this.on("set_height",this.onSetHeight,this),this.on("set_axis",this.onSetAxis,this),this.on("set_asset",this.onSetAsset,this),this.on("set_renderAsset",this.onSetRenderAsset,this),this.on("set_model",this.onSetModel,this),this.on("set_render",this.onSetRender,this)}set enabled(e){this._setValue("enabled",e)}get enabled(){return this.data.enabled}set type(e){this._setValue("type",e)}get type(){return this.data.type}set halfExtents(e){this._setValue("halfExtents",e)}get halfExtents(){return this.data.halfExtents}set linearOffset(e){this._setValue("linearOffset",e)}get linearOffset(){return this.data.linearOffset}set angularOffset(e){this._setValue("angularOffset",e)}get angularOffset(){return this.data.angularOffset}set radius(e){this._setValue("radius",e)}get radius(){return this.data.radius}set axis(e){this._setValue("axis",e)}get axis(){return this.data.axis}set height(e){this._setValue("height",e)}get height(){return this.data.height}set asset(e){this._setValue("asset",e)}get asset(){return this.data.asset}set renderAsset(e){this._setValue("renderAsset",e)}get renderAsset(){return this.data.renderAsset}set convexHull(e){this._setValue("convexHull",e)}get convexHull(){return this.data.convexHull}set shape(e){this._setValue("shape",e)}get shape(){return this.data.shape}set model(e){this._setValue("model",e)}get model(){return this.data.model}set render(e){this._setValue("render",e)}get render(){return this.data.render}set checkVertexDuplicates(e){this._setValue("checkVertexDuplicates",e)}get checkVertexDuplicates(){return this.data.checkVertexDuplicates}_setValue(e,t){const s=this.data,i=s[e];s[e]=t,this.fire("set",e,i,t)}onSetType(e,t,s){t!==s&&this.system.changeType(this,t,s)}onSetHalfExtents(e,t,s){const i=this.data.type;this.data.initialized&&i==="box"&&this.system.recreatePhysicalShapes(this)}onSetOffset(e,t,s){this._hasOffset=!this.data.linearOffset.equals(E.ZERO)||!this.data.angularOffset.equals(ae.IDENTITY),this.data.initialized&&this.system.recreatePhysicalShapes(this)}onSetRadius(e,t,s){const i=this.data.type;this.data.initialized&&(i==="sphere"||i==="capsule"||i==="cylinder"||i==="cone")&&this.system.recreatePhysicalShapes(this)}
11884onSetHeight(e,t,s){const i=this.data.type;this.data.initialized&&(i==="capsule"||i==="cylinder"||i==="cone")&&this.system.recreatePhysicalShapes(this)}onSetAxis(e,t,s){const i=this.data.type;this.data.initialized&&(i==="capsule"||i==="cylinder"||i==="cone")&&this.system.recreatePhysicalShapes(this)}onSetAsset(e,t,s){const i=this.system.app.assets;if(t){const r=i.get(t);r&&r.off("remove",this.onAssetRemoved,this)}if(s){s instanceof pe&&(this.data.asset=s.id);const r=i.get(this.data.asset);r&&(r.off("remove",this.onAssetRemoved,this),r.on("remove",this.onAssetRemoved,this))}this.data.initialized&&this.data.type==="mesh"&&(s||(this.data.model=null),this.system.recreatePhysicalShapes(this))}onSetRenderAsset(e,t,s){const i=this.system.app.assets;if(t){const r=i.get(t);r&&r.off("remove",this.onRenderAssetRemoved,this)}if(s){s instanceof pe&&(this.data.renderAsset=s.id);const r=i.get(this.data.renderAsset);r&&(r.off("remove",this.onRenderAssetRemoved,this),r.on("remove",this.onRenderAssetRemoved,this))}this.data.initialized&&this.data.type==="mesh"&&(s||(this.data.render=null),this.system.recreatePhysicalShapes(this))}onSetModel(e,t,s){this.data.initialized&&this.data.type==="mesh"&&this.system.implementations.mesh.doRecreatePhysicalShape(this)}onSetRender(e,t,s){this.onSetModel(e,t,s)}onAssetRemoved(e){e.off("remove",this.onAssetRemoved,this),this.data.asset===e.id&&(this.asset=null)}onRenderAssetRemoved(e){e.off("remove",this.onRenderAssetRemoved,this),this.data.renderAsset===e.id&&(this.renderAsset=null)}getCompoundChildShapeIndex(e){const t=this.data.shape,s=t.getNumChildShapes();for(let i=0;i<s;i++){const r=t.getChildShape(i);if(Ammo.getPointer(r)===Ammo.getPointer(e))return i}return null}_onInsert(e){if(!(typeof Ammo>"u")){if(this._compoundParent)this.system.recreatePhysicalShapes(this);else if(!this.entity.rigidbody){let t=this.entity.parent;for(;t;){if(t.collision&&t.collision.type==="compound"){t.collision.shape.getNumChildShapes()===0?this.system.recreatePhysicalShapes(t.collision):this.system.recreatePhysicalShapes(this);break}t=t.parent}}}}_updateCompound(){const e=this.entity;if(e._dirtyWorld){let t=e._dirtyLocal,s=e;for(;s&&!t&&!(s.collision&&s.collision===this._compoundParent);)s._dirtyLocal&&(t=!0),s=s.parent;if(t){e.forEach(this.system.implementations.compound._updateEachDescendantTransform,e);const i=this._compoundParent.entity.rigidbody;i&&i.activate()}}}getShapePosition(){const e=this.entity.getPosition();if(this._hasOffset){const t=this.entity.getRotation(),s=this.data.linearOffset;return Hy.copy(t).transformVector(s,Gy),Gy.add(e)}return e}getShapeRotation(){const e=this.entity.getRotation();return this._hasOffset?Hy.copy(e).mul(this.data.angularOffset):e}onEnable(){if(this.data.type==="mesh"&&(this.data.asset||this.data.renderAsset)&&this.data.initialized){const e=this.system.app.assets.get(this.data.asset||this.data.renderAsset);if(e&&(!e.resource||!this.data.shape)){this.system.recreatePhysicalShapes(this);return}}if(this.entity.rigidbody)this.entity.rigidbody.enabled&&this.entity.rigidbody.enableSimulation();else if(this._compoundParent&&this!==this._compoundParent)if(this._compoundParent.shape.getNumChildShapes()===0)this.system.recreatePhysicalShapes(this._compoundParent);else{const e=this.system._getNodeTransform(this.entity,this._compoundParent.entity);this._compoundParent.shape.addChildShape(e,this.data.shape),Ammo.destroy(e),this._compoundParent.entity.rigidbody&&this._compoundParent.entity.rigidbody.activate()}else this.entity.trigger&&this.entity.trigger.enable()}onDisable(){this.entity.rigidbody?this.entity.rigidbody.disableSimulation():this._compoundParent&&this!==this._compoundParent?this._compoundParent.entity._destroying||(this.system._removeCompoundChild(this._compoundParent,this.data.shape),this._compoundParent.entity.rigidbody&&this._compoundParent.entity.rigidbody.activate()):this.entity.trigger&&this.entity.trigger.disable()}onBeforeRemove(){this.asset&&(this.asset=null),this.renderAsset&&(this.renderAsset=null),this.entity.off("insert",this._onInsert,this),this.off()}}class mN{enabled=!0;type="box";halfExtents=new E(.5,.5,.5);linearOffset=new E;angularOffset=new ae;radius=.5;axis=1;height=2;convexHull=!1;asset=null;renderAsset=null;checkVertexDuplicates=!0;shape=null;model=null;render=null;initialized=!1}const El="static",li="dynamic",Xn="kinematic",_N=2,Ul=4,m_=1,Wy=4,Uw=5,gN=1,Xy=2,vN=4,Yy=16,jy=65535,__=65533;let ci,Ra,Yn;class zw{constructor(e,t,s){this.entity=t.entity,this.component=t,this.app=e,typeof Ammo<"u"&&!ci&&(ci=new Ammo.btVector3,Ra=new Ammo.btQuaternion,Yn=new Ammo.btTransform),this.initialize(s)}initialize(e){const t=this.entity,s=e.shape;if(s&&typeof Ammo<"u"){t.trigger&&t.trigger.destroy();const i=1,r=this.component;if(r){const n=r.getShapePosition(),o=r.getShapeRotation();ci.setValue(n.x,n.y,n.z),Ra.setValue(o.x,o.y,o.z,o.w)}else{const n=t.getPosition(),o=t.getRotation();ci.setValue(n.x,n.y,n.z),Ra.setValue(o.x,o.y,o.z,o.w)}Yn.setOrigin(ci),Yn.setRotation(Ra);const a=this.app.systems.rigidbody.createBody(i,s,Yn);a.setRestitution(0),a.setFriction(0),a.setDamping(0,0),ci.setValue(0,0,0),a.setLinearFactor(ci),a.setAngularFactor(ci),a.setCollisionFlags(a.getCollisionFlags()|Ul),a.entity=t,this.body=a,this.component.enabled&&t.enabled&&this.enable()}}destroy(){this.body&&(this.disable(),this.app.systems.rigidbody.destroyBody(this.body),this.body=null)}_getEntityTransform(e){const t=this.component;if(t){const s=t.getShapePosition(),i=t.getShapeRotation();ci.setValue(s.x,s.y,s.z),Ra.setValue(i.x,i.y,i.z,i.w)}else{const s=this.entity.getPosition(),i=this.entity.getRotation();ci.setValue(s.x,s.y,s.z),Ra.setValue(i.x,i.y,i.z,i.w)}e.setOrigin(ci),e.setRotation(Ra)}updateTransform(){this._getEntityTransform(Yn);const e=this.body;e.setWorldTransform(Yn),e.activate()}enable(){const e=this.body;if(!e)return;const t=this.app.systems.rigidbody;t._triggers.indexOf(this)<0&&(t.addBody(e,Yy,__^Yy),t._triggers.push(this)),e.forceActivationState(m_),this.updateTransform()}disable(){const e=this.body;if(!e)return;const t=this.app.systems.rigidbody,s=t._triggers.indexOf(this);s>-1&&(t.removeBody(e),t._triggers.splice(s,1)),e.forceActivationState(Uw)}}const Jh=new Z,SN=new E,yN=new E,La=new ae,qy=new He,xN=["enabled","type","halfExtents","linearOffset","angularOffset","radius","axis","height","convexHull","asset","renderAsset","shape","model","render","checkVertexDuplicates"];class xn{constructor(e){this.system=e}beforeInitialize(e,t){t.shape=null,t.model=new pa,t.model.graph=new He}afterInitialize(e,t){this.recreatePhysicalShapes(e),e.data.initialized=!0}reset(e,t){this.beforeInitialize(e,t),this.afterInitialize(e,t)}recreatePhysicalShapes(e){const t=e.entity,s=e.data;if(typeof Ammo<"u"){t.trigger&&(t.trigger.destroy(),delete t.trigger),s.shape&&(e._compoundParent&&(e!==e._compoundParent&&this.system._removeCompoundChild(e._compoundParent,s.shape),e._compoundParent.entity.rigidbody&&e._compoundParent.entity.rigidbody.activate()),this.destroyShape(s)),s.shape=this.createPhysicalShape(e.entity,s);const i=!e._compoundParent;if(s.type==="compound"&&(!e._compoundParent||e===e._compoundParent))e._
11884compoundParent=e,t.forEach(this._addEachDescendant,e);else if(s.type!=="compound"&&!e.rigidbody){e._compoundParent=null;let r=t.parent;for(;r;){if(r.collision&&r.collision.type==="compound"){e._compoundParent=r.collision;break}r=r.parent}}e._compoundParent&&e!==e._compoundParent&&(i&&e._compoundParent.shape.getNumChildShapes()===0?this.system.recreatePhysicalShapes(e._compoundParent):(this.system.updateCompoundChildTransform(t,!0),e._compoundParent.entity.rigidbody&&e._compoundParent.entity.rigidbody.activate())),t.rigidbody?(t.rigidbody.disableSimulation(),t.rigidbody.createBody(),t.enabled&&t.rigidbody.enabled&&t.rigidbody.enableSimulation()):e._compoundParent||(t.trigger?t.trigger.initialize(s):t.trigger=new zw(this.system.app,e,s))}}createPhysicalShape(e,t){}updateTransform(e,t,s,i){e.entity.trigger&&e.entity.trigger.updateTransform()}destroyShape(e){e.shape&&(Ammo.destroy(e.shape),e.shape=null)}beforeRemove(e,t){t.data.shape&&(t._compoundParent&&!t._compoundParent.entity._destroying&&(this.system._removeCompoundChild(t._compoundParent,t.data.shape),t._compoundParent.entity.rigidbody&&t._compoundParent.entity.rigidbody.activate()),t._compoundParent=null,this.destroyShape(t.data))}remove(e,t){e.rigidbody&&e.rigidbody.body&&e.rigidbody.disableSimulation(),e.trigger&&(e.trigger.destroy(),delete e.trigger)}clone(e,t){const s=this.system.store[e.guid],i={enabled:s.data.enabled,type:s.data.type,halfExtents:[s.data.halfExtents.x,s.data.halfExtents.y,s.data.halfExtents.z],linearOffset:[s.data.linearOffset.x,s.data.linearOffset.y,s.data.linearOffset.z],angularOffset:[s.data.angularOffset.x,s.data.angularOffset.y,s.data.angularOffset.z,s.data.angularOffset.w],radius:s.data.radius,axis:s.data.axis,height:s.data.height,convexHull:s.data.convexHull,asset:s.data.asset,renderAsset:s.data.renderAsset,model:s.data.model,render:s.data.render,checkVertexDuplicates:s.data.checkVertexDuplicates};return this.system.addComponent(t,i)}}class TN extends xn{createPhysicalShape(e,t){if(typeof Ammo<"u"){const s=t.halfExtents,i=new Ammo.btVector3(s?s.x:.5,s?s.y:.5,s?s.z:.5),r=new Ammo.btBoxShape(i);return Ammo.destroy(i),r}}}class wN extends xn{createPhysicalShape(e,t){if(typeof Ammo<"u")return new Ammo.btSphereShape(t.radius)}}class CN extends xn{createPhysicalShape(e,t){const s=t.axis??1,i=t.radius??.5,r=Math.max((t.height??2)-2*i,0);let a=null;if(typeof Ammo<"u")switch(s){case 0:a=new Ammo.btCapsuleShapeX(i,r);break;case 1:a=new Ammo.btCapsuleShape(i,r);break;case 2:a=new Ammo.btCapsuleShapeZ(i,r);break}return a}}class EN extends xn{createPhysicalShape(e,t){const s=t.axis??1,i=t.radius??.5,r=t.height??1;let a=null,n=null;if(typeof Ammo<"u")switch(s){case 0:a=new Ammo.btVector3(r*.5,i,i),n=new Ammo.btCylinderShapeX(a);break;case 1:a=new Ammo.btVector3(i,r*.5,i),n=new Ammo.btCylinderShape(a);break;case 2:a=new Ammo.btVector3(i,i,r*.5),n=new Ammo.btCylinderShapeZ(a);break}return a&&Ammo.destroy(a),n}}class bN extends xn{createPhysicalShape(e,t){const s=t.axis??1,i=t.radius??.5,r=t.height??1;let a=null;if(typeof Ammo<"u")switch(s){case 0:a=new Ammo.btConeShapeX(i,r);break;case 1:a=new Ammo.btConeShape(i,r);break;case 2:a=new Ammo.btConeShapeZ(i,r);break}return a}}class AN extends xn{beforeInitialize(e,t){}createAmmoHull(e,t,s,i){const r=new Ammo.btConvexHullShape,a=new Ammo.btVector3,n=[];e.getPositions(n);for(let c=0;c<n.length;c+=3)a.setValue(n[c]*i.x,n[c+1]*i.y,n[c+2]*i.z),r.addPoint(a,!1);Ammo.destroy(a),r.recalcLocalAabb(),r.setMargin(.01);const o=this.system._getNodeTransform(t);s.addChildShape(o,r),Ammo.destroy(o)}createAmmoMesh(e,t,s,i,r=!0){const a=this.system;let n;if(a._triMeshCache[e.id])n=a._triMeshCache[e.id];else{const h=e.vertexBuffer,d=h.getFormat();let u,f;for(let P=0;P<d.elements.length;P++){const L=d.elements[P];if(L.name===Ie){f=new Float32Array(h.lock(),L.offset),u=L.stride/4;break}}const p=[];e.getIndices(p);const m=e.primitive[0].count/3,_=new Ammo.btVector3;let g,v,x;const y=e.primitive[0].base;n=new Ammo.btTriangleMesh,a._triMeshCache[e.id]=n;const S=new Map,T=n.getIndexedMeshArray();T.at(0).m_numTriangles=m;const w=i?i.x:1,C=i?i.y:1,b=i?i.z:1,I=P=>{const L=f[P*u]*w,O=f[P*u+1]*C,D=f[P*u+2]*b;let N;if(r){const k=`${L}:${O}:${D}`;if(N=S.get(k),N!==void 0)return N;_.setValue(L,O,D),N=n.findOrAddVertex(_,!1),S.set(k,N)}else _.setValue(L,O,D),N=n.findOrAddVertex(_,!1);return N};for(let P=0;P<m;
11884P++)g=I(p[y+P*3]),v=I(p[y+P*3+1]),x=I(p[y+P*3+2]),n.addIndex(g),n.addIndex(v),n.addIndex(x);Ammo.destroy(_)}const o=new Ammo.btBvhTriangleMeshShape(n,!0);if(!i){const h=a._getNodeScaling(t);o.setLocalScaling(h),Ammo.destroy(h)}const c=a._getNodeTransform(t);s.addChildShape(c,o),Ammo.destroy(c)}createPhysicalShape(e,t){if(!(typeof Ammo>"u")&&(t.model||t.render)){const s=new Ammo.btCompoundShape,r=e.getWorldTransform().getScale();if(t.render){const a=t.render.meshes;for(let n=0;n<a.length;n++)t.convexHull?this.createAmmoHull(a[n],qy,s,r):this.createAmmoMesh(a[n],qy,s,r,t.checkVertexDuplicates)}else if(t.model){const a=t.model.meshInstances;for(let o=0;o<a.length;o++)this.createAmmoMesh(a[o].mesh,a[o].node,s,null,t.checkVertexDuplicates);const n=new Ammo.btVector3(r.x,r.y,r.z);s.setLocalScaling(n),Ammo.destroy(n)}return s}}recreatePhysicalShapes(e){const t=e.data;if((t.renderAsset||t.asset)&&e.enabled&&e.entity.enabled){this.loadAsset(e,t.renderAsset||t.asset,t.renderAsset?"render":"model");return}this.doRecreatePhysicalShape(e)}loadAsset(e,t,s){const i=e.data,r=this.system.app.assets,a=i[s],n=h=>{i[s]===a&&(i[s]=h.resource,this.doRecreatePhysicalShape(e))},o=h=>{h.ready(d=>{if(d.data.containerAsset){const u=r.get(d.data.containerAsset);u.loaded?n(d):(u.ready(()=>{n(d)}),r.load(u))}else n(d)}),r.load(h)},c=r.get(t);c?o(c):r.once(`add:${t}`,o)}doRecreatePhysicalShape(e){const t=e.entity,s=e.data;s.model||s.render?(this.destroyShape(s),s.shape=this.createPhysicalShape(t,s),t.rigidbody?(t.rigidbody.disableSimulation(),t.rigidbody.createBody(),t.enabled&&t.rigidbody.enabled&&t.rigidbody.enableSimulation()):t.trigger?t.trigger.initialize(s):t.trigger=new zw(this.system.app,e,s)):(this.beforeRemove(t,e),this.remove(t,s))}updateTransform(e,t,s,i){if(e.shape){const a=e.entity.getWorldTransform().getScale(),n=e.shape.getLocalScaling();(a.x!==n.x()||a.y!==n.y()||a.z!==n.z())&&this.doRecreatePhysicalShape(e)}super.updateTransform(e,t,s,i)}destroyShape(e){if(!e.shape)return;const t=e.shape.getNumChildShapes();for(let s=0;s<t;s++){const i=e.shape.getChildShape(s);Ammo.destroy(i)}Ammo.destroy(e.shape),e.shape=null}}class PN extends xn{createPhysicalShape(e,t){if(typeof Ammo<"u")return new Ammo.btCompoundShape}_addEachDescendant(e){!e.collision||e.rigidbody||(e.collision._compoundParent=this,e!==this.entity&&e.collision.system.recreatePhysicalShapes(e.collision))}_updateEachDescendant(e){e.collision&&e.collision._compoundParent===this&&(e.collision._compoundParent=null,e!==this.entity&&!e.rigidbody&&e.collision.system.recreatePhysicalShapes(e.collision))}_updateEachDescendantTransform(e){!e.collision||e.collision._compoundParent!==this.collision._compoundParent||this.collision.system.updateCompoundChildTransform(e,!1)}}class IN extends Tt{constructor(e){super(e),this.id="collision",this.ComponentType=pN,this.DataType=mN,this.schema=xN,this.implementations={},this._triMeshCache={},this.on("beforeremove",this.onBeforeRemove,this),this.on("remove",this.onRemove,this)}initializeComponentData(e,t,s){s=["type","halfExtents","radius","axis","height","convexHull","shape","model","asset","render","renderAsset","enabled","linearOffset","angularOffset","checkVertexDuplicates"];const i={};for(let n=0,o=s.length;n<o;n++){const c=s[n];i[c]=t[c]}let r;if(t.hasOwnProperty("asset")?(r=s.indexOf("model"),r!==-1&&s.splice(r,1),r=s.indexOf("render"),r!==-1&&s.splice(r,1)):t.hasOwnProperty("model")&&(r=s.indexOf("asset"),r!==-1&&s.splice(r,1)),i.type||(i.type=e.data.type),e.data.type=i.type,Array.isArray(i.halfExtents)&&(i.halfExtents=new E(i.halfExtents)),Array.isArray(i.linearOffset)&&(i.linearOffset=new E(i.linearOffset)),Array.isArray(i.angularOffset)){const n=i.angularOffset;n.length===3?i.angularOffset=new ae().setFromEulerAngles(n[0],n[1],n[2]):i.angularOffset=new ae(i.angularOffset)}const a=this._createImplementation(i.type);a.beforeInitialize(e,i),super.initializeComponentData(e,i,s),a.afterInitialize(e,i)}_createImplementation(e){if(this.implementations[e]===void 0){let t;switch(e){case"box":t=new TN(this);break;case"sphere":t=new wN(this);break;case"capsule":t=new CN(this);break;case"cylinder":t=new EN(this);break;case"cone":t=new bN(this);break;
11884case"mesh":t=new AN(this);break;case"compound":t=new PN(this);break}this.implementations[e]=t}return this.implementations[e]}_getImplementation(e){return this.implementations[e.collision.data.type]}cloneComponent(e,t){return this._getImplementation(e).clone(e,t)}onBeforeRemove(e,t){this.implementations[t.data.type].beforeRemove(e,t),t.onBeforeRemove()}onRemove(e,t){this.implementations[t.type].remove(e,t)}updateCompoundChildTransform(e,t){const s=e.collision._compoundParent;if(s!==e.collision&&e.enabled&&e.collision.enabled&&(e._dirtyLocal||t)){const i=this._getNodeTransform(e,s.entity),r=s.getCompoundChildShapeIndex(e.collision.shape);r===null?s.shape.addChildShape(i,e.collision.data.shape):s.shape.updateChildTransform(r,i,!0),Ammo.destroy(i)}}_removeCompoundChild(e,t){if(e.shape.getNumChildShapes()!==0)if(e.shape.removeChildShape)e.shape.removeChildShape(t);else{const s=e.getCompoundChildShapeIndex(t);s!==null&&e.shape.removeChildShapeByIndex(s)}}onTransformChanged(e,t,s,i){this.implementations[e.data.type].updateTransform(e,t,s,i)}changeType(e,t,s){this.implementations[t].beforeRemove(e.entity,e),this.implementations[t].remove(e.entity,e.data),this._createImplementation(s).reset(e,e.data)}recreatePhysicalShapes(e){this.implementations[e.data.type].recreatePhysicalShapes(e)}_calculateNodeRelativeTransform(e,t){if(e===t){const s=e.getWorldTransform().getScale();Jh.setScale(s.x,s.y,s.z)}else this._calculateNodeRelativeTransform(e.parent,t),Jh.mul(e.getLocalTransform())}_getNodeScaling(e){const s=e.getWorldTransform().getScale();return new Ammo.btVector3(s.x,s.y,s.z)}_getNodeTransform(e,t){let s,i;t?(this._calculateNodeRelativeTransform(e,t),s=SN,i=La,Jh.getTranslation(s),i.setFromMat4(Jh)):(s=e.getPosition(),i=e.getRotation());const r=new Ammo.btQuaternion,a=new Ammo.btTransform;a.setIdentity();const n=a.getOrigin(),o=e.collision;if(o&&o._hasOffset){const c=o.data.linearOffset,h=o.data.angularOffset,d=yN;La.copy(i).transformVector(c,d),d.add(s),La.copy(i).mul(h),n.setValue(d.x,d.y,d.z),r.setValue(La.x,La.y,La.z,La.w)}else n.setValue(s.x,s.y,s.z),r.setValue(i.x,i.y,i.z,i.w);return a.setRotation(r),Ammo.destroy(r),a}destroy(){for(const e in this._triMeshCache)Ammo.destroy(this._triMeshCache[e]);this._triMeshCache=null,super.destroy()}}const ed=new Q,DN=new Jt;class MN{constructor(e,t,s){this._entity=e,this._element=e.element,this.model=new pa,this.node=new He,this.model.graph=this.node,this.mesh=t,this.meshInstance=new Ne(this.mesh,s,this.node),this.meshInstance.name=`ImageElement: ${e.name}`,this.meshInstance.castShadow=!1,this.meshInstance.receiveShadow=!1,this._meshDirty=!1,this.model.meshInstances.push(this.meshInstance),this._entity.addChild(this.model.graph),this.model._entity=this._entity,this.unmaskMeshInstance=null}destroy(){this.setMaterial(null),this._element.removeModelFromLayers(this.model),this.model.destroy(),this.model=null,this.node=null,this.mesh=null,this.meshInstance?.destroy(),this.meshInstance=null,this.unmaskMeshInstance?.destroy(),this.unmaskMeshInstance=null,this._entity=null,this._element=null}setMesh(e){this.meshInstance&&(this.mesh=e,this.meshInstance.mesh=e,this.meshInstance.visible=!!e,this.unmaskMeshInstance&&(this.unmaskMeshInstance.mesh=e),this.forceUpdateAabb())}setMask(e){if(this.meshInstance){if(this._entity.enabled&&this._element.enabled&&this._element.removeModelFromLayers(this.model),e){this.unmaskMeshInstance=new Ne(this.mesh,this.meshInstance.material,this.node),this.unmaskMeshInstance.name=`Unmask: ${this._entity.name}`,this.unmaskMeshInstance.castShadow=!1,this.unmaskMeshInstance.receiveShadow=!1,this.unmaskMeshInstance.pick=!1,this.model.meshInstances.push(this.unmaskMeshInstance);for(const t in this.meshInstance.parameters)this.unmaskMeshInstance.setParameter(t,this.meshInstance.parameters[t].data)}else{const t=this.model.meshInstances.indexOf(this.unmaskMeshInstance);t>=0&&this.model.meshInstances.splice(t,1)}this._entity.enabled&&this._element.enabled&&this._element.addModelToLayers(this.model),e||(this.unmaskMeshInstance?.destroy(),this.unmaskMeshInstance=null)}}setMaterial(e){this.meshInstance&&(this.meshInstance.material=e,this.unmaskMeshInstance&&(this.unmaskMeshInstance.material=e))}setParameter(e,t){this.meshInstance&&(this.meshInstance.setParameter(e,t),this.unmaskMeshInstance&&this.unmaskMeshInstance.setParameter(e,t))}deleteParameter(e){this.meshInstance&&(this.meshInstance.deleteParameter(e),this.unmaskMeshInstance&&this.unmaskMeshInstance.deleteParameter(e))}setUnmaskDrawOrder(){if(!this.meshInstance)return;const e=function(t){let s;const i=t.children,r=i.length;if(r){for(let n=0;n<r;n++)i[n].element&&(s=i[n]);if(!s)return null;const a=e(s);return a||s}return null};if(this.unmaskMeshInstance){const t=e(this._entity);t&&t.element?this.unmaskMeshInstance.drawOrder=t.element.drawOrder+t.element.getMaskOffset():this.unmaskMeshInstance.drawOrder=this.meshInstance.drawOrder+this._element.getMaskOffset()}}setDrawOrder(e){this.meshInstance&&(this.meshInstance.drawOrder=e)}setCull(e){if(!this.meshInstance)return;const t=this._element;let s=null;e&&t._isScreenSpace()&&(s=function(i){return t.isVisibleForCamera(i)}),this.meshInstance.cull=e,this.meshInstance.isVisibleFunc=s,this.unmaskMeshInstance&&(this.unmaskMeshInstance.cull=e,this.unmaskMeshInstance.isVisibleFunc=s)}setScreenSpace(e){this.meshInstance&&(this.meshInstance.screenSpace=e,this.unmaskMeshInstance&&(this.unmaskMeshInstance.screenSpace=e))}setLayer(e){this.meshInstance&&(this.meshInstance.layer=e,this.unmaskMeshInstance&&(this.unmaskMeshInstance.layer=e))}forceUpdateAabb(e){this.meshInstance&&(this.meshInstance._aabbVer=-1,this.unmaskMeshInstance&&(this.unmaskMeshInstance._aabbVer=-1))}setAabbFunc(e){this.meshInstance&&(this.meshInstance._updateAabbFunc=e,this.unmaskMeshInstance&&(this.unmaskMeshInstance._updateAabbFunc=e))}}class RN{_evtSetMeshes=null;constructor(e){this._element=e,this._entity=e.entity,this._system=e.system,this._textureAsset=null,this._texture=null,this._materialAsset=null,this._material=null,this._spriteAsset=null,this._sprite=null,this._spriteFrame=0,this._pixelsPerUnit=null,this._targetAspectRatio=-1,this._rect=new ie(0,0,1,1),this._mask=!1,this._maskRef=0,this._outerScale=new j,this._outerScaleUniform=new Float32Array(2),this._innerOffset=new ie,this._innerOffsetUniform=new Float32Array(4),this._atlasRect=new ie,this._atlasRectUniform=new Float32Array(4),this._defaultMesh=this._createMesh(),this._renderable=new MN(this._entity,this._defaultMesh,this._material),this._color=new Q(1,1,1,1),this._colorUniform=new Float32Array([1,1,1]),this._updateRenderableEmissive(),this._renderable.setParameter("material_opacity",1),this._updateAabbFunc=this._updateAabb.bind(this),this._onScreenChange(this._element.screen),this._element.on("resize",this._onParentResizeOrPivotChange,this),this._element.on("set:pivot",this._onParentResizeOrPivotChange,this),this._element.on("screen:set:screenspace",this._onScreenSpaceChange,this),this._element.on("set:screen",this._onScreenChange,this),this._element.on("set:draworder",this._onDrawOrderChange,this),this._element.on("screen:set:resolution",this._onRes
11884olutionChange,this),!e._beingInitialized&&e.enabled&&e.entity.enabled&&this.onEnable()}destroy(){this.textureAsset=null,this.spriteAsset=null,this.materialAsset=null,this._renderable.setMesh(this._defaultMesh),this._renderable.destroy(),this._defaultMesh=null,this._element.off("resize",this._onParentResizeOrPivotChange,this),this._element.off("set:pivot",this._onParentResizeOrPivotChange,this),this._element.off("screen:set:screenspace",this._onScreenSpaceChange,this),this._element.off("set:screen",this._onScreenChange,this),this._element.off("set:draworder",this._onDrawOrderChange,this),this._element.off("screen:set:resolution",this._onResolutionChange,this)}_onResolutionChange(e){}_onParentResizeOrPivotChange(){this._renderable.mesh&&this._updateMesh(this._renderable.mesh)}_onScreenSpaceChange(e){this._updateMaterial(e)}_onScreenChange(e,t){e?this._updateMaterial(e.screen.screenSpace):this._updateMaterial(!1)}_onDrawOrderChange(e){this._renderable.setDrawOrder(e),this.mask&&this._element.screen&&this._element.screen.screen.once("syncdraworder",function(){this._renderable.setUnmaskDrawOrder()},this)}_hasUserMaterial(){return!!this._materialAsset||!!this._material&&this._system.defaultImageMaterials.indexOf(this._material)===-1}_use9Slicing(){return this.sprite&&(this.sprite.renderMode===kt||this.sprite.renderMode===Ut)}_updateMaterial(e){const t=!!this._mask,s=!!(this.sprite&&this.sprite.renderMode===kt),i=!!(this.sprite&&this.sprite.renderMode===Ut);this._hasUserMaterial()||(this._material=this._system.getImageElementMaterial(e,t,s,i)),this._renderable&&(this._renderable.setCull(!this._element._isScreenSpace()||this._element._isScreenCulled()),this._renderable.setMaterial(this._material),this._renderable.setScreenSpace(e),this._renderable.setLayer(e?fI:fT))}_createMesh(){const e=this._element,t=e.calculatedWidth,s=e.calculatedHeight,i=this._rect,r=this._system.app.graphicsDevice,a=new Float32Array([t,0,0,0,0,1,i.x+i.z,1-i.y,t,s,0,0,0,1,i.x+i.z,1-(i.y+i.w),0,0,0,0,0,1,i.x,1-i.y,0,s,0,0,0,1,i.x,1-(i.y+i.w)]),n=DN.get(r,()=>new Us(r,[{semantic:Ie,components:3,type:je},{semantic:Cs,components:3,type:je},{semantic:Zs,components:2,type:je}])),o=new Hi(r,n,4,{data:a.buffer}),c=new at(r);return c.vertexBuffer=o,c.primitive[0].type=Tr,c.primitive[0].base=0,c.primitive[0].count=4,c.primitive[0].indexed=!1,c.aabb.setMinMax(E.ZERO,new E(t,s,0)),this._updateMesh(c),c}_updateMesh(e){const t=this._element;let s=t.calculatedWidth,i=t.calculatedHeight;if(t.fitMode!==Ld&&this._targetAspectRatio>0){const a=t.calculatedWidth/t.calculatedHeight;t.fitMode===cN&&a>this._targetAspectRatio||t.fitMode===hN&&a<this._targetAspectRatio?s=t.calculatedHeight*this._targetAspectRatio:i=t.calculatedWidth/this._targetAspectRatio}const r=t._isScreenSpace();if(this._updateMaterial(r),this._renderable&&this._renderable.forceUpdateAabb(),this.sprite&&(this.sprite.renderMode===kt||this.sprite.renderMode===Ut)){const a=this._sprite.atlas.frames[this._sprite.frameKeys[this._spriteFrame]],n=2/a.rect.z,o=2/a.rect.w;this._innerOffset.set(a.border.x*n,a.border.y*o,a.border.z*n,a.border.w*o);const c=this.sprite.atlas.texture;this._atlasRect.set(a.rect.x/c.width,a.rect.y/c.height,a.rect.z/c.width,a.rect.w/c.height);const h=this._pixelsPerUnit!==null?this._pixelsPerUnit:this.sprite.pixelsPerUnit,d=a.rect.z/h,u=a.rect.w/h;this._outerScale.set(Math.max(s,this._innerOffset.x*d),Math.max(i,this._innerOffset.y*u));let f=d,p=u;this._outerScale.x/=d,this._outerScale.y/=u,f*=H.clamp(s/(this._innerOffset.x*d),1e-4,1),p*=H.clamp(i/(this._innerOffset.y*u),1e-4,1),this._renderable&&(this._innerOffsetUniform[0]=this._innerOffset.x,this._innerOffsetUniform[1]=this._innerOffset.y,this._innerOffsetUniform[2]=this._innerOffset.z,this._innerOffsetUniform[3]=this._innerOffset.w,this._renderable.setParameter("innerOffset",this._innerOffsetUniform),this._atlasRectUniform[0]=this._atlasRect.x,this._atlasRectUniform[1]=this._atlasRect.y,this._atlasRectUniform[2]=this._atlasRect.z,this._atlasRectUniform[3]=this._atlasRect.w,this._renderable.setParameter("atlasRect",this._atlasRectUniform),this._outerScaleUniform[0]=this._outerScale.x,this._outerScaleUniform[1]=this._outerScale.y,this._renderable.setParameter("outerScale",this._outerScaleUniform),this._renderable.setAabbFunc(this._updateAabbFunc),this._renderable.node.setLocalScale(f,p,1),this._renderable.node.setLocalPosition((.5-t.pivot.x)*s,(.5-t.pivot.y)*i,0))}else{const a=e.vertexBuffer,n=new Float32Array(a.lock()),o=t.pivot.x,c=t.pivot.y;n[0]=s-o*s,n[1]=0-c*i,n[8]=s-o*s,n[9]=i-c*i,n[16]=0-o*s,n[17]=0-c*i,n[24]=0-o*s,n[25]=i-c*i;let h=1,d=1,u=this._rect;if(this._sprite&&this._sprite.frameKeys[this._spriteFrame]&&this._sprite.atlas){const m=this._sprite.atlas.frames[this._sprite.frameKeys[this._spriteFrame]];m&&(u=m.rect,h=this._sprite.atlas.texture.width,d=this._sprite.atlas.texture.height)}n[6]=(u.x+u.z)/h,n[7]=1-u.y/d,n[14]=(u.x+u.z)/h,n[15]=1-(u.y+u.w
11884)/d,n[22]=u.x/h,n[23]=1-u.y/d,n[30]=u.x/h,n[31]=1-(u.y+u.w)/d,a.unlock();const f=new E(0-o*s,0-c*i,0),p=new E(s-o*s,i-c*i,0);e.aabb.setMinMax(f,p),this._renderable&&(this._renderable.node.setLocalScale(1,1,1),this._renderable.node.setLocalPosition(0,0,0),this._renderable.setAabbFunc(null))}this._meshDirty=!1}_updateSprite(){let e=!1,t=null;if(this._targetAspectRatio=-1,this._sprite&&this._sprite.atlas){t=this._sprite.meshes[this.spriteFrame],e=this._sprite.renderMode===kt||this._sprite.renderMode===Ut;const s=this._sprite.atlas.frames[this._sprite.frameKeys[this._spriteFrame]];s?.rect.w>0&&(this._targetAspectRatio=s.rect.z/s.rect.w)}this.mesh=e?t:this._defaultMesh,this.refreshMesh()}refreshMesh(){this.mesh&&(this._element._beingInitialized?this._meshDirty=!0:this._updateMesh(this.mesh))}_updateAabb(e){return e.center.set(0,0,0),e.halfExtents.set(this._outerScale.x*.5,this._outerScale.y*.5,.001),e.setFromTransformedAabb(e,this._renderable.node.getWorldTransform()),e}_toggleMask(){this._element._dirtifyMask();const e=this._element._isScreenSpace();this._updateMaterial(e),this._renderable.setMask(!!this._mask)}_onMaterialLoad(e){this.material=e.resource}_onMaterialAdded(e){this._system.app.assets.off(`add:${e.id}`,this._onMaterialAdded,this),this._materialAsset===e.id&&this._bindMaterialAsset(e)}_bindMaterialAsset(e){this._entity.enabled&&(e.on("load",this._onMaterialLoad,this),e.on("change",this._onMaterialChange,this),e.on("remove",this._onMaterialRemove,this),e.resource?this._onMaterialLoad(e):this._system.app.assets.load(e))}_unbindMaterialAsset(e){e.off("load",this._onMaterialLoad,this),e.off("change",this._onMaterialChange,this),e.off("remove",this._onMaterialRemove,this)}_onMaterialChange(){}_onMaterialRemove(){}_onTextureAdded(e){this._system.app.assets.off(`add:${e.id}`,this._onTextureAdded,this),this._textureAsset===e.id&&this._bindTextureAsset(e)}_bindTextureAsset(e){this._entity.enabled&&(e.on("load",this._onTextureLoad,this),e.on("change",this._onTextureChange,this),e.on("remove",this._onTextureRemove,this),e.resource?this._onTextureLoad(e):this._system.app.assets.load(e))}_unbindTextureAsset(e){e.off("load",this._onTextureLoad,this),e.off("change",this._onTextureChange,this),e.off("remove",this._onTextureRemove,this)}_onTextureLoad(e){this.texture=e.resource}_onTextureChange(e){}_onTextureRemove(e){}_onSpriteAssetAdded(e){this._system.app.assets.off(`add:${e.id}`,this._onSpriteAssetAdded,this),this._spriteAsset===e.id&&this._bindSpriteAsset(e)}_bindSpriteAsset(e){this._entity.enabled&&(e.on("load",this._onSpriteAssetLoad,this),e.on("change",this._onSpriteAssetChange,this),e.on("remove",this._onSpriteAssetRemove,this),e.resource?this._onSpriteAssetLoad(e):this._system.app.assets.load(e))}_unbindSpriteAsset(e){e.off("load",this._onSpriteAssetLoad,this),e.off("change",this._onSpriteAssetChange,this),e.off("remove",this._onSpriteAssetRemove,this),e.data.textureAtlasAsset&&this._system.app.assets.off(`load:${e.data.textureAtlasAsset}`,this._onTextureAtlasLoad,this)}_onSpriteAssetLoad(e){if(!e||!e.resource)this.sprite=null;else if(e.resource.atlas)this.sprite=e.resource;else{const t=e.data.textureAtlasAsset;if(t){const s=this._system.app.assets;s.off(`load:${t}`,this._onTextureAtlasLoad,this),s.once(`load:${t}`,this._onTextureAtlasLoad,this)}}}_onSpriteAssetChange(e){this._onSpriteAssetLoad(e)}_onSpriteAssetRemove(e){}_bindSprite(e){this._evtSetMeshes=e.on("set:meshes",this._onSpriteMeshesChange,this),e.on("set:pixelsPerUnit",this._onSpritePpuChange,this),e.on("set:atlas",this._onAtlasTextureChange,this),e.atlas&&e.atlas.on("set:texture",this._onAtlasTextureChange,this)}_unbindSprite(e){this._evtSetMeshes?.off(),this._evtSetMeshes=null,e.off("set:pixelsPerUnit",this._onSpritePpuChange,this),e.off("set:atlas",this._onAtlasTextureChange,this),e.atlas&&e.atlas.off("set:texture",this._onAtlasTextureChange,this)}_onSpriteMeshesChange(){this._sprite&&(this._spriteFrame=H.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite()}_onSpritePpuChange(){this.sprite.renderMode!==Fi&&this._pixelsPerUnit===null&&this._updateSprite()}_onAtlasTextureChange(){this.sprite&&this.sprite.atlas&&this.sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"))}_onTextureAtlasLoad(e){const t=this._spriteAsset;t instanceof pe?this._onSpriteAssetLoad(t):this._onSpriteAssetLoad(this._system.a
11884pp.assets.get(t))}onEnable(){if(this._materialAsset){const e=this._system.app.assets.get(this._materialAsset);e&&e.resource!==this._material&&this._bindMaterialAsset(e)}if(this._textureAsset){const e=this._system.app.assets.get(this._textureAsset);e&&e.resource!==this._texture&&this._bindTextureAsset(e)}if(this._spriteAsset){const e=this._system.app.assets.get(this._spriteAsset);e&&e.resource!==this._sprite&&this._bindSpriteAsset(e)}this._element.addModelToLayers(this._renderable.model)}onDisable(){this._element.removeModelFromLayers(this._renderable.model)}_setStencil(e){this._renderable.meshInstance.stencilFront=e,this._renderable.meshInstance.stencilBack=e;let t=0;if(this._element.maskedBy&&(t=this._element.maskedBy.element._image._maskRef),this._renderable.unmaskMeshInstance){const s=new $s({ref:t+1,func:Wd,zpass:tb});this._renderable.unmaskMeshInstance.stencilFront=s,this._renderable.unmaskMeshInstance.stencilBack=s}}_updateRenderableEmissive(){ed.linear(this._color),this._colorUniform[0]=ed.r,this._colorUniform[1]=ed.g,this._colorUniform[2]=ed.b,this._renderable.setParameter("material_emissive",this._colorUniform)}set color(e){const{r:t,g:s,b:i}=e;(this._color.r!==t||this._color.g!==s||this._color.b!==i)&&(this._color.r=t,this._color.g=s,this._color.b=i,this._updateRenderableEmissive()),this._element&&this._element.fire("set:color",this._color)}get color(){return this._color}set opacity(e){e!==this._color.a&&(this._color.a=e,this._renderable.setParameter("material_opacity",e)),this._element&&this._element.fire("set:opacity",e)}get opacity(){return this._color.a}set rect(e){let t,s,i,r;e instanceof ie?(t=e.x,s=e.y,i=e.z,r=e.w):(t=e[0],s=e[1],i=e[2],r=e[3]),!(t===this._rect.x&&s===this._rect.y&&i===this._rect.z&&r===this._rect.w)&&(this._rect.set(t,s,i,r),this._renderable.mesh&&(this._element._beingInitialized?this._meshDirty=!0:this._updateMesh(this._renderable.mesh)))}get rect(){return this._rect}_removeMaterialAssetEvents(){if(this._materialAsset){const e=this._system.app.assets;e.off(`add:${this._materialAsset}`,this._onMaterialAdded,this);const t=e.get(this._materialAsset);t&&(t.off("load",this._onMaterialLoad,this),t.off("change",this._onMaterialChange,this),t.off("remove",this._onMaterialRemove,this))}}set material(e){if(this._material!==e){if(!e){const t=this._element._isScreenSpace();this.mask?e=t?this._system.defaultScreenSpaceImageMaskMaterial:this._system.defaultImageMaskMaterial:e=t?this._system.defaultScreenSpaceImageMaterial:this._system.defaultImageMaterial}if(this._material=e,this._materialAsset){const t=this._system.app.assets.get(this._materialAsset);(!t||t.resource!==e)&&(this._removeMaterialAssetEvents(),this._materialAsset=null)}e&&(this._renderable.setMaterial(e),this._hasUserMaterial()?(this._renderable.deleteParameter("material_opacity"),this._renderable.deleteParameter("material_emissive")):(this._updateRenderableEmissive(),this._renderable.setParameter("material_opacity",this._color.a)))}}get material(){return this._material}set materialAsset(e){const t=this._system.app.assets;let s=e;if(e instanceof pe&&(s=e.id),this._materialAsset!==s)if(this._removeMaterialAssetEvents(),this._materialAsset=s,this._materialAsset){const i=t.get(this._materialAsset);i?this._bindMaterialAsset(i):(this._materialAsset=null,this.material=null,this._materialAsset=s,t.on(`add:${this._materialAsset}`,this._onMaterialAdded,this))}else this._materialAsset=null,this.material=null,this._materialAsset=s}get materialAsset(){return this._materialAsset}set texture(e){if(this._texture!==e){if(this._textureAsset){const t=this._system.app.assets.get(this._textureAsset);t&&t.resource!==e&&(this.textureAsset=null)}if(this._texture=e,e){this._spriteAsset&&(this.spriteAsset=null),this._renderable.setParameter("texture_emissiveMap",this._texture),this._renderable.setParameter("texture_opacityMap",this._texture),this._updateRenderableEmissive(),this._renderable.setParameter("material_opacity",this._color.a);const t=this._texture.width/this._texture.height;t!==this._targetAspectRatio&&(this._targetAspectRatio=t,this._element.fitMode!==Ld&&this.refreshMesh())}else this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap"),this._targetAspectRatio=-1,this._element.fitMode!==Ld&&this.refreshMesh()}}get texture(){return this._texture}
11884set textureAsset(e){const t=this._system.app.assets;let s=e;if(e instanceof pe&&(s=e.id),this._textureAsset!==s){if(this._textureAsset){t.off(`add:${this._textureAsset}`,this._onTextureAdded,this);const i=t.get(this._textureAsset);i&&(i.off("load",this._onTextureLoad,this),i.off("change",this._onTextureChange,this),i.off("remove",this._onTextureRemove,this))}if(this._textureAsset=s,this._textureAsset){const i=t.get(this._textureAsset);i?this._bindTextureAsset(i):(this.texture=null,t.on(`add:${this._textureAsset}`,this._onTextureAdded,this))}else this.texture=null}}get textureAsset(){return this._textureAsset}set spriteAsset(e){const t=this._system.app.assets;let s=e;if(e instanceof pe&&(s=e.id),this._spriteAsset!==s){if(this._spriteAsset){t.off(`add:${this._spriteAsset}`,this._onSpriteAssetAdded,this);const i=t.get(this._spriteAsset);i&&this._unbindSpriteAsset(i)}if(this._spriteAsset=s,this._spriteAsset){const i=t.get(this._spriteAsset);i?this._bindSpriteAsset(i):(this.sprite=null,t.on(`add:${this._spriteAsset}`,this._onSpriteAssetAdded,this))}else this.sprite=null}this._element&&this._element.fire("set:spriteAsset",s)}get spriteAsset(){return this._spriteAsset}set sprite(e){if(this._sprite!==e){if(this._sprite&&this._unbindSprite(this._sprite),this._spriteAsset){const t=this._system.app.assets.get(this._spriteAsset);t&&t.resource!==e&&(this.spriteAsset=null)}this._sprite=e,this._sprite&&(this._bindSprite(this._sprite),this._textureAsset&&(this.textureAsset=null)),this._sprite&&this._sprite.atlas&&this._sprite.atlas.texture?(this._renderable.setParameter("texture_emissiveMap",this._sprite.atlas.texture),this._renderable.setParameter("texture_opacityMap",this._sprite.atlas.texture)):(this._renderable.deleteParameter("texture_emissiveMap"),this._renderable.deleteParameter("texture_opacityMap")),this._sprite&&(this._spriteFrame=H.clamp(this._spriteFrame,0,this._sprite.frameKeys.length-1)),this._updateSprite()}}get sprite(){return this._sprite}set spriteFrame(e){const t=this._spriteFrame;this._sprite?this._spriteFrame=H.clamp(e,0,this._sprite.frameKeys.length-1):this._spriteFrame=e,this._spriteFrame!==t&&this._updateSprite(),this._element&&this._element.fire("set:spriteFrame",e)}get spriteFrame(){return this._spriteFrame}set mesh(e){this._renderable.setMesh(e),this._defaultMesh===e?this._renderable.setAabbFunc(null):this._renderable.setAabbFunc(this._updateAabbFunc)}get mesh(){return this._renderable.mesh}set mask(e){this._mask!==e&&(this._mask=e,this._toggleMask())}get mask(){return this._mask}set pixelsPerUnit(e){this._pixelsPerUnit!==e&&(this._pixelsPerUnit=e,this._sprite&&(this._sprite.renderMode===kt||this._sprite.renderMode===Ut)&&this._updateSprite())}get pixelsPerUnit(){return this._pixelsPerUnit}get aabb(){return this._renderable.meshInstance?this._renderable.meshInstance.aabb:null}}class LN extends ge{constructor(e){super(),this._app=e,e.i18n.on(fn.EVENT_CHANGE,this._onSetLocale,this),this._autoLoad=!1,this._disableLocalization=!1,this._defaultAsset=null,this._localizedAsset=null}set defaultAsset(e){const t=e instanceof pe?e.id:e;this._defaultAsset!==t&&(this._defaultAsset&&this._unbindDefaultAsset(),this._defaultAsset=t,this._defaultAsset&&this._bindDefaultAsset(),this._onSetLocale(this._app.i18n.locale))}get defaultAsset(){return this._defaultAsset}set localizedAsset(e){const t=e instanceof pe?e.id:e;this._localizedAsset!==t&&(this._localizedAsset&&(this._app.assets.off(`add:${this._localizedAsset}`,this._onLocalizedAssetAdd,this),this._unbindLocalizedAsset()),this._localizedAsset=t,this._localizedAsset&&(this._app.assets.get(this._localizedAsset)?this._bindLocalizedAsset():this._app.assets.once(`add:${this._localizedAsset}`,this._onLocalizedAssetAdd,this)))}get localizedAsset(){return this._localizedAsset}set autoLoad(e){this._autoLoad!==e&&(this._autoLoad=e,this._autoLoad&&this._localizedAsset&&(this._unbindLocalizedAsset(),this._bindLocalizedAsset()))}get autoLoad(){return this._autoLoad}set disableLocalization(e){this._disableLocalization!==e&&(this._disableLocalization=e,this._onSetLocale(this._app.i18n.locale))}get disableLocalization(){return this._disableLocalization}_bindDefaultAsset(){const e=this._app.assets.get(this._defaultAsset);e?this._onDefaultAssetAdd(e):this._app.assets.once(`add:${this._defaultAsset}`,this._onDefaultAssetAdd,this)}_unbindDefaultAsset(){if(!this._defaultAsset)return;this._app.assets.off(`add:${this._defaultAsset}`,this._onDefaultAssetAdd,this);const e=this._app.assets.get(this._defaultAsset);e&&(e.off("add:localized",this._onLocaleAdd,this),e.off("remove:localized",this._onLocaleRemove,this),e.off("remove",this._onDefaultAssetRemove,this))}_onDefaultAssetAdd(e){this._defaultAsset===e.id&&(e.on("add:localized",this._onLocaleAdd,this),e.on("remove:localized",this._onLocaleRemove,this),e.once("remove",this._onDefaultAssetRemove,this))}_onDefaultAssetRemove(e){this._defaultAsset===e.id&&(e.off("add:localized",this._onLocaleAdd,this),e.off("remove:localized",this._onLocaleAdd,this),this._app.assets.once(`add:${this._defaultAsset}`,this._onDefaultAssetAdd,this))}_bindLocalizedAsset(){if(!this._autoLoad)return;const e=this._app.assets.get(this._localizedAsset);e&&(e.on("load",this._onLocalizedAssetLoad,this),e.on("change",this._onLocalizedAssetChange,this),e.on("remove",this._onLocalizedAssetRemove,this),e.resource?this._onLocalizedAssetLoad(e):this._app.assets.load(e))}_unbindLocalizedAsset(){const e=this._app.assets.get(this._localizedAsset);e&&(e.off("load",this._onLocalizedAssetLoad,this),e.off("change",this._onLocalizedAssetChange,this),e.off("remove",this._onLocalizedAssetRemove,this))}_onLocalizedAssetAdd(e){this._localizedAsset===e.id&&this._bindLocalizedAsset()}_onLocalizedAssetLoad(e){this.fire("load",e)}_onLocalizedAssetChange(e,t,s,i){this.fire("change",e,t,s,i)}_onLocalizedAssetRemove(e){this._localizedAsset===e.id&&(this.localizedAsset=this._defaultAsset),this.fire("remove",e)}_onLocaleAdd(e,t){this._app.i18n.locale===e&&this._onSetLocale(e)}_onLocaleRemove(e,t){this._app.i18n.locale===e&&this._onSetLocale(e)}_onSetLocale(e){if(!this._defaultAsset){this.localizedAsset=null;return}const t=this._app.assets.get(this._defaultAsset);if(!t||this._disableLocalization){this.localizedAsset=this._defaultAsset;return}const s=t.getLocalizedAssetId(e);if(!s){this.localizedAsset=this._defaultAsset;return}this.localizedAsset=s}destroy(){this.defaultAsset=null,this._app.i18n.off(fn.EVENT_CHANGE,this._onSetLocale,this),this.off()}}const Su="msdf",FN="bitmap",zl=0,oo=1,g_=2,Vw=3,v_=4,S_=5,y_=6,x_=7,$y=8,ON=`
11885\r\v\f`,BN=/[\w|/]/;class NN{constructor(e){this._symbols=e,this._index=0,this._last=0,this._cur=this._symbols.length>0?this._symbols[0]:null,this._buf=[],this._mode="text",this._error=null}read(){let e=this._read();for(;e===$y;)e=this._read();return e!==zl&&e!==oo&&(this._last=this._index),e}buf(){return this._buf}last(){return this._last}error(){return this._error}debugPrint(){const e=["EOF","ERROR","TEXT","OPEN_BRACKET","CLOSE_BRACKET","EQUALS","STRING","IDENTIFIER","WHITESPACE"];let t=this.read(),s="";for(;s+=`${(s.length>0?` 11886`:"")+e[t]} '${this.buf().join("")}'`,!(t===zl||t===oo);)t=this.read();return s}_read(){return this._buf=[],this._eof()?zl:this._mode==="text"?this._text():this._tag()}_text(){for(;;)switch(this._cur){case null:return this._buf.length>0?g_:zl;case"[":return this._mode="tag",this._buf.length>0?g_:this._tag();case"\\":this._next(),this._cur==="["?this._store():this._output("\\");break;default:this._store();break}}_tag(){switch(this._cur){case null:return this._error="unexpected end of input reading tag",oo;case"[":return this._store(),Vw;case"]":return this._store(),this._mode="text",v_;case"=":return this._store(),S_;case" ":case" ":case` 11887`:case"\r":case"\v":case"\f":return this._whitespace();case'"':return this._string();default:return this._isIdentifierSymbol(this._cur)?this._identifier():(this._error="unrecognized character",oo)}}_whitespace(){for(this._store();ON.indexOf(this._cur)!==-1;)this._store();return $y}_string(){for(this._next();;)switch(this._cur){case null:return this._error="unexpected end of input reading string",oo;case'"':return this._next(),y_;default:this._store();break}}_identifier(){for(this._store();this._cur!==null&&this._isIdentifierSymbol(this._cur);)this._store();return x_}_isIdentifierSymbol(e){return e.length===1&&e.match(BN)!==null}_eof(){return this._cur===null}_next(){return this._eof()||(this._index++,this._cur=this._index<this._symbols.length?this._symbols[this._index]:null),this._cur}_store(){return this._buf.push(this._cur),this._next()}_output(e){this._buf.push(e)}}class kN{constructor(e){this._scanner=new NN(e),this._error=null}parse(e,t){for(;;)switch(this._scanner.read()){case zl:return!0;case oo:return!1;case g_:Array.prototype.push.apply(e,this._scanner.buf());break;case Vw:if(!this._parseTag(e,t))return!1;break;default:return!1}}error(){return`Error evaluating markup at #${this._scanner.last().toString()} (${this._scanner.error()||this._error})`}_parseTag(e,t){let s=this._scanner.read();if(s!==x_)return this._error="expected identifier",!1;const i=this._scanner.buf().join("");if(i[0]==="/"){for(let a=t.length-1;a>=0;--a)if(i===`/${t[a].name}`&&t[a].end===null)return t[a].end=e.length,s=this._scanner.read(),s!==v_?(this._error="expected close bracket",!1):!0;return this._error="failed to find matching tag",!1}const r={name:i,value:null,attributes:{},start:e.length,end:null};if(s=this._scanner.read(),s===S_){if(s=this._scanner.read(),s!==y_)return this._error="expected string",!1;r.value=this._scanner.buf().join(""),s=this._scanner.read()}for(;;){switch(s){case v_:return t.push(r),!0;case x_:{const a=this._scanner.buf().join("");if(s=this._scanner.read(),s!==S_)return this._error="expected equals",!1;if(s=this._scanner.read(),s!==y_)return this._error="expected string",!1;const n=this._scanner.buf().join("");r.attributes[a]=n;break}default:return this._error="expected close bracket or identifier",!1}s=this._scanner.read()}}}function Gw(l,e){for(const t in e){if(!e.hasOwnProperty(t))continue;const s=e[t];s instanceof Object?(l.hasOwnProperty(t)||(l[t]={}),Gw(l[t],e[t])):l[t]=s}}function UN(l){if(l.length===0)return null;const e={};for(let t=0;t<l.length;++t){const s=l[t],i={};i[s.name]={value:s.value,attributes:s.attributes},Gw(e,i)}return e}function zN(l,e){if(l.length===0)return null;const t={};for(let h=0;h<l.length;++h){const d=l[h];t.hasOwnProperty(d.start)?t[d.start].open===null?t[d.start].open=[d]:t[d.start].open.push(d):t[d.start]={open:[d],close:null},t.hasOwnProperty(d.end)?t[d.end].close===null?t[d.end].close=[d]:t[d.end].close.push(d):t[d.end]={open:null,close:[d]}}let s=[];function i(h){s=s.filter(d=>h.find(u=>u===d)===void 0)}function r(h){for(let d=0;d<h.length;++d)s.push(h[d])}const a=Object.keys(t).sort((h,d)=>h-d),n=[];for(let h=0;h<a.length;++h){const d=t[a[h]];d.close!==null&&i(d.close),d.open!==null&&r(d.open),n.push({start:a[h],tags:UN(s)})}const o=[];let c=null;for(let h=0;h<n.length;++h){const d=n[h];for(;o.length<d.start;)o.push(c?c.tags:null);c=d}for(;o.length<e;)o.push(null);return o}function VN(l){const e=new kN(l),t=[],s=[];if(!e.parse(t,s))return console.warn(e.error()),{symbols:l,tags:null};const i=s.find(a=>a.end===null);if(i)return console.warn(`Markup error: found unclosed tag='${i.name}'`),{symbols:l,tags:null};const r=zN(s,t.length);return{symbols:t,tags:r}}class GN{static evaluate(e){return VN(e)}}class HN{constructor(){this.count=0,this.quad=0,this.lines={},this.positions=[],this.normals=[],this.uvs=[],this.colors=[],this.indices=[],this.outlines=[],this.shadows=[],this.meshInstance=null}}function WN(l,e){const t=new at(l);return t.setPositions(e.positions),t.setNormals(e.normals),t.setColors32(e.colors),t.setUvs(0,e.uvs),t.setIndices(e.indices),t.setVertexStream(ic,e.outlines,3,void 0,je,!1),t.setVertexStream(rc,e.shadows,3,void 0,je,!1),t.update(
11887),t}const Ky=/^[\r\n]$/,XN=/^[ \t]$/,Zy=/^[ \t\-]|\u200b$/,YN=/^[a-z0-9]$/i,Qy=/^[\u1100-\u11ff]|[\u3000-\u9fff\ua960-\ua97f]|[\uac00-\ud7ff]$/,jN=/^[ãããããããããã½ã¾ã¼ã¡ã£ã¥ã§ã©ãã£ã¥ã§ã®ãµã¶ããã
ããã£ãã
ããããã°ã±ã²ã³ã´ãµã¶ã·ã¸ã¹ãºã»ã¼ã½ã¾ã¿ã
ã»]$/,qN=["â","Ø","â","â","âª","â«","â¬","â","â®","â¦","â§","â¨","â©"],$N={width:0,height:0,xadvance:0,xoffset:0,yoffset:0},Jy=new Q,KN=new j,et=new Q;class ZN{constructor(e){this._element=e,this._system=e.system,this._entity=e.entity,this._text="",this._symbols=[],this._colorPalette=[],this._outlinePalette=[],this._shadowPalette=[],this._symbolColors=null,this._symbolOutlineParams=null,this._symbolShadowParams=null,this._i18nKey=null,this._fontAsset=new LN(this._system.app),this._fontAsset.disableLocalization=!0,this._fontAsset.on("load",this._onFontLoad,this),this._fontAsset.on("change",this._onFontChange,this),this._fontAsset.on("remove",this._onFontRemove,this),this._font=null,this._color=new Q(1,1,1,1),this._colorUniform=new Float32Array(3),this._spacing=1,this._fontSize=32,this._fontMinY=0,this._fontMaxY=0,this._originalFontSize=32,this._maxFontSize=32,this._minFontSize=8,this._autoFitWidth=!1,this._autoFitHeight=!1,this._maxLines=-1,this._lineHeight=32,this._scaledLineHeight=32,this._wrapLines=!1,this._drawOrder=0,this._alignment=new j(.5,.5),this._autoWidth=!0,this._autoHeight=!0,this.width=0,this.height=0,this._node=new He,this._model=new pa,this._model.graph=this._node,this._entity.addChild(this._node),this._meshInfo=[],this._material=null,this._aabbDirty=!0,this._aabb=new Le,this._noResize=!1,this._currentMaterialType=null,this._maskedMaterialSrc=null,this._rtlReorder=!1,this._unicodeConverter=!1,this._rtl=!1,this._outlineColor=new Q(0,0,0,1),this._outlineColorUniform=new Float32Array(4),this._outlineThicknessScale=.2,this._outlineThickness=0,this._shadowColor=new Q(0,0,0,1),this._shadowColorUniform=new Float32Array(4),this._shadowOffsetScale=.005,this._shadowOffset=new j(0,0),this._shadowOffsetUniform=new Float32Array(2),this._enableMarkup=!1,this._onScreenChange(this._element.screen),e.on("resize",this._onParentResize,this),e.on("set:screen",this._onScreenChange,this),e.on("screen:set:screenspace",this._onScreenSpaceChange,this),e.on("set:draworder",this._onDrawOrderChange,this),e.on("set:pivot",this._onPivotChange,this),this._system.app.i18n.on(fn.EVENT_CHANGE,this._onLocaleSet,this),this._system.app.i18n.on("data:add",this._onLocalizationData,this),this._system.app.i18n.on("data:remove",this._onLocalizationData,this),this._rangeStart=0,this._rangeEnd=0,!e._beingInitialized&&e.enabled&&e.entity.enabled&&this.onEnable()}destroy(){this._setMaterial(null),this._model&&(this._element.removeModelFromLayers(this._model),this._model.destroy(),this._model=null),this._fontAsset.destroy(),this.font=null,this._element.off("resize",this._onParentResize,this),this._element.off("set:screen",this._onScreenChange,this),this._element.off("screen:set:screenspace",this._onScreenSpaceChange,this),this._element.off("set:draworder",this._onDrawOrderChange,this),this._element.off("set:pivot",this._onPivotChange,this),this._system.app.i18n.off(fn.EVENT_CHANGE,this._onLocaleSet,this),this._system.app.i18n.off("data:add",this._onLocalizationData,this),this._system.app.i18n.off("data:remove",this._onLocalizationData,this)}_onParentResize(e,t){this._noResize||this._font&&this._updateText()}_onScreenChange(e){e?this._updateMaterial(e.screen.screenSpace):this._updateMaterial(!1)}_onScreenSpaceChange(e){this._updateMaterial(e)}_onDrawOrderChange(e){if(this._drawOrder=e,this._model)for(let t=0,s=this._model.meshInstances.length;t<s;t++)this._model.meshInstances[t].drawOrder=e}_onPivotChange(e){this._font&&this._updateText()}_onLocaleSet(e){if(this._i18nKey){if(this.fontAsset){const t=this._system.app.assets.get(this.fontAsset);(!t||!t.resource||t.resource!==this._font)&&(this.font=null)}this._resetLocalizedText()}}_onLocalizationData(e,t){this._i18nKey&&t[this._i18nKey]&&this._resetLocalizedText()}
11887_resetLocalizedText(){this._setText(this._system.app.i18n.getText(this._i18nKey))}_setText(e){if(this.unicodeConverter){const t=this._system.getUnicodeConverter();t?e=t(e):console.warn("Element created with unicodeConverter option but no unicodeConverter function registered")}this._text!==e&&(this._font&&this._updateText(e),this._text=e)}_updateText(e){let t;if(e===void 0&&(e=this._text),this._symbols=vd.getSymbols(e.normalize?e.normalize("NFC"):e),this._symbols.length===0&&(this._symbols=[" "]),this._enableMarkup){const d=GN.evaluate(this._symbols);this._symbols=d.symbols,t=d.tags||[]}if(this._rtlReorder){const d=this._system.app.systems.element.getRtlReorder();if(d){const u=d(this._symbols);this._rtl=u.rtl,this._symbols=u.mapping.map(function(f){return this._symbols[f]},this),t&&(t=u.mapping.map(f=>t[f]))}else console.warn("Element created with rtlReorder option but no rtlReorder function registered")}else this._rtl=!1;const s=(d,u)=>`${d.toString(!0).toLowerCase()}:${u.toFixed(2)}`,i=(d,u)=>`${d.toString(!0).toLowerCase()}:${u.x.toFixed(2)}:${u.y.toFixed(2)}`;if(t){const d={},u={},f={};this._colorPalette=[Math.round(this._color.r*255),Math.round(this._color.g*255),Math.round(this._color.b*255)],this._outlinePalette=[Math.round(this._outlineColor.r*255),Math.round(this._outlineColor.g*255),Math.round(this._outlineColor.b*255),Math.round(this._outlineColor.a*255),Math.round(this._outlineThickness*255)],this._shadowPalette=[Math.round(this._shadowColor.r*255),Math.round(this._shadowColor.g*255),Math.round(this._shadowColor.b*255),Math.round(this._shadowColor.a*255),Math.round(this._shadowOffset.x*127),Math.round(this._shadowOffset.y*127)],this._symbolColors=[],this._symbolOutlineParams=[],this._symbolShadowParams=[],d[this._color.toString(!1).toLowerCase()]=0,u[s(this._outlineColor,this._outlineThickness)]=0,f[i(this._shadowColor,this._shadowOffset)]=0;for(let p=0,m=this._symbols.length;p<m;++p){const _=t[p];let g=0;if(_&&_.color&&_.color.value){const y=_.color.value;if(y.length===7&&y[0]==="#"){const S=y.substring(1).toLowerCase();d.hasOwnProperty(S)?g=d[S]:/^[0-9a-f]{6}$/.test(S)&&(g=this._colorPalette.length/3,d[S]=g,this._colorPalette.push(parseInt(S.substring(0,2),16)),this._colorPalette.push(parseInt(S.substring(2,4),16)),this._colorPalette.push(parseInt(S.substring(4,6),16)))}}this._symbolColors.push(g);let v=0;if(_&&_.outline&&(_.outline.attributes.color||_.outline.attributes.thickness)){let y=_.outline.attributes.color?Jy.fromString(_.outline.attributes.color):this._outlineColor,S=Number(_.outline.attributes.thickness);(Number.isNaN(y.r)||Number.isNaN(y.g)||Number.isNaN(y.b)||Number.isNaN(y.a))&&(y=this._outlineColor),Number.isNaN(S)&&(S=this._outlineThickness);const T=s(y,S);u.hasOwnProperty(T)?v=u[T]:(v=this._outlinePalette.length/5,u[T]=v,this._outlinePalette.push(Math.round(y.r*255),Math.round(y.g*255),Math.round(y.b*255),Math.round(y.a*255),Math.round(S*255)))}this._symbolOutlineParams.push(v);let x=0;if(_&&_.shadow&&(_.shadow.attributes.color||_.shadow.attributes.offset||_.shadow.attributes.offsetX||_.shadow.attributes.offsetY)){let y=_.shadow.attributes.color?Jy.fromString(_.shadow.attributes.color):this._shadowColor;const S=Number(_.shadow.attributes.offset),T=Number(_.shadow.attributes.offsetX),w=Number(_.shadow.attributes.offsetY);(Number.isNaN(y.r)||Number.isNaN(y.g)||Number.isNaN(y.b)||Number.isNaN(y.a))&&(y=this._shadowColor);const C=KN.set(Number.isNaN(T)?Number.isNaN(S)?this._shadowOffset.x:S:T,Number.isNaN(w)?Number.isNaN(S)?this._shadowOffset.y:S:w),b=i(y,C);f.hasOwnProperty(b)?x=f[b]:(x=this._shadowPalette.length/6,f[b]=x,this._shadowPalette.push(Math.round(y.r*255),Math.round(y.g*255),Math.round(y.b*255),Math.round(y.a*255),Math.round(C.x*127),Math.round(C.y*127)))}this._symbolShadowParams.push(x)}}else this._colorPalette=[],this._symbolColors=null,this._symbolOutlineParams=null,this._symbolShadowParams=null;this._updateMaterialEmissive(),this._updateMaterialOutline(),this._updateMaterialShadow();const r=this._calculateCharsPerTexture();let a=!1;const n=this._element,o=n._isScreenSpace(),c=n._isScreenCulled(),h=function(d){return n.isVisibleForCamera(d)};for(let d=0,u=this._meshInfo.length;d<u;d++){const f=r[d]||0,p=this._meshInfo[d];if(p.count!==f){if(a||(n.removeModelFromLayers(this._model),a=!0),p.count=f,p.positions.length=p.normals.length=f*3*4,p.indices.length=f*3*2,p.uvs.length=f*2*4,p.colors.length=f*4*4,p.outlines.length=f*4*3,p.shadows.length=f*4*3,p.meshInstance&&this._removeMeshInstance(p.meshInstance),f===0){p.meshInstance=null;continue}for(let g=0;g<f;g++)p.indices[g*3*2+0]=g*4,p.indices[g*3*2+1]=g*4+1,p.indices[g*3*2+2]=g*4+3,p.indices[g*3*2+3]=g*4+2,p.indices[g*3*2+4]=g*4+3,p.indices[g*3*2+5]=g*4+1,p.normals[g*4*3+0]=0,p.normals[g*4*3+1]=0,p.normals[g*4*3+2]=-1,p.normals[g*4*3+3]=0,p.normals[g*4*3+4]=0,p.normals[g*4*3+5]=-1,p.normals[g*4*3+6]=0,p.normals[g*4*3+7]=0,p.normals[g*4*3+8]=-1,p.normals[g*4*3+9]=0,p.normals[g*4*3+10]=0,p.normals[g*4*3+11]=-1;
11887const m=WN(this._system.app.graphicsDevice,p),_=new Ne(m,this._material,this._node);if(_.name=`Text Element: ${this._entity.name}`,_.castShadow=!1,_.receiveShadow=!1,_.cull=!o,_.screenSpace=o,_.drawOrder=this._drawOrder,c&&(_.cull=!0,_.isVisibleFunc=h),this._setTextureParams(_,this._font.textures[d]),_.setParameter("material_emissive",this._colorUniform),_.setParameter("material_opacity",this._color.a),_.setParameter("font_sdfIntensity",this._font.intensity),_.setParameter("font_pxrange",this._getPxRange(this._font)),_.setParameter("font_textureWidth",this._font.data.info.maps[d].width),_.setParameter("outline_color",this._outlineColorUniform),_.setParameter("outline_thickness",this._outlineThicknessScale*this._outlineThickness),_.setParameter("shadow_color",this._shadowColorUniform),this._symbolShadowParams)this._shadowOffsetUniform[0]=0,this._shadowOffsetUniform[1]=0;else{const g=-this._font.data.info.maps[d].width/this._font.data.info.maps[d].height;this._shadowOffsetUniform[0]=this._shadowOffsetScale*this._shadowOffset.x,this._shadowOffsetUniform[1]=g*this._shadowOffsetScale*this._shadowOffset.y}_.setParameter("shadow_offset",this._shadowOffsetUniform),p.meshInstance=_,this._model.meshInstances.push(_)}}this._element.maskedBy&&this._element._setMaskedBy(this._element.maskedBy),a&&this._element.enabled&&this._entity.enabled&&this._element.addModelToLayers(this._model),this._updateMeshes(),this._rangeStart=0,this._rangeEnd=this._symbols.length,this._updateRenderRange()}_removeMeshInstance(e){e.destroy();const t=this._model.meshInstances.indexOf(e);t!==-1&&this._model.meshInstances.splice(t,1)}_setMaterial(e){if(this._material=e,this._model)for(let t=0,s=this._model.meshInstances.length;t<s;t++){const i=this._model.meshInstances[t];i.material=e}}_updateMaterial(e){const t=this._element,s=t._isScreenCulled(),i=function(a){return t.isVisibleForCamera(a)},r=this._font&&this._font.type===Su;if(this._material=this._system.getTextElementMaterial(e,r,this._enableMarkup),this._model)for(let a=0,n=this._model.meshInstances.length;a<n;a++){const o=this._model.meshInstances[a];o.cull=!e,o.material=this._material,o.screenSpace=e,s?(o.cull=!0,o.isVisibleFunc=i):o.isVisibleFunc=null}}_updateMaterialEmissive(){this._symbolColors?(this._colorUniform[0]=1,this._colorUniform[1]=1,this._colorUniform[2]=1):(et.linear(this._color),this._colorUniform[0]=et.r,this._colorUniform[1]=et.g,this._colorUniform[2]=et.b)}_updateMaterialOutline(){this._symbolOutlineParams?(this._outlineColorUniform[0]=0,this._outlineColorUniform[1]=0,this._outlineColorUniform[2]=0,this._outlineColorUniform[3]=1):(et.linear(this._outlineColor),this._outlineColorUniform[0]=et.r,this._outlineColorUniform[1]=et.g,this._outlineColorUniform[2]=et.b,this._outlineColorUniform[3]=et.a)}_updateMaterialShadow(){this._symbolOutlineParams?(this._shadowColorUniform[0]=0,this._shadowColorUniform[1]=0,this._shadowColorUniform[2]=0,this._shadowColorUniform[3]=0):(et.linear(this._shadowColor),this._shadowColorUniform[0]=et.r,this._shadowColorUniform[1]=et.g,this._shadowColorUniform[2]=et.b,this._shadowColorUniform[3]=et.a)}_isWordBoundary(e){return Zy.test(e)}_isValidNextChar(e){return e!==null&&!jN.test(e)}_isNextCJKBoundary(e,t){return Qy.test(e)&&(Zy.test(t)||YN.test(t))}_isNextCJKWholeWord(e){return Qy.test(e)}_updateMeshes(){const e=this._font.data,t=this,s=Math.min(this._minFontSize,this._maxFontSize),i=this._maxFontSize,r=this._shouldAutoFit();r&&(this._fontSize=this._maxFontSize);const a=32,n=this._symbols.length;let o=0,c=0,h=0,d=0,u=1,f=0,p=0,m=0,_=0,g=0,v=0;const x=Math.abs(this._element.anchor.x-this._element.anchor.z)>=1e-4;let y=this._element.calculatedWidth;(this.autoWidth&&!x||!this._wrapLines)&&(y=Number.POSITIVE_INFINITY);let S=0,T=0,w,C,b,I;function P(A,M,R){t._lineWidths.push(Math.abs(R));const F=m>M?M+1:m,U=m>M?m+1:M,B=A.slice(F,U);if(v){let z=B.length;for(;z--&&v>0;)Ky.test(B[z])&&(B.splice(z,1),v--)}t._lineContents.push(B.join("")),o=0,c-=t._scaledLineHeight,u++,_=0,g=0,v=0,f=0,m=M}let L=!0;for(;L;){L=!1,r?this._scaledLineHeight=this._lineHeight*this._fontSize/(this._maxFontSize||1e-4):this._scaledLineHeight=this._lineHeight,this.width=0,this.height=0,this._lineWidths=[],this._lineContents=[],o=0,c=0,h=0,d=0,u=1,f=0,p=0,m=0,_=0,g=0,v=0;const A=this._fontSize/a;S=this._fontMinY*A,T=this._fontMaxY*A;for(let te=0;te<this._meshInfo.length;te++)this._meshInfo[te].quad=0,this._meshInfo[te].lines={};let M=255,R=255,F=255,U=255+255*256,B=255+255*256,z=0,$=255+255*256,K=255+255*256,Y=127+127*256;for(let te=0;te<n;te++){if(w=this._symbols[te],I=te+1>=n?null:this._symbols[te+1],Ky.test(w)){v++,(!this._wrapLines||this._maxLines<0||u<this._maxLines)&&
11887(P(this._symbols,te,d),p=te+1,m=te+1);continue}let _e=0,Ae=0,we=0,$e=1,Ye,Ee;if(C=e.chars[w],!C)if(qN.indexOf(w)!==-1)C=$N;else if(e.chars[" "])C=e.chars[" "];else for(const Ue in e.chars){C=e.chars[Ue];break}if(C){let Ue=0;if(g>0){const Lr=this._font.data.kerning;if(Lr){const ya=Lr[vd.getCodePoint(this._symbols[te-1])||0];ya&&(Ue=ya[vd.getCodePoint(this._symbols[te])||0]||0)}}Ye=C.scale||1,Ee=(C.width+C.height)/2,$e=A*Ee/Ye,we=(C.xadvance+Ue)*A,_e=(C.xoffset-Ue)*A,Ae=C.yoffset*A}else console.error(`Couldn't substitute missing character: '${w}'`);const Pe=XN.test(w),ke=C&&C.map||0,ps=-this._font.data.info.maps[ke].width/this._font.data.info.maps[ke].height,se=this._meshInfo[ke],Tn=o+this._spacing*we;if(Tn>y&&g>0&&!Pe&&(this._maxLines<0||u<this._maxLines))if(_===0)p=te,P(this._symbols,te,d);else{const Ue=Math.max(te-p,0);if(this._meshInfo.length<=1)se.lines[u-1]-=Ue,se.quad-=Ue;else{const Lr=p,ya=te;for(let xa=Lr;xa<ya;xa++){const th=this._symbols[xa],Ta=e.chars[th],wn=this._meshInfo[Ta&&Ta.map||0];wn.lines[u-1]-=1,wn.quad-=1}}te-=Ue+1,P(this._symbols,p,f);continue}b=se.quad,se.lines[u-1]=b;let bs=o-_e,Mr=bs+$e;const Sa=c-Ae,Rr=Sa+$e;if(this._rtl){const Ue=$e-_e-this._spacing*we-_e;bs-=Ue,Mr-=Ue}se.positions[b*4*3+0]=bs,se.positions[b*4*3+1]=Sa,se.positions[b*4*3+2]=h,se.positions[b*4*3+3]=Mr,se.positions[b*4*3+4]=Sa,se.positions[b*4*3+5]=h,se.positions[b*4*3+6]=Mr,se.positions[b*4*3+7]=Rr,se.positions[b*4*3+8]=h,se.positions[b*4*3+9]=bs,se.positions[b*4*3+10]=Rr,se.positions[b*4*3+11]=h,this.width=Math.max(this.width,Tn);let As;if(this._shouldAutoFitWidth()&&this.width>this._element.calculatedWidth&&(As=Math.floor(this._element.fontSize*this._element.calculatedWidth/(this.width||1e-4)),As=H.clamp(As,s,i),As!==this._element.fontSize)){this._fontSize=As,L=!0;break}if(this.height=Math.max(this.height,T-(c+S)),this._shouldAutoFitHeight()&&this.height>this._element.calculatedHeight&&(As=H.clamp(this._fontSize-1,s,i),As!==this._element.fontSize)){this._fontSize=As,L=!0;break}o+=this._spacing*we,Pe||(d=o),(this._isWordBoundary(w)||this._isValidNextChar(I)&&(this._isNextCJKBoundary(w,I)||this._isNextCJKWholeWord(I)))&&(_++,f=d,p=te+1),g++;const ms=this._getUv(w);if(se.uvs[b*4*2+0]=ms[0],se.uvs[b*4*2+1]=1-ms[1],se.uvs[b*4*2+2]=ms[2],se.uvs[b*4*2+3]=1-ms[1],se.uvs[b*4*2+4]=ms[2],se.uvs[b*4*2+5]=1-ms[3],se.uvs[b*4*2+6]=ms[0],se.uvs[b*4*2+7]=1-ms[3],this._symbolColors){const Ue=this._symbolColors[te]*3;M=this._colorPalette[Ue],R=this._colorPalette[Ue+1],F=this._colorPalette[Ue+2]}if(se.colors[b*4*4+0]=M,se.colors[b*4*4+1]=R,se.colors[b*4*4+2]=F,se.colors[b*4*4+3]=255,se.colors[b*4*4+4]=M,se.colors[b*4*4+5]=R,se.colors[b*4*4+6]=F,se.colors[b*4*4+7]=255,se.colors[b*4*4+8]=M,se.colors[b*4*4+9]=R,se.colors[b*4*4+10]=F,se.colors[b*4*4+11]=255,se.colors[b*4*4+12]=M,se.colors[b*4*4+13]=R,se.colors[b*4*4+14]=F,se.colors[b*4*4+15]=255,this._symbolOutlineParams){const Ue=this._symbolOutlineParams[te]*5;U=this._outlinePalette[Ue]+this._outlinePalette[Ue+1]*256,B=this._outlinePalette[Ue+2]+this._outlinePalette[Ue+3]*256,z=this._outlinePalette[Ue+4]}if(se.outlines[b*4*3+0]=U,se.outlines[b*4*3+1]=B,se.outlines[b*4*3+2]=z,se.outlines[b*4*3+3]=U,se.outlines[b*4*3+4]=B,se.outlines[b*4*3+5]=z,se.outlines[b*4*3+6]=U,se.outlines[b*4*3+7]=B,se.outlines[b*4*3+8]=z,se.outlines[b*4*3+9]=U,se.outlines[b*4*3+10]=B,se.outlines[b*4*3+11]=z,this._symbolShadowParams){const Ue=this._symbolShadowParams[te]*6;$=this._shadowPalette[Ue]+this._shadowPalette[Ue+1]*256,K=this._shadowPalette[Ue+2]+this._shadowPalette[Ue+3]*256,Y=this._shadowPalette[Ue+4]+127+Math.round(ps*this._shadowPalette[Ue+5]+127)*256}se.shadows[b*4*3+0]=$,se.shadows[b*4*3+1]=K,se.shadows[b*4*3+2]=Y,se.shadows[b*4*3+3]=$,se.shadows[b*4*3+4]=K,se.shadows[b*4*3+5]=Y,se.shadows[b*4*3+6]=$,se.shadows[b*4*3+7]=K,se.shadows[b*4*3+8]=Y,se.shadows[b*4*3+9]=$,se.shadows[b*4*3+10]=K,se.shadows[b*4*3+11]=Y,se.quad++}L||m<n&&P(this._symbols,n,o)}this._noResize=!0,this.autoWidth=this._autoWidth,this.autoHeight=this._autoHeight,this._noResize=!1;const O=this._element.pivot.x,D=this._element.pivot.y,N=this._alignment.x,k=this._alignment.y;for(let A=0;A<this._meshInfo.length;A++){if(this._meshInfo[A].count===0)continue;let M=0;for(const B in this._meshInfo[A].lines){const z=this._meshInfo[A].lines[B],$=this._lineWidths[parseInt(B,10)],K=-O*this._element.calculatedWidth+N*(this._element.calculatedWidth-$)*(this._rtl?-1:1),Y=(1-D)*this._element.calculatedHeight-T-(1-k)*(this._element.calculatedHeight-this.height);for(let te=M;te<=z;te++)this._meshInfo[A].positions[te*4*3]+=K,this._meshInfo[A].positions[te*4*3+3]+=K,this._meshInfo[A].positions[te*4*3+6]+=K,this._meshInfo[A].positions[te*4*3+9]+=K,this._meshInfo[A].positions[te*4*3+1]+=Y,this._meshInfo[A].positions[te*4*3+4]+=Y,this._meshInfo[A].positions[te*4*3+7]+=Y,this._meshInfo[A].positions[te*4*3+10]+=Y;if(this._rtl)for(let te=M;te<=z;te++){const J=te*4*3;for(let we=0;we<4;++we)this._meshInfo[A].positions[J+we*3]=this._element.calculatedWidth-this._meshInfo[A].positions[J+we*3]+K*2;const _e=this._meshInfo[A].positions[J+3],Ae=this._meshInfo[A].positions[J+6];this._meshInfo[A].positions[J+3]=this._meshInfo[A].positions[J+0],this._meshInfo[A].positions[J+6]=this._meshInfo[A].positions[J+9],this._meshInfo[A].positions[J+0]=_e,this._meshInfo[A].positions[J+9]=Ae}M=z+1}
11887const R=this._meshInfo[A].count*4,F=this._meshInfo[A].quad*4,U=new jl(this._meshInfo[A].meshInstance.mesh.vertexBuffer);for(let B=0;B<R;B++)B>=F?(U.element[Ie].set(0,0,0),U.element[Zs].set(0,0),U.element[ns].set(0,0,0,0),U.element[ic].set(0,0,0,0),U.element[rc].set(0,0,0,0)):(U.element[Ie].set(this._meshInfo[A].positions[B*3+0],this._meshInfo[A].positions[B*3+1],this._meshInfo[A].positions[B*3+2]),U.element[Zs].set(this._meshInfo[A].uvs[B*2+0],this._meshInfo[A].uvs[B*2+1]),U.element[ns].set(this._meshInfo[A].colors[B*4+0],this._meshInfo[A].colors[B*4+1],this._meshInfo[A].colors[B*4+2],this._meshInfo[A].colors[B*4+3]),U.element[ic].set(this._meshInfo[A].outlines[B*3+0],this._meshInfo[A].outlines[B*3+1],this._meshInfo[A].outlines[B*3+2]),U.element[rc].set(this._meshInfo[A].shadows[B*3+0],this._meshInfo[A].shadows[B*3+1],this._meshInfo[A].shadows[B*3+2])),U.next();U.end(),this._meshInfo[A].meshInstance.mesh.aabb.compute(this._meshInfo[A].positions),this._meshInfo[A].meshInstance._aabbVer=-1}this._aabbDirty=!0}_onFontRender(){this.font=this._font}_onFontLoad(e){this.font!==e.resource&&(this.font=e.resource)}_onFontChange(e,t,s,i){if(t==="data"){this._font.data=s;const r=this._font.data.info.maps.length;for(let a=0;a<r;a++){if(!this._meshInfo[a])continue;const n=this._meshInfo[a].meshInstance;n&&(n.setParameter("font_sdfIntensity",this._font.intensity),n.setParameter("font_pxrange",this._getPxRange(this._font)),n.setParameter("font_textureWidth",this._font.data.info.maps[a].width))}}}_onFontRemove(e){}_setTextureParams(e,t){this._font&&(this._font.type===Su?(e.deleteParameter("texture_emissiveMap"),e.deleteParameter("texture_opacityMap"),e.setParameter("texture_msdfMap",t)):this._font.type===FN&&(e.deleteParameter("texture_msdfMap"),e.setParameter("texture_emissiveMap",t),e.setParameter("texture_opacityMap",t)))}_getPxRange(e){const t=Object.keys(this._font.data.chars);for(let s=0;s<t.length;s++){const i=this._font.data.chars[t[s]];if(i.range)return(i.scale||1)*i.range}return 2}_getUv(e){const t=this._font.data;if(!t.chars[e])return t.chars[" "]?this._getUv(" "):[0,0,0,0];const s=t.chars[e].map,i=t.info.maps[s].width,r=t.info.maps[s].height,a=t.chars[e].x,n=t.chars[e].y,o=a,c=n,h=a+t.chars[e].width,d=n-t.chars[e].height,u=1-t.chars[e].height/r;return[o/i,u-c/r,h/i,u-d/r]}onEnable(){this._fontAsset.autoLoad=!0,this._model&&this._element.addModelToLayers(this._model)}onDisable(){this._fontAsset.autoLoad=!1,this._model&&this._element.removeModelFromLayers(this._model)}_setStencil(e){if(this._model){const t=this._model.meshInstances;for(let s=0;s<t.length;s++)t[s].stencilFront=e,t[s].stencilBack=e}}_shouldAutoFitWidth(){return this._autoFitWidth&&!this._autoWidth}_shouldAutoFitHeight(){return this._autoFitHeight&&!this._autoHeight}_shouldAutoFit(){return this._autoFitWidth&&!this._autoWidth||this._autoFitHeight&&!this._autoHeight}_calculateCharsPerTexture(e){const t={};e===void 0&&(e=this._symbols.length);for(let s=0,i=e;s<i;s++){const r=this._symbols[s];let a=this._font.data.chars[r];a||(a=this._font.data.chars[" "],a||(a=this._font.data.chars[Object.keys(this._font.data.chars)[0]]));const n=a.map;t[n]?t[n]++:t[n]=1}return t}_updateRenderRange(){const e=this._rangeStart===0?0:this._calculateCharsPerTexture(this._rangeStart),t=this._rangeEnd===0?0:this._calculateCharsPerTexture(this._rangeEnd);for(let s=0,i=this._meshInfo.length;s<i;s++){const r=e[s]||0,a=t[s]||0,n=this._meshInfo[s].meshInstance;if(n){const o=n.mesh;o&&(o.primitive[0].base=r*3*2,o.primitive[0].count=(a-r)*3*2)}}}set text(e){this._i18nKey=null;const t=e!=null&&e.toString()||"";this._setText(t)}get text(){return this._text}set key(e){const t=e!==null?e.toString():null;this._i18nKey!==t&&(this._i18nKey=t,t?(this._fontAsset.disableLocalization=!1,this._resetLocalizedText()):this._fontAsset.disableLocalization=!0)}get key(){return this._i18nKey}set color(e){const t=e.r,s=e.g,i=e.b;if(!(this._color.r===t&&this._color.g===s&&this._color.b===i)&&(this._color.r=t,this._color.g=s,this._color.b=i,!!this._model)){if(this._symbolColors)this._font&&this._updateText();else{et.linear(this._color),this._colorUniform[0]=et.r,this._colorUniform[1]=et.g,this._colorUniform[2]=et.b;for(let r=0,a=this._model.meshInstances.length;r<a;r++)this._model.meshInstances[r].setParameter("material_emissive",this._colorUniform)}this._element&&this._element.fire("set:color",this._color)}}get color(){return this._color}set opacity(e){if(this._color.a!==e&&(this._color.a=e,this._model))for(let t=0,s=this._model.meshInstances.length;t<s;t++)this._model.meshInstances[t].setParameter("material_opacity",e);this._element&&this._element.fire("set:opacity",e)}get opacity(){return this._color.a}set lineHeight(e){const t=this._lineHeight;this._lineHeight=e,this._scaledLineHeight=e,t!==e&&this._font&&this._updateText()}get lineHeight(){return this._lineHeight}set wrapLines(e){const t=this._wrapLines;this._wrapLines=e,t!==e&&this._font&&this._updateText()}get wrapLines(){return this._wrapLines}get lines(){return this._lineContents}set spacing(e){const t=this._spacing;this._spacing=e,t!==e&&this._font&&this._updateText()}get spacing(){return this._spacing}set fontSize(e){const t=this._fontSize;this._fontSize=e,this._originalFontSize=e,t!==e&&this._font&&this._updateText()}get fontSize(){return this._fontSize}set fontAsset(e){this._fontAsset.defaultAsset=e}get fontAsset(){return this._fontAsset.localizedAsset}set font(e){let t;if(this._font&&(t=this._font.type,this._font.off&&this._font.off("render",this._onFontRender,this)),this._font=e,this._fontMinY=0,this._fontMaxY=0,!e)return;const s=this._font.data;for(const r in s.chars){const a=s.chars[r];a.bounds&&(this._fontMinY=Math.min(this._fontMinY,a.bounds[1]),this._fontMaxY=Math.max(this._fontMaxY,a.bounds[3]))}if(this._font.on&&this._font.on("render",this._onFontRender,this),this._fontAsset.localizedAsset&&this._system.a
11887pp.assets.get(this._fontAsset.localizedAsset).resource!==this._font&&(this._fontAsset.defaultAsset=null),e.type!==t){const r=this._element._isScreenSpace();this._updateMaterial(r)}for(let r=0,a=this._font.textures.length;r<a;r++)if(!this._meshInfo[r])this._meshInfo[r]=new HN;else{const n=this._meshInfo[r].meshInstance;n&&(n.setParameter("font_sdfIntensity",this._font.intensity),n.setParameter("font_pxrange",this._getPxRange(this._font)),n.setParameter("font_textureWidth",this._font.data.info.maps[r].width),this._setTextureParams(n,this._font.textures[r]))}let i=!1;for(let r=this._font.textures.length;r<this._meshInfo.length;r++)this._meshInfo[r].meshInstance&&(i||(this._element.removeModelFromLayers(this._model),i=!0),this._removeMeshInstance(this._meshInfo[r].meshInstance));this._meshInfo.length>this._font.textures.length&&(this._meshInfo.length=this._font.textures.length),this._updateText()}get font(){return this._font}set alignment(e){e instanceof j?this._alignment.set(e.x,e.y):this._alignment.set(e[0],e[1]),this._font&&this._updateText()}get alignment(){return this._alignment}set autoWidth(e){const t=this._autoWidth;if(this._autoWidth=e,e&&Math.abs(this._element.anchor.x-this._element.anchor.z)<1e-4&&(this._element.width=this.width),t!==e){const s=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize;s!==this._fontSize&&(this._fontSize=s,this._font&&this._updateText())}}get autoWidth(){return this._autoWidth}set autoHeight(e){const t=this._autoHeight;if(this._autoHeight=e,e&&Math.abs(this._element.anchor.y-this._element.anchor.w)<1e-4&&(this._element.height=this.height),t!==e){const s=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize;s!==this._fontSize&&(this._fontSize=s,this._font&&this._updateText())}}get autoHeight(){return this._autoHeight}set rtlReorder(e){this._rtlReorder!==e&&(this._rtlReorder=e,this._font&&this._updateText())}get rtlReorder(){return this._rtlReorder}set unicodeConverter(e){this._unicodeConverter!==e&&(this._unicodeConverter=e,this._setText(this._text))}get unicodeConverter(){return this._unicodeConverter}get aabb(){if(this._aabbDirty){let e=!1;for(let t=0;t<this._meshInfo.length;t++)this._meshInfo[t].meshInstance&&(e?this._aabb.add(this._meshInfo[t].meshInstance.aabb):(this._aabb.copy(this._meshInfo[t].meshInstance.aabb),e=!0));this._aabbDirty=!1}return this._aabb}set outlineColor(e){const t=e instanceof Q?e.r:e[0],s=e instanceof Q?e.g:e[1],i=e instanceof Q?e.b:e[2],r=e instanceof Q?e.a:e[3];if(!(this._outlineColor.r===t&&this._outlineColor.g===s&&this._outlineColor.b===i&&this._outlineColor.a===r)&&(this._outlineColor.r=t,this._outlineColor.g=s,this._outlineColor.b=i,this._outlineColor.a=r,!!this._model)){if(this._symbolOutlineParams)this._font&&this._updateText();else{et.linear(this._outlineColor),this._outlineColorUniform[0]=et.r,this._outlineColorUniform[1]=et.g,this._outlineColorUniform[2]=et.b,this._outlineColorUniform[3]=et.a;for(let a=0,n=this._model.meshInstances.length;a<n;a++)this._model.meshInstances[a].setParameter("outline_color",this._outlineColorUniform)}this._element&&this._element.fire("set:outline",this._color)}}get outlineColor(){return this._outlineColor}set outlineThickness(e){const t=this._outlineThickness;if(this._outlineThickness=e,t!==e&&this._font){if(!this._model)return;if(this._symbolOutlineParams)this._font&&this._updateText();else for(let s=0,i=this._model.meshInstances.length;s<i;s++)this._model.meshInstances[s].setParameter("outline_thickness",this._outlineThicknessScale*this._outlineThickness)}}get outlineThickness(){return this._outlineThickness}set shadowColor(e){const t=e instanceof Q?e.r:e[0],s=e instanceof Q?e.g:e[1],i=e instanceof Q?e.b:e[2],r=e instanceof Q?e.a:e[3];if(!(this._shadowColor.r===t&&this._shadowColor.g===s&&this._shadowColor.b===i&&this._shadowColor.a===r)&&(this._shadowColor.r=t,this._shadowColor.g=s,this._shadowColor.b=i,this._shadowColor.a=r,!!this._model))if(this._symbolShadowParams)this._font&&this._updateText();else{et.linear(this._shadowColor),this._shadowColorUniform[0]=et.r,this._shadowColorUniform[1]=et.g,this._shadowColorUniform[2]=et.b,this._shadowColorUniform[3]=et.a;for(let a=0,n=this._model.meshInstances.length;a<n;a++)this._model.meshInstances[a].setParameter("shadow_color",this._shadowColorUniform)}}get shadowColor(){return this._shadowColor}set shadowOffset(e){const t=e instanceof j?e.x:e[0],s=e instanceof j?e.y:e[1];
11887if(!(this._shadowOffset.x===t&&this._shadowOffset.y===s)&&(this._shadowOffset.set(t,s),this._font&&this._model))if(this._symbolShadowParams)this._updateText();else for(let i=0,r=this._model.meshInstances.length;i<r;i++){const a=-this._font.data.info.maps[i].width/this._font.data.info.maps[i].height;this._shadowOffsetUniform[0]=this._shadowOffsetScale*this._shadowOffset.x,this._shadowOffsetUniform[1]=a*this._shadowOffsetScale*this._shadowOffset.y,this._model.meshInstances[i].setParameter("shadow_offset",this._shadowOffsetUniform)}}get shadowOffset(){return this._shadowOffset}set minFontSize(e){this._minFontSize!==e&&(this._minFontSize=e,this.font&&this._shouldAutoFit()&&this._updateText())}get minFontSize(){return this._minFontSize}set maxFontSize(e){this._maxFontSize!==e&&(this._maxFontSize=e,this.font&&this._shouldAutoFit()&&this._updateText())}get maxFontSize(){return this._maxFontSize}set autoFitWidth(e){this._autoFitWidth!==e&&(this._autoFitWidth=e,this._fontSize=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize,this.font&&this._updateText())}get autoFitWidth(){return this._autoFitWidth}set autoFitHeight(e){this._autoFitHeight!==e&&(this._autoFitHeight=e,this._fontSize=this._shouldAutoFit()?this._maxFontSize:this._originalFontSize,this.font&&this._updateText())}get autoFitHeight(){return this._autoFitHeight}set maxLines(e){this._maxLines!==e&&(e===null&&this._maxLines===-1||(this._maxLines=e===null?-1:e,this.font&&this._wrapLines&&this._updateText()))}get maxLines(){return this._maxLines}set enableMarkup(e){if(e=!!e,this._enableMarkup===e)return;this._enableMarkup=e,this.font&&this._updateText();const t=this._element._isScreenSpace();this._updateMaterial(t)}get enableMarkup(){return this._enableMarkup}get symbols(){return this._symbols}get symbolColors(){return this._symbolColors===null?null:this._symbolColors.map(function(e){return this._colorPalette.slice(e*3,e*3+3)},this)}get symbolOutlineParams(){return this._symbolOutlineParams===null?null:this._symbolOutlineParams.map(function(e){return this._outlinePalette.slice(e*5,e*5+5)},this)}get symbolShadowParams(){return this._symbolShadowParams===null?null:this._symbolShadowParams.map(function(e){return this._shadowPalette.slice(e*6,e*6+6)},this)}get rtl(){return this._rtl}set rangeStart(e){e=Math.max(0,Math.min(e,this._symbols.length)),e!==this._rangeStart&&(this._rangeStart=e,this._updateRenderRange())}get rangeStart(){return this._rangeStart}set rangeEnd(e){e=Math.max(this._rangeStart,Math.min(e,this._symbols.length)),e!==this._rangeEnd&&(this._rangeEnd=e,this._updateRenderRange())}get rangeEnd(){return this._rangeEnd}}const Qp=new E,e0=new Z,er=new E,QN=new E,Hs=new Z,td=new Z,sd=new Z,jn=new Z;class Hw extends ye{static EVENT_MOUSEDOWN="mousedown";static EVENT_MOUSEUP="mouseup";static EVENT_MOUSEENTER="mouseenter";static EVENT_MOUSELEAVE="mouseleave";static EVENT_MOUSEMOVE="mousemove";static EVENT_MOUSEWHEEL="mousewheel";static EVENT_CLICK="click";static EVENT_TOUCHSTART="touchstart";static EVENT_TOUCHEND="touchend";static EVENT_TOUCHMOVE="touchmove";static EVENT_TOUCHCANCEL="touchcancel";_evtLayersChanged=null;_evtLayerAdded=null;_evtLayerRemoved=null;constructor(e,t){super(e,t),this._beingInitialized=!1,this._anchor=new ie,this._localAnchor=new ie,this._pivot=new j,this._width=this._calculatedWidth=32,this._height=this._calculatedHeight=32,this._margin=new ie(0,0,-32,-32),this._modelTransform=new Z,this._screenToWorld=new Z,this._anchorTransform=new Z,this._anchorDirty=!0,this._parentWorldTransform=new Z,this._screenTransform=new Z,this._screenCorners=[new E,new E,new E,new E],this._canvasCorners=[new j,new j,new j,new j],this._worldCorners=[new E,new E,new E,new E],this._cornersDirty=!0,this._canvasCornersDirty=!0,this._worldCornersDirty=!0,this.entity.on("insert",this._onInsert,this),this._patch(),this.screen=null,this._type=Rd,this._image=null,this._text=null,this._group=null,this._drawOrder=0,this._fitMode=Ld,this._useInput=!1,this._layers=[Ef],this._addedModels=[],this._batchGroupId=-1,this._offsetReadAt=0,this._maskOffset=.5,this._maskedBy=null}set enabled(e){const t=this.data,s=t.enabled;t.enabled=e,this.fire("set","enabled",s,e)}get enabled(){return this.data.enabled}get _absLeft(){return this._localAnchor.x+this._margin.x}get _absRight(){return this._localAnchor.z-this._margin.z}get _absTop(){return this._localAnchor.w-this._margin.w}get _absBottom(){return this._localAnchor.y+this._margin.y}get _hasSplitAnchorsX(){return Math.abs(this._anchor.x-this._anchor.z)>.001}get _hasSplitAnchorsY(){return Math.abs(this._anchor.y-this._anchor.w)>.001}get aabb(){return this._image?this._image.aabb:this._text?this._text.aabb:null}
11887set anchor(e){e instanceof ie?this._anchor.copy(e):this._anchor.set(...e),!this.entity._parent&&!this.screen?this._calculateLocalAnchors():this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY),this._anchorDirty=!0,this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:anchor",this._anchor)}get anchor(){return this._anchor}set batchGroupId(e){this._batchGroupId!==e&&(this.entity.enabled&&this._batchGroupId>=0&&this.system.app.batcher?.remove(Zt.ELEMENT,this.batchGroupId,this.entity),this.entity.enabled&&e>=0&&this.system.app.batcher?.insert(Zt.ELEMENT,e,this.entity),e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&(this._image&&this._image._renderable.model?this.addModelToLayers(this._image._renderable.model):this._text&&this._text._model&&this.addModelToLayers(this._text._model)),this._batchGroupId=e)}get batchGroupId(){return this._batchGroupId}set bottom(e){this._margin.y=e;const t=this.entity.getLocalPosition(),s=this._absTop,i=this._localAnchor.y+e;this._setHeight(s-i),t.y=e+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(t)}get bottom(){return this._margin.y}set calculatedWidth(e){this._setCalculatedWidth(e,!0)}get calculatedWidth(){return this._calculatedWidth}set calculatedHeight(e){this._setCalculatedHeight(e,!0)}get calculatedHeight(){return this._calculatedHeight}get canvasCorners(){if(!this._canvasCornersDirty||!this.screen||!this.screen.screen.screenSpace)return this._canvasCorners;const e=this.system.app.graphicsDevice,t=this.screenCorners,s=e.canvas.clientWidth/e.width,i=e.canvas.clientHeight/e.height;for(let r=0;r<4;r++)this._canvasCorners[r].set(t[r].x*s,(e.height-t[r].y)*i);return this._canvasCornersDirty=!1,this._canvasCorners}set drawOrder(e){let t=0;this.screen&&(t=this.screen.screen.priority),e>16777215&&(e=16777215),this._drawOrder=(t<<24)+e,this.fire("set:draworder",this._drawOrder)}get drawOrder(){return this._drawOrder}set height(e){this._height=e,this._hasSplitAnchorsY||this._setCalculatedHeight(e,!0),this.fire("set:height",this._height)}get height(){return this._height}set layers(e){if(this._addedModels.length)for(let t=0;t<this._layers.length;t++){const s=this.system.app.scene.layers.getLayerById(this._layers[t]);if(s)for(let i=0;i<this._addedModels.length;i++)s.removeMeshInstances(this._addedModels[i].meshInstances)}if(this._layers=e,!(!this.enabled||!this.entity.enabled||!this._addedModels.length))for(let t=0;t<this._layers.length;t++){const s=this.system.app.scene.layers.getLayerById(this._layers[t]);if(s)for(let i=0;i<this._addedModels.length;i++)s.addMeshInstances(this._addedModels[i].meshInstances)}}get layers(){return this._layers}set left(e){this._margin.x=e;const t=this.entity.getLocalPosition(),s=this._absRight,i=this._localAnchor.x+e;this._setWidth(s-i),t.x=e+this._calculatedWidth*this._pivot.x,this.entity.setLocalPosition(t)}get left(){return this._margin.x}set margin(e){this._margin.copy(e),this._calculateSize(!0,!0),this.fire("set:margin",this._margin)}get margin(){return this._margin}get maskedBy(){return this._maskedBy}set pivot(e){const{pivot:t,margin:s}=this,i=t.x,r=t.y;e instanceof j?t.copy(e):t.set(...e);const a=s.x+s.z,n=t.x-i;s.x+=a*n,s.z-=a*n;const o=s.y+s.w,c=t.y-r;s.y+=o*c,s.w-=o*c,this._anchorDirty=!0,this._cornersDirty=!0,this._worldCornersDirty=!0,this._calculateSize(!1,!1),this._flagChildrenAsDirty(),this.fire("set:pivot",t)}get pivot(){return this._pivot}set right(e){this._margin.z=e;const t=this.entity.getLocalPosition(),s=this._absLeft,i=this._localAnchor.z-e;this._setWidth(i-s),t.x=this._localAnchor.z-this._localAnchor.x-e-this._calculatedWidth*(1-this._pivot.x),this.entity.setLocalPosition(t)}get right(){return this._margin.z}get screenCorners(){if(!this._cornersDirty||!this.screen)return this._screenCorners;const e=this.entity.parent&&this.entity.parent.element&&this.entity.parent.element.screenCorners[0];this._screenCorners[0].set(this._absLeft,this._absBottom,0),this._screenCorners[1].set(this._absRight,this._absBottom,0),this._screenCorners[2].set(this._absRight,this._absTop,0),this._screenCorners[3].set(this._absLeft,this._absTop,0);const t=this.screen.screen.screenSpace;for(let s=0;s<4;s++)this._screenTransform.transformPoint(this._screenCorners[s],this._screenCorners[s]),t&&this._screenCorners[s].mulScalar(this.screen.screen.scale),e&&this._screenCorners[s].add(e);return this._cornersDirty=!1,this._canvasCornersDirty=!0,this._worldCornersDirty=!0,this._screenCorners}
11887get textWidth(){return this._text?this._text.width:0}get textHeight(){return this._text?this._text.height:0}set top(e){this._margin.w=e;const t=this.entity.getLocalPosition(),s=this._absBottom,i=this._localAnchor.w-e;this._setHeight(i-s),t.y=this._localAnchor.w-this._localAnchor.y-e-this._calculatedHeight*(1-this._pivot.y),this.entity.setLocalPosition(t)}get top(){return this._margin.w}set type(e){e!==this._type&&(this._type=e,this._image&&(this._image.destroy(),this._image=null),this._text&&(this._text.destroy(),this._text=null),e===p_?this._image=new RN(this):e===kw&&(this._text=new ZN(this)))}get type(){return this._type}set useInput(e){this._useInput!==e&&(this._useInput=e,this.system.app.elementInput?e?this.enabled&&this.entity.enabled&&this.system.app.elementInput.addElement(this):this.system.app.elementInput.removeElement(this):this._useInput,this.fire("set:useInput",e))}get useInput(){return this._useInput}set fitMode(e){this._fitMode=e,this._calculateSize(!0,!0),this._image&&this._image.refreshMesh()}get fitMode(){return this._fitMode}set width(e){this._width=e,this._hasSplitAnchorsX||this._setCalculatedWidth(e,!0),this.fire("set:width",this._width)}get width(){return this._width}get worldCorners(){if(!this._worldCornersDirty)return this._worldCorners;if(this.screen){const e=this.screenCorners;if(!this.screen.screen.screenSpace){Hs.copy(this.screen.screen._screenMatrix),Hs.data[13]=-Hs.data[13],Hs.mul2(this.screen.getWorldTransform(),Hs);for(let t=0;t<4;t++)Hs.transformPoint(e[t],this._worldCorners[t])}}else{const e=this.entity.getLocalPosition();Hs.setTranslate(-e.x,-e.y,-e.z),td.setTRS(E.ZERO,this.entity.getLocalRotation(),this.entity.getLocalScale()),sd.setTranslate(e.x,e.y,e.z);const t=this.entity.parent?this.entity.parent:this.entity;jn.copy(t.getWorldTransform()),jn.mul(sd).mul(td).mul(Hs),er.set(e.x-this.pivot.x*this.calculatedWidth,e.y-this.pivot.y*this.calculatedHeight,e.z),jn.transformPoint(er,this._worldCorners[0]),er.set(e.x+(1-this.pivot.x)*this.calculatedWidth,e.y-this.pivot.y*this.calculatedHeight,e.z),jn.transformPoint(er,this._worldCorners[1]),er.set(e.x+(1-this.pivot.x)*this.calculatedWidth,e.y+(1-this.pivot.y)*this.calculatedHeight,e.z),jn.transformPoint(er,this._worldCorners[2]),er.set(e.x-this.pivot.x*this.calculatedWidth,e.y+(1-this.pivot.y)*this.calculatedHeight,e.z),jn.transformPoint(er,this._worldCorners[3])}return this._worldCornersDirty=!1,this._worldCorners}set fontSize(e){this._setValue("fontSize",e)}get fontSize(){return this._text?this._text.fontSize:null}set minFontSize(e){this._setValue("minFontSize",e)}get minFontSize(){return this._text?this._text.minFontSize:null}set maxFontSize(e){this._setValue("maxFontSize",e)}get maxFontSize(){return this._text?this._text.maxFontSize:null}set maxLines(e){this._setValue("maxLines",e)}get maxLines(){return this._text?this._text.maxLines:null}set autoFitWidth(e){this._setValue("autoFitWidth",e)}get autoFitWidth(){return this._text?this._text.autoFitWidth:null}set autoFitHeight(e){this._setValue("autoFitHeight",e)}get autoFitHeight(){return this._text?this._text.autoFitHeight:null}set color(e){this._setValue("color",e)}get color(){return this._text?this._text.color:this._image?this._image.color:null}set font(e){this._setValue("font",e)}get font(){return this._text?this._text.font:null}set fontAsset(e){this._setValue("fontAsset",e)}get fontAsset(){return this._text&&typeof this._text.fontAsset=="number"?this._text.fontAsset:null}set spacing(e){this._setValue("spacing",e)}get spacing(){return this._text?this._text.spacing:null}set lineHeight(e){this._setValue("lineHeight",e)}get lineHeight(){return this._text?this._text.lineHeight:null}set wrapLines(e){this._setValue("wrapLines",e)}get wrapLines(){return this._text?this._text.wrapLines:null}set lines(e){this._setValue("lines",e)}get lines(){return this._text?this._text.lines:null}set alignment(e){this._setValue("alignment",e)}get alignment(){return this._text?this._text.alignment:null}set autoWidth(e){this._setValue("autoWidth",e)}get autoWidth(){return this._text?this._text.autoWidth:null}set autoHeight(e){this._setValue("autoHeight",e)}get autoHeight(){return this._text?this._text.autoHeight:null}set rtlReorder(e){this._setValue("rtlReorder",e)}get rtlReorder(){return this._text?this._text.rtlReorder:null}set unicodeConverter(e){this._setValue("unicodeConverter",e)}get unicodeConverter(){return this._text?this._text.unicodeConverter:null}set text(e){this._setValue("text",e)}get text(){return this._text?this._text.text:null}set key(e){this._setValue("key",e)}get key(){return this._text?this._text.key:null}set texture(e){this._setValue("texture",e)}get texture(){return this._image?this._image.texture:null}set textureAsset(e){this._setValue("textureAsset",e)}get textureAsset(){return this._image?this._image.textureAsset:null}set material(e){this._setValue("material",e)}get material(){return this._image?this._image.material:null}set materialAsset(e){this._setValue("materialAsset",e)}get materialAsset(){return this._image?this._image.materialAsset:null}set sprite(e){this._setValue("sprite",e)}get sprite(){return this._image?this._image.sprite:null}set spriteAsset(e){this._setValue("spriteAsset",e)}get spriteAsset(){return this._image?this._image.spriteAsset:null}set spriteFrame(e){this._setValue("spriteFrame",e)}get spriteFrame(){return this._image?this._image.spriteFrame:null}set pixelsPerUnit(e){this._setValue("pixelsPerUnit",e)}get pixelsPerUnit(){return this._image?this._image.pixelsPerUnit:null}set opacity(e){this._setValue("opacity",e)}get opacity(){return this._text?this._text.opacity:this._image?this._image.opacity:null}set rect(e){this._setValue("rect",e)}
11887get rect(){return this._image?this._image.rect:null}set mask(e){this._setValue("mask",e)}get mask(){return this._image?this._image.mask:null}set outlineColor(e){this._setValue("outlineColor",e)}get outlineColor(){return this._text?this._text.outlineColor:null}set outlineThickness(e){this._setValue("outlineThickness",e)}get outlineThickness(){return this._text?this._text.outlineThickness:null}set shadowColor(e){this._setValue("shadowColor",e)}get shadowColor(){return this._text?this._text.shadowColor:null}set shadowOffset(e){this._setValue("shadowOffset",e)}get shadowOffset(){return this._text?this._text.shadowOffset:null}set enableMarkup(e){this._setValue("enableMarkup",e)}get enableMarkup(){return this._text?this._text.enableMarkup:null}set rangeStart(e){this._setValue("rangeStart",e)}get rangeStart(){return this._text?this._text.rangeStart:null}set rangeEnd(e){this._setValue("rangeEnd",e)}get rangeEnd(){return this._text?this._text.rangeEnd:null}_setValue(e,t){this._text?(this._text[e]!==t&&this._dirtyBatch(),this._text[e]=t):this._image&&(this._image[e]!==t&&this._dirtyBatch(),this._image[e]=t)}_patch(){this.entity._sync=this._sync,this.entity.setPosition=this._setPosition,this.entity.setLocalPosition=this._setLocalPosition}_unpatch(){this.entity._sync=lt.prototype._sync,this.entity.setPosition=lt.prototype.setPosition,this.entity.setLocalPosition=lt.prototype.setLocalPosition}_setPosition(e,t,s){if(!this.element.screen){lt.prototype.setPosition.call(this,e,t,s);return}e instanceof E?Qp.copy(e):Qp.set(e,t,s),this.getWorldTransform(),e0.copy(this.element._screenToWorld).invert(),e0.transformPoint(Qp,this.localPosition),this._dirtyLocal||this._dirtifyLocal()}_setLocalPosition(e,t,s){e instanceof E?this.localPosition.copy(e):this.localPosition.set(e,t,s);const i=this.element,r=this.localPosition,a=i._pivot;i._margin.x=r.x-i._calculatedWidth*a.x,i._margin.z=i._localAnchor.z-i._localAnchor.x-i._calculatedWidth-i._margin.x,i._margin.y=r.y-i._calculatedHeight*a.y,i._margin.w=i._localAnchor.w-i._localAnchor.y-i._calculatedHeight-i._margin.y,this._dirtyLocal||this._dirtifyLocal()}_sync(){const e=this.element,t=e.screen;if(t){if(e._anchorDirty){let s=0,i=0,r=0,a=1;if(this._parent&&this._parent.element)s=this._parent.element.calculatedWidth,i=this._parent.element.calculatedHeight,r=this._parent.element.pivot.x,a=this._parent.element.pivot.y;else{const n=t.screen.resolution;s=n.x/t.screen.scale,i=n.y/t.screen.scale}e._anchorTransform.setTranslate(s*(e.anchor.x-r),-(i*(a-e.anchor.y)),0),e._anchorDirty=!1,e._calculateLocalAnchors()}e._sizeDirty&&e._calculateSize(!1,!1)}if(this._dirtyLocal){this.localTransform.setTRS(this.localPosition,this.localRotation,this.localScale);const s=this.localPosition,i=e._pivot;e._margin.x=s.x-e._calculatedWidth*i.x,e._margin.z=e._localAnchor.z-e._localAnchor.x-e._calculatedWidth-e._margin.x,e._margin.y=s.y-e._calculatedHeight*i.y,e._margin.w=e._localAnchor.w-e._localAnchor.y-e._calculatedHeight-e._margin.y,this._dirtyLocal=!1}if(!t){this._dirtyWorld&&(e._cornersDirty=!0,e._canvasCornersDirty=!0,e._worldCornersDirty=!0),lt.prototype._sync.call(this);return}if(this._dirtyWorld){if(this._parent===null)this.worldTransform.copy(this.localTransform);else if(this._parent.element?e._screenToWorld.mul2(this._parent.element._modelTransform,e._anchorTransform):e._screenToWorld.copy(e._anchorTransform),e._modelTransform.mul2(e._screenToWorld,this.localTransform),t){e._screenToWorld.mul2(t.screen._screenMatrix,e._screenToWorld),t.screen.screenSpace||e._screenToWorld.mul2(t.worldTransform,e._screenToWorld),this.worldTransform.mul2(e._screenToWorld,this.localTransform);const s=e._parentWorldTransform;s.setIdentity();const i=this._parent;i&&i.element&&i!==t&&(Hs.setTRS(E.ZERO,i.getLocalRotation(),i.getLocalScale()),s.mul2(i.element._parentWorldTransform,Hs));const r=er;r.set(0,0,this.localPosition.z);const a=QN;a.set(e._absLeft+e._pivot.x*e.calculatedWidth,e._absBottom+e._pivot.y*e.calculatedHeight,0),Hs.setTranslate(-a.x,-a.y,-a.z),td.setTRS(r,this.getLocalRotation(),this.getLocalScale()),sd.setTranslate(a.x,a.y,a.z),e._screenTransform.mul2(e._parentWorldTransform,sd).mul(td).mul(Hs),e._cornersDirty=!0,e._canvasCornersDirty=!0,e._worldCornersDirty=!0}else this.worldTransform.copy(e._modelTransform);this._dirtyWorld=!1}}_onInsert(e){const t=this._parseUpToScreen();this.entity._dirtifyWorld(),this._updateScreen(t.screen),this._dirtifyMask()}_dirtifyMask(){let e=this.entity;for(;e;){const t=e.parent;if((t===null||t.screen)&&e.element){(!this.system._prerender||!this.system._prerender.length)&&(this.system._prerender=[],this.system.a
11887pp.once("prerender",this._onPrerender,this));const s=this.system._prerender.indexOf(this.entity);s>=0&&this.system._prerender.splice(s,1),this.system._prerender.indexOf(e)<0&&this.system._prerender.push(e)}e=t}}_onPrerender(){for(let e=0;e<this.system._prerender.length;e++){const t=this.system._prerender[e];t.element&&t.element.syncMask(1)}this.system._prerender.length=0}_bindScreen(e){e._bindElement(this)}_unbindScreen(e){e._unbindElement(this)}_updateScreen(e){this.screen&&this.screen!==e&&this._unbindScreen(this.screen.screen);const t=this.screen;this.screen=e,this.screen&&this._bindScreen(this.screen.screen),this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY),this.fire("set:screen",this.screen,t),this._anchorDirty=!0;const s=this.entity.children;for(let i=0,r=s.length;i<r;i++)s[i].element&&s[i].element._updateScreen(e);this.screen&&this.screen.screen.syncDrawOrder()}syncMask(e){const t=this._parseUpToScreen();this._updateMask(t.mask,e)}_setMaskedBy(e){const t=this._image||this._text;if(e){const s=e.element._image._maskRef;t?._setStencil(new $s({ref:s,func:Wd})),this._maskedBy=e}else t?._setStencil(null),this._maskedBy=null}_updateMask(e,t){if(e){if(this._setMaskedBy(e),this.mask){const i=e.element._image._maskRef,r=new $s({ref:i,func:Wd,zpass:eb});this._image._setStencil(r),this._image._maskRef=t,t++,e=this.entity}const s=this.entity.children;for(let i=0,r=s.length;i<r;i++)s[i].element?._updateMask(e,t);this.mask&&t--}else{if(this._setMaskedBy(null),this.mask){const i=new $s({ref:t,func:cr,zpass:JE});this._image._setStencil(i),this._image._maskRef=t,t++,e=this.entity}const s=this.entity.children;for(let i=0,r=s.length;i<r;i++)s[i].element?._updateMask(e,t);this.mask&&t--}}_parseUpToScreen(){const e={screen:null,mask:null};let t=this.entity._parent;for(;t&&!t.screen;)t.element&&t.element.mask&&(e.mask||(e.mask=t)),t=t.parent;return t&&t.screen&&(e.screen=t),e}_onScreenResize(e){this._anchorDirty=!0,this._cornersDirty=!0,this._worldCornersDirty=!0,this._calculateSize(this._hasSplitAnchorsX,this._hasSplitAnchorsY),this.fire("screen:set:resolution",e)}_onScreenSpaceChange(){this.fire("screen:set:screenspace",this.screen.screen.screenSpace)}_onScreenRemove(){this.screen&&(this.screen._destroying?this.screen=null:this._updateScreen(null))}_calculateLocalAnchors(){let e=1e3,t=1e3;const s=this.entity._parent;if(s&&s.element)e=s.element.calculatedWidth,t=s.element.calculatedHeight;else if(this.screen){const i=this.screen.screen.resolution,r=this.screen.screen.scale;e=i.x/r,t=i.y/r}this._localAnchor.set(this._anchor.x*e,this._anchor.y*t,this._anchor.z*e,this._anchor.w*t)}getOffsetPosition(e,t){const s=this.entity.getLocalPosition().clone();return s.x+=e,s.y+=t,this._screenToWorld.transformPoint(s,s),s}onLayersChanged(e,t){this.addModelToLayers(this._image?this._image._renderable.model:this._text._model),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this)}onLayerAdded(e){this.layers.indexOf(e.id)<0||(this._image?e.addMeshInstances(this._image._renderable.model.meshInstances):this._text&&e.addMeshInstances(this._text._model.meshInstances))}onLayerRemoved(e){this.layers.indexOf(e.id)<0||(this._image?e.removeMeshInstances(this._image._renderable.model.meshInstances):this._text&&e.removeMeshInstances(this._text._model.meshInstances))}onEnable(){const e=this.system.app.scene,t=e.layers;this._image&&this._image.onEnable(),this._text&&this._text.onEnable(),this._group&&this._group.onEnable(),this.useInput&&this.system.app.elementInput&&this.system.app.elementInput.addElement(this),this._evtLayersChanged=e.on("set:layers",this.onLayersChanged,this),t&&(this._evtLayerAdded=t.on("add",this.onLayerAdded,this),this._evtLayerRemoved=t.on("remove",this.onLayerRemoved,this)),this._batchGroupId>=0&&this.system.app.batcher?.insert(Zt.ELEMENT,this.batchGroupId,this.entity),this.fire("enableelement")}onDisable(){const t=this.system.app.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,t&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this._image&&this._image.onDisable(),this._text&&this._text.onDisable(),this._group&&this._group.onDisable(),this.system.a
11887pp.elementInput&&this.useInput&&this.system.app.elementInput.removeElement(this),this._batchGroupId>=0&&this.system.app.batcher?.remove(Zt.ELEMENT,this.batchGroupId,this.entity),this.fire("disableelement")}onRemove(){this.entity.off("insert",this._onInsert,this),this._unpatch(),this._image&&this._image.destroy(),this._text&&this._text.destroy(),this.system.app.elementInput&&this.useInput&&this.system.app.elementInput.removeElement(this),this.screen&&this.screen.screen&&(this._unbindScreen(this.screen.screen),this.screen.screen.syncDrawOrder()),this.off()}_calculateSize(e,t){if(!this.entity._parent&&!this.screen)return;this._calculateLocalAnchors();const s=this._absRight-this._absLeft,i=this._absTop-this._absBottom;e?this._setWidth(s):this._setCalculatedWidth(s,!1),t?this._setHeight(i):this._setCalculatedHeight(i,!1);const r=this.entity.getLocalPosition();r.x=this._margin.x+this._calculatedWidth*this._pivot.x,r.y=this._margin.y+this._calculatedHeight*this._pivot.y,this.entity.setLocalPosition(r),this._sizeDirty=!1}_setWidth(e){this._width=e,this._setCalculatedWidth(e,!1),this.fire("set:width",this._width)}_setHeight(e){this._height=e,this._setCalculatedHeight(e,!1),this.fire("set:height",this._height)}_setCalculatedWidth(e,t){if(!(Math.abs(e-this._calculatedWidth)<=1e-4)){if(this._calculatedWidth=e,this.entity._dirtifyLocal(),t){const s=this.entity.getLocalPosition(),i=this._pivot;this._margin.x=s.x-this._calculatedWidth*i.x,this._margin.z=this._localAnchor.z-this._localAnchor.x-this._calculatedWidth-this._margin.x}this._flagChildrenAsDirty(),this.fire("set:calculatedWidth",this._calculatedWidth),this.fire("resize",this._calculatedWidth,this._calculatedHeight)}}_setCalculatedHeight(e,t){if(!(Math.abs(e-this._calculatedHeight)<=1e-4)){if(this._calculatedHeight=e,this.entity._dirtifyLocal(),t){const s=this.entity.getLocalPosition(),i=this._pivot;this._margin.y=s.y-this._calculatedHeight*i.y,this._margin.w=this._localAnchor.w-this._localAnchor.y-this._calculatedHeight-this._margin.y}this._flagChildrenAsDirty(),this.fire("set:calculatedHeight",this._calculatedHeight),this.fire("resize",this._calculatedWidth,this._calculatedHeight)}}_flagChildrenAsDirty(){const e=this.entity._children;for(let t=0,s=e.length;t<s;t++)e[t].element&&(e[t].element._anchorDirty=!0,e[t].element._sizeDirty=!0)}addModelToLayers(e){this._addedModels.push(e);for(let t=0;t<this.layers.length;t++){const s=this.system.app.scene.layers.getLayerById(this.layers[t]);s&&s.addMeshInstances(e.meshInstances)}}removeModelFromLayers(e){const t=this._addedModels.indexOf(e);t>=0&&this._addedModels.splice(t,1);for(let s=0;s<this.layers.length;s++){const i=this.system.app.scene.layers.getLayerById(this.layers[s]);i&&i.removeMeshInstances(e.meshInstances)}}getMaskOffset(){const e=this.system.app.frame;this._offsetReadAt!==e&&(this._maskOffset=.5,this._offsetReadAt=e);const t=this._maskOffset;return this._maskOffset-=.001,t}isVisibleForCamera(e){let t,s,i,r;if(this.maskedBy){const d=this.maskedBy.element.screenCorners;t=Math.min(Math.min(d[0].x,d[1].x),Math.min(d[2].x,d[3].x)),s=Math.max(Math.max(d[0].x,d[1].x),Math.max(d[2].x,d[3].x)),r=Math.min(Math.min(d[0].y,d[1].y),Math.min(d[2].y,d[3].y)),i=Math.max(Math.max(d[0].y,d[1].y),Math.max(d[2].y,d[3].y))}else{const d=this.system.app.graphicsDevice.width,u=this.system.app.graphicsDevice.height,f=e._rect.z*d,p=e._rect.w*u;t=e._rect.x*d,s=t+f,i=(1-e._rect.y)*u,r=i-p}const a=this.screenCorners,n=Math.min(Math.min(a[0].x,a[1].x),Math.min(a[2].x,a[3].x)),o=Math.max(Math.max(a[0].x,a[1].x),Math.max(a[2].x,a[3].x)),c=Math.min(Math.min(a[0].y,a[1].y),Math.min(a[2].y,a[3].y)),h=Math.max(Math.max(a[0].y,a[1].y),Math.max(a[2].y,a[3].y));return!(o<t||n>s||c>i||h<r)}_isScreenSpace(){return this.screen&&this.screen.screen?this.screen.screen.screenSpace:!1}_isScreenCulled(){return this.screen&&this.screen.screen?this.screen.screen.cull:!1}_dirtyBatch(){this.batchGroupId!==-1&&this.system.app.batcher?.markGroupDirty(this.batchGroupId)}}class JN{enabled=!0}const ek=["enabled"];class tk extends Tt{constructor(e){super(e),this.id="element",this.ComponentType=Hw,this.DataType=JN,this.schema=ek,this._unicodeConverter=null,this._rtlReorder=null,this._defaultTexture=new ce(e.graphicsDevice,{width:1,height:1,format:us,name:"element-system"});const t=this._defaultTexture.lock(),s=new Uint8Array(4);s[0]=255,s[1]=255,s[2]=255,s[3]=255,t.set(s),this._defaultTexture.unlock(),this.defaultImageMaterial=null,this.defaultImage9SlicedMaterial=null,this.defaultImage9TiledMaterial=null,this.defaultImageMaskMaterial=null,this.defaultImage9SlicedMaskMaterial=null,this.defaultImage9TiledMaskMaterial=null,this.defaultScreenSpaceImageMaterial=null,this.defaultScreenSpaceImage9SlicedMaterial=null,this.defaultScreenSpaceImage9TiledMaterial=null,this.defaultScreenSpaceImageMask9SlicedMaterial=null,this.defaultScreenSpaceImageMask9TiledMaterial=null,this.defaultScreenSpaceImageMaskMaterial=null,this._defaultTextMaterials={},this.defaultImageMaterials=[],this.on("add",this.onAddComponent,this),this.on("beforeremove",this.onRemoveComponent,this)}destroy(){super.destroy(),this._defaultTexture.destroy()}initializeComponentData(e,t,s){e._beingInitialized=!0,t.anchor!==void 0&&(t.anchor instanceof ie?e.anchor.copy(t.anchor):e.anchor.set(t.anchor[0],t.anchor[1],t.anchor[2],t.anchor[3])),t.pivot!==void 0&&(t.pivot instanceof j?e.pivot.copy(t.pivot):e.pivot.set(t.pivot[0],t.pivot[1]));const i=Math.abs(e.anchor.x-e.anchor.z)>.001,r=Math.abs(e.anchor.y-e.anchor.w)>.001;let a=!1,n;t.margin!==void 0&&(t.margin instanceof ie?e.margin.copy(t.margin):e._margin.set(t.margin[0],t.margin[1],t.margin[2],t.margin[3]),a=!0),t.left!==void 0&&(e._margin.x=t.left,a=!0),t.bottom!==void 0&&(e._margin.y=t.bottom,a=!0),t.right!==void 0&&(e._margin.z=t.right,a=!0),t.top!==void 0&&(e._margin.w=t.top,a=!0),a&&(e.margin=e._margin);let o=!1;t.width!==void 0&&!i?e.width=t.width:i&&(o=!0),t.height!==void 0&&!r?e.height=t.height:r&&(o=!0),o&&(e.anchor=e.anchor),t.enabled!==void 0&&(e.enabled=t.enabled),t.useInput!==void 0&&(e.useInput=t.useInput),t.fitMode!==void 0&&(e.fitMode=t.fitMode),e.batchGroupId=t.batchGroupId===void 0||t.batchGroupId===null?-1:t.batchGroupId,t.layers&&Array.isArray(t.layers)&&(e.layers=t.layers.slice(0)),t.type!==void 0&&(e.type=t.type),e.type===p_?(t.rect!==void 0&&(e.rect=t.rect),t.color!==void 0&&(n=t.color,n instanceof Q||(n=new Q(t.color[0],t.color[1],t.color[2])),e.color=n),t.opacity!==void 0&&(e.opacity=t.opacity),t.textureAsset!==void 0&&(e.textureAsset=t.textureAsset),t.texture&&(e.texture=t.texture),t.spriteAsset!==void 0&&(e.spriteAsset=t.spriteAsset),t.sprite&&(e.sprite=t.sprite),t.spriteFrame!==void 0&&(e.spriteFrame=t.spriteFrame),t.pixelsPerUnit!==void 0&&t.pixelsPerUnit!==null&&(e.pixelsPerUnit=t.pixelsPerUnit),t.materialAsset!==void 0&&(e.materialAsset=t.materialAsset),t.material&&(e.material=t.material),t.mask!==void 0&&(e.mask=t.mask)):e.type===kw&&(t.autoWidth!==void 0&&(e.autoWidth=t.autoWidth),t.autoHeight!==void 0&&(e.autoHeight=t.autoHeight),t.rtlReorder!==void 0&&(e.rtlReorder=t.rtlReorder),t.unicodeConverter!==void 0&&(e.unicodeConverter=t.unicodeConverter),t.text!==null&&t.text!==void 0?e.text=t.text:t.key!==null&&t.key!==void 0&&(e.key=t.key),t.color!==void 0&&(n=t.color,n instanceof Q||(n=new Q(n[0],n[1],n[2])),e.color=n),t.opacity!==void 0&&(e.opacity=t.opacity),t.spacing!==void 0&&(e.spacing=t.spacing),t.fontSize!==void 0&&(e.fontSize=t.fontSize,t.lineHeight||(e.lineHeight=t.fontSize)),t.lineHeight!==void 0&&(e.lineHeight=t.lineHeight),t.maxLines!==void 0&&(e.maxLines=t.maxLines),t.wrapLines!==void 0&&(e.wrapLines=t.wrapLines),t.minFontSize!==void 0&&(e.minFontSize=t.minFontSize),t.maxFontSize!==void 0&&(e.maxFontSize=t.maxFontSize),t.autoFitWidth&&(e.autoFitWidth=t.autoFitWidth),t.autoFitHeight&&(e.autoFitHeight=t.autoFitHeight),t.fontAsset!==void 0&&(e.fontAsset=t.fontAsset),t.font!==void 0&&(e.font=t.font),t.alignment!==void 0&&(e.alignment=t.alignment),t.outlineColor!==void 0&&(e.outlineColor=t.outlineColor),t.outlineThickness!==void 0&&(e.outlineThickness=t.outlineThickness),t.shadowColor!==void 0&&(e.shadowColor=t.shadowColor),t.shadowOffset!==void 0&&(e.shadowOffset=t.shadowOffset),t.enableMarkup!==void 0&&(e.enableMarkup=t.enableMarkup));const c=e._parseUpToScreen();c.screen&&e._updateScreen(c.screen),super.initializeComponentData(e,t,s),e._beingInitialized=!1,e.type===p_&&e._image._meshDirty&&e._image._updateMesh(e._image.mesh)}onAddComponent(e,t){e.fire("element:add")}onRemoveComponent(e,t){t.onRemove()}cloneComponent(e,t){const s=e.element,i={enabled:s.enabled,width:s.width,height:s.height,anchor:s.anch
11887or.clone(),pivot:s.pivot.clone(),margin:s.margin.clone(),alignment:s.alignment&&s.alignment.clone()||s.alignment,autoWidth:s.autoWidth,autoHeight:s.autoHeight,type:s.type,rect:s.rect&&s.rect.clone()||s.rect,rtlReorder:s.rtlReorder,unicodeConverter:s.unicodeConverter,materialAsset:s.materialAsset,material:s.material,color:s.color&&s.color.clone()||s.color,opacity:s.opacity,textureAsset:s.textureAsset,texture:s.texture,spriteAsset:s.spriteAsset,sprite:s.sprite,spriteFrame:s.spriteFrame,pixelsPerUnit:s.pixelsPerUnit,spacing:s.spacing,lineHeight:s.lineHeight,wrapLines:s.wrapLines,layers:s.layers,fontSize:s.fontSize,minFontSize:s.minFontSize,maxFontSize:s.maxFontSize,autoFitWidth:s.autoFitWidth,autoFitHeight:s.autoFitHeight,maxLines:s.maxLines,fontAsset:s.fontAsset,font:s.font,useInput:s.useInput,fitMode:s.fitMode,batchGroupId:s.batchGroupId,mask:s.mask,outlineColor:s.outlineColor&&s.outlineColor.clone()||s.outlineColor,outlineThickness:s.outlineThickness,shadowColor:s.shadowColor&&s.shadowColor.clone()||s.shadowColor,shadowOffset:s.shadowOffset&&s.shadowOffset.clone()||s.shadowOffset,enableMarkup:s.enableMarkup};return s.key!==void 0&&s.key!==null?i.key=s.key:i.text=s.text,this.addComponent(t,i)}getTextElementMaterial(e,t,s){const i=(e&&1)|(t&&2)|(s&&4);let r=this._defaultTextMaterials[i];if(r)return r;let a="TextMaterial";return r=new Es,t?(r.msdfMap=this._defaultTexture,r.msdfTextAttribute=s,r.emissive.set(1,1,1)):(a=`Bitmap${a}`,r.emissive.set(1,1,1),r.emissiveMap=this._defaultTexture,r.opacityMap=this._defaultTexture,r.opacityMapChannel="a"),e&&(a=`ScreenSpace${a}`,r.depthTest=!1),r.name=`default${a}`,r.useLighting=!1,r.useTonemap=!1,r.useFog=!1,r.useSkybox=!1,r.diffuse.set(0,0,0),r.opacity=.5,r.blendType=Ui,r.depthWrite=!1,r.emissiveVertexColor=!0,r.update(
11887),this._defaultTextMaterials[i]=r,r}_createBaseImageMaterial(){const e=new Es;return e.diffuse.set(0,0,0),e.emissive.set(1,1,1),e.emissiveMap=this._defaultTexture,e.opacityMap=this._defaultTexture,e.opacityMapChannel="a",e.useLighting=!1,e.useTonemap=!1,e.useFog=!1,e.useSkybox=!1,e.blendType=Ui,e.depthWrite=!1,e}getImageElementMaterial(e,t,s,i){return e?t?s?(this.defaultScreenSpaceImageMask9SlicedMaterial||(this.defaultScreenSpaceImageMask9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMask9SlicedMaterial.name="defaultScreenSpaceImageMask9SlicedMaterial",this.defaultScreenSpaceImageMask9SlicedMaterial.nineSlicedMode=kt,this.defaultScreenSpaceImageMask9SlicedMaterial.depthTest=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.alphaTest=1,this.defaultScreenSpaceImageMask9SlicedMaterial.redWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.greenWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.blueWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMask9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMask9SlicedMaterial)),this.defaultScreenSpaceImageMask9SlicedMaterial):i?(this.defaultScreenSpaceImageMask9TiledMaterial||(this.defaultScreenSpaceImageMask9TiledMaterial=this.defaultScreenSpaceImage9TiledMaterial.clone(),this.defaultScreenSpaceImageMask9TiledMaterial.name="defaultScreenSpaceImageMask9TiledMaterial",this.defaultScreenSpaceImageMask9TiledMaterial.nineSlicedMode=Ut,this.defaultScreenSpaceImageMask9TiledMaterial.depthTest=!1,this.defaultScreenSpaceImageMask9TiledMaterial.alphaTest=1,this.defaultScreenSpaceImageMask9TiledMaterial.redWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.greenWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.blueWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMask9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMask9TiledMaterial)),this.defaultScreenSpaceImageMask9TiledMaterial):(this.defaultScreenSpaceImageMaskMaterial||(this.defaultScreenSpaceImageMaskMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMaskMaterial.name="defaultScreenSpaceImageMaskMaterial",this.defaultScreenSpaceImageMaskMaterial.depthTest=!1,this.defaultScreenSpaceImageMaskMaterial.alphaTest=1,this.defaultScreenSpaceImageMaskMaterial.redWrite=!1,this.defaultScreenSpaceImageMaskMaterial.greenWrite=!1,this.defaultScreenSpaceImageMaskMaterial.blueWrite=!1,this.defaultScreenSpaceImageMaskMaterial.alphaWrite=!1,this.defaultScreenSpaceImageMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMaskMaterial)),this.defaultScreenSpaceImageMaskMaterial):s?(this.defaultScreenSpaceImage9SlicedMaterial||(this.defaultScreenSpaceImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9SlicedMaterial.name="defaultScreenSpaceImage9SlicedMaterial",this.defaultScreenSpaceImage9SlicedMaterial.nineSlicedMode=kt,this.defaultScreenSpaceImage9SlicedMaterial.depthTest=!1,this.defaultScreenSpaceImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9SlicedMaterial)),this.defaultScreenSpaceImage9SlicedMaterial):i?(this.defaultScreenSpaceImage9TiledMaterial||(this.defaultScreenSpaceImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImage9TiledMaterial.name="defaultScreenSpaceImage9TiledMaterial",this.defaultScreenSpaceImage9TiledMaterial.nineSlicedMode=Ut,this.defaultScreenSpaceImage9TiledMaterial.depthTest=!1,this.defaultScreenSpaceImage9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImage9TiledMaterial)),this.defaultScreenSpaceImage9TiledMaterial):(this.defaultScreenSpaceImageMaterial||(this.defaultScreenSpaceImageMaterial=this._createBaseImageMaterial(),this.defaultScreenSpaceImageMaterial.name="defaultScreenSpaceImageMaterial",this.defaultScreenSpaceImageMaterial.depthTest=!1,this.defaultScreenSpaceImageMaterial.update(),this.defaultImageMaterials.push(this.defaultScreenSpaceImageMaterial)),this.defaultScreenSpaceImageMaterial):t?s?(this.defaultImage9SlicedMaskMaterial||(this.defaultImage9SlicedMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaskMaterial.name="defaultImage9SlicedMaskMaterial",this.defaultImage9SlicedMaskMaterial.nineSlicedMode=kt,this.defaultImage9SlicedMaskMaterial.alphaTest=1,this.defaultImage9SlicedMaskMaterial.redWrite=!1,this.defaultImage9SlicedMaskMaterial.greenWrite=!1,this.defaultImage9SlicedMaskMaterial.blueWrite=!1,this.defaultImage9SlicedMaskMaterial.alphaWrite=!1,this.defaultImage9SlicedMaskMaterial.update(
11887),this.defaultImageMaterials.push(this.defaultImage9SlicedMaskMaterial)),this.defaultImage9SlicedMaskMaterial):i?(this.defaultImage9TiledMaskMaterial||(this.defaultImage9TiledMaskMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaskMaterial.name="defaultImage9TiledMaskMaterial",this.defaultImage9TiledMaskMaterial.nineSlicedMode=Ut,this.defaultImage9TiledMaskMaterial.alphaTest=1,this.defaultImage9TiledMaskMaterial.redWrite=!1,this.defaultImage9TiledMaskMaterial.greenWrite=!1,this.defaultImage9TiledMaskMaterial.blueWrite=!1,this.defaultImage9TiledMaskMaterial.alphaWrite=!1,this.defaultImage9TiledMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9TiledMaskMaterial)),this.defaultImage9TiledMaskMaterial):(this.defaultImageMaskMaterial||(this.defaultImageMaskMaterial=this._createBaseImageMaterial(),this.defaultImageMaskMaterial.name="defaultImageMaskMaterial",this.defaultImageMaskMaterial.alphaTest=1,this.defaultImageMaskMaterial.redWrite=!1,this.defaultImageMaskMaterial.greenWrite=!1,this.defaultImageMaskMaterial.blueWrite=!1,this.defaultImageMaskMaterial.alphaWrite=!1,this.defaultImageMaskMaterial.update(),this.defaultImageMaterials.push(this.defaultImageMaskMaterial)),this.defaultImageMaskMaterial):s?(this.defaultImage9SlicedMaterial||(this.defaultImage9SlicedMaterial=this._createBaseImageMaterial(),this.defaultImage9SlicedMaterial.name="defaultImage9SlicedMaterial",this.defaultImage9SlicedMaterial.nineSlicedMode=kt,this.defaultImage9SlicedMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9SlicedMaterial)),this.defaultImage9SlicedMaterial):i?(this.defaultImage9TiledMaterial||(this.defaultImage9TiledMaterial=this._createBaseImageMaterial(),this.defaultImage9TiledMaterial.name="defaultImage9TiledMaterial",this.defaultImage9TiledMaterial.nineSlicedMode=Ut,this.defaultImage9TiledMaterial.update(),this.defaultImageMaterials.push(this.defaultImage9TiledMaterial)),this.defaultImage9TiledMaterial):(this.defaultImageMaterial||(this.defaultImageMaterial=this._createBaseImageMaterial(),this.defaultImageMaterial.name="defaultImageMaterial",this.defaultImageMaterial.update(),this.defaultImageMaterials.push(this.defaultImageMaterial)),this.defaultImageMaterial)}registerUnicodeConverter(e){this._unicodeConverter=e}registerRtlReorder(e){this._rtlReorder=e}getUnicodeConverter(){return this._unicodeConverter}getRtlReorder(){return this._rtlReorder}}const qn="free",$n="limited",Kn="locked",sk=["angularDampingX","angularDampingY","angularDampingZ","angularEquilibriumX","angularEquilibriumY","angularEquilibriumZ","angularLimitsX","angularLimitsY","angularLimitsZ","angularMotionX","angularMotionY","angularMotionZ","angularSpringX","angularSpringY","angularSpringZ","angularStiffnessX","angularStiffnessY","angularStiffnessZ","breakForce","enableCollision","enabled","entityA","entityB","linearDampingX","linearDampingY","linearDampingZ","linearEquilibriumX","linearEquilibriumY","linearEquilibriumZ","linearLimitsX","linearLimitsY","linearLimitsZ","linearMotionX","linearMotionY","linearMotionZ","linearSpringX","linearSpringY","linearSpringZ","linearStiffnessX","linearStiffnessY","linearStiffnessZ"];class qg extends ye{constructor(e,t){super(e,t),this._constraint=null,this._entityA=null,this._entityB=null,this._breakForce=34e37,this._enableCollision=!0,this._linearMotionX=Kn,this._linearLimitsX=new j(0,0),this._linearSpringX=!1,this._linearStiffnessX=0,this._linearDampingX=1,this._linearEquilibriumX=0,this._linearMotionY=Kn,this._linearLimitsY=new j(0,0),this._linearSpringY=!1,this._linearStiffnessY=0,this._linearDampingY=1,this._linearEquilibriumY=0,this._linearMotionZ=Kn,this._linearLimitsZ=new j(0,0),this._linearSpringZ=!1,this._linearStiffnessZ=0,this._linearDampingZ=1,this._linearEquilibriumZ=0,this._angularMotionX=Kn,this._angularLimitsX=new j(0,0),this._angularSpringX=!1,this._angularStiffnessX=0,this._angularDampingX=1,this._angularEquilibriumX=0,this._angularMotionY=Kn,this._angularLimitsY=new j(0,0),this._angularSpringY=!1,this._angularStiffnessY=0,this._angularDampingY=1,this._angularEquilibriumY=0,this._angularMotionZ=Kn,this._angularLimitsZ=new j(0,0),this._angularSpringZ=!1,this._angularEquilibriumZ=0,this._angularDampingZ=1,this._angularStiffnessZ=0,this.on("set_enabled",this._onSetEnabled,this)}set entityA(e){this._destroyConstraint(),this._entityA=e,this._createConstraint()}get entityA(){return this._entityA}set entityB(e){this._destroyConstraint(),this._entityB=e,this._createConstraint()}get entityB(){return this._entityB}set breakForce(e){this._constraint&&this._breakForce!==e&&(this._constraint.setBreakingImpulseThreshold(e),this._breakForce=e)}get breakForce(){return this._breakForce}set enableCollision(e){this._destroyConstraint(),this._enableCollision=e,this._createConstraint()}get enableCollision(){return this._enableCollision}set angularLimitsX(e){this._angularLimitsX.equals(e)||(this._angularLimitsX.copy(e),this._updateAngularLimits())}get angularLimitsX(){return this._angularLimitsX}set angularMotionX(e){this._angularMotionX!==e&&(this._angularMotionX=e,this._updateAngularLimits())}get angularMotionX(){return this._angularMotionX}set angularLimitsY(e){this._angularLimitsY.equals(e)||(this._angularLimitsY.copy(e),this._updateAngularLimits())}get angularLimitsY(){return this._angularLimitsY}set angularMotionY(e){this._angularMotionY!==e&&(this._angularMotionY=e,this._updateAngularLimits())}get angularMotionY(){return this._angularMotionY}set angularLimitsZ(e){this._angularLimitsZ.equals(e)||(this._angularLimitsZ.copy(e),this._updateAngularLimits())}get angularLimitsZ(){return this._angularLimitsZ}set angularMotionZ(e){this._angularMotionZ!==e&&(this._angularMotionZ=e,this._updateAngularLimits())}get angularMotionZ(){return this._angularMotionZ}set linearLimitsX(e){this._linearLimitsX.equals(e)||(this._linearLimitsX.copy(e),this._updateLinearLimits())}get linearLimitsX(){return this._linearLimitsX}set linearMotionX(e){this._linearMotionX!==e&&(this._linearMotionX=e,this._updateLinearLimits())}get linearMotionX(){return this._linearMotionX}set linearLimitsY(e){this._linearLimitsY.equals(e)||(this._linearLimitsY.copy(e),this._updateLinearLimits())}get linearLimitsY(){return this._linearLimitsY}set linearMotionY(e){this._linearMotionY!==e&&(this._linearMotionY=e,this._updateLinearLimits())}get linearMotionY(){return this._linearMotionY}set linearLimitsZ(e){this._linearLimitsZ.equals(e)||(this._linearLimitsZ.copy(e),this._updateLinearLimits())}get linearLimitsZ(){return this._linearLimitsZ}set linearMotionZ(e){this._linearMotionZ!==e&&(this._linearMotionZ=e,this._updateLinearLimits())}get linearMotionZ(){return this._linearMotionZ}_convertTransform(e,t){const s=e.getTranslation(),i=new ae;i.setFromMat4(e);const r=new Ammo.btVector3(s.x,s.y,s.z),a=new Ammo.btQuaternion(i.x,i.y,i.z,i.w);t.setOrigin(r),t.setRotation(a),Ammo.destroy(r),Ammo.destroy(a)}_updateAngularLimits(){const e=this._constraint;if(e){let t,s,i,r,a,n;this._angularMotionX===$n?(t=this._angularLimitsX.x*H.DEG_TO_RAD,r=this._angularLimitsX.y*H.DEG_TO_RAD):this._angularMotionX===qn?(t=1,r=0):t=r=0,this._angularMotionY===$n?(s=this._angularLimitsY.x*H.DEG_TO_RAD,a=this._angularLimitsY.y*H.DEG_TO_RAD):this._angularMotionY===qn?(s=1,a=0):s=a=0,this._angularMotionZ===$n?(i=this._angularLimitsZ.x*H.DEG_TO_RAD,n=this._angularLimitsZ.y*H.DEG_TO_RAD):this._angularMotionZ===qn?(i=1,n=0):i=n=0;const o=new Ammo.btVector3(t,s,i);e.setAngularLowerLimit(o),o.setValue(r,a,n),e.setAngularUpperLimit(o),Ammo.destroy(o)}}_updateLinearLimits(){const e=this._constraint;if(e){let t,s,i,r,a,n;this._linearMotionX===$n?(t=this._linearLimitsX.x,r=this._linearLimitsX.y):this._linearMotionX===qn?(t=1,r=0):t=r=0,this._linearMotionY===$n?(s=this._linearLimitsY.x,a=this._linearLimitsY.y):this._linearMotionY===qn?(s=1,a=0):s=a=0,this._linearMotionZ===$n?(i=this._linearLimitsZ.x,n=this._linearLimitsZ.y):this._linearMotionZ===qn?(i=1,n=0):i=n=0;const o=new Ammo.btVector3(t,s,i);e.setLinearLowerLimit(o),o.setValue(r,a,n),e.setLinearUpperLimit(o),Ammo.destroy(o)}}_createConstraint(){if(this._entityA&&this._entityA.rigidbody){this._destroyConstraint();const e=new Z,t=this._entityA.rigidbody.body;t.activate();const s=this.entity.getWorldTransform(),r=this._entityA.getWorldTransform().clone().invert();e.mul2(r,s);const a=new Ammo.btTransform;if(this._convertTransform(e,a),this._entityB&&this._entityB.rigidbody){const h=this._entityB.rigidbody.body;h.activate();const u=this._entityB.getWorldTransform().clone().invert();e.mul2(u,s);const f=new Ammo.btTransform;this._convertTransform(e,f),this._constraint=new Ammo.btGeneric6DofSpringConstraint(t,h,a,f,!this._enableCollision),Ammo.destroy(f)}else this._constraint=new Ammo.btGeneric6DofSpringConstraint(t,a,!this._enableCollision);Ammo.destroy(a);const n=["X","Y","Z","X","Y","Z"];for(let h=0;h<6;h++){const d=h<3?"_linear":"_angular";this._constraint.enableSpring(h,this[`${d}Spring${n[h]}`]),this._constraint.setDamping(h,this[`${d}Damping${n[h]}`]),this._constraint.setEquilibriumPoint(h,this[`${d}Equilibrium${n[h]}`]),this._constraint.setStiffness(h,this[`${d}Stiffness${n[h]}`])}this._constraint.setBreakingImpulseThreshold(this._breakForce),this._updateLinearLimits(),this._updateAngularLimits(),this.system.a
11887pp.systems.rigidbody.dynamicsWorld.addConstraint(this._constraint,!this._enableCollision)}}_destroyConstraint(){this._constraint&&(this.system.app.systems.rigidbody.dynamicsWorld.removeConstraint(this._constraint),Ammo.destroy(this._constraint),this._constraint=null)}initFromData(e){for(const t of sk)e.hasOwnProperty(t)&&(e[t]instanceof j?this[`_${t}`].copy(e[t]):this[`_${t}`]=e[t]);this._createConstraint()}onEnable(){this._createConstraint()}onDisable(){this._destroyConstraint()}_onSetEnabled(e,t,s){}_onBeforeRemove(){this.fire("remove")}}const ik={Damping:"setDamping",Equilibrium:"setEquilibriumPoint",Spring:"enableSpring",Stiffness:"setStiffness"};["linear","angular"].forEach(l=>{["Damping","Equilibrium","Spring","Stiffness"].forEach(e=>{["X","Y","Z"].forEach(t=>{const s=l+e+t,i=`_${s}`;let r=l==="linear"?0:3;t==="Y"&&(r+=1),t==="Z"&&(r+=2),Object.defineProperty(qg.prototype,s,{get:function(){return this[i]},set:function(a){this[i]!==a&&(this[i]=a,this._constraint[ik[e]](r,a))}})})})});class rk{enabled=!0}const T_=["enabled"];class ak extends Tt{constructor(e){super(e),this.id="joint",this.app=e,this.ComponentType=qg,this.DataType=rk,this.schema=T_}initializeComponentData(e,t,s){e.initFromData(t),super.initializeComponentData(e,t,T_)}}ye._buildAccessors(qg.prototype,T_);class Ww extends ye{_minWidth=0;_minHeight=0;_maxWidth=null;_maxHeight=null;_fitWidthProportion=0;_fitHeightProportion=0;_excludeFromLayout=!1;set minWidth(e){e!==this._minWidth&&(this._minWidth=e,this.fire("resize"))}get minWidth(){return this._minWidth}set minHeight(e){e!==this._minHeight&&(this._minHeight=e,this.fire("resize"))}get minHeight(){return this._minHeight}set maxWidth(e){e!==this._maxWidth&&(this._maxWidth=e,this.fire("resize"))}get maxWidth(){return this._maxWidth}set maxHeight(e){e!==this._maxHeight&&(this._maxHeight=e,this.fire("resize"))}get maxHeight(){return this._maxHeight}set fitWidthProportion(e){e!==this._fitWidthProportion&&(this._fitWidthProportion=e,this.fire("resize"))}get fitWidthProportion(){return this._fitWidthProportion}set fitHeightProportion(e){e!==this._fitHeightProportion&&(this._fitHeightProportion=e,this.fire("resize"))}get fitHeightProportion(){return this._fitHeightProportion}set excludeFromLayout(e){e!==this._excludeFromLayout&&(this._excludeFromLayout=e,this.fire("resize"))}get excludeFromLayout(){return this._excludeFromLayout}}class nk{enabled=!0}const Xw=["enabled"];class ok extends Tt{constructor(e){super(e),this.id="layoutchild",this.ComponentType=Ww,this.DataType=nk,this.schema=Xw}initializeComponentData(e,t,s){t.enabled!==void 0&&(e.enabled=t.enabled),t.minWidth!==void 0&&(e.minWidth=t.minWidth),t.minHeight!==void 0&&(e.minHeight=t.minHeight),t.maxWidth!==void 0&&(e.maxWidth=t.maxWidth),t.maxHeight!==void 0&&(e.maxHeight=t.maxHeight),t.fitWidthProportion!==void 0&&(e.fitWidthProportion=t.fitWidthProportion),t.fitHeightProportion!==void 0&&(e.fitHeightProportion=t.fitHeightProportion),t.excludeFromLayout!==void 0&&(e.excludeFromLayout=t.excludeFromLayout),super.initializeComponentData(e,t,s)}cloneComponent(e,t){const s=e.layoutchild;return this.addComponent(t,{enabled:s.enabled,minWidth:s.minWidth,minHeight:s.minHeight,maxWidth:s.maxWidth,maxHeight:s.maxHeight,fitWidthProportion:s.fitWidthProportion,fitHeightProportion:s.fitHeightProportion,excludeFromLayout:s.excludeFromLayout})}}ye._buildAccessors(Ww.prototype,Xw);const w_=0,lk=1,t0=2,ck=3,yu={};yu[Me]={axis:"x",size:"width",calculatedSize:"calculatedWidth",minSize:"minWidth",maxSize:"maxWidth",fitting:"widthFitting",fittingProportion:"fitWidthProportion"};yu[rt]={axis:"y",size:"height",calculatedSize:"calculatedHeight",minSize:"minHeight",maxSize:"maxHeight",fitting:"heightFitting",fittingProportion:"fitHeightProportion"};const $g={};$g[Me]=rt;$g[rt]=Me;const hk={minWidth:0,minHeight:0,maxWidth:Number.POSITIVE_INFINITY,maxHeight:Number.POSITIVE_INFINITY,width:null,height:null,fitWidthProportion:0,fitHeightProportion:0},Rs={NONE:"NONE",APPLY_STRETCHING:"APPLY_STRETCHING",APPLY_SHRINKING:"APPLY_SHRINKING"},Ls=new j;function Yw(l){let e;const t=yu[l],s=yu[$g[l]];function i(A,M){return-M[t.size]*A.pivot[t.axis]}function r(A,M){return-M[s.size]*A.pivot[s.axis]}function a(A,M){return M[t.size]*(1-A.pivot[t.axis])}function n(A,M){A=A.filter(o),e=M,Ls.x=e.containerSize.x-e.padding.x-e.padding.z,Ls.y=e.containerSize.y-e.padding.y-e.padding.w,c(A);const R=d(h(A)),F=f(R,u(R)),U=x(R,F);return y(R,F,U),S(R,F,U),T(R)}function o(A){const M=A.entity.layoutchild;return!M||!M.enabled||!M.excludeFromLayout}function c(A){for(let M=0;M<A.length;++M){const R=A[M],F=R.anchor;(F.x!==0||F.y!==0||F.z!==0||F.w!==0)&&(R.anchor=ie.ZERO)}}function h(A){if(!e.wrap)return[A];const M=[[]],R=w(A);let F=0;const U=e[t.fitting]===t0;for(let B=0;B<A.length;++B){M[M.length-1].length>0&&(F+=e.spacing[t.axis]);const z=R[B][t.size];F+=z,!U&&F>Ls[t.axis]&&M[M.length-1].length!==0&&(F=z,M.push([])),M[M.length-1].push(A[B]),U&&F>Ls[t.axis]&&B!==A.length-1&&(F=0,M.push([]))}return M}function d(A){const M=e.orientation===Me&&e.reverseX||e.orientation===rt&&e.reverseY,R=e.orientation===Me&&e.reverseY||e.orientation===rt&&e.reverseX;if(M)for(let F=0;F<A.length;++F)M&&A[F].reverse();return R&&A.reverse(),A}function u(A){const M=[];for(let R=0;R<A.length;++R){const F=A[R],U=w(F),B=m(U,t),z=p(e[t.fitting],B,Ls[t.axis]);z===Rs.APPLY_STRETCHING?_(U,B,t):z===Rs.APPLY_SHRINKING&&g(U,B,t),M.push(U)}return M}function f(A,M){const R=[],F=[];for(let z=0;z<A.length;++z){const $=A[z];$.largestElement=null,$.largestSize={width:Number.NEGATIVE_INFINITY,height:Number.NEGATIVE_INFINITY};for(let K=0;K<$.length;++K){const Y=M[z][K];Y[s.size]>$.largestSize[s.size]&&($.largestElement=$[K],$.largestSize=Y)}R.push($.largestElement),F.push($.largestSize)}const U=m(F,s),B=p(e[s.fitting],U,Ls[s.axis]);B===Rs.APPLY_STRETCHING?_(F,U,s):B===Rs.APPLY_SHRINKING&&g(F,U,s);for(let z=0;z<A.length;++z){const $=A[z];for(let K=0;K<$.length;++K){const Y=M[z][K],te=Y[s.size],J=A.length===1?Ls[s.axis]:$.largestSize[s.size],_e=p(e[s.fitting],te,J);_e===Rs.APPLY_STRETCHING?Y[s.size]=Math.min(J,Y[s.maxSize]):_e===Rs.APPLY_SHRINKING&&(Y[s.size]=Math.max(J,Y[s.minSize]))}}return M}function p(A,M,R){switch(A){case w_:return Rs.NONE;case lk:return M<R?Rs.APPLY_STRETCHING:Rs.NONE;case t0:return M>=R?Rs.APPLY_SHRINKING:Rs.NONE;case ck:return M<R?Rs.APPLY_STRETCHING:Rs.APPLY_SHRINKING;default:throw new Error(`Unrecognized fitting mode: ${A}`)}}function m(A,M){const R=I(A,M.size),F=(A.length-1)*e.spacing[M.axis];return R+F}function _(A,M,R){const F=O(A,R.maxSize),U=P(A,R.fittingProportion),B=k(U,F);let z=Ls[R.axis]-M;for(let $=0;$<A.length;++$){const K=F[$],Y=v(K,z,U,B),te=A[K][R.size]+Y,J=A[K][R.maxSize],_e=Math.min(te,J);A[K][R.size]=_e;const Ae=Math.max(te-_e,0),we=Y-Ae;z-=we}}function g(A,M,R){const F=O(A,R.minSize,!0),U=P(A,R.fittingProportion),B=L(U),z=k(B,F);let $=M-Ls[R.axis];for(let K=0;K<A.length;++K){const Y=F[K],te=v(Y,$,B,z),J=A[Y][R.size]-te,_e=A[Y][R.minSize],Ae=Math.max(J,_e);A[Y][R.size]=Ae;const we=Math.max(Ae-J,0),$e=te-we;$-=$e}}function v(A,M,R,F){const U=R[A],B=F[A];return Math.abs(U)<1e-5&&Math.abs(B)<1e-5?M:M*U/B}function x(A,M){const R={};R[t.axis]=0,R[s.axis]=0,A[t.size]=Number.NEGATIVE_INFINITY;const F=[];for(let U=0;U<A.length;++U){const B=A[U];if(B.length===0){F.push([]);continue}const z=[],$=M[U];for(let K=0;K<B.length;++K){const Y=B[K],te=$[K];R[s.axis]-=r(Y,te),R[t.axis]-=i(Y,te),z[K]={},z[K][t.axis]=R[t.axis],z[K][s.axis]=R[s.axis],R[s.axis]+=r(Y,te),R[t.axis]+=a(Y,te)+e.spacing[t.axis]}B[t.size]=R[t.axis]-e.spacing[t.axis],B[s.size]=B.largestSize[s.size],A[t.size]=Math.max(A[t.size],B[t.size]),R[t.axis]=0,R[s.axis]+=B[s.size]+e.spacing[s.axis],F.push(z)}return A[s.size]=R[s.axis]-e.spacing[s.axis],F}function y(A,M,R){const F=e.alignment[t.axis],U=e.alignment[s.axis],B=e.padding[t.axis],z=e.padding[s.axis];for(let $=0;$<A.length;++$){const K=A[$],Y=M[$],te=R[$],J=(Ls[t.axis]-K[t.size])*F+B,_e=(Ls[s.axis]-A[s.size])*U+z;for(let Ae=0;Ae<K.length;++Ae){const we=(K[s.size]-Y[Ae][s.size])*e.alignment[s.axis];te[Ae][t.axis]+=J,te[Ae][s.axis]+=_e+we}}}function S(A,M,R){for(let F=0;F<A.length;++F){const U=A[F],B=M[F],z=R[F];for(let $=0;$<U.length;++$){const K=U[$];K[t.calculatedSize]=B[$][t.size],K[s.calculatedSize]=B[$][s.size],e.orientation===Me?K.entity.setLocalPosition(z[$][t.axis],z[$][s.axis],K.entity.getLocalPosition().z):K.entity.setLocalPosition(z[$][s.axis],z[$][t.axis],K.entity.getLocalPosition().z)}}}function T(A){const M=A.width,R=A.height,F=(Ls.x-M)*e.alignment.x+e.padding.x,U=(Ls.y-R)*e.alignment.y+e.padding.y;return{bounds:new ie(F,U,M,R)}}function w(A){const M=[];for(let R=0;R<A.length;++R){const F=A[R],U=Math.max(C(F,"minWidth"),0),B=Math.max(C(F,"minHeight"),0),z=Math.max(C(F,"maxWidth"),U),$=Math.max(C(F,"maxHeight"),B),K=b(C(F,"width"),U,z),Y=b(C(F,"height"),B,$),te=C(F,"fitWidthProportion"),J=C(F,"fitHeightProportion");M.push({minWidth:U,minHeight:B,maxWidth:z,maxHeight:$,width:K,height:Y,fitWidthProportion:te,fitHeightProportion:J})}return M}function C(A,M){const R=A.entity.layoutchild;return R&&R.enabled&&R[M]!==void 0&&R[M]!==null?R[M]:A[M]!==void 0?A[M]:hk[M]}function b(A,M,R){return Math.min(Math.max(A,M),R)}function I(A,M){return A.reduce((R,F)=>R+F[M],0)}function P(A,M){const R=I(A,M),F=[],U=A.length;if(R===0)for(let B=0;B<U;++B)F.push(1/U);else for(let B=0;B<U;
11887++B)F.push(A[B][M]/R);return F}function L(A){if(A.length===1)return[1];const M=[],R=A.length;for(let F=0;F<R;++F)M.push((1-A[F])/(R-1));return M}function O(A,M,R){return A.forEach(D),A.slice().sort((F,U)=>R?U[M]-F[M]:F[M]-U[M]).map(N)}function D(A,M){A.index=M}function N(A){return A.index}function k(A,M){const R=[];R[M[A.length-1]]=A[M[A.length-1]];for(let F=A.length-2;F>=0;--F)R[M[F]]=R[M[F+1]]+A[M[F]];return R}return n}const Kg={};Kg[Me]=Yw(Me);Kg[rt]=Yw(rt);class dk{calculateLayout(e,t){const s=Kg[t.orientation];if(s)return s(e,t);throw new Error(`Unrecognized orientation value: ${t.orientation}`)}}function s0(l){return l.element}function uk(l){return l.enabled&&l.element&&l.element.enabled}class jw extends ye{_orientation=Me;_reverseX=!1;_reverseY=!0;_alignment=new j(0,1);_padding=new ie;_spacing=new j;_widthFitting=w_;_heightFitting=w_;_wrap=!1;_layoutCalculator=new dk;constructor(e,t){super(e,t),this._listenForReflowEvents(this.entity,"on"),this.entity.children.forEach(s=>{this._listenForReflowEvents(s,"on")}),this.entity.on("childinsert",this._onChildInsert,this),this.entity.on("childremove",this._onChildRemove,this),e.app.systems.element.on("add",this._onElementOrLayoutComponentAdd,this),e.app.systems.element.on("beforeremove",this._onElementOrLayoutComponentRemove,this),e.app.systems.layoutchild.on("add",this._onElementOrLayoutComponentAdd,this),e.app.systems.layoutchild.on("beforeremove",this._onElementOrLayoutComponentRemove,this)}set orientation(e){e!==this._orientation&&(this._orientation=e,this._scheduleReflow())}get orientation(){return this._orientation}set reverseX(e){e!==this._reverseX&&(this._reverseX=e,this._scheduleReflow())}get reverseX(){return this._reverseX}set reverseY(e){e!==this._reverseY&&(this._reverseY=e,this._scheduleReflow())}get reverseY(){return this._reverseY}set alignment(e){e.equals(this._alignment)||(this._alignment.copy(e),this._scheduleReflow())}get alignment(){return this._alignment}set padding(e){e.equals(this._padding)||(this._padding.copy(e),this._scheduleReflow())}get padding(){return this._padding}set spacing(e){e.equals(this._spacing)||(this._spacing.copy(e),this._scheduleReflow())}get spacing(){return this._spacing}set widthFitting(e){e!==this._widthFitting&&(this._widthFitting=e,this._scheduleReflow())}get widthFitting(){return this._widthFitting}set heightFitting(e){e!==this._heightFitting&&(this._heightFitting=e,this._scheduleReflow())}get heightFitting(){return this._heightFitting}set wrap(e){e!==this._wrap&&(this._wrap=e,this._scheduleReflow())}get wrap(){return this._wrap}_isSelfOrChild(e){return e===this.entity||this.entity.children.indexOf(e)!==-1}_listenForReflowEvents(e,t){e.element&&(e.element[t]("enableelement",this._scheduleReflow,this),e.element[t]("disableelement",this._scheduleReflow,this),e.element[t]("resize",this._scheduleReflow,this),e.element[t]("set:pivot",this._scheduleReflow,this)),e.layoutchild&&(e.layoutchild[t]("set_enabled",this._scheduleReflow,this),e.layoutchild[t]("resize",this._scheduleReflow,this))}_onElementOrLayoutComponentAdd(e){this._isSelfOrChild(e)&&(this._listenForReflowEvents(e,"on"),this._scheduleReflow())}_onElementOrLayoutComponentRemove(e){this._isSelfOrChild(e)&&(this._listenForReflowEvents(e,"off"),this._scheduleReflow())}_onChildInsert(e){this._listenForReflowEvents(e,"on"),this._scheduleReflow()}_onChildRemove(e){this._listenForReflowEvents(e,"off"),this._scheduleReflow()}_scheduleReflow(){this.enabled&&this.entity&&this.entity.enabled&&!this._isPerformingReflow&&this.system.scheduleReflow(this)}reflow(){const e=s0(this.entity),t=this.entity.children.filter(uk).map(s0);if(!e||t.length===0)return;const s=Math.max(e.calculatedWidth,0),i=Math.max(e.calculatedHeight,0),r={orientation:this._orientation,reverseX:this._reverseX,reverseY:this._reverseY,alignment:this._alignment,padding:this._padding,spacing:this._spacing,widthFitting:this._widthFitting,heightFitting:this._heightFitting,wrap:this._wrap,containerSize:new j(s,i)};this._isPerformingReflow=!0;const a=this._layoutCalculator.calculateLayout(t,r);this._isPerformingReflow=!1,this.fire("reflow",a)}onEnable(){this._scheduleReflow()}onRemove(){this.entity.off("childinsert",this._onChildInsert,this),this.entity.off("childremove",this._onChildRemove,this),this._listenForReflowEvents(this.entity,"off"),this.entity.children.forEac
11887h(e=>{this._listenForReflowEvents(e,"off")}),this.system.app.systems.element.off("add",this._onElementOrLayoutComponentAdd,this),this.system.app.systems.element.off("beforeremove",this._onElementOrLayoutComponentRemove,this),this.system.app.systems.layoutchild.off("add",this._onElementOrLayoutComponentAdd,this),this.system.app.systems.layoutchild.off("beforeremove",this._onElementOrLayoutComponentRemove,this)}}class fk{enabled=!0}const qw=["enabled"],pk=100;class mk extends Tt{constructor(e){super(e),this.id="layoutgroup",this.ComponentType=jw,this.DataType=fk,this.schema=qw,this._reflowQueue=[],this.on("beforeremove",this._onRemoveComponent,this),this.app.systems.on("postUpdate",this._onPostUpdate,this)}initializeComponentData(e,t,s){t.enabled!==void 0&&(e.enabled=t.enabled),t.orientation!==void 0&&(e.orientation=t.orientation),t.reverseX!==void 0&&(e.reverseX=t.reverseX),t.reverseY!==void 0&&(e.reverseY=t.reverseY),t.alignment!==void 0&&(e.alignment=Array.isArray(t.alignment)?new j(t.alignment):t.alignment),t.padding!==void 0&&(e.padding=Array.isArray(t.padding)?new ie(t.padding):t.padding),t.spacing!==void 0&&(e.spacing=Array.isArray(t.spacing)?new j(t.spacing):t.spacing),t.widthFitting!==void 0&&(e.widthFitting=t.widthFitting),t.heightFitting!==void 0&&(e.heightFitting=t.heightFitting),t.wrap!==void 0&&(e.wrap=t.wrap),super.initializeComponentData(e,t,s)}cloneComponent(e,t){const s=e.layoutgroup;return this.addComponent(t,{enabled:s.enabled,orientation:s.orientation,reverseX:s.reverseX,reverseY:s.reverseY,alignment:s.alignment,padding:s.padding,spacing:s.spacing,widthFitting:s.widthFitting,heightFitting:s.heightFitting,wrap:s.wrap})}scheduleReflow(e){this._reflowQueue.indexOf(e)===-1&&this._reflowQueue.push(e)}_onPostUpdate(){this._processReflowQueue()}_processReflowQueue(){if(this._reflowQueue.length===0)return;let e=0;for(;this._reflowQueue.length>0;){const t=this._reflowQueue.slice();this._reflowQueue.length=0,t.sort((s,i)=>s.entity.graphDepth-i.entity.graphDepth);for(let s=0;s<t.length;++s)t[s].reflow();if(++e>=pk){console.warn("Max reflow iterations limit reached, bailing.");break}}}_onRemoveComponent(e,t){t.onRemove()}destroy(){super.destroy(),this.app.systems.off("postUpdate",this._onPostUpdate,this)}}ye._buildAccessors(jw.prototype,qw);class _k{map=new Map;destroy(e){this.map.forEach(t=>t.mesh.destroy())}}const gk=new Jt,$w=(l,e)=>{const t=gk.get(l,()=>new _k);let s=t.map.get(e);if(!s){let i,r;switch(e){case"box":i=at.fromGeometry(l,new a_),r={x:2,y:2,z:2,uv:2/3};break;case"capsule":i=at.fromGeometry(l,new XM({radius:.5,height:2})),r={x:Math.PI*2,y:Math.PI,z:Math.PI*2,uv:1/3+1/3/3*2};break;case"cone":i=at.fromGeometry(l,new YM({baseRadius:.5,peakRadius:0,height:1})),r={x:2.54,y:2.54,z:2.54,uv:1/3+1/3/3};break;case"cylinder":i=at.fromGeometry(l,new jM({radius:.5,height:1})),r={x:Math.PI,y:.79*2,z:Math.PI,uv:1/3+1/3/3*2};break;case"plane":i=at.fromGeometry(l,new qM({halfExtents:new j(.5,.5),widthSegments:1,lengthSegments:1})),r={x:0,y:1,z:0,uv:1};break;case"sphere":i=at.fromGeometry(l,new rw({radius:.5})),r={x:Math.PI,y:Math.PI,z:Math.PI,uv:1};break;case"torus":i=at.fromGeometry(l,new $M({tubeRadius:.2,ringRadius:.3})),r={x:Math.PI*.5*.5-Math.PI*.1*.1,y:.4,z:.4,uv:1};break;default:throw new Error(`Invalid primitive type: ${e}`)}i.incRefCount(),s={mesh:i,area:r},t.map.set(e,s)}return s};class Zg extends ye{_type="asset";_asset=null;_model=null;_mapping={};_castShadows=!0;_receiveShadows=!0;_materialAsset=null;_material;_castShadowsLightmap=!0;_lightmapped=!1;_lightmapSizeMultiplier=1;isStatic=!1;_layers=[Ir];_batchGroupId=-1;_customAabb=null;_area=null;_materialEvents=null;_clonedModel=!1;_evtLayersChanged=null;_evtLayerAdded=null;_evtLayerRemoved=null;constructor(e,t){super(e,t),this._material=e.defaultMaterial,t.on("remove",this.onRemoveChild,this),t.on("removehierarchy",this.onRemoveChild,this),t.on("insert",this.onInsertChild,this),t.on("inserthierarchy",this.onInsertChild,this)}set meshInstances(e){this._model&&(this._model.meshInstances=e)}get meshInstances(){return this._model?this._model.meshInstances:null}set customAabb(e){if(this._customAabb=e,this._model){const t=this._model.meshInstances;if(t)for(let s=0;s<t.length;s++)t[s].setCustomAabb(this._customAabb)}}get customAabb(){return this._customAabb}set type(e){if(this._type!==e)if(this._area=null,this._type=e,e==="asset")this._asset!==null?this._bindModelAsset(this._asset):this.model=null;
11887else{const t=$w(this.system.app.graphicsDevice,e);this._area=t.area;const s=t.mesh,i=new He,r=new pa;r.graph=i,r.meshInstances=[new Ne(s,this._material,i)],this.model=r,this._asset=null}}get type(){return this._type}set asset(e){const t=this.system.app.assets;let s=e;if(e instanceof pe&&(s=e.id),this._asset!==s){if(this._asset){t.off(`add:${this._asset}`,this._onModelAssetAdded,this);const i=t.get(this._asset);i&&this._unbindModelAsset(i)}if(this._asset=s,this._asset){const i=t.get(this._asset);i?this._bindModelAsset(i):(this.model=null,t.on(`add:${this._asset}`,this._onModelAssetAdded,this))}else this.model=null}}get asset(){return this._asset}set model(e){if(this._model!==e&&!(e&&e._immutable)&&(this._model&&(this._model._immutable=!1,this.removeModelFromLayers(),this._model.getGraph().destroy(),delete this._model._entity,this._clonedModel&&(this._model.destroy(),this._clonedModel=!1)),this._model=e,this._model)){this._model._immutable=!0;const t=this._model.meshInstances;for(let s=0;s<t.length;s++)t[s].castShadow=this._castShadows,t[s].receiveShadow=this._receiveShadows,t[s].setCustomAabb(this._customAabb);this.lightmapped=this._lightmapped,this.entity.addChild(this._model.graph),this.enabled&&this.entity.enabled&&this.addModelToLayers(),this._model._entity=this.entity,this.entity.animation&&this.entity.animation.setModel(this._model),this.entity.anim&&this.entity.anim.rebind(),this.type==="asset"?this.mapping=this._mapping:this._unsetMaterialEvents()}}get model(){return this._model}set lightmapped(e){if(e!==this._lightmapped&&(this._lightmapped=e,this._model)){const t=this._model.meshInstances;for(let s=0;s<t.length;s++)t[s].setLightmapped(e)}}get lightmapped(){return this._lightmapped}set castShadows(e){if(this._castShadows===e)return;const t=this._model;if(t){const s=this.layers,i=this.system.app.scene;if(this._castShadows&&!e)for(let a=0;a<s.length;a++){const n=this.system.app.scene.layers.getLayerById(this.layers[a]);n&&n.removeShadowCasters(t.meshInstances)}const r=t.meshInstances;for(let a=0;a<r.length;a++)r[a].castShadow=e;if(!this._castShadows&&e)for(let a=0;a<s.length;a++){const n=i.layers.getLayerById(s[a]);n&&n.addShadowCasters(t.meshInstances)}}this._castShadows=e}get castShadows(){return this._castShadows}set receiveShadows(e){if(this._receiveShadows!==e&&(this._receiveShadows=e,this._model)){const t=this._model.meshInstances;for(let s=0,i=t.length;s<i;s++)t[s].receiveShadow=e}}get receiveShadows(){return this._receiveShadows}set castShadowsLightmap(e){this._castShadowsLightmap=e}get castShadowsLightmap(){return this._castShadowsLightmap}set lightmapSizeMultiplier(e){this._lightmapSizeMultiplier=e}get lightmapSizeMultiplier(){return this._lightmapSizeMultiplier}set layers(e){const t=this.system.app.scene.layers;if(this.meshInstances)for(let s=0;s<this._layers.length;s++){const i=t.getLayerById(this._layers[s]);i&&i.removeMeshInstances(this.meshInstances)}this._layers.length=0;for(let s=0;s<e.length;s++)this._layers[s]=e[s];if(!(!this.enabled||!this.entity.enabled||!this.meshInstances))for(let s=0;s<this._layers.length;s++){const i=t.getLayerById(this._layers[s]);i&&i.addMeshInstances(this.meshInstances)}}get layers(){return this._layers}set batchGroupId(e){this._batchGroupId!==e&&(this.entity.enabled&&this._batchGroupId>=0&&this.system.app.batcher?.remove(Zt.MODEL,this.batchGroupId,this.entity),this.entity.enabled&&e>=0&&this.system.app.batcher?.insert(Zt.MODEL,e,this.entity),e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addModelToLayers(),this._batchGroupId=e)}get batchGroupId(){return this._batchGroupId}set materialAsset(e){let t=e;e instanceof pe&&(t=e.id);const s=this.system.app.assets;if(t!==this._materialAsset){if(this._materialAsset){s.off(`add:${this._materialAsset}`,this._onMaterialAssetAdd,this);const i=s.get(this._materialAsset);i&&this._unbindMaterialAsset(i)}if(this._materialAsset=t,this._materialAsset){const i=s.get(this._materialAsset);i?this._bindMaterialAsset(i):(this._setMaterial(this.system.defaultMaterial),s.on(`add:${this._materialAsset}`,this._onMaterialAssetAdd,this))}else this._setMaterial(this.system.defaultMaterial)}}get materialAsset(){return this._materialAsset}set material(e){this._material!==e&&(this.materialAsset=null,this._setMaterial(e))}get material(){return this._material}set mapping(e){if(this._type!=="asset"||(this._unsetMaterialEvents(),e||(e={}),this._mapping=e,!this._model))return;
11887const t=this._model.meshInstances,s=this.asset?this.system.app.assets.get(this.asset):null,i=s?s.data.mapping:null;let r=null;for(let a=0,n=t.length;a<n;a++)if(e[a]!==void 0)e[a]?(r=this.system.app.assets.get(e[a]),this._loadAndSetMeshInstanceMaterial(r,t[a],a)):t[a].material=this.system.defaultMaterial;else if(i)if(i[a]&&(i[a].material||i[a].path)){if(i[a].material!==void 0)r=this.system.app.assets.get(i[a].material);else if(i[a].path!==void 0){const o=this._getMaterialAssetUrl(i[a].path);o&&(r=this.system.app.assets.getByUrl(o))}this._loadAndSetMeshInstanceMaterial(r,t[a],a)}else t[a].material=this.system.defaultMaterial}get mapping(){return this._mapping}addModelToLayers(){const e=this.system.app.scene.layers;for(let t=0;t<this._layers.length;t++){const s=e.getLayerById(this._layers[t]);s&&s.addMeshInstances(this.meshInstances)}}removeModelFromLayers(){const e=this.system.app.scene.layers;for(let t=0;t<this._layers.length;t++){const s=e.getLayerById(this._layers[t]);s&&s.removeMeshInstances(this.meshInstances)}}onRemoveChild(){this._model&&this.removeModelFromLayers()}onInsertChild(){this._model&&this.enabled&&this.entity.enabled&&this.addModelToLayers()}onRemove(){this.asset=null,this.model=null,this.materialAsset=null,this._unsetMaterialEvents(),this.entity.off("remove",this.onRemoveChild,this),this.entity.off("insert",this.onInsertChild,this)}onLayersChanged(e,t){this.addModelToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this)}onLayerAdded(e){this.layers.indexOf(e.id)<0||e.addMeshInstances(this.meshInstances)}onLayerRemoved(e){this.layers.indexOf(e.id)<0||e.removeMeshInstances(this.meshInstances)}_setMaterialEvent(e,t,s,i){const r=`${t}:${s}`;this.system.app.assets.on(r,i,this),this._materialEvents||(this._materialEvents=[]),this._materialEvents[e]||(this._materialEvents[e]={}),this._materialEvents[e][r]={id:s,handler:i}}_unsetMaterialEvents(){const e=this.system.app.assets,t=this._materialEvents;if(t){for(let s=0,i=t.length;s<i;s++){if(!t[s])continue;const r=t[s];for(const a in r)e.off(a,r[a].handler,this)}this._materialEvents=null}}_getAssetByIdOrPath(e){let t=null;if(!isNaN(parseInt(e,10)))t=this.system.app.assets.get(e);else if(this.asset){const i=this._getMaterialAssetUrl(e);i&&(t=this.system.app.assets.getByUrl(i))}return t}_getMaterialAssetUrl(e){if(!this.asset)return null;const t=this.system.app.assets.get(this.asset);return t?t.getAbsoluteUrl(e):null}_loadAndSetMeshInstanceMaterial(e,t,s){const i=this.system.app.assets;e&&(e.resource?(t.material=e.resource,this._setMaterialEvent(s,"remove",e.id,function(){t.material=this.system.defaultMaterial})):(this._setMaterialEvent(s,"load",e.id,function(r){t.material=r.resource,this._setMaterialEvent(s,"remove",e.id,function(){t.material=this.system.defaultMaterial})}),this.enabled&&this.entity.enabled&&i.load(e)))}onEnable(){const e=this.system.app,t=e.scene,s=t?.layers;this._evtLayersChanged=t.on("set:layers",this.onLayersChanged,this),s&&(this._evtLayerAdded=s.on("add",this.onLayerAdded,this),this._evtLayerRemoved=s.on("remove",this.onLayerRemoved,this));const i=this._type==="asset";let r;if(this._model?this.addModelToLayers():i&&this._asset&&(r=e.assets.get(this._asset),r&&r.resource!==this._model&&this._bindModelAsset(r)),this._materialAsset&&(r=e.assets.get(this._materialAsset),r&&r.resource!==this._material&&this._bindMaterialAsset(r)),i&&this._mapping)for(const a in this._mapping)this._mapping[a]&&(r=this._getAssetByIdOrPath(this._mapping[a]),r&&!r.resource&&e.assets.load(r));this._batchGroupId>=0&&e.batcher?.insert(Zt.MODEL,this.batchGroupId,this.entity)}onDisable(){const e=this.system.app,s=e.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,s&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this._batchGroupId>=0&&e.batcher?.remove(Zt.MODEL,this.batchGroupId,this.entity),this._model&&this.removeModelFromLayers()}hide(){if(this._model){const e=this._model.meshInstances;for(let t=0,s=e.length;t<s;t++)e[t].visible=!1}}show(){if(this._model){const e=this._model.meshInstances;for(let t=0,s=e.length;t<s;t++)e[t].visible=!0}}_bindMaterialAsset(e){if(e.on("load",this._onMaterialAssetLoad,this),e.on("unload",this._onMaterialAssetUnload,this),e.on("remove",this._onMaterialAssetRemove,this),e.on("change",this._onMaterialAssetChange,this),e.resource)this._onMaterialAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;
11887this.system.app.assets.load(e)}}_unbindMaterialAsset(e){e.off("load",this._onMaterialAssetLoad,this),e.off("unload",this._onMaterialAssetUnload,this),e.off("remove",this._onMaterialAssetRemove,this),e.off("change",this._onMaterialAssetChange,this)}_onMaterialAssetAdd(e){this.system.app.assets.off(`add:${e.id}`,this._onMaterialAssetAdd,this),this._materialAsset===e.id&&this._bindMaterialAsset(e)}_onMaterialAssetLoad(e){this._setMaterial(e.resource)}_onMaterialAssetUnload(e){this._setMaterial(this.system.defaultMaterial)}_onMaterialAssetRemove(e){this._onMaterialAssetUnload(e)}_onMaterialAssetChange(e){}_bindModelAsset(e){if(this._unbindModelAsset(e),e.on("load",this._onModelAssetLoad,this),e.on("unload",this._onModelAssetUnload,this),e.on("change",this._onModelAssetChange,this),e.on("remove",this._onModelAssetRemove,this),e.resource)this._onModelAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}}_unbindModelAsset(e){e.off("load",this._onModelAssetLoad,this),e.off("unload",this._onModelAssetUnload,this),e.off("change",this._onModelAssetChange,this),e.off("remove",this._onModelAssetRemove,this)}_onModelAssetAdded(e){this.system.app.assets.off(`add:${e.id}`,this._onModelAssetAdded,this),e.id===this._asset&&this._bindModelAsset(e)}_onModelAssetLoad(e){this.model=e.resource.clone(),this._clonedModel=!0}_onModelAssetUnload(e){this.model=null}_onModelAssetChange(e,t,s,i){t==="data"&&(this.mapping=this._mapping)}_onModelAssetRemove(e){this.model=null}_setMaterial(e){if(this._material===e)return;this._material=e;const t=this._model;if(t&&this._type!=="asset"){const s=t.meshInstances;for(let i=0,r=s.length;i<r;i++)s[i].material=e}}}class vk{enabled=!0}const Kw=["enabled"];class Sk extends Tt{constructor(e){super(e),this.id="model",this.ComponentType=Zg,this.DataType=vk,this.schema=Kw,this.defaultMaterial=Zo(e.graphicsDevice),this.on("beforeremove",this.onRemove,this)}initializeComponentData(e,t,s){s=["material","materialAsset","asset","castShadows","receiveShadows","castShadowsLightmap","lightmapped","lightmapSizeMultiplier","type","mapping","layers","isStatic","batchGroupId"],(t.batchGroupId===null||t.batchGroupId===void 0)&&(t.batchGroupId=-1),t.layers&&t.layers.length&&(t.layers=t.layers.slice(0));for(let i=0;i<s.length;i++)t.hasOwnProperty(s[i])&&(e[s[i]]=t[s[i]]);t.aabbCenter&&t.aabbHalfExtents&&(e.customAabb=new Le(new E(t.aabbCenter),new E(t.aabbHalfExtents))),super.initializeComponentData(e,t,["enabled"])}cloneComponent(e,t){const s={type:e.model.type,asset:e.model.asset,castShadows:e.model.castShadows,receiveShadows:e.model.receiveShadows,castShadowsLightmap:e.model.castShadowsLightmap,lightmapped:e.model.lightmapped,lightmapSizeMultiplier:e.model.lightmapSizeMultiplier,isStatic:e.model.isStatic,enabled:e.model.enabled,layers:e.model.layers,batchGroupId:e.model.batchGroupId,mapping:Ud({},e.model.mapping)};let i=e.model.materialAsset;!(i instanceof pe)&&i!=null&&(i=this.app.assets.get(i));const r=e.model.material;(!r||r===this.defaultMaterial||!i||r===i.resource)&&(s.materialAsset=i);const a=this.addComponent(t,s);if(e.model.model&&e.model.type==="asset"&&!e.model.asset&&(a.model=e.model.model.clone(),a._clonedModel=!0),s.materialAsset||(a.material=r),e.model.model){const n=e.model.model.meshInstances,o=a.model.meshInstances;for(let c=0;c<n.length;c++)o[c].mask=n[c].mask,o[c].material=n[c].material,o[c].layer=n[c].layer,o[c].receiveShadow=n[c].receiveShadow}return e.model.customAabb&&(a.customAabb=e.model.customAabb.clone()),a}onRemove(e,t){t.onRemove()}}ye._buildAccessors(Zg.prototype,Kw);const yk=["emitterExtents","emitterRadius","emitterExtentsInner","emitterRadiusInner","loop","initialVelocity","animSpeed","normalMap","particleNormal"],xk=["numParticles","lifetime","rate","rate2","startAngle","startAngle2","lighting","halfLambert","intensity","wrap","wrapBounds","depthWrite","noFog","sort","stretch","alignToMotion","preWarm","emitterShape","animTilesX","animTilesY","animStartFrame","animNumFrames","animNumAnimations","animIndex","randomizeAnimIndex","animLoop","colorMap","localSpace","screenSpace","orientation"],Tk=["scaleGraph","scaleGraph2","colorGraph","colorGraph2","alphaGraph","alphaGraph2","velocityGraph","velocityGraph2","localVelocityGraph","localVelocityGraph2","rotationSpeedGraph","rotationSpeedGraph2","radialSpeedGraph","radialSpeedGraph2"],id=["colorMapAsset","normalMapAsset","meshAsset","renderAsset"];let Zn;class wk extends ye{_requestedDepth=!1;_drawOrder=0;_evtLayersChanged=null;_evtLayerAdded=null;_evtLayerRemoved=null;_evtSetMeshes=null;constructor(e,t){super(e,t),this.on("set_colorMapAsset",this.onSetColorMapAsset,this),this.on("set_normalMapAsset",this.onSetNormalMapAsset,this),this.on("set_meshAsset",this.onSetMeshAsset,this),this.on("set_mesh",this.onSetMesh,this),this.on("set_renderAsset",this.onSetRenderAsset,this),this.on("set_loop",this.onSetLoop,this),this.on("set_blendType",this.onSetBlendType,this),this.on("set_depthSoftening",this.onSetDepthSoftening,this),this.on("set_layers",this.onSetLayers,this),yk.forEach(s=>{this.on(`set_${s}`,this.onSetSimpleProperty,this)}),xk.forEach(s=>{this.on(`set_${s}`,this.onSetComplexProperty,this)}
11887),Tk.forEach(s=>{this.on(`set_${s}`,this.onSetGraphProperty,this)})}set enabled(e){this._setValue("enabled",e)}get enabled(){return this.data.enabled}set autoPlay(e){this._setValue("autoPlay",e)}get autoPlay(){return this.data.autoPlay}set numParticles(e){this._setValue("numParticles",e)}get numParticles(){return this.data.numParticles}set lifetime(e){this._setValue("lifetime",e)}get lifetime(){return this.data.lifetime}set rate(e){this._setValue("rate",e)}get rate(){return this.data.rate}set rate2(e){this._setValue("rate2",e)}get rate2(){return this.data.rate2}set startAngle(e){this._setValue("startAngle",e)}get startAngle(){return this.data.startAngle}set startAngle2(e){this._setValue("startAngle2",e)}get startAngle2(){return this.data.startAngle2}set loop(e){this._setValue("loop",e)}get loop(){return this.data.loop}set preWarm(e){this._setValue("preWarm",e)}get preWarm(){return this.data.preWarm}set lighting(e){this._setValue("lighting",e)}get lighting(){return this.data.lighting}set halfLambert(e){this._setValue("halfLambert",e)}get halfLambert(){return this.data.halfLambert}set intensity(e){this._setValue("intensity",e)}get intensity(){return this.data.intensity}set depthWrite(e){this._setValue("depthWrite",e)}get depthWrite(){return this.data.depthWrite}set noFog(e){this._setValue("noFog",e)}get noFog(){return this.data.noFog}set depthSoftening(e){this._setValue("depthSoftening",e)}get depthSoftening(){return this.data.depthSoftening}set sort(e){this._setValue("sort",e)}get sort(){return this.data.sort}set blendType(e){this._setValue("blendType",e)}get blendType(){return this.data.blendType}set stretch(e){this._setValue("stretch",e)}get stretch(){return this.data.stretch}set alignToMotion(e){this._setValue("alignToMotion",e)}get alignToMotion(){return this.data.alignToMotion}set emitterShape(e){this._setValue("emitterShape",e)}get emitterShape(){return this.data.emitterShape}set emitterExtents(e){this._setValue("emitterExtents",e)}get emitterExtents(){return this.data.emitterExtents}set emitterExtentsInner(e){this._setValue("emitterExtentsInner",e)}get emitterExtentsInner(){return this.data.emitterExtentsInner}set emitterRadius(e){this._setValue("emitterRadius",e)}get emitterRadius(){return this.data.emitterRadius}set emitterRadiusInner(e){this._setValue("emitterRadiusInner",e)}get emitterRadiusInner(){return this.data.emitterRadiusInner}set initialVelocity(e){this._setValue("initialVelocity",e)}get initialVelocity(){return this.data.initialVelocity}set wrap(e){this._setValue("wrap",e)}get wrap(){return this.data.wrap}set wrapBounds(e){this._setValue("wrapBounds",e)}get wrapBounds(){return this.data.wrapBounds}set localSpace(e){this._setValue("localSpace",e)}get localSpace(){return this.data.localSpace}set screenSpace(e){this._setValue("screenSpace",e)}get screenSpace(){return this.data.screenSpace}set colorMapAsset(e){this._setValue("colorMapAsset",e)}get colorMapAsset(){return this.data.colorMapAsset}set normalMapAsset(e){this._setValue("normalMapAsset",e)}get normalMapAsset(){return this.data.normalMapAsset}set mesh(e){this._setValue("mesh",e)}get mesh(){return this.data.mesh}set meshAsset(e){this._setValue("meshAsset",e)}get meshAsset(){return this.data.meshAsset}set renderAsset(e){this._setValue("renderAsset",e)}get renderAsset(){return this.data.renderAsset}set orientation(e){this._setValue("orientation",e)}get orientation(){return this.data.orientation}set particleNormal(e){this._setValue("particleNormal",e)}get particleNormal(){return this.data.particleNormal}set localVelocityGraph(e){this._setValue("localVelocityGraph",e)}get localVelocityGraph(){return this.data.localVelocityGraph}set localVelocityGraph2(e){this._setValue("localVelocityGraph2",e)}get localVelocityGraph2(){return this.data.localVelocityGraph2}set velocityGraph(e){this._setValue("velocityGraph",e)}get velocityGraph(){return this.data.velocityGraph}set velocityGraph2(e){this._setValue("velocityGraph2",e)}get velocityGraph2(){return this.data.velocityGraph2}set rotationSpeedGraph(e){this._setValue("rotationSpeedGraph",e)}get rotationSpeedGraph(){return this.data.rotationSpeedGraph}set rotationSpeedGraph2(e){this._setValue("rotationSpeedGraph2",e)}get rotationSpeedGraph2(){return this.data.rotationSpeedGraph2}set radialSpeedGraph(e){this._setValue("radialSpeedGraph",e)}get radialSpeedGraph(){return this.data.radialSpeedGraph}set radialSpeedGraph2(e){this._setValue("radialSpeedGraph2",e)}get radialSpeedGraph2(){return this.data.radialSpeedGraph2}set scaleGraph(e){this._setValue("scaleGraph",e)}get scaleGraph(){return this.data.scaleGraph}set scaleGraph2(e){this._setValue("scaleGraph2",e)}get scaleGraph2(){return this.data.scaleGraph2}set colorGraph(e){this._setValue("colorGraph",e)}get colorGraph(){return this.data.colorGraph}set colorGraph2(e){this._setValue("colorGraph2",e)}get colorGraph2(){return this.data.colorGraph2}set alphaGraph(e){this._setValue("alphaGraph",e)}get alphaGraph(){return this.data.alphaGraph}set alphaGraph2(e){this._setValue("alphaGraph2",e)}get alphaGraph2(){return this.data.alphaGraph2}set colorMap(e){this._setValue("colorMap",e)}get colorMap(){return this.data.colorMap}set normalMap(e){this._setValue("normalMap",e)}get normalMap(){return this.data.normalMap}set animTilesX(e){this._setValue("animTilesX",e)}get animTilesX(){return this.data.animTilesX}set animTilesY(e){this._setValue("animTilesY",e)}get animTilesY(){return this.data.animTilesY}set animStartFrame(e){this._setValue("animStartFrame",e)}get animStartFrame(){return this.data.animStartFrame}set animNumFrames(e){this._setValue("animNumFrames",e)}get animNumFrames(){return this.data.animNumFrames}set animNumAnimations(e){this._setValue("animNumAnimations",e)}get animNumAnimations(){return this.data.animNumAnimations}set animIndex(e){this._setValue("animIndex",e)}get animIndex(){return this.data.animIndex}set randomizeAnimIndex(e){this._setValue("randomizeAnimIndex",e)}get randomizeAnimIndex(){return this.data.randomizeAnimIndex}set animSpeed(e){this._setValue("animSpeed",e)}get animSpeed(){return this.data.animSpeed}set animLoop(e){this._setValue("animLoop",e)}get animLoop(){return this.data.animLoop}set layers(e){this._setValue("layers",e)}get layers(){return this.data.layers}set drawOrder(e){this._drawOrder=e,this.emitter&&(this.emitter.drawOrder=e)}get drawOrder(){return this._drawOrder}_setValue(e,t){const s=this.data,i=s[e];s[e]=t,this.fire("set",e,i,t)}addMeshInstanceToLayers(){if(this.emitter)for(let e=0;e<this.layers.length;
11887e++){const t=this.system.app.scene.layers.getLayerById(this.layers[e]);t&&(t.addMeshInstances([this.emitter.meshInstance]),this.emitter._layer=t)}}removeMeshInstanceFromLayers(){if(this.emitter)for(let e=0;e<this.layers.length;e++){const t=this.system.app.scene.layers.getLayerById(this.layers[e]);t&&t.removeMeshInstances([this.emitter.meshInstance])}}onSetLayers(e,t,s){if(this.emitter){for(let i=0;i<t.length;i++){const r=this.system.app.scene.layers.getLayerById(t[i]);r&&r.removeMeshInstances([this.emitter.meshInstance])}if(!(!this.enabled||!this.entity.enabled))for(let i=0;i<s.length;i++){const r=this.system.app.scene.layers.getLayerById(s[i]);r&&r.addMeshInstances([this.emitter.meshInstance])}}}onLayersChanged(e,t){this.addMeshInstanceToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this)}onLayerAdded(e){!this.emitter||this.layers.indexOf(e.id)<0||e.addMeshInstances([this.emitter.meshInstance])}onLayerRemoved(e){!this.emitter||this.layers.indexOf(e.id)<0||e.removeMeshInstances([this.emitter.meshInstance])}_bindColorMapAsset(e){if(e.on("load",this._onColorMapAssetLoad,this),e.on("unload",this._onColorMapAssetUnload,this),e.on("remove",this._onColorMapAssetRemove,this),e.on("change",this._onColorMapAssetChange,this),e.resource)this._onColorMapAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}}_unbindColorMapAsset(e){e.off("load",this._onColorMapAssetLoad,this),e.off("unload",this._onColorMapAssetUnload,this),e.off("remove",this._onColorMapAssetRemove,this),e.off("change",this._onColorMapAssetChange,this)}_onColorMapAssetLoad(e){this.colorMap=e.resource}_onColorMapAssetUnload(e){this.colorMap=null}_onColorMapAssetRemove(e){this._onColorMapAssetUnload(e)}_onColorMapAssetChange(e){}onSetColorMapAsset(e,t,s){const i=this.system.app.assets;if(t){const r=i.get(t);r&&this._unbindColorMapAsset(r)}if(s){s instanceof pe&&(this.data.colorMapAsset=s.id,s=s.id);const r=i.get(s);r?this._bindColorMapAsset(r):i.once(`add:${s}`,a=>{this._bindColorMapAsset(a)})}else this.colorMap=null}_bindNormalMapAsset(e){if(e.on("load",this._onNormalMapAssetLoad,this),e.on("unload",this._onNormalMapAssetUnload,this),e.on("remove",this._onNormalMapAssetRemove,this),e.on("change",this._onNormalMapAssetChange,this),e.resource)this._onNormalMapAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}}_unbindNormalMapAsset(e){e.off("load",this._onNormalMapAssetLoad,this),e.off("unload",this._onNormalMapAssetUnload,this),e.off("remove",this._onNormalMapAssetRemove,this),e.off("change",this._onNormalMapAssetChange,this)}_onNormalMapAssetLoad(e){this.normalMap=e.resource}_onNormalMapAssetUnload(e){this.normalMap=null}_onNormalMapAssetRemove(e){this._onNormalMapAssetUnload(e)}_onNormalMapAssetChange(e){}onSetNormalMapAsset(e,t,s){const i=this.system.app.assets;if(t){const r=i.get(t);r&&this._unbindNormalMapAsset(r)}if(s){s instanceof pe&&(this.data.normalMapAsset=s.id,s=s.id);const r=i.get(s);r?this._bindNormalMapAsset(r):i.once(`add:${s}`,a=>{this._bindNormalMapAsset(a)})}else this.normalMap=null}_bindMeshAsset(e){if(e.on("load",this._onMeshAssetLoad,this),e.on("unload",this._onMeshAssetUnload,this),e.on("remove",this._onMeshAssetRemove,this),e.on("change",this._onMeshAssetChange,this),e.resource)this._onMeshAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}}_unbindMeshAsset(e){e.off("load",this._onMeshAssetLoad,this),e.off("unload",this._onMeshAssetUnload,this),e.off("remove",this._onMeshAssetRemove,this),e.off("change",this._onMeshAssetChange,this)}_onMeshAssetLoad(e){this._onMeshChanged(e.resource)}_onMeshAssetUnload(e){this.mesh=null}_onMeshAssetRemove(e){this._onMeshAssetUnload(e)}_onMeshAssetChange(e){}onSetMeshAsset(e,t,s){const i=this.system.app.assets;if(t){const r=i.get(t);r&&this._unbindMeshAsset(r)}if(s){s instanceof pe&&(this.data.meshAsset=s.id,s=s.id);const r=i.get(s);r&&this._bindMeshAsset(r)}else this._onMeshChanged(null)}onSetMesh(e,t,s){!s||s instanceof pe||typeof s=="number"?this.meshAsset=s:this._onMeshChanged(s)}_onMeshChanged(e){e&&!(e instanceof at)&&(e.meshInstances[0]?e=e.meshInstances[0].mesh:e=null),this.data.mesh=e,this.emitter&&(this.emitter.mesh=e,this.emitter.resetMaterial(),this.rebuild())}
11887onSetRenderAsset(e,t,s){const i=this.system.app.assets;if(t){const r=i.get(t);r&&this._unbindRenderAsset(r)}if(s){s instanceof pe&&(this.data.renderAsset=s.id,s=s.id);const r=i.get(s);r&&this._bindRenderAsset(r)}else this._onRenderChanged(null)}_bindRenderAsset(e){if(e.on("load",this._onRenderAssetLoad,this),e.on("unload",this._onRenderAssetUnload,this),e.on("remove",this._onRenderAssetRemove,this),e.resource)this._onRenderAssetLoad(e);else{if(!this.enabled||!this.entity.enabled)return;this.system.app.assets.load(e)}}_unbindRenderAsset(e){e.off("load",this._onRenderAssetLoad,this),e.off("unload",this._onRenderAssetUnload,this),e.off("remove",this._onRenderAssetRemove,this),this._evtSetMeshes?.off(),this._evtSetMeshes=null}_onRenderAssetLoad(e){this._onRenderChanged(e.resource)}_onRenderAssetUnload(e){this._onRenderChanged(null)}_onRenderAssetRemove(e){this._onRenderAssetUnload(e)}_onRenderChanged(e){if(!e){this._onMeshChanged(null);return}this._evtSetMeshes?.off(),this._evtSetMeshes=e.on("set:meshes",this._onRenderSetMeshes,this),e.meshes&&this._onRenderSetMeshes(e.meshes)}_onRenderSetMeshes(e){this._onMeshChanged(e&&e[0])}onSetLoop(e,t,s){this.emitter&&(this.emitter[e]=s,this.emitter.resetTime())}onSetBlendType(e,t,s){this.emitter&&(this.emitter[e]=s,this.emitter.material.blendType=s,this.emitter.resetMaterial(),this.rebuild())}_requestDepth(){this._requestedDepth||(Zn||(Zn=this.system.app.scene.layers.getLayerById(ks)),Zn&&(Zn.incrementCounter(),this._requestedDepth=!0))}_releaseDepth(){this._requestedDepth&&Zn&&(Zn.decrementCounter(),this._requestedDepth=!1)}onSetDepthSoftening(e,t,s){t!==s&&(s?(this.enabled&&this.entity.enabled&&this._requestDepth(),this.emitter&&(this.emitter[e]=s)):(this.enabled&&this.entity.enabled&&this._releaseDepth(),this.emitter&&(this.emitter[e]=s)),this.emitter&&(this.reset(),this.emitter.resetMaterial(),this.rebuild()))}onSetSimpleProperty(e,t,s){this.emitter&&(this.emitter[e]=s,this.emitter.resetMaterial())}onSetComplexProperty(e,t,s){this.emitter&&(this.emitter[e]=s,this.emitter.resetMaterial(),this.rebuild(),this.reset())}onSetGraphProperty(e,t,s){this.emitter&&(this.emitter[e]=s,this.emitter.rebuildGraphs(),this.emitter.resetMaterial())}onEnable(){const e=this.system.app.scene,t=e.layers,s=this.data;for(let i=0,r=id.length;i<r;i++){let a=s[id[i]];if(a){if(!(a instanceof pe))if(parseInt(a,10)>=0)a=this.system.app.assets.get(a);else continue;a&&!a.resource&&this.system.app.assets.load(a)}}if(!this.system.app.graphicsDevice.disableParticleSystem){if(!this.emitter){let i=s.mesh;i instanceof at||(i=null),this.emitter=new CD(this.system.app.graphicsDevice,{numParticles:s.numParticles,emitterExtents:s.emitterExtents,emitterExtentsInner:s.emitterExtentsInner,emitterRadius:s.emitterRadius,emitterRadiusInner:s.emitterRadiusInner,emitterShape:s.emitterShape,initialVelocity:s.initialVelocity,wrap:s.wrap,localSpace:s.localSpace,screenSpace:s.screenSpace,wrapBounds:s.wrapBounds,lifetime:s.lifetime,rate:s.rate,rate2:s.rate2,orientation:s.orientation,particleNormal:s.particleNormal,animTilesX:s.animTilesX,animTilesY:s.animTilesY,animStartFrame:s.animStartFrame,animNumFrames:s.animNumFrames,animNumAnimations:s.animNumAnimations,animIndex:s.animIndex,randomizeAnimIndex:s.randomizeAnimIndex,animSpeed:s.animSpeed,animLoop:s.animLoop,startAngle:s.startAngle,startAngle2:s.startAngle2,scaleGraph:s.scaleGraph,scaleGraph2:s.scaleGraph2,colorGraph:s.colorGraph,colorGraph2:s.colorGraph2,alphaGraph:s.alphaGraph,alphaGraph2:s.alphaGraph2,localVelocityGraph:s.localVelocityGraph,localVelocityGraph2:s.localVelocityGraph2,velocityGraph:s.velocityGraph,velocityGraph2:s.velocityGraph2,rotationSpeedGraph:s.rotationSpeedGraph,rotationSpeedGraph2:s.rotationSpeedGraph2,radialSpeedGraph:s.radialSpeedGraph,radialSpeedGraph2:s.radialSpeedGraph2,colorMap:s.colorMap,normalMap:s.normalMap,loop:s.loop,preWarm:s.preWarm,sort:s.sort,stretch:s.stretch,alignToMotion:s.alignToMotion,lighting:s.lighting,halfLambert:s.halfLambert,intensity:s.intensity,depthSoftening:s.depthSoftening,scene:this.system.app.scene,mesh:i,depthWrite:s.depthWrite,noFog:s.noFog,node:this.entity,blendType:s.blendType}),this.emitter.meshInstance.node=this.entity,this.emitter.drawOrder=this.drawOrder,s.autoPlay||(this.pause(),this.emitter.meshInstance.visible=!1)}this.emitter.colorMap&&this.addMeshInstanceToLayers(),this._evtLayersChanged=e.on("set:layers",this.onLayersChanged,this),t&&(this._evtLayerAdded=t.on("add",this.onLayerAdded,this),this._evtLayerRemoved=t.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&s.depthSoftening&&this._requestDepth()}}
11887onDisable(){const t=this.system.app.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,t&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this.emitter&&(this.removeMeshInstanceFromLayers(),this.data.depthSoftening&&this._releaseDepth(),this.emitter.camera=null)}onBeforeRemove(){this.enabled&&(this.enabled=!1),this.emitter&&(this.emitter.destroy(),this.emitter=null);for(let e=0;e<id.length;e++){const t=id[e];this.data[t]&&(this[t]=null)}this.off()}reset(){this.emitter&&this.emitter.reset()}stop(){this.emitter&&(this.emitter.loop=!1,this.emitter.resetTime(),this.emitter.addTime(0,!0))}pause(){this.data.paused=!0}unpause(){this.data.paused=!1}play(){this.data.paused=!1,this.emitter&&(this.emitter.meshInstance.visible=!0,this.emitter.loop=this.data.loop,this.emitter.resetTime())}isPlaying(){return this.data.paused?!1:this.emitter&&this.emitter.loop?!0:Date.now()<=this.emitter.endTime}setInTools(){const{emitter:e}=this;e&&!e.inTools&&(e.inTools=!0,this.rebuild())}rebuild(){const e=this.enabled;this.enabled=!1,this.emitter&&this.emitter.rebuild(),this.enabled=e}}class Ck{numParticles=1;rate=1;rate2=null;startAngle=0;startAngle2=null;lifetime=50;emitterExtents=new E;emitterExtentsInner=new E;emitterRadius=0;emitterRadiusInner=0;emitterShape=Ri;initialVelocity=0;wrap=!1;wrapBounds=new E;localSpace=!1;screenSpace=!1;colorMap=null;colorMapAsset=null;normalMap=null;normalMapAsset=null;loop=!0;preWarm=!1;sort=0;mode=wT;scene=null;lighting=!1;halfLambert=!1;intensity=1;stretch=0;alignToMotion=!1;depthSoftening=0;renderAsset=null;meshAsset=null;mesh=null;depthWrite=!1;noFog=!1;orientation=ru;particleNormal=new E(0,1,0);animTilesX=1;animTilesY=1;animStartFrame=0;animNumFrames=1;animNumAnimations=1;animIndex=0;randomizeAnimIndex=!1;animSpeed=1;animLoop=!0;scaleGraph=null;scaleGraph2=null;colorGraph=null;colorGraph2=null;alphaGraph=null;alphaGraph2=null;localVelocityGraph=null;localVelocityGraph2=null;velocityGraph=null;velocityGraph2=null;rotationSpeedGraph=null;rotationSpeedGraph2=null;radialSpeedGraph=null;radialSpeedGraph2=null;blendType=Wi;enabled=!0;paused=!1;autoPlay=!0;layers=[Ir]}var Ek=` 11888varying vec4 texCoordsAlphaLife; 11889uniform sampler2D colorMap; 11890uniform sampler2D colorParam; 11891uniform float graphSampleSize; 11892uniform float graphNumSamples; 11893#ifndef CAMERAPLANES 11894 #define CAMERAPLANES 11895 uniform vec4 camera_params; 11896#endif 11897#ifdef SOFT 11898 uniform float softening; 11899#endif 11900uniform float colorMult; 11901float saturate(float x) { 11902 return clamp(x, 0.0, 1.0); 11903} 11904void main(void) { 11905 vec4 tex = texture2D(colorMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y)); 11906 vec4 ramp = texture2D(colorParam, vec2(texCoordsAlphaLife.w, 0.0)); 11907 ramp.rgb *= colorMult; 11908 ramp.a += texCoordsAlphaLife.z; 11909 vec3 rgb = tex.rgb * ramp.rgb; 11910 float a = tex.a * ramp.a; 11911`,bk=` 11912vec3 unpack3NFloats(float src) { 11913 float r = fract(src); 11914 float g = fract(src * 256.0); 11915 float b = fract(src * 65536.0); 11916 return vec3(r, g, b); 11917} 11918float saturate(float x) { 11919 return clamp(x, 0.0, 1.0); 11920} 11921vec4 tex1Dlod_lerp(TEXTURE_ACCEPT_HIGHP(tex), vec2 tc) { 11922 return mix( texture2D(tex,tc), texture2D(tex,tc + graphSampleSize), fract(tc.x*graphNumSamples) ); 11923} 11924vec4 tex1Dlod_lerp(TEXTURE_ACCEPT_HIGHP(tex), vec2 tc, out vec3 w) { 11925 vec4 a = texture2D(tex,tc); 11926 vec4 b = texture2D(tex,tc + graphSampleSize); 11927 float c = fract(tc.x*graphNumSamples); 11928 vec3 unpackedA = unpack3NFloats(a.w); 11929 vec3 unpackedB = unpack3NFloats(b.w);
11930 w = mix(unpackedA, unpackedB, c); 11931 return mix(a, b, c); 11932} 11933vec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix) { 11934 float c = cos(pRotation); 11935 float s = sin(pRotation); 11936 mat2 m = mat2(c, -s, s, c); 11937 rotMatrix = m; 11938 return m * quadXY; 11939} 11940vec3 billboard(vec3 InstanceCoords, vec2 quadXY) { 11941 #ifdef SCREEN_SPACE 11942 vec3 pos = vec3(-1, 0, 0) * quadXY.x + vec3(0, -1, 0) * quadXY.y; 11943 #else 11944 vec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y; 11945 #endif 11946 return pos; 11947} 11948vec3 customFace(vec3 InstanceCoords, vec2 quadXY) { 11949 vec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y; 11950 return pos; 11951} 11952vec2 safeNormalize(vec2 v) { 11953 float l = length(v); 11954 return (l > 1e-06) ? v / l : v; 11955} 11956void main(void) { 11957 vec3 meshLocalPos = particle_vertexData.xyz; 11958 float id = floor(particle_vertexData.w); 11959 float rndFactor = fract(sin(id + 1.0 + seed)); 11960 vec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0)); 11961 float uv = id / numParticlesPot; 11962 readInput(uv); 11963#ifdef LOCAL_SPACE 11964 inVel = mat3(matrix_model) * inVel; 11965#endif 11966 vec2 velocityV = safeNormalize((mat3(matrix_view) * inVel).xy); 11967 float particleLifetime = lifetime; 11968 if (inLife <= 0.0 || inLife > particleLifetime || !inShow) 11969 meshLocalPos = vec3(0.0); 11970 vec2 quadXY = meshLocalPos.xy; 11971 float nlife = clamp(inLife / particleLifetime, 0.0, 1.0); 11972 vec3 paramDiv; 11973 vec4 params = tex1Dlod_lerp(TEXTURE_PASS(internalTex2), vec2(nlife, 0), paramDiv); 11974 float scale = params.y; 11975 float scaleDiv = paramDiv.x; 11976 float alphaDiv = paramDiv.z; 11977 scale += (scaleDiv * 2.0 - 1.0) * scaleDivMult * fract(rndFactor*10000.0); 11978#ifndef USE_MESH 11979 texCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife); 11980#else 11981 texCoordsAlphaLife = vec4(particle_uv, (alphaDiv * 2.0 - 1.0) * alphaDivMult * fract(rndFactor*1000.0), nlife); 11982#endif 11983 vec3 particlePos = inPos; 11984 vec3 particlePosMoved = vec3(0.0); 11985 mat2 rotMatrix; 11986`,Ak=` 11987 float animFrame = min(floor(texCoordsAlphaLife.w * animTexParams.y) + animTexParams.x, animTexParams.z); 11988`,Pk=` 11989 float animFrame = floor(mod(texCoordsAlphaLife.w * animTexParams.y + animTexParams.x, animTexParams.z + 1.0)); 11990`,Ik=` 11991 float animationIndex; 11992 if (animTexIndexParams.y == 1.0) { 11993 animationIndex = floor((animTexParams.w + 1.0) * rndFactor3.z) * (animTexParams.z + 1.0); 11994 } else { 11995 animationIndex = animTexIndexParams.x * (animTexParams.z + 1.0); 11996 } 11997 float atlasX = (animationIndex + animFrame) * animTexTilesParams.x; 11998 float atlasY = 1.0 - floor(atlasX + 1.0) * animTexTilesParams.y; 11999 atlasX = fract(atlasX); 12000 texCoordsAlphaLife.xy *= animTexTilesParams.xy; 12001 texCoordsAlphaLife.xy += vec2(atlasX, atlasY); 12002`,Dk=` 12003void readInput(float uv) { 12004 vec4 tex = texture2D(particleTexIN, vec2(uv, 0.25)); 12005 vec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.75)); 12006 inPos = tex.xyz; 12007 inVel = tex2.xyz; 12008 inAngle = (tex.w < 0.0? -tex.w : tex.w) - 1000.0; 12009 inShow = tex.w >= 0.0; 12010 inLife = tex2.w; 12011} 12012`,Mk=` 12013#define PI2 6.283185307179586 12014uniform vec3 inBoundsSize; 12015uniform vec3 inBoundsCenter; 12016uniform float maxVel; 12017float decodeFloatRG(vec2 rg) { 12018 return rg.y * (1.0 / 255.0) + rg.x; 12019} 12020float decodeFloatRGBA( vec4 rgba ) { 12021 return dot(rgba, vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)); 12022} 12023void readInput(float uv) { 12024 vec4 tex0 = texture2D(particleTexIN, vec2(uv, 0.125)); 12025 vec4 tex1 = texture2D(particleTexIN, vec2(uv, 0.375)); 12026 vec4 tex2 = texture2D(particleTexIN, vec2(uv, 0.625)); 12027 vec4 tex3 = texture2D(particleTexIN, vec2(uv, 0.875)); 12028 inPos = vec3(decodeFloatRG(tex0.rg), decodeFloatRG(tex0.ba), decodeFloatRG(tex1.rg)); 12029 inPos = (inPos - vec3(0.5)) * inBoundsSize + inBoundsCenter; 12030 inVel = tex2.xyz; 12031 inVel = (inVel - vec3(0.5)) * maxVel; 12032 inAngle = decodeFloatRG(tex1.ba) * PI2; 12033 inShow = tex2.a > 0.5; 12034 inLife = decodeFloatRGBA(tex3); 12035 float maxNegLife = max(lifetime, numParticles * (rate+rateDiv)); 12036 float maxPosLife = lifetime+1.0; 12037 inLife = inLife * (maxNegLife + maxPosLife) - maxNegLife; 12038} 12039`,Rk=` 12040void writeOutput() { 12041 if (gl_FragCoord.y<1.0) { 12042 gl_FragColor = vec4(outPos, (outAngle + 1000.0) * visMode); 12043 } else {
12044 gl_FragColor = vec4(outVel, outLife); 12045 } 12046} 12047`,Lk=` 12048uniform vec3 outBoundsMul; 12049uniform vec3 outBoundsAdd; 12050vec2 encodeFloatRG( float v ) { 12051 vec2 enc = vec2(1.0, 255.0) * v; 12052 enc = fract(enc); 12053 enc -= enc.yy * vec2(1.0/255.0, 1.0/255.0); 12054 return enc; 12055} 12056vec4 encodeFloatRGBA( float v ) { 12057 vec4 enc = vec4(1.0, 255.0, 65025.0, 160581375.0) * v; 12058 enc = fract(enc); 12059 enc -= enc.yzww * vec4(1.0/255.0,1.0/255.0,1.0/255.0,0.0); 12060 return enc; 12061} 12062void writeOutput() { 12063 outPos = outPos * outBoundsMul + outBoundsAdd; 12064 outAngle = fract(outAngle / PI2); 12065 outVel = (outVel / maxVel) + vec3(0.5); 12066 float maxNegLife = max(lifetime, numParticles * (rate+rateDiv)); 12067 float maxPosLife = lifetime+1.0; 12068 outLife = (outLife + maxNegLife) / (maxNegLife + maxPosLife); 12069 if (gl_FragCoord.y < 1.0) { 12070 gl_FragColor = vec4(encodeFloatRG(outPos.x), encodeFloatRG(outPos.y)); 12071 } else if (gl_FragCoord.y < 2.0) { 12072 gl_FragColor = vec4(encodeFloatRG(outPos.z), encodeFloatRG(outAngle)); 12073 } else if (gl_FragCoord.y < 3.0) { 12074 gl_FragColor = vec4(outVel, visMode*0.5+0.5); 12075 } else { 12076 gl_FragColor = encodeFloatRGBA(outLife); 12077 } 12078} 12079`,Fk=` 12080uniform mat3 spawnBounds; 12081uniform vec3 spawnPosInnerRatio; 12082vec3 calcSpawnPosition(vec3 inBounds, float rndFactor) { 12083 vec3 pos = inBounds - vec3(0.5); 12084 vec3 posAbs = abs(pos); 12085 vec3 maxPos = vec3(max(posAbs.x, max(posAbs.y, posAbs.z))); 12086 vec3 edge = maxPos + (vec3(0.5) - maxPos) * spawnPosInnerRatio; 12087 pos.x = edge.x * (maxPos.x == posAbs.x ? sign(pos.x) : 2.0 * pos.x); 12088 pos.y = edge.y * (maxPos.y == posAbs.y ? sign(pos.y) : 2.0 * pos.y); 12089 pos.z = edge.z * (maxPos.z == posAbs.z ? sign(pos.z) : 2.0 * pos.z); 12090#ifndef LOCAL_SPACE 12091 return emitterPos + spawnBounds * pos; 12092#else 12093 return spawnBounds * pos; 12094#endif 12095} 12096void addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) { 12097 localVelocity -= vec3(0, 0, initialVelocity); 12098} 12099`,Ok=` 12100 writeOutput(); 12101} 12102`,Bk=` 12103varying vec2 vUv0; 12104uniform highp sampler2D particleTexIN; 12105uniform highp sampler2D internalTex0; 12106uniform highp sampler2D internalTex1; 12107uniform highp sampler2D internalTex2; 12108uniform highp sampler2D internalTex3; 12109uniform mat3 emitterMatrix; 12110uniform mat3 emitterMatrixInv; 12111uniform vec3 emitterScale; 12112uniform vec3 emitterPos; 12113uniform vec3 frameRandom; 12114uniform vec3 localVelocityDivMult; 12115uniform vec3 velocityDivMult; 12116uniform float delta; 12117uniform float rate; 12118uniform float rateDiv; 12119uniform float lifetime; 12120uniform float numParticles; 12121uniform float rotSpeedDivMult; 12122uniform float radialSpeedDivMult; 12123uniform float seed; 12124uniform float startAngle; 12125uniform float startAngle2; 12126uniform float initialVelocity; 12127uniform float graphSampleSize; 12128uniform float graphNumSamples; 12129vec3 inPos; 12130vec3 inVel; 12131float inAngle; 12132bool inShow; 12133float inLife; 12134float visMode; 12135vec3 outPos; 12136vec3 outVel; 12137float outAngle; 12138bool outShow; 12139float outLife; 12140`,Nk=` 12141 if (outLife >= lifetime) { 12142 outLife -= max(lifetime, numParticles * particleRate); 12143 visMode = -1.0; 12144 } 12145`,kk=` 12146 visMode = outLife < 0.0? -1.0: visMode; 12147`,Uk=` 12148 if (outLife >= lifetime) { 12149 outLife -= max(lifetime, numParticles * particleRate); 12150 visMode = 1.0; 12151 } 12152 visMode = outLife < 0.0? 1.0: visMode; 12153`,zk=` 12154uniform float spawnBoundsSphere; 12155uniform float spawnBoundsSphereInnerRatio; 12156vec3 calcSpawnPosition(vec3 inBounds, float rndFactor) { 12157 float rnd4 = fract(rndFactor * 1000.0); 12158 vec3 norm = normalize(inBounds.xyz - vec3(0.5)); 12159 float r = rnd4 * (1.0 - spawnBoundsSphereInnerRatio) + spawnBoundsSphereInnerRatio; 12160#ifndef LOCAL_SPACE 12161 return emitterPos + norm * r * spawnBoundsSphere; 12162#else 12163 return norm * r * spawnBoundsSphere; 12164#endif 12165} 12166void addInitialVelocity(inout vec3 localVelocity, vec3 inBounds) { 12167 localVelocity += normalize(inBounds - vec3(0.5)) * initialVelocity; 12168} 12169`,Vk=` 12170float saturate(float x) { 12171 return clamp(x, 0.0, 1.0); 12172} 12173vec3 unpack3NFloats(float src) { 12174 float r = fract(src); 12175 float g = fract(src * 256.0); 12176 float b = fract(src * 65536.0); 12177 return vec3(r, g, b); 12178} 12179vec3 tex1Dlod_lerp(TEXTURE_ACCEPT_HIGHP(tex), vec2 tc, out vec3 w) { 12180 vec4 a = texture2D(tex, tc); 12181 vec4 b = texture2D(tex, tc + graphSampleSize); 12182 float c = fract(tc.x * graphNumSamples); 12183 vec3 unpackedA = unpack3NFloats(a.w); 12184 vec3 unpackedB = unpack3NFloats(b.w);
12185 w = mix(unpackedA, unpackedB, c); 12186 return mix(a.xyz, b.xyz, c); 12187} 12188#define HASHSCALE4 vec4(1031, .1030, .0973, .1099) 12189vec4 hash41(float p) { 12190 vec4 p4 = fract(vec4(p) * HASHSCALE4); 12191 p4 += dot(p4, p4.wzxy+19.19); 12192 return fract(vec4((p4.x + p4.y)*p4.z, (p4.x + p4.z)*p4.y, (p4.y + p4.z)*p4.w, (p4.z + p4.w)*p4.x)); 12193} 12194void main(void) { 12195 if (gl_FragCoord.x > numParticles) discard; 12196 readInput(vUv0.x); 12197 visMode = inShow? 1.0 : -1.0; 12198 vec4 rndFactor = hash41(gl_FragCoord.x + seed); 12199 float particleRate = rate + rateDiv * rndFactor.x; 12200 outLife = inLife + delta; 12201 float nlife = clamp(outLife / lifetime, 0.0, 1.0); 12202 vec3 localVelocityDiv; 12203 vec3 velocityDiv; 12204 vec3 paramDiv; 12205 vec3 localVelocity = tex1Dlod_lerp(TEXTURE_PASS(internalTex0), vec2(nlife, 0), localVelocityDiv); 12206 vec3 velocity = tex1Dlod_lerp(TEXTURE_PASS(internalTex1), vec2(nlife, 0), velocityDiv); 12207 vec3 params = tex1Dlod_lerp(TEXTURE_PASS(internalTex2), vec2(nlife, 0), paramDiv); 12208 float rotSpeed = params.x; 12209 float rotSpeedDiv = paramDiv.y; 12210 vec3 radialParams = tex1Dlod_lerp(TEXTURE_PASS(internalTex3), vec2(nlife, 0), paramDiv); 12211 float radialSpeed = radialParams.x; 12212 float radialSpeedDiv = radialParams.y; 12213 bool respawn = inLife <= 0.0 || outLife >= lifetime; 12214 inPos = respawn ? calcSpawnPosition(rndFactor.xyz, rndFactor.x) : inPos; 12215 inAngle = respawn ? mix(startAngle, startAngle2, rndFactor.x) : inAngle; 12216#ifndef LOCAL_SPACE 12217 vec3 radialVel = inPos - emitterPos; 12218#else 12219 vec3 radialVel = inPos; 12220#endif 12221 radialVel = (dot(radialVel, radialVel) > 1.0E-8) ? radialSpeed * normalize(radialVel) : vec3(0.0); 12222 radialVel += (radialSpeedDiv * vec3(2.0) - vec3(1.0)) * radialSpeedDivMult * rndFactor.xyz; 12223 localVelocity += (localVelocityDiv * vec3(2.0) - vec3(1.0)) * localVelocityDivMult * rndFactor.xyz; 12224 velocity += (velocityDiv * vec3(2.0) - vec3(1.0)) * velocityDivMult * rndFactor.xyz; 12225 rotSpeed += (rotSpeedDiv * 2.0 - 1.0) * rotSpeedDivMult * rndFactor.y; 12226 addInitialVelocity(localVelocity, rndFactor.xyz); 12227#ifndef LOCAL_SPACE 12228 outVel = emitterMatrix * localVelocity + (radialVel + velocity) * emitterScale; 12229#else 12230 outVel = (localVelocity + radialVel) / emitterScale + emitterMatrixInv * velocity; 12231#endif 12232 outPos = inPos + outVel * delta; 12233 outAngle = inAngle + rotSpeed * delta; 12234`,Gk=` 12235 quadXY = rotate(quadXY, inAngle, rotMatrix); 12236 vec3 localPos = billboard(particlePos, quadXY); 12237`,Hk=` 12238 dBlendModeFogFactor = 0.0; 12239 rgb *= saturate(gammaCorrectInput(max(a, 0.0))); 12240 if ((rgb.r + rgb.g + rgb.b) < 0.000001) discard; 12241`,Wk=` 12242 rgb = mix(vec3(1.0), rgb, vec3(a)); 12243 if (rgb.r + rgb.g + rgb.b > 2.99) discard; 12244`,Xk=` 12245 if (a < 0.01) discard; 12246`,Yk=` 12247attribute vec4 particle_vertexData; 12248attribute vec4 particle_vertexData2; 12249attribute vec4 particle_vertexData3; 12250attribute float particle_vertexData4; 12251#ifndef USE_MESH 12252 attribute vec2 particle_vertexData5; 12253#else 12254 attribute vec4 particle_vertexData5; 12255#endif 12256uniform mat4 matrix_viewProjection; 12257uniform mat4 matrix_model; 12258#ifndef VIEWMATRIX 12259 #define VIEWMATRIX 12260 uniform mat4 matrix_view; 12261#endif 12262uniform mat3 matrix_normal; 12263uniform mat4 matrix_viewInverse; 12264uniform float numParticles; 12265uniform float lifetime; 12266uniform float stretch; 12267uniform float seed; 12268uniform vec3 emitterScale; 12269uniform vec3 faceTangent; 12270uniform vec3 faceBinorm; 12271#ifdef PARTICLE_GPU 12272 #ifdef WRAP 12273 uniform vec3 wrapBounds; 12274 #endif 12275#endif 12276#ifdef PARTICLE_GPU 12277 uniform highp sampler2D internalTex0; 12278 uniform highp sampler2D internalTex1; 12279 uniform highp sampler2D internalTex2; 12280#endif 12281uniform vec3 emitterPos; 12282varying vec4 texCoordsAlphaLife; 12283vec2 rotate(vec2 quadXY, float pRotation, out mat2 rotMatrix) 12284{ 12285 float c = cos(pRotation); 12286 float s = sin(pRotation); 12287 mat2 m = mat2(c, -s, s, c); 12288 rotMatrix = m; 12289 return m * quadXY; 12290} 12291vec3 billboard(vec3 InstanceCoords, vec2 quadXY) 12292{ 12293 #ifdef SCREEN_SPACE 12294 vec3 pos = vec3(-1, 0, 0) * quadXY.x + vec3(0, -1, 0) * quadXY.y; 12295 #else 12296 vec3 pos = -matrix_viewInverse[0].xyz * quadXY.x + -matrix_viewInverse[1].xyz * quadXY.y; 12297 #endif 12298 return pos; 12299} 12300vec3 customFace(vec3 InstanceCoords, vec2 quadXY) 12301{ 12302 vec3 pos = faceTangent * quadXY.x + faceBinorm * quadXY.y; 12303 return pos; 12304} 12305void main(void) 12306{ 12307 vec3 particlePos = particle_vertexData.xyz; 12308 vec3 inPos = particlePos; 12309 vec3 vertPos = particle_vertexData3.xyz; 12310 vec3 inVel = vec3(particle_vertexData2.w, particle_vertexData3.w, particle_vertexData5.x); 12311 float id = floor(particle_vertexData4); 12312 float rndFactor = fract(sin(id + 1.0 + seed)); 12313 vec3 rndFactor3 = vec3(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0)); 12314#ifdef LOCAL_SPACE 12315 inVel = mat3(matrix_model) * inVel; 12316#endif 12317 vec2 velocityV = normalize((mat3(matrix_view) * inVel).xy); 12318 vec2 quadXY = vertPos.xy; 12319#ifdef USE_MESH 12320 texCoordsAlphaLife = vec4(particle_vertexData5.zw, particle_vertexData2.z, particle_vertexData.w); 12321#else 12322 texCoordsAlphaLife = vec4(quadXY * -0.5 + 0.5, particle_vertexData2.z, particle_vertexData.w); 12323#endif 12324 mat2 rotMatrix; 12325 float inAngle = particle_vertexData2.x; 12326 vec3 particlePosMoved = vec3(0.0); 12327 vec3 meshLocalPos = particle_vertexData3.xyz; 12328`,jk=` 12329 localPos *= particle_vertexData2.y * emitterScale; 12330 localPos += particlePos; 12331 #ifdef SCREEN_SPACE 12332 gl_Position = vec4(localPos.x, localPos.y, 0.0, 1.0); 12333 #else 12334 gl_Position = matrix_viewProjection * vec4(localPos, 1.0); 12335 #endif 12336`,qk=` 12337 quadXY = rotate(quadXY, inAngle, rotMatrix); 12338 vec3 localPos = customFace(particlePos, quadXY); 12339`,$k=` 12340 rgb = addFog(rgb); 12341 rgb = toneMap(rgb); 12342 rgb = gammaCorrectOutput(rgb); 12343 gl_FragColor = vec4(rgb, a); 12344} 12345`,Kk=`
12346 localPos *= scale * emitterScale; 12347 localPos += particlePos; 12348 #ifdef SCREEN_SPACE 12349 gl_Position = vec4(localPos.x, localPos.y, 0.0, 1.0); 12350 #else 12351 gl_Position = matrix_viewProjection * vec4(localPos.xyz, 1.0); 12352 #endif 12353`,Zk=` 12354 vec3 negNormal = normal * 0.5 + 0.5; 12355 vec3 posNormal = -normal * 0.5 + 0.5; 12356 negNormal *= negNormal; 12357 posNormal *= posNormal; 12358`,Qk=` 12359attribute vec4 particle_vertexData; 12360#if defined(USE_MESH) 12361 #if defined(USE_MESH_UV) 12362 attribute vec2 particle_uv; 12363 #else 12364 vec2 particle_uv = vec2(0.0, 0.0); 12365 #endif 12366#endif 12367uniform mat4 matrix_viewProjection; 12368uniform mat4 matrix_model; 12369uniform mat3 matrix_normal; 12370uniform mat4 matrix_viewInverse; 12371#ifndef VIEWMATRIX 12372 #define VIEWMATRIX 12373 uniform mat4 matrix_view; 12374#endif 12375uniform float numParticles; 12376uniform float numParticlesPot; 12377uniform float graphSampleSize; 12378uniform float graphNumSamples; 12379uniform float stretch; 12380uniform vec3 emitterScale; 12381uniform vec3 emitterPos; 12382uniform vec3 faceTangent; 12383uniform vec3 faceBinorm; 12384uniform float rate; 12385uniform float rateDiv; 12386uniform float lifetime; 12387uniform float scaleDivMult; 12388uniform float alphaDivMult; 12389uniform float seed; 12390uniform float delta; 12391uniform sampler2D particleTexOUT; 12392uniform sampler2D particleTexIN; 12393#ifdef PARTICLE_GPU 12394 #ifdef WRAP 12395 uniform vec3 wrapBounds; 12396 #endif 12397#endif 12398#ifdef PARTICLE_GPU 12399 uniform highp sampler2D internalTex0; 12400 uniform highp sampler2D internalTex1; 12401 uniform highp sampler2D internalTex2; 12402#endif 12403#ifndef CAMERAPLANES 12404 #define CAMERAPLANES 12405 uniform vec4 camera_params; 12406#endif 12407varying vec4 texCoordsAlphaLife; 12408vec3 inPos; 12409vec3 inVel; 12410float inAngle; 12411bool inShow; 12412float inLife; 12413`,Jk=` 12414 vec3 negNormal = max(normal, vec3(0.0)); 12415 vec3 posNormal = max(-normal, vec3(0.0)); 12416`,eU=` 12417 vec3 light = negNormal.x*lightCube[0] + posNormal.x*lightCube[1] + 12418 negNormal.y*lightCube[2] + posNormal.y*lightCube[3] + 12419 negNormal.z*lightCube[4] + posNormal.z*lightCube[5]; 12420 rgb *= light; 12421`,tU=` 12422 particlePos = (matrix_model * vec4(particlePos, 1.0)).xyz; 12423`,sU=` 12424 vec3 localPos = meshLocalPos; 12425 localPos.xy = rotate(localPos.xy, inAngle, rotMatrix); 12426 localPos.yz = rotate(localPos.yz, inAngle, rotMatrix); 12427 billboard(particlePos, quadXY); 12428`,iU=` 12429 Normal = normalize(localPos + matrix_viewInverse[2].xyz); 12430`,rU=` 12431 vec3 normalMap = normalize(texture2D(normalMap, vec2(texCoordsAlphaLife.x, 1.0 - texCoordsAlphaLife.y)).xyz * 2.0 - 1.0); 12432 vec3 normal = ParticleMat * normalMap; 12433`,aU=` 12434 inAngle = atan(velocityV.x, velocityV.y); 12435`,nU=` 12436 #include "particleUpdaterInitPS" 12437 #ifdef PACK8 12438 #include "particleInputRgba8PS" 12439 #include "particleOutputRgba8PS" 12440 #else 12441 #include "particleInputFloatPS" 12442 #include "particleOutputFloatPS" 12443 #endif 12444 #ifdef EMITTERSHAPE_BOX 12445 #include "particleUpdaterAABBPS" 12446 #else 12447 #include "particleUpdaterSpherePS" 12448 #endif 12449 #include "particleUpdaterStartPS" 12450 #ifdef RESPAWN 12451 #include "particleUpdaterRespawnPS" 12452 #endif 12453 #ifdef NO_RESPAWN 12454 #include "particleUpdaterNoRespawnPS" 12455 #endif 12456 #ifdef ON_STOP 12457 #include "particleUpdaterOnStopPS" 12458 #endif 12459 #include "particleUpdaterEndPS" 12460`,oU=` 12461 #if NORMAL != NONE 12462 #if NORMAL == VERTEX 12463 varying vec3 Normal; 12464 #endif 12465 #if NORMAL == MAP 12466 varying mat3 ParticleMat; 12467 #endif 12468 uniform vec3 lightCube[6]; 12469 #endif 12470 #ifdef SOFT 12471 varying float vDepth; 12472 #include "screenDepthPS" 12473 #endif 12474 #include "gammaPS" 12475 #include "tonemappingPS" 12476 #include "fogPS" 12477 #if NORMAL == MAP 12478 uniform sampler2D normalMap; 12479 #endif 12480 #include "particlePS" 12481 #ifdef SOFT 12482 #include "particle_softPS" 12483 #endif 12484 #if NORMAL == VERTEX 12485 vec3 normal = Normal; 12486 #endif 12487 #if NORMAL == MAP 12488 #include "particle_normalMapPS" 12489 #endif 12490 #if NORMAL != NONE 12491 #ifdef HALF_LAMBERT 12492 #include "particle_halflambertPS" 12493 #else 12494 #include "particle_lambertPS" 12495 #endif 12496 #include "particle_lightingPS" 12497 #endif 12498 #if BLEND == NORMAL 12499 #include "particle_blendNormalPS" 12500 #elif BLEND == ADDITIVE 12501 #include "particle_blendAddPS" 12502 #elif BLEND == MULTIPLICATIVE 12503 #include "particle_blendMultiplyPS" 12504 #endif 12505 #include "particle_endPS" 12506`,lU=` 12507 #ifdef ANIMTEX 12508 uniform vec2 animTexTilesParams; 12509 uniform vec4 animTexParams; 12510 uniform vec2 animTexIndexParams; 12511 #endif 12512 #if NORMAL == MAP 12513 varying mat3 ParticleMat; 12514 #endif 12515 #if NORMAL == VERTEX 12516 varying vec3 Normal; 12517 #endif 12518 #ifdef SOFT 12519 varying float vDepth; 12520 #endif 12521 #ifdef PARTICLE_GPU 12522 #include "particle_initVS" 12523 #ifdef PACK8 12524 #include "particleInputRgba8PS" 12525 #else
12526 #include "particleInputFloatPS" 12527 #endif 12528 #ifdef SOFT 12529 #include "screenDepthPS" 12530 #endif 12531 #include "particleVS" 12532 #else 12533 #ifdef SOFT 12534 #include "screenDepthPS" 12535 #endif 12536 #include "particle_cpuVS" 12537 #endif 12538 #ifdef LOCAL_SPACE 12539 #include "particle_localShiftVS" 12540 #endif 12541 #ifdef ANIMTEX 12542 #ifdef ANIMTEX_LOOP 12543 #include "particleAnimFrameLoopVS" 12544 #else 12545 #include "particleAnimFrameClampVS" 12546 #endif 12547 #include "particleAnimTexVS" 12548 #endif 12549 #ifdef PARTICLE_GPU 12550 #ifdef WRAP 12551 #include "particle_wrapVS" 12552 #endif 12553 #endif 12554 #ifdef ALIGN_TO_MOTION 12555 #include "particle_pointAlongVS" 12556 #endif 12557 #ifdef USE_MESH 12558 #include "particle_meshVS" 12559 #else 12560 #ifdef CUSTOM_FACE 12561 #include "particle_customFaceVS" 12562 #else 12563 #include "particle_billboardVS" 12564 #endif 12565 #endif 12566 #if NORMAL == VERTEX 12567 #include "particle_normalVS" 12568 #endif 12569 #if NORMAL == MAP 12570 #include "particle_TBNVS" 12571 #endif 12572 #ifdef STRETCH 12573 #include "particle_stretchVS" 12574 #endif 12575 #ifdef PARTICLE_GPU 12576 #include "particle_endVS" 12577 #else 12578 #include "particle_cpu_endVS" 12579 #endif 12580 #ifdef SOFT 12581 #include "particle_softVS" 12582 #endif 12583 } 12584`,cU=` 12585 float depth = getLinearScreenDepth(); 12586 float particleDepth = vDepth; 12587 float depthDiff = saturate(abs(particleDepth - depth) * softening); 12588 a *= depthDiff; 12589`,hU=` 12590 vDepth = getLinearDepth(localPos); 12591`,dU=` 12592 vec3 moveDir = inVel * stretch; 12593 vec3 posPrev = particlePos - moveDir; 12594 posPrev += particlePosMoved; 12595 vec2 centerToVertexV = normalize((mat3(matrix_view) * localPos).xy); 12596 float interpolation = dot(-velocityV, centerToVertexV) * 0.5 + 0.5; 12597 particlePos = mix(particlePos, posPrev, interpolation); 12598`,uU=` 12599 mat3 rot3 = mat3(rotMatrix[0][0], rotMatrix[0][1], 0.0, rotMatrix[1][0], rotMatrix[1][1], 0.0, 0.0, 0.0, 1.0); 12600 ParticleMat = mat3(-matrix_viewInverse[0].xyz, -matrix_viewInverse[1].xyz, matrix_viewInverse[2].xyz) * rot3; 12601`,fU=` 12602 vec3 origParticlePos = particlePos; 12603 particlePos -= matrix_model[3].xyz; 12604 particlePos = mod(particlePos, wrapBounds) - wrapBounds * 0.5; 12605 particlePos += matrix_model[3].xyz; 12606 particlePosMoved = particlePos - origParticlePos; 12607`;const pU={particlePS:Ek,particleVS:bk,particleAnimFrameClampVS:Ak,particleAnimFrameLoopVS:Pk,particleAnimTexVS:Ik,particleInputFloatPS:Dk,particleInputRgba8PS:Mk,particleOutputFloatPS:Rk,particleOutputRgba8PS:Lk,particleUpdaterAABBPS:Fk,particleUpdaterEndPS:Ok,particleUpdaterInitPS:Bk,particleUpdaterNoRespawnPS:Nk,particleUpdaterOnStopPS:kk,particleUpdaterRespawnPS:Uk,particleUpdaterSpherePS:zk,particleUpdaterStartPS:Vk,particle_billboardVS:Gk,particle_blendAddPS:Hk,particle_blendMultiplyPS:Wk,particle_blendNormalPS:Xk,particle_cpuVS:Yk,particle_cpu_endVS:jk,particle_customFaceVS:qk,particle_endPS:$k,particle_endVS:Kk,particle_halflambertPS:Zk,particle_initVS:Qk,particle_lambertPS:Jk,particle_lightingPS:eU,particle_localShiftVS:tU,particle_meshVS:sU,particle_normalVS:iU,particle_normalMapPS:rU,particle_pointAlongVS:aU,particle_simulationPS:nU,particle_shaderPS:oU,particle_shaderVS:lU,particle_softPS:cU,particle_softVS:hU,particle_stretchVS:dU,particle_TBNVS:uU,particle_wrapVS:fU};var mU=` 12608varying texCoordsAlphaLife: vec4f; 12609var colorMap: texture_2d<f32>; 12610var colorMapSampler: sampler; 12611var colorParam: texture_2d<f32>; 12612var colorParamSampler: sampler; 12613uniform graphSampleSize: f32; 12614uniform graphNumSamples: f32; 12615#ifndef CAMERAPLANES 12616 #define CAMERAPLANES 12617 uniform camera_params: vec4f; 12618#endif 12619#ifdef SOFT 12620 uniform softening: f32; 12621#endif 12622uniform colorMult: f32; 12623fn saturate(x: f32) -> f32 { 12624 return clamp(x, 0.0, 1.0); 12625} 12626@fragment 12627fn fragmentMain(input: FragmentInput) -> FragmentOutput { 12628 var output: FragmentOutput; 12629 let tex: vec4f = textureSample(colorMap, colorMapSampler, vec2f(input.texCoordsAlphaLife.x, 1.0 - input.texCoordsAlphaLife.y)); 12630 var ramp: vec4f = textureSample(colorParam, colorParamSampler, vec2f(input.texCoordsAlphaLife.w, 0.0)); 12631 ramp = vec4f(ramp.rgb * uniform.colorMult, ramp.a); 12632 ramp.a = ramp.a + input.texCoordsAlphaLife.z; 12633 var rgb: vec3f = tex.rgb * ramp.rgb; 12634 var a: f32 = tex.a * ramp.a; 12635`,_U=` 12636fn unpack3NFloats(src: f32) -> vec3f { 12637 let r = fract(src); 12638 let g = fract(src * 256.0); 12639 let b = fract(src * 65536.0); 12640 return vec3f(r, g, b); 12641} 12642fn saturate(x: f32) -> f32 { 12643 return clamp(x, 0.0, 1.0); 12644} 12645struct TexLerpUnpackResult { 12646 result: vec4f, 12647 unpacked: vec3f 12648} 12649fn tex1Dlod_lerp_simple(tex: texture_2d<f32>, textureSize: vec2u, tc: vec2f) -> vec4f { 12650 let tc_next = tc + vec2f(uniform.graphSampleSize); 12651 let texelA: vec2i = vec2i(tc * vec2f(textureSize)); 12652 let texelB: vec2i = vec2i(tc_next * vec2f(textureSize)); 12653 return mix( textureLoad(tex, texelA, 0), textureLoad(tex, texelB, 0), fract(tc.x * uniform.graphNumSamples) ); 12654} 12655fn tex1Dlod_lerp_unpack(tex: texture_2d<f32>, textureSize: vec2u, tc: vec2f) -> TexLerpUnpackResult { 12656 let tc_next = tc + vec2f(uniform.graphSampleSize); 12657 let texelA: vec2i = vec2i(tc * vec2f(textureSize)); 12658 let texelB: vec2i = vec2i(tc_next * vec2f(textureSize)); 12659 let a = textureLoad(tex, texelA, 0); 12660 let b = textureLoad(tex, texelB, 0); 12661 let c = fract(tc.x * uniform.graphNumSamples); 12662 let unpackedA = unpack3NFloats(a.w); 12663 let unpackedB = unpack3NFloats(b.w);
12664 let w_out = mix(unpackedA, unpackedB, c); 12665 return TexLerpUnpackResult(mix(a, b, c), w_out); 12666} 12667struct RotateResult { 12668 rotatedVec: vec2f, 12669 matrix: mat2x2f 12670} 12671fn rotateWithMatrix(quadXY: vec2f, pRotation: f32) -> RotateResult { 12672 let c = cos(pRotation); 12673 let s = sin(pRotation); 12674 let m = mat2x2f(vec2f(c, -s), vec2f(s, c)); 12675 return RotateResult(m * quadXY, m); 12676} 12677fn billboard(InstanceCoords: vec3f, quadXY: vec2f) -> vec3f { 12678 var pos: vec3f; 12679 #ifdef SCREEN_SPACE 12680 pos = vec3f(-1.0, 0.0, 0.0) * quadXY.x + vec3f(0.0, -1.0, 0.0) * quadXY.y; 12681 #else 12682 pos = -uniform.matrix_viewInverse[0].xyz * quadXY.x + -uniform.matrix_viewInverse[1].xyz * quadXY.y; 12683 #endif 12684 return pos; 12685} 12686fn customFace(InstanceCoords: vec3f, quadXY: vec2f) -> vec3f { 12687 let pos = uniform.faceTangent * quadXY.x + uniform.faceBinorm * quadXY.y; 12688 return pos; 12689} 12690fn safeNormalize(v: vec2f) -> vec2f { 12691 let l = length(v); 12692 return select(v, v / l, l > 1e-06); 12693} 12694@vertex 12695fn vertexMain(input: VertexInput) -> VertexOutput { 12696 var output: VertexOutput; 12697 let meshLocalPos_in = input.particle_vertexData.xyz; 12698 let id = floor(input.particle_vertexData.w); 12699 let rndFactor = fract(sin(id + 1.0 + uniform.seed)); 12700 let rndFactor3 = vec3f(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0)); 12701 let uv = id / uniform.numParticlesPot; 12702 readInput(uv); 12703 #ifdef LOCAL_SPACE 12704 let modelRotation = mat3x3f(uniform.matrix_model[0].xyz, uniform.matrix_model[1].xyz, uniform.matrix_model[2].xyz); 12705 inVel = modelRotation * inVel; 12706 #endif 12707 let viewRotation = mat3x3f(uniform.matrix_view[0].xyz, uniform.matrix_view[1].xyz, uniform.matrix_view[2].xyz); 12708 let velocityV = safeNormalize((viewRotation * inVel).xy); 12709 let particleLifetime = uniform.lifetime; 12710 var meshLocalPos = meshLocalPos_in; 12711 if (inLife <= 0.0 || inLife > particleLifetime || !inShow) { 12712 meshLocalPos = vec3f(0.0); 12713 } 12714 let quadXY = meshLocalPos.xy; 12715 let nlife = clamp(inLife / particleLifetime, 0.0, 1.0); 12716 let internalTexSize = textureDimensions(internalTex2, 0); 12717 let lerp_result = tex1Dlod_lerp_unpack(internalTex2, internalTexSize, vec2f(nlife, 0.0)); 12718 let params = lerp_result.result; 12719 let paramDiv = lerp_result.unpacked; 12720 var scale = params.y; 12721 let scaleDiv = paramDiv.x; 12722 let alphaDiv = paramDiv.z; 12723 scale = scale + (scaleDiv * 2.0 - 1.0) * uniform.scaleDivMult * fract(rndFactor*10000.0); 12724 #ifndef USE_MESH 12725 output.texCoordsAlphaLife = vec4f(quadXY * -0.5 + 0.5, (alphaDiv * 2.0 - 1.0) * uniform.alphaDivMult * fract(rndFactor*1000.0), nlife); 12726 #else 12727 output.texCoordsAlphaLife = vec4f(particle_uv, (alphaDiv * 2.0 - 1.0) * uniform.alphaDivMult * fract(rndFactor*1000.0), nlife); 12728 #endif 12729 var particlePos = inPos; 12730 var particlePosMoved = vec3f(0.0); 12731 var rotMatrix: mat2x2f; 12732`,gU=` 12733 let animFrame: f32 = min(floor(input.texCoordsAlphaLife.w * uniform.animTexParams.y) + uniform.animTexParams.x, uniform.animTexParams.z); 12734`,vU=` 12735 let animFrame: f32 = floor((output.texCoordsAlphaLife.w * uniform.animTexParams.y + uniform.animTexParams.x) % (uniform.animTexParams.z + 1.0)); 12736`,SU=` 12737 var animationIndex: f32; 12738 if (uniform.animTexIndexParams.y == 1.0) { 12739 animationIndex = floor((uniform.animTexParams.w + 1.0) * rndFactor3.z) * (uniform.animTexParams.z + 1.0); 12740 } else { 12741 animationIndex = uniform.animTexIndexParams.x * (uniform.animTexParams.z + 1.0); 12742 } 12743 var atlasX: f32 = (animationIndex + animFrame) * uniform.animTexTilesParams.x; 12744 let atlasY: f32 = 1.0 - floor(atlasX + 1.0) * uniform.animTexTilesParams.y; 12745 atlasX = fract(atlasX); 12746 let current_tcal_xy = output.texCoordsAlphaLife.xy; 12747 let scaled_tcal_xy = current_tcal_xy * uniform.animTexTilesParams.xy; 12748 let final_tcal_xy = scaled_tcal_xy + vec2f(atlasX, atlasY); 12749 output.texCoordsAlphaLife = vec4f(final_tcal_xy, output.texCoordsAlphaLife.z, output.texCoordsAlphaLife.w); 12750`,yU=` 12751fn readInput(uv: f32) { 12752 let textureSize = textureDimensions(particleTexIN, 0); 12753 let texel0: vec2i = vec2i(vec2f(uv, 0.25) * vec2f(textureSize)); 12754 let texel1: vec2i = vec2i(vec2f(uv, 0.75) * vec2f(textureSize)); 12755 let tex: vec4f = textureLoad(particleTexIN, texel0, 0); 12756 let tex2: vec4f = textureLoad(particleTexIN, texel1, 0); 12757 inPos = tex.xyz; 12758 inVel = tex2.xyz; 12759 inAngle = abs(tex.w) - 1000.0; 12760 inShow = tex.w >= 0.0; 12761 inLife = tex2.w; 12762} 12763`,xU=` 12764const PI2: f32 = 6.283185307179586; 12765uniform inBoundsSize: vec3f; 12766uniform inBoundsCenter: vec3f; 12767uniform maxVel: f32; 12768fn decodeFloatRG(rg: vec2f) -> f32 { 12769 return rg.y * (1.0 / 255.0) + rg.x; 12770} 12771fn decodeFloatRGBA( rgba: vec4f ) -> f32 { 12772 return dot(rgba, vec4f(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 160581375.0)); 12773} 12774fn readInput(uv: f32) { 12775 let textureSize = textureDimensions(particleTexIN, 0); 12776 let texel0: vec2i = vec2i(vec2f(uv, 0.125) * vec2f(textureSize)); 12777 let texel1: vec2i = vec2i(vec2f(uv, 0.375) * vec2f(textureSize)); 12778 let texel2: vec2i = vec2i(vec2f(uv, 0.625) * vec2f(textureSize)); 12779 let texel3: vec2i = vec2i(vec2f(uv, 0.875) * vec2f(textureSize)); 12780 let tex0 = textureLoad(particleTexIN, texel0, 0);
12781 let tex1 = textureLoad(particleTexIN, texel1, 0); 12782 let tex2 = textureLoad(particleTexIN, texel2, 0); 12783 let tex3 = textureLoad(particleTexIN, texel3, 0); 12784 inPos = vec3f(decodeFloatRG(tex0.rg), decodeFloatRG(tex0.ba), decodeFloatRG(tex1.rg)); 12785 inPos = (inPos - vec3f(0.5)) * uniform.inBoundsSize + uniform.inBoundsCenter; 12786 inVel = tex2.xyz; 12787 inVel = (inVel - vec3f(0.5)) * uniform.maxVel; 12788 inAngle = decodeFloatRG(tex1.ba) * PI2; 12789 inShow = tex2.a > 0.5; 12790 let life_decoded = decodeFloatRGBA(tex3); 12791 let maxNegLife = max(uniform.lifetime, uniform.numParticles * (uniform.rate + uniform.rateDiv)); 12792 let maxPosLife = uniform.lifetime + 1.0; 12793 inLife = life_decoded * (maxNegLife + maxPosLife) - maxNegLife; 12794}`,TU=` 12795fn getOutput() -> vec4f { 12796 if (pcPosition.y < 1.0) { 12797 return vec4f(outPos, (outAngle + 1000.0) * visMode); 12798 } else { 12799 return vec4f(outVel, outLife); 12800 } 12801} 12802`,wU=` 12803uniform outBoundsMul: vec3f; 12804uniform outBoundsAdd: vec3f; 12805fn encodeFloatRG( v: f32 ) -> vec2f { 12806 var enc: vec2f = vec2f(1.0, 255.0) * v; 12807 enc = fract(enc); 12808 enc = enc - enc.yy * (1.0 / 255.0); 12809 return enc; 12810} 12811fn encodeFloatRGBA( v: f32 ) -> vec4f { 12812 let factors = vec4f(1.0, 255.0, 65025.0, 160581375.0); 12813 var enc: vec4f = factors * v; 12814 enc = fract(enc); 12815 enc = enc - enc.yzww * vec4f(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 0.0); 12816 return enc; 12817} 12818fn getOutput() -> vec4f { 12819 outPos = outPos * uniform.outBoundsMul + uniform.outBoundsAdd; 12820 outAngle = fract(outAngle / PI2); 12821 outVel = (outVel / uniform.maxVel) + vec3f(0.5); 12822 let maxNegLife = max(uniform.lifetime, uniform.numParticles * (uniform.rate + uniform.rateDiv)); 12823 let maxPosLife = uniform.lifetime + 1.0; 12824 outLife = (outLife + maxNegLife) / (maxNegLife + maxPosLife); 12825 if (pcPosition.y < 1.0) { 12826 return vec4f(encodeFloatRG(outPos.x), encodeFloatRG(outPos.y)); 12827 } else if (pcPosition.y < 2.0) { 12828 return vec4f(encodeFloatRG(outPos.z), encodeFloatRG(outAngle)); 12829 } else if (pcPosition.y < 3.0) { 12830 return vec4f(outVel, visMode * 0.5 + 0.5); 12831 } else { 12832 return encodeFloatRGBA(outLife); 12833 } 12834} 12835`,CU=` 12836uniform spawnBounds: mat3x3f; 12837uniform spawnPosInnerRatio: vec3f; 12838fn calcSpawnPosition(inBounds: vec3f, rndFactor: f32) -> vec3f { 12839 var pos = inBounds - vec3f(0.5); 12840 let posAbs = abs(pos); 12841 let maxComp = max(posAbs.x, max(posAbs.y, posAbs.z)); 12842 let maxPos = vec3f(maxComp); 12843 let edge = maxPos + (vec3f(0.5) - maxPos) * uniform.spawnPosInnerRatio; 12844 pos.x = edge.x * select(2.0 * pos.x, sign(pos.x), maxPos.x == posAbs.x); 12845 pos.y = edge.y * select(2.0 * pos.y, sign(pos.y), maxPos.y == posAbs.y); 12846 pos.z = edge.z * select(2.0 * pos.z, sign(pos.z), maxPos.z == posAbs.z); 12847 #ifndef LOCAL_SPACE 12848 return uniform.emitterPos + uniform.spawnBounds * pos; 12849 #else 12850 return uniform.spawnBounds * pos; 12851 #endif 12852} 12853fn addInitialVelocity(localVelocity: ptr<function, vec3f>, inBounds: vec3f) { 12854 *localVelocity = *localVelocity - vec3f(0.0, 0.0, uniform.initialVelocity); 12855} 12856`,EU=` 12857 output.color = getOutput(); 12858 return output; 12859} 12860`,bU=` 12861varying vUv0: vec2f; 12862var particleTexIN: texture_2d<uff>; 12863var internalTex0: texture_2d<uff>; 12864var internalTex1: texture_2d<uff>; 12865var internalTex2: texture_2d<uff>; 12866var internalTex3: texture_2d<uff>; 12867uniform emitterMatrix: mat3x3f; 12868uniform emitterMatrixInv: mat3x3f; 12869uniform emitterScale: vec3f; 12870uniform emitterPos: vec3f; 12871uniform frameRandom: vec3f; 12872uniform localVelocityDivMult: vec3f; 12873uniform velocityDivMult: vec3f; 12874uniform delta: f32; 12875uniform rate: f32; 12876uniform rateDiv: f32; 12877uniform lifetime: f32; 12878uniform numParticles: f32; 12879uniform rotSpeedDivMult: f32; 12880uniform radialSpeedDivMult: f32; 12881uniform seed: f32; 12882uniform startAngle: f32; 12883uniform startAngle2: f32; 12884uniform initialVelocity: f32; 12885uniform graphSampleSize: f32; 12886uniform graphNumSamples: f32; 12887var<private> inPos: vec3f; 12888var<private> inVel: vec3f; 12889var<private> inAngle: f32; 12890var<private> inShow: bool; 12891var<private> inLife: f32; 12892var<private> visMode: f32; 12893var<private> outPos: vec3f; 12894var<private> outVel: vec3f; 12895var<private> outAngle: f32; 12896var<private> outShow: bool; 12897var<private> outLife: f32; 12898`,AU=` 12899 if (outLife >= uniform.lifetime) { 12900 outLife = outLife - max(uniform.lifetime, uniform.numParticles * particleRate); 12901 visMode = -1.0; 12902 } 12903`,PU=` 12904 visMode = select(visMode, -1.0, outLife < 0.0); 12905`,IU=` 12906 if (outLife >= uniform.lifetime) {
12907 let subtractAmount = max(uniform.lifetime, uniform.numParticles * particleRate); 12908 outLife = outLife - subtractAmount; 12909 visMode = 1.0; 12910 } 12911 visMode = select(visMode, 1.0, outLife < 0.0); 12912`,DU=` 12913uniform spawnBoundsSphere: f32; 12914uniform spawnBoundsSphereInnerRatio: f32; 12915fn calcSpawnPosition(inBounds: vec3f, rndFactor: f32) -> vec3f { 12916 let rnd4: f32 = fract(rndFactor * 1000.0); 12917 let norm: vec3f = normalize(inBounds.xyz - vec3f(0.5)); 12918 let r: f32 = rnd4 * (1.0 - uniform.spawnBoundsSphereInnerRatio) + uniform.spawnBoundsSphereInnerRatio; 12919 #ifndef LOCAL_SPACE 12920 return uniform.emitterPos + norm * r * uniform.spawnBoundsSphere; 12921 #else 12922 return norm * r * uniform.spawnBoundsSphere; 12923 #endif 12924} 12925fn addInitialVelocity(localVelocity: ptr<function, vec3f>, inBounds: vec3f) { 12926 let initialVelOffset: vec3f = normalize(inBounds - vec3f(0.5)) * uniform.initialVelocity; 12927 *localVelocity = *localVelocity + initialVelOffset; 12928} 12929`,MU=` 12930fn saturate(x: f32) -> f32 { 12931 return clamp(x, 0.0, 1.0); 12932} 12933fn unpack3NFloats(src: f32) -> vec3f { 12934 let r = fract(src); 12935 let g = fract(src * 256.0); 12936 let b = fract(src * 65536.0); 12937 return vec3f(r, g, b); 12938} 12939struct TexLerpUnpackResult { 12940 result: vec3f, 12941 unpacked: vec3f 12942} 12943fn tex1Dlod_lerp(tex: texture_2d<f32>, textureSize: vec2u, tc: vec2f) -> TexLerpUnpackResult { 12944 let tc_next = tc + vec2f(uniform.graphSampleSize); 12945 let texelA: vec2i = vec2i(tc * vec2f(textureSize)); 12946 let texelB: vec2i = vec2i(tc_next * vec2f(textureSize)); 12947 let a = textureLoad(tex, texelA, 0); 12948 let b = textureLoad(tex, texelB, 0); 12949 let c = fract(tc.x * uniform.graphNumSamples); 12950 let unpackedA = unpack3NFloats(a.w); 12951 let unpackedB = unpack3NFloats(b.w);
12952 let w_out = mix(unpackedA, unpackedB, c); 12953 return TexLerpUnpackResult(mix(a.xyz, b.xyz, c), w_out); 12954} 12955const HASHSCALE4: vec4f = vec4f(1031.0, 0.1030, 0.0973, 0.1099); 12956fn hash41(p: f32) -> vec4f { 12957 var p4 = fract(vec4f(p) * HASHSCALE4); 12958 p4 = p4 + dot(p4, p4.wzxy + 19.19); 12959 return fract(vec4f((p4.x + p4.y)*p4.z, (p4.x + p4.z)*p4.y, (p4.y + p4.z)*p4.w, (p4.z + p4.w)*p4.x)); 12960} 12961@fragment 12962fn fragmentMain(input : FragmentInput) -> FragmentOutput { 12963 var output: FragmentOutput; 12964 if (pcPosition.x > uniform.numParticles) { 12965 discard; 12966 return output; 12967 } 12968 readInput(input.vUv0.x); 12969 visMode = select(-1.0, 1.0, inShow); 12970 let rndFactor = hash41(pcPosition.x + uniform.seed); 12971 let particleRate = uniform.rate + uniform.rateDiv * rndFactor.x; 12972 outLife = inLife + uniform.delta; 12973 let nlife = clamp(outLife / uniform.lifetime, 0.0, 1.0); 12974 let internalTexSize = textureDimensions(internalTex0, 0); 12975 let lerpResult0 = tex1Dlod_lerp(internalTex0, internalTexSize, vec2f(nlife, 0.0)); 12976 var localVelocity = lerpResult0.result; 12977 let localVelocityDiv = lerpResult0.unpacked; 12978 let lerpResult1 = tex1Dlod_lerp(internalTex1, internalTexSize, vec2f(nlife, 0.0)); 12979 var velocity = lerpResult1.result; 12980 let velocityDiv = lerpResult1.unpacked; 12981 let lerpResult2 = tex1Dlod_lerp(internalTex2, internalTexSize, vec2f(nlife, 0.0)); 12982 let params = lerpResult2.result; 12983 let paramDiv = lerpResult2.unpacked; 12984 var rotSpeed = params.x; 12985 let rotSpeedDiv = paramDiv.y; 12986 let lerpResult3 = tex1Dlod_lerp(internalTex3, internalTexSize, vec2f(nlife, 0.0)); 12987 let radialParams = lerpResult3.result; 12988 let radialParamDiv = lerpResult3.unpacked; 12989 let radialSpeed = radialParams.x; 12990 let radialSpeedDiv = radialParamDiv.y; 12991 let respawn = inLife <= 0.0 || outLife >= uniform.lifetime; 12992 inPos = select(inPos, calcSpawnPosition(rndFactor.xyz, rndFactor.x), respawn); 12993 inAngle = select(inAngle, mix(uniform.startAngle, uniform.startAngle2, rndFactor.x), respawn); 12994 #ifndef LOCAL_SPACE 12995 var radialVel: vec3f = inPos - uniform.emitterPos; 12996 #else 12997 var radialVel: vec3f = inPos; 12998 #endif 12999 radialVel = select(vec3f(0.0), radialSpeed * normalize(radialVel), dot(radialVel, radialVel) > 1.0E-8); 13000 radialVel = radialVel + (radialSpeedDiv * vec3f(2.0) - vec3f(1.0)) * uniform.radialSpeedDivMult * rndFactor.xyz; 13001 localVelocity = localVelocity + (localVelocityDiv * vec3f(2.0) - vec3f(1.0)) * uniform.localVelocityDivMult * rndFactor.xyz; 13002 velocity = velocity + (velocityDiv * vec3f(2.0) - vec3f(1.0)) * uniform.velocityDivMult * rndFactor.xyz; 13003 rotSpeed = rotSpeed + (rotSpeedDiv * 2.0 - 1.0) * uniform.rotSpeedDivMult * rndFactor.y; 13004 addInitialVelocity(&localVelocity, rndFactor.xyz); 13005 #ifndef LOCAL_SPACE 13006 outVel = uniform.emitterMatrix * localVelocity + (radialVel + velocity) * uniform.emitterScale; 13007 #else 13008 outVel = (localVelocity + radialVel) / uniform.emitterScale + uniform.emitterMatrixInv * velocity; 13009 #endif 13010 outPos = inPos + outVel * uniform.delta; 13011 outAngle = inAngle + rotSpeed * uniform.delta; 13012`,RU=` 13013 let rotationResult = rotateWithMatrix(quadXY, inAngle); 13014 let rotatedQuadXY = rotationResult.rotatedVec; 13015 rotMatrix = rotationResult.matrix; 13016 var localPos = billboard(particlePos, rotatedQuadXY); 13017`,LU=` 13018 dBlendModeFogFactor = 0.0; 13019 rgb = rgb * saturate(gammaCorrectInput(max(a, 0.0))); 13020 if ((rgb.r + rgb.g + rgb.b) < 0.000001) { 13021 discard; 13022 } 13023`,FU=` 13024 rgb = mix(vec3f(1.0), rgb, a); 13025 if ((rgb.r + rgb.g + rgb.b) > 2.99) { 13026 discard; 13027 } 13028`,OU=` 13029 if (a < 0.01) { 13030 discard; 13031 } 13032`,BU=` 13033attribute particle_vertexData: vec4f; 13034attribute particle_vertexData2: vec4f; 13035attribute particle_vertexData3: vec4f; 13036attribute particle_vertexData4: f32; 13037#ifndef USE_MESH 13038 attribute particle_vertexData5: vec2f; 13039#else 13040 attribute particle_vertexData5: vec4f; 13041#endif 13042uniform matrix_viewProjection: mat4x4f; 13043uniform matrix_model: mat4x4f; 13044#ifndef VIEWMATRIX 13045 #define VIEWMATRIX 13046 uniform matrix_view: mat4x4f; 13047#endif 13048uniform matrix_normal: mat3x3f; 13049uniform matrix_viewInverse: mat4x4f; 13050uniform numParticles: f32; 13051uniform lifetime: f32; 13052uniform stretch: f32; 13053uniform seed: f32; 13054uniform emitterScale: vec3f; 13055uniform faceTangent: vec3f; 13056uniform faceBinorm: vec3f; 13057#ifdef PARTICLE_GPU 13058 #ifdef WRAP 13059 uniform wrapBounds: vec3f; 13060 #endif 13061#endif 13062#ifdef PARTICLE_GPU 13063 var internalTex0: texture_2d<uff>; 13064 var internalTex1: texture_2d<uff>; 13065 var internalTex2: texture_2d<uff>; 13066#endif 13067uniform emitterPos: vec3f; 13068varying texCoordsAlphaLife: vec4f; 13069struct RotateResult { 13070 rotatedVec: vec2f, 13071 matrix: mat2x2f 13072} 13073fn rotateWithMatrix(quadXY: vec2f, pRotation: f32) -> RotateResult { 13074 let c = cos(pRotation); 13075 let s = sin(pRotation); 13076 let m = mat2x2f(vec2f(c, -s), vec2f(s, c)); 13077 return RotateResult(m * quadXY, m); 13078} 13079fn billboard(InstanceCoords: vec3f, quadXY: vec2f) -> vec3f { 13080 var pos: vec3f; 13081 #ifdef SCREEN_SPACE 13082 pos = vec3f(-1.0, 0.0, 0.0) * quadXY.x + vec3f(0.0, -1.0, 0.0) * quadXY.y; 13083 #else 13084 pos = -uniform.matrix_viewInverse[0].xyz * quadXY.x + -uniform.matrix_viewInverse[1].xyz * quadXY.y; 13085 #endif 13086 return pos; 13087} 13088fn customFace(InstanceCoords: vec3f, quadXY: vec2f) -> vec3f { 13089 let pos = uniform.faceTangent * quadXY.x + uniform.faceBinorm * quadXY.y; 13090 return pos; 13091} 13092fn safeNormalize(v: vec2f) -> vec2f { 13093 let l = length(v); 13094 return select(v, v / l, l > 1e-06); 13095} 13096@vertex 13097fn vertexMain(input: VertexInput) -> VertexOutput { 13098 var output: VertexOutput; 13099 var particlePos = input.particle_vertexData.xyz; 13100 let inPos = particlePos; 13101 let vertPos = input.particle_vertexData3.xyz; 13102 var inVel = vec3f(input.particle_vertexData2.w, input.particle_vertexData3.w, input.particle_vertexData5.x); 13103 let id = floor(input.particle_vertexData4); 13104 let rndFactor = fract(sin(id + 1.0 + uniform.seed)); 13105 let rndFactor3 = vec3f(rndFactor, fract(rndFactor*10.0), fract(rndFactor*100.0)); 13106 #ifdef LOCAL_SPACE 13107 let modelRotation = mat3x3f(uniform.matrix_model[0].xyz, uniform.matrix_model[1].xyz, uniform.matrix_model[2].xyz); 13108 inVel = modelRotation * inVel; 13109 #endif 13110 let velocityV = safeNormalize((mat3x3f(uniform.matrix_view[0].xyz, uniform.matrix_view[1].xyz, uniform.matrix_view[2].xyz) * inVel).xy); 13111 let quadXY = vertPos.xy; 13112 #ifdef USE_MESH 13113 output.texCoordsAlphaLife = vec4f(input.particle_vertexData5.zw, input.particle_vertexData2.z, input.particle_vertexData.w); 13114 #else 13115 output.texCoordsAlphaLife = vec4f(quadXY * -0.5 + 0.5, input.particle_vertexData2.z, input.particle_vertexData.w); 13116 #endif 13117 var rotMatrix: mat2x2f; 13118 var inAngle = input.particle_vertexData2.x; 13119 var particlePosMoved = vec3f(0.0); 13120 let meshLocalPos = input.particle_vertexData3.xyz; 13121`,NU=` 13122 localPos = localPos * input.particle_vertexData2.y * uniform.emitterScale; 13123 localPos = localPos + particlePos; 13124 #ifdef SCREEN_SPACE 13125 output.position = vec4f(localPos.x, localPos.y, 0.0, 1.0); 13126 #else 13127 output.position = uniform.matrix_viewProjection * vec4f(localPos, 1.0); 13128 #endif 13129`,kU=` 13130 let rotationResult = rotateWithMatrix(quadXY, inAngle); 13131 let rotatedQuadXY = rotationResult.rotatedVec; 13132 rotMatrix = rotationResult.matrix; 13133 var localPos = customFace(particlePos, rotatedQuadXY); 13134`,UU=` 13135 rgb = addFog(rgb); 13136 rgb = toneMap(rgb); 13137 rgb = gammaCorrectOutput(rgb); 13138 output.color = vec4f(rgb, a); 13139 return output; 13140} 13141`,zU=` 13142 localPos = localPos * scale * uniform.emitterScale; 13143 localPos = localPos + particlePos; 13144 #ifdef SCREEN_SPACE 13145 output.position = vec4f(localPos.x, localPos.y, 0.0, 1.0); 13146 #else 13147 output.position = uniform.matrix_viewProjection * vec4f(localPos.xyz, 1.0); 13148 #endif 13149`,VU=` 13150 var negNormal: vec3f = normal * 0.5 + 0.5; 13151 var posNormal: vec3f = -normal * 0.5 + 0.5; 13152 negNormal = negNormal * negNormal; 13153 posNormal = posNormal * posNormal; 13154`,GU=` 13155attribute particle_vertexData: vec4f; 13156#if defined(USE_MESH) 13157 #if defined(USE_MESH_UV) 13158 attribute particle_uv: vec2f; 13159 #else 13160 var<private> particle_uv: vec2f = vec2f(0.0, 0.0); 13161 #endif 13162#endif 13163uniform matrix_viewProjection: mat4x4f; 13164uniform matrix_model: mat4x4f; 13165uniform matrix_normal: mat3x3f; 13166uniform matrix_viewInverse: mat4x4f; 13167#ifndef VIEWMATRIX 13168 #define VIEWMATRIX 13169 uniform matrix_view: mat4x4f; 13170#endif 13171uniform numParticles: f32; 13172uniform numParticlesPot: f32; 13173uniform graphSampleSize: f32; 13174uniform graphNumSamples: f32; 13175uniform stretch: f32; 13176uniform emitterScale: vec3f; 13177uniform emitterPos: vec3f; 13178uniform faceTangent: vec3f; 13179uniform faceBinorm: vec3f; 13180uniform rate: f32; 13181uniform rateDiv: f32; 13182uniform lifetime: f32; 13183uniform scaleDivMult: f32; 13184uniform alphaDivMult: f32; 13185uniform seed: f32; 13186uniform delta: f32; 13187#ifdef PARTICLE_GPU 13188 #ifdef WRAP 13189 uniform wrapBounds: vec3f; 13190 #endif 13191#endif 13192var particleTexOUT: texture_2d<uff>; 13193var particleTexIN: texture_2d<uff>; 13194#ifdef PARTICLE_GPU 13195 var internalTex0: texture_2d<uff>; 13196 var internalTex1: texture_2d<uff>; 13197 var internalTex2: texture_2d<uff>; 13198#endif 13199#ifndef CAMERAPLANES 13200 #define CAMERAPLANES 13201 uniform camera_params: vec4f; 13202#endif 13203varying texCoordsAlphaLife: vec4f; 13204var<private> inPos: vec3f; 13205var<private> inVel: vec3f; 13206var<private> inAngle: f32; 13207var<private> inShow: bool; 13208var<private> inLife: f32; 13209`,HU=` 13210 var negNormal: vec3f = max(normal, vec3(0.0)); 13211 var posNormal: vec3f = max(-normal, vec3(0.0)); 13212`,WU=` 13213 let light: vec3f = negNormal.x * uniform.lightCube[0] + posNormal.x * uniform.lightCube[1] + 13214 negNormal.y * uniform.lightCube[2] + posNormal.y * uniform.lightCube[3] + 13215 negNormal.z * uniform.lightCube[4] + posNormal.z * uniform.lightCube[5]; 13216 rgb = rgb * light; 13217`,XU=` 13218particlePos = (uniform.matrix_model * vec4f(particlePos, 1.0)).xyz; 13219`,YU=` 13220var localPos = meshLocalPos; 13221let rotResultXY = rotateWithMatrix(localPos.xy, inAngle); 13222localPos = vec3f(rotResultXY.rotatedVec, localPos.z); 13223rotMatrix = rotResultXY.matrix; 13224let rotResultYZ = rotateWithMatrix(localPos.yz, inAngle); 13225localPos = vec3f(localPos.x, rotResultYZ.rotatedVec); 13226rotMatrix = rotResultYZ.matrix; 13227billboard(particlePos, quadXY); 13228`,jU=` 13229output.Normal = normalize(localPos + uniform.matrix_viewInverse[2].xyz); 13230`,qU=` 13231 let sampledNormal: vec4f = textureSample(normalMap, normalMapSampler, vec2f(input.texCoordsAlphaLife.x, 1.0 - input.texCoordsAlphaLife.y)); 13232 let normalMap: vec3f = normalize(sampledNormal.xyz * 2.0 - 1.0); 13233 let ParticleMat = mat3x3<f32>(ParticleMat0, ParticleMat1, ParticleMat2); 13234 let normal: vec3f = ParticleMat * normalMap; 13235`,$U=` 13236 inAngle = atan2(velocityV.x, velocityV.y); 13237`,KU=` 13238 #include "particleUpdaterInitPS" 13239 #ifdef PACK8 13240 #include "particleInputRgba8PS" 13241 #include "particleOutputRgba8PS" 13242 #else
13243 #include "particleInputFloatPS" 13244 #include "particleOutputFloatPS" 13245 #endif 13246 #ifdef EMITTERSHAPE_BOX 13247 #include "particleUpdaterAABBPS" 13248 #else 13249 #include "particleUpdaterSpherePS" 13250 #endif 13251 #include "particleUpdaterStartPS" 13252 #ifdef RESPAWN 13253 #include "particleUpdaterRespawnPS" 13254 #endif 13255 #ifdef NO_RESPAWN 13256 #include "particleUpdaterNoRespawnPS" 13257 #endif 13258 #ifdef ON_STOP 13259 #include "particleUpdaterOnStopPS" 13260 #endif 13261 #include "particleUpdaterEndPS" 13262`,ZU=` 13263 #if NORMAL != NONE 13264 #if NORMAL == VERTEX 13265 varying Normal: vec3f; 13266 #endif 13267 #if NORMAL == MAP 13268 varying ParticleMat0: vec3f; 13269 varying ParticleMat1: vec3f; 13270 varying ParticleMat2: vec3f; 13271 #endif 13272 uniform lightCube: array<vec3f, 6>; 13273 #endif 13274 #ifdef SOFT 13275 varying vDepth: f32; 13276 #include "screenDepthPS" 13277 #endif 13278 #include "gammaPS" 13279 #include "tonemappingPS" 13280 #include "fogPS" 13281 #if NORMAL == MAP 13282 var normalMap: texture_2d<f32>; 13283 var normalMapSampler: sampler; 13284 #endif 13285 #include "particlePS" 13286 #ifdef SOFT 13287 #include "particle_softPS" 13288 #endif 13289 #if NORMAL == VERTEX 13290 var normal: vec3f = Normal; 13291 #endif 13292 #if NORMAL == MAP 13293 #include "particle_normalMapPS" 13294 #endif 13295 #if NORMAL != NONE 13296 #ifdef HALF_LAMBERT 13297 #include "particle_halflambertPS" 13298 #else 13299 #include "particle_lambertPS" 13300 #endif 13301 #include "particle_lightingPS" 13302 #endif 13303 #if BLEND == NORMAL 13304 #include "particle_blendNormalPS" 13305 #elif BLEND == ADDITIVE 13306 #include "particle_blendAddPS" 13307 #elif BLEND == MULTIPLICATIVE 13308 #include "particle_blendMultiplyPS" 13309 #endif 13310 #include "particle_endPS" 13311`,QU=` 13312 #ifdef ANIMTEX 13313 uniform animTexTilesParams: vec2f; 13314 uniform animTexParams: vec4f; 13315 uniform animTexIndexParams: vec2f; 13316 #endif 13317 #if NORMAL == MAP 13318 varying ParticleMat0: vec3f; 13319 varying ParticleMat1: vec3f; 13320 varying ParticleMat2: vec3f; 13321 #endif 13322 #if NORMAL == VERTEX 13323 varying Normal: vec3f; 13324 #endif 13325 #ifdef SOFT 13326 varying vDepth: f32; 13327 #endif 13328 #ifdef PARTICLE_GPU 13329 #include "particle_initVS" 13330 #ifdef PACK8 13331 #include "particleInputRgba8PS" 13332 #else 13333 #include "particleInputFloatPS" 13334 #endif 13335 #ifdef SOFT 13336 #include "screenDepthPS" 13337 #endif 13338 #include "particleVS" 13339 #else 13340 #ifdef SOFT 13341 #include "screenDepthPS" 13342 #endif 13343 #include "particle_cpuVS" 13344 #endif 13345 #ifdef LOCAL_SPACE 13346 #include "particle_localShiftVS" 13347 #endif 13348 #ifdef ANIMTEX 13349 #ifdef ANIMTEX_LOOP 13350 #include "particleAnimFrameLoopVS" 13351 #else 13352 #include "particleAnimFrameClampVS" 13353 #endif 13354 #include "particleAnimTexVS" 13355 #endif 13356 #ifdef PARTICLE_GPU 13357 #ifdef WRAP 13358 #include "particle_wrapVS" 13359 #endif 13360 #endif 13361 #ifdef ALIGN_TO_MOTION 13362 #include "particle_pointAlongVS" 13363 #endif 13364 #ifdef USE_MESH 13365 #include "particle_meshVS" 13366 #else 13367 #ifdef CUSTOM_FACE 13368 #include "particle_customFaceVS" 13369 #else 13370 #include "particle_billboardVS" 13371 #endif 13372 #endif 13373 #if NORMAL == VERTEX 13374 #include "particle_normalVS" 13375 #endif 13376 #if NORMAL == MAP 13377 #include "particle_TBNVS" 13378 #endif 13379 #ifdef STRETCH 13380 #include "particle_stretchVS" 13381 #endif 13382 #ifdef PARTICLE_GPU 13383 #include "particle_endVS" 13384 #else 13385 #include "particle_cpu_endVS" 13386 #endif 13387 #ifdef SOFT 13388 #include "particle_softVS" 13389 #endif 13390 return output; 13391} 13392`,JU=` 13393 var depth: f32 = getLinearScreenDepthFrag(); 13394 var particleDepth: f32 = vDepth; 13395 var depthDiff: f32 = saturate(abs(particleDepth - depth) * uniform.softening); 13396 a = a * depthDiff; 13397`,ez=` 13398 output.vDepth = getLinearDepth(localPos); 13399`,tz=` 13400 let moveDir: vec3f = inVel * uniform.stretch; 13401 var posPrev: vec3f = particlePos - moveDir; 13402 posPrev = posPrev + particlePosMoved; 13403 let viewRotationTemp: mat3x3f = mat3x3f(uniform.matrix_view[0].xyz, uniform.matrix_view[1].xyz, uniform.matrix_view[2].xyz); 13404 let centerToVertexV: vec2f = normalize((viewRotationTemp * localPos).xy); 13405 let interpolation: f32 = dot(-velocityV, centerToVertexV) * 0.5 + 0.5; 13406 particlePos = mix(particlePos, posPrev, interpolation); 13407`,sz=` 13408 let rot3 = mat3x3f( 13409 vec3f(rotMatrix[0][0], rotMatrix[1][0], 0.0), 13410 vec3f(rotMatrix[0][1], rotMatrix[1][1], 0.0), 13411 vec3f(0.0, 0.0, 1.0) 13412 ); 13413 let viewBasis = mat3x3f( 13414 -uniform.matrix_viewInverse[0].xyz, 13415 -uniform.matrix_viewInverse[1].xyz, 13416 uniform.matrix_viewInverse[2].xyz 13417 ); 13418 let tempMat = viewBasis * rot3; 13419 output.ParticleMat0 = tempMat[0]; 13420 output.ParticleMat1 = tempMat[1]; 13421 output.ParticleMat2 = tempMat[2]; 13422`,iz=` 13423 let origParticlePos: vec3f = particlePos; 13424 particlePos = particlePos - uniform.matrix_model[3].xyz; 13425 particlePos = (particlePos % uniform.wrapBounds) - uniform.wrapBounds * 0.5; 13426 particlePos = particlePos + uniform.matrix_model[3].xyz; 13427 particlePosMoved = particlePos - origParticlePos; 13428`;const rz={particlePS:mU,particleVS:_U,particleAnimFrameClampVS:gU,particleAnimFrameLoopVS:vU,particleAnimTexVS:SU,particleInputFloatP
13428S:yU,particleInputRgba8PS:xU,particleOutputFloatPS:TU,particleOutputRgba8PS:wU,particleUpdaterAABBPS:CU,particleUpdaterEndPS:EU,particleUpdaterInitPS:bU,particleUpdaterNoRespawnPS:AU,particleUpdaterOnStopPS:PU,particleUpdaterRespawnPS:IU,particleUpdaterSpherePS:DU,particleUpdaterStartPS:MU,particle_billboardVS:RU,particle_blendAddPS:LU,particle_blendMultiplyPS:FU,particle_blendNormalPS:OU,particle_cpuVS:BU,particle_cpu_endVS:NU,particle_customFaceVS:kU,particle_endPS:UU,particle_endVS:zU,particle_halflambertPS:VU,particle_initVS:GU,particle_lambertPS:HU,particle_lightingPS:WU,particle_localShiftVS:XU,particle_meshVS:YU,particle_normalVS:jU,particle_normalMapPS:qU,particle_pointAlongVS:$U,particle_simulationPS:KU,particle_shaderPS:ZU,particle_shaderVS:QU,particle_softPS:JU,particle_softVS:ez,particle_stretchVS:tz,particle_TBNVS:sz,particle_wrapVS:iz},az=["enabled","autoPlay","numParticles","lifetime","rate","rate2","startAngle","startAngle2","loop","preWarm","lighting","halfLambert","intensity","depthWrite","noFog","depthSoftening","sort","blendType","stretch","alignToMotion","emitterShape","emitterExtents","emitterExtentsInner","emitterRadius","emitterRadiusInner","initialVelocity","wrap","wrapBounds","localSpace","screenSpace","colorMapAsset","normalMapAsset","mesh","meshAsset","renderAsset","orientation","particleNormal","localVelocityGraph","localVelocityGraph2","velocityGraph","velocityGraph2","rotationSpeedGraph","rotationSpeedGraph2","radialSpeedGraph","radialSpeedGraph2","scaleGraph","scaleGraph2","colorGraph","colorGraph2","alphaGraph","alphaGraph2","colorMap","normalMap","animTilesX","animTilesY","animStartFrame","animNumFrames","animNumAnimations","animIndex","randomizeAnimIndex","animSpeed","animLoop","layers"];class nz extends Tt{constructor(e){super(e),this.id="particlesystem",this.ComponentType=wk,this.DataType=Ck,this.schema=az,this.propertyTypes={emitterExtents:"vec3",emitterExtentsInner:"vec3",particleNormal:"vec3",wrapBounds:"vec3",localVelocityGraph:"curveset",localVelocityGraph2:"curveset",velocityGraph:"curveset",velocityGraph2:"curveset",colorGraph:"curveset",colorGraph2:"curveset",alphaGraph:"curve",alphaGraph2:"curve",rotationSpeedGraph:"curve",rotationSpeedGraph2:"curve",radialSpeedGraph:"curve",radialSpeedGraph2:"curve",scaleGraph:"curve",scaleGraph2:"curve"},this.on("beforeremove",this.onBeforeRemove,this),this.app.systems.on("update",this.onUpdate,this),be.get(e.graphicsDevice,ze).add(pU),be.get(e.graphicsDevice,de).add(rz)}initializeComponentData(e,t,s){const i={};s=[];const r=this.propertyTypes;(t.mesh instanceof pe||typeof t.mesh=="number")&&(t.meshAsset=t.mesh,delete t.mesh);for(const a in t){if(t.hasOwnProperty(a)&&(s.push(a),i[a]=t[a]),r[a]==="vec3")Array.isArray(i[a])&&(i[a]=new E(i[a][0],i[a][1],i[a][2]));else if(r[a]==="curve"){if(!(i[a]instanceof _i)){const n=i[a].type;i[a]=new _i(i[a].keys),i[a].type=n}}else if(r[a]==="curveset"&&!(i[a]instanceof Ya)){const n=i[a].type;i[a]=new Ya(i[a].keys),i[a].type=n}i.layers&&Array.isArray(i.layers)&&(i.layers=i.layers.slice(0))}super.initializeComponentData(e,i,s)}cloneComponent(e,t){const s=e.particlesystem.data,i=this.schema,r={};for(let a=0,n=i.length;a<n;a++){const o=i[a];let c=s[o];c instanceof E||c instanceof _i||c instanceof Ya?(c=c.clone(),r[o]=c):o==="layers"?r.layers=s.layers.slice(0):c!=null&&(r[o]=c)}return this.addComponent(t,r)}onUpdate(e){const t=this.store,s=this.app.stats.particles,i=this.app.scene.layers;for(let r=0;r<i.layerList.length;r++)i.layerList[r].requiresLightCube=!1;for(const r in t)if(t.hasOwnProperty(r)){const a=t[r],n=a.entity,o=a.data;if(o.enabled&&n.enabled){const c=n.particlesystem.emitter;if(!c?.meshInstance.visible)continue;if(c.lighting){const h=o.layers;for(let d=0;d<h.length;d++){const u=i.getLayerById(h[d]);u&&(u.requiresLightCube=!0)}}if(!o.paused){let h=0;if(c.simTime+=e,c.simTime>=c.fixedTimeStep&&(h=Math.floor(c.simTime/c.fixedTimeStep),c.simTime-=h*c.fixedTimeStep),h){h=Math.min(h,c.maxSubSteps);for(let d=0;d<h;d++)c.addTime(c.fixedTimeStep,!1);s._updatesPerFrame+=h,s._frameTime+=c._addTimeTime,c._addTimeTime=0}c.finishFrame()}}}}onBeforeRemove(e,t){t.onBeforeRemove()}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this)}}class oz extends Cf{constructor(e,t){super(),this.skin=e,this.skinInstance=t}}class fi{static _skinInstanceCache=new Map;static createCachedSkinInstance(e,t,s){let i=fi.getCachedSkinInstance(e,t);
13428return i||(i=new $c(e),i.resolve(t,s),fi.addCachedSkinInstance(e,t,i)),i}static getCachedSkinInstance(e,t){let s=null;const i=fi._skinInstanceCache.get(t);if(i){const r=i.find(a=>a.skin===e);r&&(r.incRefCount(),s=r.skinInstance)}return s}static addCachedSkinInstance(e,t,s){let i=fi._skinInstanceCache.get(t);i||(i=[],fi._skinInstanceCache.set(t,i));let r=i.find(a=>a.skin===e);r||(r=new oz(e,s),i.push(r)),r.incRefCount()}static removeCachedSkinInstance(e){if(e){const t=e.rootBone;if(t){const s=fi._skinInstanceCache.get(t);if(s){const i=s.findIndex(r=>r.skinInstance===e);if(i>=0){const r=s[i];r.decRefCount(),r.refCount===0&&(s.splice(i,1),s.length||fi._skinInstanceCache.delete(t),e&&(e.destroy(),r.skinInstance=null))}}}}}}class Ec{_evtLoadById=null;_evtUnloadById=null;_evtAddById=null;_evtRemoveById=null;_evtLoadByUrl=null;_evtAddByUrl=null;_evtRemoveByUrl=null;constructor(e,t,s,i,r){this.propertyName=e,this.parent=t,this._scope=r,this._registry=s,this.id=null,this.url=null,this.asset=null,this._onAssetLoad=i.load,this._onAssetAdd=i.add,this._onAssetRemove=i.remove,this._onAssetUnload=i.unload}set id(e){if(this.url)throw Error("Can't set id and url");this._unbind(),this._id=e,this.asset=this._registry.get(this._id),this._bind()}get id(){return this._id}set url(e){if(this.id)throw Error("Can't set id and url");this._unbind(),this._url=e,this.asset=this._registry.getByUrl(this._url),this._bind()}get url(){return this._url}_bind(){this.id&&(this._onAssetLoad&&(this._evtLoadById=this._registry.on(`load:${this.id}`,this._onLoad,this)),this._onAssetAdd&&(this._evtAddById=this._registry.once(`add:${this.id}`,this._onAdd,this)),this._onAssetRemove&&(this._evtRemoveById=this._registry.on(`remove:${this.id}`,this._onRemove,this)),this._onAssetUnload&&(this._evtUnloadById=this._registry.on(`unload:${this.id}`,this._onUnload,this))),this.url&&(this._onAssetLoad&&(this._evtLoadByUrl=this._registry.on(`load:url:${this.url}`,this._onLoad,this)),this._onAssetAdd&&(this._evtAddByUrl=this._registry.once(`add:url:${this.url}`,this._onAdd,this)),this._onAssetRemove&&(this._evtRemoveByUrl=this._registry.on(`remove:url:${this.url}`,this._onRemove,this)))}_unbind(){this.id&&(this._evtLoadById?.off(),this._evtLoadById=null,this._evtAddById?.off(),this._evtAddById=null,this._evtRemoveById?.off(),this._evtRemoveById=null,this._evtUnloadById?.off(),this._evtUnloadById=null),this.url&&(this._evtLoadByUrl?.off(),this._evtLoadByUrl=null,this._evtAddByUrl?.off(),this._evtAddByUrl=null,this._evtRemoveByUrl?.off(),this._evtRemoveByUrl=null)}_onLoad(e){this._onAssetLoad.call(this._scope,this.propertyName,this.parent,e)}_onAdd(e){this.asset=e,this._onAssetAdd.call(this._scope,this.propertyName,this.parent,e)}_onRemove(e){this._onAssetRemove.call(this._scope,this.propertyName,this.parent,e),this.asset=null}_onUnload(e){this._onAssetUnload.call(this._scope,this.propertyName,this.parent,e)}}class Zw extends ye{_type="asset";_castShadows=!0;_receiveShadows=!0;_castShadowsLightmap=!0;_lightmapped=!1;_lightmapSizeMultiplier=1;isStatic=!1;_batchGroupId=-1;_layers=[Ir];_renderStyle=co;_meshInstances=[];_customAabb=null;_area=null;_assetReference;_materialReferences=[];_material;_rootBone=null;_evtLayersChanged=null;_evtLayerAdded=null;_evtLayerRemoved=null;_evtSetMeshes=null;constructor(e,t){super(e,t),this._assetReference=new Ec("asset",this,e.app.assets,{add:this._onRenderAssetAdded,load:this._onRenderAssetLoad,remove:this._onRenderAssetRemove,unload:this._onRenderAssetUnload},this),this._material=e.defaultMaterial,t.on("remove",this.onRemoveChild,this),t.on("removehierarchy",this.onRemoveChild,this),t.on("insert",this.onInsertChild,this),t.on("inserthierarchy",this.onInsertChild,this)}set renderStyle(e){this._renderStyle!==e&&(this._renderStyle=e,Ne._prepareRenderStyleForArray(this._meshInstances,e))}get renderStyle(){return this._renderStyle}set customAabb(e){this._customAabb=e;const t=this._meshInstances;if(t)for(let s=0;s<t.length;s++)t[s].setCustomAabb(this._customAabb)}get customAabb(){return this._customAabb}set type(e){if(this._type!==e&&(this._area=null,this._type=e,this.destroyMeshInstances(),e!=="asset")){let t=this._material;(!t||t===this.system.defaultMaterial)&&(t=this._materialReferences[0]&&this._materialReferences[0].asset&&this._materialReferences[0].asset.resource);
13428const s=$w(this.system.app.graphicsDevice,e);this._area=s.area,this.meshInstances=[new Ne(s.mesh,t||this.system.defaultMaterial,this.entity)]}}get type(){return this._type}set meshInstances(e){if(this.destroyMeshInstances(),this._meshInstances=e,this._meshInstances){const t=this._meshInstances;for(let s=0;s<t.length;s++)t[s].node||(t[s].node=this.entity),t[s].castShadow=this._castShadows,t[s].receiveShadow=this._receiveShadows,t[s].renderStyle=this._renderStyle,t[s].setLightmapped(this._lightmapped),t[s].setCustomAabb(this._customAabb);this.enabled&&this.entity.enabled&&this.addToLayers()}}get meshInstances(){return this._meshInstances}set lightmapped(e){if(e!==this._lightmapped){this._lightmapped=e;const t=this._meshInstances;if(t)for(let s=0;s<t.length;s++)t[s].setLightmapped(e)}}get lightmapped(){return this._lightmapped}set castShadows(e){if(this._castShadows!==e){const t=this._meshInstances;if(t){const s=this.layers,i=this.system.app.scene;if(this._castShadows&&!e)for(let r=0;r<s.length;r++){const a=i.layers.getLayerById(this.layers[r]);a&&a.removeShadowCasters(t)}for(let r=0;r<t.length;r++)t[r].castShadow=e;if(!this._castShadows&&e)for(let r=0;r<s.length;r++){const a=i.layers.getLayerById(s[r]);a&&a.addShadowCasters(t)}}this._castShadows=e}}get castShadows(){return this._castShadows}set receiveShadows(e){if(this._receiveShadows!==e){this._receiveShadows=e;const t=this._meshInstances;if(t)for(let s=0;s<t.length;s++)t[s].receiveShadow=e}}get receiveShadows(){return this._receiveShadows}set castShadowsLightmap(e){this._castShadowsLightmap=e}get castShadowsLightmap(){return this._castShadowsLightmap}set lightmapSizeMultiplier(e){this._lightmapSizeMultiplier=e}get lightmapSizeMultiplier(){return this._lightmapSizeMultiplier}set layers(e){const t=this.system.app.scene.layers;let s;if(this._meshInstances)for(let i=0;i<this._layers.length;i++)s=t.getLayerById(this._layers[i]),s&&s.removeMeshInstances(this._meshInstances);this._layers.length=0;for(let i=0;i<e.length;i++)this._layers[i]=e[i];if(!(!this.enabled||!this.entity.enabled||!this._meshInstances))for(let i=0;i<this._layers.length;i++)s=t.getLayerById(this._layers[i]),s&&s.addMeshInstances(this._meshInstances)}get layers(){return this._layers}set batchGroupId(e){this._batchGroupId!==e&&(this.entity.enabled&&this._batchGroupId>=0&&this.system.app.batcher?.remove(Zt.RENDER,this.batchGroupId,this.entity),this.entity.enabled&&e>=0&&this.system.app.batcher?.insert(Zt.RENDER,e,this.entity),e<0&&this._batchGroupId>=0&&this.enabled&&this.entity.enabled&&this.addToLayers(),this._batchGroupId=e)}get batchGroupId(){return this._batchGroupId}set material(e){if(this._material!==e&&(this._material=e,this._meshInstances&&this._type!=="asset"))for(let t=0;t<this._meshInstances.length;t++)this._meshInstances[t].material=e}get material(){return this._material}set materialAssets(e=[]){if(this._materialReferences.length>e.length){for(let t=e.length;t<this._materialReferences.length;t++)this._materialReferences[t].id=null;this._materialReferences.length=e.length}for(let t=0;t<e.length;t++)if(this._materialReferences[t]||this._materialReferences.push(new Ec(t,this,this.system.app.assets,{add:this._onMaterialAdded,load:this._onMaterialLoad,remove:this._onMaterialRemove,unload:this._onMaterialUnload},this)),e[t]){const s=e[t]instanceof pe?e[t].id:e[t];this._materialReferences[t].id!==s&&(this._materialReferences[t].id=s),this._materialReferences[t].asset&&this._onMaterialAdded(t,this,this._materialReferences[t].asset)}else this._materialReferences[t].id=null,this._meshInstances[t]&&(this._meshInstances[t].material=this.system.defaultMaterial)}get materialAssets(){return this._materialReferences.map(e=>e.id)}set asset(e){const t=e instanceof pe?e.id:e;this._assetReference.id!==t&&(this._assetReference.asset&&this._assetReference.asset.resource&&this._onRenderAssetRemove(),this._assetReference.id=t,this._assetReference.asset&&this._onRenderAssetAdded())}get asset(){return this._assetReference.id}assignAsset(e){const t=e instanceof pe?e.id:e;this._assetReference.id=t}set rootBone(e){if(this._rootBone!==e){const t=typeof e=="string";if(this._rootBone&&t&&this._rootBone.guid===e)return;this._rootBone&&this._clearSkinInstances(),e instanceof He?this._rootBone=e:t?(this._rootBone=this.system.a
13428pp.getEntityFromIndex(e)||null,this._rootBone):this._rootBone=null,this._rootBone&&this._cloneSkinInstances()}}get rootBone(){return this._rootBone}destroyMeshInstances(){const e=this._meshInstances;if(e){this.removeFromLayers(),this._clearSkinInstances();for(let t=0;t<e.length;t++)e[t].destroy();this._meshInstances.length=0}}addToLayers(){const e=this.system.app.scene.layers;for(let t=0;t<this._layers.length;t++){const s=e.getLayerById(this._layers[t]);s&&s.addMeshInstances(this._meshInstances)}}removeFromLayers(){if(this._meshInstances&&this._meshInstances.length){const e=this.system.app.scene.layers;for(let t=0;t<this._layers.length;t++){const s=e.getLayerById(this._layers[t]);s&&s.removeMeshInstances(this._meshInstances)}}}onRemoveChild(){this.removeFromLayers()}onInsertChild(){this._meshInstances&&this.enabled&&this.entity.enabled&&this.addToLayers()}onRemove(){this.destroyMeshInstances(),this.asset=null,this.materialAsset=null,this._assetReference.id=null;for(let e=0;e<this._materialReferences.length;e++)this._materialReferences[e].id=null;this.entity.off("remove",this.onRemoveChild,this),this.entity.off("insert",this.onInsertChild,this)}onLayersChanged(e,t){this.addToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this)}onLayerAdded(e){this.layers.indexOf(e.id)<0||e.addMeshInstances(this._meshInstances)}onLayerRemoved(e){this.layers.indexOf(e.id)<0||e.removeMeshInstances(this._meshInstances)}onEnable(){const e=this.system.app,t=e.scene,s=t.layers;this._rootBone&&this._cloneSkinInstances(),this._evtLayersChanged=t.on("set:layers",this.onLayersChanged,this),s&&(this._evtLayerAdded=s.on("add",this.onLayerAdded,this),this._evtLayerRemoved=s.on("remove",this.onLayerRemoved,this));const i=this._type==="asset";this._meshInstances&&this._meshInstances.length?this.addToLayers():i&&this.asset&&this._onRenderAssetAdded();for(let r=0;r<this._materialReferences.length;r++)this._materialReferences[r].asset&&this.system.app.assets.load(this._materialReferences[r].asset);this._batchGroupId>=0&&e.batcher?.insert(Zt.RENDER,this.batchGroupId,this.entity)}onDisable(){const e=this.system.app,s=e.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,this._rootBone&&this._clearSkinInstances(),s&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this._batchGroupId>=0&&e.batcher?.remove(Zt.RENDER,this.batchGroupId,this.entity),this.removeFromLayers()}hide(){if(this._meshInstances)for(let e=0;e<this._meshInstances.length;e++)this._meshInstances[e].visible=!1}show(){if(this._meshInstances)for(let e=0;e<this._meshInstances.length;e++)this._meshInstances[e].visible=!0}_onRenderAssetAdded(){this._assetReference.asset&&(this._assetReference.asset.resource?this._onRenderAssetLoad():this.enabled&&this.entity.enabled&&this.system.app.assets.load(this._assetReference.asset))}
13428_onRenderAssetLoad(){if(this.destroyMeshInstances(),this._assetReference.asset){const e=this._assetReference.asset.resource;this._evtSetMeshes?.off(),this._evtSetMeshes=e.on("set:meshes",this._onSetMeshes,this),e.meshes&&this._onSetMeshes(e.meshes)}}_onSetMeshes(e){this._cloneMeshes(e)}_clearSkinInstances(){for(let e=0;e<this._meshInstances.length;e++){const t=this._meshInstances[e];fi.removeCachedSkinInstance(t.skinInstance),t.skinInstance=null}}_cloneSkinInstances(){if(this._meshInstances.length&&this._rootBone instanceof He)for(let e=0;e<this._meshInstances.length;e++){const t=this._meshInstances[e],s=t.mesh;s.skin&&!t.skinInstance&&(t.skinInstance=fi.createCachedSkinInstance(s.skin,this._rootBone,this.entity))}}_cloneMeshes(e){if(e&&e.length){const t=[];for(let s=0;s<e.length;s++){const i=e[s],r=this._materialReferences[s]&&this._materialReferences[s].asset&&this._materialReferences[s].asset.resource,a=new Ne(i,r||this.system.defaultMaterial,this.entity);t.push(a),i.morph&&(a.morphInstance=new dn(i.morph))}this.meshInstances=t,this._cloneSkinInstances()}}_onRenderAssetUnload(){this._type==="asset"&&this.destroyMeshInstances()}_onRenderAssetRemove(){this._evtSetMeshes?.off(),this._evtSetMeshes=null,this._onRenderAssetUnload()}_onMaterialAdded(e,t,s){s.resource?this._onMaterialLoad(e,t,s):this.enabled&&this.entity.enabled&&this.system.app.assets.load(s)}_updateMainMaterial(e,t){e===0&&(this.material=t)}_onMaterialLoad(e,t,s){this._meshInstances[e]&&(this._meshInstances[e].material=s.resource),this._updateMainMaterial(e,s.resource)}_onMaterialRemove(e,t,s){this._meshInstances[e]&&(this._meshInstances[e].material=this.system.defaultMaterial),this._updateMainMaterial(e,this.system.defaultMaterial)}_onMaterialUnload(e,t,s){this._meshInstances[e]&&(this._meshInstances[e].material=this.system.defaultMaterial),this._updateMainMaterial(e,this.system.defaultMaterial)}resolveDuplicatedEntityReferenceProperties(e,t){e.rootBone&&(this.rootBone=t[e.rootBone.guid])}}class lz{enabled=!0}const C_=["enabled"],Fa=["material","meshInstances","asset","materialAssets","castShadows","receiveShadows","castShadowsLightmap","lightmapped","lightmapSizeMultiplier","render
13428Style","type","layers","isStatic","batchGroupId","rootBone"];class cz extends Tt{constructor(e){super(e),this.id="render",this.ComponentType=Zw,this.DataType=lz,this.schema=C_,this.defaultMaterial=Zo(e.graphicsDevice),this.on("beforeremove",this.onRemove,this)}initializeComponentData(e,t,s){(t.batchGroupId===null||t.batchGroupId===void 0)&&(t.batchGroupId=-1),t.layers&&t.layers.length&&(t.layers=t.layers.slice(0));for(let i=0;i<Fa.length;i++)t.hasOwnProperty(Fa[i])&&(e[Fa[i]]=t[Fa[i]]);t.aabbCenter&&t.aabbHalfExtents&&(e.customAabb=new Le(new E(t.aabbCenter),new E(t.aabbHalfExtents))),super.initializeComponentData(e,t,C_)}cloneComponent(e,t){const s={};for(let n=0;n<Fa.length;n++)s[Fa[n]]=e.render[Fa[n]];s.enabled=e.render.enabled,delete s.meshInstances;const i=this.addComponent(t,s),r=e.render.meshInstances,a=r.map(n=>n.mesh);i._onSetMeshes(a);for(let n=0;n<r.length;n++)i.meshInstances[n].material=r[n].material;return e.render.customAabb&&(i.customAabb=e.render.customAabb.clone()),i}onRemove(e,t){t.onRemove()}}ye._buildAccessors(Zw.prototype,C_);class Jp{_constructor;_pool=[];_count=0;constructor(e,t){this._constructor=e,this._resize(t)}_resize(e){if(e>this._pool.length)for(let t=this._pool.length;t<e;t++)this._pool[t]=new this._constructor}allocate(){return this._count>=this._pool.length&&this._resize(this._pool.length*2),this._pool[this._count++]}freeAll(){this._count=0}}let Fs,Ve,hi,Qn;const hz=new ae,dz=new ae,rd=new E;class Eo extends ye{static EVENT_CONTACT="contact";static EVENT_COLLISIONSTART="collisionstart";static EVENT_COLLISIONEND="collisionend";static EVENT_TRIGGERENTER="triggerenter";static EVENT_TRIGGERLEAVE="triggerleave";static order=-1;_angularDamping=0;_angularFactor=new E(1,1,1);_angularVelocity=new E;_body=null;_friction=.5;_group=Xy;_linearDamping=0;_linearFactor=new E(1,1,1);_linearVelocity=new E;_mask=__;_mass=1;_restitution=0;_rollingFriction=0;_simulationEnabled=!1;_type=El;static onLibraryLoaded(){typeof Ammo<"u"&&(Fs=new Ammo.btTransform,Ve=new Ammo.btVector3,hi=new Ammo.btVector3,Qn=new Ammo.btQuaternion)}static onAppDestroy(){Ammo.destroy(Fs),Ammo.destroy(Ve),Ammo.destroy(hi),Ammo.destroy(Qn),Fs=null,Ve=null,hi=null,Qn=null}set angularDamping(e){this._angularDamping!==e&&(this._angularDamping=e,this._body&&this._body.setDamping(this._linearDamping,e))}get angularDamping(){return this._angularDamping}set angularFactor(e){this._angularFactor.equals(e)||(this._angularFactor.copy(e),this._body&&this._type===li&&(Ve.setValue(e.x,e.y,e.z),this._body.setAngularFactor(Ve)))}get angularFactor(){return this._angularFactor}set angularVelocity(e){this._body&&this._type===li&&(this._body.activate(),Ve.setValue(e.x,e.y,e.z),this._body.setAngularVelocity(Ve),this._angularVelocity.copy(e))}get angularVelocity(){if(this._body&&this._type===li){const e=this._body.getAngularVelocity();this._angularVelocity.set(e.x(),e.y(),e.z())}return this._angularVelocity}set body(e){this._body!==e&&(this._body=e,e&&this._simulationEnabled&&e.activate())}get body(){return this._body}set friction(e){this._friction!==e&&(this._friction=e,this._body&&this._body.setFriction(e))}get friction(){return this._friction}set group(e){this._group!==e&&(this._group=e,this.enabled&&this.entity.enabled&&(this.disableSimulation(),this.enableSimulation()))}get group(){return this._group}set linearDamping(e){this._linearDamping!==e&&(this._linearDamping=e,this._body&&this._body.setDamping(e,this._angularDamping))}get linearDamping(){return this._linearDamping}set linearFactor(e){this._linearFactor.equals(e)||(this._linearFactor.copy(e),this._body&&this._type===li&&(Ve.setValue(e.x,e.y,e.z),this._body.setLinearFactor(Ve)))}get linearFactor(){return this._linearFactor}set linearVelocity(e){this._body&&this._type===li&&(this._body.activate(),Ve.setValue(e.x,e.y,e.z),this._body.setLinearVelocity(Ve),this._linearVelocity.copy(e))}get linearVelocity(){if(this._body&&this._type===li){const e=this._body.getLinearVelocity();this._linearVelocity.set(e.x(),e.y(),e.z())}return this._linearVelocity}set mask(e){this._mask!==e&&(this._mask=e,this.enabled&&this.entity.enabled&&(this.disableSimulation(),this.enableSimulation()))}get mask(){return this._mask}set mass(e){if(this._mass!==e&&(this._mass=e,this._body&&this._type===li)){const t=this.enabled&&this.entity.enabled;t&&this.disableSimulation(),this._body.getCollisionShape().calculateLocalInertia(e,Ve),this._body.setMassProps(e,Ve),this._body.updateInertiaTensor(),t&&this.enableSimulation()}}get mass(){return this._mass}set restitution(e){this._restitution!==e&&(this._restitution=e,this._body&&this._body.setRestitution(e))}get restitution(){return this._restitution}set rollingFriction(e){this._rollingFriction!==e&&(this._rollingFriction=e,this._body&&this._body.setRollingFriction(e))}get rollingFriction(){return this._rollingFriction}set type(e){if(this._type!==e){switch(this._type=e,this.disableSimulation(),e){case li:this._group=gN,this._mask=jy;break;case Xn:this._group=vN,this._mask=jy;break;case El:default:this._group=Xy,this._mask=__;break}this.createBody()}}get type(){return this._type}createBody(){const e=this.entity;let t;if(e.collision&&(t=e.collision.shape,e.trigger&&(e.trigger.destroy(),delete e.trigger)),t){this._body&&(this.system.removeBody(this._body),this.system.destroyBody(this._body),this._body=null);const s=this._type===li?this._mass:0;this._getEntityTransform(Fs);const i=this.system.createBody(s,t,Fs);if(i.setRestitution(this._restitution),i.setFriction(this._friction),i.setRollingFriction(this._rollingFriction),i.setDamping(this._linearDamping,this._angularDamping),this._type===li){const r=this._linearFactor;Ve.setValue(r.x,r.y,r.z),i.setLinearFactor(Ve);const a=this._angularFactor;Ve.setValue(a.x,a.y,a.z),i.setAngularFactor(Ve)}else this._type===Xn&&(i.setCollisionFlags(i.getCollisionFlags()|_N),i.setActivationState(Wy));i.entity=e,this.body=i,this.enabled&&e.enabled&&this.enableSimulation()}}isActive(){return this._body?this._body.isActive():!1}activate(){this._body&&this._body.activate()}enableSimulation(){const e=this.entity;if(e.collision&&e.collision.enabled&&!this._simulationEnabled){const t=this._body;if(t){switch(this.system.addBody(t,this._group,this._mask),this._type){case li:this.system._dynamic.push(this),t.forceActivationState(m_),this.syncEntityToBody();break;case Xn:this.system._kinematic.push(this),t.forceActivationState(Wy);break;case El:t.forceActivationState(m_),this.syncEntityToBody();break}e.collision.type==="compound"&&this.system._compounds.push(e.collision),t.activate(),this._simulationEnabled=!0}}}disableSimulation(){const e=this._body;if(e&&this._simulationEnabled){const t=this.system;let s=t._compounds.indexOf(this.entity.collision);s>-1&&t._compounds.splice(s,1),s=t._dynamic.indexOf(this),s>-1&&t._dynamic.splice(s,1),s=t._kinematic.indexOf(this),s>-1&&t._kinematic.splice(s,1),t.removeBody(e),e.forceActivationState(Uw),this._simulationEnabled=!1}}applyForce(e,t,s,i,r,a){const n=this._body;n&&(n.activate(),e instanceof E?Ve.setValue(e.x,e.y,e.z):Ve.setValue(e,t,s
13428),t instanceof E?hi.setValue(t.x,t.y,t.z):i!==void 0?hi.setValue(i,r,a):hi.setValue(0,0,0),n.applyForce(Ve,hi))}applyTorque(e,t,s){const i=this._body;i&&(i.activate(),e instanceof E?Ve.setValue(e.x,e.y,e.z):Ve.setValue(e,t,s),i.applyTorque(Ve))}applyImpulse(e,t,s,i,r,a){const n=this._body;n&&(n.activate(),e instanceof E?Ve.setValue(e.x,e.y,e.z):Ve.setValue(e,t,s),t instanceof E?hi.setValue(t.x,t.y,t.z):i!==void 0?hi.setValue(i,r,a):hi.setValue(0,0,0),n.applyImpulse(Ve,hi))}applyTorqueImpulse(e,t,s){const i=this._body;i&&(i.activate(),e instanceof E?Ve.setValue(e.x,e.y,e.z):Ve.setValue(e,t,s),i.applyTorqueImpulse(Ve))}isStatic(){return this._type===El}isStaticOrKinematic(){return this._type===El||this._type===Xn}isKinematic(){return this._type===Xn}_getEntityTransform(e){const t=this.entity,s=t.collision;if(s){const i=s.getShapePosition(),r=s.getShapeRotation();Ve.setValue(i.x,i.y,i.z),Qn.setValue(r.x,r.y,r.z,r.w)}else{const i=t.getPosition(),r=t.getRotation();Ve.setValue(i.x,i.y,i.z),Qn.setValue(r.x,r.y,r.z,r.w)}e.setOrigin(Ve),e.setRotation(Qn)}syncEntityToBody(){const e=this._body;if(e){if(this._getEntityTransform(Fs),e.setWorldTransform(Fs),this._type===Xn){const t=e.getMotionState();t&&t.setWorldTransform(Fs)}e.activate()}}_updateDynamic(){const e=this._body;if(e.isActive()){const t=e.getMotionState();if(t){const s=this.entity;t.getWorldTransform(Fs);const i=Fs.getOrigin(),r=Fs.getRotation(),a=s.collision;if(a&&a._hasOffset){const n=a.data.linearOffset,o=a.data.angularOffset,c=dz.copy(o).invert(),h=hz.set(r.x(),r.y(),r.z(),r.w()).mul(c);h.transformVector(n,rd),s.setPosition(i.x()-rd.x,i.y()-rd.y,i.z()-rd.z),s.setRotation(h)}else s.setPosition(i.x(),i.y(),i.z()),s.setRotation(r.x(),r.y(),r.z(),r.w())}}}_updateKinematic(){const e=this._body.getMotionState();e&&(this._getEntityTransform(Fs),e.setWorldTransform(Fs))}teleport(e,t,s,i,r,a){e instanceof E?this.entity.setPosition(e):this.entity.setPosition(e,t,s),t instanceof ae?this.entity.setRotation(t):t instanceof E?this.entity.setEulerAngles(t):i!==void 0&&this.entity.setEulerAngles(i,r,a),this.syncEntityToBody()}onEnable(){this._body||this.createBody(),this.enableSimulation()}onDisable(){this.disableSimulation()}}class uz{enabled=!0}let tr,sr;class i0{entity;point;normal;hitFraction;constructor(e,t,s,i){this.entity=e,this.point=t,this.normal=s,this.hitFraction=i}}class fz{a;b;impulse;localPointA;localPointB;pointA;pointB;normal;constructor(e,t,s){arguments.length!==0?(this.a=e,this.b=t,this.impulse=s.impulse,this.localPointA=s.localPoint,this.localPointB=s.localPointOther,this.pointA=s.point,this.pointB=s.pointOther,this.normal=s.normal):(this.a=null,this.b=null,this.impulse=0,this.localPointA=new E,this.localPointB=new E,this.pointA=new E,this.pointB=new E,this.normal=new E)}}class pz{localPoint;localPointOther;point;pointOther;normal;impulse;constructor(e=new E,t=new E,s=new E,i=new E,r=new E,a=0){this.localPoint=e,this.localPointOther=t,this.point=s,this.pointOther=i,this.normal=r,this.impulse=a}}class mz{other;contacts;constructor(e,t){this.other=e,this.contacts=t}}const Qw=["enabled"];class Jw extends Tt{static EVENT_CONTACT="contact";maxSubSteps=10;fixedTimeStep=1/60;gravity=new E(0,-9.81,0);_gravityFloat32=new Float32Array(3);_dynamic=[];_kinematic=[];_triggers=[];_compounds=[];constructor(e){super(e),this.id="rigidbody",this._stats=e.stats.frame,this.ComponentType=Eo,this.DataType=uz,this.contactPointPool=null,this.contactResultPool=null,this.singleContactResultPool=null,this.schema=Qw,this.collisions={},this.frameCollisions={},this.on("beforeremove",this.onBeforeRemove,this)}onLibraryLoaded(){if(typeof Ammo<"u"){if(this.collisionConfiguration=new Ammo.btDefaultCollisionConfiguration,this.dispatcher=new Ammo.btCollisionDispatcher(this.collisionConfiguration),this.overlappingPairCache=new Ammo.btDbvtBroadphase,this.solver=new Ammo.btSequentialImpulseConstraintSolver,this.dynamicsWorld=new Ammo.btDiscreteDynamicsWorld(this.dispatcher,this.overlappingPairCache,this.solver,this.collisionConfiguration),this.dynamicsWorld.setInternalTickCallback){const e=Ammo.addFunction(this._checkForCollisions.bind(this),"vif");this.dynamicsWorld.setInternalTickCallback(e)}tr=new Ammo.btVector3,sr=new Ammo.btVector3,Eo.onLibraryLoaded(),this.contactPointPool=new Jp(pz,1),this.contactResultPool=new Jp(mz,1),this.singleContactResultPool=new Jp(fz,1),this.app.systems.on("update",this.onUpdate,this)}else this.app.systems.off("update",this.onUpdate,this)}initializeComponentData(e,t,s){const i=["mass","linearDamping","angularDamping","linearFactor","angularFactor","friction","rollingFriction","restitution","type","group","mask"];for(const r of i)if(t.hasOwnProperty(r)){const a=t[r];Array.isArray(a)?e[r]=new E(a[0],a[1],a[2]):e[r]=a}super.initializeComponentData(e,t,["enabled"])}cloneComponent(e,t){const s=e.rigidbody,i={enabled:s.enabled,mass:s.mass,linearDamping:s.linearDamping,angularDamping:s.angularDamping,linearFactor:[s.linearFactor.x,s.linearFactor.y,s.linearFactor.z],angularFactor:[s.angularFactor.x,s.angularFactor.y,s.angularFactor.z],friction:s.friction,rollingFriction:s.rollingFriction,restitution:s.restitution,type:s.type,group:s.group,mask:s.mask};return this.addComponent(t,i)}onBeforeRemove(e,t){t.enabled&&(t.enabled=!1),t.body&&(this.destroyBody(t.body),t.body=null)}addBody(e,t,s){t!==void 0&&s!==void 0?this.dynamicsWorld.addRigidBody(e,t,s):this.dynamicsWorld.addRigidBody(e)}removeBody(e){this.dynamicsWorld.removeRigidBody(e)}createBody(e,t,s){const i=new Ammo.btVector3(0,0,0);e!==0&&t.calculateLocalInertia(e,i);const r=new Ammo.btDefaultMotionState(s),a=new Ammo.btRigidBodyConstructionInfo(e,r,t,i),n=new Ammo.btRigidBody(a);return Ammo.destroy(a),Ammo.destroy(i),n}destroyBody(e){const t=e.getMotionState();t&&Ammo.destroy(t),Ammo.destroy(e)}raycastFirst(e,t,s={}){if(s.filterTags||s.filterCallback)return s.sort=!0,this.raycastAll(e,t,s
13428)[0]||null;let i=null;tr.setValue(e.x,e.y,e.z),sr.setValue(t.x,t.y,t.z);const r=new Ammo.ClosestRayResultCallback(tr,sr);if(typeof s.filterCollisionGroup=="number"&&r.set_m_collisionFilterGroup(s.filterCollisionGroup),typeof s.filterCollisionMask=="number"&&r.set_m_collisionFilterMask(s.filterCollisionMask),this.dynamicsWorld.rayTest(tr,sr,r),r.hasHit()){const a=r.get_m_collisionObject(),n=Ammo.castObject(a,Ammo.btRigidBody);if(n){const o=r.get_m_hitPointWorld(),c=r.get_m_hitNormalWorld();i=new i0(n.entity,new E(o.x(),o.y(),o.z()),new E(c.x(),c.y(),c.z()),r.get_m_closestHitFraction())}}return Ammo.destroy(r),i}raycastAll(e,t,s={}){const i=[];tr.setValue(e.x,e.y,e.z),sr.setValue(t.x,t.y,t.z);const r=new Ammo.AllHitsRayResultCallback(tr,sr);if(typeof s.filterCollisionGroup=="number"&&r.set_m_collisionFilterGroup(s.filterCollisionGroup),typeof s.filterCollisionMask=="number"&&r.set_m_collisionFilterMask(s.filterCollisionMask),this.dynamicsWorld.rayTest(tr,sr,r),r.hasHit()){const a=r.get_m_collisionObjects(),n=r.get_m_hitPointWorld(),o=r.get_m_hitNormalWorld(),c=r.get_m_hitFractions(),h=a.size();for(let d=0;d<h;d++){const u=Ammo.castObject(a.at(d),Ammo.btRigidBody);if(u&&u.entity){if(s.filterTags&&!u.entity.tags.has(...s.filterTags)||s.filterCallback&&!s.filterCallback(u.entity))continue;const f=n.at(d),p=o.at(d),m=new i0(u.entity,new E(f.x(),f.y(),f.z()),new E(p.x(),p.y(),p.z()),c.at(d));i.push(m)}}s.sort&&i.sort((d,u)=>d.hitFraction-u.hitFraction)}return Ammo.destroy(r),i}_storeCollision(e,t){let s=!1;const i=e.guid;return this.collisions[i]=this.collisions[i]||{others:[],entity:e},this.collisions[i].others.indexOf(t)<0&&(this.collisions[i].others.push(t),s=!0),this.frameCollisions[i]=this.frameCollisions[i]||{others:[],entity:e},this.frameCollisions[i].others.push(t),s}_createContactPointFromAmmo(e){const t=e.get_m_localPointA(),s=e.get_m_localPointB(),i=e.getPositionWorldOnA(),r=e.getPositionWorldOnB(),a=e.get_m_normalWorldOnB(),n=this.contactPointPool.allocate();return n.localPoint.set(t.x(),t.y(),t.z()),n.localPointOther.set(s.x(),s.y(),s.z()),n.point.set(i.x(),i.y(),i.z()),n.pointOther.set(r.x(),r.y(),r.z()),n.normal.set(a.x(),a.y(),a.z()),n.impulse=e.getAppliedImpulse(),n}_createReverseContactPointFromAmmo(e){const t=e.get_m_localPointA(),s=e.get_m_localPointB(),i=e.getPositionWorldOnA(),r=e.getPositionWorldOnB(),a=e.get_m_normalWorldOnB(),n=this.contactPointPool.allocate();return n.localPointOther.set(t.x(),t.y(),t.z()),n.localPoint.set(s.x(),s.y(),s.z()),n.pointOther.set(i.x(),i.y(),i.z()),n.point.set(r.x(),r.y(),r.z()),n.normal.set(a.x(),a.y(),a.z()),n.impulse=e.getAppliedImpulse(),n}_createSingleContactResult(e,t,s){const i=this.singleContactResultPool.allocate();return i.a=e,i.b=t,i.localPointA=s.localPoint,i.localPointB=s.localPointOther,i.pointA=s.point,i.pointB=s.pointOther,i.normal=s.normal,i.impulse=s.impulse,i}_createContactResult(e,t){const s=this.contactResultPool.allocate();return s.other=e,s.contacts=t,s}_cleanOldCollisions(){for(const e in this.collisions)if(this.collisions.hasOwnProperty(e)){const t=this.frameCollisions[e],s=this.collisions[e],i=s.entity,r=i.collision,a=i.rigidbody,n=s.others;let c=n.length;for(;c--;){const h=n[c];(!t||t.others.indexOf(h)<0)&&(n.splice(c,1),i.trigger?(r&&r.fire("triggerleave",h),h.rigidbody&&h.rigidbody.fire("triggerleave",i)):h.trigger||(a&&a.fire("collisionend",h),r&&r.fire("collisionend",h)))}n.length===0&&delete this.collisions[e]}}_hasContactEvent(e){const t=e.collision;if(t&&(t.hasEvent("collisionstart")||t.hasEvent("collisionend")||t.hasEvent("contact")))return!0;const s=e.rigidbody;return s&&(s.hasEvent("collisionstart")||s.hasEvent("collisionend")||s.hasEvent("contact"))}_checkForCollisions(e,t){const i=Ammo.wrapPointer(e,Ammo.btDynamicsWorld).getDispatcher(),r=i.getNumManifolds();this.frameCollisions={};for(let a=0;a<r;a++){const n=i.getManifoldByIndexInternal(a),o=n.getBody0(),c=n.getBody1(),h=Ammo.castObject(o,Ammo.btRigidBody),d=Ammo.castObject(c,Ammo.btRigidBody),u=h.entity,f=d.entity;if(!u||!f)continue;const p=h.getCollisionFlags(),m=d.getCollisionFlags(),_=n.getNumC
13428ontacts(),g=[],v=[];let x;if(_>0)if(p&Ul||m&Ul){const y=u.collision&&(u.collision.hasEvent("triggerenter")||u.collision.hasEvent("triggerleave")),S=f.collision&&(f.collision.hasEvent("triggerenter")||f.collision.hasEvent("triggerleave")),T=u.rigidbody&&(u.rigidbody.hasEvent("triggerenter")||u.rigidbody.hasEvent("triggerleave")),w=f.rigidbody&&(f.rigidbody.hasEvent("triggerenter")||f.rigidbody.hasEvent("triggerleave"));y&&(x=this._storeCollision(u,f),x&&!(m&Ul)&&u.collision.fire("triggerenter",f)),S&&(x=this._storeCollision(f,u),x&&!(p&Ul)&&f.collision.fire("triggerenter",u)),T&&(x||(x=this._storeCollision(f,u)),x&&u.rigidbody.fire("triggerenter",f)),w&&(x||(x=this._storeCollision(u,f)),x&&f.rigidbody.fire("triggerenter",u))}else{const y=this._hasContactEvent(u),S=this._hasContactEvent(f),T=this.hasEvent("contact");if(T||y||S){for(let w=0;w<_;w++){const C=n.getContactPoint(w),b=this._createContactPointFromAmmo(C);if(y||S){g.push(b);const I=this._createReverseContactPointFromAmmo(C);v.push(I)}if(T){const I=this._createSingleContactResult(u,f,b);this.fire("contact",I)}}if(y){const w=this._createContactResult(f,g);x=this._storeCollision(u,f),u.collision&&(u.collision.fire("contact",w),x&&u.collision.fire("collisionstart",w)),u.rigidbody&&(u.rigidbody.fire("contact",w),x&&u.rigidbody.fire("collisionstart",w))}if(S){const w=this._createContactResult(u,v);x=this._storeCollision(f,u),f.collision&&(f.collision.fire("contact",w),x&&f.collision.fire("collisionstart",w)),f.rigidbody&&(f.rigidbody.fire("contact",w),x&&f.rigidbody.fire("collisionstart",w))}}}}this._cleanOldCollisions(),this.contactPointPool.freeAll(),this.contactResultPool.freeAll(),this.singleContactResultPool.freeAll()}onUpdate(e){let t,s;this._stats.physicsStart=Gt(),this._gravityFloat32[0]=this.gravity.x,this._gravityFloat32[1]=this.gravity.y,this._gravityFloat32[2]=this.gravity.z;const i=this.dynamicsWorld.getGravity();(i.x()!==this._gravityFloat32[0]||i.y()!==this._gravityFloat32[1]||i.z()!==this._gravityFloat32[2])&&(i.setValue(this.gravity.x,this.gravity.y,this.gravity.z),this.dynamicsWorld.setGravity(i));const r=this._triggers;for(t=0,s=r.length;t<s;t++)r[t].updateTransform();const a=this._compounds;for(t=0,s=a.length;t<s;t++)a[t]._updateCompound();const n=this._kinematic;for(t=0,s=n.length;t<s;t++)n[t]._updateKinematic();this.dynamicsWorld.stepSimulation(e,this.maxSubSteps,this.fixedTimeStep);const o=this._dynamic;for(t=0,s=o.length;t<s;t++)o[t]._updateDynamic();this.dynamicsWorld.setInternalTickCallback||this._checkForCollisions(Ammo.getPointer(this.dynamicsWorld),e),this._stats.physicsTime=Gt()-this._stats.physicsStart}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this),typeof Ammo<"u"&&(Ammo.destroy(this.dynamicsWorld),Ammo.destroy(this.solver),Ammo.destroy(this.overlappingPairCache),Ammo.destroy(this.dispatcher),Ammo.destroy(this.collisionConfiguration),Ammo.destroy(tr),Ammo.destroy(sr),this.dynamicsWorld=null,this.solver=null,this.overlappingPairCache=null,this.dispatcher=null,this.collisionConfiguration=null,tr=null,sr=null,Eo.onAppDestroy())}}ye._buildAccessors(Eo.prototype,Qw);const Jn="none",_z="blend",r0=new Z;class eC extends ye{_resolution=new j(640,320);_referenceResolution=new j(640,320);_scaleMode=Jn;scale=1;_scaleBlend=.5;_priority=0;_screenSpace=!1;cull=!1;_screenMatrix=new Z;_elements=new Set;constructor(e,t){super(e,t),e.app.graphicsDevice.on("resizecanvas",this._onResize,this)}syncDrawOrder(){this.system.queueDrawOrderSync(this.entity.guid,this._processDrawOrderSync,this)}_recurseDrawOrderSync(e,t){if(!(e instanceof lt))return t;if(e.element){const i=e.element.drawOrder;e.element.drawOrder=t++,e.element._batchGroupId>=0&&i!==e.element.drawOrder&&this.system.app.batcher?.markGroupDirty(e.element._batchGroupId)}e.particlesystem&&(e.particlesystem.drawOrder=t++);const s=e.children;for(let i=0;i<s.length;i++)t=this._recurseDrawOrderSync(s[i],t);return t}_processDrawOrderSync(){this._recurseDrawOrderSync(this.entity,1),this.fire("syncdraworder")}_calcProjectionMatrix(){const e=this._resolution.x/this.scale,t=this._resolution.y/this.scale,s=0,i=e,r=-t;this._screenMatrix.setOrtho(s,i,r,0,1,-1),this._screenSpace||(r0.setScale(.5*e,.5*t,1),this._screenMatrix.mul2(r0,this._screenMatrix))}_updateScale(){this.scale=this._calcScale(this._resolution,this.referenceResolution)}_calcScale(e,t){const s=Math.log2((e.x||1)/t.x),i=Math.log2((e.y||1)/t.y
13428);return Math.pow(2,s*(1-this._scaleBlend)+i*this._scaleBlend)}_onResize(e,t){this._screenSpace&&(this._resolution.set(e,t),this.resolution=this._resolution)}_bindElement(e){this._elements.add(e)}_unbindElement(e){this._elements.delete(e)}onRemove(){this.system.app.graphicsDevice.off("resizecanvas",this._onResize,this),this.fire("remove"),this._elements.forEach(e=>e._onScreenRemove()),this._elements.clear(),this.off()}set resolution(e){this._screenSpace?this._resolution.set(this.system.app.graphicsDevice.width,this.system.app.graphicsDevice.height):this._resolution.set(e.x,e.y),this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:resolution",this._resolution),this._elements.forEach(t=>t._onScreenResize(this._resolution))}get resolution(){return this._resolution}set referenceResolution(e){this._referenceResolution.set(e.x,e.y),this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:referenceresolution",this._resolution),this._elements.forEach(t=>t._onScreenResize(this._resolution))}get referenceResolution(){return this._scaleMode===Jn?this._resolution:this._referenceResolution}set screenSpace(e){this._screenSpace=e,this._screenSpace&&this._resolution.set(this.system.app.graphicsDevice.width,this.system.app.graphicsDevice.height),this.resolution=this._resolution,this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:screenspace",this._screenSpace),this._elements.forEach(t=>t._onScreenSpaceChange())}get screenSpace(){return this._screenSpace}set scaleMode(e){e!==Jn&&e!==_z&&(e=Jn),!this._screenSpace&&e!==Jn&&(e=Jn),this._scaleMode=e,this.resolution=this._resolution,this.fire("set:scalemode",this._scaleMode)}get scaleMode(){return this._scaleMode}set scaleBlend(e){this._scaleBlend=e,this._updateScale(),this._calcProjectionMatrix(),this.entity._dirtyLocal||this.entity._dirtifyLocal(),this.fire("set:scaleblend",this._scaleBlend),this._elements.forEach(t=>t._onScreenResize(this._resolution))}get scaleBlend(){return this._scaleBlend}set priority(e){e=H.clamp(e,0,127),this._priority!==e&&(this._priority=e,this.syncDrawOrder())}get priority(){return this._priority}}class gz{enabled=!0}const E_=["enabled"];class vz extends Tt{constructor(e){super(e),this.id="screen",this.ComponentType=eC,this.DataType=gz,this.schema=E_,this.windowResolution=new j,this._drawOrderSyncQueue=new mE,this.app.graphicsDevice.on("resizecanvas",this._onResize,this),this.app.systems.on("update",this._onUpdate,this),this.on("beforeremove",this.onRemoveComponent,this)}initializeComponentData(e,t,s){t.priority!==void 0&&(e.priority=t.priority),t.screenSpace!==void 0&&(e.screenSpace=t.screenSpace),e.cull=e.screenSpace,t.scaleMode!==void 0&&(e.scaleMode=t.scaleMode),t.scaleBlend!==void 0&&(e.scaleBlend=t.scaleBlend),t.resolution!==void 0&&(t.resolution instanceof j?e._resolution.copy(t.resolution):e._resolution.set(t.resolution[0],t.resolution[1]),e.resolution=e._resolution),t.referenceResolution!==void 0&&(t.referenceResolution instanceof j?e._referenceResolution.copy(t.referenceResolution):e._referenceResolution.set(t.referenceResolution[0],t.referenceResolution[1]),e.referenceResolution=e._referenceResolution),this._updateDescendantElements(e.entity,e.entity),e.syncDrawOrder(),super.initializeComponentData(e,t,E_)}_updateDescendantElements(e,t){const s=e.children;for(let i=0;i<s.length;i++){const r=s[i];r.element&&!r.element.screen&&r.element._updateScreen(t),r.screen||this._updateDescendantElements(r,t)}}destroy(){super.destroy(),this.app.graphicsDevice.off("resizecanvas",this._onResize,this),this.app.systems.off("update",this._onUpdate,this)}_onUpdate(e){const t=this.store;for(const s in t)t[s].entity.screen.update&&t[s].entity.screen.update(e)}_onResize(e,t){this.windowResolution.x=e,this.windowResolution.y=t}cloneComponent(e,t){const s=e.screen;return this.addComponent(t,{enabled:s.enabled,screenSpace:s.screenSpace,scaleMode:s.scaleMode,scaleBlend:s.scaleBlend,priority:s.priority,resolution:s.resolution.clone(),referenceResolution:s.referenceResolution.clone()})}onRemoveComponent(e,t){t.onRemove()}processDrawOrderSyncQueue(){const e=this._drawOrderSyncQueue.list();for(let t=0;t<e.length;t++){const s=e[t];s.callback.call(s.scope)}this._drawOrderSyncQueue.clear()}queueDrawOrderSync(e,t,s){this._drawOrderSyncQueue.list().length||this.app.once("prerender",this.processDrawOrderSyncQueue,this),this._drawOrderSyncQueue.has(e)||this._drawOrderSyncQueue.push(e,{callback:t,scope:s})}}ye._buildAccessors(eC.prototype,E_);const Hr=new j,a0=new E,Oa=new km,n0=new Lx,o0=new E,bl=new E,Sz=new ae,yz={x:"y",y:"x"};class tC extends ge{static EVENT_DRAGSTART="drag:start";static EVENT_DRAGEND="drag:end";static EVENT_DRAGMOVE="drag:move";
13428constructor(e,t){if(super(),!e||!(e instanceof Hw))throw new Error("Element was null or not an ElementComponent");if(t&&t!=="x"&&t!=="y")throw new Error(`Unrecognized axis: ${t}`);this._element=e,this._app=e.system.app,this._axis=t||null,this._enabled=!0,this._dragScale=new E,this._dragStartMousePosition=new E,this._dragStartHandlePosition=new E,this._deltaMousePosition=new E,this._deltaHandlePosition=new E,this._isDragging=!1,this._toggleLifecycleListeners("on")}_toggleLifecycleListeners(e){this._element[e]("mousedown",this._onMouseDownOrTouchStart,this),this._element[e]("touchstart",this._onMouseDownOrTouchStart,this),this._element[e]("selectstart",this._onMouseDownOrTouchStart,this)}_toggleDragListeners(e){const t=e==="on";this._hasDragListeners&&t||(this._app.mouse&&(this._element[e]("mousemove",this._onMove,this),this._element[e]("mouseup",this._onMouseUpOrTouchEnd,this)),Ce.touch&&(this._element[e]("touchmove",this._onMove,this),this._element[e]("touchend",this._onMouseUpOrTouchEnd,this),this._element[e]("touchcancel",this._onMouseUpOrTouchEnd,this)),this._element[e]("selectmove",this._onMove,this),this._element[e]("selectend",this._onMouseUpOrTouchEnd,this),this._hasDragListeners=t)}_onMouseDownOrTouchStart(e){if(this._element&&!this._isDragging&&this.enabled){this._dragCamera=e.camera,this._calculateDragScale();const t=this._screenToLocal(e);t&&(this._toggleDragListeners("on"),this._isDragging=!0,this._dragStartMousePosition.copy(t),this._dragStartHandlePosition.copy(this._element.entity.getLocalPosition()),this.fire("drag:start"))}}_onMouseUpOrTouchEnd(){this._isDragging&&(this._isDragging=!1,this._toggleDragListeners("off"),this.fire("drag:end"))}_screenToLocal(e){return e.inputSource?Oa.set(e.inputSource.getOrigin(),e.inputSource.getDirection()):(this._determineInputPosition(e),this._chooseRayOriginAndDirection()),o0.copy(this._element.entity.forward).mulScalar(-1),n0.setFromPointNormal(this._element.entity.getPosition(),o0),n0.intersectsRay(Oa,bl)?(Sz.copy(this._element.entity.getRotation()).invert().transformVector(bl,bl),bl.mul(this._dragScale),bl):null}_determineInputPosition(e){const t=this._app.graphicsDevice.maxPixelRatio;typeof e.x<"u"&&typeof e.y<"u"?(Hr.x=e.x*t,Hr.y=e.y*t):e.changedTouches?(Hr.x=e.changedTouches[0].x*t,Hr.y=e.changedTouches[0].y*t):console.warn("Could not determine position from input event")}_chooseRayOriginAndDirection(){this._element.screen&&this._element.screen.screen.screenSpace?(Oa.origin.set(Hr.x,-Hr.y,0),Oa.direction.copy(E.FORWARD)):(a0.copy(this._dragCamera.screenToWorld(Hr.x,Hr.y,1)),Oa.origin.copy(this._dragCamera.entity.getPosition()),Oa.direction.copy(a0).sub(Oa.origin).normalize())}_calculateDragScale(){let e=this._element.entity.parent;const t=this._element.screen&&this._element.screen.screen,s=t&&t.screenSpace,i=s?t.scale:1,r=this._dragScale;for(r.set(i,i,i);e&&(r.mul(e.getLocalScale()),e=e.parent,!(s&&e.screen)););r.x=1/r.x,r.y=1/r.y,r.z=0}_onMove(e){const{_element:t,_deltaMousePosition:s,_deltaHandlePosition:i,_axis:r}=this;if(t&&this._isDragging&&this.enabled&&t.enabled&&t.entity.enabled){const a=this._screenToLocal(e);if(a){if(s.sub2(a,this._dragStartMousePosition),i.add2(this._dragStartHandlePosition,s),r){const n=t.entity.getLocalPosition(),o=yz[r];i[o]=n[o]}t.entity.setLocalPosition(i),this.fire("drag:move",i)}}}destroy(){this._toggleLifecycleListeners("off"),this._toggleDragListeners("off")}set enabled(e){this._enabled=e}get enabled(){return this._enabled}get isDragging(){return this._isDragging}}const xz=0,l0=1,Tz=2,wz=0,Cz=1,Al=new j;class sC extends ye{static EVENT_SETSCROLL="set:scroll";_horizontal;_vertical;_scrollMode;_bounceAmount;_friction;_dragThreshold=10;_useMouseWheel=!0;_mouseWheelSensitivity=new j(1,1);_horizontalScrollbarVisibility=0;_verticalScrollbarVisibility=0;_viewportEntity=null;_contentEntity=null;_horizontalScrollbarEntity=null;_verticalScrollbarEntity=null;_evtElementAdd=null;_evtElementRemove=null;_evtViewportEntityElementAdd=null;_evtViewportElementRemove=null;_evtViewportResize=null;_evtContentEntityElementAdd=null;_evtContentElementRemove=null;_evtContentResize=null;_evtHorizontalScrollbarAdd=null;_evtHorizontalScrollbarRemove=null;_evtHorizontalScrollbarValue=null;_evtVerticalScrollbarAdd=null;_evtVerticalScrollbarRemove=null;_evtVerticalScrollbarValue=null;constructor(e,t){super(e,t),this._scrollbarUpdateFlags={},this._scrollbarEntities={},this._prevContentSizes={},this._prevContentSizes[Me]=null,this._prevContentSizes[rt]=null,this._scroll=ne
13428w j,this._velocity=new E,this._dragStartPosition=new E,this._disabledContentInput=!1,this._disabledContentInputEntities=[],this._evtElementAdd=this.entity.on("element:add",this._onElementComponentAdd,this),this._toggleElementListeners("on")}set horizontal(e){this._horizontal!==e&&(this._horizontal=e,this._syncScrollbarEnabledState(Me))}get horizontal(){return this._horizontal}set vertical(e){this._vertical!==e&&(this._vertical=e,this._syncScrollbarEnabledState(rt))}get vertical(){return this._vertical}set scrollMode(e){this._scrollMode=e}get scrollMode(){return this._scrollMode}set bounceAmount(e){this._bounceAmount=e}get bounceAmount(){return this._bounceAmount}set friction(e){this._friction=e}get friction(){return this._friction}set dragThreshold(e){this._dragThreshold=e}get dragThreshold(){return this._dragThreshold}set useMouseWheel(e){this._useMouseWheel=e}get useMouseWheel(){return this._useMouseWheel}set mouseWheelSensitivity(e){e?e instanceof j?this._mouseWheelSensitivity=e.clone():this._mouseWheelSensitivity=new j(e[0],e[1]):this._mouseWheelSensitivity=e}get mouseWheelSensitivity(){return this._mouseWheelSensitivity}set horizontalScrollbarVisibility(e){this._horizontalScrollbarVisibility=e}get horizontalScrollbarVisibility(){return this._horizontalScrollbarVisibility}set verticalScrollbarVisibility(e){this._verticalScrollbarVisibility=e}get verticalScrollbarVisibility(){return this._verticalScrollbarVisibility}set viewportEntity(e){if(this._viewportEntity===e)return;const t=typeof e=="string";this._viewportEntity&&t&&this._viewportEntity.guid===e||(this._viewportEntity&&this._viewportEntityUnsubscribe(),e instanceof He?this._viewportEntity=e:t?this._viewportEntity=this.system.app.getEntityFromIndex(e)||null:this._viewportEntity=null,this._viewportEntity&&this._viewportEntitySubscribe())}get viewportEntity(){return this._viewportEntity}set contentEntity(e){if(this._contentEntity===e)return;const t=typeof e=="string";this._contentEntity&&t&&this._contentEntity.guid===e||(this._contentEntity&&this._contentEntityUnsubscribe(),e instanceof He?this._contentEntity=e:t?this._contentEntity=this.system.app.getEntityFromIndex(e)||null:this._contentEntity=null,this._contentEntity&&this._contentEntitySubscribe())}get contentEntity(){return this._contentEntity}set horizontalScrollbarEntity(e){if(this._horizontalScrollbarEntity===e)return;const t=typeof e=="string";this._horizontalScrollbarEntity&&t&&this._horizontalScrollbarEntity.guid===e||(this._horizontalScrollbarEntity&&this._horizontalScrollbarEntityUnsubscribe(),e instanceof He?this._horizontalScrollbarEntity=e:t?this._horizontalScrollbarEntity=this.system.app.getEntityFromIndex(e)||null:this._horizontalScrollbarEntity=null,this._scrollbarEntities[Me]=this._horizontalScrollbarEntity,this._horizontalScrollbarEntity&&this._horizontalScrollbarEntitySubscribe())}get horizontalScrollbarEntity(){return this._horizontalScrollbarEntity}set verticalScrollbarEntity(e){if(this._verticalScrollbarEntity===e)return;const t=typeof e=="string";this._verticalScrollbarEntity&&t&&this._verticalScrollbarEntity.guid===e||(this._verticalScrollbarEntity&&this._verticalScrollbarEntityUnsubscribe(),e instanceof He?this._verticalScrollbarEntity=e:t?this._verticalScrollbarEntity=this.system.app.getEntityFromIndex(e)||null:this._verticalScrollbarEntity=null,this._scrollbarEntities[rt]=this._verticalScrollbarEntity,this._verticalScrollbarEntity&&this._verticalScrollbarEntitySubscribe())}get verticalScrollbarEntity(){return this._verticalScrollbarEntity}set scroll(e){this._onSetScroll(e.x,e.y)}get scroll(){return this._scroll}_toggleElementListeners(e){if(this.entity.element){if(e==="on"&&this._hasElementListeners)return;this.entity.element[e]("resize",this._syncAll,this),this.entity.element[e]("mousewheel",this._onMouseWheel,this),this._hasElementListeners=e==="on"}}_onElementComponentAdd(e){this._evtElementRemove=this.entity.element.once("beforeremove",this._onElementComponentRemove,this),this._toggleElementListeners("on")}_onElementComponentRemove(e){this._evtElementRemove?.off(),this._evtElementRemove=null,this._toggleElementListeners("off")}
13428_viewportEntitySubscribe(){this._evtViewportEntityElementAdd=this._viewportEntity.on("element:add",this._onViewportElementGain,this),this._viewportEntity.element&&this._onViewportElementGain()}_viewportEntityUnsubscribe(){this._evtViewportEntityElementAdd?.off(),this._evtViewportEntityElementAdd=null,this._viewportEntity?.element&&this._onViewportElementLose()}_viewportEntityElementSubscribe(){const e=this._viewportEntity.element;this._evtViewportElementRemove=e.once("beforeremove",this._onViewportElementLose,this),this._evtViewportResize=e.on("resize",this._syncAll,this)}_viewportEntityElementUnsubscribe(){this._evtViewportElementRemove?.off(),this._evtViewportElementRemove=null,this._evtViewportResize?.off(),this._evtViewportResize=null}_onViewportElementGain(){this._viewportEntityElementSubscribe(),this._syncAll()}_onViewportElementLose(){this._viewportEntityElementUnsubscribe()}_contentEntitySubscribe(){this._evtContentEntityElementAdd=this._contentEntity.on("element:add",this._onContentElementGain,this),this._contentEntity.element&&this._onContentElementGain()}_contentEntityUnsubscribe(){this._evtContentEntityElementAdd?.off(),this._evtContentEntityElementAdd=null,this._contentEntity?.element&&this._onContentElementLose()}_contentEntityElementSubscribe(){const e=this._contentEntity.element;this._evtContentElementRemove=e.once("beforeremove",this._onContentElementLose,this),this._evtContentResize=e.on("resize",this._syncAll,this)}_contentEntityElementUnsubscribe(){this._evtContentElementRemove?.off(),this._evtContentElementRemove=null,this._evtContentResize?.off(),this._evtContentResize=null}_onContentElementGain(){this._contentEntityElementSubscribe(),this._destroyDragHelper(),this._contentDragHelper=new tC(this._contentEntity.element),this._contentDragHelper.on("drag:start",this._onContentDragStart,this),this._contentDragHelper.on("drag:end",this._onContentDragEnd,this),this._contentDragHelper.on("drag:move",this._onContentDragMove,this),this._prevContentSizes[Me]=null,this._prevContentSizes[rt]=null,this._syncAll()}_onContentElementLose(){this._contentEntityElementUnsubscribe(),this._destroyDragHelper()}_onContentDragStart(){this._contentEntity&&this.enabled&&this.entity.enabled&&this._dragStartPosition.copy(this._contentEntity.getLocalPosition())}_onContentDragEnd(){this._prevContentDragPosition=null,this._enableContentInput()}_onContentDragMove(e){if(this._contentEntity&&this.enabled&&this.entity.enabled&&(this._wasDragged=!0,this._setScrollFromContentPosition(e),this._setVelocityFromContentPositionDelta(e),!this._disabledContentInput)){const t=e.x-this._dragStartPosition.x,s=e.y-this._dragStartPosition.y;(Math.abs(t)>this.dragThreshold||Math.abs(s)>this.dragThreshold)&&this._disableContentInput()}}_horizontalScrollbarEntitySubscribe(){this._evtHorizontalScrollbarAdd=this._horizontalScrollbarEntity.on("scrollbar:add",this._onHorizontalScrollbarGain,this),this._horizontalScrollbarEntity.scrollbar&&this._onHorizontalScrollbarGain()}_verticalScrollbarEntitySubscribe(){this._evtVerticalScrollbarAdd=this._verticalScrollbarEntity.on("scrollbar:add",this._onVerticalScrollbarGain,this),this._verticalScrollbarEntity.scrollbar&&this._onVerticalScrollbarGain()}_horizontalScrollbarEntityUnsubscribe(){this._evtHorizontalScrollbarAdd?.off(),this._evtHorizontalScrollbarAdd=null,this._horizontalScrollbarEntity.scrollbar&&this._onHorizontalScrollbarLose()}_verticalScrollbarEntityUnsubscribe(){this._evtVerticalScrollbarAdd?.off(),this._evtVerticalScrollbarAdd=null,this._verticalScrollbarEntity.scrollbar&&this._onVerticalScrollbarLose()}_onSetHorizontalScrollbarValue(e){!this._scrollbarUpdateFlags[Me]&&this.enabled&&this.entity.enabled&&this._onSetScroll(e,null)}_onSetVerticalScrollbarValue(e){!this._scrollbarUpdateFlags[rt]&&this.enabled&&this.entity.enabled&&this._onSetScroll(null,e)}_onHorizontalScrollbarGain(){const e=this._horizontalScrollbarEntity?.scrollbar;this._evtHorizontalScrollbarRemove=e.on("beforeremove",this._onHorizontalScrollbarLose,this),this._evtHorizontalScrollbarValue=e.on("set:value",this._onSetHorizontalScrollbarValue,this),this._syncScrollbarEnabledState(Me),this._syncScrollbarPosition(Me)}_onVerticalScrollbarGain(){const e=this._verticalScrollbarEntity?.scrollbar;this._evtVerticalScrollbarRemove=e.on("beforeremove",this._onVerticalScrollbarLose,this),this._evtVerticalScrollbarValue=e.on("set:value",this._onSetVerticalScrollbarValue,this),this._syncScrollbarEnabledState(rt),this._syncScrollbarPosition(rt)}_onHorizontalScrollbarLose(){this._evtHorizontalScrollbarRemove?.off(),this._evtHorizontalScrollbarRemove=null,this._evtHorizontalScrollbarValue?.off(),this._evtHorizontalScrollbarValue=null}_onVerticalScrollbarLose(){this._evtVerticalScrollbarRemove?.off(),this._evtVerticalScrollbarRemove=null,this._evtVerticalScrollbarValue?.off(),this._evtVerticalScrollbarValue=null}_onSetScroll(e,t,s){s!==!1&&this._velocity.set(0,0,0);const i=this._updateAxis(e,"x",Me),r=this._updateAxis(t,"y",rt);(i||r)&&this.fire("set:scroll",this._scroll)}_updateAxis(e,t,s){const i=e!==null&&Math.abs(e-this._scroll[t])>1e-5;return(i||this._isDragging()||e===0)&&(this._scroll[t]=this._determineNewScrollValue(e,t,s
13428),this._syncContentPosition(s),this._syncScrollbarPosition(s)),i}_determineNewScrollValue(e,t,s){if(!this._getScrollingEnabled(s))return this._scroll[t];switch(this.scrollMode){case xz:return H.clamp(e,0,this._getMaxScrollValue(s));case l0:return this._setVelocityFromOvershoot(e,t,s),e;case Tz:return e;default:return console.warn(`Unhandled scroll mode:${this.scrollMode}`),e}}_syncAll(){this._syncContentPosition(Me),this._syncContentPosition(rt),this._syncScrollbarPosition(Me),this._syncScrollbarPosition(rt),this._syncScrollbarEnabledState(Me),this._syncScrollbarEnabledState(rt)}_syncContentPosition(e){if(!this._contentEntity)return;const t=this._getAxis(e),s=this._getSign(e),i=this._prevContentSizes[e],r=this._getContentSize(e);if(i!==null&&Math.abs(i-r)>1e-4){const o=this._getMaxOffset(e,i),c=this._getMaxOffset(e,r);c===0?this._scroll[t]=1:this._scroll[t]=H.clamp(this._scroll[t]*o/c,0,1)}const a=this._scroll[t]*this._getMaxOffset(e),n=this._contentEntity.getLocalPosition();n[t]=a*s,this._contentEntity.setLocalPosition(n),this._prevContentSizes[e]=r}_syncScrollbarPosition(e){const t=this._scrollbarEntities[e];if(!t?.scrollbar)return;const s=this._getAxis(e);this._scrollbarUpdateFlags[e]=!0,t.scrollbar.value=this._scroll[s],t.scrollbar.handleSize=this._getScrollbarHandleSize(s,e),this._scrollbarUpdateFlags[e]=!1}_syncScrollbarEnabledState(e){const t=this._scrollbarEntities[e];if(!t)return;const s=this._getScrollingEnabled(e),i=this._getScrollbarVisibility(e);switch(i){case wz:t.enabled=s;return;case Cz:t.enabled=s&&this._contentIsLargerThanViewport(e);return;default:console.warn(`Unhandled scrollbar visibility:${i}`),t.enabled=s}}_contentIsLargerThanViewport(e){return this._getContentSize(e)>this._getViewportSize(e)}_contentPositionToScrollValue(e){const t=this._getMaxOffset(Me),s=this._getMaxOffset(rt);return t===0?Al.x=0:Al.x=e.x/t,s===0?Al.y=0:Al.y=e.y/-s,Al}_getMaxOffset(e,t){t=t===void 0?this._getContentSize(e):t;const s=this._getViewportSize(e);return t<s?-this._getViewportSize(e):s-t}_getMaxScrollValue(e){return this._contentIsLargerThanViewport(e)?1:0}_getScrollbarHandleSize(e,t){const s=this._getViewportSize(t),i=this._getContentSize(t);if(Math.abs(i)<.001)return 1;const r=Math.min(s/i,1),a=this._toOvershoot(this._scroll[e],t);return a===0?r:r/(1+Math.abs(a))}_getViewportSize(e){return this._getSize(e,this._viewportEntity)}_getContentSize(e){return this._getSize(e,this._contentEntity)}_getSize(e,t){return t?.element?t.element[this._getCalculatedDimension(e)]:0}_getScrollingEnabled(e){if(e===Me)return this.horizontal;if(e===rt)return this.vertical}_getScrollbarVisibility(e){if(e===Me)return this.horizontalScrollbarVisibility;if(e===rt)return this.verticalScrollbarVisibility}_getSign(e){return e===Me?1:-1}_getAxis(e){return e===Me?"x":"y"}_getCalculatedDimension(e){return e===Me?"calculatedWidth":"calculatedHeight"}_destroyDragHelper(){this._contentDragHelper&&this._contentDragHelper.destroy()}onUpdate(){this._contentEntity&&(this._updateVelocity(),this._syncScrollbarEnabledState(Me),this._syncScrollbarEnabledState(rt))}_updateVelocity(){if(!this._isDragging()){if(this.scrollMode===l0&&(this._hasOvershoot("x",Me)&&this._setVelocityFromOvershoot(this.scroll.x,"x",Me),this._hasOvershoot("y",rt)&&this._setVelocityFromOvershoot(this.scroll.y,"y",rt)),Math.abs(this._velocity.x)>1e-4||Math.abs(this._velocity.y)>1e-4){const e=this._contentEntity.getLocalPosition();e.x+=this._velocity.x,e.y+=this._velocity.y,this._contentEntity.setLocalPosition(e),this._setScrollFromContentPosition(e)}this._velocity.x*=1-this.friction,this._velocity.y*=1-this.friction}}_hasOvershoot(e,t){return Math.abs(this._toOvershoot(this.scroll[e],t))>.001}_toOvershoot(e,t){const s=this._getMaxScrollValue(t);return e<0?e:e>s?e-s:0}_setVelocityFromOvershoot(e,t,s){const r=this._toOvershoot(e,s)*this._getMaxOffset(s)*this._getSign(s);Math.abs(r)>0&&(this._velocity[t]=-r/(this.bounceAmount*50+1))}_setVelocityFromContentPositionDelta(e){this._prevContentDragPosition?(this._velocity.sub2(e,this._prevContentDragPosition),this._prevContentDragPosition.copy(e)):(this._velocity.set(0,0,0),this._prevContentDragPosition=e.clone())}_setScrollFromContentPosition(e){let t=this._contentPositionToScrollValue(e);this._isDragging()&&(t=this._applyScrollValueTension(t)),this._onSetScroll(t.x,t.y,!1)}_applyScrollValueTension(e){let s=this._getMaxScrollValue(Me),i=this._toOvershoot(e.x,Me);return i>0?e.x=s+1*Math.log10(1+i):i<0&&(e.x=-1*Math.log10(1-i)),s=this._getMaxScrollValue(rt),i=this._toOvershoot(e.y,rt),i>0?e.y=s+1*Math.log10(1+i):i<0&&(e.y=-1*Math.log10(1-i)),e}_isDragging(){return this._contentDragHelper&&this._contentDragHelper.isDragging}_setScrollbarComponentsEnabled(e){this._horizontalScrollbarEntity?.scrollbar&&(this._horizontalScrollbarEntity.scrollbar.enabled=e),this._verticalScrollbarEntity?.scrollbar&&(this._verticalScrollbarEntity.scrollbar.enabled=e)}_setContentDraggingEnabled(e){this._contentDragHelper&&(this._contentDragHelper.enabled=e)}_onMouseWheel(e){if(!this.useMouseWheel||!this._contentEntity?.element)return;const t=e.event,s=t.deltaX/this._contentEntity.element.calculatedWidth*this.mouseWheelSensitivity.x,i=t.deltaY/this._contentEntity.element.calculatedHeight*this.mouseWheelSensitivity.y,r=H.clamp(this._scroll.x+s,0,this._getMaxScrollValue(Me)),a=H.clamp(this._scroll.y+i,0,this._getMaxScrollValue(rt));
13428this.scroll=new j(r,a)}_enableContentInput(){for(;this._disabledContentInputEntities.length;){const e=this._disabledContentInputEntities.pop();e.element&&(e.element.useInput=!0)}this._disabledContentInput=!1}_disableContentInput(){const e=t=>{t.element&&t.element.useInput&&(this._disabledContentInputEntities.push(t),t.element.useInput=!1);const s=t.children;for(let i=0,r=s.length;i<r;i++)e(s[i])};if(this._contentEntity){const t=this._contentEntity.children;for(let s=0,i=t.length;s<i;s++)e(t[s])}this._disabledContentInput=!0}onEnable(){this._setScrollbarComponentsEnabled(!0),this._setContentDraggingEnabled(!0),this._syncAll()}onDisable(){this._setScrollbarComponentsEnabled(!1),this._setContentDraggingEnabled(!1)}onRemove(){this._evtElementAdd?.off(),this._evtElementAdd=null,this._evtElementRemove?.off(),this._evtElementRemove=null,this.viewportEntity=null,this.contentEntity=null,this.horizontalScrollbarEntity=null,this.verticalScrollbarEntity=null,this._toggleElementListeners("off"),this._destroyDragHelper()}resolveDuplicatedEntityReferenceProperties(e,t){e.viewportEntity&&(this.viewportEntity=t[e.viewportEntity.guid]),e.contentEntity&&(this.contentEntity=t[e.contentEntity.guid]),e.horizontalScrollbarEntity&&(this.horizontalScrollbarEntity=t[e.horizontalScrollbarEntity.guid]),e.verticalScrollbarEntity&&(this.verticalScrollbarEntity=t[e.verticalScrollbarEntity.guid])}}class Ez{enabled=!0}const b_=["enabled"],c0=["horizontal","vertical","scrollMode","bounceAmount","friction","dragThreshold","useMouseWheel","mouseWheelSensitivity","horizontalScrollbarVisibility","verticalScrollbarVisibility","viewportEntity","contentEntity","horizontalScrollbarEntity","verticalScrollbarEntity"];class bz extends Tt{constructor(e){super(e),this.id="scrollview",this.ComponentType=sC,this.DataType=Ez,this.schema=b_,this.on("beforeremove",this._onRemoveComponent,this),this.app.systems.on("update",this.onUpdate,this)}initializeComponentData(e,t,s){for(let i=0;i<c0.length;i++){const r=c0[i];t[r]!==void 0&&(e[r]=t[r])}super.initializeComponentData(e,t,b_)}cloneComponent(e,t){const s=e.scrollview;return this.addComponent(t,{enabled:s.enabled,horizontal:s.horizontal,vertical:s.vertical,scrollMode:s.scrollMode,bounceAmount:s.bounceAmount,friction:s.friction,dragThreshold:s.dragThreshold,useMouseWheel:s.useMouseWheel,mouseWheelSensitivity:s.mouseWheelSensitivity,horizontalScrollbarVisibility:s.horizontalScrollbarVisibility,verticalScrollbarVisibility:s.verticalScrollbarVisibility,viewportEntity:s.viewportEntity,contentEntity:s.contentEntity,horizontalScrollbarEntity:s.horizontalScrollbarEntity,verticalScrollbarEntity:s.verticalScrollbarEntity})}onUpdate(e){const t=this.store;for(const s in t){const i=t[s].entity,r=i.scrollview;r.enabled&&i.enabled&&r.onUpdate()}}_onRemoveComponent(e,t){t.onRemove()}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this)}}ye._buildAccessors(sC.prototype,b_);class iC extends ye{static EVENT_SETVALUE="set:value";_orientation=Me;_value=0;_handleSize=0;_handleEntity=null;_evtHandleEntityElementAdd=null;_evtHandleEntityChanges=[];_handleDragHelper=null;set orientation(e){this._orientation!==e&&(this._orientation=e,this._handleEntity?.element&&(this._handleEntity.element[this._getOppositeDimension()]=0,this._rebuildDragHelper(),this._updateHandlePositionAndSize()))}get orientation(){return this._orientation}set value(e){Math.abs(e-this._value)>1e-5&&(this._value=H.clamp(e,0,1),this._updateHandlePositionAndSize(),this.fire("set:value",this._value))}get value(){return this._value}set handleSize(e){Math.abs(e-this._handleSize)>1e-5&&(this._handleSize=H.clamp(e,0,1),this._updateHandlePositionAndSize())}get handleSize(){return this._handleSize}set handleEntity(e){let t;e instanceof He?t=e:typeof e=="string"?t=this.system.app.getEntityFromIndex(e)??null:t=null,this._handleEntity!==t&&(this._handleEntity&&this._handleEntityUnsubscribe(),this._handleEntity=t,t&&this._handleEntitySubscribe())}get handleEntity(){return this._handleEntity}_handleEntitySubscribe(){this._evtHandleEntityElementAdd=this._handleEntity.on("element:add",this._onHandleElementGain,this),this._handleEntity.element&&this._onHandleElementGain()}_handleEntityUnsubscribe(){this._evtHandleEntityElementAdd?.off(),this._evtHandleEntityElementAdd=null,this._handleEntity?.element&&this._onHandleElementLose()}_handleEntityElementSubscribe(){const e=this._handleEntity.element,t=this._evtHandleEntityChanges;t.push(e.once("beforeremove",this._onHandleElementLose,this)),t.push(e.on("set:anchor",this._updateHandlePositionAndSize,this)),t.push(e.on("set:margin",this._updateHandlePositionAndSize,this)),t.push(e.on("set:pivot",this._updateHandlePositionAndSize,this))}_handleEntityElementUnsubscribe(){for(let e=0;e<this._evtHandleEntityChanges.length;e++)this._evtHandleEntityChanges[e].off();this._evtHandleEntityChanges.length=0}_onHandleElementGain(){this._handleEntityElementSubscribe(),this._rebuildDragHelper(),this._updateHandlePositionAndSize()}_rebuildDragHelper(){this._destroyDragHelper(),this._handleDragHelper=new tC(this._handleEntity.element,this._getAxis()),this._handleDragHelper.enabled=this.enabled&&this.entity.enabled,this._handleDragHelper.on("drag:move",this._onHandleDrag,this)}_onHandleElementLose(){this._handleEntityElementUnsubscribe(),this._destroyDragHelper()}_onHandleDrag(e){this._handleEntity&&this.enabled&&this.entity.enabled&&(this.value=this._handlePositionToScrollValue(e[this._getAxis()]))}_updateHandlePositionAndSize(){const e=this._handleEntity;if(!e)return;const t=e.getLocalPosition();t[this._getAxis()]=this._getHandlePosition(),e.setLocalPosition(t),e.element&&(e.element[this._getDimension()]=this._getHandleLength())}_handlePositionToScrollValue(e){return e*this._getSign()/this._getUsableTrackLength()}
13428_scrollValueToHandlePosition(e){return e*this._getSign()*this._getUsableTrackLength()}_getUsableTrackLength(){return Math.max(this._getTrackLength()-this._getHandleLength(),.001)}_getTrackLength(){return this.entity.element?this._orientation===Me?this.entity.element.calculatedWidth:this.entity.element.calculatedHeight:0}_getHandleLength(){return this._getTrackLength()*this._handleSize}_getHandlePosition(){return this._scrollValueToHandlePosition(this._value)}_getSign(){return this._orientation===Me?1:-1}_getAxis(){return this._orientation===Me?"x":"y"}_getDimension(){return this._orientation===Me?"width":"height"}_getOppositeDimension(){return this._orientation===Me?"height":"width"}_destroyDragHelper(){this._handleDragHelper?.destroy(),this._handleDragHelper=null}onEnable(){this._handleDragHelper&&(this._handleDragHelper.enabled=!0)}onDisable(){this._handleDragHelper&&(this._handleDragHelper.enabled=!1)}onRemove(){this._destroyDragHelper()}resolveDuplicatedEntityReferenceProperties(e,t){e.handleEntity&&(this.handleEntity=t[e.handleEntity.guid])}}class Az{enabled=!0}const A_=["enabled"],h0=["orientation","value","handleSize","handleEntity"];class Pz extends Tt{constructor(e){super(e),this.id="scrollbar",this.ComponentType=iC,this.DataType=Az,this.schema=A_,this.on("add",this._onAddComponent,this),this.on("beforeremove",this._onRemoveComponent,this)}initializeComponentData(e,t,s){for(let i=0;i<h0.length;i++){const r=h0[i];t.hasOwnProperty(r)&&(e[r]=t[r])}super.initializeComponentData(e,t,A_)}cloneComponent(e,t){const s=e.scrollbar;return this.addComponent(t,{enabled:s.enabled,orientation:s.orientation,value:s.value,handleSize:s.handleSize,handleEntity:s.handleEntity})}_onAddComponent(e){e.fire("scrollbar:add")}_onRemoveComponent(e,t){t.onRemove()}}ye._buildAccessors(iC.prototype,A_);const Iz={volume:0,pitch:0,loop:!1,startTime:0,duration:0,position:new E,maxDistance:0,refDistance:0,rollOffFactor:0,distanceModel:0,onPlay:null,onPause:null,onResume:null,onStop:null,onEnd:null};class em extends ge{static EVENT_PLAY="play";static EVENT_PAUSE="pause";static EVENT_RESUME="resume";static EVENT_STOP="stop";static EVENT_END="end";static EVENT_LOAD="load";name;instances=[];constructor(e,t="Untitled",s={}){super(),this._component=e,this._assets=e.system.app.assets,this._manager=e.system.manager,this.name=t,this._volume=s.volume!==void 0?H.clamp(Number(s.volume)||0,0,1):1,this._pitch=s.pitch!==void 0?Math.max(.01,Number(s.pitch)||0):1,this._loop=!!(s.loop!==void 0&&s.loop),this._duration=s.duration>0?s.duration:null,this._startTime=Math.max(0,Number(s.startTime)||0),this._overlap=!!s.overlap,this._autoPlay=!!s.autoPlay,this._firstNode=null,this._lastNode=null,this._asset=s.asset,this._asset instanceof pe&&(this._asset=this._asset.id),this._onInstancePlayHandler=this._onInstancePlay.bind(this),this._onInstancePauseHandler=this._onInstancePause.bind(this),this._onInstanceResumeHandler=this._onInstanceResume.bind(this),this._onInstanceStopHandler=this._onInstanceStop.bind(this),this._onInstanceEndHandler=this._onInstanceEnd.bind(this)}play(){if(this.overlap||this.stop(),!this.isLoaded&&!this._hasAsset())return;const e=this._createInstance();if(this.instances.push(e),this.isLoaded)e.play();else{const t=function(s){const i=e._playWhenLoaded;e.sound=s,i&&e.play()};this.off("load",t),this.once("load",t),this.load()}return e}pause(){let e=!1;const t=this.instances;for(let s=0,i=t.length;s<i;s++)t[s].pause()&&(e=!0);return e}resume(){let e=!1;const t=this.instances;for(let s=0,i=t.length;s<i;s++)t[s].resume()&&(e=!0);return e}stop(){let e=!1;const t=this.instances;let s=t.length;for(;s--;)t[s].stop(),e=!0;return t.length=0,e}load(){if(!this._hasAsset())return;const e=this._assets.get(this._asset);if(!e){this._assets.off(`add:${this._asset}`,this._onAssetAdd,this),this._assets.once(`add:${this._asset}`,this._onAssetAdd,this);return}if(e.off("remove",this._onAssetRemoved,this),e.on("remove",this._onAssetRemoved,this),!e.resource){e.off("load",this._onAssetLoad,this),e.once("load",this._onAssetLoad,this),this._assets.load(e);return}this.fire("load",e.resource)}setExternalNodes(e,t){if(!e){console.error("The firstNode must have a valid AudioNode");return}if(t||(t=e),this._firstNode=e,this._lastNode=t,!this._overlap){const s=this.instances;for(let i=0,r=s.length;i<r;i++)s[i].setExternalNodes(e,t)}}clearExternalNodes(){if(this._firstNode=null,this._lastNode=null,!this._overlap){const e=this.instances;for(let t=0,s=e.length;t<s;t++)e[t].clearExternalNodes()}}getExternalNodes(){return[this._firstNode,this._lastNode]}_hasAsset(){return this._asset!=null}_createInstance(){let e=null;const t=this._component;let s=null;if(this._hasAsset()){const r=this._assets.get(this._asset);r&&(s=r.resource)}const i=Iz;return i.volume=this._volume*t.volume,i.pitch=this._pitch*t.pitch,i.loop=this._loop,i.startTime=this._startTime,i.duration=this._duration,i.onPlay=this._onInstancePlayHandler,i.onPause=this._onInstancePauseHandler,i.onResume=this._onInstanceResumeHandler,i.onStop=this._onInstanceStopHandler,i.onEnd=this._onInstanceEndHandler,t.positional?(i.position.copy(t.entity.getPosition()),i.maxDistance=t.maxDistance,i.refDistance=t.refDistance,i.rollOffFactor=t.rollOffFactor,i.distanceModel=t.distanceModel,e=new cI(this._manager,s,i)):e=new dT(this._manager,s,i),this._firstNode&&e.setExternalNodes(this._firstNode,this._lastNode),e}_onInstancePlay(e){this.fire("play",e),this._component.fire("play",this,e)}_onInstancePause(e){this.fire("pause",e),this._component.fire("pause",this,e)}_onInstanceResume(e){this.fire("resume",e),this._component.fire("resume",this,e)}_onInstanceStop(e){const t=this.instances.indexOf(e);t!==-1&&this.instances.splice(t,1),this.fire("stop",e),this._component.fire("stop",this,e)}_onInstanceEnd(e){const t=this.instances.indexOf(e);t!==-1&&this.instances.splice(t,1),this.fire("end",e),this._component.fire("end",this,e)}_onAssetAdd(e){this.load()}_onAssetLoad(e){this.load()}_onAssetRemoved(e){e.off("remove",this._onAssetRemoved,this),this._assets.off(`add:${e.id}`,this._onAssetAdd,this),this.stop()}updatePosition(e){const t=this.instances;for(let s=0,i=t.length;s<i;s++)t[s].position=e}set asset(e){const t=this._asset;if(t){this._assets.off(`add:${t}`,this._onAssetAdd,this);const s=this._assets.get(t);s&&s.off("remove",this._onAssetRemoved,this)}this._asset=e,this._asset instanceof pe&&(this._asset=this._asset.id),this._hasAsset()&&this._component.enabled&&this._component.entity.enabled&&this.load()}get asset(){return this._asset}set autoPlay(e){this._autoPlay=!!e}get autoPlay(){return this._autoPlay}set duration(e){if(this._duration=Math.max(0,Number(e)||0)||null,!this._overlap){const t=this.instances;for(let s=0,i=t.length;s<i;s++)t[s].duration=this._duration}}get duration(){let e=0;if(this._hasAsset()){const t=this._assets.get(this._asset);e=t?.resource?t.resource.duration:0}
13428return this._duration!=null?this._duration%(e||1):e}get isLoaded(){if(this._hasAsset()){const e=this._assets.get(this._asset);if(e)return!!e.resource}return!1}get isPaused(){const e=this.instances,t=e.length;if(t===0)return!1;for(let s=0;s<t;s++)if(!e[s].isPaused)return!1;return!0}get isPlaying(){const e=this.instances;for(let t=0,s=e.length;t<s;t++)if(e[t].isPlaying)return!0;return!1}get isStopped(){const e=this.instances;for(let t=0,s=e.length;t<s;t++)if(!e[t].isStopped)return!1;return!0}set loop(e){this._loop=!!e;const t=this.instances;for(let s=0,i=t.length;s<i;s++)t[s].loop=this._loop}get loop(){return this._loop}set overlap(e){this._overlap=!!e}get overlap(){return this._overlap}set pitch(e){if(this._pitch=Math.max(Number(e)||0,.01),!this._overlap){const t=this.instances;for(let s=0,i=t.length;s<i;s++)t[s].pitch=this.pitch*this._component.pitch}}get pitch(){return this._pitch}set startTime(e){if(this._startTime=Math.max(0,Number(e)||0),!this._overlap){const t=this.instances;for(let s=0,i=t.length;s<i;s++)t[s].startTime=this._startTime}}get startTime(){return this._startTime}set volume(e){if(this._volume=H.clamp(Number(e)||0,0,1),!this._overlap){const t=this.instances;for(let s=0,i=t.length;s<i;s++)t[s].volume=this._volume*this._component.volume}}get volume(){return this._volume}}class rC extends ye{static EVENT_PLAY="play";static EVENT_PAUSE="pause";static EVENT_RESUME="resume";static EVENT_STOP="stop";static EVENT_END="end";_volume=1;_pitch=1;_positional=!0;_refDistance=1;_maxDistance=1e4;_rollOffFactor=1;_distanceModel=jm;_slots={};_playingBeforeDisable={};_updateSoundInstances(e,t,s){const i=this._slots;for(const r in i){const a=i[r];if(!a.overlap){const n=a.instances;for(let o=0,c=n.length;o<c;o++)n[o][e]=s?a[e]*t:t}}}set distanceModel(e){this._distanceModel=e,this._updateSoundInstances("distanceModel",e,!1)}get distanceModel(){return this._distanceModel}set maxDistance(e){this._maxDistance=e,this._updateSoundInstances("maxDistance",e,!1)}get maxDistance(){return this._maxDistance}set refDistance(e){this._refDistance=e,this._updateSoundInstances("refDistance",e,!1)}get refDistance(){return this._refDistance}set rollOffFactor(e){this._rollOffFactor=e,this._updateSoundInstances("rollOffFactor",e,!1)}get rollOffFactor(){return this._rollOffFactor}set pitch(e){this._pitch=e,this._updateSoundInstances("pitch",e,!0)}get pitch(){return this._pitch}set volume(e){this._volume=e,this._updateSoundInstances("volume",e,!0)}get volume(){return this._volume}set positional(e){this._positional=e;const t=this._slots;for(const s in t){const i=t[s];if(!i.overlap){const r=i.instances,a=r.length;for(let n=a-1;n>=0;n--){const o=r[n].isPlaying||r[n].isSuspended,c=r[n].currentTime;o&&r[n].stop();const h=i._createInstance();o&&(h.play(),h.currentTime=c),r.push(h)}}}}get positional(){return this._positional}set slots(e){const t=this._slots;if(t)for(const i in t)t[i].stop();const s={};for(const i in e)e[i]instanceof em?s[e[i].name]=e[i]:e[i].name&&(s[e[i].name]=new em(this,e[i].name,e[i]));this._slots=s,this.enabled&&this.entity.enabled&&this.onEnable()}get slots(){return this._slots}onEnable(){if(this.system._inTools)return;const e=this._slots,t=this._playingBeforeDisable;for(const s in e){const i=e[s];i.autoPlay&&i.isStopped?i.play():t[s]?i.resume():i.isLoaded||i.load()}}onDisable(){const e=this._slots,t={};for(const s in e)e[s].overlap||e[s].isPlaying&&(e[s].pause(),t[s]=!0);this._playingBeforeDisable=t}onRemove(){this.off()}addSlot(e,t){const s=this._slots;if(s[e])return null;const i=new em(this,e,t);return s[e]=i,i.autoPlay&&this.enabled&&this.entity.enabled&&i.play(),i}removeSlot(e){const t=this._slots;t[e]&&(t[e].stop(),delete t[e])}slot(e){return this._slots[e]}_getSlotProperty(e,t){if(!this.enabled||!this.entity.enabled)return;const s=this._slots[e];if(s)return s[t]}isPlaying(e){return this._getSlotProperty(e,"isPlaying")||!1}isLoaded(e){return this._getSlotProperty(e,"isLoaded")||!1}isPaused(e){return this._getSlotProperty(e,"isPaused")||!1}isStopped(e){return this._getSlotProperty(e,"isStopped")||!1}play(e){if(!this.enabled||!this.entity.enabled)return null;const t=this._slots[e];return t?t.play():null}pause(e){const t=this._slots;if(e){const s=t[e];if(!s)return;s.pause()}else for(const s in t)t[s].pause()}resume(e){const t=this._slots;if(e){const s=t[e];if(!s)return;s.isPaused&&s.resume()}else for(const s in t)t[s].resume()}stop(e){const t=this._slots;if(e){const s=t[e];if(!s)return;s.stop()}else for(const s in t)t[s].stop()}}class Dz{enabled=!0}const aC=["enabled"];class Mz extends Tt{constructor(e){super(e),this.id="sound",this.ComponentType=rC,this.DataType=Dz,this.schema=aC,this.manager=e.soundManager,this.app.systems.on("update",this.onUpdate,this),this.on("beforeremove",this.onBeforeRemove,this)}set volume(e){this.manager.volume=e}get volume(){return this.manager.volume}get context(){return this.manager.context}initializeComponentData(e,t,s){s=["volume","pitch","positional","refDistance","maxDistance","rollOffFactor","distanceModel","slots"];for(let i=0;i<s.length;i++)t.hasOwnProperty(s[i])&&(e[s[i]]=t[s[i]]);super.initializeComponentData(e,t,["enabled"])}cloneComponent(e,t){const s=e.sound,i=s.slots,r={};for(const n in i){const o=i[n];r[n]={name:o.name,volume:o.volume,pitch:o.pitch,loop:o.loop,duration:o.duration,startTime:o.startTime,overlap:o.overlap,autoPlay:o.autoPlay,asset:o.asset}}const a={distanceModel:s.distanceModel,enabled:s.enabled,maxDistance:s.maxDistance,pitch:s.pitch,positional:s.positional,refDistance:s.refDistance,rollOffFactor:s.rollOffFactor,slots:r,volume:s.volume};return this.addComponent(t,a)}onUpdate(e){const t=this.store;for(const s in t)if(t.hasOwnProperty(s)){const r=t[s].entity;if(r.enabled){const a=r.sound;if(a.enabled&&a.positional){const n=r.getPosition(),o=a.slots;for(const c in o)o[c].updatePosition(n)}}}}onBeforeRemove(e,t){const s=t.slots;for(const i in s)s[i].overlap||s[i].stop();t.onRemove()}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this)}}ye._buildAccessors(rC.prototype,aC);const d0="simple",u0="animated";class tm extends ge{static EVENT_PLAY="play";static EVENT_PAUSE="pause";static EVENT_RESUME="resume";static EVENT_STOP="stop";static EVENT_END="end";static EVENT_LOOP="loop";_evtSetMeshes=null;_component;_frame=0;_sprite=null;_spriteAsset=null;_playing=!1;_paused=!1;_time=0;name;fps=0;loop=!1;constructor(e,t){super(),this._component=e,this.fps=t.fps||0,this.loop=t.loop||!1,this.name=t.name,this.spriteAsset=t.spriteAsset}get duration(){if(this._sprite){const e=this.fps||Number.MIN_VALUE;return this._sprite.frameKeys.length/Math.abs(e)}return 0}
13428set frame(e){this._setFrame(e);const t=this.fps||Number.MIN_VALUE;this._setTime(this._frame/t)}get frame(){return this._frame}get isPaused(){return this._paused}get isPlaying(){return this._playing}set sprite(e){if(this._sprite&&(this._evtSetMeshes?.off(),this._evtSetMeshes=null,this._sprite.off("set:pixelsPerUnit",this._onSpritePpuChanged,this),this._sprite.off("set:atlas",this._onSpriteMeshesChange,this),this._sprite.atlas&&this._sprite.atlas.off("set:texture",this._onSpriteMeshesChange,this)),this._sprite=e,this._sprite&&(this._evtSetMeshes=this._sprite.on("set:meshes",this._onSpriteMeshesChange,this),this._sprite.on("set:pixelsPerUnit",this._onSpritePpuChanged,this),this._sprite.on("set:atlas",this._onSpriteMeshesChange,this),this._sprite.atlas&&this._sprite.atlas.on("set:texture",this._onSpriteMeshesChange,this)),this._component.currentClip===this){let t;!e||!e.atlas?(t=this._component._meshInstance,t&&(t.deleteParameter("texture_emissiveMap"),t.deleteParameter("texture_opacityMap")),this._component.removeFromLayers()):(e.atlas.texture&&(t=this._component._meshInstance,t&&(t.setParameter("texture_emissiveMap",e.atlas.texture),t.setParameter("texture_opacityMap",e.atlas.texture)),this._component.enabled&&this._component.entity.enabled&&this._component.addToLayers()),this.time&&this.fps?this.time=this.time:this.frame=this.frame)}}get sprite(){return this._sprite}
13428set spriteAsset(e){const t=this._component.system.app.assets;let s=e;if(e instanceof pe&&(s=e.id),this._spriteAsset!==s){if(this._spriteAsset){const i=t.get(this._spriteAsset);i&&this._unbindSpriteAsset(i)}if(this._spriteAsset=s,this._spriteAsset){const i=t.get(this._spriteAsset);i?this._bindSpriteAsset(i):(this.sprite=null,t.on(`add:${this._spriteAsset}`,this._onSpriteAssetAdded,this))}else this.sprite=null}}get spriteAsset(){return this._spriteAsset}set time(e){this._setTime(e),this._sprite?this.frame=Math.min(this._sprite.frameKeys.length-1,Math.floor(this._time*Math.abs(this.fps))):this.frame=0}get time(){return this._time}_onSpriteAssetAdded(e){this._component.system.app.assets.off(`add:${e.id}`,this._onSpriteAssetAdded,this),this._spriteAsset===e.id&&this._bindSpriteAsset(e)}_bindSpriteAsset(e){e.on("load",this._onSpriteAssetLoad,this),e.on("remove",this._onSpriteAssetRemove,this),e.resource?this._onSpriteAssetLoad(e):this._component.system.app.assets.load(e)}_unbindSpriteAsset(e){e&&(e.off("load",this._onSpriteAssetLoad,this),e.off("remove",this._onSpriteAssetRemove,this),e.resource&&!e.resource.atlas&&this._component.system.a
13428pp.assets.off(`load:${e.data.textureAtlasAsset}`,this._onTextureAtlasLoad,this))}_onSpriteAssetLoad(e){if(!e.resource)this.sprite=null;else if(e.resource.atlas)this.sprite=e.resource;else{const t=e.data.textureAtlasAsset,s=this._component.system.app.assets;s.off(`load:${t}`,this._onTextureAtlasLoad,this),s.once(`load:${t}`,this._onTextureAtlasLoad,this)}}_onTextureAtlasLoad(e){const t=this._spriteAsset;t instanceof pe?this._onSpriteAssetLoad(t):this._onSpriteAssetLoad(this._component.system.app.assets.get(t))}_onSpriteAssetRemove(e){this.sprite=null}_onSpriteMeshesChange(){this._component.currentClip===this&&this._component._showFrame(this.frame)}_onSpritePpuChanged(){this._component.currentClip===this&&this.sprite.renderMode!==Fi&&this._component._showFrame(this.frame)}_update(e){if(this.fps===0||!this._playing||this._paused||!this._sprite)return;const t=this.fps<0?-1:1,s=this._time+e*this._component.speed*t,i=this.duration,r=s>i||s<0;this._setTime(s);let a=this.frame;this._sprite?a=Math.floor(this._sprite.frameKeys.length*this._time/i):a=0,a!==this._frame&&this._setFrame(a),r&&(this.loop?(this.fire("loop"),this._component.fire("loop",this)):(this._playing=!1,this._paused=!1,this.fire("end"),this._component.fire("end",this)))}_setTime(e){this._time=e;const t=this.duration;this._time<0?this.loop?this._time=this._time%t+t:this._time=0:this._time>t&&(this.loop?this._time%=t:this._time=t)}_setFrame(e){this._sprite?this._frame=H.clamp(e,0,this._sprite.frameKeys.length-1):this._frame=e,this._component.currentClip===this&&this._component._showFrame(this._frame)}_destroy(){if(this._spriteAsset){const e=this._component.system.a
13428pp.assets;this._unbindSpriteAsset(e.get(this._spriteAsset))}this._sprite&&(this.sprite=null),this._spriteAsset&&(this.spriteAsset=null)}play(){this._playing||(this._playing=!0,this._paused=!1,this.frame=0,this.fire("play"),this._component.fire("play",this))}pause(){!this._playing||this._paused||(this._paused=!0,this.fire("pause"),this._component.fire("pause",this))}resume(){this._paused&&(this._paused=!1,this.fire("resume"),this._component.fire("resume",this))}stop(){this._playing&&(this._playing=!1,this._paused=!1,this._time=0,this.frame=0,this.fire("stop"),this._component.fire("stop",this))}}const f0="texture_emissiveMap",p0="texture_opacityMap",m0="material_emissive",_0="material_opacity",Rz="innerOffset",Lz="outerScale",Fz="atlasRect";class nC extends ye{static EVENT_PLAY="play";static EVENT_PAUSE="pause";static EVENT_RESUME="resume";static EVENT_STOP="stop";static EVENT_END="end";static EVENT_LOOP="loop";_evtLayersChanged=null;_evtLayerAdded=null;_evtLayerRemoved=null;_type=d0;_material=null;_color=new Q(1,1,1,1);_colorUniform=new Float32Array(3);_speed=1;_flipX=!1;_flipY=!1;_width=1;_height=1;_drawOrder=0;_layers=[Ir];_outerScale=new j(1,1);_outerScaleUniform=new Float32Array(2);_innerOffset=new ie;_innerOffsetUniform=new Float32Array(4);_atlasRect=new ie;_atlasRectUniform=new Float32Array(4);_batchGroupId=-1;_node=new He;_meshInstance=null;_updateAabbFunc=null;_inLayers=!1;_autoPlayClip=null;_clips={};_defaultClip=null;_currentClip=null;constructor(e,t){super(e,t),this._material=e.defaultMaterial,t.addChild(this._node),this._updateAabbFunc=this._updateAabb.bind(this),this._defaultClip=new tm(this,{name:this.entity.name,fps:0,loop:!1,spriteAsset:null}),this._currentClip=this._defaultClip}set type(e){this._type!==e&&(this._type=e,this._type===d0?(this.stop(),this._currentClip=this._defaultClip,this.enabled&&this.entity.enabled&&(this._currentClip.frame=this.frame,this._currentClip.sprite?this.addToLayers():this.removeFromLayers())):this._type===u0&&(this.stop(),this._autoPlayClip&&this._tryAutoPlay(),this._currentClip&&this._currentClip.isPlaying&&this.enabled&&this.entity.enabled?this.addToLayers():this.removeFromLayers()))}get type(){return this._type}set frame(e){this._currentClip.frame=e}get frame(){return this._currentClip.frame}set spriteAsset(e){this._defaultClip.spriteAsset=e}get spriteAsset(){return this._defaultClip._spriteAsset}set sprite(e){this._currentClip.sprite=e}get sprite(){return this._currentClip.sprite}set material(e){this._material=e,this._meshInstance&&(this._meshInstance.material=e)}get material(){return this._material}set color(e){this._color.r=e.r,this._color.g=e.g,this._color.b=e.b,this._meshInstance&&(this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._meshInstance.setParameter(m0,this._colorUniform))}get color(){return this._color}set opacity(e){this._color.a=e,this._meshInstance&&this._meshInstance.setParameter(_0,e)}get opacity(){return this._color.a}set clips(e){if(!e){for(const t in this._clips)this.removeClip(t);return}for(const t in this._clips){let s=!1;for(const i in e)if(e[i].name===t){s=!0,this._clips[t].fps=e[i].fps,this._clips[t].loop=e[i].loop,e[i].hasOwnProperty("sprite")?this._clips[t].sprite=e[i].sprite:e[i].hasOwnProperty("spriteAsset")&&(this._clips[t].spriteAsset=e[i].spriteAsset);break}s||this.removeClip(t)}for(const t in e)this._clips[e[t].name]||this.addClip(e[t]);this._autoPlayClip&&this._tryAutoPlay(),(!this._currentClip||!this._currentClip.sprite)&&this.removeFromLayers()}get clips(){return this._clips}get currentClip(){return this._currentClip}set speed(e){this._speed=e}get speed(){return this._speed}set flipX(e){this._flipX!==e&&(this._flipX=e,this._updateTransform())}get flipX(){return this._flipX}set flipY(e){this._flipY!==e&&(this._flipY=e,this._updateTransform())}get flipY(){return this._flipY}set width(e){e!==this._width&&(this._width=e,this._outerScale.x=this._width,this.sprite&&(this.sprite.renderMode===Ut||this.sprite.renderMode===kt)&&this._updateTransform())}get width(){return this._width}set height(e){e!==this._height&&(this._height=e,this._outerScale.y=this.height,this.sprite&&(this.sprite.renderMode===Ut||this.sprite.renderMode===kt)&&this._updateTransform())}get height(){return this._height}set batchGroupId(e){if(this._batchGroupId===e)return;const t=this._batchGroupId;this._batchGroupId=e,this.entity.enabled&&t>
13428=0&&this.system.app.batcher?.remove(Zt.SPRITE,t,this.entity),this.entity.enabled&&e>=0?this.system.app.batcher?.insert(Zt.SPRITE,e,this.entity):t>=0&&this._currentClip&&this._currentClip.sprite&&this.enabled&&this.entity.enabled&&this.addToLayers()}get batchGroupId(){return this._batchGroupId}set autoPlayClip(e){this._autoPlayClip=e instanceof tm?e.name:e,this._tryAutoPlay()}get autoPlayClip(){return this._autoPlayClip}set drawOrder(e){this._drawOrder=e,this._meshInstance&&(this._meshInstance.drawOrder=e)}get drawOrder(){return this._drawOrder}set layers(e){this._inLayers&&this.removeFromLayers(),this._layers=e,this._meshInstance&&this.enabled&&this.entity.enabled&&this.addToLayers()}get layers(){return this._layers}get aabb(){return this._meshInstance?this._meshInstance.aabb:null}onEnable(){const e=this.system.app,t=e.scene,s=t.layers;this._evtLayersChanged=t.on("set:layers",this._onLayersChanged,this),s&&(this._evtLayerAdded=s.on("add",this._onLayerAdded,this),this._evtLayerRemoved=s.on("remove",this._onLayerRemoved,this)),this.addToLayers(),this._autoPlayClip&&this._tryAutoPlay(),this._batchGroupId>=0&&e.batcher?.insert(Zt.SPRITE,this._batchGroupId,this.entity)}onDisable(){const e=this.system.app,s=e.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,s&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this.stop(),this.removeFromLayers(),this._batchGroupId>=0&&e.batcher?.remove(Zt.SPRITE,this._batchGroupId,this.entity)}onDestroy(){this._currentClip=null,this._defaultClip&&(this._defaultClip._destroy(),this._defaultClip=null);for(const e in this._clips)this._clips[e]._destroy();this._clips=null,this.removeFromLayers(),this._node?.remove(),this._node=null,this._meshInstance&&(this._meshInstance.material=null,this._meshInstance.mesh=null,this._meshInstance=null)}addToLayers(){if(this._inLayers||!this._meshInstance)return;const e=[this._meshInstance];for(let t=0,s=this._layers.length;t<s;t++){const i=this.system.app.scene.layers.getLayerById(this._layers[t]);i&&i.addMeshInstances(e)}this._inLayers=!0}removeFromLayers(){if(!this._inLayers||!this._meshInstance)return;const e=[this._meshInstance];for(let t=0,s=this._layers.length;t<s;t++){const i=this.system.app.scene.layers.getLayerById(this._layers[t]);i&&i.removeMeshInstances(e)}this._inLayers=!1}_showFrame(e){if(!this.sprite)return;const t=this.sprite.meshes[e];if(!t){this._meshInstance&&(this._meshInstance.mesh=null,this._meshInstance.visible=!1);return}let s;if(this.sprite.renderMode===kt?s=this.system.default9SlicedMaterialSlicedMode:this.sprite.renderMode===Ut?s=this.system.default9SlicedMaterialTiledMode:s=this.system.defaultMaterial,this._meshInstance||(this._meshInstance=new Ne(t,this._material,this._node),this._meshInstance.castShadow=!1,this._meshInstance.receiveShadow=!1,this._meshInstance.drawOrder=this._drawOrder,this._colorUniform[0]=this._color.r,this._colorUniform[1]=this._color.g,this._colorUniform[2]=this._color.b,this._meshInstance.setParameter(m0,this._colorUniform),this._meshInstance.setParameter(_0,this._color.a),this.enabled&&this.entity.enabled&&this.addToLayers()),this._meshInstance.material!==s&&(this._meshInstance.material=s),this._meshInstance.mesh!==t&&(this._meshInstance.mesh=t,this._meshInstance.visible=!0,this._meshInstance._aabbVer=-1),this.sprite.atlas&&this.sprite.atlas.texture?(this._meshInstance.setParameter(f0,this.sprite.atlas.texture),this._meshInstance.setParameter(p0,this.sprite.atlas.texture)):(this._meshInstance.deleteParameter(f0),this._meshInstance.deleteParameter(p0)),this.sprite.atlas&&(this.sprite.renderMode===kt||this.sprite.renderMode===Ut)){this._meshInstance._updateAabbFunc=this._updateAabbFunc;const i=this.sprite.atlas.frames[this.sprite.frameKeys[e]];if(i){const r=2/i.rect.z,a=2/i.rect.w;this._innerOffset.set(i.border.x*r,i.border.y*a,i.border.z*r,i.border.w*a);const n=this.sprite.atlas.texture;this._atlasRect.set(i.rect.x/n.width,i.rect.y/n.height,i.rect.z/n.width,i.rect.w/n.height)}else this._innerOffset.set(0,0,0,0);this._innerOffsetUniform[0]=this._innerOffset.x,this._innerOffsetUniform[1]=this._innerOffset.y,this._innerOffsetUniform[2]=this._innerOffset.z,this._innerOffsetUniform[3]=this._innerOffset.w,this._meshInstance.setParameter(Rz,this._innerOffsetUniform),this._atlasRectUniform[0]=this._atlasRect.x,this._atlasRectUniform[1]=this._atlasRect.y,this._atlasRectUniform[2]=this._atlasRect.z,this._atlasRectUniform[3]=this._atlasRect.w,this._meshInstance.setParameter(Fz,this._atlasRectUniform)}else this._meshInstance._updateAabbFunc=null;this._updateTransform()}_updateTransform(){let e=this.flipX?-1:1,t=this.flipY?-1:1,s=0,i=0;if(this.sprite&&(this.sprite.renderMode===kt||this.sprite.renderMode===Ut)){let r=1,a=1;if(this.sprite.atlas){const c=this.sprite.atlas.frames[this.sprite.frameKeys[this.frame]];c&&(r=c.rect.z,a=c.rect.w,s=(.5-c.pivot.x)*this._width,i=(.5-c.pivot.y)*this._height)}const n=r/this.sprite.pixelsPerUnit,o=a/this.sprite.pixelsPerUnit;this._outerScale.set(Math.max(this._width,this._innerOffset.x*n),Math.max(this._height,this._innerOffset.y*o)),e*=n,t*=o,this._outerScale.x/=n,this._outerScale.y/=o,e*=H.clamp(this._width/(this._innerOffset.x*n),1e-4,1),t*=H.clamp(this._height/(this._innerOffset.y*o),1e-4,1),this._meshInstance&&(this._outerScaleUniform[0]=this._outerScale.x,this._outerScaleUniform[1]=this._outerScale.y,this._meshInstance.setParameter(Lz,this._outerScaleUniform))}this._node.setLocalScale(e,t,1),this._node.setLocalPosition(s,i,0)}_updateAabb(e){return e.center.set(0,0,0),e.halfExtents.set(this._outerScale.x*.5,this._outerScale.y*.5,.001),e.setFromTransformedAabb(e,this._node.getWorldTransform()),e}_tryAutoPlay(){if(!this._autoPlayClip||this.type!==u0)return;const e=this._clips[this._autoPlayClip];e&&!e.isPlaying&&(!this._currentClip||!this._currentClip.isPlaying)&&this.enabled&&this.entity.enabled&&this.play(e.name)}_onLayersChanged(e,t){e.off("add",this._onLayerAdded,this),e.off("remove",this._onLayerRemoved,this),t.on("add",this._onLayerAdded,this),t.on("remove",this._onLayerRemoved,this),this.enabled&&this.entity.enabled&&this.addToLayers()}_onLayerAdded(e){this.layers.indexOf(e.id)<0||this._inLayers&&this.enabled&&this.entity.enabled&&this._meshInstance&&e.addMeshInstances([this._meshInstance])}_onLayerRemoved(e){!this._meshInstance||this.layers.indexOf(e.id)<0||e.removeMeshInstances([this._meshInstance])}addClip(e){const t=new tm(this,{name:e.name,fps:e.fps,loop:e.loop,spriteAsset:e.spriteAsset});return this._clips[e.name]=t,t.name&&t.name===this._autoPlayClip&&this._tryAutoPlay(),t}removeClip(e){delete this._clips[e]}clip(e){return this._clips[e]}play(e){const t=this._clips[e],s=this._currentClip;return s&&s!==t&&(s._playing=!1),this._currentClip=t,this._currentClip&&(this._currentClip=t,this._currentClip.play()),t}pause(){this._currentClip!==this._defaultClip&&this._currentClip.isPlaying&&this._currentClip.pause()}resume(){this._currentClip!==this._defaultClip&&this._currentClip.isPaused&&this._currentClip.resume()}stop(){this._currentClip!==this._defaultClip&&this._currentClip.stop()}}class Oz{enabled=!0}const oC=["enabled"];class Bz extends Tt{constructor(e){super(e),this.id="sprite",this.ComponentType=nC,this.DataType=Oz,this.schema=oC,this._defaultTexture=null,this._defaultMaterial=null,this._default9SlicedMaterialSlicedMode=null,this._default9SlicedMaterialTiledMode=null,this.app.systems.on("update",this.onUpdate,this),this.on("beforeremove",this.onBeforeRemove,this)}set defaultMaterial(e){this._defaultMaterial=e}get defaultMaterial(){if(!this._defaultMaterial){const e=new ce(this.app.graphicsDevice,{width:1,height:1,format:us,name:"sprite"}),t=new Uint8Array(e.lock());t[0]=t[1]=t[2]=t[3]=255,e.unlock();const s=new Es;s.diffuse.set(0,0,0),s.emissive.set(1,1,1),s.emissiveMap=e,s.opacityMap=e,s.opacityMapChannel="a",s.useLighting=!1,s.useTonemap=!1,s.useFog=!1,s.use
13428Skybox=!1,s.blendType=Ui,s.depthWrite=!1,s.pixelSnap=!1,s.cull=Yt,s.update(),this._defaultTexture=e,this._defaultMaterial=s}return this._defaultMaterial}set default9SlicedMaterialSlicedMode(e){this._default9SlicedMaterialSlicedMode=e}get default9SlicedMaterialSlicedMode(){if(!this._default9SlicedMaterialSlicedMode){const e=this.defaultMaterial.clone();e.nineSlicedMode=kt,e.update(),this._default9SlicedMaterialSlicedMode=e}return this._default9SlicedMaterialSlicedMode}set default9SlicedMaterialTiledMode(e){this._default9SlicedMaterialTiledMode=e}get default9SlicedMaterialTiledMode(){if(!this._default9SlicedMaterialTiledMode){const e=this.defaultMaterial.clone();e.nineSlicedMode=Ut,e.update(),this._default9SlicedMaterialTiledMode=e}return this._default9SlicedMaterialTiledMode}destroy(){super.destroy(),this.app.systems.off("update",this.onUpdate,this),this._defaultTexture&&(this._defaultTexture.destroy(),this._defaultTexture=null)}initializeComponentData(e,t,s){if(t.enabled!==void 0&&(e.enabled=t.enabled),e.type=t.type,t.layers&&Array.isArray(t.layers)&&(e.layers=t.layers.slice(0)),t.drawOrder!==void 0&&(e.drawOrder=t.drawOrder),t.color!==void 0&&(t.color instanceof Q?e.color.set(t.color.r,t.color.g,t.color.b,t.opacity??1):e.color.set(t.color[0],t.color[1],t.color[2],t.opacity??1),e.color=e.color),t.opacity!==void 0&&(e.opacity=t.opacity),t.flipX!==void 0&&(e.flipX=t.flipX),t.flipY!==void 0&&(e.flipY=t.flipY),t.width!==void 0&&(e.width=t.width),t.height!==void 0&&(e.height=t.height),t.spriteAsset!==void 0&&(e.spriteAsset=t.spriteAsset),t.sprite&&(e.sprite=t.sprite),t.frame!==void 0&&(e.frame=t.frame),t.clips)for(const i in t.clips)e.addClip(t.clips[i]);t.speed!==void 0&&(e.speed=t.speed),t.autoPlayClip&&(e.autoPlayClip=t.autoPlayClip),e.batchGroupId=t.batchGroupId===void 0||t.batchGroupId===null?-1:t.batchGroupId,super.initializeComponentData(e,t,s)}cloneComponent(e,t){const s=e.sprite;return this.addComponent(t,{enabled:s.enabled,type:s.type,spriteAsset:s.spriteAsset,sprite:s.sprite,width:s.width,height:s.height,frame:s.frame,color:s.color.clone(),opacity:s.opacity,flipX:s.flipX,flipY:s.flipY,speed:s.speed,clips:s.clips,autoPlayClip:s.autoPlayClip,batchGroupId:s.batchGroupId,drawOrder:s.drawOrder,layers:s.layers.slice(0)})}onUpdate(e){const t=this.store;for(const s in t)if(t.hasOwnProperty(s)){const i=t[s];if(i.data.enabled&&i.entity.enabled){const r=i.entity.sprite;r._currentClip&&r._currentClip._update(e)}}}onBeforeRemove(e,t){t.onDestroy()}}ye._buildAccessors(nC.prototype,oC);class lC extends ye{static EVENT_ENABLE="enable";static EVENT_DISABLE="disable";static EVENT_STATE="state";static EVENT_REMOVE="remove";_oldState=!0;_size=new E;constructor(e,t){super(e,t),this.on("set_enabled",this._onSetEnabled,this)}set size(e){e instanceof E?this._size.copy(e):e instanceof Array&&e.length>=3&&this.size.set(e[0],e[1],e[2])}get size(){return this._size}onEnable(){this._checkState()}onDisable(){this._checkState()}_onSetEnabled(e,t,s){this._checkState()}_checkState(){const e=this.enabled&&this.entity.enabled;e!==this._oldState&&(this._oldState=e,this.fire("enable"),this.fire("state",this.enabled))}_onBeforeRemove(){this.fire("remove")}}class Nz{enabled=!0}const cC=["enabled"];class kz extends Tt{constructor(e){super(e),this.id="zone",this.ComponentType=lC,this.DataType=Nz,this.schema=cC,this.on("beforeremove",this._onBeforeRemove,this)}initializeComponentData(e,t,s){e.enabled=t.hasOwnProperty("enabled")?!!t.enabled:!0,t.size&&(t.size instanceof E?e.size.copy(t.size):t.size instanceof Array&&t.size.length>=3&&e.size.set(t.size[0],t.size[1],t.size[2]))}cloneComponent(e,t){const s={enabled:e.zone.enabled,size:e.zone.size};return this.addComponent(t,s)}_onBeforeRemove(e,t){t._onBeforeRemove()}}ye._buildAccessors(lC.prototype,cC);class Uz{constructor(e,t){this.effect=e,this.inputTarget=t,this.outputTarget=null,this.name=e.constructor.name}}class zz{constructor(e,t){this.app=e,this.camera=t,this.destinationRenderTarget=null,this.effects=[],this.enabled=!1,this.depthTarget=null,t.on("set:rect",this.onCameraRectChanged,this)}_allocateColorBuffer(e,t){const s=this.camera.rect,i=this.destinationRenderTarget,r=this.app.graphicsDevice,a=Math.floor(s.z*(i?.width??r.width)),n=Math.floor(s.w*(i?.height??r.height));return ce.createDataTexture2D(r,t,a,n,e)}_createOffscreenTarget(e,t){const s=this.app.graphicsDevice,r=(this.destinationRenderTarget??s.backBuffer).isColorBufferSrgb(0),a=(t&&s.getRenderableHdrFormat([Ge,mt],!0))??(r?us:Re),n=`${this.camera.entity.name}-posteffect-${this.effects.length}`,o=this._allocateColorBuffer(a,n);return new St({colorBuffer:o,depth:e,stencil:e&&this.app.graphicsDevice.supportsStencil,samples:e?s.samples:1})}_resizeOffscreenTarget(e){const t=e.colorBuffer.format,s=e.colorBuffer.name;e.destroyFrameBuffers(),e.destroyTextureBuffers(),e._colorBuffer=this._allocateColorBuffer(t,s),e._colorBuffers=[e._colorBuffer],e.evaluateDimensions()}
13428_destroyOffscreenTarget(e){e.destroyTextureBuffers(),e.destroy()}addEffect(e){const t=this.effects,s=t.length===0,i=this._createOffscreenTarget(s,e.hdr),r=new Uz(e,i);t.push(r),this._sourceTarget=r.inputTarget,t.length>1&&(t[t.length-2].outputTarget=r.inputTarget),this._newPostEffect=e,e.needsDepthBuffer&&this._requestDepthMap(),this.enable(),this._newPostEffect=void 0}removeEffect(e){let t=-1;for(let s=0,i=this.effects.length;s<i;s++)if(this.effects[s].effect===e){t=s;break}t>=0&&(t>0?this.effects[t-1].outputTarget=t+1<this.effects.length?this.effects[t+1].inputTarget:null:this.effects.length>1&&(this.effects[1].inputTarget._depth||(this._destroyOffscreenTarget(this.effects[1].inputTarget),this.effects[1].inputTarget=this._createOffscreenTarget(!0,this.effects[1].hdr),this._sourceTarget=this.effects[1].inputTarget),this.camera.renderTarget=this.effects[1].inputTarget),this._destroyOffscreenTarget(this.effects[t].inputTarget),this.effects.splice(t,1)),this.enabled&&e.needsDepthBuffer&&this._releaseDepthMap(),this.effects.length===0&&this.disable()}_requestDepthMaps(){for(let e=0,t=this.effects.length;e<t;e++){const s=this.effects[e].effect;this._newPostEffect!==s&&s.needsDepthBuffer&&this._requestDepthMap()}}_releaseDepthMaps(){for(let e=0,t=this.effects.length;e<t;e++)this.effects[e].effect.needsDepthBuffer&&this._releaseDepthMap()}_requestDepthMap(){const e=this.app.scene.layers.getLayerById(ks);e&&(e.incrementCounter(),this.camera.requestSceneDepthMap(!0))}_releaseDepthMap(){const e=this.app.scene.layers.getLayerById(ks);e&&(e.decrementCounter(),this.camera.requestSceneDepthMap(!1))}destroy(){for(let e=0,t=this.effects.length;e<t;e++)this.effects[e].inputTarget.destroy();this.effects.length=0,this.disable()}enable(){!this.enabled&&this.effects.length&&(this.enabled=!0,this._requestDepthMaps(),this.app.graphicsDevice.on("resizecanvas",this._onCanvasResized,this),this.destinationRenderTarget=this.camera.renderTarget,this.camera.renderTarget=this.effects[0].inputTarget,this.camera.onPostprocessing=()=>{if(this.enabled){let e=null;const t=this.effects.length;if(t)for(let s=0;s<t;s++){const i=this.effects[s];let r=i.outputTarget;s===t-1&&(e=this.camera.rect,this.destinationRenderTarget&&(r=this.destinationRenderTarget)),i.effect.render(i.inputTarget,r,e)}}})}disable(){this.enabled&&(this.enabled=!1,this.app.graphicsDevice.off("resizecanvas",this._onCanvasResized,this),this._releaseDepthMaps(),this._destroyOffscreenTarget(this._sourceTarget),this.camera.renderTarget=this.destinationRenderTarget,this.camera.onPostprocessing=null)}_onCanvasResized(e,t){const s=this.camera.rect,i=this.destinationRenderTarget;e=i?.width??e,t=i?.height??t,this.camera.camera.aspectRatio=e*s.z/(t*s.w),this.resizeRenderTargets()}resizeRenderTargets(){const e=this.app.graphicsDevice,t=this.destinationRenderTarget,s=t?.width??e.width,i=t?.height??e.height,r=this.camera.rect,a=Math.floor(r.z*s),n=Math.floor(r.w*i),o=this.effects;for(let c=0,h=o.length;c<h;c++){const d=o[c];(d.inputTarget.width!==a||d.inputTarget.height!==n)&&this._resizeOffscreenTarget(d.inputTarget)}}onCameraRectChanged(e,t,s){this.enabled&&this.resizeRenderTargets()}}class ga extends ye{onPostprocessing=null;_renderSceneDepthMap=0;_renderSceneColorMap=0;_sceneDepthMapRequested=!1;_sceneColorMapRequested=!1;_priority=0;_disablePostEffectsLayer=Ef;_camera;_evtLayersChanged=null;_evtLayerAdded=null;_evtLayerRemoved=null;constructor(e,t){super(e,t),this._camera=new cs(e.app.graphicsDevice),this._camera.node=t,this._postEffects=new zz(e.app,this)}setShaderPass(e){const t=zi.get(this.system.app.graphicsDevice),s=e?t.allocate(e,{isForward:!0}):null;return this._camera.shaderPassInfo=s,s.index}getShaderPass(){return this._camera.shaderPassInfo?.name}set framePasses(e){this._camera.framePasses=e||[],this.dirtyLayerCompositionCameras(),this.system.app.scene.updateShaders=!0}get framePasses(){return this._camera.framePasses}set renderPasses(e){this.framePasses=e}get renderPasses(){return this.framePasses}get shaderParams(){return this._camera.shaderParams}set gammaCorrection(e){this.camera.shaderParams.gammaCorrection=e}get gammaCorrection(){return this.camera.shaderParams.gammaCorrection}set toneMapping(e){this.camera.shaderParams.toneMapping=e}get toneMapping(){return this.camera.shaderParams.toneMapping}set fog(e){this._camera.fogParams=e}get fog(){return this._camera.fogParams}set aperture(e){this._camera.aperture=e}get aperture(){return this._camera.aperture}set aspectRatio(e){this._camera.aspectRatio=e}get aspectRatio(){return this._camera.aspectRatio}set aspectRatioMode(e){this._camera.aspectRatioMode=e}get aspectRatioMode(){return this._camera.aspectRatioMode}set calculateProjection(e){this._camera.calculateProjection=e}get calculateProjection(){return this._camera.calculateProjection}set calculateTransform(e){this._camera.calculateTransform=e}get calculateTransform(){return this._camera.calculateTransform}get camera(){return this._camera}set clearColor(e){this._camera.clearColor=e}get clearColor(){return this._camera.clearColor}set clearColorBuffer(e){this._camera.clearColorBuffer=e,this.dirtyLayerCompositionCameras()}get clearColorBuffer(){return this._camera.clearColorBuffer}set clearDepth(e){this._camera.clearDepth=e}get clearDepth(){return this._camera.clearDepth}set clearDepthBuffer(e){this._camera.clearDepthBuffer=e,this.dirtyLayerCompositionCameras()}get clearDepthBuffer(){return this._camera.clearDepthBuffer}set clearStencilBuffer(e){this._camera.clearStencilBuffer=e,this.dirtyLayerCompositionCameras()}get clearStencilBuffer(){return this._camera.clearStencilBuffer}set cullFaces(e){this._camera.cullFaces=e}get cullFaces(){return this._camera.cullFaces}set disablePostEffectsLayer(e){this._disablePostEffectsLayer=e,this.dirtyLayerCompositionCameras()}get disablePostEffectsLayer(){return this._disablePostEffectsLayer}set farClip(e){this._camera.farClip=e}get farClip(){return this._camera.farClip}set flipFaces(e){this._camera.flipFaces=e}get flipFaces(){return this._camera.flipFaces}set fov(e){this._camera.fov=e}get fov(){return this._camera.fov}
13428get frustum(){return this._camera.frustum}set frustumCulling(e){this._camera.frustumCulling=e}get frustumCulling(){return this._camera.frustumCulling}set horizontalFov(e){this._camera.horizontalFov=e}get horizontalFov(){return this._camera.horizontalFov}set layers(e){const t=this._camera.layers,s=this.system.app.scene;t.forEach(i=>{s.layers.getLayerById(i)?.removeCamera(this)}),this._camera.layers=e,this.enabled&&this.entity.enabled&&e.forEach(i=>{s.layers.getLayerById(i)?.addCamera(this)}),this.fire("set:layers")}get layers(){return this._camera.layers}get layersSet(){return this._camera.layersSet}set jitter(e){this._camera.jitter=e}get jitter(){return this._camera.jitter}set nearClip(e){this._camera.nearClip=e}get nearClip(){return this._camera.nearClip}set orthoHeight(e){this._camera.orthoHeight=e}get orthoHeight(){return this._camera.orthoHeight}get postEffects(){return this._postEffects}get postEffectsEnabled(){return this._postEffects.enabled}set priority(e){this._priority=e,this.dirtyLayerCompositionCameras()}get priority(){return this._priority}set projection(e){this._camera.projection=e}get projection(){return this._camera.projection}get projectionMatrix(){return this._camera.projectionMatrix}set rect(e){this._camera.rect=e,this.fire("set:rect",this._camera.rect)}get rect(){return this._camera.rect}set renderSceneColorMap(e){e&&!this._sceneColorMapRequested?(this.requestSceneColorMap(!0),this._sceneColorMapRequested=!0):!e&&this._sceneColorMapRequested&&(this.requestSceneColorMap(!1),this._sceneColorMapRequested=!1)}get renderSceneColorMap(){return this._renderSceneColorMap>0}set renderSceneDepthMap(e){e&&!this._sceneDepthMapRequested?(this.requestSceneDepthMap(!0),this._sceneDepthMapRequested=!0):!e&&this._sceneDepthMapRequested&&(this.requestSceneDepthMap(!1),this._sceneDepthMapRequested=!1)}get renderSceneDepthMap(){return this._renderSceneDepthMap>0}set renderTarget(e){this._camera.renderTarget=e,this.dirtyLayerCompositionCameras()}get renderTarget(){return this._camera.renderTarget}set scissorRect(e){this._camera.scissorRect=e}get scissorRect(){return this._camera.scissorRect}set sensitivity(e){this._camera.sensitivity=e}get sensitivity(){return this._camera.sensitivity}set shutter(e){this._camera.shutter=e}get shutter(){return this._camera.shutter}get viewMatrix(){return this._camera.viewMatrix}_enableDepthLayer(e){if(this.layers.find(s=>s===ks)){const s=this.system.app.scene.layers.getLayerById(ks);e?s?.incrementCounter():s?.decrementCounter()}else if(e)return!1;return!0}requestSceneColorMap(e){this._renderSceneColorMap+=e?1:-1,this._enableDepthLayer(e),this.camera._enableRenderPassColorGrab(this.system.app.graphicsDevice,this.renderSceneColorMap),this.system.app.scene.layers.markDirty()}requestSceneDepthMap(e){this._renderSceneDepthMap+=e?1:-1,this._enableDepthLayer(e),this.camera._enableRenderPassDepthGrab(this.system.app.graphicsDevice,this.system.app.renderer,this.renderSceneDepthMap),this.system.app.scene.layers.markDirty()}dirtyLayerCompositionCameras(){const e=this.system.app.scene.layers;e._dirty=!0}screenToWorld(e,t,s,i){const r=this.system.app.graphicsDevice,{width:a,height:n}=r.clientRect;return this._camera.screenToWorld(e,t,s,a,n,i)}worldToScreen(e,t){const s=this.system.app.graphicsDevice,{width:i,height:r}=s.clientRect;return this._camera.worldToScreen(e,i,r,t)}onAppPrerender(){this._camera._viewMatDirty=!0,this._camera._viewProjMatDirty=!0}addCameraToLayers(){const e=this.layers;for(let t=0;t<e.length;t++){const s=this.system.app.scene.layers.getLayerById(e[t]);s&&s.addCamera(this)}}removeCameraFromLayers(){const e=this.layers;for(let t=0;t<e.length;t++){const s=this.system.app.scene.layers.getLayerById(e[t]);s&&s.removeCamera(this)}}onLayersChanged(e,t){this.addCameraToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this)}onLayerAdded(e){this.layers.indexOf(e.id)<0||e.addCamera(this)}onLayerRemoved(e){this.layers.indexOf(e.id)<0||e.removeCamera(this)}onEnable(){const e=this.system.app.scene,t=e.layers;this.system.addCamera(this),this._evtLayersChanged?.off(),this._evtLayersChanged=e.on("set:layers",this.onLayersChanged,this),t&&(this._evtLayerAdded?.off(),this._evtLayerAdded=t.on("add",this.onLayerAdded,this),this._evtLayerRemoved?.off(),this._evtLayerRemoved=t.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&this.addCameraToLayers(),this.postEffe
13428cts.enable()}onDisable(){const t=this.system.app.scene.layers;this.postEffects.disable(),this.removeCameraFromLayers(),this._evtLayersChanged?.off(),this._evtLayersChanged=null,t&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this.system.removeCamera(this)}onRemove(){this.onDisable(),this.off(),this.camera.destroy()}calculateAspectRatio(e){return this._camera.calculateAspectRatio(e)}frameUpdate(e){this.aspectRatioMode===hu&&(this.aspectRatio=this.calculateAspectRatio(e))}startXr(e,t,s){this.system.app.xr.start(this,e,t,s)}endXr(e){if(!this._camera.xr){e&&e(new Error("Camera is not in XR"));return}this._camera.xr.end(e)}copy(e){this.aperture=e.aperture,this.aspectRatio=e.aspectRatio,this.aspectRatioMode=e.aspectRatioMode,this.calculateProjection=e.calculateProjection,this.calculateTransform=e.calculateTransform,this.clearColor=e.clearColor,this.clearColorBuffer=e.clearColorBuffer,this.clearDepthBuffer=e.clearDepthBuffer,this.clearStencilBuffer=e.clearStencilBuffer,this.cullFaces=e.cullFaces,this.disablePostEffectsLayer=e.disablePostEffectsLayer,this.farClip=e.farClip,this.flipFaces=e.flipFaces,this.fov=e.fov,this.frustumCulling=e.frustumCulling,this.horizontalFov=e.horizontalFov,this.layers=e.layers,this.nearClip=e.nearClip,this.orthoHeight=e.orthoHeight,this.priority=e.priority,this.projection=e.projection,this.rect=e.rect,this.renderTarget=e.renderTarget,this.scissorRect=e.scissorRect,this.sensitivity=e.sensitivity,this.shutter=e.shutter}}class Vz{enabled=!0}const hC=["enabled"];class Gz extends Tt{cameras=[];constructor(e){super(e),this.id="camera",this.ComponentType=ga,this.DataType=Vz,this.schema=hC,this.on("beforeremove",this.onBeforeRemove,this),this.app.on("prerender",this.onAppPrerender,this)}initializeComponentData(e,t,s){s=["aspectRatio","aspectRatioMode","calculateProjection","calculateTransform","clearColor","clearColorBuffer","clearDepth","clearDepthBuffer","clearStencilBuffer","renderSceneColorMap","renderSceneDepthMap","cullFaces","farClip","flipFaces","fog","fov","frustumCulling","horizontalFov","layers","renderTarget","nearClip","orthoHeight","projection","priority","rect","scissorRect","aperture","shutter","sensitivity","gammaCorrection","toneMapping"];for(let i=0;i<s.length;i++){const r=s[i];if(t.hasOwnProperty(r)){const a=t[r];switch(r){case"rect":case"scissorRect":Array.isArray(a)?e[r]=new ie(a[0],a[1],a[2],a[3]):e[r]=a;break;case"clearColor":Array.isArray(a)?e[r]=new Q(a[0],a[1],a[2],a[3]):e[r]=a;break;default:e[r]=a;break}}}super.initializeComponentData(e,t,["enabled"])}cloneComponent(e,t){const s=e.camera;return this.addComponent(t,{aspectRatio:s.aspectRatio,aspectRatioMode:s.aspectRatioMode,calculateProjection:s.calculateProjection,calculateTransform:s.calculateTransform,clearColor:s.clearColor,clearColorBuffer:s.clearColorBuffer,clearDepthBuffer:s.clearDepthBuffer,clearStencilBuffer:s.clearStencilBuffer,renderSceneDepthMap:s.renderSceneDepthMap,renderSceneColorMap:s.renderSceneColorMap,cullFaces:s.cullFaces,enabled:s.enabled,farClip:s.farClip,flipFaces:s.flipFaces,fov:s.fov,frustumCulling:s.frustumCulling,horizontalFov:s.horizontalFov,layers:s.layers,renderTarget:s.renderTarget,nearClip:s.nearClip,orthoHeight:s.orthoHeight,projection:s.projection,priority:s.priority,rect:s.rect,scissorRect:s.scissorRect,aperture:s.aperture,sensitivity:s.sensitivity,shutter:s.shutter,gammaCorrection:s.gammaCorrection,toneMapping:s.toneMapping})}onBeforeRemove(e,t){this.removeCamera(t),t.onRemove()}onAppPrerender(){for(let e=0,t=this.cameras.length;e<t;e++)this.cameras[e].onAppPrerender()}addCamera(e){this.cameras.push(e),vc(this.cameras)}removeCamera(e){const t=this.cameras.indexOf(e);t>=0&&(this.cameras.splice(t,1),vc(this.cameras))}destroy(){this.app.off("prerender",this.onAppPrerender,this),super.destroy()}}ye._buildAccessors(ga.prototype,hC);const mo=["type","color","intensity","luminance","shape","affectSpecularity","castShadows","shadowDistance","shadowIntensity","shadowResolution","shadowBias","numCascades","cascadeBlend","bakeNumSamples","bakeArea","cascadeDistribution","normalOffsetBias","range","innerConeAngle","outerConeAngle","falloffMode","shadowType","vsmBlurSize","vsmBlurMode","vsmBias","cookieAsset","cookie","cookieIntensity","cookieFalloff","cookieChannel","cookieAngle","cookieScale","cookieOffset","shadowUpdateMode","mask","affectDynamic","affectLightmapped","bake","bakeDir","isStatic","layers","penumbraSize","penumbraFalloff","shadowSamples","shadowBlockerSamples"];class dC extends ye{_light;_evtLayersChanged=null;_evtLayerAdded=null;_evtLayerRemoved=null;_cookieAsset=null;_cookieAssetId=null;_cookieAssetAdd=!1;_cookieMatrix=null;_shadowBias=.05;_cookieAngle=0;_cookieScale=null;_castShadows=!1;_affectSpecularity=!0;_affectDynamic=!0;_affectLightmapped=!1;_bake=!1;_layers=[Ir];_type="directional";constructor(e,t){super(e,t),this._light=new Sc(e.app.graphicsDevice,e.app.scene.clusteredLightingEnabled),this._light._node=t,this._light.setColor(1,1,1)}get light(){return this._light}set type(e){this._type!==e&&(this.removeLightFromLayers(),this._type=e,this._light.type=ZT[e],this.refreshPro
13428perties())}get type(){return this._type}set color(e){this._light.setColor(e)}get color(){return this._light.getColor()}set intensity(e){this._light.intensity=e}get intensity(){return this._light.intensity}set luminance(e){this._light.luminance=e}get luminance(){return this._light.luminance}set shape(e){this._light.shape=e}get shape(){return this._light.shape}set affectSpecularity(e){this._affectSpecularity=e,this._light.affectSpecularity=e}get affectSpecularity(){return this._affectSpecularity}set castShadows(e){this._castShadows=e,this._light.castShadows=e}get castShadows(){return this._castShadows}set shadowDistance(e){this._light.shadowDistance=e}get shadowDistance(){return this._light.shadowDistance}set shadowIntensity(e){this._light.shadowIntensity=e}get shadowIntensity(){return this._light.shadowIntensity}set shadowResolution(e){this._light.shadowResolution=e}get shadowResolution(){return this._light.shadowResolution}set shadowBias(e){this._shadowBias=e,this._light.shadowBias=-.01*H.clamp(e,0,1)}get shadowBias(){return this._shadowBias}set numCascades(e){this._light.numCascades=H.clamp(Math.floor(e),1,4)}get numCascades(){return this._light.numCascades}set cascadeBlend(e){this._light.cascadeBlend=H.clamp(e,0,1)}get cascadeBlend(){return this._light.cascadeBlend}set bakeNumSamples(e){this._light.bakeNumSamples=H.clamp(Math.floor(e),1,255)}get bakeNumSamples(){return this._light.bakeNumSamples}set bakeArea(e){this._light.bakeArea=H.clamp(e,0,180)}get bakeArea(){return this._light.bakeArea}set cascadeDistribution(e){this._light.cascadeDistribution=H.clamp(e,0,1)}get cascadeDistribution(){return this._light.cascadeDistribution}set normalOffsetBias(e){this._light.normalOffsetBias=H.clamp(e,0,1)}get normalOffsetBias(){return this._light.normalOffsetBias}set range(e){this._light.attenuationEnd=e}get range(){return this._light.attenuationEnd}set innerConeAngle(e){this._light.innerConeAngle=e}get innerConeAngle(){return this._light.innerConeAngle}set outerConeAngle(e){this._light.outerConeAngle=e}get outerConeAngle(){return this._light.outerConeAngle}set falloffMode(e){this._light.falloffMode=e}get falloffMode(){return this._light.falloffMode}set shadowType(e){this._light.shadowType=e}get shadowType(){return this._light.shadowType}set vsmBlurSize(e){this._light.vsmBlurSize=e}get vsmBlurSize(){return this._light.vsmBlurSize}set vsmBlurMode(e){this._light.vsmBlurMode=e}get vsmBlurMode(){return this._light.vsmBlurMode}set vsmBias(e){this._light.vsmBias=H.clamp(e,0,1)}get vsmBias(){return this._light.vsmBias}set cookieAsset(e){if(!(this._cookieAssetId&&(e instanceof pe&&e.id===this._cookieAssetId||e===this._cookieAssetId))){if(this.onCookieAssetRemove(),this._cookieAssetId=null,e instanceof pe)this._cookieAssetId=e.id,this.onCookieAssetAdd(e);else if(typeof e=="number"){this._cookieAssetId=e;const t=this.system.app.assets.get(e);t?this.onCookieAssetAdd(t):(this._cookieAssetAdd=!0,this.system.app.assets.on(`add:${this._cookieAssetId}`,this.onCookieAssetAdd,this))}}}get cookieAsset(){return this._cookieAssetId}set cookie(e){this._light.cookie=e}get cookie(){return this._light.cookie}set cookieIntensity(e){this._light.cookieIntensity=H.clamp(e,0,1)}get cookieIntensity(){return this._light.cookieIntensity}set cookieFalloff(e){this._light.cookieFalloff=e}get cookieFalloff(){return this._light.cookieFalloff}set cookieChannel(e){this._light.cookieChannel=e}get cookieChannel(){return this._light.cookieChannel}set cookieAngle(e){if(this._cookieAngle!==e)if(this._cookieAngle=e,e!==0||this._cookieScale!==null){this._cookieMatrix||(this._cookieMatrix=new ie);let t=1,s=1;this._cookieScale&&(t=this._cookieScale.x,s=this._cookieScale.y);const i=Math.cos(e*H.DEG_TO_RAD),r=Math.sin(e*H.DEG_TO_RAD);this._cookieMatrix.set(i/t,-r/t,r/s,i/s),this._light.cookieTransform=this._cookieMatrix}else this._light.cookieTransform=null}get cookieAngle(){return this._cookieAngle}set cookieScale(e){if(this._cookieScale=e,e!==null||this._cookieAngle!==0){this._cookieMatrix||(this._cookieMatrix=new ie);const t=e?e.x:1,s=e?e.y:1,i=Math.cos(this._cookieAngle*H.DEG_TO_RAD),r=Math.sin(this._cookieAngle*H.DEG_TO_RAD);this._cookieMatrix.set(i/t,-r/t,r/s,i/s),this._light.cookieTransform=this._cookieMatrix}else this._light.cookieTransform=null}get cookieScale(){return this._cookieScale}set cookieOffset(e){this._light.cookieOffset=e}get cookieOffset(){return this._light.cookieOffset}set shadowUpdateMode(e){this._light.shadowUpdateMode=e}get shadowUpdateMode(){return this._light.shadowUpdateMode}set mask(e){this._light.mask=e}get mask(){return this._light.mask}set affectDynamic(e){this._affectDynamic!==e&&(this._affectDynamic=e,e?this._light.mask|=Js:this._light.mask&=~Js,this._light.layersDirty())}get affectDynamic(){return this._affectDynamic}set affectLightmapped(e){this._affectLightmapped!==e&&(this._affectLightmapped=e,e?(this._light.mask|=ur,this._bake&&(this._light.mask&=~fr)):(this._light.mask&=~ur,this._bake&&(this._light.mask|=fr)))}get affectLightmapped(){return this._affectLightmapped}set bake(e){this._bake!==e&&(this._bake=e,e?(this._light.mask|=fr,this._affectLightmapped&&(this._light.mask&=~ur)):(this._light.mask&=~fr,this._affectLightmapped&&(this._light.mask|=ur)),this._light.layersDirty())}get bake(){return this._bake}set bakeDir(e){this._light.bakeDir=e}get bakeDir(){return this._light.bakeDir}set isStatic(e){this._light.isStatic=e}get isStatic(){return this._light.isStatic}set layers(e){const t=this._layers;for(let s=0;s<t.length;
13428s++){const i=this.system.app.scene.layers.getLayerById(t[s]);i&&(i.removeLight(this),this._light.removeLayer(i))}this._layers=e;for(let s=0;s<e.length;s++){const i=this.system.app.scene.layers.getLayerById(e[s]);i&&this.enabled&&this.entity.enabled&&(i.addLight(this),this._light.addLayer(i))}}get layers(){return this._layers}set shadowUpdateOverrides(e){this._light.shadowUpdateOverrides=e}get shadowUpdateOverrides(){return this._light.shadowUpdateOverrides}set shadowSamples(e){this._light.shadowSamples=e}get shadowSamples(){return this._light.shadowSamples}set shadowBlockerSamples(e){this._light.shadowBlockerSamples=e}get shadowBlockerSamples(){return this._light.shadowBlockerSamples}set penumbraSize(e){this._light.penumbraSize=e}get penumbraSize(){return this._light.penumbraSize}set penumbraFalloff(e){this._light.penumbraFalloff=e}get penumbraFalloff(){return this._light.penumbraFalloff}addLightToLayers(){for(let e=0;e<this._layers.length;e++){const t=this.system.app.scene.layers.getLayerById(this._layers[e]);t&&(t.addLight(this),this._light.addLayer(t))}}removeLightFromLayers(){for(let e=0;e<this._layers.length;e++){const t=this.system.app.scene.layers.getLayerById(this._layers[e]);t&&(t.removeLight(this),this._light.removeLayer(t))}}onLayersChanged(e,t){this.enabled&&this.entity.enabled&&this.addLightToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this)}onLayerAdded(e){this._layers.indexOf(e.id)>=0&&this.enabled&&this.entity.enabled&&(e.addLight(this),this._light.addLayer(e))}onLayerRemoved(e){this._layers.indexOf(e.id)>=0&&(e.removeLight(this),this._light.removeLayer(e))}refreshProperties(){for(let e=0;e<mo.length;e++){const t=mo[e];this[t]=this[t]}this.enabled&&this.entity.enabled&&this.onEnable()}onCookieAssetSet(){let e=!1;this._cookieAsset.type==="cubemap"&&!this._cookieAsset.loadFaces&&(this._cookieAsset.loadFaces=!0,e=!0),(!this._cookieAsset.resource||e)&&this.system.app.assets.load(this._cookieAsset),this._cookieAsset.resource&&this.onCookieAssetLoad()}onCookieAssetAdd(e){this._cookieAssetId===e.id&&(this._cookieAsset=e,this._light.enabled&&this.onCookieAssetSet(),this._cookieAsset.on("load",this.onCookieAssetLoad,this),this._cookieAsset.on("remove",this.onCookieAssetRemove,this))}onCookieAssetLoad(){!this._cookieAsset||!this._cookieAsset.resource||(this.cookie=this._cookieAsset.resource)}onCookieAssetRemove(){this._cookieAssetId&&(this._cookieAssetAdd&&(this.system.app.assets.off(`add:${this._cookieAssetId}`,this.onCookieAssetAdd,this),this._cookieAssetAdd=!1),this._cookieAsset&&(this._cookieAsset.off("load",this.onCookieAssetLoad,this),this._cookieAsset.off("remove",this.onCookieAssetRemove,this),this._cookieAsset=null),this.cookie=null)}onEnable(){const e=this.system.app.scene,t=e.layers;this._light.enabled=!0,this._evtLayersChanged?.off(),this._evtLayersChanged=e.on("set:layers",this.onLayersChanged,this),t&&(this._evtLayerAdded?.off(),this._evtLayerAdded=t.on("add",this.onLayerAdded,this),this._evtLayerRemoved?.off(),this._evtLayerRemoved=t.on("remove",this.onLayerRemoved,this)),this.enabled&&this.entity.enabled&&this.addLightToLayers(),this._cookieAsset&&!this.cookie&&this.onCookieAssetSet()}onDisable(){const t=this.system.app.scene.layers;this._light.enabled=!1,this._evtLayersChanged?.off(),this._evtLayersChanged=null,t&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this.removeLightFromLayers()}onRemove(){this.onDisable(),this._light.destroy(),this.cookieAsset=null}}class Hz{enabled=!0}const uC=["enabled"];class Wz extends Tt{constructor(e){super(e),this.id="light",this.ComponentType=dC,this.DataType=Hz,this.schema=uC,this.on("beforeremove",this._onRemoveComponent,this)}initializeComponentData(e,t){const s={...t};s.layers&&Array.isArray(s.layers)&&(s.layers=s.layers.slice(0)),s.color&&Array.isArray(s.color)&&(s.color=new Q(s.color[0],s.color[1],s.color[2])),s.cookieOffset&&s.cookieOffset instanceof Array&&(s.cookieOffset=new j(s.cookieOffset[0],s.cookieOffset[1])),s.cookieScale&&s.cookieScale instanceof Array&&(s.cookieScale=new j(s.cookieScale[0],s.cookieScale[1])),s.hasOwnProperty("enable")&&(console.warn("WARNING: enable: Property is deprecated. Set enabled property instead."),s.enabled=s.enable);for(let i=0;i<mo.length;i++){const r=mo[i];s.hasOwnProperty(r)&&(e[r]=s[r])}super.initializeComponentData(e,s,["enabled"])}_onRemoveComponent(e,t){t.onRemove()}cloneComponent(e,t){const s=e.light,i={enabled:s.enabled};for(let r=0;r<mo.length;r++){const a=mo[r],n=s[a];n&&n.clone?i[a]=n.clone():i[a]=n}return this.addComponent(t,i)}}ye._buildAccessors(dC.prototype,uC);const Xz=["x","y","z","w"],Yz=[void 0,void 0,j,E,ie];function Go(l,e,t,s){switch(e.type){case"boolean":return!!t;case"number":if(typeof t=="number")return t;if(typeof t=="string"){const i=parseInt(t,10);return isNaN(i)?null:i}else if(typeof t=="boolean")return 0+t;return null;case"json":{const i={};
13428if(Array.isArray(e.schema)){(!t||typeof t!="object")&&(t={});for(let r=0;r<e.schema.length;r++){const a=e.schema[r];if(a.name)if(a.array){i[a.name]=[];const n=Array.isArray(t[a.name])?t[a.name]:[];for(let o=0;o<n.length;o++)i[a.name].push(Go(l,a,n[o]))}else{const n=t.hasOwnProperty(a.name)?t[a.name]:a.default;i[a.name]=Go(l,a,n)}}}return i}case"asset":return t instanceof pe?t:typeof t=="number"?l.assets.get(t)||null:typeof t=="string"&&l.assets.get(parseInt(t,10))||null;case"entity":return t instanceof He?t:typeof t=="string"?l.getEntityFromIndex(t):null;case"rgb":case"rgba":if(t instanceof Q)return s instanceof Q?(s.copy(t),s):t.clone();if(t instanceof Array&&t.length>=3&&t.length<=4){for(let i=0;i<t.length;i++)if(typeof t[i]!="number")return null;return s||(s=new Q),s.r=t[0],s.g=t[1],s.b=t[2],s.a=t.length===3?1:t[3],s}else if(typeof t=="string"&&/#(?:[0-9a-f]{2}){3,4}/i.test(t))return s||(s=new Q),s.fromString(t),s;return null;case"vec2":case"vec3":case"vec4":{const i=parseInt(e.type.slice(3),10),r=Yz[i];if(t instanceof r)return s instanceof r?(s.copy(t),s):t.clone();if(t instanceof Array&&t.length===i){for(let a=0;a<t.length;a++)if(typeof t[a]!="number")return null;s||(s=new r);for(let a=0;a<i;a++)s[Xz[a]]=t[a];return s}return null}case"curve":if(t){let i;if(t instanceof _i||t instanceof Ya)i=t.clone();else{const r=t.keys[0]instanceof Array?Ya:_i;i=new r(t.keys),i.type=t.type}return i}break}return t}function fC(l,e,t,s){return e.array?t.map((i,r)=>Go(l,e,i,s?s[r]:null)):Go(l,e,t,s)}function pC(l,e,t,s){if(t)for(const i in e){const r=e[i],a=t[i];a!==void 0&&(s[i]=fC(l,r,a,s[i]))}}class eh{static assignAttributesToScript=pC;static attributeToValue=fC;constructor(e){this.scriptType=e,this.index={}}static reservedNames=new Set(["app","entity","enabled","_enabled","_enabledOld","_destroyed","__attributes","__attributesRaw","__scriptType","__executionOrder","_callbacks","_callbackActive","has","get","on","off","fire","once","hasEvent"]);add(e,t){t&&t.type&&(this.index[e]||eh.reservedNames.has(e)||(this.index[e]=t,Object.defineProperty(this.scriptType.prototype,e,{get:function(){return this.__attributes[e]},set:function(s){const i="attr",r=`attr:${e}`,a=this.__attributes[e];let n=a;if(a&&t.type!=="json"&&t.type!=="entity"&&a.clone&&(this.hasEvent(i)||this.hasEvent(r))&&(n=a.clone()),t.array){if(this.__attributes[e]=[],s)for(let o=0,c=s.length;o<c;o++)this.__attributes[e].push(Go(this.app,t,s[o],a?a[o]:null))}else this.__attributes[e]=Go(this.app,t,s,a);this.fire(i,e,this.__attributes[e],n),this.fire(r,this.__attributes[e],n)}})))}remove(e){return this.index[e]?(delete this.index[e],delete this.scriptType.prototype[e],!0):!1}has(e){return!!this.index[e]}get(e){return this.index[e]||null}}const P_="initialize",I_="postInitialize",jz="update",qz="postUpdate",$z="swap";class xu extends ge{static EVENT_ENABLE="enable";static EVENT_DISABLE="disable";static EVENT_STATE="state";static EVENT_DESTROY="destroy";static EVENT_ATTR="attr";static EVENT_ERROR="error";app;entity;_enabled;_enabledOld;_initialized;_postInitialized;__destroyed;__scriptType;__executionOrder;constructor(e){super(),this.initScript(e)}set enabled(e){this._enabled=!!e,this.enabled!==this._enabledOld&&(this._enabledOld=this.enabled,this.fire(this.enabled?"enable":"disable"),this.fire("state",this.enabled),!this._initialized&&this.enabled&&(this._initialized=!0,this.fire("preInitialize"),this.initialize&&this.entity.script._scriptMethod(this,P_)),this._initialized&&!this._postInitialized&&this.enabled&&!this.entity.script._beingEnabled&&(this._postInitialized=!0,this.postInitialize&&this.entity.script._scriptMethod(this,I_)))}get enabled(){return this._enabled&&!this._destroyed&&this.entity.script.enabled&&this.entity.enabled}initScript(e){const t=this.constructor;this.app=e.app,this.entity=e.entity,this._enabled=typeof e.enabled=="boolean"?e.enabled:!0,this._enabledOld=this.enabled,this.__destroyed=!1,this.__scriptType=t,this.__executionOrder=-1}static __name=null;static __getScriptName=mC;static set scriptName(e){this.__name=e}static get scriptName(){return this.__name}}const Kz=/^\s*function(?:\s|\s*\/\*.*\*\/\s*)+([^(\s\/]*)\s*/;function mC(l){if(typeof l!="function")return;if(l.scriptName)return l.scriptName;if("name"in Function.prototype)return l.name;if(l===Function||l===Function.prototype.constructor)return"Function";const e=`${l}`.match(Kz);return e?e[1]:void 0}class Zl extends xu{__attributes;__attributesRaw;constructor(e){super(e),this.initScriptType(e)}static get attributes(){return this.hasOwnProperty("__attributes")||(this.__attributes=new eh(this)),this.__attributes}initScript(e){xu.prototype.initScript.call(this,e),this.__attributes={},this.__attributesRaw=e.attributes||{}}initScriptType(e){this.initScript(e)}__initializeAttributes(e){if(!(!e&&!this.__attributesRaw)){for(const t in this.__scriptType.attributes.index)this.__attributesRaw&&this.__attributesRaw.hasOwnProperty(t)?this[t]=this.__attributesRaw[t]:this.__attributes.hasOwnProperty(t)||(this.__scriptType.attributes.index[t].hasOwnProperty("default")?this[t]=this.__scriptType.attributes.index[t].default:this[t]=null);this.__attributesRaw=null}}static extend(e){for(const t in e)e.hasOwnProperty(t)&&(this.prototype[t]=e[t])}}const Zz=l=>l[0].toLowerCase()+l.substring(1);class Qz extends ye{_attributeDataMap=new Map;static EVENT_CREATE="create";static EVENT_DESTROY="destroy";static EVENT_ENABLE="enable";static EVENT_DISABLE="disable";static EVENT_REMOVE="remove";static EVENT_STATE="state";static EVENT_MOVE="move";static EVENT_ERROR="error";
13428constructor(e,t){super(e,t),this._scripts=[],this._updateList=new zd({sortBy:"__executionOrder"}),this._postUpdateList=new zd({sortBy:"__executionOrder"}),this._scriptsIndex={},this._destroyedScripts=[],this._destroyed=!1,this._scriptsData=null,this._oldState=!0,this._enabled=!0,this._beingEnabled=!1,this._isLoopingThroughScripts=!1,this._executionOrder=-1,this.on("set_enabled",this._onSetEnabled,this)}set scripts(e){this._scriptsData=e;for(const t in e){if(!e.hasOwnProperty(t))continue;const s=this._scriptsIndex[t];if(s){if(typeof e[t].enabled=="boolean"&&(s.once("preInitialize",()=>{this.initializeAttributes(s)}),s.enabled=!!e[t].enabled),typeof e[t].attributes=="object"){for(const i in e[t].attributes)if(!eh.reservedNames.has(i)){if(!s.__attributes.hasOwnProperty(i)){const r=this.system.app.scripts.get(t);r&&r.attributes.add(i,{})}s[i]=e[t].attributes[i]}}}else console.log(this.order)}}get scripts(){return this._scripts}set enabled(e){const t=this._enabled;this._enabled=e,this.fire("set","enabled",t,e)}get enabled(){return this._enabled}onEnable(){this._beingEnabled=!0,this._checkState(),this.entity._beingEnabled||this.onPostStateChange(),this._beingEnabled=!1}onDisable(){this._checkState()}onPostStateChange(){const e=this._beginLooping();for(let t=0,s=this.scripts.length;t<s;t++){const i=this.scripts[t];i._initialized&&!i._postInitialized&&i.enabled&&(i._postInitialized=!0,i.postInitialize&&this._scriptMethod(i,I_))}this._endLooping(e)}_beginLooping(){const e=this._isLoopingThroughScripts;return this._isLoopingThroughScripts=!0,e}_endLooping(e){this._isLoopingThroughScripts=e,this._isLoopingThroughScripts||this._removeDestroyedScripts()}_onSetEnabled(e,t,s){this._beingEnabled=!0,this._checkState(),this._beingEnabled=!1}_checkState(){const e=this.enabled&&this.entity.enabled;if(e===this._oldState)return;this._oldState=e,this.fire(e?"enable":"disable"),this.fire("state",e),e?this.system._addComponentToEnabled(this):this.system._removeComponentFromEnabled(this);const t=this._beginLooping();for(let s=0,i=this.scripts.length;s<i;s++){const r=this.scripts[s];r.once("preInitialize",()=>{this.initializeAttributes(r)}),r.enabled=r._enabled}this._endLooping(t)}_onBeforeRemove(){this.fire("remove");const e=this._beginLooping();for(let t=0;t<this.scripts.length;t++){const s=this.scripts[t];s&&this.destroy(s.__scriptType.__name)}this._endLooping(e)}_removeDestroyedScripts(){const e=this._destroyedScripts.length;if(e){for(let t=0;t<e;t++){const s=this._destroyedScripts[t];this._removeScriptInstance(s)}this._destroyedScripts.length=0,this._resetExecutionOrder(0,this._scripts.length)}}_onInitializeAttributes(){for(let e=0,t=this.scripts.length;e<t;e++){const s=this.scripts[e];this.initializeAttributes(s)}}initializeAttributes(e){if(e instanceof Zl)e.__initializeAttributes();else{const t=e.__scriptType.__name,s=this._attributeDataMap.get(t);if(!s)return;const i=this.system.app.scripts?.getSchema(t);pC(this.system.app,i.attributes,s,e)}}_scriptMethod(e,t,s){e[t](s)}_onInitialize(){const e=this._scripts,t=this._beginLooping();for(let s=0,i=e.length;s<i;s++){const r=e[s];!r._initialized&&r.enabled&&(r._initialized=!0,r.initialize&&this._scriptMethod(r,P_))}this._endLooping(t)}_onPostInitialize(){this.onPostStateChange()}_onUpdate(e){const t=this._updateList;if(!t.length)return;const s=this._beginLooping();for(t.loopIndex=0;t.loopIndex<t.length;t.loopIndex++){const i=t.items[t.loopIndex];i.enabled&&this._scriptMethod(i,jz,e)}this._endLooping(s)}_onPostUpdate(e){const t=this._postUpdateList;if(!t.length)return;const s=this._beginLooping();for(t.loopIndex=0;t.loopIndex<t.length;t.loopIndex++){const i=t.items[t.loopIndex];i.enabled&&this._scriptMethod(i,qz,e)}this._endLooping(s)}_insertScriptInstance(e,t,s){t===-1?(this._scripts.push(e),e.__executionOrder=s,e.update&&this._updateList.append(e),e.postUpdate&&this._postUpdateList.append(e)):(this._scripts.splice(t,0,e),e.__executionOrder=t,this._resetExecutionOrder(t+1,s+1),e.update&&this._updateList.insert(e),e.postUpdate&&this._postUpdateList.insert(e))}_removeScriptInstance(e){const t=this._scripts.indexOf(e);return t===-1||(this._scripts.splice(t,1),e.update&&this._updateList.remove(e),e.postUpdate&&this._postUpdateList.remove(e)),t}_resetExecutionOrder(e,t){for(let s=e;s<t;s++)this._scripts[s].__executionOrder=s}_resolveEntityScriptAttribute(e,t,s,i,r,a){if(e.array){const n=s.length;if(!n)return;const o=s.slice();for(let c=0;c<n;c++){const h=o[c]instanceof lt?o[c].guid:o[c];
13428a[h]&&(o[c]=i?a[h].guid:a[h])}r[t]=o}else{if(s instanceof lt)s=s.guid;else if(typeof s!="string")return;a[s]&&(r[t]=a[s])}}has(e){if(typeof e=="string")return!!this._scriptsIndex[e];if(!e)return!1;const t=e,s=t.__name,i=this._scriptsIndex[s];return(i&&i.instance)instanceof t}get(e){if(typeof e=="string"){const a=this._scriptsIndex[e];return a?a.instance:null}if(!e)return null;const t=e,s=t.__name,i=this._scriptsIndex[s],r=i&&i.instance;return r instanceof t?r:null}create(e,t={}){const s=this;let i=e,r=e;if(typeof i=="string")i=this.system.app.scripts.get(i);else if(i){const a=mC(i),n=Zz(a);!(i.prototype instanceof Zl)&&i.scriptName,i.__name??(i.__name=i.scriptName??n),r=i.__name}if(i){if(!this._scriptsIndex[r]||!this._scriptsIndex[r].instance){const a=new i({app:this.system.app,entity:this.entity,enabled:t.hasOwnProperty("enabled")?t.enabled:!0,attributes:t.attributes||{}});t.properties&&typeof t.properties=="object"&&Object.assign(a,t.properties),!(a instanceof Zl)&&t.attributes&&this._attributeDataMap.set(r,{...t.attributes});const n=this._scripts.length;let o=-1;return typeof t.ind=="number"&&t.ind!==-1&&n>t.ind&&(o=t.ind),this._insertScriptInstance(a,o,n),this._scriptsIndex[r]={instance:a,onSwap:function(){s.swap(r)}},this[r]=a,t.preloading||this.initializeAttributes(a),this.fire("create",r,a),this.fire(`create:${r}`,a),this.system.app.scripts.on(`swap:${r}`,this._scriptsIndex[r].onSwap),t.preloading||(a.enabled&&!a._initialized&&(a._initialized=!0,a.initialize&&this._scriptMethod(a,P_)),a.enabled&&!a._postInitialized&&(a._postInitialized=!0,a.postInitialize&&this._scriptMethod(a,I_))),a}}else this._scriptsIndex[r]={awaiting:!0,ind:this._scripts.length};return null}destroy(e){let t=e,s=e;typeof s=="string"?s=this.system.app.scripts.get(s):s&&(t=s.__name);const i=this._scriptsIndex[t];if(delete this._scriptsIndex[t],!i)return!1;this._attributeDataMap.delete(t);const r=i.instance;if(r&&!r._destroyed)if(r.enabled=!1,r._destroyed=!0,this._isLoopingThroughScripts)this._destroyedScripts.push(r);else{const a=this._removeScriptInstance(r);a>=0&&this._resetExecutionOrder(a,this._scripts.length)}return this.system.app.scripts.off(`swap:${t}`,i.onSwap),delete this[t],this.fire("destroy",t,r||null),this.fire(`destroy:${t}`,r||null),r&&r.fire("destroy"),!0}swap(e){let t=e,s=e;typeof s=="string"?s=this.system.app.scripts.get(s):s&&(t=s.__name);const i=this._scriptsIndex[t];if(!i||!i.instance)return!1;const r=i.instance,a=this._scripts.indexOf(r),n=new s({app:this.system.app,entity:this.entity,enabled:r.enabled,attributes:r.__attributes});return n.swap?(this.initializeAttributes(n),this._scripts[a]=n,this._scriptsIndex[t].instance=n,this[t]=n,n.__executionOrder=a,r.update&&this._updateList.remove(r),r.postUpdate&&this._postUpdateList.remove(r),n.update&&this._updateList.insert(n),n.postUpdate&&this._postUpdateList.insert(n),this._scriptMethod(n,$z,r),this.fire("swap",t,n),this.fire(`swap:${t}`,n),!0):!1}resolveDuplicatedEntityReferenceProperties(e,t){const s=this.entity.script;for(const i in e._scriptsIndex){const r=this.system.app.scripts.get(i);if(!r)continue;const a=e._scriptsIndex[i];if(!a||!a.instance)continue;const n=s[i].__attributesRaw??s._attributeDataMap.get(i),o=s[i].__attributes;if(!n&&!o)continue;const c=!!n,h=a.instance.__attributes??s._attributeDataMap.get(i);for(const d in h){if(!h[d])continue;const u=r.attributes?.get(d)??this.system.app.scripts.getSchema(i)?.attributes?.[d];if(u){if(u.type==="entity")this._resolveEntityScriptAttribute(u,d,h[d],c,n||o,t);else if(u.type==="json"&&Array.isArray(u.schema)){const f=h[d],p=n?n[d]:o[d];for(let m=0;m<u.schema.length;m++){const _=u.schema[m];if(_.type==="entity")if(u.array)for(let g=0;g<f.length;g++)this._resolveEntityScriptAttribute(_,_.name,f[g][_.name],c,p[g],t);else this._resolveEntityScriptAttribute(_,_.name,f[_.name],c,p,t)}}}}}}move(e,t){const s=this._scripts.length;if(t>=s||t<0)return!1;let i=e,r=e;typeof r!="string"?r=e.__name:i=null;const a=this._scriptsIndex[r];if(!a||!a.instance)return!1;const n=a.instance;if(i&&!(n instanceof i))return!1;const o=this._scripts.indexOf(n);return o===-1||o===t?!1:(this._scripts.splice(t,0,this._scripts.splice(o,1)[0]),this._resetExecutionOrder(0,s),this._updateList.sort(),this._postUpdateList.sort(),this.fire("move",r,n,t,o),this.fire(`move:${r}`,n,t,o),!0)}}class Jz{enabled=!0}const eV="_onInitializeAttributes",tV="_onInitialize",sV="_onPostInitialize",iV="_onUpdate",rV="_onPostUpdate";let ad=0;class aV extends Tt{constructor(e){super(e),this.id="script",this.ComponentType=Qz,this.DataType=Jz,this._components=new zd({sortBy:"_executionOrder"}),this._enabledComponents=new zd({sortBy:"_executionOrder"}),this.preloading=!0,this.on("beforeremove",this._onBeforeRemove,this),this.app.systems.on("initialize",this._onInitialize,this),this.app.systems.on("postInitialize",this._onPostInitialize,this),this.app.systems.on("update",this._onUpdate,this),this.app.systems.on("postUpdate",this._onPostUpdate,this)}initializeComponentData(e,t){if(e._executionOrder=ad++,this._components.append(e),ad>Number.MAX_SAFE_INTEGER&&this._resetExecutionOrder(),e.enabled=t.hasOwnProperty("enabled")?!!t.enabled:!0,e.enabled&&e.entity.enabled&&this._enabledComponents.append(e),t.hasOwnProperty("order")&&t.hasOwnProperty("scripts")){e._scriptsData=t.scripts;for(let s=0;s<t.order.length;s++)e.create(t.order[s],{enabled:t.scripts[t.order[s]].enabled,attributes:t.scripts[t.order[s]].attributes,preloading:this.preloading})}}cloneComponent(e,t){const s=[],i={};for(let a=0;a<e.script._scripts.length;a++){const n=e.script._scripts[a],o=n.__scriptType.__name;s.push(o);const c=e.script._attributeDataMap?.get(o)||{};for(const h in n.__attributes)c[h]=n.__attributes[h];i[o]={enabled:n._enabled,attributes:c}}for(const a in e.script._scriptsIndex)a.awaiting&&s.splice(a.ind,0,a);const r={enabled:e.script.enabled,order:s,scripts:i};return this.addComponent(t,r)}_resetExecutionOrder(){ad=0;for(let e=0,t=this._components.length;e<t;e++)this._components.items[e]._executionOrder=ad++}_callComponentMethod(e,t,s){for(e.loopIndex=0;
13428e.loopIndex<e.length;e.loopIndex++)e.items[e.loopIndex][t](s)}_onInitialize(){this.preloading=!1,this._callComponentMethod(this._components,eV),this._callComponentMethod(this._enabledComponents,tV)}_onPostInitialize(){this._callComponentMethod(this._enabledComponents,sV)}_onUpdate(e){this._callComponentMethod(this._enabledComponents,iV,e)}_onPostUpdate(e){this._callComponentMethod(this._enabledComponents,rV,e)}_addComponentToEnabled(e){this._enabledComponents.insert(e)}_removeComponentFromEnabled(e){this._enabledComponents.remove(e)}_onBeforeRemove(e,t){this._components.items.indexOf(t)>=0&&t._onBeforeRemove(),this._removeComponentFromEnabled(t),this._components.remove(t)}destroy(){super.destroy(),this.app.systems.off("initialize",this._onInitialize,this),this.app.systems.off("postInitialize",this._onPostInitialize,this),this.app.systems.off("update",this._onUpdate,this),this.app.systems.off("postUpdate",this._onPostUpdate,this)}}const nV=new j;let sm=new Uint32Array(0);const im=[0,0];class g0{device;resource;node;lodIndex;placementId;allocId;parentPlacementId;numSplats;activeSplats=0;intervals=[];intervalOffsets=[];intervalAllocIds=[];intervalNodeIndices=[];previousWorldTransform=new Z;aabb=new Le;subDrawTexture=null;subDrawCount=0;numBoundsEntries=0;boundsBaseIndex=0;octreeNodes=null;nodeInfos=null;colorAccumulatedTranslation=0;parameters=null;getWorkBufferModifier=null;getInstanceStreams=null;_consumeRenderDirty=null;constructor(e,t,s,i=null,r=null,a=null){this.device=e,this.resource=t,this.node=s.node,this.lodIndex=s.lodIndex,this.placementId=s.id,this.allocId=s.allocId,this.parentPlacementId=r&&s.parentPlacement?s.parentPlacement.allocId:s.allocId,this.numSplats=t.numSplats,this.aabb.copy(s.aabb),this.parameters=s.parameters,this.getWorkBufferModifier=()=>s.workBufferModifier,this.getInstanceStreams=()=>s.streams,this._consumeRenderDirty=i,this.octreeNodes=r,this.nodeInfos=a,this.updateIntervals(s.intervals)}destroy(){this.intervals.length=0,this.intervalOffsets.length=0,this.intervalAllocIds.length=0,this.intervalNodeIndices.length=0,this.subDrawTexture?.destroy(),this.subDrawTexture=null,this.subDrawCount=0}setLayout(e){this.intervalOffsets=e,this.subDrawTexture?.destroy(),this.subDrawTexture=null,this.subDrawCount=0}ensureSubDrawTexture(e){!this.subDrawTexture&&e>0&&this.updateSubDraws(e)}updateIntervals(e){const t=this.resource;if(this.intervals.length=0,this.intervalAllocIds.length=0,this.intervalNodeIndices.length=0,this.activeSplats=t.numSplats,e.size>0){let s=0,i=0;this.intervals.length=e.size*2;for(const[r,a]of e)this.intervals[i++]=a.x,this.intervals[i++]=a.y+1,s+=a.y-a.x+1,this.nodeInfos&&(this.intervalAllocIds.push(this.nodeInfos[r].allocId),this.intervalNodeIndices.push(r));this.octreeNodes?(this.activeSplats=s,this.numBoundsEntries=this.octreeNodes.length):s===this.numSplats?this.intervals.length=0:this.activeSplats=s}else{this.numBoundsEntries=1,this.intervalAllocIds.push(this.allocId);const s=t.maxSplats;s&&this.activeSplats<s&&(this.intervals[0]=0,this.intervals[1]=this.activeSplats)}}appendSubDraws(e,t,s,i,r,a){let n=i,o=r/a|0;const c=r%a;if(c>0){const d=Math.min(n,a-c),u=t*4;e[u]=o|65536,e[u+1]=c,e[u+2]=c+d,e[u+3]=s,t++,s+=d,n-=d,o++}const h=n/a|0;if(h>0){const d=t*4;e[d]=o|h<<16,e[d+1]=0,e[d+2]=a,e[d+3]=s,t++,s+=h*a,n-=h*a,o+=h}if(n>0){const d=t*4;e[d]=o|65536,e[d+1]=0,e[d+2]=n,e[d+3]=s,t++}return t}updateSubDraws(e){let t=this.intervals,s=t.length/2;s===0&&(im[0]=0,im[1]=this.activeSplats,t=im,s=1);const r=s*3*4;sm.length<r&&(sm=new Uint32Array(r));const a=sm;let n=0;for(let d=0;d<s;d++)n=this.appendSubDraws(a,n,t[d*2],t[d*2+1]-t[d*2],this.intervalOffsets[d],e);this.subDrawCount=n;const{x:o,y:c}=Xt.calcTextureSize(n,nV);this.subDrawTexture=ce.createDataTexture2D(this.device,"subDrawData",o,c,Wt),this.subDrawTexture.lock().set(a.subarray(0,n*4)),this.subDrawTexture.unlock()}update(){const e=this.node.getWorldTransform(),t=!this.previousWorldTransform.equals(e);t&&this.previousWorldTransform.copy(e);const s=this._consumeRenderDirty?this._consumeRenderDirty():!1;return t||s}writeBoundsSpheres(e,t){if(this.octreeNodes)for(let s=0;s<this.octreeNodes.length;s++){const i=this.octreeNodes[s].boundingSphere;e[t++]=i.x,e[t++]=i.y,e[t++]=i.z,e[t++]=i.w}
13428else{const s=this.resource.aabb,i=s.halfExtents,r=Math.sqrt(i.x*i.x+i.y*i.y+i.z*i.z);e[t++]=s.center.x,e[t++]=s.center.y,e[t++]=s.center.z,e[t++]=r}}get hasSphericalHarmonics(){return this.resource.gsplatData?.shBands>0}}function oV(){const l=typeof self<"u"&&self||require("node:worker_threads").parentPort,e=new Map;let t,s,i,r,a=!1,n=!1;const o=32,c=new Float32Array(o+1),h=new Float32Array(o+1),d=new GSplatSortBinWeights,u=S=>{for(let T=0;T<o;T++)c[T]=S[T*2],h[T]=S[T*2+1];c[o]=c[o-1]+h[o-1],h[o]=0},f=(S,T,w,C,b,I,P)=>{const{ids:L,intervals:O}=I,D=o/w;let N=0;for(let k=0;k<S.length;k++){const A=S[k],M=L[k],R=e.get(M);R||console.error("UnifiedSortWorker: No centers found for id",M);const F=O[k].length>0?O[k]:[0,R.length/3];for(let U=0;U<F.length;U+=2){const B=F[U]*3,z=F[U+1]*3;N=P(R,A,B,z,N,D,T,w,C,b)}}},p=(S,T,w,C,b,I)=>{f(S,T,w,C,b,I,(P,L,O,D,N,k,A,M,R,F)=>{const{transformedDirection:U,offset:B,scale:z}=L,$=U.x,K=U.y,Y=U.z,te=$*z,J=K*z,_e=Y*z,Ae=B-A;for(let we=O;we<D;we+=3){const $e=P[we],Ye=P[we+1],Ee=P[we+2],ke=($e*te+Ye*J+Ee*_e+Ae)*k,ps=ke>>>0,se=c[ps]+h[ps]*(ke-ps)>>>0;R[N++]=se,F[se]++}return N})},m=(S,T,w,C,b,I)=>{f(S,T,w,C,b,I,(P,L,O,D,N,k,A,M,R,F)=>{const{transformedPosition:U,scale:B}=L,z=U.x,$=U.y,K=U.z;for(let Y=O;Y<D;Y+=3){const te=P[Y]-z,J=P[Y+1]-$,_e=P[Y+2]-K,Ae=te*te+J*J+_e*_e,we=Math.sqrt(Ae)*B,Ye=(M-we)*k,Ee=Ye>>>0,Pe=c[Ee]+h[Ee]*(Ye-Ee)>>>0;R[N++]=Pe,F[Pe]++}return N})},_=(S,T,w,C,b)=>{for(let P=1;P<S;P++)T[P]+=T[P-1];const I=T[S-1];I!==w&&!n&&(n=!0,console.warn(`[SortWorker] ${w-I} splats lost due to sortKey overflow. Check resource AABB bounds contain all the splats.`));for(let P=0;P<w;P++){const L=C[P],O=--T[L];b[O]=r[P]}},g=S=>{let T=1/0,w=-1/0;for(let C=0;C<S.length;C++){const b=S[C],{transformedDirection:I,offset:P,scale:L,aabbMin:O,aabbMax:D}=b,N=I.x,k=I.y,A=I.z,M=N>=0?O[0]:D[0],R=k>=0?O[1]:D[1],F=A>=0?O[2]:D[2],U=N>=0?D[0]:O[0],B=k>=0?D[1]:O[1],z=A>=0?D[2]:O[2],$=M*N+R*k+F*A,K=U*N+B*k+z*A,Y=$*L+P,te=K*L+P,J=Math.min(Y,te),_e=Math.max(Y,te);J<T&&(T=J),_e>w&&(w=_e)}return T===1/0&&(T=0,w=0),{minDist:T,maxDist:w}},v=S=>{let T=-1/0;for(let C=0;C<S.length;C++){const b=S[C],{transformedPosition:I,scale:P,aabbMin:L,aabbMax:O}=b,D=I.x,N=I.y,k=I.z;for(let A=0;A<8;A++){const M=A&1?O[0]:L[0],R=A&2?O[1]:L[1],F=A&4?O[2]:L[2],U=M-D,B=R-N,z=F-k,$=U*U+B*B+z*z,K=Math.sqrt($)*P;K>T&&(T=K)}}const w=0;return T<0&&(T=0),{minDist:w,maxDist:T}},x=(S,T,w)=>{const C=performance.now(),{minDist:b,maxDist:I}=a?v(S):g(S),P=w.totalActiveSplats,O=2**Math.max(10,Math.min(20,Math.round(Math.log2(P/4))))+1;s?.length!==P&&(s=new Uint32Array(P)),!i||i.length!==O?i=new Uint32Array(O):i.fill(0);const D=I-b,N=GSplatSortBinWeights.computeCameraBin(a,b,D),k=d.compute(N,O);u(k),a?m(S,b,D,s,i,w):p(S,b,D,s,i,w),_(O,i,P,s,T);const A=P,M=performance.now()-C,R=[T.buffer],F={order:T.buffer,count:A,version:w.version,sortTime:M};l.postMessage(F,R)},y=S=>{const{ids:T,pixelOffsets:w,intervals:C,totalActiveSplats:b}=S;(!r||r.length<b)&&(r=new Uint32Array(b));let I=0;for(let P=0;P<T.length;P++){const L=e.get(T[P]),O=w[P],D=C[P].length>0?C[P]:[0,L.length/3];for(let N=0;N<D.length;N+=2){let k=O[N/2];const A=D[N+1]-D[N];for(let M=0;M<A;M++)r[I++]=k++}}};l.addEventListener("message",S=>{const T=S.data??S;switch(T.command){case"addCenters":{e.set(T.id,new Float32Array(T.centers));break}case"removeCenters":{e.delete(T.id);break}case"sort":{a=T.radialSorting||!1;const w=new Uint32Array(T.order);x(T.sortParams,w,t);break}case"intervals":{t=T,y(t);break}}})}let Vl=class Gl{static get NUM_BINS(){return 32}static get WEIGHT_TIERS(){return[{maxDistance:0,weight:40},{maxDistance:2,weight:20},{maxDistance:5,weight:8},{maxDistance:10,weight:3},{maxDistance:1/0,weight:1}]}constructor(){const e=Gl.NUM_BINS,t=Gl.WEIGHT_TIERS;this.binWeights=new Float32Array(e*2),this.bitsPerBin=new Float32Array(e),this.weightByDistance=new Float32Array(e);for(let s=0;s<e;s++){let i=1;for(let r=0;r<t.length;r++)if(s<=t[r].maxDistance){i=t[r].weight;break}this.weightByDistance[s]=i}this.lastCameraBin=-1,this.lastBucketCount=-1}static computeCameraBin(e,t,s){const i=Gl.NUM_BINS;if(e)return i-1;const a=-t/s*i;return Math.max(0,Math.min(i-1,Math.floor(a)))}compute(e,t){if(e===this.lastCameraBin&&t===this.lastBucketCount)return this.binWeights;this.lastCameraBin=e,this.lastBucketCount=t;const s=Gl.NUM_BINS,i=this.bitsPerBin;for(let n=0;n<s;n++){const o=Math.abs(n-e);i[n]=this.weightByDistance[o]}let r=0;for(let n=0;n<s;n++)r+=i[n];let a=0;for(let n=0;n<s;n++){const o=Math.max(1,Math.floor(i[n]/r*t));this.binWeights[n*2]=a,this.binWeights[n*2+1]=o,a+=o}if(a>t){const n=a-t,o=(s-1)*2+1;this.binWeights[o]=Math.max(1,this.binWeights[o]-n)}return this.binWeights}};const rm=new Set;class lV extends ge{worker;bufferLength=0;availableOrderData=[];jobsInFlight=0;hasNewVersion=!1;pendingSorted=null;centersSet=new Set;_destroyed=!1;scene=null;constructor(e){super(),this.scene=e??null;const t=` 13429 const GSplatSortBinWeights = ${Vl.toString()}; 13430 (${oV.toString()})() 13431 `;Ce.environment==="node"?(this.worker=new Worker(t,{eval:!0}),this.worker.on("message",this.onSorted.bind(this))):(this.worker=new Worker(URL.createObjectURL(new Blob([t],{type:"application/javascript"}))),this.worker.addEventListener("message",this.onSorted.bind(this)))}onSorted(e){if(this._destroyed)return;const t=e.data??e;this.scene&&t.sortTime!==void 0&&this.scene.fire("gsplat:sorted",t.sortTime);const s=new Uint32Array(t.order);this.jobsInFlight--,this.pendingSorted&&this.releaseOrderData(this.pendingSorted.orderData),this.pendingSorted={count:t.count,version:t.version,orderData:s}}applyPendingSorted(){if(this.pendingSorted){const{count:e,version:t,orderData:s}=this.pendingSorted;this.pendingSorted=null,this.fire("sorted",e,t,s),this.releaseOrderData(s)}}releaseOrderData(e){e.length===this.bufferLength&&this.availableOrderData.push(e)}destroy(){this._destroyed=!0,this.pendingSorted=null,this.worker.terminate(),this.worker=null}setCenters(e,t){if(t){if(!this.centersSet.has(e)){this.centersSet.add(e);const s=t.buffer.slice();this.worker.postMessage({command:"addCenters",id:e,centers:s},[s])}}else this.centersSet.has(e)&&(this.centersSet.delete(e),this.worker.postMessage({command:"removeCenters",id:e}))}updateCentersForSplats(e){for(const t of e){const s=t.resource.id;rm.add(s),this.centersSet.has(s)||this.setCenters(s,t.resource.centers)}for(const t of this.centersSet)rm.has(t)||this.setCenters(t,null);rm.clear()}setSortParameters(e){this.hasNewVersion=!0;const{textureSize:t}=e,s=t*t;s!==this.bufferLength&&(this.bufferLength=s,this.availableOrderData.length=0),this.worker.postMessage(e)}setSortParams(e,t){if(this.hasNewVersion||this.jobsInFlight===0){let s=this.availableOrderData.pop();s||(s=new Uint32Array(this.bufferLength)),this.jobsInFlight++,this.hasNewVersion=!1,this.worker.postMessage({command:"sort",sortParams:e,radialSorting:t,order:s.buffer},[s.buffer])}}}var _C=` 13432#include "tonemappingPS" 13433#include "decodePS" 13434#include "gammaPS" 13435#include "fogPS" 13436#if FOG != NONE && !defined(GSPLAT_NO_FOG) 13437 #define GSPLAT_FOG 13438#endif 13439fn prepareOutputFromGamma(gammaColor: vec3f, depth: f32) -> vec3f { 13440 var color = gammaColor; 13441 #if TONEMAP != NONE || GAMMA == NONE || defined(GSPLAT_FOG) 13442 color = decodeGamma3(color); 13443 #endif 13444 #ifdef GSPLAT_FOG 13445 color = addFog(color, depth); 13446 #endif 13447 #if TONEMAP != NONE 13448 color = toneMap(color); 13449 #endif 13450 #if TONEMAP != NONE || (GAMMA != NONE && defined(GSPLAT_FOG)) 13451 color = gammaCorrectOutput(color); 13452 #endif 13453 return color; 13454} 13455`;class Qg{device;node;cameraNode;layer;workBuffer;renderMode;_workBufferFormatVersion=-1;fisheyeProj=new sw;constructor(e,t,s,i,r){this.device=e,this.node=t,this.cameraNode=s,this.layer=i,this.workBuffer=r,this._workBufferFormatVersion=r?.format.extraStreamsVersion??-1}destroy(){}setRenderMode(e){this.renderMode=e}get material(){return null}setDataSource(e){this.workBuffer=e,this.onWorkBufferFormatChanged()}onWorkBufferFormatChanged(){}update(e,t){}setGpuSortedRendering(e,t,s,i){}setCpuSortedRendering(){}setOrderData(){}
13455frameUpdate(e,t,s){}updateOverdrawMode(e){}_createTonemapIncludes(e){e.set("gsplatOutputVS",_C);const t=["tonemappingPS","tonemappingNonePS","tonemappingLinearPS","tonemappingFilmicPS","tonemappingHejlPS","tonemappingAcesPS","tonemappingAces2PS","tonemappingNeutralPS","decodePS","gammaPS"];for(const s of t)e.set(s,Kl[s])}}class cV extends Qg{_material;meshInstance;originalBlendType=nn;_internalDefines=new Set;forceCopyMaterial=!0;_lastFisheyeEnabled=!1;_lastSourceChunksKey="";constructor(e,t,s,i,r){super(e,t,s,i,r),this._material=new ei({uniqueName:"UnifiedSplatMaterial",vertexGLSL:'#include "gsplatVS"',fragmentGLSL:'#include "gsplatPS"',vertexWGSL:'#include "gsplatVS"',fragmentWGSL:'#include "gsplatPS"',attributes:{vertex_position:Ie}}),this._material.setDefine("{GSPLAT_INSTANCE_SIZE}",Rt.instanceSize),this.configureMaterial(),this._material.defines.forEach((a,n)=>{this._internalDefines.add(n)}),this._internalDefines.add("{GSPLAT_INSTANCE_SIZE}"),this._internalDefines.add("GSPLAT_UNIFIED_ID"),this._internalDefines.add("PICK_CUSTOM_ID"),this._internalDefines.add("GSPLAT_INDIRECT_DRAW"),this._internalDefines.add("GSPLAT_SEPARATE_OPACITY"),this._internalDefines.add("GSPLAT_FISHEYE"),this.meshInstance=this.createMeshInstance()}setRenderMode(e){const t=this.renderMode??0,s=(t&xs)!==0,i=(t&ho)!==0,r=(e&xs)!==0,a=(e&ho)!==0;this.meshInstance.castShadow=a,s&&!r&&this.layer.removeMeshInstances([this.meshInstance],!0),i&&!a&&this.layer.removeShadowCasters([this.meshInstance]),!s&&r&&this.layer.addMeshInstances([this.meshInstance],!0),!i&&a&&this.layer.addShadowCasters([this.meshInstance]),super.setRenderMode(e)}destroy(){this.renderMode&&(this.renderMode&xs&&this.layer.removeMeshInstances([this.meshInstance],!0),this.renderMode&ho&&this.layer.removeShadowCasters([this.meshInstance])),this._material.destroy(),this.meshInstance.destroy(),super.destroy()}get material(){return this._material}onWorkBufferFormatChanged(){this.configureMaterial()}configureMaterial(){const{workBuffer:e}=this;this._injectFormatChunks(),this._material.setDefine("SH_BANDS","0"),this._material.setDefine("GSPLAT_SEPARATE_OPACITY","");const t=e.format.getStream("dataColor");t&&t.format!==Vi&&this._material.setDefine("GSPLAT_COLOR_FLOAT",""),this._updateIdDefines(),this._bindWorkBufferTextures(),this._material.setParameter("numSplats",0),this.setOrderData(),this._material.setDefine("DITHER_NONE",""),this._material.cull=Yt,this._material.blendType=Ui,this._material.depthWrite=!1,this._material.update()}_bindWorkBufferTextures(){const{workBuffer:e}=this;for(const t of e.format.resourceStreams){const s=e.getTexture(t.name);s&&this._material.setParameter(t.name,s)}}_injectFormatChunks(){const e=this.device.isWebGPU?this._material.shaderChunks.wgsl:this._material.shaderChunks.glsl,t=this.workBuffer.format;e.set("gsplatDeclarationsVS",t.getInputDeclarations()),e.set("gsplatReadVS",t.getReadCode())}update(e,t){this.meshInstance.instancingCount=Math.ceil(e/Rt.instanceSize),this._material.setParameter("numSplats",e),this._material.setParameter("splatTextureSize",t),this.meshInstance.visible=e>0}setGpuSortedRendering(e,t,s,i){this.meshInstance.setIndirect(null,e,1),this._material.setParameter("compactedSplatIds",t),this._material.setParameter("numSplatsStorage",s),this._material.getDefine("GSPLAT_INDIRECT_DRAW")||(this._material.setDefine("GSPLAT_INDIRECT_DRAW",!0),this._material.update()),this._material.setParameter("splatTextureSize",i),this.meshInstance.visible=!0,this.meshInstance.instancingCount<=0&&(this.meshInstance.instancingCount=1)}setCpuSortedRendering(){this.meshInstance.setIndirect(null,-1),this._material.getDefine("GSPLAT_INDIRECT_DRAW")&&(this._material.setDefine("GSPLAT_INDIRECT_DRAW",!1),this._material.update()),this.setOrderData(),this.meshInstance.visible=!1}setOrderData(){this.device.isWebGPU?this._material.setParameter("splatOrder",this.workBuffer.orderBuffer):this._material.setParameter("splatOrder",this.workBuffer.orderTexture)}frameUpdate(e){e.colorRamp&&this._material.setParameter("colorRampIntensity",e.colorRampIntensity);const t=this.cameraNode.camera;this.fisheyeProj.update(e.fisheye,t.fov,t.projectionMatrix);const s=this.fisheyeProj.enabled;if(s!==this._lastFisheyeEnabled&&(this._lastFisheyeEnabled=s,this._material.setDefine("GSPLAT_FISHEYE",s),this._material.update(
13455)),s){const r=this.fisheyeProj;this._material.setParameter("fisheye_k",r.k),this._material.setParameter("fisheye_inv_k",r.invK),this._material.setParameter("fisheye_projMat00",r.projMat00),this._material.setParameter("fisheye_projMat11",r.projMat11)}const i=!e.useFog;i!==this._lastNoFog&&(this._lastNoFog=i,this._material.setDefine("GSPLAT_NO_FOG",i),this._material.update()),this._syncWithWorkBufferFormat(),(this.forceCopyMaterial||e.material.dirty)&&(this.copyMaterialSettings(e.material),this.forceCopyMaterial=!1)}_updateIdDefines(){const e=!!this.workBuffer.format.getStream("pcId");this._material.setDefine("GSPLAT_UNIFIED_ID",e),this._material.setDefine("PICK_CUSTOM_ID",e)}_syncWithWorkBufferFormat(){const e=this.workBuffer.format;this._workBufferFormatVersion!==e.extraStreamsVersion&&(this._workBufferFormatVersion=e.extraStreamsVersion,this.workBuffer.syncWithFormat(),this._injectFormatChunks(),this._bindWorkBufferTextures(),this._updateIdDefines(),this._material.update())}copyMaterialSettings(e){const t=[];this._material.defines.forEach((i,r)=>{!this._internalDefines.has(r)&&!e.defines.has(r)&&t.push(r)}),t.forEach(i=>this._material.setDefine(i,void 0)),e.defines.forEach((i,r)=>{this._material.setDefine(r,i)});const s=e.parameters;for(const i in s)s.hasOwnProperty(i)&&this._material.setParameter(i,s[i].data);if(e.hasShaderChunks){const i=e.shaderChunks.key;i!==this._lastSourceChunksKey&&(this._material.shaderChunks.copy(e.shaderChunks),this._injectFormatChunks(),this._lastSourceChunksKey=i)}this._material.update()}updateOverdrawMode(e){const t=!!e.colorRamp,s=this._material.getDefine("GSPLAT_OVERDRAW");t&&(this._material.setParameter("colorRamp",e.colorRamp),this._material.setParameter("colorRampIntensity",e.colorRampIntensity)),t!==s&&(this._material.setDefine("GSPLAT_OVERDRAW",t),t?(this.originalBlendType=this._material.blendType,this._material.blendType=nn):this._material.blendType=this.originalBlendType,this._material.update())}createMeshInstance(){const e=Rt.createMesh(this.device),t=new Ne(e,this._material);t.node=this.node,t.setInstancing(!0,!0),t.instancingCount=0;const s=this.cameraNode.camera;return t.isVisibleFunc=i=>{const r=this.renderMode??0;return s.camera===i&&r&xs?!0:r&ho?i.node?.name===kg:!1},t}}
13455const Tu=8,v0=new Z,hV=new Z;class dV extends Qg{_material;meshInstance;_pickMaterial=null;_pickMeshInstance=null;_clipToViewZ=new Float32Array(4);_clipToViewZPick=null;originalBlendType=nn;_internalDefines=new Set;forceCopyMaterial=!0;constructor(e,t,s,i,r){super(e,t,s,i,r),this._material=new ei({uniqueName:"UnifiedSplatHybridMaterial",vertexWGSL:'#include "gsplatHybridVS"',fragmentWGSL:'#include "gsplatPS"',attributes:{vertex_position:Ie}}),this._material.setDefine("{GSPLAT_INSTANCE_SIZE}",Rt.instanceSize),this._material.setDefine("{CACHE_STRIDE}",Tu),this.configureMaterial(),this._material.defines.forEach((a,n)=>{this._internalDefines.add(n)}),this._internalDefines.add("{GSPLAT_INSTANCE_SIZE}"),this._internalDefines.add("{CACHE_STRIDE}"),this._internalDefines.add("GSPLAT_UNIFIED_ID"),this._internalDefines.add("PICK_CUSTOM_ID"),this._internalDefines.add("GSPLAT_OVERDRAW"),this._internalDefines.add("GSPLAT_NO_FOG"),this.meshInstance=this.createMeshInstance()}setRenderMode(e){const s=((this.renderMode??0)&xs)!==0,i=(e&xs)!==0;s&&!i&&this.layer.removeMeshInstances([this.meshInstance],!0),!s&&i&&this.layer.addMeshInstances([this.meshInstance],!0),super.setRenderMode(e)}destroy(){this.renderMode&&this.renderMode&xs&&this.layer.removeMeshInstances([this.meshInstance],!0),this._material.destroy(),this._pickMaterial?.destroy(),this.meshInstance.destroy(),this._pickMeshInstance?.destroy(),super.destroy()}get material(){return this._material}onWorkBufferFormatChanged(){this.configureMaterial()}configureMaterial(){this._material.setDefine("SH_BANDS","0"),this._material.setDefine("GSPLAT_INDIRECT_DRAW",!0),this._updateIdDefines(this._material),this._material.setDefine("DITHER_NONE",""),this._material.cull=Yt,this._material.blendType=Ui,this._material.depthWrite=!1,this._material.update()}update(e,t){this.meshInstance.instancingCount<=0&&(this.meshInstance.instancingCount=1),this.meshInstance.visible=e>0}setHybridSortedRendering(e,t,s,i){this.meshInstance.setIndirect(null,e,1),this._material.setParameter("sortedIndices",t),this._material.setParameter("projCache",s),this._material.setParameter("numSplatsStorage",i),this._computeClipToViewZ(this.cameraNode,this._clipToViewZ),this._material.setParameter("clipToViewZ",this._clipToViewZ),this.meshInstance.visible=!0,this.meshInstance.instancingCount<=0&&(this.meshInstance.instancingCount=1)}prepareForPicking(e,t,s,i,r,a,n){if(this._pickMaterial)this._updateIdDefines(this._pickMaterial)&&this._pickMaterial.update();else{this._pickMaterial=new ei({uniqueName:"UnifiedSplatHybridPickMaterial",vertexWGSL:'#include "gsplatHybridVS"',fragmentWGSL:'#include "gsplatPS"',attributes:{vertex_position:Ie}}),this._pickMaterial.setDefine("{GSPLAT_INSTANCE_SIZE}",Rt.instanceSize),this._pickMaterial.setDefine("{CACHE_STRIDE}",Tu),this._pickMaterial.setDefine("SH_BANDS","0"),this._pickMaterial.setDefine("GSPLAT_INDIRECT_DRAW",!0),this._pickMaterial.setDefine("DITHER_NONE",""),this._updateIdDefines(this._pickMaterial),this._pickMaterial.cull=Yt,this._pickMaterial.blendType=Ns,this._pickMaterial.depthWrite=!1,this._pickMaterial.update();const h=Rt.createMesh(this.device);this._pickMeshInstance=new Ne(h,this._pickMaterial),this._pickMeshInstance.node=this.node,this._pickMeshInstance.setInstancing(!0,!0),this._pickMeshInstance.instancingCount=1}const o=this._pickMaterial,c=this._pickMeshInstance;return c.setIndirect(null,e,1),o.setParameter("sortedIndices",t),o.setParameter("projCache",s),o.setParameter("numSplatsStorage",i),o.setParameter("alphaClip",r),o.setParameter("alphaClipForward",a),this._clipToViewZPick??(this._clipToViewZPick=new Float32Array(4)),this._computeClipToViewZ(n,this._clipToViewZPick),o.setParameter("clipToViewZ",this._clipToViewZPick),c}_computeClipToViewZ(e,t){const s=e.camera,i=s.camera;if(this.fisheyeProj.enabled){const n=i.nearClip,o=i.farClip;t[0]=0,t[1]=0,t[2]=o-n,t[3]=n;return}const r=!!s.renderTarget?.flipY;v0.copy(cs.applyShaderProjectionTransform(i.projectionMatrix,hV,r,this.device.isWebGPU)).invert();const a=v0.data;t[0]=-a[2],t[1]=-a[6],t[2]=-a[10],t[3]=-a[14]}setCpuSortedRendering(){this.meshInstance.setIndirect(null,-1),this.meshInstance.visible=!1}setOrderData(){}frameUpdate(e){this._material.setParameter("alphaClip",e.alphaClip),this._material.setParameter("alphaClipForward",e.alphaClipForward),this._pickMaterial?.setParameter("alphaClip",e.alphaClip),this._pickMaterial?.setParameter("alphaClipForward",e.alphaClipForward),e.colorRamp&&this._material.setParameter("colorRampIntensity",e.colorRampIntensity);const t=!e.useFog;t!==this._lastNoFog&&(this._lastNoFog=t,this._material.setDefine("GSPLAT_NO_FOG",t),this._material.update(
13455))}_updateIdDefines(e){const t=!!this.workBuffer.format.getStream("pcId"),s=e.getDefine("GSPLAT_UNIFIED_ID")!==t||e.getDefine("PICK_CUSTOM_ID")!==t;return e.setDefine("GSPLAT_UNIFIED_ID",t),e.setDefine("PICK_CUSTOM_ID",t),s}updateOverdrawMode(e){const t=!!e.colorRamp,s=this._material.getDefine("GSPLAT_OVERDRAW");t&&(this._material.setParameter("colorRamp",e.colorRamp),this._material.setParameter("colorRampIntensity",e.colorRampIntensity)),t!==s&&(this._material.setDefine("GSPLAT_OVERDRAW",t),t?(this.originalBlendType=this._material.blendType,this._material.blendType=nn):this._material.blendType=this.originalBlendType,this._material.update())}createMeshInstance(){const e=Rt.createMesh(this.device),t=new Ne(e,this._material);t.node=this.node,t.setInstancing(!0,!0),t.instancingCount=0,t.pick=!1;const s=this.cameraNode.camera;return t.isVisibleFunc=i=>{const r=this.renderMode??0;return s.camera===i&&r&xs?!0:(i.node?.name===kg,!1)},t}}class uV extends gn{renderer;constructor(e){super(e.device),this.renderer=e,this.name="FramePassGSplatComputeLocal"}frameUpdate(){const e=this.renderer,t=e.cameraNode.camera,s=t.renderTarget,i=s?s.width:this.device.width,r=s?s.height:this.device.height,a=t.rect,n=Math.floor(i*a.z),o=Math.floor(r*a.w);e.resizeOutputTexture(n,o)}execute(){this.renderer.dispatch()}}const fV=` 13456@group(0) @binding(0) var<storage, read> sortElementCount: array<u32>; 13457@group(0) @binding(1) var<storage, read_write> dispatchArgs: array<u32>; 13458@compute @workgroup_size(1) 13459fn main() { 13460 let count = sortElementCount[0]; 13461 let maxDim = {MAX_DIM}u; 13462 let countWg = (count + {SPLATS_PER_WG_MINUS_1}u) / {SPLATS_PER_WG}u; 13463 if (countWg <= maxDim) { 13464 dispatchArgs[0] = countWg; 13465 dispatchArgs[1] = 1u; 13466 } else { 13467 let y = (countWg + maxDim - 1u) / maxDim; 13468 let x = (countWg + y - 1u) / y; 13469 dispatchArgs[0] = x; 13470 dispatchArgs[1] = y; 13471 } 13472 dispatchArgs[2] = 1u; 13473 let placeWg = (count + 255u) / 256u; 13474 if (placeWg <= maxDim) { 13475 dispatchArgs[3] = placeWg; 13476 dispatchArgs[4] = 1u; 13477 } else { 13478 let y = (placeWg + maxDim - 1u) / maxDim; 13479 let x = (placeWg + y - 1u) / y; 13480 dispatchArgs[3] = x; 13481 dispatchArgs[4] = y; 13482 } 13483 dispatchArgs[5] = 1u; 13484} 13485`,pV=` 13486@group(0) @binding(0) var<storage, read> countersBuffer: array<u32>; 13487@group(0) @binding(1) var<storage, read_write> dispatchArgs: array<u32>; 13488@group(0) @binding(2) var<storage, read> largeSplatIds: array<u32>; 13489@compute @workgroup_size(1) 13490fn main() { 13491 let count = min(countersBuffer[1], arrayLength(&largeSplatIds)); 13492 let maxDim = {MAX_DIM}u; 13493 if (count <= maxDim) { 13494 dispatchArgs[0] = count; 13495 dispatchArgs[1] = 1u; 13496 } else { 13497 let y = (count + maxDim - 1u) / maxDim; 13498 let x = (count + y - 1u) / y; 13499 dispatchArgs[0] = x; 13500 dispatchArgs[1] = y; 13501 } 13502 dispatchArgs[2] = 1u; 13503} 13504`,mV=` 13505#include "gsplatCommonCS" 13506#include "gsplatTileIntersectCS" 13507const MAX_TILE_ENTRIES: u32 = 0xFFFFu; 13508const BITMASK_W: u32 = 8u; 13509const BITMASK_H: u32 = 4u; 13510const LARGE_AABB_THRESHOLD: u32 = 64u; 13511@group(0) @binding(0) var<storage, read> compactedSplatIds: array<u32>; 13512@group(0) @binding(1) var<storage, read> sortElementCount: array<u32>; 13513@group(0) @binding(2) var<storage, read_write> projCache: array<u32>; 13514@group(0) @binding(3) var<storage, read_write> tileSplatCounts: array<atomic<u32>>; 13515struct Uniforms { 13516 splatTextureSize: u32, 13517 numTilesX: u32, 13518 numTilesY: u32, 13519 viewProj: mat4x4f, 13520 viewMatrix: mat4x4f, 13521 focal: f32, 13522 viewportWidth: f32, 13523 viewportHeight: f32, 13524 nearClip: f32, 13525 farClip: f32, 13526 minPixelSize: f32, 13527 isOrtho: u32, 13528 exposure: f32, 13529 alphaClip: f32, 13530 minContribution: f32, 13531 #ifdef GSPLAT_FISHEYE 13532 fisheye_k: f32, 13533 fisheye_inv_k: f32, 13534 fisheye_projMat00: f32, 13535 fisheye_projMat11: f32, 13536 #endif 13537} 13538@group(0) @binding(4) var<uniform> uniforms: Uniforms; 13539@group(0) @binding(5) var<storage, read_write> pairBuffer: array<u32>; 13540@group(0) @binding(6) var<storage, read_write> countersBuffer: array<atomic<u32>>; 13541@group(0) @binding(7) var<storage, read_write> splatPairStart: array<u32>; 13542@group(0) @binding(8) var<storage, read_write> splatPairCount: array<u32>; 13543@group(0) @binding(9) var<storage, read_write> largeSplatIds: array<u32>; 13544@group(0) @binding(10) var<storage, read_write> depthBuffer: array<u32>; 13545#include "gsplatComputeSplatCS" 13546#include "gsplatFormatDeclCS" 13547#include "gsplatFormatReadCS" 13548#include "gsplatProjectCommonCS" 13549@compute @workgroup_size(256) 13550fn main( 13551 @builtin(global_invocation_id) gid: vec3u, 13552 @builtin(num_workgroups) numWorkgroups: vec3u 13553) { 13554 let threadIdx = gid.y * (numWorkgroups.x * 256u) + gid.x; 13555 let numVisible = sortElementCount[0]; 13556 let projected = projectSplatCommon( 13557 threadIdx, 13558 numVisible, 13559 uniforms.alphaClip, 13560 uniforms.minPixelSize, 13561 uniforms.minContribution, 13562 uniforms.viewMatrix, 13563 uniforms.viewProj, 13564 uniforms.focal, 13565 uniforms.viewportWidth,
13566 uniforms.viewportHeight, 13567 uniforms.nearClip, 13568 uniforms.farClip, 13569 uniforms.isOrtho, 13570 #ifdef GSPLAT_FISHEYE 13571 uniforms.fisheye_k, uniforms.fisheye_inv_k, 13572 uniforms.fisheye_projMat00, uniforms.fisheye_projMat11, 13573 #endif 13574 ); 13575 if (!projected.valid) { 13576 if (threadIdx < numVisible) { 13577 projCache[threadIdx * {CACHE_STRIDE}u + 6u] = 0u; 13578 splatPairStart[threadIdx] = 0u; 13579 splatPairCount[threadIdx] = 0u; 13580 } 13581 return; 13582 } 13583 let opacity = projected.opacity; 13584 let proj = projected.proj; 13585 let det = proj.a * proj.c - proj.b * proj.b; 13586 let invDet = 1.0 / det; 13587 let cx = 4.0 * proj.c * invDet; 13588 let cy = -4.0 * proj.b * invDet; 13589 let cz = 4.0 * proj.a * invDet; 13590 let base = threadIdx * {CACHE_STRIDE}u; 13591 projCache[base + 0u] = bitcast<u32>(proj.screen.x); 13592 projCache[base + 1u] = bitcast<u32>(proj.screen.y); 13593 projCache[base + 2u] = bitcast<u32>(cx); 13594 projCache[base + 3u] = bitcast<u32>(cy); 13595 projCache[base + 4u] = bitcast<u32>(cz); 13596#ifdef PICK_MODE 13597 let pcIdVal = loadPcId().r; 13598 projCache[base + 5u] = pcIdVal; 13599 projCache[base + 6u] = pack2x16float(vec2f(0.0, opacity)); 13600#else 13601 let color = getColor(); 13602 var rgb = max(color, vec3f(0.0)); 13603 projCache[base + 5u] = pack2x16float(vec2f(rgb.x, rgb.y)); 13604 projCache[base + 6u] = pack2x16float(vec2f(rgb.z, opacity)); 13605#endif 13606 depthBuffer[threadIdx] = bitcast<u32>(proj.viewDepth); 13607 let screen = proj.screen; 13608 let eval = computeSplatTileEval(screen, cx, cy, cz, half(opacity), 13609 uniforms.viewportWidth, uniforms.viewportHeight, 13610 uniforms.alphaClip); 13611 let radiusFactor = eval.radiusFactor; 13612 projCache[base + 7u] = bitcast<u32>(-0.5 * radiusFactor); 13613 let minTileX = max(0i, i32(floor(eval.splatMin.x / f32(TILE_SIZE)))); 13614 let maxTileX = min(i32(uniforms.numTilesX) - 1i, i32(floor(eval.splatMax.x / f32(TILE_SIZE)))); 13615 let minTileY = max(0i, i32(floor(eval.splatMin.y / f32(TILE_SIZE)))); 13616 let maxTileY = min(i32(uniforms.numTilesY) - 1i, i32(floor(eval.splatMax.y / f32(TILE_SIZE)))); 13617 let aabbW = u32(maxTileX - minTileX + 1i); 13618 var deferredToLarge = false; 13619 if (maxTileX >= minTileX && maxTileY >= minTileY && 13620 aabbW * u32(maxTileY - minTileY + 1i) > LARGE_AABB_THRESHOLD) { 13621 let idx = atomicAdd(&countersBuffer[1], 1u); 13622 if (idx < arrayLength(&largeSplatIds)) { 13623 largeSplatIds[idx] = threadIdx; 13624 deferredToLarge = true; 13625 } 13626 } 13627 if (deferredToLarge) { 13628 splatPairStart[threadIdx] = 0u; 13629 splatPairCount[threadIdx] = 0u; 13630 return; 13631 } 13632 var myPairCount: u32 = 0u; 13633 var bitmask: u32 = 0u; 13634 if (minTileX == maxTileX && minTileY == maxTileY) { 13635 myPairCount = 1u; 13636 bitmask = 1u; 13637 } else { 13638 for (var ty = minTileY; ty <= maxTileY; ty++) { 13639 for (var tx = minTileX; tx <= maxTileX; tx++) { 13640 let tMin = vec2f(f32(tx) * f32(TILE_SIZE), f32(ty) * f32(TILE_SIZE)); 13641 let tMax = tMin + vec2f(f32(TILE_SIZE)); 13642 if (tileIntersectsEllipse(tMin, tMax, screen, cx, cy, cz, radiusFactor)) { 13643 myPairCount++; 13644 let localX = u32(tx - minTileX); 13645 let localY = u32(ty - minTileY); 13646 if (localX < BITMASK_W && localY < BITMASK_H) { 13647 let bitIdx = localY * BITMASK_W + localX; 13648 bitmask |= (1u << bitIdx); 13649 } 13650 } 13651 } 13652 } 13653 } 13654 if (myPairCount == 0u) { 13655 splatPairStart[threadIdx] = 0u; 13656 splatPairCount[threadIdx] = 0u; 13657 return; 13658 } 13659 let pairBase = atomicAdd(&countersBuffer[0], myPairCount); 13660 splatPairStart[threadIdx] = pairBase; 13661 splatPairCount[threadIdx] = myPairCount; 13662 var j: u32 = 0u; 13663 for (var ty = minTileY; ty <= maxTileY; ty++) { 13664 for (var tx = minTileX; tx <= maxTileX; tx++) { 13665 let localX = u32(tx - minTileX); 13666 let localY = u32(ty - minTileY); 13667 var hits: bool; 13668 if (localX < BITMASK_W && localY < BITMASK_H) { 13669 let bitIdx = localY * BITMASK_W + localX; 13670 hits = (bitmask & (1u << bitIdx)) != 0u; 13671 } else { 13672 let tMin = vec2f(f32(tx) * f32(TILE_SIZE), f32(ty) * f32(TILE_SIZE)); 13673 let tMax = tMin + vec2f(f32(TILE_SIZE)); 13674 hits = tileIntersectsEllipse(tMin, tMax, screen, cx, cy, cz, radiusFactor); 13675 } 13676 if (hits) { 13677 let tileIdx = u32(ty) * uniforms.numTilesX + u32(tx); 13678 let localOff = atomicAdd(&tileSplatCounts[tileIdx], 1u); 13679 if (localOff < MAX_TILE_ENTRIES) { 13680 pairBuffer[pairBase + j] = (tileIdx << 16u) | (localOff & 0xFFFFu); 13681 j++; 13682 } 13683 } 13684 } 13685 } 13686 if (j != myPairCount) { 13687 splatPairCount[threadIdx] = j; 13688 } 13689} 13690`,_V=` 13691#include "gsplatCommonCS" 13692#include "gsplatTileIntersectCS" 13693const WG_SIZE: u32 = 256u; 13694const MAX_TILE_ENTRIES: u32 = 0xFFFFu; 13695@group(0) @binding(0) var<storage, read> projCache: array<u32>; 13696@group(0) @binding(1) var<storage, read_write> tileSplatCounts: array<atomic<u32>>; 13697@group(0) @binding(2) var<storage, read_write> pairBuffer: array<u32>; 13698@group(0) @binding(3) var<storage, read_write> countersBuffer: array<atomic<u32>>; 13699@group(0) @binding(4) var<storage, read_write> splatPairStart: array<u32>; 13700@group(0) @binding(5) var<storage, read_write> splatPairCount: array<u32>; 13701@group(0) @binding(6) var<storage, read> largeSplatIds: array<u32>; 13702struct Uniforms { 13703 numTilesX: u32, 13704 numTilesY: u32, 13705 viewportWidth: f32,
13706 viewportHeight: f32, 13707 alphaClip: f32, 13708} 13709@group(0) @binding(7) var<uniform> uniforms: Uniforms; 13710var<workgroup> wgPairCounts: array<u32, WG_SIZE>; 13711var<workgroup> wgPairOffsets: array<u32, WG_SIZE>; 13712var<workgroup> wgBase: u32; 13713@compute @workgroup_size(256) 13714fn main( 13715 @builtin(workgroup_id) wgId: vec3u, 13716 @builtin(num_workgroups) numWorkgroups: vec3u, 13717 @builtin(local_invocation_index) lid: u32 13718) { 13719 let largeSplatIdx = wgId.y * numWorkgroups.x + wgId.x; 13720 let count = min(atomicLoad(&countersBuffer[1]), arrayLength(&largeSplatIds)); 13721 let isActive = largeSplatIdx < count; 13722 var threadIdx = u32(0); 13723 var minTileX = 0i; 13724 var maxTileX = 0i; 13725 var minTileY = 0i; 13726 var maxTileY = 0i; 13727 var aabbW = u32(0); 13728 var totalTiles = u32(0); 13729 var screen = vec2f(0.0); 13730 var cx = 0.0f; 13731 var cy = 0.0f; 13732 var cz = 0.0f; 13733 var radiusFactor = 0.0f; 13734 if (isActive) { 13735 threadIdx = largeSplatIds[largeSplatIdx]; 13736 let cacheBase = threadIdx * {CACHE_STRIDE}u; 13737 screen = vec2f(bitcast<f32>(projCache[cacheBase + 0u]), bitcast<f32>(projCache[cacheBase + 1u])); 13738 cx = bitcast<f32>(projCache[cacheBase + 2u]); 13739 cy = bitcast<f32>(projCache[cacheBase + 3u]); 13740 cz = bitcast<f32>(projCache[cacheBase + 4u]); 13741 let opacity = unpack2x16float(projCache[cacheBase + 6u]).y; 13742 let eval = computeSplatTileEval(screen, cx, cy, cz, half(opacity), 13743 uniforms.viewportWidth, uniforms.viewportHeight, 13744 uniforms.alphaClip); 13745 radiusFactor = eval.radiusFactor; 13746 minTileX = max(0i, i32(floor(eval.splatMin.x / f32(TILE_SIZE)))); 13747 maxTileX = min(i32(uniforms.numTilesX) - 1i, i32(floor(eval.splatMax.x / f32(TILE_SIZE)))); 13748 minTileY = max(0i, i32(floor(eval.splatMin.y / f32(TILE_SIZE)))); 13749 maxTileY = min(i32(uniforms.numTilesY) - 1i, i32(floor(eval.splatMax.y / f32(TILE_SIZE)))); 13750 if (maxTileX >= minTileX && maxTileY >= minTileY) { 13751 aabbW = u32(maxTileX - minTileX + 1i); 13752 totalTiles = aabbW * u32(maxTileY - minTileY + 1i); 13753 } 13754 } 13755 var myHitCount: u32 = 0u; 13756 for (var i = lid; i < totalTiles; i += WG_SIZE) { 13757 let localX = i % aabbW; 13758 let localY = i / aabbW; 13759 let tx = minTileX + i32(localX); 13760 let ty = minTileY + i32(localY); 13761 let tMin = vec2f(f32(tx) * f32(TILE_SIZE), f32(ty) * f32(TILE_SIZE)); 13762 let tMax = tMin + vec2f(f32(TILE_SIZE)); 13763 if (tileIntersectsEllipse(tMin, tMax, screen, cx, cy, cz, radiusFactor)) { 13764 myHitCount++; 13765 } 13766 } 13767 wgPairCounts[lid] = myHitCount; 13768 workgroupBarrier(); 13769 if (lid == 0u && isActive) { 13770 var sum: u32 = 0u; 13771 for (var i: u32 = 0u; i < WG_SIZE; i++) { 13772 wgPairOffsets[i] = sum; 13773 sum += wgPairCounts[i]; 13774 } 13775 if (sum > 0u) { 13776 wgBase = atomicAdd(&countersBuffer[0], sum); 13777 } else { 13778 wgBase = 0u; 13779 } 13780 splatPairStart[threadIdx] = wgBase; 13781 splatPairCount[threadIdx] = sum | 0x80000000u; 13782 } 13783 workgroupBarrier(); 13784 let myBase = wgBase + wgPairOffsets[lid]; 13785 var j: u32 = 0u; 13786 for (var i = lid; i < totalTiles; i += WG_SIZE) { 13787 let localX = i % aabbW; 13788 let localY = i / aabbW; 13789 let tx = minTileX + i32(localX); 13790 let ty = minTileY + i32(localY); 13791 let tMin = vec2f(f32(tx) * f32(TILE_SIZE), f32(ty) * f32(TILE_SIZE)); 13792 let tMax = tMin + vec2f(f32(TILE_SIZE)); 13793 if (tileIntersectsEllipse(tMin, tMax, screen, cx, cy, cz, radiusFactor)) { 13794 let tileIdx = u32(ty) * uniforms.numTilesX + u32(tx); 13795 let localOff = atomicAdd(&tileSplatCounts[tileIdx], 1u); 13796 if (localOff < MAX_TILE_ENTRIES) { 13797 pairBuffer[myBase + j] = (tileIdx << 16u) | (localOff & 0xFFFFu); 13798 j++; 13799 } 13800 } 13801 } 13802 wgPairCounts[lid] = j; 13803 workgroupBarrier(); 13804 if (lid == 0u && isActive) { 13805 var actualTotal: u32 = 0u; 13806 for (var i: u32 = 0u; i < WG_SIZE; i++) { 13807 actualTotal += wgPairCounts[i]; 13808 } 13809 let storedCount = splatPairCount[threadIdx] & 0x7FFFFFFFu; 13810 if (actualTotal != storedCount) { 13811 splatPairCount[threadIdx] = actualTotal | 0x80000000u; 13812 } 13813 } 13814} 13815`,gV=` 13816@group(0) @binding(0) var<storage, read> pairBuffer: array<u32>; 13817@group(0) @binding(1) var<storage, read> splatPairStart: array<u32>; 13818@group(0) @binding(2) var<storage, read> splatPairCount: array<u32>; 13819@group(0) @binding(3) var<storage, read> tileSplatCounts: array<u32>; 13820@group(0) @binding(4) var<storage, read_write> tileEntries: array<u32>; 13821@group(0) @binding(5) var<storage, read> sortElementCount: array<u32>; 13822@compute @workgroup_size(256) 13823fn main(@builtin(global_invocation_id) gid: vec3u, @builtin(num_workgroups) numWorkgroups: vec3u) { 13824 let threadIdx = gid.y * (numWorkgroups.x * 256u) + gid.x; 13825 let numVisible = sortElementCount[0]; 13826 if (threadIdx >= numVisible) { 13827 return; 13828 } 13829 let rawCount = splatPairCount[threadIdx]; 13830 if (rawCount == 0u || (rawCount & 0x80000000u) != 0u) { 13831 return; 13832 } 13833 let count = rawCount; 13834 let start = splatPairStart[threadIdx]; 13835 let pairLen = arrayLength(&pairBuffer); 13836 let tileEntriesLen = arrayLength(&tileEntries); 13837 for (var j: u32 = 0u; j < count; j++) { 13838 let pairIdx = start + j; 13839 if (pairIdx >= pairLen) { break; }
13840 let packed = pairBuffer[pairIdx]; 13841 let tileIdx = packed >> 16u; 13842 let localOff = packed & 0xFFFFu; 13843 let entryIdx = tileSplatCounts[tileIdx] + localOff; 13844 if (entryIdx < tileEntriesLen) { 13845 tileEntries[entryIdx] = threadIdx; 13846 } 13847 } 13848} 13849`,vV=` 13850const WG_SIZE: u32 = 256u; 13851@group(0) @binding(0) var<storage, read> pairBuffer: array<u32>; 13852@group(0) @binding(1) var<storage, read> splatPairStart: array<u32>; 13853@group(0) @binding(2) var<storage, read> splatPairCount: array<u32>; 13854@group(0) @binding(3) var<storage, read> tileSplatCounts: array<u32>; 13855@group(0) @binding(4) var<storage, read_write> tileEntries: array<u32>; 13856@group(0) @binding(5) var<storage, read> largeSplatIds: array<u32>; 13857@group(0) @binding(6) var<storage, read> countersBuffer: array<u32>; 13858@compute @workgroup_size(256) 13859fn main( 13860 @builtin(workgroup_id) wgId: vec3u, 13861 @builtin(num_workgroups) numWorkgroups: vec3u, 13862 @builtin(local_invocation_index) lid: u32 13863) { 13864 let largeSplatIdx = wgId.y * numWorkgroups.x + wgId.x; 13865 let numLarge = min(countersBuffer[1], arrayLength(&largeSplatIds)); 13866 if (largeSplatIdx >= numLarge) { 13867 return; 13868 } 13869 let threadIdx = largeSplatIds[largeSplatIdx]; 13870 let pairCount = splatPairCount[threadIdx] & 0x7FFFFFFFu; 13871 if (pairCount == 0u) { 13872 return; 13873 } 13874 let start = splatPairStart[threadIdx]; 13875 let pairLen = arrayLength(&pairBuffer); 13876 let tileEntriesLen = arrayLength(&tileEntries); 13877 for (var j = lid; j < pairCount; j += WG_SIZE) { 13878 let pairIdx = start + j; 13879 if (pairIdx >= pairLen) { break; } 13880 let packed = pairBuffer[pairIdx]; 13881 let tileIdx = packed >> 16u; 13882 let localOff = packed & 0xFFFFu; 13883 let entryIdx = tileSplatCounts[tileIdx] + localOff; 13884 if (entryIdx < tileEntriesLen) { 13885 tileEntries[entryIdx] = threadIdx; 13886 } 13887 } 13888} 13889`,SV=` 13890#include "gsplatLocalBitonicCS" 13891@group(0) @binding(0) var<storage, read_write> tileEntries: array<u32>; 13892@group(0) @binding(1) var<storage, read> tileSplatCounts: array<u32>; 13893@group(0) @binding(2) var<storage, read> depthBuffer: array<u32>; 13894@group(0) @binding(3) var<storage, read> smallTileList: array<u32>; 13895@group(0) @binding(4) var<storage, read> tileListCounts: array<u32>; 13896@compute @workgroup_size(256) 13897fn main( 13898 @builtin(local_invocation_index) localIdx: u32, 13899 @builtin(workgroup_id) wid: vec3u, 13900 @builtin(num_workgroups) numWorkgroups: vec3u 13901) { 13902 let workgroupIdx = wid.y * numWorkgroups.x + wid.x; 13903 if (workgroupIdx >= tileListCounts[0]) { 13904 return; 13905 } 13906 let tileIdx = smallTileList[workgroupIdx]; 13907 let tStart = tileSplatCounts[tileIdx]; 13908 let tEnd = tileSplatCounts[tileIdx + 1u]; 13909 let count = tEnd - tStart; 13910 bitonicSortRange(localIdx, tStart, count); 13911} 13912`;var Bf=` 13913fn calcDispatch2D(count: u32, maxDim: u32) -> vec2u { 13914 if (count <= maxDim) { 13915 return vec2u(count, 1u); 13916 } 13917 let y = (count + maxDim - 1u) / maxDim; 13918 let x = (count + y - 1u) / y; 13919 return vec2u(x, y); 13920} 13921`;const yV=` 13922${Of} 13923${Bf} 13924const MAX_TILE_ENTRIES: u32 = 4096u; 13925const CLASSIFY_WORKGROUP: u32 = 256u; 13926@group(0) @binding(0) var<storage, read> tileSplatCounts: array<u32>; 13927@group(0) @binding(1) var<storage, read_write> smallTileList: array<u32>; 13928@group(0) @binding(2) var<storage, read_write> largeTileList: array<u32>; 13929@group(0) @binding(3) var<storage, read_write> rasterizeTileList: array<u32>; 13930@group(0) @binding(4) var<storage, read_write> tileListCounts: array<atomic<u32>>; 13931@group(0) @binding(5) var<storage, read_write> indirectDispatchArgs: array<u32>; 13932@group(0) @binding(6) var<storage, read_write> largeTileOverflowBases: array<u32>; 13933@group(0) @binding(8) var<storage, read_write> indirectDrawArgs: array<DrawIndirectArgs>; 13934struct Uniforms { 13935 numTiles: u32, 13936 dispatchSlotOffset: u32, 13937 bufferCapacity: u32, 13938 maxWorkgroupsPerDim: u32, 13939 drawSlot: u32, 13940} 13941@group(0) @binding(7) var<uniform> uniforms: Uniforms; 13942@compute @workgroup_size(256) 13943fn main(@builtin(local_invocation_index) localIdx: u32) { 13944 let numTiles = uniforms.numTiles; 13945 let totalEntries = tileSplatCounts[numTiles]; 13946 for (var i: u32 = localIdx; i < numTiles; i += CLASSIFY_WORKGROUP) { 13947 let tStart = tileSplatCounts[i]; 13948 let tEnd = tileSplatCounts[i + 1u]; 13949 let count = tEnd - tStart; 13950 if (count == 0u || tEnd > uniforms.bufferCapacity) { 13951 continue; 13952 } 13953 let rIdx = atomicAdd(&tileListCounts[2], 1u); 13954 rasterizeTileList[rIdx] = i; 13955 if (count <= MAX_TILE_ENTRIES) {
13956 let sIdx = atomicAdd(&tileListCounts[0], 1u); 13957 smallTileList[sIdx] = i; 13958 } else { 13959 let overflowOffset = atomicAdd(&tileListCounts[3], count); 13960 let lIdx = atomicAdd(&tileListCounts[1], 1u); 13961 largeTileList[lIdx] = i; 13962 largeTileOverflowBases[lIdx] = totalEntries + overflowOffset; 13963 } 13964 } 13965 workgroupBarrier(); 13966 if (localIdx == 0u) { 13967 let smallCount = atomicLoad(&tileListCounts[0]); 13968 let largeCount = atomicLoad(&tileListCounts[1]); 13969 let rasterizeCount = atomicLoad(&tileListCounts[2]); 13970 let off = uniforms.dispatchSlotOffset; 13971 let maxDim = uniforms.maxWorkgroupsPerDim; 13972 let smallDim = calcDispatch2D(smallCount, maxDim); 13973 indirectDispatchArgs[off + 0u] = smallDim.x; 13974 indirectDispatchArgs[off + 1u] = smallDim.y; 13975 indirectDispatchArgs[off + 2u] = 1u; 13976 let largeDim = calcDispatch2D(largeCount, maxDim); 13977 indirectDispatchArgs[off + 3u] = largeDim.x; 13978 indirectDispatchArgs[off + 4u] = largeDim.y; 13979 indirectDispatchArgs[off + 5u] = 1u; 13980 let rasterDim = calcDispatch2D(rasterizeCount, maxDim); 13981 indirectDispatchArgs[off + 6u] = rasterDim.x; 13982 indirectDispatchArgs[off + 7u] = rasterDim.y; 13983 indirectDispatchArgs[off + 8u] = 1u; 13984 indirectDrawArgs[uniforms.drawSlot] = DrawIndirectArgs(rasterizeCount * 6u, 1u, 0u, 0u, 0u); 13985 } 13986} 13987`,xV=128,TV=` 13988const NUM_BUCKETS: u32 = ${xV}u; 13989const MAX_CHUNK_SIZE: u32 = 4096u; 13990const WG_SIZE: u32 = 256u; 13991@group(0) @binding(0) var<storage, read_write> tileEntries: array<u32>; 13992@group(0) @binding(1) var<storage, read> largeTileOverflowBases: array<u32>; 13993@group(0) @binding(2) var<storage, read> tileSplatCounts: array<u32>; 13994@group(0) @binding(3) var<storage, read> depthBuffer: array<u32>; 13995@group(0) @binding(4) var<storage, read> largeTileList: array<u32>; 13996@group(0) @binding(5) var<storage, read_write> chunkRanges: array<u32>; 13997@group(0) @binding(6) var<storage, read_write> totalChunks: array<atomic<u32>>; 13998@group(0) @binding(7) var<storage, read> tileListCounts: array<u32>; 13999struct Uniforms { 14000 bufferCapacity: u32, 14001 maxChunks: u32, 14002} 14003@group(0) @binding(8) var<uniform> uniforms: Uniforms; 14004var<workgroup> sDepthMin: atomic<u32>; 14005var<workgroup> sDepthMax: atomic<u32>; 14006var<workgroup> sBucketCounts: array<atomic<u32>, NUM_BUCKETS>; 14007var<workgroup> sBucketOffsets: array<u32, NUM_BUCKETS + 1>; 14008var<workgroup> sBucketCursors: array<atomic<u32>, NUM_BUCKETS>; 14009@compute @workgroup_size(256) 14010fn main( 14011 @builtin(local_invocation_index) localIdx: u32, 14012 @builtin(workgroup_id) wid: vec3u, 14013 @builtin(num_workgroups) numWorkgroups: vec3u 14014) { 14015 let largeTileIdx = wid.y * numWorkgroups.x + wid.x; 14016 if (largeTileIdx >= tileListCounts[1]) { 14017 return; 14018 } 14019 let tileIdx = largeTileList[largeTileIdx]; 14020 let tStart = tileSplatCounts[tileIdx]; 14021 let tEnd = tileSplatCounts[tileIdx + 1u]; 14022 let count = tEnd - tStart; 14023 let overflowBase = largeTileOverflowBases[largeTileIdx]; 14024 if (overflowBase + count > uniforms.bufferCapacity) { 14025 return; 14026 } 14027 if (localIdx == 0u) { 14028 atomicStore(&sDepthMin, 0xFFFFFFFFu); 14029 atomicStore(&sDepthMax, 0u); 14030 } 14031 if (localIdx < NUM_BUCKETS) { 14032 atomicStore(&sBucketCounts[localIdx], 0u); 14033 atomicStore(&sBucketCursors[localIdx], 0u); 14034 } 14035 workgroupBarrier(); 14036 for (var i: u32 = localIdx; i < count; i += WG_SIZE) { 14037 let entryIdx = tileEntries[tStart + i]; 14038 let depthU = depthBuffer[entryIdx]; 14039 atomicMin(&sDepthMin, depthU); 14040 atomicMax(&sDepthMax, depthU); 14041 } 14042 workgroupBarrier(); 14043 let depthMinU = atomicLoad(&sDepthMin); 14044 let depthMaxU = atomicLoad(&sDepthMax); 14045 let depthMin = bitcast<f32>(depthMinU); 14046 let depthMax = bitcast<f32>(depthMaxU); 14047 let logMin = log(max(depthMin, 1e-6)); 14048 let logRange = log(max(depthMax, 1e-6)) - logMin; 14049 let bucketScale = select(f32(NUM_BUCKETS) / logRange, 0.0, logRange < 1e-10); 14050 for (var i: u32 = localIdx; i < count; i += WG_SIZE) { 14051 let entryIdx = tileEntries[tStart + i]; 14052 let depth = bitcast<f32>(depthBuffer[entryIdx]); 14053 let bucket = min(u32((log(max(depth, 1e-6)) - logMin) * bucketScale), NUM_BUCKETS - 1u); 14054 atomicAdd(&sBucketCounts[bucket], 1u); 14055 tileEntries[overflowBase + i] = entryIdx; 14056 } 14057 workgroupBarrier(); 14058 if (localIdx == 0u) { 14059 sBucketOffsets[0] = 0u; 14060 for (var b: u32 = 0u; b < NUM_BUCKETS; b++) { 14061 sBucketOffsets[b + 1u] = sBucketOffsets[b] + atomicLoad(&sBucketCounts[b]); 14062 } 14063 } 14064 workgroupBarrier(); 14065 for (var i: u32 = localIdx; i < count; i += WG_SIZE) { 14066 let entryIdx = tileEntries[overflowBase + i]; 14067 let depth = bitcast<f32>(depthBuffer[entryIdx]); 14068 let bucket = min(u32((log(max(depth, 1e-6)) - logMin) * bucketScale), NUM_BUCKETS - 1u); 14069 let writePos = sBucketOffsets[bucket] + atomicAdd(&sBucketCurs
14069ors[bucket], 1u); 14070 tileEntries[tStart + writePos] = entryIdx; 14071 } 14072 workgroupBarrier(); 14073 if (localIdx == 0u) { 14074 var chunkStart: u32 = 0u; 14075 var currentSize: u32 = 0u; 14076 let maxChunks = uniforms.maxChunks; 14077 for (var b: u32 = 0u; b < NUM_BUCKETS; b++) { 14078 var bRemaining = sBucketOffsets[b + 1u] - sBucketOffsets[b]; 14079 if (bRemaining == 0u) { 14080 continue; 14081 } 14082 while (bRemaining > 0u) { 14083 let space = MAX_CHUNK_SIZE - currentSize; 14084 let take = min(bRemaining, space); 14085 currentSize += take; 14086 bRemaining -= take; 14087 if (currentSize == MAX_CHUNK_SIZE) { 14088 let cIdx = atomicAdd(&totalChunks[0], 1u); 14089 if (cIdx < maxChunks) { 14090 chunkRanges[cIdx * 2u] = tStart + chunkStart; 14091 chunkRanges[cIdx * 2u + 1u] = currentSize; 14092 } 14093 chunkStart += currentSize; 14094 currentSize = 0u; 14095 } 14096 } 14097 } 14098 if (currentSize > 0u) { 14099 let cIdx = atomicAdd(&totalChunks[0], 1u); 14100 if (cIdx < maxChunks) { 14101 chunkRanges[cIdx * 2u] = tStart + chunkStart; 14102 chunkRanges[cIdx * 2u + 1u] = currentSize; 14103 } 14104 } 14105 } 14106} 14107`,wV=` 14108#include "gsplatLocalBitonicCS" 14109@group(0) @binding(0) var<storage, read_write> tileEntries: array<u32>; 14110@group(0) @binding(1) var<storage, read> depthBuffer: array<u32>; 14111@group(0) @binding(2) var<storage, read> chunkRanges: array<u32>; 14112@group(0) @binding(3) var<storage, read> totalChunks: array<u32>; 14113struct Uniforms { 14114 maxChunks: u32, 14115} 14116@group(0) @binding(4) var<uniform> uniforms: Uniforms; 14117@compute @workgroup_size(256) 14118fn main( 14119 @builtin(local_invocation_index) localIdx: u32, 14120 @builtin(workgroup_id) wid: vec3u, 14121 @builtin(num_workgroups) numWorkgroups: vec3u 14122) { 14123 let chunkIdx = wid.y * numWorkgroups.x + wid.x; 14124 if (chunkIdx >= min(totalChunks[0], uniforms.maxChunks)) { 14125 return; 14126 } 14127 let tStart = chunkRanges[chunkIdx * 2u]; 14128 let count = chunkRanges[chunkIdx * 2u + 1u]; 14129 bitonicSortRange(localIdx, tStart, count); 14130} 14131`,CV=` 14132${Bf} 14133@group(0) @binding(0) var<storage, read> totalChunks: array<u32>; 14134@group(0) @binding(1) var<storage, read_write> chunkSortIndirect: array<u32>; 14135struct Uniforms { 14136 maxChunks: u32, 14137 maxWorkgroupsPerDim: u32, 14138} 14139@group(0) @binding(2) var<uniform> uniforms: Uniforms; 14140@compute @workgroup_size(1) 14141fn main() { 14142 let count = min(totalChunks[0], uniforms.maxChunks); 14143 let dim = calcDispatch2D(count, uniforms.maxWorkgroupsPerDim); 14144 chunkSortIndirect[0] = dim.x; 14145 chunkSortIndirect[1] = dim.y; 14146 chunkSortIndirect[2] = 1u; 14147} 14148`,EV=` 14149const MAX_TILE_ENTRIES: u32 = 4096u; 14150const INDEX_BITS: u32 = 12u; 14151const INDEX_MASK: u32 = 0xFFFu; 14152const DEPTH_LEVELS: f32 = 1048575.0; 14153const BITONIC_WG_SIZE: u32 = 256u; 14154var<workgroup> sData: array<u32, 4096>; 14155var<workgroup> sDepthMin: atomic<u32>; 14156var<workgroup> sDepthMax: atomic<u32>; 14157fn insertZeroBit(v: u32, bitPos: u32) -> u32 { 14158 let mask = (1u << bitPos) - 1u; 14159 return ((v >> bitPos) << (bitPos + 1u)) | (v & mask); 14160} 14161fn bitonicSortRange(localIdx: u32, tStart: u32, count: u32) { 14162 let clampedCount = min(count, MAX_TILE_ENTRIES); 14163 if (clampedCount <= 1u) { 14164 return; 14165 } 14166 if (localIdx == 0u) { 14167 atomicStore(&sDepthMin, 0xFFFFFFFFu); 14168 atomicStore(&sDepthMax, 0u); 14169 } 14170 var sortN: u32 = 1u; 14171 while (sortN < clampedCount) { 14172 sortN = sortN << 1u; 14173 } 14174 for (var i: u32 = localIdx; i < sortN; i += BITONIC_WG_SIZE) { 14175 if (i < clampedCount) { 14176 let entryIdx = tileEntries[tStart + i]; 14177 sData[i] = depthBuffer[entryIdx]; 14178 } else { 14179 sData[i] = 0xFFFFFFFFu; 14180 } 14181 } 14182 workgroupBarrier(); 14183 for (var i: u32 = localIdx; i < clampedCount; i += BITONIC_WG_SIZE) { 14184 atomicMin(&sDepthMin, sData[i]); 14185 atomicMax(&sDepthMax, sData[i]); 14186 } 14187 workgroupBarrier(); 14188 let depthMinU = atomicLoad(&sDepthMin); 14189 let depthMaxU = atomicLoad(&sDepthMax); 14190 let depthMin = bitcast<f32>(depthMinU); 14191 let depthMax = bitcast<f32>(depthMaxU); 14192 let logMin = log(max(depthMin, 1e-6)); 14193 let logRange = log(max(depthMax, 1e-6)) - logMin; 14194 let invLogRange = select(DEPTH_LEVELS / logRange, 0.0, logRange < 1e-10); 14195 for (var i: u32 = localIdx; i < sortN; i += BITONIC_WG_SIZE) { 14196 if (i < clampedCount) { 14197 let depth = bitcast<f32>(sData[i]); 14198 let logDepth = log(max(depth, 1e-6)); 14199 let depth20 = min(u32((logDepth - logMin) * invLogRange + 0.5), u32(DEPTH_LEVELS)); 14200 sData[i] = (depth20 << INDEX_BITS) | i; 14201 } else { 14202 sData[i] = 0xFFFFFFFFu; 14203 } 14204 } 14205 workgroupBarrier(); 14206 for (var k: u32 = 2u; k <= sortN; k = k << 1u) { 14207 for (var j: u32 = k >> 1u; j > 0u; j = j >> 1u) { 14208 let bitPos = countTrailingZeros(j); 14209 let halfN = sortN >> 1u; 14210 for (var c: u32 = localIdx; c < halfN; c += BITONIC_WG_SIZE) { 14211 let l = insertZeroBit(c, bitPos); 14212 let r = l | j; 14213 let ascending = (l & k) == 0u; 14214 let shouldSwap = select(sData[l] < sData[r], sData[l] > sData[r], ascending); 14215 if (shouldSwap) { 14216 let tmp = sData[l]; sData[l] = sData[r]; sData[r] = tmp; 14217 } 14218 } 14219 workgroupBarrier(); 14220 } 14221 } 14222 for (var i: u32 = localIdx; i < clampedCount; i += BITONIC_WG_SIZE) { 14223 let localIndex = sData[i] & INDEX_MASK;
14224 sData[i] = tileEntries[tStart + localIndex]; 14225 } 14226 workgroupBarrier(); 14227 for (var i: u32 = localIdx; i < clampedCount; i += BITONIC_WG_SIZE) { 14228 tileEntries[tStart + i] = sData[i]; 14229 } 14230} 14231`,gC=` 14232struct ProjectedSplatCommon { 14233 valid: bool, 14234 splatId: u32, 14235 center: vec3f, 14236 opacity: f32, 14237 proj: SplatCov2D 14238} 14239fn invalidProjectedSplatCommon() -> ProjectedSplatCommon { 14240 var cov: SplatCov2D; 14241 cov.screen = vec2f(0.0); 14242 cov.a = 0.0; 14243 cov.b = 0.0; 14244 cov.c = 0.0; 14245 cov.viewDepth = 0.0; 14246 cov.valid = false; 14247 return ProjectedSplatCommon(false, 0u, vec3f(0.0), 0.0, cov); 14248} 14249fn projectSplatCommon( 14250 threadIdx: u32, 14251 numVisible: u32, 14252 alphaClip: f32, 14253 minPixelSize: f32, 14254 minContribution: f32, 14255 viewMatrix: mat4x4f, 14256 viewProj: mat4x4f, 14257 focal: f32, 14258 viewportWidth: f32, 14259 viewportHeight: f32, 14260 nearClip: f32, 14261 farClip: f32, 14262 isOrtho: u32, 14263 #ifdef GSPLAT_FISHEYE 14264 fisheye_k: f32, 14265 fisheye_inv_k: f32, 14266 fisheye_projMat00: f32, 14267 fisheye_projMat11: f32, 14268 #endif 14269) -> ProjectedSplatCommon { 14270 if (threadIdx >= numVisible) { 14271 return invalidProjectedSplatCommon(); 14272 } 14273 let splatId = compactedSplatIds[threadIdx]; 14274 setSplat(splatId); 14275 let center = getCenter(); 14276 let opacity = getOpacity(); 14277 if (opacity <= alphaClip) { 14278 return invalidProjectedSplatCommon(); 14279 } 14280 let rotation = half4(getRotation()); 14281 let scale = half3(getScale()); 14282 let proj = computeSplatCov( 14283 center, rotation, scale, 14284 viewMatrix, viewProj, 14285 focal, viewportWidth, viewportHeight, 14286 nearClip, farClip, opacity, minPixelSize, 14287 isOrtho, alphaClip, minContribution, 14288 #ifdef GSPLAT_FISHEYE 14289 fisheye_k, fisheye_inv_k, 14290 fisheye_projMat00, fisheye_projMat11, 14291 #endif 14292 ); 14293 if (!proj.valid) { 14294 return invalidProjectedSplatCommon(); 14295 } 14296 return ProjectedSplatCommon(true, splatId, center, opacity, proj); 14297} 14298`,vC=` 14299#include "halfTypesCS" 14300const TILE_SIZE: u32 = 16u; 14301fn quatToMat3(r: half4) -> half3x3 { 14302 let r2: half4 = r + r; 14303 let x: half = r2.x * r.w; 14304 let y: half4 = r2.y * r; 14305 let z: half4 = r2.z * r; 14306 let w: half = r2.w * r.w; 14307 return half3x3( 14308 half(1.0) - z.z - w, y.z + x, y.w - z.x, 14309 y.z - x, half(1.0) - y.y - w, z.w + y.x, 14310 y.w + z.x, z.w - y.x, half(1.0) - y.y - z.z 14311 ); 14312} 14313struct SplatCov2D { 14314 screen: vec2f, 14315 a: f32, 14316 b: f32, 14317 c: f32, 14318 viewDepth: f32, 14319 valid: bool, 14320 #if GSPLAT_AA 14321 aaFactor: f32, 14322 #endif 14323} 14324fn computeSplatCov( 14325 worldCenter: vec3f, 14326 rotation: half4, 14327 scale: half3, 14328 viewMatrix: mat4x4f, 14329 viewProj: mat4x4f, 14330 focal: f32, 14331 viewportWidth: f32, 14332 viewportHeight: f32, 14333 nearClip: f32, 14334 farClip: f32, 14335 opacity: f32, 14336 minPixelSize: f32, 14337 isOrtho: u32, 14338 alphaClip: f32, 14339 minContribution: f32, 14340 #ifdef GSPLAT_FISHEYE 14341 fisheye_k: f32, 14342 fisheye_inv_k: f32, 14343 fisheye_projMat00: f32, 14344 fisheye_projMat11: f32, 14345 #endif 14346) -> SplatCov2D { 14347 var result: SplatCov2D; 14348 result.valid = false; 14349 let viewCenter = (viewMatrix * vec4f(worldCenter, 1.0)).xyz; 14350 #ifdef GSPLAT_FISHEYE 14351 let fv = viewCenter; 14352 let r_xy = length(fv.xy); 14353 let neg_z = -fv.z; 14354 let theta = atan2(r_xy, neg_z); 14355 let maxTheta = min(fisheye_k * 1.5707963, 3.13); 14356 if (theta > maxTheta - 0.01 || dot(fv, fv) < 0.0001) { 14357 return result; 14358 } 14359 let tk = theta * fisheye_inv_k; 14360 let sin_tk = sin(tk); 14361 let cos_tk = cos(tk); 14362 let g_theta = fisheye_k * sin_tk / cos_tk; 14363 let fisheye_s = select(select(0.0, 1.0 / neg_z, neg_z > 0.0), g_theta / r_xy, r_xy > 1e-4); 14364 let fndc = vec2f(fisheye_projMat00 * fisheye_s * fv.x, fisheye_projMat11 * fisheye_s * fv.y); 14365 let screen = vec2f( 14366 (fndc.x * 0.5 + 0.5) * viewportWidth, 14367 (fndc.y * 0.5 + 0.5) * viewportHeight 14368 ); 14369 #else 14370 if (viewCenter.z > 0.0) { 14371 return result; 14372 } 14373 let clip = viewProj * vec4f(worldCenter, 1.0); 14374 let ndc = clip.xy / clip.w; 14375 let screen = vec2f( 14376 (ndc.x * 0.5 + 0.5) * viewportWidth, 14377 (ndc.y * 0.5 + 0.5) * viewportHeight 14378 ); 14379 #endif 14380 let rot: half3x3 = quatToMat3(rotation); 14381 let s: vec3f = vec3f(scale); 14382 let M: mat3x3f = transpose(mat3x3f( 14383 s.x * vec3f(rot[0]), 14384 s.y * vec3f(rot[1]), 14385 s.z * vec3f(rot[2]) 14386 )); 14387 let w0 = vec3f(viewMatrix[0].x, viewMatrix[1].x, viewMatrix[2].x); 14388 let w1 = vec3f(viewMatrix[0].y, viewMatrix[1].y, viewMatrix[2].y); 14389 let w2 = vec3f(viewMatrix[0].z, viewMatrix[1].z, viewMatrix[2].z); 14390 #ifdef GSPLAT_FISHEYE 14391 let fisheyeFocal = viewportWidth * fisheye_projMat00; 14392 let g_prime = 1.0 / (cos_tk * cos_tk); 14393 let d2 = dot(fv, fv); 14394 let r_sq = max(r_xy * r_xy, 1e-8); 14395 let K_coeff = select(0.0, (g_prime * neg_z / d2 - fisheye_s) / r_sq, r_xy > 1e-4); 14396 let Jxx = fisheyeFocal * (fisheye_s + K_coeff * fv.x * fv.x); 14397 let Jxy = fisheyeFocal * K_coeff * fv.x * fv.y; 14398 let Jyy = fisheyeFocal * (fisheye_s + K_coeff * fv.y * fv.y); 14399 let Jzx = fisheyeFocal * g_prime * fv.x / d2; 14400 let Jzy = fisheyeFocal * g_prime * fv.y / d2; 14401 let tt0 = Jxx * w0 + Jxy * w1 + Jzx * w2; 14402 let tt1 = Jxy * w0 + Jyy * w1 + Jzy * w2; 14403 #else 14404 let ortho = isOrtho == 1u; 14405 let v = select(viewCenter.xyz, vec3f(0.0, 0.0, 1.0), ortho); 14406 let vz = select(min(v.z, -0.001), v.z, ortho); 14407 let J1 = focal / vz; 14408 let J2 = -J1 / vz * v.xy; 14409 let tt0 = J1 * w0 + J2.x * w2; 14410 let tt1 = J1 * w1 + J2.y * w2; 14411 #endif 14412 let b0 = M * tt0; 14413 let b1 = M * tt1; 14414 let aRaw = dot(b0, b0); 14415 let b = dot(b0, b1); 14416 let cRaw = dot(b1, b1); 14417 let a = aRaw + 0.3; 14418 let c = cRaw + 0.3; 14419 let det = a * c - b * b; 14420 if (det <= 0.0) { 14421 return result; 14422 } 14423 #if GSPLAT_AA 14424 let detOrig = aRaw * cRaw - b * b; 14425 result.aaFactor = sqrt(max(detOrig / det, 0.0)); 14426 #endif 14427 let totalContribution = opacity * 6.283185 * sqrt(det); 14428 if (totalContribution < minContribution) { 14429 return result; 14430 }
14431 let radiusFactor = computeRadiusFactor(half(opacity), alphaClip); 14432 let vmin = min(1024.0, min(viewportWidth, viewportHeight)); 14433 let maxRadius = vmin; 14434 let radiusXUncapped = sqrt(2.0 * a); 14435 let radiusYUncapped = sqrt(2.0 * c); 14436 let radiusX = min(radiusXUncapped, maxRadius); 14437 let radiusY = min(radiusYUncapped, maxRadius); 14438 if (max(radiusX, radiusY) < minPixelSize) { 14439 return result; 14440 } 14441 if (screen.x + radiusX < 0.0 || screen.x - radiusX > viewportWidth || 14442 screen.y + radiusY < 0.0 || screen.y - radiusY > viewportHeight) { 14443 return result; 14444 } 14445 let capScale = max(1.0, max(radiusXUncapped, radiusYUncapped) / maxRadius); 14446 let invCapScale2 = 1.0 / (capScale * capScale); 14447 result.screen = screen; 14448 let scaledCov = vec3f(a, b, c) * invCapScale2; 14449 result.a = scaledCov.x; 14450 result.b = scaledCov.y; 14451 result.c = scaledCov.z; 14452 #ifdef GSPLAT_FISHEYE 14453 result.viewDepth = sqrt(d2); 14454 #else 14455 result.viewDepth = -viewCenter.z; 14456 #endif 14457 result.valid = true; 14458 return result; 14459} 14460`,SC=` 14461struct SplatTileEval { 14462 radiusFactor: f32, 14463 splatMin: vec2f, 14464 splatMax: vec2f, 14465} 14466fn computeRadiusFactor(opacity: half, alphaClip: f32) -> f32 { 14467 return min(8.0, 2.0 * log(f32(opacity) / alphaClip)); 14468} 14469fn computeSplatTileEval( 14470 screen: vec2f, 14471 cx: f32, cy: f32, cz: f32, 14472 opacity: half, 14473 viewportWidth: f32, viewportHeight: f32, 14474 alphaClip: f32 14475) -> SplatTileEval { 14476 let K = cx * cz - cy * cy; 14477 let a = 4.0 * cz / K; 14478 let c = 4.0 * cx / K; 14479 let radiusFactor = computeRadiusFactor(opacity, alphaClip); 14480 let vmin = min(1024.0, min(viewportWidth, viewportHeight)); 14481 let radius = vec2f(min(sqrt(2.0 * a), vmin), min(sqrt(2.0 * c), vmin)); 14482 var result: SplatTileEval; 14483 result.radiusFactor = radiusFactor;
14484 result.splatMin = screen - radius; 14485 result.splatMax = screen + radius; 14486 return result; 14487} 14488fn segmentIntersectsEllipse(a: f32, b: f32, c: f32, d: f32, l: f32, r: f32) -> bool { 14489 let delta = b * b - 4.0 * a * c; 14490 let t1 = (l - d) * (2.0 * a) + b; 14491 let t2 = (r - d) * (2.0 * a) + b; 14492 return delta >= 0.0 && (t1 <= 0.0 || t1 * t1 <= delta) && (t2 >= 0.0 || t2 * t2 <= delta); 14493} 14494fn tileIntersectsEllipse( 14495 tileMin: vec2f, tileMax: vec2f, center: vec2f, 14496 cx: f32, cy: f32, cz: f32, 14497 radiusFactor: f32 14498) -> bool { 14499 if (center.x >= tileMin.x && center.x <= tileMax.x && 14500 center.y >= tileMin.y && center.y <= tileMax.y) { 14501 return true; 14502 } 14503 let w = radiusFactor; 14504 var dx: f32; 14505 if (center.x * 2.0 < tileMin.x + tileMax.x) { 14506 dx = center.x - tileMin.x; 14507 } else { 14508 dx = center.x - tileMax.x; 14509 } 14510 if (segmentIntersectsEllipse(cz, -2.0 * cy * dx, cx * dx * dx - w, center.y, tileMin.y, tileMax.y)) { 14511 return true; 14512 } 14513 var dy: f32; 14514 if (center.y * 2.0 < tileMin.y + tileMax.y) { 14515 dy = center.y - tileMin.y; 14516 } else { 14517 dy = center.y - tileMax.y; 14518 } 14519 if (segmentIntersectsEllipse(cx, -2.0 * cy * dy, cz * dy * dy - w, center.x, tileMin.x, tileMax.x)) { 14520 return true; 14521 } 14522 return false; 14523} 14524`;class bV{device;_material;_mesh;_meshInstance;_pickMaterial=null;_pickMeshInstance=null;_node;constructor(e,t,s){this.device=e,this._node=t,this._material=new ei({uniqueName:"GSplatTileComposite",vertexWGSL:'#include "gsplatTileCompositeVS"',fragmentWGSL:'#include "gsplatTileCompositePS"'}),this._material.blendType=Ui,this._material.cull=Yt,this._material.depthWrite=!1,this._material.update(),this._mesh=new at(e),this._mesh.primitive[0].type=qs,this._mesh.primitive[0].base=0,this._mesh.primitive[0].count=0,this._mesh.primitive[0].indexed=!1,this._meshInstance=new Ne(this._mesh,this._material),this._meshInstance.node=t,this._meshInstance.instancingCount=1,this._meshInstance.isVisibleFunc=s,this._meshInstance.pick=!1}destroy(){this._material.destroy(),this._mesh.destroy(),this._meshInstance.destroy(),this._pickMaterial?.destroy(),this._pickMeshInstance?.destroy()}get material(){return this._material}get meshInstance(){return this._meshInstance}update(e,t,s,i,r,a){this._meshInstance.setIndirect(null,e,1),this._material.setParameter("source",t),this._material.setParameter("rasterizeTileList",s),this._material.setParameter("numTilesX",i),this._material.setParameter("screenWidth",r),this._material.setParameter("screenHeight",a)}prepareForPicking(e,t,s,i,r,a,n){this._pickMaterial||(this._pickMaterial=new ei({uniqueName:"GSplatTileCompositePick",vertexWGSL:'#include "gsplatTileCompositeVS"',fragmentWGSL:'#include "gsplatTileCompositePS"'}),this._pickMaterial.setDefine("PICK_MODE",!0),this._pickMaterial.cull=Yt,this._pickMaterial.depthWrite=!1,this._pickMaterial.update(),this._pickMeshInstance=new Ne(this._mesh,this._pickMaterial),this._pickMeshInstance.node=this._node,this._pickMeshInstance.instancingCount=1);const o=this._pickMeshInstance,c=this._pickMaterial;return o.setIndirect(null,e,1),c.setParameter("pickIdTexture",t),c.setParameter("pickDepthTexture",s),c.setParameter("rasterizeTileList",i),c.setParameter("numTilesX",r),c.setParameter("screenWidth",a),c.setParameter("screenHeight",n),o}}const AV=` 14525#include "halfTypesCS" 14526#ifndef PICK_MODE 14527 #include "decodePS" 14528 #if FOG != NONE 14529 #include "fogMathPS" 14530 #include "gammaPS" 14531 #endif 14532#endif 14533const BATCH_SIZE: u32 = 64u; 14534const ALPHA_THRESHOLD: half = half(1.0) / half(255.0); 14535const EXP4: half = exp(half(-4.0)); 14536const INV_EXP4: half = half(1.0) / (half(1.0) - EXP4); 14537struct Uniforms { 14538 screenWidth: u32, 14539 screenHeight: u32, 14540 numTilesX: u32, 14541 nearClip: f32, 14542 farClip: f32, 14543 alphaClip: f32, 14544 #if FOG != NONE 14545 fog_color: vec3f, 14546 fog_start: f32, 14547 fog_end: f32, 14548 fog_density: f32, 14549 #endif 14550} 14551@group(0) @binding(0) var<uniform> uniforms: Uniforms; 14552@group(0) @binding(1) var<storage, read> tileEntries: array<u32>; 14553@group(0) @binding(2) var<storage, read> tileSplatCounts: array<u32>; 14554@group(0) @binding(3) var<storage, read> projCache: array<u32>; 14555@group(0) @binding(4) var<storage, read> rasterizeTileList: array<u32>; 14556@group(0) @binding(5) var<storage, read> tileListCounts: array<u32>; 14557@group(0) @binding(6) var<storage, read> depthBuffer: array<u32>; 14558#ifdef PICK_MODE 14559 @group(0) @binding(7) var pickIdTexture: texture_storage_2d<r32uint, write>; 14560 @group(0) @binding(8) var pickDepthTexture: texture_storage_2d<rgba16float, write>; 14561#else 14562 @group(0) @binding(7) var outputTexture: texture_storage_2d<rgba16float, write>; 14563 #ifdef DEPTH_TEST 14564 @group(0) @binding(8) var sceneDepthMap: texture_2d<f32>; 14565 #endif 14566#endif 14567var<workgroup> sharedCenterScreen: array<vec2f, 64>; 14568var<workgroup> sharedCoeffs: array<vec3f, 64>; 14569var<workgroup> sharedPowerCutoff: array<f32, 64>; 14570#ifdef HEATMAP_MODE 14571 var<workgroup> sharedHeatCount: atomic<u32>; 14572#endif 14573#ifdef PICK_MODE 14574 var<workgroup> sharedOpacity: array<half, 64>; 14575 var<workgroup> sharedPickId: array<u32, 64>; 14576 var<workgroup> sharedViewDepth: array<f32, 64>; 14577#else 14578 var<workgroup> sharedColor: array<half4, 64>; 14579 #ifdef DEPTH_TEST 14580 var<workgroup> sharedViewDepth: array<f32, 64>; 14581 #endif 14582#endif 14583#ifdef PICK_MODE 14584fn evalSplatPick(pixelCoord: vec2f, center: vec2f, coeffX: f32, coeffY: f32, coeffXY: f32, 14585 opacity: half, pickId: u32, viewDepth: f32, alphaClip: half, 14586 bestPickId: ptr<function, u32>, depthAccum: ptr<function, f32>,
14587 weightAccum: ptr<function, f32>, T: ptr<function, half>) { 14588 let dx = pixelCoord - center; 14589 let power = coeffX * dx.x * dx.x + coeffXY * dx.x * dx.y + coeffY * dx.y * dx.y; 14590 let gauss = (half(exp(power)) - EXP4) * INV_EXP4; 14591 let alpha = half(min(half(0.99), opacity * gauss)); 14592 let newT = *T * (half(1.0) - alpha); 14593 let visible = power > -4.0 && alpha > ALPHA_THRESHOLD && *T >= ALPHA_THRESHOLD; 14594 if (!visible) { return; } 14595 if (alpha >= alphaClip) { 14596 if (*bestPickId == 0xFFFFFFFFu) { 14597 *bestPickId = pickId; 14598 } 14599 let normalizedDepth = saturate((viewDepth - uniforms.nearClip) / (uniforms.farClip - uniforms.nearClip)); 14600 let w = f32(alpha) * f32(*T); 14601 *depthAccum += w * normalizedDepth; 14602 *weightAccum += w; 14603 } 14604 *T = newT; 14605} 14606#endif 14607#ifdef HEATMAP_MODE 14608fn heatmapColor(v: f32) -> vec3f { 14609 let t = saturate(v / 2000.0); 14610 if (t < 0.2) { 14611 return mix(vec3f(0.0, 0.0, 1.0), vec3f(0.0, 1.0, 1.0), t * 5.0); 14612 } else if (t < 0.4) { 14613 return mix(vec3f(0.0, 1.0, 1.0), vec3f(1.0, 1.0, 0.0), (t - 0.2) * 5.0); 14614 } else if (t < 0.6) { 14615 return mix(vec3f(1.0, 1.0, 0.0), vec3f(1.0, 0.0, 0.0), (t - 0.4) * 5.0); 14616 } 14617 return mix(vec3f(1.0, 0.0, 0.0), vec3f(0.15, 0.0, 0.0), (t - 0.6) * 2.5); 14618} 14619#endif 14620@compute @workgroup_size(8, 8) 14621fn main( 14622 @builtin(local_invocation_id) lid: vec3u, 14623 @builtin(local_invocation_index) localIdx: u32, 14624 @builtin(workgroup_id) wid: vec3u, 14625 @builtin(num_workgroups) numWorkgroups: vec3u 14626) { 14627 let workgroupIdx = wid.y * numWorkgroups.x + wid.x; 14628 if (workgroupIdx >= tileListCounts[2]) { 14629 return; 14630 } 14631 let tileIdx = rasterizeTileList[workgroupIdx]; 14632 let tileX = tileIdx % uniforms.numTilesX; 14633 let tileY = tileIdx / uniforms.numTilesX; 14634 let tStart = tileSplatCounts[tileIdx]; 14635 let tEnd = tileSplatCounts[tileIdx + 1u]; 14636 let basePixel = vec2u(tileX * 16u + lid.x * 2u, tileY * 16u + lid.y * 2u); 14637 let p00 = vec2f(f32(basePixel.x) + 0.5, f32(basePixel.y) + 0.5); 14638 let p10 = p00 + vec2f(1.0, 0.0); 14639 let p01 = p00 + vec2f(0.0, 1.0); 14640 let p11 = p00 + vec2f(1.0, 1.0); 14641 #ifdef PICK_MODE 14642 var T00: half = half(1.0); var T10: half = half(1.0); 14643 var T01: half = half(1.0); var T11: half = half(1.0); 14644 var pickId00: u32 = 0xFFFFFFFFu; var pickId10: u32 = 0xFFFFFFFFu; 14645 var pickId01: u32 = 0xFFFFFFFFu; var pickId11: u32 = 0xFFFFFFFFu; 14646 var dAcc00: f32 = 0.0; var dAcc10: f32 = 0.0; 14647 var dAcc01: f32 = 0.0; var dAcc11: f32 = 0.0; 14648 var wAcc00: f32 = 0.0; var wAcc10: f32 = 0.0; 14649 var wAcc01: f32 = 0.0; var wAcc11: f32 = 0.0; 14650 let clipH = half(uniforms.alphaClip); 14651 #else 14652 var T = half4(1.0); 14653 var c00 = half3(0.0); var c10 = half3(0.0); 14654 var c01 = half3(0.0); var c11 = half3(0.0); 14655 #ifdef DEPTH_TEST 14656 var sceneDepth = vec4f(1e20); 14657 let depthY0 = uniforms.screenHeight - 1u - basePixel.y; 14658 let depthY1 = depthY0 - 1u; 14659 if (basePixel.x < uniforms.screenWidth && basePixel.y < uniforms.screenHeight) { 14660 sceneDepth.x = textureLoad(sceneDepthMap, vec2i(vec2u(basePixel.x, depthY0)), 0).r; 14661 } 14662 if (basePixel.x + 1u < uniforms.screenWidth && basePixel.y < uniforms.screenHeight) { 14663 sceneDepth.y = textureLoad(sceneDepthMap, vec2i(vec2u(basePixel.x + 1u, depthY0)), 0).r; 14664 } 14665 if (basePixel.x < uniforms.screenWidth && basePixel.y + 1u < uniforms.screenHeight) { 14666 sceneDepth.z = textureLoad(sceneDepthMap, vec2i(vec2u(basePixel.x, depthY1)), 0).r; 14667 } 14668 if (basePixel.x + 1u < uniforms.screenWidth && basePixel.y + 1u < uniforms.screenHeight) { 14669 sceneDepth.w = textureLoad(sceneDepthMap, vec2i(vec2u(basePixel.x + 1u, depthY1)), 0).r; 14670 } 14671 #endif 14672 #endif 14673 let tileCount = tEnd - tStart; 14674 #ifdef HEATMAP_MODE 14675 if (localIdx == 0u) { atomicStore(&sharedHeatCount, 0u); } 14676 workgroupBarrier(); 14677 var processedCount: u32 = 0u; 14678 #endif 14679 let numBatches = (tileCount + BATCH_SIZE - 1u) / BATCH_SIZE; 14680 var threadDone = false; 14681 for (var batch: u32 = 0u; batch < numBatches; batch++) { 14682 let batchOffset = batch * BATCH_SIZE + localIdx; 14683 if (batchOffset < tileCount) { 14684 let cacheIdx = tileEntries[tStart + batchOffset]; 14685 let base = cacheIdx * {CACHE_STRIDE}u; 14686 sharedCenterScreen[localIdx] = vec2f( 14687 bitcast<f32>(projCache[base + 0u]), 14688 bitcast<f32>(projCache[base + 1u]) 14689 ); 14690 let cx = bitcast<f32>(projCache[base + 2u]); 14691 let cy = bitcast<f32>(projCache[base + 3u]); 14692 let cz = bitcast<f32>(projCache[base + 4u]); 14693 sharedCoeffs[localIdx] = vec3f(cx * -0.5, cz * -0.5, -cy); 14694 sharedPowerCutoff[localIdx] = bitcast<f32>(projCache[base + 7u]); 14695 #ifdef PICK_MODE 14696 sharedPickId[localIdx] = projCache[base + 5u]; 14697 sharedOpacity[localIdx] = half(unpack2x16float(projCache[base + 6u]).y); 14698 sharedViewDepth[localIdx] = bitcast<f32>(depthBuffer[cacheIdx]); 14699 #else 14700 let rg = unpack2x16float(projCache[base + 5u]); 14701 let ba = unpack2x16float(projCache[base + 6u]); 14702 #if FOG != NONE 14703 let viewDepth = bitcast<f32>(depthBuffer[cacheIdx]); 14704 #if (FOG == LINEAR) 14705 let fogFactor = evaluateFogFactorLinear(viewDepth, uniforms.fog_start, uniforms.fog_end); 14706 #elif (FOG == EXP) 14707 let fogFactor = evaluateFogFactorExp(viewDepth, uniforms.fog_density); 14708 #elif (FOG == EXP2) 14709 let fogFactor = evaluateFogFactorExp2(viewDepth, uniforms.fog_density); 14710 #endif 14711 var foggedColor = decodeGamma3(vec3f(rg.x, rg.y, ba.x)); 14712 foggedColor = mix(uniforms.fog_color, foggedColor, fogFactor); 14713 sharedColor[localIdx] = half4(half3(gammaCorrectOutput(foggedColor)), half(ba.y)); 14714 #else 14715 sharedColor[localIdx] = half4(half(rg.x), half(rg.y), half(ba.x), half(ba.y)); 14716 #endif 14717 #ifdef DEPTH_TEST 14718 sharedViewDepth[localIdx] = bitcast<f32>(depthBuffer[cacheIdx]); 14719 #endif 14720 #endif 14721 } 14722 workgroupBarrier(); 14723 if (!threadDone) { 14724 let batchCount = min(BATCH_SIZE, tileCount - batch * BATCH_SIZE); 14725 for (var i: u32 = 0u; i < batchCount; i++) { 14726 let center = sharedCenterScreen[i]; 14727 let coeffs = sharedCoeffs[i]; 14728 #ifdef PICK_MODE 14729 let splatOpacity = sharedOpacity[i]; 14730 let splatPickId = sharedPickId[i]; 14731 let splatDepth = sharedViewDepth[i]; 14732 let d = p00 - center; 14733 let dxV = vec4f(d.x, d.x + 1.0, d.x, d.x + 1.0); 14734 let dyV = vec4f(d.y, d.y, d.y + 1.0, d.y + 1.0); 14735 let power4 = coeffs.x * dxV * dxV + coeffs.z * dxV * dyV + coeffs.y * dyV * dyV; 14736 if (all(power4 <= vec4f(sharedPowerCutoff[i]))) { 14737 continue; 14738 } 14739 evalSplatPick(p00, center, coeffs.x, coeffs.y, coeffs.z, splatOpacity, splatPickId, splatDepth, clipH, &pickId00, &dAcc00, &wAcc00, &T00); 14740 evalSplatPick(p10, center, coeffs.x, coeffs.y, coeffs.z, splatOpacity, splatPickId, splatDepth, clipH, &pickId10, &dAcc10, &wAcc10, &T10); 14741 evalSplatPick(p01, center, coeffs.x, coeffs.y, coeffs.z, splatOpacity, splatPickId, splatDepth, clipH, &pickId01, &dAcc01, &wAcc01, &T01); 14742 evalSplatPick(p11, center, coeffs.x, coeffs.y, coeffs.z, splatOpacity, splatPickId, splatDepth, clipH, &pickId11, &dAcc11, &wAcc11, &T11); 14743 if (all(vec4<half>(T00, T10, T01, T11) < half4(ALPHA_THRESHOLD))) { 14744 threadDone = true; 14745 break; 14746 } 14747 #else 14748 let splatColor = sharedColor[i]; 14749 #ifdef DEPTH_TEST 14750 let splatDepth = sharedViewDepth[i]; 14751 if (all(vec4f(splatDepth) > sceneDepth)) { 14752 threadDone = true; 14753 break; 14754 } 14755 #endif 14756 let d = p00 - center; 14757 let dxV = vec4f(d.x, d.x + 1.0, d.x, d.x + 1.0); 14758 let dyV = vec4f(d.y, d.y, d.y + 1.0, d.y + 1.0); 14759 let power4 = coeffs.x * dxV * dxV + coeffs.z * dxV * dyV + coeffs.y * dyV * dyV; 14760 if (all(power4 <= vec4f(sharedPowerCutoff[i]))) { 14761 continue; 14762 } 14763 let gauss4 = (half4(exp(power4)) - half4(EXP4)) * half4(INV_EXP4); 14764 let alpha4 = min(half4(0.99), half4(splatColor.a) * gauss4); 14765 let newT = T * (half4(1.0) - alpha4);
14766 var valid = (power4 > vec4f(-4.0)) & (alpha4 > half4(ALPHA_THRESHOLD)) & (T >= half4(ALPHA_THRESHOLD)); 14767 #ifdef DEPTH_TEST 14768 valid = valid & (vec4f(splatDepth) <= sceneDepth); 14769 #endif 14770 let weight = alpha4 * T * select(half4(0.0), half4(1.0), valid); 14771 c00 += splatColor.rgb * weight.x; 14772 c10 += splatColor.rgb * weight.y; 14773 c01 += splatColor.rgb * weight.z; 14774 c11 += splatColor.rgb * weight.w; 14775 T = select(T, newT, valid); 14776 #ifdef HEATMAP_MODE 14777 processedCount += 1u; 14778 #endif 14779 if (all(T < half4(ALPHA_THRESHOLD))) { 14780 threadDone = true; 14781 break; 14782 } 14783 #endif 14784 } 14785 } 14786 workgroupBarrier(); 14787 } 14788 #ifdef HEATMAP_MODE 14789 atomicAdd(&sharedHeatCount, processedCount); 14790 workgroupBarrier(); 14791 let avgCount = f32(atomicLoad(&sharedHeatCount)) / 64.0; 14792 let heatColor = vec4f(heatmapColor(avgCount), 1.0); 14793 if (basePixel.x < uniforms.screenWidth && basePixel.y < uniforms.screenHeight) { 14794 textureStore(outputTexture, basePixel, heatColor); 14795 } 14796 if (basePixel.x + 1u < uniforms.screenWidth && basePixel.y < uniforms.screenHeight) { 14797 textureStore(outputTexture, vec2u(basePixel.x + 1u, basePixel.y), heatColor); 14798 } 14799 if (basePixel.x < uniforms.screenWidth && basePixel.y + 1u < uniforms.screenHeight) { 14800 textureStore(outputTexture, vec2u(basePixel.x, basePixel.y + 1u), heatColor); 14801 } 14802 if (basePixel.x + 1u < uniforms.screenWidth && basePixel.y + 1u < uniforms.screenHeight) { 14803 textureStore(outputTexture, vec2u(basePixel.x + 1u, basePixel.y + 1u), heatColor); 14804 } 14805 #else 14806 if (basePixel.x < uniforms.screenWidth && basePixel.y < uniforms.screenHeight) { 14807 #ifdef PICK_MODE 14808 textureStore(pickIdTexture, basePixel, vec4u(pickId00, 0u, 0u, 0u)); 14809 textureStore(pickDepthTexture, basePixel, vec4f(dAcc00, wAcc00, 0.0, 0.0)); 14810 #else 14811 textureStore(outputTexture, basePixel, vec4f(decodeGamma3(vec3f(c00)), f32(half(1.0) - T.x))); 14812 #endif 14813 } 14814 if (basePixel.x + 1u < uniforms.screenWidth && basePixel.y < uniforms.screenHeight) { 14815 let px10 = vec2u(basePixel.x + 1u, basePixel.y); 14816 #ifdef PICK_MODE 14817 textureStore(pickIdTexture, px10, vec4u(pickId10, 0u, 0u, 0u)); 14818 textureStore(pickDepthTexture, px10, vec4f(dAcc10, wAcc10, 0.0, 0.0)); 14819 #else 14820 textureStore(outputTexture, px10, vec4f(decodeGamma3(vec3f(c10)), f32(half(1.0) - T.y))); 14821 #endif 14822 } 14823 if (basePixel.x < uniforms.screenWidth && basePixel.y + 1u < uniforms.screenHeight) { 14824 let px01 = vec2u(basePixel.x, basePixel.y + 1u); 14825 #ifdef PICK_MODE 14826 textureStore(pickIdTexture, px01, vec4u(pickId01, 0u, 0u, 0u)); 14827 textureStore(pickDepthTexture, px01, vec4f(dAcc01, wAcc01, 0.0, 0.0)); 14828 #else 14829 textureStore(outputTexture, px01, vec4f(decodeGamma3(vec3f(c01)), f32(half(1.0) - T.z))); 14830 #endif 14831 } 14832 if (basePixel.x + 1u < uniforms.screenWidth && basePixel.y + 1u < uniforms.screenHeight) { 14833 let px11 = vec2u(basePixel.x + 1u, basePixel.y + 1u); 14834 #ifdef PICK_MODE 14835 textureStore(pickIdTexture, px11, vec4u(pickId11, 0u, 0u, 0u)); 14836 textureStore(pickDepthTexture, px11, vec4f(dAcc11, wAcc11, 0.0, 0.0)); 14837 #else 14838 textureStore(outputTexture, px11, vec4f(decodeGamma3(vec3f(c11)), f32(half(1.0) - T.w))); 14839 #endif 14840 } 14841 #endif 14842} 14843`,wu=1/255,Fd=8,Kr=64,PV=8;class IV{device;pickMode;_countShader=null;_countBindGroupFormat=null;_countCompute=null;_countShaderFisheye=null;_countBindGroupFormatFisheye=null;_countComputeFisheye=null;placeEntriesCompute;largeSplatCompute;largePlaceEntriesCompute;classifyCompute;sortCompute;bucketSortCompute;copyCompute;chunkSortCompute;_rasterizeVariants=new Map;prefixSumKernel;_tileSplatCountsBuffer=null;_smallTileListBuffer=null;_largeTileListBuffer=null;_largeTileOverflowBasesBuffer=null;_rasterizeTileListBuffer=null;_tileListCountsBuffer=null;_chunkRangesBuffer=null;_totalChunksBuffer=null;_chunkSortIndirectBuffer=null;_allocatedTileCapacity=0;outputTexture=null;pickIdTexture=null;pickDepthTexture=null;constructor(e,t){this.device=e,this.pickMode=t,this.prefixSumKernel=new Gg(e),t?(this.pickIdTexture=new ce(e,{name:"GSplatLocalPickId",width:4,height:4,format:js,mipmaps:!1,minFilter:Fe,magFilter:Fe,storage:!0}),this.pickDepthTexture=new ce(e,{name:"GSplatLocalPickDepth",width:4,height:4,format:Ge,mipmaps:!1,minFilter:Fe,magFilter:Fe,storage:!0})):this.outputTexture=new ce(e,{name:"GSplatLocalComputeOutput",width:4,height:4,format:Ge,mipmaps:!1,minFilter:Fe,magFilter:Fe,storage:!0})}resizeOutputTextures(e,t){this.pickMode?(this.pickIdTexture?.resize(e,t),this.pickDepthTexture?.resize(e,t)):this.outputTexture?.resize(e,t)}ensureTileBuffers(e){const t=e+1;if(t<=this._allocatedTileCapacity)return;this._tileSplatCountsBuffer?.destroy(),this._smallTileListBuffer?.destroy(),this._largeTileListBuffer?.destroy(),this._largeTileOverflowBasesBuffer?.destroy(),this._rasterizeTileListBuffer?.destroy(),this._tileListCountsBuffer?.destroy(),this._chunkRangesBuffer?.destroy(),this._totalChunksBuffer?.destroy(),this._chunkSortIndirectBuffer?.destroy(),this._allocatedTileCapacity=t,this._tileSplatCountsBuffer=new Se(this.device,t*4,ct|Si),this._smallTileListBuffer=new Se(this.device,e*4),this._largeTileListBuffer=new Se(this.device,e*4),this._largeTileOverflowBasesBuffer=new Se(this.device,e*4),this._rasterizeTileListBuffer=new Se(this.device,e*4),this._tileListCountsBuffer=new Se(this.device,16,ct|Si);const s=e*PV;this._chunkRangesBuffer=new Se(this.device,s*8),this._totalChunksBuffer=new Se(this.device,4,ct),this._chunkSortIndirectBuffer=new Se(this.device,12,ct|Po),this.prefixSumKernel.destroyPasses()}getCountCompute(e,t){if(e){if(!this._countComputeFisheye){const{shader:s,bindGroupFormat:i}=t(this.pickMode,!0);this._countShaderFisheye=s,this._countBindGroupFormatFisheye=i;
14843const r=this.pickMode?"GSplatPickTileCountFisheye":"GSplatLocalTileCountFisheye";this._countComputeFisheye=new Qe(this.device,s,r)}return this._countComputeFisheye}if(!this._countCompute){const{shader:s,bindGroupFormat:i}=t(this.pickMode,!1);this._countShader=s,this._countBindGroupFormat=i;const r=this.pickMode?"GSplatPickTileCount":"GSplatLocalTileCount";this._countCompute=new Qe(this.device,s,r)}return this._countCompute}destroyCountResources(){this._countShader?.destroy(),this._countBindGroupFormat?.destroy(),this._countCompute?.destroy(),this._countShaderFisheye?.destroy(),this._countBindGroupFormatFisheye?.destroy(),this._countComputeFisheye?.destroy(),this._countShader=null,this._countBindGroupFormat=null,this._countCompute=null,this._countShaderFisheye=null,this._countBindGroupFormatFisheye=null,this._countComputeFisheye=null}getRasterizeCompute(e,t,s="none",i=!1){let r=e?"pick":"color";t&&(r+="-depth"),s!=="none"&&(r+=`-fog-${s}`),i&&(r+="-heatmap");let a=this._rasterizeVariants.get(r);if(!a){const{shader:n,bindGroupFormat:o}=this._createRasterizeShaderAndFormat(e,t,s,i),c=new Qe(this.device,n,`GSplatRasterize-${r}`);a={shader:n,bindGroupFormat:o,compute:c},this._rasterizeVariants.set(r,a)}return a.compute}_createRasterizeShaderAndFormat(e,t=!1,s="none",i=!1){const r=this.device,a=s!=="none",n=[new X("screenWidth",le),new X("screenHeight",le),new X("numTilesX",le),new X("nearClip",me),new X("farClip",me),new X("alphaClip",me)];a&&n.push(new X("fog_color",hs),new X("fog_start",me),new X("fog_end",me),new X("fog_density",me));const o=new vt(r,n),c=[new At("uniforms",G),new q("tileEntries",G,!0),new q("tileSplatCounts",G,!0),new q("projCache",G,!0),new q("rasterizeTileList",G,!0),new q("tileListCounts",G,!0),new q("depthBuffer",G,!0)],h=e?[new wd("pickIdTexture",js),new wd("pickDepthTexture",Ge)]:[new wd("outputTexture",Ge)],d=t?[new No("sceneDepthMap",G,ys,da,!1)]:[],u=new Ze(r,[...c,...h,...d]),f=new Map;f.set("{CACHE_STRIDE}",Fd.toString()),e&&f.set("PICK_MODE",""),t&&f.set("DEPTH_TEST",""),i&&f.set("HEATMAP_MODE",""),f.set("GAMMA","SRGB"),f.set("FOG",a?s.toUpperCase():"NONE");const p=e?void 0:new Map([["decodePS",Kl.decodePS]]);a&&p&&(p.set("fogMathPS",Kl.fogMathPS),p.set("gammaPS",Kl.gammaPS));let m="GSplatLocalRasterize";return e?m="GSplatLocalRasterizePick":t&&(m="GSplatLocalRasterizeDepth"),{shader:new tt(r,{name:m,shaderLanguage:de,cshader:AV,cdefines:f.size>0?f:void 0,cincludes:p,computeBindGroupFormat:u,computeUniformBufferFormats:{uniforms:o}}),bindGroupFormat:u}}destroy(){this.destroyCountResources();for(const{shader:e,bindGroupFormat:t,compute:s}of this._rasterizeVariants.values())s.destroy(),e.destroy(),t.destroy();this._tileSplatCountsBuffer?.destroy(),this._smallTileListBuffer?.destroy(),this._largeTileListBuffer?.destroy(),this._largeTileOverflowBasesBuffer?.destroy(),this._rasterizeTileListBuffer?.destroy(),this._tileListCountsBuffer?.destroy(),this._chunkRangesBuffer?.destroy(),this._totalChunksBuffer?.destroy(),this._chunkSortIndirectBuffer?.destroy(),this.prefixSumKernel.destroy(),this.outputTexture?.destroy(),this.pickIdTexture?.destroy(),this.pickDepthTexture?.destroy()}}var yC=` 14844struct Splat { 14845 index: u32, 14846 uv: vec2i 14847} 14848var<private> splat: Splat; 14849fn setSplat(idx: u32) { 14850 splat.index = idx; 14851 splat.uv = vec2i(i32(idx % uniforms.splatTextureSize), i32(idx / uniforms.splatTextureSize)); 14852} 14853`;const am=2.5,S0=2,DV=200,MV=16384,y0=16,x0=65535,nm=8,T0=new Z,w0=new Float32Array(16),C0=new Float32Array(16),E0=new Z,nd=new Q,od=new Float32Array(3);class RV extends Qg{_mainSet;_pickSet=null;framePass;tileComposite;_needsFramePassRegister=!1;_textureSize=0;_minPixelSize=2;_minContribution=3;_alphaClip=.3;_alphaClipForward=wu;_exposure=1;_numSplats=0;_compactedSplatIds=null;_sortElementCountBuffer=null;_projCacheBuffer=null;_tileEntriesBuffer=null;_pairBuffer=null;_countersBuffer=null;_splatPairStartBuffer=null;_splatPairCountBuffer=null;_largeSplatIdsBuffer=null;_largeSplatIdsCapacity=MV;_allocatedLargeSplatCapacity=0;_allocatedSplatCapacity=0;_allocatedEntryCapacity=0;_tileEntryMultiplier=am;_lastBufferSubmitVersion=-1;_lastReadbackEntryCount=-1;_shrinkFrameCount=0;_fisheye=0;_dataSource;_placeEntriesShader;_placeEntriesBindGroupFormat;_placeEntryPrepShader;_placeEntryPrepBindGroupFormat;_placeEntryPrepDispatchBuffer=null;_placeEntryPrepCompute=null;_largeSplatShader;_largeSplatBindGroupFormat;_largeSplatPrepShader;_largeSplatPrepBindGroupFormat;_largeSplatDispatchBuffer=null;_largeSplatPrepCompute=null;_largePlaceEntriesShader;_largePlaceEntriesBindGroupFormat;_classifyShader;_classifyBindGroupFormat;_sortShader;_sortBindGroupFormat;_bucketSortShader;_bucketSortBindGroupFormat;_copyShader;_copyBindGroupFormat;_chunkSortShader;_chunkSortBindGroupFormat;constructor(e,t,s,i,r){super(e,t,s,i,r),this._dataSource=r,this._createSharedShaders(),this._mainSet=this._createDispatchSet(!1),this.framePass=new uV(this);const a=s.camera;this.tileComposite=new bV(e,t,n=>{const o=this.renderMode??0;return a.camera===n&&(o&xs)!==0&&this._mainSet._rasterizeTileListBuffer!==null})}setDataSource(e){this._dataSource=e}destroy(){this._unregisterFramePass(),this.renderMode&&this.renderMode&xs&&this.layer.removeMeshInstances([this.tileComposite.meshInstance],!0),this._mainSet.destroy(),this._pickSet?.destroy(),this._placeEntriesShader.destroy(),this._placeEntriesBindGroupFormat.destroy(),this._placeEntryPrepShader.destroy(),this._placeEntryPrepBindGroupFormat.destroy(),this._placeEntryPrepDispatchBuffer?.destroy(),this._largeSplatShader.destroy(),this._largeSplatBindGroupFormat.destroy(),this._largeSplatPrepShader.destroy(),this._largeSplatPrepBindGroupFormat.destroy(),this._largeSplatDispatchBuffer?.destroy(),this._largePlaceEntriesShader.destroy(),this._largePlaceEntriesBindGroupFormat.destroy(),this._classifyShader.destroy(),this._classifyBindGroupFormat.destroy(),this._sortShader.destroy(),this._sortBindGroupFormat.destroy(),this._bucketSortShader.destroy(),this._bucketSortBindGroupFormat.destroy(),this._copyShader.destroy(),this._copyBindGroupFormat.destroy(),this._chunkSortShader.destroy(),this._chunkSortBindGroupFormat.destroy(),this._projCacheBuffer?.destroy(),this._depthBuffer?.destroy(),this._tileEntriesBuffer?.destroy(),this._pairBuffer?.destroy(),this._countersBuffer?.destroy(),this._splatPairStartBuffer?.destroy(),this._splatPairCountBuffer?.destroy(),this._largeSplatIdsBuffer?.destroy(),this.tileComposite.destroy(),super.destroy()}get material(){return this.tileComposite.material}setRenderMode(e){const s=((this.renderMode??0)&xs)!==0,i=(e&xs)!==0;!s&&i&&(this.layer.addMeshInstances([this.tileComposite.meshInstance],!0),this._registerFramePass()),s&&!i&&(this.layer.removeMeshInstances([this.tileComposite.meshInstance],!0),this._unregisterFramePass()),super.setRenderMode(e)}
14853frameUpdate(e,t,s){this._needsFramePassRegister&&this._registerFramePass(),this._minPixelSize=e.minPixelSize,this._minContribution=e.minContribution,this._alphaClip=e.alphaClip,this._alphaClipForward=e.alphaClipForward,this._exposure=t??1,this._fisheye=e.fisheye,this._fogParams=s??null,this._debugMode=e.debug;const i=this._dataSource.format.hash;i!==this._formatHash&&(this._formatHash=i,this._invalidateCountCompute())}setCompactedData(e,t,s,i){this._compactedSplatIds=e,this._sortElementCountBuffer=t,this._textureSize=s,this._numSplats=i}_registerFramePass(){const e=this.cameraNode.camera?.camera;e?(e.beforePasses.includes(this.framePass)||e.beforePasses.push(this.framePass),this._needsFramePassRegister=!1):this._needsFramePassRegister=!0}_unregisterFramePass(){this._needsFramePassRegister=!1;const e=this.cameraNode.camera?.camera;if(e){const t=e.beforePasses.indexOf(this.framePass);t!==-1&&e.beforePasses.splice(t,1)}}resizeOutputTexture(e,t){this._mainSet.resizeOutputTextures(e,t)}_ensureSharedBuffers(e){const t=this.device,s=t.submitVersion!==this._lastBufferSubmitVersion,i=this._lastReadbackEntryCount;if(i!==-1){this._lastReadbackEntryCount=-1;const o=this._allocatedEntryCapacity;if(o>0&&i<o/2?this._shrinkFrameCount++:this._shrinkFrameCount=0,this._shrinkFrameCount>=DV&&e>0){const c=Math.max(am,i/e*S0);this._tileEntryMultiplier=Math.max(c,this._tileEntryMultiplier*.9),this._shrinkFrameCount=0}}if(!s)return;e>this._allocatedSplatCapacity&&(this._projCacheBuffer?.destroy(),this._depthBuffer?.destroy(),this._splatPairStartBuffer?.destroy(),this._splatPairCountBuffer?.destroy(),this._allocatedSplatCapacity=e,this._projCacheBuffer=new Se(t,e*Fd*4),this._depthBuffer=new Se(t,e*4),this._splatPairStartBuffer=new Se(t,e*4),this._splatPairCountBuffer=new Se(t,e*4)),this._countersBuffer||(this._countersBuffer=new Se(t,8,ct|Si)),this._largeSplatIdsCapacity>this._allocatedLargeSplatCapacity&&(this._largeSplatIdsBuffer?.destroy(),this._allocatedLargeSplatCapacity=this._largeSplatIdsCapacity,this._largeSplatIdsBuffer=new Se(t,this._largeSplatIdsCapacity*4));const r=Math.ceil(e*this._tileEntryMultiplier),a=r>this._allocatedEntryCapacity,n=this._allocatedEntryCapacity>0&&r*2<this._allocatedEntryCapacity;(a||n)&&(this._tileEntriesBuffer?.destroy(),this._pairBuffer?.destroy(),this._allocatedEntryCapacity=r,this._tileEntriesBuffer=new Se(t,r*4,ct),this._pairBuffer=new Se(t,r*4)),this._lastBufferSubmitVersion=t.submitVersion}dispatch(){const e=this._mainSet,t=e.outputTexture;if(!t)return;const s=t.width,i=t.height;this._dispatchPipeline(e,s,i,!1),this.tileComposite.update(this._lastDrawSlot,t,e._rasterizeTileListBuffer,this._lastNumTilesX,s,i)}dispatchPick(e,t,s){this._pickSet||(this._pickSet=this._createDispatchSet(!0));const i=this._pickSet;return i.resizeOutputTextures(t,s),this._dispatchPipeline(i,t,s,!0),this.tileComposite.prepareForPicking(this._lastDrawSlot,i.pickIdTexture,i.pickDepthTexture,i._rasterizeTileListBuffer,this._lastNumTilesX,t,s)}_lastDrawSlot=0;_lastNumTilesX=0;_dispatchPipeline(e,t,s,i){const r=this._numSplats;
14853if(!this._compactedSplatIds||!this._sortElementCountBuffer||r===0)return;const a=this.device;let n=Math.ceil(t/y0),o=Math.ceil(s/y0);if(n*o>x0){const N=Math.sqrt(x0/(n*o));n=Math.max(1,Math.floor(n*N)),o=Math.max(1,Math.floor(o*N))}const c=n*o;this._ensureSharedBuffers(r),e.ensureTileBuffers(c);const h=this._allocatedEntryCapacity,d=this._dataSource,u=this.cameraNode.camera,f=u.camera,p=f.viewMatrix,m=!!u.renderTarget?.flipY,_=a.isWebGPU;T0.mul2(cs.applyShaderProjectionTransform(f.projectionMatrix,E0,m,_),p),w0.set(T0.data),C0.set(p.data);const g=t*E0.data[0],v=i?this._alphaClip:Math.max(wu,this._alphaClipForward);this.fisheyeProj.update(this._fisheye,u.fov,f.projectionMatrix);const x=this.fisheyeProj.enabled,y=(N,k)=>this._createCountShaderAndFormat(N,k),S=e.getCountCompute(x,y);this._placeEntryPrepCompute.setParameter("sortElementCount",this._sortElementCountBuffer),this._placeEntryPrepCompute.setParameter("dispatchArgs",this._placeEntryPrepDispatchBuffer),this._placeEntryPrepCompute.setupDispatch(1,1,1),a.computeDispatch([this._placeEntryPrepCompute],"GSplatLocalDispatchPrep"),e._tileSplatCountsBuffer.clear(),this._countersBuffer.clear(),S.setParameter("compactedSplatIds",this._compactedS
14853platIds),S.setParameter("sortElementCount",this._sortElementCountBuffer),S.setParameter("projCache",this._projCacheBuffer),S.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),S.setParameter("pairBuffer",this._pairBuffer),S.setParameter("countersBuffer",this._countersBuffer),S.setParameter("splatPairStart",this._splatPairStartBuffer),S.setParameter("splatPairCount",this._splatPairCountBuffer),S.setParameter("largeSplatIds",this._largeSplatIdsBuffer),S.setParameter("depthBuffer",this._depthBuffer);for(const N of d.format.streams)S.setParameter(N.name,d.getTexture(N.name));for(const N of d.format.extraStreams)S.setParameter(N.name,d.getTexture(N.name));if(S.setParameter("splatTextureSize",this._textureSize),S.setParameter("numTilesX",n),S.setParameter("numTilesY",o),S.setParameter("viewProj",w0),S.setParameter("viewMatrix",C0),S.setParameter("focal",g),S.setParameter("viewportWidth",t),S.setParameter("viewportHeight",s),S.setParameter("nearClip",f.nearClip),S.setParameter("farClip",f.farClip),S.setParameter("minPixelSize",this._minPixelSize*.5),S.setParameter("isOrtho",f.projection===Sn?1:0),S.setParameter("exposure",this._exposure),S.setParameter("alphaClip",v),S.setParameter("minContribution",this._minContribution),x){const N=this.fisheyeProj;S.setParameter("fisheye_k",N.k),S.setParameter("fisheye_inv_k",N.invK),S.setParameter("fisheye_projMat00",N.projMat00),S.setParameter("fisheye_projMat11",N.projMat11)}S.setupIndirectDispatch(0,this._placeEntryPrepDispatchBuffer),a.computeDispatch([S],i?"GSplatPickTileCount":"GSplatLocalTileCount"),this._largeSplatPrepCompute.setParameter("countersBuffer",this._countersBuffer),this._largeSplatPrepCompute.setParameter("dispatchArgs",this._largeSplatDispatchBuffer),this._largeSplatPrepCompute.setParameter("largeSplatIds",this._largeSplatIdsBuffer),this._largeSplatPrepCompute.setupDispatch(1,1,1),a.computeDispatch([this._largeSplatPrepCompute],i?"GSplatPickLargeSplatPrep":"GSplatLocalLargeSplatPrep"),e.largeSplatCompute.setParameter("projCache",this._projCacheBuffer),e.largeSplatCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.largeSplatCompute.setParameter("pairBuffer",this._pairBuffer),e.largeSplatCompute.setParameter("countersBuffer",this._countersBuffer),e.largeSplatCompute.setParameter("splatPairStart",this._splatPairStartBuffer),e.largeSplatCompute.setParameter("splatPairCount",this._splatPairCountBuffer),e.largeSplatCompute.setParameter("largeSplatIds",this._largeSplatIdsBuffer),e.largeSplatCompute.setParameter("numTilesX",n),e.largeSplatCompute.setParameter("numTilesY",o),e.largeSplatCompute.setParameter("viewportWidth",t),e.largeSplatCompute.setParameter("viewportHeight",s),e.largeSplatCompute.setParameter("alphaClip",v),e.largeSplatCompute.setupIndirectDispatch(0,this._largeSplatDispatchBuffer),a.computeDispatch([e.largeSplatCompute],i?"GSplatPickLargeTileCount":"GSplatLocalLargeTileCount"),e.prefixSumKernel.resize(e._tileSplatCountsBuffer,c+1),e.prefixSumKernel.dispatch(a),e.placeEntriesCompute.setParameter("pairBuffer",this._pairBuffer),e.placeEntriesCompute.setParameter("splatPairStart",this._splatPairStartBuffer),e.placeEntriesCompute.setParameter("splatPairCount",this._splatPairCountBuffer),e.placeEntriesCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.placeEntriesCompute.setParameter("tileEntries",this._tileEntriesBuffer),e.placeEntriesCompute.setParameter("sortElementCount",this._sortElementCountBuffer),e.placeEntriesCompute.setupIndirectDispatch(1,this._placeEntryPrepDispatchBuffer),a.computeDispatch([e.placeEntriesCompute],i?"GSplatPickPlaceEntries":"GSplatLocalPlaceEntries"),e.largePlaceEntriesCompute.setParameter("pairBuffer",this._pairBuffer),e.largePlaceEntriesCompute.setParameter("splatPairStart",this._splatPairStartBuffer),e.largePlaceEntriesCompute.setParameter("splatPairCount",this._splatPairCountBuffer),e.largePlaceEntriesCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.largePlaceEntriesCompute.setParameter("tileEntries",this._tileEntriesBuffer),e.largePlaceEntriesCompute.setParameter("largeSplatIds",this._largeSplatIdsBuffer),e.largePlaceEntriesCompute.setParameter("countersBuffer",this._countersBuffer),e.largePlaceEntriesCompute.setupIndirectDispatch(0,this._largeSplatDispatchBuffer),a.computeDispatch([e.largePlaceEntriesCompute],i?"GSplatPickLargePlaceEntries":"GSplatLocalLargePlaceEntries"),e._tileListCountsBuffer.clear(),e._totalChunksBuffer.clear(),e._chunkSortIndirectBuffer.clear();const T=a.getIndirectDispatchSlot(3),w=a.getIndirectDrawSlot(1);e.classifyCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.classifyCompute.setParameter("smallTileList",e._smallTileListBuffer),e.classifyCompute.setParameter("largeTileList",e._largeTileListBuffer),e.classifyCompute.setParameter("rasterizeTileList",e._rasterizeTileListBuffer),e.classifyCompute.setParameter("tileListCounts",e._tileListCountsBuffer),e.classifyCompute.setParameter("indirectDispatchArgs",a.indirectDispatchBuffer),e.classifyCompute.setParameter("largeTileOverflowBases",e._largeTileOverflowBasesBuffer),e.classifyCompute.setParameter("indirectDrawArgs",a.indirectDrawBuffer),e.classifyCompute.setParameter("numTiles",c),e.classifyCompute.setParameter("dispatchSlotOffset",T*3),e.classifyCompute.setParameter("bufferCapacity",h),e.classifyCompute.setParameter("maxWorkgroupsPerDim",a.limits.maxComputeWorkgroupsPerDimension||65535),e.classifyCompute.setParameter("drawSlot",w
14853),e.classifyCompute.setupDispatch(1,1,1),a.computeDispatch([e.classifyCompute],i?"GSplatPickClassify":"GSplatLocalClassify"),e.bucketSortCompute.setParameter("tileEntries",this._tileEntriesBuffer),e.bucketSortCompute.setParameter("largeTileOverflowBases",e._largeTileOverflowBasesBuffer),e.bucketSortCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.bucketSortCompute.setParameter("depthBuffer",this._depthBuffer),e.bucketSortCompute.setParameter("largeTileList",e._largeTileListBuffer),e.bucketSortCompute.setParameter("chunkRanges",e._chunkRangesBuffer),e.bucketSortCompute.setParameter("totalChunks",e._totalChunksBuffer),e.bucketSortCompute.setParameter("tileListCounts",e._tileListCountsBuffer),e.bucketSortCompute.setParameter("bufferCapacity",h),e.bucketSortCompute.setParameter("maxChunks",c*nm),e.bucketSortCompute.setupIndirectDispatch(T+1),a.computeDispatch([e.bucketSortCompute],i?"GSplatPickBucketSort":"GSplatLocalBucketSort"),e.copyCompute.setParameter("totalChunks",e._totalChunksBuffer),e.copyCompute.setParameter("chunkSortIndirect",e._chunkSortIndirectBuffer),e.copyCompute.setParameter("maxChunks",c*nm),e.copyCompute.setParameter("maxWorkgroupsPerDim",a.limits.maxComputeWorkgroupsPerDimension||65535),e.copyCompute.setupDispatch(1,1,1),a.computeDispatch([e.copyCompute],i?"GSplatPickCopy":"GSplatLocalCopy"),e.sortCompute.setParameter("tileEntries",this._tileEntriesBuffer),e.sortCompute.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),e.sortCompute.setParameter("depthBuffer",this._depthBuffer),e.sortCompute.setParameter("smallTileList",e._smallTileListBuffer),e.sortCompute.setParameter("tileListCounts",e._tileListCountsBuffer),e.sortCompute.setupIndirectDispatch(T),a.computeDispatch([e.sortCompute],i?"GSplatPickTileSort":"GSplatLocalTileSort"),e.chunkSortCompute.setParameter("tileEntries",this._tileEntriesBuffer),e.chunkSortCompute.setParameter("depthBuffer",this._depthBuffer),e.chunkSortCompute.setParameter("chunkRanges",e._chunkRangesBuffer),e.chunkSortCompute.setParameter("totalChunks",e._totalChunksBuffer),e.chunkSortCompute.setParameter("maxChunks",c*nm),e.chunkSortCompute.setupIndirectDispatch(0,e._chunkSortIndirectBuffer),a.computeDispatch([e.chunkSortCompute],i?"GSplatPickChunkSort":"GSplatLocalChunkSort");const b=f.shaderParams.sceneDepthMapLinear?a.scope.resolve("uSceneDepthMap").value:null,I=!i&&b,P=this._fogParams,L=P&&P.type!==vn?P.type:"none",O=!i&&this._debugMode===e_,D=e.getRasterizeCompute(i,I,L,O);D.setParameter("screenWidth",t),D.setParameter("screenHeight",s),D.setParameter("numTilesX",n),D.setParameter("nearClip",f.nearClip),D.setParameter("farClip",f.farClip),D.setParameter("alphaClip",v),L!=="none"&&(nd.linear(P.color),od[0]=nd.r,od[1]=nd.g,od[2]=nd.b,D.setParameter("fog_color",od),D.setParameter("fog_start",P.start),D.setParameter("fog_end",P.end),D.setParameter("fog_density",P.density)),D.setParameter("tileEntries",this._tileEntriesBuffer),D.setParameter("tileSplatCounts",e._tileSplatCountsBuffer),D.setParameter("projCache",this._projCacheBuffer),D.setParameter("rasterizeTileList",e._rasterizeTileListBuffer),D.setParameter("tileListCounts",e._tileListCountsBuffer),D.setParameter("depthBuffer",this._depthBuffer),i?(D.setParameter("pickIdTexture",e.pickIdTexture),D.setParameter("pickDepthTexture",e.pickDepthTexture)):(D.setParameter("outputTexture",e.outputTexture),I&&D.setParameter("sceneDepthMap",b)),D.setupIndirectDispatch(T+2),a.computeDispatch([D],i?"GSplatPickRasterize":"GSplatLocalRasterize"),this._lastDrawSlot=w,this._lastNumTilesX=n,this._scheduleReadback(r,c,e)}_scheduleReadback(e,t,s){if(e===0)return;const i=e,r=s._tileSplatCountsBuffer.read(t*4,4),a=s._tileListCountsBuffer.read(12,4),n=this._countersBuffer.read(4,4);Promise.all([r,a,n]).then(([o,c,h])=>{const d=new Uint32Array(o.buffer,o.byteOffset,1)[0],u=new Uint32Array(c.buffer,c.byteOffset,1)[0],f=d+u;i>0&&(this._tileEntryMultiplier=Math.max(this._tileEntryMultiplier,f/i*S0),this._tileEntryMultiplier=Math.max(this._tileEntryMultiplier,am)),this._lastReadbackEntryCount=f;const p=new Uint32Array(h.buffer,h.byteOffset,1)[0];p>this._largeSplatIdsCapacity&&(this._largeSplatIdsCapacity=Math.ceil(p*1.2))}).catch(()=>{})}_invalidateCountCompute(){this._mainSet.destroyCountResources(),this._pickSet?.destroyCountResources()}_createCommonIncludes(){const e=new Map;return e.set("gsplatCommonCS",vC),e.set("gsplatTileIntersectCS",SC),e}_createBitonicIncludes(){const e=new Map;return e.set("gsplatLocalBitonicCS",EV),e}_createSharedShaders(){const e=this.device;this._placeEntriesBindGroupFormat=new Ze(e,[new q("pairBuffer",G,!0),new q("splatPairStart",G,!0),new q("splatPairCount",G,!0),new q("tileSplatCounts",G,!0),new q("tileEntries",G),new q("sortElementCount",G,!0)]),this._placeEntriesShader=new tt(e,{name:"GSplatLocalPlaceEntries",shaderLanguage:de,cshader:gV,computeBindGroupFormat:this._placeEntriesBindGroupFormat});{const t=e.limits.maxComputeWorkgroupsPerDimension||65535,s=new Map;s.set("{MAX_DIM}",t.toString()),s.set("{SPLATS_PER_WG}","256"),s.set("{SPLATS_PER_WG_MINUS_1}
14853","255"),this._placeEntryPrepBindGroupFormat=new Ze(e,[new q("sortElementCount",G,!0),new q("dispatchArgs",G)]),this._placeEntryPrepShader=new tt(e,{name:"GSplatLocalPlaceEntryPrep",shaderLanguage:de,cshader:fV,cdefines:s,computeBindGroupFormat:this._placeEntryPrepBindGroupFormat}),this._placeEntryPrepDispatchBuffer=new Se(e,24,Po),this._placeEntryPrepCompute=new Qe(e,this._placeEntryPrepShader)}{const t=this._createCommonIncludes(),s=new vt(e,[new X("numTilesX",le),new X("numTilesY",le),new X("viewportWidth",me),new X("viewportHeight",me),new X("alphaClip",me)]);this._largeSplatBindGroupFormat=new Ze(e,[new q("projCache",G,!0),new q("tileSplatCounts",G),new q("pairBuffer",G),new q("countersBuffer",G),new q("splatPairStart",G),new q("splatPairCount",G),new q("largeSplatIds",G,!0),new At("uniforms",G)]);const i=new Map;i.set("{CACHE_STRIDE}",Fd.toString()),this._largeSplatShader=new tt(e,{name:"GSplatLocalTileCountLarge",shaderLanguage:de,cshader:_V,cincludes:t,cdefines:i,computeBindGroupFormat:this._largeSplatBindGroupFormat,computeUniformBufferFormats:{uniforms:s}})}{const t=e.limits.maxComputeWorkgroupsPerDimension||65535,s=new Map;s.set("{MAX_DIM}",t.toString()),this._largeSplatPrepBindGroupFormat=new Ze(e,[new q("countersBuffer",G,!0),new q("dispatchArgs",G),new q("largeSplatIds",G,!0)]),this._largeSplatPrepShader=new tt(e,{name:"GSplatLocalLargeSplatPrep",shaderLanguage:de,cshader:pV,cdefines:s,computeBindGroupFormat:this._largeSplatPrepBindGroupFormat}),this._largeSplatDispatchBuffer=new Se(e,12,Po),this._largeSplatPrepCompute=new Qe(e,this._largeSplatPrepShader)}this._largePlaceEntriesBindGroupFormat=new Ze(e,[new q("pairBuffer",G,!0),new q("splatPairStart",G,!0),new q("splatPairCount",G,!0),new q("tileSplatCounts",G,!0),new q("tileEntries",G),new q("largeSplatIds",G,!0),new q("countersBuffer",G,!0)]),this._largePlaceEntriesShader=new tt(e,{name:"GSplatLocalPlaceEntriesLarge",shaderLanguage:de,cshader:vV,computeBindGroupFormat:this._largePlaceEntriesBindGroupFormat});{const t=new vt(e,[new X("numTiles",le),new X("dispatchSlotOffset",le),new X("bufferCapacity",le),new X("maxWorkgroupsPerDim",le),new X("drawSlot",le)]);this._classifyBindGroupFormat=new Ze(e,[new q("tileSplatCounts",G,!0),new q("smallTileList",G),new q("largeTileList",G),new q("rasterizeTileList",G),new q("tileListCounts",G),new q("indirectDispatchArgs",G),new q("largeTileOverflowBases",G),new At("uniforms",G),new q("indirectDrawArgs",G)]),this._classifyShader=new tt(e,{name:"GSplatLocalClassify",shaderLanguage:de,cshader:yV,computeBindGroupFormat:this._classifyBindGroupFormat,computeUniformBufferFormats:{uniforms:t}})}this._sortBindGroupFormat=new Ze(e,[new q("tileEntries",G),new q("tileSplatCounts",G,!0),new q("depthBuffer",G,!0),new q("smallTileList",G,!0),new q("tileListCounts",G,!0)]),this._sortShader=new tt(e,{name:"GSplatLocalTileSort",shaderLanguage:de,cshader:SV,cincludes:this._createBitonicIncludes(),computeBindGroupFormat:this._sortBindGroupFormat});{const t=new vt(e,[new X("bufferCapacity",le),new X("maxChunks",le)]);this._bucketSortBindGroupFormat=new Ze(e,[new q("tileEntries",G),new q("largeTileOverflowBases",G,!0),new q("tileSplatCounts",G,!0),new q("depthBuffer",G,!0),new q("largeTileList",G,!0),new q("chunkRanges",G),new q("totalChunks",G),new q("tileListCounts",G,!0),new At("uniforms",G)]),this._bucketSortShader=new tt(e,{name:"GSplatLocalBucketSort",shaderLanguage:de,cshader:TV,computeBindGroupFormat:this._bucketSortBindGroupFormat,computeUniformBufferFormats:{uniforms:t}})}{const t=new vt(e,[new X("maxChunks",le),new X("maxWorkgroupsPerDim",le)]);this._copyBindGroupFormat=new Ze(e,[new q("totalChunks",G,!0),new q("chunkSortIndirect",G),new At("uniforms",G)]),this._copyShader=new tt(e,{name:"GSplatLocalCopy",shaderLanguage:de,cshader:CV,computeBindGroupFormat:this._copyBindGroupFormat,computeUniformBufferFormats:{uniforms:t}})}{const t=new vt(e,[new X("maxChunks",le)]);this._chunkSortBindGroupFormat=new Ze(e,[new q("tileEntries",G),new q("depthBuffer",G,!0),new q("chunkRanges",G,!0),new q("totalChunks",G,!0),new At("uniforms",G)]),this._chunkSortShader=new tt(e,{name:"GSplatLocalChunkSort",shaderLanguage:de,cshader:wV,cincludes:this._createBitonicIncludes(),computeBindGroupFormat:this._chunkSortBindGroupFormat,computeUniformBufferFormats:{uniforms:t}})}}_createCountShaderAndFormat(e,t){const s=this.device,i=[new X("splatTextureSize",le),new X("numTilesX",le),new X("numTilesY",le),new X("viewProj",Ss),new X("viewMatrix",Ss),new X("focal",me),new X("viewportWidth",me),new X("viewportHe
14853ight",me),new X("nearClip",me),new X("farClip",me),new X("minPixelSize",me),new X("isOrtho",le),new X("exposure",me),new X("alphaClip",me),new X("minContribution",me)];t&&i.push(new X("fisheye_k",me),new X("fisheye_inv_k",me),new X("fisheye_projMat00",me),new X("fisheye_projMat11",me));const r=new vt(s,i),a=this._dataSource.format,n=[new q("compactedSplatIds",G,!0),new q("sortElementCount",G,!0),new q("projCache",G),new q("tileSplatCounts",G),new At("uniforms",G),new q("pairBuffer",G),new q("countersBuffer",G),new q("splatPairStart",G),new q("splatPairCount",G),new q("largeSplatIds",G),new q("depthBuffer",G)],o=new Ze(s,[...n,...a.getComputeBindFormats()]),c=this._createCommonIncludes();c.set("gsplatComputeSplatCS",yC),c.set("gsplatFormatDeclCS",a.getComputeInputDeclarations(n.length)),c.set("gsplatFormatReadCS",a.getReadCode()),c.set("gsplatProjectCommonCS",gC);const h=new Map;h.set("{CACHE_STRIDE}",Fd.toString()),t&&h.set("GSPLAT_FISHEYE",""),e&&h.set("PICK_MODE","");const d=a.getStream("dataColor");d&&d.format!==Vi&&h.set("GSPLAT_COLOR_FLOAT","");const u=t?"Fisheye":"";return{shader:new tt(s,{name:e?`GSplatLocalTileCountPick${u}`:`GSplatLocalTileCount${u}`,shaderLanguage:de,cshader:mV,cincludes:c,cdefines:h,computeBindGroupFormat:o,computeUniformBufferFormats:{uniforms:r}}),bindGroupFormat:o}}_createDispatchSet(e){const t=this.device,s=new IV(t,e);return s.placeEntriesCompute=new Qe(t,this._placeEntriesShader,e?"GSplatPickPlaceEntries":"GSplatLocalPlaceEntries"),s.largeSplatCompute=new Qe(t,this._largeSplatShader,e?"GSplatPickLargeTileCount":"GSplatLocalLargeTileCount"),s.largePlaceEntriesCompute=new Qe(t,this._largePlaceEntriesShader,e?"GSplatPickLargePlaceEntries":"GSplatLocalLargePlaceEntries"),s.classifyCompute=new Qe(t,this._classifyShader,e?"GSplatPickClassify":"GSplatLocalClassify"),s.sortCompute=new Qe(t,this._sortShader,e?"GSplatPickTileSort":"GSplatLocalTileSort"),s.bucketSortCompute=new Qe(t,this._bucketSortShader,e?"GSplatPickBucketSort":"GSplatLocalBucketSort"),s.copyCompute=new Qe(t,this._copyShader,e?"GSplatPickCopy":"GSplatLocalCopy"),s.chunkSortCompute=new Qe(t,this._chunkSortShader,e?"GSplatPickChunkSort":"GSplatLocalChunkSort"),s}}const LV=` 14854#include "gsplatCommonCS" 14855#include "gsplatTileIntersectCS" 14856@group(0) @binding(0) var<storage, read> compactedSplatIds: array<u32>; 14857@group(0) @binding(1) var<storage, read> sortElementCount: array<u32>; 14858@group(0) @binding(2) var<storage, read_write> projCache: array<u32>; 14859@group(0) @binding(3) var<storage, read_write> sortKeys: array<u32>; 14860@group(0) @binding(4) var<storage, read_write> renderCounter: array<atomic<u32>>; 14861struct BinWeight { 14862 base: f32,
14863 divider: f32 14864} 14865@group(0) @binding(5) var<storage, read> binWeights: array<BinWeight>; 14866struct ProjectorUniforms { 14867 splatTextureSize: u32, 14868 numBins: u32, 14869 isOrtho: u32, 14870 pad0: u32, 14871 viewProj: mat4x4f, 14872 viewMatrix: mat4x4f, 14873 cameraPosition: vec3f, 14874 minPixelSize: f32, 14875 cameraDirection: vec3f, 14876 focal: f32, 14877 viewportWidth: f32, 14878 viewportHeight: f32, 14879 nearClip: f32, 14880 farClip: f32, 14881 alphaClip: f32, 14882 minContribution: f32, 14883 minDist: f32, 14884 invRange: f32, 14885 #ifdef GSPLAT_FISHEYE 14886 fisheye_k: f32, 14887 fisheye_inv_k: f32, 14888 fisheye_projMat00: f32, 14889 fisheye_projMat11: f32, 14890 #endif 14891} 14892@group(0) @binding(6) var<uniform> uniforms: ProjectorUniforms; 14893#include "gsplatComputeSplatCS" 14894#include "gsplatFormatDeclCS" 14895#include "gsplatFormatReadCS" 14896#include "gsplatProjectCommonCS" 14897var<workgroup> wgCount: atomic<u32>; 14898var<workgroup> wgBase: u32; 14899@compute @workgroup_size(256) 14900fn main( 14901 @builtin(global_invocation_id) gid: vec3u, 14902 @builtin(num_workgroups) numWorkgroups: vec3u, 14903 @builtin(local_invocation_index) localIdx: u32 14904) { 14905 if (localIdx == 0u) { 14906 atomicStore(&wgCount, 0u); 14907 } 14908 workgroupBarrier(); 14909 let threadIdx = gid.y * (numWorkgroups.x * 256u) + gid.x; 14910 let numVisible = sortElementCount[0]; 14911 var valid = false; 14912 var clipPos: vec4f = vec4f(0.0); 14913 var v1: vec2f = vec2f(0.0); 14914 var v2: vec2f = vec2f(0.0); 14915 var rgb: vec3f = vec3f(0.0); 14916 var alpha: f32 = 0.0; 14917 var pcId: u32 = 0u; 14918 var sortKey: u32 = 0u; 14919 let projected = projectSplatCommon( 14920 threadIdx, 14921 numVisible, 14922 uniforms.alphaClip, 14923 uniforms.minPixelSize, 14924 uniforms.minContribution, 14925 uniforms.viewMatrix, 14926 uniforms.viewProj, 14927 uniforms.focal, 14928 uniforms.viewportWidth, 14929 uniforms.viewportHeight, 14930 uniforms.nearClip, 14931 uniforms.farClip, 14932 uniforms.isOrtho, 14933 #ifdef GSPLAT_FISHEYE 14934 uniforms.fisheye_k, 14935 uniforms.fisheye_inv_k, 14936 uniforms.fisheye_projMat00, 14937 uniforms.fisheye_projMat11, 14938 #endif 14939 ); 14940 if (projected.valid) { 14941 let center = projected.center; 14942 let opacity = projected.opacity; 14943 let proj = projected.proj; 14944 let mid = 0.5 * (proj.a + proj.c); 14945 let radius = length(vec2f(0.5 * (proj.a - proj.c), proj.b)); 14946 let lambda1 = mid + radius; 14947 let lambda2 = max(mid - radius, 0.1); 14948 let vmin = min(1024.0, min(uniforms.viewportWidth, uniforms.viewportHeight)); 14949 let l1 = 2.0 * min(sqrt(2.0 * lambda1), vmin); 14950 let l2 = 2.0 * min(sqrt(2.0 * lambda2), vmin); 14951 let dir = normalize(vec2f(proj.b, lambda1 - proj.a)); 14952 v1 = l1 * dir; 14953 v2 = l2 * vec2f(dir.y, -dir.x); 14954 #ifdef GSPLAT_FISHEYE 14955 let viewCenter = uniforms.viewMatrix * vec4f(center, 1.0); 14956 let neg_z = -viewCenter.z; 14957 let ndcX = proj.screen.x / uniforms.viewportWidth * 2.0 - 1.0; 14958 let ndcY = proj.screen.y / uniforms.viewportHeight * 2.0 - 1.0; 14959 let depthNdc = clamp( 14960 (neg_z - uniforms.nearClip) / (uniforms.farClip - uniforms.nearClip), 14961 0.0, 1.0 14962 ); 14963 clipPos = vec4f(ndcX, ndcY, depthNdc, 1.0); 14964 #else 14965 clipPos = uniforms.viewProj * vec4f(center, 1.0); 14966 clipPos.z = clamp(clipPos.z, 0.0, abs(clipPos.w)); 14967 #endif 14968 #ifdef RADIAL_SORT 14969 let delta = center - uniforms.cameraPosition; 14970 let radialDist = length(delta); 14971 let dist = (1.0 / uniforms.invRange) - radialDist - uniforms.minDist; 14972 #else 14973 let toSplat = center - uniforms.cameraPosition; 14974 let dist = dot(toSplat, uniforms.cameraDirection) - uniforms.minDist; 14975 #endif 14976 let d = dist * uniforms.invRange * f32(uniforms.numBins); 14977 let binFloat = clamp(d, 0.0, f32(uniforms.numBins) - 0.001); 14978 let bin = u32(binFloat); 14979 let binFrac = binFloat - f32(bin); 14980 sortKey = u32(binWeights[bin].base + binWeights[bin].divider * binFrac); 14981 #ifdef PICK_MODE 14982 pcId = loadPcId().r; 14983 alpha = opacity; 14984 #else 14985 let color = getColor(); 14986 rgb = max(color, vec3f(0.0)); 14987 #if GSPLAT_AA 14988 alpha = opacity * proj.aaFactor; 14989 #else 14990 alpha = opacity; 14991 #endif 14992 #endif 14993 valid = true; 14994 } 14995 var localDst: u32 = 0u; 14996 if (valid) { 14997 localDst = atomicAdd(&wgCount, 1u); 14998 } 14999 workgroupBarrier(); 15000 if (localIdx == 0u) { 15001 let total = atomicLoad(&wgCount); 15002 wgBase = atomicAdd(&renderCounter[0], total); 15003 } 15004 workgroupBarrier(); 15005 if (valid) { 15006 let dst = wgBase + localDst; 15007 let base = dst * {CACHE_STRIDE}u; 15008 projCache[base + 0u] = bitcast<u32>(clipPos.x); 15009 projCache[base + 1u] = bitcast<u32>(clipPos.y); 15010 projCache[base + 2u] = bitcast<u32>(clipPos.z); 15011 projCache[base + 3u] = bitcast<u32>(clipPos.w); 15012 projCache[base + 4u] = pack2x16float(v1); 15013 projCache[base + 5u] = pack2x16float(v2); 15014 #ifdef PICK_MODE 15015 projCache[base + 6u] = pcId;
15016 projCache[base + 7u] = pack2x16float(vec2f(0.0, alpha)); 15017 #else 15018 projCache[base + 6u] = pack2x16float(vec2f(rgb.x, rgb.y)); 15019 projCache[base + 7u] = pack2x16float(vec2f(rgb.z, alpha)); 15020 #endif 15021 sortKeys[dst] = sortKey; 15022 } 15023} 15024`,FV=` 15025${Of} 15026${Bf} 15027${jg} 15028@group(0) @binding(0) var<storage, read> renderCounter: array<u32>; 15029@group(0) @binding(1) var<storage, read_write> indirectDrawArgs: array<DrawIndexedIndirectArgs>; 15030@group(0) @binding(2) var<storage, read_write> numSplatsBuf: array<u32>; 15031@group(0) @binding(3) var<storage, read_write> indirectDispatchArgs: array<u32>; 15032@group(0) @binding(4) var<storage, read_write> sortElementCountBuf: array<u32>; 15033struct WriteArgsUniforms { 15034 drawSlot: u32, 15035 indexCount: u32, 15036 sortSlotBase: u32, 15037 pad0: u32, 15038 sortIndirectInfo: vec4<u32> 15039}; 15040@group(0) @binding(5) var<uniform> uniforms: WriteArgsUniforms; 15041@compute @workgroup_size(1) 15042fn main() { 15043 let count = renderCounter[0]; 15044 let instanceCount = (count + {INSTANCE_SIZE}u - 1u) / {INSTANCE_SIZE}u; 15045 indirectDrawArgs[uniforms.drawSlot] = DrawIndexedIndirectArgs( 15046 uniforms.indexCount, 15047 instanceCount, 15048 0u, 15049 0, 15050 0u 15051 ); 15052 numSplatsBuf[0] = count; 15053 sortElementCountBuf[0] = count; 15054 writeSortIndirectArgs(uniforms.sortSlotBase, count, uniforms.sortIndirectInfo); 15055} 15056`,OV=6*Rt.instanceSize,BV=256,NV=new E,om=new j,b0=new Z,A0=new Float32Array(16),P0=new Float32Array(16),I0=new Z;class kV{device;projCache=null;sortKeys=null;renderCounter=null;binWeightsBuffer=null;binWeightsUtil;_projectorComputes=new Map;_projectorBindGroupFormat=null;_projectorUniformBufferFormat=null;_projectorUniformBufferFormatFisheye=null;_writeIndirectArgsCompute=null;_writeArgsBindGroupFormat=null;_writeArgsUniformBufferFormat=null;_formatVersion=-1;_allocatedCacheCount=0;cameraPositionData=new Float32Array(3);cameraDirectionData=new Float32Array(3);constructor(e){this.device=e,this.binWeightsUtil=new Vl,this.binWeightsBuffer=new Se(e,Vl.NUM_BINS*2*4,Si|ct),this.renderCounter=new Se(e,4,Si|ct),this._createUniformBufferFormats(),this._createWriteIndirectArgsCompute()}destroy(){this.projCache?.destroy(),this.sortKeys?.destroy(),this.renderCounter?.destroy(),this.binWeightsBuffer?.destroy();for(const e of this._projectorComputes.values())e.shader?.destroy();this._projectorComputes.clear(),this._projectorBindGroupFormat?.destroy(),this._writeIndirectArgsCompute?.shader?.destroy(),this._writeArgsBindGroupFormat?.destroy(),this.projCache=null,this.sortKeys=null,this.renderCounter=null,this.binWeightsBuffer=null,this._projectorBindGroupFormat=null,this._projectorUniformBufferFormat=null,this._projectorUniformBufferFormatFisheye=null,this._writeIndirectArgsCompute=null,this._writeArgsBindGroupFormat=null,this._writeArgsUniformBufferFormat=null}_createUniformBufferFormats(){const e=this.device,t=[new X("splatTextureSize",le),new X("numBins",le),new X("isOrtho",le),new X("pad0",le),new X("viewProj",Ss),new X("viewMatrix",Ss),new X("cameraPosition",hs),new X("minPixelSize",me),new X("cameraDirection",hs),new X("focal",me),new X("viewportWidth",me),new X("viewportHeight",me),new X("nearClip",me),new X("farClip",me),new X("alphaClip",me),new X("minContribution",me),new X("minDist",me),new X("invRange",me)];this._projectorUniformBufferFormat=new vt(e,t),this._projectorUniformBufferFormatFisheye=new vt(e,[...t.map(s=>new X(s.name,s.type)),new X("fisheye_k",me),new X("fisheye_inv_k",me),new X("fisheye_projMat00",me),new X("fisheye_projMat11",me)]),this._writeArgsUniformBufferFormat=new vt(e,[new X("drawSlot",le),new X("indexCount",le),new X("sortSlotBase",le),new X("pad0",le),new X("sortIndirectInfo",oa)])}_createWriteIndirectArgsCompute(){const e=this.device;this._writeArgsBindGroupFormat=new Ze(e,[new q("renderCounter",G,!0),new q("indirectDrawArgs",G,!1),new q("numSplatsBuf",G,!1),new q("indirectDispatchArgs",G,!1),new q("sortElementCountBuf",G,!1),new At("uniforms",G)]);const t=new Map([["{INSTANCE_SIZE}",Rt.instanceSize.toString()]]),s=new tt(e,{name:"GSplatProjectorWriteIndirectArgs",shaderLanguage:de,cshader:FV,cdefines:t,computeBindGroupFormat:this._writeArgsBindGroupFormat,computeUniformBufferFormats:{uniforms:this._writeArgsUniformBufferFormat}});this._writeIndirectArgsCompute=new Qe(e,s,"GSplatProjectorWriteIndirectArgs")}_destroyProjectorComputes(){for(const e of this._projectorComputes.values())e.shader?.destroy();this._projectorComputes.clear(),this._projectorBindGroupFormat?.destroy(),this._projectorBindGroupFormat=null}_projectorKey(e,t,s,i){return`${e?"r":"l"}${t?"p":""}${s?"f":""}${i?"a":""}`}_createProjectorCompute(e,t,s,i,r){const a=this.device,n=e.format,o=[new q("compactedS
15056platIds",G,!0),new q("sortElementCount",G,!0),new q("projCache",G),new q("sortKeys",G),new q("renderCounter",G),new q("binWeights",G,!0),new At("uniforms",G)];this._projectorBindGroupFormat||(this._projectorBindGroupFormat=new Ze(a,[...o,...n.getComputeBindFormats()]));const c=new Map;c.set("gsplatCommonCS",vC),c.set("gsplatTileIntersectCS",SC),c.set("gsplatComputeSplatCS",yC),c.set("gsplatFormatDeclCS",n.getComputeInputDeclarations(o.length)),c.set("gsplatFormatReadCS",n.getReadCode()),c.set("gsplatProjectCommonCS",gC);const h=new Map;h.set("{CACHE_STRIDE}",Tu.toString()),t&&h.set("RADIAL_SORT",""),s&&h.set("PICK_MODE",""),i&&h.set("GSPLAT_FISHEYE",""),r&&h.set("GSPLAT_AA","");const d=n.getStream("dataColor");d&&d.format!==Vi&&h.set("GSPLAT_COLOR_FLOAT","");const u=`GSplatProjector${t?"Radial":"Linear"}${s?"Pick":""}${i?"Fisheye":""}${r?"Aa":""}`,f=i?this._projectorUniformBufferFormatFisheye:this._projectorUniformBufferFormat,p=new tt(a,{name:u,shaderLanguage:de,cshader:LV,cincludes:c,cdefines:h,computeBindGroupFormat:this._projectorBindGroupFormat,computeUniformBufferFormats:{uniforms:f}});return new Qe(a,p,u)}_getProjectorCompute(e,t,s=!1,i=!1,r=!1){const a=e.format;this._formatVersion!==a.extraStreamsVersion&&(this._destroyProjectorComputes(),this._formatVersion=a.extraStreamsVersion);const n=this._projectorKey(t,s,i,r);let o=this._projectorComputes.get(n);return o||(o=this._createProjectorCompute(e,t,s,i,r),this._projectorComputes.set(n,o)),o}_ensureCapacity(e){e>this._allocatedCacheCount&&(this.projCache?.destroy(),this.sortKeys?.destroy(),this._allocatedCacheCount=e,this.projCache=new Se(this.device,e*Tu*4),this.sortKeys=new Se(this.device,e*4,Si))}dispatch(e){const{workBuffer:t,cameraNode:s,compactedSplatIds:i,sortElementCountBuffer:r,totalCapacity:a,radialSort:n,numBits:o,minDist:c,maxDist:h,alphaClip:d,minPixelSize:u,minContribution:f,viewportWidth:p,viewportHeight:m,flipY:_,pickMode:g=!1,fisheyeProj:v,antiAlias:x=!1}=e,y=!!v?.enabled,S=x&&!g;this._ensureCapacity(a),this.renderCounter.clear();const T=this._getProjectorCompute(t,n,g,y,S),w=s.getPosition(),b=s.getWorldTransform().getZ(NV).normalize(),I=h-c,P=I>0?1/I:1,L=1<<o,O=Vl.computeCameraBin(n,c,I),D=this.binWeightsUtil.compute(O,L);this.binWeightsBuffer.write(0,D),T.setParameter("compactedSplatIds",i),T.setParameter("sortElementCount",r),T.setParameter("projCache",this.projCache),T.setParameter("sortKeys",this.sortKeys),T.setParameter("renderCounter",this.renderCounter),T.setParameter("binWeights",this.binWeightsBuffer);for(const U of t.format.resourceStreams){const B=t.getTexture(U.name);B&&T.setParameter(U.name,B)}const k=s.camera.camera,A=k.viewMatrix,M=this.device.isWebGPU;b0.mul2(cs.applyShaderProjectionTransform(k.projectionMatrix,I0,_,M),A),A0.set(b0.data),P0.set(A.data);const R=p*I0.data[0];this.cameraPositionData[0]=w.x,this.cameraPositionData[1]=w.y,this.cameraPositionData[2]=w.z,T.setParameter("cameraPosition",this.cameraPositionData),this.cameraDirectionData[0]=b.x,this.cameraDirectionData[1]=b.y,this.cameraDirectionData[2]=b.z,T.setParameter("cameraDirection",this.cameraDirectionData),T.setParameter("viewMatrix",P0),T.setParameter("viewProj",A0),T.setParameter("focal",R),T.setParameter("viewportWidth",p),T.setParameter("viewportHeight",m),T.setParameter("nearClip",k.nearClip),T.setParameter("farClip",k.farClip),T.setParameter("alphaClip",d),T.setParameter("minPixelSize",u),T.setParameter("minContribution",f),T.setParameter("isOrtho",k.projection===Sn?1:0),T.setParameter("splatTextureSize",t.textureSize),T.setParameter("numBins",Vl.NUM_BINS),T.setParameter("minDist",c),T.setParameter("invRange",P),T.setParameter("pad0",0),y&&(T.setParameter("fisheye_k",v.k),T.setParameter("fisheye_inv_k",v.invK),T.setParameter("fisheye_projMat00",v.projMat00),T.setParameter("fisheye_projMat11",v.projMat11));const F=Math.ceil(a/BV);Qe.calcDispatchSize(F,om,this.device.limits.maxComputeWorkgroupsPerDimension||65535),T.setupDispatch(om.x,om.y,1),this.device.computeDispatch([T],"GSplatProjector")}writeIndirectArgs(e,t,s,i,r){const a=this._writeIndirectArgsCompute;a.setParameter("renderCounter",this.renderCounter),a.setParameter("indirectDrawArgs",this.device.indirectDrawBuffer),a.setParameter("numSplatsBuf",s),a.setParameter("indirectDispatchArgs",this.device.indirectDispatchBuffer),a.setParameter("sortElementCountBuf",i),a.setParameter("drawSlot",e),a.setParameter("indexCount",OV),a.setParameter("sortSlotBase",t),a.setParameter("pad0",0),a.setParameter("sortIndirectInfo",r),a.setupDispatch(1),this.device.computeDispatch([a],"GSplatProjectorWriteIndirectArgs")}}const xC=new GT;class D_{resource;node;intervals=new Map;id=0;allocId=xC.get();lodIndex=0;_lodBaseDistance=5;_lodMultiplier=3;set lodBaseDistance(e){this._lodBaseDistance!==e&&(this._lodBaseDistance=e,this.lod
15056Dirty=!0)}get lodBaseDistance(){return this._lodBaseDistance}set lodMultiplier(e){this._lodMultiplier!==e&&(this._lodMultiplier=e,this.lodDirty=!0)}get lodMultiplier(){return this._lodMultiplier}_aabb=null;parameters=null;_streams=null;lodDirty=!1;renderDirty=!1;workBufferUpdate=Qm;_lastFormatVersion=-1;_workBufferModifier=null;parentPlacement=null;constructor(e,t,s=0,i=null,r=null,a=null){this.id=a??r?.id??0,this.resource=e,this.node=t,this.lodIndex=s,this.parameters=i??r?.parameters??null,this.parentPlacement=r}destroy(){this._streams?.destroy(),this._streams=null,this.intervals.clear(),this.resource=null}set workBufferModifier(e){this._workBufferModifier=e,this.renderDirty=!0}get workBufferModifier(){return this.parentPlacement?.workBufferModifier??this._workBufferModifier}consumeRenderDirty(){const e=this.resource?.format;e&&this._lastFormatVersion!==e.extraStreamsVersion&&(this._lastFormatVersion=e.extraStreamsVersion,this.renderDirty=!0),this.workBufferUpdate===XI?this.renderDirty=!0:this.workBufferUpdate===WI&&(this.renderDirty=!0,this.workBufferUpdate=Qm);const t=this.renderDirty;return this.renderDirty=!1,t}set aabb(e){this._aabb=e?.clone()??null}get aabb(){return this._aabb??this.resource?.aabb}getLodDistance(e){return this.lodBaseDistance*Math.pow(this.lodMultiplier,e)}getInstanceTexture(e,t){const s=this.resource;if(s?.format)return!this._streams&&s.format.instanceStreams.length>0&&(this._streams=new pu(t,!0),this._streams.textureDimensions.copy(s.streams.textureDimensions),this._streams.syncWithFormat(s.format)),this._streams?.getTexture(e)}get streams(){return this.parentPlacement?.streams??this._streams}ensureInstanceStreams(e){const t=this.resource;t?.format&&!this._streams&&t.format.instanceStreams.length>0&&(this._streams=new pu(e,!0),this._streams.textureDimensions.copy(t.streams.textureDimensions),this._streams.syncWithFormat(t.format))}}const lm=new Z,UV=new E,zV=new E,Wr=[];new Le;const VV=Math.tan(22.5*H.DEG_TO_RAD);new Q(1,0,0),new Q(0,1,0),new Q(0,0,1),new Q(1,1,0),new Q(1,0,1);class GV{currentLod=-1;optimalLod=-1;worldDistance=0;colorAccumulatedTranslation=0;inst=null;lods=null;budgetBucket=0;allocId=xC.get();resetLod(){this.currentLod=-1,this.optimalLod=-1}}class HV{octree;placement;activePlacements=new Set;dirtyModifiedPlacements=!1;dirtyPlacementSetChanged=!1;device;nodeInfos;filePlacements;pending=new Set;pendingDecrements=new Map;removedCandidates=new Set;rangeMin=0;rangeMax=0;previousPosition=new E;needsLodUpdate=!1;prefetchPending=new Set;pendingVisibleAdds=new Map;get pendingLoadCount(){let e=this.pending.size+this.prefetchPending.size;return this.octree.environmentUrl&&!this.environmentPlacement&&e++,e}environmentPlacement=null;_deviceLostEvent=null;_lodMinDistThresholds=null;constructor(e,t,s){this.device=e,this.octree=t,this.placement=s,this.nodeInfos=new Array(t.nodes.length);for(let r=0;r<t.nodes.length;r++){const a=new GV;a.inst=this,this.nodeInfos[r]=a}const i=t.files.length;this.filePlacements=new Array(i).fill(null),t.environmentUrl&&(t.incEnvironmentRefCount(),t.ensureEnvironmentResource()),this._deviceLostEvent=e.on("devicelost",this._onDeviceLost,this)}destroy(e=!1){if(!e&&this.octree&&!this.octree.destroyed){const t=this.getFileDecrements();for(const s of t)this.octree.decRefCount(s,0);for(const s of this.pending)this.filePlacements[s]||this.octree.unloadResource(s);for(const s of this.prefetchPending)this.filePlacements[s]||this.octree.unloadResource(s);this.environmentPlacement&&this.octree.decEnvironmentRefCount()}this.pending.clear(),this.pendingDecrements.clear(),this.filePlacements.length=0,this.environmentPlacement&&(this.activePlacements.delete(this.environmentPlacement),this.environmentPlacement=null),this._deviceLostEvent?.off(),this._deviceLostEvent=null}_onDeviceLost(){for(let e=0;e<this.filePlacements.length;e++)this.filePlacements[e]&&this.octree.decRefCount(e,0);this.filePlacements.fill(null),this.activePlacements.clear(),this.pending.clear(),this.pendingDecrements.clear(),this.removedCandidates.clear(),this.prefetchPending.clear(),this.pendingVisibleAdds.clear();for(const e of this.nodeInfos)e.resetLod();this.environmentPlacement&&(this.activePlacements.delete(this.environmentPlacement),this.environmentPlacement=null,this.octree.unloadEnvironmentResource()),this.dirtyModifiedPlacements=!0,this.dirtyPlacementSetChanged=!0,this.needsLodUpdate=!0}getFileDecrements(){const e=[];for(let t=0;t<this.filePlacements.length;t++)this.filePlacements[t]&&e.push(t);return e}selectDesiredLodIndex(e,t,s,i){if(i>0){const r=Math.min(s,t+i);for(let a=t;a<=r;a++){const n=e.lods[a].fileIndex;if(n!==-1&&this.octree.getFileResource(n))return a}for(let a=r;a>=t;a--)if(e.lods[a].fileIndex!==-1)return a}return t}prefetchNextLod(e,t,s){if(t===-1||s===-1)return;if(t===s){const r=e.lods[s].fileIndex;r!==-1&&(this.octree.ensureFileResource(r),this.octree.getFileResource(r)||this.prefetchPending.add(r));return}const i=Math.max(s,t-1);for(let r=i;r>=s;r--){const a=e.lods[r].fileIndex;if(a!==-1){this.octree.ensureFileResource(a),this.octree.getFileResource(a)||this.prefetchPending.add(a);break}}}updateLod(e,t){const s=this.octree.lodLevels-1,{lodBaseDistance:i,lodMultiplier:r}=this.placement,{lodRangeMin:a,lodRangeMax:n}=t,o=Math.max(0,Math.min(a??0,s)),c=Math.max(o,Math.min(n??s,s)),h=this.placement.node.getWorldTransform().getScale().x;this.evaluateNodeLods(e,s,i,r,o,c,t,h,!1),this.applyLodChanges(s,t)}_ensureLodMinDistThresholds(e,t,s){const i=e+1;let r=this._lodMinDistThresholds;(!r||r.length<i)&&(r=new Float32Array(i),this._lodMinDistThresholds=r);let a=t;r[1]=a;for(let n=2;n<=e;n++)a*=s,r[n]=a;return r}evaluateNodeLods(e,t,s,i,r,a,n,o,c=!0,h=0){const{lodBehindPenalty:d}=n,u=e.camera;let f=Math.tan(u.fov*.5*H.DEG_TO_RAD);u.horizontalFov&&(f/=u.aspectRatio);const p=f*u.aspectRatio,m=Math.min(f,p)/VV,_=e.getPosition(),g=this.placement.node.getWorldTransform();lm.copy(g).invert();const v=lm.transformPoint(_,UV),x=e.forward,y=lm.transformVector(x,zV).normalize(),S=this.octree.nodes,T=this.nodeInfos,w=this.octree.nodeBoundsMinMax,C=v.x,b=v.y,I=v.z,P=y.x,L=y.y,O=y.z;let D=0,N=null;t>=1&&(N=this._ensureLodMinDistThresholds(t,s,i));const k=h>0?Kr/Math.sqrt(h):0;for(let A=0;A<S.length;A++){const M=T[A],R=A*6;let F=C;const U=w[R],B=w[R+3];F<U?F=U:F>B&&(F=B);let z=b;const $=w[R+1],K=w[R+4];z<$?z=$:z>K&&(z=K);let Y=I;const te=w[R+2],J=w[R+5];Y<te?Y=te:Y>J&&(Y=J);const _e=F-C,Ae=z-b,we=Y-I,$e=Math.sqrt(_e*_e+Ae*Ae+we*we);let Ye=$e;if(d>1&&$e>.01){const ke=(P*_e+L*Ae+O*we)/$e;if(ke<0){const se=1+-ke*(d-1);Ye=$e*se}}const Ee=Ye*m;let Pe;if(t===0||Ee<s)Pe=0;else for(Pe=t;Pe>1&&Ee<N[Pe];)Pe--;if(Pe<r&&(Pe=r),Pe>a&&(Pe=a),M.optimalLod=Pe,M.worldDistance=Ee*o,k>0&&Pe>=0){const ke=Math.sqrt(M.worldDistance)*k>>>0;M.budgetBucket=ke<Kr?ke:Kr-1}if(c){const ke=S[A].lods[Pe];ke&&ke.count&&(D+=ke.count)}}return D}
15056evaluateOptimalLods(e,t,s=1,i=0){const r=this.octree.lodLevels-1,{lodBaseDistance:a,lodMultiplier:n}=this.placement,{lodRangeMin:o,lodRangeMax:c}=t,h=Math.max(0,Math.min(o??0,r)),d=Math.max(h,Math.min(c??r,r));this.rangeMin=h,this.rangeMax=d;const u=this.placement.node.getWorldTransform().getScale().x,f=a*s,p=Math.max(1.2,n*Math.pow(s,-.2));return this.evaluateNodeLods(e,r,f,p,h,d,t,u,!0,i)}applyLodChanges(e,t){const s=this.octree.nodes,{lodUnderfillLimit:i=0}=t;for(let r=0;r<s.length;r++){const a=s[r],n=this.nodeInfos[r],o=n.optimalLod,c=n.currentLod,h=this.selectDesiredLodIndex(a,o,e,i);if(h!==c){const d=c>=0?a.lods[c].fileIndex:-1,u=h>=0?a.lods[h].fileIndex:-1,f=d!==-1,p=u!==-1,m=this.pendingDecrements.get(r);if(m&&m.newFileIndex!==u&&(this.filePlacements[m.newFileIndex]&&this.decrementFileRef(m.newFileIndex,r),f&&p?this.pendingDecrements.set(r,{oldFileIndex:m.oldFileIndex,newFileIndex:u}):this.pendingDecrements.delete(r)),!f&&p){const _=this.pendingVisibleAdds.get(r);_!==void 0&&_!==u&&(this.decrementFileRef(_,r),this.pendingVisibleAdds.delete(r)),this.incrementFileRef(u,r,h),this.filePlacements[u]?.resource?(n.currentLod=h,this.pendingVisibleAdds.delete(r)):this.pendingVisibleAdds.set(r,u)}else if(f&&!p){const _=this.pendingDecrements.get(r);_&&(this.decrementFileRef(_.newFileIndex,r),this.pendingDecrements.delete(r)),this.decrementFileRef(d,r),n.currentLod=-1,this.pendingVisibleAdds.delete(r)}else f&&p&&(this.incrementFileRef(u,r,h),this.filePlacements[u]?.resource?(this.decrementFileRef(d,r),this.pendingDecrements.delete(r),n.currentLod=h,this.pendingVisibleAdds.delete(r)):(this.pendingDecrements.set(r,{oldFileIndex:d,newFileIndex:u}),this.pendingVisibleAdds.delete(r)))}this.prefetchNextLod(a,h,o)}}incrementFileRef(e,t,s){if(e===-1)return;let i=this.filePlacements[e];i||(i=new D_(null,this.placement.node,s,null,this.placement),this.filePlacements[e]=i,this.removedCandidates.delete(e)||this.octree.incRefCount(e),this.addFilePlacement(e)||(this.octree.ensureFileResource(e),this.pending.add(e)));const n=this.octree.nodes[t].lods[s],o=new j(n.offset,n.offset+n.count-1);i.intervals.set(t,o),this.dirtyModifiedPlacements=!0}decrementFileRef(e,t){if(e===-1)return;const s=this.filePlacements[e];s&&s&&(s.intervals.delete(t),this.dirtyModifiedPlacements=!0,s.intervals.size===0&&(s.resource&&(this.activePlacements.delete(s),this.activePlacements.size===0&&(this.dirtyPlacementSetChanged=!0)),this.removedCandidates.add(e),this.filePlacements[e]=null,this.pending.delete(e)))}addFilePlacement(e){const t=this.octree.getFileResource(e);if(t){const s=this.filePlacements[e];if(s)return s.resource=t,this.activePlacements.size===0&&(this.dirtyPlacementSetChanged=!0),this.activePlacements.add(s),this.dirtyModifiedPlacements=!0,this.removedCandidates.delete(e),!0}return!1}testMoved(e){return this.placement.node.getPosition().distance(this.previousPosition)>e}updateMoved(){this.previousPosition.copy(this.placement.node.getPosition())}update(){if(this.placement.lodDirty&&(this.placement.lodDirty=!1,this.needsLodUpdate=!0),this.pending.size){for(const t of this.pending)if(this.octree.ensureFileResource(t),this.addFilePlacement(t)){Wr.push(t);for(const[s,{oldFileIndex:i,newFileIndex:r}]of this.pendingDecrements)if(r===t){this.decrementFileRef(i,s),this.pendingDecrements.delete(s);let a=0;const n=this.octree.nodes[s].lods;for(let o=0;o<n.length;o++)if(n[o].fileIndex===r){a=o;break}this.nodeInfos[s].currentLod=a}}Wr.length>0&&(this.needsLodUpdate=!0);for(const t of Wr)this.pending.delete(t);Wr.length=0}if(this.pollPrefetchCompletions(),this.octree.environmentUrl&&!this.environmentPlacement){this.octree.ensureEnvironmentResource();const t=this.octree.environmentResource;t&&(this.environmentPlacement=new D_(t,this.placement.node,0,null,this.placement),this.environmentPlacement.aabb.copy(t.aabb),this.activePlacements.add(this.environmentPlacement),this.dirtyModifiedPlacements=!0,this.dirtyPlacementSetChanged=!0,t.releaseTextureSources?.())}const e=this.dirtyModifiedPlacements;return this.dirtyModifiedPlacements=!1,e}consumePlacementSetChanged(){const e=this.dirtyPlacementSetChanged;return this.dirtyPlacementSetChanged=!1,e}debugRender(e){}consumeNeedsLodUpdate(){const e=this.needsLodUpdate;return this.needsLodUpdate=!1,e}pollPrefetchCompletions(){if(this.prefetchPending.size){for(const e of this.prefetchPending)this.octree.ensureFileResource(e),this.octree.getFileResource(e)&&Wr.push(e);Wr.length>0&&(this.needsLodUpdate=!0);for(const e of Wr)this.prefetchPending.delete(e);Wr.length=0}}}const D0=new E,M0=new E;class WV{lods;bounds=new Le;boundingSphere=new ie;constructor(e,t){this.lods=e,D0.set(t.min[0],t.min[1],t.min[2]),M0.set(t.max[0],t.max[1],t.max[2]),this.bounds.setMinMax(D0,M0);
15056const s=this.bounds.center,i=this.bounds.halfExtents,r=Math.sqrt(i.x*i.x+i.y*i.y+i.z*i.z);this.boundingSphere.set(s.x,s.y,s.z,r)}}const cm=[];class XV{nodes;nodeBoundsMinMax;files;lodLevels;assetFileUrl;fileResources=new Map;fileRefCounts;cooldowns=new Map;environmentUrl=null;environmentResource=null;environmentRefCount=0;assetLoader=null;destroyed=!1;cooldownTicks=100;constructor(e,t){this.lodLevels=t.lodLevels,this.assetFileUrl=e;const s=ve.getDirectory(e);this.files=t.filenames.map(n=>({url:ve.isRelativePath(n)?ve.join(s,n):n,lodLevel:-1})),this.fileRefCounts=new Int32Array(this.files.length),t.environment&&(this.environmentUrl=ve.isRelativePath(t.environment)?ve.join(s,t.environment):t.environment);const i=[];this._extractLeafNodes(t.tree,i),this.nodes=i.map(n=>{const o=[];for(let c=0;c<this.lodLevels;c++){const h=n.lods[c.toString()];h?(o.push({file:this.files[h.file].url||"",fileIndex:h.file,offset:h.offset||0,count:h.count||0}),this.files[h.file].lodLevel=c):o.push({file:"",fileIndex:-1,offset:0,count:0})}return new WV(o,n.bound)});const r=this.nodes.length,a=new Float32Array(r*6);for(let n=0;n<r;n++){const o=this.nodes[n].bounds,c=o.getMin(),h=o.getMax(),d=n*6;a[d+0]=c.x,a[d+1]=c.y,a[d+2]=c.z,a[d+3]=h.x,a[d+4]=h.y,a[d+5]=h.z}this.nodeBoundsMinMax=a}destroy(){this.destroyed=!0,this.fileResources.clear(),this.cooldowns.clear(),this.assetLoader?.destroy(),this.assetLoader=null,this.environmentResource=null}_traceLodCounts(){}_extractLeafNodes(e,t){if(e.lods)t.push({lods:e.lods,bound:e.bound});else if(e.children)for(const s of e.children)this._extractLeafNodes(s,t)}getFileResource(e){return this.fileResources.get(e)}incRefCount(e){const t=this.fileRefCounts[e]+1;this.fileRefCounts[e]=t,this.cooldowns.delete(e)}decRefCount(e,t){const s=this.fileRefCounts[e]-1;this.fileRefCounts[e]=s,s===0&&(t===0?this.unloadResource(e):this.cooldowns.set(e,t))}unloadResource(e){if(!this.assetLoader)return;const t=this.files[e].url;this.assetLoader.unload(t),this.fileResources.has(e)&&(this.fileResources.delete(e),this._traceLodCounts())}updateCooldownTick(e){this.cooldownTicks=e,this.cooldowns.size>0&&(this.cooldowns.forEach((t,s)=>{t<=1?(this.fileRefCounts[s]===0&&this.unloadResource(s),cm.push(s)):this.cooldowns.set(s,t-1)}),cm.forEach(t=>this.cooldowns.delete(t)),cm.length=0)}ensureFileResource(e){if(this.fileResources.has(e))return;const t=this.files[e].url,s=this.assetLoader?.getResource(t);if(s){this.fileResources.set(e,s),s.releaseTextureSources?.(),this.fileRefCounts[e]===0&&this.cooldowns.set(e,this.cooldownTicks),this._traceLodCounts();return}this.assetLoader?.load(t)}incEnvironmentRefCount(){this.environmentRefCount++}decEnvironmentRefCount(){this.environmentRefCount--,this.environmentRefCount===0&&this.unloadEnvironmentResource()}ensureEnvironmentResource(){if(!this.assetLoader||!this.environmentUrl||this.environmentResource)return;const e=this.assetLoader.getResource(this.environmentUrl);if(e){this.environmentResource=e,this.environmentRefCount===0&&this.unloadEnvironmentResource();return}this.assetLoader.load(this.environmentUrl)}unloadEnvironmentResource(){this.assetLoader&&this.environmentResource&&this.environmentUrl&&(this.assetLoader.unload(this.environmentUrl),this.environmentResource=null)}}class TC{aabb=new Le;centersVersion=0;octree;data;constructor(e,t,s){this.octree=new XV(e,t),this.octree.assetLoader=s,this.aabb.setMinMax(new E(t.tree.bound.min),new E(t.tree.bound.max)),this.data=t,this.data.tree=null}destroy(){this.octree?.destroy(),this.octree=null}}const hm=new Set,ir=[],eo=[],to=[];class YV{version=0;sortParametersSet=!1;sortedBefore=!1;splats=[];textureSize=0;totalActiveSplats=0;totalIntervals=0;boundsGroups=[];pendingReleases=[];needsUpload=[];needsUploadIds=new Set;allocIdToSplat=new Map;fullRebuild=!1;constructor(e,t,s,i,r){if(this.version=t,this.splats=s,s.length===0){for(const[,o]of r)i.free(o);r.clear(),this.totalActiveSplats=0,this.totalIntervals=0,this.textureSize=1;return}this.computeAllocationDiff(s,r);const{fullRebuild:a,changedAllocIds:n}=this.applyAllocations(e,i,r);this.assignSplatOffsets(s,r,a,n),this.buildBoundsGroups(s)}
15056destroy(){this.splats.forEach(e=>e.destroy()),this.splats.length=0,this.needsUpload.length=0,this.needsUploadIds.clear(),this.allocIdToSplat.clear(),this.boundsGroups.length=0}computeAllocationDiff(e,t){for(let s=0;s<e.length;s++){const i=e[s],r=i.intervalAllocIds,a=i.intervals,n=a.length/2;if(n>0&&r.length===n)for(let o=0;o<n;o++)this._diffAlloc(r[o],a[o*2+1]-a[o*2],t);else this._diffAlloc(i.allocId,i.activeSplats,t)}for(const[s,i]of t)hm.has(s)||(to.push(i),t.delete(s))}_diffAlloc(e,t,s){hm.add(e);const i=s.get(e);i?i.size!==t&&(to.push(i),s.delete(e),t>0&&(ir.push(e),eo.push(t))):t>0&&(ir.push(e),eo.push(t))}applyAllocations(e,t,s){let i=!1;if(to.length>0||eo.length>0){i=t.updateAllocation(to,eo);for(let c=0;c<ir.length;c++)s.set(ir[c],eo[c])}this.fullRebuild=i;const r=to.length+ir.length,a=Math.max(50,r);if(!i&&t.fragmentation>.3){const c=t.defrag(a);if(c.size>0)for(const[h,d]of s)c.has(d)&&ir.push(h)}const n=t.capacity;this.textureSize=n>0?Math.ceil(Math.sqrt(n)):1;const o=ir.length>0?new Set(ir):null;return hm.clear(),ir.length=0,eo.length=0,to.length=0,{fullRebuild:i,changedAllocIds:o}}assignSplatOffsets(e,t,s,i){let r=0,a=0;for(let n=0;n<e.length;n++){const o=e[n],c=o.intervalAllocIds,h=o.intervals,d=h.length/2;a+=d>0?d:1;let u=s;const f=[];if(d>0&&c.length===d)for(let p=0;p<d;p++){this.allocIdToSplat.set(c[p],o);const m=t.get(c[p]);m&&(f.push(m.offset),r+=h[p*2+1]-h[p*2],i&&i.has(c[p])&&(u=!0,this.needsUploadIds.add(c[p])))}else{this.allocIdToSplat.set(o.allocId,o);const p=t.get(o.allocId);p&&(f.push(p.offset),r+=o.activeSplats,i&&i.has(o.allocId)&&(u=!0,this.needsUploadIds.add(o.allocId)))}if(f.length>0&&(o.setLayout(f),u&&(this.needsUpload.push(o),s)))for(let p=0;p<c.length;p++)this.needsUploadIds.add(c[p])}this.totalActiveSplats=r,this.totalIntervals=a}buildBoundsGroups(e){const t=new Map;for(let i=0;i<e.length;i++){const r=e[i],a=r.parentPlacementId;t.has(a)||t.set(a,{splat:r,boundsBaseIndex:0,numBoundsEntries:r.numBoundsEntries})}let s=0;for(const i of t.values())i.boundsBaseIndex=s,s+=i.numBoundsEntries,this.boundsGroups.push(i);for(let i=0;i<e.length;i++){const r=t.get(e[i].parentPlacementId);e[i].boundsBaseIndex=r.boundsBaseIndex}}}class jV{_states=new WeakMap;hasChanges(e){let t=!1;for(const s of e){if(!s.resource)continue;const i=s.resource.format?.extraStreamsVersion??0,r=s.workBufferModifier?.hash??0,a=s.resource.numSplats??0,n=s.resource.centersVersion,o=this._states.get(s);o?(o.formatVersion!==i||o.modifierHash!==r||o.numSplats!==a||o.centersVersion!==n)&&(o.formatVersion=i,o.modifierHash=r,o.numSplats=a,o.centersVersion=n,t=!0):(this._states.set(s,{formatVersion:i,modifierHash:r,numSplats:a,centersVersion:n}),t=!0)}return t}}const qV=` 15057struct Interval { 15058 workBufferBase: u32, 15059 splatCount: u32, 15060 boundsIndex: u32, 15061 pad: u32 15062}; 15063struct BoundsEntry { 15064 centerX: f32, 15065 centerY: f32, 15066 centerZ: f32, 15067 radius: f32, 15068 transformIndex: u32, 15069 pad0: u32, 15070 pad1: u32, 15071 pad2: u32 15072}; 15073struct CullUniforms { 15074#ifdef GSPLAT_FISHEYE 15075 cameraWorldPos: vec3f, 15076 maxTheta: f32, 15077 cameraForward: vec3f, 15078 numIntervals: u32, 15079#else 15080 frustumPlanes: array<vec4f, 6>, 15081 numIntervals: u32 15082#endif 15083}; 15084@group(0) @binding(0) var<uniform> uniforms: CullUniforms; 15085@group(0) @binding(1) var<storage, read> intervals: array<Interval>; 15086@group(0) @binding(2) var<storage, read_write> countBuffer: array<u32>; 15087@group(0) @binding(3) var<storage, read> boundsBuffer: array<BoundsEntry>; 15088@group(0) @binding(4) var<storage, read> transformsBuffer: array<vec4f>; 15089@compute @workgroup_size({WORKGROUP_SIZE}) 15090fn main(@builtin(global_invocation_id) gid: vec3u) { 15091 let idx = gid.x; 15092 if (idx < uniforms.numIntervals) { 15093 let interval = intervals[idx]; 15094 let entry = boundsBuffer[interval.boundsIndex]; 15095 let localCenter = vec3f(entry.centerX, entry.centerY, entry.centerZ); 15096 let radius = entry.radius; 15097 let base = entry.transformIndex * 3u; 15098 let row0 = transformsBuffer[base]; 15099 let row1 = transformsBuffer[base + 1u]; 15100 let row2 = transformsBuffer[base + 2u]; 15101 let worldCenter = vec3f( 15102 dot(vec4f(localCenter, 1.0), row0), 15103 dot(vec4f(localCenter, 1.0), row1), 15104 dot(vec4f(localCenter, 1.0), row2) 15105 );
15106 let worldRadius = radius * length(vec3f(row0.x, row1.x, row2.x)); 15107 #ifdef GSPLAT_FISHEYE 15108 let v = worldCenter - uniforms.cameraWorldPos; 15109 let d = length(v); 15110 var visible = true; 15111 if (d > worldRadius) { 15112 let cosAngle = dot(v / d, uniforms.cameraForward); 15113 let theta = acos(clamp(cosAngle, -1.0, 1.0)); 15114 let angularRadius = asin(min(worldRadius / d, 1.0)); 15115 visible = (theta - angularRadius) < uniforms.maxTheta; 15116 } 15117 #else 15118 var visible = true; 15119 for (var p = 0; p < 6; p++) { 15120 let plane = uniforms.frustumPlanes[p]; 15121 let dist = dot(plane.xyz, worldCenter) + plane.w; 15122 if (dist <= -worldRadius) { 15123 visible = false; 15124 break; 15125 } 15126 } 15127 #endif 15128 countBuffer[idx] = select(0u, interval.splatCount, visible); 15129 } 15130 if (idx == 0u) { 15131 countBuffer[uniforms.numIntervals] = 0u; 15132 } 15133} 15134`,$V=` 15135struct Interval { 15136 workBufferBase: u32, 15137 splatCount: u32, 15138 boundsIndex: u32, 15139 pad: u32 15140}; 15141struct ScatterUniforms { 15142 numIntervals: u32, 15143 pad0: u32, 15144 pad1: u32, 15145 pad2: u32 15146}; 15147@group(0) @binding(0) var<uniform> uniforms: ScatterUniforms; 15148@group(0) @binding(1) var<storage, read> intervals: array<Interval>; 15149@group(0) @binding(2) var<storage, read> prefixSumBuffer: array<u32>; 15150@group(0) @binding(3) var<storage, read_write> compactedOutput: array<u32>; 15151@compute @workgroup_size({WORKGROUP_SIZE}) 15152fn main(@builtin(workgroup_id) wgId: vec3u, @builtin(local_invocation_id) lid: vec3u) { 15153 let intervalIdx = wgId.x; 15154 if (intervalIdx >= uniforms.numIntervals) { return; } 15155 let outputOffset = prefixSumBuffer[intervalIdx]; 15156 let nextOffset = prefixSumBuffer[intervalIdx + 1u]; 15157 let count = nextOffset - outputOffset; 15158 if (count == 0u) { return; } 15159 let workBufferBase = intervals[intervalIdx].workBufferBase; 15160 let tid = lid.x; 15161 for (var j = tid; j < count; j += {WORKGROUP_SIZE}u) { 15162 compactedOutput[outputOffset + j] = workBufferBase + j; 15163 } 15164} 15165`,KV=` 15166${Of} 15167${Bf} 15168${jg} 15169@group(0) @binding(0) var<storage, read> prefixSumBuffer: array<u32>; 15170@group(0) @binding(1) var<storage, read_write> indirectDrawArgs: array<DrawIndexedIndirectArgs>; 15171@group(0) @binding(2) var<storage, read_write> numSplatsBuf: array<u32>; 15172@group(0) @binding(3) var<storage, read_write> indirectDispatchArgs: array<u32>; 15173@group(0) @binding(4) var<storage, read_write> sortElementCountBuf: array<u32>; 15174struct WriteArgsUniforms { 15175 drawSlot: u32, 15176 indexCount: u32, 15177 dispatchSlotBase: u32, 15178 totalSplats: u32, 15179 sortIndirectInfo: vec4<u32> 15180}; 15181@group(0) @binding(5) var<uniform> uniforms: WriteArgsUniforms; 15182@compute @workgroup_size(1) 15183fn main(@builtin(global_invocation_id) gid: vec3u) { 15184 let count = prefixSumBuffer[uniforms.totalSplats]; 15185 let instanceCount = (count + {INSTANCE_SIZE}u - 1u) / {INSTANCE_SIZE}u; 15186 indirectDrawArgs[uniforms.drawSlot] = DrawIndexedIndirectArgs( 15187 uniforms.indexCount, 15188 instanceCount, 15189 0u, 15190 0, 15191 0u 15192 ); 15193 numSplatsBuf[0] = count; 15194 let keygenSlot = uniforms.dispatchSlotBase; 15195 let keygenOffset = keygenSlot * 3u; 15196 let keygenWorkgroupCount = (count + {KEYGEN_THREADS_PER_WORKGROUP}u - 1u) / {KEYGEN_THREADS_PER_WORKGROUP}u; 15197 let keygenDim = calcDispatch2D(keygenWorkgroupCount, {MAX_WORKGROUPS_PER_DIM}u); 15198 indirectDispatchArgs[keygenOffset + 0u] = keygenDim.x; 15199 indirectDispatchArgs[keygenOffset + 1u] = keygenDim.y; 15200 indirectDispatchArgs[keygenOffset + 2u] = 1u; 15201 writeSortIndirectArgs(keygenSlot + 1u, count, uniforms.sortIndirectInfo); 15202 sortElementCountBuf[0] = count; 15203} 15204`,dm=256,ZV=6*Rt.instanceSize,um=4;class R0{device;compactedSplatIds=null;intervalsBuffer=null;countBuffer=null;prefixSumKernel=null;numSplatsBuffer=null;sortElementCountBuffer=null;allocatedCompactedCount=0;allocatedIntervalCount=0;allocatedCountBufferSize=0;_uploadedVersion=-1;_cullComputePerspective=null;_cullComputeFisheye=null;_scatterCompute=null;_writeIndirectArgsCompute=null;_cullBindGroupFormatPerspective=null;_cullBindGroupFormatFisheye=null;_scatterBindGroupFormat=null;_writeArgsBindGroupFormat=null;_scatterUniformBufferFormat=null;_writeArgsUniformBufferFormat=null;constructor(e){this.device=e,this.numSplatsBuffer=new Se(e,4,Si|ct),this.sortElementCountBuffer=new Se(e,4,Si|ct),this.prefixSumKernel=new Gg(e),this._createUniformBufferFormats(),this._createScatterCompute(),this._createWriteIndirectArgsCompute()}
15204destroy(){this.compactedSplatIds?.destroy(),this.intervalsBuffer?.destroy(),this.countBuffer?.destroy(),this.prefixSumKernel?.destroy(),this.numSplatsBuffer?.destroy(),this.sortElementCountBuffer?.destroy(),this._destroyCullPass(),this._scatterCompute?.shader?.destroy(),this._scatterBindGroupFormat?.destroy(),this._writeIndirectArgsCompute?.shader?.destroy(),this._writeArgsBindGroupFormat?.destroy(),this.compactedSplatIds=null,this.intervalsBuffer=null,this.countBuffer=null,this.prefixSumKernel=null,this.numSplatsBuffer=null,this.sortElementCountBuffer=null,this._scatterCompute=null,this._scatterBindGroupFormat=null,this._writeIndirectArgsCompute=null,this._writeArgsBindGroupFormat=null,this._scatterUniformBufferFormat=null,this._writeArgsUniformBufferFormat=null}_destroyCullPass(){this._cullComputePerspective?.shader?.destroy(),this._cullBindGroupFormatPerspective?.destroy(),this._cullComputePerspective=null,this._cullBindGroupFormatPerspective=null,this._cullComputeFisheye?.shader?.destroy(),this._cullBindGroupFormatFisheye?.destroy(),this._cullComputeFisheye=null,this._cullBindGroupFormatFisheye=null}_createUniformBufferFormats(){const e=this.device;this._scatterUniformBufferFormat=new vt(e,[new X("numIntervals",le),new X("pad0",le),new X("pad1",le),new X("pad2",le)]),this._writeArgsUniformBufferFormat=new vt(e,[new X("drawSlot",le),new X("indexCount",le),new X("dispatchSlotBase",le),new X("totalSplats",le),new X("sortIndirectInfo",oa)])}_createCullPass(e){const t=this.device,s=e?"Fisheye":"",i=new Ze(t,[new At("uniforms",G),new q("intervals",G,!0),new q("countBuffer",G,!1),new q("boundsBuffer",G,!0),new q("transformsBuffer",G,!0)]),r=new Map([["{WORKGROUP_SIZE}",dm.toString()]]);e&&r.set("GSPLAT_FISHEYE","");const a=e?new vt(t,[new X("cameraWorldPos",hs),new X("maxTheta",me),new X("cameraForward",hs),new X("numIntervals",le)]):new vt(t,[new X("frustumPlanes",Cr,6),new X("numIntervals",le)]),n=new tt(t,{name:`GSplatIntervalCull${s}`,shaderLanguage:de,cshader:qV,cdefines:r,computeBindGroupFormat:i,computeUniformBufferFormats:{uniforms:a}});return{compute:new Qe(t,n,`GSplatIntervalCull${s}`),bindGroupFormat:i}}_getCullCompute(e){if(e){if(!this._cullComputeFisheye){const{compute:t,bindGroupFormat:s}=this._createCullPass(!0);this._cullComputeFisheye=t,this._cullBindGroupFormatFisheye=s}return this._cullComputeFisheye}if(!this._cullComputePerspective){const{compute:t,bindGroupFormat:s}=this._createCullPass(!1);this._cullComputePerspective=t,this._cullBindGroupFormatPerspective=s}return this._cullComputePerspective}_createScatterCompute(){const e=this.device;this._scatterBindGroupFormat=new Ze(e,[new At("uniforms",G),new q("intervals",G,!0),new q("prefixSumBuffer",G,!0),new q("compactedOutput",G,!1)]);const t=new Map([["{WORKGROUP_SIZE}",dm.toString()]]),s=new tt(e,{name:"GSplatIntervalScatter",shaderLanguage:de,cshader:$V,cdefines:t,computeBindGroupFormat:this._scatterBindGroupFormat,computeUniformBufferFormats:{uniforms:this._scatterUniformBufferFormat}});this._scatterCompute=new Qe(e,s,"GSplatIntervalScatter")}_createWriteIndirectArgsCompute(){const e=this.device;this._writeArgsBindGroupFormat=new Ze(e,[new q("prefixSumBuffer",G,!0),new q("indirectDrawArgs",G,!1),new q("numSplatsBuf",G,!1),new q("indirectDispatchArgs",G,!1),new q("sortElementCountBuf",G,!1),new At("uniforms",G)]);const t=new Map([["{INSTANCE_SIZE}",Rt.instanceSize],["{KEYGEN_THREADS_PER_WORKGROUP}",256],["{MAX_WORKGROUPS_PER_DIM}",e.limits.maxComputeWorkgroupsPerDimension||65535]]),s=new tt(e,{name:"GSplatIntervalWriteIndirectArgs",shaderLanguage:de,cshader:KV,cdefines:t,computeBindGroupFormat:this._writeArgsBindGroupFormat,computeUniformBufferFormats:{uniforms:this._writeArgsUniformBufferFormat}});this._writeIndirectArgsCompute=new Qe(e,s,"GSplatIntervalWriteIndirectArgs")}_ensureCapacity(e,t){t>this.allocatedCompactedCount&&(this.compactedSplatIds?.destroy(),this.allocatedCompactedCount=t,this.compactedSplatIds=new Se(this.device,t*4,Si));const s=e+1;s>this.allocatedCountBufferSize&&(this.countBuffer?.destroy(),this.allocatedCountBufferSize=s,this.countBuffer=new Se(this.device,s*4),this.prefixSumKernel&&this.prefixSumKernel.destroyPasses())}uploadIntervals(e){if(e.version===this._uploadedVersion)return;this._uploadedVersion=e.version;const t=e.splats,s=e.totalIntervals;if(s===0)return;s>this.allocatedIntervalCount&&(this.intervalsBuffer?.destroy(),this.allocatedIntervalCount=s,this.intervalsBuffer=new Se(this.device,s*um*4,ct));const i=new Uint32Array(s*um);let r=0;for(let a=0;a<t.length;a++){const n=t[a];if(n.intervals.length>0){const o=n.intervalNodeIndices;for(let c=0;c<n.intervals.length;c+=2){const h=n.intervals[c+1]-n.intervals[c];i[r++]=n.intervalOffsets[c/2],i[r++]=h,i[r++]=n.boundsBaseIndex+(o.length>0?o[c/2]:0),i[r++]=0}}else i[r++]=n.intervalOffsets[0],i[r++]=n.activeSplats,i[r++]=n.boundsBaseIndex,i[r++]=0}this.intervalsBuffer.write(0,i,0,s*um)}
15204dispatchCompact(e,t,s,i){if(t===0)return;this._ensureCapacity(t,s);const r=this._getCullCompute(i);r.setParameter("intervals",this.intervalsBuffer),r.setParameter("countBuffer",this.countBuffer),r.setParameter("boundsBuffer",e.boundsBuffer),r.setParameter("transformsBuffer",e.transformsBuffer),i?(r.setParameter("cameraWorldPos",e.fisheyeCameraPos),r.setParameter("maxTheta",e.fisheyeMaxTheta),r.setParameter("cameraForward",e.fisheyeCameraForward)):r.setParameter("frustumPlanes[0]",e.frustumPlanes),r.setParameter("numIntervals",t);const a=Math.ceil(t/dm);r.setupDispatch(a),this.device.computeDispatch([r],"GSplatIntervalCull");const n=t+1;this.prefixSumKernel.resize(this.countBuffer,n),this.prefixSumKernel.dispatch(this.device);const o=this._scatterCompute;o.setParameter("intervals",this.intervalsBuffer),o.setParameter("prefixSumBuffer",this.countBuffer),o.setParameter("compactedOutput",this.compactedSplatIds),o.setParameter("numIntervals",t),o.setParameter("pad0",0),o.setParameter("pad1",0),o.setParameter("pad2",0),o.setupDispatch(t),this.device.computeDispatch([o],"GSplatIntervalScatter")}writeIndirectArgs(e,t,s,i){const r=this._writeIndirectArgsCompute;r.setParameter("prefixSumBuffer",this.countBuffer),r.setParameter("indirectDrawArgs",this.device.indirectDrawBuffer),r.setParameter("numSplatsBuf",this.numSplatsBuffer),r.setParameter("indirectDispatchArgs",this.device.indirectDispatchBuffer),r.setParameter("sortElementCountBuf",this.sortElementCountBuffer),r.setParameter("drawSlot",e),r.setParameter("indexCount",ZV),r.setParameter("dispatchSlotBase",t),r.setParameter("totalSplats",s),r.setParameter("sortIndirectInfo",i),r.setupDispatch(1),this.device.computeDispatch([r],"GSplatIntervalWriteIndirectArgs")}}class QV{_buckets=null;_initBuckets(){if(!this._buckets){this._buckets=new Array(Kr);for(let e=0;e<Kr;e++)this._buckets[e]=[]}}balance(e,t){this._initBuckets();for(let n=0;n<Kr;n++)this._buckets[n].length=0;let s=0;for(const[,n]of e){const o=n.octree.nodes,c=n.nodeInfos;for(let h=0,d=o.length;h<d;h++){const u=c[h],f=u.optimalLod;if(f<0)continue;const p=o[h].lods;u.lods=p,this._buckets[u.budgetBucket].push(u),s+=p[f].count}}let i=s;if(i===t)return;const r=i>t;let a=!1;for(;!a&&(r?i>t:i<t);){let n=!1;if(r)for(let o=Kr-1;o>=0&&!a;o--){const c=this._buckets[o];for(let h=0,d=c.length;h<d;h++){const u=c[h];if(u.optimalLod<u.inst.rangeMax){const f=u.lods,p=u.optimalLod;if(i-=f[p].count-f[p+1].count,u.optimalLod=p+1,n=!0,i<=t){a=!0;break}}}}else for(let o=0;o<Kr&&!a;o++){const c=this._buckets[o];for(let h=0,d=c.length;h<d;h++){const u=c[h];if(u.optimalLod>u.inst.rangeMin){const f=u.lods,p=u.optimalLod,m=f[p-1].count-f[p].count;if(i+m<=t){if(u.optimalLod=p-1,i+=m,n=!0,i>=t){a=!0;break}}else{a=!0;break}}}}if(!n)break}}}class JV{_offset=0;_size=0;_free=!0;_prev=null;_next=null;_prevFree=null;_nextFree=null;_bucket=-1;get offset(){return this._offset}get size(){return this._size}}class eG{_headAll=null;_tailAll=null;_freeBucketHeads=[];_pool=[];_capacity=0;_usedSize=0;_freeSize=0;_freeRegionCount=0;_growMultiplier;constructor(e=0,t=1.1){if(this._growMultiplier=t,e>0){this._capacity=e,this._freeSize=e;const s=this._obtain(0,e,!0);this._headAll=s,this._tailAll=s,this._addToBucket(s)}}get capacity(){return this._capacity}get usedSize(){return this._usedSize}get freeSize(){return this._freeSize}get fragmentation(){return this._freeSize>0?1-1/this._freeRegionCount:0}_bucketFor(e){return 31-Math.clz32(e)}_addToBucket(e){const t=this._bucketFor(e._size);for(e._bucket=t;t>=this._freeBucketHeads.length;)this._freeBucketHeads.push(null);e._prevFree=null,e._nextFree=this._freeBucketHeads[t],this._freeBucketHeads[t]&&(this._freeBucketHeads[t]._prevFree=e),this._freeBucketHeads[t]=e,this._freeRegionCount++}_removeFromBucket(e){const t=e._bucket;e._prevFree?e._prevFree._nextFree=e._nextFree:this._freeBucketHeads[t]=e._nextFree,e._nextFree&&(e._nextFree._prevFree=e._prevFree),e._prevFree=null,e._nextFree=null,e._bucket=-1,this._freeRegionCount--}_rebucket(e){this._bucketFor(e._size)!==e._bucket&&(this._removeFromBucket(e),this._addToBucket(e))}_obtain(e,t,s){let i;return this._pool.length>
vendor: 4,446 bytes, line 15204
152040?i=this._pool.pop():i=new JV,i._offset=e,i._size=t,i._free=s,i._prev=null,i._next=null,i._prevFree=null,i._nextFree=null,i._bucket=-1,i}_release(e){e._prev=null,e._next=null,e._prevFree=null,e._nextFree=null,e._bucket=-1,this._pool.push(e)}_insertAfterInMainList(e,t){t===null?(e._prev=null,e._next=this._headAll,this._headAll&&(this._headAll._prev=e),this._headAll=e,this._tailAll||(this._tailAll=e)):(e._prev=t,e._next=t._next,t._next&&(t._next._prev=e),t._next=e,this._tailAll===t&&(this._tailAll=e))}_removeFromMainList(e){e._prev?e._prev._next=e._next:this._headAll=e._next,e._next?e._next._prev=e._prev:this._tailAll=e._prev,e._prev=null,e._next=null}_findFreeBlock(e){const t=this._bucketFor(e),s=this._freeBucketHeads.length;if(t<s){let i=null,r=this._freeBucketHeads[t];for(;r&&!(r._size>=e&&(!i||r._size<i._size)&&(i=r,r._size===e));)r=r._nextFree;if(i)return i}for(let i=t+1;i<s;i++)if(this._freeBucketHeads[i])return this._freeBucketHeads[i];return null}allocate(e){const t=this._findFreeBlock(e);if(!t)return null;if(this._usedSize+=e,this._freeSize-=e,t._size===e)return t._free=!1,this._removeFromBucket(t),t;const s=this._obtain(t._offset,e,!1);return t._offset+=e,t._size-=e,this._rebucket(t),this._insertAfterInMainList(s,t._prev),s}free(e){e._free=!0,this._usedSize-=e._size,this._freeSize+=e._size;const t=e._prev,s=e._next,i=t&&t._free,r=s&&s._free;i&&r?(t._size+=e._size+s._size,this._removeFromMainList(e),this._removeFromMainList(s),this._removeFromBucket(s),this._release(e),this._release(s),this._rebucket(t)):i?(t._size+=e._size,this._removeFromMainList(e),this._release(e),this._rebucket(t)):r?(e._size+=s._size,this._removeFromMainList(s),this._removeFromBucket(s),this._release(s),this._addToBucket(e)):this._addToBucket(e)}grow(e){if(e<=this._capacity)return;const t=e-this._capacity;if(this._capacity=e,this._freeSize+=t,this._tailAll&&this._tailAll._free)this._tailAll._size+=t,this._rebucket(this._tailAll);else{const s=this._obtain(this._capacity-t,t,!0);this._insertAfterInMainList(s,this._tailAll),this._addToBucket(s)}}defrag(e=0,t=new Set){return t.clear(),this._freeRegionCount===0||(e===0?this._defragFull(t):this._defragIncremental(e,t)),t}_defragFull(e){for(let r=0;r<this._freeBucketHeads.length;r++){let a=this._freeBucketHeads[r];for(;a;){const n=a._nextFree;this._removeFromMainList(a),a._prevFree=null,a._nextFree=null,a._bucket=-1,this._pool.push(a),a=n}this._freeBucketHeads[r]=null}this._freeRegionCount=0;let t=0,s=this._headAll;for(;s;)s._offset!==t&&(s._offset=t,e.add(s)),t+=s._size,s=s._next;const i=this._capacity-t;if(i>0){const r=this._obtain(t,i,!0);this._insertAfterInMainList(r,this._tailAll),this._addToBucket(r)}}_defragIncremental(e,t){const s=Math.ceil(e/2),i=e-s;for(let a=0;a<s;a++){let n=this._tailAll;for(;n&&n._free;)n=n._prev;if(!n)break;const o=this._findFreeBlock(n._size);if(!o||o._offset>=n._offset)break;this._moveBlock(n,o),t.add(n)}let r=this._headAll;for(let a=0;a<i&&r;){const n=r._next;if(r._free&&n&&!n._free){const o=n,c=r;o._offset=c._offset,c._offset=o._offset+o._size;const h=c._prev,d=o._next;if(o._prev=h,o._next=c,c._prev=o,c._next=d,h?h._next=o:this._headAll=o,d?d._prev=c:this._tailAll=c,c._next&&c._next._free){const u=c._next;c._size+=u._size,this._removeFromMainList(u),this._removeFromBucket(u),this._release(u),this._rebucket(c)}t.add(o),a++,r=c._next}else r=n}}_moveBlock(e,t){const s=e._size,i=t._offset,r=e._prev;this._removeFromMainList(e);const a=this._obtain(e._offset,s,!0);if(this._insertAfterInMainList(a,r),this._addToBucket(a),a._next&&a._next._free){const n=a._next;a._size+=n._size,this._removeFromMainList(n),this._removeFromBucket(n),this._release(n),this._rebucket(a)}if(a._prev&&a._prev._free){const n=a._prev;n._size+=a._size,this._removeFromMainList(a),this._removeFromBucket(a),this._release(a),this._rebucket(n)}if(e._offset=i,t._size===s){const n=t._prev;this._removeFromMainList(t),this._removeFromBucket(t),this._release(t),this._insertAfterInMainList(e,n)}else t._offset+=s,t._size-=s,this._rebucket(t),this._insertAfterInMainList(e,t._prev)}updateAllocation(e,t){for(let s=0;s<e.length;s++)this.free(e[s]);for(let s=0;s<t.length;s++){const i=t[s],r=this.allocate(i);if(r)t[s]=r;else{let a=i;for(let c=s+1;c<t.length;c++)a+=t[c];const n=this._usedSize+a,o=Math.ceil(n*this._growMultiplier);o>this._capacity&&this.grow(o),this.defrag(0);for(let c=s;c<t.length;c++){const h=t[c],d=this.allocate(h);t[c]=d}return!0}}return!1}}
15204const Xr=new E,Pl=new E,L0=new E,rr=new E,Il=new Z,tG=new Uint32Array([0,0,0,0]),so=new Set,fm=new Set,ld=[],pm=[],Dl=new Set,mm={translationDelta:0},_m=new E,F0=new E,gm=new Set,vm=new Set,O0=[[1,0,0],[0,1,0],[0,0,1],[1,1,0],[1,0,1],[0,1,1],[1,.5,0],[.5,0,1]];new Q(1,0,0),new Q(0,1,0),new Q(0,0,1),new Q(1,1,0),new Q(1,0,1),new Q(0,1,1),new Q(1,.5,0),new Q(.5,0,1);let Yr=null;class sG{device;node=new He("GSplatManager");workBuffer;renderer;worldStates=new Map;lastWorldStateVersion=0;activeRenderer;_worldStateDirty=!1;cpuSorter=null;gpuSorter=null;intervalCompaction=null;projector=null;indirectDrawSlot=-1;indirectDispatchSlot=-1;lastCompactedNumIntervals=0;sortedVersion=0;_awaitingLodUpdate=!1;_workBufferFormatVersion=-1;_workBufferRebuildRequired=!1;bufferCopyUploaded=0;bufferCopyTotal=0;_stateTracker=new jV;_centersVersions=new Map;framesTillFullUpdate=0;lastLodCameraPos=new E(1/0,1/0,1/0);lastLodCameraFwd=new E(1/0,1/0,1/0);lastLodCameraFov=-1;lastSortCameraPos=new E(1/0,1/0,1/0);lastSortCameraFwd=new E(1/0,1/0,1/0);lastCullingCameraFwd=new E(1/0,1/0,1/0);lastCullingProjMat=new Z;sortNeeded=!0;_budgetBalancer=new QV;_budgetScale=1;_allocator;_allocationMap=new Map;lastColorUpdateCameraPos=new E(1/0,1/0,1/0);cameraNode;scene;layerPlacements=[];layerPlacementsDirty=!1;_placementSetChanged=!1;octreeInstances=new Map;octreeInstancesToDestroy=[];hasNewOctreeInstances=!1;renderMode;constructor(e,t,s,i){this.device=e,this.scene=t.scene,this.director=t,this.cameraNode=i;const r=1.15,a=this.scene.gsplat.splatBudget;this._allocator=new eG(a>0?Math.ceil(a*r):0,r),this.workBuffer=new xy(e,this.scene.gsplat.format),this.layer=s,this._createRenderer(this.scene.gsplat.currentRenderer),this._workBufferFormatVersion=this.workBuffer.format.extraStreamsVersion}destroy(){this._destroyed=!0;for(const[,e]of this.worldStates){for(const t of e.splats)t.resource.decRefCount();e.destroy()}this.worldStates.clear();for(const[,e]of this.octreeInstances)e.destroy();this.octreeInstances.clear();for(const e of this.octreeInstancesToDestroy)e.destroy();this.octreeInstancesToDestroy.length=0,this.destroyGpuSorting(),this.destroyCpuSorting(),this.workBuffer.destroy(),this.renderer.destroy()}destroyGpuSorting(){this.gpuSorter?.destroy(),this.gpuSorter=null,this.projector?.destroy(),this.projector=null;const e=!1;this.renderer.setCpuSortedRendering(),this.destroyIntervalCompaction(e)}destroyIntervalCompaction(e=!0){this.intervalCompaction&&(e&&this.renderer.setCpuSortedRendering(),this.intervalCompaction.destroy(),this.intervalCompaction=null)}destroyCpuSorting(){this.cpuSorter?.destroy(),this.cpuSorter=null}initHybridSorting(){this.gpuSorter||(this.gpuSorter=new OM(this.device,{indirect:!0})),this.projector||(this.projector=new kV(this.device))}initCpuSorting(){this.cpuSorter||(this.cpuSorter=this.createSorter());const e=this.worldStates.get(this.sortedVersion);e&&(e.sortParametersSet=!1,e.sortedBefore=!1,this.cpuSorter.updateCentersForSplats(e.splats)),this.renderer.setCpuSortedRendering()}get material(){return this.renderer.material}prepareForPicking(e,t,s){if(this.activeRenderer===uo){const r=this.worldStates.get(this.sortedVersion);if(!r?.sortedBefore||!e.node)return null;const a=this.sortGpuHybridForCamera(r,e.node,t,s,Math.max(wu,this.scene.gsplat.alphaClip),!!this.workBuffer.format.getStream("pcId"));if(!a)return null;const n=this.projector,o=this.intervalCompaction;return this.renderer.prepareForPicking(this.indirectDrawSlot,a,n.projCache,o.numSplatsBuffer,this.scene.gsplat.alphaClip,this.scene.gsplat.alphaClipForward,e.node)}return this.activeRenderer!==Pd?null:this.renderer.dispatchPick(e,t,s)}createSorter(){const e=new lV(this.scene);return e.on("sorted",(t,s,i)=>{this.onSorted(t,s,i)}),e}setRenderMode(e){this.renderMode=e,this.renderer.setRenderMode(e)}get canCull(){return this.activeRenderer!==To&&this.workBuffer.frustumCuller.totalBoundsEntries>0}_createRenderer(e){e===Pd?this.renderer=new RV(this.device,this.node,this.cameraNode,this.layer,this.workBuffer):e===uo?(this.renderer=new dV(this.device,this.node,this.cameraNode,this.layer,this.workBuffer),this.initHybridSorting()):(this.renderer=new cV(this.device,this.node,this.cameraNode,this.layer,this.workBuffer),this.initCpuSorting()),this.activeRenderer=e}prepareRendererMode(){const e=this.scene.gsplat.currentRenderer;e!==this.activeRenderer&&(this._worldStateDirty=!0,this.destroyGpuSorting(),this.destroyCpuSorting(),this.renderer.destroy(),this._createRenderer(e),this.renderer.setRenderMode(this.renderMode),this._workBufferRebuildRequired=!0,this.sortNeeded=!0)}reconcile(e){so.clear();for(const t of e)t.resource instanceof TC?(this.octreeInstances.has(t)||(this.octreeInstances.set(t,new HV(this.device,t.resource.octree,t)),this.hasNewOctreeInstances=!0),fm.add(t)):so.add(t);for(const[t,s]of this.octreeInstances)fm.has(t)||(this.octreeInstances.delete(t),this.layerPlacementsDirty=!0,this._placementSetChanged=!0,this.octreeInstancesToDestroy.push(s));if(this.layerPlacementsDirty||(this.layerPlacementsDirty=this.layerPlacements.length!==so.size),!this.layerPlacementsDirty)for(let t=0;t<this.layerPlacements.length;t++){const s=this.layerPlacements[t];if(!so.has(s)){this.layerPlacementsDirty=!0;break}}this._placementSetChanged||(this._placementSetChanged=this.layerPlacementsDirty),this.layerPlacements.length=0;for(const t of so)this.layerPlacements.push(t);so.clear(),fm.clear()}updateWorldState(){let e=this._stateTracker.hasChanges(this.layerPlacements);for(const[,i]of this.octreeInstances)this._stateTracker.hasChanges(i.activePlacements)&&(e=!0);if(this.layerPlacementsDirty||e||this.worldStates.size===0||this._worldStateDirty){this.lastWorldStateVersion++;const i=[];for(const a of this.layerPlacements){if(this.cpuSorter&&!a.resource.hasCenters)continue;a.ensureInstanceStreams(this.device);const n=new g0(this.device,a.resource,a,a.consumeRenderDirty.bind(a));i.push(n)}
15204for(const[,a]of this.octreeInstances)a.activePlacements.forEach(n=>{if(n.resource){const o=n.resource;if(this.cpuSorter&&!o.hasCenters)return;n.ensureInstanceStreams(this.device);const c=n.intervals.size>0?a.octree.nodes:null,h=c?a.nodeInfos:null,d=new g0(this.device,n.resource,n,n.consumeRenderDirty.bind(n),c,h);i.push(d)}});if(this.cpuSorter)for(const a of i){const n=a.resource;this._centersVersions.get(n.id)!==n.centersVersion&&(this._centersVersions.set(n.id,n.centersVersion),this.cpuSorter.setCenters(n.id,null),this.cpuSorter.setCenters(n.id,n.centers))}this.cpuSorter?.updateCentersForSplats(i);const r=new YV(this.device,this.lastWorldStateVersion,i,this._allocator,this._allocationMap);for(const a of r.splats)a.resource.incRefCount();for(const[,a]of this.octreeInstances)if(a.removedCandidates&&a.removedCandidates.size){for(const n of a.removedCandidates)r.pendingReleases.push([a.octree,n]);a.removedCandidates.clear()}if(this.octreeInstancesToDestroy.length){for(const a of this.octreeInstancesToDestroy){if(a.removedCandidates&&a.removedCandidates.size){for(const o of a.removedCandidates)r.pendingReleases.push([a.octree,o]);a.removedCandidates.clear()}const n=a.getFileDecrements();for(const o of n)r.pendingReleases.push([a.octree,o]);a.destroy(!0)}this.octreeInstancesToDestroy.length=0}this._placementSetChanged&&(r.fullRebuild=!0),this.worldStates.set(this.lastWorldStateVersion,r),this.layerPlacementsDirty=!1,this._placementSetChanged=!1,this._worldStateDirty=!1,this.sortNeeded=!0}}onSorted(e,t,s){this.cleanupOldWorldStates(t),this.sortedVersion=t;const i=this.worldStates.get(t);i&&(i.sortedBefore||(i.sortedBefore=!0,this.rebuildWorkBuffer(i,e)),this.workBuffer.setOrderData(s),this.renderer.setOrderData())}rebuildWorkBuffer(e,t,s=!1){const i=e.textureSize;i!==this.workBuffer.textureSize&&this.workBuffer.resize(i),this.activeRenderer!==To&&(this.workBuffer.frustumCuller.updateBoundsData(e.boundsGroups),this.workBuffer.frustumCuller.updateTransformsData(e.boundsGroups));const r=s||e.fullRebuild,a=r?e.splats:e.needsUpload,n=r?null:e.needsUploadIds;if(a.length>0){const o=this._allocationMap.size,c=r?o:e.needsUploadIds.size;this.bufferCopyUploaded+=c,this.bufferCopyTotal=o,this.workBuffer.render(a,this.cameraNode,this.getDebugColors(),n)}for(let o=0;o<e.splats.length;o++)e.splats[o].update();if(this.updateColorCameraTracking(),e.pendingReleases&&e.pendingReleases.length){const o=this.scene.gsplat.cooldownTicks;for(const[c,h]of e.pendingReleases)c.decRefCount(h,o);e.pendingReleases.length=0}this.renderer.update(t,i)}cleanupOldWorldStates(e){const t=this.worldStates.get(e);if(!t.fullRebuild){for(let s=this.sortedVersion+1;s<e;s++)if(this.worldStates.get(s)?.fullRebuild){t.fullRebuild=!0;break}}if(!t.fullRebuild){const s=t.needsUploadIds,i=t.allocIdToSplat;for(let r=this.sortedVersion+1;r<e;r++){const a=this.worldStates.get(r);if(a){for(const n of a.needsUploadIds)if(!s.has(n)){s.add(n);const o=i.get(n);o&&!vm.has(o)&&(t.needsUpload.push(o),vm.add(o))}}}vm.clear()}for(let s=this.sortedVersion;s<e;s++){const i=this.worldStates.get(s);if(i){for(const r of i.splats)r.resource.decRefCount();this.worldStates.delete(s),i.destroy()}}}applyWorkBufferUpdates(e){const{colorUpdateAngle:t}=this.scene.gsplat,s=Math.tan(t*H.DEG_TO_RAD),i=this.cameraNode.getPosition(),{translationDelta:r}=this.calculateColorCameraDeltas(),a=r>0;let n=0;e.splats.forEach(o=>{if(o.update()){if(ld.push(o),n+=o.intervalAllocIds.length,o.nodeInfos)for(const c of o.intervalNodeIndices)o.nodeInfos[c].colorAccumulatedTranslation=0;else o.colorAccumulatedTranslation=0;this.sortNeeded=!0}else if(a&&o.hasSphericalHarmonics)if(pm.push(o),o.nodeInfos){const c=o.intervalNodeIndices;for(let h=0;h<c.length;h++){const d=o.nodeInfos[c[h]];d.colorAccumulatedTranslation+=r;const u=s*Math.max(1,d.worldDistance);d.colorAccumulatedTranslation>=u&&(Dl.add(o.intervalAllocIds[h]),d.colorAccumulatedTranslation=0,n++)}}else{o.colorAccumulatedTranslation+=r,Il.copy(o.node.getWorldTransform()).invert(),Il.transformPoint(i,_m),o.aabb.closestPoint(_m,F0);const c=_m.distance(F0)*o.node.getWorldTransform().getScale().x,h=s*Math.max(1,c);o.colorAccumulatedTranslation>=h&&(Dl.add(o.allocId),n+=o.intervalAllocIds.length,o.colorAccumulatedTranslation=0)}}),this.bufferCopyUploaded+=n,this.bufferCopyTotal=this._allocationMap.size,ld.length>0&&(this.workBuffer.render(ld,this.cameraNode,this.getDebugColors()),ld.length=0),Dl.size>0&&(this.workBuffer.renderColor(pm,this.cameraNode,this.getDebugColors(),Dl),Dl.clear()),pm.length=0}testCameraMovedForLod(){const e=this.scene.gsplat.lodUpdateDistance,t=this.cameraNode.getPosition(),s=this.lastLodCameraPos.distance(t)>e;if(s)return!0;let i=!1;const r=this.scene.gsplat.lodUpdateAngle;if(r>0)if(Number.isFinite(this.lastLodCameraFwd.x)){const o=this.cameraNode.forward,c=Math.min(1,Math.max(-1,this.lastLodCameraFwd.dot(o))),h=Math.acos(c),d=r*H.DEG_TO_RAD;i=h>d}else i=!0;const a=this.cameraNode.camera.fov,n=this.lastLodCameraFov<0||Math.abs(a-this.lastLodCameraFov)>this.lastLodCameraFov*.02;return s||i||n}testCameraMovedForSort(){if(this.scene.gsplat.radialSorting){const t=this.cameraNode.getPosition();return this.lastSortCameraPos.distance(t)>.001}if(Number.isFinite(this.lastSortCameraFwd.x)){const t=this.cameraNode.forward,s=Math.min(1,Math.max(-1,this.lastSortCameraFwd.dot(t)));return Math.acos(s)>.001}return!0}testFrustumChanged(){if(!this.lastCullingProjMat.equals(this.cameraNode.camera.projectionMatrix))return!0;const t=this.cameraNode.forward,s=Math.min(1,Math.max(-1,this.lastCullingCameraFwd.dot(t)));return Math.acos(s)>.001}
15204updateColorCameraTracking(){this.lastColorUpdateCameraPos.copy(this.cameraNode.getPosition())}getDebugColors(){const e=this.scene.gsplat.debug;if(e===Jm){Yr??(Yr=[]);const t=Math.random(),s=Math.random(),i=Math.random();for(let r=0;r<O0.length;r++)Yr[r]??(Yr[r]=[0,0,0]),Yr[r][0]=t,Yr[r][1]=s,Yr[r][2]=i;return Yr}else if(e===Bl)return O0}calculateColorCameraDeltas(){if(mm.translationDelta=0,isFinite(this.lastColorUpdateCameraPos.x)){const e=this.cameraNode.getPosition();mm.translationDelta=this.lastColorUpdateCameraPos.distance(e)}return mm}fireFrameReadyEvent(){const e=this.sortedVersion===this.lastWorldStateVersion&&!this._awaitingLodUpdate;let t=0;for(const[,s]of this.octreeInstances)t+=s.pendingLoadCount;this.director.eventHandler.fire("frame:ready",this.cameraNode.camera,this.renderer.layer,e,t)}computeGlobalMaxDistance(){let e=0;Xr.copy(this.cameraNode.getPosition());for(const[,t]of this.octreeInstances){const s=t.placement.node.getWorldTransform(),i=t.placement.aabb;s.transformPoint(i.center,rr);const r=s.getScale().x,a=rr.distance(Xr)+i.halfExtents.length()*r;a>e&&(e=a)}return Math.max(e,1)}_enforceBudget(e){const t=this.workBuffer.textureSize;let s=0,i=0;for(const c of this.layerPlacements){const h=c.resource;if(h){const d=h.numSplats??0;s+=d,i+=(t-d%t)%t}}const r=Math.max(1,e-s),a=this.computeGlobalMaxDistance();let n=0;for(const[,c]of this.octreeInstances){n+=c.evaluateOptimalLods(this.cameraNode,this.scene.gsplat,this._budgetScale,a);for(const h of c.activePlacements){const u=h.resource?.numSplats??0;i+=(t-u%t)%t}}const o=Math.max(1,r-i);if(n>0){const c=n/o,h=.4,d=.3;if(c>1+h||c<1-h){const u=1/Math.sqrt(c);this._budgetScale*=1+(u-1)*d,this._budgetScale=Math.max(.01,Math.min(this._budgetScale,100))}}this._budgetBalancer.balance(this.octreeInstances,o);for(const[,c]of this.octreeInstances){const h=c.octree.lodLevels-1;c.applyLodChanges(h,this.scene.gsplat)}}handleFormatChange(){const e=this.scene.gsplat.format;this.workBuffer.format!==e&&(this.workBuffer.destroy(),this.workBuffer=new xy(this.device,e),this.renderer.setDataSource(this.workBuffer),this._workBufferFormatVersion=this.workBuffer.format.extraStreamsVersion,this._workBufferRebuildRequired=!0,this.sortNeeded=!0)}update(){this.bufferCopyUploaded=0,this.bufferCopyTotal=0,this.handleFormatChange();const e=this.workBuffer.format.extraStreamsVersion;this._workBufferFormatVersion!==e&&(this._workBufferFormatVersion=e,this.workBuffer.syncWithFormat(),this._workBufferRebuildRequired=!0,this.sortNeeded=!0),this.prepareRendererMode(),this.cpuSorter&&this.cpuSorter.applyPendingSorted();const t=this.activeRenderer!==To||this.cpuSorter&&this.cpuSorter.jobsInFlight<3;let s=!1;this.framesTillFullUpdate--,this.framesTillFullUpdate<=0&&(this.framesTillFullUpdate=10,t&&(s=!0));const i=this.hasNewOctreeInstances&&t;i&&(this.hasNewOctreeInstances=!1);let r=!1,a=!1,n=!1;if(s){for(const[,f]of this.octreeInstances){const p=f.update();this.layerPlacementsDirty||(this.layerPlacementsDirty=p),this._placementSetChanged||(this._placementSetChanged=f.consumePlacementSetChanged());const m=f.consumeNeedsLodUpdate();r||(r=m)}const u=this.scene.gsplat.lodUpdateDistance;for(const[,f]of this.octreeInstances){const p=f.testMoved(u);a||(a=p)}n=this.testCameraMovedForLod(),this._awaitingLodUpdate=!1}if(this.testCameraMovedForSort()&&(this.sortNeeded=!0),this.intervalCompaction&&!this.sortNeeded&&this.testFrustumChanged()&&(this.lastCullingCameraFwd.copy(this.cameraNode.forward),this.lastCullingProjMat.copy(this.cameraNode.camera.projectionMatrix),this.sortNeeded=!0),this.scene.gsplat.dirty&&(this.layerPlacementsDirty=!0,this.renderer.updateOverdrawMode(this.scene.gsplat),this._workBufferRebuildRequired=!0,this.sortNeeded=!0,this.octreeInstances.size>0&&(this._awaitingLodUpdate=!0)),n||a||this.scene.gsplat.dirty||r||i){for(const[,p]of this.octreeInstances)p.updateMoved();const u=this.cameraNode;this.lastLodCameraPos.copy(u.getPosition()),this.lastLodCameraFwd.copy(u.forward),this.lastLodCameraFov=u.camera.fov;const f=this.scene.gsplat.splatBudget;if(f>0)this._enforceBudget(f);else{this._budgetScale=1;for(const[,p]of this.octreeInstances)p.updateLod(this.cameraNode,this.scene.gsplat)}}this.updateWorldState();const o=this.worldStates.get(this.lastWorldStateVersion);if(o&&this.cpuSorter&&!o.sortParametersSet){o.sortParametersSet=!0;const u=this.prepareSortParameters(o);this.cpuSorter.setSortParameters(u)}const c=this.worldStates.get(this.sortedVersion);if(c?.sortedBefore)if(this._workBufferRebuildRequired){const u=c.totalActiveSplats;this.rebuildWorkBuffer(c,u,!0),this._workBufferRebuildRequired=!1,this.renderer.setOrderData(),this.intervalCompaction&&(this.intervalCompaction._uploadedVersion=-1)}else this.applyWorkBufferUpdates(c);let h=!1;if(this.sortNeeded&&o&&(this.activeRenderer===Pd?(this.compactGpu(o),h=!0):this.activeRenderer===uo?(this.sortGpuHybrid(o),h=!0):this.sortCpu(o),this.sortNeeded=!1,this.lastSortCameraPos.copy(this.cameraNode.getPosition()),this.lastSortCameraFwd.copy(this.cameraNode.forward),this.lastCullingCameraFwd.copy(this.cameraNode.forward),this.lastCullingProjMat.copy(this.cameraNode.camera.projectionMatrix)),this.activeRenderer===uo&&o&&!h&&(this.sortGpuHybrid(o),h=!0),c?.sortedBefore&&this.updateColorCameraTracking(),this.octreeInstances.size){const u=this.scene.gsplat.cooldownTicks;for(const[,f]of this.octreeInstances){const p=f.octree;gm.has(p)||(gm.add(p),p.updateCooldownTick(u))}gm.clear()}if(this.fireFrameReadyEvent(),this.scene.gsplat.dirty)for(const[,u]of this.octreeInstances)u.needsLodUpdate=!0;const d=this.scene.gsplat.useFog?this.cameraNode.camera.fogParams??this.scene.fog:null;return this.renderer.frameUpdate(this.scene.gsplat,this.scene.exposure,d),c?c.totalActiveSplats:0}sortGpuHybrid(e){const t=this.cameraNode.camera,s=t.camera,i=t.renderTarget,r=t.rect,a=s.xr?.session?s.xr.views.list[0]:null,n=Math.floor((a?a.viewport.z:i?i.width:this.device.width)*r.z),o=Math.floor((a?a.viewport.w:i?i.height:this.device.height)*r.w),c=this.sortGpuHybridForCamera(e,this.cameraNode,n,o,Math.max(wu,this.scene.gsplat.alphaClipForward),!1);c&&this.applyGpuSortResults(c)}sortGpuHybridForCamera(e,t,s,i,r,a){const n=this.gpuSorter,o=this.projector;if(!n||!o)return null;const c=e.totalActiveSplats;if(c===0)return null;if(this.intervalCompaction||(this.intervalCompaction=new R0(this.device)),e.sortedBefore||(e.sortedBefore=!0,this.cleanupOldWorldStates(e.version),this.sortedVersion=e.version,this.rebuildWorkBuffer(e,c)),this.intervalCompaction.uploadIntervals(e),this.canCull){const T=this.worldStates.get(this.sortedVersion);T&&this._runFrustumCulling(T,t)}
15204const h=this.renderer.fisheyeProj,d=e.totalIntervals,u=e.totalActiveSplats;this.intervalCompaction.dispatchCompact(this.workBuffer.frustumCuller,d,u,h.enabled),this.allocateAndWriteIntervalIndirectArgs(d);const f=this.intervalCompaction,p=f.compactedSplatIds,m=this.scene.gsplat,_=Math.max(10,Math.min(20,Math.round(Math.log2(c/4)))),g=n.radixBits,v=Math.ceil(_/g)*g,{minDist:x,maxDist:y}=this.computeDistanceRange(e,t),S=n.prepareIndirect();return o.dispatch({workBuffer:this.workBuffer,cameraNode:t,compactedSplatIds:p,sortElementCountBuffer:f.sortElementCountBuffer,totalCapacity:c,radialSort:m.radialSorting,numBits:v,minDist:x,maxDist:y,alphaClip:r,minPixelSize:m.minPixelSize*.5,minContribution:m.minContribution,viewportWidth:s,viewportHeight:i,flipY:!!t.camera.renderTarget?.flipY,pickMode:a,fisheyeProj:h,antiAlias:m.antiAlias}),o.writeIndirectArgs(this.indirectDrawSlot,this.indirectDispatchSlot+1,f.numSplatsBuffer,f.sortElementCountBuffer,S),n.sortIndirect(o.sortKeys,c,v,this.indirectDispatchSlot+1,f.sortElementCountBuffer,void 0,!1,!0)}compactGpu(e){this.intervalCompaction||(this.intervalCompaction=new R0(this.device));const t=e.totalActiveSplats;if(t===0)return;if(e.sortedBefore||(e.sortedBefore=!0,this.cleanupOldWorldStates(e.version),this.sortedVersion=e.version,this.rebuildWorkBuffer(e,t)),this.intervalCompaction.uploadIntervals(e),this.canCull){const n=this.worldStates.get(this.sortedVersion);n&&this._runFrustumCulling(n)}const s=e.totalIntervals,i=e.totalActiveSplats;this.intervalCompaction.dispatchCompact(this.workBuffer.frustumCuller,s,i,this.renderer.fisheyeProj.enabled),this.allocateAndWriteIntervalIndirectArgs(s);const r=this.intervalCompaction;this.renderer.setCompactedData(r.compactedSplatIds,r.sortElementCountBuffer,e.textureSize,i)}allocateAndWriteIntervalIndirectArgs(e){const t=this.gpuSorter,s=t?t.prepareIndirect():tG,i=s[0];this.indirectDrawSlot=this.device.getIndirectDrawSlot(1),this.indirectDispatchSlot=this.device.getIndirectDispatchSlot(1+i),this.intervalCompaction.writeIndirectArgs(this.indirectDrawSlot,this.indirectDispatchSlot,e,s),this.lastCompactedNumIntervals=e}applyGpuSortResults(e){const t=this.projector,s=this.intervalCompaction;this.renderer.setHybridSortedRendering(this.indirectDrawSlot,e,t.projCache,s.numSplatsBuffer)}_runFrustumCulling(e,t=this.cameraNode){this.workBuffer.frustumCuller.updateTransformsData(e.boundsGroups);const s=t.camera;this.workBuffer.frustumCuller.computeFrustumPlanes(s.projectionMatrix,s.viewMatrix);const i=this.scene.gsplat,r=this.renderer.fisheyeProj;r.update(i.fisheye,s.fov,s.projectionMatrix),r.enabled&&this.workBuffer.frustumCuller.setFisheyeData(t.getPosition(),t.forward,r.maxTheta)}computeDistanceRange(e,t=this.cameraNode){const s=t.getWorldTransform();s.getTranslation(Xr),s.getZ(Pl).normalize();const i=this.scene.gsplat.radialSorting;let r=i?0:1/0,a=i?0:-1/0;for(const n of e.splats){const o=n.node.getWorldTransform(),c=n.aabb.getMin(),h=n.aabb.getMax();for(let d=0;d<8;d++)if(rr.x=d&1?h.x:c.x,rr.y=d&2?h.y:c.y,rr.z=d&4?h.z:c.z,o.transformPoint(rr,rr),i){const u=rr.distance(Xr);u>a&&(a=u)}else{const u=rr.sub(Xr).dot(Pl);u<r&&(r=u),u>a&&(a=u)}}return a===0||a===-1/0?{minDist:0,maxDist:1}:{minDist:r,maxDist:a}}sortCpu(e){if(!this.cpuSorter)return;const s=this.cameraNode.getWorldTransform();s.getTranslation(Xr),s.getZ(Pl).normalize();const i=[];e.splats.forEach(r=>{const a=r.node.getWorldTransform();Il.copy(a).invert();const n=a.getScale().x,o=Il.transformVector(Pl).normalize(),c=Il.transformPoint(Xr);a.getTranslation(L0);const h=L0.sub(Xr).dot(Pl),d=r.aabb.getMin(),u=r.aabb.getMax();i.push({transformedDirection:o,transformedPosition:c,offset:h,scale:n,modelMat:a.data.slice(),aabbMin:[d.x,d.y,d.z],aabbMax:[u.x,u.y,u.z]})}),this.cpuSorter.setSortParams(i,this.scene.gsplat.radialSorting)}prepareSortParameters(e){return{command:"intervals",textureSize:e.textureSize,totalActiveSplats:e.totalActiveSplats,version:e.version,ids:e.splats.map(t=>t.resource.id),pixelOffsets:e.splats.map(t=>t.intervalOffsets),intervals:e.splats.map(t=>t.intervals)}}}class iG{static equals(e,t){if(e.size!==t.size)return!1;for(const s of e)if(!t.has(s))return!1;return!0}}const cd=[];class rG{gsplatManager=null;gsplatManagerShadow=null;constructor(e,t,s,i){this.updateConfiguration(e,t,s,i)}createManager(e,t,s,i,r,a){const n=new sG(e,t,s,i);return n.setRenderMode(a),t.eventHandler&&t.eventHandler.fire("material:created",
15204n.material,r,s),n}updateConfiguration(e,t,s,i){const r=i.node,a=s.gsplatPlacements.length>0,n=s.gsplatShadowCasters.length>0,c=iG.equals(s.gsplatPlacementsSet,s.gsplatShadowCastersSet)&&a,h=c?xs|ho:a?xs:0,d=c?0:n?ho:0;h?this.gsplatManager?this.gsplatManager.setRenderMode(h):this.gsplatManager=this.createManager(e,t,s,r,i,h):this.gsplatManager&&(this.gsplatManager.destroy(),this.gsplatManager=null),d?this.gsplatManagerShadow?this.gsplatManagerShadow.setRenderMode(d):this.gsplatManagerShadow=this.createManager(e,t,s,r,i,d):this.gsplatManagerShadow&&(this.gsplatManagerShadow.destroy(),this.gsplatManagerShadow=null)}destroy(){this.gsplatManager?.destroy(),this.gsplatManager=null,this.gsplatManagerShadow?.destroy(),this.gsplatManagerShadow=null}}class aG{layersMap=new Map;destroy(){this.layersMap.forEach(e=>e.destroy()),this.layersMap.clear()}removeLayerData(e){const t=this.layersMap.get(e);t&&(t.destroy(),this.layersMap.delete(e))}getLayerData(e,t,s,i){let r=this.layersMap.get(s);return r||(r=new rG(e,t,s,i),this.layersMap.set(s,r)),r}}class nG{device;camerasMap=new Map;scene;eventHandler;constructor(e,t,s,i){this.device=e,this.renderer=t,this.scene=s,this.eventHandler=i}destroy(){this.camerasMap.forEach(e=>e.destroy()),this.camerasMap.clear()}getCameraData(e){let t=this.camerasMap.get(e);return t||(t=new aG,this.camerasMap.set(e,t)),t}prepareForPicking(e,t,s,i){const r=this.camerasMap.get(e);if(!r)return null;const a=r.layersMap.get(i);return a?.gsplatManager?a.gsplatManager.prepareForPicking(e,t,s):null}update(e){xc.process(this.device),this.camerasMap.forEach((a,n)=>{if(!e.camerasSet.has(n))a.destroy(),this.camerasMap.delete(n);else{a.layersMap.forEach((o,c)=>{(!n.layersSet.has(c.id)||!c.enabled)&&cd.push(c)});for(let o=0;o<cd.length;o++){const c=cd[o],h=a.layersMap.get(c);h&&(h.destroy(),a.layersMap.delete(c))}cd.length=0}});let t=0,s=0,i=0;const r=e.cameras;for(let a=0;a<r.length;a++){const n=r[a].camera;let o=this.camerasMap.get(n);const c=n.layers;for(let h=0;h<c.length;h++){const d=e.getLayerById(c[h]);if(d?.enabled&&(d.gsplatPlacementsDirty||!o)){const u=d.gsplatPlacements.length>0,f=d.gsplatShadowCasters.length>0;if(!u&&!f)o&&o.removeLayerData(d);else{o??(o=this.getCameraData(n));const p=o.getLayerData(this.device,this,d,n);p.updateConfiguration(this.device,this,d,n),p.gsplatManager&&p.gsplatManager.reconcile(d.gsplatPlacements),p.gsplatManagerShadow&&p.gsplatManagerShadow.reconcile(d.gsplatShadowCasters)}}}if(o)for(const h of o.layersMap.values())h.gsplatManager&&(t+=h.gsplatManager.update(),s+=h.gsplatManager.bufferCopyUploaded,i+=h.gsplatManager.bufferCopyTotal),h.gsplatManagerShadow&&(t+=h.gsplatManagerShadow.update(),s+=h.gsplatManagerShadow.bufferCopyUploaded,i+=h.gsplatManagerShadow.bufferCopyTotal)}this.renderer._gsplatCount=t,this.renderer._gsplatBufferCopy=i>0?s/i*100:0,this.scene.gsplat.frameEnd();for(let a=0;a<e.layerList.length;a++)e.layerList[a].gsplatPlacementsDirty=!1}}class wC extends ye{_layers=[Ir];_instance=null;_placement=null;_id=HT.get();_materialTmp=null;_highQualitySH=!0;_lodBaseDistance=5;_lodMultiplier=3;_customAabb=null;_assetReference;_resource=null;_evtLayersChanged=null;_evtLayerAdded=null;_evtLayerRemoved=null;_castShadows=!1;_unified=!0;_parameters=new Map;_workBufferUpdate=Qm;_workBufferModifier=null;constructor(e,t){super(e,t),this._assetReference=new Ec("asset",this,e.app.assets,{add:this._onGSplatAssetAdded,load:this._onGSplatAssetLoad,remove:this._onGSplatAssetRemove,unload:this._onGSplatAssetUnload},this),t.on("remove",this.onRemoveChild,this),t.on("removehierarchy",this.onRemoveChild,this),t.on("insert",this.onInsertChild,this),t.on("inserthierarchy",this.onInsertChild,this)}set customAabb(e){this._customAabb=e,this._instance?.meshInstance?.setCustomAabb(this._customAabb),this._placement&&(this._placement.aabb=this._customAabb)}get customAabb(){return this._customAabb??this._placement?.aabb??this.resource?.aabb??null}set instance(e){if(!this.unified&&(this.destroyInstance(),this._instance=e,this._instance)){const t=this._instance.meshInstance;t.node||(t.node=this.entity),t.castShadow=this._castShadows,t.setCustomAabb(this._customAabb),this.enabled&&this.entity.enabled&&this.addToLayers()}}get instance(){return this.unified,this._instance}set material(e){this.unified||(this._instance?this._instance.material=e:this._materialTmp=e)}get material(){return this.unified?null:this._instance?.material??this._materialTmp??null}set highQualitySH(e){e!==this._highQualitySH&&(this._highQualitySH=e,this._instance?.
15204setHighQualitySH(e))}get highQualitySH(){return this._highQualitySH}set castShadows(e){if(this._castShadows!==e){const t=this.layers,s=this.system.app.scene;if(this._placement)if(e)for(let r=0;r<t.length;r++)s.layers.getLayerById(t[r])?.addGSplatShadowCaster(this._placement);else for(let r=0;r<t.length;r++)s.layers.getLayerById(t[r])?.removeGSplatShadowCaster(this._placement);const i=this._instance?.meshInstance;if(i){if(this._castShadows&&!e)for(let r=0;r<t.length;r++)s.layers.getLayerById(this.layers[r])?.removeShadowCasters([i]);if(i.castShadow=e,!this._castShadows&&e)for(let r=0;r<t.length;r++)s.layers.getLayerById(t[r])?.addShadowCasters([i])}this._castShadows=e}}get castShadows(){return this._castShadows}set lodBaseDistance(e){this._lodBaseDistance=Math.max(.1,e),this._placement&&(this._placement.lodBaseDistance=this._lodBaseDistance)}get lodBaseDistance(){return this._lodBaseDistance}set lodMultiplier(e){this._lodMultiplier=Math.max(1.2,e),this._placement&&(this._placement.lodMultiplier=this._lodMultiplier)}get lodMultiplier(){return this._lodMultiplier}set lodDistances(e){Array.isArray(e)&&e.length>0&&(this.lodBaseDistance=e[0],this.lodMultiplier=3)}get lodDistances(){return[]}set splatBudget(e){}get splatBudget(){return 0}set unified(e){this._unified!==e&&(this._unified=e,this._onGSplatAssetAdded())}get unified(){return this._unified}get id(){return this._id}set workBufferUpdate(e){this._workBufferUpdate=e,this._placement&&(this._placement.workBufferUpdate=e)}get workBufferUpdate(){return this._workBufferUpdate}setWorkBufferModifier(e){if(e){const s=(this.system.app.graphicsDevice.isWebGPU?e.wgsl:e.glsl)??null;this._workBufferModifier=s?{code:s,hash:Xs(s)}:null}else this._workBufferModifier=null;this._placement&&(this._placement.workBufferModifier=this._workBufferModifier)}set layers(e){this.removeFromLayers(),this._layers.length=0;for(let t=0;t<e.length;t++)this._layers[t]=e[t];!this.enabled||!this.entity.enabled||this.addToLayers()}get layers(){return this._layers}set asset(e){const t=e instanceof pe?e.id:e;this._assetReference.id!==t&&(this._assetReference.asset&&this._assetReference.asset.resource&&this._onGSplatAssetRemove(),this._assetReference.id=t,this._assetReference.asset&&this._onGSplatAssetAdded())}get asset(){return this._assetReference.id}set resource(e){this._resource!==e&&((this._resource||this._assetReference.asset?.resource)&&this._onGSplatAssetRemove(),e&&this._assetReference.id&&(this._assetReference.id=null),this._resource=e,this._resource&&this.enabled&&this.entity.enabled&&this._onGSplatAssetLoad())}get resource(){return this._resource??this._assetReference.asset?.resource??null}destroyInstance(){this._placement&&(this.removeFromLayers(),this._placement.destroy(),this._placement=null),this._instance&&(this.removeFromLayers(),this._instance?.destroy(),this._instance=null)}addToLayers(){if(this._placement){const t=this.system.app.scene.layers;for(let s=0;s<this._layers.length;s++){const i=t.getLayerById(this._layers[s]);i&&(i.addGSplatPlacement(this._placement),this._castShadows&&i.addGSplatShadowCaster(this._placement))}return}const e=this._instance?.meshInstance;if(e){const t=this.system.app.scene.layers;for(let s=0;s<this._layers.length;s++)t.getLayerById(this._layers[s])?.addMeshInstances([e])}}removeFromLayers(){if(this._placement){const t=this.system.app.scene.layers;for(let s=0;s<this._layers.length;s++){const i=t.getLayerById(this._layers[s]);i&&(i.removeGSplatPlacement(this._placement),i.removeGSplatShadowCaster(this._placement))}return}const e=this._instance?.meshInstance;if(e){const t=this.system.app.scene.layers;for(let s=0;s<this._layers.length;s++)t.getLayerById(this._layers[s])?.removeMeshInstances([e])}}onRemoveChild(){this.removeFromLayers()}onInsertChild(){this.enabled&&this.entity.enabled&&(this._instance||this._placement)&&this.addToLayers()}onRemove(){this.destroyInstance(),this.asset=null,this._assetReference.id=null,this.entity.off("remove",this.onRemoveChild,this),this.entity.off("insert",this.onInsertChild,this)}onLayersChanged(e,t){this.addToLayers(),e.off("add",this.onLayerAdded,this),e.off("remove",this.onLayerRemoved,this),t.on("add",this.onLayerAdded,this),t.on("remove",this.onLayerRemoved,this)}onLayerAdded(e){this.layers.indexOf(e.id)<0||this.unified||this._instance&&e.addMeshInstances(this._instance.meshInstance)}onLayerRemoved(e){this.layers.indexOf(e.id)<0||this.unified||this._instance&&e.removeMeshInstances(this._instance.meshInstance)}
15204onEnable(){const e=this.system.app.scene,t=e.layers;this._evtLayersChanged=e.on("set:layers",this.onLayersChanged,this),t&&(this._evtLayerAdded=t.on("add",this.onLayerAdded,this),this._evtLayerRemoved=t.on("remove",this.onLayerRemoved,this)),this._instance||this._placement?this.addToLayers():this.asset?this._onGSplatAssetAdded():this._resource&&this._onGSplatAssetLoad()}onDisable(){const t=this.system.app.scene.layers;this._evtLayersChanged?.off(),this._evtLayersChanged=null,t&&(this._evtLayerAdded?.off(),this._evtLayerAdded=null,this._evtLayerRemoved?.off(),this._evtLayerRemoved=null),this.removeFromLayers()}hide(){this._instance&&(this._instance.meshInstance.visible=!1)}show(){this._instance&&(this._instance.meshInstance.visible=!0)}setParameter(e,t){const s=this.system.app.graphicsDevice.scope.resolve(e);this._parameters.set(e,{scopeId:s,data:t}),this._placement&&(this._placement.renderDirty=!0)}getParameter(e){return this._parameters.get(e)?.data}deleteParameter(e){this._parameters.delete(e),this._placement&&(this._placement.renderDirty=!0)}getInstanceTexture(e){return this._placement?this._placement.getInstanceTexture(e,this.system.app.graphicsDevice)??null:null}_onGSplatAssetAdded(){this._assetReference.asset&&(this._assetReference.asset.resource?this._onGSplatAssetLoad():this.enabled&&this.entity.enabled&&this.system.app.assets.load(this._assetReference.asset))}_onGSplatAssetLoad(){this.destroyInstance();const e=this._resource??this._assetReference.asset?.resource;e&&(this.unified?(this._placement=null,this._placement=new D_(e,this.entity,0,this._parameters,null,this._id),this._placement.lodBaseDistance=this._lodBaseDistance,this._placement.lodMultiplier=this._lodMultiplier,this._placement.workBufferUpdate=this._workBufferUpdate,this._placement.workBufferModifier=this._workBufferModifier,this.enabled&&this.entity.enabled&&this.addToLayers()):(this.instance=new ER(e,{material:this._materialTmp,highQualitySH:this._highQualitySH,scene:this.system.app.scene}),this._materialTmp=null))}_onGSplatAssetUnload(){this.destroyInstance()}_onGSplatAssetRemove(){this._onGSplatAssetUnload()}}class oG{enabled=!0}var lG=` 15205uniform mat4 matrix_model; 15206uniform mat4 matrix_view; 15207#ifndef GSPLAT_CENTER_NOPROJ 15208 uniform vec4 camera_params; 15209 uniform mat4 matrix_projection; 15210 #ifdef GSPLAT_FISHEYE 15211 uniform float fisheye_k; 15212 uniform float fisheye_inv_k; 15213 uniform float fisheye_projMat00; 15214 uniform float fisheye_projMat11; 15215 #endif 15216#endif 15217bool initCenter(vec3 modelCenter, inout SplatCenter center) { 15218 mat4 modelView = matrix_view * matrix_model; 15219 vec4 centerView = modelView * vec4(modelCenter, 1.0); 15220 #ifndef GSPLAT_CENTER_NOPROJ 15221 #ifdef GSPLAT_FISHEYE 15222 vec3 v = centerView.xyz; 15223 float r_xy = length(v.xy); 15224 float neg_z = -v.z; 15225 float theta = atan(r_xy, neg_z); 15226 float maxTheta = min(fisheye_k * 1.5707963, 3.13); 15227 if (theta > maxTheta - 0.01 || dot(v, v) < 0.0001) { 15228 return false; 15229 } 15230 float tk = theta * fisheye_inv_k; 15231 float sin_tk = sin(tk); 15232 float cos_tk = cos(tk); 15233 float g_theta = fisheye_k * sin_tk / cos_tk; 15234 float fisheye_s = (r_xy > 1e-4) ? g_theta / r_xy : (neg_z > 0.0 ? 1.0 / neg_z : 0.0); 15235 vec2 ndc = vec2(fisheye_projMat00 * fisheye_s * v.x, fisheye_projMat11 * fisheye_s * v.y); 15236 float near = camera_params.z; 15237 float far = camera_params.y; 15238 float linearDepth = neg_z; 15239 #if WEBGPU 15240 float depthNdc = clamp((linearDepth - near) / (far - near), 0.0, 1.0); 15241 #else 15242 float depthNdc = clamp(2.0 * (linearDepth - near) / (far - near) - 1.0, -1.0, 1.0); 15243 #endif 15244 center.proj = vec4(ndc, depthNdc, 1.0); 15245 center.projMat00 = fisheye_projMat00; 15246 center.fisheyeSinTK = sin_tk; 15247 center.fisheyeCosTK = cos_tk; 15248 center.fisheyeRxy = r_xy; 15249 #else 15250 if (camera_params.w != 1.0 && centerView.z > 0.0) { 15251 return false; 15252 } 15253 vec4 centerProj = matrix_projection * centerView; 15254 #if WEBGPU 15255 centerProj.z = clamp(centerProj.z, 0, abs(centerProj.w)); 15256 #else 15257 centerProj.z = clamp(centerProj.z, -abs(centerProj.w), abs(centerProj.w)); 15258 #endif 15259 center.proj = centerProj; 15260 center.projMat00 = matrix_projection[0][0]; 15261 #endif 15262 #endif 15263 center.view = centerView.xyz / centerView.w; 15264 center.modelView = modelView; 15265 return true; 15266} 15267`,cG=` 15268#include "gsplatHelpersVS" 15269#include "gsplatFormatVS" 15270#include "gsplatStructsVS" 15271#include "gsplatDeclarationsVS" 15272#include "gsplatModifyVS" 15273#include "gsplatEvalSHVS" 15274#include "gsplatQuatToMat3VS" 15275#include "gsplatReadVS" 15276#include "gsplatSourceVS" 15277#include "gsplatCenterVS" 15278#include "gsplatCornerVS" 15279#include "gsplatOutputVS" 15280#if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS) 15281uniform float alphaClip; 15282#else 15283uniform float alphaClipForward; 15284#endif 15285void clipCorner(inout SplatCorner corner, float alpha) { 15286 #if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS) 15287 float alphaClipValue = alphaClip; 15288 #else 15289 float alphaClipValue = alphaClipForward; 15290 #endif 15291 float clip = min(1.0, sqrt(max(0.0, log(alpha / alphaClipValue))) * 0.5); 15292 corner.offset *= clip; 15293 corner.uv *= clip; 15294} 15295`,hG=` 15296struct Splat { 15297 uint index; 15298 ivec2 uv; 15299}; 15300Splat splat; 15301void setSplat(uint idx) { 15302 splat.index = idx; 15303 splat.uv = ivec2(idx % splatTextureSize, idx / splatTextureSize); 15304} 15305`,dG=` 15306 #if SH_BANDS == 1 15307 #define SH_COEFFS 3 15308 #elif SH_BANDS == 2 15309 #define SH_COEFFS 8 15310 #elif SH_BANDS == 3 15311 #define SH_COEFFS 15 15312 #else 15313 #define SH_COEFFS 0 15314 #endif 15315 #if SH_BANDS > 0 15316 const float SH_C1 = 0.4886025119029199f; 15317 #if SH_BANDS > 1 15318 const float SH_C2_0 = 1.0925484305920792f; 15319 const float SH_C2_1 = -1.0925484305920792f; 15320 const float SH_C2_2 = 0.31539156525252005f; 15321 const float SH_C2_3 = -1.0925484305920792f; 15322 const float SH_C2_4 = 0.5462742152960396f; 15323 #endif 15324 #if SH_BANDS > 2 15325 const float SH_C3_0 = -0.5900435899266435f; 15326 const float SH_C3_1 = 2.890611442640554f; 15327 const float SH_C3_2 = -0.4570457994644658f; 15328 const float SH_C3_3 = 0.3731763325901154f; 15329 const float SH_C3_4 = -0.4570457994644658f; 15330 const float SH_C3_5 = 1.445305721320277f; 15331 const float SH_C3_6 = -0.5900435899266435f; 15332 #endif 15333 vec3 evalSH(in vec3 sh[SH_COEFFS], in vec3 dir) { 15334 float x = dir.x; 15335 float y = dir.y; 15336 float z = dir.z;
15337 vec3 result = SH_C1 * (-sh[0] * y + sh[1] * z - sh[2] * x); 15338 #if SH_BANDS > 1 15339 float xx = x * x; 15340 float yy = y * y; 15341 float zz = z * z; 15342 float xy = x * y; 15343 float yz = y * z; 15344 float xz = x * z; 15345 result += 15346 sh[3] * (SH_C2_0 * xy) + 15347 sh[4] * (SH_C2_1 * yz) + 15348 sh[5] * (SH_C2_2 * (2.0 * zz - xx - yy)) + 15349 sh[6] * (SH_C2_3 * xz) + 15350 sh[7] * (SH_C2_4 * (xx - yy)); 15351 #endif 15352 #if SH_BANDS > 2 15353 result += 15354 sh[8] * (SH_C3_0 * y * (3.0 * xx - yy)) + 15355 sh[9] * (SH_C3_1 * xy * z) + 15356 sh[10] * (SH_C3_2 * y * (4.0 * zz - xx - yy)) + 15357 sh[11] * (SH_C3_3 * z * (2.0 * zz - 3.0 * xx - 3.0 * yy)) + 15358 sh[12] * (SH_C3_4 * x * (4.0 * zz - xx - yy)) + 15359 sh[13] * (SH_C3_5 * z * (xx - yy)) + 15360 sh[14] * (SH_C3_6 * x * (xx - 3.0 * yy)); 15361 #endif 15362 return result; 15363 } 15364 #endif 15365`,uG=` 15366void gsplatMakeSpherical(inout vec3 scale, float size) { 15367 scale = vec3(size); 15368} 15369float gsplatGetSizeFromScale(vec3 scale) { 15370 return sqrt((scale.x * scale.x + scale.y * scale.y + scale.z * scale.z) / 3.0); 15371} 15372`,fG=` 15373void modifySplatCenter(inout vec3 center) { 15374} 15375void modifySplatRotationScale(vec3 originalCenter, vec3 modifiedCenter, inout vec4 rotation, inout vec3 scale) { 15376} 15377void modifySplatColor(vec3 center, inout vec4 color) { 15378} 15379`,pG=` 15380mat3 quatToMat3(vec4 R) { 15381 vec4 R2 = R + R; 15382 float X = R2.x * R.w; 15383 vec4 Y = R2.y * R; 15384 vec4 Z = R2.z * R; 15385 float W = R2.w * R.w; 15386 return mat3( 15387 1.0 - Z.z - W, 15388 Y.z + X, 15389 Y.w - Z.x, 15390 Y.z - X, 15391 1.0 - Y.y - W, 15392 Z.w + Y.x, 15393 Y.w + Z.x, 15394 Z.w - Y.x, 15395 1.0 - Y.y - Z.z 15396 ); 15397} 15398vec4 quatMul(vec4 a, vec4 b) { 15399 return vec4( 15400 a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, 15401 a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x, 15402 a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w, 15403 a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z 15404 ); 15405} 15406`,mG=` 15407#include "gsplatSplatVS" 15408struct SplatSource { 15409 uint order; 15410 vec2 cornerUV; 15411}; 15412struct SplatCenter { 15413 vec3 view; 15414 vec4 proj; 15415 mat4 modelView; 15416 float projMat00; 15417 vec3 modelCenterOriginal; 15418 vec3 modelCenterModified; 15419 #ifdef GSPLAT_FISHEYE 15420 float fisheyeSinTK; 15421 float fisheyeCosTK; 15422 float fisheyeRxy; 15423 #endif 15424}; 15425struct SplatCorner { 15426 vec3 offset; 15427 vec2 uv; 15428 #if GSPLAT_AA 15429 float aaFactor; 15430 #endif 15431 vec2 v; 15432 float dlen; 15433}; 15434`,_G=` 15435uniform vec4 viewport_size; 15436uniform float minPixelSize; 15437void computeCovariance(vec4 rotation, vec3 scale, out vec3 covA, out vec3 covB) { 15438 mat3 rot = quatToMat3(rotation); 15439 mat3 M = transpose(mat3( 15440 scale.x * rot[0], 15441 scale.y * rot[1], 15442 scale.z * rot[2] 15443 )); 15444 covA = vec3(dot(M[0], M[0]), dot(M[0], M[1]), dot(M[0], M[2])); 15445 covB = vec3(dot(M[1], M[1]), dot(M[1], M[2]), dot(M[2], M[2])); 15446} 15447bool initCornerCov(SplatSource source, SplatCenter center, out SplatCorner corner, vec3 covA, vec3 covB) { 15448 mat3 Vrk = mat3( 15449 covA.x, covA.y, covA.z, 15450 covA.y, covB.x, covB.y, 15451 covA.z, covB.y, covB.z 15452 ); 15453 float focal = viewport_size.x * center.projMat00; 15454 vec3 v = center.view.xyz; 15455 #ifdef GSPLAT_FISHEYE 15456 float r_sq = max(center.fisheyeRxy * center.fisheyeRxy, 1e-8); 15457 float d2 = dot(v, v); 15458 float neg_z = -v.z; 15459 float g_prime = 1.0 / (center.fisheyeCosTK * center.fisheyeCosTK); 15460 float g_theta = fisheye_k * center.fisheyeSinTK / center.fisheyeCosTK; 15461 float sv = (center.fisheyeRxy > 1e-4) ? g_theta / center.fisheyeRxy : (neg_z > 0.0 ? 1.0 / neg_z : 0.0); 15462 float K = (center.fisheyeRxy > 1e-4) ? (g_prime * neg_z / d2 - sv) / r_sq : 0.0; 15463 mat3 J = mat3( 15464 focal * (sv + K * v.x * v.x), focal * K * v.x * v.y, focal * g_prime * v.x / d2, 15465 focal * K * v.x * v.y, focal * (sv + K * v.y * v.y), focal * g_prime * v.y / d2, 15466 0.0, 0.0, 0.0 15467 ); 15468 #else 15469 vec3 vp = camera_params.w == 1.0 ? vec3(0.0, 0.0, 1.0) : v; 15470 float J1 = focal / vp.z; 15471 vec2 J2 = -J1 / vp.z * vp.xy; 15472 mat3 J = mat3( 15473 J1, 0.0, J2.x, 15474 0.0, J1, J2.y, 15475 0.0, 0.0, 0.0 15476 ); 15477 #endif 15478 mat3 W = transpose(mat3(center.modelView)); 15479 mat3 T = W * J; 15480 mat3 cov = transpose(T) * Vrk * T; 15481 #if GSPLAT_AA 15482 float detOrig = cov[0][0] * cov[1][1] - cov[0][1] * cov[0][1]; 15483 float detBlur = (cov[0][0] + 0.3) * (cov[1][1] + 0.3) - cov[0][1] * cov[0][1]; 15484 corner.aaFactor = sqrt(max(detOrig / detBlur, 0.0)); 15485 #endif 15486 float diagonal1 = cov[0][0] + 0.3; 15487 float offDiagonal = cov[0][1]; 15488 float diagonal2 = cov[1][1] + 0.3; 15489 float mid = 0.5 * (diagonal1 + diagonal2); 15490 float radius = length(vec2((diagonal1 - diagonal2) / 2.0, offDiagonal)); 15491 float lambda1 = mid + radius;
15492 float lambda2 = max(mid - radius, 0.1); 15493 float vmin = min(1024.0, min(viewport_size.x, viewport_size.y)); 15494 float l1 = 2.0 * min(sqrt(2.0 * lambda1), vmin); 15495 float l2 = 2.0 * min(sqrt(2.0 * lambda2), vmin); 15496 if (max(l1, l2) < minPixelSize) { 15497 return false; 15498 } 15499 vec2 c = center.proj.ww * viewport_size.zw; 15500 if (any(greaterThan(abs(center.proj.xy) - vec2(max(l1, l2)) * c, center.proj.ww))) { 15501 return false; 15502 } 15503 vec2 diagonalVector = normalize(vec2(offDiagonal, lambda1 - diagonal1)); 15504 vec2 v1 = l1 * diagonalVector; 15505 vec2 v2 = l2 * vec2(diagonalVector.y, -diagonalVector.x); 15506 corner.offset = vec3((source.cornerUV.x * v1 + source.cornerUV.y * v2) * c, 0.0); 15507 corner.uv = source.cornerUV; 15508 return true; 15509} 15510#if GSPLAT_2DGS 15511void initCorner2DGS(SplatSource source, vec4 rotation, vec3 scale, out SplatCorner corner) { 15512 vec2 localPos = source.cornerUV * vec2(scale.x, scale.y) * 3.0; 15513 vec3 v = vec3(localPos, 0.0); 15514 vec3 t = 2.0 * cross(rotation.xyz, v); 15515 corner.offset = v + rotation.w * t + cross(rotation.xyz, t); 15516 corner.uv = source.cornerUV; 15517} 15518#endif 15519bool initCorner(SplatSource source, SplatCenter center, out SplatCorner corner) { 15520 vec4 rotation = getRotation().yzwx; 15521 vec3 scale = getScale(); 15522 modifySplatRotationScale(center.modelCenterOriginal, center.modelCenterModified, rotation, scale); 15523 #if GSPLAT_2DGS 15524 initCorner2DGS(source, rotation, scale, corner); 15525 return true; 15526 #else 15527 vec3 covA, covB; 15528 computeCovariance(rotation.wxyz, scale, covA, covB); 15529 return initCornerCov(source, center, corner, covA, covB); 15530 #endif 15531} 15532`,gG=` 15533#include "tonemappingPS" 15534#include "decodePS" 15535#include "gammaPS" 15536#include "fogPS" 15537#if FOG != NONE && !defined(GSPLAT_NO_FOG) 15538 #define GSPLAT_FOG 15539#endif 15540vec3 prepareOutputFromGamma(vec3 gammaColor, float depth) { 15541 vec3 color = gammaColor; 15542 #if TONEMAP != NONE || GAMMA == NONE || defined(GSPLAT_FOG) 15543 color = decodeGamma(color); 15544 #endif 15545 #ifdef GSPLAT_FOG 15546 color = addFog(color, depth); 15547 #endif 15548 #if TONEMAP != NONE 15549 color = toneMap(color); 15550 #endif 15551 #if TONEMAP != NONE || (GAMMA != NONE && defined(GSPLAT_FOG)) 15552 color = gammaCorrectOutput(color); 15553 #endif 15554 return color; 15555} 15556`,vG=` 15557#ifndef DITHER_NONE 15558 #include "bayerPS" 15559 #include "opacityDitherPS" 15560 varying float id; 15561#endif 15562#if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS) 15563 uniform float alphaClip; 15564#endif 15565#ifdef PREPASS_PASS 15566 varying float vLinearDepth; 15567 #include "floatAsUintPS" 15568#endif 15569#if !defined(SHADOW_PASS) && !defined(PICK_PASS) && !defined(PREPASS_PASS) 15570 uniform float alphaClipForward; 15571#endif 15572varying mediump vec2 gaussianUV; 15573varying mediump vec4 gaussianColor; 15574#if defined(GSPLAT_UNIFIED_ID) && defined(PICK_PASS) 15575 flat varying uint vPickId; 15576#endif 15577#ifdef PICK_PASS 15578 #include "pickPS" 15579#endif 15580const float EXP4 = exp(-4.0); 15581const float INV_EXP4 = 1.0 / (1.0 - EXP4); 15582float normExp(float x) { 15583 return (exp(x * -4.0) - EXP4) * INV_EXP4; 15584} 15585void main(void) { 15586 mediump float A = dot(gaussianUV, gaussianUV); 15587 if (A > 1.0) { 15588 discard; 15589 } 15590 mediump float alpha = normExp(A) * gaussianColor.a; 15591 #if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS) 15592 if (alpha < alphaClip) { 15593 discard; 15594 } 15595 #endif 15596 #ifdef PICK_PASS 15597 #ifdef GSPLAT_UNIFIED_ID 15598 pcFragColor0 = encodePickOutput(vPickId); 15599 #else 15600 pcFragColor0 = getPickOutput(); 15601 #endif 15602 #ifdef DEPTH_PICK_PASS 15603 pcFragColor1 = getPickDepth(); 15604 #endif 15605 #elif SHADOW_PASS 15606 gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); 15607 #elif PREPASS_PASS 15608 gl_FragColor = float2vec4(vLinearDepth); 15609 #else 15610 if (alpha < alphaClipForward) { 15611 discard; 15612 } 15613 #ifndef DITHER_NONE 15614 opacityDither(alpha, id * 0.013); 15615 #endif 15616 gl_FragColor = vec4(gaussianColor.xyz * alpha, alpha); 15617 #endif 15618} 15619`,SG=` 15620attribute vec3 vertex_position; 15621uniform uint numSplats; 15622uniform highp usampler2D splatOrder; 15623bool initSource(out SplatSource source) { 15624 source.order = uint(gl_InstanceID) * {GSPLAT_INSTANCE_SIZE}u + uint(vertex_position.z); 15625 if (source.order >= numSplats) { 15626 return false; 15627 } 15628 ivec2 orderUV = ivec2(source.order % splatTextureSize, source.order / splatTextureSize); 15629 uint splatId = texelFetch(splatOrder, orderUV, 0).r; 15630 setSplat(splatId); 15631 source.cornerUV = vertex_position.xy; 15632 return true; 15633} 15634`,yG=` 15635#include "gsplatCommonVS" 15636varying mediump vec2 gaussianUV; 15637varying mediump vec4 gaussianColor; 15638#ifndef DITHER_NONE 15639 varying float id; 15640#endif 15641mediump vec4 discardVec = vec4(0.0, 0.0, 2.0, 1.0); 15642#ifdef PREPASS_PASS 15643 varying float vLinearDepth; 15644#endif 15645#if defined(GSPLAT_UNIFIED_ID) && defined(PICK_PASS) 15646 flat varying uint vPickId; 15647#endif 15648#ifdef GSPLAT_OVERDRAW 15649 uniform sampler2D colorRamp; 15650 uniform float colorRampIntensity; 15651#endif 15652void main(void) { 15653 SplatSource source; 15654 if (!initSource(source)) { 15655 gl_Position = discardVec; 15656 return; 15657 } 15658 vec3 modelCenter = getCenter(); 15659 SplatCenter center; 15660 center.modelCenterOriginal = modelCenter; 15661 15662 modifySplatCenter(modelCenter); 15663 center.modelCenterModified = modelCenter; 15664 if (!initCenter(modelCenter, center)) { 15665 gl_Position = discardVec; 15666 return; 15667 }
15668 SplatCorner corner; 15669 if (!initCorner(source, center, corner)) { 15670 gl_Position = discardVec; 15671 return; 15672 } 15673 #ifdef GSPLAT_SEPARATE_OPACITY 15674 float opacity = getOpacity(); 15675 vec4 clr = vec4(getColor(), opacity); 15676 #else 15677 vec4 clr = getColor(); 15678 #endif 15679 #if GSPLAT_AA 15680 clr.a *= corner.aaFactor; 15681 #endif 15682 #if SH_BANDS > 0 15683 vec3 dir = normalize(center.view * mat3(center.modelView)); 15684 vec3 sh[SH_COEFFS]; 15685 float scale; 15686 readSHData(sh, scale); 15687 clr.xyz += evalSH(sh, dir) * scale; 15688 #endif 15689 modifySplatColor(modelCenter, clr); 15690 #if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS) 15691 float alphaClipValue = alphaClip; 15692 #else 15693 float alphaClipValue = alphaClipForward; 15694 #endif 15695 if (clr.w <= alphaClipValue) { 15696 gl_Position = discardVec; 15697 return; 15698 } 15699 clipCorner(corner, clr.w); 15700 #if GSPLAT_2DGS 15701 vec3 modelCorner = center.modelCenterModified + corner.offset; 15702 gl_Position = matrix_projection * center.modelView * vec4(modelCorner, 1.0); 15703 #else 15704 gl_Position = center.proj + vec4(corner.offset.xyz, 0); 15705 #endif 15706 gaussianUV = corner.uv; 15707 #ifdef GSPLAT_OVERDRAW 15708 float t = clamp(modelCenter.y / 20.0, 0.0, 1.0); 15709 vec3 rampColor = textureLod(colorRamp, vec2(t, 0.5), 0.0).rgb; 15710 clr.a *= (1.0 / 32.0) * colorRampIntensity; 15711 gaussianColor = vec4(rampColor, clr.a); 15712 #else 15713 gaussianColor = vec4(prepareOutputFromGamma(max(clr.xyz, 0.0), -center.view.z), clr.w); 15714 #endif 15715 #ifndef DITHER_NONE 15716 id = float(splat.index); 15717 #endif 15718 #ifdef PREPASS_PASS 15719 vLinearDepth = -center.view.z; 15720 #endif 15721 #if defined(GSPLAT_UNIFIED_ID) && defined(PICK_PASS) 15722 vPickId = loadPcId().r; 15723 #endif 15724} 15725`,xG=` 15726uint pack8888(vec4 v) { 15727 uvec4 t = uvec4(v * 255.0) << uvec4(24u, 16u, 8u, 0u); 15728 return t.x | t.y | t.z | t.w; 15729} 15730uint pack101010(vec3 v) { 15731 uvec3 t = uvec3(v * 1023.0) << uvec3(20u, 10u, 0u); 15732 return t.x | t.y | t.z; 15733} 15734uint pack111110(vec3 v) { 15735 uvec3 t = uvec3(v * vec3(2047.0, 2047.0, 1023.0)) << uvec3(21u, 10u, 0u); 15736 return t.x | t.y | t.z; 15737} 15738vec4 unpack8888(uint v) { 15739 return vec4((uvec4(v) >> uvec4(24u, 16u, 8u, 0u)) & 0xffu) / 255.0; 15740} 15741vec3 unpack101010(uint v) { 15742 return vec3((uvec3(v) >> uvec3(20u, 10u, 0u)) & 0x3ffu) / 1023.0; 15743} 15744vec3 unpack111110(uint v) { 15745 return vec3((uvec3(v) >> uvec3(21u, 10u, 0u)) & uvec3(0x7ffu, 0x7ffu, 0x3ffu)) / vec3(2047.0, 2047.0, 1023.0); 15746} 15747vec3 resolveCodebook(vec3 s, vec4 codebook[64]) { 15748 uvec3 idx = uvec3(s * 255.0); 15749 vec3 v = vec3( 15750 codebook[idx.x >> 2u][idx.x & 3u], 15751 codebook[idx.y >> 2u][idx.y & 3u], 15752 codebook[idx.z >> 2u][idx.z & 3u] 15753 ); 15754 return (v - codebook[0].x) / (codebook[63].w - codebook[0].x); 15755} 15756`,TG=` 15757uniform uint splatTextureSize; 15758`,wG=` 15759uint tAw; 15760vec4 tBcached; 15761vec4 unpackRotation(vec3 data) { 15762 return vec4(data.xyz, sqrt(max(0.0, 1.0 - dot(data, data)))); 15763} 15764vec3 getCenter() { 15765 uvec4 tA = loadTransformA(); 15766 tAw = tA.w; 15767 tBcached = loadTransformB(); 15768 return uintBitsToFloat(tA.xyz); 15769} 15770vec4 getColor() { 15771 return loadSplatColor(); 15772} 15773vec4 getRotation() { 15774 return unpackRotation(vec3(unpackHalf2x16(tAw), tBcached.w)).wxyz; 15775} 15776vec3 getScale() { 15777 return tBcached.xyz; 15778} 15779#include "gsplatUncompressedSHVS" 15780`,CG=` 15781#if SH_BANDS > 0 15782vec3 unpack111011s(uint bits) { 15783 return vec3((uvec3(bits) >> uvec3(21u, 11u, 0u)) & uvec3(0x7ffu, 0x3ffu, 0x7ffu)) / vec3(2047.0, 1023.0, 2047.0) * 2.0 - 1.0; 15784} 15785void fetchScale(in uvec4 t, out float scale, out vec3 a, out vec3 b, out vec3 c) { 15786 scale = uintBitsToFloat(t.x); 15787 a = unpack111011s(t.y); 15788 b = unpack111011s(t.z); 15789 c = unpack111011s(t.w); 15790} 15791void fetch(in uvec4 t, out vec3 a, out vec3 b, out vec3 c, out vec3 d) { 15792 a = unpack111011s(t.x); 15793 b = unpack111011s(t.y); 15794 c = unpack111011s(t.z); 15795 d = unpack111011s(t.w); 15796} 15797void fetch(in uint t, out vec3 a) { 15798 a = unpack111011s(t); 15799} 15800#if SH_BANDS == 1 15801 void readSHData(out vec3 sh[3], out float scale) { 15802 fetchScale(loadSplatSH_1to3(), scale, sh[0], sh[1], sh[2]); 15803 } 15804#elif SH_BANDS == 2 15805 void readSHData(out vec3 sh[8], out float scale) { 15806 fetchScale(loadSplatSH_1to3(), scale, sh[0], sh[1], sh[2]); 15807 fetch(loadSplatSH_4to7(), sh[3], sh[4], sh[5], sh[6]); 15808 fetch(loadSplatSH_8to11().x, sh[7]); 15809 } 15810#else 15811 void readSHData(out vec3 sh[15], out float scale) { 15812 fetchScale(loadSplatSH_1to3(), scale, sh[0], sh[1], sh[2]); 15813 fetch(loadSplatSH_4to7(), sh[3], sh[4], sh[5], sh[6]); 15814 fetch(loadSplatSH_8to11(), sh[7], sh[8], sh[9], sh[10]); 15815 fetch(loadSplatSH_12to15(), sh[11], sh[12], sh[13], sh[14]); 15816 } 15817#endif 15818#endif 15819`,EG=` 15820#include "gsplatPackingPS" 15821uniform highp sampler2D chunkTexture; 15822vec4 chunkDataA; 15823vec4 chunkDataB; 15824vec4 chunkDataC; 15825vec4 chunkDataD; 15826vec4 chunkDataE; 15827uvec4 packedData; 15828vec3 unpack111011(uint bits) { 15829 return vec3( 15830 float(bits >> 21u) / 2047.0, 15831 float((bits >> 11u) & 0x3ffu) / 1023.0, 15832 float(bits & 0x7ffu) / 2047.0 15833 ); 15834} 15835const float norm = sqrt(2.0); 15836vec4 unpackRotation(uint bits) { 15837 float a = (float((bits >> 20u) & 0x3ffu) / 1023.0 - 0.5) * norm; 15838 float b = (float((bits >> 10u) & 0x3ffu) / 1023.0 - 0.5) * norm; 15839 float c = (float(bits & 0x3ffu) / 1023.0 - 0.5) * norm; 15840 float m = sqrt(1.0 - (a * a + b * b + c * c)); 15841 uint mode = bits >> 30u; 15842 if (mode == 0u) return vec4(m, a, b, c); 15843 if (mode == 1u) return vec4(a, m, b, c); 15844 if (mode == 2u) return vec4(a, b, m, c); 15845 return vec4(a, b, c, m); 15846} 15847vec3 getCenter() { 15848 uint w = uint(textureSize(chunkTexture, 0).x) / 5u; 15849 uint chunkId = splat.index / 256u; 15850 ivec2 chunkUV = ivec2((chunkId % w) * 5u, chunkId / w); 15851 chunkDataA = texelFetch(chunkTexture, chunkUV, 0); 15852 chunkDataB = texelFetch(chunkTexture, chunkUV + ivec2(1, 0), 0);
15853 chunkDataC = texelFetch(chunkTexture, chunkUV + ivec2(2, 0), 0); 15854 chunkDataD = texelFetch(chunkTexture, chunkUV + ivec2(3, 0), 0); 15855 chunkDataE = texelFetch(chunkTexture, chunkUV + ivec2(4, 0), 0); 15856 packedData = loadPackedTexture(); 15857 return mix(chunkDataA.xyz, vec3(chunkDataA.w, chunkDataB.xy), unpack111011(packedData.x)); 15858} 15859vec4 getColor() { 15860 vec4 r = unpack8888(packedData.w); 15861 return vec4(mix(chunkDataD.xyz, vec3(chunkDataD.w, chunkDataE.xy), r.rgb), r.w); 15862} 15863vec4 getRotation() { 15864 return unpackRotation(packedData.y); 15865} 15866vec3 getScale() { 15867 return exp(mix(vec3(chunkDataB.zw, chunkDataC.x), chunkDataC.yzw, unpack111011(packedData.z))); 15868} 15869#include "gsplatCompressedSHVS" 15870`,bG=` 15871#if SH_BANDS > 0 15872vec4 unpack8888s(in uint bits) { 15873 return vec4((uvec4(bits) >> uvec4(0u, 8u, 16u, 24u)) & 0xffu) * (8.0 / 255.0) - 4.0; 15874} 15875void readSHData(out vec3 sh[15], out float scale) { 15876 uvec4 shData0 = loadShTexture0(); 15877 uvec4 shData1 = loadShTexture1(); 15878 uvec4 shData2 = loadShTexture2(); 15879 vec4 r0 = unpack8888s(shData0.x); 15880 vec4 r1 = unpack8888s(shData0.y); 15881 vec4 r2 = unpack8888s(shData0.z); 15882 vec4 r3 = unpack8888s(shData0.w); 15883 vec4 g0 = unpack8888s(shData1.x); 15884 vec4 g1 = unpack8888s(shData1.y); 15885 vec4 g2 = unpack8888s(shData1.z); 15886 vec4 g3 = unpack8888s(shData1.w); 15887 vec4 b0 = unpack8888s(shData2.x); 15888 vec4 b1 = unpack8888s(shData2.y); 15889 vec4 b2 = unpack8888s(shData2.z); 15890 vec4 b3 = unpack8888s(shData2.w); 15891 sh[0] = vec3(r0.x, g0.x, b0.x); 15892 sh[1] = vec3(r0.y, g0.y, b0.y); 15893 sh[2] = vec3(r0.z, g0.z, b0.z); 15894 sh[3] = vec3(r0.w, g0.w, b0.w); 15895 sh[4] = vec3(r1.x, g1.x, b1.x); 15896 sh[5] = vec3(r1.y, g1.y, b1.y); 15897 sh[6] = vec3(r1.z, g1.z, b1.z); 15898 sh[7] = vec3(r1.w, g1.w, b1.w); 15899 sh[8] = vec3(r2.x, g2.x, b2.x);
15900 sh[9] = vec3(r2.y, g2.y, b2.y); 15901 sh[10] = vec3(r2.z, g2.z, b2.z); 15902 sh[11] = vec3(r2.w, g2.w, b2.w); 15903 sh[12] = vec3(r3.x, g3.x, b3.x); 15904 sh[13] = vec3(r3.y, g3.y, b3.y); 15905 sh[14] = vec3(r3.z, g3.z, b3.z); 15906 scale = 1.0; 15907} 15908#endif 15909`,AG=` 15910uniform vec3 means_mins; 15911uniform vec3 means_maxs; 15912#ifndef SOG_V2 15913 uniform vec3 scales_mins; 15914 uniform vec3 scales_maxs; 15915 uniform vec4 sh0_mins; 15916 uniform vec4 sh0_maxs; 15917#endif 15918const float SH_C0 = 0.28209479177387814; 15919const float norm = sqrt(2.0); 15920#ifdef SOG_V2 15921 float lutScales(int b) { return texelFetch(sogCodebook, ivec2(b, 0), 0).r; } 15922 float lutSh0(int b) { return texelFetch(sogCodebook, ivec2(b, 0), 0).g; } 15923 float lutShN(int b) { return texelFetch(sogCodebook, ivec2(b, 0), 0).b; } 15924#endif 15925vec3 getCenter() { 15926 vec3 l = texelFetch(means_l, splat.uv, 0).xyz; 15927 vec3 u = texelFetch(means_u, splat.uv, 0).xyz; 15928 vec3 n = (l + u * 256.0) / 257.0; 15929 vec3 v = mix(means_mins, means_maxs, n); 15930 return sign(v) * (exp(abs(v)) - 1.0); 15931} 15932vec4 getRotation() { 15933 vec4 q = texelFetch(quats, splat.uv, 0); 15934 uint qmode = uint(q.w * 255.0 + 0.5) - 252u; 15935 vec3 abc = (q.xyz - 0.5) * norm; 15936 float d = sqrt(max(0.0, 1.0 - dot(abc, abc))); 15937 return (qmode == 0u) ? vec4(d, abc) : 15938 ((qmode == 1u) ? vec4(abc.x, d, abc.yz) : 15939 ((qmode == 2u) ? vec4(abc.xy, d, abc.z) : vec4(abc, d))); 15940} 15941vec3 getScale() { 15942 vec3 s = texelFetch(scales, splat.uv, 0).xyz; 15943 #ifdef SOG_V2 15944 ivec3 i = ivec3(s * 255.0 + 0.5); 15945 vec3 logS = vec3(lutScales(i.x), lutScales(i.y), lutScales(i.z)); 15946 #else 15947 vec3 logS = mix(scales_mins, scales_maxs, s); 15948 #endif 15949 return exp(logS); 15950} 15951vec4 getColor() { 15952 vec4 c = texelFetch(sh0, splat.uv, 0); 15953 #ifdef SOG_V2 15954 ivec3 i = ivec3(c.xyz * 255.0 + 0.5); 15955 vec3 rgb = vec3(lutSh0(i.x), lutSh0(i.y), lutSh0(i.z)); 15956 float alpha = c.w; 15957 #else 15958 vec3 rgb = mix(sh0_mins.xyz, sh0_maxs.xyz, c.xyz); 15959 float logitAlpha = mix(sh0_mins.w, sh0_maxs.w, c.w); 15960 float alpha = 1.0 / (1.0 + exp(-logitAlpha)); 15961 #endif 15962 return vec4(vec3(0.5) + rgb * SH_C0, alpha); 15963} 15964#include "gsplatSogSHVS" 15965`,PG=` 15966#if SH_BANDS > 0 15967 #ifndef SOG_V2 15968 uniform float shN_mins; 15969 uniform float shN_maxs; 15970 #endif 15971 void readSHData(out vec3 sh[SH_COEFFS], out float scale) { 15972 vec4 labels = texelFetch(sh_labels, splat.uv, 0); 15973 int n = int(labels.x * 255.0 + 0.5) + int(labels.y * 255.0 + 0.5) * 256; 15974 int u = (n % 64) * SH_COEFFS; 15975 int v = n / 64; 15976 for (int i = 0; i < SH_COEFFS; i++) { 15977 vec4 t = texelFetch(sh_centroids, ivec2(u + i, v), 0); 15978 #ifdef SOG_V2 15979 ivec3 idx = ivec3(t.xyz * 255.0 + 0.5); 15980 sh[i] = vec3(lutShN(idx.x), lutShN(idx.y), lutShN(idx.z)); 15981 #else 15982 sh[i] = mix(vec3(shN_mins), vec3(shN_maxs), t.xyz); 15983 #endif 15984 } 15985 scale = 1.0; 15986 } 15987#endif 15988`,IG=` 15989#include "gsplatContainerDeclarationsVS" 15990vec3 splatCenter; 15991vec4 splatColor; 15992vec3 splatScale; 15993vec4 splatRotation; 15994`,DG=` 15995vec3 getCenter() { 15996 #include "gsplatContainerUserReadVS" 15997 return splatCenter; 15998} 15999vec4 getRotation() { 16000 return splatRotation; 16001} 16002vec3 getScale() { 16003 return splatScale; 16004} 16005vec4 getColor() { 16006 return splatColor; 16007} 16008`;const MG={gsplatCenterVS:lG,gsplatCornerVS:_G,gsplatCommonVS:cG,gsplatSplatVS:hG,gsplatEvalSHVS:dG,gsplatHelpersVS:uG,gsplatModifyVS:fG,gsplatQuatToMat3VS:pG,gsplatStructsVS:mG,gsplatOutputVS:gG,gsplatPS:vG,gsplatSourceVS:SG,gsplatVS:yG,gsplatPackingPS:xG,gsplatFormatVS:TG,gsplatUncompressedVS:wG,gsplatUncompressedSHVS:CG,gsplatCompressedVS:EG,gsplatCompressedSHVS:bG,gsplatSogVS:AG,gsplatSogSHVS:PG,gsplatContainerDeclVS:IG,gsplatContainerReadVS:DG,gsplatContainerFloatReadVS:ew};var RG=` 16009uniform matrix_model: mat4x4f; 16010uniform matrix_view: mat4x4f; 16011#ifndef GSPLAT_CENTER_NOPROJ 16012 uniform camera_params: vec4f; 16013 uniform matrix_projection: mat4x4f; 16014 #ifdef GSPLAT_FISHEYE 16015 uniform fisheye_k: f32; 16016 uniform fisheye_inv_k: f32; 16017 uniform fisheye_projMat00: f32; 16018 uniform fisheye_projMat11: f32; 16019 #endif 16020#endif 16021fn initCenter(modelCenter: vec3f, center: ptr<function, SplatCenter>) -> bool { 16022 let modelView: mat4x4f = uniform.matrix_view * uniform.matrix_model; 16023 let centerView: vec4f = modelView * vec4f(modelCenter, 1.0); 16024 #ifndef GSPLAT_CENTER_NOPROJ 16025 #ifdef GSPLAT_FISHEYE 16026 let v: vec3f = centerView.xyz; 16027 let r_xy: f32 = length(v.xy); 16028 let neg_z: f32 = -v.z; 16029 let theta: f32 = atan2(r_xy, neg_z); 16030 let maxTheta: f32 = min(uniform.fisheye_k * 1.5707963, 3.13); 16031 if (theta > maxTheta - 0.01 || dot(v, v) < 0.0001) { 16032 return false;
16033 } 16034 let tk: f32 = theta * uniform.fisheye_inv_k; 16035 let sin_tk: f32 = sin(tk); 16036 let cos_tk: f32 = cos(tk); 16037 let g_theta: f32 = uniform.fisheye_k * sin_tk / cos_tk; 16038 let fisheye_s: f32 = select(select(0.0, 1.0 / neg_z, neg_z > 0.0), g_theta / r_xy, r_xy > 1e-4); 16039 let ndc: vec2f = vec2f(uniform.fisheye_projMat00 * fisheye_s * v.x, uniform.fisheye_projMat11 * fisheye_s * v.y); 16040 let near: f32 = uniform.camera_params.z; 16041 let far: f32 = uniform.camera_params.y; 16042 let linearDepth: f32 = neg_z; 16043 let depthNdc: f32 = clamp((linearDepth - near) / (far - near), 0.0, 1.0); 16044 center.proj = vec4f(ndc, depthNdc, 1.0); 16045 center.projMat00 = uniform.fisheye_projMat00; 16046 center.fisheyeSinTK = sin_tk; 16047 center.fisheyeCosTK = cos_tk; 16048 center.fisheyeRxy = r_xy; 16049 #else 16050 if (uniform.camera_params.w != 1.0 && centerView.z > 0.0) { 16051 return false; 16052 } 16053 var centerProj: vec4f = uniform.matrix_projection * centerView; 16054 centerProj.z = clamp(centerProj.z, 0.0, abs(centerProj.w)); 16055 center.proj = centerProj; 16056 center.projMat00 = uniform.matrix_projection[0][0]; 16057 #endif 16058 #endif 16059 center.view = centerView.xyz / centerView.w; 16060 center.modelView = modelView; 16061 return true; 16062} 16063`,LG=` 16064#include "gsplatHelpersVS" 16065#include "gsplatFormatVS" 16066#include "gsplatStructsVS" 16067#include "gsplatDeclarationsVS" 16068#include "gsplatModifyVS" 16069#include "gsplatEvalSHVS" 16070#include "gsplatQuatToMat3VS" 16071#include "gsplatReadVS" 16072#include "gsplatSourceVS" 16073#include "gsplatCenterVS" 16074#include "gsplatCornerVS" 16075#include "gsplatOutputVS" 16076#if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS) 16077uniform alphaClip: f32; 16078#else 16079uniform alphaClipForward: f32; 16080#endif 16081fn clipCorner(corner: ptr<function, SplatCorner>, alpha: half) { 16082 #if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS) 16083 let alphaClipValue = half(uniform.alphaClip); 16084 #else 16085 let alphaClipValue = half(uniform.alphaClipForward); 16086 #endif 16087 let clip = min(half(1.0), sqrt(max(half(0.0), log(alpha / alphaClipValue))) * half(0.5)); 16088 corner.offset = corner.offset * f32(clip); 16089 corner.uv = corner.uv * clip; 16090} 16091`,FG=` 16092struct Splat { 16093 index: u32, 16094 uv: vec2i 16095} 16096var<private> splat: Splat; 16097fn setSplat(idx: u32) { 16098 splat.index = idx; 16099 splat.uv = vec2i(i32(idx % uniform.splatTextureSize), i32(idx / uniform.splatTextureSize)); 16100} 16101`,OG=` 16102 #if SH_BANDS == 1 16103 const SH_COEFFS: i32 = 3; 16104 #elif SH_BANDS == 2 16105 const SH_COEFFS: i32 = 8; 16106 #elif SH_BANDS == 3 16107 const SH_COEFFS: i32 = 15; 16108 #else 16109 const SH_COEFFS: i32 = 0; 16110 #endif 16111 #if SH_BANDS > 0 16112 const SH_C1: half = half(0.4886025119029199); 16113 #if SH_BANDS > 1 16114 const SH_C2_0: half = half(1.0925484305920792); 16115 const SH_C2_1: half = half(-1.0925484305920792); 16116 const SH_C2_2: half = half(0.31539156525252005); 16117 const SH_C2_3: half = half(-1.0925484305920792); 16118 const SH_C2_4: half = half(0.5462742152960396); 16119 #endif 16120 #if SH_BANDS > 2 16121 const SH_C3_0: half = half(-0.5900435899266435); 16122 const SH_C3_1: half = half(2.890611442640554); 16123 const SH_C3_2: half = half(-0.4570457994644658); 16124 const SH_C3_3: half = half(0.3731763325901154); 16125 const SH_C3_4: half = half(-0.4570457994644658); 16126 const SH_C3_5: half = half(1.445305721320277); 16127 const SH_C3_6: half = half(-0.5900435899266435); 16128 #endif 16129 fn evalSH(sh: ptr<function, array<half3, SH_COEFFS>>, dir: vec3f) -> half3 { 16130 let d: half3 = half3(dir); 16131 var result: half3 = SH_C1 * (-sh[0] * d.y + sh[1] * d.z - sh[2] * d.x); 16132 #if SH_BANDS > 1 16133 let xx: half = d.x * d.x; 16134 let yy: half = d.y * d.y; 16135 let zz: half = d.z * d.z; 16136 let xy: half = d.x * d.y; 16137 let yz: half = d.y * d.z; 16138 let xz: half = d.x * d.z; 16139 result = result + ( 16140 sh[3] * (SH_C2_0 * xy) + 16141 sh[4] * (SH_C2_1 * yz) + 16142 sh[5] * (SH_C2_2 * (half(2.0) * zz - xx - yy)) + 16143 sh[6] * (SH_C2_3 * xz) + 16144 sh[7] * (SH_C2_4 * (xx - yy)) 16145 ); 16146 #endif 16147 #if SH_BANDS > 2 16148 result = result + ( 16149 sh[8] * (SH_C3_0 * d.y * (half(3.0) * xx - yy)) + 16150 sh[9] * (SH_C3_1 * xy * d.z) + 16151 sh[10] * (SH_C3_2 * d.y * (half(4.0) * zz - xx - yy)) + 16152 sh[11] * (SH_C3_3 * d.z * (half(2.0) * zz - half(3.0) * xx - half(3.0) * yy)) + 16153 sh[12] * (SH_C3_4 * d.x * (half(4.0) * zz - xx - yy)) + 16154 sh[13] * (SH_C3_5 * d.z * (xx - yy)) + 16155 sh[14] * (SH_C3_6 * d.x * (xx - half(3.0) * yy)) 16156 ); 16157 #endif 16158 return result; 16159 } 16160 #endif 16161`,BG=` 16162fn gsplatMakeSpherical(scale: ptr<function, vec3f>, size: f32) { 16163 *scale = vec3f(size); 16164}
16165fn gsplatGetSizeFromScale(scale: vec3f) -> f32 { 16166 return sqrt((scale.x * scale.x + scale.y * scale.y + scale.z * scale.z) / 3.0); 16167} 16168`,NG=` 16169fn modifySplatCenter(center: ptr<function, vec3f>) { 16170} 16171fn modifySplatRotationScale(originalCenter: vec3f, modifiedCenter: vec3f, rotation: ptr<function, vec4f>, scale: ptr<function, vec3f>) { 16172} 16173fn modifySplatColor(center: vec3f, color: ptr<function, vec4f>) { 16174} 16175`,kG=` 16176fn quatToMat3(r: half4) -> half3x3 { 16177 let r2: half4 = r + r; 16178 let x: half = r2.x * r.w; 16179 let y: half4 = r2.y * r; 16180 let z: half4 = r2.z * r; 16181 let w: half = r2.w * r.w; 16182 return half3x3( 16183 half(1.0) - z.z - w, y.z + x, y.w - z.x, 16184 y.z - x, half(1.0) - y.y - w, z.w + y.x, 16185 y.w + z.x, z.w - y.x, half(1.0) - y.y - z.z 16186 ); 16187} 16188fn quatMul(a: half4, b: half4) -> half4 { 16189 return half4( 16190 a.w * b.x + a.x * b.w + a.y * b.z - a.z * b.y, 16191 a.w * b.y - a.x * b.z + a.y * b.w + a.z * b.x, 16192 a.w * b.z + a.x * b.y - a.y * b.x + a.z * b.w, 16193 a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z 16194 ); 16195} 16196`,UG=` 16197#include "gsplatSplatVS" 16198struct SplatSource { 16199 order: u32, 16200 cornerUV: half2 16201} 16202struct SplatCenter { 16203 view: vec3f, 16204 proj: vec4f, 16205 modelView: mat4x4f, 16206 projMat00: f32, 16207 modelCenterOriginal: vec3f, 16208 modelCenterModified: vec3f, 16209 #ifdef GSPLAT_FISHEYE 16210 fisheyeSinTK: f32, 16211 fisheyeCosTK: f32, 16212 fisheyeRxy: f32, 16213 #endif 16214} 16215struct SplatCorner { 16216 offset: vec3f, 16217 uv: half2, 16218 #if GSPLAT_AA 16219 aaFactor: half, 16220 #endif 16221} 16222`,zG=` 16223uniform viewport_size: vec4f; 16224uniform minPixelSize: f32; 16225fn computeCovariance(rotation: half4, scale: half3, covA_ptr: ptr<function, vec3f>, covB_ptr: ptr<function, vec3f>) { 16226 let rot: half3x3 = quatToMat3(rotation); 16227 let s: vec3f = vec3f(scale); 16228 let M: mat3x3f = transpose(mat3x3f( 16229 s.x * vec3f(rot[0]), 16230 s.y * vec3f(rot[1]), 16231 s.z * vec3f(rot[2]) 16232 )); 16233 *covA_ptr = vec3f(dot(M[0], M[0]), dot(M[0], M[1]), dot(M[0], M[2])); 16234 *covB_ptr = vec3f(dot(M[1], M[1]), dot(M[1], M[2]), dot(M[2], M[2])); 16235} 16236fn initCornerCov(source: ptr<function, SplatSource>, center: ptr<function, SplatCenter>, corner: ptr<function, SplatCorner>, covA: vec3f, covB: vec3f) -> bool { 16237 let Vrk = mat3x3f( 16238 vec3f(covA.x, covA.y, covA.z), 16239 vec3f(covA.y, covB.x, covB.y), 16240 vec3f(covA.z, covB.y, covB.z) 16241 ); 16242 let focal = uniform.viewport_size.x * center.projMat00; 16243 let v = center.view.xyz; 16244 #ifdef GSPLAT_FISHEYE 16245 let r_sq = max(center.fisheyeRxy * center.fisheyeRxy, 1e-8); 16246 let d2 = dot(v, v); 16247 let neg_z = -v.z; 16248 let g_prime = 1.0 / (center.fisheyeCosTK * center.fisheyeCosTK); 16249 let g_theta = uniform.fisheye_k * center.fisheyeSinTK / center.fisheyeCosTK; 16250 let sv = select(select(0.0, 1.0 / neg_z, neg_z > 0.0), g_theta / center.fisheyeRxy, center.fisheyeRxy > 1e-4); 16251 let K = select(0.0, (g_prime * neg_z / d2 - sv) / r_sq, center.fisheyeRxy > 1e-4); 16252 let J = mat3x3f( 16253 vec3f(focal * (sv + K * v.x * v.x), focal * K * v.x * v.y, focal * g_prime * v.x / d2), 16254 vec3f(focal * K * v.x * v.y, focal * (sv + K * v.y * v.y), focal * g_prime * v.y / d2), 16255 vec3f(0.0, 0.0, 0.0) 16256 ); 16257 #else 16258 let vp = select(center.view.xyz, vec3f(0.0, 0.0, 1.0), uniform.camera_params.w == 1.0); 16259 let J1 = focal / vp.z; 16260 let J2 = -J1 / vp.z * vp.xy; 16261 let J = mat3x3f( 16262 vec3f(J1, 0.0, J2.x), 16263 vec3f(0.0, J1, J2.y), 16264 vec3f(0.0, 0.0, 0.0) 16265 ); 16266 #endif 16267 let W = transpose(mat3x3f(center.modelView[0].xyz, center.modelView[1].xyz, center.modelView[2].xyz)); 16268 let T = W * J; 16269 let cov = transpose(T) * Vrk * T; 16270 #if GSPLAT_AA 16271 let detOrig = cov[0][0] * cov[1][1] - cov[0][1] * cov[1][0]; 16272 let detBlur = (cov[0][0] + 0.3) * (cov[1][1] + 0.3) - cov[0][1] * cov[1][0]; 16273 corner.aaFactor = half(sqrt(max(detOrig / detBlur, 0.0))); 16274 #endif 16275 let diagonal1 = cov[0][0] + 0.3; 16276 let offDiagonal = cov[0][1]; 16277 let diagonal2 = cov[1][1] + 0.3; 16278 let mid = 0.5 * (diagonal1 + diagonal2); 16279 let radius = length(vec2f((diagonal1 - diagonal2) / 2.0, offDiagonal)); 16280 let lambda1 = mid + radius; 16281 let lambda2 = max(mid - radius, 0.1); 16282 let vmin = min(1024.0, min(uniform.viewport_size.x, uniform.viewport_size.y)); 16283 let l1 = 2.0 * min(sqrt(2.0 * lambda1), vmin); 16284 let l2 = 2.0 * min(sqrt(2.0 * lambda2), vmin); 16285 if (max(l1, l2) < uniform.minPixelSize) { 16286 return false;
16287 } 16288 let c = center.proj.ww * uniform.viewport_size.zw; 16289 if (any((abs(center.proj.xy) - vec2f(max(l1, l2)) * c) > center.proj.ww)) { 16290 return false; 16291 } 16292 let diagonalVector = normalize(vec2f(offDiagonal, lambda1 - diagonal1)); 16293 let v1 = l1 * diagonalVector; 16294 let v2 = l2 * vec2f(diagonalVector.y, -diagonalVector.x); 16295 corner.offset = vec3f((f32(source.cornerUV.x) * v1 + f32(source.cornerUV.y) * v2) * c, 0.0); 16296 corner.uv = source.cornerUV; 16297 return true; 16298} 16299#if GSPLAT_2DGS 16300fn initCorner2DGS(source: ptr<function, SplatSource>, rotation: vec4f, scale: vec3f, corner: ptr<function, SplatCorner>) { 16301 let localPos: vec2f = vec2f(source.cornerUV) * vec2f(scale.x, scale.y) * 3.0; 16302 let v: vec3f = vec3f(localPos, 0.0); 16303 let t: vec3f = 2.0 * cross(rotation.xyz, v); 16304 corner.offset = v + rotation.w * t + cross(rotation.xyz, t); 16305 corner.uv = source.cornerUV; 16306} 16307#endif 16308fn initCorner(source: ptr<function, SplatSource>, center: ptr<function, SplatCenter>, corner: ptr<function, SplatCorner>) -> bool { 16309 var rotation: vec4f = getRotation().yzwx; 16310 var scale: vec3f = getScale(); 16311 modifySplatRotationScale(center.modelCenterOriginal, center.modelCenterModified, &rotation, &scale); 16312 #if GSPLAT_2DGS 16313 initCorner2DGS(source, rotation, scale, corner); 16314 return true; 16315 #else 16316 var covA: vec3f; 16317 var covB: vec3f; 16318 computeCovariance(half4(rotation.wxyz), half3(scale), &covA, &covB); 16319 return initCornerCov(source, center, corner, covA, covB); 16320 #endif 16321} 16322`,VG=` 16323varying vUv0: vec2f; 16324var<storage, read> rasterizeTileList: array<u32>; 16325uniform numTilesX: u32; 16326uniform screenWidth: f32; 16327uniform screenHeight: f32; 16328@vertex 16329fn vertexMain(input: VertexInput) -> VertexOutput { 16330 var output: VertexOutput; 16331 let quadIdx = pcVertexIndex / 6u; 16332 let cornerIdx = pcVertexIndex % 6u; 16333 let tileIdx = rasterizeTileList[quadIdx]; 16334 let tileX = tileIdx % uniform.numTilesX; 16335 let tileY = tileIdx / uniform.numTilesX; 16336 let corners = array<vec2f, 6>( 16337 vec2f(0.0, 0.0), vec2f(1.0, 0.0), vec2f(1.0, 1.0), 16338 vec2f(0.0, 0.0), vec2f(1.0, 1.0), vec2f(0.0, 1.0) 16339 ); 16340 let corner = corners[cornerIdx]; 16341 let x0 = f32(tileX * 16u); 16342 let y0 = f32(tileY * 16u); 16343 let pixelX = x0 + corner.x * 16.0; 16344 let pixelY = y0 + corner.y * 16.0; 16345 output.position = vec4f( 16346 pixelX / uniform.screenWidth * 2.0 - 1.0, 16347 pixelY / uniform.screenHeight * 2.0 - 1.0, 16348 0.5, 1.0 16349 ); 16350 output.vUv0 = vec2f(pixelX / uniform.screenWidth, 16351 pixelY / uniform.screenHeight); 16352 return output; 16353} 16354`,GG=` 16355#ifndef DITHER_NONE 16356 #include "bayerPS" 16357 #include "opacityDitherPS" 16358 varying id: f32; 16359#endif 16360#if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS) 16361 uniform alphaClip: f32; 16362#endif 16363#ifdef PREPASS_PASS 16364 varying vLinearDepth: f32; 16365 #include "floatAsUintPS" 16366#endif 16367#if !defined(SHADOW_PASS) && !defined(PICK_PASS) && !defined(PREPASS_PASS) 16368 uniform alphaClipForward: f32; 16369#endif 16370const EXP4: half = exp(half(-4.0)); 16371const INV_EXP4: half = half(1.0) / (half(1.0) - EXP4); 16372fn normExp(x: half) -> half { 16373 return (exp(x * half(-4.0)) - EXP4) * INV_EXP4; 16374} 16375varying gaussianUV: half2; 16376varying gaussianColor: half4; 16377#if defined(GSPLAT_UNIFIED_ID) && defined(PICK_PASS) 16378 varying @interpolate(flat) vPickId: u32; 16379#endif 16380#ifdef PICK_PASS 16381 #include "pickPS" 16382#endif 16383@fragment 16384fn fragmentMain(input: FragmentInput) -> FragmentOutput { 16385 var output: FragmentOutput; 16386 let A: half = dot(gaussianUV, gaussianUV); 16387 if (A > half(1.0)) { 16388 discard; 16389 return output; 16390 } 16391 var alpha: half = normExp(A) * gaussianColor.a; 16392 #if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS) 16393 if (alpha < half(uniform.alphaClip)) { 16394 discard; 16395 return output; 16396 } 16397 #endif 16398 #ifdef PICK_PASS 16399 #ifdef GSPLAT_UNIFIED_ID 16400 output.color = encodePickOutput(vPickId); 16401 #else 16402 output.color = getPickOutput(); 16403 #endif 16404 #ifdef DEPTH_PICK_PASS 16405 output.color1 = getPickDepth(); 16406 #endif 16407 #elif SHADOW_PASS 16408 output.color = vec4f(0.0, 0.0, 0.0, 1.0); 16409 #elif PREPASS_PASS 16410 output.color = float2vec4(vLinearDepth); 16411 #else 16412 if (alpha < half(uniform.alphaClipForward)) { 16413 discard; 16414 return output; 16415 } 16416 #ifndef DITHER_NONE 16417 opacityDither(f32(alpha), id * 0.013); 16418 #endif 16419 output.color = vec4f(vec3f(gaussianColor.xyz * alpha), f32(alpha)); 16420 #endif 16421 return output; 16422}`,HG=` 16423#ifdef PICK_MODE 16424 #include "pickPS" 16425 #include "floatAsUintPS" 16426 var pickIdTexture: texture_2d<u32>; 16427 var pickDepthTexture: texture_2d<f32>; 16428#else 16429 #include "tonemappingPS" 16430 #include "gammaPS" 16431 var source: texture_2d<f32>; 16432#endif 16433varying vUv0: vec2f; 16434@fragment fn fragmentMain(input: FragmentInput) -> FragmentOutput { 16435 var output: FragmentOutput; 16436 #ifdef PICK_MODE 16437 let texSize = vec2f(textureDimensions(pickIdTexture)); 16438 let coord = vec2u(input.vUv0 * texSize); 16439 let pickId = textureLoad(pickIdTexture, coord, 0).r; 16440 if (pickId == 0xFFFFFFFFu) { 16441 discard; 16442 return output; 16443 } 16444 output.color = encodePickOutput(pickId); 16445 let depthData = textureLoad(pickDepthTexture, coord, 0); 16446 let normalizedDepth = select(depthData.r / depthData.g, 1.0, depthData.g < 1e-6); 16447 output.color1 = float2uint(normalizedDepth); 16448 #else 16449 let texSize = vec2f(textureDimensions(source)); 16450 let coord = vec2u(input.vUv0 * texSize); 16451 let linear = textureLoad(source, coord, 0); 16452 output.color = vec4f(gammaCorrectOutput(toneMap(linear.rgb)), linear.a); 16453 #endif 16454 return output; 16455} 16456`,WG=` 16457attribute vertex_position: vec3f; 16458#ifdef GSPLAT_INDIRECT_DRAW 16459 var<storage, read> numSplatsStorage: array<u32>; 16460 var<storage, read>
16460 compactedSplatIds: array<u32>; 16461#else 16462 uniform numSplats: u32; 16463 var<storage, read> splatOrder: array<u32>; 16464#endif 16465fn initSource(source: ptr<function, SplatSource>) -> bool { 16466 source.order = pcInstanceIndex * {GSPLAT_INSTANCE_SIZE}u + u32(vertex_position.z); 16467 #ifdef GSPLAT_INDIRECT_DRAW 16468 let numSplats = numSplatsStorage[0]; 16469 #else 16470 let numSplats = uniform.numSplats; 16471 #endif 16472 if (source.order >= numSplats) { 16473 return false; 16474 } 16475 var splatId: u32; 16476 #ifdef GSPLAT_INDIRECT_DRAW 16477 splatId = compactedSplatIds[source.order]; 16478 #else 16479 splatId = splatOrder[source.order]; 16480 #endif 16481 setSplat(splatId); 16482 source.cornerUV = half2(vertex_position.xy); 16483 return true; 16484} 16485`,XG=` 16486#include "gsplatCommonVS" 16487varying gaussianUV: half2; 16488varying gaussianColor: half4; 16489#ifndef DITHER_NONE 16490 varying id: f32; 16491#endif 16492const discardVec: vec4f = vec4f(0.0, 0.0, 2.0, 1.0); 16493#ifdef PREPASS_PASS 16494 varying vLinearDepth: f32; 16495#endif 16496#if defined(GSPLAT_UNIFIED_ID) && defined(PICK_PASS) 16497 varying @interpolate(flat) vPickId: u32; 16498#endif 16499#ifdef GSPLAT_OVERDRAW 16500 uniform colorRampIntensity: f32; 16501 var colorRamp: texture_2d<f32>; 16502 var colorRampSampler: sampler; 16503#endif 16504@vertex 16505fn vertexMain(input: VertexInput) -> VertexOutput { 16506 var output: VertexOutput; 16507 var source: SplatSource; 16508 if (!initSource(&source)) { 16509 output.position = discardVec; 16510 return output; 16511 } 16512 var modelCenter: vec3f = getCenter(); 16513 var center: SplatCenter; 16514 center.modelCenterOriginal = modelCenter; 16515 16516 modifySplatCenter(&modelCenter); 16517 center.modelCenterModified = modelCenter; 16518 if (!initCenter(modelCenter, ¢er)) { 16519 output.position = discardVec; 16520 return output; 16521 } 16522 var corner: SplatCorner; 16523 if (!initCorner(&source, ¢er, &corner)) { 16524 output.position = discardVec; 16525 return output; 16526 } 16527 #ifdef GSPLAT_SEPARATE_OPACITY 16528 let opacity = getOpacity(); 16529 var clr: half4 = half4(vec4f(getColor(), opacity)); 16530 #else 16531 var clr: half4 = half4(getColor()); 16532 #endif 16533 #if GSPLAT_AA 16534 clr.a = clr.a * corner.aaFactor; 16535 #endif 16536 #if SH_BANDS > 0 16537 let modelView3x3 = mat3x3f(center.modelView[0].xyz, center.modelView[1].xyz, center.modelView[2].xyz); 16538 let dir = normalize(center.view * modelView3x3); 16539 var sh: array<half3, SH_COEFFS>; 16540 var scale: f32; 16541 readSHData(&sh, &scale); 16542 clr = half4(clr.xyz + evalSH(&sh, dir) * half(scale), clr.a); 16543 #endif 16544 var clrF32 = vec4f(clr); 16545 modifySplatColor(modelCenter, &clrF32); 16546 clr = half4(clrF32); 16547 #if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS) 16548 let alphaClipValue = half(uniform.alphaClip); 16549 #else 16550 let alphaClipValue = half(uniform.alphaClipForward); 16551 #endif 16552 if (clr.w <= alphaClipValue) { 16553 output.position = discardVec; 16554 return output; 16555 } 16556 clipCorner(&corner, clr.w); 16557 #if GSPLAT_2DGS 16558 let modelCorner: vec3f = center.modelCenterModified + corner.offset; 16559 output.position = uniform.matrix_projection * center.modelView * vec4f(modelCorner, 1.0); 16560 #else 16561 output.position = center.proj + vec4f(corner.offset.xyz, 0.0); 16562 #endif 16563 output.gaussianUV = corner.uv; 16564 #ifdef GSPLAT_OVERDRAW 16565 let t: f32 = clamp(center.modelCenterOriginal.y / 20.0, 0.0, 1.0); 16566 let rampColor: vec3f = textureSampleLevel(colorRamp, colorRampSampler, vec2f(t, 0.5), 0.0).rgb; 16567 clr.a = clr.a * half(1.0 / 32.0) * half(uniform.colorRampIntensity); 16568 output.gaussianColor = half4(half3(rampColor), clr.a); 16569 #else 16570 output.gaussianColor = half4(half3(prepareOutputFromGamma(max(vec3f(clr.xyz), vec3f(0.0)), -center.view.z)), clr.w); 16571 #endif 16572 #ifndef DITHER_NONE 16573 output.id = f32(splat.index); 16574 #endif 16575 #ifdef PREPASS_PASS 16576 output.vLinearDepth = -center.view.z; 16577 #endif 16578 #if defined(GSPLAT_UNIFIED_ID) && defined(PICK_PASS) 16579 output.vPickId = loadPcId().r; 16580 #endif 16581 return output; 16582} 16583`,YG=` 16584#include "gsplatHelpersVS" 16585#include "gsplatOutputVS" 16586attribute vertex_position: vec3f; 16587uniform viewport_size: vec4f; 16588uniform clipToViewZ: vec4f; 16589#if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS) 16590 uniform alphaClip: f32; 16591#else 16592 uniform alphaClipForward: f32; 16593#endif 16594var<storage, read> sortedIndices: array<u32>; 16595var<storage, read> projCache: array<u32>; 16596var<storage, read> numSplatsStorage: array<u32>; 16597varying gaussianUV: half2; 16598varying gaussianColor: half4; 16599#ifndef DITHER_NONE 16600 varying id: f32; 16601#endif 16602#ifdef PREPASS_PASS 16603 varying vLinearDepth: f32; 16604#endif 16605#if defined(GSPLAT_UNIFIED_ID) && defined(PICK_PASS) 16606 varying @interpolate(flat) vPickId: u32; 16607#endif 16608#ifdef GSPLAT_OVERDRAW 16609 uniform colorRampIntensity: f32; 16610 var colorRamp: texture_2d<f32>; 16611 var colorRampSampler: sampler; 16612#endif 16613const discardVec: vec4f = vec4f(0.0, 0.0, 2.0, 1.0); 16614@vertex 16615fn vertexMain(input: VertexInput) -> VertexOutput { 16616 var output: VertexOutput; 16617 let order = pcInstanceIndex * {GSPLAT_INSTANCE_SIZE}u + u32(vertex_position.z); 16618 let numSplats = numSplatsStorage[0]; 16619 if (order >= numSplats) { 16620 output.position = discardVec; 16621 return output; 16622 } 16623 let cacheIdx = sortedIndices[order]; 16624 let base = cacheIdx * {CACHE_STRIDE}u; 16625 let proj = vec4f( 16626 bitcast<f32>(projCache[base + 0u]), 16627 bitcast<f32>(projCache[base + 1u]), 16628 bitcast<f32>(projCache[base + 2u]), 16629 bitcast<f32>(projCache[base + 3u]) 16630 ); 16631 let v1 = unpack2x16float(projCache[base + 4u]); 16632 let v2 = unpack2x16float(projCache[base + 5u]); 16633 let ba = unpack2x16float(projCache[base + 7u]); 16634 let alpha = half(ba.y); 16635 #if defined(GSPLAT_UNIFIED_ID) && defined(PICK_PASS) 16636 let pickId = projCache[base + 6u]; 16637 #endif 16638 #ifdef PICK_PASS
16639 var clr: half4 = half4(half(0.0), half(0.0), half(0.0), alpha); 16640 #else 16641 let rg = unpack2x16float(projCache[base + 6u]); 16642 var clr: half4 = half4(half(rg.x), half(rg.y), half(ba.x), alpha); 16643 #endif 16644 let cornerUV = vec2f(vertex_position.xy); 16645 #if defined(SHADOW_PASS) || defined(PICK_PASS) || defined(PREPASS_PASS) 16646 let alphaClipValue = half(uniform.alphaClip); 16647 #else 16648 let alphaClipValue = half(uniform.alphaClipForward); 16649 #endif 16650 let clip = min(half(1.0), sqrt(max(half(0.0), log(alpha / alphaClipValue))) * half(0.5)); 16651 let cornerClipped = cornerUV * f32(clip); 16652 let c = vec2f(proj.w) * uniform.viewport_size.zw; 16653 let pixelOffset = cornerClipped.x * v1 + cornerClipped.y * v2; 16654 let clipOffset = pixelOffset * c; 16655 output.position = proj + vec4f(clipOffset, 0.0, 0.0); 16656 output.gaussianUV = half2(cornerClipped); 16657 let viewDepth = dot(uniform.clipToViewZ, proj); 16658 #ifdef GSPLAT_OVERDRAW 16659 let t: f32 = clamp(viewDepth / 20.0, 0.0, 1.0); 16660 let rampColor: vec3f = textureSampleLevel(colorRamp, colorRampSampler, vec2f(t, 0.5), 0.0).rgb; 16661 let outAlpha = alpha * half(1.0 / 32.0) * half(uniform.colorRampIntensity); 16662 output.gaussianColor = half4(half3(rampColor), outAlpha); 16663 #else 16664 output.gaussianColor = half4( 16665 half3(prepareOutputFromGamma(max(vec3f(clr.xyz), vec3f(0.0)), viewDepth)), 16666 alpha 16667 ); 16668 #endif 16669 #ifndef DITHER_NONE 16670 output.id = f32(cacheIdx); 16671 #endif 16672 #ifdef PREPASS_PASS 16673 output.vLinearDepth = viewDepth; 16674 #endif 16675 #if defined(GSPLAT_UNIFIED_ID) && defined(PICK_PASS) 16676 output.vPickId = pickId; 16677 #endif 16678 return output; 16679} 16680`,jG=` 16681fn pack8888(v: vec4f) -> u32 { 16682 let t = vec4u(v * 255.0) << vec4u(24u, 16u, 8u, 0u); 16683 return t.x | t.y | t.z | t.w; 16684} 16685fn pack101010(v: vec3f) -> u32 { 16686 let t = vec3u(v * vec3f(1023.0, 1023.0, 1023.0)) << vec3u(20u, 10u, 0u); 16687 return t.x | t.y | t.z; 16688} 16689fn pack111110(v: vec3f) -> u32 { 16690 let t = vec3u(v * vec3f(2047.0, 2047.0, 1023.0)) << vec3u(21u, 10u, 0u); 16691 return t.x | t.y | t.z; 16692} 16693fn unpack8888(v: u32) -> vec4f { 16694 return vec4f((vec4u(v) >> vec4u(24u, 16u, 8u, 0u)) & vec4u(0xffu)) / 255.0; 16695} 16696fn unpack101010(v: u32) -> vec3f { 16697 return vec3f((vec3u(v) >> vec3u(20u, 10u, 0u)) & vec3u(0x3ffu)) / 1023.0; 16698} 16699fn unpack111110(v: u32) -> vec3f { 16700 return vec3f((vec3u(v) >> vec3u(21u, 10u, 0u)) & vec3u(0x7ffu, 0x7ffu, 0x3ffu)) / vec3f(2047.0, 2047.0, 1023.0); 16701}`,qG=` 16702uniform splatTextureSize: u32; 16703`,$G=` 16704var<private> tAw: u32; 16705var<private> tBcached: vec4f; 16706fn unpackRotation(data: vec3f) -> vec4f { 16707 return vec4f(data.xyz, sqrt(max(0.0, 1.0 - dot(data, data)))); 16708} 16709fn getCenter() -> vec3f { 16710 let tA: vec4<u32> = loadTransformA(); 16711 tAw = tA.w; 16712 tBcached = loadTransformB(); 16713 return bitcast<vec3f>(tA.xyz); 16714} 16715fn getColor() -> vec4f { 16716 return loadSplatColor(); 16717} 16718fn getRotation() -> vec4f { 16719 return unpackRotation(vec3f(unpack2x16float(tAw), tBcached.w)).wxyz; 16720} 16721fn getScale() -> vec3f { 16722 return tBcached.xyz; 16723} 16724#include "gsplatUncompressedSHVS" 16725`,KG=` 16726#if SH_BANDS > 0 16727fn unpack111011s(bits: u32) -> vec3f { 16728 return (vec3f((vec3<u32>(bits) >> vec3<u32>(21u, 11u, 0u)) & vec3<u32>(0x7ffu, 0x3ffu, 0x7ffu)) / vec3f(2047.0, 1023.0, 2047.0)) * 2.0 - 1.0; 16729} 16730struct ScaleAndSH { 16731 scale: f32, 16732 a: vec3f, 16733 b: vec3f, 16734 c: vec3f 16735}; 16736fn fetchScale(t_in: vec4<u32>) -> ScaleAndSH { 16737 var result: ScaleAndSH; 16738 result.scale = bitcast<f32>(t_in.x); 16739 result.a = unpack111011s(t_in.y); 16740 result.b = unpack111011s(t_in.z); 16741 result.c = unpack111011s(t_in.w); 16742 return result; 16743} 16744struct SH { 16745 a: vec3f, 16746 b: vec3f, 16747 c: vec3f, 16748 d: vec3f 16749}; 16750fn fetch4(t_in: vec4<u32>) -> SH { 16751 var result: SH; 16752 result.a = unpack111011s(t_in.x); 16753 result.b = unpack111011s(t_in.y); 16754 result.c = unpack111011s(t_in.z); 16755 result.d = unpack111011s(t_in.w); 16756 return result; 16757} 16758fn fetch1(t_in: u32) -> vec3f { 16759 return unpack111011s(t_in); 16760} 16761#if SH_BANDS == 1 16762 fn readSHData(sh: ptr<function, array<half3, 3>>, scale: ptr<function, f32>) { 16763 let result = fetchScale(loadSplatSH_1to3()); 16764 *scale = result.scale; 16765 sh[0] = half3(result.a); 16766 sh[1] = half3(result.b); 16767 sh[2] = half3(result.c); 16768 } 16769#elif SH_BANDS == 2 16770 fn readSHData(sh: ptr<function, array<half3, 8>>, scale: ptr<function, f32>) { 16771 let first: ScaleAndSH = fetchScale(loadSplatSH_1to3()); 16772 *scale = first.scale; 16773 sh[0] = half3(first.a); 16774 sh[1] = half3(first.b); 16775 sh[2] = half3(first.c); 16776 let second: SH = fetch4(loadSplatSH_4to7()); 16777 sh[3] = half3(second.a); 16778 sh[4] = half3(second.b); 16779 sh[5] = half3(second.c); 16780 sh[6] = half3(second.d); 16781 sh[7] = half3(fetch1(loadSplatSH_8to11().x)); 16782 } 16783#else 16784 fn readSHData(sh: ptr<function, array<half3, 15>>, scale: ptr<function, f32>) { 16785 let first: ScaleAndSH = fetchScale(loadSplatSH_1to3()); 16786 *scale = first.scale; 16787 sh[0] = half3(first.a); 16788 sh[1] = half3(first.b); 16789 sh[2] = half3(first.c); 16790 let second: SH = fetch4(loadSplatSH_4to7()); 16791 sh[3] = half3(second.a); 16792 sh[4] = half3(second.b); 16793 sh[5] = half3(second.c); 16794 sh[6] = half3(second.d); 16795 let third: SH = fetch4(loadSplatSH_8to11()); 16796 sh[7] = half3(third.a); 16797 sh[8] = half3(third.b); 16798 sh[9] = half3(third.c); 16799 sh[10] = half3(third.d); 16800 let fourth: SH = fetch4(loadSplatSH_12to15()); 16801 sh[11] = half3(fourth.a); 16802 sh[12] = half3(fourth.b); 16803 sh[13] = half3(fourth.c);
16804 sh[14] = half3(fourth.d); 16805 } 16806#endif 16807#endif 16808`,ZG=` 16809#include "gsplatPackingPS" 16810var chunkTexture: texture_2d<uff>; 16811var<private> chunkDataA: vec4f; 16812var<private> chunkDataB: vec4f; 16813var<private> chunkDataC: vec4f; 16814var<private> chunkDataD: vec4f; 16815var<private> chunkDataE: vec4f; 16816var<private> packedData: vec4u; 16817fn unpack111011(bits: u32) -> vec3f { 16818 return (vec3f((vec3<u32>(bits) >> vec3<u32>(21u, 11u, 0u)) & vec3<u32>(0x7ffu, 0x3ffu, 0x7ffu))) / vec3f(2047.0, 1023.0, 2047.0); 16819} 16820const norm_const: f32 = sqrt(2.0); 16821fn unpackRotation(bits: u32) -> vec4f { 16822 let a = (f32((bits >> 20u) & 0x3ffu) / 1023.0 - 0.5) * norm_const; 16823 let b = (f32((bits >> 10u) & 0x3ffu) / 1023.0 - 0.5) * norm_const; 16824 let c = (f32(bits & 0x3ffu) / 1023.0 - 0.5) * norm_const; 16825 let m = sqrt(1.0 - (a * a + b * b + c * c)); 16826 let mode = bits >> 30u; 16827 if (mode == 0u) { return vec4f(m, a, b, c); } 16828 if (mode == 1u) { return vec4f(a, m, b, c); } 16829 if (mode == 2u) { return vec4f(a, b, m, c); } 16830 return vec4f(a, b, c, m); 16831} 16832fn getCenter() -> vec3f { 16833 let tex_size_u = textureDimensions(chunkTexture, 0); 16834 let w: u32 = tex_size_u.x / 5u; 16835 let chunkId: u32 = splat.index / 256u; 16836 let chunkUV: vec2<i32> = vec2<i32>(i32((chunkId % w) * 5u), i32(chunkId / w)); 16837 chunkDataA = textureLoad(chunkTexture, chunkUV + vec2<i32>(0, 0), 0); 16838 chunkDataB = textureLoad(chunkTexture, chunkUV + vec2<i32>(1, 0), 0); 16839 chunkDataC = textureLoad(chunkTexture, chunkUV + vec2<i32>(2, 0), 0); 16840 chunkDataD = textureLoad(chunkTexture, chunkUV + vec2<i32>(3, 0), 0); 16841 chunkDataE = textureLoad(chunkTexture, chunkUV + vec2<i32>(4, 0), 0); 16842 packedData = loadPackedTexture(); 16843 return mix(chunkDataA.xyz, vec3f(chunkDataA.w, chunkDataB.xy), unpack111011(packedData.x)); 16844} 16845fn getColor() -> vec4f { 16846 let r = unpack8888(packedData.w); 16847 return vec4f(mix(chunkDataD.xyz, vec3f(chunkDataD.w, chunkDataE.xy), r.rgb), r.w); 16848} 16849fn getRotation() -> vec4f { 16850 return unpackRotation(packedData.y); 16851} 16852fn getScale() -> vec3f { 16853 return exp(mix(vec3f(chunkDataB.zw, chunkDataC.x), chunkDataC.yzw, unpack111011(packedData.z))); 16854} 16855#include "gsplatCompressedSHVS" 16856`,QG=` 16857#if SH_BANDS > 0 16858fn unpack8888s(bits: u32) -> half4 { 16859 let unpacked_u = (vec4<u32>(bits) >> vec4<u32>(0u, 8u, 16u, 24u)) & vec4<u32>(0xffu); 16860 return half4(vec4f(unpacked_u) * (8.0 / 255.0) - 4.0); 16861} 16862fn readSHData(sh: ptr<function, array<half3, 15>>, scale: ptr<function, f32>) { 16863 let shData0: vec4<u32> = loadShTexture0(); 16864 let shData1: vec4<u32> = loadShTexture1(); 16865 let shData2: vec4<u32> = loadShTexture2(); 16866 let r0: half4 = unpack8888s(shData0.x); 16867 let r1: half4 = unpack8888s(shData0.y); 16868 let r2: half4 = unpack8888s(shData0.z); 16869 let r3: half4 = unpack8888s(shData0.w); 16870 let g0: half4 = unpack8888s(shData1.x); 16871 let g1: half4 = unpack8888s(shData1.y); 16872 let g2: half4 = unpack8888s(shData1.z); 16873 let g3: half4 = unpack8888s(shData1.w); 16874 let b0: half4 = unpack8888s(shData2.x); 16875 let b1: half4 = unpack8888s(shData2.y); 16876 let b2: half4 = unpack8888s(shData2.z); 16877 let b3: half4 = unpack8888s(shData2.w); 16878 sh[0] = half3(r0.x, g0.x, b0.x); 16879 sh[1] = half3(r0.y, g0.y, b0.y); 16880 sh[2] = half3(r0.z, g0.z, b0.z); 16881 sh[3] = half3(r0.w, g0.w, b0.w); 16882 sh[4] = half3(r1.x, g1.x, b1.x); 16883 sh[5] = half3(r1.y, g1.y, b1.y); 16884 sh[6] = half3(r1.z, g1.z, b1.z); 16885 sh[7] = half3(r1.w, g1.w, b1.w); 16886 sh[8] = half3(r2.x, g2.x, b2.x);
16887 sh[9] = half3(r2.y, g2.y, b2.y); 16888 sh[10] = half3(r2.z, g2.z, b2.z); 16889 sh[11] = half3(r2.w, g2.w, b2.w); 16890 sh[12] = half3(r3.x, g3.x, b3.x); 16891 sh[13] = half3(r3.y, g3.y, b3.y); 16892 sh[14] = half3(r3.z, g3.z, b3.z); 16893 *scale = 1.0; 16894} 16895#endif 16896`,JG=` 16897uniform means_mins: vec3f; 16898uniform means_maxs: vec3f; 16899#ifndef SOG_V2 16900 uniform scales_mins: vec3f; 16901 uniform scales_maxs: vec3f; 16902 uniform sh0_mins: vec4f; 16903 uniform sh0_maxs: vec4f; 16904#endif 16905const SH_C0: f32 = 0.28209479177387814; 16906const norm: f32 = sqrt(2.0); 16907#ifdef SOG_V2 16908 fn lutScales(b: i32) -> f32 { return textureLoad(sogCodebook, vec2i(b, 0), 0).r; } 16909 fn lutSh0(b: i32) -> f32 { return textureLoad(sogCodebook, vec2i(b, 0), 0).g; } 16910 fn lutShN(b: i32) -> f32 { return textureLoad(sogCodebook, vec2i(b, 0), 0).b; } 16911#endif 16912fn getCenter() -> vec3f { 16913 let l = textureLoad(means_l, splat.uv, 0).xyz; 16914 let u = textureLoad(means_u, splat.uv, 0).xyz; 16915 let n = (l + u * 256.0) / 257.0; 16916 let v = mix(uniform.means_mins, uniform.means_maxs, n); 16917 return sign(v) * (exp(abs(v)) - 1.0); 16918} 16919fn getRotation() -> vec4f { 16920 let q = textureLoad(quats, splat.uv, 0); 16921 let qmode = u32(q.w * 255.0 + 0.5) - 252u; 16922 let abc = (q.xyz - 0.5) * norm; 16923 let d = sqrt(max(0.0, 1.0 - dot(abc, abc))); 16924 var quat: vec4f; 16925 if (qmode == 0u) { 16926 quat = vec4f(d, abc); 16927 } else if (qmode == 1u) { 16928 quat = vec4f(abc.x, d, abc.y, abc.z); 16929 } else if (qmode == 2u) { 16930 quat = vec4f(abc.x, abc.y, d, abc.z); 16931 } else { 16932 quat = vec4f(abc.x, abc.y, abc.z, d); 16933 } 16934 return quat; 16935} 16936fn getScale() -> vec3f { 16937 let s = textureLoad(scales, splat.uv, 0).xyz; 16938 var logS: vec3f; 16939 #ifdef SOG_V2 16940 let i = vec3i(s * 255.0 + 0.5); 16941 logS = vec3f(lutScales(i.x), lutScales(i.y), lutScales(i.z)); 16942 #else 16943 logS = mix(uniform.scales_mins, uniform.scales_maxs, s); 16944 #endif 16945 return exp(logS); 16946} 16947fn getColor() -> vec4f { 16948 let c = textureLoad(sh0, splat.uv, 0); 16949 var rgb: vec3f; 16950 var alpha: f32; 16951 #ifdef SOG_V2 16952 let i = vec3i(c.xyz * 255.0 + 0.5); 16953 rgb = vec3f(lutSh0(i.x), lutSh0(i.y), lutSh0(i.z)); 16954 alpha = c.w; 16955 #else 16956 rgb = mix(uniform.sh0_mins.xyz, uniform.sh0_maxs.xyz, c.xyz); 16957 let logitAlpha = mix(uniform.sh0_mins.w, uniform.sh0_maxs.w, c.w); 16958 alpha = 1.0 / (1.0 + exp(-logitAlpha)); 16959 #endif 16960 return vec4f(vec3f(0.5) + rgb * SH_C0, alpha); 16961} 16962#include "gsplatSogSHVS" 16963`,e4=` 16964#if SH_BANDS > 0 16965 #ifndef SOG_V2 16966 uniform shN_mins: f32; 16967 uniform shN_maxs: f32; 16968 #endif 16969 fn readSHTexel(u: i32, v: i32) -> half3 { 16970 let t = textureLoad(sh_centroids, vec2i(u, v), 0); 16971 #ifdef SOG_V2 16972 let idx = vec3i(t.xyz * 255.0 + 0.5); 16973 return half3(vec3f(lutShN(idx.x), lutShN(idx.y), lutShN(idx.z))); 16974 #else 16975 return mix(half3(half(uniform.shN_mins)), half3(half(uniform.shN_maxs)), half3(t.xyz)); 16976 #endif 16977 } 16978 fn readSHData(sh: ptr<function, array<half3, SH_COEFFS>>, scale: ptr<function, f32>) { 16979 let labels = textureLoad(sh_labels, splat.uv, 0); 16980 let n = i32(labels.x * 255.0 + 0.5) + i32(labels.y * 255.0 + 0.5) * 256; 16981 let u = (n % 64) * SH_COEFFS; 16982 let v = n / 64; 16983 sh[0] = readSHTexel(u, v); 16984 sh[1] = readSHTexel(u + 1, v); 16985 sh[2] = readSHTexel(u + 2, v); 16986 #if SH_BANDS > 1 16987 sh[3] = readSHTexel(u + 3, v); 16988 sh[4] = readSHTexel(u + 4, v); 16989 sh[5] = readSHTexel(u + 5, v); 16990 sh[6] = readSHTexel(u + 6, v); 16991 sh[7] = readSHTexel(u + 7, v); 16992 #endif 16993 #if SH_BANDS > 2 16994 sh[8] = readSHTexel(u + 8, v); 16995 sh[9] = readSHTexel(u + 9, v); 16996 sh[10] = readSHTexel(u + 10, v); 16997 sh[11] = readSHTexel(u + 11, v); 16998 sh[12] = readSHTexel(u + 12, v); 16999 sh[13] = readSHTexel(u + 13, v); 17000 sh[14] = readSHTexel(u + 14, v); 17001 #endif 17002 *scale = 1.0; 17003 } 17004#endif 17005`,t4=` 17006#include "gsplatContainerDeclarationsVS" 17007var<private> splatCenter: vec3f; 17008var<private> splatColor: vec4f; 17009var<private> splatScale: vec3f; 17010var<private> splatRotation: vec4f; 17011`,s4=` 17012fn getCenter() -> vec3f { 17013 #include "gsplatContainerUserReadVS" 17014 return splatCenter; 17015} 17016fn getRotation() -> vec4f { 17017 return splatRotation; 17018} 17019fn getScale() -> vec3f { 17020 return splatScale; 17021} 17022fn getColor() -> vec4f { 17023 return splatColor; 17024} 17025`;const i4={gsplatCenterVS:RG,gsplatCornerVS:zG,gsplatTileCompositeVS:VG,gsplatCommonVS:LG,gsplatSplatVS:FG,gsplatEvalSHVS:OG,gsplatHelpersVS:BG,gsplatModifyVS:NG,gsplatStructsVS:UG,gsplatQuatToMat3VS:kG,gsplatOutputVS:_C,gsplatPS:GG,gsplatTileCompositePS:HG,gsplatSourceVS:WG,gsplatVS:XG,gsplatHybridVS:YG,gsplatPackingPS:jG,g
17025splatFormatVS:qG,gsplatUncompressedVS:$G,gsplatUncompressedSHVS:KG,gsplatCompressedVS:ZG,gsplatCompressedSHVS:QG,gsplatSogVS:JG,gsplatSogSHVS:e4,gsplatContainerDeclVS:t4,gsplatContainerReadVS:s4,gsplatContainerFloatReadVS:tw},M_=["enabled"],Ml=["unified","lodBaseDistance","lodMultiplier","castShadows","material","highQualitySH","asset","resource","layers"];class r4 extends Tt{static EVENT_MATERIALCREATED="material:created";static EVENT_FRAMEREADY="frame:ready";constructor(e){super(e),this.id="gsplat",this.ComponentType=wC,this.DataType=oG,this.schema=M_,e.renderer.gsplatDirector=new nG(e.graphicsDevice,e.renderer,e.scene,this),be.get(e.graphicsDevice,ze).add(MG),be.get(e.graphicsDevice,de).add(i4),this.on("beforeremove",this.onRemove,this)}initializeComponentData(e,t,s){t.layers&&t.layers.length&&(t.layers=t.layers.slice(0));for(let i=0;i<Ml.length;i++)t.hasOwnProperty(Ml[i])&&(e[Ml[i]]=t[Ml[i]]);t.aabbCenter&&t.aabbHalfExtents&&(e.customAabb=new Le(new E(t.aabbCenter),new E(t.aabbHalfExtents))),super.initializeComponentData(e,t,M_)}cloneComponent(e,t){const s=e.gsplat,i={};Ml.forEach(a=>{if(a==="material"){if(!s.unified){const n=s[a];n&&(i[a]=n.clone())}}else i[a]=s[a]}),i.enabled=s.enabled;const r=this.addComponent(t,i);return r.customAabb=s.customAabb?.clone()??null,r}onRemove(e,t){t.onRemove()}getMaterial(e,t){const s=this.app.renderer.gsplatDirector;if(!s)return null;const i=s.camerasMap.get(e);return i?i.layersMap.get(t)?.gsplatManager?.material??null:null}getGSplatMaterial(e,t){return this.getMaterial(e,t)}}ye._buildAccessors(wC.prototype,M_);class CC extends ge{static EVENT_SETMESHES="set:meshes";_meshes=null;set meshes(e){this.decRefMeshes(),this._meshes=e,this.incRefMeshes(),this.fire("set:meshes",e)}get meshes(){return this._meshes}destroy(){this.meshes=null}decRefMeshes(){this._meshes?.forEach((e,t)=>{e&&(e.decRefCount(),e.refCount<1&&(e.destroy(),this._meshes[t]=null))})}incRefMeshes(){this._meshes?.forEach(e=>{e?.incRefCount()})}}function Od(l){const e=this;if(!e.resource)return;const t=l.resource,s=t.renders&&t.renders[e.data.renderIndex];s&&(e.resource.meshes=s.resource.meshes)}function B0(l){const e=this;e.registry.off(`load:${l.id}`,Od,e),e.registry.on(`load:${l.id}`,Od,e),e.registry.off(`remove:${l.id}`,N0,e),e.registry.once(`remove:${l.id}`,N0,e),l.resource?Od.call(e,l):e.registry.load(l)}function N0(l){const e=this;e.registry.off(`load:${l.id}`,Od,e),e.resource&&e.resource.destroy()}class a4 extends dt{constructor(e){super(e,"render"),this._registry=e.assets}open(e,t){return new CC}patch(e,t){if(!e.data.containerAsset)return;const s=t.get(e.data.containerAsset);if(!s){t.once(`add:${e.data.containerAsset}`,B0,e);return}B0.call(e,s)}}class EC{constructor(e,t,s,i){this._paths=e,this._input=t,this._output=s,this._interpolation=i}get paths(){return this._paths}get input(){return this._input}get output(){return this._output}get interpolation(){return this._interpolation}}class Cu{constructor(e,t){this._components=e,this._data=t}get components(){return this._components}get data(){return this._data}}function n4(l,e){let t;
17025const r=(p,m)=>{switch(m){case t.DT_INT8:return new Int8Array(p.buffer,p.byteOffset,p.byteLength);case t.DT_INT16:return new Int16Array(p.buffer,p.byteOffset,p.byteLength/2);case t.DT_INT32:return new Int32Array(p.buffer,p.byteOffset,p.byteLength/4);case t.DT_UINT8:return new Uint8Array(p.buffer,p.byteOffset,p.byteLength);case t.DT_UINT16:return new Uint16Array(p.buffer,p.byteOffset,p.byteLength/2);case t.DT_UINT32:return new Uint32Array(p.buffer,p.byteOffset,p.byteLength/4);case t.DT_FLOAT32:return new Float32Array(p.buffer,p.byteOffset,p.byteLength/4)}return null},a=p=>{switch(p){case t.DT_INT8:return 1;case t.DT_INT16:return 2;case t.DT_INT32:return 4;case t.DT_UINT8:return 1;case t.DT_UINT16:return 2;case t.DT_UINT32:return 4;case t.DT_FLOAT32:return 4}return 1},n=p=>{switch(p){case t.DT_INT8:return 0;case t.DT_UINT8:return 1;case t.DT_INT16:return 2;case t.DT_UINT16:return 3;case t.DT_INT32:return 4;case t.DT_UINT32:return 5;case t.DT_FLOAT32:return 6;default:return 6}},o=p=>p.num_components()*a(p.data_type()),c={0:0,1:1,5:2,2:3,7:4,8:5,4:6,3:7},h=(p,m)=>{const _=(O,D,N)=>{O[0]=D[0]-N[0],O[1]=D[1]-N[1],O[2]=D[2]-N[2]},g=(O,D,N)=>{O[0]=D[1]*N[2]-N[1]*D[2],O[1]=D[2]*N[0]-N[2]*D[0],O[2]=D[0]*N[1]-N[0]*D[1]},v=(O,D)=>{const N=O[D+0],k=O[D+1],A=O[D+2],M=1/Math.sqrt(N*N+k*k+A*A);O[D+0]*=M,O[D+1]*=M,O[D+2]*=M},x=(O,D,N)=>{for(let k=0;k<3;++k)O[k]=D[N+k]},y=m.length/3,S=p.length/3,T=new Float32Array(p.length),w=[0,0,0],C=[0,0,0],b=[0,0,0],I=[0,0,0],P=[0,0,0],L=[0,0,0];for(let O=0;O<y;++O){const D=m[O*3+0]*3,N=m[O*3+1]*3,k=m[O*3+2]*3;x(w,p,D),x(C,p,N),x(b,p,k),_(I,C,w),_(P,b,w),g(L,I,P),v(L,0);for(let A=0;A<3;++A)T[D+A]+=L[A],T[N+A]+=L[A],T[k+A]+=L[A]}for(let O=0;O<S;++O)v(T,O*3);return new Uint8Array(T.buffer)},d=p=>{const m={},_=new t.DecoderBuffer;_.Init(p,p.length);const g=new t.Decoder;if(g.GetEncodedGeometryType(_)!==t.TRIANGULAR_MESH)return m.error="Failed to decode draco mesh: not a mesh",m;const v=new t.Mesh,x=g.DecodeBufferToMesh(_,v);if(!x||!x.ok()||t.getPointer(v)===0)return m.error="Failed to decode draco asset",m;const y=v.num_faces()*3,S=v.num_points()<=65535,T=y*(S?2:4),w=t._malloc(T);S?(g.GetTrianglesUInt16Array(v,T,w),m.indices=new Uint16Array(t.HEAPU16.buffer,w,y).slice().buffer):(g.GetTrianglesUInt32Array(v,T,w),m.indices=new Uint32Array(t.HEAPU32.buffer,w,y).slice().buffer),t._free(w);const C=[];for(let D=0;D<v.num_attributes();++D)C.push(g.GetAttribute(v,D));C.sort((D,N)=>(c[D.attribute_type()]??c.length)-(c[N.attribute_type()]??c.length));let b=0;const I=C.map(D=>{const N=b;return b+=Math.ceil(o(D)/4)*4,N}),P=C.some(D=>D.attribute_type()===1);let L=I[1]??0;if(!P){L=I[0]+Math.ceil(o(C[0])/4)*4;for(let D=1;D<I.length;++D)I[D]+=12;b+=12}m.attributes=C.map((D,N)=>({id:D.unique_id(),dataType:n(D.data_type()),numComponents:D.num_components(),offset:I[N]})),P||m.attributes.splice(1,0,{id:-1,dataType:6,numComponents:3,offset:L}),m.stride=b,m.vertices=new ArrayBuffer(v.num_points()*b);const O=new Uint8Array(m.vertices);for(let D=0;D<v.num_attributes();++D){const N=C[D],k=o(N),A=v.num_points()*k,M=t._malloc(A);g.GetAttributeDataArrayForAllPoints(v,N,N.data_type(),A,M);const R=new Uint8Array(t.HEAPU8.buffer,M,A);for(let F=0;F<v.num_points();++F)for(let U=0;U<k;++U)O[F*b+I[D]+U]=R[F*k+U];if(!P&&N.attribute_type()===0){const F=h(r(R,N.data_type()),S?new Uint16Array(m.indices):new Uint32Array(m.indices));for(let U=0;U<v.num_points();++U)for(let B=0;B<12;++B)O[U*b+L+B]=F[U*12+B]}t._free(M)}return t.destroy(v),t.destroy(g),t.destroy(_),m},u=p=>{const m=d(new Uint8Array(p.buffer));self.postMessage({jobId:p.jobId,error:m.error,indices:m.indices,vertices:m.vertices,attributes:m.attributes,stride:m.stride},[m.indices,m.vertices].filter(_=>_!=null))},f=[];self.onmessage=p=>{const m=p.data;switch(m.type){case"init":self.DracoDecoderModule({instantiateWasm:(_,g)=>(WebAssembly.instantiate(m.module,_).then(v=>g(v)).catch(v=>console.error(`instantiate failed + ${v}`)),{})}).then(_=>{t=_,f.forEach(g=>u(g))});break;case"decodeMesh":t?u(m):f.push(m);break}}}const k0=3;class o4{constructor(){this.workers=[[],[],[]],this.jobId=0,this.jobQueue=[],this.jobCallbacks=new Map,this.run=(e,t)=>{e.postMessage({type:"decodeMesh",jobId:t.jobId,buffer:t.buffer},[t.buffer])}}init(e){for(e.forEach(t=>{t.addEventListener("message",s=>{const i=s.data,r=this.jobCallbacks.get(i.jobId);if(r&&r(i.error,{indices:i.indices,vertices:i.vertices,attributes:i.attributes,str
17025ide:i.stride}),this.jobCallbacks.delete(i.jobId),this.jobQueue.length>0){const a=this.jobQueue.shift();this.run(t,a)}else{const a=this.workers[2].indexOf(t);if(a!==-1)this.workers[2].splice(a,1),this.workers[1].push(t);else{const n=this.workers[1].indexOf(t);n!==-1&&(this.workers[1].splice(n,1),this.workers[0].push(t))}}})}),this.workers[0]=e;this.jobQueue.length&&(this.workers[0].length||this.workers[1].length);){const t=this.jobQueue.shift();if(this.workers[0].length>0){const s=this.workers[0].shift();this.workers[1].push(s),this.run(s,t)}else{const s=this.workers[1].shift();this.workers[2].push(s),this.run(s,t)}}}enqueueJob(e,t){const s={jobId:this.jobId++,buffer:e};if(this.jobCallbacks.set(s.jobId,t),this.workers[0].length>0){const i=this.workers[0].shift();this.workers[1].push(i),this.run(i,s)}else if(this.workers[1].length>0){const i=this.workers[1].shift();this.workers[2].push(i),this.run(i,s)}else this.jobQueue.push(s)}}const l4=l=>new Promise((e,t)=>{const s={cache:!0,responseType:"text",retry:k0>0,maxRetries:k0};ht.get(l,s,(i,r)=>{i?t(i):e(r)})}),c4=l=>{const e=()=>fetch(l).then(s=>s.arrayBuffer()).then(s=>WebAssembly.compile(s)),t=()=>WebAssembly.compileStreaming(fetch(l)).catch(s=>e());return WebAssembly.compileStreaming?t():e()},U0=1;let Bd;const h4=l=>{if(Bd)return!0;if(!l){const e=Ix.getConfig("DracoDecoderModule");e?l={jsUrl:e.glueUrl,wasmUrl:e.wasmUrl,numWorkers:e.numWorkers}:l={jsUrl:"draco.wasm.js",wasmUrl:"draco.wasm.wasm",numWorkers:U0}}return!l.jsUrl||!l.wasmUrl?!1:(Bd=new o4,Promise.all([l4(l.jsUrl),c4(l.wasmUrl)]).then(([e,t])=>{const s=["/* draco */",e,"/* worker */",`( 17026${n4.toString()} 17027)() 17028 17029`].join(` 17030`),i=new Blob([s],{type:"application/javascript"}),r=URL.createObjectURL(i),a=Math.max(1,Math.min(16,l.numWorkers||U0)),n=[];for(let o=0;o<a;++o){const c=new Worker(r);c.postMessage({type:"init",module:t}),n.push(c)}Bd.init(n)}),!0)},d4=(l,e)=>h4()?(Bd.enqueueJob(l,e),!0):!1;class u4{gltf;nodes;scenes;animations;textures;materials;variants;meshVariants;meshDefaultMaterials;renders;skins;lights;cameras;nodeInstancingMap;destroy(){this.renders&&this.renders.forEach(e=>{e.meshes=null})}}const bC=l=>/^data:[^\n\r,\u2028\u2029]*,.*$/i.test(l),f4=l=>l.substring(l.indexOf(":")+1,l.indexOf(";")),Eu=l=>{switch(l){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":return 4;case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16;default:return 3}},Jg=l=>{switch(l){case 5120:return ua;case 5121:return mr;case 5122:return fa;case 5123:return mn;case 5124:return Yo;case 5125:return Xc;case 5126:return je;default:return 0}},p4=l=>{switch(l){case 5120:return 1;case 5121:return 1;case 5122:return 2;case 5123:return 2;case 5124:return 4;case 5125:return 4;case 5126:return 4;default:return 0}},m4=l=>{switch(l){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5124:return Int32Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:return null}},R_={POSITION:Ie,NORMAL:Cs,TANGENT:Gi,COLOR_0:ns,JOINTS_0:Bs,WEIGHTS_0:ki,TEXCOORD_0:Zs,TEXCOORD_1:pn,TEXCOORD_2:Uc,TEXCOORD_3:zc,TEXCOORD_4:Vc,TEXCOORD_5:Gc,TEXCOORD_6:Hc,TEXCOORD_7:Wc},z0={[Ie]:0,[Cs]:1,[Gi]:2,[ns]:3,[Bs]:4,[ki]:5,[Zs]:6,[pn]:7,[Uc]:8,[zc]:9,[Vc]:10,[Gc]:11,[Hc]:12,[Wc]:13},_4=l=>{switch(l){case ua:return e=>Math.max(e/127,-1);case mr:return e=>e/255;case fa:return e=>Math.max(e/32767,-1);case mn:return e=>e/65535;default:return e=>e}},L_=(l,e,t)=>{const s=_4(t),i=e.length;for(let r=0;r<i;++r)l[r]=s(e[r]);return l},Qa=(l,e,t=!1)=>{const s=Eu(l.type),i=m4(l.componentType);if(!i)return null;let r;if(l.sparse){const a=l.sparse,n={count:a.count,type:"SCALAR"},o=Qa(Object.assign(n,a.indices),e,!0),c={count:a.count,type:l.type,componentType:l.componentType},h=Qa(Object.assign(c,a.values),e,!0);if(l.hasOwnProperty("bufferView")){const d={bufferView:l.bufferView,byteOffset:l.byteOffset,componentType:l.componentType,count:l.count,type:l.type};r=Qa(d,e,!0).slice()}else r=new i(l.count*s);for(let d=0;d<a.count;++d){const u=o[d];for(let f=0;f<s;++f)r[u*s+f]=h[d*s+f]}}else if(l.hasOwnProperty("bufferView")){const a=e[l.bufferView];if(t&&a.hasOwnProperty("byteStride")){const n=s*i.BYTES_PER_ELEMENT,o=new ArrayBuffer(l.count*n),c=new Uint8Array(o);let h=0;for(let d=0;d<l.count;++d){let u=(l.byteOffset||0)+d*a.byteStride;for(let f=0;f<n;++f)c[h++]=a[u++]}r=new i(o)}else r=new i(a.buffer,a.byteOffset+(l.byteOffset||0),l.count*s)}else r=new i(l.count*s);return r},bo=(l,e)=>{const t=Qa(l,e,!0);if(t instanceof Float32Array||!l.normalized)return t;const s=new Float32Array(t.length);return L_(s,t,Jg(l.componentType)),s},F_=l=>{let e=l.min,t=l.max;if(!e||!t)return null;if(l.normalized){const s=Jg(l.componentType);e=L_([],e,s),t=L_([],t,s)}
17030return new Le(new E((t[0]+e[0])*.5,(t[1]+e[1])*.5,(t[2]+e[2])*.5),new E((t[0]-e[0])*.5,(t[1]-e[1])*.5,(t[2]-e[2])*.5))},AC=l=>{if(!l.hasOwnProperty("mode"))return qs;switch(l.mode){case 0:return lf;case 1:return cf;case 2:return Nx;case 3:return og;case 4:return qs;case 5:return Tr;case 6:return qa;default:return qs}},g4=l=>{const e=new Uint16Array(l);for(let t=0;t<l;t++)e[t]=t;return e},v4=(l,e)=>{const t=l[Ie];if(!t||t.components!==3)return;let s;if(t.size!==t.stride){const n=t.stride/Xl[t.type],o=new yo[t.type](t.buffer,t.offset,t.count*n);s=new yo[t.type](t.count*3);for(let c=0;c<t.count;++c)s[c*3+0]=o[c*n+0],s[c*3+1]=o[c*n+1],s[c*3+2]=o[c*n+2]}else s=new yo[t.type](t.buffer,t.offset,t.count*3);const i=t.count;e||(e=g4(i));const r=iw(s,e),a=new Float32Array(r.length);a.set(r),l[Cs]={buffer:a.buffer,size:12,offset:0,stride:12,count:i,components:3,type:je}},S4=l=>{const e=s=>{const i=[];for(let r=0;r<s._levels.length;++r){let a=[];if(s.cubemap)for(let n=0;n<6;++n)a.push(s._levels[r][n]);else a=s._levels[r];i.push(a)}return i},t=new ce(l.device,l);return t._levels=e(l),t},y4=l=>{const e=new pe(`${l.name}_clone`,l.type,l.file,l.data,l.options);return e.loaded=!0,e.resource=S4(l.resource),l.registry.add(e),e},x4=(l,e)=>{const t=e[Ie];if(!t)return null;const s=t.count,i=[];for(const g in e)if(e.hasOwnProperty(g)){const v={semantic:g,components:e[g].components,type:e[g].type,normalize:!!e[g].normalize};Us.isElementValid(l,v)||v.components++,i.push(v)}i.sort((g,v)=>z0[g.semantic]-z0[v.semantic]);let r,a,n,o,c,h;const d=new Us(l,i);let u=!0;for(r=0;r<d.elements.length;++r)if(c=d.elements[r],o=e[c.name],h=o.offset-t.offset,o.buffer!==t.buffer||o.stride!==c.stride||o.size!==c.size||h!==c.offset){u=!1;break}const f=new Hi(l,d,s),p=f.lock(),m=new Uint32Array(p);let _;if(u)_=new Uint32Array(t.buffer,t.offset,s*f.format.size/4),m.set(_);else{let g,v;for(r=0;r<f.format.elements.length;++r){c=f.format.elements[r],g=c.stride/4,o=e[c.name],v=o.stride/4,_=new Uint32Array(o.buffer,o.offset,(o.count-1)*v+(o.size+3)/4);let x=0,y=c.offset/4;const S=Math.floor((o.size+3)/4);for(a=0;a<s;++a){for(n=0;n<S;++n)m[y+n]=_[x+n];x+=v,y+=g}}}return f.unlock(),f},T4=(l,e,t,s,i,r)=>{const a={},n=[];for(const h in e)e.hasOwnProperty(h)&&R_.hasOwnProperty(h)&&(a[h]=e[h],n.push(`${h}:${e[h]}`));n.sort();const o=n.join();let c=r[o];if(!c){const h={};for(const d in a){const u=s[e[d]],f=Qa(u,i),p=i[u.bufferView],m=R_[d],_=Eu(u.type)*p4(u.componentType),g=p&&p.hasOwnProperty("byteStride")?p.byteStride:_;h[m]={buffer:f.buffer,size:_,offset:f.byteOffset,stride:g,count:u.count,components:Eu(u.type),type:Jg(u.componentType),normalize:u.normalized}}h.hasOwnProperty(Cs)||v4(h,t),c=x4(l,h),r[o]=c}return c},w4=(l,e,t,s,i,r)=>{let a,n,o;const c=e.joints,h=c.length,d=[];if(e.hasOwnProperty("inverseBindMatrices")){const m=e.inverseBindMatrices,_=Qa(t[m],s,!0),g=[];for(a=0;a<h;a++){for(n=0;n<16;n++)g[n]=_[a*16+n];o=new Z,o.set(g),d.push(o)}}else for(a=0;a<h;a++)o=new Z,d.push(o);const u=[];for(a=0;a<h;a++)u[a]=i[c[a]].name;const f=u.join("#");let p=r.get(f);return p||(p=new ow(l,d,u),r.set(f,p)),p},C4=(l,e,t,s,i,r,a)=>{const n=new at(l);if(n.aabb=F_(t[e.attributes.POSITION]),a.push(new Promise((o,c)=>{const h=e.extensions.KHR_draco_mesh_compression;d4(s[h.bufferView].slice().buffer,(d,u)=>{if(d)console.log(d),c(d);else{const f={};for(const[S,T]of Object.entries(h.attributes))f[T]=R_[S];f[-1]=Cs;const p=[];for(const S of u.attributes){const T=f[S.id];if(T!==void 0){let w=!1;if(S.id!==-1){for(const[C,b]of Object.entries(h.attributes))if(b===S.id&&e.attributes[C]!==void 0){w=t[e.attributes[C]].normalized??(T===ns&&(S.dataType===mr||S.dataType===mn));break}}p.push({semantic:T,components:S.numComponents,type:S.dataType,normalize:w,offset:S.offset,stride:u.stride})}}const m=new Us(l,p),_=u.vertices.byteLength/u.stride,g=_<=65535?Ni:ra,v=u.indices.byteLength/(_<=65535?2:4),x=new Hi(l,m,_,{data:u.vertices}),y=new la(l,g,v,Ys,u.indices);n.vertexBuffer=x,n.indexBuffer[0]=y,n.primitive[0].type=AC(e),n.primitive[0].base=0,n.primitive[0].count=y?v:_,n.primitive[0].indexed=!!y,o()}})})),e?.extensions?.KHR_materials_variants){const o=e.extensions.KHR_materials_variants,c={};
17030o.mappings.forEach(h=>{h.variants.forEach(d=>{c[d]=h.material})}),i[n.id]=c}return r[n.id]=e.material,n},E4=(l,e,t,s,i,r,a,n,o)=>{const c=[];return e.primitives.forEach(h=>{if(h.extensions?.KHR_draco_mesh_compression)c.push(C4(l,h,t,s,r,a,o));else{let d=h.hasOwnProperty("indices")?Qa(t[h.indices],s,!0):null;const u=T4(l,h.attributes,d,t,s,i),f=AC(h),p=new at(l);if(p.vertexBuffer=u,p.primitive[0].type=f,p.primitive[0].base=0,p.primitive[0].indexed=d!==null,d!==null){let _;d instanceof Uint8Array?_=zm:d instanceof Uint16Array?_=Ni:_=ra,_===zm&&l.isWebGPU&&(_=Ni,d=new Uint16Array(d));const g=new la(l,_,d.length,Ys,d);p.indexBuffer[0]=g,p.primitive[0].count=d.length}else p.primitive[0].count=u.numVertices;if(h.hasOwnProperty("extensions")&&h.extensions.hasOwnProperty("KHR_materials_variants")){const _=h.extensions.KHR_materials_variants,g={};_.mappings.forEach(v=>{v.variants.forEach(x=>{g[x]=v.material})}),r[p.id]=g}a[p.id]=h.material;let m=t[h.attributes.POSITION];if(p.aabb=F_(m),h.hasOwnProperty("targets")){const _=[];h.targets.forEach((g,v)=>{const x={};g.hasOwnProperty("POSITION")&&(m=t[g.POSITION],x.deltaPositions=bo(m,s),x.aabb=F_(m)),g.hasOwnProperty("NORMAL")&&(m=t[g.NORMAL],x.deltaNormals=bo(m,s)),e.hasOwnProperty("extras")&&e.extras.hasOwnProperty("targetNames")?x.name=e.extras.targetNames[v]:x.name=v.toString(10),e.hasOwnProperty("weights")&&(x.defaultWeight=e.weights[v]),x.preserveData=n.morphPreserveData,_.push(new Mf(x))}),p.morph=new zg(_,l,{preferHighPrecision:n.morphPreferHighPrecision})}c.push(p)}}),c},zt=(l,e,t)=>{let s;const i=l.texCoord;if(i)for(s=0;s<t.length;++s)e[`${t[s]}MapUv`]=i;const r=[0,0],a=[1,1],n=l.extensions?.KHR_texture_transform;if(n){const o=n.offset||r,c=n.scale||a,h=n.rotation?-n.rotation*H.RAD_TO_DEG:0,d=new j(c[0],c[1]),u=new j(o[0],1-c[1]-o[1]);for(s=0;s<t.length;++s)e[`${t[s]}MapTiling`]=d,e[`${t[s]}MapOffset`]=u,e[`${t[s]}MapRotation`]=h}},b4=(l,e,t)=>{let s;if(l.hasOwnProperty("diffuseFactor")){const[i,r,a,n]=l.diffuseFactor;e.diffuse.set(i,r,a).gamma(),e.opacity=n}else e.diffuse.set(1,1,1),e.opacity=1;if(l.hasOwnProperty("diffuseTexture")){const i=l.diffuseTexture;s=t[i.index],e.diffuseMap=s,e.diffuseMapChannel="rgb",e.opacityMap=s,e.opacityMapChannel="a",zt(i,e,["diffuse","opacity"])}if(e.useMetalness=!1,l.hasOwnProperty("specularFactor")){const[i,r,a]=l.specularFactor;e.specular.set(i,r,a).gamma()}else e.specular.set(1,1,1);if(l.hasOwnProperty("glossinessFactor")?e.gloss=l.glossinessFactor:e.gloss=1,l.hasOwnProperty("specularGlossinessTexture")){const i=l.specularGlossinessTexture;e.specularMap=e.glossMap=t[i.index],e.specularMapChannel="rgb",e.glossMapChannel="a",zt(i,e,["gloss","metalness"])}},A4=(l,e,t)=>{if(l.hasOwnProperty("clearcoatFactor")?e.clearCoat=l.clearcoatFactor*.25:e.clearCoat=0,l.hasOwnProperty("clearcoatTexture")){const s=l.clearcoatTexture;e.clearCoatMap=t[s.index],e.clearCoatMapChannel="r",zt(s,e,["clearCoat"])}if(l.hasOwnProperty("clearcoatRoughnessFactor")?e.clearCoatGloss=l.clearcoatRoughnessFactor:e.clearCoatGloss=0,l.hasOwnProperty("clearcoatRoughnessTexture")){const s=l.clearcoatRoughnessTexture;e.clearCoatGlossMap=t[s.index],e.clearCoatGlossMapChannel="g",zt(s,e,["clearCoatGloss"])}if(l.hasOwnProperty("clearcoatNormalTexture")){const s=l.clearcoatNormalTexture;e.clearCoatNormalMap=t[s.index],zt(s,e,["clearCoatNormal"]),s.hasOwnProperty("scale")?e.clearCoatBumpiness=s.scale:e.clearCoatBumpiness=1}e.clearCoatGlossInvert=!0},P4=(l,e,t)=>{e.useLighting=!1,e.emissive.copy(e.diffuse),e.emissiveMap=e.diffuseMap,e.emissiveMapUv=e.diffuseMapUv,e.emissiveMapTiling.copy(e.diffuseMapTiling),e.emissiveMapOffset.copy(e.diffuseMapOffset),e.emissiveMapRotation=e.diffuseMapRotation,e.emissiveMapChannel=e.diffuseMapChannel,e.emissiveVertexColor=e.diffuseVertexColor,e.emissiveVertexColorChannel=e.diffuseVertexColorChannel,e.useLighting=!1,e.useSkybox=!1,e.diffuse.set(1,1,1),e.diffuseMap=null,e.diffuseVertexColor=!1},I4=(l,e,t)=>{if(e.useMetalnessSpecularColor=!0,l.hasOwnProperty("specularColorTexture")&&(e.specularMap=t[l.specularColorTexture.index],e.specularMapChannel="rgb",zt(l.specularColorTexture,e,["specular"])),l.hasOwnProperty("specularColorFactor")){const[s,i,r]=l.specularColorFactor;e.specular.set(s,i,r).gamma()}else e.specular.set(1,1,1);l.hasOwnProperty("specularFactor")?e.specularityFactor=l.specularFactor:e.specularityFactor=1,l.hasOwnProperty("specularTexture")&&(e.specularityFactorMapChannel="a",e.specularityFactorMap=t[l.specularTexture.index],zt(l.specularTexture,e,["specularityFactor"]))},D4=(l,e,t)=>{l.hasOwnProperty("ior")&&(e.refractionIndex=1/l.ior)},M4=(l,e,t)=>{l.hasOwnProperty("dispersion")&&(e.dispersion=l.dispersion)},R4=(l,e,t)=>{e.blendType=Wi,e.useDynamicRefraction=!0,l.hasOwnProperty("transmissionFactor")&&(e.refraction=l.transmissionFactor),l.hasOwnProperty("transmissionTexture")&&(e.refractionMapChannel="r",e.refractionMap=t[l.transmissionTexture.index],zt(l.transmissionTexture,e,["refraction"]))},L4=(l,e,t)=>{if(e.useSheen=!0,l.hasOwnProperty("sheenColorFactor")){const[s,i,r]=l.sheenColorFactor;e.sheen.set(s,i,r).gamma()}else e.sheen.set(1,1,1);l.hasOwnProperty("sheenColorTexture")&&(e.sheenMap=t[l.sheenColorTexture.index],zt(l.sheenColorTexture,e,["sheen"])),e.sheenGloss=l.hasOwnProperty("sheenRoughnessFactor")?l.sheenRoughnessFactor:0,l.hasOwnProperty("sheenRoughnessTexture")&&(e.sheenGlossMap=t[l.sheenRoughnessTexture.index],e.sheenGlossMapChannel="a",zt(l.sheenRoughnessTexture,e,["sheenGloss"])),e.sheenGlossInvert=!0},F4=(l,e,t)=>{if(e.blendType=Wi,e.useDynamicRefraction=!0,l.hasOwnProperty("thicknessFactor")&&(e.thickness=l.thicknessFactor),l.hasOwnProperty("thicknessTexture")&&(e.thicknessMap=t[l.thicknessTexture.index],e.thicknessMapChannel="g",zt(l.thicknessTexture,e,["thickness"])),l.hasOwnProperty("attenuationDistance")&&(e.attenuationDistance=l.attenuationDistance),l.hasOwnProperty("attenuationColor")){const[s,i,r]=l.attenuationColor;e.attenuation.set(s,i,r).gamma()}},O4=(l,e,t)=>{l.hasOwnProperty("emissiveStrength")&&(e.emissiveIntensity=l.emissiveStrength)},B4=(l,e,t)=>{e.useIridescence=!0,l.hasOwnProperty("iridescenceFactor")&&(e.iridescence=l.iridescenceFactor),l.hasOwnProperty("iridescenceTexture")&&(e.iridescenceMapChannel="r",e.iridescenceMap=t[l.iridescenceTexture.index],zt(l.iridescenceTexture,e,["iridescence"])),l.hasOwnProperty("iridescenceIor")&&(e.iridescenceRefractionIndex=l.iridescenceIor),l.hasOwnProperty("iridescenceThicknessMinimum")&&(e.iridescenceThicknessMin=l.iridescenceThicknessMinimum),l.hasOwnProperty("iridescenceThicknessMaximum")&&(e.iridescenceThicknessMax=l.iridescenceThicknessMaximum),l.hasOwnProperty("iridescenceThicknessTexture")&&(e.iridescenceThicknessMapChannel="g",e.iridescenceThicknessMap=t[l.iridescenceThicknessTexture.index],zt(l.iridescenceThicknessTexture,e,["iridescenceThickness"]))},N4=(l,e,t)=>{if(e.enableGGXSpecular=!0,l.hasOwnProperty("anisotropyStrength")?e.anisotropyIntensity=l.anisotropyStrength:e.anisotropyIntensity=0,l.hasOwnProperty("anisotropyTexture")){const s=l.anisotropyTexture;e.anisotropyMap=t[s.index],zt(s,e,["anisotropy"])}l.hasOwnProperty("anisotropyRotation")?e.anisotropyRotation=l.anisotropyRotation*H.RAD_TO_DEG:e.anisotropyRotation=0},PC=(l,e)=>{const t=new Es;l.hasOwnProperty("name")&&(t.name=l.name),t.occludeSpecular=Af,t.diffuseVertexColor=!0,t.specularTint=!0,t.specularVertexColor=!0,t.specular.set(1,1,1),t.gloss=1,t.glossInvert=!0,t.useMetalness=!0;let s;if(l.hasOwnProperty("pbrMetallicRoughness")){const r=l.pbrMetallicRoughness;if(r.hasOwnProperty("baseColorFactor")){const[a,n,o,c]=r.baseColorFactor;t.diffuse.set(a,n,o).gamma(),t.opacity=c}if(r.hasOwnProperty("baseColorTexture")){const a=r.baseColorTexture;s=e[a.index],t.diffuseMap=s,t.diffuseMapChannel="rgb",t.opacityMap=s,t.opacityMapChannel="a",zt(a,t,["diffuse","opacity"])}if(r.hasOwnProperty("metallicFactor")&&(t.metalness=r.metallicFactor),r.hasOwnProperty("roughnessFactor")&&(t.gloss=r.roughnessFactor),r.hasOwnProperty("metallicRoughnessTexture")){const a=r.metallicRoughnessTexture;t.metalnessMap=t.glossMap=e[a.index],t.metalnessMapChannel="b",t.glossMapChannel="g",zt(a,t,["gloss","metalness"])}}if(l.hasOwnProperty("normalTexture")){const r=l.normalTexture;t.normalMap=e[r.index],zt(r,t,["normal"]),r.hasOwnProperty("scale")&&(t.bumpiness=r.scale)}if(l.hasOwnProperty("occlusionTexture")){const r=l.occlusionTexture;t.aoMap=e[r.index],t.aoMapChannel="r",zt(r,t,["ao"])}if(l.hasOwnProperty("emissiveFactor")){const[r,a,n]=l.emissiveFactor;t.emissive.set(r,a,n).gamma()}if(l.hasOwnProperty("emissiveTexture")){const r=l.emissiveTexture;t.emissiveMap=e[r.index],zt(r,t,["emissive"])}if(l.hasOwnProperty("alphaMode"))switch(l.alphaMode){case"MASK":t.blendType=Ns,l.hasOwnProperty("alphaCutoff")?t.alphaTest=l.alphaCutoff:t.alphaTest=.5;break;case"BLEND":t.blendType=Wi,t.depthWrite=!1;break;default:case"OPAQUE":t.blendType=Ns;break}else t.blendType=Ns;l.hasOwnProperty("doubleSided")?(t.twoSidedLighting=l.doubleSided,t.cull=l.doubleSided?Yt:tc):(t.twoSidedLighting=!1,t.cull=tc);const i={KHR_materials_clearcoat:A4,KHR_materials_emissive_strength:O4,KHR_materials_ior:D4,KHR_materials_dispersion:M4,KHR_materials_iridescence:B4,KHR_materials_pbrSpecularGlossiness:b4,KHR_materials_sheen:L4,KHR_materials_specular:I4,KHR_materials_transmission:R4,KHR_materials_unlit:P4,KHR_materials_volume:F4,KHR_materials_anisotropy:N4};if(l.hasOwnProperty("extensions"))for(const r in l.extensions){const a=i[r];a!==void 0&&a(l.extensions[r],t,e)}
17030return t.update(),t},k4=(l,e,t,s,i,r,a)=>{const n=C=>new Cu(Eu(C.type),bo(C,s)),o={STEP:Iw,LINEAR:o_,CUBICSPLINE:l_},c={},h={},d={};let u=1,f;for(f=0;f<l.samplers.length;++f){const C=l.samplers[f];c.hasOwnProperty(C.input)||(c[C.input]=n(t[C.input])),h.hasOwnProperty(C.output)||(h[C.output]=n(t[C.output]));const b=C.hasOwnProperty("interpolation")&&o.hasOwnProperty(C.interpolation)?o[C.interpolation]:o_,I={paths:[],input:C.input,output:C.output,interpolation:b};d[f]=I}const p=[],m={translation:"localPosition",rotation:"localRotation",scale:"localScale"},_=C=>{const b=[];for(;C;)b.unshift(C.name),C=C.parent;return b},g=(C,b,I)=>{const P=h[C.output];if(!P)return;let L;if(r&&r[b.mesh]){const M=r[b.mesh];M.hasOwnProperty("extras")&&M.extras.hasOwnProperty("targetNames")&&(L=M.extras.targetNames)}const O=P.data,D=O.length/c[C.input].data.length,N=O.length/D,k=N*4,A=new ArrayBuffer(k*D);for(let M=0;M<D;M++){const R=new Float32Array(A,k*M,N);for(let z=0;z<N;z++)R[z]=O[z*D+M];const F=new Cu(1,R),U=L?.[M]?`name.${L[M]}`:M;h[-u]=F;const B={paths:[{entityPath:I,component:"graph",propertyPath:[`weight.${U}`]}],input:C.input,output:-u,interpolation:C.interpolation};u++,d[`morphCurve-${f}-${M}`]=B}};for(f=0;f<l.channels.length;++f){const C=l.channels[f],b=C.target,I=d[C.sampler],P=i[b.node],L=a[b.node],O=_(P);b.path.startsWith("weights")?(g(I,L,O),d[C.sampler].morphCurve=!0):I.paths.push({entityPath:O,component:"graph",propertyPath:[m[b.path]]})}const v=[],x=[],y=[];for(const C in c)v.push(c[C]),c[C]=v.length-1;for(const C in h)x.push(h[C]),h[C]=x.length-1;for(const C in d){const b=d[C];b.morphCurve||(y.push(new EC(b.paths,c[b.input],h[b.output],b.interpolation)),b.paths.length>0&&b.paths[0].propertyPath[0]==="localRotation"&&b.interpolation!==l_&&p.push(y[y.length-1].output))}p.sort();let S=null,T;for(f=0;f<p.length;++f){const C=p[f];if(f===0||C!==S){if(T=x[C],T.components===4){const b=T.data,I=b.length-4;for(let P=0;P<I;P+=4)b[P+0]*b[P+4]+b[P+1]*b[P+5]+b[P+2]*b[P+6]+b[P+3]*b[P+7]<0&&(b[P+4]*=-1,b[P+5]*=-1,b[P+6]*=-1,b[P+7]*=-1)}S=C}}let w=0;for(f=0;f<v.length;f++)T=v[f]._data,w=Math.max(w,T.length===0?0:T[T.length-1]);return new Dr(l.hasOwnProperty("name")?l.name:`animation_${e}`,w,v,x,y)},Rl=new Z,Ll=new E,V0=new ae,U4=(l,e,t)=>{const s=new He;if(l.hasOwnProperty("name")&&l.name.length>0?s.name=l.name:s.name=`node_${e}`,l.hasOwnProperty("matrix")&&(Rl.data.set(l.matrix),Rl.getTranslation(Ll),s.setLocalPosition(Ll),V0.setFromMat4(Rl),s.setLocalRotation(V0),Rl.getScale(Ll),Ll.x*=Rl.scaleSign,s.setLocalScale(Ll)),l.hasOwnProperty("rotation")){const i=l.rotation;s.setLocalRotation(i[0],i[1],i[2],i[3])}if(l.hasOwnProperty("translation")){const i=l.translation;s.setLocalPosition(i[0],i[1],i[2])}if(l.hasOwnProperty("scale")){const i=l.scale;s.setLocalScale(i[0],i[1],i[2])}return l.hasOwnProperty("extensions")&&l.extensions.EXT_mesh_gpu_instancing&&t.set(l,{ext:l.extensions.EXT_mesh_gpu_instancing}),s},z4=(l,e)=>{const t=l.type==="orthographic",s=t?l.orthographic:l.perspective,i={enabled:!1,projection:t?Sn:mi,nearClip:s.znear,aspectRatioMode:hu};s.zfar&&(i.farClip=s.zfar),t?(i.orthoHeight=s.ymag,s.xmag&&s.ymag&&(i.aspectRatioMode=Zm,i.aspectRatio=s.xmag/s.ymag)):(i.fov=s.yfov*H.RAD_TO_DEG,s.aspectRatio&&(i.aspectRatioMode=Zm,i.aspectRatio=s.aspectRatio));const r=new lt(l.name);return r.addComponent("camera",i),r},V4=(l,e)=>{const t={enabled:!1,type:l.type==="point"?"omni":l.type,color:l.hasOwnProperty("color")?new Q(l.color):Q.WHITE,range:l.hasOwnProperty("range")?l.range:9999,falloffMode:vT,intensity:l.hasOwnProperty("intensity")?H.clamp(l.intensity,0,2):1};if(l.hasOwnProperty("spot")&&(t.innerConeAngle=l.spot.hasOwnProperty("innerConeAngle")?l.spot.innerConeAngle*H.RAD_TO_DEG:0,t.outerConeAngle=l.spot.hasOwnProperty("outerConeAngle")?l.spot.outerConeAngle*H.RAD_TO_DEG:45),l.hasOwnProperty("intensity")){const i=l.spot?.outerConeAngle??Math.PI/4,r=l.spot?.innerConeAngle??0;t.luminance=l.intensity*Sc.getLightUnitConversion(ZT[t.type],i,r)}const s=new lt(e.name);return s.rotateLocal(90,0,0),s.addComponent("light",t),s},G4=(l,e,t,s)=>{if(!e.hasOwnProperty("skins")||e.skins.length===0)return[];const i=new Map;return e.skins.map(r=>w4(l,r,e.accessors,s,t,i))},H4=(l,e,t,s)=>{const i={},r={},a={},n=[];return{meshes:!s.skipMeshes&&e?.meshes?.length&&e?.accessors?.length&&e?.bufferViews?.length?e.meshes.map(h=>E4(l,h,e.accessors,t,i,r,a,s,n)):[],meshVariants:r,meshDefaultMaterials:a,promises:n}},W4=(l,e,t)=>{if(!l.hasOwnProperty("materials")||l.materials.length===0)return[];const s=t?.material?.preprocess,i=t?.material?.process??PC,r=t?.material?.postprocess;return l.materials.map(a=>{s&&s(a);const n=i(a,e);return r&&r(a,n),n})},X4=l=>{if(!l.hasOwnProperty("extensions")||!l.extensions.hasOwnProperty("KHR_materials_variants"))return null;const e=l.extensions.KHR_materials_variants.variants,t={};for(let s=0;s<e.length;s++)t[e[s].name]=s;return t},Y4=(l,e,t,s)=>{if(!l.hasOwnProperty("animations")||l.animations.length===0)return[];const i=s?.animation?.preprocess,r=s?.animation?.postprocess;return l.animations.map((a,n)=>{i&&i(a);const o=k4(a,n,l.accessors,t,e,l.meshes,l.nodes);return r&&r(a,o),o})},j4=(l,e,t,s)=>{const i=e.accessors;t.forEach((r,a)=>{const n=r.ext.attributes;let o;if(n.hasOwnProperty("TRANSLATION")){const u=i[n.TRANSLATION];o=bo(u,s)}let c;if(n.hasOwnProperty("ROTATION")){const u=i[n.ROTATION];c=bo(u,s)}let h;
17030if(n.hasOwnProperty("SCALE")){const u=i[n.SCALE];h=bo(u,s)}const d=(o?o.length/3:0)||(c?c.length/4:0)||(h?h.length/3:0);if(d){const u=new Float32Array(d*16),f=new E,p=new ae,m=new E(1,1,1),_=new Z;let g=0;for(let v=0;v<d;v++){const x=v*3;if(o&&f.set(o[x],o[x+1],o[x+2]),c){const y=v*4;p.set(c[y],c[y+1],c[y+2],c[y+3])}h&&m.set(h[x],h[x+1],h[x+2]),_.setTRS(f,p,m);for(let y=0;y<16;y++)u[g++]=_.data[y]}r.matrices=u}})},q4=(l,e,t)=>{if(!l.hasOwnProperty("nodes")||l.nodes.length===0)return[];const s=e?.node?.preprocess,i=e?.node?.process??U4,r=e?.node?.postprocess,a=l.nodes.map((n,o)=>{s&&s(n);const c=i(n,o,t);return r&&r(n,c),c});for(let n=0;n<l.nodes.length;++n){const o=l.nodes[n];if(o.hasOwnProperty("children")){const c=a[n],h={};for(let d=0;d<o.children.length;++d){const u=a[o.children[d]];u.parent||(h.hasOwnProperty(u.name)?u.name+=h[u.name]++:h[u.name]=1,c.addChild(u))}}}return a},$4=(l,e)=>{const t=[],s=l.scenes.length;if(s===1&&l.scenes[0].nodes?.length===1){const i=l.scenes[0].nodes[0];t.push(e[i])}else for(let i=0;i<s;i++){const r=l.scenes[i];if(r.nodes){const a=new He(r.name);for(let n=0;n<r.nodes.length;n++){const o=e[r.nodes[n]];a.addChild(o)}t.push(a)}}return t},K4=(l,e,t)=>{let s=null;if(l.hasOwnProperty("nodes")&&l.hasOwnProperty("cameras")&&l.cameras.length>0){const i=t?.camera?.preprocess,r=t?.camera?.process??z4,a=t?.camera?.postprocess;l.nodes.forEach((n,o)=>{if(n.hasOwnProperty("camera")){const c=l.cameras[n.camera];if(c){i&&i(c);const h=r(c,e[o]);a&&a(c,h),h&&(s||(s=new Map),s.set(n,h))}}})}return s},Z4=(l,e,t)=>{let s=null;if(l.hasOwnProperty("nodes")&&l.hasOwnProperty("extensions")&&l.extensions.hasOwnProperty("KHR_lights_punctual")&&l.extensions.KHR_lights_punctual.hasOwnProperty("lights")){const i=l.extensions.KHR_lights_punctual.lights;if(i.length){const r=t?.light?.preprocess,a=t?.light?.process??V4,n=t?.light?.postprocess;l.nodes.forEach((o,c)=>{if(o.hasOwnProperty("extensions")&&o.extensions.hasOwnProperty("KHR_lights_punctual")&&o.extensions.KHR_lights_punctual.hasOwnProperty("light")){const h=o.extensions.KHR_lights_punctual.light,d=i[h];if(d){r&&r(d);const u=a(d,e[c]);n&&n(d,u),u&&(s||(s=new Map),s.set(o,u))}}})}}return s},Q4=(l,e,t)=>{l.nodes.forEach(s=>{s.hasOwnProperty("mesh")&&s.hasOwnProperty("skin")&&e[s.mesh].meshes.forEach(r=>{r.skin=t[s.skin]})})},J4=async(l,e,t,s,i)=>{const r=i?.global?.preprocess,a=i?.global?.postprocess;r&&r(e),e.asset&&e.asset.generator;const n=new Map,o=q4(e,i,n),c=$4(e,o),h=Z4(e,o,i),d=K4(e,o,i),u=X4(e),f=await Promise.all(t),{meshes:p,meshVariants:m,meshDefaultMaterials:_,promises:g}=H4(l,e,f,i),v=Y4(e,o,f,i);j4(l,e,n,f);const x=await Promise.all(s),y=x.map(b=>b.resource),S=W4(e,y,i),T=G4(l,e,o,f),w=[];for(let b=0;b<p.length;b++)w[b]=new CC,w[b].meshes=p[b];Q4(e,w,T);const C=new u4;return C.gltf=e,C.nodes=o,C.scenes=c,C.animations=v,C.textures=x,C.materials=S,C.variants=u,C.meshVariants=m,C.meshDefaultMaterials=_,C.renders=w,C.skins=T,C.lights=h,C.cameras=d,C.nodeInstancingMap=n,a&&a(e,C),await Promise.all(g),C},eH=(l,e)=>{const t=(i,r)=>{switch(i){case 9728:return Fe;case 9729:return It;case 9984:return Ac;case 9985:return Ic;case 9986:return Pc;case 9987:return ia;default:return r}},s=(i,r)=>{switch(i){case 33071:return ue;case 33648:return Iu;case 10497:return Ft;default:return r}};l&&(e=e??{},l.minFilter=t(e.minFilter,ia),l.magFilter=t(e.magFilter,It),l.addressU=s(e.wrapS,Ft),l.addressV=s(e.wrapT,Ft))};let tH=0;const lo=l=>l.extensions?.KHR_texture_basisu?.source??l.extensions?.EXT_texture_webp?.source??l.source,sH=(l,e,t,s,i)=>{if(!l.images||l.images.length===0)return[];const r=i?.image?.preprocess,a=i?.image?.processAsync,n=i?.image?.postprocess,o={"image/png":"png","image/jpeg":"jpg","image/basis":"basis","image/ktx":"ktx","image/ktx2":"ktx2","image/vnd-ms.dds":"dds"},c=u=>{const f=new Set;return u.hasOwnProperty("materials")&&u.materials.forEach(p=>{if(p.hasOwnProperty("pbrMetallicRoughness")){const m=p.pbrMetallicRoughness;if(m.hasOwnProperty("baseColorTexture")){const _=u.textures[m.baseColorTexture.index];f.add(lo(_))}}if(p.hasOwnProperty("emissiveTexture")){const m=u.textures[p.emissiveTexture.index];f.add(lo(m))}if(p.hasOwnProperty("extensions")){const m=p.extensions.KHR_materials_sheen;if(m&&m.hasOwnProperty("sheenColorTexture")){const v=u.textures[m.sheenColorTexture.index];f.add(lo(v))}const _=p.extensions.KHR_materials_pbrSpecularGlossiness;if(_&&_.hasOwnProperty("specularGlossinessTexture")){const v=u.textures[_.specularGlossinessTexture.index];f.add(lo(v))}const g=p.extensions.KHR_materials_specular;if(g&&g.hasOwnProperty("specularColorTexture")){const v=u.textures[g.specularColorTexture.index];f.add(lo(v))}}}),f},h=(u,f,p,m,_,g)=>
17030new Promise((v,x)=>{const y=S=>{const T=`${u.name||"gltf-texture"}-${tH++}`,w={url:f||T};if(S&&(w.contents=S.slice(0).buffer),m){const I=o[m];I&&(w.filename=`${w.url}.${I}`)}const C={srgb:g},b=new pe(T,"texture",w,C,_);b.on("load",I=>v(I)),b.on("error",I=>x(I)),s.add(b),s.load(b)};p?p.then(S=>y(S)):y(null)}),d=c(l);return l.images.map((u,f)=>{r&&r(u);let p;return a?p=new Promise((m,_)=>{a(u,(g,v)=>{g?_(g):m(v)})}):p=new Promise(m=>{m(null)}),p=p.then(m=>{const _=d.has(f);return m||(u.hasOwnProperty("uri")?bC(u.uri)?h(u,u.uri,null,f4(u.uri),null,_):h(u,Vo.test(u.uri)?u.uri:ve.join(t,u.uri),null,null,{crossOrigin:"anonymous"},_):u.hasOwnProperty("bufferView")&&u.hasOwnProperty("mimeType")?h(u,null,e[u.bufferView],u.mimeType,null,_):Promise.reject(new Error(`Invalid image found in gltf (neither uri or bufferView found). index=${f}`)))}),n&&(p=p.then(m=>(n(u,m),m))),p})},iH=(l,e,t)=>{if(!l?.images?.length||!l?.textures?.length)return[];const s=t?.texture?.preprocess,i=t?.texture?.processAsync,r=t?.texture?.postprocess,a=new Set;return l.textures.map(n=>{s&&s(n);let o;return i?o=new Promise((c,h)=>{i(n,l.images,(d,u)=>{d?h(d):c(u)})}):o=new Promise(c=>{c(null)}),o=o.then(c=>{c=c??lo(n);const h=a.has(c);return a.add(c),e[c].then(d=>{const u=h?y4(d):d;return eH(u.resource,(l.samplers??[])[n.sampler]),u})}),r&&(o=o.then(c=>(r(n,c),c))),o})},rH=(l,e,t,s)=>{if(!l.buffers||l.buffers.length===0)return[];const i=s?.buffer?.preprocess,r=s?.buffer?.processAsync,a=s?.buffer?.postprocess;return l.buffers.map((n,o)=>{i&&i(n);let c;return r?c=new Promise((h,d)=>{r(n,(u,f)=>{u?d(u):h(f)})}):c=new Promise(h=>{h(null)}),c=c.then(h=>{if(h)return h;if(n.hasOwnProperty("uri")){if(bC(n.uri)){const d=atob(n.uri.split(",")[1]),u=new Uint8Array(d.length);for(let f=0;f<d.length;f++)u[f]=d.charCodeAt(f);return u}return new Promise((d,u)=>{ht.get(Vo.test(n.uri)?n.uri:ve.join(t,n.uri),{cache:!0,responseType:"arraybuffer",retry:!1},(f,p)=>{f?u(f):d(new Uint8Array(p))})})}return e}),a&&(c=c.then(h=>(a(l.buffers[o],h),h))),c})},aH=(l,e)=>{const s=JSON.parse((i=>{if(typeof TextDecoder<"u")return new TextDecoder().decode(i);let r="";for(let a=0;a<i.length;a++)r+=String.fromCharCode(i[a]);return decodeURIComponent(escape(r))})(l));if(s.asset&&s.asset.version&&parseFloat(s.asset.version)<2){e(`Invalid gltf version. Expected version 2.0 or above but found version '${s.asset.version}'.`);return}e(null,s)},nH=(l,e)=>{const t=l instanceof ArrayBuffer?new DataView(l):new DataView(l.buffer,l.byteOffset,l.byteLength),s=t.getUint32(0,!0),i=t.getUint32(4,!0),r=t.getUint32(8,!0);if(s!==1179937895){e(`Invalid magic number found in glb header. Expected 0x46546C67, found 0x${s.toString(16)}`);return}if(i!==2){e(`Invalid version number found in glb header. Expected 2, found ${i}`);return}if(r<=0||r>t.byteLength){e(`Invalid length found in glb header. Found ${r}`);return}const a=[];let n=12;for(;n<r;){const o=t.getUint32(n,!0);n+o+8>t.byteLength&&e(`Invalid chunk length found in glb. Found ${o}`);const c=t.getUint32(n+4,!0),h=new Uint8Array(t.buffer,t.byteOffset+n+8,o);a.push({length:o,type:c,data:h}),n+=o+8}if(a.length!==1&&a.length!==2){e("Invalid number of chunks found in glb file.");return}if(a[0].type!==1313821514){e(`Invalid chunk type found in glb file. Expected 0x4E4F534A, found 0x${a[0].type.toString(16)}`);return}if(a.length>1&&a[1].type!==5130562){e(`Invalid chunk type found in glb file. Expected 0x004E4942, found 0x${a[1].type.toString(16)}`);return}e(null,{gltfChunk:a[0].data,binaryChunk:a.length===2?a[1].data:null})},oH=(l,e,t)=>{const s=()=>{const i=new Uint8Array(e);return i[0]===103&&i[1]===108&&i[2]===84&&i[3]===70};l&&l.toLowerCase().endsWith(".glb")||s()?nH(e,t):t(null,{gltfChunk:e,binaryChunk:null})},lH=(l,e,t)=>{const s=[],i=t?.bufferView?.preprocess,r=t?.bufferView?.processAsync,a=t?.bufferView?.postprocess;if(!l.bufferViews?.length)return s;for(let n=0;n<l.bufferViews.length;++n){const o=l.bufferViews[n];i&&i(o);let c;r?c=new Promise((h,d)=>{r(o,e,(u,f)=>{u?d(u):h(f)})}):c=new Promise(h=>{h(null)}),c=c.then(h=>h||e[o.buffer].then(d=>new Uint8Array(d.buffer,d.byteOffset+(o.byteOffset||0),o.byteLength))),o.hasOwnProperty("byteStride")&&(c=c.then(h=>(h.byteStride=o.byteStride,h))),a&&(c=c.then(h=>(a(o,h),h))),s.push(c)}return s};class bu{static parse(e,t,s,i,r,a,n){oH(e,s,(o,c)=>{if(o){n(o);return}aH(c.gltfChunk,(h,d)=>
17030{if(h){n(h);return}const u=rH(d,c.binaryChunk,t,a),f=lH(d,u,a),p=sH(d,f,t,r,a),m=iH(d,p,a);J4(i,d,f,m,a).then(_=>n(null,_)).catch(_=>n(_))})})}static createDefaultMaterial(){return PC({name:"defaultGlbMaterial"},[])}}class cH extends dt{constructor(e){super(e,"animation"),this.device=e.graphicsDevice,this.assets=e.assets}load(e,t,s){typeof e=="string"&&(e={load:e,original:e});const i={retry:this.maxRetries>0,maxRetries:this.maxRetries};(e.load.startsWith("blob:")||e.load.startsWith("data:"))&&(ve.getExtension(e.original).toLowerCase()===".glb"?i.responseType=De.ResponseType.ARRAY_BUFFER:i.responseType=De.ResponseType.JSON),ht.get(e.load,i,(r,a)=>{r?t(`Error loading animation resource: ${e.original} [${r}]`):ve.getExtension(e.original).toLowerCase()===".glb"?bu.parse("filename.glb","",a,this.device,this.assets,s?.options??{},(n,o)=>{if(n)t(n);else{const c=o.animations;if(s?.data?.events)for(let h=0;h<c.length;h++)c[h].events=new Lw(Object.values(s.data.events));o.destroy(),t(null,c)}}):t(null,this[`_parseAnimationV${a.animation.version}`](a))})}open(e,t,s){return t}_parseAnimationV3(e){const t=e.animation,s=new my;s.name=t.name,s.duration=t.duration;for(let i=0;i<t.nodes.length;i++){const r=new py,a=t.nodes[i];r._name=a.name;for(let n=0;n<a.keys.length;n++){const o=a.keys[n],c=o.time,h=o.pos,d=o.rot,u=o.scale,f=new E(h[0],h[1],h[2]),p=new ae().setFromEulerAngles(d[0],d[1],d[2]),m=new E(u[0],u[1],u[2]),_=new fy(c,f,p,m);r._keys.push(_)}s.addNode(r)}return s}_parseAnimationV4(e){const t=e.animation,s=new my;s.name=t.name,s.duration=t.duration;for(let i=0;i<t.nodes.length;i++){const r=new py,a=t.nodes[i];r._name=a.name;const n=a.defaults.p,o=a.defaults.r,c=a.defaults.s;for(let h=0;h<a.keys.length;h++){const d=a.keys[h],u=d.t,f=n||d.p,p=o||d.r,m=c||d.s,_=new E(f[0],f[1],f[2]),g=new ae().setFromEulerAngles(p[0],p[1],p[2]),v=new E(m[0],m[1],m[2]),x=new fy(u,_,g,v);r._keys.push(x)}s.addNode(r)}return s}}class hH extends dt{constructor(e){super(e,"animclip")}load(e,t){typeof e=="string"&&(e={load:e,original:e});const s={retry:this.maxRetries>0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(s.responseType=De.ResponseType.JSON),ht.get(e.load,s,(i,r)=>{i?t(`Error loading animation clip resource: ${e.original} [${i}]`):t(null,r)})}open(e,t){const s=t.name,i=t.duration,r=t.inputs.map(o=>new Cu(1,o)),a=t.outputs.map(o=>new Cu(o.components,o.data)),n=t.curves.map(o=>new EC([o.path],o.inputIndex,o.outputIndex,o.interpolation));return new Dr(s,i,r,a,n)}}class dH extends dt{constructor(e){super(e,"animstategraph")}load(e,t){typeof e=="string"&&(e={load:e,original:e});const s={retry:this.maxRetries>0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(s.responseType=De.ResponseType.JSON),ht.get(e.load,s,(i,r)=>{i?t(`Error loading animation state graph resource: ${e.original} [${i}]`):t(null,r)})}open(e,t){return new Md(t)}}const uH=[".ogg",".mp3",".wav",".mp4a",".m4a",".mp4",".aac",".opus"];class fH extends dt{constructor(e){super(e,"audio"),this.manager=e.soundManager}_isSupported(e){const t=ve.getExtension(e);return uH.indexOf(t)>-1}load(e,t){typeof e=="string"&&(e={load:e,original:e});const s=function(r){t(null,new oI(r))},i=function(r){let a=`Error loading audio url: ${e.original}`;r&&(a+=`: ${r.message||r}`),console.warn(a),t(a)};if(this._createSound){if(!this._isSupported(e.original)){i(`Audio format for ${e.original} not supported`);return}this._createSound(e.load,s,i)}else i(null)}_createSound(e,t,s){const i=this.manager;if(!i.context){s("Audio manager has no audio context");return}const r={retry:this.maxRetries>0,maxRetries:this.maxRetries};(e.startsWith("blob:")||e.startsWith("data:"))&&(r.responseType=De.ResponseType.ARRAY_BUFFER),ht.get(e,r,(a,n)=>{if(a){s(a);return}i.context.decodeAudioData(n,t,s)})}}class pH extends dt{constructor(e){super(e,"binary")}load(e,t){typeof e=="string"&&(e={load:e,original:e}),ht.get(e.load,{responseType:De.ResponseType.ARRAY_BUFFER,retry:this.maxRetries>0,maxRetries:this.maxRetries},(s,i)=>{s?t(`Error loading binary resource: ${e.original} [${s}]`):t(null,i)})}openBinary(e){return e.buffer}}class Zr{constructor(e,t,s,i){const r=function(c,h,d){const u=Zr.createAsset(t.name,c,h,d);return s.add(u),u},a=[];for(let c=0;c<e.renders.length;
17030++c)a.push(r("render",e.renders[c],c));const n=[];for(let c=0;c<e.materials.length;++c)n.push(r("material",e.materials[c],c));const o=[];for(let c=0;c<e.animations.length;++c)o.push(r("animation",e.animations[c],c));this.data=e,this._model=null,this._assetName=t.name,this._assets=s,this._defaultMaterial=i,this.renders=a,this.materials=n,this.textures=e.textures,this.animations=o}get model(){if(!this._model){const e=Zr.createModel(this.data,this._defaultMaterial),t=Zr.createAsset(this._assetName,"model",e,0);this._assets.add(t),this._model=t}return this._model}static createAsset(e,t,s,i){const r=new pe(`${e}/${t}/${i}`,t,{url:""});return r.resource=s,r.loaded=!0,r}instantiateModelEntity(e){const t=new lt(void 0,this._assets._loader._app);return t.addComponent("model",Object.assign({type:"asset",asset:this.model},e)),t}instantiateRenderEntity(e){const t=this._defaultMaterial,s=[],i=function(n,o,c,h,d,u,f,p){const m=d[c.id],_=m===void 0?t:h[m],g=new Ne(c,_);c.morph&&(g.morphInstance=new dn(c.morph)),f.hasOwnProperty("skin")&&s.push({meshInstance:g,rootBone:n,entity:o});const v=p.get(f);if(v){const x=v.matrices,y=Us.getDefaultInstancingFormat(c.device),S=new Hi(c.device,y,x.length/16,{data:x});g.setInstancing(S),g.instancingData._destroyVertexBuffer=!0}return g},r=(n,o,c)=>{const h=new lt(void 0,this._assets._loader._app);o._cloneInternal(h),n||(n=h);let d=null,u=null;for(let p=0;p<c.nodes.length;p++)if(c.nodes[p]===o){const _=c.gltf.nodes[p];if(_.hasOwnProperty("mesh")){const g=c.renders[_.mesh].meshes;u=this.renders[_.mesh];for(let v=0;v<g.length;v++){const x=g[v];if(x){const y=i(n,h,x,c.materials,c.meshDefaultMaterials,c.skins,_,c.nodeInstancingMap);d||(d=[]),d.push(y)}}}if(c.lights){const g=c.lights.get(_);g&&h.addChild(g.clone())}if(c.cameras){const g=c.cameras.get(_);g&&g.camera.system.cloneComponent(g,h)}}d&&(h.addComponent("render",Object.assign({type:"asset",meshInstances:d},e)),h.render.assignAsset(u));const f=o.children;for(let p=0;p<f.length;p++){const m=r(n,f[p],c);h.addChild(m)}return h},a=[];for(const n of this.data.scenes)a.push(r(null,n,this.data));return s.forEach(n=>{n.meshInstance.skinInstance=fi.createCachedSkinInstance(n.meshInstance.mesh.skin,n.rootBone,n.entity),n.meshInstance.node.render.rootBone=n.rootBone}),Zr.createSceneHierarchy(a,lt)}getMaterialVariants(){return this.data.variants?Object.keys(this.data.variants):[]}applyMaterialVariant(e,t){const s=t?this.data.variants[t]:null;if(s===void 0)return;const i=e.findComponents("render");for(let r=0;r<i.length;r++){const a=i[r];this._applyMaterialVariant(s,a.meshInstances)}}applyMaterialVariantInstances(e,t){const s=t?this.data.variants[t]:null;s!==void 0&&this._applyMaterialVariant(s,e)}_applyMaterialVariant(e,t){t.forEach(s=>{if(e===null)s.material=this._defaultMaterial;else{const i=this.data.meshVariants[s.mesh.id];i&&(s.material=this.data.materials[i[e]])}})}static createSceneHierarchy(e,t){let s=null;if(e.length===1)s=e[0];else{s=new t("SceneGroup");for(const i of e)s.addChild(i)}return s}static createModel(e,t){const s=function(a,n,o,c,h,d,u){const f=e.meshDefaultMaterials[n.id],p=f===void 0?t:h[f],m=new Ne(n,p,d);if(n.morph){const _=new dn(n.morph);m.morphInstance=_,a.morphInstances.push(_)}if(u.hasOwnProperty("skin")){const _=u.skin,g=o[_];n.skin=g;const v=c[_];m.skinInstance=v,a.skinInstances.push(v)}a.meshInstances.push(m)},i=new pa,r=[];for(const a of e.skins){const n=new $c(a);n.bones=a.bones,r.push(n)}i.graph=Zr.createSceneHierarchy(e.scenes,He);for(let a=0;a<e.nodes.length;a++){const n=e.nodes[a];if(n.root===i.graph){const o=e.gltf.nodes[a];if(o.hasOwnProperty("mesh")){const c=e.renders[o.mesh].meshes;for(let h=0;h<c.length;h++){const d=c[h];d&&s(i,d,e.skins,r,e.materials,n,o)}}}}return i}destroy(){const e=this._assets,t=function(i){e.remove(i),i.unload()},s=function(i){i.forEach(r=>{t(r)})};this.animations&&(s(this.animations),this.animations=null),this.textures&&(s(this.textures),this.textures=null),this.materials&&(s(this.materials),this.materials=null),this.renders&&(s(this.renders),this.renders=null),this._model&&(t(this._model),this._model=null),this.data=null,this.assets=null}}class mH{constructor(e,t,s){this._device=e,this._assets=t,this._defaultMaterial=bu.createDefaultMaterial(),this.maxRetries=s}_getUrlWithoutParams(e){return e.indexOf("?")>=0?e.split("?")[0]:e}load(e,t,s){pe.fetchArrayBuffer(e.load,(i,r)=>{i?t(i):bu.parse(this._getUrlWithoutParams(e.original),ve.extractPath(e.load),r,this._device,s.registry,s.options,
17030(a,n)=>{a?t(a):t(null,new Zr(n,s,this._assets,this._defaultMaterial))})},s,this.maxRetries)}open(e,t,s){return t}patch(e,t){}}class _H extends dt{constructor(e){super(e,"container"),this.glbContainerParser=new mH(e.graphicsDevice,e.assets,0),this.parsers={}}set maxRetries(e){this.glbContainerParser.maxRetries=e;for(const t in this.parsers)this.parsers.hasOwnProperty(t)&&(this.parsers[t].maxRetries=e)}get maxRetries(){return this.glbContainerParser.maxRetries}_getUrlWithoutParams(e){return e.indexOf("?")>=0?e.split("?")[0]:e}_getParser(e){const t=e?ve.getExtension(this._getUrlWithoutParams(e)).toLowerCase().replace(".",""):null;return this.parsers[t]||this.glbContainerParser}load(e,t,s){typeof e=="string"&&(e={load:e,original:e}),this._getParser(e.original).load(e,t,s)}open(e,t,s){return this._getParser(e).open(e,t,s)}}class gH extends dt{decoder=null;constructor(e){super(e,"css")}load(e,t){typeof e=="string"&&(e={load:e,original:e}),ht.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(s,i)=>{s?t(`Error loading css resource: ${e.original} [${s}]`):t(null,i)})}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)}}class vH extends dt{constructor(e){super(e,"cubemap"),this._device=e.graphicsDevice,this._registry=e.assets,this._loader=e.loader}load(e,t,s){this.loadAssets(s,t)}open(e,t,s){return s?s.resource:null}patch(e,t){this.loadAssets(e,(s,i)=>{s&&(t.fire("error",e),t.fire(`error:${e.id}`,s,e),e.fire("error",e))})}getAssetIds(e){const t=[];if(t[0]=e.file,(e.loadFaces||!e.file)&&e.data&&e.data.textures)for(let s=0;s<6;++s)t[s+1]=e.data.textures[s];else t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=null;return t}compareAssetIds(e,t){return e&&t?parseInt(e,10)===e||typeof e=="string"?e===t:e.url===t.url:e!==null==(t!==null)}update(e,t,s){const i=e.data||{},r=e._handlerState.assets,a=e._resources;let n,o,c;const h=[null,null,null,null,null,null,null],d=function(){return i.hasOwnProperty("type")?i.type:i.hasOwnProperty("rgbm")?i.rgbm?wr:Qs:null};if(!e.loaded||s[0]!==r[0]){if(s[0])if(n=s[0].resource,n.cubemap)for(c=0;c<6;++c)h[c+1]=new ce(this._device,{name:`${e.name}_prelitCubemap${n.width>>c}`,cubemap:!0,type:d()||n.type,width:n.width>>c,height:n.height>>c,format:n.format,levels:[n._levels[c]],addressU:ue,addressV:ue,mipmaps:c===0});else h[1]=n}else h[1]=a[1]||null,h[2]=a[2]||null,h[3]=a[3]||null,h[4]=a[4]||null,h[5]=a[5]||null,h[6]=a[6]||null;const u=s.slice(1);if(!e.loaded||!this.cmpArrays(u,r.slice(1))){if(u.indexOf(null)===-1){const f=u.map(g=>g.resource),p=[];for(o=0;o<f[0]._levels.length;++o)p.push(f.map(g=>g._levels[o]));const m=f[0].format,_=new ce(this._device,{name:`${e.name}_faces`,cubemap:!0,type:d()||f[0].type,width:f[0].width,height:f[0].height,format:m===Er?Re:m,mipmaps:i.mipmaps??!0,levels:p,minFilter:i.hasOwnProperty("minFilter")?i.minFilter:f[0].minFilter,magFilter:i.hasOwnProperty("magFilter")?i.magFilter:f[0].magFilter,anisotropy:i.hasOwnProperty("anisotropy")?i.anisotropy:1,addressU:ue,addressV:ue});h[0]=_}}else h[0]=a[0]||null;if(!this.cmpArrays(h,a))for(e.resources=h,e._handlerState.assetIds=t,e._handlerState.assets=s,c=0;c<a.length;++c)a[c]!==null&&h.indexOf(a[c])===-1&&a[c].destroy();for(c=0;c<r.length;++c)r[c]!==null&&s.indexOf(r[c])===-1&&r[c].unload()}cmpArrays(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;++s)if(e[s]!==t[s])return!1;return!0}resolveId(e){const t=parseInt(e,10);return t===e||t.toString()===e?t:e}loadAssets(e,t){e.hasOwnProperty("_handlerState")||(e._handlerState={assetIds:[null,null,null,null,null,null,null],assets:[null,null,null,null,null,null,null]});const s=this,i=s.getAssetIds(e),r=[null,null,null,null,null,null,null],a=e._handlerState.assetIds,n=e._handlerState.assets,o=s._registry;let c=7;const h=function(p,m){r[p]=m,c--,c===0&&(s.update(e,i,r),t(null,e.resources))},d=function(p,m,_){t(m)},u=function(p,m){m.loaded?h(p,m):(o.once(`load:${m.id}`,h.bind(s,p)),o.once(`error:${m.id}`,d.bind(s,p)),m.loading||o.load(m))};let f;for(let p=0;p<7;++p){const m=this.resolveId(i[p]);if(!m)h(p,null);else if(s.compareAssetIds(m,a[p]))u(p,n[p]);else if(parseInt(m,10)===m)f=o.get(m),f?u(p,f):setTimeout(((_,g)=>{const v=o.get(g);v?u(_,v):d(_,`failed to find dependent cubemap asset=${g}`)}).bind(null,p,m));else{const _=typeof m=="string"?{url:m,filename:m}:m,g=_.url.search(".dds")===-1?{type:"rgbp",addressu:"clamp",addressv:"clamp",mipmaps:!1}:null;f=new pe(`${e.name}_part_${p}`,"texture",_,g),o.add(f),u(p,f)}}}}class SH extends dt{constructor(e){super(e,"folder")}load(e,t){t(null,null)}}class G0{constructor(e,t){this.type=t&&t.type||Su,this.em=1,this.textures=e,this.intensity=0,this._data=null,this.data=t}set data(e){if(this._data=e,!!e&&(this._data.intensity!==void 0&&(this.intensity=this._data.intensity),this._data.info||(this._data.info={}),(!this._data.version||this._data.version<2)&&(this._data.info.maps=[{width:this._data.info.width,height:this._data.info.height}],this._data.chars)))for(const t in this._data.chars)this._data.chars[t].map=0}get data(){return this._data}}function Sm(l){return l.version<3&&(l.version<2&&(l.info.maps=l.info.maps||[{width:l.info.width,height:l.info.height}]),l.chars=Object.keys(l.chars||{}).reduce((e,t)=>
17030{const s=l.chars[t],i=s.letter!==void 0?s.letter:vd.fromCodePoint(t);return l.version<2&&(s.map=s.map||0),e[i]=s,e},{}),l.version=3),l}class yH extends dt{constructor(e){super(e,"font"),this._loader=e.loader,this.maxRetries=0}load(e,t,s){typeof e=="string"&&(e={load:e,original:e});const i=this;ve.getExtension(e.original)===".json"?ht.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(r,a)=>{if(r)t(`Error loading font resource: ${e.original} [${r}]`);else{const n=Sm(a);i._loadTextures(e.load.replace(".json",".png"),n,(o,c)=>{o?t(o):t(null,{data:n,textures:c})})}}):(s&&s.data&&(s.data=Sm(s.data)),this._loadTextures(e.load,s&&s.data,t))}_loadTextures(e,t,s){const i=t.info.maps.length;let r=0,a=null;const n=new Array(i),o=this._loader,c=function(h){const d=function(u,f){if(!a){if(u){a=u,s(u);return}f.upload(),n[h]=f,r++,r===i&&s(null,n)}};h===0?o.load(e,"texture",d):o.load(e.replace(".png",`${h}.png`),"texture",d)};for(let h=0;h<i;h++)c(h)}open(e,t,s){let i;return t.textures?i=new G0(t.textures,t.data):i=new G0(t,
17030null),i}patch(e,t){const s=e.resource;!s.data&&e.data?s.data=e.data:!e.data&&s.data&&(e.data=s.data),e.data&&(e.data=Sm(e.data))}}const ym=.28209479177387814;class xH{constructor(e,t,s,i,r,a){const n=(y,S)=>{const T=(1<<S)-1;return(y&T)/T},o=(y,S)=>{y.x=n(S>>>21,11),y.y=n(S>>>11,10),y.z=n(S,11)},c=(y,S)=>{y.x=n(S>>>24,8),y.y=n(S>>>16,8),y.z=n(S>>>8,8),y.w=n(S,8)},h=(y,S)=>{const T=Math.SQRT2,w=(n(S>>>20,10)-.5)*T,C=(n(S>>>10,10)-.5)*T,b=(n(S,10)-.5)*T,I=Math.sqrt(1-(w*w+C*C+b*b));switch(S>>>30){case 0:y.set(w,C,b,I);break;case 1:y.set(I,C,b,w);break;case 2:y.set(C,I,b,w);break;case 3:y.set(C,b,I,w);break}},d=(y,S,T)=>y*(1-T)+S*T,{chunkData:u,chunkSize:f,vertexData:p,shData0:m,shData1:_,shData2:g,shBands:v}=e,x=[3,8,15][v-1];this.read=y=>{const S=Math.floor(y/256)*f;if(t&&(o(t,p[y*4+0]),t.x=d(u[S+0],u[S+3],t.x),t.y=d(u[S+1],u[S+4],t.y),t.z=d(u[S+2],u[S+5],t.z)),s&&h(s,p[y*4+1]),i&&(o(i,p[y*4+2]),i.x=d(u[S+6],u[S+9],i.x),i.y=d(u[S+7],u[S+10],i.y),i.z=d(u[S+8],u[S+11],i.z)),r&&(c(r,p[y*4+3]),f>12&&(r.x=d(u[S+12],u[S+15],r.x),r.y=d(u[S+13],u[S+16],r.y),r.z=d(u[S+14],u[S+17],r.z))),a&&v>0){const T=[m,_,g];for(let w=0;w<3;++w)for(let C=0;C<15;++C)a[w*15+C]=C<x?T[w][y*16+C]*(8/255)-4:0}}}}class TH{numSplats;comments;chunkData;vertexData;shData0;shData1;shData2;shBands;createIter(e,t,s,i,r){return new xH(this,e,t,s,i,r)}calcAabb(e){const{chunkData:t,numChunks:s,chunkSize:i}=this;let r=Math.exp(Math.max(t[9],t[10],t[11])),a=t[0]-r,n=t[1]-r,o=t[2]-r,c=t[3]+r,h=t[4]+r,d=t[5]+r;for(let u=1;u<s;++u){const f=u*i;r=Math.exp(Math.max(t[f+9],t[f+10],t[f+11])),a=Math.min(a,t[f+0]-r),n=Math.min(n,t[f+1]-r),o=Math.min(o,t[f+2]-r),c=Math.max(c,t[f+3]+r),h=Math.max(h,t[f+4]+r),d=Math.max(d,t[f+5]+r)}return e.center.set((a+c)*.5,(n+h)*.5,(o+d)*.5),e.halfExtents.set((c-a)*.5,(h-n)*.5,(d-o)*.5),!0}getCenters(){const{vertexData:e,chunkData:t,numChunks:s,chunkSize:i}=this,r=new Float32Array(this.numSplats*3);let a,n,o,c,h,d;for(let u=0;u<s;++u){const f=u*i;a=t[f+0],n=t[f+1],o=t[f+2],c=t[f+3],h=t[f+4],d=t[f+5];const p=Math.min(this.numSplats,(u+1)*256);for(let m=u*256;m<p;++m){const _=e[m*4],g=(_>>>21)/2047,v=(_>>>11&1023)/1023,x=(_&2047)/2047;r[m*3+0]=(1-g)*a+g*c,r[m*3+1]=(1-v)*n+v*h,r[m*3+2]=(1-x)*o+x*d}}return r}getChunks(e){const{chunkData:t,numChunks:s,chunkSize:i}=this;let r,a,n,o,c,h;for(let d=0;d<s;++d){const u=d*i;r=t[u+0],a=t[u+1],n=t[u+2],o=t[u+3],c=t[u+4],h=t[u+5],e[d*6+0]=r,e[d*6+1]=a,e[d*6+2]=n,e[d*6+3]=o,e[d*6+4]=c,e[d*6+5]=h}}calcFocalPoint(e){const{chunkData:t,numChunks:s,chunkSize:i}=this;e.x=0,e.y=0,e.z=0;for(let r=0;r<s;++r){const a=r*i;e.x+=t[a+0]+t[a+3],e.y+=t[a+1]+t[a+4],e.z+=t[a+2]+t[a+5]}e.mulScalar(.5/s)}get isCompressed(){return!0}get numChunks(){return Math.ceil(this.numSplats/256)}get chunkSize(){return this.chunkData.length/this.numChunks}decompress(){const e=["x","y","z","f_dc_0","f_dc_1","f_dc_2","opacity","scale_0","scale_1","scale_2","rot_0","rot_1","rot_2","rot_3"],{shBands:t}=this;if(t>0){const h=[];for(let u=0;u<45;++u)h.push(`f_rest_${u}`);const d=Math.max(...["f_dc_0","f_dc_1","f_dc_2"].map(u=>e.indexOf(u)));e.splice(d+1,0,...h)}const s={};e.forEach(h=>{s[h]=new Float32Array(this.numSplats)});const i=new E,r=new ae,a=new E,n=new ie,o=t>0?new Float32Array(45):null,c=this.createIter(i,r,a,n,o);for(let h=0;h<this.numSplats;++h)if(c.read(h),s.x[h]=i.x,s.y[h]=i.y,s.z[h]=i.z,s.rot_1[h]=r.x,s.rot_2[h]=r.y,s.rot_3[h]=r.z,s.rot_0[h]=r.w,s.scale_0[h]=a.x,s.scale_1[h]=a.y,s.scale_2[h]=a.z,s.f_dc_0[h]=(n.x-.5)/ym,s.f_dc_1[h]=(n.y-.5)/ym,s.f_dc_2[h]=(n.z-.5)/ym,s.opacity[h]=n.w<=0?-40:n.w>=1?40:-Math.log(1/n.w-1),o)for(let d=0;d<45;++d)s[`f_rest_${d}`][h]=o[d];return new ha([{name:"vertex",count:this.numSplats,properties:e.map(h=>({name:h,type:"float",byteSize:4,storage:s[h]}))}],this.comments)}}const wH=(l,e,t,s,i)=>{for(let r=0;r<i;++r)for(let a=0;a<s;++a)l[r*e+a]=t[r*s+a]};class CH extends Rt{constructor(e,t,s={}){super(e,t,s);const{chunkData:i,chunkSize:r,numChunks:a,numSplats:n,vertexData:o,shBands:c}=t;this.chunks=new Float32Array(a*6),t.getChunks(this.chunks);const h=[{name:"packedTexture",format:Wt}];c>0&&(h.push({name:"shTexture0",format:Wt}),h.push({name:"shTexture1",format:Wt}),h.push({name:"shTexture2",format:Wt})),this._format=new ca(e,h,{readGLSL:'#include "gsplatCompressedVS"',readWGSL:'#include "gsplatCompressedVS"'}),this.streams.init(this.format,n);const d=this.streams.getTexture("packedTexture");
17030if(d.lock().set(o),d.unlock(),c>0){const _=this.streams.getTexture("shTexture0"),g=this.streams.getTexture("shTexture1"),v=this.streams.getTexture("shTexture2");_.lock().set(new Uint32Array(t.shData0.buffer)),_.unlock(),g.lock().set(new Uint32Array(t.shData1.buffer)),g.unlock(),v.lock().set(new Uint32Array(t.shData2.buffer)),v.unlock()}const f=this.evalChunkTextureSize(a),p=this.streams.createTexture("chunkTexture",mt,f);this.streams.textures.set("chunkTexture",p);const m=p.lock();if(wH(m,20,i,r,a),r===12)for(let _=0;_<a;++_)m[_*20+15]=1,m[_*20+16]=1,m[_*20+17]=1;p.unlock()}destroy(){super.destroy()}configureMaterialDefines(e){e.set("SH_BANDS",this.streams.textures.has("shTexture0")?3:0)}evalChunkTextureSize(e){const t=Math.ceil(Math.sqrt(e)),s=Math.ceil(e/t);return new j(t*5,s)}}const H0=new Uint8Array([112,108,121,10]),W0=new Uint8Array([10,101,110,100,95,104,101,97,100,101,114,10]),O_=new Map([["char",Int8Array],["uchar",Uint8Array],["short",Int16Array],["ushort",Uint16Array],["int",Int32Array],["uint",Uint32Array],["float",Float32Array],["double",Float64Array]]);class EH{reader;progressFunc;data;view;head=0;tail=0;constructor(e,t){this.reader=e,this.progressFunc=t}async read(){const{value:e,done:t}=await this.reader.read();if(t)throw new Error("Stream finished before end of header");this.push(e),this.progressFunc?.(e.byteLength)}push(e){if(!this.data)this.data=e,this.view=new DataView(this.data.buffer),this.tail=e.length;else{const t=this.tail-this.head,s=t+e.length;if(this.data.length>=s)this.head>0?(this.data.copyWithin(0,this.head,this.tail),this.data.set(e,t),this.head=0,this.tail=s):(this.data.set(e,this.tail),this.tail+=e.length);else{const i=new Uint8Array(s);this.head>0||this.tail<this.data.length?i.set(this.data.subarray(this.head,this.tail),0):i.set(this.data,0),i.set(e,t),this.data=i,this.view=new DataView(this.data.buffer),this.head=0,this.tail=s}}}compact(){this.head>0&&(this.data.copyWithin(0,this.head,this.tail),this.tail-=this.head,this.head=0)}get remaining(){return this.tail-this.head}getInt8(){const e=this.view.getInt8(this.head);return this.head++,e}getUint8(){const e=this.view.getUint8(this.head);return this.head++,e}getInt16(){const e=this.view.getInt16(this.head,!0);return this.head+=2,e}getUint16(){const e=this.view.getUint16(this.head,!0);return this.head+=2,e}getInt32(){const e=this.view.getInt32(this.head,!0);return this.head+=4,e}getUint32(){const e=this.view.getUint32(this.head,!0);return this.head+=4,e}getFloat32(){const e=this.view.getFloat32(this.head,!0);return this.head+=4,e}getFloat64(){const e=this.view.getFloat64(this.head,!0);return this.head+=8,e}}const bH=l=>{const e=[],t=[];let s;for(let i=1;i<l.length;++i){const r=l[i].split(" ");switch(r[0]){case"comment":t.push(r.slice(1).join(" "));break;case"format":s=r[1];break;case"element":e.push({name:r[1],count:parseInt(r[2],10),properties:[]});break;case"property":{if(!O_.has(r[1]))throw new Error(`Unrecognized property data type '${r[1]}' in ply header`);e[e.length-1].properties.push({type:r[1],name:r[2],storage:null,byteSize:O_.get(r[1]).BYTES_PER_ELEMENT});break}default:throw new Error(`Unrecognized header value '${r[0]}' in ply header`)}}return{elements:e,format:s,comments:t}},AH=l=>{const e=["min_x","min_y","min_z","max_x","max_y","max_z","min_scale_x","min_scale_y","min_scale_z","max_scale_x","max_scale_y","max_scale_z","min_r","min_g","min_b","max_r","max_g","max_b"],t=["packed_position","packed_rotation","packed_scale","packed_color"],s=new Array(45).fill("").map((a,n)=>`f_rest_${n}`),i=()=>l[0].name==="chunk"&&l[0].properties.every((a,n)=>a.name===e[n]&&a.type==="float")&&l[1].name==="vertex"&&l[1].properties.every((a,n)=>a.name===t[n]&&a.type==="uint"),r=()=>l[2].name==="sh"&&[9,24,45].indexOf(l[2].properties.length)!==-1&&l[2].properties.every((a,n)=>a.name===s[n]&&a.type==="uchar");return l.length===2&&i()||l.length===3&&i()&&r()},PH=l=>l.length===1&&l[0].name==="vertex"&&l[0].properties.every(e=>e.type==="float"),IH=async(l,e,t)=>{const s=new TH;s.comments=t;const i=e[0].count,r=e[0].properties.length,a=e[1].count,o=(h=>{const d=Math.ceil(Math.sqrt(h)),u=Math.ceil(h/d);return d*u})(a);s.numSplats=a,s.chunkData=new Float32Array(i*r),s.vertexData=new Uint32Array(o*4);const c=async(h,d)=>{const u=new Uint8Array(h);let f=0;for(;f<d;){for(;l.remaining===0;)await l.read();const p=Math.min(d-f,l.remaining),m=l.data;for(let _=0;_<p;++_)u[f++]=m[l.head++]}};if(await c(s.chunkData.buffer,i*r*4),await c(s.vertexData.buffer,a*4*4),e.length===3){const h=o*16,d=new Uint8Array(h),u=new Uint8Array(h),f=new Uint8Array(h),p=1024,m=e[2].properties.length/3,_=new Uint8Array(p*m*3);for(let g=0;g<s.numSplats;g+=p){const v=Math.min(p,s.numSplats-g);await c(_.buffer,v*m*3);for(let x=0;x<v;++x)for(let y=0;y<15;++y){const S=(g+x)*16+y;y<m?(d[S]=_[(x*3+0)*m+y],u[S]=_[(x*3+1)*m+y],f[S]=_[(x*3+2)*m+y]):(d[S]=127,u[S]=127,f[S]=127)}}s.shData0=d,s.shData1=u,s.shData2=f,s.shBands={3:1,8:2,15:3}[m]}else s.shBands=0;return s},DH=async(l,e,t)=>{const s=e[0],i=s.properties,r=i.length,a=i.map(d=>d.storage),n=i.reduce((d,u)=>d+u.byteSize,0);let o=0,c;const h=()=>{const d=l.data.buffer;c?.buffer!==d&&(c=new Float32Array(d,0,d.byteLength/4))};for(h();o<s.count;){for(;l.remaining<n;)await l.read(),h();const d=Math.min(s.count-o,Math.floor(l.remaining/n));for(let u=0;u<r;++u){const f=a[u];for(let p=0;p<d;++p)f[p+o]=c[p*r+u]}o+=d,l.head+=d*n}return new ha(e,t)},MH=async(l,e,t)=>{for(let s=0;s<e.length;++s){const i=e[s],r=i.properties.reduce((o,c)=>o+c.byteSize,0),a=i.properties.map(o=>{if(o.storage)switch(o.type){case"char":return(c,h)=>{o.storage[h]=c.getInt8()};case"uchar":return(c,h)=>{o.storage[h]=c.getUint8()};case"short":return(c,h)=>{o.storage[h]=c.getInt16()};case"ushort":return(c,h)=>{o.storage[h]=c.getUint16()};case"int":return(c,h)=>{o.storage[h]=c.getInt32()};case"uint":return(c,h)=>{o.storage[h]=c.getUint32()};case"float":return(c,h)=>{o.storage[h]=c.getFloat32()};case"double":return(c,h)=>{o.storage[h]=c.getFloat64()};default:throw new Error(`Unsupported property data type '${o.type}' in ply header`)}else return c=>{c.head+=o.byteSize}});let n=0;for(;n<i.count;){for(;l.remaining<r;)await l.read();const o=Math.min(i.count-n,Math.floor(l.remaining/r));for(let c=0;c<o;++c){for(let h=0;h<i.properties.length;++h)a[h](l,n);n++}}}return new ha(e,t)},RH=async(l,e=null,t=null)=>{const s=(u,f)=>{const p=u.length-f.length;let m,_;for(m=0;m<=p;++m){for(_=0;_<f.length&&u[m+_]===f[_];++_);if(_===f.length)return m}return-1},i=(u,f)=>{if(u.length<f.length)return!1;for(let p=0;p<f.length;++p)if(u[p]!==f[p])return!1;return!0},r=new EH(l,t);let a;for(;;){if(await r.read(),r.tail>=H0.length&&!i(r.data,H0))throw new Error("Invalid ply header");if(a=s(r.data,W0),a!==-1)break}const n=new TextDecoder("ascii").decode(r.data.subarray(0,a)).split(` 17031`),{elements:o,format:c,comments:h}=bH(n);if(c!=="binary_little_endian")throw new Error("Unsupported ply format");return r.head=a+W0.length,r.compact(),await(async()=>
17031AH(o)?await IH(r,o,h):(o.forEach(u=>{u.properties.forEach(f=>{const p=O_.get(f.type);if(p){const m=!e||e(f.name)?new p(u.count):null;f.storage=m}})}),PH(o)?await DH(r,o,h):await MH(r,o,h)))()},LH=l=>!0;class FH{app;maxRetries;constructor(e,t){this.app=e,this.maxRetries=t}async load(e,t,s){const i=this.app.scene?.gsplatCentersEnabled!==!1;try{const r=await(s.file?.contents??fetch(e.load));if(!r||!r.body)t("Error loading resource",null);else{const a=parseInt(r.headers.get("content-length")??"0",10);let n=0;const o=await RH(r.body.getReader(),s.data.elementFilter??LH,d=>{n+=d,s&&s.fire("progress",n,a)});s.fire("load:data",o),o.isCompressed||(s.data.reorder??!0)&&o.reorderData();const c=i,h=o.isCompressed&&!s.data.decompress?new CH(this.app.graphicsDevice,o,{prepareCenters:c}):new Ff(this.app.graphicsDevice,o.isCompressed?o.decompress():o,{prepareCenters:c});t(null,h)}}catch(r){t(r,null)}}open(e,t){return t}}const OH=(l,e)=>{const t=new Map,s=e.length,i=()=>{let r=0,a=0;t.forEach(o=>{r+=o.loaded,a+=o.total});const n=t.size;n>0&&n<s&&(a=Math.ceil(a*s/n)),l.fire("progress",r,a)};e.forEach(r=>{const a=(o,c)=>{t.set(r,{loaded:o,total:c}),i()},n=()=>{r.off("progress",a),r.off("load",n),r.off("error",n)};r.on("progress",a),r.on("load",n),r.on("error",n)})},BH=l=>{const e={version:1,count:l.means.shape[0],means:{mins:l.means.mins,maxs:l.means.maxs,files:l.means.files},scales:{mins:l.scales.mins,maxs:l.scales.maxs,files:l.scales.files},quats:{files:l.quats.files},sh0:{mins:l.sh0.mins,maxs:l.sh0.maxs,files:l.sh0.files}};return l.shN&&(e.shN={mins:l.shN.mins,maxs:l.shN.maxs,files:l.shN.files}),e};class NH{app;maxRetries;constructor(e,t){this.app=e,this.maxRetries=t}_shouldAbort(e,t){return!!(t||!this.app.assets.get(e.id)||!this.app?.graphicsDevice||this.app.graphicsDevice._destroyed)}async loadTextures(e,t,s,i){const r=this.app.scene?.gsplatCentersEnabled!==!1;i.version!==2&&(i=BH(i));const{assets:a}=this.app,n=["means","quats","scales","sh0","shN"],o={},c=[],h=window.document?.baseURI??window.location.href;n.forEach(g=>{const v=i[g]?.files??[];o[g]=v.map(x=>{const y=new pe(x,"texture",{url:s.options?.mapUrl?.(x)??new URL(x,new URL(e.load,h).toString()).toString(),filename:x},{mipmaps:!1},{crossOrigin:"anonymous"}),S=new Promise((T,w)=>{y.on("load",()=>T(null)),y.on("error",C=>w(C))});return a.add(y),c.push(S),y})});const d=n.map(g=>o[g]).flat();let u=!1;if(s.once("unload",()=>{u=!0,d.forEach(g=>{a.remove(g),g.unload()})}),OH(s,d),d.forEach(g=>a.load(g)),await Promise.allSettled(c),this._shouldAbort(s,u)){d.forEach(g=>{a.remove(g),g.unload()}),t(null,null);return}const f=new Tc;f.url=e.original,f.meta=i,f.numSplats=i.count,f.means_l=o.means[0].resource,f.means_u=o.means[1].resource,f.quats=o.quats[0].resource,f.scales=o.scales[0].resource,f.sh0=o.sh0[0].resource,f.sh_centroids=o.shN?.[0]?.resource,f.sh_labels=o.shN?.[1]?.resource,f.shBands=Tc.calcBands(f.sh_centroids?.width);const p=s.data?.decompress;if(!p){if(this._shouldAbort(s,u)){f.destroy(),t(null,null);return}f.prepareCodebook(),r&&await f.prepareGpuData()}if(this._shouldAbort(s,u)){f.destroy(),t(null,null);return}const m=r,_=p?new Ff(this.app.graphicsDevice,await f.decompress(),{prepareCenters:m}):new Tw(this.app.graphicsDevice,f,{prepareCenters:m});if(this._shouldAbort(s,u)){_.destroy(),t(null,null);return}t(null,_)}load(e,t,s){if(s.data?.means)this.loadTextures(e,t,s,s.data);else{typeof e=="string"&&(e={load:e,original:e});const i={retry:this.maxRetries>0,maxRetries:this.maxRetries,responseType:De.ResponseType.JSON};ht.get(e.load,i,(r,a)=>{if(this._shouldAbort(s,!1)){t(null,null);return}r?t(`Error loading gsplat meta: ${e.original} [${r}]`):this.loadTextures(e,t,s,a)})}}}const kH=l=>{const e=new DataView(l),t=h=>e.getUint16(h,!0),s=h=>e.getUint32(h,!0),i=h=>({magic:s(h),numFiles:t(h+8),cdSizeBytes:s(h+12),cdOffsetBytes:s(h+16)}),r=h=>{const d=t(h+28),u=t(h+30),f=t(h+32);return{magic:s(h),compressionMethod:t(h+10),compressedSizeBytes:s(h+20),uncompressedSizeBytes:s(h+24),lfhOffsetBytes:s(h+42),filename:new TextDecoder().decode(new Uint8Array(l,h+46,d)),recordSizeBytes:46+d+u+f}},a=h=>{const d=t(h+26),u=t(h+28);return{magic:s(h),offsetBytes:h+30+d+u}},n=i(e.byteLength-22);
17031if(n.magic!==101010256)throw new Error("Invalid zip file: EOCDR not found");if(n.cdOffsetBytes===4294967295||n.cdSizeBytes===4294967295)throw new Error("Invalid zip file: Zip64 not supported");const o=[];let c=n.cdOffsetBytes;for(let h=0;h<n.numFiles;h++){const d=r(c);if(d.magic!==33639248)throw new Error("Invalid zip file: CDR not found");const u=a(d.lfhOffsetBytes);if(u.magic!==67324752)throw new Error("Invalid zip file: LFH not found");o.push({filename:d.filename,compression:{0:"none",8:"deflate"}[d.compressionMethod]??"unknown",data:new Uint8Array(l,u.offsetBytes,d.compressedSizeBytes)}),c+=d.recordSizeBytes}return o},UH=async l=>{const e=new DecompressionStream("deflate-raw"),t=new Blob([l]).stream().pipeThrough(e),s=await new Response(t).arrayBuffer();return new Uint8Array(s)},zH=async(l,e)=>{const t=await(e.file?.contents??fetch(l.load));if(!t)throw new Error("Error loading resource");if(t instanceof Response){if(!t.ok)throw new Error(`Error loading resource: ${t.status} ${t.statusText}`);const s=parseInt(t.headers.get("content-length")??"0",10);if(!t.body||!t.body.getReader){const n=await t.arrayBuffer();return e.fire("progress",n.byteLength,s),n}const i=t.body.getReader(),r=[];let a=0;try{for(;;){const{done:n,value:o}=await i.read();if(n)break;r.push(o),a+=o.byteLength,e.fire("progress",a,s)}}finally{i.releaseLock()}return new Blob(r).arrayBuffer()}return t};class VH{app;maxRetries;constructor(e,t=3){this.app=e,this.maxRetries=t}async load(e,t,s){const i=this.app.scene?.gsplatCentersEnabled!==!1;try{const r=await zH(e,s),a=kH(r);for(const g of a)g.compression==="deflate"&&(g.data=await UH(g.data));const n=a.find(g=>g.filename==="meta.json");if(!n){t("Error: meta.json not found");return}let o;try{o=JSON.parse(new TextDecoder().decode(n.data))}catch(g){t(`Error parsing meta.json: ${g}`);return}const c=["means","scales","quats","sh0","shN"].map(g=>o[g]?.files??[]).flat(),h={},d=[];for(const g of c){const v=a.find(S=>S.filename===g);let x;if(v)x=new pe(g,"texture",{url:`${e.load}/${g}`,filename:g,contents:v.data},{mipmaps:!1},{crossOrigin:"anonymous"});else{const S=new URL(g,new URL(g,window.location.href).toString()).toString();x=new pe(g,"texture",{url:S,filename:g},{mipmaps:!1},{crossOrigin:"anonymous"})}const y=new Promise((S,T)=>{x.on("load",()=>S(null)),x.on("error",w=>T(w))});this.app.assets.add(x),h[g]=x,d.push(y)}Object.values(h).forEach(g=>this.app.assets.load(g)),await Promise.allSettled(d);const{assets:u}=this.app;s.once("unload",()=>{Object.values(h).forEach(g=>{u.remove(g),g.unload()})});const f=s.data?.decompress,p=new Tc;p.url=e.original,p.meta=o,p.numSplats=o.count,p.means_l=h[o.means.files[0]].resource,p.means_u=h[o.means.files[1]].resource,p.quats=h[o.quats.files[0]].resource,p.scales=h[o.scales.files[0]].resource,p.sh0=h[o.sh0.files[0]].resource,p.sh_centroids=h[o.shN?.files[0]]?.resource,p.sh_labels=h[o.shN?.files[1]]?.resource,p.shBands=Tc.calcBands(p.sh_centroids?.width),f||(p.prepareCodebook(),i&&await p.prepareGpuData());const m=i,_=f?new Ff(this.app.graphicsDevice,await p.decompress(),{prepareCenters:m}):new Tw(this.app.graphicsDevice,p,{prepareCenters:m});t(null,_)}catch(r){t(r)}}}class GH{load(e){}unload(e){}getResource(e){}destroy(){}}class HH extends GH{_urlToAsset=new Map;_registry;maxConcurrentLoads=2;maxRetries=2;_currentlyLoading=new Set;_loadQueue=[];_retryCount=new Map;_destroyed=!1;constructor(e){super(),this._registry=e}destroy(){this._destroyed=!0;for(const e of this._urlToAsset.values())e.fire("unload",e),e.off("load"),e.off("error"),this._registry.remove(e),e.unload();this._urlToAsset.clear(),this._loadQueue.length=0,this._currentlyLoading.clear(),this._retryCount.clear()}_canLoad(){return!!this._registry.loader?.getHandler("gsplat")}load(e){this._urlToAsset.get(e)?.loaded||this._currentlyLoading.has(e)||this._loadQueue.includes(e)||(this._currentlyLoading.size<this.maxConcurrentLoads?this._startLoading(e):this._loadQueue.push(e))}_startLoading(e){this._currentlyLoading.add(e);let t=this._urlToAsset.get(e);t||(t=new pe(e,"gsplat",{url:e}),this._registry.add(t),this._urlToAsset.set(e,t)),t.once("load",()=>this._onAssetLoadSuccess(e,t)),t.once("error",s=>this._onAssetLoadError(e,t,s)),!t.loaded&&!t.loading&&this._registry.load(t)}_onAssetLoadSuccess(e,t){this._destroyed||!this._urlToAsset.has(e)||(this._currentlyLoading.delete(e),this._retryCount.delete(e),this._processQueue())}_onAssetLoadError(e,t,s){if(this._destroyed||!this._canLoad()||!this._urlToAsset.has(e))return;const i=this._retryCount.get(e)||0;i<this.maxRetries?(this._retryCount.set(e,i+1),t.loaded=!1,t.loading=!1,this._registry.load(t)):(this._currentlyLoading.delete(e),this._retryCount.delete(e),this._processQueue())}_processQueue(){if(!(this._destroyed||!this._canLoad()))for(;this._currentlyLoading.size<this.maxConcurrentLoads&&this._loadQueue.length>0;){const e=this._loadQueue.shift();e&&this._startLoading(e)}}unload(e){this._currentlyLoading.delete(e);const t=this._loadQueue.indexOf(e);t!==-1&&this._loadQueue.splice(t,1),this._retryCount.delete(e);const s=this._urlToAsset.get(e);s&&(s.fire("unload",s),s.off("load"),s.off("error"),this._registry.remove(s),s.unload(),this._urlToAsset.delete(e)),this._processQueue()}getResource(e){return this._urlToAsset.get(e)?.resource}}class WH{app;maxRetries;constructor(e,t){this.app=e,this.maxRetries=t}load(e,t,s){typeof e=="string"&&(e={load:e,original:e});const i={retry:this.maxRetries>0,maxRetries:this.maxRetries,responseType:De.ResponseType.JSON};ht.get(e.load,i,(r,a)=>{if(r)t(`Error loading gsplat octree: ${e.original} [${r}]`);else{const n=new HH(this.app.assets),o=new TC(s.file.url,a,n);t(null,o)}})}}class XH extends dt{constructor(e){super(e,"gsplat"),this.parsers={ply:new FH(e,3),sog:ne
17031w VH(e),json:new NH(e,3),octree:new WH(e,3)}}_getUrlWithoutParams(e){return e.indexOf("?")>=0?e.split("?")[0]:e}_getParser(e){const t=ve.getBasename(this._getUrlWithoutParams(e)).toLowerCase();if(t==="lod-meta.json")return this.parsers.octree;const s=ve.getExtension(t).replace(".","");return this.parsers[s]||this.parsers.ply}load(e,t,s){typeof e=="string"&&(e={load:e,original:e}),this._getParser(e.original).load(e,t,s)}open(e,t,s){return t}}class B_{static setCompressedPRS(e,t,s){const i=s.singleVecs;let r,a;const n=t.___1;n||(r=s.tripleVecs,a=t.___2);let o=n?n[0]:r[a];e.setLocalPosition(i[o],i[o+1],i[o+2]),o=n?n[1]:r[a+1],e.setLocalEulerAngles(i[o],i[o+1],i[o+2]),o=n?n[2]:r[a+2],e.setLocalScale(i[o],i[o+1],i[o+2])}static oneCharToKey(e,t){const s=e.charCodeAt(0)-t.fieldFirstCode;return t.fieldArray[s]}static multCharToKey(e,t){let s=0;for(let i=0;i<e.length;i++)s=s*t.fieldCodeBase+e.charCodeAt(i)-t.fieldFirstCode;return t.fieldArray[s]}}class Au{constructor(e,t){this._node=e,this._data=t}run(){const e=Object.prototype.toString.call(this._node);return e==="[object Object]"?this._handleMap():e==="[object Array]"?this._handleArray():this._result=this._node,this._result}_handleMap(){this._result={},Object.keys(this._node).forEach(this._handleKey,this)}_handleKey(e){let t=e;const s=e.length;s===1?t=B_.oneCharToKey(e,this._data):s===2&&(t=B_.multCharToKey(e,this._data)),this._result[t]=new Au(this._node[e],this._data).run()}_handleArray(){this._result=[],this._node.forEach(this._handleArElt,this)}_handleArElt(e){const t=new Au(e,this._data).run();this._result.push(t)}}class ev{constructor(e,t){this._app=e,this._isTemplate=t}parse(e){const t={};let s=null;const i=e.compressedFormat;i&&!e.entDecompressed&&(e.entDecompressed=!0,e.entities=new Au(e.entities,i).run());for(const r in e.entities){const a=e.entities[r],n=this._createEntity(a,i);t[r]=n,a.parent===null&&(s=n)}for(const r in e.entities){const a=t[r],n=e.entities[r].children,o=n.length;for(let c=0;c<o;c++){const h=t[n[c]];h&&a.addChild(h)}}return this._openComponentData(s,e.entities),s}_createEntity(e,t){const s=new lt(e.name,this._app);if(s.guid=e.resource_id,this._setPosRotScale(s,e,t),s._enabled=e.enabled??!0,this._isTemplate?s._template=!0:s._enabledInHierarchy=s._enabled,s.template=e.template,e.tags)for(let i=0;i<e.tags.length;i++)s.tags.add(e.tags[i]);return s}_setPosRotScale(e,t,s){if(s)B_.setCompressedPRS(e,t,s);else{const i=t.position,r=t.rotation,a=t.scale;e.setLocalPosition(i[0],i[1],i[2]),e.setLocalEulerAngles(r[0],r[1],r[2]),e.setLocalScale(a[0],a[1],a[2])}}_openComponentData(e,t){const s=this._app.systems.list;let i=s.length;const r=t[e.guid];for(let n=0;n<i;n++){const o=s[n],c=r.components[o.id];c&&o.addComponent(e,c)}i=r.children.length;const a=e._children;for(let n=0;n<i;n++)a[n]&&(a[n]=this._openComponentData(a[n],t));return e}}class IC{static load(e,t,s){typeof e=="string"&&(e={load:e,original:e}),ht.get(e.load,{retry:t>0,maxRetries:t},(i,r)=>{if(!i)s(i,r);else{let a=`Error while loading scene JSON ${e.original}`;i.message?(a+=`: ${i.message}`,i.stack&&(a+=` 17032${i.stack}`)):a+=`: ${i}`,s(a)}})}}class YH extends dt{constructor(e){super(e,"hierarchy")}load(e,t){IC.load(e,this.maxRetries,t)}open(e,t){this._app.systems.script.preloading=!0;const i=new ev(this._app,!1).parse(t);return this._app.systems.script.preloading=!1,i}}class jH extends dt{decoder=null;constructor(e){super(e,"html")}load(e,t){typeof e=="string"&&(e={load:e,original:e}),ht.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(s,i)=>{s?t(`Error loading html resource: ${e.original} [${s}]`):t(null,i)})}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)}}class qH extends dt{decoder=null;constructor(e){super(e,"json")}load(e,t){typeof e=="string"&&(e={load:e,original:e});const s={retry:this.maxRetries>0,maxRetries:this.maxRetries};e.load.startsWith("blob:")&&(s.responseType=De.ResponseType.JSON),ht.get(e.load,s,(i,r)=>{i?t(`Error loading JSON resource: ${e.original} [${i}]`):t(null,r)})}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),JSON.parse(this.decoder.decode(e))}}class $H{constructor(){this.removeInvalid=!0,this.valid=!0,this.enumValidators={occludeSpecular:this._createEnumValidator([bT,Af,AT]),cull:this._createEnumValidator([Yt,tc,Bx,RE]),blendType:this._createEnumValidator([yg,nn,Wi,Ns,Ui,xg,Tg,wg,Cg,Eg,bg]),depthFunc:this._createEnumValidator([FE,Hd,Wd,Um,OE,BE,NE,cr])}}setInvalid(e,t){this.valid=!1,this.removeInvalid&&delete t[e]}validate(e){const t=zo,s=VM,i=e.mappingFormat==="path";
17032for(const r in e){const a=t[r];if(!a){s[r]?delete e[r]:this.valid=!1;continue}if(a.startsWith("enum")){const n=a.split(":")[1];this.enumValidators[n]&&(this.enumValidators[n](e[r])||this.setInvalid(r,e))}else if(a==="number")typeof e[r]!="number"&&this.setInvalid(r,e);else if(a==="boolean")typeof e[r]!="boolean"&&this.setInvalid(r,e);else if(a==="string")typeof e[r]!="string"&&this.setInvalid(r,e);else if(a==="vec2")e[r]instanceof Array&&e[r].length===2||this.setInvalid(r,e);else if(a==="rgb")e[r]instanceof Array&&e[r].length===3||this.setInvalid(r,e);else if(a==="texture")i?typeof e[r]=="string"||e[r]===null||e[r]instanceof ce||this.setInvalid(r,e):typeof e[r]=="number"||e[r]===null||e[r]instanceof ce||this.setInvalid(r,e);else if(a==="boundingbox")e[r].center&&e[r].center instanceof Array&&e[r].center.length===3||this.setInvalid(r,e),e[r].halfExtents&&e[r].halfExtents instanceof Array&&e[r].halfExtents.length===3||this.setInvalid(r,e);else if(a==="cubemap")typeof e[r]=="number"||e[r]===null||e[r]===void 0||e[r]instanceof ce&&e[r].cubemap||this.setInvalid(r,e);else if(a==="chunks"){const n=Object.keys(e[r]);for(let o=0;o<n.length;o++)typeof e[r][n[o]]!="string"&&this.setInvalid(n[o],e[r])}else console.error(`Unknown material type: ${a}`)}return e.validated=!0,this.valid}_createEnumValidator(e){return function(t){return e.indexOf(t)>=0}}}class KH{constructor(){this._validator=null}parse(e){const t=this.migrate(e),s=this._validate(t),i=new Es;return this.initialize(i,s),i}initialize(e,t){if(t.validated||(t=this._validate(t)),t.chunks&&t.chunks&&Object.keys(t.chunks).length>0){const s=e.shaderChunks.glsl;Object.entries(t.chunks).forEach(([i,r])=>s.set(i,r))}for(const s in t){const i=zo[s],r=t[s];if(i==="vec2")e[s]=new j(r[0],r[1]);else if(i==="rgb")e[s]=new Q(r[0],r[1],r[2]);else if(i==="texture")r instanceof ce?e[s]=r:e[s]instanceof ce&&typeof r=="number"&&r>0||(e[s]=null);else if(i==="cubemap")r instanceof ce?e[s]=r:e[s]instanceof ce&&typeof r=="number"&&r>0||(e[s]=null),s==="cubeMap"&&!r&&(e.prefilteredCubemaps=null);else if(i==="boundingbox"){const a=new E(r.center[0],r.center[1],r.center[2]),n=new E(r.halfExtents[0],r.halfExtents[1],r.halfExtents[2]);e[s]=new Le(a,n)}else e[s]=t[s]}e.update()}migrate(e){e.shader&&delete e.shader,e.mapping_format&&(e.mappingFormat=e.mapping_format,delete e.mapping_format);let t;const s=[["bumpMapFactor","bumpiness"],["aoUvSet","aoMapUv"],["aoMapVertexColor","aoVertexColor"],["diffuseMapVertexColor","diffuseVertexColor"],["emissiveMapVertexColor","emissiveVertexColor"],["specularMapVertexColor","specularVertexColor"],["metalnessMapVertexColor","metalnessVertexColor"],["opacityMapVertexColor","opacityVertexColor"],["glossMapVertexColor","glossVertexColor"],["lightMapVertexColor","lightVertexColor"],["specularMapTint","specularTint"],["metalnessMapTint","metalnessTint"],["clearCoatGlossiness","clearCoatGloss"]];for(t=0;t<s.length;t++){const r=s[t][0],a=s[t][1];e[r]!==void 0&&(e[a]===void 0&&(e[a]=e[r]),delete e[r])}const i=["fresnelFactor","shadowSampleType"];for(t=0;t<i.length;t++){const r=i[t];e.hasOwnProperty(r)&&delete e[r]}return e}_validate(e){return e.validated||(this._validator||(this._validator=new $H),this._validator.validate(e)),e}}const ZH={aoMap:"white",aoDetailMap:"white",diffuseMap:"gray",diffuseDetailMap:"gray",specularMap:"gray",specularityFactorMap:"white",metalnessMap:"black",glossMap:"gray",sheenMap:"black",sheenGlossMap:"gray",clearCoatMap:"black",clearCoatGlossMap:"gray",clearCoatNormalMap:"normal",refractionMap:"white",emissiveMap:"gray",normalMap:"normal",normalDetailMap:"normal",heightMap:"gray",opacityMap:"gray",sphereMap:"gray",lightMap:"white",thicknessMap:"black",iridescenceMap:"black",iridescenceThicknessMap:"black",envAtlas:"black",anisotropyMap:"black"};class QH extends dt{constructor(e){super(e,"material"),this._assets=e.assets,this._device=e.graphicsDevice,this._parser=new KH}load(e,t){typeof e=="string"&&(e={load:e,original:e}),ht.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(s,i)=>{s?t&&t(`Error loading material: ${e.original} [${s}]`):t&&(i._engine=!0,t(null,i))})}open(e,t){const s=this._parser.parse(t);return t._engine&&(s._data=t,delete t._engine),s}patch(e,t){e.resource._data&&(e._data=e.resource._data,delete e.resource._data),e.data.name=e.name,e.resource.name=e.name,this._bindAndAssignAssets(e,t),e.off("unload",this._onAssetUnload,this),e.on("unload",this._onAssetUnload,this)}_onAssetUnload(e){delete e.data.parameters,delete e.data.chunks,delete e.data.name}_assignTexture(e,t,s){t.resource[e]=s}_getPlaceholderTexture(e){const t=ZH[e];return Za(this._device,t)}_assignPlaceholderTexture(e,t){t.resource[e]=this._getPlaceholderTexture(e)}_onTextureLoad(e,t,s){this._assignTexture(e,t,s.resource),t.resource.update(
17032)}_onTextureAdd(e,t,s){this._assets.load(s)}_onTextureRemoveOrUnload(e,t,s){const i=t.resource;i&&t.resource[e]===s.resource&&(this._assignPlaceholderTexture(e,t),i.update())}_assignCubemap(e,t,s){if(t.resource[e]=s[0],e==="cubeMap"){const i=s.slice(1);i.every(r=>r)?t.resource.prefilteredCubemaps=i:i[0]&&(t.resource.envAtlas=i[0])}}_onCubemapLoad(e,t,s){this._assignCubemap(e,t,s.resources),this._parser.initialize(t.resource,t.data)}_onCubemapAdd(e,t,s){this._assets.load(s)}_onCubemapRemoveOrUnload(e,t,s){const i=t.resource;t.data.prefilteredCubeMap128===s.resources[1]&&(this._assignCubemap(e,t,[null,null,null,null,null,null,null]),i.update())}_bindAndAssignAssets(e,t){const s=this._parser.migrate(e.data),i=e.resource,r=s.mappingFormat==="path",a=Rf;let n,o,c;for(n=0;n<a.length;n++){o=a[n],c=i._assetReferences[o];const d=s[o],u=i[o],f=u===this._getPlaceholderTexture(o),p=s.validated;d&&(!u||!p||f)?(c||(c=new Ec(o,e,t,{load:this._onTextureLoad,add:this._onTextureAdd,remove:this._onTextureRemoveOrUnload,unload:this._onTextureRemoveOrUnload},this),i._assetReferences[o]=c),r?c.url=e.getAbsoluteUrl(d):c.id=d,c.asset&&(c.asset.resource?this._assignTexture(o,e,c.asset.resource):this._assignPlaceholderTexture(o,e),t.load(c.asset))):c&&(r?c.url=null:c.id=null)}const h=Hg;for(n=0;n<h.length;n++)o=h[n],c=i._assetReferences[o],s[o]&&!e.data.prefilteredCubeMap128&&(c||(c=new Ec(o,e,t,{load:this._onCubemapLoad,add:this._onCubemapAdd,remove:this._onCubemapRemoveOrUnload,unload:this._onCubemapRemoveOrUnload},this),i._assetReferences[o]=c),r?c.url=s[o]:c.id=s[o],c.asset&&(c.asset.loaded&&this._assignCubemap(o,e,c.asset.resources),t.load(c.asset)));this._parser.initialize(i,s)}}class JH{constructor(e){this._device=e.device,this._defaultMaterial=e.defaultMaterial,this._assets=e.assets}parse(e,t,s){bu.parse("filename.glb","",e,this._device,this._assets,s?.options??{},(i,r)=>{if(i)t(i);else{const a=Zr.createModel(r,this._defaultMaterial);r.destroy(),t(null,a)}})}}const eW={points:lf,lines:cf,lineloop:Nx,linestrip:og,triangles:qs,trianglestrip:Tr,trianglefan:qa},tW={int8:ua,uint8:mr,int16:fa,uint16:mn,int32:Yo,uint32:Xc,float32:je};class sW{constructor(e){this._device=e.device,this._defaultMaterial=e.defaultMaterial}parse(e,t){const s=e.model;if(!s){t(null,null);return}if(s.version<=1){t("JsonModelParser#parse: Trying to parse unsupported model format.");return}const i=this._parseNodes(e),r=this._parseSkins(e,i),a=this._parseVertexBuffers(e),n=this._parseIndexBuffers(e,a),o=this._parseMorphs(e,i,a),c=this._parseMeshes(e,r.skins,o.morphs,a,n.buffer,n.data),h=this._parseMeshInstances(e,i,c,r.skins,r.instances,o.morphs,o.instances),d=new pa;d.graph=i[0],d.meshInstances=h,d.skinInstances=r.instances,d.morphInstances=o.instances,d.getGraph().syncHierarchy(),t(null,d)}_parseNodes(e){const t=e.model,s=[];let i;for(i=0;i<t.nodes.length;i++){const r=t.nodes[i],a=new He(r.name);a.setLocalPosition(r.position[0],r.position[1],r.position[2]),a.setLocalEulerAngles(r.rotation[0],r.rotation[1],r.rotation[2]),a.setLocalScale(r.scale[0],r.scale[1],r.scale[2]),a.scaleCompensation=!!r.scaleCompensation,s.push(a)}for(i=1;i<t.parents.length;i++)s[t.parents[i]].addChild(s[i]);return s}_parseSkins(e,t){const s=e.model,i=[],r=[];let a,n;for(a=0;a<s.skins.length;a++){const o=s.skins[a],c=[];for(n=0;n<o.inverseBindMatrices.length;n++){const f=o.inverseBindMatrices[n];c[n]=new Z().set(f)}const h=new ow(this._device,c,o.boneNames);i.push(h);const d=new $c(h),u=[];for(n=0;n<h.boneNames.length;n++){const f=h.boneNames[n],p=t[0].findByName(f);u.push(p)}d.bones=u,r.push(d)}return{skins:i,instances:r}}_getMorphVertexCount(e,t,s){for(let i=0;i<e.meshes.length;i++){const r=e.meshes[i];if(r.morph===t)return s[r.vertices].numVertices}}_parseMorphs(e,t,s){const i=e.model,r=[],a=[];let n,o,c,h,d,u;if(i.morphs){const f=function(p,m,_){const g=new Float32Array(_*3);for(let v=0;v<m.length;v++){const x=m[v]*3;g[x]=p[v*3],g[x+1]=p[v*3+1],g[x+2]=p[v*3+2]}return g};for(n=0;n<i.morphs.length;n++){for(h=i.morphs[n].targets,u=[],c=this._getMorphVertexCount(i,n,s),o=0;o<h.length;o++){const _=h[o].aabb,g=_.min,v=_.max,x=new Le(new E((v[0]+g[0])*.5,
17032(v[1]+g[1])*.5,(v[2]+g[2])*.5),new E((v[0]-g[0])*.5,(v[1]-g[1])*.5,(v[2]-g[2])*.5)),y=h[o].indices;let S=h[o].deltaPositions,T=h[o].deltaNormals;y&&(S=f(S,y,c),T=f(T,y,c)),d=new Mf({deltaPositions:S,deltaNormals:T,name:h[o].name,aabb:x}),u.push(d)}const p=new zg(u,this._device);r.push(p);const m=new dn(p);a.push(m)}}return{morphs:r,instances:a}}_parseVertexBuffers(e){const t=e.model,s=[],i={position:Ie,normal:Cs,tangent:Gi,blendWeight:ki,blendIndices:Bs,color:ns,texCoord0:Zs,texCoord1:pn,texCoord2:Uc,texCoord3:zc,texCoord4:Vc,texCoord5:Gc,texCoord6:Hc,texCoord7:Wc};for(let r=0;r<t.vertices.length;r++){const a=t.vertices[r],n=[];for(const u in a){const f=a[u];n.push({semantic:i[u],components:f.components,type:tW[f.type],normalize:i[u]===ns})}const o=new Us(this._device,n),c=a.position.data.length/a.position.components,h=new Hi(this._device,o,c),d=new jl(h);for(let u=0;u<c;u++){for(const f in a){const p=a[f];switch(p.components){case 1:d.element[i[f]].set(p.data[u]);break;case 2:d.element[i[f]].set(p.data[u*2],1-p.data[u*2+1]);break;case 3:d.element[i[f]].set(p.data[u*3],p.data[u*3+1],p.data[u*3+2]);break;case 4:d.element[i[f]].set(p.data[u*4],p.data[u*4+1],p.data[u*4+2],p.data[u*4+3]);break}}d.next()}d.end(),s.push(h)}return s}_parseIndexBuffers(e,t){const s=e.model;let i=null,r=null,a,n=0;for(a=0;a<s.meshes.length;a++){const c=s.meshes[a];c.indices!==void 0&&(n+=c.indices.length)}let o=0;for(a=0;a<t.length;a++)o=Math.max(o,t[a].numVertices);return n>0&&(o>65535?(i=new la(this._device,ra,n),r=new Uint32Array(i.lock())):(i=new la(this._device,Ni,n),r=new Uint16Array(i.lock()))),{buffer:i,data:r}}_parseMeshes(e,t,s,i,r,a){const n=e.model,o=[];let c=0;for(let h=0;h<n.meshes.length;h++){const d=n.meshes[h],u=d.aabb,f=u.min,p=u.max,m=new Le(new E((p[0]+f[0])*.5,(p[1]+f[1])*.5,(p[2]+f[2])*.5),new E((p[0]-f[0])*.5,(p[1]-f[1])*.5,(p[2]-f[2])*.5)),_=d.indices!==void 0,g=new at(this._device);g.vertexBuffer=i[d.vertices],g.indexBuffer[0]=_?r:null,g.primitive[0].type=eW[d.type],g.primitive[0].base=_?d.base+c:d.base,g.primitive[0].count=d.count,g.primitive[0].indexed=_,g.skin=d.skin!==void 0?t[d.skin]:null,g.morph=d.morph!==void 0?s[d.morph]:null,g.aabb=m,_&&(a.set(d.indices,c),c+=d.indices.length),o.push(g)}return r!==null&&r.unlock(),o}_parseMeshInstances(e,t,s,i,r,a,n){const o=e.model,c=[];let h;for(h=0;h<o.meshInstances.length;h++){const d=o.meshInstances[h],u=t[d.node],f=s[d.mesh],p=new Ne(f,this._defaultMaterial,u);if(f.skin){const m=i.indexOf(f.skin);p.skinInstance=r[m]}if(f.morph){const m=a.indexOf(f.morph);p.morphInstance=n[m]}c.push(p)}return c}}class iW extends dt{constructor(e){super(e,"model"),this._parsers=[],this.device=e.graphicsDevice,this.assets=e.assets,this.defaultMaterial=Zo(this.device),this.addParser(new sW(this),(t,s)=>ve.getExtension(t)===".json"),this.addParser(new JH(this),(t,s)=>ve.getExtension(t)===".glb")}load(e,t,s){typeof e=="string"&&(e={load:e,original:e});const i={retry:this.maxRetries>0,maxRetries:this.maxRetries};(e.load.startsWith("blob:")||e.load.startsWith("data:"))&&(ve.getExtension(e.original).toLowerCase()===".glb"?i.responseType=De.ResponseType.ARRAY_BUFFER:i.responseType=De.ResponseType.JSON),ht.get(e.load,i,(r,a)=>{if(t)if(r)t(`Error loading model: ${e.original} [${r}]`);else{for(let n=0;n<this._parsers.length;n++){const o=this._parsers[n];if(o.decider(e.original,a)){o.parser.parse(a,(c,h)=>{c?t(c):t(null,h)},s);return}}t("No parsers found")}})}open(e,t){return t}patch(e,t){if(!e.resource)return;const s=e.data,i=this;e.resource.meshInstances.forEach((r,a)=>{if(s.mapping){const n=function(d){d.resource?r.material=d.resource:(d.once("load",n),t.load(d)),d.once("remove",u=>{r.material===u.resource&&(r.material=i.defaultMaterial)})};if(!s.mapping[a]){r.material=i.defaultMaterial;return}const o=s.mapping[a].material,c=s.mapping[a].path;let h;if(o!==void 0)o?(h=t.get(o),h?n(h):t.once(`add:${o}`,n)):r.material=i.defaultMaterial;else if(c){const d=e.getAbsoluteUrl(s.mapping[a].path);h=t.getByUrl(d),h?n(h):t.once(`add:url:${d}`,n)}}})}addParser(e,t){this._parsers.push({parser:e,decider:t})}}class rW extends dt{constructor(e){super(e,"scene")}load(e,t){IC.load(e,this.maxRetries,t)}open(e,t){this._app.systems.script.preloading=!0;const i=new ev(this._app,!1).parse(t),r=this._app.scene;return r.root=i,this._app.applySceneSettings(t.settings),this._app.systems.script.preloading=!1,r}}class Wa{static _types=[];static push(e){Wa._types.push(e)}}const aW=new Set(["system","entity","create","destroy","swap","move","data","scripts","_scripts","_scriptsIndex","_scriptsData","enabled","_oldState","onEnable","onDisable","onPostStateChange","_onSetEnabled","_checkState","_onBeforeRemove","_onInitializeAttributes","_onInitialize","_onPostInitialize","_onUpdate","_onPostUpdate","_callbacks","_callbackActive","has","get","on","off","fire","once","hasEvent","worker"]),nW={};
17032eh.reservedNames.forEach((l,e,t)=>{nW[l]=1});function oW(l,e,t){if(typeof l!="function")throw new Error(`script class: '${l}' must be a constructor function (i.e. class).`);if(!(l.prototype instanceof xu))throw new Error(`script class: '${Zl.__getScriptName(l)}' does not extend pc.Script.`);if(e=e||l.__name||Zl.__getScriptName(l),aW.has(e))throw new Error(`script name: '${e}' is reserved, please change script name`);l.__name=e,Ts.getApplication().scripts.add(l),Wa.push(l)}const lW=l=>l[0].toLowerCase()+l.substring(1);class cW extends dt{constructor(e){super(e,"script"),this._scripts={},this._cache={}}clearCache(){for(const e in this._cache){const t=this._cache[e],s=t.parentNode;s&&s.removeChild(t)}this._cache={}}load(e,t){typeof e=="string"&&(e={load:e,original:e});const s=this;this._app;const i=(e.load,(n,o,c)=>{if(n)t(n);else{const h={};for(let u=0;u<Wa._types.length;u++)h[Wa._types[u].name]=Wa._types[u];Wa._types.length=0,t(null,h,c);const d=o.split("&hash=")[0];delete s._loader._cache[Co.makeKey(d,"script")]}}),[r]=e.load.split("?");r.endsWith(".mjs")?this._loadModule(r,i):this._loadScript(e.load,i)}open(e,t){return t}patch(e,t){}_loadScript(e,t){const s=document.head,i=document.createElement("script");this._cache[e]=i,i.async=!1,i.addEventListener("error",a=>{t(`Script: ${a.target.src} failed to load`)},!1);let r=!1;i.onload=i.onreadystatechange=function(){!r&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")&&(r=!0,t(null,e,i))},i.src=e,s.appendChild(i)}_loadModule(e,t){const i=Ce.browser&&window.location.origin!=="null"?window.location.origin+window.location.pathname:import.meta.url,r=new URL(e,i);import(r.toString()).then(a=>{const n=r.pathname.split("/").pop(),o=this._app.assets.find(n,"script")?.data?.scripts;for(const c in a){const h=a[c];if(h.prototype instanceof xu){const u=lW(h.name);h.scriptName;const f=h.scriptName??u;oW(h,f),o&&this._app.scripts.addSchema(f,o[f])}}t(null,e,null)}).catch(a=>{t(a)})}}class hW extends dt{decoder=null;constructor(e){super(e,"shader")}load(e,t){typeof e=="string"&&(e={load:e,original:e}),ht.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(s,i)=>{s?t(`Error loading shader resource: ${e.original} [${s}]`):t(null,i)})}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)}}function xm(l){const e=this;e.resource&&(e.resource.atlas=l.resource)}function Tm(l){this.registry.load(l)}class dW extends dt{constructor(e){super(e,"sprite"),this._assets=e.assets,this._device=e.graphicsDevice}load(e,t){typeof e=="string"&&(e={load:e,original:e}),ve.getExtension(e.original)===".json"&&ht.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(s,i)=>{s?t(s):t(null,i)})}open(e,t){const s=new wM(this._device);return e&&(s.__data=t),s}patch(e,t){const s=e.resource;if(s.__data&&(e.data.pixelsPerUnit=s.__data.pixelsPerUnit,e.data.renderMode=s.__data.renderMode,e.data.frameKeys=s.__data.frameKeys,s.__data.textureAtlasAsset)){const i=t.getByUrl(s.__data.textureAtlasAsset);i?e.data.textureAtlasAsset=i.id:console.warn(`Could not find textureatlas with url: ${s.__data.textureAtlasAsset}`)}s.startUpdate(),s.renderMode=e.data.renderMode,s.pixelsPerUnit=e.data.pixelsPerUnit,s.frameKeys=e.data.frameKeys,this._updateAtlas(e),s.endUpdate(),e.off("change",this._onAssetChange,this),e.on("change",this._onAssetChange,this)}_updateAtlas(e){const t=e.resource;if(!e.data.textureAtlasAsset){t.atlas=null;return}this._assets.off(`load:${e.data.textureAtlasAsset}`,xm,e),this._assets.on(`load:${e.data.textureAtlasAsset}`,xm,e);const s=this._assets.get(e.data.textureAtlasAsset);s&&s.resource?t.atlas=s.resource:s?this._assets.load(s):(this._assets.off(`add:${e.data.textureAtlasAsset}`,Tm,e),this._assets.on(`add:${e.data.textureAtlasAsset}`,Tm,e))}_onAssetChange(e,t,s,i){t==="data"&&s&&s.textureAtlasAsset&&i&&s.textureAtlasAsset!==i.textureAtlasAsset&&(this._assets.off(`load:${i.textureAtlasAsset}`,xm,e),this._assets.off(`add:${i.textureAtlasAsset}`,Tm,e))}}class X0{_app;_data;_templateRoot=null;constructor(e,t){this._app=e,this._data=t}instantiate(){return this._templateRoot||this._parseTemplate(),this._templateRoot.clone()}_parseTemplate(){const e=new ev(this._app,!0);this._templateRoot=e.parse(this._data)}set data(e){this._data=e,this._templateRoot=null}get data(){return this._data}}class uW extends dt{decoder=null;constructor(e){super(e,"template")}load(e,t){typeof e=="string"&&(e={load:e,original:e});const s={retry:this.maxRetries>0,maxRetries:this.maxRetries};ht.get(e.load,s,(i,r)=>{i?t(`Error requesting template: ${e.original}`):t(i,r)})}open(e,t){return new X0(this._app,t)}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),new X0(this._app,JSON.parse(this.decoder.decode(e)))}patch(e,t){if(!e||!e.resource||!e.data||!e.data.entities)return;const s=e.resource;s.data=e.data}}class fW extends dt{decoder=null;constructor(e){super(e,"text")}load(e,t){typeof e=="string"&&(e={load:e,original:e}),ht.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(s,i)=>{s?t(`Error loading text resource: ${e.original} [${s}]`):t(null,i)})}openBinary(e){return this.decoder??(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)}}const hd={repeat:Ft,clamp:ue,mirror:Iu},dd={nearest:Fe,linear:It,nearest_mip_nearest:Ac,linear_mip_nearest:Ic,nearest_mip_linear:Pc,linear_mip_linear:ia},pW=/^data\.frames\.(\d+)$/;class mW extends dt{constructor(e){super(e,"textureatlas"),this._loader=e.loader}load(e,t){typeof e=="string"&&(e={load:e,original:e});const s=this,i=this._loader.getHandler("texture");ve.getExtension(e.original)===".json"?ht.get(e.load,{retry:this.maxRetries>0,maxRetries:this.maxRetries},(r,a)=>{if(r)t(r);else{const n=e.original.replace(".json",".png");s._loader.load(n,"texture",(o,c)=>{o?t(o):t(null,{data:a,texture:c})})}}):i.load(e,t)}open(e,t,s){const i=new CM;if(t.texture&&t.data)i.texture=t.texture,i.__data=t.data;else{const a=this._loader.getHandler("texture").open(e,t,s);if(!a)return null;i.texture=a}return i}patch(e,t){if(!e.resource)return;e.resource.__data&&(e.resource.__data.minfilter!==void 0&&(e.data.minfilter=e.resource.__data.minfilter),e.resource.__data.magfilter!==void 0&&(e.data.magfilter=e.resource.__data.magfilter),e.resource.__data.addressu!==void 0&&(e.data.addressu=e.resource.__data.addressu),e.resource.__data.addressv!==void 0&&(e.data.addressv=e.resource.__data.addressv),e.resource.__data.mipmaps!==void 0&&(e.data.mipmaps=e.resource.__data.mipmaps),e.resource.__data.anisotropy!==void 0&&(e.data.anisotropy=e.resource.__data.anisotropy),e.resource.__data.rgbm!==void 0&&(e.data.rgbm=!!e.resource.__data.rgbm),e.data.frames=e.resource.__data.frames,delete e.resource.__data);const s=e.resource.texture;if(s&&(s.name=e.name,e.data.hasOwnProperty("minfilter")&&s.minFilter!==dd[e.data.minfilter]&&(s.minFilter=dd[e.data.minfilter]),e.data.hasOwnProperty("magfilter")&&s.magFilter!==dd[e.data.magfilter]&&(s.magFilter=dd[e.data.magfilter]),e.data.hasOwnProperty("addressu")&&s.addressU!==hd[e.data.addressu]&&(s.addressU=hd[e.data.addressu]),e.data.hasOwnProperty("addressv")&&s.addressV!==hd[e.data.addressv]&&(s.addressV=hd[e.data.addressv]),e.data.hasOwnProperty("mipmaps")&&s.mipmaps!==e.data.mipmaps&&(s.mipmaps=e.data.mipmaps),e.data.hasOwnProperty("anisotropy")&&s.anisotropy!==e.data.anisotropy&&(s.anisotropy=e.data.anisotropy),e.data.hasOwnProperty("rgbm"))){const r=e.data.rgbm?wr:Qs;s.type!==r&&(s.type=r)}e.resource.texture=s;const i={};for(const r in e.data.frames){const a=e.data.frames[r];i[r]={rect:new ie(a.rect),pivot:new j(a.pivot),border:new ie(a.border)}}e.resource.frames=i,e.off("change",this._onAssetChange,this),e.on("change",this._onAssetChange,this)}
17032_onAssetChange(e,t,s){let i;if(t==="data"||t==="data.frames"){const r={};for(const a in s.frames)i=s.frames[a],r[a]={rect:new ie(i.rect),pivot:new j(i.pivot),border:new ie(i.border)};e.resource.frames=r}else{const r=t.match(pW);if(r){const a=r[1];s?(e.resource.frames[a]?(i=e.resource.frames[a],i.rect.set(s.rect[0],s.rect[1],s.rect[2],s.rect[3]),i.pivot.set(s.pivot[0],s.pivot[1]),i.border.set(s.border[0],s.border[1],s.border[2],s.border[3])):e.resource.frames[a]={rect:new ie(s.rect),pivot:new j(s.pivot),border:new ie(s.border)},e.resource.fire("set:frame",a,e.resource.frames[a])):e.resource.frames[a]&&(delete e.resource.frames[a],e.resource.fire("remove:frame",a))}}}}function _W(){const l={cTFETC1:0,cTFETC2:1,cTFBC1:2,cTFBC3:3,cTFPVRTC1_4_RGB:8,cTFPVRTC1_4_RGBA:9,cTFASTC_4x4:10,cTFATC_RGB:11,cTFATC_RGBA_INTERPOLATED_ALPHA:12,cTFRGBA32:13,cTFRGB565:14,cTFRGBA4444:16},e={astc:l.cTFASTC_4x4,dxt:l.cTFBC1,etc1:l.cTFETC1,etc2:l.cTFETC1,pvr:l.cTFPVRTC1_4_RGB,atc:l.cTFATC_RGB,none:l.cTFRGB565},t={astc:l.cTFASTC_4x4,dxt:l.cTFBC3,etc1:l.cTFRGBA4444,etc2:l.cTFETC2,pvr:l.cTFPVRTC1_4_RGBA,atc:l.cTFATC_RGBA_INTERPOLATED_ALPHA,none:l.cTFRGBA4444},s={ETC1:21,ETC2_RGB:22,ETC2_RGBA:23,DXT1:8,DXT5:10,PVRTC_4BPP_RGB_1:26,PVRTC_4BPP_RGBA_1:27,ASTC_4x4:28,ATC_RGB:29,ATC_RGBA:30,R8_G8_B8_A8:7,R5_G6_B5:3,R4_G4_B4_A4:5},i=(y,S)=>{switch(y){case l.cTFETC1:return S.formats.etc2?s.ETC2_RGB:s.ETC1;case l.cTFETC2:return s.ETC2_RGBA;case l.cTFBC1:return s.DXT1;case l.cTFBC3:return s.DXT5;case l.cTFPVRTC1_4_RGB:return s.PVRTC_4BPP_RGB_1;case l.cTFPVRTC1_4_RGBA:return s.PVRTC_4BPP_RGBA_1;case l.cTFASTC_4x4:return s.ASTC_4x4;case l.cTFATC_RGB:return s.ATC_RGB;case l.cTFATC_RGBA_INTERPOLATED_ALPHA:return s.ATC_RGBA;case l.cTFRGBA32:return s.R8_G8_B8_A8;case l.cTFRGB565:return s.R5_G6_B5;case l.cTFRGBA4444:return s.R4_G4_B4_A4}},r=y=>{const S=function(T,w){const C=T*.00784313725490196-1,b=w*(2/255)-1,I=Math.sqrt(1-Math.min(1,C*C+b*b));return Math.max(0,Math.min(255,Math.floor((I+1)*.5*255)))};for(let T=0;T<y.length;T+=4){const w=y[T+3],C=y[T+1];y[T+0]=w,y[T+2]=S(w,C),y[T+3]=255}return y},a=y=>{const S=new Uint16Array(y.length/4);for(let T=0;T<y.length;T+=4){const w=y[T+0],C=y[T+1],b=y[T+2];S[T/4]=(w&248)<<8|(C&252)<<3|b>>3}return S},n=(y,S)=>(y&y-1)===0&&(S&S-1)===0,o=()=>typeof performance<"u"?performance.now():0;let c,h,d;const u=(y,S,T)=>{if(T){if(y.formats.astc)return"astc"}else if(S){if(y.formats.etc2)return"etc2"}else{if(y.formats.etc2)return"etc2";if(y.formats.etc1)return"etc1"}return(C=>{for(let b=0;b<C.length;++b){const I=C[b];if(y.formats[I])return I}return"none"})(S?d:h)},f=(y,S,T)=>{switch(T){case l.cTFETC1:case l.cTFETC2:return!0;case l.cTFBC1:case l.cTFBC3:return(y&3)===0&&(S&3)===0;case l.cTFPVRTC1_4_RGB:case l.cTFPVRTC1_4_RGBA:return n(y,S);case l.cTFASTC_4x4:return!0;case l.cTFATC_RGB:case l.cTFATC_RGBA_INTERPOLATED_ALPHA:return!0}return!1},p=(y,S,T)=>{if(!c.KTX2File)throw new Error("Basis transcoder module does not include support for KTX2.");const w=o(),C=new c.KTX2File(new Uint8Array(S)),b=C.getWidth(),I=C.getHeight(),P=C.getLevels(),L=!!C.getHasAlpha(),O=C.isUASTC&&C.isUASTC();if(!b||!I||!P)throw C.close(),C.delete(),new Error(`Invalid image dimensions url=${y} width=${b} height=${I} levels=${P}`);const D=u(T.deviceDetails,L,O),N=!!T.isGGGR&&D==="pvr";let k;if(N?k=l.cTFRGBA32:(k=L?t[D]:e[D],f(b,I,k)||(k=L?l.cTFRGBA32:l.cTFRGB565)),!C.startTranscoding())throw C.close(),C.delete(),new Error(`Failed to start transcoding url=${y}`);let A;const M=[];for(let R=0;R<P;++R){const F=C.getImageTranscodedSizeInBytes(R,0,0,k),U=new Uint8Array(F);if(!C.transcodeImage(U,R,0,0,k,0,-1,-1))throw C.close(),C.delete(),new Error(`Failed to transcode image url=${y}`);const B=k===l.cTFRGB565||k===l.cTFRGBA4444;M.push(B?new Uint16Array(U.buffer):U)}if(C.close(),C.delete(),N)for(k=l.cTFRGB565,A=0;A<M.length;++A)M[A]=a(r(M[A]));return{format:i(k,T.deviceDetails),width:b,height:I,levels:M,cubemap:!1,transcodeTime:o()-w,url:y,unswizzledGGGR:N}},m=(y,S,T)=>{const w=o(),C=new c.BasisFile(new Uint8Array(S)),b=C.getImageWidth(0,0),I=C.getImageHeight(0,0),P=C.getNumImages(),L=C.getNumLevels(0),O=!!C.getHasAlpha(),D=C.isUASTC&&C.isUASTC();if(!b||!I||!P||!L)throw C.close(),C.delete(),new Error(`Invalid image dimensions url=${y} width=${b} height=${I} images=${P} levels=${L}`);const N=u(T.deviceDetails,O,D),k=!!T.isGGGR&&N==="pvr";let A;if(k?A=l.cTFRGBA32:(A=O?t[N]:e[N],f(b,I,A)||(A=O?l.cTFRGBA32:l.cTFRGB565)),!C.startTranscoding())throw C.close(),C.delete(),new Error(`Failed to start transcoding url=${y}`);let M;const R=[];for(let F=0;F<L;++F){const U=C.getImageTranscodedSizeInBytes(0,F,A),B=new Uint8Array(U);if(!C.transcodeImage(B,0,F,A,0,0))if(F===L-1&&U===R[F-1].buffer.byteLength)B.set(new Uint8Array(R[F-1].buffer)),console.warn(`Failed to transcode last mipmap level, using previous level instead url=${y}`);else throw C.close(),C.delete(),new Error(`Failed to transcode image url=${y}`);const z=A===l.cTFRGB565||A===l.cTFRGBA4444;R.push(z?new Uint16Array(B.buffer):B)}if(C.close(),C.delete(),k)for(A=l.cTFRGB565,M=0;M<R.length;++M)R[M]=a(r(R[M]));return{format:i(A,T.deviceDetails),width:b,height:I,levels:R,cubemap:!1,transcodeTime:o()-w,url:y,unswizzledGGGR:k}},_=(y,S,T)=>T.isKTX2?p(y,S,T):m(y,S,T),g=(y,S,T)=>{try{const w=_(y,S,T);w.levels=w.levels.map(C=>C.buffer),self.postMessage({url:y,data:w},w.levels)}catch(w){self.postMessage({url:y,err:w}
17032,null)}},v=(y,S)=>{const T=(w,C)=>(WebAssembly.instantiate(y.module,w).then(b=>{C(b)}).catch(b=>{console.error(`instantiate failed + ${b}`)}),{});self.BASIS(y.module?{instantiateWasm:T}:null).then(w=>{w.initializeBasis(),c=w,h=y.rgbPriority,d=y.rgbaPriority,S(null)})},x=[];self.onmessage=y=>{const S=y.data;switch(S.type){case"init":v(S.config,()=>{for(let T=0;T<x.length;++T)g(x[T].url,x[T].data,x[T].options);x.length=0});break;case"transcode":c?g(S.url,S.data,S.options):x.push(S);break}}}const gW=l=>({astc:!!l.extCompressedTextureASTC,atc:!!l.extCompressedTextureATC,dxt:!!l.extCompressedTextureS3TC,etc1:!!l.extCompressedTextureETC1,etc2:!!l.extCompressedTextureETC,pvr:!!l.extCompressedTexturePVRTC}),vW=(l,e)=>{const t=a=>{const n=["/* basis */",a,"",`(${_W.toString()})() 17033 17034`].join(` 17035`);return new Blob([n],{type:"application/javascript"})},s=()=>{try{if(typeof WebAssembly=="object"&&typeof WebAssembly.instantiate=="function"){const a=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(a instanceof WebAssembly.Module)return new WebAssembly.Instance(a)instanceof WebAssembly.Instance}}catch{}return!1},i=(a,n)=>{e(null,{workerUrl:URL.createObjectURL(t(a)),module:n,rgbPriority:l.rgbPriority,rgbaPriority:l.rgbaPriority})},r={cache:!0,responseType:"text",retry:l.maxRetries>0,maxRetries:l.maxRetries};if(l.glueUrl&&l.wasmUrl&&s()){let a=null,n=null;ht.get(l.glueUrl,r,(h,d)=>{h?e(h):n?i(d,n):a=d});const o=fetch(l.wasmUrl),c=()=>{o.then(h=>h.arrayBuffer()).then(h=>WebAssembly.compile(h)).then(h=>{a?i(a,h):n=h}).catch(h=>{e(h,null)})};WebAssembly.compileStreaming?WebAssembly.compileStreaming(o).then(h=>{a?i(a,h):n=h}).catch(h=>{c()}):c()}else ht.get(l.fallbackUrl,r,(a,n)=>{a?e(a,null):i(n,null)})};class SW{constructor(){this.callbacks={},this.queue=[],this.clients=[]}enqueueJob(e,t,s,i){if(this.callbacks.hasOwnProperty(e))this.callbacks[e].push(s);else{this.callbacks[e]=[s];const r={url:e,data:t,options:i};this.clients.length>0?this.clients.shift().run(r):this.queue.push(r)}}enqueueClient(e){this.queue.length>0?e.run(this.queue.shift()):this.clients.push(e)}handleResponse(e,t,s){const i=this.callbacks[e];if(t)for(let r=0;r<i.length;++r)i[r](t);else{s.format===Dc||s.format===Mc?s.levels=s.levels.map(r=>new Uint16Array(r)):s.levels=s.levels.map(r=>new Uint8Array(r));for(let r=0;r<i.length;++r)i[r](null,s)}delete this.callbacks[e]}}class yW{constructor(e,t,s){this.queue=e,this.worker=new Worker(t.workerUrl),this.worker.addEventListener("message",i=>{const r=i.data;this.queue.handleResponse(r.url,r.err,r.data),this.eager||this.queue.enqueueClient(this)}),this.worker.postMessage({type:"init",config:t}),this.eager=s}run(e){const t=[];e.data instanceof ArrayBuffer&&t.push(e.data),this.worker.postMessage({type:"transcode",url:e.url,format:e.format,data:e.data,options:e.options},t),this.eager&&this.queue.enqueueClient(this)}}const xW=1,TW=["etc2","etc1","astc","dxt","pvr","atc"],wW=["astc","dxt","etc2","pvr","atc"],CW=5,N_=new SW;let Y0=null,k_=!1;function EW(l){if(!k_){if(!l)l=Y0||{};else if(l.lazyInit){Y0=l;return}if(!l.glueUrl||!l.wasmUrl||!l.fallbackUrl){const e=Ix.getConfig("BASIS");e&&(l={glueUrl:e.glueUrl,wasmUrl:e.wasmUrl,fallbackUrl:e.fallbackUrl,numWorkers:e.numWorkers})}if(l.glueUrl||l.wasmUrl||l.fallbackUrl){k_=!0;const e=Math.max(1,Math.min(16,l.numWorkers||xW)),t=l.numWorkers===1||(l.hasOwnProperty("eagerWorkers")?l.eagerWorkers:!0);l.rgbPriority=l.rgbPriority||TW,l.rgbaPriority=l.rgbaPriority||wW,l.maxRetries=l.hasOwnProperty("maxRetries")?l.maxRetries:CW,vW(l,(s,i)=>{if(s)console.error(`failed to initialize basis worker: ${s}`);else for(let r=0;r<e;++r)N_.enqueueClient(new yW(N_,i,t))})}}}let wm=null;function DC(l,e,t,s,i){return EW(),wm||(wm={formats:gW(l)}),N_.enqueueJob(e,t,s,{deviceDetails:wm,isGGGR:!!i?.isGGGR,isKTX2:!!i?.isKTX2}),k_}class Jo{load(e,t,s){throw new Error("not implemented")}open(e,t,s){throw new Error("not implemented")}}class bW extends Jo{constructor(e,t){super(),this.device=t,this.maxRetries=0}load(e,t,s){const i=this.device,r=a=>{DC(i,e.load,a,t,{isGGGR:(s?.file?.variants?.basis?.opt&8)!==0})||t(`Basis module not found. Asset [${s.name}](${s.getFileUrl()}) basis texture variant will not be loaded.`)};pe.fetchArrayBuffer(e.load,(a,n)=>{a?t(a):r(n)},s,this.maxRetries)}open(e,t,s,i={}){const r=i.srgb?of(t.format):t.format,a=new ce(s,{name:e,addressU:t.cubemap?ue:Ft,addressV:t.cubemap?ue:Ft,width:t.width,height:t.height,format:r,cubemap:t.cubemap,levels:t.levels,...i});return a.upload(),a}}class AW extends Jo{constructor(e,t){super(),this.crossOrigin=e.prefix?"anonymous":null,this.maxRetries=0,this.device=t}load(e,t,s){const i=!!s?.file?.contents;if(i){if(this.device.supportsImageBitmap){this._loadImageBitmapFromBlob(new Blob([s.file.contents]),t);return}e={load:URL.createObjectURL(new Blob([s.file.contents])),original:e.original}}const r=(n,o)=>{i&&URL.revokeObjectURL(e.load),t(n,o)};let a;s&&s.options&&s.options.hasOwnProperty("crossOrigin")?a=s.options.crossOrigin:Vo.test(e.load)&&(a=this.crossOrigin),this.device.supportsImageBitmap?this._loadImageBitmap(e.load,e.original,a,r,s):this._loadImage(e.load,e.original,a,r,s)}open(e,t,s,i={}){const r=new ce(s,{name:e,width:t.width,height:t.height,format:i.srgb?us:Re,...i});return r.setSource(t),r}_loadImage(e,t,s,i,r){const a=new Image;s&&(a.crossOrigin=s);let n=0;const o=this.maxRetries;let c;const h=1024*1024;r?.fire("progress",0,h),a.onload=function(){r?.fire("progress",h,h),i(null,a)},a.onerror=function(){if(!c)if(o>0&&++n<=o){const d=Math.pow(2,n)*100;console.log(`Error loading Texture from: '${t}' - Retrying in ${d}ms...`);const f=e.indexOf("?")>=0?"&":"?";c=setTimeout(()=>{a.src=`${e+f}retry=${Date.now()}`,c=null},d)}else i(`Error loading Texture from: '${t}'`)},a.src=e}_loadImageBitmap(e,t,s,i,r){const a={cache:!0,responseType:"blob",retry:this.maxRetries>0,maxRetries:this.maxRetries,progress:r};ht.get(e,a,(n,o)=>{n?i(n):this._loadImageBitmapFromBlob(o,i)})}_loadImageBitmapFromBlob(e,t){createImageBitmap(e,{premultiplyAlpha:"none",colorSpaceConversion:"none"}).then(s=>
17035t(null,s)).catch(s=>t(s))}}const Cm=[1481919403,3140563232,169478669],PW={33776:Rc,33778:Ru,33779:Ho,36196:Fc,37492:Ou,37496:Bu,35840:Oc,35841:Wo,35842:Bc,35843:Xo,32849:Er,32856:Re,35905:Fu,35907:us,35898:tn,34843:Lc,34842:Ge};function IW(l,e,t,s){return l===tn?new Uint32Array(e,t,s/4):new Uint8Array(e,t,s)}class DW extends Jo{constructor(e){super(),this.maxRetries=0}load(e,t,s){pe.fetchArrayBuffer(e.load,t,s,this.maxRetries)}open(e,t,s,i={}){const r=this.parse(t);if(!r)return null;const a=i.srgb?of(r.format):r.format,n=new ce(s,{name:e,addressU:r.cubemap?ue:Ft,addressV:r.cubemap?ue:Ft,width:r.width,height:r.height,format:a,cubemap:r.cubemap,levels:r.levels,...i});return n.upload(),n}parse(e){const t=new Uint32Array(e);if(Cm[0]!==t[0]||Cm[1]!==t[1]||Cm[2]!==t[2])return null;const s={endianness:t[3],glType:t[4],glTypeSize:t[5],glFormat:t[6],glInternalFormat:t[7],glBaseInternalFormat:t[8],pixelWidth:t[9],pixelHeight:t[10],pixelDepth:t[11],numberOfArrayElements:t[12],numberOfFaces:t[13],numberOfMipmapLevels:t[14],bytesOfKeyValueData:t[15]};if(s.pixelDepth>1||s.numberOfArrayElements!==0)return null;const i=PW[s.glInternalFormat];if(i===void 0)return null;let r=16+s.bytesOfKeyValueData/4;const a=s.numberOfFaces>1,n=[];for(let o=0;o<(s.numberOfMipmapLevels||1);o++){const c=t[r++];a&&n.push([]);const h=a?n[o]:n;for(let d=0;d<(a?6:1);++d)h.push(IW(i,e,r*4,c)),r+=c+3>>2}return{format:i,width:s.pixelWidth,height:s.pixelHeight,levels:n,cubemap:a}}}const MW={KHR_DF_MODEL_UASTC:166};class RW extends Jo{constructor(e,t){super(),this.maxRetries=0,this.device=t}load(e,t,s){pe.fetchArrayBuffer(e.load,(i,r)=>{i?t(i,r):this.parse(r,e,t,s)},s,this.maxRetries)}open(e,t,s,i={}){const r=i.srgb?of(t.format):t.format,a=new ce(s,{name:e,addressU:t.cubemap?ue:Ft,addressV:t.cubemap?ue:Ft,width:t.width,height:t.height,format:r,cubemap:t.cubemap,levels:t.levels,...i});return a.upload(),a}parse(e,t,s,i){const r=new Dx(e),a=[r.readU32be(),r.readU32be(),r.readU32be()];if(a[0]!==2873840728||a[1]!==540160187||a[2]!==218765834)return null;const n={vkFormat:r.readU32(),typeSize:r.readU32(),pixelWidth:r.readU32(),pixelHeight:r.readU32(),pixelDepth:r.readU32(),layerCount:r.readU32(),faceCount:r.readU32(),levelCount:r.readU32(),supercompressionScheme:r.readU32()},o={dfdByteOffset:r.readU32(),dfdByteLength:r.readU32(),kvdByteOffset:r.readU32(),kvdByteLength:r.readU32(),sgdByteOffset:r.readU64(),sgdByteLength:r.readU64()},c=[];for(let u=0;u<Math.max(1,n.levelCount);++u)c.push({byteOffset:r.readU64(),byteLength:r.readU64(),uncompressedByteLength:r.readU64()});if(r.readU32()!==o.kvdByteOffset-o.dfdByteOffset)return null;r.skip(8);const d=r.readU8();r.skip(o.dfdByteLength-9),r.skip(o.kvdByteLength),n.supercompressionScheme===1||d===MW.KHR_DF_MODEL_UASTC?DC(this.device,t.load,e,s,{isGGGR:(i?.file?.variants?.basis?.opt&8)!==0,isKTX2:!0})||s(`Basis module not found. Asset [${i.name}](${i.getFileUrl()}) basis texture variant will not be loaded.`):s("unsupported KTX2 pixel format")}}class LW extends Jo{constructor(e){super(),this.maxRetries=0}load(e,t,s){pe.fetchArrayBuffer(e.load,t,s,this.maxRetries)}open(e,t,s,i={}){const r=new Uint32Array(t,0,32),a=r[4],n=r[3],o=Math.max(r[7],1),c=r[20]===4,h=r[21],d=r[22],u=r[28]===65024,f=827611204,p=894720068,m=113,_=116,g=826496069,v=825438800,x=825504336,y=825439312,S=825504848;let T=!1,w=!1,C=!1,b=!1,I=null,P=1,L;if(c?h===f?(I=Rc,T=!0):h===p?(I=Ho,T=!0):h===m?(I=Ge,P=2):h===_?(I=mt,P=4):h===g?(I=Fc,T=!0,w=!0):h===v||h===x?(I=h===v?Wo:Xo,T=!0,C=!0):(h===y||h===S)&&(I=h===y?Oc:Bc,T=!0,b=!0):d===32&&(I=Re),!I)return L=new ce(s,{width:4,height:4,format:Er,name:"dds-legacy-empty"}),L;L=new ce(s,{name:e,addressU:u?ue:Ft,addressV:u?ue:Ft,width:a,height:n,format:I,cubemap:u,mipmaps:o>1,...i});let O=128;const D=u?6:1;let N;const k=4,A=4,M=h===f?8:16;let R,F,U;for(let B=0;B<D;B++){let z=a,$=n;for(let K=0;K<o;K++){T?w?N=Math.floor((z+3)/4)*Math.floor(($+3)/4)*8:C?N=Math.max(z,16)*Math.max($,8)/4:b?N=Math.max(z,8)*Math.max($,8)/2:(R=Math.floor((z+k-1)/k),F=Math.floor(($+A-1)/A),U=R*F,N=U*M):N=z*$*4;const Y=I===mt?new Float32Array(t,O,N):I===Ge?new Uint16Array(t,O,N):new Uint8Array(t,O,N);u?(L._levels[K]||(L._levels[K]=[]),L._levels[K][B]=Y):L._levels[K]=Y,O+=N*P,z=Math.max(z*.5,1),$=Math.max($*.5,1)}}return L.upload(),L}}class FW extends Jo{constructor(e){super(),this.maxRetries=0}load(e,t,s){pe.fetchArrayBuffer(e.load,t,s,this.maxRetries),s.data&&!s.data.type&&(s.data.type=eu)}open(e,t,s,i={}){const r=this.parse(t);if(!r)return null;const a=new ce(s,{name:e,addressU:Ft,addressV:ue,minFilter:Fe,magFilter:Fe,width:r.width,height:r.height,levels:r.levels,format:Re,type:eu,mipmaps:!1,...i});return a.upload(),a}parse(e){const t=new Dx(e);if(!t.readLine().startsWith("#?RADIANCE"))return null;const i={};for(;;){const c=t.readLine();if(c.length===0)break;{const h=c.split("=");h.length===2&&(i[h[0]]=h[1])}}if(!i.hasOwnProperty("FORMAT"))return null;const r=t.readLine().split(" ");if(r.length!==4)return null;const a=parseInt(r[1],10),n=parseInt(r[3],10),o=this._readPixels(t,n,a,r[0]==="-Y");return o?{width:n,height:a,levels:[o]}:null}_readPixels(e,t,s,i){if(t<8||t>
1703532767)return this._readPixelsFlat(e,t,s);const r=[0,0,0,0];if(e.readArray(r),r[0]!==2||r[1]!==2||(r[2]&128)!==0)return e.skip(-4),this._readPixelsFlat(e,t,s);const a=new ArrayBuffer(t*s*4),n=new Uint8Array(a);let o=i?0:t*4*(s-1),c,h,d,u,f,p;for(h=0;h<s;++h){if(h&&e.readArray(r),(r[2]<<8)+r[3]!==t)return null;for(u=0;u<4;++u)for(c=0;c<t;)if(f=e.readU8(),f>128){if(f-=128,c+f>t)return null;for(p=e.readU8(),d=0;d<f;++d)n[o+u+4*c++]=p}else{if(f===0||c+f>t)return null;for(d=0;d<f;++d)n[o+u+4*c++]=e.readU8()}o+=t*4*(i?1:-1)}return n}_readPixelsFlat(e,t,s){return e.remainingBytes===t*s*4?new Uint8Array(e.arraybuffer,e.offset):null}}const j0={repeat:Ft,clamp:ue,mirror:Iu},q0={nearest:Fe,linear:It,nearest_mip_nearest:Ac,linear_mip_nearest:Ic,nearest_mip_linear:Pc,linear_mip_linear:ia},OW={default:Qs,rgbm:wr,rgbe:eu,rgbp:ac,swizzleGGGR:nc},BW=function(l){const e=Xt.calcMipLevelsCount(l._width,l._height),t=function(i){return i instanceof HTMLCanvasElement||i instanceof HTMLImageElement||i instanceof HTMLVideoElement};if(!(l._format===Re||l._format===mt)||l._volume||l._compressed||l._levels.length===1||l._levels.length===e||t(l._cubemap?l._levels[0][0]:l._levels[0]))return;const s=function(i,r,a){const n=Math.max(1,i>>1),o=Math.max(1,r>>1),c=new a.constructor(n*o*4),h=Math.floor(i/n),d=Math.floor(r/o),u=h*d;for(let f=0;f<o;++f)for(let p=0;p<n;++p)for(let m=0;m<4;++m){let _=0;for(let g=0;g<d;++g)for(let v=0;v<h;
17035++v)_+=a[(p*h+v+(f*d+g)*i)*4+m];c[(p+f*n)*4+m]=_/u}return c};for(let i=l._levels.length;i<e;++i){const r=Math.max(1,l._width>>i-1),a=Math.max(1,l._height>>i-1);if(l._cubemap){const n=[];for(let o=0;o<6;++o)n.push(s(r,a,l._levels[i-1][o]));l._levels.push(n)}else l._levels.push(s(r,a,l._levels[i-1]))}l._levelsUpdated=l._cubemap?[[!0,!0,!0,!0,!0,!0]]:[!0]};class NW extends dt{constructor(e){super(e,"texture");const t=e.assets,s=e.graphicsDevice;this._device=s,this._assets=t,this.imgParser=new AW(t,s),this.parsers={dds:new LW(t),ktx:new DW(t),ktx2:new RW(t,s),basis:new bW(t,s),hdr:new FW(t)}}set crossOrigin(e){this.imgParser.crossOrigin=e}get crossOrigin(){return this.imgParser.crossOrigin}set maxRetries(e){this.imgParser.maxRetries=e;for(const t in this.parsers)this.parsers.hasOwnProperty(t)&&(this.parsers[t].maxRetries=e)}get maxRetries(){return this.imgParser.maxRetries}_getUrlWithoutParams(e){return e.indexOf("?")>=0?e.split("?")[0]:e}_getParser(e){const t=ve.getExtension(this._getUrlWithoutParams(e)).toLowerCase().replace(".","");return this.parsers[t]||this.imgParser}_getTextureOptions(e){const t={};if(e){e.name?.length>0&&(t.name=e.name);const s=e.data;s.hasOwnProperty("minfilter")&&(t.minFilter=q0[s.minfilter]),s.hasOwnProperty("magfilter")&&(t.magFilter=q0[s.magfilter]),s.hasOwnProperty("addressu")&&(t.addressU=j0[s.addressu]),s.hasOwnProperty("addressv")&&(t.addressV=j0[s.addressv]),s.hasOwnProperty("mipmaps")&&(t.mipmaps=s.mipmaps),s.hasOwnProperty("anisotropy")&&(t.anisotropy=s.anisotropy),s.hasOwnProperty("flipY")&&(t.flipY=!!s.flipY),s.hasOwnProperty("srgb")&&(t.srgb=!!s.srgb),t.type=Qs,s.hasOwnProperty("type")?t.type=OW[s.type]:s.hasOwnProperty("rgbm")&&s.rgbm?t.type=wr:e.file&&(e.file.opt&8)!==0&&(t.type=nc)}return t}load(e,t,s){typeof e=="string"&&(e={load:e,original:e}),this._getParser(e.original).load(e,t,s)}open(e,t,s){if(!e)return;const i=this._getTextureOptions(s);let r=this._getParser(e).open(e,t,this._device,i);return r===null?r=new ce(this._device,{width:4,height:4,format:Er}):(BW(r),t.unswizzledGGGR&&(s.file.variants.basis.opt&=-9)),r}patch(e,t){const s=e.resource;if(!s)return;const i=this._getTextureOptions(e);for(const r of Object.keys(i))s[r]=i[r]}}const kW="inline",UW="immersive-vr",Ql="immersive-ar",$0="viewer",zW="left",VW="cpu-optimized",MC="gpu-optimized",RC="luminance-alpha",LC="unsigned-short",FC="float32";class GW{_manager;_supported=Ce.browser&&!!window.XRDOMOverlayState;_root=null;constructor(e){this._manager=e}get supported(){return this._supported}get available(){return this._supported&&this._manager.active&&this._manager._session.domOverlayState!==null}get state(){return!this._supported||!this._manager.active||!this._manager._session.domOverlayState?null:this._manager._session.domOverlayState.type}set root(e){!this._supported||this._manager.active||(this._root=e)}get root(){return this._root}}const ud=[],K0=[];class HW extends ge{static EVENT_REMOVE="remove";static EVENT_RESULT="result";manager;_xrHitTestSource;_transient;_inputSource;constructor(e,t,s,i=null){super(),this.manager=e,this._xrHitTestSource=t,this._transient=s,this._inputSource=i}remove(){if(!this._xrHitTestSource)return;const e=this.manager.hitTest.sources,t=e.indexOf(this);t!==-1&&e.splice(t,1),this.onStop()}onStop(){this._xrHitTestSource.cancel(),this._xrHitTestSource=null,this.fire("remove"),this.manager.hitTest.fire("remove",this)}update(e){if(this._transient){const t=e.getHitTestResultsForTransientInput(this._xrHitTestSource);for(let s=0;s<t.length;s++){const i=t[s];if(!i.results.length)continue;let r;i.inputSource&&(r=this.manager.input._getByInputSource(i.inputSource)),this.updateHitResults(i.results,r)}}else{const t=e.getHitTestResults(this._xrHitTestSource);if(!t.length)return;this.updateHitResults(t)}}updateHitResults(e,t){if(this._inputSource&&this._inputSource!==t)return;const s=ud.pop()??new E;t?s.copy(t.getOrigin()):s.copy(this.manager.camera.getPosition());let i=1/0,r=null;const a=ud.pop()??new E,n=K0.pop()??new ae;for(let o=0;o<e.length;o++){const c=e[o].getPose(this.manager._referenceSpace),h=s.distance(c.transform.position);h>=i||(i=h,r=e[o],a.copy(c.transform.position),n.copy(c.transform.orientation))}this.fire("result",a,n,t||this._inputSource,r),this.manager.hitTest.fire("result",this,a,n,t||this._inputSource,r),ud.push(s),ud.push(a),K0.push(n)}}class WW extends ge{static EVENT_AVAILABLE="available";static EVENT_UNAVAILABLE="unavailable";static EVENT_ADD="add";static EVENT_REMOVE="remove";static EVENT_RESULT="result";static EVENT_ERROR="error";manager;_supported=Ce.browser&&!!(window.XRSession&&window.XRSession.prototype.requestHitTestSource);_available=!1;_checkingAvailability=!1;sources=[];constructor(e){super(),this.manager=e,this._supported&&(this.manager.on("start",this._onSessionStart,this),this.manager.on("end",this._onSessionEnd,this))}
17035_onSessionStart(){if(this.manager.session.enabledFeatures){const e=this.manager.session.enabledFeatures.indexOf("hit-test")!==-1;if(!e)return;this._available=e,this.fire("available")}else this._checkingAvailability||(this._checkingAvailability=!0,this.manager.session.requestReferenceSpace($0).then(e=>{this.manager.session.requestHitTestSource({space:e}).then(t=>{t.cancel(),this.manager.active&&(this._available=!0,this.fire("available"))}).catch(()=>{})}).catch(()=>{}))}_onSessionEnd(){if(this._available){this._available=!1;for(let e=0;e<this.sources.length;e++)this.sources[e].onStop();this.sources=[],this.fire("unavailable")}}start(e={}){if(!this._supported){e.callback?.(new Error("XR HitTest is not supported"),null);return}if(!this._available){e.callback?.(new Error("XR HitTest is not available"),null);return}!e.profile&&!e.spaceType&&(e.spaceType=$0);let t;const s=e.offsetRay;if(s){const r=new DOMPoint(s.origin.x,s.origin.y,s.origin.z,1),a=new DOMPoint(s.direction.x,s.direction.y,s.direction.z,0);t=new XRRay(r,a)}const i=e.callback;e.spaceType?this.manager.session.requestReferenceSpace(e.spaceType).then(r=>{if(!this.manager.session){const a=new Error("XR Session is not started (2)");i&&i(a),this.fire("error",a);return}this.manager.session.requestHitTestSource({space:r,entityTypes:e.entityTypes||void 0,offsetRay:t}).then(a=>{this._onHitTestSource(a,!1,e.inputSource,i)}).catch(a=>{i&&i(a),this.fire("error",a)})}).catch(r=>{i&&i(r),this.fire("error",r)}):this.manager.session.requestHitTestSourceForTransientInput({profile:e.profile,entityTypes:e.entityTypes||void 0,offsetRay:t}).then(r=>{this._onHitTestSource(r,!0,e.inputSource,i)}).catch(r=>{i&&i(r),this.fire("error",r)})}_onHitTestSource(e,t,s,i){if(!this.manager.session){e.cancel();const a=new Error("XR Session is not started (3)");i&&i(a),this.fire("error",a);return}const r=new HW(this.manager,e,t,s??null);this.sources.push(r),i&&i(null,r),this.fire("add",r)}update(e){if(this._available)for(let t=0;t<this.sources.length;t++)this.sources[t].update(e)}get supported(){return this._supported}get available(){return this._available}}class XW extends ge{static EVENT_TRACKED="tracked";static EVENT_UNTRACKED="untracked";_image;_width;_bitmap=null;_measuredWidth=0;_trackable=!1;_tracking=!1;_emulated=!1;_pose=null;_position=new E;_rotation=new ae;constructor(e,t){super(),this._image=e,this._width=t}get image(){return this._image}set width(e){this._width=e}get width(){return this._width}get trackable(){return this._trackable}get tracking(){return this._tracking}get emulated(){return this._emulated}prepare(){return this._bitmap?{image:this._bitmap,widthInMeters:this._width}:createImageBitmap(this._image).then(e=>(this._bitmap=e,{image:this._bitmap,widthInMeters:this._width}))}destroy(){this._image=null,this._pose=null,this._bitmap&&(this._bitmap.close(),this._bitmap=null)}getPosition(){return this._pose&&this._position.copy(this._pose.transform.position),this._position}getRotation(){return this._pose&&this._rotation.copy(this._pose.transform.orientation),this._rotation}}class YW extends ge{static EVENT_ERROR="error";_manager;_supported=Ce.browser&&!!window.XRImageTrackingResult;_available=!1;_images=[];constructor(e){super(),this._manager=e,this._supported&&(this._manager.on("start",this._onSessionStart,this),this._manager.on("end",this._onSessionEnd,this))}add(e,t){if(!this._supported||this._manager.active)return null;const s=new XW(e,t);return this._images.push(s),s}remove(e){if(this._manager.active)return;const t=this._images.indexOf(e);t!==-1&&(e.destroy(),this._images.splice(t,1))}_onSessionStart(){this._manager.session.getTrackedImageScores().then(e=>{this._available=!0;for(let t=0;t<e.length;t++)this._images[t]._trackable=e[t]==="trackable"}).catch(e=>{this._available=!1,this.fire("error",e)})}_onSessionEnd(){this._available=!1;for(let e=0;e<this._images.length;e++){const t=this._images[e];t._pose=null,t._measuredWidth=0,t._tracking&&(t._tracking=!1,t.fire("untracked"))}}prepareImages(e){this._images.length?Promise.all(this._images.map(t=>t.prepare())).then(t=>{e(null,t)}).catch(t=>{e(t,null)}):e(null,null)}update(e){if(!this._available)return;const t=e.getImageTrackingResults(),s={};for(let i=0;i<t.length;i++){s[t[i].index]=t[i];const r=this._images[t[i].index];r._emulated=t[i].trackingState==="emulated",r._measuredWidth=t[i].measuredWidthInMeters,r._pose=e.getPose(t[i].imageSpace,this._manager._referenceSpace)}for(let i=0;i<this._images.length;i++)this._images[i]._tracking&&!s[i]?(this._images[i]._tracking=!1,this._images[i].fire("untracked")):!this._images[i]._tracking&&s[i]&&(this._images[i]._tracking=!0,this._images[i].fire("tracked"))}get supported(){return this._supported}get available(){return this._available}get images(){return this._images}}class jW{_index;_hand;_joints=[];_tip=null;constructor(e,t){this._index=e,this._hand=t,this._hand._fingers.push(this)}get index(){return this._index}get hand(){return this._hand}get joints(){return this._joints}get tip(){return this._tip}}const Z0=Ce.browser&&window.XRHand?["thumb-tip","index-finger-tip","middle-finger-tip","ring-finger-tip","pinky-finger-tip"]:[],OC={};for(let l=0;l<Z0.length;l++)OC[Z0[l]]=!0;class Q0{_index;_id;_hand;_finger;_wrist;_tip;_radius=null;_localTransform=new Z;_worldTransform=new Z;_localPosition=new E;_localRotation=new ae;_position=new E;_rotation=new ae;_dirtyLocal=!0;constructor(e,t,s,i=null){this._index=e,this._id=t,this._hand=s,this._finger=i,this._wrist=t==="wrist",this._tip=this._finger&&!!OC[t]}update(e){this._dirtyLocal=!0,this._radius=e.radius,this._localPosition.copy(e.transform.position),this._localRotation.copy(e.transform.orientation)}_updateTransforms(){this._dirtyLocal&&(this._dirtyLocal=!1,this._localTransform.setTRS(this._localPosition,this._localRotation,E.ONE));const t=this._hand._manager.camera.parent;t?this._worldTransform.mul2(t.getWorldTransform(),this._localTransform):this._worldTransform.copy(this._localTransform)}getPosition(){return this._updateTransforms(),this._worldTransform.getTranslation(this._position),this._position}getRotation(){return this._updateTransforms(),this._rotation.setFromMat4(this._worldTransform),this._rotation}get id(){return this._id}get index(){return this._index}get hand(){return this._hand}get finger(){return this._finger}get wrist(){return this._wrist}get tip(){return this._tip}get radius(){return this._radius||.005}}let Nd=[];const Ba=new E,fd=new E,J0=new E;Ce.browser&&window.XRHand&&(Nd=[["thumb-metacarpal","thumb-phalanx-proximal","thumb-phalanx-distal","thumb-tip"],["index-finger-metacarpal","index-finger-phalanx-proximal","index-finger-phalanx-intermediate","index-finger-phalanx-distal","index-finger-tip"],["middle-finger-metacarpal","middle-finger-phalanx-proximal","middle-finger-phalanx-intermediate","middle-finger-phalanx-distal","middle-finger-tip"],["ring-finger-metacarpal","ring-finger-phalanx-proximal","ring-finger-phalanx-intermediate","ring-finger-phalanx-distal","ring-finger-tip"],["pinky-finger-metacarpal","pinky-finger-phalanx-proximal","pinky-finger-phalanx-intermediate","pinky-finger-phalanx-distal","pinky-finger-tip"]]);class qW extends ge{static EVENT_TRACKING="tracking";static EVENT_TRACKINGLOST="trackinglost";_manager;_inputSource;_tracking=!1;_fingers=[];_joints=[];_jointsById={};_tips=[];_wrist=null;constructor(e){super();const t=e._xrInputSource.hand;if(this._manager=e._manager,this._inputSource=e,t.get("wrist")){const s=new Q0(0,"wrist",this,null);this._wrist=s,this._joints.push(s),this._jointsById.wrist=s}for(let s=0;s<Nd.length;s++){const i=new jW(s,this);for(let r=0;r<Nd[s].length;r++){const a=Nd[s][r];if(!t.get(a))continue;const n=new Q0(r,a,this,i);this._joints.push(n),this._jointsById[a]=n,n.tip&&(this._tips.push(n),i._tip=n),i._joints.push(n)}}}update(e){const t=this._inputSource._xrInputSource;for(let h=0;h<this._joints.length;h++){const d=this._joints[h],u=t.hand.get(d._id);if(u){let f;if(e.session.visibilityState!=="hidden"&&(f=e.getJointPose(u,this._manager._referenceSpace)),f)d.update(f),d.wrist&&!this._tracking&&(this._tracking=!0,this.fire("tracking"));else if(d.wrist){this._tracking&&(this._tracking=!1,this.fire("trackinglost"));break}}}const s=this._jointsById["thumb-metacarpal"],i=this._jointsById["thumb-tip"],r=this._jointsById["index-finger-phalanx-proximal"],a=this._jointsById["index-finger-tip"],n=this._jointsById["ring-finger-phalanx-proximal"],o=this._jointsById["pinky-finger-phalanx-proximal"];if(s&&i&&r&&a&&n&&o){this._inputSource._dirtyRay=!0,this._inputSource._rayLocal.origin.lerp(i._localPosition,a._localPosition,.5);let h=s,d=o;if(this._inputSource.handedness===zW){const u=h;h=d,d=u}Ba.sub2(h._localPosition,this._wrist._localPosition),fd.sub2(d._localPosition,this._wrist._localPosition),J0.cross(Ba,fd).normalize(),Ba.lerp(r._localPosition,n._localPosition,.5),Ba.sub(this._wrist._localPosition).normalize(),this._inputSource._rayLocal.direction.lerp(J0,Ba,.5).normalize()}this._fingerIsClosed(1)&&this._fingerIsClosed(2)&&this._fingerIsClosed(3)&&this._fingerIsClosed(4)?this._inputSource._squeezing||(this._inputSource._squeezing=!0,this._inputSource.fire("squeezestart"),this._manager.input.fire("squeezestart",this._inputSource)):this._inputSource._squeezing&&(this._inputSource._squeezing=!1,this._inputSource.fire("squeeze"),this._manager.input.fire("squeeze",this._inputSource),this._inputSource.fire("squeezeend"),this._manager.input.fire("squeezeend",this._inputSource))}_fingerIsClosed(e){const t=this._fingers[e];return Ba.sub2(t.joints[0]._localPosition,t.joints[1]._localPosition).normalize(),fd.sub2(t.joints[2]._localPosition,t.joints[3]._localPosition).normalize(),Ba.dot(fd)<-.8}getJointById(e){return this._jointsById[e]||null}get fingers(){return this._fingers}get joints(){return this._joints}get tips(){return this._tips}get wrist(){return this._wrist}get tracking(){return this._tracking}}const ex=new E,tx=new ae;let $W=0;class Nf extends ge{static EVENT_REMOVE="remove";static EVENT_SELECT="select";static EVENT_SELECTSTART="selectstart";static EVENT_SELECTEND="selectend";
17035static EVENT_SQUEEZE="squeeze";static EVENT_SQUEEZESTART="squeezestart";static EVENT_SQUEEZEEND="squeezeend";static EVENT_HITTESTADD="hittest:add";static EVENT_HITTESTREMOVE="hittest:remove";static EVENT_HITTESTRESULT="hittest:result";_id;_manager;_xrInputSource;_ray=new km;_rayLocal=new km;_grip=!1;_hand=null;_velocitiesAvailable=!1;_velocitiesTimestamp=Gt();_localTransform=null;_worldTransform=null;_position=new E;_rotation=new ae;_localPosition=null;_localPositionLast=null;_localRotation=null;_linearVelocity=null;_dirtyLocal=!0;_dirtyRay=!1;_selecting=!1;_squeezing=!1;_elementInput=!0;_elementEntity=null;_hitTestSources=[];constructor(e,t){super(),this._id=++$W,this._manager=e,this._xrInputSource=t,t.hand&&(this._hand=new qW(this))}get id(){return this._id}get inputSource(){return this._xrInputSource}get targetRayMode(){return this._xrInputSource.targetRayMode}get handedness(){return this._xrInputSource.handedness}get profiles(){return this._xrInputSource.profiles}get grip(){return this._grip}get hand(){return this._hand}get gamepad(){return this._xrInputSource.gamepad||null}get selecting(){return this._selecting}get squeezing(){return this._squeezing}set elementInput(e){this._elementInput!==e&&(this._elementInput=e,this._elementInput||(this._elementEntity=null))}get elementInput(){return this._elementInput}get elementEntity(){return this._elementEntity}get hitTestSources(){return this._hitTestSources}update(e){if(this._hand)this._hand.update(e);else{const t=this._xrInputSource.gripSpace;if(t){const i=e.getPose(t,this._manager._referenceSpace);if(i){this._grip||(this._grip=!0,this._localTransform=new Z,this._worldTransform=new Z,this._localPositionLast=new E,this._localPosition=new E,this._localRotation=new ae,this._linearVelocity=new E);const r=Gt(),a=(r-this._velocitiesTimestamp)/1e3;this._velocitiesTimestamp=r,this._dirtyLocal=!0,this._localPositionLast.copy(this._localPosition),this._localPosition.copy(i.transform.position),this._localRotation.copy(i.transform.orientation),this._velocitiesAvailable=!0,this._manager.input.velocitiesSupported&&i.linearVelocity?this._linearVelocity.copy(i.linearVelocity):a>0&&(ex.sub2(this._localPosition,this._localPositionLast).divScalar(a),this._linearVelocity.lerp(this._linearVelocity,ex,.15))}else this._velocitiesAvailable=!1}const s=e.getPose(this._xrInputSource.targetRaySpace,this._manager._referenceSpace);s&&(this._dirtyRay=!0,this._rayLocal.origin.copy(s.transform.position),this._rayLocal.direction.set(0,0,-1),tx.copy(s.transform.orientation),tx.transformVector(this._rayLocal.direction,this._rayLocal.direction))}}_updateTransforms(){this._dirtyLocal&&(this._dirtyLocal=!1,this._localTransform.setTRS(this._localPosition,this._localRotation,E.ONE));const e=this._manager.camera.parent;e?this._worldTransform.mul2(e.getWorldTransform(),this._localTransform):this._worldTransform.copy(this._localTransform)}_updateRayTransforms(){const e=this._dirtyRay;this._dirtyRay=!1;const t=this._manager.camera.parent;if(t){const s=t.getWorldTransform();s.getTranslation(this._position),this._rotation.setFromMat4(s),this._rotation.transformVector(this._rayLocal.origin,this._ray.origin),this._ray.origin.add(this._position),this._rotation.transformVector(this._rayLocal.direction,this._ray.direction)}else e&&(this._ray.origin.copy(this._rayLocal.origin),this._ray.direction.copy(this._rayLocal.direction))}getPosition(){return this._grip?(this._updateTransforms(),this._worldTransform.getTranslation(this._position),this._position):null}getLocalPosition(){return this._localPosition}getRotation(){return this._grip?(this._updateTransforms(),this._rotation.setFromMat4(this._worldTransform),this._rotation):null}getLocalRotation(){return this._localRotation}getLinearVelocity(){return this._velocitiesAvailable?this._linearVelocity:null}getOrigin(){return this._updateRayTransforms(),this._ray.origin}getDirection(){return this._updateRayTransforms(),this._ray.direction}hitTestStart(e={}){e.inputSource=this,e.profile=this._xrInputSource.profiles[0];const t=e.callback;e.callback=(s,i)=>{i&&this.onHitTestSourceAdd(i),t&&t(s,i)},this._manager.hitTest.start(e)}onHitTestSourceAdd(e){this._hitTestSources.push(e),this.fire("hittest:add",e),e.on("result",(t,s,i,r)=>{i===this&&this.fire("hittest:result",e,t,s,r)}),e.once("remove",()=>{this.onHitTestSourceRemove(e),this.fire("hittest:remove",e)})}onHitTestSourceRemove(e){const t=this._hitTestSources.indexOf(e);t!==-1&&this._hitTestSources.splice(t,1)}}class KW extends ge{static EVENT_ADD="add";static EVENT_REMOVE="remove";static EVENT_SELECT="select";static EVENT_SELECTSTART="selectstart";static EVENT_SELECTEND="selectend";
17035static EVENT_SQUEEZE="squeeze";static EVENT_SQUEEZESTART="squeezestart";static EVENT_SQUEEZEEND="squeezeend";manager;_inputSources=[];_onInputSourcesChangeEvt;velocitiesSupported=!1;constructor(e){super(),this.manager=e,this.velocitiesSupported=!!(Ce.browser&&window.XRPose?.prototype?.hasOwnProperty("linearVelocity")),this._onInputSourcesChangeEvt=t=>{this._onInputSourcesChange(t)},this.manager.on("start",this._onSessionStart,this),this.manager.on("end",this._onSessionEnd,this)}_onSessionStart(){const e=this.manager.session;e.addEventListener("inputsourceschange",this._onInputSourcesChangeEvt),e.addEventListener("select",s=>{const i=this._getByInputSource(s.inputSource);i.update(s.frame),i.fire("select",s),this.fire("select",i,s)}),e.addEventListener("selectstart",s=>{const i=this._getByInputSource(s.inputSource);i.update(s.frame),i._selecting=!0,i.fire("selectstart",s),this.fire("selectstart",i,s)}),e.addEventListener("selectend",s=>{const i=this._getByInputSource(s.inputSource);i.update(s.frame),i._selecting=!1,i.fire("selectend",s),this.fire("selectend",i,s)}),e.addEventListener("squeeze",s=>{const i=this._getByInputSource(s.inputSource);i.update(s.frame),i.fire("squeeze",s),this.fire("squeeze",i,s)}),e.addEventListener("squeezestart",s=>{const i=this._getByInputSource(s.inputSource);i.update(s.frame),i._squeezing=!0,i.fire("squeezestart",s),this.fire("squeezestart",i,s)}),e.addEventListener("squeezeend",s=>{const i=this._getByInputSource(s.inputSource);i.update(s.frame),i._squeezing=!1,i.fire("squeezeend",s),this.fire("squeezeend",i,s)});const t=e.inputSources;for(let s=0;s<t.length;s++)this._addInputSource(t[s])}_onSessionEnd(){let e=this._inputSources.length;for(;e--;){const s=this._inputSources[e];this._inputSources.splice(e,1),s.fire("remove"),this.fire("remove",s)}this.manager.session.removeEventListener("inputsourceschange",this._onInputSourcesChangeEvt)}_onInputSourcesChange(e){for(let t=0;t<e.removed.length;t++)this._removeInputSource(e.removed[t]);for(let t=0;t<e.added.length;t++)this._addInputSource(e.added[t])}_getByInputSource(e){for(let t=0;t<this._inputSources.length;t++)if(this._inputSources[t].inputSource===e)return this._inputSources[t];return null}_addInputSource(e){if(this._getByInputSource(e))return;const t=new Nf(this.manager,e);this._inputSources.push(t),this.fire("add",t)}_removeInputSource(e){for(let t=0;t<this._inputSources.length;t++){if(this._inputSources[t].inputSource!==e)continue;const s=this._inputSources[t];this._inputSources.splice(t,1);let i=s.hitTestSources.length;for(;i--;)s.hitTestSources[i].remove();s.fire("remove"),this.fire("remove",s);return}}update(e){for(let t=0;t<this._inputSources.length;t++)this._inputSources[t].update(e)}get inputSources(){return this._inputSources}}const io=new E,sx=new E,Em=new Z,ix=new Z;class ZW extends ge{static EVENT_AVAILABLE="available";static EVENT_ERROR="error";_manager;_supported=!1;_available=!1;_lightProbeRequested=!1;_lightProbe=null;_intensity=0;_rotation=new ae;_color=new Q;_sphericalHarmonics=new Float32Array(27);constructor(e){super(),this._manager=e,this._manager.on("start",this._onSessionStart,this),this._manager.on("end",this._onSessionEnd,this)}_onSessionStart(){this._manager.session.requestLightProbe&&(this._supported=!0)}_onSessionEnd(){this._supported=!1,this._available=!1,this._lightProbeRequested=!1,this._lightProbe=null}start(){let e;if(this._manager.session||(e=new Error("XR session is not running")),!e&&this._manager.type!==Ql&&(e=new Error("XR session type is not AR")),!e&&!this._supported&&(e=new Error("light-estimation is not supported")),(!e&&this._lightProbe||this._lightProbeRequested)&&(e=new Error("light estimation is already requested")),e){this.fire("error",e);return}this._lightProbeRequested=!0,this._manager.session.requestLightProbe().then(t=>{const s=this._lightProbeRequested;this._lightProbeRequested=!1,this._manager.active?s&&(this._lightProbe=t):this.fire("error",new Error("XR session is not active"))}).catch(t=>{this._lightProbeRequested=!1,this.fire("error",t)})}end(){this._lightProbeRequested=!1,this._lightProbe=null,this._available=!1}update(e){if(!this._lightProbe)return;const t=e.getLightEstimate(this._lightProbe);if(!t)return;this._available||(this._available=!0,this.fire("available"));const s=t.primaryLightIntensity;this._intensity=Math.max(1,Math.max(s.x,Math.max(s.y,s.z))),io.copy(s).mulScalar(1/this._intensity),this._color.set(io.x,io.y,io.z),io.set(0,0,0),sx.copy(t.primaryLightDirection),Em.setLookAt(sx,io,E.UP),ix.setFromAxisAngle(E.RIGHT,90),Em.mul(ix),this._rotation.setFromMat4(Em),this._sphericalHarmonics.set(t.sphericalHarmonicsCoefficients)}get supported(){return this._supported}get available(){return this._available}get intensity(){return this._available?this._intensity:null}get color(){return this._available?this._color:null}get rotation(){return this._available?this._rotation:null}get sphericalHarmonics(){return this._available?this._sphericalHarmonics:null}}let QW=0;class JW extends ge{static EVENT_REMOVE="remove";static EVENT_CHANGE="change";_id;_planeDetection;_xrPlane;_lastChangedTime;_orientation;_position=new E;_rotation=new ae;constructor(e,t){super(),this._id=++QW,this._planeDetection=e,this._xrPlane=t,this._lastChangedTime=t.lastChangedTime,this._orientation=t.orientation}destroy(){this._xrPlane&&(this._xrPlane=null,this.fire("remove"))}update(e){const t=this._planeDetection._manager,s=e.getPose(this._xrPlane.planeSpace,t._referenceSpace);s&&(this._position.copy(s.transform.position),this._rotation.copy(s.transform.orientation)),this._lastChangedTime!==this._xrPlane.last
17035ChangedTime&&(this._lastChangedTime=this._xrPlane.lastChangedTime,this.fire("change"))}getPosition(){return this._position}getRotation(){return this._rotation}get id(){return this._id}get orientation(){return this._orientation}get points(){return this._xrPlane.polygon}get label(){return this._xrPlane.semanticLabel||""}}class e5 extends ge{static EVENT_AVAILABLE="available";static EVENT_UNAVAILABLE="unavailable";static EVENT_ADD="add";static EVENT_REMOVE="remove";_manager;_supported=Ce.browser&&!!window.XRPlane;_available=!1;_planesIndex=new Map;_planes=[];constructor(e){super(),this._manager=e,this._supported&&(this._manager.on("start",this._onSessionStart,this),this._manager.on("end",this._onSessionEnd,this))}_onSessionStart(){this._manager.session.enabledFeatures&&this._manager.session.enabledFeatures.indexOf("plane-detection")!==-1&&(this._available=!0,this.fire("available"))}_onSessionEnd(){for(let e=0;e<this._planes.length;e++)this._planes[e].destroy(),this.fire("remove",this._planes[e]);this._planesIndex.clear(),this._planes.length=0,this._available&&(this._available=!1,this.fire("unavailable"))}update(e){if(!this._available)if(!this._manager.session.enabledFeatures&&e.detectedPlanes.size)this._available=!0,this.fire("available");else return;const t=e.detectedPlanes;for(const[s,i]of this._planesIndex)t.has(s)||(this._planesIndex.delete(s),this._planes.splice(this._planes.indexOf(i),1),i.destroy(),this.fire("remove",i));for(const s of t){let i=this._planesIndex.get(s);i?i.update(e):(i=new JW(this,s),this._planesIndex.set(s,i),this._planes.push(i),i.update(e),this.fire("add",i))}}get supported(){return this._supported}get available(){return this._available}get planes(){return this._planes}}class t5 extends ge{static EVENT_DESTROY="destroy";static EVENT_CHANGE="change";static EVENT_PERSIST="persist";static EVENT_FORGET="forget";_position=new E;_rotation=new ae;_uuid=null;_uuidRequests=null;constructor(e,t,s=null){super(),this._anchors=e,this._xrAnchor=t,this._uuid=s}destroy(){if(!this._xrAnchor)return;const e=this._xrAnchor;this._xrAnchor.delete(),this._xrAnchor=null,this.fire("destroy",e,this)}update(e){if(!this._xrAnchor)return;const t=e.getPose(this._xrAnchor.anchorSpace,this._anchors.manager._referenceSpace);if(t){if(this._position.equals(t.transform.position)&&this._rotation.equals(t.transform.orientation))return;this._position.copy(t.transform.position),this._rotation.copy(t.transform.orientation),this.fire("change")}}getPosition(){return this._position}getRotation(){return this._rotation}persist(e){if(!this._anchors.persistence){e?.(new Error("Persistent Anchors are not supported"),null);return}if(this._uuid){e?.(null,this._uuid);return}if(this._uuidRequests){e&&this._uuidRequests.push(e);return}this._uuidRequests=[],this._xrAnchor.requestPersistentHandle().then(t=>{this._uuid=t,this._anchors._indexByUuid.set(this._uuid,this),e?.(null,t);for(const s of this._uuidRequests)s(null,t);this._uuidRequests=null,this.fire("persist",t)}).catch(t=>{e?.(t,null);for(const s of this._uuidRequests)s(t,null);this._uuidRequests=null})}forget(e){if(!this._uuid){e?.(new Error("Anchor is not persistent"));return}this._anchors.forget(this._uuid,t=>{this._uuid=null,e?.(t),this.fire("forget")})}get uuid(){return this._uuid}get persistent(){return!!this._uuid}}class s5 extends ge{static EVENT_AVAILABLE="available";static EVENT_UNAVAILABLE="unavailable";static EVENT_ERROR="error";static EVENT_ADD="add";static EVENT_DESTROY="destroy";manager;
17035_supported=Ce.browser&&!!window.XRAnchor;_available=!1;_checkingAvailability=!1;_persistence=Ce.browser&&!!window?.XRSession?.prototype.restorePersistentAnchor;_creationQueue=[];_index=new Map;_indexByUuid=new Map;_list=[];_callbacksAnchors=new Map;constructor(e){super(),this.manager=e,this._supported&&(this.manager.on("start",this._onSessionStart,this),this.manager.on("end",this._onSessionEnd,this))}_onSessionStart(){const e=this.manager.session.enabledFeatures?.indexOf("anchors")>=0;e&&(this._available=e,this.fire("available"))}_onSessionEnd(){if(!this._available)return;this._available=!1;for(let t=0;t<this._creationQueue.length;t++)this._creationQueue[t].callback&&this._creationQueue[t].callback(new Error("session ended"),null);this._creationQueue.length=0,this._index.clear(),this._indexByUuid.clear();let e=this._list.length;for(;e--;)this._list[e].destroy();this._list.length=0,this.fire("unavailable")}_createAnchor(e,t=null){const s=new t5(this,e,t);return this._index.set(e,s),t&&this._indexByUuid.set(t,s),this._list.push(s),s.once("destroy",this._onAnchorDestroy,this),s}_onAnchorDestroy(e,t){this._index.delete(e),t.uuid&&this._indexByUuid.delete(t.uuid);const s=this._list.indexOf(t);s!==-1&&this._list.splice(s,1),this.fire("destroy",t)}
17035create(e,t,s){if(!this._available){s?.(new Error("Anchors API is not available"),null);return}if(window.XRHitTestResult&&e instanceof XRHitTestResult){const i=e;if(s=t,!this._supported){s?.(new Error("Anchors API is not supported"),null);return}if(!i.createAnchor){s?.(new Error("Creating Anchor from Hit Test is not supported"),null);return}i.createAnchor().then(r=>{const a=this._createAnchor(r);s?.(null,a),this.fire("add",a)}).catch(r=>{s?.(r,null),this.fire("error",r)})}else this._creationQueue.push({transform:new XRRigidTransform(e,t),callback:s})}restore(e,t){if(!this._available){t?.(new Error("Anchors API is not available"),null);return}if(!this._persistence){t?.(new Error("Anchor Persistence is not supported"),null);return}if(!this.manager.active){t?.(new Error("WebXR session is not active"),null);return}this.manager.session.restorePersistentAnchor(e).then(s=>{const i=this._createAnchor(s,e);t?.(null,i),this.fire("add",i)}).catch(s=>{t?.(s,null),this.fire("error",s)})}forget(e,t){if(!this._available){t?.(new Error("Anchors API is not available"));return}if(!this._persistence){t?.(new Error("Anchor Persistence is not supported"));return}if(!this.manager.active){t?.(new Error("WebXR session is not active"));return}this.manager.session.deletePersistentAnchor(e).then(()=>{t?.(null)}).catch(s=>{t?.(s),this.fire("error",s)})}update(e){if(!this._available){!this.manager.session.enabledFeatures&&!this._checkingAvailability&&(this._checkingAvailability=!0,e.createAnchor(new XRRigidTransform,this.manager._referenceSpace).then(t=>{t.delete(),this.manager.active&&(this._available=!0,this.fire("available"))}).catch(()=>{}));return}if(this._creationQueue.length){for(let t=0;t<this._creationQueue.length;t++){const s=this._creationQueue[t];e.createAnchor(s.transform,this.manager._referenceSpace).then(i=>{s.callback&&this._callbacksAnchors.set(i,s.callback)}).catch(i=>{s.callback&&s.callback(i,null),this.fire("error",i)})}this._creationQueue.length=0}for(const[t,s]of this._index)e.trackedAnchors.has(t)||(this._index.delete(t),s.destroy());for(let t=0;t<this._list.length;t++)this._list[t].update(e);for(const t of e.trackedAnchors){if(this._index.has(t))continue;try{const r=t.anchorSpace}catch{continue}const s=this._createAnchor(t);s.update(e);const i=this._callbacksAnchors.get(t);i&&(this._callbacksAnchors.delete(t),i(null,s)),this.fire("add",s)}}get supported(){return this._supported}get available(){return this._available}get persistence(){return this._persistence}get uuids(){return!this._available||!this._persistence||!this.manager.active?null:this.manager.session.persistentAnchors}get list(){return this._list}}class i5 extends ge{static EVENT_REMOVE="remove";static EVENT_CHANGE="change";_meshDetection;_xrMesh;_lastChanged=0;_position=new E;_rotation=new ae;constructor(e,t){super(),this._meshDetection=e,this._xrMesh=t,this._lastChanged=this._xrMesh.lastChangedTime}get xrMesh(){return this._xrMesh}get label(){return this._xrMesh.semanticLabel||""}get vertices(){return this._xrMesh.vertices}get indices(){return this._xrMesh.indices}destroy(){this._xrMesh&&(this._xrMesh=null,this.fire("remove"))}update(e){const t=this._meshDetection._manager,s=e.getPose(this._xrMesh.meshSpace,t._referenceSpace);s&&(this._position.copy(s.transform.position),this._rotation.copy(s.transform.orientation)),this._lastChanged!==this._xrMesh.lastChangedTime&&(this._lastChanged=this._xrMesh.lastChangedTime,this.fire("change"))}getPosition(){return this._position}getRotation(){return this._rotation}}class r5 extends ge{static EVENT_AVAILABLE="available";static EVENT_UNAVAILABLE="unavailable";static EVENT_ADD="add";static EVENT_REMOVE="remove";_manager;_supported=Ce.browser&&!!window.XRMesh;_available=!1;_index=new Map;_list=[];constructor(e){super(),this._manager=e,this._supported&&(this._manager.on("start",this._onSessionStart,this),this._manager.on("end",this._onSessionEnd,this))}update(e){if(!this._available)if(!this._manager.session.enabledFeatures&&e.detectedMeshes.size)this._available=!0,this.fire("available");else return;for(const t of e.detectedMeshes){let s=this._index.get(t);s?s.update(e):(s=new i5(this,t),this._index.set(t,s),this._list.push(s),s.update(e),this.fire("add",s))}for(const t of this._index.values())e.detectedMeshes.has(t.xrMesh)||this._removeMesh(t)}_removeMesh(e){this._index.delete(e.xrMesh),this._list.splice(this._list.indexOf(e),1),e.destroy(),this.fire("remove",e)}
17035_onSessionStart(){if(this._manager.session.enabledFeatures){const e=this._manager.session.enabledFeatures.indexOf("mesh-detection")!==-1;if(!e)return;this._available=e,this.fire("available")}}_onSessionEnd(){if(this._available){this._available=!1;for(const e of this._index.values())this._removeMesh(e);this.fire("unavailable")}}get supported(){return this._supported}get available(){return this._available}get meshes(){return this._list}}class a5 extends ge{static EVENT_DEPTHRESIZE="depth:resize";_manager;_xrView;_positionData=new Float32Array(3);_viewport=new ie;_projMat=new Z;_projViewOffMat=new Z;_viewMat=new Z;_viewOffMat=new Z;_viewMat3=new xi;_viewInvMat=new Z;_viewInvOffMat=new Z;_xrCamera=null;_textureColor=null;_textureDepth=null;_depthInfo=null;_emptyDepthBuffer=new Uint8Array(32);_depthMatrix=new Z;constructor(e,t,s){super(),this._manager=e,this._xrView=t;const i=this._manager.app.graphicsDevice;if(this._manager.views.supportedColor&&(this._xrCamera=this._xrView.camera,this._manager.views.availableColor&&this._xrCamera&&(this._textureColor=new ce(i,{format:Er,mipmaps:!1,addressU:ue,addressV:ue,minFilter:It,magFilter:It,width:this._xrCamera.width,height:this._xrCamera.height,name:`XrView-${this._xrView.eye}-Color`}))),this._manager.views.supportedDepth&&this._manager.views.availableDepth){const r=this._manager.views.depthGpuOptimized?Fe:It;this._textureDepth=new ce(i,{format:this._manager.views.depthPixelFormat,arrayLength:s===1?0:s,mipmaps:!1,addressU:ue,addressV:ue,minFilter:r,magFilter:r,width:4,height:4,name:`XrView-${this._xrView.eye}-Depth`});for(let a=0;a<this._textureDepth._levels.length;a++)this._textureDepth._levels[a]=this._emptyDepthBuffer;this._textureDepth.upload()}(this._textureColor||this._textureDepth)&&i.on("devicelost",this._onDeviceLost,this)}get textureColor(){return this._textureColor}get textureDepth(){return this._textureDepth}get depthUvMatrix(){return this._depthMatrix}get depthValueToMeters(){return this._depthInfo?.rawValueToMeters||0}get eye(){return this._xrView.eye}get viewport(){return this._viewport}get projMat(){return this._projMat}get projViewOffMat(){return this._projViewOffMat}get viewOffMat(){return this._viewOffMat}get viewInvOffMat(){return this._viewInvOffMat}get viewMat3(){return this._viewMat3}get positionData(){return this._positionData}update(e,t){this._xrView=t,this._manager.views.availableColor&&(this._xrCamera=this._xrView.camera);const s=this._manager.xrBridge.getViewport(e,this._xrView);this._viewport.x=s.x,this._viewport.y=s.y,this._viewport.z=s.width,this._viewport.w=s.height,this._projMat.set(this._xrView.projectionMatrix),this._viewMat.set(this._xrView.transform.inverse.matrix),this._viewInvMat.set(this._xrView.transform.matrix),this._updateTextureColor(),this._updateDepth(e)}_updateTextureColor(){!this._manager.views.availableColor||!this._xrCamera||!this._textureColor||this._manager.xrBridge?.syncCameraColorTexture(this._xrCamera,this._textureColor)}_updateDepth(e){if(!this._manager.views.availableDepth||!this._textureDepth)return;const t=this._manager.views.depthGpuOptimized,s=t?this._manager.graphicsBinding:e;if(!s){this._depthInfo=null;return}const i=s.getDepthInformation(this._xrView);if(!i){this._depthInfo=null;return}let r=!this._depthInfo!=!i;this._depthInfo=i;const a=this._depthInfo?.width||4,n=this._depthInfo?.height||4;let o=!1;(this._textureDepth.width!==a||this._textureDepth.height!==n)&&(this._textureDepth._width=a,this._textureDepth._height=n,r=!0,o=!0),r&&(this._depthInfo?this._depthMatrix.data.set(this._depthInfo.normDepthBufferFromNormView.matrix):this._depthMatrix.setIdentity()),this._depthInfo?t?this._manager.xrBridge?.syncCameraDepthTexture(this._depthInfo,this._textureDepth,this._manager.views.depthPixelFormat??Ti):(this._textureDepth._levels[0]=new Uint8Array(this._depthInfo.data),this._textureDepth.upload()):(this._textureDepth._levels[0]=this._emptyDepthBuffer,this._textureDepth.upload()),o&&this.fire("depth:resize",a,n)}updateTransforms(e){e?(this._viewInvOffMat.mul2(e,this._viewInvMat),this.viewOffMat.copy(this._viewInvOffMat).invert()):(this._viewInvOffMat.copy(this._viewInvMat),this.viewOffMat.copy(this._viewMat)),this._viewMat3.setFromMat4(this._viewOffMat),this._projViewOffMat.mul2(this._projMat,this._viewOffMat),this._positionData[0]=this._viewInvOffMat.data[12],this._positionData[1]=this._viewInvOffMat.data[13],this._positionData[2]=this._viewInvOffMat.data[14]}_onDeviceLost(){this._depthInfo=null}getDepth(e,t){return this._manager.views.depthGpuOptimized?null:this._depthInfo?.getDepthInMeters(e,t)??null}destroy(){this._depthInfo=null,this._textureColor&&(this._textureColor.destroy(),this._textureColor=null),this._textureDepth&&(this._textureDepth.destroy(),this._textureDepth=null)}}class n5 extends ge{static EVENT_ADD="add";static EVENT_REMOVE="remove";_manager;_index=new Map;_indexTmp=new Map;_list=[];_supportedColor=!1;_supportedDepth=Ce.browser&&!!window.XRDepthInformation;_availableColor=!1;_availableDepth=!1;_depthUsage="";_depthFormat="";_depthFormats={[RC]:Du,[LC]:Oi,[FC]:Ti};constructor(e){super(),this._manager=e;const t=e.app?.graphicsDevice;Ce.browser&&window.XRCamera&&(t?.isWebGL2&&window.XRWebGLBinding?this._supportedColor=!0:t?.isWebGPU&&window.XRGPUBinding&&(this._supportedColor=!0)),this._manager.on("start",this._onSessionStart,this),this._manager.on("end",this._onSessionEnd,this)}get list(){return this._list}get supportedColor(){return this._supportedColor}get supportedDepth(){return this._supportedDepth}get availableColor(){return this._availableColor}get availableDepth(){return this._availableDepth}get depthUsage(){return this._depthUsage}get depthGpuOptimized(){return this._depthUsage===MC}get depthFormat(){return this._depthFormat}get depthPixelFormat(){return this._depthFormats[this._depthFormat]??null}update(e,t){for(let s=0;s<t.length;s++)this._indexTmp.set(t[s].eye,t[s]);for(const[s,i]of this._indexTmp){let r=this._index.get(s);r?r.update(e,i):(r=new a5(this._manager,i,t.length),this._index.set(s,r),this._list.push(r),r.update(e,i),this.fire("add",r))}for(const[s,i]of this._index){if(this._indexTmp.has(s))continue;i.destroy(),this._index.delete(s);const r=this._list.indexOf(i);r!==-1&&this._list.splice(r,1),this.fire("remove",i)}this._indexTmp.clear()}get(e){return this._index.get(e)||null}
17035_onSessionStart(){if(this._manager.type===Ql&&this._manager.session.enabledFeatures&&(this._availableColor=this._manager.session.enabledFeatures.indexOf("camera-access")!==-1,this._availableDepth=this._manager.session.enabledFeatures.indexOf("depth-sensing")!==-1,this._availableDepth)){const e=this._manager.session;this._depthUsage=e.depthUsage,this._depthFormat=e.depthDataFormat}}_onSessionEnd(){for(const e of this._index.values())e.destroy();this._index.clear(),this._availableColor=!1,this._availableDepth=!1,this._depthUsage="",this._depthFormat="",this._list.length=0}}class o5{device;eventHandler;impl;_evtDeviceLost=null;_evtDeviceRestored=null;_session=null;_framebufferScaleFactor=1;_onBindingError;constructor(e,t){this.device=e,this.eventHandler=t,this.impl=e.createXrBridgeImpl(this),this._evtDeviceLost=e.on("devicelost",this._onDeviceLost,this),this._evtDeviceRestored=e.on("devicerestored",this._onDeviceRestored,this)}destroy(){const e=this.device;e&&(this._evtDeviceLost?.off(),this._evtDeviceLost=null,this._evtDeviceRestored?.off(),this._evtDeviceRestored=null,this.impl.endFrame(),this.impl.destroy(e),this.impl=null,this._session=null,this._framebufferScaleFactor=1,this._onBindingError=void 0,this.device=null,this.eventHandler=null)}_onDeviceLost(){this.impl.onGraphicsDeviceLost()}_onDeviceRestored(){this.impl.onGraphicsDeviceRestored()}attachPresentation(e,t){this._session=e,this._framebufferScaleFactor=t.framebufferScaleFactor,this._onBindingError=t.onBindingError,this.impl.attachPresentation(e,t)}releasePresentation(){this.impl.releasePresentation()}beginFrame(e,t){this.impl.beginFrame(e,t)}endFrame(){this.impl.endFrame()}getFramebufferSize(e,t){this.impl.getFramebufferSize(e,t)}getViewport(e,t){return this.impl.getViewport(e,t)}syncCameraColorTexture(e,t){this.impl?.syncCameraColorTexture?.(e,t)}syncCameraDepthTexture(e,t,s){this.impl?.syncCameraDepthTexture?.(e,t,s)}get presentationLayer(){return this.impl.presentationLayer??null}get graphicsBinding(){return this.impl.graphicsBinding??null}}class l5 extends ge{static EVENT_AVAILABLE="available";static EVENT_START="start";static EVENT_END="end";static EVENT_UPDATE="update";static EVENT_ERROR="error";app;_supported=Ce.browser&&!!navigator.xr;_available={};_type=null;_spaceType=null;_session=null;xrBridge=null;get graphicsBinding(){return this.xrBridge?.graphicsBinding??null}_referenceSpace=null;domOverlay;hitTest;imageTracking;planeDetection;meshDetection;input;lightEstimation;views;anchors;_camera=null;_localPosition=new E;_localRotation=new ae;_depthNear=.1;_depthFar=1e3;_supportedFrameRates=null;_width=0;_height=0;_framebufferSize=new j;_framebufferScaleFactor=1;constructor(e){super(),this.app=e,this._available[kW]=!1,this._available[UW]=!1,this._available[Ql]=!1,this.domOverlay=new GW(this),this.hitTest=new WW(this),this.imageTracking=new YW(this),this.planeDetection=new e5(this),this.meshDetection=new r5(this),this.input=new KW(this),this.lightEstimation=new ZW(this),this.anchors=new s5(this),this.views=new n5(this),this._supported&&(navigator.xr.addEventListener("devicechange",()=>{this._deviceAvailabilityCheck()}),this._deviceAvailabilityCheck())}destroy(){this.xrBridge&&(this.xrBridge.destroy(),this.xrBridge=null)}start(e,t,s,i){let r=i;if(typeof i=="object"&&(r=i.callback),!this._available[t]){r&&r(new Error("XR is not available"));return}if(this._session){r&&r(new Error("XR session is already started"));return}this._camera=e,this._camera.camera.xr=this,this._type=t,this._spaceType=s,this._framebufferScaleFactor=i?.framebufferScaleFactor??1,this._setClipPlanes(e.nearClip,e.farClip);const a={requiredFeatures:[s],optionalFeatures:[]};if(this.app.graphicsDevice?.isWebGPU&&a.requiredFeatures.push("webgpu"),t===Ql){if(a.optionalFeatures.push("light-estimation"),a.optionalFeatures.push("hit-test"),i&&(i.imageTracking&&this.imageTracking.supported&&a.optionalFeatures.push("image-tracking"),i.planeDetection&&a.optionalFeatures.push("plane-detection"),i.meshDetection&&a.optionalFeatures.push("mesh-detection")),this.domOverlay.supported&&this.domOverlay.root&&(a.optionalFeatures.push("dom-overlay"),a.domOverlay={root:this.domOverlay.root}),i&&i.anchors&&this.anchors.supported&&a.optionalFeatures.push("anchors"),i&&i.depthSensing&&this.views.supportedDepth){a.optionalFeatures.push("depth-sensing");const o=[],c=[];if(o.push(MC,VW),c.push(FC,RC,LC),i.depthSensing.usagePreference){const h=o.indexOf(i.depthSensing.usagePreference);h!==-1&&o.splice(h,1),o.unshift(i.depthSensing.usagePreference)}if(i.depthSensing.dataFormatPreference){const h=c.indexOf(i.depthSensing.dataFormatPreference);h!==-1&&c.splice(h,1),c.unshift(i.depthSensing.dataFormatPreference)}a.depthSensing={usagePreference:o,dataFormatPreference:c}}i&&i.cameraColor&&this.views.supportedColor&&a.optionalFeatures.push("camera-access")}a.optionalFeatures.push("hand-tracking"),i&&i.optionalFeatures&&(a.optionalFeatures=a.optionalFeatures.concat(i.optionalFeatures)),this.imageTracking.supported&&this.imageTracking.images.length?this.imageTracking.prepareImages((o,c)=>{if(o){r&&r(o),this.fire("error",o);return}c!==null&&(a.trackedImages=c),this._onStartOptionsReady(t,s,a,r)}):this._onStartOptionsReady(t,s,a,r)}_onStartOptionsReady(e,t,s,i){navigator.xr.requestSession(e,s).then(r=>{this._onSessionStart(r,t,i)}).catch(r=>{this._camera.camera.xr=null,this._camera=null,this._type=null,this._spaceType=null,i&&i(r),this.fire("error",r)})}end(e){if(!this._session){e&&e(new Error("XR Session is not initialized"));return}this.xrBridge?.releasePresentation(),e&&this.once("end",e),this._session.end()}isAvailable(e){return this._available[e]}_deviceAvailabilityCheck(){for(const e in this._available)this._sessionSupportCheck(e)}initiateRoomCapture(e){if(!this._session){e(new Error("Session is not active"));return}if(!this._session.initiateRoomCapture){e(new Error("Session does not support manual room capture"));return}this._session.initiateRoomCapture().then(()=>{e&&e(null)}
17035).catch(t=>{e&&e(t)})}updateTargetFrameRate(e,t){if(!this._session?.updateTargetFrameRate){t?.(new Error("unable to update frameRate"));return}this._session.updateTargetFrameRate(e).then(()=>{t?.()}).catch(s=>{t?.(s)})}_sessionSupportCheck(e){navigator.xr.isSessionSupported(e).then(t=>{this._available[e]!==t&&(this._available[e]=t,this.fire("available",e,t),this.fire(`available:${e}`,t))}).catch(t=>{this.fire("error",t)})}_onSessionStart(e,t,s){let i=!1;this._session=e,this.xrBridge=new o5(this.app.graphicsDevice,this);const r=()=>{this.fire("visibility:change",e.visibilityState)},a=()=>{this._setClipPlanes(this._camera.nearClip,this._camera.farClip)},n=()=>{this.fire("frameratechange",this._session?.frameRate)},o=()=>{this._camera&&(this._camera.off("set_nearClip",a),this._camera.off("set_farClip",a),this._camera.camera.xr=null,this._camera=null),e.removeEventListener("end",o),e.removeEventListener("visibilitychange",r),e.removeEventListener("frameratechange",n),i||this.fire("end"),this.xrBridge&&(this.xrBridge.destroy(),this.xrBridge=null),this._session=null,this._referenceSpace=null,this._width=0,this._height=0,this._type=null,this._spaceType=null,this.app.systems&&this.app.requestAnimationFrame()};e.addEventListener("end",o),e.addEventListener("visibilitychange",r),this._camera.on("set_nearClip",a),this._camera.on("set_farClip",a);const h=this.app.graphicsDevice.maxPixelRatio/window.devicePixelRatio*this._framebufferScaleFactor;this.xrBridge.attachPresentation(this._session,{framebufferScaleFactor:h,depthNear:this._depthNear,depthFar:this._depthFar,onBindingError:d=>{this.fire("error",d)}}),this.session.supportedFrameRates?this._supportedFrameRates=Array.from(this.session.supportedFrameRates):this._supportedFrameRates=null,this._session.addEventListener("frameratechange",n),e.requestReferenceSpace(t).then(d=>{this._referenceSpace=d,this.app.requestAnimationFrame(),s&&s(null),this.fire("start")}).catch(d=>{i=!0,e.end(),s&&s(d),this.fire("error",d)})}_setClipPlanes(e,t){this._depthNear===e&&this._depthFar===t||(this._depthNear=e,this._depthFar=t,this._session&&this._session.updateRenderState({depthNear:this._depthNear,depthFar:this._depthFar}))}update(e){if(!this._session)return!1;this.xrBridge.getFramebufferSize(e,this._framebufferSize);const t=this._framebufferSize.x,s=this._framebufferSize.y;(this._width!==t||this._height!==s)&&(this._width=t,this._height=s,this.app.graphicsDevice.setResolution(t,s));const i=e.getViewerPose(this._referenceSpace);if(!i)return!1;const r=this.views.list.length;this.views.update(e,i.views);const a=i.transform.position,n=i.transform.orientation;if(this._localPosition.set(a.x,a.y,a.z),this._localRotation.set(n.x,n.y,n.z,n.w),r===0&&this.views.list.length>0){const o=new Z,c=this.views.list[0];o.copy(c.projMat);const h=o.data,d=2*Math.atan(1/h[5])*180/Math.PI,u=h[5]/h[0],f=h[14]/(h[10]+1),p=h[14]/(h[10]-1);this._camera.camera.setXrProperties({aspectRatio:u,farClip:f,fov:d,horizontalFov:!1,nearClip:p})}return this._camera.camera._node.setLocalPosition(this._localPosition),this._camera.camera._node.setLocalRotation(this._localRotation),this.input.update(e),this._type===Ql&&(this.hitTest.supported&&this.hitTest.update(e),this.lightEstimation.supported&&this.lightEstimation.update(e),this.imageTracking.supported&&this.imageTracking.update(e),this.anchors.supported&&this.anchors.update(e),this.planeDetection.supported&&this.planeDetection.update(e),this.meshDetection.supported&&this.meshDetection.update(e)),this.fire("update",e),this.xrBridge.beginFrame(e,this._referenceSpace),!0}get supported(){return this._supported}get active(){return!!this._session}get type(){return this._type}get spaceType(){return this._spaceType}get session(){return this._session}get frameRate(){return this._session?.frameRate??null}get supportedFrameRates(){return this._supportedFrameRates}get framebufferScaleFactor(){return this._framebufferScaleFactor}set fixedFoveation(e){const t=this.xrBridge?.presentationLayer;(t?.fixedFoveation??null)!==null&&(this.app.graphicsDevice.samples>1,t.fixedFoveation=e)}get fixedFoveation(){return this.xrBridge?.presentationLayer?.fixedFoveation??null}get camera(){return this._camera?this._camera.entity:null}get visibilityState(){return this._session?this._session.visibilityState:null}}class c5 extends Ts{constructor(e,t={}){super(e);const s=new TB;s.graphicsDevice=t.graphicsDevice??this.createDevice(e,t),this.addComponentSystems(s),this.addResourceHandles(s),s.elementInput=t.elementInput,s.keyboard=t.keyboard,s.mouse=t.mouse,s.touch=t.touch,s.gamepads=t.gamepads,s.scriptPrefix=t.scriptPrefix,s.assetPrefix=t.assetPrefix,s.scriptsOrder=t.scriptsOrder,s.soundManager=new nI,s.lightmapper=OB,s.batchManager=u1,s.xr=l5,this.init(s)}createDevice(e,t){return t.graphicsDeviceOptions||(t.graphicsDeviceOptions={}),Ce.browser&&navigator.xr&&(t.graphicsDeviceOptions.xrCompatible=!0),t.graphicsDeviceOptions.alpha=t.graphicsDeviceOptions.alpha||!1,new hT(e,t.graphicsDeviceOptions)}addComponentSystems(e){e.componentSystems=[Jw,IN,ak,eN,nN,Sk,cz,Gz,Wz,aV,Mz,lN,nz,vz,tk,fN,bz,Pz,Bz,mk,ok,kz,r4]}addResourceHandles(e){e.resourceHandlers=[a4,cH,hH,dH,iW,QH,NW,fW,qH,fH,cW,rW,vH,jH,gH,hW,YH,SH,yH,pH,mW,dW,uW,_H,XH]}}j.prototype.scale=j.prototype.mulScalar;E.prototype.scale=E.prototype.mulScalar;ie.prototype.scale=ie.prototype.mulScalar;new ie;Object.defineProperties(St.prototype,{_glFrameBuffer:{get:function(){return this.impl._glFrameBuffer},set:function(l){}}});Object.defineProperty(Us,"defaultInstancingFormat",{get:function(){return null}});Object.defineProperties(ce.prototype,{rgbm:{get:function(){return this.type===wr},set:function(l){this.type=l?wr:Qs}},swizzleGGGR:{get:function(){return this.type===nc},set:function(l){this.type=l?nc:Qs}},_glTexture:{get:function(){return this.impl._glTexture}}});Object.defineProperty(Je.prototype,"boneLimit",{get:function(){return 1024}});Object.defineProperty(Je.prototype,"webgl2",{get:function(){return this.isWebG
17035L2}});Object.defineProperty(Je.prototype,"textureFloatHighPrecision",{get:function(){return!0}});Object.defineProperty(Je.prototype,"extBlendMinmax",{get:function(){return!0}});Object.defineProperty(Je.prototype,"extTextureHalfFloat",{get:function(){return!0}});Object.defineProperty(Je.prototype,"extTextureLod",{get:function(){return!0}});Object.defineProperty(Je.prototype,"textureHalfFloatFilterable",{get:function(){return!0}});Object.defineProperty(Je.prototype,"supportsMrt",{get:function(){return!0}});Object.defineProperty(Je.prototype,"supportsVolumeTextures",{get:function(){return!0}});Object.defineProperty(Je.prototype,"supportsInstancing",{get:function(){return!0}});Object.defineProperty(Je.prototype,"textureHalfFloatUpdatable",{get:function(){return!0}});Object.defineProperty(Je.prototype,"extTextureFloat",{get:function(){return!0}});Object.defineProperty(Je.prototype,"extStandardDerivatives",{get:function(){return!0}});xt.DEFAULT=Object.freeze(new xt);const Pt=new xt,xr=new ds;Je.prototype.setBlendFunction=function(l,e){const t=this.blendState;Pt.copy(t),Pt.setColorBlend(t.colorOp,l,e),Pt.setAlphaBlend(t.alphaOp,l,e),this.setBlendState(Pt)};Je.prototype.setBlendFunctionSeparate=function(l,e,t,s){const i=this.blendState;Pt.copy(i),Pt.setColorBlend(i.colorOp,l,e),Pt.setAlphaBlend(i.alphaOp,t,s),this.setBlendState(Pt)};Je.prototype.setBlendEquation=function(l){const e=this.blendState;Pt.copy(e),Pt.setColorBlend(l,e.colorSrcFactor,e.colorDstFactor),Pt.setAlphaBlend(l,e.alphaSrcFactor,e.alphaDstFactor),this.setBlendState(Pt)};Je.prototype.setBlendEquationSeparate=function(l,e){const t=this.blendState;Pt.copy(t),Pt.setColorBlend(l,t.colorSrcFactor,t.colorDstFactor),Pt.setAlphaBlend(e,t.alphaSrcFactor,t.alphaDstFactor),this.setBlendState(Pt)};Je.prototype.setColorWrite=function(l,e,t,s){const i=this.blendState;Pt.copy(i),Pt.setColorWrite(l,e,t,s),this.setBlendState(Pt)};Je.prototype.getBlending=function(){return this.blendState.blend};Je.prototype.setBlending=function(l){Pt.copy(this.blendState),Pt.blend=l,this.setBlendState(Pt)};Je.prototype.setDepthWrite=function(l){xr.copy(this.depthState),xr.write=l,this.setDepthState(xr)};Je.prototype.setDepthFunc=function(l){xr.copy(this.depthState),xr.func=l,this.setDepthState(xr)};Je.prototype.setDepthTest=function(l){xr.copy(this.depthState),xr.test=l,this.setDepthState(xr)};Je.prototype.getCullMode=function(){return this.cullMode};new Proxy({},{get(l,e){return be.get(yi().graphicsDevice,ze).get(e)},set(l,e,t){return be.get(yi().graphicsDevice,ze).set(e,t),!0}});Object.defineProperty(ti.prototype,"defaultMaterial",{get:function(){return Zo(yi().graphicsDevice)}});Object.defineProperty(ti.prototype,"fogColor",{set:function(l){this.fog.color=l},get:function(){return this.fog.color}});Object.defineProperty(ti.prototype,"fogEnd",{set:function(l){this.fog.end=l},get:function(){return this.fog.end}});Object.defineProperty(ti.prototype,"fogStart",{set:function(l){this.fog.start=l},get:function(){return this.fog.start}});Object.defineProperty(ti.prototype,"fogDensity",{set:function(l){this.fog.density=l},get:function(){return this.fog.density}});Object.defineProperty(ti.prototype,"toneMapping",{set:function(l){},get:function(){}});Object.defineProperty(ti.prototype,"gammaCorrection",{set:function(l){},get:function(){}});Object.defineProperty(ti.prototype,"rendering",{set:function(l){},get:function(){}});Object.defineProperty(i_.prototype,"_meshInstances",{get:function(){return null}});Object.defineProperty(ti.prototype,"drawCalls",{get:function(){return null}});["128","64","32","16","8","4"].forEach((l,e)=>{Object.defineProperty(ti.prototype,`skyboxPrefiltered${l}`,{get:function(){return this._prefilteredCubemaps[e]},set:function(t){this._prefilteredCubemaps[e]=t,this.updateShaders=!0}})});Object.defineProperty(ti.prototype,"models",{get:function(){return this._models||(this._models=[]),this._models}});function es(l,e,t=""){Object.defineProperty(l.prototype,e,{set:function(s){},get:function(){}})}es(Kt,"renderTarget");es(Kt,"onPreCull");es(Kt,"onPreRender");es(Kt,"onPreRenderOpaque");es(Kt,"onPreRenderTransparent");es(Kt,"onPostCull");es(Kt,"onPostRender");es(Kt,"onPostRenderOpaque");es(Kt,"onPostRenderTransparent");es(Kt,"onDrawCall");es(Kt,"layerReference");es(ga,"onPreCull","Use Scene#EVENT_PRECULL event instead.");es(ga,"onPostCull","Use Scene#EVENT_POSTCULL event instead.");es(ga,"onPreRender","Use Scene#EVENT_PRERENDER event instead.");es(ga,"onPostRender","Use Scene#EVENT_POSTRENDER event instead.");es(ga,"onPreRenderLayer","Use Scene#EVENT_PRERENDER_LAYER event instead.");es(ga,"onPostRenderLayer","Use Scene#EVENT_POSTRENDER_LAYER event instead.");KT.prototype.renderComposition=function(l){yi().renderComposition(l)};Ne.prototype.syncAabb=function(){};zg.prototype.getTarget=function(l){return this.targets[l]};He.prototype.getChildren=function(){return this.children};He.prototype.getName=function(){return this.name};He.prototype.getPath=function(){return this.path};He.prototype.getRoot=function(){return this.root};He.prototype.getParent=function(){return this.parent};He.prototype.setName=function(l){this.name=l};Object.defineProperty(yn.prototype,"shader",{set:function(l){},get:function(){return null}});Object.defineProperty(yn.prototype,"blend",{set:function(l){this.blendState.blend=l},get:function(){return this.blendState.blend}});Object.defineProperty(Es.prototype,"shininess",{get:function(){return this.gloss*100},set:function(l){this.gloss=l*.01}});Object.defineProperty(Es.prototype,"useGammaTonemap",{get:function(){return this.useTonemap},set:function(l){this.useTonemap=l}});Object.defineProperty(Es.prototype,"anisotropy",{get:function(){const l=Math.sign(Math.cos(this.anisotropyRotation*H.DEG_TO_RAD*2));return this.anisotropyIntensity*l},set:function(l){this.anisotropyIntensity=Math.abs(l),l>=0?this.anisotropyRotation=0:this.anisotropyRotation=90}});function wi(l,e){Object.defineProperty(Es.prototype,e,{get:function(){return this[l]},set:function(t){this[l]=t}})}function kf(l){Object.defineProperty(Es.prototype,l,{get:function(){return!0},set:function(e){}})}kf("sheenTint");kf("diffuseTint");kf("emissiveTint");kf("ambientTint");wi("specularTint","specularMapTint");wi("aoVertexColor","aoMapVertexColor");wi("diffuseVertexColor","diffuseMapVertexColor");wi("specularVertexColor","specularMapVertexColor");wi("emissiveVertexColor","emissiveMapVertexColor");wi("metalnessVertexColor","metalnessMapVertexColor");wi("glossVertexColor","glossMapVertexColor");wi("opacityVertexColor","opacityMapVertexColor");wi("lightVertexColor","lightMapVertexColor");wi("sheenGloss","sheenGlossiess");wi("clearCoatGloss","clearCostGlossiness");function BC(l,e){l!=="pass"&&Object.defineProperty(yc.prototype,l,{get:function(){return this.litOptions[e||l]},set:function(t){this.litOptions[e||l]=t}})}BC("refraction","useRefraction");const h5=new vw,rx=Object.getOwnPropertyNames(h5);for(const l in rx)BC(rx[l]);Ew.prototype.getAssetById=function(l){return this.get(l)};Object.defineProperty(Nf.prototype,"ray",{get:function(){return this._rayLocal}});Object.defineProperty(Nf.prototype,"position",{get:function(){return this._localPosition}});Object.defineProperty(Nf.prototype,"rotation",{get:function(){return this._localRotation}});Object.defineProperty(Ga.prototype,"wheel",{get:function(){return this.wheelDelta*-2}});Ts.prototype.isFullscreen=function(){return!!document.fullscreenElement};Ts.prototype.enableFullscreen=function(l,e,t){l=l||this.graphicsDevice.canvas;const s=function(){e(),document.removeEventListener("fullscreenchange",s)},i=function(){t(),document.removeEventListener("fullscreenerror",i)};e&&document.addEventListener("fullscreenchange",s,!1),t&&document.addEventListener("fullscreenerror",i,!1),l.requestFullscreen?l.requestFullscreen(Element.ALLOW_KEYBOARD_INPUT):t()};Ts.prototype.disableFullscreen=function(l){const e=function(){l(),document.removeEventListener("fullscreenchange",e)};l&&document.addEventListener("fullscreenchange",e,!1),document.exitFullscreen()};Ts.prototype.getSceneUrl=function(l){const e=this.scenes.find(l);return e?e.url:null};Ts.prototype.loadScene=function(l,e){this.scenes.loadScene(l,e)};Ts.prototype.loadSceneHierarchy=function(l,e){this.scenes.loadSceneHierarchy(l,e)};Ts.prototype.loadSceneSettings=function(l,e){this.scenes.loadSceneSettings(l,e)};Zg.prototype.setVisible=function(l){this.enabled=l};Object.defineProperty(Eo.prototype,"bodyType",{get:function(){return this.type},set:function(l){this.type=l}});Eo.prototype.syncBodyToEntity=function(){this._updateDynamic()};Jw.prototype.setGravity=function(){arguments.length===1?this.gravity.copy(arguments[0]):this.gravity.set(arguments[0],arguments[1],arguments[2])};var d5=1347635022,u5=3,bc=[0,3,8,15,24],bm=.15,f5=2,p5=[-1,-1,1,-1,1,1,-1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,1,1,-1,1,-1,-1];function m5(l){if(l.length<16)return null;const e=new DataView(l.buffer,l.byteOffset,16);return e.getUint32(0,!0)!==d5?null:{version:e.getUint32(4,!0),numPoints:e.getUint32(8,!0),shDegree:e.getUint8(12),fractionalBits:e.getUint8(13),flags:e.getUint8(14)}}function _5(l,e){const t=l===1?6:9,s=l>=3?4:3;return t+1+3+3+s+e*3}async function g5(l,e){const t=new Uint8Array(l,0,2);if(t[0]!==31||t[1]!==139)throw new Error("Unsupported SPZ container (expected a gzip-compressed .spz file)");const i=new Response(l).body.pipeThrough(new DecompressionStream("gzip")).getReader();let r=null,a=0,n=null,o=0,c=[];const h=d=>{if(!n||d<=n.length)return;const u=new Uint8Array(Math.max(d,Math.ceil(n.length*1.5)));u.set(n.subarray(0,o)),n=u};for(;;){const{value:d,done:u}=await i.read();if(u)break;if(!n){c.push(d);let f=0;for(const g of c)f+=g.length;if(f<16)continue;const p=new Uint8Array(16);let m=0;for(const g of c){const v=Math.min(g.length,16-m);if(p.set(g.subarray(0,v),m),m+=v,m===16)break}if(r=m5(p),!r)throw new Error("Not an SPZ file (bad NGSP magic)");if(r.version===1)throw new Error("SPZ version 1 (float16) is not supported");if(r.version>u5)throw new Error(`SPZ version ${r.version} is not supported`);if(r.shDegree>=bc.length)throw new Error(`Unsupported SH degree ${r.shDegree}`);const _=bc[r.shDegree];a=16+r.numPoints*_5(r.version,_),n=new Uint8Array(a);for(const g of c)h(o+g.length),n.set(g,o),o+=g.length;c=null;continue}h(o+d.length),n.set(d,o),o+=d.length,a>0&&e(Math.min(1,o/a))}if(!r)throw new Error("SPZ stream ended before the header");
17035if(!n)throw new Error("SPZ stream ended with no data");if(o<a)throw new Error(`Truncated SPZ: expected ${a} bytes, got ${o}`);return r.flags&f5&&console.warn("[spz-decoder] SPZ has extension blocks; extensions are ignored."),{header:r,data:n.subarray(0,o)}}function v5(l,e,t){for(let s=e;s>0;s--){const i=14+bc[s]*3;if(l*i*4<=t)return s}return 0}async function S5(l,e={}){const{onProgress:t=()=>{},maxOutputBytes:s=2e9}=e,{header:i,data:r}=await g5(l,Y=>t(Y*.4)),{version:a,numPoints:n,shDegree:o,fractionalBits:c}=i,h=bc[o],d=v5(n,o,s),u=bc[d],f=a>=3?4:3,p=16,m=p+n*9,_=m+n,g=_+n*3,v=g+n*3,x=v+n*f,y=()=>new Float32Array(n),S=y(),T=y(),w=y(),C=y(),b=y(),I=y(),P=y(),L=y(),O=y(),D=y(),N=y(),k=y(),A=y(),M=y(),R=[];for(let Y=0;Y<u*3;Y++)R.push(y());const F=1/(1<<c),U=Math.SQRT1_2,B=511,z=new Float32Array(4),$=2e5;for(let Y=0;Y<n;Y+=$){const te=Math.min(n,Y+$);for(let J=Y;J<te;J++){let _e=p+J*9;for(let Ye=0;Ye<3;Ye++,_e+=3){let Ee=r[_e]|r[_e+1]<<8|r[_e+2]<<16;Ee&8388608&&(Ee-=16777216);const Pe=Ee*F;Ye===0?S[J]=Pe:Ye===1?T[J]=-Pe:w[J]=-Pe}const Ae=r[m+J]/255;P[J]=Math.log(Ae/(1-Ae));const we=_+J*3;C[J]=(r[we]/255-.5)/bm,b[J]=(r[we+1]/255-.5)/bm,I[J]=(r[we+2]/255-.5)/bm;const $e=g+J*3;if(L[J]=r[$e]/16-10,O[J]=r[$e+1]/16-10,D[J]=r[$e+2]/16-10,f===4){const Ye=v+J*4;let Ee=(r[Ye]|r[Ye+1]<<8|r[Ye+2]<<16|r[Ye+3]<<24)>>>0;const Pe=Ee>>>30;let ke=0;for(let ps=3;ps>=0;ps--){if(ps===Pe)continue;const se=Ee&B,Tn=Ee>>>9&1;Ee>>>=10;let bs=U*se/B;Tn&&(bs=-bs),z[ps]=bs,ke+=bs*bs}z[Pe]=Math.sqrt(Math.max(0,1-ke))}else{const Ye=v+J*3,Ee=r[Ye]/127.5-1,Pe=r[Ye+1]/127.5-1,ke=r[Ye+2]/127.5-1;z[0]=Ee,z[1]=Pe,z[2]=ke,z[3]=Math.sqrt(Math.max(0,1-(Ee*Ee+Pe*Pe+ke*ke)))}if(N[J]=z[3],k[J]=z[0],A[J]=-z[1],M[J]=-z[2],u>0){const Ye=x+J*h*3;for(let Ee=0;Ee<u;Ee++){const Pe=p5[Ee],ke=Ye+Ee*3;R[Ee][J]=(r[ke]-128)/128*Pe,R[u+Ee][J]=(r[ke+1]-128)/128*Pe,R[u*2+Ee][J]=(r[ke+2]-128)/128*Pe}}}t(.4+.6*(te/n)),te<n&&await new Promise(J=>setTimeout(J,0))}const K=[["x",S],["y",T],["z",w],["f_dc_0",C],["f_dc_1",b],["f_dc_2",I],["opacity",P],["scale_0",L],["scale_1",O],["scale_2",D],["rot_0",N],["rot_1",k],["rot_2",A],["rot_3",M]];for(let Y=0;Y<u*3;Y++)K.push([`f_rest_${Y}`,R[Y]]);return{count:n,shDegree:o,shDegreeKept:d,columns:K}}var NC={none:Rg,linear:bf,filmic:wI,aces:CI,neutral:EI},y5=new Map(Object.entries(NC).map(([l,e])=>[e,l])),x5=4,ax=!1,Am={mobile:{name:"mobile",maxPixelDim:1080,pixelRatioScale:{flat:.35,lod:.65},budgetCapMillions:{flat:1,lod:2},lodRangeMin:2,lodRangeMax:5,lodBaseDistance:24,lodMultiplier:2.5,lodUpdateAngle:90,lodUpdateDistance:1,lodUnderfillLimit:10,colorUpdateAngle:6,minPixelSize:{flat:3,lod:2.5},minContribution:{flat:5,lod:3},alphaClipForward:{flat:2/255,lod:1/255}},constrained:{name:"constrained",maxPixelDim:1440,pixelRatioScale:{flat:.55,lod:.75},budgetCapMillions:{flat:2,lod:2},lodRangeMin:2,lodRangeMax:5,lodBaseDistance:5,lodMultiplier:2,lodUpdateAngle:90,lodUpdateDistance:1,lodUnderfillLimit:10,colorUpdateAngle:4,minPixelSize:{flat:2.5,lod:2},minContribution:{flat:3,lod:2},alphaClipForward:{flat:1/255,lod:1/255}},desktop:{name:"desktop",maxPixelDim:2160,pixelRatioScale:{flat:1,lod:.75},budgetCapMillions:{flat:12,lod:8},lodRangeMin:0,lodRangeMax:1e3,lodBaseDistance:5,lodMultiplier:3,lodUpdateAngle:90,lodUpdateDistance:1,lodUnderfillLimit:10,colorUpdateAngle:2,minPixelSize:{flat:2,lod:2},minContribution:{flat:1,lod:1},alphaClipForward:{flat:1/255,lod:1/255}}};function Uf(){const l=typeof navigator<"u"?navigator:void 0;return{isMobile:Ce.mobile,devicePixelRatio:typeof window<"u"&&window.devicePixelRatio||1,screenWidth:typeof screen<"u"?screen.width:1,screenHeight:typeof screen<"u"?screen.height:1,maxTouchPoints:l?.maxTouchPoints??0,deviceMemory:l?.deviceMemory,hardwareConcurrency:l?.hardwareConcurrency}}function Xi(l=Uf()){if(l.isMobile)return Am.mobile;const e=Math.min(l.screenWidth||1,l.screenHeight||1),t=l.maxTouchPoints>1&&e<=1180,s=l.deviceMemory!==void 0&&l.deviceMemory<=4,i=l.hardwareConcurrency!==void 0&&l.hardwareConcurrency<=4;return t||s||i?Am.constrained:Am.desktop}function zf(l,e){return l==="sog-lod"||Bi(e).lodLevels>0?"lod":"flat"}function T5(l,e=Uf()){const t=Xi(e),s=zf(l),i=Math.min(e.screenWidth||1,e.screenHeight||1);return Math.min(t.maxPixelDim/i,e.devicePixelRatio||1)*t.pixelRatioScale[s]}var w5=4,nx=8;function tv(l,e,t,s=Uf()){const i=Xi(s),r=zf(e,t),a=i.budgetCapMillions[r],{splatCount:n}=Bi(t),o=n!==void 0?n/1e6:void 0;if(i.name==="desktop"&&o!==void 0){const h=l>0?Math.min(l,o):o;return Math.min(h,a)}const c=l>0?l:w5;return Math.min(c,a)}function kC(l,e,t,s,i=Uf()){const r=tv(e,t,s,i);
17035if(l!=="highest"||Xi(i).name!=="desktop")return r;const{splatCount:n}=Bi(s),o=n!==void 0?n/1e6:nx;return Math.max(r,Math.min(nx,o))}function C5(l){const e=typeof l[0]=="string"?l[0]:"";return e.startsWith("WebgpuGraphicsDevice initialization")||e.startsWith("WEBGPU (")||e.startsWith("Powered by PlayCanvas")}function E5(l){return!(l instanceof DOMException)||l.name!=="AbortError"?!1:l.message.includes("mapAsync")&&l.message.includes("unmapped before mapping was resolved")}function b5(){ax||(ax=!0,window.addEventListener("unhandledrejection",l=>{E5(l.reason)&&l.preventDefault()}))}async function ox(l){const e=console.log,t=console.info,s=i=>(...r)=>{C5(r)||i.apply(console,r)};console.log=s(e),console.info=s(t);try{return await l()}finally{console.log=e,console.info=t}}async function A5(l,e={}){const t=e.background??[0,0,0],{app:s,device:i,renderer:r}=await ox(async()=>{const x=await OP(l,{deviceTypes:e.forceWebgl?[]:["webgpu"],antialias:!1,depth:!0,stencil:!1,powerPreference:"high-performance"});x.maxPixelRatio=T5(e.format);const y=x.deviceType==="webgpu"?"webgpu":"webgl";return{app:new c5(l,{graphicsDevice:x,mouse:new sI(l),touch:new rI(l),keyboard:new tI(window)}),device:x,renderer:y}}),a=s.loader.getHandler("texture");a?.imgParser&&(a.imgParser.crossOrigin="anonymous"),s.setCanvasFillMode(AR),s.setCanvasResolution(n_),H5(s.graphicsDevice),V5(s);const n=s.scene.gsplat;n&&(n.renderer=uo),s.autoRender=!1;let o=0;const c={fps:0,frameMs:0,renderedFrames:0},h=()=>{o=0,s.renderNextFrame=!0},d=x=>{if(x>0){const y=1/x,S=x*1e3;c.fps=c.fps?c.fps*.9+y*.1:y,c.frameMs=c.frameMs?c.frameMs*.9+S*.1:S}o+=x,o<x5&&(s.renderNextFrame=!0)};s.on("update",d);const u=()=>{c.renderedFrames+=1};s.on("postrender",u);const f=s.systems.gsplat,p=(...x)=>{const y=x[2],S=x[3];(!y||typeof S=="number"&&S>0)&&h()};f?.on?.("frame:ready",p),s.scene.ambientLight.set(.51,.55,.65);const m=new lt("camera");m.addComponent("camera",{clearColor:new Q(t[0],t[1],t[2]),fov:e.fov??75,nearClip:.1,farClip:1e3}),s.root.addChild(m);const _=new ResizeObserver(()=>{s.resizeCanvas(),h()});_.observe(l),await ox(()=>s.start()),h();let g=!1;return{app:s,camera:m,renderer:r,frameStats:c,requestRender:h,dispose:()=>{if(g)return;g=!0,_.disconnect(),s.off("update",d),s.off("postrender",u),f?.off?.("frame:ready",p);const x=i.gpuContext,y=i.wgpu,S=i.gl;s.destroy();try{x?.unconfigure?.()}catch{}b5(),y?.destroy?.(),S?.getExtension?.("WEBGL_lose_context")?.loseContext?.()}}}async function P5(l,e,t={}){const{transform:s="none",onProgress:i}=t,a=new URL(e,window.location.href).pathname.split("/").pop()||"scene",n=a.toLowerCase()==="meta.json"?await(await fetch(e)).json():void 0,o=new pe(a,"gsplat",{url:e,filename:a},n);return new Promise((c,h)=>{if(o.once("load",()=>{const d=new lt("gsplat");d.setLocalEulerAngles(s==="flip-yz"?180:0,0,0),d.addComponent("gsplat",{unified:!0,asset:o}),l.root.addChild(d),c(d)}),i){let d=0;o.on("progress",(u,f)=>{if(!f)return;const p=Math.min(1,u/f)*100;p>d&&(d=p,i(Math.trunc(d)))})}o.once("error",d=>h(new Error(d))),l.assets.add(o),l.assets.load(o)})}function I5(l,e,t){const s=t.map(([n,o])=>({name:n,type:"float",byteSize:Float32Array.BYTES_PER_ELEMENT,storage:o})),i=new ha([{name:"vertex",count:e,properties:s}]),r=new Ff(l,i),a=new lt("gsplat");return a.addComponent("gsplat",{unified:!0,resource:r}),a}async function D5(l,e){let t=35;const s=u=>{const f=Math.max(t,Math.min(90,u));f!==t&&(t=f,e?.(f))},i=await fetch(l);if(!i.ok)throw new Error(`SPZ download failed (${i.status})`);const r=i.headers.get("content-length"),a=r?Number(r):0,n=i.body?.getReader();if(!n)return i.arrayBuffer();const o=[];let c=0;for(;;){const{done:u,value:f}=await n.read();if(u)break;f&&(o.push(f),c+=f.byteLength,a>0?s(35+Math.min(1,c/a)*35):s(Math.min(70,35+Math.log10(c+1)*6)))}const h=new Uint8Array(c);let d=0;for(const u of o)h.set(u,d),d+=u.byteLength;return s(70),h.buffer}function lx(){return new Promise(l=>setTimeout(l,0))}async function M5(l,e,t={}){const{onProgress:s}=t;s?.(35);const i=await D5(e,s);await lx();let r;try{r=await S5(i,{onProgress:n=>{s?.(70+Math.trunc(n*15))}})}catch(n){const o=n instanceof Error?n.message:String(n),c=new Error(`SPZ decode failed: ${o}`);throw c.spzTooLarge=/memory|allocat/i.test(o),c}r.shDegreeKept<r.shDegree&&console.warn(`[pc-splat-viewer] Large SPZ: kept SH degree ${r.shDegreeKept}/${r.shDegree} to fit browser memory`),s?.(85),await lx();const a=I5(l.graphicsDevice,r.count,r.columns);return l.root.addChild(a),s?.(90),a}async function R5(l,e,t={}){const{format:s,transform:i="none",onProgress:r}=t;return s==="spz"?M5(l,e,{onProgress:r}):P5(l,e,{transform:i,onProgress:r})}function L5(l,e){return l==="spz"?"none":e==="flip-yz"?"x180":"none"}function F5(l,e,t={}){const s=l.scene.gsplat;if(!s)return;const i=Xi(),r=zf(t.format,e),a=kC(t.lodQualityPreset,t.budgetMillions??4,t.format,e);s.splatBudget=a*1e6;const[n,o]=t.lodQualityPreset&&r==="lod"?zC(t.lodQualityPreset,e):O5(i.lodRangeMin,i.lodRangeMax,e);s.lodRangeMin=n,s.lodRangeMax=o,s.lodUpdateAngle=i.lodUpdateAngle,s.lodUpdateDistance=i.lodUpdateDistance,s.lodUnderfillLimit=i.lodUnderfillLimit,s.lodBehindPenalty=5;
17035const c=t.renderSettings;s.radialSorting=c?!!c.radialSorting:!0,s.antiAlias=c?!!c.antialiased:!1,s.colorUpdateAngle=i.colorUpdateAngle,s.minPixelSize=i.minPixelSize[r],s.minContribution=i.minContribution[r],s.alphaClip=1/255,s.alphaClipForward=i.alphaClipForward[r],VC(e,i),GC(e,n,o)}function va(l){return l.scene.gsplat}function Bi(l){const e=l?.gsplat?.resource;return{splatCount:e?.numSplats??e?.splatCount??e?.numSplatsTotal,lodLevels:e?.octree?.lodLevels??0}}function O5(l,e,t,s=Xi()){const i=Bi(t).lodLevels,r=i>0?i-1:s.lodRangeMax,a=Math.min(s.lodRangeMin,r),n=Math.min(s.lodRangeMax,r),o=Math.max(a,Math.min(l,r)),c=Math.max(o,Math.min(e,n));return[o,c]}function UC(l,e,t){const s=Bi(t).lodLevels,i=s>0?s-1:Xi().lodRangeMax,r=Math.max(0,Math.min(l,i)),a=Math.max(r,Math.min(e,i));return[r,a]}function U_(l,e,t=Xi()){const s=e>0?e-1:2;return l==="highest"?0:l==="fast"?s:t.name==="desktop"?Math.min(1,s):Math.min(2,s)}function zC(l,e){const t=Bi(e).lodLevels,s=U_(l,t),i=t>0?t-1:1e3;return UC(s,Math.max(s,i),e)}function VC(l,e=Xi()){const t=l?.gsplat;t&&(t.lodBaseDistance=e.lodBaseDistance,t.lodMultiplier=e.lodMultiplier)}function GC(l,e,t){const s=l?.gsplat;s&&(s.lodRangeMin=e,s.lodRangeMax=t)}function Pm(l){const e=va(l);return e?{budgetMillions:(e.splatBudget??4e6)/1e6,lodRangeMin:e.lodRangeMin??0,lodRangeMax:e.lodRangeMax??1e3}:null}function B5(l,e,t,s){const i=va(l);i&&(i.splatBudget=tv(e,t,s)*1e6)}function z_(l,e,t,s){const i=va(l);if(!i)return;const[r,a]=UC(e,t,s);i.lodRangeMin=r,i.lodRangeMax=a,GC(s,r,a)}function N5(l,e,t,s){const[i,r]=zC(e,t);z_(l,i,r,t);const a=va(l);a&&(a.splatBudget=kC(e,0,s,t)*1e6)}var sv=2,sa=1e9,k5=` 17036uniform float minimapClipMaxY; 17037 17038void modifySplatCenter(inout vec3 center) { 17039} 17040 17041void modifySplatRotationScale(vec3 originalCenter, vec3 modifiedCenter, inout vec4 rotation, inout vec3 scale) { 17042 if (modifiedCenter.y > minimapClipMaxY) { 17043 scale = vec3(0.0); 17044 } 17045} 17046 17047void modifySplatColor(vec3 center, inout vec4 color) { 17048} 17049`,U5=` 17050uniform minimapClipMaxY: f32; 17051 17052fn modifySplatCenter(center: ptr<function, vec3f>) { 17053} 17054 17055fn modifySplatRotationScale(originalCenter: vec3f, modifiedCenter: vec3f, rotation: ptr<function, vec4f>, scale: ptr<function, vec3f>) { 17056 if (modifiedCenter.y > uniform.minimapClipMaxY) { 17057 *scale = vec3f(0.0); 17058 } 17059} 17060 17061fn modifySplatColor(center: vec3f, color: ptr<function, vec4f>) { 17062} 17063`;function HC(l){l.shaderChunksVersion="2.19",l.getShaderChunks?.(ze)?.set("gsplatModifyVS",k5),l.getShaderChunks?.(de)?.set("gsplatModifyVS",U5),l.setParameter?.("minimapClipMaxY",sa),l.update?.()}function z5(l,e){const t=Number.isFinite(e)?e:sa;l.graphicsDevice.scope.resolve("minimapClipMaxY").setValue(t);const s=va(l)?.material;s&&(s.setParameter?.("minimapClipMaxY",t),s.update?.())}function V5(l){const e=va(l)?.material;e&&HC(e),l.graphicsDevice.scope.resolve("minimapClipMaxY").setValue(sa)}function G5(l){const e=va(l);e&&(e.dirty=!0)}function H5(l){const e=(t,s,i)=>{const r=be.get(l,t);let a=r.get(s);if(!a){console.warn(`[pc-splat-viewer] missing shader chunk ${s}`);return}for(const[n,o]of i){if(!a.includes(n)){console.warn(`[pc-splat-viewer] point-mode anchor not found in ${s}: ${n}`);return}a=a.replace(n,o)}r.set(s,a)};e(de,"gsplatHybridVS",[["uniform clipToViewZ: vec4f;",`uniform clipToViewZ: vec4f; 17064uniform splatPointMode: f32; 17065uniform splatPointPixels: f32;`],["let pixelOffset = cornerClipped.x * v1 + cornerClipped.y * v2;",`var v1p = v1; 17066 var v2p = v2; 17067 if (uniform.splatPointMode > 0.5) { 17068 v1p = v1 * (uniform.splatPointPixels / max(length(v1), 1e-6)); 17069 v2p = v2 * (uniform.splatPointPixels / max(length(v2), 1e-6)); 17070 } 17071 let pixelOffset = cornerClipped.x * v1p + cornerClipped.y * v2p;`]]),e(de,"gsplatCornerVS",[["uniform minPixelSize: f32;",`uniform minPixelSize: f32; 17072uniform splatPointMode: f32; 17073uniform splatPointPixels: f32;`],["let v1 = l1 * diagonalVector;",`var l1p = l1; 17074 var l2p = l2; 17075 if (uniform.splatPointMode > 0.5) { 17076 l1p = uniform.splatPointPixels; 17077 l2p = uniform.splatPointPixels; 17078 } 17079 let v1 = l1p * diagonalVector;`],["let v2 = l2 * vec2f(diagonalVector.y, -diagonalVector.x);","let v2 = l2p * vec2f(diagonalVector.y, -diagonalVector.x);"]]),e(ze,"gsplatCornerVS",[["uniform float minPixelSize;",`uniform float minPixelSize; 17080uniform float splatPointMode; 17081uniform float splatPointPixels;`],["vec2 v1 = l1 * diagonalVector;",`if (splatPointMode > 0.5) { 17082 l1 = splatPointPixels; 17083 l2 = splatPointPixels; 17084 } 17085 vec2 v1 = l1 * diagonalVector;`]]),l.scope.resolve("splatPointMode").setValue(0),l.scope.resolve("splatPointPixels").setValue(sv)}var cx=new WeakMap;function W5(l){const e=cx.get(l)??1;cx.set(l,-e);const t=l.getLocalPosition();l.setLocalPosition(t.x,t.y+e*1e-5,t.z)}var X5=` 17086 vec4 q = rotation; 17087 vec3 col0 = vec3(1.0 - 2.0*(q.y*q.y + q.z*q.z), 2.0*(q.x*q.y + q.w*q.z), 2.0*(q.x*q.z - q.w*q.y)); 17088 vec3 col1 = vec3(2.0*(q.x*q.y - q.w*q.z), 1.0 - 2.0*(q.x*q.x + q.z*q.z), 2.0*(q.y*q.z + q.w*q.x)); 17089 vec3 col2 = vec3(2.0*(q.x*q.z + q.w*q.y), 2.0*(q.y*q.z - q.w*q.x), 1.0 - 2.0*(q.x*q.x + q.y*q.y)); 17090 if (scale.x <= scale.y && scale.x <= scale.z) { gsplatNormalWS = col0; } 17091 else if (scale.y <= scale.x && scale.y <= scale.z) { gsplatNormalWS = col1; } 17092 else { gsplatNormalWS = col2; }
17093 gsplatNormalWS = normalize(gsplatNormalWS);`,Y5=` 17094 let q = *rotation; 17095 let s = *scale; 17096 let col0 = vec3f(1.0 - 2.0*(q.y*q.y + q.z*q.z), 2.0*(q.x*q.y + q.w*q.z), 2.0*(q.x*q.z - q.w*q.y)); 17097 let col1 = vec3f(2.0*(q.x*q.y - q.w*q.z), 1.0 - 2.0*(q.x*q.x + q.z*q.z), 2.0*(q.y*q.z + q.w*q.x)); 17098 let col2 = vec3f(2.0*(q.x*q.z + q.w*q.y), 2.0*(q.y*q.z - q.w*q.x), 1.0 - 2.0*(q.x*q.x + q.y*q.y)); 17099 if (s.x <= s.y && s.x <= s.z) { gsplatNormalWS = normalize(col0); } 17100 else if (s.y <= s.x && s.y <= s.z) { gsplatNormalWS = normalize(col1); } 17101 else { gsplatNormalWS = normalize(col2); }`;function j5(l,e,t){const s=t!==null?` 17102 if (modifiedCenter.y > ${t.toFixed(6)}) { scale = vec3(0.0); return; }`:"",i=t!==null?` 17103 if (modifiedCenter.y > ${t.toFixed(6)}) { *scale = vec3f(0.0); return; }`:"";return{glsl:` 17104vec3 gsplatNormalWS = vec3(0.0, 0.0, 1.0); 17105void modifySplatCenter(inout vec3 center) {} 17106void modifySplatRotationScale(vec3 originalCenter, vec3 modifiedCenter, inout vec4 rotation, inout vec3 scale) {${s}${e?X5:""}} 17107void modifySplatColor(vec3 center, inout vec4 color) { 17108${e?" color.rgb = gsplatNormalWS * 0.5 + vec3(0.5);":""} 17109${l?" color.a = 1.0;":""} 17110} 17111`,wgsl:` 17112var<private> gsplatNormalWS: vec3f = vec3f(0.0, 0.0, 1.0); 17113fn modifySplatCenter(center: ptr<function, vec3f>) {} 17114fn modifySplatRotationScale(originalCenter: vec3f, modifiedCenter: vec3f, rotation: ptr<function, vec4f>, scale: ptr<function, vec3f>) {${i}${e?Y5:""}} 17115fn modifySplatColor(center: vec3f, color: ptr<function, vec4f>) { 17116${e?" (*color) = vec4f(gsplatNormalWS * 0.5 + vec3f(0.5), (*color).a);":""} 17117${l?" (*color).a = 1.0;":""} 17118} 17119`}}function Im(l,e,t){const{pointMode:s,normalMode:i}=t,r=t.minimapClipMaxY??null,a=r!==null&&Number.isFinite(r)&&r<sa/2;z5(l,a&&r!==null?r:sa);const n=e?.gsplat,o=va(l),c=l.graphicsDevice;c.scope.resolve("splatPointMode").setValue(s?1:0),c.scope.resolve("splatPointPixels").setValue(t.pointSizePx??sv);const h=()=>{if(!o)return;const d=Xi(),u=zf(t.format,e);o.minPixelSize=d.minPixelSize[u]};if(!n?.setWorkBufferModifier){h();return}n.setWorkBufferModifier(j5(s,i,a?r:null)),a||G5(l),e&&W5(e),o&&s?o.minPixelSize=1:h()}function q5(l,e){const t=l.camera;t&&(t.toneMapping=NC[e])}function hx(l){const t=l.camera?.toneMapping;return(t!==void 0?y5.get(t):void 0)??"none"}function $5(l,e){return new Promise((t,s)=>{const i=new pe("skybox","texture",{url:e},{type:"rgbp",mipmaps:!1,addressu:"repeat",addressv:"clamp"});i.once("load",()=>{l.scene.envAtlas=i.resource,t()}),i.once("error",r=>s(new Error(r))),l.assets.add(i),l.assets.load(i)})}function K5(l,e,t=4,s){const i=l.scene.gsplat;i&&(i.splatBudget=tv(t,s,e)*1e6),VC(e);const r=Bi(e).lodLevels;return i&&r?(i.lodRangeMin=r-1,i.lodRangeMax=r-1,!0):!1}function Z5(l,e,t=12e3,s={}){return new Promise((i,r)=>{const a=l.systems.gsplat;if(!a?.on){i();return}let n=!1,o=1,c=!1;const h=performance.now(),d=s.observeGraceMs??600;let u;const f=(..._)=>{const g=_[2],v=_[3];typeof v=="number"&&v>0&&(c=!0,o=Math.max(o,v),e?.(Math.trunc((o-v)/o*100)));const x=s.requireLoadingZero?v===0:v===0||v===void 0,y=!s.requireObservedLoading||c||performance.now()-h>=d;g&&x&&y&&m()},p=()=>{n||(n=!0,a.off?.("frame:ready",f),u&&clearTimeout(u))},m=()=>{p(),i()};a.on("frame:ready",f),l.renderNextFrame=!0,u=setTimeout(()=>{if(p(),s.rejectOnTimeout){r(new Error("Timed out waiting for complete gsplat frame"));return}i()},t)})}var pt=Math.PI/180,dx=.005,Q5=.01,Fl=800,J5=55,eX=89,tX=6,Xa=1e9;function sX(l,e,t,s){const i=l<s-.001,r=e<s-.001;return i!==r?t<.5?l:e:l+(e-l)*t}function Pu(l,e,t,s,i,r){const a=l<Xa/2,n=e<Xa/2;if(a&&n)return l+(e-l)*t;if(!a&&!n)return i;const o=a?l:e;return s>o-r?o:i}var iX=1.5,rX=.2,aX=1.3,nX=.2,oX=.15,lX=.1,cX=64,ux=1/30,fx=.25,pd=1/60,hX=10,dX=9.8,uX=57,fX=1,pX=.1,mX=4,_X=.001,gX=5,px=3,vX=.01;function md(l,e=null){const t=nX*l,s=rX*l,i=e!==null&&Number.isFinite(e)&&e>0?e*l:null,r=iX*l,a=Math.max(i!==null?i-t:aX*l,s);return{capsuleHeight:r,capsuleRadius:s,eyeHeight:a,hoverHeight:t,maxStep:lX*l,maxClimb:oX*l,gravity:dX*l,groundProbeRange:fX*l,freefallThreshold:pX*l,jumpSpeed:mX*l,settleVelocity:_X*l,spawnSearchRadius:gX*l}}var SX=class{app;entity;canvas;pivot=new E;yaw=0;pitch=0;distance=4;fov=50;up=new E(0,1,0);rollSign=1;initial={pivot:new E,yaw:0,pitch:0,distance:4,fov:50};navigationEyeY=null;moveSpeed=px;moveSpeedMeters=null;worldScale=1;walkModeHeightMeters=null;autoWalkRestHeightMeters=null;walkDims=md(1);cameraMode="fly";hasCollision=!1;collider=null;colliderSignX=1;colliderSignY=1;colliderSignZ=1;walkEyeY=0;walkVelocityY=0;walkGrounded=!1;walkAccumulator=0;walkJumping=!1;walkJumpHeld=!1;walkForceStep=!1;
17119walkBounds=null;pointers=new Map;pinchDistance=0;keys=new Set;externalForward=!1;externalBackward=!1;externalLeft=!1;externalRight=!1;externalSpeedMultiplier=1;autoMode="off";autoSpeed=.8;autoVerticalSpeed=.3;autoDollySpeed=0;autoRadius=4;autoAngle=0;autoBaseHeight=0;autoPivot=new E;autoForward=new E;externallyDriven=!1;dollhouse=!1;dollhouseRoofCutY=null;pendingRoofCloseY=null;roofCutListener=null;dollhouseJumpListener=null;resetTween=null;tweenQuat=new ae;tweenMat=new Z;trajectory=null;trajPos=new E;trajAhead=new E;trajForward=new E;orbitSpeed=.115;panSpeed=.002;tmpA=new E;tmpB=new E;tmpC=new E;dir=new E;pos=new E;pushOut={x:0,y:0,z:0};requestRender;constructor(l,e,t,s){this.app=l,this.entity=e,this.canvas=t,this.requestRender=s??(()=>{this.app.renderNextFrame=!0}),this.attach()}setPose(l,e,t){this.pivot.copy(e),this.dir.sub2(l,e),this.distance=Math.max(this.dir.length(),.001),this.pitch=Math.asin(Bt(this.dir.y/this.distance,-1,1))/pt,this.yaw=Math.atan2(this.dir.x,this.dir.z)/pt,this.fov=t,this.initial={pivot:this.pivot.clone(),yaw:this.yaw,pitch:this.pitch,distance:this.distance,fov:this.fov},this.walkEyeY=l.y,this.navigationEyeY===null&&(this.navigationEyeY=l.y),this.walkVelocityY=0,this.walkGrounded=!1,this.walkAccumulator=0,this.walkJumping=!1,this.walkJumpHeld=!1,this.apply(),this.cameraMode==="walk"&&this.hasCollision&&(this.spawnWalk(),this.walkForceStep=!0,this.syncWalkPivotY(),this.apply())}setWorldScale(l){const e=Number.isFinite(l)&&l>0?l:1;e!==this.worldScale&&(this.worldScale=e,this.walkDims=md(e,this.effectiveWalkHeightMeters()),this.syncMoveSpeed(),this.cameraMode==="walk"&&(this.walkForceStep=!0,this.requestRender()))}getWorldScale(){return this.worldScale}setMoveSpeed(l){const e=l!==null&&Number.isFinite(l)&&l>0?l:null;e!==this.moveSpeedMeters&&(this.moveSpeedMeters=e,this.syncMoveSpeed())}getMoveSpeed(){return this.moveSpeedMeters}syncMoveSpeed(){this.moveSpeed=(this.moveSpeedMeters??px)*this.worldScale}setWalkModeHeight(l){const e=l!==null&&Number.isFinite(l)&&l>0?l:null;if(e===this.walkModeHeightMeters)return;const t=this.walkDims.hoverHeight+this.walkDims.eyeHeight;if(this.walkModeHeightMeters=e,this.walkDims=md(this.worldScale,this.effectiveWalkHeightMeters()),this.cameraMode==="walk"){const s=this.walkDims.hoverHeight+this.walkDims.eyeHeight;this.walkEyeY+=s-t,this.walkVelocityY=0,this.walkGrounded=!1,this.walkForceStep=!0,this.syncWalkPivotY(),this.apply(),this.requestRender()}}getWalkModeHeight(){return this.walkModeHeightMeters}effectiveWalkHeightMeters(){return this.walkModeHeightMeters??this.autoWalkRestHeightMeters}ensureAutoWalkHeight(l){if(this.walkModeHeightMeters!==null||this.autoWalkRestHeightMeters!==null||this.navigationEyeY===null)return;const e=this.navigationEyeY-l,t=this.walkDims.hoverHeight+this.walkDims.capsuleRadius,s=this.collider?.gridBounds,i=s?s.max[1]-s.min[1]:Number.POSITIVE_INFINITY;!(e>t)||e>i||(this.autoWalkRestHeightMeters=e/this.worldScale,this.walkDims=md(this.worldScale,this.effectiveWalkHeightMeters()))}getFov(){return this.fov}getCameraMode(){return this.cameraMode}getCameraPose(){const l=this.entity.getPosition(),e=this.pivot;return{position:[l.x,l.y,l.z],target:[e.x,e.y,e.z],yawDegrees:this.yaw,pitchDegrees:this.pitch,fov:this.fov}}navigateToXZ(l,e,t=Fl){if(!Number.isFinite(l)||!Number.isFinite(e))return!1;this.stopAutoCamera();const s=this.getCameraPose(),i=this.resolveNavigationPosition(l,e);if(!i)return!1;const r=this.tmpA.copy(this.entity.forward);r.length()<=1e-6&&r.set(0,0,-1),r.normalize();const a=this.tmpB.copy(i).add(r.mulScalar(this.distance)),n=this.orbitStateFromPose(i,a,s.fov);return this.startResetTween(n,t),!0}playPath(l,e={}){if(!Array.isArray(l)||l.length<2)return!1;this.stopAutoCamera(),this.resetTween=null;const t=this.buildPathEyePositions(l);if(t.length<2)return!1;const s=TX(t),i=[0];let r=0;for(let o=1;o<s.length;o++)r+=s[o].distance(s[o-1]),i.push(r);if(!(r>0))return!1;const a=e.speed&&e.speed>0?e.speed:this.moveSpeed,n=e.durationMs&&e.durationMs>0?e.durationMs:Math.max(250,r/a*1e3);return this.trajectory={points:s,cumulative:i,total:r,pitchDegrees:Number.isFinite(e.pitchDegrees)?e.pitchDegrees:0,elapsedMs:0,durationMs:n,loop:!!e.loop,smoothForward:null,onProgress:e.onProgress,onDone:e.onDone},this.requestRender(),!0}playPoseKeyframes(l,e={}){if(!Array.isArray(l)||l.length<2)return!1;this.stopAutoCamera(),this.resetTween=null;const t=[],s=[],i=[],r=[];let a=[],n=!1;for(const P of l){if(!P||!Array.isArray(P.position))continue;const L=new E(P.position[0],P.position[1],P.position[2]),O=t.length-1;if(O>=0){const N=t[O].distance(L)<1e-4,k=Math.abs(V_(s[O],P.yaw))<.5,A=Math.abs(i[O]-P.pitch)<.5;if(N&&k&&A)continue}t.push(L),s.push(P.yaw),i.push(P.pitch),r.push(Number.isFinite(P.fov)?P.fov:this.fov);const D=typeof P.roofCut=="number"&&Number.isFinite(P.roofCut)?P.roofCut:Xa;a.push(D),D<Xa/2&&(n=!0)}if(t.length<2)return!1;const o=this.roofFullyVisibleY(a.find(P=>P<Xa/2)??0),c=fx*this.worldScale;let h=t,d=s,u=i,f=r,p=a;if(e.route!==!1){h=[],d=[],u=[],f=[],p=[];for(let P=0;P<t.length-1;P++){const L=this.planKeyframeRoute(t[P],t[P+1]),O=[0];let D=0;for(let N=1;N<L.length;N++)D+=L[N].distance(L[N-1]),O.push(D);for(let N=0;N<L.length-1;N++){const k=D>1e-6?O[N]/D:0;h.push(L[N]),d.push(kd(s[P],s[P+1],k)),u.push(i[P]+(i[P+1]-i[P])*k),f.push(r[P]+(r[P+1]-r[P])*k),p.push(Pu(a[P],a[P+1],k,L[N].y,o,c))}}h.push(t[t.length-1]),d.push(s[s.length-1]),u.push(i[i.length-1]),f.pu
17119sh(r[r.length-1]),p.push(a[a.length-1])}const m=EX(h,d,u,f,n?p:void 0,n?o:void 0,c),{points:_,yaws:g,pitches:v,fovs:x,roofCuts:y}=m,S=e.turnSpeed&&e.turnSpeed>0?e.turnSpeed:1,T=12*this.worldScale/S,w=[0];let C=0;for(let P=1;P<_.length;P++){const L=_[P].distance(_[P-1]),O=Math.abs(V_(g[P-1],g[P])),D=Math.abs(v[P]-v[P-1]),N=(O+D)*pt*T;C+=L+N,w.push(C)}if(!(C>0))return!1;const b=e.speed&&e.speed>0?e.speed:this.moveSpeed,I=e.durationMs&&e.durationMs>0?e.durationMs:Math.max(250,C/b*1e3);if(this.dollhouse=!1,n){const P=Pu(a[0],a[1],0,t[0].y,o,c);this.roofCutListener?.(P>=o-.001?null:P)}return this.trajectory={points:_,cumulative:w,total:C,pitchDegrees:0,elapsedMs:0,durationMs:I,loop:!!e.loop,smoothForward:null,yaws:g,pitches:v,fovs:x,roofCuts:y,roofCutOpenY:n?o:void 0,onProgress:e.onProgress,onDone:e.onDone},this.requestRender(),!0}routeWalkWaypoints(l,e=0){if(!Array.isArray(l)||l.length<2)return[];const t=[],s=(r,a)=>{const n=t[t.length-1];n&&Math.hypot(n.x-r,n.z-a)<.001||t.push({x:r,z:a})};for(let r=0;r<l.length-1;r++){const a=l[r],n=l[r+1];if(!a?.position||!n?.position)continue;const o=new E(a.position[0],a.position[1],a.position[2]),c=new E(n.position[0],n.position[1],n.position[2]),h=this.planKeyframeRoute(o,c,e);for(let d=0;d<h.length-1;d++)s(h[d].x,h[d].z)}const i=l[l.length-1];return i?.position&&s(i.position[0],i.position[2]),t}stopPath(){this.trajectory&&(this.trajectory=null,this.cameraMode="fly",this.syncFromCameraPose(),this.requestRender())}isPlayingPath(){return this.trajectory!==null}getActivePathDurationMs(){return this.trajectory?this.trajectory.durationMs:null}stepTrajectory(l){const e=this.trajectory;if(!e)return;e.elapsedMs+=l*1e3;let t=!1,s=e.durationMs>0?e.elapsedMs/e.durationMs:1;s>=1&&(e.loop?(e.elapsedMs%=e.durationMs,s=e.durationMs>0?e.elapsedMs/e.durationMs:0):(s=1,t=!0));const i=s*e.total,r=this.sampleTrajectoryAt(e,i,this.trajPos);if(e.yaws&&e.pitches){const c=kd(e.yaws[r.i],e.yaws[r.i+1],r.t),h=e.pitches[r.i]+(e.pitches[r.i+1]-e.pitches[r.i])*r.t,d=e.fovs?e.fovs[r.i]+(e.fovs[r.i+1]-e.fovs[r.i])*r.t:this.fov;if(e.roofCuts){const u=e.roofCutOpenY??Xa,f=sX(e.roofCuts[r.i],e.roofCuts[r.i+1],r.t,u);this.roofCutListener?.(f>=u-.001?null:f)}
17119if(e.smoothYaw==null||e.smoothPitch==null)e.smoothYaw=c,e.smoothPitch=h;else{const u=1-Math.exp(-8*l);e.smoothYaw=kd(e.smoothYaw,c,u),e.smoothPitch+=(h-e.smoothPitch)*u}if(this.applyKeyframePose(this.trajPos,e.smoothYaw,e.smoothPitch,d),e.onProgress?.(s),t){const u=e.onDone;this.trajectory=null,this.syncFromCameraPose(),u?.()}return}const a=Math.max(e.total*.06,1e-4);this.sampleTrajectoryAt(e,Math.min(i+a,e.total),this.trajAhead);let n=this.trajAhead.x-this.trajPos.x,o=this.trajAhead.z-this.trajPos.z;if(n*n+o*o<1e-8&&(this.sampleTrajectoryAt(e,Math.max(i-a,0),this.trajAhead),n=this.trajPos.x-this.trajAhead.x,o=this.trajPos.z-this.trajAhead.z),this.trajForward.set(n,0,o),this.trajForward.length()>1e-6?this.trajForward.normalize():this.trajForward.set(0,0,-1),e.smoothForward){const c=1-Math.exp(-8*l);e.smoothForward.lerp(e.smoothForward,this.trajForward,c),e.smoothForward.length()>1e-6?e.smoothForward.normalize():e.smoothForward.copy(this.trajForward)}else e.smoothForward=this.trajForward.clone();if(this.applyTrajectoryPose(this.trajPos,e.smoothForward,e.pitchDegrees),e.onProgress?.(s),t){const c=e.onDone;this.trajectory=null,this.cameraMode="fly",this.syncFromCameraPose(),c?.()}}sampleTrajectoryAt(l,e,t){const s=l.points,i=l.cumulative,r=s.length;if(r===1)return t.copy(s[0]),{i:0,t:0};const a=Bt(e,0,l.total);let n=0;for(;n<r-2&&i[n+1]<a;)n++;const o=i[n],c=i[n+1]-o,h=c>1e-9?Bt((a-o)/c,0,1):0;return t.lerp(s[n],s[n+1],h),{i:n,t:h}}applyKeyframePose(l,e,t,s){this.yaw=e,this.pitch=Bt(t,-89,89),Number.isFinite(s)&&(this.fov=s);const i=this.pitch*pt,r=this.yaw*pt;this.dir.set(Math.cos(i)*Math.sin(r),Math.sin(i),Math.cos(i)*Math.cos(r)),this.pivot.copy(l).sub(this.tmpA.copy(this.dir).mulScalar(this.distance)),this.walkEyeY=l.y,this.apply()}applyTrajectoryPose(l,e,t){const s=Bt(t,-89,89)*pt,i=Math.cos(s),r=Math.sin(s),a=this.tmpA.set(e.x*i,-r,e.z*i);a.length()>1e-6?a.normalize():a.set(0,0,-1),this.pivot.copy(l).add(this.tmpB.copy(a).mulScalar(this.distance)),this.dir.sub2(l,this.pivot);const n=Math.max(this.dir.length(),.001);this.pitch=Bt(Math.asin(Bt(this.dir.y/n,-1,1))/pt,-89,89),this.yaw=Math.atan2(this.dir.x,this.dir.z)/pt,this.walkEyeY=l.y,this.apply()}setCollisionAvailable(l){this.hasCollision=l,!l&&this.cameraMode==="walk"&&(this.cameraMode="fly")}setVoxelCollider(l,e=[1,1,1]){this.collider=l,this.setColliderSigns(e),this.setCollisionAvailable(!!l)}setColliderSigns(l){this.colliderSignX=l[0],this.colliderSignY=l[1],this.colliderSignZ=l[2]}setWalkBounds(l){this.walkBounds=l}setCameraMode(l){if(l==="walk"&&!this.hasCollision){this.cameraMode="fly";return}l!==this.cameraMode&&(this.cameraMode=l,l==="walk"&&(this.dollhouse=!1,this.stopAutoCamera(),this.walkEyeY=this.entity.getPosition().y,this.walkVelocityY=0,this.walkGrounded=!1,this.walkAccumulator=0,this.walkJumping=!1,this.walkJumpHeld=!1,this.spawnWalk(),this.walkForceStep=!0,this.syncWalkPivotY(),this.apply()))}setFov(l){this.fov=l,this.apply()}setDollhouseMode(l,e){if(this.dollhouse=l,l){this.dollhouseRoofCutY=e!==void 0&&Number.isFinite(e)?e:null,this.pendingRoofCloseY=null,this.stopAutoCamera(),this.cameraMode="fly";return}this.dollhouseRoofCutY=null,this.cancelResetTween(!0)}isDollhouseMode(){return this.dollhouse}setRoofCutListener(l){this.roofCutListener=l}setDollhouseJumpListener(l){this.dollhouseJumpListener=l}roofFullyVisibleY(l){const e=this.walkBounds??this.collider?.gridBounds;if(e){const t=this.colliderSignY*e.min[1],s=this.colliderSignY*e.max[1],i=Math.max(t,s);return Math.max(i+2,l+4)}return l+12}exitDollhouseToOrigin(l="fly",e){this.restoreOriginFromDollhouse(()=>{this.finishRoofRestore(),l==="walk"&&this.setCameraMode("walk"),e?.()})}jumpFromDollhouseClick(l,e){const t=this.pickDollhouseHit(l,e);t&&this.jumpFromDollhouseToXZ(t.x,t.z)}jumpFromDollhouseToXZ(l,e){this.restoreOriginFromDollhouse(()=>{this.setCameraMode("walk"),this.navigateToXZ(l,e,Fl),this.dollhouseJumpListener?.()})}restoreOriginFromDollhouse(l){const e=this.dollhouseRoofCutY;this.setDollhouseMode(!1),this.pendingRoofCloseY=e===null?null:e-fx*this.worldScale,this.pendingRoofCloseY===null&&this.roofCutListener?.(null),this.stopAutoCamera(),this.cameraMode="fly",this.startResetTween(this.initial,Fl,l,!0)}finishRoofRestore(){this.pendingRoofCloseY=null,this.roofCutListener?.(null)}pickDollhouseHit(l,e){const t=this.entity.camera;if(!t?.screenToWorld)return null;const s=this.canvas.getBoundingClientRect(),i=l-s.left,r=e-s.top,a=t.nearClip??.1,n=t.farClip??1e3;t.screenToWorld(i,r,a,this.tmpA),t.screenToWorld(i,r,n,this.tmpB);const o=this.tmpA.x,c=this.tmpA.y,h=this.tmpA.z,d=this.tmpB.x-o,u=this.tmpB.y-c,f=this.tmpB.z-h,p=Math.hypot(d,u,f);if(p<1e-8)return null;const m=1/p,_=d*m,g=u*m,v=f*m,x=this.worldRayHit(o,c,h,_,g,v,n);if(x)return x;if(Math.abs(g)<1e-6)return null;const y=(this.pivot.y-c)/g;return!(y>0)||y>n?null:{x:o+_*y,y:this.pivot.y,z:h+v*y}}worldRayHit(l,e,t,s,i,r,a){const n=this.collider;if(!n)return null;const o=this.colliderSignX,c=this.colliderSignY,h=this.colliderSignZ,d=n.queryRay(o*l,c*e,h*t,o*s,c*i,h*r,a);return d?{x:o*d.x,y:c*d.y,z:h*d.z}:null}flyTo(l,e=Fl,t,s={}){this.stopAutoCamera(),this.stopPath(),this.cameraMode="fly",this.startResetTween({pivot:new E(l.pivot[0],l.pivot[1],l.pivot[2]),yaw:l.yaw,pitch:l.pitch,distance:Math.max(l.distance,.001),fov:l.fov},e,t,s.lockInput===!0)}setExternalMovement(l){this.externalForward=l.forward,this.externalBackward=l.backward,this.externalLeft=l.left,this.externalRight=l.right,this.externalSpeedMultiplier=l.speedMultiplier??1,(l.forward||l.backward||l.left||l.right)&&(this.cancelResetTween(),this.requestRender())}getAutoCameraMode(){return this.autoMode}startAutoCamera(l,e={}){if(l==="off"){this.stopAutoCamera();return}this.resetTween=null;const t=this.entity.getPosition();this.autoPivot.copy(this.pivot),this.autoForward.copy(this.entity.forward);const s=t.x-this.autoPivot.x,i=t.z-this.autoPivot.z,r=Math.sqrt(s*s+i*i);this.autoRadius=e.radius!==void 0?Math.max(.1,e.radius):Math.max(.5,r),this.autoAngle=Math.atan2(t.z-this.autoPivot.z,t.x-this.autoPivot.x),this.autoBaseHeight=t.y,this.autoSpeed=e.speed??.8,this.autoVerticalSpeed=e.verticalSpeed??.3,this.autoDollySpeed=e.dollySpeed??0,this.autoMode=l,this.requestRender()}stopAutoCamera(){if(this.autoMode==="off")return;const l=this.autoMode;if(this.autoMode="off",l==="turntable"||l==="crane")this.syncOrbitFromCamera(this.autoPivot);else{const e=this.tmpA.copy(this.entity.forward),t=this.tmpB.copy(this.entity.getPosition()).add(e.mulScalar(this.distance));this.syncOrbitFromCamera(t)}}syncOrbitFromCamera(l){this.pivot.copy(l);const e=this.entity.getPosition();this.dir.sub2(e,this.pivot),this.distance=Math.max(this.dir.length(),.001),this.pitch=Math.asin(Bt(this.dir.y/this.distance,-1,1))/pt,this.yaw=Math.atan2(this.dir.x,this.dir.z)/pt}orbitStateFromPose(l,e,t){const s=this.tmpC.sub2(l,e),i=Math.max(s.length(),.001);return{pivot:e.clone(),yaw:Math.atan2(s.x,s.z)/pt,pitch:Math.asin(Bt(s.y/i,-1,1))/pt,distance:i,fov:t}}syncFromCameraPose(){const l=this.tmpA.copy(this.entity.forward),e=this.tmpB.copy(this.entity.getPosition()).add(l.mulScalar(this.distance));this.syncOrbitFromCamera(e)}beginExternalDrive(){this.externallyDriven=!0}endExternalDrive(){this.externallyDriven=!1}stepAutoCamera(l){this.autoMode!=="off"&&this.updateAutoCamera(l)}updateAutoCamera(l){switch(this.autoMode){case"turntable":{this.autoAngle+=this.autoSpeed*l,this.autoDollySpeed!==0&&(this.autoRadius=Math.max(.3,this.autoRadius-this.autoDollySpeed*l)),this.pos.set(this.autoPivot.x+Math.cos(this.autoAngle)*this.autoRadius,this.autoBaseHeight,this.autoPivot.z+Math.sin(this.autoAngle)*this.autoRadius),this.entity.setPosition(this.pos),this.entity.lookAt(this.autoPivot,this.up);break}case"dolly":{const e=this.autoSpeed*l;this.pos.copy(this.entity.getPosition()).add(this.tmpA.copy(this.autoForward).mulScalar(e)),this.entity.setPosition(this.pos);break}case"crane":{this.autoBaseHeight+=this.autoVerticalSpeed*l,this.autoDollySpeed!==0&&(this.autoRadius=Math.max(.3,this.autoRadius-this.autoDollySpeed*l)),this.pos.set(this.autoPivot.x+Math.cos(this.autoAngle)*this.autoRadius,this.autoBaseHeight,this.autoPivot.z+Math.sin(this.autoAngle)*this.autoRadius),this.entity.setPosition(this.pos),this.entity.lookAt(this.autoPivot,this.up);break}}}applyDragToAutoCamera(l,e,t){if(this.autoMode==="dolly"){if(t){const s=Q5;this.tmpA.copy(this.entity.right).mulScalar(-l*s),this.tmpB.copy(this.entity.up).mulScalar(e*s),this.pos.copy(this.entity.getPosition()).add(this.tmpA).add(this.tmpB),this.entity.setPosition(this.pos)}else this.entity.rotate(0,-l*this.orbitSpeed,0),this.entity.rotateLocal(-e*this.orbitSpeed,0,0),this.autoForward.copy(this.entity.forward);return}if(t){const s=this.autoRadius*this.panSpeed;this.tmpA.copy(this.entity.right).mulScalar(-l*s),this.tmpB.copy(this.entity.up).mulScalar(e*s),this.autoPivot.add(this.tmpA).add(this.tmpB)}else this.autoAngle-=l*this.rollSign*dx,this.autoBaseHeight+=e*this.rollSign*dx*this.autoRadius}applyKeysToAutoCamera(l){const e=this.keys.has("KeyW")||this.keys.has("ArrowUp")||this.externalForward,t=this.keys.has("KeyS")||this.keys.has("ArrowDown")||this.externalBackward,s=this.keys.has("KeyD")||this.keys.has("ArrowRight")||this.externalRight,i=this.keys.has("KeyA")||this.keys.has("ArrowLeft")||this.externalLeft,r=this.keys.has("KeyE"),a=this.keys.has("KeyQ");if(!e&&!t&&!s&&!i&&!r&&!a)return;const n=this.keys.has("ShiftLeft")||this.keys.has("ShiftRight")?3:1,o=this.moveSpeed*n*l;if(this.autoMode==="dolly")e&&this.translateEntity(this.entity.forward,o),t&&this.translateEntity(this.entity.forward,-o),s&&this.translateEntity(this.entity.right,o),i&&this.translateEntity(this.entity.right,-o),r&&this.translateEntity(this.up,o),a&&this.translateEntity(this.up,-o);else{const c=(n===3?1.5:.6)*l;i&&(this.autoAngle-=c),s&&(this.autoAngle+=c),e&&(this.autoRadius=Math.max(.3,this.autoRadius-o)),t&&(this.autoRadius+=o),r&&(this.autoBaseHeight+=o),a&&(this.autoBaseHeight-=o)}}translateEntity(l,e){this.pos.copy(this.entity.getPosition()).add(this.tmpA.copy(l).mulScalar(e)),this.entity.setPosition(this.pos)}applyWheelToAutoCamera(l){const e=l/100*this.moveSpeed*.5;this.autoMode==="dolly"?this.translateEntity(this.autoForward,-e):this.autoRadius=Math.max(.3,this.autoRadius+e)}reset(l=!0){if(this.stopAutoCamera(),!l){this.resetTween=null,this.applyOrbitState(this.initial);return}this.startResetTween(this.initial,Fl)}applyOrbitState(l){this.pivot.copy(l.pivot),this.yaw=l.yaw,this.pitch=l.pitch,this.distance=l.distance,this.fov=l.fov,this.apply()}computePosition(l,e){const t=l.pitch*pt,s=l.yaw*pt;return this.dir.set(Math.cos(t)*Math.sin(s),Math.sin(t),Math.cos(t)*Math.cos(s)),e.copy(l.pivot).add(this.dir.mulScalar(l.distance))}startResetTween(l,e,t,s=!1){const i=this.computePosition(l,new E);this.tweenMat.setLookAt(i,l.pivot,this.up);const r=new ae().setFromMat4(this.tweenMat);this.resetTween={startPos:this.entity.getPosition().clone(),endPos:i,startQuat:this.entity.getRotation().clone(),endQuat:r,startFov:this.fov,endFov:l.fov,startTime:performance.now(),duration:Math.max(e,1),target:{pivot:l.pivot.clone(),yaw:l.yaw,pitch:l.pitch,distance:l.distance,fov:l.fov},onDone:t,locked:s},this.requestRender()}isTransitionLocked(){return this.resetTween?.locked===!0}isWalkableXZ(l,e,t=0){if(!this.collider||!Number.isFinite(l)||!Number.isFinite(e)||!this.isColumnWalkable(l,e))return!1;const i=Math.max(0,t)*this.worldScale;if(i<=0)return!0;const r=8;for(let a=0;a<r;a++){const n=2*Math.PI*a/r,o=l+Math.cos(n)*i,c=e+Math.sin(n)*i;if(!this.isColumnWalkable(o,c))return!1}return!0}isColumnWalkable(l,e){const t=this.collider;if(!t)return!1;const s=t.gridBounds,i=s.max[1]-s.min[1],r=s.max[1]+i*.5,a=i*2+1,n=this.walkRayDownHitY(l,r,e,a);return n===null?!1:this.isWalkFree(l,n+this.walkDims.hoverHeight+this.walkDims.capsuleRadius,e)}routeFloorYAt(l,e,t,s=0){const i=this.collider;if(!i)return null;const r=i.gridBounds,a=r.max[1]-r.min[1],n=a*2+1,o=Math.max(.2,a*.05),c=(u,f)=>{const p=this.walkRayDownHitY(u,t+o,f,n);if(p===null)return null;const m=p+this.walkDims.hoverHeight+this.walkDims.capsuleRadius;return this.isWalkFree(u,m,f)?p:null},h=c(l,e);if(h===null)return null;const d=Math.max(0,s)*this.worldScale;if(d>0)for(let u=0;u<8;u++){const f=2*Math.PI*u/8;if(c(l+Math.cos(f)*d,e+Math.sin(f)*d)===null)return null}return h}isRouteSegmentClear(l,e,t,s,i,r=0){const a=this.collider;if(!a)return!0;const n=a.voxelResolution;if(!(n>0))return!0;const o=Math.hypot(t-l,s-e),c=Math.max(1,Math.ceil(o/n));for(let h=0;h<=c;h++){const d=h/c;if(this.routeFloorYAt(l+(t-l)*d,e+(s-e)*d,i,r)===null)return!1}return!0}planKeyframeRoute(l,e,t=0){const s=this.collider;if(!s)return[l,e];const i=s.voxelResolution*1.5;if(!(i>0))return[l,e];const r=(l.y+e.y)/2;if(this.isRouteSegmentClear(l.x,l.z,e.x,e.z,r,t))return[l,e];
17119const a=this.routeFloorYAt(l.x,l.z,l.y),n=this.routeFloorYAt(e.x,e.z,e.y);if(a===null||n===null)return[l,e];const o=(l.y-a+(e.y-n))/2,c=this.aStarXZ(l,e,i,r,t);if(!c||c.length<2)return[l,e];const h=[l.clone()];for(let d=1;d<c.length-1;d++){const u=c[d],f=this.routeFloorYAt(u.x,u.z,r,t);h.push(new E(u.x,(f??r-o)+o,u.z))}return h.push(e.clone()),h}aStarXZ(l,e,t,s,i){const r=(S,T)=>`${S},${T}`,a=Math.round(l.x/t),n=Math.round(l.z/t),o=Math.round(e.x/t),c=Math.round(e.z/t),h=(S,T)=>Math.hypot(S-o,T-c),d=new Map,u=(S,T)=>{const w=r(S,T),C=d.get(w);if(C!==void 0)return C;const b=this.routeFloorYAt(S*t,T*t,s,i)!==null;return d.set(w,b),b},f=new Map,p=new Map,m=new Map,_=[],g=new Set,v=r(a,n);f.set(v,0),p.set(v,null),m.set(v,[a,n]),_.push({ix:a,iz:n,f:h(a,n)});const x=8e3;let y=0;for(;_.length>0;){let S=0;for(let b=1;b<_.length;b++)_[b].f<_[S].f&&(S=b);const T=_.splice(S,1)[0],w=r(T.ix,T.iz);if(g.has(w))continue;if(g.add(w),T.ix===o&&T.iz===c){const b=[];let I=w;for(;I;){const L=m.get(I);if(!L)break;b.push(L),I=p.get(I)??null}b.reverse();let P=b.map(([L,O])=>({x:L*t,z:O*t}));return P[0]={x:l.x,z:l.z},P[P.length-1]={x:e.x,z:e.z},this.stringPullRoute(P,s,i)}if(++y>x)return null;const C=f.get(w)??0;for(let b=-1;b<=1;b++)for(let I=-1;I<=1;I++){if(b===0&&I===0)continue;const P=T.ix+b,L=T.iz+I,O=r(P,L);if(g.has(O)||!u(P,L)||b!==0&&I!==0&&(!u(T.ix+b,T.iz)||!u(T.ix,T.iz+I)))continue;const D=C+Math.hypot(b,I);D<(f.get(O)??1/0)&&(f.set(O,D),p.set(O,w),m.set(O,[P,L]),_.push({ix:P,iz:L,f:D+h(P,L)}))}}return null}stringPullRoute(l,e,t){if(l.length<=2)return l;const s=[l[0]];let i=0;for(;i<l.length-1;){let r=l.length-1;for(;r>i+1&&!this.isRouteSegmentClear(l[i].x,l[i].z,l[r].x,l[r].z,e,t);r--);s.push(l[r]),i=r}return s}buildPathEyePositions(l){const e=l.filter(a=>a&&Number.isFinite(a.x)&&Number.isFinite(a.z)),t=[],s=a=>{const n=t[t.length-1];n&&n.distance(a)<.001||t.push(a)},i=this.collider;if(this.cameraMode==="walk"&&i&&e.length>0){const a=i.gridBounds,n=this.entity.getPosition(),o=Bt(n.y,a.min[1],a.max[1]),c=this.findWalkSpawnNear(e[0].x,o,e[0].z);c&&this.ensureAutoWalkHeight(c.floorY);const h=this.walkDims.hoverHeight+this.walkDims.eyeHeight,d=c?c.floorY+h:this.walkEyeY||n.y;for(const u of e)s(new E(u.x,d,u.z));return t}const r=this.navigationEyeY??this.entity.getPosition().y;for(const a of e)s(new E(a.x,r,a.z));return t}resolveNavigationPosition(l,e){const t=this.entity.getPosition();if(this.cameraMode!=="walk"){const o=this.navigationEyeY??t.y;return this.walkBounds?new E(Bt(l,this.walkBounds.min[0],this.walkBounds.max[0]),o,Bt(e,this.walkBounds.min[2],this.walkBounds.max[2])):new E(l,o,e)}const s=this.collider;if(!s)return this.walkBounds?new E(Bt(l,this.walkBounds.min[0],this.walkBounds.max[0]),t.y,Bt(e,this.walkBounds.min[2],this.walkBounds.max[2])):null;const i=s.gridBounds,r=Bt(this.entity.getPosition().y,i.min[1],i.max[1]),a=this.findWalkSpawnNear(l,r,e);if(!a)return null;this.ensureAutoWalkHeight(a.floorY);const n=a.floorY+this.walkDims.hoverHeight+this.walkDims.eyeHeight;return new E(a.x,n,a.z)}updateResetTween(){const l=this.resetTween;if(!l)return;const e=(performance.now()-l.startTime)/l.duration;if(e>=1){this.resetTween=null,this.applyOrbitState(l.target),this.closeRoofAfterCrossing(this.entity.getPosition().y),l.onDone?.();return}const t=xX(e<0?0:e);this.pos.lerp(l.startPos,l.endPos,t),this.entity.setPosition(this.pos),this.closeRoofAfterCrossing(this.pos.y),this.tweenQuat.slerp(l.startQuat,l.endQuat,t),this.entity.setRotation(this.tweenQuat),this.entity.camera&&(this.entity.camera.fov=l.startFov+(l.endFov-l.startFov)*t),this.requestRender()}closeRoofAfterCrossing(l){this.pendingRoofCloseY===null||l>this.pendingRoofCloseY||(this.pendingRoofCloseY=null,this.roofCutListener?.(null))}cancelResetTween(l=!1){this.resetTween&&(this.resetTween.locked&&!l||(this.resetTween=null,this.pendingRoofCloseY!==null&&(this.pendingRoofCloseY=null,this.roofCutListener?.(null)),this.syncFromCameraPose()))}dispose(){this.app.off("update",this.onUpdate,this);const l=this.canvas;l.removeEventListener("pointerdown",this.onPointerDown),window.removeEventListener("pointermove",this.onPointerMove),window.removeEventListener("pointerup",this.onPointerUp),l.removeEventListener("wheel",this.onWheel),l.removeEventListener("contextmenu",this.onContextMenu),window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp)}attach(){this.app.on("update",this.onUpdate,this);const l=this.canvas;l.addEventListener("pointerdown",this.onPointerDown),window.addEventListener("pointermove",this.onPointerMove),window.addEventListener("pointerup",this.onPointerUp),l.addEventListener("wheel",this.onWheel,{passive:!1}),l.addEventListener("contextmenu",this.onContextMenu),window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp)}apply(){const l=this.pitch*pt,e=this.yaw*pt;this.dir.set(Math.cos(l)*Math.sin(e),Math.sin(l),Math.cos(l)*Math.cos(e)),this.pos.copy(this.pivot).add(this.dir.mulScalar(this.distance)),this.entity.setPosition(this.pos),this.entity.lookAt(this.pivot,this.up),this.entity.camera&&(this.entity.camera.fov=this.fov),this.requestRender()}orbit(l,e){if(this.dollhouse){this.yaw-=l*this.rollSign*this.orbitSpeed,this.pitch=Bt(this.pitch+e*this.orbitSpeed,J5,eX),this.apply();return}const t=this.tmpC.copy(this.entity.getPosition());this.yaw-=l*this.rollSign*this.orbitSpeed,this.pitch=Bt(this.pitch+e*this.orbitSpeed,-89,89);const s=this.pitch*pt,i=this.yaw*pt,r=this.tmpA.set(Math.cos(s)*Math.sin(i),Math.sin(s),Math.cos(s)*Math.cos(i));this.cameraMode==="walk"&&(this.walkEyeY=t.y),this.pivot.copy(t).sub(r.mulScalar(this.distance)),this.apply()}pan(l,e){if(this.cameraMode==="walk"){this.walkPanOrDolly(-l,-e);return}if(this.dollhouse){const s=this.distance*this.panSpeed,i=this.yaw*pt;this.tmpA.set(Math.cos(i),0,-Math.sin(i)),this.tmpB.set(Math.sin(i),0,Math.cos(i)),this.pivot.add(this.tmpA.mulScalar(-l*s)).add(this.tmpB.mulScalar(e*s)),this.apply();return}const t=this.distance*this.panSpeed;this.tmpA.copy(this.entity.right).mulScalar(-l*t),this.tmpB.copy(this.entity.up).mulScalar(e*t),this.pivot.add(this.tmpA).add(this.tmpB),this.apply()}dolly(l){if(this.cameraMode==="walk"){const e=this.tmpA.copy(this.entity.forward);if(e.y=0,e.lengthSq()<1e-12)return;e.normalize().mulScalar(l),this.walkMove(e),this.finishWalkPointerMove();return}if(this.dollhouse){this.distance=Math.max(.5,this.distance-l),this.apply();return}this.tmpA.copy(this.entity.forward).mulScalar(l),this.pivot.add(this.tmpA),this.apply()}walkPanOrDolly(l,e){const t=this.moveSpeed*.005,s=this.tmpA.copy(this.entity.right);s.y=0;const i=this.tmpB.copy(this.entity.forward);i.y=0,s.lengthSq()>1e-12?s.normalize():s.set(0,0,0),i.lengthSq()>1e-12?i.normalize():i.set(0,0,0);const r=s.mulScalar(l*t).add(i.mulScalar(e*t));r.lengthSq()<1e-12||(this.walkMove(r),this.finishWalkPointerMove())}finishWalkPointerMove(){this.syncWalkPivotY(),this.walkForceStep=!0,this.apply()}onUpdate=l=>{if(this.externallyDriven)return;if(this.trajectory){this.stepTrajectory(l);return}if(this.resetTween){this.updateResetTween();return}if(this.autoMode!=="off"){this.applyKeysToAutoCamera(l),this.updateAutoCamera(l),this.requestRender();return}if(this.cameraMode==="walk"){this.updateWalk(l);return}const e=this.externalForward||this.externalBackward||this.externalLeft||this.externalRight;if(this.keys.size===0&&!e)return;const t=this.keys.has("KeyW")||this.keys.has("ArrowUp")||this.externalForward,s=this.keys.has("KeyS")||this.keys.has("ArrowDown")||this.externalBackward,i=this.keys.has("KeyD")||this.keys.has("ArrowRight")||this.externalRight,r=this.keys.has("KeyA")||this.keys.has("ArrowLeft")||this.externalLeft,a=(t?1:0)-(s?1:0),n=(i?1:0)-(r?1:0),o=(this.keys.has("KeyE")?1:0)-(this.keys.has("KeyQ")?1:0);if(a===0&&n===0&&o===0)return;const c=this.keys.has("ShiftLeft")||this.keys.has("ShiftRight")?3:1,h=this.externalSpeedMultiplier<1?this.externalSpeedMultiplier:1,d=Math.min(l,ux),u=this.moveSpeed*c*h*d;if(this.dollhouse){const _=this.yaw*pt;this.tmpA.set(Math.sin(_),0,Math.cos(_)),this.tmpB.set(Math.cos(_),0,-Math.sin(_)),this.pivot.add(this.tmpA.mulScalar(a*u)).add(this.tmpB.mulScalar(n*u)),o!==0&&(this.distance=Math.max(.5,this.distance-o*u)),this.apply();return}const f=this.tmpA.copy(this.entity.forward),p=this.tmpB.copy(this.entity.right),m=f.mulScalar(a*u).add(p.mulScalar(n*u));this.pivot.add(m),this.pivot.add(this.tmpB.copy(this.up).mulScalar(o*u)),this.apply()};updateWalk(l){const e=this.keys.has("KeyW")||this.keys.has("ArrowUp")||this.externalForward,t=this.keys.has("KeyS")||this.keys.has("ArrowDown")||this.externalBackward,s=this.keys.has("KeyD")||this.keys.has("ArrowRight")||this.externalRight,i=this.keys.has("KeyA")||this.keys.has("ArrowLeft")||this.externalLeft,r=(e?1:0)-(t?1:0),a=(s?1:0)-(i?1:0),n=r!==0||a!==0,o=this.keys.has("Space");if(n||o||this.walkJumping||this.walkForceStep||!this.walkGrounded||Math.abs(this.walkVelocityY)>
17119this.walkDims.settleVelocity){if(this.walkForceStep=!1,n){const h=this.keys.has("ShiftLeft")||this.keys.has("ShiftRight")?3:1,d=this.externalSpeedMultiplier<1?this.externalSpeedMultiplier:1,u=Math.min(l,ux),f=this.moveSpeed*h*d*u,p=this.tmpA.copy(this.entity.forward),m=this.tmpB.copy(this.entity.right);p.y=0,m.y=0,p.length()>1e-6&&p.normalize(),m.length()>1e-6&&m.normalize();const _=p.mulScalar(r*f).add(m.mulScalar(a*f));this.walkMove(_)}this.collider&&this.stepWalkVertical(l,o),this.syncWalkPivotY(),this.apply()}}walkMove(l){const e=Math.sqrt(l.x*l.x+l.z*l.z),t=this.walkDims.maxStep,s=t*cX;let i=l.x,r=l.z,a=e;if(e>s){const h=s/e;i*=h,r*=h,a=s}const n=a>t?Math.ceil(a/t):1,o=i/n,c=r/n;for(let h=0;h<n;h++)this.pivot.x+=o,this.pivot.z+=c,this.tryWalkStepUp()||this.resolveWalkCollision();this.walkBounds&&!this.collider&&(this.pivot.x=Bt(this.pivot.x,this.walkBounds.min[0],this.walkBounds.max[0]),this.pivot.z=Bt(this.pivot.z,this.walkBounds.min[2],this.walkBounds.max[2]))}walkCapsuleColliding(){const l=this.collider;if(!l)return!1;const e=this.walkEyePosition(this.tmpC),t=this.walkDims,s=e.y-t.eyeHeight+t.capsuleHeight*.5,i=t.capsuleHeight*.5-t.capsuleRadius,r=this.colliderSignX,a=this.colliderSignY,n=this.colliderSignZ;return l.queryCapsule(r*e.x,a*s,n*e.z,i,t.capsuleRadius,this.pushOut)}tryWalkStepUp(){const l=this.collider;if(!l||!this.walkGrounded)return!1;const e=this.walkDims.maxClimb;if(!(e>0)||!this.walkCapsuleColliding())return!1;const t=this.walkEyeY,s=Math.max(l.voxelResolution>0?l.voxelResolution:.05,e/8);for(let i=s;i<=e+1e-6;i+=s)if(this.walkEyeY=t+i,this.syncWalkPivotY(),!this.walkCapsuleColliding())return this.walkVelocityY<0&&(this.walkVelocityY=0),this.walkGrounded=!0,!0;return this.walkEyeY=t,this.syncWalkPivotY(),!1}resolveWalkCollision(){if(!this.walkCapsuleColliding())return;const l=this.colliderSignX,e=this.colliderSignY,t=this.colliderSignZ,s=l*this.pushOut.x,i=e*this.pushOut.y,r=t*this.pushOut.z;this.pivot.x+=s,this.pivot.z+=r,this.walkEyeY+=i,i<0&&this.walkVelocityY>0&&(this.walkVelocityY=0),!this.walkGrounded&&i>0&&this.walkVelocityY<0&&(this.walkVelocityY=0,this.walkGrounded=!0),this.syncWalkPivotY()}walkEyePosition(l){const e=this.pitch*pt,t=this.yaw*pt,s=Math.cos(e);return l.set(this.pivot.x+s*Math.sin(t)*this.distance,this.walkEyeY,this.pivot.z+s*Math.cos(t)*this.distance)}syncWalkPivotY(){this.pivot.y=this.walkEyeY-Math.sin(this.pitch*pt)*this.distance}stepWalkVertical(l,e){for(this.walkAccumulator=Math.min(this.walkAccumulator+l,hX*pd);this.walkAccumulator>=pd;)this.walkVerticalSubstep(pd,e),this.walkAccumulator-=pd}walkVerticalSubstep(l,e){const t=this.probeWalkGround();this.walkVelocityY<0&&(this.walkJumping=!1),e&&!this.walkJumping&&this.walkGrounded&&!this.walkJumpHeld&&(this.walkJumping=!0,this.walkVelocityY=this.walkDims.jumpSpeed,this.walkGrounded=!1),this.walkJumpHeld=e;const s=this.walkDims;if(t!==null&&!this.walkJumping){const i=t+s.hoverHeight+s.eyeHeight,r=this.walkEyeY-i;if(r>s.freefallThreshold)this.walkVelocityY-=s.gravity*l,this.walkEyeY+this.walkVelocityY*l<=i?(this.walkEyeY=i,this.walkVelocityY=0,this.walkGrounded=!0):this.walkGrounded=!1;else{const a=-800*r-uX*this.walkVelocityY;this.walkVelocityY+=a*l,this.walkGrounded=!0}}else this.walkVelocityY-=s.gravity*l,this.walkGrounded=!1;this.walkEyeY+=this.walkVelocityY*l,this.syncWalkPivotY(),this.resolveWalkVerticalCollision()}probeWalkGround(){if(!this.collider)return null;const e=this.walkEyePosition(this.tmpC),t=e.y-this.walkDims.eyeHeight,s=this.walkDims.capsuleRadius;let i=0,r=0;for(let a=0;a<5;a++){let n=e.x,o=e.z;a===1?n-=s:a===2?n+=s:a===3?o+=s:a===4&&(o-=s);const c=this.walkRayDownHitY(n,t,o,this.walkDims.groundProbeRange);c!==null&&(i+=c,r++)}return r>0?i/r:null}walkRayHitY(l,e,t,s,i){const r=this.collider;if(!r)return null;const a=this.colliderSignX,n=this.colliderSignY,o=this.colliderSignZ,c=r.queryRay(a*l,n*e,o*t,0,n*s,0,i);return c?n*c.y:null}walkRayDownHitY(l,e,t,s){return this.walkRayHitY(l,e,t,-1,s)}resolveWalkVerticalCollision(){const l=this.collider;if(!l)return;const e=this.walkEyePosition(this.tmpC),t=this.walkDims,s=e.y-t.eyeHeight+t.capsuleHeight*.5,i=t.capsuleHeight*.5-t.capsuleRadius,r=this.colliderSignX,a=this.colliderSignY,n=this.colliderSignZ;if(!l.queryCapsule(r*e.x,a*s,n*e.z,i,t.capsuleRadius,this.pushOut))return;const o=r*this.pushOut.x,c=a*this.pushOut.y,h=n*this.pushOut.z;this.pivot.x+=o,this.pivot.z+=h,this.walkEyeY+=c,c<0&&this.walkVelocityY>0&&(this.walkVelocityY=0),!this.walkGrounded&&c>0&&this.walkVelocityY<0&&(this.walkVelocityY=0,this.walkGrounded=!0),this.syncWalkPivotY()}spawnWalk(){const l=this.entity.getPosition(),e=this.findWalkSpawnNear(l.x,l.y,l.z);e&&this.applyWalkSpawn(e)}findWalkSpawnNear(l,e,t){const s=this.collider;if(!s)return null;const i=s.voxelResolution;if(!(i>0))return null;const r=this.walkDims,a=Math.max(i,r.spawnSearchRadius/24),n=r.spawnSearchRadius*r.spawnSearchRadius,o=Math.ceil(r.spawnSearchRadius/a),c=(r.capsuleHeight+r.hoverHeight)*.5,h=r.capsuleRadius,d=Math.min(Math.ceil(h/i),3),u=h*h,f=s.gridBounds.max[1]-s.gridBounds.min[1],p=Math.min(f*2+i,40);let m=1/0,_=null,g=15e4;e:for(let v=0;v<=o&&!(v*a*(v*a)>=m);v++)for(let y=-v;y<=v;y++){const S=y<0?-y:y;for(let T=-v;T<=v;T++){const w=T<0?-T:T;for(let C=-v;C<=v;C++){if((C<0?-C:C)<v&&S<v&&w<v)continue;const I=(C*C+y*y+T*T)*a*a;if(I>=m||I>n)continue;const P=l+C*a,L=e+y*a,O=t+T*a;if(!this.isWalkFree(P,L,O))continue;let D=-1/0,N=1/0,k=!0;for(let A=-d;A<=d&&k;A++){const M=A*i,R=M*M;for(let F=-d;F<=d;F++){const U=F*i;if(R+U*U>u)continue;const B=P+M,z=O+U;if(g-=2,g<=0)break e;const $=this.walkRayHitY(B,L,z,-1,p);if($===null){k=!1;break}$>D&&(D=$);const K=this.walkRayHitY(B,L,z,1,p);K!==null&&K<N&&(N=K)}}k&&(D+2*c>N||(m=I,_={x:P,floorY:D,z:O}))}}}return _}applyWalkSpawn(l){this.ensureAutoWalkHeight(l.floorY);const e=this.walkDims,t=l.floorY+e.hoverHeight+e.eyeHeight;this.walkEyeY=t,this.walkVelocityY=0,this.walkGrounded=!0,this.walkJumping=!1;const s=this.pitch*pt,i=this.yaw*pt,r=Math.cos(s);this.pivot.x=l.x-r*Math.sin(i)*this.distance,this.pivot.z=l.z-r*Math.cos(i)*this.distance}isWalkFree(l,e,t){const s=this.collider;return s?!s.isPointBlocked(this.colliderSignX*l,this.colliderSignY*e,this.colliderSignZ*t):!1}onPointerDown=l=>{this.isTransitionLocked()||(this.stopPath(),this.cancelResetTween(),this.canvas.setPointerCapture?.(l.pointerId),this.pointers.set(l.pointerId,{x:l.clientX,y:l.clientY,button:l.button,startX:l.clientX,startY:l.clientY,dragged:!1}),this.pointers.size===2&&(this.pinchDistance=this.currentPinchDistance()))};onPointerMove=l=>{const e=this.pointers.get(l.pointerId);if(!e)return;const t=l.clientX-e.x,s=l.clientY-e.y;if(e.x=l.clientX,e.y=l.clientY,!e.dragged&&Math.hypot(l.clientX-e.startX,l.clientY-e.startY)>tX&&(e.dragged=!0),this.isTransitionLocked())return;if(this.pointers.size>=2){const r=this.currentPinchDistance(),a=r-this.pinchDistance;this.pinchDistance>0&&this.dolly(a*this.moveSpeed*vX),this.pinchDistance=r,this.pan(t,s);return}const i=e.button===1||e.button===2||l.shiftKey||typeof l.buttons=="number"&&(l.buttons&2)!==0;if(this.autoMode!=="off"){this.applyDragToAutoCamera(t,s,i),this.requestRender();return}i?this.pan(t,s):this.orbit(t,s)};onPointerUp=l=>{const e=this.pointers.get(l.pointerId);this.pointers.delete(l.pointerId),this.pointers.size<2&&(this.pinchDistance=0),this.dollhouse&&e&&!e.dragged&&e.button===0&&this.pointers.size===0&&!this.isTransitionLocked()&&this.jumpFromDollhouseClick(e.startX,e.startY)};onWheel=l=>{if(l.preventDefault(),!this.isTransitionLocked()){if(this.stopPath(),this.cancelResetTween(),this.autoMode!=="off"){this.applyWheelToAutoCamera(l.deltaY),this.requestRender();return}if(this.cameraMode==="walk"){const e=this.moveSpeed*.5,t=-l.deltaY/100*e,s=l.deltaX/100*e,i=this.tmpA.copy(this.entity.forward);i.y=0;const r=this.tmpB.copy(this.entity.right);r.y=0,i.lengthSq()>1e-12?i.normalize():i.set(0,0,0),r.lengthSq()>1e-12?r.normalize():r.set(0,0,0);const a=i.mulScalar(t).add(r.mulScalar(s));a.lengthSq()>1e-12&&(this.walkMove(a),this.finishWalkPointerMove());return}this.dolly(-l.deltaY/100*this.moveSpeed*.5)}};onContextMenu=l=>{l.preventDefault()};onKeyDown=l=>{if(!yX(l.target)&&((l.code==="ArrowUp"||l.code==="ArrowDown"||l.code==="ArrowLeft"||l.code==="ArrowRight")&&l.preventDefault(),l.code==="Space"&&this.cameraMode==="walk"&&l.preventDefault(),!this.isTransitionLocked())){if(this.stopPath(),l.code==="Digit0"||l.code==="Numpad0"){this.reset();return}this.cancelResetTween(),this.keys.add(l.code)}};onKeyUp=l=>{this.keys.delete(l.code)};currentPinchDistance(){const l=[...this.pointers.values()];if(l.length<2)return 0;const e=l[0],t=l[1];return Math.hypot(e.x-t.x,e.y-t.y)}};function Bt(l,e,t){return l<e?e:l>t?t:l}function yX(l){if(!(l instanceof HTMLElement))return!1;if(l.isContentEditable)return!0;const e=l.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"}function xX(l){return l<.5?4*l*l*l:1-(-2*l+2)**3/2}function TX(l){const e=l.length;if(e<2)return l.map(r=>r.clone());const t=16,s=[],i=r=>l[r<0?0:r>=e?e-1:r];for(let r=0;r<e-1;r++)CX(i(r-1),i(r),i(r+1),i(r+2),t,s);return s.push(l[e-1].clone()),s}var wX=.5,mx=16;function Ao(l,e,t){return l+Math.max(Math.pow(e.distance(t),wX),1e-6)}function CX(l,e,t,s,i,r){const n=Ao(0,l,e),o=Ao(n,e,t),c=Ao(o,t,s);for(let h=0;h<i;h++){const d=n+h/i*(o-n);r.push(WC(l,e,t,s,0,n,o,c,d))}}function V_(l,e){return(e-l+540)%360-180}function kd(l,e,t){return l+V_(l,e)*t}function EX(l,e,t,s,i,r,a=0){const n=l.length,o=[],c=[],h=[],d=[],u=i?[]:void 0,f=r??Xa,p=m=>l[m<0?0:m>=n?n-1:m];for(let m=0;m<n-1;m++){const _=p(m-1),g=p(m),v=p(m+1),x=p(m+2),y=0,S=Ao(y,_,g),T=Ao(S,g,v),w=Ao(T,v,x);for(let C=0;C<mx;C++){const b=C/mx,I=S+b*(T-S),P=WC(_,g,v,x,y,S,T,w,I);o.push(P),c.push(kd(e[m],e[m+1],b)),h.push(t[m]+(t[m+1]-t[m])*b),d.push(s[m]+(s[m+1]-s[m])*b),u&&i&&u.push(Pu(i[m],i[m
17119+1],b,P.y,f,a))}}return o.push(l[n-1].clone()),c.push(e[n-1]),h.push(t[n-1]),d.push(s[n-1]),u&&i&&u.push(Pu(i[n-2],i[n-1],1,l[n-1].y,f,a)),{points:o,yaws:c,pitches:h,fovs:d,roofCuts:u}}function ro(l,e,t,s,i){const r=s-t,a=r>1e-9?(i-t)/r:0;return new E(l.x+(e.x-l.x)*a,l.y+(e.y-l.y)*a,l.z+(e.z-l.z)*a)}function WC(l,e,t,s,i,r,a,n,o){const c=ro(l,e,i,r,o),h=ro(e,t,r,a,o),d=ro(t,s,a,n,o),u=ro(c,h,i,a,o),f=ro(h,d,r,n,o);return ro(u,f,r,a,o)}var bX=["video/mp4;codecs=avc1.42E01E","video/mp4","video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"];function AX(){const l=globalThis.MediaRecorder;if(typeof l?.isTypeSupported=="function")for(const e of bX)try{if(l.isTypeSupported(e))return e}catch{}}function PX(l){return l.includes("mp4")?"video/mp4":"video/webm"}var IX=class{constructor(l,e,t,s){this.app=l,this.camera=e,this.controller=t,this.canvas=s,this.captureClip=this.captureClip.bind(this)}app;camera;controller;canvas;tmpQuat=new ae;savedPixelRatio=null;resolveCanvas(){return this.app?.graphicsDevice?.canvas??this.canvas}saveCameraState(){const l=this.camera.getPosition(),e=this.camera.getRotation();return{position:[l.x,l.y,l.z],quaternion:[e.x,e.y,e.z,e.w]}}restoreCameraState(l){this.camera.setPosition(l.position[0],l.position[1],l.position[2]),this.tmpQuat.set(l.quaternion[0],l.quaternion[1],l.quaternion[2],l.quaternion[3]),this.camera.setRotation(this.tmpQuat),this.controller.syncFromCameraPose(),this.app.renderNextFrame=!0}resetView(){this.controller.reset()}async prepare({durationMs:l,pixelRatio:e}){this.controller.reset(!1),await _x();const t=this.app.graphicsDevice;e>1&&Number.isFinite(e)&&(this.savedPixelRatio=t.maxPixelRatio,t.maxPixelRatio=Math.max(t.maxPixelRatio,e),this.app.resizeCanvas());const s=Math.max(.85*l/1e3,.001),i=Math.PI/s;this.controller.startAutoCamera("turntable",{speed:i}),await _x()}beginRecording(){this.controller.beginExternalDrive()}async renderFrame(l){const e=l/1e3;this.controller.stepAutoCamera(e),this.app.update(e),this.app.render()}endRecording(){this.controller.endExternalDrive()}captureClip({durationMs:l,frameRate:e,videoBitsPerSecond:t,onProgress:s}){const i=this.resolveCanvas();if(!i||typeof i.captureStream!="function")throw new Error("Viewer is not ready to record yet.");const r=Math.max(1,Math.round(e)),a=i.captureStream(r),n=AX(),o=new MediaRecorder(a,{videoBitsPerSecond:t,...n?{mimeType:n}:{}}),c=[];o.ondataavailable=_=>{_.data&&_.data.size>0&&c.push(_.data)};let h=!1,d=null;const u=new Promise((_,g)=>{o.onerror=()=>g(new Error("MediaRecorder failed")),o.onstop=()=>{if(a.getTracks().forEach(x=>x.stop()),h){g(new Error("Recording cancelled"));return}const v=PX(o.mimeType||n||"");_(new Blob(c,{type:v}))}}),f=performance.now();o.start(1e3);const p=()=>{if(h)return;this.app.renderNextFrame=!0;const _=performance.now()-f;if(s?.(Math.min(1,_/l)),_>=l){o.state!=="inactive"&&o.stop();return}d=requestAnimationFrame(p)};return d=requestAnimationFrame(p),{done:u,cancel:()=>{h=!0,d!==null&&cancelAnimationFrame(d),o.state!=="inactive"&&o.stop()}}}cleanup(){if(this.controller.stopAutoCamera(),this.savedPixelRatio!==null){const l=this.app.graphicsDevice;l.maxPixelRatio=this.savedPixelRatio,this.savedPixelRatio=null,this.app.resizeCanvas()}this.app.renderNextFrame=!0}};async function _x(l=2){for(let e=0;e<l;e+=1)await new Promise(t=>requestAnimationFrame(()=>t()))}function DX({loading:l,progress:e=0,error:t=!1}){if(t)return Lt.jsx("div",{style:BX,children:Lt.jsx("div",{style:NX,children:"Scene failed to load"})});if(!l)return null;const s=Number.isFinite(e)?Math.max(0,Math.min(100,e)):0,i=s>0?s:35;return Lt.jsx("div",{style:RX,children:Lt.jsxs("div",{style:LX,children:[Lt.jsx(MX,{}),Lt.jsx("div",{style:FX,children:Lt.jsx("div",{style:{...OX,width:`${i}%`}})})]})})}function MX({size:l=64}){return Lt.jsxs("svg",{width:l,height:l,viewBox:"0 0 64 64",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[Lt.jsx("style",{children:` 17120 .pcv-loader-core { 17121 transform-origin: 32px 32px; 17122 transform-box: fill-box; 17123 animation: pcv-core-pulse 1.5s ease-in-out infinite alternate; 17124 } 17125 .pcv-orbit-x { 17126 transform-origin: 32px 32px; 17127 transform-box: fill-box; 17128 animation: pcv-spin-x 3s linear infinite; 17129 } 17130 .pcv-orbit-y { 17131 transform-origin: 32px 32px; 17132 transform-box: fill-box; 17133 animation: pcv-spin-y 4s linear infinite; 17134 } 17135 .pcv-orbit-z { 17136 transform-origin: 32px 32px; 17137 transform-box: fill-box; 17138 animation: pcv-spin-z 8s linear infinite; 17139 } 17140 .pcv-compile-line-1 { stroke-dasharray: 100; animation: pcv-compile 2s ease-in-out infinite; } 17141 .pcv-compile-line-2 { stroke-dasharray: 100; animation: pcv-compile 2s ease-in-out infinite 1s; } 17142 @keyframes pcv-core-pulse { 17143 0% { transform: scale(0.8); filter: drop-shadow(0 0 4px #3B82F6); } 17144 100% { transform: scale(1.3); filter: drop-shadow(0 0 10px #2DD4BF); } 17145 } 17146 @keyframes pcv-spin-x { 100% { transform: rotateX(360deg); } } 17147 @keyframes pcv-spin-y { 100% { transform: rotateY(360deg); } } 17148 @keyframes pcv-spin-z { 100% { transform: rotateZ(360deg); } } 17149 @keyframes pcv-compile { 17150 0% { stroke-dashoffset: 100; opacity: 0; } 17151 50% { stroke-dashoffset: 0; opacity: 1; filter: drop-shadow(0 0 4px #2DD4BF); } 17152 100% { stroke-dashoffset: -100; opacity: 0; } 17153 } 17154 `}),Lt.jsx("circle",{cx:"32",cy:"32",r:"28",stroke:"#D1D5DB",strokeWidth:"1",strokeOpacity:"0.1"}),Lt.jsx("ellipse",{cx:"32",cy:"32",rx:"28",ry:"8",stroke:"#3B82F6",strokeWidth:"1.5",strokeOpacity:"0.6",className:"pcv-orbit-x"}),Lt.jsx("ellipse",{cx:"32",cy:"32",rx:"8",ry:"28",stroke:"#2DD4BF",strokeWidth:"1.5",strokeOpacity:"0.6",className:"pcv-orbit-y"}),Lt.jsx("circle",{cx:"32",cy:"32",r:"28",stroke:"#D1D5DB",strokeWidth:"1.5",strokeDasharray:"2 6",strokeOpacity:"0.3",className:"pcv-orbit-z"}),Lt.jsx("path",{d:"M 32 4 A 28 28 0 0 1 32 60 A 28 28 0 0 1 32 4",stroke:"#2DD4BF",strokeWidth:"2",fill:"none",strokeLinecap:"round",className:"pcv-compile-line-1"}),Lt.jsx("path",{d:"M 32 4 A 28 28 0 0 0 32 60 A 28 28 0 0 0 32 4",stroke:"#3B82F6",strokeWidth:"2",fill:"none",strokeLinecap:"round",className:"pcv-compile-line-2"}),Lt.jsx("circle",{cx:"32",cy:"32",r:"4.5",fill:"#2DD4BF",className:"pcv-loader-core"}),Lt.jsx("circle",{cx:"32",cy:"32",r:"2",fill:"#111114"})]})}var RX={position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:"#000",zIndex:10,pointerEvents:"none"},LX={display:"flex",flexDirection:"column",alignItems:"center",gap:8},FX={width:192,height:8,borderRadius:9999,background:"color-mix(in oklab, var(--primary, #2DD4BF) 20%, transparent)",overflow:"hidden"},OX={height:"100%",borderRadius:9999,background:"var(--primary, #2DD4BF)",transition:"width 0.2s ease"},BX={position:"absolute",inset:0,display:"flex",alignItems:"center",justifyContent:"center",background:"#000",zIndex:10},NX={fontSize:14,fontWeight:500,color:"#f87171",maxWidth:320,textAlign:"center"},Dm=4278190080,_d=1e-4,Mm={none:[1,1,1],x180:[1,-1,-1],y180:[-1,1,-1],z180:[-1,-1,1]},kX=1.1;function gx(l,e){const t=parseFloat(l),i=Number.isFinite(t)&&t<kX?Mm.none:Mm.z180,r=Mm[e];return[i[0]*r[0],i[1]*r[1],i[2]*r[2]]}var UX=2.6,gd=48,zX=2,VX=1,GX=40,HX=.5,WX=5;function XX(l){const e=l.voxelResolution;if(!(e>0))return 1;const[t,s,i]=l.gridBounds.min,[r,a,n]=l.gridBounds.max,o=(r-t)/gd,c=(n-i)/gd,h=e*zX;if(!(o>0)||!(c>0)||!(a-s>h))return 1;const d=[];for(let p=0;p<gd;p++){const m=t+(p+.5)*o;for(let _=0;_<gd;_++){const g=i+(_+.5)*c;let v=0,x=null,y=!1;for(let S=s+e*.5;S<a;S+=h)if(l.queryPoint(m,S,g)){if(x!==null&&y){const T=S-x;T>v&&(v=T)}x=null,y=!0}else x===null&&y&&(x=S);v>=VX&&d.push(v)}}if(d.length<GX)return 1;d.sort((p,m)=>p-m);const f=d[Math.floor(d.length/2)]/UX;return Math.min(WX,Math.max(HX,f))}function YX(l){return l>>>=0,l-=l>>>1&1431655765,l=(l&858993459)+(l>>>2&858993459),(l+(l>>>4)&252645135)*16843009>>>24}function vx(l){return Array.isArray(l)&&l.length===3&&l.every(e=>typeof e=="number"&&Number.isFinite(e))}function jX(l){if(!l||typeof l!="object")return!1;const e=l,{leafSize:t,treeDepth:s,nodeCount:i,leafDataCount:r,voxelResolution:a}=e;return e.gridBounds!==void 0&&typeof e.gridBounds=="object"&&vx(e.gridBounds.min)&&vx(e.gridBounds.max)&&typeof a=="number"&&a>0&&typeof t=="number"&&Number.isInteger(t)&&t>0&&typeof s=="number"&&Number.isInteger(s)&&s>=0&&typeof i=="number"&&Number.isInteger(i)&&i>=0&&typeof r=="number"&&Number.isInteger(r)&&r>=0}function qX(l){const e=".voxel.json",t=l.indexOf(e);return t>=0?`${l.slice(0,t)}.voxel.bin${l.slice(t+e.length)}`:new URL("splat.voxel.bin",l).toString()}var $X=class XC{gridBounds;gaussianBounds;voxelResolution;leafSize;treeDepth;numVoxelsX;numVoxelsY;numVoxelsZ;nodes;leafData;version;push={x:0,y:0,z:0};rayHit={x:0,y:0,z:0};constraintNormals=[{x:0,y:0,z:0},{x:0,y:0,z:0},{x:0,y:0,z:0}];constructor(e,t,s){this.version=e.version,this.gridBounds=e.gridBounds,this.gaussianBounds=e.gaussianBounds,this.voxelResolution=e.voxelResolution,this.leafSize=e.leafSize,this.treeDepth=e.treeDepth,this.numVoxelsX=Math.round((e.gridBounds.max[0]-e.gridBounds.min[0])/e.voxelResolution),this.numVoxelsY=Math.round((e.gridBounds.max[1]-e.gridBounds.min[1])/e.voxelResolution),this.numVoxelsZ=Math.round((e.gridBounds.max[2]-e.gridBounds.min[2])/e.voxelResolution),this.nodes=t,this.leafData=s}static async load(e){const t=await fetch(e,{credentials:"omit"});if(!t.ok)throw new Error(`Failed to fetch voxel metadata: ${t.status}`);const s=await t.json();if(!jX(s))throw new Error("Invalid voxel metadata");const i=await fetch(qX(e),{credentials:"omit"});if(!i.ok)throw new Error(`Failed to fetch voxel binary: ${i.status}`);const r=await i.arrayBuffer();if(r.byteLength%Uint32Array.BYTES_PER_ELEMENT!==0)throw new Error("Invalid voxel binary length");const a=new Uint32Array(r),n=s.nodeCount+s.leafDataCount;if(a.length<n)throw new Error("Voxel binary is shorter than metadata declares");return new XC(s,a.slice(0,s.nodeCount),a.slice(s.nodeCount,s.nodeCount+s.leafDataCount))}
17154queryPoint(e,t,s){const i=Math.floor((e-this.gridBounds.min[0])/this.voxelResolution),r=Math.floor((t-this.gridBounds.min[1])/this.voxelResolution),a=Math.floor((s-this.gridBounds.min[2])/this.voxelResolution);return this.isVoxelSolid(i,r,a)}estimateWorldScale(){return this.cachedWorldScale??=XX(this),this.cachedWorldScale}cachedWorldScale=null;isPointBlocked(e,t,s){const i=Math.floor((e-this.gridBounds.min[0])/this.voxelResolution),r=Math.floor((t-this.gridBounds.min[1])/this.voxelResolution),a=Math.floor((s-this.gridBounds.min[2])/this.voxelResolution);return this.isSolidForResolve(i,r,a)}queryCapsule(e,t,s,i,r,a){return this.queryIterative((n,o,c)=>this.resolveDeepestCapsulePenetration(n,o,c,i,r))(e,t,s,a)}querySphere(e,t,s,i,r){return this.queryIterative((a,n,o)=>this.resolveDeepestSpherePenetration(a,n,o,i))(e,t,s,r)}queryRay(e,t,s,i,r,a,n){if(this.nodes.length===0)return null;const o=this.voxelResolution,c=this.gridBounds.min[0],h=this.gridBounds.min[1],d=this.gridBounds.min[2],u=c+this.numVoxelsX*o,f=h+this.numVoxelsY*o,p=d+this.numVoxelsZ*o,m=1e-12;let _=0,g=n;if(Math.abs(i)>m){let B=(c-e)/i,z=(u-e)/i;if(B>z){const $=B;B=z,z=$}if(B>_&&(_=B),g=Math.min(g,z),_>g)return null}else if(e<c||e>=u)return null;if(Math.abs(r)>m){let B=(h-t)/r,z=(f-t)/r;if(B>z){const $=B;B=z,z=$}if(B>_&&(_=B),g=Math.min(g,z),_>g)return null}else if(t<h||t>=f)return null;if(Math.abs(a)>m){let B=(d-s)/a,z=(p-s)/a;if(B>z){const $=B;B=z,z=$}if(B>_&&(_=B),g=Math.min(g,z),_>g)return null}else if(s<d||s>=p)return null;const v=e+i*_,x=t+r*_,y=s+a*_;let S=Rm(Math.floor((v-c)/o),this.numVoxelsX-1),T=Rm(Math.floor((x-h)/o),this.numVoxelsY-1),w=Rm(Math.floor((y-d)/o),this.numVoxelsZ-1);const C=i>0?1:i<0?-1:0,b=r>0?1:r<0?-1:0,I=a>0?1:a<0?-1:0,P=Math.abs(i)>m?1/i:0,L=Math.abs(r)>m?1/r:0,O=Math.abs(a)>m?1/a:0;let D=Math.abs(i)>m?(c+(S+(i>0?1:0))*o-e)*P:1/0,N=Math.abs(r)>m?(h+(T+(r>0?1:0))*o-t)*L:1/0,k=Math.abs(a)>m?(d+(w+(a>0?1:0))*o-s)*O:1/0;const A=Math.abs(i)>m?o*Math.abs(P):1/0,M=Math.abs(r)>m?o*Math.abs(L):1/0,R=Math.abs(a)>m?o*Math.abs(O):1/0;let F=_;const U=this.numVoxelsX+this.numVoxelsY+this.numVoxelsZ;for(let B=0;B<U;B++){if(this.isVoxelSolid(S,T,w))return this.rayHit.x=e+i*F,this.rayHit.y=t+r*F,this.rayHit.z=s+a*F,this.rayHit;if(D<N?D<k?(F=D,S+=C,D+=A):(F=k,w+=I,k+=R):N<k?(F=N,T+=b,N+=M):(F=k,w+=I,k+=R),S<0||T<0||w<0||S>=this.numVoxelsX||T>=this.numVoxelsY||w>=this.numVoxelsZ||F>n)return null}return null}sampleSolidVoxels(e){const t=[];if(this.nodes.length===0||e<=0)return t;const s=this.numVoxelsX*this.numVoxelsY*this.numVoxelsZ,i=Math.max(1,Math.ceil(Math.cbrt(s/e))),r=this.voxelResolution*i;for(let a=0;a<this.numVoxelsZ;a+=i)for(let n=0;n<this.numVoxelsY;n+=i)for(let o=0;o<this.numVoxelsX;o+=i){if(!this.isVoxelSolid(o,n,a)||!this.isSampleSurface(o,n,a,i))continue;const c=[this.gridBounds.min[0]+o*this.voxelResolution,this.gridBounds.min[1]+n*this.voxelResolution,this.gridBounds.min[2]+a*this.voxelResolution];if(t.push({min:c,max:[c[0]+r,c[1]+r,c[2]+r]}),t.length>=e)return t}return t}sampleSolidVoxelCenters(e){const t=[];if(this.nodes.length===0||e<=0)return t;const s=this.leafSize,i=this.voxelResolution,r=this.gridBounds.min[0],a=this.gridBounds.min[1],n=this.gridBounds.min[2],o=(h,d,u,f)=>{const p=f*s/2;t.push({x:r+(h*s+p)*i,y:a+(d*s+p)*i,z:n+(u*s+p)*i})},c=[{nodeIndex:0,blockX:0,blockY:0,blockZ:0,sizeBlocks:1<<this.treeDepth}];for(;c.length>0&&t.length<e;){const h=c.pop();if(!h||h.nodeIndex>=this.nodes.length)continue;const d=this.nodes[h.nodeIndex]>>>0;if(d===Dm){o(h.blockX,h.blockY,h.blockZ,h.sizeBlocks);continue}const u=d>>>24&255;if(u===0){o(h.blockX,h.blockY,h.blockZ,1);continue}const f=d&16777215,p=h.sizeBlocks>>1;let m=0;for(let _=0;_<8;_++){if((u&1<<_)===0)continue;const g=_&1?p:0,v=_&2?p:0,x=_&4?p:0;c.push({nodeIndex:f+m,blockX:h.blockX+g,blockY:h.blockY+v,blockZ:h.blockZ+x,sizeBlocks:p}),m+=1}}return t}isSampleSurface(e,t,s,i){const r=(a,n,o)=>a>=0&&n>=0&&o>=0&&a<this.numVoxelsX&&n<this.numVoxelsY&&o<this.numVoxelsZ&&!this.isVoxelSolid(a,n,o);return r(e-i,t,s)||r(e+i,t,s)||r(e,t-i,s)||r(e,t+i,s)||r(e,t,s-i)||r(e,t,s+i)}queryIterative(e){return(t,s,i,r)=>{if(this.nodes.length===0)return!1;let a=t,n=s,o=i,c=0,h=0,d=0,u=!1,f=0;for(let _=0;_<4&&e(a,n,o);_++){u=!0;let g=this.push.x,v=this.push.y,x=this.push.z;for(let S=0;S<f;S++){const T=this.constraintNormals[S],w=g*T.x+v*T.y+x*T.z;w>=0||(g-=w*T.x,v-=w*T.y,x-=w*T.z)}const y=Math.sqrt(this.push.x*this.push.x+this.push.y*this.push.y+this.push.z*this.push.z);if(y>_d&&f<3){const S=this.constraintNormals[f],T=1/y;S.x=this.push.x*T,S.y=this.push.y*T,S.z=this.push.z*T,f++}a+=g,n+=v,o+=x,c+=g,h+=v,d+=x}const p=c*c+h*h+d*d,m=u&&p>_d*_d;return m&&(r.x=c,r.y=h,r.z=d),m}}resolveDeepestSpherePenetration(e,t,s,i){const r=Math.floor((e-i-this.gridBounds.min[0])/this.voxelResolution),a=Math.floor((t-i-this.gridBounds.min[1])/this.voxelResolution),n=Math.floor((s-i-this.gridBounds.min[2])/this.voxelResolution),o=Math.floor((e+i-this.gridBounds.min[0])/this.voxelResolution),c=Math.floor((t+i-this.gridBounds.min[1])/this.voxelResolution),h=Math.floor((s+i-this.gridBounds.min[2])/this.voxelResolution);return this.resolveDeepestVoxelPenetration(r,a,n,o,c,h,i,(d,u)=>Math.max(d,Math.min(t,u)),e,s)}resolveDeepestCapsulePenetration(e,t,s,i,r){const a=t-i,n=t+i,o=Math.floor((e-r-this.gridBounds.min[0])/this.voxelResolution),c=Math.floor((a-r-this.gridBounds.min[1])/this.voxelResolution),h=Math.floor((s-r-this.gridBounds.min[2])/this.voxelResolution),d=Math.floor((e+r-this.gridBounds.min[0])/this.voxelResolution),u=Math.floor((n+r-this.gridBounds.min[1])/this.voxelResolution),f=Math.floor((s+r-this.gridBounds.min[2])/this.voxelResolution);return this.resolveDeepestVoxelPenetration(o,c,h,d,u,f,r,(p,m)=>n<p?n:a>m?a:Math.max(a,Math.min((p+m)*.5,n)),e,s)}resolveDeepestVoxelPenetration(e,t,s,i,r,a,n,o,c,h){const d=n*n;let u=0,f=0,p=0,m=_d,_=!1;for(let g=s;g<=a;g++)for(let v=t;v<=r;v++)for(let x=e;x<=i;x++){if(!this.isSolidForResolve(x,v,g))continue;const y=this.gridBounds.min[0]+x*this.voxelResolution,S=this.gridBounds.min[1]+v*this.voxelResolution,T=this.gridBounds.min[2]+g*this.voxelResolution,w=y+this.voxelResolution,C=S+this.voxelResolution,b=T+this.voxelResolution,I=o(S,C),P=Math.max(y,Math.min(c,w)),L=Math.max(S,Math.min(I,C)),O=Math.max(T,Math.min(h,b)),D=c-P,N=I-L,k=h-O,A=D*D+N*N+k*k;if(A>=d)continue;const M=this.getVoxelPush(A,D,N,k,c,I,h,y,S,T,w,C,b,n);M.penetration<=m||(m=M.penetration,u=M.x,f=M.y,p=M.z,_=!0)}return _&&(this.push.x=u,this.push.y=f,this.push.z=p),_}getVoxelPush(e,t,s,i,r,a,n,o,c,h,d,u,f,p){if(e>1e-12){const S=Math.sqrt(e),T=p-S,w=1/S;return{x:t*w*T,y:s*w*T,z:i*w*T,penetration:T}}const m=r-o<d-r?-(r-o+p):d-r+p,_=a-c<u-a?-(a-c+p):u-a+p,g=n-h<f-n?-(n-h+p):f-n+p,v=Math.abs(m),x=Math.abs(_),y=Math.abs(g);return v<=x&&v<=y?{x:m,y:0,z:0,penetration:v}:x<=y?{x:0,y:_,z:0,penetration:x}:{x:0,y:0,z:g,penetration:y}}
17154isSolidForResolve(e,t,s){return e<0||t<0||s<0||e>=this.numVoxelsX||t>=this.numVoxelsY||s>=this.numVoxelsZ?this.nodes.length>0:this.isVoxelSolid(e,t,s)}isVoxelSolid(e,t,s){if(this.nodes.length===0||e<0||t<0||s<0||e>=this.numVoxelsX||t>=this.numVoxelsY||s>=this.numVoxelsZ)return!1;const i=Math.floor(e/this.leafSize),r=Math.floor(t/this.leafSize),a=Math.floor(s/this.leafSize);let n=0;for(let c=this.treeDepth-1;c>=0;c--){const h=this.nodes[n]>>>0;if(h===Dm)return!0;const d=h>>>24&255;if(d===0)return this.checkLeafByIndex(h,e,t,s);const u=i>>>c&1,f=r>>>c&1,m=(a>>>c&1)<<2|f<<1|u;if((d&1<<m)===0||(n=(h&16777215)+YX(d&(1<<m)-1),n>=this.nodes.length))return!1}const o=this.nodes[n]>>>0;return o===Dm?!0:this.checkLeafByIndex(o,e,t,s)}checkLeafByIndex(e,t,s,i){const a=(e&16777215)*2;if(a+1>=this.leafData.length)return!1;const n=(i&3)*16+(s&3)*4+(t&3);return n<32?(this.leafData[a]>>>0>>>n&1)===1:(this.leafData[a+1]>>>0>>>n-32&1)===1}};function Rm(l,e){return l<0?0:l>e?e:l}var KX=1400,ZX=class{app;boxes;color=new Q(.2,.85,1,.8);corners=Array.from({length:8},()=>new E);isEnabled=!1;signX;signY;signZ;constructor(l,e,t=[1,1,1]){this.app=l,this.boxes=e.sampleSolidVoxels(KX),this.signX=t[0],this.signY=t[1],this.signZ=t[2],this.app.on("update",this.onUpdate,this)}setSigns(l){this.signX=l[0],this.signY=l[1],this.signZ=l[2],this.isEnabled&&(this.app.renderNextFrame=!0)}voxelToPlayCanvas(l,e){return e.set(this.signX*l[0],this.signY*l[1],this.signZ*l[2])}get enabled(){return this.isEnabled}set enabled(l){this.isEnabled=l,l&&(this.app.renderNextFrame=!0)}destroy(){this.app.off("update",this.onUpdate,this)}onUpdate=()=>{if(this.isEnabled)for(const l of this.boxes)this.drawBox(l)};drawBox(l){const[e,t,s]=l.min,[i,r,a]=l.max;this.voxelToPlayCanvas([e,t,s],this.corners[0]),this.voxelToPlayCanvas([i,t,s],this.corners[1]),this.voxelToPlayCanvas([i,r,s],this.corners[2]),this.voxelToPlayCanvas([e,r,s],this.corners[3]),this.voxelToPlayCanvas([e,t,a],this.corners[4]),this.voxelToPlayCanvas([i,t,a],this.corners[5]),this.voxelToPlayCanvas([i,r,a],this.corners[6]),this.voxelToPlayCanvas([e,r,a],this.corners[7]),this.line(0,1),this.line(1,2),this.line(2,3),this.line(3,0),this.line(4,5),this.line(5,6),this.line(6,7),this.line(7,4),this.line(0,4),this.line(1,5),this.line(2,6),this.line(3,7)}line(l,e){this.app.drawLine(this.corners[l],this.corners[e],this.color,!1)}},QX=75,JX=1,eY=.42,tY=.78,YC=1.08,sY=68,iY=350;function Sx(l){if(!(l instanceof HTMLElement))return!1;const e=l.tagName.toLowerCase();return l.isContentEditable||e==="input"||e==="textarea"||e==="select"}function yx(l){return l.loadingCount>0?`Loading ${l.label} detail...`:`Loading ${l.label} detail...`}function rY(l){return l==="fast"?"Fast":l==="highest"?"Highest Quality":"Balance"}async function aY(l){if(!l)return{collider:null,failed:!1};try{return{collider:await $X.load(l),failed:!1}}catch{return{collider:null,failed:!0}}}function xx(l,e,t){if(t!=="auto")switch(t){case"x180":return"x180";case"y180":return"y180";case"z180":return"z180";default:return"none"}const s=L5(l,e);return s==="x180"?"x180":s==="z180"?"z180":"none"}
17154var Tx={none:[0,0,0],x180:[180,0,0],y180:[0,180,0],z180:[0,0,180]};async function nY(l){try{if(typeof createImageBitmap!="function")return!1;const e=await createImageBitmap(l),t=Math.max(1,Math.min(e.width,64)),s=Math.max(1,Math.min(e.height,64)),i=document.createElement("canvas");i.width=t,i.height=s;const r=i.getContext("2d");if(!r)return e.close?.(),!1;r.drawImage(e,0,0,t,s),e.close?.();const{data:a}=r.getImageData(0,0,t,s);let n=0;for(let o=0;o<a.length;o+=4)(a[o]>8||a[o+1]>8||a[o+2]>8)&&(n+=1);return n/(t*s)<.005}catch{return!1}}function wx(l){return Array.isArray(l)&&l.length===3&&l.every(e=>typeof e=="number"&&Number.isFinite(e))}function _o(l){if(!l||typeof l!="object")return!1;const e=l;return wx(e.min)&&wx(e.max)}function Hl(l,e){const t=e[0]*l.min[0],s=e[0]*l.max[0],i=e[1]*l.min[1],r=e[1]*l.max[1],a=e[2]*l.min[2],n=e[2]*l.max[2];return{min:[Math.min(t,s),Math.min(i,r),Math.min(a,n)],max:[Math.max(t,s),Math.max(i,r),Math.max(a,n)]}}function ao(l,e){const t=l.slice().sort((i,r)=>i-r),s=Math.min(t.length-1,Math.max(0,Math.round(e*(t.length-1))));return t[s]}function jC(l,e){if(!l)return null;const t=l.sampleSolidVoxelCenters(4e4);if(t.length<32)return null;const s=[],i=[],r=[];for(const n of t){const o=e[0]*n.x,c=e[1]*n.y,h=e[2]*n.z;!Number.isFinite(o)||!Number.isFinite(c)||!Number.isFinite(h)||(s.push(o),i.push(c),r.push(h))}if(s.length<32)return null;const a=l.voxelResolution||0;return{min:[ao(s,.02)-a,ao(i,.02)-a,ao(r,.02)-a],max:[ao(s,.98)+a,ao(i,.98)+a,ao(r,.98)+a]}}function qC(l,e){const t={xAxis:[1,0],yAxis:[0,1]};if(!l)return t;let s=0,i=0;const r=[],a=l.sampleSolidVoxelCenters(4096);if(a.length>=8)for(const _ of a){const g=e[0]*_.x,v=e[2]*_.z;r.push([g,v]),s+=g,i+=v}else{const _=l.sampleSolidVoxels(4096);if(_.length<8)return t;for(const g of _){const v=e[0]*((g.min[0]+g.max[0])*.5),x=e[2]*((g.min[2]+g.max[2])*.5);r.push([v,x]),s+=v,i+=x}}if(r.length<8)return t;s/=r.length,i/=r.length;for(const[_,g]of r)if(!Number.isFinite(_)||!Number.isFinite(g))return t;let n=0,o=0,c=0;for(const[_,g]of r){const v=_-s,x=g-i;n+=v*v,o+=v*x,c+=x*x}if(n+c<=1e-6)return t;const h=.5*Math.atan2(2*o,n-c),d=[0,Math.PI/2,h,h+Math.PI/2];let u=0,f=1/0;for(const _ of d){const g=Math.cos(_),v=Math.sin(_),x=-v,y=g;let S=1/0,T=-1/0,w=1/0,C=-1/0;for(const[I,P]of r){const L=I-s,O=P-i,D=L*g+O*v,N=L*x+O*y;S=Math.min(S,D),T=Math.max(T,D),w=Math.min(w,N),C=Math.max(C,N)}const b=(T-S)*(C-w);b<f&&(f=b,u=_)}let p=Math.cos(u),m=Math.sin(u);if(Math.abs(p)<Math.abs(m)){const _=-m;m=p,p=_}return(p<0||Math.abs(p)<1e-6&&m<0)&&(p*=-1,m*=-1),{xAxis:[p,m],yAxis:[-m,p]}}function Cx(l,e,t,s=16/9,i=tY){if(!l||!_o(l.gridBounds))return null;const r=_o(l.gaussianBounds)?l.gaussianBounds:l.gridBounds,a=jC(l,e)??Hl(r,e),[n,o,c]=a.min,[h,d,u]=a.max,f=h-n,p=u-c,m=d-o;if(!(f>0)||!(p>0)||!(m>0))return null;const _=(n+h)/2,g=(c+u)/2,{xAxis:v,yAxis:x}=qC(l,e),y=[[n,c],[n,u],[h,c],[h,u]];let S=0,T=0;for(const[B,z]of y){const $=B-_,K=z-g;S=Math.max(S,Math.abs($*v[0]+K*v[1])),T=Math.max(T,Math.abs($*x[0]+K*x[1]))}const w=o+m*i,C=sY,b=C*Math.PI/180,I=Math.sin(b);if(I<.001)return null;const P=o+m*.12,L=s>.2?s:16/9,O=(t>5?t:75)*Math.PI/180/2,D=Math.tan(O);if(D<.001)return null;const N=YC,k=T*N/D,A=S*N/(D*L),M=Math.max(k,A)/I,R=(d+m*.45-P)/I,F=Math.max(M,R,2);let U=(d+m*.18-P)/I;return U>.5||(U=F*.45),U>=F*.9&&(U=F*.5),U=Math.max(U,1),{pivot:[_,P,g],yaw:Math.atan2(x[0],x[1])*180/Math.PI,pitch:C,cutHeight:w,fov:t,outsideDistance:U,overviewDistance:F}}async function oY(l){if(typeof document>"u"||typeof createImageBitmap!="function")return null;try{const e=await createImageBitmap(l),t=Math.min(e.width,e.height);if(!(t>0))return e.close?.(),null;const s=document.createElement("canvas");s.width=t,s.height=t;const i=s.getContext("2d");if(!i)return e.close?.(),null;i.drawImage(e,Math.round((e.width-t)/2),Math.round((e.height-t)/2),t,t,0,0,t,t),e.close?.();const r=await new Promise(a=>s.toBlob(a,"image/png"));return r?{blob:r,size:t}:null}catch{return null}}var dY=he.forwardRef(function({contentUrl:e,format:t,skyboxUrl:s,collisionUrl:i,background:r=[0,0,0],fov:a=QX,initialCamera:n,transform:o="none",transformOverride:c="auto",render
17154Settings:h=null,splatBudgetMillions:d=0,forceWebgl:u,initialLodQualityPreset:f="recommended",hideLoadingOverlay:p=!1,cameraMode:m="fly",walkModeHeight:_=null,walkModeSpeed:g=null,showCollisionDebug:v=!1,className:x,style:y,onLoaded:S,onError:T,onLoadingStatusChange:w,onCollisionUnavailable:C,onDollhouseChange:b,pointCloudMode:I,pointSizePx:P=sv,onPointCloudModeChange:L,pointModeHotkey:O=!0,normalMode:D,onNormalModeChange:N,normalModeHotkey:k=!0},A){const M=he.useRef(null),R=he.useRef(null),F=he.useRef(null),U=he.useRef(null),B=he.useRef(null),z=he.useRef(null),$=he.useRef(null),K=he.useRef([1,1,1]),Y=he.useRef(new Set),te=he.useRef(null),J=he.useRef(!1),_e=he.useRef(!1),Ae=he.useRef(!1),we=he.useRef(L);we.current=L;const $e=I!==void 0,[Ye,Ee]=he.useState(!1),Pe=$e?I:Ye,ke=he.useRef(!1),ps=he.useRef(N);ps.current=N;const se=D!==void 0,[Tn,bs]=he.useState(!1),Mr=se?D:Tn,Sa=he.useRef(0),Rr=he.useRef(!1),As=he.useRef(!1),[ms,Ue]=he.useState(!0),[Lr,ya]=he.useState(null),[xa,th]=he.useState(0),[Ta,wn]=he.useState(f),el=he.useRef(f),sh=he.useRef(null),ih=he.useRef(0),[iv,rh]=he.useState(null),xe=he.useRef({background:r,fov:a,initialCamera:n,initialLodQualityPreset:f,splatBudgetMillions:d,format:t,transform:o,transformOverride:c,renderSettings:h,collisionUrl:i,cameraMode:m,walkModeHeight:_,walkModeSpeed:g,showCollisionDebug:v,onLoaded:S,onError:T,onLoadingStatusChange:w,onCollisionUnavailable:C,onDollhouseChange:b});xe.current={background:r,fov:a,initialCamera:n,initialLodQualityPreset:f,splatBudgetMillions:d,format:t,transform:o,transformOverride:c,renderSettings:h,collisionUrl:i,cameraMode:m,walkModeHeight:_,walkModeSpeed:g,showCollisionDebug:v,onLoaded:S,onError:T,onLoadingStatusChange:w,onCollisionUnavailable:C,onDollhouseChange:b};const Cn=he.useCallback(()=>{sh.current=null,rh(ih.current>0?"Loading more detail...":null)},[]),ah=he.useCallback(V=>{const W=F.current,ee=U.current,fe=Bi(ee).lodLevels;if(!W||xe.current.format!=="sog-lod"&&fe===0){Cn();return}const Oe={label:rY(V),targetLevel:U_(V,fe),startedAt:performance.now(),loadingCount:0,observedLoading:!1,ready:!1};sh.current=Oe,rh(yx(Oe)),W.requestRender()},[Cn]),rv=he.useCallback((V,W)=>{el.current=V,wn(V);const ee=F.current;ee&&(N5(ee.app,V,U.current,xe.current.format),W?.showLoading!==!1&&ah(V),ee.requestRender())},[ah]),tl=he.useCallback((V,W,ee=P)=>{Ae.current=V,ke.current=W;const fe=F.current;fe&&(Im(fe.app,U.current,{pointMode:V,normalMode:W,pointSizePx:ee,format:xe.current.format,minimapClipMaxY:te.current}),fe.requestRender())},[P]),nh=he.useCallback(V=>{$e||Ee(V),we.current?.(V)},[$e]),oh=he.useCallback(V=>{se||bs(V),ps.current?.(V)},[se]),lh=he.useCallback(V=>{Y.current.forEach(W=>{W.setParameter?.("minimapClipMaxY",V),W.update?.()})},[]),jt=he.useCallback(V=>{const W=V!==null&&Number.isFinite(V)&&V<sa/2?V:null;te.current=W,lh(W??sa);const ee=F.current;ee&&(Im(ee.app,U.current,{pointMode:Ae.current,normalMode:ke.current,pointSizePx:P,format:xe.current.format,minimapClipMaxY:W??sa}),ee.requestRender())},[lh,P]),av=he.useRef(Promise.resolve()),nv=he.useCallback(async V=>{const W=F.current,ee=R.current,fe=M.current;if(!W||!ee||!fe)return null;const Oe=(()=>{const vs=$.current;if(!vs||!_o(vs.gridBounds))return null;const Br=K.current,En=_o(vs.gaussianBounds)?vs.gaussianBounds:vs.gridBounds;return{gridBounds:Hl(vs.gridBounds,Br),gaussianBounds:Hl(En,Br),voxelResolution:vs.voxelResolution}})();if(!Oe)return null;const We=jC($.current,K.current)??Oe.gaussianBounds,[wt,Ct,si]=We.min,[ts,_s,Ci]=We.max,Ei=ts-wt,yt=Ci-si,Ps=_s-Ct;if(!(Ei>0)||!(yt>0)||!(Ps>0))return null;const Fr=W.camera,qt=Fr.camera;if(!qt)return null;const Yi=ee.getCameraPose(),Vf=qt.projection,Gf=qt.orthoHeight,sl=qt.nearClip,ii=qt.farClip,Hf=qt.fov,wa=fe.clientWidth>0&&fe.clientHeight>0?fe.clientWidth/fe.clientHeight:1,gs=(wt+ts)/2,Or=(si+Ci)/2,{xAxis:Et,yAxis:os}=qC($.current,K.current),bi=[[wt,si],[wt,Ci],[ts,si],[ts,Ci]];let ss=0,il=0;for(const[vs,Br]of bi){const En=vs-gs,rl=Br-Or;ss=Math.max(ss,Math.abs(En*Et[0]+rl*Et[1])),il=Math.max(il,Math.abs(En*os[0]+rl*os[1]))}const Wf=Math.max(1,V?.coverageScale??1),ch=Math.max(il,ss)*YC*Wf,Xf=wa>=1?ch:ch/wa,$C=Xf*wa,hh=Ct+Ps*(V?.roofCutRatio??eY),Yf=hh,cv=Ct-Math.max(Ps,1),KC=Math.max(1,Yf-Ct+Ps*.25);try{ee.beginExternalDrive(),lh(hh),Im(W.app,U.current,{pointMode:Ae.current,normalMode:ke.current,pointSizePx:P,format:xe.current.format,minimapClipMaxY:hh}),qt.projection=Sn,qt.orthoHeight=Xf,qt.nearClip=.01,qt.farClip=KC,Fr.setPosition(gs,Yf,Or),Fr.lookAt(new E(gs,cv,Or),new E(-os[0],0,-os[1]));for(let dh=0;dh<4;dh+=1)Fr.setPosition(gs,Yf,Or),Fr.lookAt(new E(gs,cv,Or),new E(-os[0],0,-os[1])),W.requestRender(),await new Promise(ZC=>
17154requestAnimationFrame(()=>ZC()));const vs=await new Promise(dh=>fe.toBlob(dh,"image/png"));if(!vs||await nY(vs))return null;const Br=await oY(vs),En=Br?[ch,ch]:[$C,Xf],rl=Br?.size??Math.min(fe.width,fe.height);return{blob:Br?.blob??vs,bounds:{min:[wt,Ct,si],max:[ts,_s,Ci]},coordinateFrame:{origin:[gs,Or],xAxis:Et,yAxis:os,halfSize:En},width:rl,height:rl,cutHeight:hh}}finally{jt(te.current),qt.projection=Vf??mi,qt.orthoHeight=Gf,qt.nearClip=sl,qt.farClip=ii,qt.fov=Hf,ee.endExternalDrive(),ee.setPose(new E(Yi.position[0],Yi.position[1],Yi.position[2]),new E(Yi.target[0],Yi.target[1],Yi.target[2]),Yi.fov),W.requestRender()}},[lh,jt,P]),ov=he.useCallback(V=>{const W=av.current.then(()=>nv(V));return av.current=W.then(()=>{},()=>{}),W},[nv]),lv=he.useCallback(async V=>{const W=F.current,ee=M.current;if(!W||!ee||ee.width===0||ee.height===0)return null;W.requestRender(),await new Promise(Oe=>requestAnimationFrame(()=>Oe()));const fe=await new Promise(Oe=>ee.toBlob(Oe,"image/png"));if(!fe)return null;try{if(typeof createImageBitmap!="function")return await new Promise(Ci=>{const Ei=new FileReader;Ei.onload=()=>Ci(typeof Ei.result=="string"?Ei.result:null),Ei.onerror=()=>Ci(null),Ei.readAsDataURL(fe)});const Oe=await createImageBitmap(fe),We=Math.max(32,V?.maxWidthPx??160),wt=Math.min(1,We/Math.max(1,Oe.width)),Ct=Math.max(1,Math.round(Oe.width*wt)),si=Math.max(1,Math.round(Oe.height*wt)),ts=document.createElement("canvas");ts.width=Ct,ts.height=si;const _s=ts.getContext("2d");return _s?(_s.imageSmoothingEnabled=!0,_s.imageSmoothingQuality="high",_s.drawImage(Oe,0,0,Ct,si),Oe.close?.(),ts.toDataURL("image/jpeg",V?.quality??.72)):(Oe.close?.(),null)}catch{return null}},[]);return he.useImperativeHandle(A,()=>({resetView:()=>R.current?.reset(),setExternalMovement:V=>R.current?.setExternalMovement(V),getAutoCameraMode:()=>R.current?.getAutoCameraMode()??"off",getCameraMode:()=>R.current?.getCameraMode()??"fly",setCameraMode:V=>{const W=R.current;if((J.current||W?.isDollhouseMode()===!0)&&V==="walk"&&W){_e.current=!0,J.current=!1,W.exitDollhouseToOrigin("walk",()=>{_e.current=!1,jt(null)}),F.current?.requestRender();return}V==="walk"&&(J.current=!1,W?.setDollhouseMode(!1),jt(null)),W?.setCameraMode(V),F.current?.requestRender()},getCameraPose:()=>R.current?.getCameraPose()??null,getNavigationBounds:()=>{const V=$.current;if(!V||!_o(V.gridBounds))return null;const W=K.current,ee=_o(V.gaussianBounds)?V.gaussianBounds:V.gridBounds;return{gridBounds:Hl(V.gridBounds,W),gaussianBounds:Hl(ee,W),voxelResolution:V.voxelResolution}},navigateToXZ:(V,W,ee)=>R.current?.navigateToXZ(V,W,ee?.durationMs)??!1,enterDollhouse:V=>{const W=R.current,ee=$.current,fe=M.current;if(!W||!ee)return!1;const Oe=fe&&fe.clientWidth>0&&fe.clientHeight>0?fe.clientWidth/fe.clientHeight:16/9,We=Cx(ee,K.current,W.getFov(),Oe,V?.roofCutRatio);if(!We)return!1;W.setCameraMode("fly"),W.setDollhouseMode(!0,We.cutHeight),J.current=!0,_e.current=!1,jt(We.cutHeight);const wt=ts=>({pivot:We.pivot,yaw:We.yaw,pitch:We.pitch,distance:ts,fov:We.fov}),Ct=V?.durationMs??800,si=Math.round(Ct*1.25);return W.flyTo(wt(We.outsideDistance),Ct,()=>{W.isDollhouseMode()&&W.flyTo(wt(We.overviewDistance),si,void 0,{lockInput:!0})},{lockInput:!0}),F.current?.requestRender(),!0},exitDollhouse:()=>{R.current?.setDollhouseMode(!1),J.current=!1,_e.current=!1,jt(null)},exitDollhouseToOrigin:V=>{const W=R.current;if(!W)return;const ee=V?.mode??"fly";if(_e.current=!0,J.current=!1,!W.isDollhouseMode()){_e.current=!1,ee==="walk"?W.setCameraMode("walk"):W.reset(),F.current?.requestRender();return}W.exitDollhouseToOrigin(ee,()=>{_e.current=!1,jt(null)}),F.current?.requestRender()},isDollhouse:()=>J.current||R.current?.isDollhouseMode()===!0,getRoofCut:()=>te.current,setRoofCut:V=>jt(V),setDollhouseRoofCutRatio:V=>{const W=R.current,ee=$.current,fe=M.current;if(!W||!ee||!Number.isFinite(V))return!1;const Oe=fe&&fe.clientWidth>0&&fe.clientHeight>0?fe.clientWidth/fe.clientHeight:16/9,We=Cx(ee,K.current,W.getFov(),Oe,V);return We?(W.isDollhouseMode()&&(W.setDollhouseMode(!0,We.cutHeight),jt(We.cutHeight),F.current?.requestRender()),!0):!1},captureTopDownMinimap:ov,captureViewportThumbnail:lv,startAutoCamera:(V,W)=>R.current?.startAutoCamera(V,W),stopAutoCamera:()=>R.current?.stopAutoCamera(),getRecordingTarget:()=>B.current,playCameraPath:(V,W)=>R.current?.playPath(V,W)??!1,isWalkableXZ:(V,W,ee)=>R.current?.isWalkableXZ(V,W,ee)??!1,stopCameraPath:()=>{R.current?.stopPath(),J.current||jt(null)},isPlayingCameraPath:()=>R.current?.isPlayingPath()??!1,recordCameraPath:(V,W)=>{const ee=R.current,fe=B.current;if(!ee||!fe||(ee.setCameraMode("walk"),!ee.playPath(V,{speed:W?.speed,durationMs:W?.durationMs,pitchDegrees:W?.pitchDegrees})))return null;const We=ee.getActivePathDurationMs()??W?.durationMs??5e3,wt=fe.captureClip({durationMs:We,frameRate:W?.frameRate??30,videoBitsPerSecond:W?.videoBitsPerSecond??12e6,onProgress:W?.onProgress});return{done:wt.done.finally(()=>ee.stopPath()),cancel:()=>{wt.cancel(),ee.stopPath()}}},routeWalkPath:(V,W)=>R.current?.routeWalkWaypoints(V.map(ee=>({position:ee.position,yaw:ee.yawDegrees,pitch:ee.pitchDegrees,fov:ee.fov})),W)??[],playCameraPoses:(V,W)=>(J.current=!1,R.current?.setDollhouseMode(!1),R.current?.playPoseKeyframes(V.map(ee=>({position:ee.position,yaw:ee.yawDegrees,pitch:ee.pitchDegrees,fov:ee.fov,roofCut:ee.roofCut})),W)??!1),recordCameraPoses:(V,W)=>{const ee=R.current,fe=B.current;if(!ee||!fe||(ee.setCameraMode("fly"),ee.setDollhouseMode(!1),J.current=!1,!ee.playPoseKeyframes(V.map(Ct=>({position:Ct.position,yaw:Ct.yawDegrees,pitch:Ct.pitchDegrees,fov:Ct.fov,roofCut:Ct.roofCut})),{speed:W?.speed,durationMs:W?.durationMs,route:W?.route,turnSpeed:W?.turnSpeed})))return null;const We=ee.getActivePathDurationMs()??W?.durationMs??5e3,wt=fe.captureClip({durationMs:We,frameRate:W?.frameRate??30,videoBitsPerSecond:W?.videoBitsPerSecond??12e6,onProgress:W?.onProgress});return{done:wt.done.finally(()=>ee.stopPath()),cancel:()=>{wt.cancel(),ee.stopPath()}}},setPointMode:(V,W)=>{nh(V),tl(V,ke.current,W?.pointSizePx??P)},getPointMode:()=>Ae.current,setNormalMode:V=>
17154{oh(V),tl(Ae.current,V)},getNormalMode:()=>ke.current,getRenderParams:()=>{const V=F.current,W=V?Pm(V.app):null;return{splatBudgetMillions:W?.budgetMillions??xe.current.splatBudgetMillions,lodRangeMin:W?.lodRangeMin??0,lodRangeMax:W?.lodRangeMax??1e3,toneMapping:V?hx(V.camera):"none",fov:R.current?.getFov()??xe.current.fov,walkModeHeight:R.current?.getWalkModeHeight()??xe.current.walkModeHeight,walkModeSpeed:R.current?.getMoveSpeed()??xe.current.walkModeSpeed}},setRenderParams:V=>{const W=F.current;if(W&&V.splatBudgetMillions!==void 0&&B5(W.app,V.splatBudgetMillions,xe.current.format,U.current),W&&(V.lodRangeMin!==void 0||V.lodRangeMax!==void 0)){const ee=Pm(W.app);wn("custom"),z_(W.app,V.lodRangeMin??ee?.lodRangeMin??0,V.lodRangeMax??ee?.lodRangeMax??1e3,U.current)}W&&V.toneMapping!==void 0&&q5(W.camera,V.toneMapping),V.fov!==void 0&&R.current?.setFov(V.fov),V.walkModeHeight!==void 0&&R.current?.setWalkModeHeight(V.walkModeHeight),V.walkModeSpeed!==void 0&&R.current?.setMoveSpeed(V.walkModeSpeed),W?.requestRender()},setLodQualityPreset:V=>rv(V),getLodQualityPreset:()=>Ta,getStats:()=>{const V=F.current,W=M.current;if(!V||!W)return null;const ee=Pm(V.app),fe=V.app.graphicsDevice,Oe=V.camera.getPosition(),We=Bi(U.current);return{fps:V.frameStats.fps,frameMs:V.frameStats.frameMs,renderedFrames:V.frameStats.renderedFrames,renderer:V.renderer,devicePixelRatio:fe.maxPixelRatio??window.devicePixelRatio??1,canvasWidth:W.clientWidth,canvasHeight:W.clientHeight,backbufferWidth:fe.width??W.width,backbufferHeight:fe.height??W.height,deviceProfile:Xi().name,contentFormat:xe.current.format,splatCount:We.splatCount,lodLevels:We.lodLevels,collisionLoaded:Rr.current,collisionDebugVisible:z.current?.enabled??!1,cameraMode:R.current?.getCameraMode()??"fly",renderParams:{splatBudgetMillions:ee?.budgetMillions??xe.current.splatBudgetMillions,lodRangeMin:ee?.lodRangeMin??0,lodRangeMax:ee?.lodRangeMax??1e3,toneMapping:hx(V.camera),fov:R.current?.getFov()??xe.current.fov,walkModeHeight:R.current?.getWalkModeHeight()??xe.current.walkModeHeight,walkModeSpeed:R.current?.getMoveSpeed()??xe.current.walkModeSpeed},cameraPosition:[Oe.x,Oe.y,Oe.z]}}}),[tl,ov,lv,P,jt,nh,oh,rv,Ta]),he.useEffect(()=>{ms||tl(Pe,Mr,P)},[ms,Pe,Mr,P,e,tl]),he.useEffect(()=>{const V={loading:ms,progress:xa,error:!!Lr,lodLoadingText:iv,qualityPreset:Ta};xe.current.onLoadingStatusChange?.(V)},[ms,xa,Lr,iv,Ta]),he.useEffect(()=>{if(O===!1)return;const V=W=>{W.defaultPrevented||W.repeat||W.metaKey||W.ctrlKey||W.altKey||W.key.toLowerCase()!=="p"||W.shiftKey||Sx(W.target)||nh(!Pe)};return window.addEventListener("keydown",V),()=>window.removeEventListener("keydown",V)},[O,Pe,nh]),he.useEffect(()=>{if(k===!1)return;const V=W=>{W.defaultPrevented||W.repeat||W.metaKey||W.ctrlKey||W.altKey||W.key.toLowerCase()!=="n"||W.shiftKey||Sx(W.target)||oh(!Mr)};return window.addEventListener("keydown",V),()=>window.removeEventListener("keydown",V)},[k,Mr,oh]),he.useEffect(()=>{let V=!1,W=null,ee=null,fe=null,Oe=null,We=null;const wt=M.current;if(!wt)return;Ue(!0),ya(null),Ae.current=!1,$e||Ee(!1),ke.current=!1,se||bs(!1),el.current=xe.current.initialLodQualityPreset,wn(xe.current.initialLodQualityPreset),ih.current=0,Cn(),Sa.current=0,th(0),Rr.current=!1,As.current=!1,K.current=[1,1,1];const Ct=ts=>{if(V)return;const _s=Math.max(0,Math.min(100,ts));_s<=Sa.current||(Sa.current=_s,th(_s))};return(async()=>{const{background:ts,fov:_s,initialCamera:Ci,splatBudgetMillions:Ei}=xe.current;try{if(await new Promise(Et=>setTimeout(Et,0)),V)return;const yt=await A5(wt,{background:ts,fov:_s,format:t,forceWebgl:u});if(W=yt,F.current=yt,Y.current.clear(),fe=yt.app.systems.gsplat??null,Oe=Et=>{const os=Et;HC(os),Y.current.add(os)},fe?.on?.("material:created",Oe),We=(...Et)=>{const os=!!Et[2],bi=Number(Et[3])||0;bi!==ih.current&&(ih.current=bi,sh.current||rh(bi>0?"Loading more detail...":null));const ss=sh.current;if(!ss)return;ss.ready=os,ss.loadingCount=bi,bi>0&&(ss.observedLoading=!0);const il=performance.now()-ss.startedAt,Wf=ss.observedLoading||il>=iY;if(ss.ready&&bi===0&&Wf){Cn();return}rh(yx(ss))},fe?.on?.("frame:ready",We),V){fe?.off?.("material:created",Oe),fe?.off?.("frame:ready",We),yt.dispose();return}if(s&&(await $5(yt.app,s).catch(()=>{}),V))return;const Ps=await R5(yt.app,e,{format:xe.current.format,transform:xe.current.transform,onProgress:Et=>Ct(Et*.9)});if(V)return;Ct(90),U.current=Ps;const Fr=xx(xe.current.format,xe.current.transform,xe.current.transformOverride),[qt,Yi,Vf]=Tx[Fr];Ps.setLocalEulerAngles(qt,Yi,Vf);const Gf=K5(yt.app,Ps,Ei,xe.current.format);let sl=!1;if(Gf){const Et=Bi(Ps).lodLevels,os=Et-1,bi=U_(el.current,Et),ss=Math.min(os,Math.max(JX,bi));ss<os&&(z_(yt.app,ss,ss,Ps),sl=!0)}ee=new SX(yt.app,yt.camera,wt,yt.requestRender),ee.setWalkModeHeight(xe.current.walkModeHeight),ee.setMoveSpeed(xe.current.walkModeSpeed),ee.setRoofCutListener(Et=>jt(Et)),ee.setDollhouseJumpListener(()=>{J.current=!1,xe.current.onDollhouseChange?.(!1)}),R.current=ee;const{collider:ii,failed:Hf}=await aY(xe.current.collisionUrl);if(V)return;As.current=!0,Rr.current=!!ii,$.current=ii,Hf&&xe.current.onCollisionUnavailable?.();const wa=ii?gx(ii.version,Fr):[1,1,1];if(K.current=wa,ee.setVoxelCollider(ii,wa),ee.setWalkBounds(ii?.gridBounds??null),ii){const Et=new ZX(yt.app,ii,wa);Et.enabled=xe.current.showCollisionDebug,z.current=Et}
17154B.current=new IX(yt.app,yt.camera,ee,wt);const gs=Ci??{position:[0,0,0],target:[0,0,-1],fov:_s};ee.setPose(new E(gs.position[0],gs.position[1],gs.position[2]),new E(gs.target[0],gs.target[1],gs.target[2]),gs.fov);const Or=ii||xe.current.cameraMode!=="walk"?xe.current.cameraMode:"fly";if(ee.setCameraMode(Or),await Z5(yt.app,Et=>Ct(90+Et*.1),xe.current.format==="spz"?6e4:sl?2e4:12e3,xe.current.format==="spz"?{rejectOnTimeout:!0,requireLoadingZero:!0}:sl?{requireObservedLoading:!0,requireLoadingZero:!0}:void 0),V)return;F5(yt.app,Ps,{budgetMillions:Ei,format:xe.current.format,lodQualityPreset:el.current,renderSettings:xe.current.renderSettings}),ah(el.current),Ct(100),Ue(!1),xe.current.onLoaded?.()}catch(yt){if(V)return;const Ps=yt instanceof Error?yt.message:String(yt);ya(Ps),Ue(!1),xe.current.onError?.(yt)}})(),()=>{V=!0,B.current=null,U.current=null,z.current?.destroy(),z.current=null,$.current=null,Oe&&fe?.off?.("material:created",Oe),We&&fe?.off?.("frame:ready",We),Cn(),Y.current.clear(),Rr.current=!1,As.current=!1,ee?.dispose(),R.current=null,W?.dispose(),F.current=null}},[e,s,i,u,o,t,$e,se,ah,Cn]),he.useEffect(()=>{const V=U.current;if(!V)return;const W=xx(t,o,c),ee=Tx[W];V.setLocalEulerAngles(ee[0],ee[1],ee[2]);const fe=$.current;if(fe){const Oe=gx(fe.version,W);K.current=Oe,R.current?.setColliderSigns(Oe),z.current?.setSigns(Oe)}F.current?.requestRender()},[o,c,t]),he.useEffect(()=>{const V=R.current;if(!V)return;const W=As.current&&m==="walk"&&!Rr.current,ee=W?"fly":m;if(W&&xe.current.onCollisionUnavailable?.(),!_e.current){if((J.current||V.isDollhouseMode())&&ee==="walk"){_e.current=!0,J.current=!1,V.exitDollhouseToOrigin("walk",()=>{_e.current=!1,jt(null)}),F.current?.requestRender();return}V.setCameraMode(ee),ee==="walk"&&(J.current=!1,V.isDollhouseMode()&&V.setDollhouseMode(!1),jt(null)),F.current?.requestRender()}},[m,jt]),he.useEffect(()=>{const V=R.current;V&&(V.setRoofCutListener(W=>jt(W)),V.setDollhouseJumpListener(()=>{J.current=!1,xe.current.onDollhouseChange?.(!1)}))},[jt]),he.useEffect(()=>{R.current?.setWalkModeHeight(_),F.current?.requestRender()},[_]),he.useEffect(()=>{R.current?.setMoveSpeed(g),F.current?.requestRender()},[g]),he.useEffect(()=>{const V=z.current;V&&(V.enabled=v,F.current?.requestRender())},[v]),Lt.jsxs("div",{className:x,style:{position:"relative",width:"100%",height:"100%",...y},children:[Lt.jsx("canvas",{ref:M,style:{width:"100%",height:"100%",display:"block",touchAction:"none"}}),!p&&Lt.jsx(DX,{loading:ms,progress:xa,error:!!Lr})]})});export{tY as DEFAULT_DOLLHOUSE_ROOF_CUT_RATIO,sv as POINT_MODE_DEFAULT_SIZE_PX,dY as PlayCanvasSplatViewer};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.