@margoengine/gltf 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/LICENSE +201 -201
  2. package/NOTICE +4 -4
  3. package/README.md +1754 -1438
  4. package/dist/accessor-CU_1uSZ1.js +1 -0
  5. package/dist/asset-DN3ocEdY.js +4 -0
  6. package/dist/asset-entry.js +1 -1
  7. package/dist/asset.d.ts +76 -0
  8. package/dist/audio.js +1 -1
  9. package/dist/auto.js +1 -1
  10. package/dist/compression-CUOCmjmE.js +1 -0
  11. package/dist/compression.d.ts +6 -0
  12. package/dist/dds.js +1 -1
  13. package/dist/default-materials.d.ts +3 -1
  14. package/dist/default-transmission.d.ts +13 -0
  15. package/dist/extended.js +1 -1
  16. package/dist/group.d.ts +15 -3
  17. package/dist/index.d.ts +11 -0
  18. package/dist/index.js +1 -1
  19. package/dist/{instanced-shader-BebTnbkj.js → instanced-shader-C9ZMazvo.js} +1 -1
  20. package/dist/instancing.js +1 -1
  21. package/dist/lights.js +1 -1
  22. package/dist/material-draw-state-GKiHDb0p.js +1 -0
  23. package/dist/material-draw.js +1 -1
  24. package/dist/meshopt.js +1 -1
  25. package/dist/mipmaps-38NmjDc3.js +21 -0
  26. package/dist/model-C77ATxi1.js +25 -0
  27. package/dist/model-entry.js +1 -1
  28. package/dist/model.d.ts +84 -7
  29. package/dist/native-glass-D85twud0.js +19 -0
  30. package/dist/pack-DdxRO8k6.js +1 -0
  31. package/dist/pbr-instancing.js +1 -1
  32. package/dist/pbr.js +1 -1
  33. package/dist/physics.js +1 -1
  34. package/dist/prepare.js +1 -1
  35. package/dist/progressive-lod.d.ts +13 -0
  36. package/dist/progressive.d.ts +5 -2
  37. package/dist/progressive.js +3 -3
  38. package/dist/quantized.js +1 -1
  39. package/dist/report.js +1 -1
  40. package/dist/scene-data.js +1 -1
  41. package/dist/scene-scope-CZDEkd24.js +2 -2
  42. package/dist/scene.js +3 -3
  43. package/dist/{shader-DPqfUcmp.js → shader-C29RtPAw.js} +43 -39
  44. package/dist/shader.d.ts +24 -0
  45. package/dist/shared/caster.d.ts +159 -152
  46. package/dist/shared/gltf.d.ts +257 -257
  47. package/dist/shared/iridescence.d.ts +2 -2
  48. package/dist/shared/prepared-geometry.d.ts +8 -8
  49. package/dist/soft-mesh.d.ts +39 -1
  50. package/dist/soft-mesh.js +2 -2
  51. package/dist/spec-gloss.js +2 -2
  52. package/dist/splats.js +1 -1
  53. package/dist/src-Btvz5f6i.js +4 -0
  54. package/dist/stream-CrfNNCRd.js +1 -0
  55. package/dist/stream.d.ts +20 -3
  56. package/dist/stroke-width-B2cnYGgn.js +1 -0
  57. package/dist/stroke-width.d.ts +18 -0
  58. package/dist/strokes.d.ts +12 -0
  59. package/dist/strokes.js +1 -0
  60. package/dist/texture-stream-Cu_XpyVO.js +3 -3
  61. package/dist/textured.js +3 -3
  62. package/dist/transmission.d.ts +81 -0
  63. package/dist/transmission.js +66 -0
  64. package/dist/version-B6NE5cJf.js +1 -0
  65. package/dist/vertex-inputs.d.ts +6 -0
  66. package/dist/{unit-light-DvtsuFYP.js → warning-UqjZyyqW.js} +2 -22
  67. package/dist/warning.d.ts +24 -0
  68. package/dist/worker.d.ts +1 -1
  69. package/dist/worker.js +3 -3
  70. package/dist/workers/gltf.js +36 -36
  71. package/dist/workers/progressive.js +1 -1
  72. package/package.json +234 -213
  73. package/dist/accessor-nVsu_f1L.js +0 -1
  74. package/dist/asset-1b8ejkZX.js +0 -4
  75. package/dist/compression-D4IkO5vE.js +0 -1
  76. package/dist/errors-THVaUwlL.js +0 -1
  77. package/dist/material-draw-state-BHeTb1FP.js +0 -1
  78. package/dist/model-iRvuj19h.js +0 -39
  79. package/dist/optimize-7SEzNA23.js +0 -1
  80. package/dist/pack-BVDYuqZe.js +0 -1
  81. package/dist/src-WMRHArDp.js +0 -4
  82. package/dist/stream-C3bKMy1B.js +0 -1
  83. package/dist/version-BmU1nesQ.js +0 -1
@@ -0,0 +1,25 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const je=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import{t as e}from"./node-matrix-R9BipGnp.js";import{f as t}from"./version-B6NE5cJf.js";import{t as n}from"./scene-scope-CZDEkd24.js";import{i as r,t as i}from"./mesh-source-DvU8YvMc.js";import{t as a}from"./mipmaps-38NmjDc3.js";import{a as o,i as s,n as c,r as l,t as u}from"./warning-UqjZyyqW.js";import{a as d,c as f,d as p,f as m,i as h,l as g,m as _,n as v,o as y,p as b,r as x,t as S,u as C}from"./native-glass-D85twud0.js";import{i as w,n as T,t as E}from"./material-draw-state-GKiHDb0p.js";import{i as D,n as O,r as k,t as A}from"./instanced-shader-C9ZMazvo.js";import{t as j}from"./visibility-C_Oqz9Sr.js";import{D as M,E as N,M as P,P as ee,S as F,_ as I,a as te,d as L,g as R,h as z,k as ne,l as re,o as B,p as ie,r as V,s as H,t as ae,v as U,x as oe}from"./asset-DN3ocEdY.js";import{n as W}from"./stroke-width-B2cnYGgn.js";import{C as se,S as ce,_ as le,c as ue,d as de,f as G,g as fe,h as pe,i as me,l as he,m as K,n as ge,p as _e,r as ve,s as ye,t as be,u as xe,v as Se,w as Ce,x as we,y as Te}from"./shader-C29RtPAw.js";import{n as Ee,r as De,t as Oe}from"./texture-coordinates-XFsEMdU6.js";import{i as q,n as ke,r as Ae}from"./pack-DdxRO8k6.js";import{engineRuntime as __margoRuntime,fault as Me,margoError as J,rangeError as Ne,typeError as Pe}from"@margoengine/core/extension";import{invertMatrixStable as Y,multiplyMatrices as Fe}from"@margoengine/math/mat4";import{createKTX2Texture as Ie,getBytesPerRow as Le}from"@margoengine/decoders/texture";var Re=`@group(0) @binding(0) var source:texture_2d<f32>;
5
+ @vertex fn vertex(@builtin(vertex_index) i:u32)->@builtin(position) vec4f {
6
+ let p=array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3));return vec4f(p[i],0,1);
7
+ }
8
+ @fragment fn fragment(@builtin(position) p:vec4f)->@location(0) vec4f {return textureLoad(source,vec2i(p.xy),0);}`,ze=/* @__PURE__ */ new WeakMap,Be=/* @__PURE__ */ new WeakMap;function Ve(e,t){let n=Be.get(e);n||Be.set(e,n={ids:/* @__PURE__ */ new WeakMap,next:0,entries:/* @__PURE__ */ new Map});let r=n,i=t.map(e=>{let t=r.ids.get(e.view);t===void 0&&r.ids.set(e.view,t=r.next++);let n=e.sampler;return[t,e.width,e.height,e.levels,n.magFilter,n.minFilter,n.wrapS,n.wrapT].join(`,`)}).join(`;`),a=e=>{e.users++;let t=!1;return{texture:e.texture,view:e.view,params:e.params,destroy(){t||(t=!0,--e.users===0&&(r.entries.delete(i),e.texture.destroy(),e.params.destroy()))}}},o=r.entries.get(i);if(o)return a(o);let s=Math.max(...t.map(e=>e.width)),c=Math.max(...t.map(e=>e.height)),l=Math.max(...t.map(e=>e.levels)),u=e.createTexture({label:`glTF packed base maps`,size:[s,c,5],mipLevelCount:l,format:`rgba32float`,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT}),d;try{d=e.createBuffer({label:`glTF packed base samplers`,size:160,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let n=/* @__PURE__ */ new Float32Array(40),o=e=>e===33071?0:e===33648?2:1;t.forEach((e,t)=>n.set([e.width,e.height,e.levels,e.sampler.magFilter===9728?0:1,+![9728,9984,9986].includes(e.sampler.minFilter),[9728,9729].includes(e.sampler.minFilter)?2:+![9984,9985].includes(e.sampler.minFilter),o(e.sampler.wrapS),o(e.sampler.wrapT)],t*8)),e.queue.writeBuffer(d,0,n);let s=ze.get(e);s||ze.set(e,s=/* @__PURE__ */ new Map);let c=e.createCommandEncoder();t.forEach((t,n)=>{for(let r=0;r<t.levels;r++){let i=t.view,a=s.get(r);if(!a){let t=e.createShaderModule({code:Re.replace(`textureLoad(source,vec2i(p.xy),0)`,`textureLoad(source,vec2i(p.xy),${r})`)});a=e.createRenderPipeline({layout:`auto`,vertex:{module:t,entryPoint:`vertex`},fragment:{module:t,entryPoint:`fragment`,targets:[{format:`rgba32float`}]}}),s.set(r,a)}let o=e.createBindGroup({layout:a.getBindGroupLayout(0),entries:[{binding:0,resource:i}]}),l=c.beginRenderPass({colorAttachments:[{view:u.createView({dimension:`2d`,baseArrayLayer:n,arrayLayerCount:1,baseMipLevel:r,mipLevelCount:1}),loadOp:`clear`,storeOp:`store`,clearValue:[0,0,0,0]}]});l.setPipeline(a),l.setBindGroup(0,o),l.setViewport(0,0,Math.max(1,t.width>>r),Math.max(1,t.height>>r),0,1),l.draw(3),l.end()}}),e.queue.submit([c.finish()]);let l={texture:u,view:u.createView({dimension:`2d-array`}),params:d,users:0};return r.entries.set(i,l),a(l)}catch(e){throw u.destroy(),d?.destroy(),e}}function He(e){return e?.adapterInfo?.vendor===`margo-webgl2`?`webgl2`:`native`}function Ue(e,t){return He(e)===`webgl2`?e.textureUnits?.(t):void 0}var We=e=>e===`section`?6:16,Ge=/@group\(0\) @binding\((\d+)\) var<uniform> section:Section;/,Ke=/* @__PURE__ */ new Map,qe,Je;function Ye(e){let t=e.shader;if(t!==qe){let e=Ge.exec(t);qe=t,Je=e?Number(e[1]):void 0}if(Je===void 0)return;let n=e.bindings;for(let e=0;e<n.length;e++)if(n[e].binding===Je){let t=n[e].resource;return t&&`buffer`in t?t:void 0}}function Xe(e,t=`i.position`){return e===`section`?`for(var p=0u;p<u32(section.settings.x);p++){if(dot(section.planes[p].xyz,${t})+section.planes[p].w<0){discard;}}`:`{let ${e}Count=u32(${e}.settings.x);var ${e}Behind=0u;for(var p=0u;p<${e}Count;p++){if(dot(${e}.planes[p].xyz,${t})+${e}.planes[p].w<0){${e}Behind++;}}if(${e}Count>0u&&select(${e}Behind>0u,${e}Behind==${e}Count,${e}.settings.y>0.5)){discard;}}`}function Ze(e,t,n=`o.position`){let r=Math.min(8,We(t)),i=/@vertex\s+fn\s+\w+\([\s\S]*?\)->Out\s*\{/.exec(e),a=i?e.indexOf(`return o;`,i.index):-1;if(a<0)throw TypeError(`Hardware clip distances need a vertex stage that returns Out; use clippingPlanes without the feature`);let o=`for(var margoP=0u;margoP<${r}u;margoP++){o.margoClip[margoP]=select(1.0,dot(${t}.planes[margoP].xyz,${n})+${t}.planes[margoP].w,margoP<u32(${t}.settings.x));}`;return`enable clip_distances;
9
+ `+(e.slice(0,a)+o+e.slice(a)).replace(i[0],i[0].replace(`->Out`,`->MargoClipped`)).replace(`var o:Out;`,`var o:MargoClipped;`).replace(/struct Out \{([^}]*)\}/,(e,t)=>`${e}\nstruct MargoClipped {${t.trimEnd().replace(/,$/,``)},@builtin(clip_distances) margoClip:array<f32,${r}>}`)}var X=/\/\/ margo clip distances (\w+)$/m;function Qe(e){let t=X.exec(e);return t?Ze(e,t[1]):e}function $e(e,t,n,r=`section`){let i=`${t}:${n}:${r}:${e}`;if(Ke.has(i))return Ke.get(i);let a=r===`section`?`Section`:`${r}Planes`,o=Xe(r),s=/@fragment\s+fn\s+\w+\(i:Out\b[^{]*\{/g,c=``,l=0;for(;s.exec(e);){let t=s.lastIndex,n=t,i=1;for(;n<e.length&&i;)e[n]===`{`?i++:e[n]===`}`&&i--,n++;let a=e.slice(t,n-1);c+=e.slice(l,t)+(a.includes(`return`)?a.replace(/\breturn\s+([^;]+);/g,(e,t)=>`{let ${r}Result=${t};${o}return ${r}Result;}`):a+o)+`}`,l=s.lastIndex=n}return c=`struct ${a} {planes:array<vec4f,${We(r)}>,settings:vec4f}\n@group(${t}) @binding(${n}) var<uniform> ${r}:${a};\n`+c+e.slice(l),Ke.size>=64&&Ke.clear(),Ke.set(i,c),c}var et=/* @__PURE__ */ new WeakMap,tt=/* @__PURE__ */ new WeakMap,nt=/* @__PURE__ */ new Map;function rt(e,t){let n=nt.get(e);n||(nt.size>=256&&nt.clear(),nt.set(e,n=/* @__PURE__ */ new Map));let r=t.join(),i=n.get(r);if(i)return i;let a=/* @__PURE__ */ new Map;for(let t of e.matchAll(/\bfn\s+(\w+)\s*\(/g)){let n=e.indexOf(`{`,t.index),r=0,i=n;for(;i<e.length;i++)if(e[i]===`{`)r++;else if(e[i]===`}`&&!--r)break;a.set(t[1],e.slice(t.index,i+1))}let o=/* @__PURE__ */ new Set,s=t.filter(e=>a.has(e)),c=``;for(;s.length;){let e=s.pop();if(o.has(e))continue;o.add(e);let t=a.get(e);c+=t+`
10
+ `;for(let[e]of t.matchAll(/\b\w+\b/g))a.has(e)&&!o.has(e)&&s.push(e)}let l=new Set(c.match(/\b\w+\b/g));i=/* @__PURE__ */ new Map;for(let t of e.matchAll(/@group\((\d+)\)\s*@binding\((\d+)\)\s*var(?:<[^>]*>)?\s+(\w+)/g)){let e=+t[1];i.has(e)||i.set(e,/* @__PURE__ */ new Set),l.has(t[3])&&i.get(e).add(+t[2])}return n.set(r,i),i}function it(e,t,n){let r=[n.vertex.entryPoint,n.fragment?.entryPoint].filter(e=>!!e);tt.set(e,rt(t,r))}function at(e,t,n,r){let i=tt.get(t)?.get(n);if(i&&(r=r.filter(e=>i.has(e.binding))),r.length)return e.createBindGroup({layout:t.getBindGroupLayout(n),entries:r});let a=et.get(e);return a||(a=e.createBindGroup({layout:e.createBindGroupLayout({entries:[]}),entries:[]}),et.set(e,a)),a}function ot(e,t){let n=t.position,r=t.up??[0,1,0],i=n[0]-t.target[0],a=n[1]-t.target[1],o=n[2]-t.target[2],s=Math.abs(i),c=Math.abs(a),l=Math.abs(o),u=s>c?s:c,d=u>l?u:l,f;if(s===1/0||c===1/0||l===1/0)f=1/0;else if(s!==s||c!==c||l!==l)f=s+c+l;else if(d===0)f=0;else{let e=s/d*(s/d),t=c/d*(c/d),n=e+t-e-t,r=l/d*(l/d)-n;f=Math.sqrt(e+t+r)*d}i/=f,a/=f,o/=f;let p=r[1]*o-r[2]*a,m=r[2]*i-r[0]*o,h=r[0]*a-r[1]*i,g=Math.abs(p),_=Math.abs(m),v=Math.abs(h),y=g>_?g:_,b=y>v?y:v,x;if(g===1/0||_===1/0||v===1/0)x=1/0;else if(g!==g||_!==_||v!==v)x=g+_+v;else if(b===0)x=0;else{let e=g/b*(g/b),t=_/b*(_/b),n=e+t-e-t,r=v/b*(v/b)-n;x=Math.sqrt(e+t+r)*b}if(!f||!x)throw RangeError(`Invalid camera view; pass distinct eye and target and another up vector`);p/=x,m/=x,h/=x;let S=a*h-o*m,C=o*p-i*h,w=i*m-a*p;return e[0]=p,e[1]=S,e[2]=i,e[3]=0,e[4]=m,e[5]=C,e[6]=a,e[7]=0,e[8]=h,e[9]=w,e[10]=o,e[11]=0,e[12]=-p*n[0]-m*n[1]-h*n[2],e[13]=-S*n[0]-C*n[1]-w*n[2],e[14]=-i*n[0]-a*n[1]-o*n[2],e[15]=1,e}function st(e,t){return e===1?1:e**t}var ct=256,lt=256,ut=16384,dt=class{constructor(e){this.device=e,this.chunks=[],this.dirty=!1,this.draws=0,this.idle=[],this.unit=Math.max(ct,e.limits?.minUniformBufferOffsetAlignment??ct)}allocate(e,t){t||this.draws++;let n=Math.ceil(e*4/this.unit);for(let r of this.chunks){let i=r.free.get(n)?.pop();if(i!==void 0)return new mt(this,r,i,e,n,t);if(r.used+n<=r.units){let i=r.used;return r.used+=n,new mt(this,r,i,e,n,t)}}let r=Math.max(n,Math.min(ut,lt<<Math.min(this.chunks.length,8))),i={buffer:this.device.createBuffer({label:`gltf/pbr uniform arena`,size:r*this.unit,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),cpu:new Float32Array(r*this.unit/4),used:n,live:0,units:r,lo:1/0,hi:0,free:/* @__PURE__ */ new Map};return this.chunks.push(i),new mt(this,i,0,e,n,t)}free(e){let t=e.chunk;if(t.live--,t.live===0)this.chunks.splice(this.chunks.indexOf(t),1),t.buffer.destroy();else{let n=t.free.get(e.units);n||t.free.set(e.units,n=[]),n.push(e.offset)}if(!e.shared&&--this.draws===0)for(let e of this.idle.splice(0))e()}},ft=/* @__PURE__ */ new WeakMap,pt=e=>{let t=ft.get(e);return t||ft.set(e,t=new dt(e)),t},mt=class{constructor(e,t,n,r,i,a){this.arena=e,this.chunk=t,this.offset=n,this.floats=r,this.units=i,this.shared=a,this.frame=0,this.uses=0,this.extras=[],this.gone=!1,t.live++,this.start=n*e.unit/4,this.shadow=t.cpu.subarray(this.start,this.start+r),this.binding={buffer:t.buffer,offset:n*e.unit,size:r*4}}write(e,t){let n=this.arena.device,r=g(n,t),i=this.shadow,a=this.floats,o=this.frame===r&&this.view!==t;for(let t=0;o&&t<a;t++)o=i[t]===e[t];if(this.frame!==r||this.view===t||o){this.frame!==r&&(this.frame=r,this.view=t,this.uses=0);let n=-1,o=-1;for(let t=0;t<a;t++)Object.is(i[t],e[t])||(i[t]=e[t],n<0&&(n=t),o=t);if(n>=0){let e=this.chunk;this.start+n<e.lo&&(e.lo=this.start+n),this.start+o+1>e.hi&&(e.hi=this.start+o+1),this.arena.dirty=!0}return}let s=this.extras[this.uses++]??=n.createBuffer({label:`frame uniform copy`,size:a*4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});return n.queue.writeBuffer(s,0,e),{buffer:s}}get contents(){return this.shadow}get destroyed(){return this.gone}destroy(){if(!this.gone){this.gone=!0;for(let e of this.extras)m(this.arena.device,e);this.extras=[],this.arena.free(this)}}};function ht(e,t,n=!1){return pt(e).allocate(t,n)}function gt(e,t){pt(e).idle.push(t)}function _t(e){let t=ft.get(e);if(t?.dirty){for(let n of t.chunks)n.lo<n.hi&&(e.queue.writeBuffer(n.buffer,n.lo*4,n.cpu,n.lo,n.hi-n.lo),n.lo=1/0,n.hi=0);t.dirty=!1}}function vt(e,t,n,r,i,a,o,s,c){return e+t*4+n*16+r*32+i*64+a*128+o*256+s*512+c*1024}var yt=/* @__PURE__ */ new WeakMap;function bt(e){let t=yt.get(e);return t||yt.set(e,t={codes:/* @__PURE__ */ new Map,codeCount:0,pipelines:/* @__PURE__ */ new Map,derivations:/* @__PURE__ */ new WeakMap,groups:/* @__PURE__ */ new Map}),t}function xt(e,t){let n=wt(t.pipeline)+`:`+t.floatCount+`:`+ +t.replacesTextures,r=t.effect?.entries;if(r)for(let e=0;e<r.length;e++){let t=r[e],i=t.resource;n+=`,`+t.binding+`=`+(`buffer`in i?wt(i.buffer)+`@`+(i.offset??0)+`+`+(i.size??``):wt(i))}let i=e.groups.get(n);return i||(e.groups.size>=4096&&e.groups.clear(),e.groups.set(n,i={})),i}var St=/* @__PURE__ */ new WeakMap,Ct=1;function wt(e){if(!e)return 0;let t=St.get(e);return t===void 0&&St.set(e,t=Ct++),t}function Tt(e,t){if(e.mode!==t.mode||e.depthCompare!==t.depthCompare||e.format!==t.format||e.samples!==t.samples||e.depthFormat!==t.depthFormat||e.section!==t.section||e.oit!==t.oit||e.hook!==t.hook||e.hooks!==t.hooks||e.glass!==t.glass||e.lighting.length!==t.lighting.length)return!1;for(let n=0;n<e.lighting.length;n++)if(e.lighting[n]!==t.lighting[n])return!1;return!0}function Et(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}var Dt=/* @__PURE__ */ new WeakSet,Ot=/* @__PURE__ */ new WeakMap;function kt(e,t,n,r){let i=Ot.get(e);if(!i){let t=i=[];Ot.set(e,t),gt(e,()=>{Ot.get(e)===t&&Ot.delete(e);for(let n of t)m(e,n.slot);t.length=0})}let a=g(e,n),o,s;for(let e=0;e<i.length;e++){let c=i[e];if(c.view===n&&c.owner===r){o=c;break}if(c.frame!==a)s??=c;else if(!o){let e=c.slot.contents,n=!0;for(let r=0;n&&r<48;r++)n=e[r]===t[r];n&&(o=c)}}return o&&(o.view!==n||o.owner!==r)||(o||(o=s??{slot:ht(e,48,!0),view:n,owner:r,frame:a},s||i.push(o),o.view=n,o.owner=r),o.frame=a,o.slot.write(t,n)),o.slot.binding}var At=class{constructor(e,t=!1){this.mirrored=e,this.rows=t,this.layout=D}shader(e){return A(e)}},jt=[new At(!1),new At(!0),new At(!1,!0),new At(!0,!0)],Mt=(e,t=!1)=>jt[+e+2*t],Nt=class{constructor(){this.data=/* @__PURE__ */ new Float32Array,this.bindings=[],this.floats=0,this.perBinding=0,this.stride=0,this.owners=[],this.versions=[]}write(e,t,n,r,i,a){let o=t.length,s=Math.ceil(o/a);if((i!==this.floats||a!==this.perBinding)&&(this.floats=i,this.perBinding=a,this.stride=Math.ceil(a*i/64)*64,this.data=/* @__PURE__ */ new Float32Array,this.owners.length=this.versions.length=0),this.data.length<s*this.stride){let t=Math.max(s,Math.ceil(this.data.length/this.stride*1.5)),n=new Float32Array(t*this.stride);n.set(this.data),this.data=n,this.buffer&&m(e,this.buffer),this.buffer=void 0,this.owners.length=this.versions.length=0}if(!this.buffer){this.buffer=e.createBuffer({label:`gltf/pbr draw batch rows`,size:this.data.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),this.bindings=[];for(let e=0;e<this.data.length/this.stride;e++)this.bindings.push({buffer:this.buffer,offset:e*this.stride*4,size:a*i*4})}let c=this.data,l=c.length,u=0;for(let e=0;e<o;e++){let o=n[e],s=r[e];if(this.owners[e]===o&&this.versions[e]===s)continue;let d=t[e],f=Math.floor(e/a)*this.stride+e%a*i,p=this.owners[e]===void 0;for(let e=0;e<i;e++){let t=e>=16&&e<48?+((e-(e<32?16:32))%5==0):e===97?1:d[e];c[f+e]!==t&&(c[f+e]=t,p=!0)}this.owners[e]=o,this.versions[e]=s,p&&(f<l&&(l=f),f+i>u&&(u=f+i))}l<u&&e.queue.writeBuffer(this.buffer,l*4,c,l,u-l)}destroy(e){this.buffer&&m(e,this.buffer),this.buffer=void 0,this.bindings=[],this.owners.length=this.versions.length=0}},Pt=class{constructor(){this.data=/* @__PURE__ */ new Float32Array,this.uploaded=0}holds(e,t){if(e.length>this.uploaded)return!1;let n=this.data;for(let r=0;r<e.length;r++){for(let t=0;t<16;t++)if(n[r*24+t]!==Math.fround(e[r][t]))return!1;for(let e=0;e<4;e++)if(n[r*24+16+e]!==(t?Math.fround(t[r][e]):1))return!1}return!0}write(e,t,n){let r=t.length;if(this.data.length<r*24){let t=Math.max(r,Math.ceil(this.data.length/24*1.5),16),n=new Float32Array(t*24);n.set(this.data);for(let e=this.data.length/24;e<t;e++){let t=e*24;n[t+16]=n[t+17]=n[t+18]=n[t+19]=1,n[t+20]=n[t+21]=1}this.data=n,this.buffer&&m(e,this.buffer),this.buffer=void 0,this.uploaded=0}let i=this.data,a=r,o=0;for(let e=0;e<r;e++){let r=t[e],s=e*24,c=e>=this.uploaded;for(let e=0;e<16;e++)i[s+e]!==r[e]&&(i[s+e]=r[e],c=!0);let l=n?.[e];for(let e=0;e<4;e++){let t=l?Math.fround(l[e]):1;i[s+16+e]!==t&&(i[s+16+e]=t,c=!0)}c&&(e<a&&(a=e),o=e+1)}return this.buffer||=e.createBuffer({label:`gltf/pbr draw batch`,size:i.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),a<o&&e.queue.writeBuffer(this.buffer,a*96,i,a*24,(o-a)*24),r>this.uploaded&&(this.uploaded=r),this.buffer}destroy(e){this.buffer&&m(e,this.buffer),this.buffer=void 0,this.uploaded=0}},Ft=[0,1,2,3,4],It=/\n {2}var t=i\.tangent[^]*?\n {2}s\.n=normalize\(t\*sampledNormal[^;]*;/,Lt=/(?:let|const) sampledNormal=vec4f\(0\.5,0\.5,1,1\)\.xyz\*2-1;/,Rt=/\nfn uv\(i:Out, ?\w+:f32\)->vec2f \{[^\n]*\}(?=\n)/;function zt(e){let t=e.indexOf(`fn surface(`),n=e.slice(t),r=It.exec(n);if(t<0||!r||!Lt.test(e))return e;let i=n.slice(r.index+r[0].length),a=i.indexOf(`
11
+ return s;`);return a<0||/\b(t|b|dp1|dp2|duv1|duv2)\b/.test(i.slice(0,a))?e:e.slice(0,t)+n.replace(It,`
12
+ s.n=normalize(n);`)}function Bt(e){let t=e.indexOf(`@vertex fn vertex(`);return[t,e.indexOf(`return o;
13
+ }`,t)]}function Vt(e,t){let[n,r]=Bt(e),i=(e.slice(0,n)+e.slice(r)).replace(Rt,``),a=e.slice(n,r).replace(RegExp(`\\s*o\\.${t}=[^;]*;`),``);return RegExp(`\\.${t}\\b|\\b${t}\\(i,`).test(i+a)?e:(e.slice(0,n).replace(RegExp(`(struct Out \\{[^}]*?),?\\s*@location\\(\\d+\\) ${t}:vec4f`),`$1`)+a+e.slice(r)).replace(t===`uv`?Rt:``,``)}function Ht(e){return e.replace(/\blet (\w+)=(vec4f\((?:1|0\.5,0\.5,1,1|1,0\.5,1,1)\)(?:\.xyz\*2-1)?);/g,`const $1=$2;`)}var Ut={arrayStride:16,attributes:[{shaderLocation:11,offset:0,format:`float32x4`}]};function Wt(e){return/\bo\.uv=/.test(e)?e.replaceAll(/select\(i\.uv\.xy,i\.uv\.zw,([^;)]*?)>0\.5\)/g,`margoUVSet(i,$1)`).replace(/struct Input \{([^}]*?)\s*\}/,`struct Input {$1, @location(11) uvs:vec4f}`).replace(/(struct Out \{[^}]*?)\n\}/,`$1, @location(15) uvs:vec4f
14
+ }`).replace(/\bo\.uv=([^;]*);/,(e,t)=>`${e} o.uvs=${t.replace(/\bi\.uv\b/g,`i.uvs`)};`)+`
15
+ fn margoUVSet(i:Out,k:f32)->vec2f {return select(select(i.uv.xy,i.uv.zw,k>0.5),select(i.uvs.xy,i.uvs.zw,k>2.5),k>1.5);}
16
+ `:e}function Gt(e,t=0,n=e.length/20-t){for(let r=t*20+16,i=(t+n)*20;r<i;r+=20)if(e[r]!==1||e[r+1]!==1||e[r+2]!==1||e[r+3]!==1)return!1;return!0}function Kt(e,t=0,n=e.length/20-t){for(let r=t*20+19,i=(t+n)*20;r<i;r+=20)if(e[r]!==1)return!1;return!0}function qt(e){let[t,n]=Bt(e);if(t<0||n<0)return e;let r=e.slice(t,n),i=e.slice(0,t)+e.slice(n);if(r.match(/\bo\.color=[^;]*;/g)?.length!==1||e.includes(`fn margoClearAlpha(`)||[...i.matchAll(/(\w+)\s*:\s*Out\b/g)].some(e=>e[1]!==`i`)||[...i.matchAll(/\bi\s*:\s*(\w+)/g)].some(e=>e[1]!==`Out`)||/\b(let|var|const)\s+i\b/.test(i))return e;let a=r.replace(/\bo\.color=([^;]*);/,`o.color=margoClearAlpha($1);`),o=e=>e.replace(/\bi\.color\b/g,`margoClearAlpha(i.color)`);return o(e.slice(0,t))+a+o(e.slice(n))+`
17
+ fn margoClearAlpha(c:vec4f)->vec4f {return vec4f(c.rgb,1.0-c.a);}
18
+ `}function Jt(e){return{arrayStride:80,attributes:e.locations.map(t=>({shaderLocation:t,offset:t*16,format:e.narrow.includes(t)?`float32x3`:`float32x4`}))}}var Yt=/* @__PURE__ */ new WeakMap;function Xt(e,t){let n=/\bstruct Instance \{([^}]*)\}/.exec(e);if(!n)return t;let r=new Set([...n[1].matchAll(/@location\((\d+)\)/g)].map(e=>+e[1])),i=[...t.attributes].filter(e=>r.has(e.shaderLocation));if(i.length===[...t.attributes].length)return t;let a=i.map(e=>e.shaderLocation).join(),o=Yt.get(t);o||Yt.set(t,o=/* @__PURE__ */ new Map);let s=o.get(a);return s||o.set(a,s={...t,attributes:i}),s}function Zt(e,t=!1){let n={code:e,locations:Ft,narrow:[]};if(!/\bstruct Input \{/.test(e)||e.split(`:Input`).length!==2||Math.min(...Bt(e))<0)return n;let r=Vt(Vt(zt(e),`tangent`),`uv`),[i,a]=Bt(r),o=r.indexOf(`)->Out {`,i),s=r.slice(o,a);if(/\bi\b(?!\.)/.test(s))return n;t&&/\bi\.color\b/.test(s)&&(s=s.replace(/\bi\.color\b/g,`vec4f(1)`),r=r.slice(0,o)+s+r.slice(a)),s.includes(`k.uvt`)||(r=r.replace(`, @location(10) uvt:vec4f}`,`}`));let c=/struct Input \{([^}]*)\}/.exec(r),l=[...c[1].matchAll(/@location\((\d+)\) (\w+):vec4f/g)],u=l.filter(e=>s.includes(`i.`+e[2]));return l.length===5?{code:u.length<5?r.replace(c[1],[...u,...c[1].matchAll(/@builtin\(\w+\) \w+:\w+/g)].map(e=>e[0]).join(`, `)):r,locations:u.map(e=>+e[1]),narrow:u.filter(([,,e])=>s.match(RegExp(`\\bi\\.${e}\\b(\\.\\w+)?`,`g`)).every(e=>e.endsWith(`.xyz`))).map(e=>+e[1])}:n}var Qt=Symbol.for(`@margoengine/internal/shadowPrimitivesInto`);function $t(e){return(e.extension??e.material.extension)?.afterOpaque===!0}function en(e){let{vertices:t,indices:n}=e,r=t?.length/20;if(!(t instanceof Float32Array)||!(n instanceof Uint32Array)||!Number.isInteger(r)||r<3||r>1e6||!n.length||n.length%3)throw RangeError(`Invalid prepared PBR geometry; run prepareAsset again`);for(let e=0;e<n.length;e++)if(n[e]>=r)throw RangeError(`Invalid prepared PBR geometry; run prepareAsset again`);tn(t,0,r,e.interpolatedDirections===!0)}function tn(e,t,n,r=!1){for(let r=t*20;r<n*20;r++)if(!Number.isFinite(e[r]))throw RangeError(`Non-finite prepared PBR vertex; run prepareAsset again`);for(let i=t*20;i<n*20;i+=20){let t=e[i+11];if(e[i+3]!==1||e[i+7]!==0||(r?Math.hypot(e[i+4],e[i+5],e[i+6])>1.001:Math.abs(Math.hypot(e[i+4],e[i+5],e[i+6])-1)>.001)||t!==0&&t!==-1&&t!==1)throw RangeError(`Invalid prepared PBR normal/tangent; run prepareAsset again`);if(e[i+11]&&(r?Math.hypot(e[i+8],e[i+9],e[i+10])>1.001:Math.abs(Math.hypot(e[i+8],e[i+9],e[i+10])-1)>.001))throw RangeError(`Invalid prepared PBR tangent; run prepareAsset again`);for(let t=16;t<20;t++)if(e[i+t]<0||e[i+t]>1)throw RangeError(`Invalid prepared PBR color; run prepareAsset again`)}}var nn=(e,t)=>!!e.materials?.some(e=>!!e?.extensions&&typeof e.extensions==`object`&&t in e.extensions);async function rn(e,t){return t.transmission!==void 0||!t.materials||!nn(e,`KHR_materials_transmission`)?t:{...t,transmission:(await import(`./transmission.js`)).screenTransmission}}async function an(e){let t=await rn(e.doc,e.hooks);t!==e.hooks&&(e.hooks=t)}function on(e,t,n){return e.value=t,e.device=typeof t==`function`?void 0:n,e.made=void 0,e.told=!1,e}var sn=(e,t,n,r)=>on({name:t,setter:n},e,r);function cn(e,t,n){let{value:r}=e;if(typeof r==`function`)return e.device!==t&&(e.made=r(e.device=t)),e.made;if(r!=null){if(e.device??=t,e.device===t)return r;e.told||(e.told=!0,n?.onError(Me(`state`,`${e.name} lost with the device; pass a function or call ${e.setter}`,`borrowed-lost`)))}}var ln=/* @__PURE__ */ new WeakMap,un=/* @__PURE__ */ new WeakMap;function dn(e){let t=un.get(e);if(!t){let n=e.createTexture({size:[1,1],format:`rgba8unorm`,usage:6});e.queue.writeTexture({texture:n},new Uint8Array([255,255,255,255]),{bytesPerRow:4},[1,1]),t={view:n.createView(),sampler:e.createSampler({magFilter:`linear`,minFilter:`linear`})},un.set(e,t)}return t}function fn(e,t,n,r){let i=ln.get(t);if(!i||i.from!==t.view||i.samplerFrom!==t.sampler){let e=`give the material a new MaterialExtension`;i={view:sn(t.view,`MaterialExtension textures[${n}].view`,e),sampler:t.sampler?sn(t.sampler,`MaterialExtension textures[${n}].sampler`,e):void 0,from:t.view,samplerFrom:t.sampler},ln.set(t,i)}let a=cn(i.view,e,r),o=i.sampler?cn(i.sampler,e,r):void 0;return{view:a??dn(e).view,sampler:i.sampler?o??dn(e).sampler:void 0}}function pn(e){return(e?.textures??[]).every(e=>typeof e.view==`function`&&(e.sampler===void 0||typeof e.sampler==`function`))}function mn(e){if(e!==void 0&&typeof e!=`string`)throw TypeError(`Invalid material extension WGSL; pass WGSL source that follows the documented hook`);if(typeof e==`string`&&/@\s*(?:group|binding)\b/.test(e))throw TypeError(`Material extension declarations cannot declare @group or @binding; use factors and textures`)}function hn(e,t,n,r){if(!t||typeof t!=`object`||t.wgsl!==void 0&&typeof t.wgsl!=`string`||t.direct!==void 0&&typeof t.direct!=`string`||t.coat!==void 0&&![`keep`,`direct`,`normal`,`roughness`].every(e=>typeof t.coat?.[e]==`string`)||t.ambient!==void 0&&typeof t.ambient!=`string`||t.output!==void 0&&typeof t.output!=`string`||t.transmission!==void 0&&typeof t.transmission!=`string`||t.ior!==void 0&&typeof t.ior!=`string`||t.lighting!==void 0&&typeof t.lighting!=`boolean`||t.declarations!==void 0&&typeof t.declarations!=`string`)throw TypeError(`Invalid material extension WGSL; pass WGSL source that follows the documented hook`);if(t.afterOpaque!==void 0&&typeof t.afterOpaque!=`boolean`)throw TypeError(`Material extension afterOpaque must be a boolean; pass true or false`);mn(t.declarations);let{factors:i,textures:a=[]}=t;if(i!==void 0&&(!(i instanceof Float32Array)||!i.length||i.length%4||i.some(e=>!Number.isFinite(e))))throw TypeError(`Material extension factors require finite vec4 values`);let o=i?.byteLength??0;if(o>Math.min(e.limits.maxUniformBufferBindingSize??1/0,e.limits.maxBufferSize))throw RangeError(`Material extension factors exceed device limit; load a smaller model, or reduce its textures and meshes`);if(!Array.isArray(a)||a.some(e=>!e?.view))throw TypeError(`Invalid material extension textures; pass the documented texture bindings`);if(a.length+5>(e.limits.maxSampledTexturesPerShaderStage??1/0)||a.filter(e=>e.sampler).length+5>(e.limits.maxSamplersPerShaderStage??1/0))throw RangeError(`Material extension textures exceed device binding limits; load a smaller model, or reduce its textures and meshes`);if((o||a.length)&&(e.limits.maxBindGroups??4)<4)throw RangeError(`Material extensions require bind group 3`);let s=n??{bytes:0,entries:[],groups:/* @__PURE__ */ new Map};if(o!==s.bytes){let t=o?e.createBuffer({size:o,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}):void 0;m(e,s.uniform),s.uniform=t,s.bytes=o,s.groups.clear()}try{i&&e.queue.writeBuffer(s.uniform,0,i)}catch(e){throw n||s.uniform?.destroy(),e}return s.entries=s.uniform?[{binding:0,resource:{buffer:s.uniform}}]:[],a.forEach((t,n)=>{let i=fn(e,t,n,r);s.entries.push({binding:1+n*2,resource:i.view}),i.sampler&&s.entries.push({binding:2+n*2,resource:i.sampler})}),s}function gn(e){let t=e.factors?`_ = materialFactors;
19
+ `:``;return(e.textures??[]).forEach((e,n)=>{t+=`_ = materialTexture${n};\n`,e.sampler&&(t+=`_ = materialSampler${n};\n`)}),t}function _n(e,t){return e.replaceAll(`let s=surface(i,front);`,()=>`var s=surface(i,front);\n${gn(t)}${t.wgsl??``}\n`+(t.transmission?`s.tr=clamp(${t.transmission},0.0,1.0);\n`:``)+(t.coat?`s.cn=${t.coat.normal};s.cr=${t.coat.roughness};\n`:``)+(t.ior?`{let materialIorRatio=select((max(${t.ior},1.0)-1.0)/(max(${t.ior},1.0)+1.0),1.0,${t.ior}==0.0);s.f0=vec3f(materialIorRatio*materialIorRatio);}\n`:``))}function vn(e){if(e.includes(` f0:vec3f`))return e;let t=`mix(vec3f(0.04),s.base.rgb,s.metal)`,n=/struct Surface \{([^}]*)\}/;if(!n.test(e)||!e.includes(t))throw J(`unsupported`,`PBR shader IOR target missing: the Surface struct or its 0.04 F0; use matching @margoengine/gltf/pbr and materials versions`);return e.replace(n,`struct Surface {$1, f0:vec3f}`).replaceAll(t,`mix(s.f0,s.base.rgb,s.metal)`).replaceAll(`let dielectric=vec3f(0.04);`,`let dielectric=s.f0;`)}function yn(e){let t=/struct Surface \{([^}]*)\}/;if(!t.test(e))throw J(`unsupported`,`PBR shader coat target missing: the Surface struct; use matching @margoengine/gltf/pbr and materials versions`);return e.includes(` cn:vec3f`)||(e=e.replace(t,`struct Surface {$1, cn:vec3f, cr:f32}`)),e.includes(`fn margoCoatAmbient(`)||(e+=`
20
+ fn margoCoatAmbient(s:Surface,v:vec3f)->vec3f {return 0.5*mix(vec3f(0.35,0.3,0.25),vec3f(1),clamp(s.cn.y*0.5+0.5,0.0,1.0))*f.radiance.w*s.occlusion;}
21
+ `),e.includes(`var<private> margoDirectVisible:vec3f=vec3f(1);`)?e.replace(/fn margoLit\([^}]*\}/,`fn margoLit(s:Surface,l:vec3f,direct:vec3f)->vec3f {return vec3f(1);}`):`${se}\n${e}`}function bn(e,t){let n=e?.coat?.keep;return n?`(${t})*(${n})+(1.0-(${n}))*margoCoatAmbient(s,v)`:t}function xn(e,t){mn(t.declarations);let n=`// Material extension: group 3
22
+ `;t.factors&&(n+=`@group(3) @binding(0) var<uniform> materialFactors:array<vec4f,${t.factors.length/4}>;\n`),(t.textures??[]).forEach((e,t)=>{n+=`@group(3) @binding(${1+t*2}) var materialTexture${t}:texture_2d<f32>;\n`,e.sampler&&(n+=`@group(3) @binding(${2+t*2}) var materialSampler${t}:sampler;\n`)});let r=t.transmission?ce(e):e;return t.ior&&(r=vn(r)),t.coat&&(r=yn(r)),t.direct&&(r=r.replace(`let direct=`,`var direct=`).replace(`var color=`,()=>`${t.direct}\n var color=`)),t.output&&(r=r.replace(` return vec4f(color,select(1.0,s.base.a,f.settings.x>1.5));`,()=>` ${t.output}\n return vec4f(color,select(1.0,s.base.a,f.settings.x>1.5));`)),r=_n(r,t),n+(t.declarations??``)+`
23
+ `+r}function Sn(e,t){let{ambient:n,coat:r}=t;if(!n&&!r)return e;let i=(t,n)=>{let r=e.indexOf(`@fragment fn `+t+`(`);if(r<0)return;let i=e.indexOf(`@fragment`,r+1),a=i<0?e.length:i;e=e.slice(0,r)+n(e.slice(r,a))+e.slice(a)};return n&&(i(`fragment`,e=>e.replace(`var color=`,()=>`var materialAmbient=ambient(s);\n${n}\n var color=`).replace(`ambient(s)+s.emissive`,`materialAmbient+s.emissive`)),i(`ambientFragment`,e=>e.replace(`return vec4f(ambient(s),`,()=>`var materialAmbient=ambient(s);\n${n}\n return vec4f(materialAmbient,`))),r&&(i(`fragment`,e=>e.replace(/var color=[^;]*\+s\.emissive[^;]*;/,e=>`${e}\n color=${bn(t,`color`)}+(${r.direct})*margoDirectVisible;`)),i(`ambientFragment`,e=>e.replace(/return vec4f\((materialAmbient|ambient\(s\)),/,(e,n)=>`let v=normalize(f.eye.xyz-i.position);\n return vec4f(${bn(t,n)},`))),e}function Cn(e,t,n,r,i){let{entries:a}=r;if(!a.length)return;let o=r.groups.get(n);(!o||a.length!==o.entries.length||a.some((e,t)=>{let n=o.entries[t].resource,r=e.resource;return e.binding!==o.entries[t].binding||!(r===n||`buffer`in r&&`buffer`in n&&r.buffer===n.buffer)}))&&(o={entries:a,group:e.createBindGroup({layout:n.getBindGroupLayout(3),entries:a}),gap:i?void 0:e.createBindGroup({layout:n.getBindGroupLayout(2),entries:[]})},r.groups.set(n,o)),i||(o.gap??=e.createBindGroup({layout:n.getBindGroupLayout(2),entries:[]}),t.setBindGroup(2,o.gap)),t.setBindGroup(3,o.group)}function wn(e,t,n,r,i){let a=!1,o,s={prepare(n){if(a)throw J(`disposed`,`PBR device renderer is disposed; create a new one`);if(n.device!==e)throw J(`attached`,`PBR renderer belongs to another GPU device; create one per device`);t(n)},draw(t,r,i,o){if(a)throw J(`disposed`,`PBR device renderer is disposed; create a new one`);if(t.device!==e)throw J(`attached`,`PBR renderer belongs to another GPU device; create one per device`);return n(t,r,i,o)},dispose(){a||(a=!0,o?.(),o=void 0,r())}};return o=i(()=>s.dispose()),s}var Tn=/* @__PURE__ */ new Map;function En(e){let t=Tn.get(e);if(t)return t;let n=e.includes(`o.mirror=margoS;`)?e.replaceAll(`let facing=front==(f.coordsB.y>0);`,`let facing=front==(i.mirror>0);`):e,r=0,i=n.replace(/if\((margoFaceTest&&)?!facing&&f\.settings\.z<0\.5\)/g,(e,t)=>(r++,`if(${t??``}facing)`));if(r!==1)throw J(`failed`,`Back-side material requires one PBR surface face guard; use the default PBR shader or side: "front"`);let a=n.match(/let facing=(front==[^;]+);/)?.[1];if(!a)throw J(`failed`,`Back-side material requires the PBR logical facing expression; use the default PBR shader or side: "front"`);return i=i.replace(`@fragment fn margoTint(i:Out)->@location(0) vec4f {return margoTintShare(i,vec3f(f.coordsB.zw,f.ext.z));}`,`@fragment fn margoTint(i:Out,@builtin(front_facing) front:bool)->@location(0) vec4f {if(${a}){discard;}return margoTintShare(i,vec3f(f.coordsB.zw,f.ext.z));}`),Tn.size>=64&&Tn.delete(Tn.keys().next().value),Tn.set(e,i),i}var Dn=[`never`,`less`,`equal`,`less-equal`,`greater`,`not-equal`,`greater-equal`,`always`],On=[`keep`,`zero`,`replace`,`invert`,`increment-clamp`,`decrement-clamp`,`increment-wrap`,`decrement-wrap`],kn=[`stencilFront`,`stencilBack`,`stencilReadMask`,`stencilWriteMask`,`stencilReference`],An=/* @__PURE__ */ new WeakMap;function jn(e,t){if(!(t&&kn.some(e=>t[e]!==void 0))&&!An.get(e))return;let n=t?.stencilReference??0;e.setStencilReference?.(n),An.set(e,n)}function Mn(e){let t=e?.stencilFront,n=e?.stencilBack;return!t&&!n?!1:(t?.compare??`always`)!==(n?.compare??`always`)||(t?.failOp??`keep`)!==(n?.failOp??`keep`)||(t?.depthFailOp??`keep`)!==(n?.depthFailOp??`keep`)||(t?.passOp??`keep`)!==(n?.passOp??`keep`)}function Nn(e){return`var<private> margoCoverage:f32=1.0;
24
+ `+e.replace(/if\((?:margoAlphaTest&&)?f\.settings\.x>0\.5&&f\.settings\.x<1\.5&&s\.base\.a<f\.settings\.y\)\{discard;\}/g,`margoCoverage=clamp((s.base.a-f.settings.y)/max(fwidth(s.base.a),0.0001)+0.5,0.0,1.0);`).replaceAll(`select(1.0,s.base.a,f.settings.x>1.5)`,`margoCoverage`)}function Pn(e,t){if(e.depthBiasMode!==void 0&&![`native`,`away`].includes(e.depthBiasMode))throw TypeError(`PBR renderState depthBiasMode is invalid; set it to native or away`);if(e.depthBias!==void 0&&typeof e.depthBias!=`number`)throw TypeError(`PBR renderState depthBias must be a number; set a signed 32-bit integer`);if(e.depthBias!==void 0&&(!Number.isInteger(e.depthBias)||e.depthBias<-2147483648||e.depthBias>2147483647))throw RangeError(`PBR renderState depthBias must be a signed 32-bit integer; set an integer from -2147483648 through 2147483647`);for(let t of[`depthBiasSlopeScale`,`depthBiasClamp`]){let n=e[t];if(n!==void 0&&typeof n!=`number`)throw TypeError(`PBR renderState `+t+` must be a number; set a finite float32 value`);if(n!==void 0&&!Number.isFinite(Math.fround(n)))throw RangeError(`PBR renderState `+t+` is not finite as float32; set a finite number representable as float32`)}for(let t of[`stencilReadMask`,`stencilWriteMask`,`stencilReference`]){let n=e[t];if(n!==void 0&&typeof n!=`number`)throw TypeError(`PBR renderState `+t+` must be a number; set an unsigned 32-bit integer`);if(n!==void 0&&(!Number.isInteger(n)||n<0||n>4294967295))throw RangeError(`PBR renderState `+t+` must be an unsigned 32-bit integer; set an integer from 0 through 4294967295`)}for(let t of[`stencilFront`,`stencilBack`]){let n=e[t];if(n!==void 0){if(!n||typeof n!=`object`||Array.isArray(n)||Object.getPrototypeOf(n)!==Object.prototype&&Object.getPrototypeOf(n)!==null)throw TypeError(`PBR renderState `+t+` must be a stencil face state; pass {} or an object with compare, failOp, depthFailOp and passOp fields`);if(n.compare!==void 0&&!Dn.includes(n.compare))throw TypeError(`PBR renderState `+t+`.compare is invalid; set one of `+Dn.join(`, `));for(let e of[`failOp`,`depthFailOp`,`passOp`])if(n[e]!==void 0&&!On.includes(n[e]))throw TypeError(`PBR renderState `+t+`.`+e+` is invalid; set one of `+On.join(`, `))}}if(e.transmissionBlend!==void 0&&![`auto`,`two-draw`,`dual-source`].includes(e.transmissionBlend))throw TypeError(`PBR renderState transmissionBlend is invalid; set 'auto', 'two-draw' or 'dual-source'`);if(e.alphaToCoverage!==void 0&&typeof e.alphaToCoverage!=`boolean`)throw TypeError(`PBR renderState alphaToCoverage must be a boolean; set true or false`);if(e.colorWrite!==void 0&&typeof e.colorWrite!=`boolean`)throw TypeError(`PBR renderState colorWrite must be a boolean; set true or false`);if(kn.some(t=>e[t]!==void 0)&&!t.includes(`stencil`))throw TypeError(`PBR stencil state requires a target format with a stencil aspect; render into depth24plus-stencil8 or depth32float-stencil8, or remove the stencil fields (received `+t+`)`)}function Fn(e){return e?JSON.stringify({...e,stencilReference:void 0}):``}function In(e,t,n){if(!e)return{};let r=e.depthBiasMode===`away`&&!n?-1:1,i=t&&e.depthBias!==void 0?e.depthBias*r:void 0;if(i!==void 0&&(i<-2147483648||i>2147483647))throw RangeError(`Converted PBR renderState depthBias must be a signed 32-bit integer; reduce its magnitude or use native mode for a literal WebGPU bias`);let a={};return i!==void 0&&(a.depthBias=i),t&&e.depthBiasSlopeScale!==void 0&&(a.depthBiasSlopeScale=e.depthBiasSlopeScale*r),t&&e.depthBiasClamp!==void 0&&(a.depthBiasClamp=e.depthBiasClamp*r),e.stencilFront!==void 0&&(a.stencilFront=e.stencilFront),e.stencilBack!==void 0&&(a.stencilBack=e.stencilBack),e.stencilReadMask!==void 0&&(a.stencilReadMask=e.stencilReadMask),e.stencilWriteMask!==void 0&&(a.stencilWriteMask=e.stencilWriteMask),a}var Ln=20,Rn=/* @__PURE__ */ new WeakMap;function zn(e,t){for(let n=0;n<e.length;n++)if(!Object.is(e[n],t[n]))return!1;return!0}function Bn(e,t){return Rn.get(e[0].vertices)?.find(n=>n.parts.length===e.length*2&&e.every((e,r)=>n.parts[2*r]===e.vertices&&n.parts[2*r+1]===e.indices&&zn(n.stamps[r],t[r])))}function Vn(e){return e[0]*(e[5]*e[10]-e[6]*e[9])-e[4]*(e[1]*e[10]-e[2]*e[9])+e[8]*(e[1]*e[6]-e[2]*e[5])}function Hn(e){let t=e.material;return e.topology||e.instances||e.deformed||e.part||t.extended?.bump||e.uvs||$t(e)||e.definition.targets?.length||e.definition.attributes?.JOINTS_0!==void 0||t.settings[0]===2||t.tint&&!t.extension?.replacesPhysical||e.indices.length<3||e.indices.length%3||e.vertices.length<60?!1:e.vertices.length%Ln===0}function Un(e,t,n,r,i,a){let o=e[0],s=e[1],c=e[2];t[n]=r[0]*o+r[4]*s+r[8]*c+r[12],t[n+1]=r[1]*o+r[5]*s+r[9]*c+r[13],t[n+2]=r[2]*o+r[6]*s+r[10]*c+r[14],t[n+3]=e[3];let l=e[4],u=e[5],d=e[6];t[n+4]=i[0]*l+i[1]*u+i[2]*d,t[n+5]=i[4]*l+i[5]*u+i[6]*d,t[n+6]=i[8]*l+i[9]*u+i[10]*d,t[n+7]=e[7];let f=e[8],p=e[9],m=e[10];t[n+8]=r[0]*f+r[4]*p+r[8]*m,t[n+9]=r[1]*f+r[5]*p+r[9]*m,t[n+10]=r[2]*f+r[6]*p+r[10]*m,t[n+11]=e[11]*(a?-1:1),t.set(e.subarray(12,20),n+12)}function Wn(e,t,n,r){return{node:e,nodeIndex:-1,vertices:n,indices:r,definition:{attributes:{POSITION:0},mode:4},material:t,weights:/* @__PURE__ */ new Float32Array,targetNames:[]}}function Gn(e,t,n){return e.map(e=>{let r=n(),i=e.parts.map(e=>({...e,primitive:t(e.primitive)})),a=i[0].primitive.material,{vertices:o,indices:s}=e.primitive;return{node:r,material:a,primitive:Wn(r,a,o,s),parts:i}})}function Kn(e,t,n){let r=/* @__PURE__ */ new Map;for(let t of e){if(!Hn(t))continue;let e=r.get(t.material);e?e.push(t):r.set(t.material,[t])}let i=/* @__PURE__ */ new Float32Array(16),a=/* @__PURE__ */ new Float32Array(16),o=/* @__PURE__ */ new Float32Array(16),s=/* @__PURE__ */ new Float64Array(52),c=[];if(!Y(t.matrix,i,s))return c;for(let[e,t]of r){if(t.length<2)continue;let r=0,l=0,u=!1,d=[],f=[];for(let e of t){Fe(i,e.node.matrix,a);let t=Vn(a);if(!t||!Number.isFinite(t)||!Y(a,o,s)){u=!0;break}r+=e.vertices.length/Ln,l+=e.indices.length;let n=/* @__PURE__ */ new Float32Array(16);n.set(a),d.push(n),f.push(t<0)}if(u||r>1e6||!l)continue;let p=Bn(t,d),m=p?.vertices??new Float32Array(r*Ln),h=p?.indices??new Uint32Array(l),g=0,_=0;for(let e=0;!p&&e<t.length;e++){let n=t[e],r=f[e];Fe(i,n.node.matrix,a),Y(a,o,s);let c=n.vertices;for(let e=0;e<c.length;e+=Ln)Un(c.subarray(e,e+Ln),m,g*Ln+e,a,o,r);let l=n.indices;for(let e=0;e<l.length;e+=3){let t=g+l[e],n=g+l[e+1],i=g+l[e+2];h[_+e]=t,h[_+e+1]=r?i:n,h[_+e+2]=r?n:i}g+=c.length/Ln,_+=l.length}if(!p){let e=Rn.get(t[0].vertices);e||Rn.set(t[0].vertices,e=[]),e.length>=4&&e.shift(),e.push({parts:t.flatMap(e=>[e.vertices,e.indices]),stamps:d,vertices:m,indices:h})}let v=n();c.push({node:v,material:e,primitive:Wn(v,e,m,h),parts:t.map((e,t)=>({primitive:e,stamp:d[t],vertices:e.vertices,indices:e.indices}))})}return c}var qn=`vec4f(normalize((f.view*vec4f(s.n,0)).xyz),-(f.view*vec4f(i.position,1)).z)`,Jn=`select(1.0,s.base.a,f.settings.x>1.5)`,Yn=`@fragment fn fragment(i:Out,@builtin(front_facing) front:bool)->@location(0) vec4f`,Xn=`struct MargoOcclusionOut {@location(0) normal:vec4f,@location(1) ambient:vec4f}
25
+ `,Zn=[`return vec4f(margoAmbient,${Jn});`,`return vec4f(select(margoAmbient,vec3f(0),f.ext.x>0.5),${Jn});`];function Qn(e){return{entry:`margoOcclusion`,code:e+`\n${Xn}@fragment fn margoOcclusion(i:Out,@builtin(front_facing) front:bool)->MargoOcclusionOut {\n let s=surface(i,front);\n return MargoOcclusionOut(${qn},vec4f(ambient(s),${Jn}));\n}\n`}}function $n(e){if(!e.includes(`margoAmbient`)||!e.includes(Yn))return Qn(e);let t=Zn.find(t=>e.includes(t));if(!t)return Qn(e);let n=t.slice(13,-2),r=e.replace(Yn,`${Xn}@fragment fn fragment(i:Out,@builtin(front_facing) front:bool)->MargoOcclusionOut`).replace(t,`return MargoOcclusionOut(${qn},vec4f(${n}));`);return!r.includes(`->MargoOcclusionOut`)||r===e?Qn(e):{code:r,entry:`fragment`}}var er=Symbol.for(`margoengine.gltf/pbr.defer-static-batches`),tr=/* @__PURE__ */ new WeakMap;function nr(e){let t=tr.get(e);return t||tr.set(e,t=/* @__PURE__ */ new Map),t}var rr=G,ir=[2,7],ar=e=>e.settings[0]===2||!!e.tint&&!e.extension?.replacesPhysical,or=e=>ar(e.primitive.material)||!e.batch&&$t(e.primitive),sr=/* @__PURE__ */ new WeakMap,cr=(e,t)=>{let n=sr.get(e);return n?.from!==e.extended&&sr.set(e,n={...t.plan(e.maps,e.extended),from:e.extended}),n},lr=e=>140+8*Math.max(21,e.maps.length),ur=/* @__PURE__ */ new WeakMap,dr=/* @__PURE__ */ new WeakSet,fr=/* @__PURE__ */ new WeakMap,pr=(e,t)=>{let n=ur.get(e);n||ur.set(e,n=/* @__PURE__ */ new WeakSet),n.add(t)},mr=e=>{let t=fr.get(e);return t||fr.set(e,t={...e,packedBase:!0}),t},hr=(e,t,n)=>{if(!e.extended||t<5)return!0;let r=cr(e,n).slots,i=r[t];if(i<0)return!1;let a=r.indexOf(i),o=r.findIndex((e,t)=>e===i&&G.includes(t));return(o>=0?o:a)===t},gr=e=>e.settings[0]===2&&!e.tint&&!e.renderState,_r=/* @__PURE__ */ new WeakMap,vr=e=>{let t=e.renderState;if(e.tint)return!t&&!e.extension?.replacesPhysical?3:0;if(e.settings[0]!==2||!t?.blend)return 0;let n=_r.get(t);if(n===void 0){let{srcFactor:e,dstFactor:r}=t.blend.color;n=Object.entries(t).every(([e,t])=>e===`blend`||t===void 0)?e===`src-alpha`&&r===`one`?1:e===`zero`&&r===`src`?2:0:0,_r.set(t,n)}return n},yr=e=>we(e),br=e=>e.settings[0]===2&&!e.tint&&e.renderState?.blend===void 0&&e.renderState?.blendSpace===`linear`,xr=/* @__PURE__ */ new WeakMap,Sr=e=>{if(!br(e))return!1;let t=e.renderState,n=xr.get(t);return n===void 0&&xr.set(t,n=Object.entries(t).every(([e,t])=>e===`blendSpace`||t===void 0)),n},Cr=e=>!!e.attenuation&&!e.shading;function wr(e,t){for(let[n,r,i]of[[`sampled textures`,/var\s*\w+\s*:\s*texture_(?!storage)/g,e.limits?.maxSampledTexturesPerShaderStage??16],[`samplers`,/var\s*\w+\s*:\s*sampler/g,e.limits?.maxSamplersPerShaderStage??16]]){let e=t.match(r)?.length??0;if(e>i)return{kind:n,count:e,limit:i}}}function Tr(e,t,n){let r=wr(e,t);if(r)throw RangeError(`gltf/pbr: ${n().join(` + `)} needs ${r.count} ${r.kind} per shader stage; this device allows ${r.limit}`)}var Er=/* @__PURE__ */ new WeakMap;function Dr(e,t,n,r,i,a,o){if(e)for(let s=0;s<e.length;s++){let c=e[s];if(c.frame===t&&c.source===n&&c.instances===r&&!!c.white===o&&c.topology===i&&c.sign===a&&c.extension===void 0)return c}}function Or(e,t,n,r,i,a,o,s=!1){let c=Dr(e,t,n,r,i,a,s),l=o.shading;if(c||!e||!l||t.lighting.length||n||o.extension)return c;let u=l.version;if(u!==void 0&&u===u)for(let o=0;o<e.length;o++){let c=e[o];if(!c.nativeGlass&&c.version===u&&c.complete&&c.shading===l&&c.source===n&&c.instances===r&&!!c.white===s&&c.topology===i&&c.sign===a&&c.extension===void 0&&Tt(c.frame,t))return c.frame=t,c}}var kr=Object.freeze([]);function Ar(e,t,n,r,i){if(!t||!n||!r)return;let a=e?.tintEffect;return a&&a.entries===r.entries&&e.tint===t?a:{entries:r.entries,group:at(i,t,2,r.entries)}}var jr=/* @__PURE__ */ new Map,Mr=(e,t)=>e.split(t).length-1;function Nr(e){let t=jr.get(e);if(t===void 0){jr.size>=256&&jr.clear();let n=Mr(e,`*f.base*i.color`);t=n>0&&Mr(e,`f.base`)===n&&Mr(e,`i.color`)===n+Mr(e,`o.color=i.color`),jr.set(e,t)}return t}var Pr=/* @__PURE__ */ new Map,Fr={},Ir=[],Lr=0;function Rr(e,t,n){let r=t.matrix,i=t.position,a=n.direction,o=n.radiance,s=Math.hypot(a[0],a[1],a[2]);for(let t=0;t<16;t++)if(e[t]!==Math.fround(r[t]))return!1;for(let t=0;t<3;t++)if(e[32+t]!==Math.fround(i[t]))return!1;for(let t=0;t<4;t++)if(e[36+t]!==Math.fround(t<3?a[t]/s:a[t])||e[40+t]!==Math.fround(o[t]))return!1;return!0}function zr(e,t,n){let r=e.folds.get(t),i=r?.get(n);if(i!==void 0)return i;let a=t.frame===n.frame&&t.sign===n.sign&&t.topology===n.topology&&t.instances===n.instances&&t.source===n.source&&t.floatCount===n.floatCount&&t.compact===n.compact&&t.replacesTextures===n.replacesTextures&&t.extension===void 0&&n.extension===void 0&&!t.tinted&&!n.tinted&&t.blend===n.blend&&Fn(t.state)===Fn(n.state),o=t.block,s=n.block;for(let e=0;a&&e<o.length;e++)(e<16||e>=48)&&(e<76||e>=80)&&e!==97&&!Object.is(o[e],s[e])&&(a=!1);return r||e.folds.set(t,r=/* @__PURE__ */ new Map),r.set(n,a),a}function Br(e,t){if(e===t)return!0;if(!e||!t||e.entries.length!==t.entries.length)return!1;for(let n=0;n<e.entries.length;n++){let r=e.entries[n],i=t.entries[n],a=r.resource,o=i.resource;if(r.binding!==i.binding||!(a===o||`buffer`in a&&`buffer`in o&&a.buffer===o.buffer&&a.offset===o.offset&&a.size===o.size))return!1}return!0}function Vr(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}var Hr=(e,t)=>t.group!==void 0&&e.group===t.group&&e.frame===t.frame&&e.sign===t.sign&&e.topology===t.topology&&e.blend===t.blend;function Ur(e,t,n,r,i,a){let o=i.view??i,s=n.primitive;if(r.blend){let c=e.pending[e.pending.length-1];if(c?.d.blend&&c.view===o&&c.viewAt===a&&c.owner.primitive.vertices===s.vertices&&c.owner.primitive.indices===s.indices){let i=c.d===r||!c.rows&&zr(e,c.d,r);if(i||Hr(c.d,r)){c.d!==r&&(c.folded=!0,i||(c.rows=!0)),Gr(c,t,n,r);return}}e.fence++;let l=Kr(e,t,n,r,i,o,a);e.pending.push(l),Gr(l,t,n,r);return}let c=r.joinedRun===e?r.joined:void 0;if(c&&c.fence===e.fence&&c.view===o&&c.viewAt===a&&c.owner.primitive.vertices===s.vertices&&c.owner.primitive.indices===s.indices){Gr(c,t,n,r);return}c=void 0;let l=r.group??r,u=e.batches.get(l);if(u)for(let t=0;t<u.length;t++){let n=u[t],i=n.owner.primitive;if(n.fence===e.fence&&n.view===o&&n.viewAt===a&&i.vertices===s.vertices&&i.indices===s.indices&&(n.d===r||Hr(n.d,r))){c=n,n.d!==r&&(c.rows=c.folded=!0);break}}c||(c=Kr(e,t,n,r,i,o,a),u||e.batches.set(l,u=[]),u.push(c),e.pending.push(c)),r.joined=c,r.joinedRun=e,Gr(c,t,n,r)}var Wr=e=>e.batch?.parts.length??e.primitive.instances?.count??1;function Gr(e,t,n,r){e.members.push(n),e.models.push(t),e.nodes.push(n.primitive.node),e.ds.push(r)}function Kr(e,t,n,r,i,a,o){let s=e.spare.pop();return s?(s.model=t,s.owner=n,s.d=r,s.c=i,s.view=a,s.viewAt=o,s.folded=s.rows=!1,s.fence=e.fence,s):{model:t,owner:n,d:r,c:i,view:a,viewAt:o,members:[],models:[],nodes:[],ds:[],folded:!1,rows:!1,fence:e.fence}}function qr(e){let t=e.pending;if(t.length)try{for(let n=0;n<t.length;n++){let r=t[n];r.model.disposed||r.model.drawBatch(r,e)}}finally{for(let n=0;n<t.length;n++){let r=t[n],i=r.ds;for(let e=0;e<i.length;e++)i[e].joined===r&&(i[e].joined=i[e].joinedRun=void 0);r.members.length=r.models.length=r.nodes.length=i.length=0,r.model=r.c=r.view=r.viewAt=r.owner=r.d=void 0,e.spare.push(r)}t.length=0;for(let t of e.batches.values())t.length=0;e.batches.clear()}}function Jr(e,t,n){let r=t.primitive;return!r.instances&&!r.deformed&&!r.topology&&!t.batch&&!t.mergedInto&&!e.tinted&&!e.nativeGlass&&e.extension===void 0&&n!==0&&Number.isFinite(n)&&(e.replacesTextures||!r.material.maps.some(Boolean))}function Yr(e,t){e.pass=t,e.pipeline=e.vertex=e.instances=e.uvs=e.index=void 0,e.groups.fill(void 0)}function Xr(e,t){e.pipeline!==t&&e.pass.setPipeline(e.pipeline=t)}function Z(e,t,n){e.groups[t]!==n&&e.pass.setBindGroup(t,e.groups[t]=n)}function Zr(e,t){t&&e.uvs!==t&&e.pass.setVertexBuffer(2,e.uvs=t)}function Qr(e,t,n,r,i=0){let a=e.pass;(e.vertex!==t||e.vertexOffset!==i)&&a.setVertexBuffer(0,e.vertex=t,(e.vertexOffset=i)||void 0),n&&e.instances!==n&&a.setVertexBuffer(1,e.instances=n),e.index!==r&&a.setIndexBuffer(e.index=r,`uint32`)}function $r(e,t,n,r,i,a,o,s,c){let l=e?.lastFrame;if(l&&l.lighting===c&&e.lastContext===r&&e.lastDescriptor===r.descriptor&&l.mode===t&&l.depthCompare===n&&l.format===r.format&&l.section===i&&l.oit===a&&l.hook===o&&l.hooks===(s||void 0)&&l.glass===!!h(r)&&l.samples===r.descriptor.multisample?.count&&l.depthFormat===r.descriptor.depthStencil.format)return l;let u=ei(e,t,n,r,i,a,o,s,c);return e&&(e.lastFrame=u,e.lastContext=r,e.lastDescriptor=r.descriptor),u}function ei(e,t,n,r,i,a,o,s,c){let l=r.descriptor.multisample?.count,u=r.descriptor.depthStencil.format,d=s||void 0,f=!!h(r);if(e)for(let s=0;s<e.frames.length;s++){let p=e.frames[s];if(p.mode===t&&p.depthCompare===n&&p.format===r.format&&p.samples===l&&p.depthFormat===u&&p.section===i&&p.oit===a&&p.hook===o&&p.hooks===d&&p.glass===f&&Et(p.lighting,c))return p}let p={mode:t,depthCompare:n,format:r.format,samples:l,depthFormat:u,section:i,oit:a,hook:o,hooks:d,lighting:c,glass:f};return e&&e.frames.length<16&&e.frames.push(p),p}var ti=class{constructor(){this.frames=[],this.bindings={pass:void 0,groups:[void 0,void 0,void 0,void 0]},this.view={data:/* @__PURE__ */ new Float32Array(48),format:void 0,at:void 0},this.pending=[],this.spare=[],this.batches=/* @__PURE__ */ new Map,this.fence=0,this.folds=/* @__PURE__ */ new Map}quickFor(e){let t=this.quick;return t?.c!==e&&(this.quick=t={c:e,section:Ye(e)?.buffer,draws:bt(e.device),opaque:!!Er.get(e),viewChecked:!1,frame:void 0,lighting:void 0,oit:void 0,hook:void 0,hooks:void 0}),t}end(){let e=this.pass;try{qr(this)}finally{this.pass=void 0,this.frames.length=0,this.lastFrame=this.lastContext=this.lastDescriptor=void 0,this.pending.length=0,this.batches.clear(),this.folds.clear(),this.view.at=this.view.format=void 0,this.quick=void 0,Yr(this.bindings,void 0);try{e?.end()}finally{this.device&&_t(this.device)}}}},ni=/* @__PURE__ */ new WeakMap,ri=()=>({revision:-1,segment:[],segments:/* @__PURE__ */ new WeakMap,run:new ti}),ii=Symbol.for(`margoengine.pbr-source.v1`),ai=e=>e.side??(e.settings[2]===2?`back`:e.settings[2]>=.5?`double`:`front`),oi=e=>e===`double`?1:e===`back`?2:0;function si(e,t,n){let{maps:r}=e;for(let e=0;e<r.length;e++)if(r[e]?.extensions?.KHR_texture_transform!==void 0)return-1;return+(!!r[2]&&t[94]===1)+!!n*2}function ci({vertices:e,uvs:t}){if(!(t instanceof Float32Array)||t.length!==e.length/5)throw RangeError(`Prepared uvs need four floats a vertex; pass TEXCOORD_2 then TEXCOORD_3 for each vertex`)}function li(e,t,n,r,i,a,o){if((t.mode??4)!==4||t.targets||t.extensions)throw TypeError(`Prepared PBR requires static triangles`);let s=t.material===void 0?Ii():a[R(t.material,`material`)],c=Array.isArray(n)?n:[n];if(!c.length)throw TypeError(`Missing prepared PBR primitives; this is a loader bug, report it with the file`);return c.flatMap(n=>{let a=o.get(n);if(!a){a=n?.vertices?.length/20>e.partVertices?ee(n,e.partVertices,s?.alphaMode===`BLEND`):[n];for(let e of a)en(e);o.set(n,a)}return a.map(n=>ui(e,t,n,r,i,s))})}function ui(e,t,n,r,i,a){let{vertices:o,indices:s}=n;if(!a)throw TypeError(`Missing prepared PBR material; this is a loader bug, report it with the file`);for(let t of a.maps)if(t){if(R(t.texCoord??0,`texture coordinate`)>(n.uvs?3:1))throw RangeError(`Invalid prepared PBR UV set`);z(e.doc.textures,t.index,`texture`)}return n.uvs&&ci(n),{node:r,nodeIndex:i,vertices:o,indices:s,...n.uvs?{uvs:n.uvs}:{},...n.part?{part:n.part}:{},definition:t,material:a,weights:/* @__PURE__ */ new Float32Array,targetNames:[]}}var di=/* @__PURE__ */ new WeakMap,fi=e=>!e.primitive.deformed&&di.get(e.vertex)===!0,pi=/* @__PURE__ */ new WeakMap,mi=e=>!e.primitive.deformed&&!e.primitive.instances&&pi.get(e.vertex)===!0;function hi(e){let t=new Uint32Array(e.length*2),n=/* @__PURE__ */ new Set,r=0;for(let t=0;t<e.length;t++)e[t]>=r&&(r=e[t]+1);let i=r<=2**26,a=0,o=(e,o)=>{let s=e<o?e:o,c=e<o?o:e,l=i?s*r+c:s+`,`+c;n.has(l)||(n.add(l),t[a++]=e,t[a++]=o)};for(let t=0;t+2<e.length;t+=3){let n=e[t],r=e[t+1],i=e[t+2];o(n,r),o(r,i),o(i,n)}return t.slice(0,a)}function gi(e){let t=e.primitive,n=t.material.wireframe;if(n!==void 0&&typeof n!=`boolean`)throw TypeError(`PBR material wireframe must be a boolean; set wireframe to true or false`);if(!n||t.topology)return;if(e.wireframe)return e.wireframe;if(t.indices.byteLength*2>e.device.limits.maxBufferSize)throw RangeError(`PBR wireframe buffer exceeds the device limit; split the geometry into smaller meshes`);let r=hi(t.indices),i=Math.max(4,r.byteLength),a=e.device.createBuffer({size:i,usage:GPUBufferUsage.INDEX|GPUBufferUsage.COPY_DST});try{e.device.queue.writeBuffer(a,0,r)}catch(e){throw a.destroy(),e}return e.wireframe={index:a,count:r.length}}function _i(e,t,n){let r=e?.extensions?.MSFT_lod;if(r===void 0)return[];let i=r?.ids;if(!Array.isArray(i)||i.some(e=>!Number.isInteger(e)||e<0||e>=n||e===t))throw TypeError(`glTF node ${t} MSFT_lod ids must be other nodes of the file; re-export it`);return i}function vi(e,t){let n=e.primitive,r=n.material,i=gi(e),a=r.maps[0]?De(r.maps[0]):void 0;t.primitive=n,t.node=n.node,t.vertex=n.deformed??e.vertex,t.vertexOffset=n.deformed?n.deformedOffset??0:0,t.vertexSize=n.vertices.byteLength,t.index=i?.index??e.index,t.count=i?.count??n.indices.length,i?t.topology=`line-list`:delete t.topology,t.stride=80;let o=r.castMask;t.alphaTexture=o?o.view:e.views[0],t.alphaSampler=o?o.sampler:e.samplers[0],t.alpha=r.base[3];let s=o?o.texCoord:r.maps[0]?De(r.maps[0]).texCoord:0;t.cutoff=r.settings[0]===1&&s<2?r.settings[1]:0,t.texCoord=s<2?s:0,o?t.alphaTransform=o.transform:r.maps[0]?.extensions?.KHR_texture_transform?t.alphaTransform=a?.transform:delete t.alphaTransform;let c=o?.opacity;c?t.opacity=c:delete t.opacity;let l=t.cutoff>0?r.castAnimation:void 0;l?t.animation=l:delete t.animation,t.cutoff>0&&r.castHashed?(t.hashed=r.castHashed,t.alpha*=r.castShare??1):delete t.hashed,(r.vertexAlpha===!1||mi(e))&&t.cutoff>0?t.vertexAlpha=!1:delete t.vertexAlpha;let u=r.extended?.diffuseTransmission?r.physical:void 0;u?t.transmits=[u[21]*u[20],u[22]*u[20],u[23]*u[20]]:delete t.transmits,t.instances=n.instances;let d=r.displacement,f=r.clip;d?t.displacement=d:delete t.displacement,f?t.clip=f:delete t.clip,f&&r.clipHardware?t.clipHardware=!0:delete t.clipHardware;let p=r.surfaceClip;p?t.surfaceClip=p:delete t.surfaceClip,t.dynamic=!e.batch&&(!!e.edited||!!d||!!c||!!l||!!f||n.definition.attributes?.JOINTS_0!==void 0||!!n.definition.targets?.length||!!n.instances||!!n.deformed)}function yi(e,t,n,r,i){Tr(e,t,()=>[n.extended?`extended material`:n.physical?`physical material`:`material`,...r?[`transmission`]:[],...[...i].flatMap(e=>{let t=e;return[t.name??`shader patch`,...t.shadow?.name?[t.shadow.name]:[]]})])}function bi(e,t,n,r,i,a,o=n.uniform.binding){return e.createBindGroup({layout:t.getBindGroupLayout(0),entries:[{binding:0,resource:o},...a&&Dt.has(t)?[{binding:3,resource:a}]:[],...r?[{binding:1,resource:{buffer:n.volume??=e.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})}}]:[],...i?[{binding:2,resource:{buffer:i}}]:[]]})}function xi(e,t,n,r,i,a,o){let s=e.get(n);s||e.set(n,s=/* @__PURE__ */ new Map);let c=s.get(o);c||s.set(o,c=/* @__PURE__ */ new Map);let l=c.get(a);return l||c.set(a,l=bi(t,n,r,!1,i,a,o)),l}function Si(e,t,n,r,i,a,o){let s=(n.copies??=/* @__PURE__ */ new Map).get(a.buffer);s||n.copies.set(a.buffer,s=/* @__PURE__ */ new Map);let c=s.get(o);c||s.set(o,c=/* @__PURE__ */ new Map);let l=c.get(t);return l||c.set(t,l=bi(e,t,n,r,i,o,a)),l}function Ci(e,t,n,r,i,a,o,s){let c=[bi(e,t,n,i,o,s),wi(e,t,n,r,a)];return c.view=s,c}function wi(e,t,n,r,i){let a=dr.has(t);return a&&!n.packedBase&&(n.packedBase=Ve(e,n.baseSources)),at(e,t,1,[...a?[{binding:0,resource:n.packedBase.view},{binding:1,resource:{buffer:n.packedBase.params}}]:[],...n.views.flatMap((e,t)=>{if(t<5&&a||t>=5&&r.physical&&!r.shading&&!(n.primitive.extension??r.extension)&&(r.extended||t>=13?!r.maps[t]:xe(r.maps,t,13)!==t))return[];let o=t<5||!r.extended?t*2:10+cr(r,i).slots[t]*2;return e&&(!(n.primitive.extension??r.extension)?.replacesPhysical||t<5)?[{binding:o,resource:e},{binding:o+1,resource:n.samplers[t]}]:[]})])}function Ti(e,t,n,r,i){let a=e.descriptor.depthStencil.format.includes(`stencil`),o=t.depth,s=t.color;return s.view=n,o.view=r,s.resolveTarget&&=void 0,s.loadOp=o.depthLoadOp=`load`,s.storeOp=o.depthStoreOp=`store`,o.stencilLoadOp=a?`load`:void 0,o.stencilStoreOp=a?`store`:void 0,e.attach?.(s,o,!!i&&!Er.get(e)),e.encoder.beginRenderPass(t.descriptor)}function Ei(e,t){let n={view:e,loadOp:`load`,storeOp:`store`},r={view:t,depthLoadOp:`load`,depthStoreOp:`store`},i={matrices:[],tints:[],blocks:[],versions:[],checked:/* @__PURE__ */ new Set,batchValues:/* @__PURE__ */ new Float32Array,viewData:/* @__PURE__ */ new Float32Array(48),bound:{pass:void 0,groups:[void 0,void 0,void 0,void 0]},projection:/* @__PURE__ */ new Float32Array(16),view:/* @__PURE__ */ new Float32Array(16),eye:/* @__PURE__ */ new Float32Array(3),resources:[],effects:[],entries:[],color:n,depth:r,code:``,ambient:!1,effectCount:0,liveBatches:/* @__PURE__ */ new Map,blendDistance:/* @__PURE__ */ new Map,descriptor:{colorAttachments:[n],depthStencilAttachment:r},compare(e,t){let n=or(e),r=or(t);if(n!==r)return+n-r;if(!n)return 0;let a=i.blendDistance;return a.get(t)-a.get(e)}};return i}var Di=/* @__PURE__ */ new WeakMap;function Oi(e){if(e.pbr){let t=e.pbr(2);t&&(this.code=Ce(this.code,t),this.ambient||=!!t.ambient)}else this.code=e.shader(this.code,2)}function ki(e){this.effects[this.effectCount++]=e}function Ai(e,t,n){if(t.upload)return t.upload(e,n);let r={rgba8unorm:`rgba8`,"bc7-rgba-unorm":`bc7`,"astc-4x4-unorm":`astc-4x4`,"etc2-rgba8unorm":`etc2`},i=t.format.replace(/-srgb$/,``),a=r[i];if(!a)throw TypeError(`Unsupported KTX2 texture format `+t.format+`; transcode to a format the device supports`);let o=i+(n?`-srgb`:``);if(!Number.isSafeInteger(t.width)||!Number.isSafeInteger(t.height)||t.width<1||t.height<1||!t.mipmaps.length||t.mipmaps.length>Math.floor(Math.log2(Math.max(t.width,t.height)))+1)throw RangeError(`Invalid compressed image dimensions; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let s=a===`rgba8`?1:4,c=t.mipmaps.map((e,n)=>{let r=Math.max(1,t.width>>n),i=Math.max(1,t.height>>n),a=Le(o,r)*Math.ceil(i/s);if(e.width!==r||e.height!==i||!(e.data instanceof Uint8Array)||e.data.byteLength!==a)throw RangeError(`Invalid compressed image mip; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);return{...e,byteLength:a}});return Ie(e,{...t,format:o,target:a,srgb:n,hasAlpha:!0,mipmaps:c})}var ji=0,Q=(e,t,n,r=-1/0,i=1/0)=>{if(!Array.isArray(e)||e.length!==t||e.some(e=>typeof e!=`number`||!Number.isFinite(Math.fround(e))||e<r||e>i))throw TypeError(`Invalid glTF `+n+`; re-export the file and check it with the glTF Validator`);return e},$=(e,t,n,r)=>Q([e],1,r,t,n)[0];function Mi(e={},t=0){let[n,r]=Q(e.offset??[0,0],2,`texture offset`),[i,a]=Q(e.scale??[1,1],2,`texture scale`),o=$(e.rotation??0,-1/0,1/0,`texture rotation`),s=Math.cos(o),c=Math.sin(o);return[s*i,c*a,n,t,-c*i,s*a,r,0]}var Ni=Symbol(`volume-depth`),Pi={configurable:!0,enumerable:!0,get(){let e=this[Ni],t=this.attenuation;if(e.depth&&t){for(let n=0;n<3;n++)(t!==e.source||t[n]!==e.samples[n])&&(e.depth[n]=t[n]===1?0:-Math.log(t[n])),e.samples[n]=t[n];e.source=t}return e.depth},set(e){let t=this[Ni];t.depth=e,t.source=this.attenuation,t.samples=t.source?.slice()??[]}};function Fi(e){return e.attenuation?(Object.defineProperty(e,Ni,{value:{depth:e.opticalDepth,source:e.attenuation,samples:e.attenuation.slice()},configurable:!0}),Object.defineProperty(e,"opticalDepth",Pi)):e}function Ii(e={},t){e=t?.convert?.(e)??e;let n=e.pbrMetallicRoughness??{},r=e.alphaMode??`OPAQUE`,i=t?e.extensions??{}:{KHR_materials_unlit:e.extensions?.KHR_materials_unlit,KHR_materials_emissive_strength:e.extensions?.KHR_materials_emissive_strength};if(![`OPAQUE`,`MASK`,`BLEND`].includes(r))throw TypeError(`Invalid glTF alpha mode; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);if(e.doubleSided!==void 0&&typeof e.doubleSided!=`boolean`)throw TypeError(`Invalid glTF doubleSided; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let a=i.KHR_materials_clearcoat,o=i.KHR_materials_transmission,s=i.KHR_materials_sheen,c=i.KHR_materials_specular,l=i.KHR_materials_volume,u=e.extensions?.KHR_materials_dispersion?.dispersion,d=Q(n.baseColorFactor??[1,1,1,1],4,`base color`,0,1),f=$(o?.transmissionFactor??0,0,1,`transmission`),p=$(i.KHR_materials_emissive_strength?.emissiveStrength??1,0,1/0,`emissive strength`),m=Q(l?.attenuationColor??[1,1,1],3,`attenuation color`,0,1),h=$(l?.thicknessFactor??0,0,1/0,`thickness`),g=l?.attenuationDistance===void 0?1/0:$(l.attenuationDistance,Number.MIN_VALUE,1/0,`attenuation distance`),_=h/g,v=o?m.map(e=>st(e,_)):void 0,y=t?.parse(i),b=!!(y||a||o||s||c||l||i.KHR_materials_ior||i.KHR_materials_dispersion),x=[n.baseColorTexture,n.metallicRoughnessTexture,e.normalTexture,e.occlusionTexture,e.emissiveTexture,...b?[a?.clearcoatTexture,a?.clearcoatRoughnessTexture,a?.clearcoatNormalTexture,o?.transmissionTexture,s?.sheenColorTexture,s?.sheenRoughnessTexture,c?.specularTexture,c?.specularColorTexture]:[],...y?y.maps:[]].map(e=>e?.extensions?.KHR_texture_transform===void 0?e:{...e,texCoord:De(e).texCoord});return Fi({...e,base:d,factors:[$(n.roughnessFactor??1,0,1,`roughness`),$(n.metallicFactor??1,0,1,`metallic`),$(e.normalTexture?.scale??1,-1/0,1/0,`normal scale`),$(e.occlusionTexture?.strength??1,0,1,`occlusion strength`)],emission:Q(e.emissiveFactor??[0,0,0],3,`emissive`,0,1).map(e=>e*p),settings:[[`OPAQUE`,`MASK`,`BLEND`].indexOf(r),$(e.alphaCutoff??.5,0,1/0,`alpha cutoff`),+(e.doubleSided??!1),0],get side(){return this.settings[2]===2?`back`:this.settings[2]>=.5?`double`:`front`},set side(e){if(![`front`,`back`,`double`].includes(e))throw TypeError(`Invalid material side; use front, back or double`);this.settings[2]=oi(e)},maps:x,uvt:x.flatMap(e=>Mi(e?.extensions?.KHR_texture_transform??{},e?.texCoord??0)),ext:[+!!i.KHR_materials_unlit,$(i.KHR_materials_ior?.ior??1.5,0,1/0,`ior`),0,0],dispersion:$(u===void 0?0:u,0,1/0,`dispersion`),physical:b?[$(a?.clearcoatFactor??0,0,1,`clearcoat`),$(a?.clearcoatRoughnessFactor??0,0,1,`clearcoat roughness`),$(a?.clearcoatNormalTexture?.scale??1,-1/0,1/0,`clearcoat normal scale`),f,...Q(c?.specularColorFactor??[1,1,1],3,`specular color`,0),$(c?.specularFactor??1,0,1,`specular`),...Q(s?.sheenColorFactor??[0,0,0],3,`sheen color`,0,1),$(s?.sheenRoughnessFactor??0,0,1,`sheen roughness`),...y?y.rows:[]]:void 0,extended:y?.features,tint:f?d.slice(0,3).map((e,t)=>e*f*st(m[t],_)):void 0,attenuation:v,opticalDepth:o?m.map(e=>e===1||_===0?0:-Math.log(e)*_):void 0,volume:o?[h,...m.map(e=>st(e,1/g))]:void 0})}var Li=/* @__PURE__ */ new WeakMap,Ri=/* @__PURE__ */ new WeakMap,zi=/* @__PURE__ */ new WeakMap,Bi=/* @__PURE__ */ new WeakMap,Vi=/* @__PURE__ */ new WeakMap,Hi=/* @__PURE__ */ new WeakMap,Ui=/* @__PURE__ */ new WeakMap;function Wi(e){let t=Vi.get(e);return t?t.users>1?!1:(Gi(t),!0):!0}function Gi(e){Vi.delete(e.buffer),e.map.get(e.data)===e&&e.map.delete(e.data)}function Ki(e,t){let n=Vi.get(t);n&&--n.users>0||(n&&Gi(n),m(e,t))}function qi(e,t){let n=zi.get(e);n||zi.set(e,n=/* @__PURE__ */ new WeakMap);let r=n.get(t);return r||n.set(t,r=/* @__PURE__ */ new Map),r}function Ji(e,t){let n=Bi.get(t);n&&--n.users>0||(n&&(Bi.delete(t),n.map.delete(n.key)),m(e,t))}function Yi(e,t,n,r,i,a,o,s){let c=Li.get(e);c||Li.set(e,c=/* @__PURE__ */ new WeakMap);let l=q.get(t)??o.get(t)??c.get(t);l||(l=Ae(e,t),c.set(t,l)),o.set(t,l);let u=Qi(e,t,t.material===void 0?Ii():a[R(t.material,`material`)],!!l[0].topology,t.material===void 0?void 0:R(t.material,`material`),s),d=t.targets??[];if(!Array.isArray(d))throw TypeError(`Invalid morph targets; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let f=Q(e.doc.nodes[r].weights??i.weights??Array(d.length).fill(0),d.length,`morph weights`);return l.map(e=>{let a={node:n,nodeIndex:r,vertices:e.vertices,indices:e.indices,definition:t,material:u,weights:Float32Array.from(f),targetNames:d.map((e,t)=>i.extras?.targetNames?.[t]??`Target `+t)};return e.topology&&(a.topology=e.topology),e.uvs&&(a.uvs=e.uvs),e.part&&(a.part=e.part),a})}var Xi=[`baseColorTexture`,`metallicRoughnessTexture`,`normalTexture`,`occlusionTexture`,`emissiveTexture`,`clearcoatTexture`,`clearcoatRoughnessTexture`,`clearcoatNormalTexture`,`transmissionTexture`,`sheenColorTexture`,`sheenRoughnessTexture`,`specularTexture`,`specularColorTexture`,`iridescenceTexture`,`iridescenceThicknessTexture`,`anisotropyTexture`,`diffuseTransmissionTexture`,`diffuseTransmissionColorTexture`,`bumpTexture`,`multiscatterColorTexture`,`thicknessTexture`,`diffuseRoughnessTexture`],Zi=/* @__PURE__ */ new WeakMap;function Qi(e,t,n,r,i,a){if(!n)throw TypeError(`Missing glTF material; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let o=t.attributes??{},s=[];n.maps.forEach((t,r)=>{if(!t)return;let l=R(t.texCoord??0,`texture coordinate`);if(z(e.doc.textures,t.index,`texture`),l>3)throw J(`failed`,`Material requires available TEXCOORD_${l}, and at most TEXCOORD_3; add the attribute or remove the texture`);o[`TEXCOORD_`+l]===void 0&&(s.push(r),a&&i!==void 0&&u(a,c(i,n.name,Xi[r]??`map ${r}`,l)))});let l=(e,t)=>{let n=Object.getOwnPropertyDescriptor(e,`side`),r={...e,...t};return n?Object.defineProperty(r,"side",n):r};if(s.length){let e=s.join(`,`),t=Zi.get(n);t||Zi.set(n,t=/* @__PURE__ */ new Map);let r=t.get(e);if(!r){let i=n.maps.map((e,t)=>s.includes(t)?void 0:e);t.set(e,r=l(n,{maps:i}))}n=r}return r&&o.NORMAL===void 0?l(n,{ext:[1,...n.ext.slice(1)]}):n}function $i(e,t){for(let[n,r]of[[`translation`,3],[`rotation`,4],[`scale`,3]]){let i=e[n];if(i!==void 0&&(!Array.isArray(i)||i.length!==r||i.some(e=>typeof e!=`number`||!Number.isFinite(Math.fround(e)))))throw Pe(`Invalid glTF ${n} on node ${t}: ${r} finite numbers`,`gltf-transform`)}}function ea(t,n,r){if(n.matrix!==void 0){let i=Q(n.matrix,16,`matrix`);if(n.translation||n.rotation||n.scale||i[3]||i[7]||i[11]||i[15]!==1)throw TypeError(`Invalid glTF affine matrix; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let a=e(i);if(!a.ok)throw a.reason===`singular`?/* @__PURE__ */ RangeError(`Singular glTF matrix`):Pe(`Sheared glTF matrix on node ${r}`,`gltf-transform`);t.setPosition(a.position).setScale(a.scale).setQuaternion(a.rotation)}else $i(n,r),t.setPosition(n.translation??[0,0,0]).setScale(n.scale??[1,1,1]).setQuaternion(n.rotation??[0,0,0,1])}function ta(e,t){return!j(e.store,t.id)}var na=/* @__PURE__ */ new WeakMap;function ra(e,t){if(!e||e.length<24||t.instances||t.deformed||t.topology)return!1;let n=t.material;if(n.shading||n.displacement||t.definition.targets?.length||t.definition.attributes?.JOINTS_0!==void 0)return!1;let r=na.get(t.vertices);if(!r){let e=t.vertices,n=[1/0,1/0,1/0],i=[-1/0,-1/0,-1/0];for(let t=0;t<e.length;t+=20)for(let r=0;r<3;r++)e[t+r]<n[r]&&(n[r]=e[t+r]),e[t+r]>i[r]&&(i[r]=e[t+r]);if(r=/* @__PURE__ */ new Float32Array(4),!(n[0]<=i[0]))r[3]=-1;else{for(let e=0;e<3;e++)r[e]=(n[e]+i[e])/2;let t=0;for(let n=0;n<e.length;n+=20){let i=e[n]-r[0],a=e[n+1]-r[1],o=e[n+2]-r[2];t=Math.max(t,i*i+a*a+o*o)}r[3]=Math.sqrt(t)*(1+1e-6)+1e-6}na.set(t.vertices,r)}if(r[3]<0)return!1;let i=t.node.matrix,a=i[0]*r[0]+i[4]*r[1]+i[8]*r[2]+i[12],o=i[1]*r[0]+i[5]*r[1]+i[9]*r[2]+i[13],s=i[2]*r[0]+i[6]*r[1]+i[10]*r[2]+i[14],c=Math.sqrt(Math.max(i[0]*i[0]+i[1]*i[1]+i[2]*i[2],i[4]*i[4]+i[5]*i[5]+i[6]*i[6],i[8]*i[8]+i[9]*i[9]+i[10]*i[10])),l=r[3]*c;if(!Number.isFinite(a+o+s+l))return!1;for(let t=0;t<24;t+=4)if(e[t]*a+e[t+1]*o+e[t+2]*s+e[t+3]<-l)return!0;return!1}var ia=class e{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static beginOpaquePass(e){Er.set(e,/* @__PURE__ */ new Set)}static cancelOpaquePass(e){Er.delete(e)}static endOpaquePass(e){let t=Er.get(e);Er.delete(e);for(let n of t??[])n.draw(e,`beauty`,e.color,e.depth,`blend`)}get meshes(){return[...new Set(this.primitives.map(e=>e.node))]}constructor(t,n,a=[],o,s){this.asset=n,this.images=a,this.glassQueued=!1,this.name=`gltf/pbr:`+ji++,this.nodes=[],this.primitives=[],this.lights=[],this.lods=[],this.cameras=[],this.warnings=[],this.pointsAndLines=[],this.defaults=/* @__PURE__ */ new Map,this.disposed=!1,this.created=[],this.resources=[],this.byNode=/* @__PURE__ */ new Map,this.textures=[],this.gpuCache=/* @__PURE__ */ new Map,this.inverse=/* @__PURE__ */ new Float32Array(16),this.workspace=/* @__PURE__ */ new Float64Array(52),this.bufferSources=/* @__PURE__ */ new Map,this.cleanupCallbacks=/* @__PURE__ */ new Set,this.strokeCandidates=[],this.splatPrimitives=[],this.splats=[],this.lighting=/* @__PURE__ */ new Set,this.sceneSky=!0,this.lightingList=kr,this.replays=/* @__PURE__ */ new Map,this.gpuRevision=0;for(let e of a)if(e&&`data`in e&&(!Number.isSafeInteger(e.width)||e.width<1||!Number.isSafeInteger(e.height)||e.height<1||!Number.isSafeInteger(e.width*e.height*4)||!(e.data instanceof Uint8Array)||e.data.byteLength!==e.width*e.height*4))throw RangeError(`Invalid glTF pixel image; provide positive integer dimensions and exactly width * height * 4 RGBA8 bytes`);this.engine=je(t),Object.defineProperty(this,Qt,{value:e.prototype.writeShadowPrimitives});let c=n.doc,l=c.nodes??[],u=new Int32Array(l.length).fill(-1),d=this.materials=(c.materials??[]).map(e=>Ii(e,n.hooks.materials||void 0)),f=c.extensions?.KHR_materials_variants?.variants??[];if(!Array.isArray(f)||f.some(e=>typeof e?.name!=`string`))throw TypeError(`Invalid glTF material variants; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);this.variants=f.map(e=>e.name),l.forEach((e,t)=>{if(!e||e.children!==void 0&&!Array.isArray(e.children))throw TypeError(`Invalid glTF node; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let n=e.extensions?.KHR_node_visibility;if(n!==void 0&&(!n||typeof n!=`object`||Array.isArray(n)||n.visible!==void 0&&typeof n.visible!=`boolean`))throw TypeError(`glTF node ${t} KHR_node_visibility must be an object with an optional boolean visible`);for(let n of e.children??[]){let e=R(n,`child`);if(e>=l.length||u[e]!==-1||e===t)throw TypeError(`Invalid glTF hierarchy; give each node one parent and valid child indices`);u[e]=t}}),l.forEach((e,t)=>{for(let n of _i(e,t,l.length))u[n]===-1&&(u[n]=u[t])});for(let e=0;e<l.length;e++){let t=0;for(let n=e;n!==-1;n=u[n])if(++t>l.length)throw Pe(`glTF hierarchy cycle through node ${e}`,`gltf-transform`);if(t>62)throw Ne(`glTF node ${e} is ${t} levels deep, past 62`,`gltf-transform`)}let p=c.scenes?z(c.scenes,c.scene??0,`scene`).nodes??[]:l.map((e,t)=>t).filter(e=>u[e]===-1);if(!Array.isArray(p)||new Set(p).size!==p.length||p.some(e=>u[R(e,`scene root`)]!==-1))throw TypeError(`Invalid scene roots; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let m=/* @__PURE__ */ new Set,h=e=>{z(l,e,`node`),m.add(e);for(let t of l[e].children??[])h(t);for(let t of _i(l[e],e,l.length))m.has(t)||h(t)};for(let e of p)h(e);try{this.root=this.engine.createMesh(null,s),this.created.push(this.root);for(let e=0;e<l.length;e++){let t=this.engine.createMesh(null,s);this.nodes.push(t),this.created.push(t),t.name=l[e].name??``,t.visible=l[e].extensions?.KHR_node_visibility?.visible??!0,ea(t,l[e],e)}for(let e=0;e<l.length;e++)this.nodes[e].setParent(u[e]<0?this.root:this.nodes[u[e]]);for(let e of m){let t=_i(l[e],e,l.length);if(!t.length)continue;let n=l[e].extras?.MSFT_screencoverage;if(n!==void 0&&(!Array.isArray(n)||n.length>t.length+1||n.some((e,t)=>!(e>0&&e<=1)||t>0&&e>=n[t-1])))throw TypeError(`glTF node ${e} MSFT_screencoverage must hold decreasing numbers from 0 to 1, at most one per level; re-export the file`);for(let e of t)this.nodes[e].visible=!1;this.lods.push({node:this.nodes[e],levels:[this.nodes[e],...t.map(e=>this.nodes[e])],...n?{screenCoverage:[...n]}:{}})}for(let e of m){let t=l[e],n=t.extensions?.KHR_lights_punctual;if(n){let t=z(c.extensions?.KHR_lights_punctual?.lights,n.light,`light`),r=t.type===`spot`?{innerConeAngle:$(t.spot?.innerConeAngle??0,0,Math.PI/2,`spot cone`),outerConeAngle:$(t.spot?.outerConeAngle??Math.PI/4,0,Math.PI/2,`spot cone`)}:{};if(![`directional`,`point`,`spot`].includes(t.type)||t.range!==void 0&&!(t.range>0)||r.innerConeAngle>=r.outerConeAngle)throw TypeError(`Invalid glTF light; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);this.lights.push({...t,...r,color:Q(t.color??[1,1,1],3,`light color`,0),intensity:$(t.intensity??1,0,1/0,`light intensity`),node:this.nodes[e],nodeIndex:e})}if(t.camera!==void 0){let n=z(c.cameras,t.camera,`camera`);if(![`perspective`,`orthographic`].includes(n.type)||typeof n[n.type]!=`object`)throw TypeError(`Invalid glTF camera; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);this.cameras.push({...n,node:this.nodes[e],nodeIndex:e})}}let e=0,t=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Set,f=n.hooks.instancing;if(!f&&c.extensionsRequired?.includes(`EXT_mesh_gpu_instancing`))throw J(`unsupported`,`Required glTF extensions are unsupported: EXT_mesh_gpu_instancing (pass decoders.instancing from @margoengine/gltf/pbr-instancing)`);for(let r of m)if(l[r].mesh!==void 0){let s=z(c.meshes,l[r].mesh,`mesh`);if(!Array.isArray(s.primitives)||!s.primitives.length)throw TypeError(`Missing primitives; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);if(o&&o[l[r].mesh]?.length!==s.primitives.length)throw TypeError(`Missing prepared PBR primitives; this is a loader bug, report it with the file`);let u=l[r].extensions?.EXT_mesh_gpu_instancing,p=u&&f?.read(n,u);for(let u=0;u<s.primitives.length;u++){let f=s.primitives[u];if(f?.attributes?.POSITION===void 0&&!q.has(f)&&!o?.[l[r].mesh]?.[u])continue;if(n.hooks.splats&&ne(f)){this.splatPrimitives.push({primitive:f,nodeIndex:r});continue}if(!o&&(f?.mode??4)<4&&q.has(f)&&!q.get(f)[0].topology)continue;let m=o?li(n,f,o[l[r].mesh][u],this.nodes[r],r,d,t):Yi(n,f,this.nodes[r],r,s,d,i,this.warnings);for(let t of m){for(let n of[t.vertices,t.indices])a.has(n)||(e+=n.byteLength,a.add(n));if(e>n.maxBytes*4)throw U(`Decoded glTF geometry exceeds byte budget`,n.maxBytes*4);if(p&&(t.instances=p),(t.topology?this.pointsAndLines:this.primitives).push(t),t.topology&&n.hooks.strokes&&!p&&l[r].skin===void 0&&!f.targets?.length){let e=W(c,f);e&&this.strokeCandidates.push({primitive:t,width:e})}}}}let p=[`KHR_audio_emitter`,`MSFT_audio_emitter`].some(e=>c.extensions?.[e]&&(c.nodes?.some(t=>t.extensions?.[e])||c.scenes?.some(t=>t.extensions?.[e])));if(!this.primitives.length&&!this.pointsAndLines.length&&!this.splatPrimitives.length&&!this.cameras.length&&!this.lights.length&&!p)throw J(`failed`,`glTF contains no renderable meshes, cameras or lights; add a mesh with triangle primitives`);let h=this;for(let e of this.created)Object.defineProperty(e,ii,{value:h,configurable:!0});let g=this.byNode;for(let e of this.primitives){let t=g.get(e.node);t?t.push(e):g.set(e.node,[e])}for(let[e,t]of g){let n=this,i={model:n,node:e,primitives:t,stride:80,skinned:t.some(e=>c.nodes?.[e.nodeIndex]?.skin!==void 0),morphed:t.some(e=>!!e.definition.targets?.length),get bounds(){let e=new Float32Array([1/0,1/0,1/0,-1/0,-1/0,-1/0]);for(let n of t)for(let t=0;t<n.vertices.length;t+=20)for(let r=0;r<3;r++)e[r]=Math.min(e[r],n.vertices[t+r]),e[r+3]=Math.max(e[r+3],n.vertices[t+r]);return e},get draws(){return n.pickingPrimitives.filter(t=>t.node===e)},get shadowPrimitives(){return n.nodeShadowPrimitives(e)},get tintPrimitives(){return n.tintPrimitives.filter(t=>t.node===e)},prepareDeformation(e){n.prepareDeformation?.(e)},async readPickingGeometry(){return(await n.readPickingGeometry()).filter(t=>t.node===e)}};r(e,i)}let _=n[er];_&&(_.commit=()=>this.commitStaticBatches())}catch(e){for(let e of this.created.reverse())i(e),Reflect.deleteProperty(e,ii),e.dispose();throw e}}insertPart(e,t,n){let r=this.primitives.indexOf(e)+1,i=this.byNode.get(e.node);this.primitives.splice(r,0,t),this.resources.splice(r,0,n),i.splice(i.indexOf(e)+1,0,t),this.gpuRevision++}get bounds(){if(this.disposed)throw J(`disposed`,`PBRModel is disposed; load the model again`);this.engine.store.tick(!1);let e=new Float32Array([1/0,1/0,1/0,-1/0,-1/0,-1/0]);for(let t of this.pointsAndLines.length?[...this.primitives,...this.pointsAndLines]:this.primitives){if(t.instances){t.instances.bounds(t.node.matrix,t.vertices,e);continue}if(this.engine.meshes.get(t.node.id)!==t.node)continue;let n=t.node.matrix,r=t.vertices;for(let t=0;t<r.length;t+=20)for(let i=0;i<3;i++){let a=n[i]*r[t]+n[i+4]*r[t+1]+n[i+8]*r[t+2]+n[i+12];e[i]=Math.min(e[i],a),e[i+3]=Math.max(e[i+3],a)}}for(let{bounds:t}of this.splats)for(let n=0;n<3;n++)e[n]=Math.min(e[n],t[n]),e[n+3]=Math.max(e[n+3],t[n+3]);if(!Number.isFinite(e[0]))throw J(`state`,`No geometry; load a model with triangle meshes first`);return e}async attachSplats(e){let t=this.asset.hooks.splats;if(!t||!this.splatPrimitives.length)return;this.engine.store.tick(!1);let n=await t.attach(this.engine,this.asset,this.splatPrimitives.filter(({nodeIndex:e})=>ta(this.engine,this.nodes[e])).map(({primitive:e,nodeIndex:t})=>({primitive:e,matrix:this.nodes[t].matrix})),e);if(this.disposed)for(let{cloud:e}of n)e.dispose();else{this.splats=n;for(let{cloud:e}of n)this.cleanupCallbacks.add(()=>e.dispose())}}async attachStrokes(e){let t=this.asset.hooks.strokes,n=this.strokeCandidates.splice(0);if(!t||!n.length)return;let r=this.asset.doc,i=n.map(({primitive:e,width:t})=>{let n=e.definition.attributes?._WIDTH,i=n===void 0?void 0:this.asset.accessor(n,`SCALAR`),a=e.part?.vertexMap,o=i&&a?Float32Array.from(a,e=>i[e]):i,s=e.definition.material===void 0?void 0:r.materials?.[e.definition.material];return{width:t,extras:e.definition.extras,vertices:e.vertices,indices:e.indices,...o?{widths:o}:{},material:{base:e.material.base,alphaMode:s?.alphaMode,extensions:s?.extensions},node:e.node}}),a=await t.attach(this.engine,i,e);if(this.disposed)a.dispose();else{for(let{primitive:e}of n)e.widened=!0;this.cleanupCallbacks.add(()=>a.dispose())}}get raw(){return this.pickingPrimitives.filter(e=>this.engine.meshes.get(e.node.id)===e.node)}bufferUpload(e){let t=this.gpuCache,n=Ri.get(e);n||Ri.set(e,n=/* @__PURE__ */ new WeakMap);let r=n.get(this.asset);r||n.set(this.asset,r=/* @__PURE__ */ new WeakMap);let i=r;return(n,r)=>{let a=t.get(n);if(a)return a;let o=i.get(n);if(o&&o.usage===r)return o.users++,t.set(n,o.buffer),o.buffer;if(n.byteLength>e.limits.maxBufferSize)throw RangeError(`PBR buffer exceeds device limit; load a smaller model, or reduce its textures and meshes`);if(r&GPUBufferUsage.STORAGE&&n.byteLength>e.limits.maxStorageBufferBindingSize)throw RangeError(`PBR vertex buffer of ${n.byteLength} bytes exceeds this device's ${e.limits.maxStorageBufferBindingSize}-byte storage binding; lower maxPartVertices`);let s=e.createBuffer({size:n.byteLength,usage:r|GPUBufferUsage.COPY_DST});try{e.queue.writeBuffer(s,0,n)}catch(e){throw s.destroy(),e}let c={buffer:s,data:n,usage:r,users:1,map:i};return i.set(n,c),Vi.set(s,c),t.set(n,s),s}}dropBuffer(e,t){for(let[e,n]of this.gpuCache)n===t&&this.gpuCache.delete(e);Ki(e,t)}setup(e,t=e.gpu){if(e!==this.engine||this.disposed)throw J(`attached`,`PBRModel belongs to another engine or is disposed; load it into this engine`);if(!t)throw J(`unsupported`,`PBRModel requires WebGPU; use a browser that supports it; see https://margoengine.com/errors#webgpu`);let n=this.bufferUpload(t);for(let e of this.pointsAndLines.length?[...this.primitives,...this.pointsAndLines]:this.primitives){let r={primitive:e,device:t,vertex:void 0,index:void 0,uniform:void 0,values:void 0,groups:/* @__PURE__ */ new Map,views:[],samplers:[]};this.resources.push(r);let i=this.bufferSources?.get(e)??e;r.vertex=n(i.vertices,GPUBufferUsage.VERTEX|GPUBufferUsage.STORAGE),di.has(r.vertex)||di.set(r.vertex,Gt(i.vertices)),pi.has(r.vertex)||pi.set(r.vertex,Kt(i.vertices)),r.index=n(i.indices,GPUBufferUsage.INDEX),i.uvs&&(r.uvs=n(i.uvs,GPUBufferUsage.VERTEX)),e.buffers={vertex:r.vertex,index:r.index},this.bindMaterial(r,t)}this.installBatches(t,n)}shareBuffers(e,t){let n=this.asset;if(this.disposed||e===t||n[er])return!1;for(let n of[e,t])if(!this.primitives.includes(n)||n.topology||n.deformed||n.definition.targets?.length||n.definition.attributes?.JOINTS_0!==void 0||this.asset.doc.nodes?.[n.nodeIndex]?.skin!==void 0)return!1;let r=e.vertices,i=t.vertices,a=e.indices,o=t.indices;if(r.length!==i.length||a.length!==o.length)return!1;for(let e=0;e<r.length;e++)if(r[e]!==i[e])return!1;for(let e=0;e<a.length;e++)if(a[e]!==o[e])return!1;let s=this.bufferSources.get(t)??t;if(s===e)return!1;for(let[t,n]of this.bufferSources)n===e&&this.bufferSources.set(t,s);this.bufferSources.set(e,s);let c=this.resources.find(e=>e.primitive===s&&!e.batch),l=this.resources.find(t=>t.primitive===e&&!t.batch);if(!c||!l||l.vertex===c.vertex)return!0;let u=[l.vertex,l.index];for(let e of this.resources)!e.batch&&e.vertex===u[0]&&(e.vertex=c.vertex,e.index=c.index,e.primitive.buffers={vertex:c.vertex,index:c.index});for(let e of u)this.resources.some(t=>t.vertex===e||t.index===e)||this.dropBuffer(l.device,e);return!0}writeGeometry(e,t){if(this.disposed)throw J(`disposed`,`PBRModel is disposed; create a new model`);let n=this.primitives,r=this.resources[0]?.device.limits.maxBufferSize??1/0,i=new Set(this.bufferSources.values());if(!Array.isArray(e)||e.length!==n.length)throw RangeError(`PBR geometry needs one entry per primitive; pass model.primitives.length entries`);for(let a=0;a<n.length;a++){let o=n[a],s=e[a];if(o.deformed)throw TypeError(`PBR geometry writes need an undeformed primitive; dispose its Skin or other deformer, write, then attach it again`);if(o.definition.targets?.length||o.definition.attributes?.JOINTS_0!==void 0||this.bufferSources.has(o)||i.has(o))throw TypeError(`PBR geometry writes need unskinned, unmorphed, unshared primitives; recreate the model`);if(!t)en(s);else if(!(s?.vertices instanceof Float32Array)||!(s.indices instanceof Uint32Array)||s.vertices.length!==o.vertices.length||s.indices.length!==o.indices.length)throw RangeError(`A ranged PBR geometry write keeps the vertex and index counts; omit the range to resize`);if(s.uvs&&ci(s),o.uvs&&!s.uvs&&s.vertices.length!==o.vertices.length)throw RangeError(`A primitive with TEXCOORD_2 or 3 keeps its vertex count; pass uvs with the write to resize it`);if(s.topology)throw TypeError(`PBR geometry writes take triangle lists; remove topology`);if(s.vertices.byteLength>r||s.indices.byteLength>r)throw RangeError(`PBR buffer exceeds device limit; split the geometry into smaller meshes`)}if(t){let{start:r,count:i}=t,a=n[0].vertices.length/20;if(!Number.isSafeInteger(r)||!Number.isSafeInteger(i)||r<0||i<1||r+i>a)throw RangeError(`PBR geometry range must be whole vertices inside the mesh; pass start >= 0 and count >= 1`);for(let t of new Set(e.map(e=>e.vertices)))tn(t,r,r+i)}this.retireBatches();let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Set,s=/* @__PURE__ */ new Set;for(let e of this.resources)if(!n.includes(e.primitive))for(let t of[e.vertex,e.index,e.uvs])t&&o.add(t);let c=this.resources[0]?.device,l=!!c&&p(c),u=(e,t,n,i,c)=>{let u=a.get(n);if(!u){let s=c||n.byteLength<=t.size;!o.has(t)&&s&&!l&&Wi(t)?(c?c[1]&&e.device.queue.writeBuffer(t,c[0]*4,n,c[0],c[1]):e.device.queue.writeBuffer(t,0,n),u=t):(u=e.device.createBuffer({size:Math.min(r,Math.max(n.byteLength,s?t.size:t.size*2)),usage:i|GPUBufferUsage.COPY_DST}),e.device.queue.writeBuffer(u,0,n)),a.set(n,u),o.add(u)}return u!==t&&s.add(t),u};for(let r of this.resources){let i=n.indexOf(r.primitive);if(i<0)continue;let c=r.primitive,l=e[i],d=r.vertex;r.vertex=u(r,r.vertex,l.vertices,GPUBufferUsage.VERTEX|GPUBufferUsage.STORAGE,t&&[t.start*20,t.count*20]),di.set(r.vertex,t&&r.vertex===d?di.get(d)===!0&&Gt(l.vertices,t.start,t.count):Gt(l.vertices)),pi.set(r.vertex,t&&r.vertex===d?pi.get(d)===!0&&Kt(l.vertices,t.start,t.count):Kt(l.vertices)),r.index=u(r,r.index,l.indices,GPUBufferUsage.INDEX,t&&[0,0]),l.uvs&&(r.uvs?r.uvs=u(r,r.uvs,l.uvs,GPUBufferUsage.VERTEX):(r.uvs=r.device.createBuffer({size:l.uvs.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),r.device.queue.writeBuffer(r.uvs,0,l.uvs),a.set(l.uvs,r.uvs),o.add(r.uvs))),!t&&r.wireframe&&(s.add(r.wireframe.index),r.wireframe=void 0),c.buffers={vertex:r.vertex,index:r.index},r.edited=!0}for(let e of s)this.resources.some(t=>t.vertex===e||t.index===e||t.uvs===e)||Ki(c,e);for(let t=0;t<n.length;t++){let{uvs:r}=e[t];for(let e of[n[t].vertices,n[t].indices,...r?[n[t].uvs]:[]])a.has(e)||this.gpuCache.delete(e);na.delete(n[t].vertices),n[t].vertices=e[t].vertices,na.delete(n[t].vertices),n[t].indices=e[t].indices,r&&(n[t].uvs=r)}for(let[e,t]of a)this.gpuCache.set(e,t)}retireBatches(){if(this.staticBatches?.length){for(let e of this.resources)if(e.batch){for(let t of[e.vertex,e.index])this.dropBuffer(e.device,t);for(let t of[e.wireframe?.index,e.uniform,e.extension?.uniform,e.volume,e.packedBase])m(e.device,t)}this.resources=this.resources.filter(e=>!e.batch);for(let e of this.resources)e.mergedInto=void 0;this.staticBatches=[]}}adoptStaticBatches(e){let t=this.asset,n=e.staticBatches,r=this.primitives,i=e.primitives;if(this.disposed||e.disposed||this.asset!==e.asset||this.staticBatches!==void 0||!n||t[er]||r.length!==i.length||r.some((e,t)=>e.vertices!==i[t].vertices||e.indices!==i[t].indices)||this.engine.store.parents[e.root.id]!==-1)return!1;let a=new Map(i.map((e,t)=>[e,t])),o=e=>r[a.get(e)];for(let t of n){if(!e.pose(t,void 0,!0))return!1;let n=o(t.parts[0].primitive).material;for(let e of t.parts){let t=o(e.primitive);if(t.material!==n||!Hn(t))return!1}}return this.staticBatches=Gn(n,o,()=>this.batchNode()),!0}commitStaticBatches(){let e=this.asset;if(delete e[er],this.disposed||this.staticBatches!==void 0)return;let t=this.engine.gpu;if(!t)throw J(`unsupported`,`PBRModel requires WebGPU; use a browser that supports it`);this.installBatches(t,this.bufferUpload(t))}batchNode(){let e=this.root.scene.createMesh(this.root);return this.created.push(e),e}installBatches(e,t){if(this.asset[er]||!Object.hasOwn(this,`engine`)||(this.staticBatches===void 0&&(this.engine.store.tick(!1),this.staticBatches=Kn(this.primitives,this.root,()=>this.batchNode())),this.resources.some(e=>e.batch)))return;let n=new Map(this.resources.map(e=>[e.primitive,e]));for(let r of this.staticBatches){let i=r.primitive,a={primitive:i,device:e,vertex:void 0,index:void 0,uniform:void 0,values:void 0,groups:/* @__PURE__ */ new Map,views:[],samplers:[],batch:r};this.resources.push(a),a.vertex=t(i.vertices,GPUBufferUsage.VERTEX|GPUBufferUsage.STORAGE),a.index=t(i.indices,GPUBufferUsage.INDEX),i.buffers={vertex:a.vertex,index:a.index},this.bindMaterial(a,e);for(let e of r.parts){let t=n.get(e.primitive);t&&(t.mergedInto=a)}}}pose(e,t,n=!1){this.relative??=/* @__PURE__ */ new Float32Array(16);let r=this.root.matrix,i=e.node.matrix;for(let e=0;e<16;e++)if(i[e]!==r[e]){this.engine.store.tick(!1);break}if(!Y(r,this.inverse,this.workspace))return!1;let a=this.relative;for(let r=0;r<e.parts.length;r++){let i=e.parts[r],o=i.primitive;if(o.material!==e.material||t&&!_(t,o.node)||$t(o)||o.deformed||o.instances||o.topology||o.vertices!==i.vertices||o.indices!==i.indices||!n&&!ta(this.engine,o.node))return!1;Fe(this.inverse,o.node.matrix,a);let s=i.stamp;for(let e=0;e<16;e++)if(a[e]!==s[e])return!1}return!0}nodeShadowPrimitives(e){let t=[];for(let n=0;n<this.resources.length;n++){let r=this.resources[n];if(r.batch||r.primitive.node!==e||r.primitive.material.settings[0]===2||r.primitive.topology||$t(r.primitive))continue;let i={};vi(r,i),t.push(i)}return t}bindMaterial(e,t){m(t,e.packedBase),e.packedBase=void 0;let n=[],r=Math.max(V.get(this.asset)??1,Di.get(e.primitive.material)??1),i=e.primitive.material,c=!(e.primitive.extension??i.extension)?.replacesPhysical&&(i.extendedFrame||i.physical||i.ext?.[0])?i.extended?lr(i):220:100,l=this.gpuCache;if(e.values?.length!==c&&(m(e.device,e.uniform),e.values=new Float32Array(c),e.uniform=ht(t,c)),e.views=[],e.maps=[],e.samplers=[],e.streamed=void 0,e.groups.clear(),e.copies?.clear(),e.replacesTextures=!!i.shading?.replacesTextures,!e.replacesTextures){for(let c=0;c<i.maps.length;c++){if(!hr(i,c,this.asset.hooks.materials||void 0)){e.views.push(void 0),e.maps.push(void 0),e.samplers.push(void 0);continue}let u=i.maps[c],d=u?z(this.asset.doc.textures,u.index,`texture`):null,f=d?[`KHR_texture_basisu`,`MSFT_texture_dds`,`EXT_texture_webp`,`EXT_texture_avif`].map(e=>d.extensions?.[e]?.source).find(e=>e!==void 0&&this.images[e])??R(d.source,`image`):-1,p=this.images[f];if(d&&!p)throw TypeError(`Missing decoded glTF image; this is a loader bug, report it with the file`);let m=p&&`streamed`in p?p:void 0;if(m&&t!==this.engine.gpu)throw J(`unsupported`,"Streamed textures live on the engine device; load the model without `textures` to draw it on another device");let h=m?.view(t,rr.includes(c)),g=m?void 0:p;m&&(e.streamed??=[]).push(m);let _=g&&`ktx2`in g?g.ktx2:g&&`mipmaps`in g?g:void 0,v=_?`gpuFormat`in _&&_.gpuFormat?.(t,rr.includes(c))||_.format.replace(/-srgb$/,``)+(rr.includes(c)?`-srgb`:``):!g&&ir.includes(c)?`rgba16float`:rr.includes(c)?`rgba8unorm-srgb`:`rgba8unorm`,y=g?[g.width,g.height]:[1,1];if(y.some(e=>e>t.limits.maxTextureDimension2D))throw RangeError(`Image exceeds device limit; load a smaller model, or reduce its textures and meshes`);let b=d?.sampler===void 0?{}:z(this.asset.doc.samplers,d.sampler,`sampler`),x=c===0&&i.settings[0]===1&&g&&!_&&![9728,9729].includes(b.minFilter)?o(i.settings[1],i.base[3]):0,S=x?`:mask`+x:``,C=!x&&c===0&&i.settings[0]===2&&g&&!_?`:blend`:``,w=g?f+`:`+v+S+C:`default:`+c,T=h?void 0:l.get(w),E=T||h?void 0:qi(t,g??this.asset),D=g?v+S+C:w,O=E?.get(D);O&&(O.users++,T=O.texture,this.textures.push(T),l.set(w,T));let k=e=>{let t={texture:e,key:D,users:1,map:E};E.set(D,t),Bi.set(e,t),this.textures.push(e),l.set(w,e)};if(!T&&_&&(T=Ai(t,_,rr.includes(c)),k(T)),!T&&!h){let e=_?_.mipmaps.length:g?Math.floor(Math.log2(Math.max(...y)))+1:1;T=t.createTexture({size:y,format:v,mipLevelCount:e,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|(_?0:GPUTextureUsage.RENDER_ATTACHMENT)}),k(T),g&&`data`in g?t.queue.writeTexture({texture:T},g.data,{bytesPerRow:g.width*4},y):g?t.queue.copyExternalImageToTexture({source:g},{texture:T},y):t.queue.writeTexture({texture:T},ir.includes(c)?new Uint16Array([14336,14336,15360,15360]):new Uint8Array([255,255,255,255]),{bytesPerRow:ir.includes(c)?8:4},[1,1]),x?s(t,T,e,nr(t),i.settings[1],i.base[3]):_||a(t,T,e,nr(t),1,C?`weighted`:`plain`)}let A=h??Hi.get(T);A||Hi.set(T,A=T.createView()),e.views.push(A),e.maps.push(h?void 0:T);let j=h?m?.viewSize?.():void 0,M=j?.levels??T?.mipLevelCount??_?.mipmaps.length??Math.floor(Math.log2(Math.max(...y)))+1;c<5&&n.push({view:A,width:j?.width??y[0],height:j?.height??y[1],levels:M,sampler:b});let N=e=>{if(e===void 0||e===10497)return`repeat`;if(e===33071)return`clamp-to-edge`;if(e===33648)return`mirror-repeat`;throw TypeError(`Invalid texture wrapping; use a glTF sampler constant`)};if(b.magFilter!==void 0&&![9728,9729].includes(b.magFilter)||b.minFilter!==void 0&&![9728,9729,9984,9985,9986,9987].includes(b.minFilter))throw TypeError(`Invalid texture filter; use a glTF sampler constant`);let P={addressModeU:N(b.wrapS),addressModeV:N(b.wrapT),magFilter:b.magFilter===9728?`nearest`:`linear`,minFilter:[9728,9984,9986].includes(b.minFilter)?`nearest`:`linear`,mipmapFilter:[9728,9729,9984,9985].includes(b.minFilter)?`nearest`:`linear`,lodMaxClamp:[9728,9729].includes(b.minFilter)?.25:32};r>1&&d&&(h?j?.levels??1:M)>1&&P.magFilter===`linear`&&P.minFilter===`linear`&&P.mipmapFilter===`linear`&&(P.maxAnisotropy=r);let ee=Object.values(P).join(),F=Ui.get(t);F||Ui.set(t,F=/* @__PURE__ */ new Map);let I=F.get(ee);I||F.set(ee,I=t.createSampler(P)),e.samplers.push(I)}e.baseSources=n}}registerPasses(e){let t=ni.get(e);t||ni.set(e,t=ri()),t.revision!==e.revision&&(t.segment=[]);let n=t;e.add({name:this.name,order:1,joins:!0,execute:e=>{e.backend===`webgpu`&&this.drawSegment(e,n)}}),t.segment.push(this),t.segments.set(this,t.segment),!this.releaseNativeGlass&&this.engine.gpu&&this.materials.some(e=>e.tint||e.attenuation||br(e))&&(this.releaseNativeGlass=S(this.engine,()=>this.glassActive()));let r=this.asset.hooks.transmission;r&&!this.releaseTransmission&&!this.transmission&&this.engine.gpu&&this.asset.doc.materials?.some(e=>!!e?.extensions&&`KHR_materials_transmission`in e.extensions)&&(this.releaseTransmission=r.attach(this,this.engine,e)),t.revision=e.revision}glassActive(){return this.primitives.some(e=>br(e.material)||!this.takesTransparent(e.material)&&yr(e.material))}transmitted(e,t){let n=this.transmission;return!!n&&yr(e)&&n.takes?.(t)!==!1}wantGlass(){if(this.releaseNativeGlass||this.glassQueued||!this.engine.gpu)return;this.glassQueued=!0;let e=this.engine.frameGraph;queueMicrotask(()=>{if(this.glassQueued=!1,!(this.disposed||this.releaseNativeGlass)){for(let t of this.engine.scenes)if(t.frameGraph===e){this.releaseNativeGlass=S(this.engine,()=>this.glassActive(),t);return}}})}drawSegment(e,t){let n=t.segments.get(this),r=0,i;if(n)for(let e of n)!e.disposed&&r++===0&&(i=e);if(r<2)return this.draw(e,`beauty`,e.color,e.depth);if(i!==this)return;let a=t.run;try{for(let t of n)t.disposed||t.draw(e,`beauty`,e.color,e.depth,`all`,void 0,a)}finally{a.end()}}shareImages(){if(this.disposed)throw J(`disposed`,`PBRModel is disposed; load the model again`);return oe(this.images),[...this.images]}rebindStreamed(e){let t=this.engine.gpu;if(this.disposed&&e.users.delete(this),!this.disposed&&t)for(let n of this.resources)n.streamed?.includes(e)&&this.bindMaterial(n,t)}dropTexture(e,t,n){this.gpuCache.delete(t),this.textures.splice(this.textures.indexOf(n),1),Ji(e,n)}async compile(){if(this.disposed)throw J(`disposed`,`PBRModel is disposed; load the model again`);let e=this.engine.renderTarget,t=this.engine.gpu;if(!e||!t)return;this.joinSceneSky(),this.root.matrix[15]||this.engine.store.tick(!1);let n={device:t,format:e.format,descriptor:{multisample:{count:e.samples},depthStencil:{format:e.depthFormat}}},r=/* @__PURE__ */ new Map,i=Ei(void 0,void 0),a=bt(t),o=$r(void 0,`beauty`,void 0,n,void 0,this.transparency,this.capture,this.asset.hooks.materials,this.lightingList);i.compiling=r,i.context=n;for(let e of this.resources){let t=e.primitive,r=t.material;if(t.topology||e.batch||e.mergedInto||this.takesTransparent(r)||this.transmitted(r,n)||!t.instances&&!t.deformed&&!r.shading?.replacesTextures&&!r.maps.some(Boolean))continue;t.node.check();let s=t.node.matrix,c=s[0]*(s[5]*s[10]-s[6]*s[9])-s[4]*(s[1]*s[10]-s[2]*s[9])+s[8]*(s[1]*s[6]-s[2]*s[5]);if(c===0||!Number.isFinite(c))continue;let l=gi(e);this.derive(void 0,o,a,n,`beauty`,i,e,l?`line-list`:void 0,l,c<0?-1:1,void 0,t.instances)}await Promise.all(r.values())}image(e,t=!1){if(this.disposed)throw J(`disposed`,`PBRModel is disposed; load the model again`);if(typeof t!=`boolean`)throw Pe(`Optional image lookup must be boolean; pass true or omit it`,`material`);let n=this.images[R(e,`image`)];if(!n&&!t)throw TypeError(`Missing decoded glTF image; this is a loader bug, report it with the file`);return n}uploadImage(e,t,n=!1){let r=this.image(e);if(`streamed`in r)throw J(`unsupported`,"A streamed texture has no whole image to upload; load the model without `textures`");if(`ktx2`in r||`mipmaps`in r)return Ai(t,`ktx2`in r?r.ktx2:r,n);let i=[r.width,r.height],a=t.createTexture({size:i,format:n?`rgba8unorm-srgb`:`rgba8unorm`,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT});try{return`data`in r?t.queue.writeTexture({texture:a},r.data,{bytesPerRow:r.width*4},i):t.queue.copyExternalImageToTexture({source:r},{texture:a},i),a}catch(e){throw a.destroy(),e}}joinSceneSky(){let e;if(this.sceneSky!==!1&&!this.disposed){let t=this.engine.sceneOf?.(this)?.plugins;for(let n of[`environment:lighting`,`sky`]){let r=t?.get(n);if(r&&typeof r.add==`function`&&typeof r.pbr==`function`&&r.pbr(2)?.ambient){e=r;break}}if(e){for(let t of this.lighting)if(t!==e&&t!==this.joinedSky?.sky&&t.pbr?.(2)?.ambient){e=void 0;break}}}let t=this.joinedSky;(t?.sky!==e||e&&!this.lighting.has(e))&&(t&&(this.joinedSky=void 0,t.release()),e&&!this.lighting.has(e)&&(this.joinedSky={sky:e,release:e.add(this)}))}addLighting(e){if(this.disposed||!e||typeof(e.pbr??e.shader)!=`function`||typeof e.bindings!=`function`)throw TypeError(`Invalid PBR lighting effect; pass the effect made by createLighting for this engine`);if(e.owner&&e.owner!==this.engine)throw J(`attached`,`PBR lighting belongs to another engine; create it with this engine`);return this.lighting.add(e),this.lightingList=[...this.lighting],()=>{this.lighting.delete(e),this.lightingList=this.lighting.size?[...this.lighting]:kr}}takesTransparent(e){let t=this.transparency;return!!t&&(gr(e)||!!t.linearLayers&&Sr(e)||!!t.blends&&!(e.tint&&this.transmission&&!t.depthWrite)&&vr(e)>0)}drawTransparent(e,t){let n=this.transparency;this.transparency=t;try{this.draw(e,`transparent`,e.color,e.depth)}finally{this.transparency=n}}setTransparency(e){if(this.disposed||!e||typeof e.declarations!=`function`||typeof e.bindings!=`function`||typeof e.begin!=`function`||!Array.isArray(e.targets))throw TypeError(`Invalid PBR transparency hook; pass a function, or null to remove the hook`);return this.transparency=e,()=>{this.transparency===e&&(this.transparency=void 0)}}setCapture(e){if(this.disposed||!e||typeof e.declarations!=`function`||typeof e.begin!=`function`||!Array.isArray(e.targets))throw TypeError(`Invalid PBR capture hook; pass a function, or null to remove the hook`);return this.capture=e,()=>{this.capture===e&&(this.capture=void 0)}}setTransmission(e){if(this.disposed||!e||typeof e.declarations!=`function`||typeof e.bindings!=`function`||typeof e.begin!=`function`||!Array.isArray(e.targets))throw TypeError(`Invalid PBR transmission hook; pass a function, or null to remove the hook`);let t=this.releaseTransmission;return t&&this.transmission!==e&&(this.releaseTransmission=void 0,t()),this.transmission=e,()=>{this.transmission===e&&(this.transmission=void 0)}}selectVariant(e){let t=typeof e==`string`?this.variants.indexOf(e):e??-1;if(this.disposed||e!==void 0&&!(Number.isInteger(t)&&t>=0&&t<this.variants.length))throw RangeError(`selectVariant: the model has no material variant ${e}; pass an index below the variant count`);let n=[];for(let e of[...this.primitives,...this.pointsAndLines]){let r=e.definition.extensions?.KHR_materials_variants?.mappings;if(r===void 0)continue;if(!Array.isArray(r))throw TypeError(`Invalid glTF material variant mappings; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let i=this.defaults.get(e)??e.material,a=r.find(e=>Array.isArray(e?.variants)&&e.variants.includes(t)),o=a?Qi(this.asset,e.definition,this.materials[R(a.material,`material`)],!!e.topology,R(a.material,`material`),this.warnings):i;o!==e.material&&n.push([e,o])}let r=this.engine.gpu,i=new Map(this.resources.map(e=>[e.primitive,e]));for(let[e,t]of n){this.defaults.has(e)||this.defaults.set(e,e.material),e.material=t;let n=i.get(e);n&&r&&this.bindMaterial(n,r)}this.selectedVariant=e===void 0?void 0:t}setPrimitiveMaterials(e){if(this.disposed)throw J(`disposed`,`The model is disposed; load a new model before changing materials.`);let t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set([...this.primitives,...this.pointsAndLines]),r=e.map(({primitive:e,material:r})=>{if(!n.has(e)||t.has(e)||r!==void 0&&(!Number.isInteger(r)||r<0||r>=this.materials.length))throw RangeError(`Material changes need unique primitives from this model and valid material indices; check the model material count.`);t.add(e);let i=r===void 0?this.defaults.get(e)??e.material:Qi(this.asset,e.definition,this.materials[r],!!e.topology,r,this.warnings);return[e,i,!e.uvs&&i.maps.some(e=>e&&(e.texCoord??0)>1)?e.part?ke(this.asset,e.definition,e.part.vertexMap):Ae(this.asset,{...e.definition,material:r})[0].uvs:void 0]}),i=new Map(this.resources.map(e=>[e.primitive,e])),a=this.engine.gpu;for(let[e,t,n]of r){if(t===e.material)continue;this.defaults.has(e)||this.defaults.set(e,e.material),e.material=t;let r=i.get(e);n&&(e.uvs=n,r&&a&&(r.uvs=a.createBuffer({size:n.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),a.queue.writeBuffer(r.uvs,0,n))),r&&a&&this.bindMaterial(r,a)}}setAlphaMode(e,t,n=e?.settings?.[1]){if(this.disposed)throw J(`disposed`,`The model is disposed; load a new model before changing its materials.`);let r=[`OPAQUE`,`MASK`,`BLEND`].indexOf(t);if(!this.primitives.some(t=>t.material===e))throw RangeError(`setAlphaMode needs a material one of this model's primitives draws with; pick it from model.primitives`);if(r<0)throw RangeError(`setAlphaMode mode must be 'OPAQUE', 'MASK' or 'BLEND'`);if(t===`MASK`&&!(n>=0&&n<=1))throw RangeError(`setAlphaMode cutoff must be from 0 to 1; pass 0.5 for the glTF default`);e.settings[0]=r,t===`MASK`&&(e.settings[1]=n);let i=this.engine.gpu;if(i)for(let t of this.resources)t.primitive.material===e&&this.bindMaterial(t,i)}setAnisotropy(e,t){if(this.disposed)throw J(`disposed`,`The model is disposed; load a new model before changing its materials.`);if(!this.primitives.some(t=>t.material===e))throw RangeError(`setAnisotropy needs a material one of this model's primitives draws with; pick it from model.primitives`);Di.set(e,B(t));let n=this.engine.gpu;if(n)for(let t of this.resources)t.primitive.material===e&&this.bindMaterial(t,n)}get ownedMeshes(){return this.created}get shadowPrimitives(){let e=[];return this.writeShadowPrimitives(e),e}get tintPrimitives(){let e=[];for(let t=0;t<this.resources.length;t++){let n=this.resources[t],r=n.primitive,i=r.material;if(r.topology||i.settings[0]!==2&&!$t(r))continue;let a={};vi(n,a),a.tint=i.tint??[0,1,2].map(e=>1-i.base[3]*(1-i.base[e])),e.push(a)}return e}get pickingPrimitives(){return this.disposed?[]:this.resources.filter(e=>!e.batch).map(e=>{let t=e.primitive.material,n=t.pickMask,r=n?n.texCoord:t.maps[0]?De(t.maps[0]).texCoord:0,i=r>1?0:t.settings[0]===1?t.settings[1]:t.settings[0]===2?.001:0;return{primitive:e.primitive,node:e.primitive.node,vertex:e.primitive.deformed??e.vertex,vertexOffset:e.primitive.deformed?e.primitive.deformedOffset??0:0,index:e.index,count:e.primitive.indices.length,stride:80,alphaTexture:n?n.view:e.views[0],alphaSampler:n?n.sampler:e.samplers[0],alpha:t.base[3],cutoff:i,side:ai(t),doubleSided:ai(t)===`double`,texCoord:r>1?0:r,...n?{alphaTransform:n.transform}:t.maps[0]?.extensions?.KHR_texture_transform?{alphaTransform:De(t.maps[0]).transform}:{},...n?.opacity?{opacity:n.opacity}:{},...i>0&&t.castAnimation?{animation:t.castAnimation}:{},...(t.vertexAlpha===!1||mi(e))&&i>0?{vertexAlpha:!1}:{},...t.displacement?{displacement:t.displacement}:{},...t.surfaceClip?{clip:t.surfaceClip}:{},...e.primitive.instances?{instances:e.primitive.instances}:{}}})}async readPickingGeometry(){let e=this.engine.gpu,t=this.gpuRevision;if(this.disposed||this.engine.disposed||!e)return[];this.engine.store.tick(!1);let n=new Map(this.primitives.map((e,t)=>[e,t])),r=this.resources.filter(e=>!e.batch).map(e=>({resource:e,primitive:e.primitive,primitiveIndex:n.get(e.primitive),nodeIndex:e.primitive.nodeIndex,deformed:e.primitive.deformed,deformedOffset:e.primitive.deformedOffset??0,matrix:e.primitive.node.matrix.slice(),vertices:e.primitive.deformed?void 0:e.primitive.vertices.slice(),indices:e.primitive.indices.slice(),side:ai(e.primitive.material),doubleSided:ai(e.primitive.material)===`double`,read:void 0}));try{if(this.prepareDeformation||r.some(e=>e.deformed)){let t=e.createCommandEncoder();this.prepareDeformation?.({backend:`webgpu`,device:e,encoder:t});for(let n of r)if(n.deformed){if(!(n.deformed.usage&GPUBufferUsage.COPY_SRC))throw TypeError(`Deformed picking snapshots require COPY_SRC buffers`);let r=n.primitive.vertices.byteLength;if(r>e.limits.maxBufferSize)throw RangeError(`Picking snapshot exceeds device buffer limit; load a smaller model, or reduce its textures and meshes`);n.read=e.createBuffer({label:`PBR picking snapshot`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),t.copyBufferToBuffer(n.deformed,n.deformedOffset,n.read,0,r)}e.queue.submit([t.finish()]),await Promise.all(r.filter(e=>e.read).map(e=>e.read.mapAsync(GPUMapMode.READ)))}return this.disposed||this.engine.disposed||this.engine.gpu!==e||t!==this.gpuRevision||r.some(e=>e.primitive.deformed!==e.deformed||e.deformed&&(e.primitive.deformedOffset??0)!==e.deformedOffset)?[]:r.filter(e=>this.engine.meshes.get(e.primitive.node.id)===e.primitive.node).map(e=>({node:e.primitive.node,matrix:e.matrix,vertices:e.read?new Float32Array(e.read.getMappedRange()).slice():e.vertices,indices:e.indices,doubleSided:e.doubleSided,side:e.side,...e.primitiveIndex===void 0?{}:{primitiveIndex:e.primitiveIndex},...e.nodeIndex>=0?{nodeIndex:e.nodeIndex}:{}}))}catch(n){if(this.disposed||this.engine.disposed||this.engine.gpu!==e||t!==this.gpuRevision||r.some(e=>e.primitive.deformed!==e.deformed||e.deformed&&(e.primitive.deformedOffset??0)!==e.deformedOffset))return[];throw n}finally{for(let{read:e}of r)e&&(e.mapState===`mapped`&&e.unmap(),e.destroy())}}writeShadowPrimitives(e){if(aa.call(this,`shadowPrimitives`)!==sa)return!1;let t=this.shadowBatchLive??=/* @__PURE__ */ new Map;t.clear();let n=e=>{let n=t.get(e);return n===void 0&&t.set(e,n=this.pose(e)),n},r=0;for(let t=0;t<this.resources.length;t++){let i=this.resources[t],a=i.primitive;a.material.settings[0]===2||a.topology||$t(a)||(i.batch?!n(i.batch):i.mergedInto?.batch&&n(i.mergedInto.batch))||(vi(i,e[r]??={}),r++)}return e.length=r,!0}draw(e,t,n,r,i=`all`,a,o){this.joinSceneSky();let s=E(this);if(s){let c=[e,t,n,r,i,a,o];w(this,s,c,()=>{this.draw(...c),o?.pending.length&&qr(o)});return}if(o&&!a&&t===`beauty`&&o.pass&&o.view.at&&o.view.format===e.format){let t=o.quickFor(e);if(!t.opaque&&this.joinRun(e,o,i,t,o.view.at))return;t.viewChecked=!1}let c=t===`transmission`,u=c?this.transmission:this.transparency,d=t===`transparent`||c,p=this.capture,g=t===`capture`,v=Ye(e)?.buffer;if(this.disposed||d&&!u||g&&!p)return;let x=t===`beauty`?Er.get(e):void 0;if(x){if(i===`blend`&&x.delete(this),x.add(this),i===`blend`)return;i=`opaque`}let S=t===`beauty`&&o,T=Ir[Lr]??=Ei(n,r),D=e.camera,O=this.engine.lighting;T.eye.set(D.position);let k=T.viewData,A=o&&!a?o.view:void 0,j;A?.at&&A.format===e.format&&Rr(A.data,D,O)?j=A.at:(k.set(D.matrix),a?k.set(a.view,16):(ot(T.view,D),k.set(T.view,16)),k.set(T.eye,32),k[35]=0,l(k,36,O.direction),k.set(O.radiance,40),k[44]=+y(e.format)),Lr++,f(e.device,e.view??e),T.context=e;let M=bt(e.device),N=o&&!a?o:void 0,P=N?N.bindings:T.bound,ee=d&&!c&&!!u?.linearLayers&&!y(e.format)&&!a,F=$r(N,t,a?.depthCompare,e,v,u,p,this.asset.hooks.materials,this.lightingList);N||Yr(P,void 0),o&&(o.device=e.device);let I=a?.pass??o?.pass,te;try{let s=this.resources;if(!d&&!g){s=T.resources;let e=this.resources,t=!1;for(let n=0;n<e.length;n++)s[n]=e[n],t||=or(e[n]);if(s.length=e.length,t&&s.length>1){let e=T.eye,t=T.blendDistance;t.clear();for(let n=0;n<s.length;n++){let r=s[n];if(!or(r))continue;let i=r.primitive.node.matrix;t.set(r,Math.hypot(e[0]-i[12],e[1]-i[13],e[2]-i[14]))}s.sort(T.compare)}}let l=T.liveBatches;l.size&&l.clear();let f=n=>{let r=l.get(n);return r===void 0&&l.set(n,r=(t!==`beauty`||!Mn(n.material.renderState))&&this.pose(n,e)),r};for(let l=0;l<s.length;l++){let y=s[l];if(y.batch?!f(y.batch):y.mergedInto?.batch&&f(y.mergedInto.batch))continue;let x=y.primitive,C=x.material,w=x.node,E=x.instances,O=!y.batch&&$t(x);if(!y.batch&&!_(e,w)||(x.topology?t!==`beauty`||x.widened:d?O||!(c?yr(C):this.takesTransparent(C)):g?O||ar(C)||C.ext[0]:t===`beauty`&&!O&&(this.takesTransparent(C)||this.transmitted(C,e)))||i!==`all`&&(ar(C)||O)!==(i===`blend`)||(w.check(),!ta(this.engine,w)||E&&!E.count)||!y.batch&&!y.mergedInto&&ra(D.planes,x))continue;if(ee&&br(C)){ee=!1;let t=h(e),n=t?.copy;if(n){let r=t.entries[0].resource;u.linearLayers(()=>(n.call(t,e),r))}else this.wantGlass(),u.linearLayers()}let L=gi(y),R=x.topology??(L?`line-list`:void 0),z=L?.index??y.index,ne=L?.count??x.indices.length,re=E?.upload(e.device),B=E&&!L?x.redirect:void 0,ie=E||L?void 0:x.culled,V=B?.instances??re,H=w.matrix,ae=H[0]*(H[5]*H[10]-H[6]*H[9])-H[4]*(H[1]*H[10]-H[2]*H[9])+H[8]*(H[1]*H[6]-H[2]*H[5]),U=ae<0?-1:1,oe=x.extension;Et(F.lighting,this.lightingList)||(F=$r(N,t,a?.depthCompare,e,v,u,p,this.asset.hooks.materials,this.lightingList));let W=Or(M.derivations.get(C),F,oe,E,R,U,C,!!E&&fi(y)),se=W!==void 0,ce=!!N&&t===`beauty`;if(W||=this.derivation(M,C,F,oe,R,U,e,t,T,y,L,a,E,!ce),ce&&Jr(W,y,ae)){I||(N.pass=I=Ti(e,T,n,r,S),b(I,e)),j||(j=kt(e.device,k,e.view??e,void 0),A.at=j,A.format=e.format,A.data.set(k)),Ur(N,this,y,W,e,j);continue}if(N?.pending.length&&(I&&(N.pass=I),qr(N)),!W.complete)W=this.derivation(M,C,F,oe,R,U,e,t,T,y,L,a,E);else if(se){(y.values.length!==W.floatCount||y.replacesTextures!==W.replacesTextures)&&this.bindMaterial(y,e.device),y.coordinates=void 0,y.extension&&=(m(y.device,y.extension.uniform),void 0);let t=y.values;t.set(W.block),this.nodeRows(y,H,t),t[97]=U}let{pipeline:le,blend:ue,state:de,extension:G,effectBindings:fe}=W,pe=y.uniform.write(y.values,e.view??e);y.sectionBuffer!==v&&(y.groups.clear(),y.copies?.clear(),y.sectionBuffer=v),j||(j=kt(e.device,k,e.view??e,a?this:g?Fr:void 0),A&&(A.at=j,A.format=e.format,A.data.set(k)));let me=y.groups.get(le);me||(me=Ci(e.device,le,y,C,c,F.hooks,v,j),y.groups.set(le,me));let he=me[0];(pe||me.view!==j)&&(he=Si(e.device,le,y,c,v,pe??y.uniform.binding,j));let K;if(W.nativeGlass){let t=h(e);a?I=a.pass=t.reopen(I):(I?.end(),I=void 0,e.settle?.(),t.copy(e))}if(d||g?K=te??=(d?u:p).begin():(!a&&!o&&ue&&t!==`gbuffer`&&(I?.end(),I=void 0),I||(I=Ti(e,T,n,r,S),b(I,e)),K=I),c){let t=C.volume,n=y.volumeData;(!n||n.length!==t.length)&&(y.volumeData=n=new Float32Array(t.length));let r=y.volumeWritten!==y.volume;if(!r)for(let e=0;e<t.length;e++)n[e]!==Math.fround(t[e])&&(r=!0);r&&(n.set(t),e.device.queue.writeBuffer(y.volume,0,n),y.volumeWritten=y.volume)}if(this.disposed)break;if(this.engine.meshes.get(w.id)!==w)continue;P.pass!==K&&Yr(P,K);let ge=x.deformed??y.vertex,_e=x.deformed?x.deformedOffset??0:0;if(W.tint){let t=W.tint,n=W.mappedTint,r=y.groups.get(t);r||(n?r=Ci(e.device,t,y,C,!1,F.hooks,v,j):(r=[bi(e.device,t,y,!1,v,j)],r.view=j),y.groups.set(t,r));let i=pe||r.view!==j?Si(e.device,t,y,!1,v,pe??y.uniform.binding,j):r[0];Xr(P,t),Z(P,0,i),n&&(Z(P,1,r[1]),fe&&Z(P,2,W.tintEffect.group),G&&(Cn(e.device,K,t,y.extension,fe),P.groups[2]=P.groups[3]=void 0)),Qr(P,ge,V,z,_e),Zr(P,y.uvs),jn(K,de),B?K.drawIndexedIndirect(B.args,0):E?K.drawIndexed(ne,E.count):ie?K.drawIndexedIndirect(ie.args,ie.offset):K.drawIndexed(ne)}Xr(P,le),Z(P,0,he),Z(P,1,me[1]),W.effect&&Z(P,2,W.effect.group),G&&(Cn(e.device,K,le,y.extension,fe),P.groups[2]=P.groups[3]=void 0),Qr(P,ge,V,z,_e),Zr(P,y.uvs),jn(K,de),B?K.drawIndexedIndirect(B.args,0):E?K.drawIndexed(ne,E.count):ie?K.drawIndexedIndirect(ie.args,ie.offset):K.drawIndexed(ne),!a&&!o&&ue&&t!==`gbuffer`&&!d&&!g&&(I.end(),I=void 0),(t===`beauty`||d)&&!a&&(this.engine.stats.visible+=Wr(y),this.engine.stats.drawCalls++)}}catch(e){if(!a)try{a||I?.end()}catch{}throw o&&(o.pass=void 0),e}finally{a&&I&&(a.pass=I),C(e.device),Lr--,T.context=void 0,T.code=``;for(let e=0;e<T.effects.length;e++)T.effects[e]=void 0;for(let e=0;e<T.entries.length;e++)T.entries[e]=void 0;T.color.view=T.depth.view=void 0,T.liveBatches.size&&T.liveBatches.clear(),T.blendDistance.size&&T.blendDistance.clear()}o&&!a?o.pass=I:a||I?.end(),o||_t(e.device)}derivation(e,t,n,r,i,a,o,s,c,l,u,d,f,p=!0){let m=e.derivations.get(t),h=-1,g=!!f&&fi(l);if(m)for(let e=0;e<m.length;e++){let t=m[e];if(t.source===r&&t.instances===f&&!!t.white===g&&t.topology===i&&t.sign===a&&Tt(t.frame,n)){h=e;break}}let _=this.derive(h>=0?m[h]:void 0,n,e,o,s,c,l,i,u,a,d,f,p);_.white=g,m||e.derivations.set(t,m=[]),h<0&&(m.length<32&&m.length++,h=m.length-1);for(let e=h;e>0;e--)m[e]=m[e-1];return m[0]=_,_}joinRun(e,t,n,r,i){let a=this.resources;if(this.disposed||a.length!==1||this.staticBatches?.length)return!1;let o=a[0],s=o.primitive,c=s.material,l=s.node;if(o.batch||o.mergedInto||s.instances||s.topology||$t(s))return!1;let u=this.transparency;if(this.takesTransparent(c)||this.transmitted(c,e)||n!==`all`&&ar(c)!==(n===`blend`))return!1;if(!r.viewChecked){if(!Rr(t.view.data,e.camera,this.engine.lighting))return!1;r.viewChecked=!0}if(!_(e,l)||(l.check(),!ta(this.engine,l)))return!0;let d=this.lightingList,f=this.capture,p=this.asset.hooks.materials||void 0,m=r.frame;(!m||r.lighting!==d||r.oit!==u||r.hook!==f||r.hooks!==p)&&(m=$r(t,`beauty`,void 0,e,r.section,u,f,p,d),r.frame=m,r.lighting=d,r.oit=u,r.hook=f,r.hooks=p);let h=l.matrix,g=h[0]*(h[5]*h[10]-h[6]*h[9])-h[4]*(h[1]*h[10]-h[2]*h[9])+h[8]*(h[1]*h[6]-h[2]*h[5]),v=Or(r.draws.derivations.get(c),m,s.extension,void 0,gi(o)?`line-list`:void 0,g<0?-1:1,c);return!v||!Jr(v,o,g)?!1:(Ur(t,this,o,v,e,i),!0)}drawBatch(e,t){let{owner:n,d:r,c:i,members:a,viewAt:o,view:s}=e,c=t.pass,l=t.bindings,u=i.device,d=n.primitive,p=d.material,h=r.topology,_=h?gi(n):void 0,v=_?.count??d.indices.length,y=r.frame,b=y.section;l.pass!==c&&Yr(l,c);let x=0;for(let e=0;e<a.length;e++)x+=Wr(a[e]);this.engine.stats.visible+=x,f(u,s);let S=Ir[Lr]??=Ei(i.color,i.depth);Lr++;try{if(a.length===1){this.drawOwn(n,e,t,S);return}if((n.values.length!==r.floatCount||n.replacesTextures!==r.replacesTextures)&&this.bindMaterial(n,u),e.rows){this.drawRows(e,t,S);return}let f=Mt(r.sign<0),x=bt(u),C=Or(x.derivations.get(p),y,d.extension,f,h,1,p,fi(n))??this.derivation(x,p,y,d.extension,h,1,i,`beauty`,S,n,_,void 0,f),w=C.pipeline;if(!C.modelFree||e.folded&&!this.folds(e,C,f,h,S,x)){for(let n=0;n<a.length;n++)e.models[n].disposed||e.models[n].drawOwn(a[n],e,t,S);return}let T=e.folded?S.tints:void 0;if(T){for(let e=0;e<a.length;e++)T[e]=a[e].primitive.material.base;T.length=a.length}n.sectionBuffer!==b&&(n.groups.clear(),n.copies?.clear(),n.sectionBuffer=b);let E=n.groups.get(w);E||(E=Ci(u,w,n,p,!1,y.hooks,b,o),n.groups.set(w,E));let D,O;{let t=r.blend?void 0:n.batchStates??=/* @__PURE__ */ new Map,i=t?t.get(r):r.blendStates??=[];if(t&&!i){if(t.size>=8)for(let[e,n]of t){for(let e of n)m(u,e.uniform),e.instances.destroy(u);t.delete(e);break}t.set(r,i=[])}let c=S.batchValues.length===C.floatCount?S.batchValues:S.batchValues=new Float32Array(C.floatCount);c.set(C.block),c.fill(0,16,48),c[16]=c[21]=c[26]=c[31]=c[32]=c[37]=c[42]=c[47]=1,c[97]=1,T&&(c[76]=c[77]=c[78]=c[79]=1);let l=S.matrices,d=e.nodes;for(let e=0;e<d.length;e++)l[e]=d[e].matrix;l.length=a.length;let f=g(u,s),p,h,_,v;for(let e of i)if(t)e.view===s?h=e:e.frame===f?!_&&e.uniform.floats===c.length&&e.instances.holds(l,T)&&Vr(e.uniform.contents,c)&&(_=e):v??=e;else if(e.frame!==f){v=e;break}p=h??_??v,p||i.push(p={instances:new Pt,uniform:ht(u,C.floatCount),groups:/* @__PURE__ */ new Map,frame:f,view:s}),p!==_&&(p.frame=f,p.view=s),O=p.instances.write(u,l,T);for(let e=0;e<l.length;e++)l[e]=void 0;if(T)for(let e=0;e<T.length;e++)T[e]=void 0;p.uniform.floats!==C.floatCount&&(m(u,p.uniform),p.uniform=ht(u,C.floatCount),p.groups.clear());let y=p.uniform.write(c,s)??p.uniform.binding;D=xi(p.groups,u,w,n,b,o,y)}Xr(l,w),Z(l,0,D),Z(l,1,E[1]),C.effect&&Z(l,2,C.effect.group),Qr(l,n.vertex,O,_?.index??n.index),jn(c,C.state),c.drawIndexed(v,a.length),this.engine.stats.drawCalls++}finally{C(u),Lr--,S.checked.clear(),S.code=``;for(let e=0;e<S.effects.length;e++)S.effects[e]=void 0;for(let e=0;e<S.entries.length;e++)S.entries[e]=void 0}}drawRows(e,t,n){let{owner:r,d:i,c:a,members:o,viewAt:s,view:c,ds:l}=e,u=a.device,d=r.primitive,f=d.material,p=i.topology,m=p?gi(r):void 0,h=m?.count??d.indices.length,_=i.frame,v=_.section,y=t.bindings,b=t.pass,x=Mt(i.sign<0,!0),S=bt(u),C=Or(S.derivations.get(f),_,d.extension,x,p,1,f,fi(r))??this.derivation(S,f,_,d.extension,p,1,a,`beauty`,n,r,m,void 0,x),w=C.pipeline;if(!C.modelFree||!this.rowsFit(e,C,x,n,S)){for(let r=0;r<o.length;r++)e.models[r].disposed||e.models[r].drawOwn(o[r],e,t,n);return}let T=g(u,c),E=i.blend?void 0:r.rowStates??=/* @__PURE__ */ new Map,D=E?E.get(C):C.blendRows??=[];if(E&&!D){if(E.size>=8)for(let[e,t]of E){for(let e of t)e.rows.destroy(u),e.instances.destroy(u);E.delete(e);break}E.set(C,D=[])}let k,A;for(let e of D){if(E&&e.view===c){k=e;break}e.frame!==T&&(A??=e)}k??=A,k||D.push(k={instances:new Pt,rows:new Nt,groups:/* @__PURE__ */ new Map,textures:/* @__PURE__ */ new Map,frame:T,view:c}),k.frame=T,k.view=c;let j=n.matrices,M=n.blocks,N=n.versions,P=e.nodes;for(let e=0;e<P.length;e++)j[e]=P[e].matrix,M[e]=l[e].block,N[e]=l[e].version??NaN;j.length=M.length=N.length=o.length;let ee=k.instances.write(u,j),F=O(C.floatCount),I=k.rows;I.write(u,M,l,N,C.floatCount,F);for(let e=0;e<o.length;e++)j[e]=M[e]=void 0;k.texturesOf!==r.views&&(k.textures.clear(),k.texturesOf=r.views);let te=k.textures.get(w);te||k.textures.set(w,te=wi(u,w,r,f,_.hooks)),Xr(y,w),Z(y,1,te),C.effect&&Z(y,2,C.effect.group),Qr(y,r.vertex,ee,m?.index??r.index),jn(b,C.state);for(let e=0,t=0;e<o.length;e+=F,t++)Z(y,0,xi(k.groups,u,w,r,v,s,I.bindings[t])),b.drawIndexed(h,Math.min(F,o.length-e),0,0,e),this.engine.stats.drawCalls++}rowsFit(e,t,n,r,i){let a=e.ds,o=e.d,s=o.topology;for(let c=0;c<a.length;c++){let l=a[c];if(l===o)continue;if(l.rowsOf===t&&l.rowsAt===l.version&&l.rowsOfAt===t.version){if(!l.rowsOk)return!1;continue}let u=e.models[c];if(u.disposed)return!1;let d=e.members[c],f=d.primitive,p=f.material,m=Or(i.derivations.get(p),o.frame,f.extension,n,s,1,p,fi(d))??u.derivation(i,p,o.frame,f.extension,s,1,e.c,`beauty`,r,d,s?gi(d):void 0,void 0,n),h=m.pipeline===t.pipeline&&m.modelFree&&m.floatCount===t.floatCount&&m.block.length===l.block.length&&Br(m.effect,t.effect);if(l.rowsOf=t,l.rowsAt=l.version,l.rowsOfAt=t.version,l.rowsOk=h,!h)return!1}return!0}folds(e,t,n,r,i,a){if(!t.tintable)return!1;let o=i.checked;o.clear(),o.add(e.owner.primitive.material);for(let s=0;s<e.members.length;s++){let c=e.members[s],l=c.primitive,u=l.material;if(o.has(u))continue;o.add(u);let d=e.models[s];if(d.disposed)return!1;let f=Or(a.derivations.get(u),e.d.frame,l.extension,n,r,1,u,fi(c))??d.derivation(a,u,e.d.frame,l.extension,r,1,e.c,`beauty`,i,c,r?gi(c):void 0,void 0,n);if(f.pipeline!==t.pipeline||!f.modelFree||!Br(f.effect,t.effect))return!1}return!0}drawOwn(e,t,n,r){let{c:i,viewAt:a,view:o}=t,s=t.d.frame,c=i.device,l=e.primitive,u=l.material,d=l.node.matrix,f=s.section,p=n.bindings,m=n.pass,h=d[0]*(d[5]*d[10]-d[6]*d[9])-d[4]*(d[1]*d[10]-d[2]*d[9])+d[8]*(d[1]*d[6]-d[2]*d[5])<0?-1:1,g=bt(c),_=t.d.topology,v=_?gi(e):void 0,y=Or(g.derivations.get(u),s,l.extension,void 0,_,h,u);y?.complete?(e.values.length!==y.floatCount||e.replacesTextures!==y.replacesTextures)&&this.bindMaterial(e,c):y=this.derivation(g,u,s,l.extension,_,h,i,`beauty`,r,e,v,void 0,void 0);let b=e.values;b.set(y.block),this.nodeRows(e,d,b),b[97]=h;let x=e.uniform.write(b,o),S=y.pipeline;e.sectionBuffer!==f&&(e.groups.clear(),e.copies?.clear(),e.sectionBuffer=f);let C=e.groups.get(S);C||(C=Ci(c,S,e,u,!1,s.hooks,f,a),e.groups.set(S,C)),Xr(p,S),Z(p,0,x||C.view!==a?Si(c,S,e,!1,f,x??e.uniform.binding,a):C[0]),Z(p,1,C[1]),y.effect&&Z(p,2,y.effect.group),Qr(p,e.vertex,void 0,v?.index??e.index),Zr(p,e.uvs),jn(m,y.state),l.culled&&!v?m.drawIndexedIndirect(l.culled.args,l.culled.offset):m.drawIndexed(v?.count??l.indices.length),this.engine.stats.drawCalls++}derive(e,t,n,r,i,a,o,s,c,l,u,f=o.primitive.instances,p=!0){let g=o.primitive,_=g.material,v=g.node,b=i===`transmission`,S=b?this.transmission:this.transparency,C=i===`transparent`||b,w=this.capture,T=i===`capture`,E=t.section,D=_.shading,A=D?.version;if(e?.complete&&A!==void 0&&A===e.version&&e.shading===D&&!t.lighting.length&&!C&&!T&&!(g.extension??_.extension)){(o.values.length!==e.floatCount||o.replacesTextures!==e.replacesTextures)&&this.bindMaterial(o,r.device),o.extension&&=(m(o.device,o.extension.uniform),void 0),e.frame=t;let n=o.values;return n.set(e.block),this.nodeRows(o,v.matrix,n),n[97]=l,e}let j=!!(g.extension??_.extension)?.replacesPhysical||!_.extendedFrame&&!_.physical&&!_.ext?.[0],M=j?100:_.extended?lr(_):220,N=!!g.uvs;(o.values.length!==M||o.replacesTextures!==!!_.shading?.replacesTextures)&&this.bindMaterial(o,r.device);let P=o.values;this.nodeRows(o,v.matrix,P),P.set(_.base,76),P.set(_.factors,80),!_.maps[2]&&!_.extendedFrame&&(P[82]=0),P.set(_.emission,84),P.set(_.settings,88);let ee=ai(_),F=oi(ee);P[90]=s?1:F;for(let e=0;e<5;e++)P[92+e]=j?_.maps[e]?De(_.maps[e]).texCoord:0:e;if(P[97]=l,j||(P.set(_.ext,100),P[103]=_.dispersion??0,P.set(_.uvt,104)),!j&&_.physical){let e=_.extended?lr(_)-36:208;P.set(_.physical,e),!_.maps[7]&&!_.shading?.replacesTextures&&(P[e+2]=0)}if(!j&&_.tint){let e=Cr(_),t=e?_.attenuation:_.tint,n=e?_.opticalDepth:void 0;for(let r=0;r<3;r++){let i=e?n?.[r]??(t[r]===1?0:-Math.log(t[r])):t[r];P[r<2?98+r:102]=e&&i===1/0?-1:i}}let I=g.extension??_.extension,te=!j&&!!(_.maps[2]?De(_.maps[2]).texCoord!==0||De(_.maps[2]).transform:_.extendedFrame&&(P[123]>.5||P[120]!==1||P[121]!==0||P[122]!==0||P[124]!==0||P[125]!==1||P[126]!==0)),L=vt(_.settings[0],P[90],te,!j&&!!_.tint,!!_.physical,!!_.physical&&_.maps.length>5,!!D?.texturedTint,!!D?.replacesTextures,N),R=D?.shaderRevision,z=j&&!f&&!D&&!I&&!_.renderState&&!_.attenuation?si(_,P,c):-1;if(e&&(j?z>=0&&e.plain===z:R!==void 0&&e.revision===R)&&e.shading===D&&e.renderState===_.renderState&&e.structure===L&&e.floatCount===M&&e.compact===j&&!I&&!_.extended&&!t.lighting.length&&!C&&!T&&(!p||e.pipeline!==void 0)){j&&(o.coordinates=void 0),o.extension&&=(m(o.device,o.extension.uniform),void 0),e.frame=t,e.replacesTextures=o.replacesTextures;let i=e.pipeline!==void 0;if(e.complete=i,e.version=NaN,i){let t=e.effect;e.effect=e.effectBindings?this.effectGroup(e,e.pipeline,r,a,D,!1,void 0,e.nativeGlass):void 0,e.tintEffect=Ar(e,e.tint,e.mappedTint,e.effect,r.device),!f&&(!e.group||e.effect!==t)&&(e.group=xt(n,e)),e.version=D?.version}else e.group=void 0;return e.block.set(P),e}let ne=this.asset.hooks.materials||void 0,re=!j&&!_.shading?.replacesTextures&&(_.extended?!!ne:!!_.physical&&_.maps.length>5&&!D&&!I),B=re&&!!ur.get(r.device)?.has(_),ie=j?ue:_.physical?_.maps.length>5?!D&&!I?de(_.maps,B):he():ye():me,V=!j&&_.extended?ne.shader(B?mr(cr(_,ne)):cr(_,ne)):!j&&_.tint?fe(ie):ie,H=i===`beauty`||b?`fragment`:i===`gbuffer`?`gbuffer`:C?`transparent`:T?`capture`:`ambientFragment`,ae=i===`beauty`||C||T;j&&(V=ge(V)),j?(o.coordinates=Oe(_.maps,I,o.coordinates),V=Ee(V,o.coordinates,!!_.maps[2]&&P[94]>=1)):te&&(V=V.replace(`if(abs(i.tangent.w)<0.5)`,`if(true)`));let U=j?o.coordinates?.extension??I:I;if(U?(o.extension=hn(r.device,U,o.extension,this.engine),V=xn(V,U)):o.extension&&=(m(o.device,o.extension.uniform),void 0),!p){let n=!j&&!!_.tint,a=i===`beauty`?_.renderState:void 0,c=e??{};return c.frame=t,c.source=g.extension,c.instances=f,c.topology=s,c.sign=l,c.compact=j,c.floatCount=M,c.replacesTextures=o.replacesTextures,c.extension=U,c.complete=!1,c.structure=void 0,c.plain=-1,c.version=NaN,c.group=void 0,c.blend=_.settings[0]===2||n,c.tinted=n&&a?.blend===void 0,c.nativeGlass=i===`beauty`&&!y(r.format)&&br(_)&&!!h(r),c.state=a,c.block?.length!==P.length&&(c.block=new Float32Array(P.length)),c.block.set(P),c}let oe=U?.lighting!==!1;if(D||i!==`gbuffer`&&oe&&this.lighting.size){a.code=V,a.ambient=!1,D&&Oi.call(a,D);let e=a.code;i!==`gbuffer`&&oe&&this.lighting.forEach(Oi,a),D?.lit&&(a.code=D.lit(a.code));let t=a.code,n=a.ambient;if(ae)V=t;else if(i===`ambient`&&n){let e=this.replays.get(t);e===void 0&&(this.replays.size>=64&&this.replays.clear(),this.replays.set(t,e=t.replace(`return vec4f(color,`,j?`_=color;return vec4f(${bn(U,`margoAmbient`)},`:`_=color;return vec4f(select(${bn(U,`margoAmbient`)},vec3f(0),f.ext.x>0.5),`))),V=e,H=`fragment`,ae=!0}else V=e}(U?.ambient||U?.coat)&&(V=Sn(V,U)),b?V=pe(V,S.declarations(2)):C?V=le(V,S.declarations(2)):T&&(V=be(V,w.declarations(V),U?.coat?.keep),U&&(V=_n(V,U))),f&&(V=f.shader(V)),ee===`back`&&!s&&(V=En(V)),_.shading?.texturedTint?V=K(V):!j&&yr(_)&&Cr(_)&&(V=_e(V)),C&&!b&&this.transparency.blends&&_.tint&&(V=Se(V));let W=i===`beauty`&&!y(r.format),se=W&&!!h(r),ce=W&&br(_),G=se&&(yr(_)&&_.renderState?.blend===void 0||ce);if((ce||this.transmission&&yr(_))&&!se&&!u&&this.wantGlass(),G&&(V=ce?x(V):d(V)),i===`occlusion`){let e=$n(V);V=U?_n(e.code,U):e.code,H=e.entry}E&&(V=$e(V,0,2)),V=Te(V);let xe=Pr.get(V);if(xe===void 0&&(Pr.size>=256&&Pr.clear(),xe=!/\bf\.(model|normalMatrix)\b/.test(V.replaceAll(`let margoI=f.model*`,``)),Pr.set(V,xe)),f instanceof At&&f.rows){let e=k(V,O(M));e?V=e:xe=!1}let Ce=+(!s&&!!f?.mirrored&&F!==1),we=!c&&F!==1&&!Ce?P[97]>0==(ee===`front`)?`back`:`front`:`none`,q=i===`beauty`?_.renderState:void 0;q&&Pn(q,r.descriptor.depthStencil.format);let ke=+(_.settings[0]===1);ke&&(V=qt(V));let Ae=!!q?.alphaToCoverage&&!!ke&&(r.descriptor.multisample?.count??1)>1;Ae&&(V=Nn(V));let je=q?.transmissionBlend??`auto`,Me=je!==`two-draw`&&i===`beauty`&&!C&&!T&&!G&&!j&&!!_.tint&&q?.blend===void 0;if(Me){let e=!!r.device.features?.has(`dual-source-blending`),t=e?ve(V):void 0;if(je===`dual-source`&&!t)throw J(`unsupported`,e?`renderState transmissionBlend 'dual-source' cannot join this surface's tint and lit draws (a shading hook replaced the transmission entry points); use 'auto' or 'two-draw'`:`renderState transmissionBlend 'dual-source' needs a device with 'dual-source-blending'; create the engine with features: ['dual-source-blending'] where the adapter has it, or use 'auto'`);t?(V=t,H=`margoDual`):Me=!1}let Ne=n.codes.get(V);Ne===void 0&&(n.codes.size>=256&&n.codes.clear(),n.codes.set(V,Ne=n.codeCount++));let Pe=!j&&!!_.tint,Y=_.settings[0]===2||Pe,Fe=C&&!b&&this.transparency.blends?vr(_):0,Ie=C&&!b&&!y(r.format)&&!!this.transparency.linearLayers&&br(_),Le=b&&!!S.depthWrite&&_.settings[0]!==2,Re=!Me&&!G&&Pe&&(i===`beauty`||i===`ambient`||Fe===3&&!j&&!this.transparency.depthWrite)&&q?.blend===void 0,ze=Fn(q)+(u?.depthCompare??``)+(U?`:extension`:``),Be=r.descriptor.multisample?.count,Ve=r.descriptor.depthStencil.format,He=!!f&&fi(o),We=i+`:`+r.format+`:`+Y+Pe+`:`+we+`:`+Be+`:`+Ve+`:`+H+`:`+Ne+`:`+ke+ze+(f?`:i`+Ce+`:`+wt(f.layout)+(He?`w`:``):``)+(s?`:`+s:``)+(N?`:uv`:``)+(C||T?`:o`+wt((C?S:w).targets)+`:`+Fe+(Ie?`l`:``)+(Le?`w`:``):``)+(Re&&(D?.texturedTint||Cr(_))?`:t`:``),Ge=n.pipelines.get(We);if(!Ge&&p){if(re&&!B&&wr(r.device,V))return pr(r.device,_),this.derive(e,t,n,r,i,a,o,s,c,l,u,f,p);yi(r.device,V,_,b,this.lighting);let d=Zt(V,He),m=Qe(Ht(N?Wt(d.code):d.code)),h=r.device.createShaderModule({code:m}),g=i===`beauty`?r.format:`rgba16float`,v={layout:`auto`,vertex:{module:h,entryPoint:`vertex`,buffers:[Jt(d),...f?[Xt(d.code,f.layout)]:N?[null]:[],...N?[Ut]:[]]},fragment:{module:h,entryPoint:H,constants:{margoFaceTest:Ce,margoAlphaTest:ke,...C&&!b&&this.transparency.blends?{margoKind:Fe}:{},...Ie?{margoLinear:1}:{}},targets:C||T?Le?S.targets.map(({blend:e,...t})=>t):(C?S:w).targets:i===`occlusion`?[{format:g},{format:g,blend:Y?{color:Pe?{srcFactor:`one`,dstFactor:`one`}:{srcFactor:`src-alpha`,dstFactor:`one-minus-src-alpha`},alpha:{srcFactor:`one`,dstFactor:`one-minus-src-alpha`}}:void 0}]:[{format:g,...q?.colorWrite===!1?{writeMask:0}:{},blend:q?.blend===void 0?Y&&i!==`gbuffer`&&!G?{color:Me?{srcFactor:`one`,dstFactor:`src1`}:Pe?{srcFactor:`one`,dstFactor:`one`}:{srcFactor:`src-alpha`,dstFactor:`one-minus-src-alpha`},alpha:{srcFactor:`one`,dstFactor:`one-minus-src-alpha`}}:void 0:q.blend??void 0}]},multisample:Ae?{...r.descriptor.multisample,alphaToCoverageEnabled:!0}:r.descriptor.multisample,primitive:s?{topology:s}:{topology:`triangle-list`,cullMode:we},depthStencil:{...In(q,!s,u?.depthCompare===`less`||u?.depthCompare===`less-equal`),format:r.descriptor.depthStencil.format,depthWriteEnabled:q?.depthWrite??((i===`beauty`||T)&&!Y||Le||C&&!b&&!!this.transparency.depthWrite),depthCompare:u?.depthCompare??q?.depthCompare??(i===`beauty`||C||T?`greater-equal`:`equal`)}};if(re&&!B&&Ue(r.device,v)?.over)return pr(r.device,_),this.derive(e,t,n,r,i,a,o,s,c,l,u,f,p);let y=V.includes(`margoView.`),x=V.includes(`var margoBaseMaps:`),E=(e,t,r)=>(n.pipelines.size>=4096&&n.pipelines.clear(),n.pipelines.set(e,t),it(t,m,r),y&&Dt.add(t),x&&dr.add(t),t),D=(e,t)=>{a.compiling.has(e)||a.compiling.set(e,r.device.createRenderPipelineAsync(t).then(r=>{n.pipelines.has(e)||E(e,r,t)}))};if(a.compiling?D(We,v):Ge=E(We,r.device.createRenderPipeline(v),v),Re){let e={...v,depthStencil:{...v.depthStencil,depthWriteEnabled:!1,...q&&Ve.includes(`stencil`)?{stencilWriteMask:0}:{}},fragment:{module:h,entryPoint:`margoTint`,constants:_.shading?.texturedTint||Cr(_)?{margoFaceTest:Ce,margoAlphaTest:ke}:void 0,targets:C?S.targets:[{format:g,...q?.colorWrite===!1?{writeMask:0}:{},blend:{color:{srcFactor:`zero`,dstFactor:`src`},alpha:{srcFactor:`zero`,dstFactor:`one`}}}]}};a.compiling?D(We+`:tint`,e):E(We+`:tint`,r.device.createRenderPipeline(e),e)}}if(a.compiling)return;let Ke=G||!!D||ae&&(oe&&this.lighting.size>0||C),qe=Ke&&p?this.effectGroup(e,Ge,r,a,D,ae&&oe,C?S:void 0,G):void 0,Je=Re&&p?n.pipelines.get(We+`:tint`):void 0,Ye=!!D?.texturedTint||Cr(_),Xe=Ar(e,Je,Ye,qe,r.device),Ze=p&&!f&&e?.group&&e.pipeline===Ge&&e.effect===qe?e.group:void 0,X=e??{};return X.nativeGlass=G,X.revision=R,X.plain=z,X.version=p&&!j&&!I&&!_.extended&&!t.lighting.length&&!C&&!T?D?.version:NaN,X.shading=D,X.renderState=_.renderState,X.structure=L,X.frame=t,X.source=g.extension,X.instances=f,X.topology=s,X.sign=l,X.compact=j,X.floatCount=M,X.replacesTextures=o.replacesTextures,X.extension=U,X.pipeline=Ge,X.complete=p,X.tint=Je,X.tinted=Re,X.blend=Y,X.state=q,X.effectBindings=Ke,X.effect=qe,X.tintEffect=Xe,X.mappedTint=Ye,X.modelFree=xe,X.tintable=Nr(V),X.group=p&&!f?Ze??xt(n,X):void 0,X.block?.length!==P.length&&(X.block=new Float32Array(P.length)),X.block.set(P),X}nodeRows(e,t,n){let r=e.nodeCache??=(/* @__PURE__ */ new Float32Array(32)).fill(NaN),i=!0;for(let e=0;i&&e<16;e++)i=r[e]===Math.fround(t[e]);if(!i){let e=Y(t,this.inverse,this.workspace);for(let n=0;n<16;n++)r[n]=t[n],r[16+n]=e?this.inverse[n%4*4+Math.floor(n/4)]:+(n===15);if(!e)for(let e=0;e<3;e++){let n=(e+1)%3*4,i=(e+2)%3*4;r[16+e*4]=t[n+1]*t[i+2]-t[n+2]*t[i+1],r[17+e*4]=t[n+2]*t[i]-t[n]*t[i+2],r[18+e*4]=t[n]*t[i+1]-t[n+1]*t[i]}}n.set(r,16)}effectGroup(e,t,n,r,i,a,o,s=!1){let c=r.entries,l=r.effects,u=0;r.effectCount=0,i&&ki.call(r,i),a&&this.lighting.forEach(ki,r),l.length=r.effectCount;for(let e=0;e<l.length;e++){let t=l[e].bindings();for(let e=0;e<t.length;e++)c[u++]=t[e]}if(o){let e=o.bindings();for(let t=0;t<e.length;t++)c[u++]=e[t]}c.length=u,s&&c.push(...h(n).entries);let d=e?.effect,f=!d||e.pipeline!==t||c.length!==d.entries.length;for(let e=0;!f&&e<c.length;e++){let t=c[e],n=d.entries[e],r=t.resource,i=n.resource;f=t.binding!==n.binding||!(r===i||`buffer`in r&&`buffer`in i&&r.buffer===i.buffer&&r.offset===i.offset&&r.size===i.size)}if(f){let e=c.map(({binding:e,resource:t})=>({binding:e,resource:`buffer`in t?{buffer:t.buffer,offset:t.offset,size:t.size}:t}));d={entries:e,group:at(n.device,t,2,e)}}return d}createRenderer(n){if(this.disposed||this.engine.disposed)throw J(`disposed`,`PBRModel is disposed; load the model again`);for(let e of[...this.primitives,...this.pointsAndLines]){if(e.material.shading&&n!==this.engine.gpu)throw J(`unsupported`,`Cross-device PBR rendering requires recreating local material shading`);if(!pn(e.extension??e.material.extension))throw J(`unsupported`,`Cross-device PBR rendering requires material extension textures given as (device) => view or sampler`)}let r=Object.create(e.prototype);Object.assign(r,{name:this.name+`:device:`+ji++,root:this.root,nodes:this.nodes,primitives:this.primitives.map(e=>({...e,instances:void 0,deformed:void 0,deformedOffset:void 0,culled:void 0})),asset:this.asset,images:this.images,disposed:!1,created:[],resources:[],textures:[],inverse:/* @__PURE__ */ new Float32Array(16),workspace:/* @__PURE__ */ new Float64Array(52),engine:this.engine,cleanupCallbacks:/* @__PURE__ */ new Set,lighting:/* @__PURE__ */ new Set,lightingList:kr,gpuRevision:0,gpuCache:/* @__PURE__ */ new Map,replays:/* @__PURE__ */ new Map,pointsAndLines:this.pointsAndLines.map(e=>({...e,instances:void 0,deformed:void 0,culled:void 0})),lights:this.lights,cameras:this.cameras,variants:this.variants,materials:this.materials,defaults:/* @__PURE__ */ new Map});let i,a=this.createDeformationRenderer,o,s=/* @__PURE__ */ new Map,c=/* @__PURE__ */ new Set,l=(e,t,i)=>{for(let a=0;a<e.length;a++){let o=e[a],l=t[a];if(o.material.shading&&n!==this.engine.gpu)throw J(`unsupported`,`Cross-device PBR rendering requires recreating local material shading`);if(!pn(o.extension??o.material.extension))throw J(`unsupported`,`Cross-device PBR rendering requires material extension textures given as (device) => view or sampler`);if(l.extension=o.extension,l.material!==o.material){let e=l.material,t=r.resources[i+a];l.material=o.material;try{t&&r.bindMaterial(t,n)}catch(t){throw l.material=e,t}}if(l.weights=o.weights,o.instances){let e=s.get(o.instances);e||s.set(o.instances,e=o.instances.createProjection()),l.instances=e,c.add(o.instances)}else l.instances=void 0}},u=()=>{c.clear(),l(this.primitives,r.primitives,0),l(this.pointsAndLines,r.pointsAndLines,this.primitives.length);for(let[e,t]of s)c.has(e)||(t.dispose(),s.delete(e))},d=()=>{if(r.disposed)return;r.disposed=!0;let e=new t;e.run(()=>i?.dispose()).run(()=>o?.release()).run(()=>r.releaseGPU()).run(()=>{for(let e=r.created.length-1;e>=0;e--)r.created[e].dispose()});for(let t of s.values())e.run(()=>t.dispose());s.clear(),e.finish()};try{if(u(),r.setup(this.engine,n),a)i=a(r,n);else if(this.primitives.some(e=>e.deformed))throw J(`unsupported`,`Cross-device deformed PBR rendering requires an isolated deformation renderer`);return wn(n,e=>{if(u(),a!==this.createDeformationRenderer||a&&!i){i?.dispose(),i=void 0;let e=this.createDeformationRenderer;a=void 0,e&&(i=e(r,n)),a=e}if(!a&&this.primitives.some(e=>e.deformed))throw J(`unsupported`,`Cross-device deformed PBR rendering requires an isolated deformation renderer`);i?.prepare(e)},(e,t,i,a)=>{T(this,r);let s={pass:t,view:i,depthCompare:`less-equal`},c=a?.snapshot,l=c&&!y(e.format)?o??=v(n):void 0;l?.install(e,c);try{r.draw(e,`beauty`,e.color,e.depth,`all`,s)}finally{l?.finish(e)}return s.pass},d,e=>this.onDispose(e))}catch(e){throw d(),e}}clusteredLights(){return this.engine.store.tick(!1),this.lights.filter(e=>e.type!==`directional`&&ta(this.engine,e.node)).map(e=>{let t=e.node.matrix,n={position:[t[12],t[13],t[14]],range:e.range??(Math.sqrt(e.intensity*256)||1),color:e.color,intensity:e.intensity};return e.type===`spot`&&Object.assign(n,{direction:[-t[8],-t[9],-t[10]],outerAngle:Math.min(e.outerConeAngle,Math.PI/2-1e-4),innerAngle:Math.min(e.innerConeAngle,Math.PI/2-1e-4)}),n})}extras(){this.engine.store.tick(!1);let e=[];return(this.asset.doc.nodes??[]).forEach((t,n)=>{let r=t.extras;r&&typeof r==`object`&&!Array.isArray(r)&&e.push({node:this.nodes[n],nodeIndex:n,name:this.nodes[n].name,extras:r,matrix:this.nodes[n].matrix.slice()})}),e}onDispose(e){if(typeof e!=`function`)throw TypeError(`Expected cleanup callback`);return this.disposed?(e(),()=>{}):(this.cleanupCallbacks.add(e),()=>this.cleanupCallbacks.delete(e))}releaseGPU(){this.gpuRevision++;let e=new t,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=this.resources[0]?.device??this.engine.gpu;for(let e of this.resources){if(e.batchStates)for(let t of e.batchStates.values())for(let r of t)n.set(r.uniform,e.device),r.instances.buffer&&n.set(r.instances.buffer,e.device);if(e.batchStates=void 0,e.rowStates)for(let t of e.rowStates.values())for(let r of t)r.rows.buffer&&n.set(r.rows.buffer,e.device),r.instances.buffer&&n.set(r.instances.buffer,e.device);e.rowStates=void 0;for(let t of[e.wireframe?.index,e.uniform,e.extension?.uniform,e.volume,e.packedBase])t&&n.set(t,e.device);for(let t of[e.vertex,e.index,e.uvs])t&&r.set(t,e.device)}for(let[t,r]of n)e.run(()=>m(r,t));for(let[t,n]of r)e.run(()=>Ki(n,t));if(i)for(let t of this.textures)e.run(()=>Ji(i,t));for(let t of[...this.primitives,...this.pointsAndLines])t.buffers=void 0,e.run(()=>t.instances?.dispose());this.resources=[],this.textures=[],this.gpuCache.clear(),e.finish()}onDeviceRestored(e){this.releaseGPU();for(let e of this.primitives)e.deformed=e.deformedOffset=void 0;this.setup(e)}dispose(){if(this.disposed)return;this.disposed=!0;let e=new t;e.run(()=>this.releaseNativeGlass?.()),this.releaseNativeGlass=void 0,e.run(()=>this.releaseTransmission?.()),this.releaseTransmission=void 0;for(let e of this.created)i(e),Reflect.deleteProperty(e,ii);let n=this.joinedSky;this.joinedSky=void 0,n&&e.run(n.release),this.lighting.clear(),this.lightingList=kr;let r=this.engine.sceneOf(this);r?e.run(()=>this.engine.removePlugin(this.name,r)):e.run(()=>this.engine.frameGraph.removeOwner(this.name));for(let t of this.cleanupCallbacks)e.run(t);this.cleanupCallbacks.clear(),e.run(()=>this.releaseGPU());for(let t=this.created.length-1;t>=0;t--)e.run(()=>this.created[t].dispose());e.run(()=>H(this.images)),e.finish()}[Symbol.dispose??Symbol()](){this.dispose()}destroy(){this.dispose()}},aa=Reflect.get(Object.prototype,`__lookupGetter__`);function oa(e){return Object.getOwnPropertyDescriptor(e.prototype,`shadowPrimitives`).get}var sa=/* @__PURE__ */ oa(ia);function ca(e,t,n=[],r=[],i={},{maxNodes:a,maxPartVertices:o,maxAnisotropy:s}={}){let c;try{let l=P(o),u=B(s),{doc:d,binary:f}=re(t),p=new ae(d,n,f,i,void 0,a);return p.partVertices=l,V.set(p,u),c=new ia(e,p,r),je(e).use(c),c}catch(e){throw c?c.dispose():H(r),e}}function la(e,t,n,r=[],{maxNodes:i,maxPartVertices:a}={}){let o;try{let s=P(a);if(te(t),t.buffers?.length||t.skins?.length||t.animations?.length||t.nodes?.some(e=>e.skin!==void 0)||!Array.isArray(n)||n.length!==t.meshes?.length)throw TypeError(`Prepared PBR requires a static scene`);let c=new ae(t,[],void 0,{},void 0,i);return c.partVertices=s,o=new ia(e,c,r,n),je(e).use(o),o}catch(e){throw o?o.dispose():H(r),e}}async function ua(e,t,r={}){let i=n(e);return _a(e,await I(t,{...r,decoders:{...r.decoders,...r.draco?{draco:r.draco}:{},...r.ktx2?{ktx2:r.ktx2}:{}}},void 0,{device:je(e).gpu??void 0,ktx2:r.ktx2}),r.signal,i)}async function da(e,t,r,i=[],a={}){r===void 0&&(r=arguments.length<4?{}:[]);let o=n(e);if(!Array.isArray(r)){let n=r;return _a(e,await I(void 0,{...n,decoders:{...n.decoders,...n.draco?{draco:n.draco}:{},...n.ktx2?{ktx2:n.ktx2}:{}}},t,{device:je(e).gpu??void 0,ktx2:n.ktx2}),n.signal,o)}let s,c;try{a.signal?.throwIfAborted();let n=B(a.maxAnisotropy),{doc:o,binary:l}=re(t,ie(a.maxDownloadBytes));s=new ae(o,r??[],l,await M(o,a.decoders),a.maxDownloadBytes,a.maxNodes),s.partVertices=P(a.maxPartVertices),V.set(s,n),await an(s),a.optimize&&(s.reorder=await F()),await s.prepareMeshopt(),N(s)?await(await import(`./compression-CUOCmjmE.js`)).decompressPrimitives(s,{...a,draco:a.draco??a.decoders?.draco}):a.signal?.throwIfAborted(),c=await L(s,i??[],{...a,ktx2:a.ktx2??a.decoders?.ktx2,device:je(e).gpu??void 0})}catch(e){throw H(i??[]),e}return _a(e,{asset:s,images:c},a.signal,o)}var fa=/* @__PURE__ */ new WeakMap,pa=e=>Float32Array.from([...e.lighting.direction,...e.lighting.radiance.subarray(0,3)]);function ma(e,{clustered:t,exposure:n=1}={}){if(!Number.isFinite(n)||n<0)throw RangeError(`applyGLTFLights: exposure must be a finite number >= 0`);let r=e.engine,i=e.lights.find(e=>e.type===`directional`&&ta(r,e.node)),a=fa.get(r),o=pa(r),s=a?.applied.every((e,t)=>e===o[t]);if(i){r.store.tick(!1);let t=i.node.matrix,c=Math.hypot(t[8],t[9],t[10])||1;r.lighting.direction.set([t[8]/c,t[9]/c,t[10]/c,i.intensity*n]),r.lighting.radiance.set(i.color),fa.set(r,{owner:new WeakRef(e),baseline:s?a.baseline:o,applied:pa(r)})}else a?.owner.deref()===e&&(s&&(r.lighting.direction.set(a.baseline.subarray(0,4)),r.lighting.radiance.set(a.baseline.subarray(4))),fa.delete(r));if(!t)return()=>{};let c=e.clusteredLights();for(let e of c)e.intensity*=n;return t.setLights(c),t.add(e)}var ha=/* @__PURE__ */ new WeakSet;function ga(e,t=0){let n=typeof t==`number`?e.cameras[t]:t;if(!n)throw RangeError(`viewGLTFCamera: the model has no glTF camera ${t}; pass an index below the camera count`);let r=e.engine,i=r.camera;r.store.tick(!1);let a=n.node.matrix,o=Math.hypot(a[8],a[9],a[10])||1,s=Math.hypot(a[4],a[5],a[6])||1;if(i.position=[a[12],a[13],a[14]],i.target=[a[12]-a[8]/o,a[13]-a[9]/o,a[14]-a[10]/o],i.up=[a[4]/s,a[5]/s,a[6]/s],n.type===`perspective`){let e=n.perspective;i.fov=e.yfov*180/Math.PI,i.near=e.znear,e.zfar!==void 0&&(i.far=e.zfar),i.project&&ha.has(i.project)&&(i.project=void 0)}else{let{ymag:e,znear:t,zfar:r}=n.orthographic,a=r-t;i.near=t,i.far=r,i.project=(n,i,o)=>{n[0]=1/(Math.abs(e)*i),n[5]=1/Math.abs(e),n[10]=o?1/a:-2/a,n[14]=o?r/a:-(r+t)/a,n[15]=1},ha.add(i.project)}}async function _a(e,t,n,r){try{await an(t.asset)}catch(e){throw H(t.images),e}let i=r.run(()=>va(e,t,n));try{return await r.run(()=>i.attachSplats(n)),await r.run(()=>i.attachStrokes(n)),i}catch(e){throw i.dispose(),e}}function va(e,{asset:t,images:n},r){let i;try{return r?.throwIfAborted(),i=new ia(e,t,n),je(e).use(i),i}catch(e){throw i?i.dispose():H(n),e}}export{ca as a,Mi as c,en as d,ua as i,ga as l,ia as n,da as o,ma as r,la as s,ti as t,rn as u};
@@ -1 +1 @@
1
- import{a as e,c as t,n,s as r,t as i}from"./model-iRvuj19h.js";import{o as a,t as o}from"./asset-1b8ejkZX.js";import{r as s}from"./texture-coordinates-XFsEMdU6.js";export{o as GLTFAsset,i as PBRDrawRun,n as PBRModel,a as closeImages,e as parseGLTF,r as parsePreparedPBR,s as textureCoordinates,t as textureTransform};
1
+ import{a as e,c as t,n,s as r,t as i}from"./model-C77ATxi1.js";import{s as a,t as o}from"./asset-DN3ocEdY.js";import{r as s}from"./texture-coordinates-XFsEMdU6.js";export{o as GLTFAsset,i as PBRDrawRun,n as PBRModel,a as closeImages,e as parseGLTF,r as parsePreparedPBR,s as textureCoordinates,t as textureTransform};
package/dist/model.d.ts CHANGED
@@ -17,6 +17,8 @@ export type { PBRDeviceDrawOptions, PBRDeviceRenderer, PBRDeformationRenderer }
17
17
  import type { PBRInstances } from './pbr-instancing.js';
18
18
  import { type StaticBatch } from './coalesce.js';
19
19
  export { GLTFAsset, closeImages } from './asset.js';
20
+ export type { GLTFWarning } from './warning.js';
21
+ import { type GLTFWarning } from './warning.js';
20
22
  export type { GLTFDocument } from './asset.js';
21
23
  export type { GLTFImage, GLTFPixelImage, GLTFStreamedImage, GLTFStreamSource, GLTFTextureOpener, KTX2Image, } from './asset.js';
22
24
  export { textureCoordinates } from './texture-coordinates.js';
@@ -296,6 +298,12 @@ export interface PBRMaterial extends GLTFMaterial {
296
298
  * texels equal to the opacity. The material carries it, so a shadow package bundles no hash WGSL of its own.
297
299
  */
298
300
  castHashed?: (code: string) => string;
301
+ /**
302
+ * With `castHashed`, the share of the light reaching the surface that it stops, above 0 and at most 1: the hashed
303
+ * caster keeps this share of the texels its opacity keeps (`@margoengine/materials` `hair()`, whose fibres pass part
304
+ * of the light on). Default 1: an opaque surface stops all of it.
305
+ */
306
+ castShare?: number;
299
307
  /** False when the material's colour pass reads white for vertex colours (`@margoengine/materials` `vertexColors`). */
300
308
  vertexAlpha?: boolean;
301
309
  /** Use the retained UV-transform frame layout for constructed optional materials. */
@@ -352,6 +360,11 @@ export interface PBRPrimitive {
352
360
  };
353
361
  /** Set for glTF POINTS (`point-list`) and LINES, LINE_LOOP, LINE_STRIP (`line-list`, as index pairs); absent for triangles. */
354
362
  topology?: 'point-list' | 'line-list';
363
+ /**
364
+ * True once a point or line primitive that asks for a width is drawn wide by `decoders.strokes` (@margoengine/points
365
+ * or @margoengine/lines), which then draws it in place of the model's 1 px draw. Read only.
366
+ */
367
+ widened?: boolean;
355
368
  /**
356
369
  * Set when the primitive's definition has more vertices than `maxPartVertices`: this is part `index` of `count`, all
357
370
  * with the same node, material and definition. `vertexMap` holds the definition's vertex for each local vertex:
@@ -414,6 +427,16 @@ export interface PBRRenderState {
414
427
  * both are the same. The transparency hook (OIT) does not read this option.
415
428
  */
416
429
  blendSpace?: 'display' | 'linear';
430
+ /**
431
+ * How a transmissive surface (KHR_materials_transmission without a transmission pass) tints what is behind it on the
432
+ * beauty pass. 'two-draw' multiplies the target by the tint in one draw, then adds the lit surface in a second.
433
+ * 'dual-source' draws once: the fragment writes the lit colour and the tint as WebGPU's two blend sources (feature
434
+ * `dual-source-blending`, colour `one` + `src1`), so each layer of the surface filters the layers already drawn
435
+ * behind it, with no rounding of the target between the two steps. 'auto' (default) is 'dual-source' on a device
436
+ * created with that feature (`features: ['dual-source-blending']`) and 'two-draw' elsewhere. 'dual-source' on a
437
+ * device without it throws MargoError `unsupported`.
438
+ */
439
+ transmissionBlend?: 'auto' | 'two-draw' | 'dual-source';
417
440
  }
418
441
  export { validatePreparedGeometry };
419
442
  interface DrawResource {
@@ -444,6 +467,11 @@ interface DrawResource {
444
467
  copies?: Map<GPUBuffer, Map<GPUBufferBinding | undefined, Map<GPURenderPipeline, GPUBindGroup>>>;
445
468
  sectionBuffer?: GPUBuffer;
446
469
  views: GPUTextureView[];
470
+ /**
471
+ * The texture each map slot binds, beside `views` (undefined for a slot it does not own or a streamed view): what a
472
+ * scene record reads for a map's size and format, since `textures` holds the uploads in creation order.
473
+ */
474
+ maps?: (GPUTexture | undefined)[];
447
475
  samplers: GPUSampler[];
448
476
  packedBase?: PackedBaseTextures;
449
477
  baseSources?: BaseTextureSource[];
@@ -585,6 +613,8 @@ export declare class PBRModel implements EnginePlugin {
585
613
  readonly asset: GLTFAsset;
586
614
  private readonly images;
587
615
  private releaseNativeGlass?;
616
+ /** Remover of the default screen-space transmission pass (`decoders.transmission`), set once the model joins a graph. */
617
+ private releaseTransmission?;
588
618
  /** True while an acquisition asked for during a frame waits for the frame to end (`wantGlass`). */
589
619
  private glassQueued;
590
620
  /** Optional scene-wide opaque phase, used by caller-owned color captures. */
@@ -614,6 +644,8 @@ export declare class PBRModel implements EnginePlugin {
614
644
  /** The file's `MSFT_lod` objects; `LOD.fromModel` from `@margoengine/lod` drives them. Empty without the extension. */
615
645
  readonly lods: GLTFLOD[];
616
646
  readonly cameras: GLTFCamera[];
647
+ /** Problems in the file the loader worked around, each listed once (`code` says which; KB-GLTFA A2). */
648
+ readonly warnings: GLTFWarning[];
617
649
  /**
618
650
  * glTF POINTS, LINES, LINE_LOOP and LINE_STRIP primitives (`topology` set), drawn in the beauty pass only: no shadows,
619
651
  * SSAO, SSR or transparency hook. Kept out of `primitives`, which picking, BVH, outlines, walk collisions and exporters
@@ -642,6 +674,8 @@ export declare class PBRModel implements EnginePlugin {
642
674
  private relative?;
643
675
  private engine;
644
676
  private readonly cleanupCallbacks;
677
+ /** Point and line primitives that ask for a width, for `attachStrokes`. */
678
+ private readonly strokeCandidates;
645
679
  /** @internal The mesh primitives `decoders.splats` reads in place of drawing them. */
646
680
  readonly splatPrimitives: {
647
681
  primitive: GLTFPrimitive;
@@ -651,11 +685,13 @@ export declare class PBRModel implements EnginePlugin {
651
685
  splats: readonly GLTFSplatCloud[];
652
686
  private readonly lighting;
653
687
  /**
654
- * Lit by the image-based light of its scene's `Sky` (`@margoengine/sky`, the scene's `'sky'` plugin): diffuse light
655
- * and reflections blurred by each material's roughness, as core meshes get it, without `sky.add(model)`. It joins on
656
- * the next draw once the sky has an ambient (`lighting.ambient` or `environment`) and leaves when the sky does. An
657
- * ambient given to the model itself (`environment.add(model)`, light probes, another sky) takes its place, as on core
658
- * meshes. Set false to keep the built-in ambient. Default true.
688
+ * Lit by the image-based light of its scene, as core meshes are, without `lighting.add(model)` or `sky.add(model)`:
689
+ * the scene's `EnvironmentLighting` (`@margoengine/environment`, the `'environment:lighting'` plugin) when it has
690
+ * one, else its `Sky`'s (`@margoengine/sky`, the `'sky'` plugin, with `lighting.ambient` or `environment`). Diffuse
691
+ * light and reflections blurred by each material's roughness. It joins on the next draw once that light is ready and
692
+ * leaves when it does. An ambient given to the model itself (`lighting.add(model)`, light probes, another sky) takes
693
+ * its place, as on core meshes. An EnvironmentLighting attached under another `name` is not joined; add it to the
694
+ * model. Set false to keep the built-in ambient. Default true.
659
695
  */
660
696
  sceneSky: boolean;
661
697
  /** The scene sky this model joined by itself (`sceneSky`), and its remover. */
@@ -687,6 +723,11 @@ export declare class PBRModel implements EnginePlugin {
687
723
  * A node hidden by KHR_node_visibility, or under a hidden node, gives no cloud.
688
724
  */
689
725
  attachSplats(signal?: AbortSignal): Promise<void>;
726
+ /**
727
+ * @internal Hands the points and lines that ask for a width to `decoders.strokes`, which draws them wide in place of
728
+ * the model's 1 px draw until the model is disposed. The loaders call it.
729
+ */
730
+ attachStrokes(signal?: AbortSignal): Promise<void>;
690
731
  /** Borrowed GPU buffers, preserving one record per primitive and current deformation. */
691
732
  get raw(): {
692
733
  primitive: PBRPrimitive;
@@ -774,6 +815,12 @@ export declare class PBRModel implements EnginePlugin {
774
815
  * layer a transparency hook takes reads it in the hook's composite (KB3148d).
775
816
  */
776
817
  private glassActive;
818
+ /**
819
+ * Whether the transmission hook draws `m` in this view. A hook whose `takes(c)` is false (no scene source: an
820
+ * environment probe face, an external renderer pass, an XR view without a capture) leaves `m` on the tinted blend, so
821
+ * nothing disappears (KB4000).
822
+ */
823
+ private transmitted;
777
824
  /**
778
825
  * KB3148b: a draw found a linear-blend material and no capture (the option was set after the model joined the frame
779
826
  * graph, or the model draws for the materials queue). Plugins cannot join a frame graph while it runs, so the capture
@@ -845,6 +892,32 @@ export declare class PBRModel implements EnginePlugin {
845
892
  primitive: PBRPrimitive;
846
893
  material: number | undefined;
847
894
  }[]): void;
895
+ /**
896
+ * Changes a material's glTF alpha mode after load, as if the file had said it: `'OPAQUE'`, `'MASK'` cut at `cutoff`
897
+ * (default the material's own), or `'BLEND'`. The primitives that use it bind their textures again, so the base
898
+ * colour map's mip chain is the new mode's own: a MASK chain keeps its cut-out coverage per level (Castano 2010,
899
+ * "Computing Alpha Mipmaps"), which scales alpha up and so would overstate a blend's coverage; a BLEND chain averages
900
+ * colour by alpha. Writing `material.settings[0]` alone keeps the chain the material loaded with.
901
+ * @example
902
+ * const stubble = model.primitives.find((p) => p.material.name === 'Beard_Transparency')!.material;
903
+ * model.setAlphaMode(stubble, 'BLEND'); // fibres finer than a pixel blend as their coverage
904
+ * @throws RangeError for a material this model does not draw, an unknown mode or a cutoff outside 0 to 1.
905
+ */
906
+ setAlphaMode(material: PBRMaterial, mode: 'OPAQUE' | 'MASK' | 'BLEND', cutoff?: number): void;
907
+ /**
908
+ * Samples one material's textures with up to `maxAnisotropy` taps along a pixel's footprint (an integer from 1 to 16),
909
+ * above the asset's own `maxAnisotropy`, on its trilinear samplers with more than one mip. A surface seen at a grazing
910
+ * angle covers a long, thin footprint in its texture; trilinear filtering takes the mip that fits the long side, which
911
+ * blurs the short side too (Williams, "Pyramidal Parametrics", SIGGRAPH 1983), and anisotropic filtering takes several
912
+ * samples of a finer mip along the long side instead (Heckbert, "Fundamentals of Texture Mapping and Image Warping",
913
+ * 1989; McCormack, Perry, Farkas and Jouppi, "Feline", SIGGRAPH 1999). Hair and lash cards are such surfaces: seen
914
+ * nearly edge on, their alpha's strands and gaps average into one sheet. The primitives that use it bind again.
915
+ * @example
916
+ * const hair = model.primitives.find((p) => p.material.name === 'Hair_Transparency')!.material;
917
+ * model.setAnisotropy(hair, 16); // strands stay strands on cards seen edge on
918
+ * @throws RangeError for a material this model does not draw; MargoError `unsupported` for a level outside 1 to 16.
919
+ */
920
+ setAnisotropy(material: PBRMaterial, maxAnisotropy: number): void;
848
921
  /**
849
922
  * Every mesh this model made and will dispose: `root`, `nodes` and the meshes of its baked batches. A mesh you
850
923
  * parented to a node is yours and is not here. `@margoengine/save/engine` reads it to tell the two apart.
@@ -972,8 +1045,12 @@ export declare class PBRModel implements EnginePlugin {
972
1045
  /** @deprecated Use dispose(); kept as an alias until 1.0. */
973
1046
  destroy(): void;
974
1047
  }
975
- /** Synchronous parse of in-memory JSON/GLB with decoded `images`; `decoders` takes only the synchronous `instancing` reader, `meshopt` decoder and `materials` shaders; `maxNodes` and `maxPartVertices` as for loadGLTF. */
976
- export declare function parseGLTF(instance: EngineKernel, input: string | object | ArrayBuffer | ArrayBufferView, buffers?: Array<ArrayBuffer | ArrayBufferView>, images?: readonly GLTFImage[], decoders?: Pick<GLTFDecoderHooks, 'instancing' | 'materials' | 'meshopt'>, { maxNodes, maxPartVertices }?: Pick<AssetOptions, 'maxNodes' | 'maxPartVertices'>): PBRModel;
1048
+ /**
1049
+ * Synchronous parse of in-memory JSON/GLB with decoded `images`; `decoders` takes only the synchronous `instancing` reader, `meshopt` decoder, `materials` shaders and `transmission` pass; `maxNodes` and `maxPartVertices` as for loadGLTF.
1050
+ * The call takes `images` (KB-GLTFA A9): the model closes each `ImageBitmap` at `dispose()`, and a parse that throws
1051
+ * closes them before it throws, whatever failed. Pass `model.shareImages()` or bitmaps you will not use again.
1052
+ */
1053
+ export declare function parseGLTF(instance: EngineKernel, input: string | object | ArrayBuffer | ArrayBufferView, buffers?: Array<ArrayBuffer | ArrayBufferView>, images?: readonly GLTFImage[], decoders?: Pick<GLTFDecoderHooks, 'instancing' | 'materials' | 'meshopt' | 'transmission'>, { maxNodes, maxPartVertices, maxAnisotropy }?: Pick<AssetOptions, 'maxNodes' | 'maxPartVertices' | 'maxAnisotropy'>): PBRModel;
977
1054
  /** A static scene whose geometry is already packed (as @margoengine/blender's .margo); `maxNodes` and `maxPartVertices` as for loadGLTF. */
978
1055
  export declare function parsePreparedPBR(instance: EngineKernel, doc: GLTFAsset['doc'], geometry: readonly (readonly PreparedPrimitive[])[], images?: readonly GLTFImage[], { maxNodes, maxPartVertices }?: Pick<AssetOptions, 'maxNodes' | 'maxPartVertices'>): PBRModel;
979
1056
  /**
@@ -0,0 +1,19 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import"@margoengine/core/extension";import{MargoError as e}from"@margoengine/math/errors";function t(e){return e?.view?.viewport}function n(e,n){let r=t(n);if(!r)return;e.setViewport(r[0],r[1],r[2],r[3],0,1);let i=n.view.scissor??r;e.setScissorRect(i[0],i[1],i[2],i[3])}function r(){return globalThis[Symbol.for(`margoengine.layers`)]}function i(e){return r()?.maskOf(e)??1}function a(e,t){let n=e?.view?.layers;return n===void 0||(i(t)&n)!==0}var o=(globalThis[Symbol.for(`margoengine.frame-resources`)]??={devices:/* @__PURE__ */ new WeakMap}).devices;function s(e){let t=o.get(e);return t||(o.set(e,t={frame:0,open:!1,lost:!1,views:/* @__PURE__ */ new Set,drawing:0,retired:[],written:/* @__PURE__ */ new WeakMap}),e.lost?.then?.(()=>{t.lost=!0;let e=t.retired;t.retired=[];for(let t of e)t.destroy()})),t}function c(e,t){let n=s(e);return n.open||(n.open=!0,n.frame++,queueMicrotask(n.close??=()=>{if(n.open=!1,n.views.clear(),!n.retired.length)return;let e=n.retired;n.retired=[];for(let t of e)t.destroy()})),t&&n.views.add(t),n.frame}function l(e){let t=o.get(e);return!!t?.open&&t.views.size>1}function u(e,t){c(e,t),s(e).drawing++}function d(e){s(e).drawing--}function f(e,t){if(!t)return;let n=s(e),r=[t,...n.written.get(t)?.extras??[]];if(n.written.delete(t),!n.lost&&n.open&&(n.views.size>1||n.drawing>0))n.retired.push(...r);else for(let e of r)e.destroy()}var p=`@vertex fn vertex(@builtin(vertex_index) i:u32)->@builtin(position) vec4f {return vec4f(array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i],0,1);}`,m=Symbol.for(`margoengine.optional.msaa`);p+``;function h(e){let t=e[m];return t?.color===e.color&&t.depth===e.depth?t:void 0}function g(t,n){if(t.backend===`webgl2`||!t.gpu)throw new e(`unsupported`,`${n} needs WebGPU; see https://margoengine.com/errors#webgpu`)}var _=e=>typeof e==`string`&&e.endsWith(`float`),v=/* @__PURE__ */ new WeakMap,y=/* @__PURE__ */ new WeakMap,b=`@group(0) @binding(0) var source:texture_2d<f32>;
5
+ @vertex fn vertex(@builtin(vertex_index) k:u32)->@builtin(position) vec4f {
6
+ return vec4f(vec2f(f32((k<<1u)&2u),f32(k&2u))*2.0-1.0,0,1);
7
+ }
8
+ @fragment fn fragment(@builtin(position) p:vec4f)->@location(0) vec4f {return textureLoad(source,vec2i(p.xy),0);}`,x=126,S=class{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);name=`materials:native-glass`;users=/* @__PURE__ */ new Set;constructor(e){this.engine=e}setup(e){g(e,`Native glass capture`),this.device=e.gpu}registerPasses(e){e.add({name:this.name+`:begin`,order:-40,execute:e=>this.begin(e)}),e.add({name:this.name+`:present`,order:29,execute:e=>this.present(e,!1)}),e.add({name:this.name+`:present-nested`,order:10000.5,execute:e=>this.present(e,!0)})}begin(e){if(e.backend!==`webgpu`||_(e.format)||![...this.users].some(e=>e()))return;c(e.device,e.view??e);let t=e.descriptor.multisample?.count??1,n=[e.width,e.height,e.format,t,e.descriptor.depthStencil.format].join(`:`);if(this.key!==n){this.release();try{this.key=n;let r=t=>e.device.createTexture({size:[e.width,e.height],format:t,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING});this.color=r(e.format),this.snapshot=r(e.format),this.view=this.snapshot.createView(),this.entries=[{binding:x,resource:this.view}],t===4&&(this.multisample=e.device.createTexture({size:[e.width,e.height],format:e.format,sampleCount:4,usage:GPUTextureUsage.RENDER_ATTACHMENT})),this.colorView=(this.multisample??this.color).createView(),this.resolution={label:`native-glass:resolve`,colorAttachments:[{view:this.colorView,resolveTarget:this.color.createView(),loadOp:`load`,storeOp:`store`}]};let i=e.device.createShaderModule({code:b}),a=t=>e.device.createRenderPipeline({layout:`auto`,vertex:{module:i,entryPoint:`vertex`},fragment:{module:i,entryPoint:`fragment`,targets:[{format:e.format}]},multisample:{count:t}});this.copyPipeline=a(1),this.presentPipeline=a(t);let o=t=>e.device.createBindGroup({layout:t.getBindGroupLayout(0),entries:[{binding:0,resource:this.color.createView()}]});this.copyGroup=o(this.copyPipeline),this.presentGroup=o(this.presentPipeline)}catch(e){throw this.release(),e}}y.set(e,this),this.redirected=!h(e),this.redirected&&(this.original=e.color,e.color=this.colorView)}copy(e){let t=h(e);t?.resolve(e.encoder),!t&&this.multisample&&e.encoder.beginRenderPass(this.resolution).end();let n=t?.resolvedColor??this.color,r=n===this.color?this.copyGroup:e.device.createBindGroup({layout:this.copyPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:n.createView()}]}),i=e.encoder.beginRenderPass({label:`native-glass:copy`,colorAttachments:[{view:this.view,loadOp:`clear`,storeOp:`store`}]});i.setPipeline(this.copyPipeline),i.setBindGroup(0,r),i.draw(3),i.end()}resolved(e,t=!0){if(y.get(e)===this&&this.redirected&&e.color===this.colorView)return t&&this.multisample&&e.encoder.beginRenderPass(this.resolution).end(),this.color}present(e,t){if(!(y.get(e)!==this||!t&&this.redirected&&e.color!==this.colorView)){if(this.redirected){this.multisample&&e.encoder.beginRenderPass(this.resolution).end();let t=e.encoder.beginRenderPass({label:`native-glass:present`,colorAttachments:[{view:this.original,loadOp:`load`,storeOp:`store`}]});t.setPipeline(this.presentPipeline),t.setBindGroup(0,this.presentGroup),n(t,e),t.draw(3),t.end(),e.color=this.original}y.delete(e)}}release(){for(let e of[this.color,this.multisample,this.snapshot])f(this.device,e);this.color=this.multisample=this.snapshot=this.key=void 0}onDeviceRestored(e){this.release(),this.setup(e)}dispose(){this.release();let e=this.engine.sceneOf(this);e&&this.engine.removePlugin(this.name,e)}};function C(e,t,n){let r=(n??e).frameGraph,i=v.get(r);return i||(i=new S(e),n?e.use(i,n):e.use(i),v.set(r,i)),i.users.add(t),()=>{i.users.delete(t),i.users.size||(v.delete(r),i.dispose())}}function w(e){return y.get(e)}var T=class{constructor(e){this.device=e}install(e,t){let n=[e.width,e.height,e.format].join(`:`);this.key!==n&&(this.release(),this.snapshot=e.device.createTexture({label:`native-glass:external-snapshot`,size:[e.width,e.height],format:e.format,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST}),this.entries=[{binding:x,resource:this.snapshot.createView()}],this.key=n),this.hook=t,y.set(e,this)}reopen(e){let t=this.hook(e,this.snapshot);if(!t||typeof t.setPipeline!=`function`)throw TypeError(`PBR glass snapshot hook returned no render pass; end the pass, write the colour into target, then return the reopened pass`);return t}finish(e){y.get(e)===this&&y.delete(e),this.hook=void 0}release(){f(this.device,this.snapshot),this.snapshot=this.entries=this.key=void 0}};function E(e){return new T(e)}function D(e){let t=/@fragment fn margoTint\(i:Out,@builtin\(front_facing\) front:bool\)/.test(e),n=/let s=surface\(i,front\);return ([^;]+);/.exec(e)?.[1]??`margoGlassShare(i${t?`,front`:``})`;return e.replace(/@fragment fn margoTint\(i:Out(?:,@builtin\(front_facing\) front:bool)?\)->@location\(0\) vec4f \{/,`fn margoGlassShare(i:Out${t?`,front:bool`:``})->vec4f {`).replace(/fn margoTintEncode\(share:vec3f\)->vec4f \{[^}]+\}/,`fn margoTintEncode(share:vec3f)->vec4f {return vec4f(share,1);}`).replace(`return vec4f(color,`,`color=margoGlassEncode(margoGlassLinear(color)+margoGlassLinear(textureLoad(margoGlassScene,vec2i(i.clip.xy),0).rgb)*${n}.rgb);return vec4f(color,`).replace(`return vec4f(color,select(1.0,s.base.a,f.settings.x>1.5));`,`let glassAlpha=select(1.0,s.base.a,f.settings.x>1.5);return vec4f(color,glassAlpha+textureLoad(margoGlassScene,vec2i(i.clip.xy),0).a*(1.0-glassAlpha));`)+`
9
+ @group(2) @binding(${x}) var margoGlassScene:texture_2d<f32>;
10
+ fn margoGlassLinear(c:vec3f)->vec3f {let x=max(c,vec3f(0));return select(x/12.92,pow((x+0.055)/1.055,vec3f(2.4)),x>vec3f(0.04045));}
11
+ fn margoGlassEncode(c:vec3f)->vec3f {let x=max(c,vec3f(0));return select(x*12.92,1.055*pow(x,vec3f(1.0/2.4))-0.055,x>vec3f(0.0031308));}`}var O=/@fragment fn fragment\(((?:[^()]|\([^()]*\))*)\)->@location\(0\) vec4f \{/;function k(e){let t=O.exec(e);if(!t||O.test(e.slice(t.index+t[0].length)))throw TypeError(`blendSpace 'linear' needs exactly one PBR fragment entry returning vec4f; this material's shader has none, so use blendSpace 'display' with it`);let n=t[1].split(`,`).map(e=>e.replace(/@builtin\([^)]*\)\s*/,``).trim()),r=n.map(e=>e.slice(0,e.indexOf(`:`)).trim()).join(`,`);return e.slice(0,t.index)+`fn margoBlendSurface(${n.join(`,`)})->vec4f {`+e.slice(t.index+t[0].length)+`
12
+ @group(2) @binding(${x}) var margoGlassScene:texture_2d<f32>;
13
+ fn margoGlassLinear(c:vec3f)->vec3f {let x=max(c,vec3f(0));return select(x/12.92,pow((x+0.055)/1.055,vec3f(2.4)),x>vec3f(0.04045));}
14
+ fn margoGlassEncode(c:vec3f)->vec3f {let x=max(c,vec3f(0));return select(x*12.92,1.055*pow(x,vec3f(1.0/2.4))-0.055,x>vec3f(0.0031308));}
15
+ ${t[0]}
16
+ let margoBlendSrc=margoBlendSurface(${r});let margoBlendA=clamp(margoBlendSrc.a,0.0,1.0);
17
+ let margoBlendDst=textureLoad(margoGlassScene,vec2i(${r.split(`,`)[0]}.clip.xy),0);
18
+ return vec4f(margoGlassEncode(margoGlassLinear(margoBlendSrc.rgb)*margoBlendA+margoGlassLinear(margoBlendDst.rgb)*(1.0-margoBlendA)),margoBlendA+margoBlendDst.a*(1.0-margoBlendA));
19
+ }`}export{D as a,u as c,l as d,f,w as i,c as l,a as m,E as n,_ as o,n as p,k as r,h as s,C as t,d as u};