@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
@@ -1,4 +1,4 @@
1
- import{n as e}from"./errors-THVaUwlL.js";import{a as t,i as n}from"./shader-DPqfUcmp.js";import{r}from"./texture-coordinates-XFsEMdU6.js";import{extendedMaterials as i}from"./extended.js";var a=`KHR_materials_pbrSpecularGlossiness`,o=(e,t)=>{if(typeof e!=`number`||!Number.isFinite(e)||e<0||e>1)throw TypeError(`Invalid glTF spec/gloss ${t}; pass a finite number from 0 to 1`);return e},s=(e,t,n)=>{if(!Array.isArray(e)||e.length!==t||Array.from(e).some(e=>typeof e!=`number`))throw TypeError(`Invalid glTF spec/gloss ${n}; pass ${t} finite components from 0 to 1`);return Array.from(e,e=>o(e,n))},c=e=>{if(e!==void 0){if(!e||typeof e!=`object`||Array.isArray(e)||!Number.isSafeInteger(e.index)||e.index<0)throw TypeError(`Invalid glTF spec/gloss texture; pass a textureInfo with a nonnegative integer index`);return r(e),e}};function l(e=[1,1,1,1],t=[1,1,1],n=1){let r=s(e,4,`diffuse`),i=s(t,3,`specular`),a=e=>Math.sqrt(.299*e[0]**2+.587*e[1]**2+.114*e[2]**2),c=a(r),l=a(i),u=1-Math.max(...i),d=c*u/.96+l-.08,f=l<.04?0:Math.min(1,Math.max(0,(-d+Math.sqrt(d*d-.16*(.04-l)))/.08));return{baseColor:[...i.map((e,t)=>{let n=r[t]*u/(.96*Math.max(1-f,1e-6)),i=(e-.04*(1-f))/Math.max(f,1e-6);return Math.min(1,Math.max(0,n*(1-f*f)+i*f*f))}),r[3]],metallic:f,roughness:1-o(n,`glossiness`)}}function u(e){let t=e.extensions?.[a];if(t===void 0)return e;if(!t||typeof t!=`object`||Array.isArray(t))throw TypeError(`Invalid glTF spec/gloss extension; pass a material extension object`);let n=t,r=s(n.diffuseFactor===void 0?[1,1,1,1]:n.diffuseFactor,4,`diffuse`),i=s(n.specularFactor===void 0?[1,1,1]:n.specularFactor,3,`specular`),l=o(n.glossinessFactor===void 0?1:n.glossinessFactor,`glossiness`);return{...e,pbrMetallicRoughness:{baseColorFactor:r,baseColorTexture:c(n.diffuseTexture),roughnessFactor:l,metallicFactor:0},extensions:{...e.extensions,KHR_materials_specular:{specularColorFactor:i.map(e=>e*25),specularColorTexture:c(n.specularGlossinessTexture)},KHR_materials_ior:{ior:1.5}}}}var d=`
1
+ import{a as e,o as t}from"./shader-C29RtPAw.js";import{r as n}from"./texture-coordinates-XFsEMdU6.js";import{extendedMaterials as r}from"./extended.js";import{margoError as i}from"@margoengine/core/extension";var a=`KHR_materials_pbrSpecularGlossiness`,o=(e,t)=>{if(typeof e!=`number`||!Number.isFinite(e)||e<0||e>1)throw TypeError(`Invalid glTF spec/gloss ${t}; pass a finite number from 0 to 1`);return e},s=(e,t,n)=>{if(!Array.isArray(e)||e.length!==t||Array.from(e).some(e=>typeof e!=`number`))throw TypeError(`Invalid glTF spec/gloss ${n}; pass ${t} finite components from 0 to 1`);return Array.from(e,e=>o(e,n))},c=e=>{if(e!==void 0){if(!e||typeof e!=`object`||Array.isArray(e)||!Number.isSafeInteger(e.index)||e.index<0)throw TypeError(`Invalid glTF spec/gloss texture; pass a textureInfo with a nonnegative integer index`);return n(e),e}};function l(e=[1,1,1,1],t=[1,1,1],n=1){let r=s(e,4,`diffuse`),i=s(t,3,`specular`),a=e=>Math.sqrt(.299*e[0]**2+.587*e[1]**2+.114*e[2]**2),c=a(r),l=a(i),u=1-Math.max(...i),d=c*u/.96+l-.08,f=l<.04?0:Math.min(1,Math.max(0,(-d+Math.sqrt(d*d-.16*(.04-l)))/.08));return{baseColor:[...i.map((e,t)=>{let n=r[t]*u/(.96*Math.max(1-f,1e-6)),i=(e-.04*(1-f))/Math.max(f,1e-6);return Math.min(1,Math.max(0,n*(1-f*f)+i*f*f))}),r[3]],metallic:f,roughness:1-o(n,`glossiness`)}}function u(e){let t=e.extensions?.[a];if(t===void 0)return e;if(!t||typeof t!=`object`||Array.isArray(t))throw TypeError(`Invalid glTF spec/gloss extension; pass a material extension object`);let n=t,r=s(n.diffuseFactor===void 0?[1,1,1,1]:n.diffuseFactor,4,`diffuse`),i=s(n.specularFactor===void 0?[1,1,1]:n.specularFactor,3,`specular`),l=o(n.glossinessFactor===void 0?1:n.glossinessFactor,`glossiness`);return{...e,pbrMetallicRoughness:{baseColorFactor:r,baseColorTexture:c(n.diffuseTexture),roughnessFactor:l,metallicFactor:0},extensions:{...e.extensions,KHR_materials_specular:{specularColorFactor:i.map(e=>e*25),specularColorTexture:c(n.specularGlossinessTexture)},KHR_materials_ior:{ior:1.5}}}}var d=`
2
2
  fn margoSpecGloss(d:vec3f,s:vec3f)->vec4f {
3
3
  let weights=vec3f(0.299,0.587,0.114);
4
4
  let db=sqrt(dot(d*d,weights)); let sb=sqrt(dot(s*s,weights));
@@ -8,7 +8,7 @@ fn margoSpecGloss(d:vec3f,s:vec3f)->vec4f {
8
8
  let bs=(s-vec3f(0.04*(1-metal)))/max(metal,0.000001);
9
9
  return vec4f(clamp(mix(bd,bs,metal*metal),vec3f(0),vec3f(1)),metal);
10
10
  }
11
- `,f={extensions:[a],convert:u,parse(e){let t=i.parse(e);return e[a]===void 0?t:{features:{iridescence:!1,anisotropy:!1,diffuseTransmission:!1,...t?.features,specularGlossiness:!0},maps:t?.maps??Array(8).fill(void 0),rows:t?.rows??Array(24).fill(0)}},plan:n,shader(n){let r=t(n);if(!n.specularGlossiness)return r;let i=n.slots[12],a=i>=0?`textureSample(margoMap${i},margoSampler${i},uv(i,12)).a`:`1.0`,o=` return s;`;if(r.split(o).length!==2)throw e(`failed`,`Spec/gloss surface conversion anchor changed; update the optional material shader`);return d+r.replace(o,`
11
+ `,f={extensions:[a],convert:u,parse(e){let t=r.parse(e);return e[a]===void 0?t:{features:{iridescence:!1,anisotropy:!1,diffuseTransmission:!1,...t?.features,specularGlossiness:!0},maps:t?.maps??Array(8).fill(void 0),rows:t?.rows??Array(24).fill(0)}},plan:e,shader(e){let n=t(e);if(!e.specularGlossiness)return n;let r=e.slots[12],a=r>=0?`textureSample(margoMap${r},margoSampler${r},uv(i,12)).a`:`1.0`,o=` return s;`;if(n.split(o).length!==2)throw i(`failed`,`Spec/gloss surface conversion anchor changed; update the optional material shader`);return d+n.replace(o,`
12
12
  if(f.ext.x<0.5){
13
13
  let converted=margoSpecGloss(s.base.rgb,s.f0);
14
14
  s.base=vec4f(converted.rgb,s.base.a); s.metal=converted.a;
package/dist/splats.js CHANGED
@@ -1 +1 @@
1
- import{n as e}from"./errors-THVaUwlL.js";import{t}from"./scene-scope-CZDEkd24.js";var n=`KHR_gaussian_splatting`,r=`KHR_gaussian_splatting_compression_spz_2`,i=5126,a=[3,5,7],o=3e6,s=.2820947917738781,c=[[i,!1],[5120,!0],[5122,!0]],l=[[i,!1],[5121,!1],[5121,!0],[5123,!1],[5123,!0]],u=[[i,!1],[5121,!0],[5123,!0]],d=[[i,!1]],f=e=>/* @__PURE__ */ TypeError(`Invalid glTF ${n} ${e}; the file is not valid, re-export it and check it with the glTF Validator`),p=t=>t.catch(t=>{throw e(`unsupported`,`${n} needs @margoengine/splats (${t instanceof Error?t.message:t}): install it, or pass decoders: {splats: false} for the point cloud fallback`)});function m(e,t,n,r,i,a){let o=t[n];if(o===void 0)throw f(`primitive: ${n} is missing`);let s=e.doc.accessors?.[o];if(!i.some(([e,t])=>e===s?.componentType&&t===!!s?.normalized))throw f(`accessor for ${n}: componentType ${s?.componentType}${s?.normalized?` normalized`:``}`);let c=e.accessor(o,r);if(s?.count!==a)throw f(`accessor for ${n}: its count differs from POSITION`);return c}async function h(t,i,{signal:o}={}){let s=i.extensions?.[n],h=i.attributes??{};if(!s||typeof s!=`object`||Array.isArray(s))throw f(`extension`);if(i.mode!==0)throw f(`primitive: its mode must be POINTS`);let{kernel:g=`ellipse`,colorSpace:_=`srgb_rec709_display`}=s;if(g!==`ellipse`)throw e(`unsupported`,`${n} kernel ${g} is not supported; re-export the file with "ellipse"`);if(_!==`srgb_rec709_display`&&_!==`lin_rec709_display`)throw e(`unsupported`,`${n} color space ${_} is not supported; re-export the file in rec709`);let{parseSpz:v,splatsFromAttributes:y}=await p(import(`@margoengine/splats/data`));o?.throwIfAborted();let b=s.extensions?.[r];if(b){if(_!==`srgb_rec709_display`)throw f(`primitive: SPZ colour is srgb_rec709_display`);return v(t.view(b.bufferView),{signal:o})}let x=t.accessor(h.POSITION,`VEC3`),S=x.length/3,C=(e,r,i)=>m(t,h,`${n}:${e}`,r,i,S),w=C(`ROTATION`,`VEC4`,c),T=C(`SCALE`,`VEC3`,l),E=C(`OPACITY`,`SCALAR`,u),D=C(`SH_DEGREE_0_COEF_0`,`VEC3`,d),O=[],k=!1;a.forEach((e,t)=>{let r=Array.from({length:e},(e,n)=>`SH_DEGREE_${t+1}_COEF_${n}`),i=r.filter(e=>`${n}:${e}`in h).length;if(i&&(i!==e||k))throw f(`primitive: spherical harmonics degree ${t+1}`);if(i)for(let e of r)O.push(C(e,`VEC3`,d));else k=!0});let A={count:S,positions:x,logScales:T.map(Math.log),rotations:new Float32Array(S*4),dc:D,alphas:E};for(let e=0;e<S;e++)A.rotations[e*4]=w[e*4+3],A.rotations.set(w.subarray(e*4,e*4+3),e*4+1);if(O.length){let e=new Float32Array(S*O.length*3);O.forEach((t,n)=>{for(let r=0;r<S;r++)e.set(t.subarray(r*3,r*3+3),(r*O.length+n)*3)}),A.rest=e}return y(A,{linear:_===`lin_rec709_display`})}var g=e=>e.sphericalHarmonics?e.sphericalHarmonics.length/(e.positions.length/3)/3:0;function _(e,t){let n=g(e);if(n===t)return e;let r=e.positions.length/3,i=new Float32Array(r*t*3);for(let a=0;a<r;a++)if(n)i.set(e.sphericalHarmonics.subarray(a*n*3,(a+1)*n*3),a*t*3);else for(let n=0;n<3;n++)i[a*t*3+n]=(e.colors[a*4+n]-.5)/s;return{...e,sphericalHarmonics:i}}function v({positions:e}){let t=new Float32Array([1/0,1/0,1/0,-1/0,-1/0,-1/0]);for(let n=0;n<e.length;n+=3)for(let r=0;r<3;r++)t[r]=Math.min(t[r],e[n+r]),t[r+3]=Math.max(t[r+3],e[n+r]);return t}var y={async attach(e,n,r,i){let a=t(e),{Splats:s,mergeSplats:c,transformSplats:l}=await p(import(`@margoengine/splats`)),u=[];for(let{primitive:e,matrix:t}of r)u.push(l(await h(n,e,{signal:i}),t));let d=Math.max(...u.map(g)),f=[],m=o;for(let e of u){let t=e.positions.length/3;m+t>o&&(f.push([]),m=0),f[f.length-1].push(d?_(e,d):e),m+=t}let y=[];try{for(let t of f){i?.throwIfAborted();let n=t.length>1?c(...t):t[0],r=new s(n);a.run(()=>e.use(r)),y.push({cloud:r,bounds:v(n)})}}catch(e){for(let{cloud:e}of y)e.dispose();throw e}return y}};export{y as gaussianSplats,h as readGaussianSplats};
1
+ import{t as e}from"./scene-scope-CZDEkd24.js";import{margoError as t}from"@margoengine/core/extension";var n=`KHR_gaussian_splatting`,r=`KHR_gaussian_splatting_compression_spz_2`,i=5126,a=[3,5,7],o=3e6,s=.2820947917738781,c=[[i,!1],[5120,!0],[5122,!0]],l=[[i,!1],[5121,!1],[5121,!0],[5123,!1],[5123,!0]],u=[[i,!1],[5121,!0],[5123,!0]],d=[[i,!1]],f=e=>/* @__PURE__ */ TypeError(`Invalid glTF ${n} ${e}; the file is not valid, re-export it and check it with the glTF Validator`),p=e=>e.catch(e=>{throw t(`unsupported`,`${n} needs @margoengine/splats (${e instanceof Error?e.message:e}): install it, or pass decoders: {splats: false} for the point cloud fallback`)});function m(e,t,n,r,i,a){let o=t[n];if(o===void 0)throw f(`primitive: ${n} is missing`);let s=e.doc.accessors?.[o];if(!i.some(([e,t])=>e===s?.componentType&&t===!!s?.normalized))throw f(`accessor for ${n}: componentType ${s?.componentType}${s?.normalized?` normalized`:``}`);let c=e.accessor(o,r);if(s?.count!==a)throw f(`accessor for ${n}: its count differs from POSITION`);return c}async function h(e,i,{signal:o}={}){let s=i.extensions?.[n],h=i.attributes??{};if(!s||typeof s!=`object`||Array.isArray(s))throw f(`extension`);if(i.mode!==0)throw f(`primitive: its mode must be POINTS`);let{kernel:g=`ellipse`,colorSpace:_=`srgb_rec709_display`}=s;if(g!==`ellipse`)throw t(`unsupported`,`${n} kernel ${g} is not supported; re-export the file with "ellipse"`);if(_!==`srgb_rec709_display`&&_!==`lin_rec709_display`)throw t(`unsupported`,`${n} color space ${_} is not supported; re-export the file in rec709`);let{parseSpz:v,splatsFromAttributes:y}=await p(import(`@margoengine/splats/data`));o?.throwIfAborted();let b=s.extensions?.[r];if(b){if(_!==`srgb_rec709_display`)throw f(`primitive: SPZ colour is srgb_rec709_display`);return v(e.view(b.bufferView),{signal:o})}let x=e.accessor(h.POSITION,`VEC3`),S=x.length/3,C=(t,r,i)=>m(e,h,`${n}:${t}`,r,i,S),w=C(`ROTATION`,`VEC4`,c),T=C(`SCALE`,`VEC3`,l),E=C(`OPACITY`,`SCALAR`,u),D=C(`SH_DEGREE_0_COEF_0`,`VEC3`,d),O=[],k=!1;a.forEach((e,t)=>{let r=Array.from({length:e},(e,n)=>`SH_DEGREE_${t+1}_COEF_${n}`),i=r.filter(e=>`${n}:${e}`in h).length;if(i&&(i!==e||k))throw f(`primitive: spherical harmonics degree ${t+1}`);if(i)for(let e of r)O.push(C(e,`VEC3`,d));else k=!0});let A={count:S,positions:x,logScales:T.map(Math.log),rotations:new Float32Array(S*4),dc:D,alphas:E};for(let e=0;e<S;e++)A.rotations[e*4]=w[e*4+3],A.rotations.set(w.subarray(e*4,e*4+3),e*4+1);if(O.length){let e=new Float32Array(S*O.length*3);O.forEach((t,n)=>{for(let r=0;r<S;r++)e.set(t.subarray(r*3,r*3+3),(r*O.length+n)*3)}),A.rest=e}return y(A,{linear:_===`lin_rec709_display`})}var g=e=>e.sphericalHarmonics?e.sphericalHarmonics.length/(e.positions.length/3)/3:0;function _(e,t){let n=g(e);if(n===t)return e;let r=e.positions.length/3,i=new Float32Array(r*t*3);for(let a=0;a<r;a++)if(n)i.set(e.sphericalHarmonics.subarray(a*n*3,(a+1)*n*3),a*t*3);else for(let n=0;n<3;n++)i[a*t*3+n]=(e.colors[a*4+n]-.5)/s;return{...e,sphericalHarmonics:i}}function v({positions:e}){let t=new Float32Array([1/0,1/0,1/0,-1/0,-1/0,-1/0]);for(let n=0;n<e.length;n+=3)for(let r=0;r<3;r++)t[r]=Math.min(t[r],e[n+r]),t[r+3]=Math.max(t[r+3],e[n+r]);return t}var y={async attach(t,n,r,i){let a=e(t),{Splats:s,mergeSplats:c,transformSplats:l}=await p(import(`@margoengine/splats`)),u=[];for(let{primitive:e,matrix:t}of r)u.push(l(await h(n,e,{signal:i}),t));let d=Math.max(...u.map(g)),f=[],m=o;for(let e of u){let t=e.positions.length/3;m+t>o&&(f.push([]),m=0),f[f.length-1].push(d?_(e,d):e),m+=t}let y=[];try{for(let e of f){i?.throwIfAborted();let n=e.length>1?c(...e):e[0],r=new s(n);a.run(()=>t.use(r)),y.push({cloud:r,bounds:v(n)})}}catch(e){for(let{cloud:e}of y)e.dispose();throw e}return y}};export{y as gaussianSplats,h as readGaussianSplats};
@@ -0,0 +1,4 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const _=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import{t as e}from"./node-matrix-R9BipGnp.js";import{a as t,c as n,d as r,l as i,o as a,s as o,t as s,u as c}from"./version-B6NE5cJf.js";import{n as l,t as u}from"./limits-_LZ441oV.js";import{t as d}from"./scene-scope-CZDEkd24.js";import{n as f,r as p,t as m}from"./accessor-CU_1uSZ1.js";import{Geometry as h,PbrMaterial as g,engineRuntime as __margoRuntime,fault as v,margoError as y,rangeError as b,typeError as x}from"@margoengine/core/extension";var S=`version https://git-lfs`;function C(e,t){if(!(e.length<23)){for(let t=0;t<23;t++)if((typeof e==`string`?e.charCodeAt(t):e[t])!==S.charCodeAt(t))return;throw v(`failed`,`${t} is a Git LFS pointer file, not the asset; run git lfs pull and serve the real file`,`git-lfs`)}}var w=67108864,T=e=>y(`unsupported`,`${e} over the light loader's 64 MiB; use @margoengine/gltf/pbr (512 MiB by default) or loadAuto`),E=e=>!!e&&typeof e==`object`&&!Array.isArray(e);function D(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{throw x(`Invalid glTF JSON: not UTF-8`,`gltf-invalid`)}}function O(e){try{return c(e)}catch(e){throw x(`Invalid glTF JSON: ${e.message}`,`gltf-invalid`)}}function k(e){return e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function A(e){if(typeof e==`string`){if(C(e,`The glTF input`),e.length>w||new TextEncoder().encode(e).length>w)throw RangeError(`glTF JSON exceeds 64 MiB; load a smaller file or split it`);return{doc:O(e)}}if(!(e instanceof ArrayBuffer)&&!ArrayBuffer.isView(e))return{doc:e};let n=k(e);if(C(n,`The glTF input`),n.length>w)throw RangeError(`GLB exceeds 64 MiB; load a smaller file or split it`);let r=a(n),i=O(D(r[0].data)),o=r[1]?.type===5130562?r[1].data:void 0,s=i.buffers?.[0];return o&&s&&typeof s==`object`&&s.uri===void 0&&t(o.length,s.byteLength),{doc:i,binary:o}}function j(e){let t=/^data:application\/(?:octet-stream|gltf-buffer);base64,([A-Za-z0-9+/]*={0,2})$/.exec(e);if(!t||t[1].length>89478489.33333333)throw TypeError(`Invalid glTF data URI; use a base64 data URI`);let n;try{n=atob(t[1])}catch{throw TypeError(`Invalid glTF data URI; use a base64 data URI`)}return Uint8Array.from(n,e=>e.charCodeAt(0))}function M(e,t,n){let r=l(`maxNodes`,t);if(!e||!s(e.asset))throw TypeError(`Expected glTF 2.0`);for(let t of[`buffers`,`bufferViews`,`accessors`,`meshes`,`nodes`,`scenes`,`materials`,`skins`,`animations`,`extensionsRequired`])if(e[t]!==void 0&&!Array.isArray(e[t]))throw TypeError(`glTF ${t} must be an array`);for(let t of[`buffers`,`bufferViews`,`accessors`,`meshes`,`nodes`,`scenes`,`materials`]){let n=e[t];if(Array.isArray(n)&&!n.every(E))throw x(`Invalid glTF ${t} entry`,`gltf-invalid`)}if(e.extensionsRequired?.some(e=>!n.some(t=>t.handles.includes(e)))||e.skins?.length||e.animations?.length)throw v(`unsupported`,`Skins, animations and required extensions need @margoengine/gltf/pbr`,`gltf-light`);u(`Too many glTF nodes`,e.nodes?.length??0,r,`maxNodes`)}function N(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 x(`Invalid glTF ${n} on node ${t}: ${r} finite numbers`,`gltf-transform`)}}function P(t,n,r){if(n.matrix!==void 0){if(n.translation!==void 0||n.rotation!==void 0||n.scale!==void 0||!Array.isArray(n.matrix)||n.matrix.length!==16||n.matrix.some(e=>typeof e!=`number`||!Number.isFinite(Math.fround(e))))throw x(`Invalid glTF matrix`,`gltf-invalid`);let i=n.matrix;if(i[3]!==0||i[7]!==0||i[11]!==0||i[15]!==1)throw TypeError(`glTF matrix must be affine`);let a=e(i);if(!a.ok)throw a.reason===`singular`?/* @__PURE__ */ RangeError(`Singular glTF matrix`):x(`Sheared glTF matrix on node ${r}`,`gltf-transform`);t.setPosition(a.position).setScale(a.scale).setQuaternion(a.rotation)}else N(n,r),t.setPosition(n.translation??[0,0,0]).setScale(n.scale??[1,1,1]).setQuaternion(n.rotation??[0,0,0,1])}var F=(e,t)=>e.some(e=>e.handles.some(e=>t?.extensions?.[e]!==void 0)),I=(e,t,n,r)=>{let i=e.buffers[t];if(n.some(e=>e.handles.some(e=>i.extensions?.[e]?.fallback===!0)))return!0;let a=(e.bufferViews??[]).filter(e=>e.buffer===t);return!r&&i.uri===void 0&&a.length>0&&a.every(e=>F(n,e))};function L(e,t,{maxNodes:n,extensions:r=[]}){let{doc:i,binary:a}=A(e);M(i,n,r);let o=0;return{doc:i,buffers:(i.buffers??[]).map((e,n)=>{let s=f(e.byteLength,`buffer length`,1);if(I(i,n,r,(t[n]?.byteLength??0)>0||n===0&&!!a&&!e.uri))return/* @__PURE__ */ new Uint8Array;let c=t[n]?k(t[n]):e.uri?j(e.uri):n===0?a:void 0;if(!c||s>c.length)throw RangeError(`Truncated glTF buffer; download the file again, it is incomplete`);if(o+=c.length,o>w)throw T(`glTF buffers are`);return c.subarray(0,s)}),maxNodes:n}}function R(e,t,{maxNodes:n,extensions:r=[]}){let i=_(e);for(let e of r)e.read?.(t);let{doc:a}=t;r.length&&M(a,n,r);let o=0,s=(e,n)=>{for(let i of r){let r=i.attribute?.(t,e,f(n,`accessor`));if(r)return r}return p(t,n,3,e=>!e.normalized&&e.type===`VEC3`&&e.componentType===5126)},c=[],l=e=>{let t=e.pbrMetallicRoughness??{},n=t.baseColorFactor??[1,1,1,1];if((e.alphaMode??`OPAQUE`)!==`OPAQUE`||!Array.isArray(n)||n.length!==4||e.emissiveFactor!==void 0&&(!Array.isArray(e.emissiveFactor)||e.emissiveFactor.some(e=>e!==0))||e.extensions||[t.baseColorTexture,t.metallicRoughnessTexture,e.normalTexture,e.occlusionTexture,e.emissiveTexture].some(Boolean))throw v(`unsupported`,`Maps, emission and transparency need @margoengine/gltf/textured or gltf/pbr`,`gltf-light`);return new g({color:n.slice(0,3),roughness:t.roughnessFactor??1,metalness:t.metallicFactor??1,doubleSided:e.doubleSided??!1})},u=(a.meshes??[]).map(e=>{if(!Array.isArray(e.primitives)||!e.primitives.length||!e.primitives.every(E))throw x(`Missing glTF primitives`,`gltf-invalid`);return e.primitives.flatMap(e=>{if(e.attributes?.POSITION===void 0)return[];if((e.mode??4)!==4||e.targets||e.extensions||Object.keys(e.attributes??{}).some(e=>/^(COLOR|JOINTS|WEIGHTS)_/.test(e)))throw v(`unsupported`,`Points, lines, morphs, skins and vertex colours need @margoengine/gltf/pbr`,`gltf-light`);let n=s(`POSITION`,e.attributes?.POSITION),r=e.attributes?.NORMAL===void 0?null:s(`NORMAL`,e.attributes.NORMAL),i=e.indices===void 0?Uint32Array.from({length:n.length/3},(e,t)=>t):p(t,e.indices,1,e=>!e.normalized&&e.type===`SCALAR`&&[5121,5123,5125].includes(e.componentType),!0);if(i.length%3)throw RangeError(`Indices must contain complete triangles`);let u=r?void 0:i;if(o+=r?n.length/3:i.length,o>1e6)throw v(`unsupported`,`glTF exceeds one million vertices, the light loader limit`,`gltf-light`);if(!r){let e=new Float32Array(i.length*3);r=new Float32Array(e.length);for(let t=0,r=n.length/3;t<i.length;t++){let a=i[t];if(a>=r)throw RangeError(`Index exceeds vertices; load a smaller file or split it`);e[t*3]=n[a*3],e[t*3+1]=n[a*3+1],e[t*3+2]=n[a*3+2]}for(let t=0;t<e.length;t+=9){let n=e,i=n[t+3]-n[t],a=n[t+4]-n[t+1],o=n[t+5]-n[t+2],s=n[t+6]-n[t],c=n[t+7]-n[t+1],l=n[t+8]-n[t+2],u=a*l-o*c,d=o*s-i*l,f=i*c-a*s;for(let e=t;e<t+9;e+=3)r[e]=u,r[e+1]=d,r[e+2]=f}n=e,i=new Uint32Array(e.length/3);for(let e=0;e<i.length;e++)i[e]=e}let d=e.material===void 0?new g({color:[1,1,1],roughness:1,metalness:1,doubleSided:!1}):a.materials?.[f(e.material,`material reference`)]&&(c[e.material]??=l(a.materials[e.material]));if(!d)throw x(`Missing glTF material`,`gltf-invalid`);return[{geometry:new h(n,r,i),material:d,source:e,expanded:u}]})}),d=a.nodes??[],y=new Int32Array(d.length).fill(-1);d.forEach((e,t)=>{if(!e||e.skin!==void 0||e.camera!==void 0||e.extensions)throw v(`unsupported`,`Unsupported glTF node for the light loader`,`gltf-light`);if(e.children!==void 0&&!Array.isArray(e.children))throw x(`Invalid glTF children`,`gltf-invalid`);for(let n of e.children??[]){let e=f(n,`child reference`);if(e>=d.length||y[e]!==-1||e===t)throw x(`Invalid glTF hierarchy`,`gltf-transform`);y[e]=t}});for(let e=0;e<d.length;e++){let t=0;for(let n=e;n!==-1;n=y[n])if(++t>d.length)throw x(`glTF hierarchy cycle through node ${e}`,`gltf-transform`);if(t>62)throw b(`glTF node ${e} is ${t} levels deep, past 62`,`gltf-transform`)}let S=a.scenes?m(a.scenes,a.scene??0,`scene`).nodes??[]:d.map((e,t)=>t).filter(e=>y[e]===-1);if(!Array.isArray(S)||new Set(S).size!==S.length)throw x(`Invalid glTF scene roots`,`gltf-invalid`);let C=[],w=[],T=[],D=[],O;try{let e=i.createMesh();C.push(e);let n=S.map(t=>({id:f(t,`root`),parent:e})).reverse();for(;n.length;){let{id:t,parent:r}=n.pop(),a=m(d,t,`node`);if(r===e&&y[t]!==-1)throw x(`glTF scene root has a parent`,`gltf-transform`);let o=i.createMesh(r);if(C.push(o),T.push(o),D[t]=o,o.name=typeof a.name==`string`?a.name:``,P(o,a,t),a.mesh!==void 0){let e=u[f(a.mesh,`mesh reference`)];if(!e)throw x(`Missing glTF mesh`,`gltf-invalid`);for(let t of e){let e=i.createMesh(o);C.push(e),e.setGeometry(t.geometry).setMaterial(t.material),w.push(e)}}let s=a.children??[];for(let e=s.length-1;e>=0;e--)n.push({id:s[e],parent:o})}if(!w.length&&!r.some(e=>e.allowEmptyScene))throw v(`failed`,`glTF contains no renderable meshes`,`gltf-light`);let a=()=>{for(let e=C.length-1;e>=0;e--)C[e].dispose()};O={root:e,meshes:w,nodes:T,warnings:[],dispose:a,[Symbol.dispose??Symbol()]:a};for(let e of r)e.finish?.(O,t,{engine:i,primitives:u.flat(),nodes:D});return O}catch(e){if(O)O.dispose();else for(let e=C.length-1;e>=0;e--)C[e].dispose();throw e}}async function z(e,t,n,r,i){let a=n.extensions??[],o=[];try{for(let e of a)o.push(e),await e.load?.(t,r),r?.throwIfAborted();return i.run(()=>R(e,t,n))}catch(e){for(let e of o)e.abandon?.(t);throw e}}function B(e,t,n=[],r={}){if(r.extensions?.some(e=>e.load))throw y(`unsupported`,`This glTF extension loads asynchronously; use parseGLTFAsync or loadGLTF`);return R(e,L(t,n,r),r)}async function V(e,t,n=[],{signal:r,...i}={}){return r?.throwIfAborted(),z(e,L(t,n,i),i,r,d(e))}async function H(e,t,{signal:a,maxNodes:s,allowedURLs:c,extensions:l=[],fetch:u=globalThis.fetch}={}){a?.throwIfAborted();let f=d(e),p=new URL(t,globalThis.location?.href),m=0;async function h(e,t=!1){if(![`http:`,`https:`].includes(e.protocol))throw x(`glTF URL must use HTTP(S)`,`gltf-url`);let n=await u(e,{signal:a});t&&n.url?p=new URL(n.url):t||i(n,p,c,`glTF buffer`);let o=await r(n,{maxBytes:w-m,signal:a,label:`glTF download`}).catch(e=>{throw e instanceof RangeError?T(`glTF download is`):e});if(C(o,e.href),(m+=o.byteLength)>w)throw T(`glTF download is`);return o}let g=await h(p,!0),{doc:_,binary:v}=A(o(g)?g:D(g));M(_,s,l);let y=[];for(let[e,t]of(_.buffers??[]).entries())if(I(_,e,l,e===0&&!t.uri&&!!v))y.push(/* @__PURE__ */ new Uint8Array);else if(!t.uri)y.push(e===0&&v||/* @__PURE__ */ new Uint8Array);else if(typeof t.uri==`string`&&t.uri.startsWith(`data:`)){let e=j(t.uri);if(m+=e.length,m>w)throw T(`glTF download is`);y.push(e)}else y.push(await h(n(t.uri,p,c,`glTF buffer`)));a?.throwIfAborted();let b={maxNodes:s,extensions:l},S=L(_,y,b);return S.fetch=e=>h(n(e,p,c,`glTF image`)),z(e,S,b,a,f)}export{C as i,B as n,V as r,H as t};
@@ -0,0 +1 @@
1
+ import{a as e,c as t,d as n,l as r}from"./version-B6NE5cJf.js";import{t as i}from"./accessor-DuqjpuxI.js";import"./image-limit-DvFSfR5T.js";import{A as a,C as o,O as s,T as c,a as l,b as u,c as d,h as f,i as p,m,t as h,u as g,v as _,y as v}from"./asset-DN3ocEdY.js";import{a as y,o as b,r as x,t as S}from"./pack-DdxRO8k6.js";import{margoError as C}from"@margoengine/core/extension";function w(e,t){let n=f(e.bufferViews,t,`bufferView`),r=n.extensions?.EXT_meshopt_compression??n.extensions?.KHR_meshopt_compression,i=r??n;return{buffer:i.buffer,offset:i.byteOffset??0,length:i.byteLength,packed:!!r}}var T=1<<20,E=262144,D=4;function O(e,t,n){let r=[],i=!1;for(let a=0;a<e.length;a+=2){let o=e[a],s=e[a+1];s<t?r.push(o,s):o>n?(i||=(r.push(t,n),!0),r.push(o,s)):(t=Math.min(t,o),n=Math.max(n,s))}i||r.push(t,n),e.length=0;for(let t of r)e.push(t)}function k(e,t,n){let r=[];for(let i=0;i<e.length&&t<n;i+=2)if(!(e[i+1]<=t)){if(e[i]>=n)break;e[i]>t&&r.push([t,e[i]]),t=Math.max(t,e[i+1])}return t<n&&r.push([t,n]),r}var A=(e,t,n)=>!k(e,t,n).length,j=e=>{let{name:t=`Error`,code:n}=e??{};return{name:t,message:e instanceof Error?e.message:String(e),...typeof n==`string`?{code:n}:{}}},M=class{constructor(e,t,n,r=p,i,o,s=!1,c=a,l={}){this.url=e,this.post=t,this.signal=n,this.limit=r,this.maxNodes=i,this.allowedURLs=o,this.textures=s,this.partVertices=c,this.decoders=l,this.sources=[],this.map=[],this.needs=[],this.posted=/* @__PURE__ */ new Set,this.waiters=[],this.inflight=0,this.pending=0,this.loaded=0,this.reported=0,this.decoding=Promise.resolve(),this.base=e,n.addEventListener(`abort`,()=>this.notify(),{once:!0})}setOrder(e){this.order=e,this.notify()}notify(){for(let e of this.waiters.splice(0))e()}async next(){if(await new Promise(e=>this.waiters.push(e)),this.signal.throwIfAborted(),this.failure)throw this.failure}async run(){try{let e=await this.head();if(l(e),s(e)||e.meshes?.some(e=>e?.primitives?.some(e=>(e?.mode??4)<4))||e.textures?.some(e=>e?.extensions?.MSFT_texture_dds)||!this.textures&&(e.textures?.some(e=>e?.extensions?.KHR_texture_basisu)||e.images?.some(e=>e?.mimeType===`image/ktx2`))||!this.decoders.draco&&e.meshes?.some(e=>e?.primitives?.some(e=>e?.extensions?.KHR_draco_mesh_compression))){this.post({type:`fallback`});return}for(this.post({type:`doc`,doc:e}),this.buffers(e),await this.asset.prepareMeshopt();!this.order;)await this.next();await this.geometry(e),await this.images(e);for(let[e,t]of this.sources.entries())if(t.ranged!==!1){let n=k(t.asked,0,t.data.length);for(let t=0;t<n.length;){let r=n[t][0],i=n[t++][1];for(;t<n.length&&n[t][0]-i<=E;)i=n[t++][1];this.request(e,r,i)}}for(;this.inflight||this.sources.some(e=>!A(e.got,0,e.data?.length??0));)await this.next();this.bytes(!0);let t=new Map(S(this.asset)),n=[];y(e).forEach((e,r)=>{let i=c.get(this.asset)?.get(e);if(!i)return;n.push([r,i]);let a=e.extensions.KHR_draco_mesh_compression;for(let n of[...Object.keys(a.attributes).map(t=>e.attributes[t]),e.indices])n!==void 0&&t.set(n,this.asset.accessor(n))}),this.post({type:`done`,buffers:this.asset.buffers,accessors:[...t],...n.length?{draco:n}:{}})}catch(e){this.signal.aborted||this.post({type:`error`,error:j(e)})}}bytes(e=!1){let t=Date.now();!e&&t-this.reported<100||(this.reported=t,this.post({type:`bytes`,loaded:this.loaded,total:this.sources.reduce((e,t)=>e+(t.size??0),0)}))}fetch(e,t,n=!1){if(![`http:`,`https:`].includes(e.url.protocol))throw TypeError(`glTF URL must use HTTP(S); for a blob: or file: source, read its bytes (await file.arrayBuffer()) and pass them to parseGLTFAsync`);return fetch(e.url,{signal:this.signal,headers:t}).then(e=>{if(n||r(e,this.base,this.allowedURLs,`glTF`),!e.ok)throw C(`failed`,`glTF download request failed: HTTP ${e.status}; check the URL and that the server allows the request`);return e})}allocate(e,t){if(!Number.isSafeInteger(t)||t>this.limit-this.sources.reduce((e,t)=>e+(t.data?.length??0),0))throw _(`glTF exceeds download budget`,this.limit);e.data=new Uint8Array(t),e.size??=t}async read(e,t,n,r={left:0}){let i=t.body.getReader(),a=()=>i.cancel().catch(()=>{});this.signal.addEventListener(`abort`,a,{once:!0});try{for(;;){let{done:t,value:o}=await i.read();if(this.signal.throwIfAborted(),t)break;let s=e.data.length-n,c=o.length>s?o.subarray(0,s):o;e.data.set(c,n),O(e.got,n,n+c.length),this.loaded+=c.length,n+=c.length;let l=Math.min(c.length,r.left);if(r.left-=l,this.pending-=l,this.bytes(),this.notify(),n>=e.data.length){a();break}}}finally{this.signal.removeEventListener(`abort`,a)}}async head(){let e={url:this.url,got:[],asked:[]};this.sources.push(e);let t=await this.fetch(e,{Range:`bytes=0-65535`},!0),r=/^bytes 0-\d+\/(\d+|\*)$/.exec(t.headers.get(`content-range`)??``),i=r&&r[1]!==`*`?Number(r[1]):void 0;t.url&&(e.url=this.base=new URL(t.url)),e.ranged=t.status===206&&!!r;let a=t.body.getReader(),o=[],s=0;for(;s<12;){let{done:e,value:t}=await a.read();if(e)break;o.push(t),s+=t.length}let c=new Uint8Array(s);o.reduce((e,t)=>(c.set(t,e),e+t.length),0);let l=new DataView(c.buffer);if(s<12||l.getUint32(0,!0)!==1179937895){for(let e;!(e=await a.read()).done;)if(o.push(e.value),(s+=e.value.length)>this.limit)throw a.cancel().catch(()=>{}),_(`glTF JSON exceeds byte budget`,this.limit);let t=i===void 0?s-1:s;e.ranged&&(i===void 0?s>=65536:i>s)&&o.push((await n(await this.fetch(e,{Range:`bytes=${t}-`}),{maxBytes:this.limit-t,signal:this.signal,label:`glTF JSON`}).catch(e=>{throw e instanceof RangeError?_(`glTF JSON exceeds byte budget`,this.limit):e})).subarray(s-t));let r=new Uint8Array(o.reduce((e,t)=>e+t.length,0));if(o.reduce((e,t)=>(r.set(t,e),e+t.length),0),this.loaded+=r.length,r.length>this.limit)throw _(`glTF JSON exceeds byte budget`,this.limit);return this.sources.length=0,u(r,e.url.href),v(r)}let d=l.getUint32(8,!0);if(l.getUint32(4,!0)!==2||d<20||i!==void 0&&i!==d)throw TypeError(`Invalid GLB header; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);this.allocate(e,d),e.data.set(c.subarray(0,d)),O(e.got,0,Math.min(s,d)),this.loaded+=s;let f=s,p=(async()=>{try{for(;;){let{done:t,value:n}=await a.read();if(this.signal.throwIfAborted(),t)break;let r=n.subarray(0,Math.max(0,d-f));e.data.set(r,f),O(e.got,f,f+r.length),this.loaded+=r.length,f+=r.length,this.bytes(),this.notify()}if(!e.ranged&&f<d)throw RangeError(`Truncated GLB; download the file again, it is incomplete`)}catch(e){this.failure??=e,this.notify()}})();if(O(e.asked,0,e.ranged?Math.min(65536,d):d),e.ranged&&(await p,!this.failure&&!A(e.got,0,Math.min(65536,d))))throw RangeError(`Truncated glTF range response; download the file again, it is incomplete`);let m=()=>new DataView(e.data.buffer).getUint32(12,!0),h=()=>Math.min(d,28+m());for(;!A(e.got,0,20);)await this.next();if(m()%4||20+m()>d||new DataView(e.data.buffer).getUint32(16,!0)!==1313821514)throw TypeError(`Invalid GLB chunk; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);if(e.ranged)for(let[t,n]of k(e.got,0,h()))this.request(0,t,n);for(;!A(e.got,0,h());)await this.next();return v(e.data.subarray(20,20+m()))}buffers(n){let r=this.sources[0],i=/* @__PURE__ */ new Map,a=0,o=0,s=0;if(r){let e=r.data,t=new DataView(e.buffer),n=20+t.getUint32(12,!0);n+8<=e.length&&A(r.got,n,n+8)&&t.getUint32(n+4,!0)===5130562&&(a=n+8,s=t.getUint32(n,!0),o=Math.min(s,e.length-a))}let c=(n.buffers??[]).map((n,c)=>{let l=n?.extensions;if((l?.EXT_meshopt_compression??l?.KHR_meshopt_compression)?.fallback===!0)return this.map.push({source:-1,offset:0}),/* @__PURE__ */ new Uint8Array;if(n?.uri===void 0)return c===0&&r&&o?(e(s,n.byteLength),this.map.push({source:0,offset:a}),r.data.subarray(a,a+o)):(this.map.push({source:-1,offset:0}),/* @__PURE__ */ new Uint8Array);if(typeof n.uri==`string`&&n.uri.startsWith(`data:`)){this.map.push({source:-1,offset:0});let e=m(n.uri,this.limit);return this.loaded+=e.length,e}let u=t(n.uri,this.base,this.allowedURLs,`glTF`).href,d=i.get(u);if(d===void 0){d=this.sources.length,i.set(u,d);let e={url:new URL(u),got:[],asked:[]};this.sources.push(e),this.allocate(e,Number.isSafeInteger(n.byteLength)&&n.byteLength>0?n.byteLength:0)}return this.map.push({source:d,offset:0}),this.sources[d].data}),{meshopt:l}=this.decoders;this.asset=new h(n,c,void 0,l?{meshopt:l}:{},this.limit,this.maxNodes),this.asset.partVertices=this.partVertices,this.needs=y(n).map(e=>{let t=[],r=e?.attributes??{},i=e?.extensions?.KHR_draco_mesh_compression;try{let a=[`POSITION`,`NORMAL`,`TANGENT`,`TEXCOORD_0`,`TEXCOORD_1`,...b(n,e)?[`TEXCOORD_2`,`TEXCOORD_3`]:[],`COLOR_0`];i&&this.whole(n,i.bufferView,t);for(let o of[...a.filter(e=>!(i?.attributes&&e in i.attributes)).map(e=>r[e]),i?void 0:e.indices])o!==void 0&&this.ranges(n,o,t)}catch{for(let[e,n]of this.map.entries())n.source>=0&&t.push([n.source,n.offset,n.offset+this.asset.buffers[e].length])}return t})}ranges(e,t,n){let r=f(e.accessors,t,`accessor`),a=i[r.componentType],o=d[r.type],s=r.count,c=(t,r,i)=>{if(w(e,t).packed)return this.whole(e,t,n);let a=f(e.bufferViews,t,`bufferView`),o=this.map[a.buffer],s=(a.byteOffset??0)+r,c=(a.byteOffset??0)+a.byteLength;if(!o||!Number.isSafeInteger(s)||s<0||!Number.isSafeInteger(c)||!(i>0))throw TypeError(`range; pass a { start, end } byte range`);let l=Math.min(s+i,c,this.asset.buffers[a.buffer].length);o.source>=0&&s<l&&n.push([o.source,o.offset+s,o.offset+l])};if(r.bufferView!==void 0&&c(r.bufferView,r.byteOffset??0,(s-1)*(f(e.bufferViews,r.bufferView,`bufferView`).byteStride??a*o)+a*o),r.sparse){let e=r.sparse.count;c(r.sparse.indices.bufferView,r.sparse.indices.byteOffset??0,e*i[r.sparse.indices.componentType]),c(r.sparse.values.bufferView,r.sparse.values.byteOffset??0,e*a*o)}}whole(e,t,n){let{buffer:r,offset:i,length:a}=w(e,t),o=this.map[r],s=i+a;if(!o||!Number.isSafeInteger(i)||i<0||!Number.isSafeInteger(s)||!(a>0))throw TypeError(`range; pass a { start, end } byte range`);let c=Math.min(s,this.asset.buffers[r].length);o.source>=0&&i<c&&n.push([o.source,o.offset+i,o.offset+c])}request(e,t,n){let r=this.sources[e],i={left:n-t};O(r.asked,t,n),this.inflight++,this.pending+=n-t,r.ranged===void 0&&(r.probing=!0),(async()=>{let e=await this.fetch(r,{Range:`bytes=${t}-${n-1}`}),a=/^bytes (\d+)-\d+\/(\d+|\*)$/.exec(e.headers.get(`content-range`)??``);if(e.status===206&&a&&+a[1]===t){if(r.ranged===void 0&&a[2]!==`*`&&+a[2]<r.data.length)throw RangeError(`Truncated glTF buffer; download the file again, it is incomplete`);if(r.ranged=!0,await this.read(r,e,t,i),!A(r.got,t,Math.min(n,r.data.length)))throw RangeError(`Truncated glTF range response; download the file again, it is incomplete`)}else if(r.ranged=!1,O(r.asked,0,r.data.length),await this.read(r,e,0,i),!A(r.got,0,r.data.length))throw RangeError(`Truncated glTF buffer; download the file again, it is incomplete`)})().catch(e=>{this.failure??=e}).finally(()=>{this.inflight--,this.pending-=i.left,r.probing=!1,this.notify()})}ready(e){return this.needs[e].every(([e,t,n])=>A(this.sources[e].got,t,n))}async geometry(e){let t=y(e);for(;;){if(this.failure)throw this.failure;let e=this.order.filter(e=>!this.posted.has(e));for(let n of e)this.ready(n)&&(this.posted.add(n),t[n]?.extensions?.KHR_draco_mesh_compression?this.decoding=this.decoding.then(()=>this.decompress(n,t[n])):this.pack(n,t[n]));if(this.order.every(e=>this.posted.has(e)))return this.decoding;let n=T,r=[];for(let t of e){if(this.inflight>=D||n<=0||this.pending>=T)break;for(let[e,i,a]of this.needs[t]){let t=this.sources[e];if(!(t.ranged===!1||t.probing)){for(let[o,s]of k(t.asked,i-i%E,Math.min(t.data.length,Math.ceil(a/E)*E)))if(r.push([e,o,s]),O(t.asked,o,s),n-=s-o,t.ranged===void 0){t.probing=!0;break}}}}r.sort((e,t)=>e[0]-t[0]||e[1]-t[1]);for(let e=0;e<r.length;){let[t,n,i]=r[e++];for(;e<r.length&&r[e][0]===t&&r[e][1]<=i;)i=Math.max(i,r[e++][2]);this.request(t,n,i)}r.length||await this.next()}}pack(e,t){try{x(this.asset,t,({vertices:t,indices:n,uvs:r,part:i})=>this.post({type:`geometry`,key:e,vertices:t,indices:n,uvs:r,...i?{part:i}:{}}))}catch(t){this.post({type:`geometry`,key:e,error:j(t)})}}async decompress(e,t){try{let{decompressPrimitive:e}=await import(`./compression-CUOCmjmE.js`);this.signal.throwIfAborted(),await e(this.asset,t,async()=>this.decoders.draco,this.signal),this.signal.throwIfAborted()}catch(t){this.signal.aborted||this.post({type:`geometry`,key:e,error:j(t)});return}this.pack(e,t)}async textureSource(e,n){if(n.bufferView===void 0){if(typeof n.uri!=`string`)throw TypeError(`Invalid glTF image; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);return n.uri.startsWith(`data:`)?{bytes:m(n.uri,this.limit)}:{url:t(n.uri,this.base,this.allowedURLs,`glTF`).href}}let r=w(e,n.bufferView),i=this.map[r.buffer];if(r.packed||this.asset.view(n.bufferView),i?.source>=0){let e=this.sources[i.source],t=i.offset+r.offset,n=t+r.length;for(;e.ranged===void 0;)e.probing||this.request(i.source,t,Math.min(n,t+1)),await this.next();if(e.ranged&&!r.packed)return O(e.asked,t,n),O(e.got,t,n),{url:e.url.href,offset:t,length:r.length};if(e.ranged)for(let[r,a]of k(e.asked,t,Math.min(n,e.data.length)))this.request(i.source,r,a);for(;!A(e.got,t,Math.min(n,e.data.length));)await this.next()}return{bytes:this.asset.view(n.bufferView).slice()}}async images(e){let r=y(e),i=[],a=e.images??[],s=t=>e.materials?.[t?.material],c=(e,t=[],n=0)=>{if(e&&typeof e==`object`&&n<8){let r=e.index;typeof r==`number`&&Number.isSafeInteger(r)&&r>=0&&t.push(r);for(let r of Object.values(e))c(r,t,n+1)}return t};for(let t of this.order)for(let n of c(s(r[t]))){let t=e.textures?.[n];for(let e of[t?.source,...Object.values(t?.extensions??{}).map(e=>e?.source)])Number.isInteger(e)&&!i.includes(e)&&i.push(e)}let l=[...i,...a.map((e,t)=>t).filter(e=>!i.includes(e))].filter(e=>e<a.length),u=0,d=this.textures?o(e):/* @__PURE__ */ new Set,f=async r=>{let i=a[r],o=i.mimeType===`image/ktx2`||/\.ktx2$/i.test(i.uri??``);if(o&&this.textures){this.post({type:`image`,index:r,source:await this.textureSource(e,i)});return}if(o||d.has(r)){this.post({type:`image`,index:r});return}let s;if(i.bufferView!==void 0){let t=w(e,i.bufferView),n=this.map[t.buffer];if(t.packed||this.asset.view(i.bufferView),n?.source>=0){let e=this.sources[n.source],r=n.offset+t.offset,i=Math.min(r+t.length,e.data.length);if(e.ranged){let t=k(e.asked,r,i);for(let[e,r]of t)this.request(n.source,e,r)}for(;!A(e.got,r,Math.min(i,e.data.length));)e.ranged===void 0&&!e.probing&&this.request(n.source,r,i),await this.next()}s=this.asset.view(i.bufferView)}else if(typeof i.uri==`string`&&i.uri.startsWith(`data:`))s=m(i.uri,this.limit);else if(typeof i.uri==`string`){let e=await this.fetch({url:t(i.uri,this.base,this.allowedURLs,`glTF`),got:[],asked:[]});s=await n(e,{maxBytes:Math.max(0,this.limit-this.loaded),signal:this.signal,label:`glTF image`}).catch(e=>{throw e instanceof RangeError?_(`glTF exceeds download budget`,this.limit):e}),this.loaded+=s.length}else throw TypeError(`Invalid glTF image; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let c=await g(s,i.mimeType,r,this.signal);if(u+=c.width*c.height*4,c.width*c.height>67108864)throw`close`in c&&c.close(),RangeError(`glTF images exceed decoded size limit; load a smaller model, or reduce its textures and meshes`);if(u>this.limit*4)throw`close`in c&&c.close(),_(`glTF images exceed decoded size limit`,this.limit*4);this.post({type:`image`,index:r,image:c})},p=Array.from({length:D},async()=>{for(let e;(e=l.shift())!==void 0;)await f(e)});await Promise.all(p)}};export{M as GLTFStream};
package/dist/stream.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { PrimitivePart } from './model.js';
2
- import type { GLTFDocument, GLTFStreamSource } from './asset.js';
2
+ import type { GLTFDecoderHooks, GLTFDocument, GLTFDracoDecodeOptions, GLTFStreamSource } from './asset.js';
3
3
  /** An error as it crosses to the main thread; `code` keeps a MargoError's code. */
4
4
  export type StreamError = {
5
5
  name: string;
@@ -33,10 +33,21 @@ export type StreamMessage = {
33
33
  type: 'done';
34
34
  buffers: Uint8Array[];
35
35
  accessors: [number, Float32Array][];
36
+ /** Decoded indices of each Draco primitive, by key. */
37
+ draco?: [number, Float32Array][];
38
+ }
39
+ /** From the worker script: a Draco stream for the main thread's decoder, answered by `{ draco: id, result }`. */
40
+ | {
41
+ type: 'draco';
42
+ id: number;
43
+ data: Uint8Array;
44
+ options: GLTFDracoDecodeOptions;
36
45
  } | {
37
46
  type: 'error';
38
47
  error: StreamError;
39
48
  };
49
+ /** The decoders a stream uses: Draco (the main thread's, for a worker) and a caller's own meshopt decoder. */
50
+ export type StreamDecoders = Pick<GLTFDecoderHooks, 'draco' | 'meshopt'>;
40
51
  export declare class GLTFStream {
41
52
  private readonly url;
42
53
  private readonly post;
@@ -46,6 +57,7 @@ export declare class GLTFStream {
46
57
  private readonly allowedURLs?;
47
58
  private readonly textures;
48
59
  private readonly partVertices;
60
+ private readonly decoders;
49
61
  private order?;
50
62
  private readonly sources;
51
63
  private map;
@@ -60,12 +72,14 @@ export declare class GLTFStream {
60
72
  private loaded;
61
73
  private reported;
62
74
  private base;
75
+ /** Draco primitives decode one after another here, while the requests go on. */
76
+ private decoding;
63
77
  /**
64
78
  * `limit`: maxDownloadBytes, already validated by the caller; `maxNodes`: the load's maxNodes; `textures`: KTX2 images
65
79
  * stream on the main thread, so this reports where each one is and fetches none of it; `partVertices`: the load's
66
- * maxPartVertices, already validated.
80
+ * maxPartVertices, already validated; `decoders`: what decodes Draco and, when given, meshopt.
67
81
  */
68
- constructor(url: URL, post: (message: StreamMessage) => void, signal: AbortSignal, limit?: number, maxNodes?: number | undefined, allowedURLs?: readonly string[] | undefined, textures?: boolean, partVertices?: number);
82
+ constructor(url: URL, post: (message: StreamMessage) => void, signal: AbortSignal, limit?: number, maxNodes?: number | undefined, allowedURLs?: readonly string[] | undefined, textures?: boolean, partVertices?: number, decoders?: StreamDecoders);
69
83
  /** Primitive keys still wanted, most important first (the main thread re-sends this as the camera moves). */
70
84
  setOrder(order: number[]): void;
71
85
  private notify;
@@ -79,9 +93,12 @@ export declare class GLTFStream {
79
93
  private head;
80
94
  private buffers;
81
95
  private ranges;
96
+ private whole;
82
97
  private request;
83
98
  private ready;
84
99
  private geometry;
100
+ private pack;
101
+ private decompress;
85
102
  private textureSource;
86
103
  private images;
87
104
  }
@@ -0,0 +1 @@
1
+ var e=e=>typeof e==`number`&&Number.isFinite(e)&&e>0;function t(t,n){let r=n?.mode??4;if(r>3)return;let i=r===0?`points`:`lines`,a=n.extras,o=a?.[i===`points`?`pointSize`:`lineWidth`],s=a?.[i===`points`?`pointSizeUnits`:`lineWidthUnits`]??`pixels`;if(e(o)&&(s===`pixels`||s===`world`))return{kind:i,size:o,units:s,bentley:!1};let c=(n.material===void 0?void 0:t.materials?.[n.material])?.extensions?.[i===`points`?`BENTLEY_materials_point_style`:`BENTLEY_materials_line_style`]?.[i===`points`?`diameter`:`width`];return e(c)?{kind:i,size:c,units:`pixels`,bentley:!0}:void 0}var n=e=>!!e.meshes?.some(n=>n?.primitives?.some(n=>t(e,n)!==void 0));export{t as n,n as t};
@@ -0,0 +1,18 @@
1
+ import type { GLTFDocument, GLTFPrimitive } from './shared/gltf.js';
2
+ /** A point diameter or line width and its units. */
3
+ export interface StrokeWidth {
4
+ readonly kind: 'points' | 'lines';
5
+ readonly size: number;
6
+ readonly units: 'pixels' | 'world';
7
+ /** From a Bentley material style, which draws a point as a disc; false for the primitive's extras. */
8
+ readonly bentley: boolean;
9
+ }
10
+ /**
11
+ * The width primitive `p` of `doc` asks for, or undefined for a triangle primitive or one that asks for none. Extras
12
+ * come first, being the file's own value; a value that is not a positive finite number, or units other than `'pixels'`
13
+ * and `'world'` (absent means pixels), is not this convention's and is not read, as extras are application-specific
14
+ * (glTF 2.0 section 3.12).
15
+ */
16
+ export declare function strokeWidth(doc: GLTFDocument, p: GLTFPrimitive | undefined): StrokeWidth | undefined;
17
+ /** True when some primitive of `doc` asks for a width: the strokes reader then loads. */
18
+ export declare const hasStrokes: (doc: GLTFDocument) => boolean;
@@ -0,0 +1,12 @@
1
+ import type { GLTFStrokeReader } from './asset.js';
2
+ /**
3
+ * The key on the plugins this reader adds: scene writers of @margoengine/exporters skip them, as the model writes these
4
+ * points and lines itself, with their widths.
5
+ */
6
+ export declare const strokesKey: unique symbol;
7
+ /**
8
+ * The reader `loadGLTF` and `parseGLTFAsync` import when a file asks for a point or line width: each item drawn by a
9
+ * scene-wide `gltf-lines` or `gltf-points` plugin, following its node's world matrix and visibility.
10
+ */
11
+ export declare const wideStrokes: GLTFStrokeReader;
12
+ export { strokeWidth, type StrokeWidth } from './stroke-width.js';
@@ -0,0 +1 @@
1
+ import{t as e}from"./scene-scope-CZDEkd24.js";import{n as t}from"./stroke-width-B2cnYGgn.js";import{margoError as n}from"@margoengine/core/extension";var r=Symbol.for(`margoengine.gltf-strokes.v1`),i=`gltf-lines`,a=`gltf-points`,o=(e,t)=>t.catch(t=>{throw n(`unsupported`,`Wide glTF points and lines need ${e} (${t instanceof Error?t.message:t}): install it, or pass decoders: {strokes: false} to draw them 1 px wide`)});function s(e,t,i,a){let o=e.plugins.get(t);if(o){if(!(o instanceof a))throw n(`state`,`A plugin named "${t}" is not gltf/pbr's; remove it before loading wide glTF lines`);return o}let s=i();return Object.defineProperty(s,r,{value:!0}),e.use(s),s}function c(e,t,n){let r=t.length,i=new Float32Array(r*3),a=new Float32Array(r*4),o=!1;for(let s=0;s<r;s++){let r=t[s]*20;i[s*3]=e[r],i[s*3+1]=e[r+1],i[s*3+2]=e[r+2];for(let t=0;t<4;t++){let i=t===3&&!n?1:e[r+16+t];a[s*4+t]=i,i!==1&&(o=!0)}}return{positions:i,colors:o?a:null}}function l(e){if(e.length<4)return{order:e,mode:`segments`};let t=[e[0]];for(let n=1;n<e.length;n+=2){if(n>1&&e[n-1]!==e[n-2])return{order:e,mode:`segments`};t.push(e[n])}return t.length>3&&t[t.length-1]===t[0]?(t.pop(),{order:t,mode:`loop`}):{order:t,mode:`strip`}}var u=e=>e===`butt`||e===`round`||e===`square`,d=e=>typeof e==`boolean`,f=e=>typeof e==`number`&&Number.isFinite(e)&&e>=0,p={shape:e=>e===`square`||e===`round`,minPixelSize:f,maxPixelSize:f,edl:d,adaptiveSize:f,alphaTest:e=>f(e)&&e<=1,blending:e=>e===`normal`||e===`additive`,depthTest:d,depthWrite:d,fog:d};function m(e,t,n){let r={};for(let[i,a]of Object.entries(t)){let t=n[`${e}${i[0].toUpperCase()}${i.slice(1)}`];a(t)&&(r[i]=t)}return r}function h(e){let t=m(`point`,p,Object(e));return Number(t.minPixelSize??1)>Number(t.maxPixelSize??256)&&(delete t.minPixelSize,delete t.maxPixelSize),t}var g={join:e=>e===`miter`||e===`round`||e===`bevel`,cap:u,miterLimit:e=>f(e)&&e>=1,onTop:d,antialias:d,depthWrite:d,depthBias:e=>f(e)&&e<1,behind:d,alphaToCoverage:d,fog:d};function _(e){let t=Object(e),n=m(`line`,g,t),r=t.lineDash;if(Array.isArray(r)&&r.length===2&&f(r[0])&&r[0]>0&&f(r[1])){let{lineDashOffset:e,lineDashCap:i}=t;Object.assign(n,{dashed:!0,dashSize:r[0],gapSize:r[1]}),Number.isFinite(e)&&(n.dashOffset=e),u(i)&&(n.dashCap=i)}return n}function v(e,t){if(!e)return;let n=Float32Array.from(t,t=>e[t]);if(n.some(e=>!Number.isFinite(e)||e<0))throw RangeError(`Invalid glTF _WIDTH values; each must be finite and non-negative, re-export the file`);return n.every(e=>e===1)?void 0:n}var y={async attach(t,n,r){let i=e(t),a=n.some(e=>e.width.kind===`lines`),s=n.some(e=>e.width.kind===`points`),[c,l,u]=await Promise.all([a?o(`@margoengine/lines`,import(`@margoengine/lines`)):void 0,a?o(`@margoengine/lines`,import(`@margoengine/lines/stroke`)):void 0,s?o(`@margoengine/points`,import(`@margoengine/points`)):void 0]);r?.throwIfAborted();let d=[],f=()=>{for(let{owner:e,item:n}of d.splice(0)){e.remove(n);let r=e,i=t.sceneOf(e);!(r.lines??r.pointClouds)?.size&&i&&i.removePlugin(e.name)}};try{i.run(()=>{for(let e of n)d.push(...b(t,e,c,l,u))})}catch(e){throw f(),e}return{dispose:f}}};function b(e,t,n,r,o){let{width:u,vertices:d,indices:f,material:p,node:m}=t,g=p.alphaMode===`BLEND`,y=[p.base[0],p.base[1],p.base[2]],b=g?p.base[3]:1;if(u.kind===`lines`){let a=s(e,i,()=>new n.Lines({name:i}),n.Lines),{order:o,mode:p}=l(f),{positions:h,colors:x}=c(d,o,g),S=v(t.widths,o);if(o.length<2)return[];let C={positions:h,colors:x,mode:p,mesh:m,color:y,opacity:b,width:u.size,worldUnits:u.units===`world`,..._(t.extras)},w=S?new r.Stroke({...C,widths:S}):new n.Line(C);return[{owner:a,item:a.add(w)}]}let x=s(e,a,()=>new o.PointsPlugin({name:a}),o.PointsPlugin),{positions:S,colors:C}=c(d,f,g),w=v(t.widths,f),T=!(p.extensions&&`KHR_materials_unlit`in p.extensions);if(!f.length)return[];let E=new o.PointCloud({positions:S,colors:C??void 0,colorFormat:`float`,colorSpace:`linear`,sizes:w,material:{color:y,opacity:b,size:u.size,sizeUnits:u.units,shape:u.bentley?`round`:void 0,shading:T?`sphere`:`flat`,transparent:g,...h(t.extras)}});return E.attach(m),[{owner:x,item:x.add(E)}]}export{t as strokeWidth,r as strokesKey,y as wideStrokes};
@@ -1,4 +1,4 @@
1
- // @margo/core-built 0.1.0
1
+ // @margo/core-built 1.0.0
2
2
  import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
- const t=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
- import{r as e}from"./texture-coordinates-XFsEMdU6.js";import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";import{KTX2Streamer as n,colorTwin as r}from"@margoengine/decoders/ktx2-stream";var i=4096;function a(e,t,n){let r=[1/0,1/0,1/0],a=[-1/0,-1/0,-1/0];for(let t=0;t<e.length;t+=20)for(let n=0;n<3;n++)r[n]=Math.min(r[n],e[t+n]),a[n]=Math.max(a[n],e[t+n]);let o=[0,1,2].map(e=>(r[e]+a[e])/2||0),s=Math.hypot(a[0]-r[0],a[1]-r[1],a[2]-r[2])/2||0,c=Math.floor(t.length/3),l=Math.max(1,Math.floor(c/i)),u=[0,0,0,0],d=0,f=(t,r,i)=>r<2?e[t*20+12+r*2+i]:n?.[t*4+(r-2)*2+i]??0;for(let n=0;n<c;n+=l){let r=t[n*3],i=t[n*3+1],a=t[n*3+2],o=r*20,s=i*20,c=a*20,l=e[s]-e[o],p=e[s+1]-e[o+1],m=e[s+2]-e[o+2],h=e[c]-e[o],g=e[c+1]-e[o+1],_=e[c+2]-e[o+2];d+=Math.hypot(p*_-m*g,m*h-l*_,l*g-p*h)/2;for(let e=0;e<4;e++){let t=f(r,e,0),n=f(r,e,1);u[e]+=Math.abs((f(i,e,0)-t)*(f(a,e,1)-n)-(f(a,e,0)-t)*(f(i,e,1)-n))/2}}return{centre:o,radius:s,spans:u.map(e=>e>0&&d>0?Math.sqrt(d/e):s*2)}}function o(e,t=0){return Math.max(Math.hypot(e[t],e[t+1],e[t+2]),Math.hypot(e[t+4],e[t+5],e[t+6]),Math.hypot(e[t+8],e[t+9],e[t+10]))}var s=.2,c=/* @__PURE__ */ new WeakMap,l=0,u=(e,t,n,r,i=0)=>[e[i]*t+e[i+4]*n+e[i+8]*r+e[i+12],e[i+1]*t+e[i+5]*n+e[i+9]*r+e[i+13],e[i+2]*t+e[i+6]*n+e[i+10]*r+e[i+14]];function d(e,t,n){let r=e.views?.length?e.views:[void 0],i=e.canvas.height,a=0;for(let o of r){let r=o?.camera??e.camera,s=r.planes,c=!0;if(s.some(e=>e!==0))for(let e=0;e<24;e+=4)s[e]*t[0]+s[e+1]*t[1]+s[e+2]*t[2]+s[e+3]<-n&&(c=!1);if(!c)continue;let l=r.position,u=Math.max(Math.hypot(t[0]-l[0],t[1]-l[1],t[2]-l[2])-n,r.near);a=Math.max(a,i/2/(u*Math.tan(r.fov*Math.PI/360)))}return a}var f=class{constructor(e,t){this.owner=e,this.source=t,this.streamed=!0,this.users=/* @__PURE__ */ new Set,this.width=1,this.height=1,this.wanted=0,this.views=/* @__PURE__ */ new Map}view(e,t){let n=this.stream;if(!n||this.owner.device!==e)return;let i=this.views.get(t);if(!i){let e=n.format.replace(/-srgb$/,``),a=t&&r(e)?r(e):e;this.views.set(t,i=n.texture.createView({format:a}))}return i}viewSize(){let e=this.stream?.texture;return e?{width:e.width,height:e.height,levels:e.mipLevelCount}:void 0}use(e){this.stream=e,this.width=e.width,this.height=e.height,e.onChange=()=>this.changed(),this.changed()}changed(){this.views.clear();for(let e of[...this.users])e.rebindStreamed(this)}drop(){this.stream?.dispose(),this.stream=void 0,this.views.clear()}close(){this.drop(),this.owner.forget(this)}},p=class r{static attach(e,t={},n){__margoAssertCore(e,__margoCoreRequirement("0.1.0",import.meta.url));return new r(e,t,n)}constructor(e,n={},r=new AbortController().signal){this.options=n,this.signal=r,this.name=`gltf-pbr-textures-${++l}`,this.images=/* @__PURE__ */ new Set,this.models=/* @__PURE__ */ new Set,this.uses=/* @__PURE__ */ new WeakMap,this.since=0,this.closed=!1,this.engine=t(e),this.start();let i=this;this.engine.use(this.plugin={coreRequirement:/*@__PURE__*/__margoCoreRequirement("0.1.0",import.meta.url),name:this.name,setup(){},onPreUpdate(e){i.since+=e,i.since>=s&&i.update()},onDeviceRestored(){i.restart()}})}start(){this.streamer=new n({...this.options,device:this.engine.gpu,onError:e=>(this.options.onError??console.error)(e)})}get device(){return this.streamer.device}get budgetBytes(){return this.streamer.budgetBytes}set budgetBytes(e){this.streamer.budgetBytes=e}get usedBytes(){return this.streamer.usedBytes}get textures(){return[...this.images].flatMap(({stream:e,width:t,height:n,wanted:r})=>e?[{width:t,height:n,level:e.residentLevel,levels:e.levels,pixels:r}]:[])}async begin(e){let{source:t}=e,{streamer:n}=this,r={signal:this.signal,colorViews:!0},i=`bytes`in t?await n.open(t.bytes,r):await n.open(t.url,{...r,offset:t.offset,length:t.length});this.closed||!this.images.has(e)||n!==this.streamer?i.dispose():e.use(i)}async open(e){let t=new f(this,e);this.images.add(t);for(let e of this.models)t.users.add(e);return await this.begin(t),t}attach(e){this.models.add(e);for(let t of this.images)t.users.add(e);e.onDispose(()=>{this.models.delete(e),!this.models.size&&!this.images.size&&this.dispose()})}forget(e){this.images.delete(e),this.images.size||this.dispose()}mapsOf(t,n,r){let i=this.uses.get(r);return i||(i=r.maps.flatMap(r=>{let i=r&&n.textures?.[r.index],a=i?.extensions?.KHR_texture_basisu?.source??i?.source,o=a===void 0?void 0:t.images[a];if(!(o instanceof f))return[];let{texCoord:s,transform:c}=e(r);return[{image:o,set:s,repeat:(c?Math.min(Math.hypot(c[0],c[4]),Math.hypot(c[1],c[5])):1)||1}]}),r.maps.some(Boolean)&&this.uses.set(r,i)),i}measure(e,t){let n=this.mapsOf(e,e.asset.doc,t.material);if(!n.length)return;let r=c.get(t.vertices);r||c.set(t.vertices,r=a(t.vertices,t.indices,t.uvs));let{centre:i,radius:s,spans:l}=r,f=t.node.matrix,p=o(f),m=(e,t)=>{let r=d(this.engine,e,s*t)*t;for(let e of n)e.image.wanted=Math.max(e.image.wanted,r*(l[e.set]??0)/e.repeat)},h=t.instances;if(!h)m(u(f,...i),p);else for(let e=0,t=h.count;e<t;e++)m(u(f,...u(h.data,...i,e*24)),p*o(h.data,e*24))}update(){if(this.since=0,!this.closed){for(let e of this.images)e.wanted=0;for(let e of this.models)if(e.disposed)this.models.delete(e);else for(let t of e.primitives)this.measure(e,t);for(let e of this.images)e.stream?.want(e.wanted);this.streamer.update()}}restart(){if(!this.closed){for(let e of this.images)e.drop();this.streamer.dispose(),this.start();for(let e of this.images)this.begin(e).catch(e=>(this.options.onError??console.error)(e))}}dispose(){if(!this.closed){this.closed=!0;for(let e of this.images)e.drop();this.images.clear(),this.streamer.dispose(),this.engine.sceneOf(this.plugin)?.removePlugin(this.name)}}};export{p as GLTFTextureStream};
3
+ const t=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import{r as e}from"./texture-coordinates-XFsEMdU6.js";import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";import{KTX2Streamer as n,colorTwin as r}from"@margoengine/decoders/ktx2-stream";var i=4096;function a(e,t,n){let r=[1/0,1/0,1/0],a=[-1/0,-1/0,-1/0];for(let t=0;t<e.length;t+=20)for(let n=0;n<3;n++)r[n]=Math.min(r[n],e[t+n]),a[n]=Math.max(a[n],e[t+n]);let o=[0,1,2].map(e=>(r[e]+a[e])/2||0),s=Math.hypot(a[0]-r[0],a[1]-r[1],a[2]-r[2])/2||0,c=Math.floor(t.length/3),l=Math.max(1,Math.floor(c/i)),u=[0,0,0,0],d=0,f=(t,r,i)=>r<2?e[t*20+12+r*2+i]:n?.[t*4+(r-2)*2+i]??0;for(let n=0;n<c;n+=l){let r=t[n*3],i=t[n*3+1],a=t[n*3+2],o=r*20,s=i*20,c=a*20,l=e[s]-e[o],p=e[s+1]-e[o+1],m=e[s+2]-e[o+2],h=e[c]-e[o],g=e[c+1]-e[o+1],_=e[c+2]-e[o+2];d+=Math.hypot(p*_-m*g,m*h-l*_,l*g-p*h)/2;for(let e=0;e<4;e++){let t=f(r,e,0),n=f(r,e,1);u[e]+=Math.abs((f(i,e,0)-t)*(f(a,e,1)-n)-(f(a,e,0)-t)*(f(i,e,1)-n))/2}}return{centre:o,radius:s,spans:u.map(e=>e>0&&d>0?Math.sqrt(d/e):s*2)}}function o(e,t=0){return Math.max(Math.hypot(e[t],e[t+1],e[t+2]),Math.hypot(e[t+4],e[t+5],e[t+6]),Math.hypot(e[t+8],e[t+9],e[t+10]))}var s=.2,c=/* @__PURE__ */ new WeakMap,l=0,u=(e,t,n,r,i=0)=>[e[i]*t+e[i+4]*n+e[i+8]*r+e[i+12],e[i+1]*t+e[i+5]*n+e[i+9]*r+e[i+13],e[i+2]*t+e[i+6]*n+e[i+10]*r+e[i+14]];function d(e,t,n){let r=e.views?.length?e.views:[void 0],i=e.canvas.height,a=0;for(let o of r){let r=o?.camera??e.camera,s=r.planes,c=!0;if(s.some(e=>e!==0))for(let e=0;e<24;e+=4)s[e]*t[0]+s[e+1]*t[1]+s[e+2]*t[2]+s[e+3]<-n&&(c=!1);if(!c)continue;let l=r.position,u=Math.max(Math.hypot(t[0]-l[0],t[1]-l[1],t[2]-l[2])-n,r.near);a=Math.max(a,i/2/(u*Math.tan(r.fov*Math.PI/360)))}return a}var f=class{constructor(e,t){this.owner=e,this.source=t,this.streamed=!0,this.users=/* @__PURE__ */ new Set,this.width=1,this.height=1,this.wanted=0,this.views=/* @__PURE__ */ new Map}view(e,t){let n=this.stream;if(!n||this.owner.device!==e)return;let i=this.views.get(t);if(!i){let e=n.format.replace(/-srgb$/,``),a=t&&r(e)?r(e):e;this.views.set(t,i=n.texture.createView({format:a}))}return i}viewSize(){let e=this.stream?.texture;return e?{width:e.width,height:e.height,levels:e.mipLevelCount}:void 0}use(e){this.stream=e,this.width=e.width,this.height=e.height,e.onChange=()=>this.changed(),this.changed()}changed(){this.views.clear();for(let e of[...this.users])e.rebindStreamed(this)}drop(){this.stream?.dispose(),this.stream=void 0,this.views.clear()}close(){this.drop(),this.owner.forget(this)}},p=class r{static attach(e,t={},n){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));return new r(e,t,n)}constructor(e,n={},r=new AbortController().signal){this.options=n,this.signal=r,this.name=`gltf-pbr-textures-${++l}`,this.images=/* @__PURE__ */ new Set,this.models=/* @__PURE__ */ new Set,this.uses=/* @__PURE__ */ new WeakMap,this.since=0,this.closed=!1,this.engine=t(e),this.start();let i=this;this.engine.use(this.plugin={coreRequirement:/*@__PURE__*/__margoCoreRequirement("1.0.0",import.meta.url),name:this.name,setup(){},onPreUpdate(e){i.since+=e,i.since>=s&&i.update()},onDeviceRestored(){i.restart()}})}start(){this.streamer=new n({...this.options,device:this.engine.gpu,onError:e=>(this.options.onError??console.error)(e)})}get device(){return this.streamer.device}get budgetBytes(){return this.streamer.budgetBytes}set budgetBytes(e){this.streamer.budgetBytes=e}get usedBytes(){return this.streamer.usedBytes}get textures(){return[...this.images].flatMap(({stream:e,width:t,height:n,wanted:r})=>e?[{width:t,height:n,level:e.residentLevel,levels:e.levels,pixels:r}]:[])}async begin(e){let{source:t}=e,{streamer:n}=this,r={signal:this.signal,colorViews:!0},i=`bytes`in t?await n.open(t.bytes,r):await n.open(t.url,{...r,offset:t.offset,length:t.length});this.closed||!this.images.has(e)||n!==this.streamer?i.dispose():e.use(i)}async open(e){let t=new f(this,e);this.images.add(t);for(let e of this.models)t.users.add(e);return await this.begin(t),t}attach(e){this.models.add(e);for(let t of this.images)t.users.add(e);e.onDispose(()=>{this.models.delete(e),!this.models.size&&!this.images.size&&this.dispose()})}forget(e){this.images.delete(e),this.images.size||this.dispose()}mapsOf(t,n,r){let i=this.uses.get(r);return i||(i=r.maps.flatMap(r=>{let i=r&&n.textures?.[r.index],a=i?.extensions?.KHR_texture_basisu?.source??i?.source,o=a===void 0?void 0:t.images[a];if(!(o instanceof f))return[];let{texCoord:s,transform:c}=e(r);return[{image:o,set:s,repeat:(c?Math.min(Math.hypot(c[0],c[4]),Math.hypot(c[1],c[5])):1)||1}]}),r.maps.some(Boolean)&&this.uses.set(r,i)),i}measure(e,t){let n=this.mapsOf(e,e.asset.doc,t.material);if(!n.length)return;let r=c.get(t.vertices);r||c.set(t.vertices,r=a(t.vertices,t.indices,t.uvs));let{centre:i,radius:s,spans:l}=r,f=t.node.matrix,p=o(f),m=(e,t)=>{let r=d(this.engine,e,s*t)*t;for(let e of n)e.image.wanted=Math.max(e.image.wanted,r*(l[e.set]??0)/e.repeat)},h=t.instances;if(!h)m(u(f,...i),p);else for(let e=0,t=h.count;e<t;e++)m(u(f,...u(h.data,...i,e*24)),p*o(h.data,e*24))}update(){if(this.since=0,!this.closed){for(let e of this.images)e.wanted=0;for(let e of this.models)if(e.disposed)this.models.delete(e);else for(let t of e.primitives)this.measure(e,t);for(let e of this.images)e.stream?.want(e.wanted);this.streamer.update()}}restart(){if(!this.closed){for(let e of this.images)e.drop();this.streamer.dispose(),this.start();for(let e of this.images)this.begin(e).catch(e=>(this.options.onError??console.error)(e))}}dispose(){if(!this.closed){this.closed=!0;for(let e of this.images)e.drop();this.images.clear(),this.streamer.dispose(),this.engine.sceneOf(this.plugin)?.removePlugin(this.name)}}};export{p as GLTFTextureStream};
package/dist/textured.js CHANGED
@@ -1,5 +1,5 @@
1
- // @margo/core-built 0.1.0
1
+ // @margo/core-built 1.0.0
2
2
  import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
3
 
4
- import{n as e,r as t,t as n}from"./accessor-nVsu_f1L.js";import{r}from"./mesh-source-DvU8YvMc.js";import{i,n as a,r as o,t as s}from"./unit-light-DvtsuFYP.js";import{uploadRows as c}from"@margoengine/core/extension";import{MargoError as l}from"@margoengine/math/errors";var u=`KHR_texture_transform`,d=e=>/* @__PURE__ */ TypeError(`Invalid glTF ${e}; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`),f=e=>new l(`unsupported`,`${e} is not on the light path; load the file with @margoengine/gltf/pbr`);function p(e){let t=Object.keys(e.extensions??{}).filter(e=>e!==u);if(t.length)throw f(`Texture extension ${t[0]}`);let n=e.extensions?.[u];if(!n)return;let[r,i]=n.scale??[1,1],[a,o]=n.offset??[0,0],s=n.rotation??0,c=[Math.cos(s)*r,Math.sin(s)*i,a,-Math.sin(s)*r,Math.cos(s)*i,o];if(!c.every(Number.isFinite))throw d(`texture transform`);return c}function m(t,r){let i=r.pbrMetallicRoughness??{},a=i.baseColorTexture,o=r.alphaMode===`MASK`;if(!a&&!o||!o&&(r.alphaMode??`OPAQUE`)!==`OPAQUE`)return;let s=i.baseColorFactor?.[3]??1,c=o?r.alphaCutoff??.5:0,l={texCoord:0,alpha:s,cutoff:c};if(!(s>=0&&s<=1)||!(c>=0))throw d(`alpha`);if(a){let r=n(t.textures,a.index,`texture`);if(r.extensions&&Object.keys(r.extensions).length)throw f(`A compressed or WebP texture`);l.image=e(r.source,`texture source`),n(t.images,l.image,`image`),r.sampler!==void 0&&n(t.samplers,l.sampler=r.sampler,`sampler`),l.transform=p(a);let i=a.extensions?.[u];l.texCoord=e(i?.texCoord??a.texCoord??0,`texCoord`)}return l}async function h(t,r){let i=n(t.doc.images,r,`image`);if(i.bufferView!==void 0){let r=n(t.doc.bufferViews,i.bufferView,`bufferView`),a=t.buffers[e(r.buffer,`buffer reference`)],o=e(r.byteOffset??0,`view offset`),s=e(r.byteLength,`view length`,1);if(!a||o+s>a.length)throw RangeError(`glTF image is outside its buffer; re-export the file`);return a.subarray(o,o+s)}if(typeof i.uri!=`string`)throw d(`image`);let a=/^data:image\/[a-z+.-]+;base64,([A-Za-z0-9+/]*={0,2})$/.exec(i.uri);if(a)try{return Uint8Array.from(atob(a[1]),e=>e.charCodeAt(0))}catch(e){throw TypeError(`glTF image ${r} has a data: URI with invalid base64; re-export the file`,{cause:e})}if(!t.fetch)throw TypeError(`glTF image URI needs the file location; use loadGLTF`);return t.fetch(i.uri)}async function g(e,t){try{return await createImageBitmap(new Blob([e]),{colorSpaceConversion:`none`,premultiplyAlpha:`none`})}catch(e){throw TypeError(`glTF image ${t} could not be decoded (${e?.message??e}); re-export it as PNG or JPEG`,{cause:e})}}var _=e=>e===33071?`clamp-to-edge`:e===33648?`mirror-repeat`:`repeat`,v=(e={})=>{let t=e.minFilter;return{addressModeU:_(e.wrapS),addressModeV:_(e.wrapT),magFilter:e.magFilter===9728?`nearest`:`linear`,minFilter:t===9728||t===9984||t===9986?`nearest`:`linear`,mipmapFilter:t===9984||t===9985?`nearest`:`linear`,lodMaxClamp:t===9728||t===9729?0:32}};function y(e){let t=`@group(1) @binding(0) var baseMap:texture_2d<f32>;@group(1) @binding(1) var baseSampler:sampler;@group(1) @binding(2) var<uniform> surface:vec4f;
5
- `+e.replace(`struct Input {`,`struct Input { @location(15) uv:vec2f,`).replace(`struct Output {`,`struct Output { @location(14) uv:vec2f,`).replace(/(@vertex fn vertex\(i:Input\)[\s\S]*?)return o;/,`$1o.uv=i.uv;return o;`).replace(/@fragment fn fragment\(i:Output([^{]*)\{/,`@fragment fn fragment(source:Output$1{var i=source;let texel=textureSample(baseMap,baseSampler,i.uv);if(texel.a*surface.x<surface.y){discard;}i.color*=texel.rgb;`);if(!t.includes(`o.uv=i.uv`)||!t.includes(`var i=source`))throw new l(`failed`,`A package replaced the core shader parts @margoengine/gltf/textured patches; remove that package or load the file with @margoengine/gltf/pbr`);return t}var b=/* @__PURE__ */ new WeakMap,x=class{coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);constructor(){this.name=`gltf-textured`,this.parts=/* @__PURE__ */ new Map,this.values=/* @__PURE__ */ new Float32Array(32),this.textures=/* @__PURE__ */ new Map,this.mips=/* @__PURE__ */ new Map,this.pipelines=/* @__PURE__ */ new Map,this.shaders=/* @__PURE__ */ new Map,this.frameGroups=/* @__PURE__ */ new WeakMap,this.color={view:null,loadOp:`load`,storeOp:`store`},this.depth={view:null}}setup(e){if(!e.gpu)throw new l(`unsupported`,`Textured glTF needs WebGPU or the WebGL2 compatibility layer; call install() from @margoengine/webgl2-compat before Engine.create where WebGPU is missing; see https://margoengine.com/errors#webgpu`);this.engine=e,this.frame=e.gpu.createBuffer({size:128,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})}registerPasses(e){e.add({name:`gltf-textured:claim`,order:-1e6,execute:e=>{e.backend===`webgpu`&&this.claim(e)}}),e.add({name:`gltf-textured:draw`,order:.5,joins:!0,execute:e=>{e.backend===`webgpu`&&this.draw(e)}})}add(e){this.parts.set(e.geometry,e),this.upload(e)}remove(e){if(this.parts.delete(e.geometry),r(e.geometry,void 0),e.uvBuffer?.destroy(),e.block?.destroy(),e.casterBuffer?.destroy(),e.bitmap&&![...this.parts.values()].some(t=>t.bitmap===e.bitmap)){for(let t of this.textures.get(e.bitmap)?.values()??[])t.destroy();this.textures.delete(e.bitmap)}}texture(e,t,n=0){let r=this.engine.gpu,o=e?this.textures.get(e)?.get(n):this.white;if(o)return o;let{width:s,height:c}=e??{width:1,height:1},l=r.limits.maxTextureDimension2D;if(s>l||c>l)throw RangeError(`glTF image is ${s} x ${c}, over this GPU's ${l}; resize it`);let u=Math.floor(Math.log2(Math.max(s,c)))+1,d=r.createTexture({size:[s,c],format:`rgba8unorm-srgb`,mipLevelCount:u,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT});if(e){r.queue.copyExternalImageToTexture({source:e},{texture:d},[s,c]),n&&t?a(r,d,u,this.mips,t.cutoff,t.alpha):i(r,d,u,this.mips);let o=this.textures.get(e);o||this.textures.set(e,o=/* @__PURE__ */ new Map),o.set(n,d)}else r.queue.writeTexture({texture:d},new Uint8Array([255,255,255,255]),{},[1,1]),this.white=d;return d}upload(e){e.keep=e.bitmap&&e.sampler.lodMaxClamp!==0?o(e.surface.cutoff,e.surface.alpha):0;let t=this.engine.gpu,n=this.texture(e.bitmap,e.surface,e.keep);r(e.geometry,{uv:e.uv,caster:e.surface.cutoff>0?this.caster(e,n):void 0}),e.uvBuffer=t.createBuffer({size:e.uv.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),t.queue.writeBuffer(e.uvBuffer,0,e.uv),e.block=t.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),t.queue.writeBuffer(e.block,0,new Float32Array([e.surface.alpha,e.surface.cutoff,0,0])),e.groups=/* @__PURE__ */ new WeakMap,e.sent=!1}caster(e,t){let n=this.engine.gpu,r=e.geometry.vertices,i=r.length/6,a=new Float32Array(i*20);for(let t=0;t<i;t++)a.set(r.subarray(t*6,t*6+3),t*20),a.set(e.uv.subarray(t*2,t*2+2),t*20+12);return e.casterBuffer=n.createBuffer({size:a.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),n.queue.writeBuffer(e.casterBuffer,0,a),{vertex:e.casterBuffer,stride:80,alphaTexture:t.createView(),alphaSampler:n.createSampler(e.sampler),alpha:e.surface.alpha,cutoff:e.surface.cutoff,vertexAlpha:!1}}claim(e){let t=e.batches??[];for(let n=0;n<t.length;n++){let r=t[n],i=this.parts.get(r.geometry);i&&(!r.claimed&&(r.count||r.redirect)&&this.engine.stats.drawCalls--,r.claimed=!0,c(e.device.queue,this.engine.geometryBuffers(r.geometry).instance,r,!i.sent),i.sent=!0)}}pipeline(e){let t=e.descriptor,n=`${t.multisample?.count} ${e.format} ${t.depthStencil?.format} ${e.shader}`,r=this.pipelines.get(n);if(!r){let i=e.device.createShaderModule({code:this.shaderFor(e.shader)});r=e.device.createRenderPipeline({...t,vertex:{...t.vertex,module:i,buffers:[...t.vertex.buffers,{arrayStride:8,attributes:[{shaderLocation:15,offset:0,format:`float32x2`}]}]},fragment:{...t.fragment,module:i,targets:[{format:e.format}]}}),this.pipelines.set(n,r)}return r}shaderFor(e){let t=this.shaders.get(e);return t===void 0&&this.shaders.set(e,t=y(e)),t}frameGroup(e,t){let n=this.frameGroups.get(t),r=e.bindings;if(n&&n.bindings.length===r.length&&n.bindings.every((e,t)=>e.binding===r[t].binding&&e.resource===r[t].resource))return n.group;let i=e.device.createBindGroup({layout:t.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.frame}},...r]});return this.frameGroups.set(t,{group:i,bindings:[...r]}),i}surfaceGroup(e,t,n){let r=n.groups.get(t);return r||(r=e.device.createBindGroup({layout:t.getBindGroupLayout(1),entries:[{binding:0,resource:this.texture(n.bitmap,n.surface,n.keep).createView()},{binding:1,resource:e.device.createSampler(n.sampler)},{binding:2,resource:{buffer:n.block}}]}),n.groups.set(t,r)),r}draw(e){let t=e.batches??[],n,r;for(let i=0;i<t.length;i++){let a=t[i],o=this.parts.get(a.geometry);if(!o||!a.count&&!a.redirect)continue;if(!n){r=this.pipeline(e);let{direction:t,radiance:i,ambient:a}=this.engine.lighting,o=this.values;o.set(e.camera.matrix),o.set(e.camera.position,16),s(o,20,t),o.set(i,24),o.fill(1,28,31),a&&o.set(a,28),e.device.queue.writeBuffer(this.frame,0,o);let c=this.color,l=this.depth,u=e.descriptor.depthStencil.format.includes(`stencil`);c.view=e.color,c.loadOp=`load`,c.storeOp=`store`,c.resolveTarget=void 0,l.view=e.depth,l.depthLoadOp=`load`,l.depthStoreOp=`store`,l.stencilLoadOp=u?`load`:void 0,l.stencilStoreOp=u?`store`:void 0,e.attach?.(c,l,!0),n=e.encoder.beginRenderPass({colorAttachments:[c],depthStencilAttachment:l});let d=e.view;d&&(n.setViewport(...d.viewport,0,1),n.setScissorRect(...d.scissor??d.viewport)),n.setPipeline(r),n.setBindGroup(0,this.frameGroup(e,r))}let c=this.engine.geometryBuffers(a.geometry),l=a.redirect;n.setBindGroup(1,this.surfaceGroup(e,r,o)),n.setVertexBuffer(0,c.vertex),n.setVertexBuffer(1,l?.instances??c.instance),n.setVertexBuffer(2,o.uvBuffer),n.setIndexBuffer(c.index,`uint32`),l?n.drawIndexedIndirect(l.args,0):n.drawIndexed(a.geometry.indices.length,a.count),this.engine.stats.drawCalls++}n?.end()}onDeviceRestored(e){this.release(),this.setup(e);for(let e of this.parts.values())this.upload(e)}release(){this.frame?.destroy(),this.white?.destroy(),this.white=void 0;for(let e of this.textures.values())for(let t of e.values())t.destroy();this.textures.clear(),this.mips=/* @__PURE__ */ new Map,this.pipelines.clear()}dispose(){this.release();for(let e of this.parts.values())r(e.geometry,void 0),e.uvBuffer?.destroy(),e.block?.destroy(),e.casterBuffer?.destroy();this.parts.clear()}},S=/* @__PURE__ */ new WeakMap,C=/* @__PURE__ */ new WeakMap;function w(e){if(typeof OffscreenCanvas>`u`)throw TypeError(`texturedAlphaMasks needs OffscreenCanvas to read an image here; pass the pixels option.`);let t=new OffscreenCanvas(e.width,e.height).getContext(`2d`,{willReadFrequently:!0});return t.drawImage(e,0,0),t.getImageData(0,0,e.width,e.height)}var T=e=>e===`clamp-to-edge`?`clamp`:e===`mirror-repeat`?`mirror`:`repeat`;async function E(e,{signal:t,pixels:n=w}={}){let r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map;for(let a of C.get(e)??[]){t?.throwIfAborted();let{surface:e,bitmap:o,sampler:s,geometry:c}=a;if(!(e.cutoff>0))continue;let l={width:1,height:1,data:[255,255,255,255]};o&&(l=i.get(o)??await n(o),i.set(o,l)),r.set(c,{width:l.width,height:l.height,data:l.data,cutoff:e.cutoff,factor:e.alpha,wrap:[T(s.addressModeU),T(s.addressModeV)]})}return t?.throwIfAborted(),e=>r.get(e.mesh.geometry)??null}var D={handles:[u],async load(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;S.set(e,{images:n,surfaces:t}),(e.doc.materials??[]).forEach((n,r)=>{let i=m(e.doc,n);i&&t.set(r,i)});let r=new Set([...t.values()].flatMap(({image:e})=>e===void 0?[]:[e])),i=(await Promise.allSettled([...r].map(async t=>{n.set(t,await g(await h(e,t),t))}))).find(e=>e.status===`rejected`);if(i)throw D.abandon(e),i.reason},abandon(e){let t=S.get(e);if(S.delete(e),t&&!t.owned)for(let e of t.images.values())e.close()},read(e){let{surfaces:t}=S.get(e);e.doc={...e.doc,materials:e.doc.materials?.map((e,n)=>{if(!t.has(n))return e;let{alphaMode:r,alphaCutoff:i,...a}=e,{baseColorTexture:o,baseColorFactor:s=[1,1,1,1],...c}=e.pbrMetallicRoughness??{};return{...a,pbrMetallicRoughness:{...c,baseColorFactor:[s[0],s[1],s[2],1]}}})}},finish(e,n,r){let i=S.get(n),{images:a,surfaces:o}=i,s=r.engine,c=[];for(let{geometry:e,source:i,expanded:s}of r.primitives){let r=i.material===void 0?void 0:o.get(i.material);if(!r)continue;let l=(()=>{if(r.image===void 0)return new Float32Array(e.vertices.length/6*2);let a=i.attributes?.[`TEXCOORD_${r.texCoord}`];if(a===void 0)throw d(`primitive: its material needs TEXCOORD_${r.texCoord}`);return t(n,a,2,e=>e.type===`VEC2`&&[5126,5120,5121,5122,5123].includes(e.componentType))})(),u=e.vertices.length/6,f=new Float32Array(u*2),p=r.transform??[1,0,0,0,1,0];for(let e=0;e<u;e++){let t=s?s[e]:e,n=l[t*2],r=l[t*2+1];if(n===void 0||r===void 0)throw RangeError(`glTF TEXCOORD has fewer vertices than POSITION; re-export the file`);f[e*2]=p[0]*n+p[1]*r+p[2],f[e*2+1]=p[3]*n+p[4]*r+p[5]}c.push({geometry:e,uv:f,surface:r,bitmap:r.image===void 0?void 0:a.get(r.image),sampler:v(r.sampler===void 0?void 0:n.doc.samplers?.[r.sampler]),keep:0,groups:/* @__PURE__ */ new WeakMap,sent:!1})}if(!c.length)return;let l=s.frameGraph,u=b.get(l);u||(u=new x,s.use(u),b.set(l,u));let f=u,p=()=>{f.parts.size||(b.delete(l),s.sceneOf(f)?.removePlugin(f.name))};try{for(let e of c)f.add(e)}catch(e){for(let e of c)f.parts.get(e.geometry)===e&&f.remove(e);throw p(),e}i.owned=!0,C.set(e,c);let m=e.dispose,h=!0;e.dispose=()=>{if(h){h=!1;for(let e of c)f.remove(e);for(let e of a.values())e.close();p()}m()}}};export{D as textured,E as texturedAlphaMasks};
4
+ import{n as e,r as t,t as n}from"./accessor-CU_1uSZ1.js";import{r}from"./mesh-source-DvU8YvMc.js";import{t as i}from"./mipmaps-38NmjDc3.js";import{a,i as o,n as s,r as c,t as l}from"./warning-UqjZyyqW.js";import{uploadRows as u}from"@margoengine/core/extension";import{MargoError as d}from"@margoengine/math/errors";var f=`KHR_texture_transform`,p=e=>/* @__PURE__ */ TypeError(`Invalid glTF ${e}; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`),m=e=>new d(`unsupported`,`${e} is not on the light path; load the file with @margoengine/gltf/pbr`);function h(e){let t=Object.keys(e.extensions??{}).filter(e=>e!==f);if(t.length)throw m(`Texture extension ${t[0]}`);let n=e.extensions?.[f];if(!n)return;let[r,i]=n.scale??[1,1],[a,o]=n.offset??[0,0],s=n.rotation??0,c=[Math.cos(s)*r,Math.sin(s)*i,a,-Math.sin(s)*r,Math.cos(s)*i,o];if(!c.every(Number.isFinite))throw p(`texture transform`);return c}function g(t,r){let i=r.pbrMetallicRoughness??{},a=i.baseColorTexture,o=r.alphaMode===`MASK`;if(!a&&!o||!o&&(r.alphaMode??`OPAQUE`)!==`OPAQUE`)return;let s=i.baseColorFactor?.[3]??1,c=o?r.alphaCutoff??.5:0,l={texCoord:0,alpha:s,cutoff:c};if(!(s>=0&&s<=1)||!(c>=0))throw p(`alpha`);if(a){let r=n(t.textures,a.index,`texture`);if(r.extensions&&Object.keys(r.extensions).length)throw m(`A compressed or WebP texture`);l.image=e(r.source,`texture source`),n(t.images,l.image,`image`),r.sampler!==void 0&&n(t.samplers,l.sampler=r.sampler,`sampler`),l.transform=h(a);let i=a.extensions?.[f];l.texCoord=e(i?.texCoord??a.texCoord??0,`texCoord`)}return l}async function _(t,r){let i=n(t.doc.images,r,`image`);if(i.bufferView!==void 0){let r=n(t.doc.bufferViews,i.bufferView,`bufferView`),a=t.buffers[e(r.buffer,`buffer reference`)],o=e(r.byteOffset??0,`view offset`),s=e(r.byteLength,`view length`,1);if(!a||o+s>a.length)throw RangeError(`glTF image is outside its buffer; re-export the file`);return a.subarray(o,o+s)}if(typeof i.uri!=`string`)throw p(`image`);let a=/^data:image\/[a-z+.-]+;base64,([A-Za-z0-9+/]*={0,2})$/.exec(i.uri);if(a)try{return Uint8Array.from(atob(a[1]),e=>e.charCodeAt(0))}catch(e){throw TypeError(`glTF image ${r} has a data: URI with invalid base64; re-export the file`,{cause:e})}if(!t.fetch)throw TypeError(`glTF image URI needs the file location; use loadGLTF`);return t.fetch(i.uri)}async function v(e,t){try{return await createImageBitmap(new Blob([e]),{colorSpaceConversion:`none`,premultiplyAlpha:`none`})}catch(e){throw TypeError(`glTF image ${t} could not be decoded (${e?.message??e}); re-export it as PNG or JPEG`,{cause:e})}}var y=e=>e===33071?`clamp-to-edge`:e===33648?`mirror-repeat`:`repeat`,b=(e={})=>{let t=e.minFilter;return{addressModeU:y(e.wrapS),addressModeV:y(e.wrapT),magFilter:e.magFilter===9728?`nearest`:`linear`,minFilter:t===9728||t===9984||t===9986?`nearest`:`linear`,mipmapFilter:t===9984||t===9985?`nearest`:`linear`,lodMaxClamp:t===9728||t===9729?0:32}};function x(e){let t=`@group(1) @binding(0) var baseMap:texture_2d<f32>;@group(1) @binding(1) var baseSampler:sampler;@group(1) @binding(2) var<uniform> surface:vec4f;
5
+ `+e.replace(`struct Input {`,`struct Input { @location(15) uv:vec2f,`).replace(`struct Output {`,`struct Output { @location(14) uv:vec2f,`).replace(/(@vertex fn vertex\(i:Input\)[\s\S]*?)return o;/,`$1o.uv=i.uv;return o;`).replace(/@fragment fn fragment\(i:Output([^{]*)\{/,`@fragment fn fragment(source:Output$1{var i=source;let texel=textureSample(baseMap,baseSampler,i.uv);if(texel.a*surface.x<surface.y){discard;}i.color*=texel.rgb;`);if(!t.includes(`o.uv=i.uv`)||!t.includes(`var i=source`))throw new d(`failed`,`A package replaced the core shader parts @margoengine/gltf/textured patches; remove that package or load the file with @margoengine/gltf/pbr`);return t}var S=/* @__PURE__ */ new WeakMap,C=class{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);constructor(){this.name=`gltf-textured`,this.parts=/* @__PURE__ */ new Map,this.values=/* @__PURE__ */ new Float32Array(32),this.textures=/* @__PURE__ */ new Map,this.mips=/* @__PURE__ */ new Map,this.pipelines=/* @__PURE__ */ new Map,this.shaders=/* @__PURE__ */ new Map,this.frameGroups=/* @__PURE__ */ new WeakMap,this.color={view:null,loadOp:`load`,storeOp:`store`},this.depth={view:null}}setup(e){if(!e.gpu)throw new d(`unsupported`,`Textured glTF needs WebGPU or the WebGL2 compatibility layer; call install() from @margoengine/webgl2-compat before Engine.create where WebGPU is missing; see https://margoengine.com/errors#webgpu`);this.engine=e,this.frame=e.gpu.createBuffer({size:128,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})}registerPasses(e){e.add({name:`gltf-textured:claim`,order:-1e6,execute:e=>{e.backend===`webgpu`&&this.claim(e)}}),e.add({name:`gltf-textured:draw`,order:.5,joins:!0,execute:e=>{e.backend===`webgpu`&&this.draw(e)}})}add(e){this.parts.set(e.geometry,e),this.upload(e)}remove(e){if(this.parts.delete(e.geometry),r(e.geometry,void 0),e.uvBuffer?.destroy(),e.block?.destroy(),e.casterBuffer?.destroy(),e.bitmap&&![...this.parts.values()].some(t=>t.bitmap===e.bitmap)){for(let t of this.textures.get(e.bitmap)?.values()??[])t.destroy();this.textures.delete(e.bitmap)}}texture(e,t,n=0){let r=this.engine.gpu,a=e?this.textures.get(e)?.get(n):this.white;if(a)return a;let{width:s,height:c}=e??{width:1,height:1},l=r.limits.maxTextureDimension2D;if(s>l||c>l)throw RangeError(`glTF image is ${s} x ${c}, over this GPU's ${l}; resize it`);let u=Math.floor(Math.log2(Math.max(s,c)))+1,d=r.createTexture({size:[s,c],format:`rgba8unorm-srgb`,mipLevelCount:u,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT});if(e){r.queue.copyExternalImageToTexture({source:e},{texture:d},[s,c]),n&&t?o(r,d,u,this.mips,t.cutoff,t.alpha):i(r,d,u,this.mips);let a=this.textures.get(e);a||this.textures.set(e,a=/* @__PURE__ */ new Map),a.set(n,d)}else r.queue.writeTexture({texture:d},new Uint8Array([255,255,255,255]),{},[1,1]),this.white=d;return d}upload(e){e.keep=e.bitmap&&e.sampler.lodMaxClamp!==0?a(e.surface.cutoff,e.surface.alpha):0;let t=this.engine.gpu,n=this.texture(e.bitmap,e.surface,e.keep);r(e.geometry,{uv:e.uv,caster:e.surface.cutoff>0?this.caster(e,n):void 0}),e.uvBuffer=t.createBuffer({size:e.uv.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),t.queue.writeBuffer(e.uvBuffer,0,e.uv),e.block=t.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),t.queue.writeBuffer(e.block,0,new Float32Array([e.surface.alpha,e.surface.cutoff,0,0])),e.groups=/* @__PURE__ */ new WeakMap,e.sent=!1}caster(e,t){let n=this.engine.gpu,r=e.geometry.vertices,i=r.length/6,a=new Float32Array(i*20);for(let t=0;t<i;t++)a.set(r.subarray(t*6,t*6+3),t*20),a.set(e.uv.subarray(t*2,t*2+2),t*20+12);return e.casterBuffer=n.createBuffer({size:a.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),n.queue.writeBuffer(e.casterBuffer,0,a),{vertex:e.casterBuffer,stride:80,alphaTexture:t.createView(),alphaSampler:n.createSampler(e.sampler),alpha:e.surface.alpha,cutoff:e.surface.cutoff,vertexAlpha:!1}}claim(e){let t=e.batches??[];for(let n=0;n<t.length;n++){let r=t[n],i=this.parts.get(r.geometry);i&&(!r.claimed&&(r.count||r.redirect)&&this.engine.stats.drawCalls--,r.claimed=!0,u(e.device.queue,this.engine.geometryBuffers(r.geometry).instance,r,!i.sent),i.sent=!0)}}pipeline(e){let t=e.descriptor,n=`${t.multisample?.count} ${e.format} ${t.depthStencil?.format} ${e.shader}`,r=this.pipelines.get(n);if(!r){let i=e.device.createShaderModule({code:this.shaderFor(e.shader)});r=e.device.createRenderPipeline({...t,vertex:{...t.vertex,module:i,buffers:[...t.vertex.buffers,{arrayStride:8,attributes:[{shaderLocation:15,offset:0,format:`float32x2`}]}]},fragment:{...t.fragment,module:i,targets:[{format:e.format}]}}),this.pipelines.set(n,r)}return r}shaderFor(e){let t=this.shaders.get(e);return t===void 0&&this.shaders.set(e,t=x(e)),t}frameGroup(e,t){let n=this.frameGroups.get(t),r=e.bindings;if(n&&n.bindings.length===r.length&&n.bindings.every((e,t)=>e.binding===r[t].binding&&e.resource===r[t].resource))return n.group;let i=e.device.createBindGroup({layout:t.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.frame}},...r]});return this.frameGroups.set(t,{group:i,bindings:[...r]}),i}surfaceGroup(e,t,n){let r=n.groups.get(t);return r||(r=e.device.createBindGroup({layout:t.getBindGroupLayout(1),entries:[{binding:0,resource:this.texture(n.bitmap,n.surface,n.keep).createView()},{binding:1,resource:e.device.createSampler(n.sampler)},{binding:2,resource:{buffer:n.block}}]}),n.groups.set(t,r)),r}draw(e){let t=e.batches??[],n,r;for(let i=0;i<t.length;i++){let a=t[i],o=this.parts.get(a.geometry);if(!o||!a.count&&!a.redirect)continue;if(!n){r=this.pipeline(e);let{direction:t,radiance:i,ambient:a}=this.engine.lighting,o=this.values;o.set(e.camera.matrix),o.set(e.camera.position,16),c(o,20,t),o.set(i,24),o.fill(1,28,31),a&&o.set(a,28),e.device.queue.writeBuffer(this.frame,0,o);let s=this.color,l=this.depth,u=e.descriptor.depthStencil.format.includes(`stencil`);s.view=e.color,s.loadOp=`load`,s.storeOp=`store`,s.resolveTarget=void 0,l.view=e.depth,l.depthLoadOp=`load`,l.depthStoreOp=`store`,l.stencilLoadOp=u?`load`:void 0,l.stencilStoreOp=u?`store`:void 0,e.attach?.(s,l,!0),n=e.encoder.beginRenderPass({colorAttachments:[s],depthStencilAttachment:l});let d=e.view;d&&(n.setViewport(...d.viewport,0,1),n.setScissorRect(...d.scissor??d.viewport)),n.setPipeline(r),n.setBindGroup(0,this.frameGroup(e,r))}let s=this.engine.geometryBuffers(a.geometry),l=a.redirect;n.setBindGroup(1,this.surfaceGroup(e,r,o)),n.setVertexBuffer(0,s.vertex),n.setVertexBuffer(1,l?.instances??s.instance),n.setVertexBuffer(2,o.uvBuffer),n.setIndexBuffer(s.index,`uint32`),l?n.drawIndexedIndirect(l.args,0):n.drawIndexed(a.geometry.indices.length,a.count),this.engine.stats.drawCalls++}n?.end()}onDeviceRestored(e){this.release(),this.setup(e);for(let e of this.parts.values())this.upload(e)}release(){this.frame?.destroy(),this.white?.destroy(),this.white=void 0;for(let e of this.textures.values())for(let t of e.values())t.destroy();this.textures.clear(),this.mips=/* @__PURE__ */ new Map,this.pipelines.clear()}dispose(){this.release();for(let e of this.parts.values())r(e.geometry,void 0),e.uvBuffer?.destroy(),e.block?.destroy(),e.casterBuffer?.destroy();this.parts.clear()}},w=/* @__PURE__ */ new WeakMap,T=/* @__PURE__ */ new WeakMap;function E(e){if(typeof OffscreenCanvas>`u`)throw TypeError(`texturedAlphaMasks needs OffscreenCanvas to read an image here; pass the pixels option.`);let t=new OffscreenCanvas(e.width,e.height).getContext(`2d`,{willReadFrequently:!0});return t.drawImage(e,0,0),t.getImageData(0,0,e.width,e.height)}var D=e=>e===`clamp-to-edge`?`clamp`:e===`mirror-repeat`?`mirror`:`repeat`;async function O(e,{signal:t,pixels:n=E}={}){let r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map;for(let a of T.get(e)??[]){t?.throwIfAborted();let{surface:e,bitmap:o,sampler:s,geometry:c}=a;if(!(e.cutoff>0))continue;let l={width:1,height:1,data:[255,255,255,255]};o&&(l=i.get(o)??await n(o),i.set(o,l)),r.set(c,{width:l.width,height:l.height,data:l.data,cutoff:e.cutoff,factor:e.alpha,wrap:[D(s.addressModeU),D(s.addressModeV)]})}return t?.throwIfAborted(),e=>r.get(e.mesh.geometry)??null}var k={handles:[f],async load(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;w.set(e,{images:n,surfaces:t}),(e.doc.materials??[]).forEach((n,r)=>{let i=g(e.doc,n);i&&t.set(r,i)});let r=new Set([...t.values()].flatMap(({image:e})=>e===void 0?[]:[e])),i=(await Promise.allSettled([...r].map(async t=>{n.set(t,await v(await _(e,t),t))}))).find(e=>e.status===`rejected`);if(i)throw k.abandon(e),i.reason},abandon(e){let t=w.get(e);if(w.delete(e),t&&!t.owned)for(let e of t.images.values())e.close()},read(e){let{surfaces:t}=w.get(e);e.doc={...e.doc,materials:e.doc.materials?.map((e,n)=>{if(!t.has(n))return e;let{alphaMode:r,alphaCutoff:i,...a}=e,{baseColorTexture:o,baseColorFactor:s=[1,1,1,1],...c}=e.pbrMetallicRoughness??{};return{...a,pbrMetallicRoughness:{...c,baseColorFactor:[s[0],s[1],s[2],1]}}})}},finish(e,n,r){let i=w.get(n),{images:a,surfaces:o}=i,c=r.engine,u=[];for(let{geometry:i,source:c,expanded:d}of r.primitives){let r=c.material===void 0?void 0:o.get(c.material);if(!r)continue;let f=c.attributes?.[`TEXCOORD_${r.texCoord}`],p=r.image!==void 0&&f===void 0;p&&l(e.warnings,s(c.material,n.doc.materials?.[c.material]?.name,`baseColorTexture`,r.texCoord));let m=r.image===void 0||f===void 0?new Float32Array(i.vertices.length/6*2):t(n,f,2,e=>e.type===`VEC2`&&[5126,5120,5121,5122,5123].includes(e.componentType)),h=i.vertices.length/6,g=new Float32Array(h*2),_=r.transform??[1,0,0,0,1,0];for(let e=0;e<h;e++){let t=d?d[e]:e,n=m[t*2],r=m[t*2+1];if(n===void 0||r===void 0)throw RangeError(`glTF TEXCOORD has fewer vertices than POSITION; re-export the file`);g[e*2]=_[0]*n+_[1]*r+_[2],g[e*2+1]=_[3]*n+_[4]*r+_[5]}u.push({geometry:i,uv:g,surface:r,bitmap:r.image===void 0||p?void 0:a.get(r.image),sampler:b(r.sampler===void 0?void 0:n.doc.samplers?.[r.sampler]),keep:0,groups:/* @__PURE__ */ new WeakMap,sent:!1})}if(!u.length)return;let d=c.frameGraph,f=S.get(d);f||(f=new C,c.use(f),S.set(d,f));let p=f,m=()=>{p.parts.size||(S.delete(d),c.sceneOf(p)?.removePlugin(p.name))};try{for(let e of u)p.add(e)}catch(e){for(let e of u)p.parts.get(e.geometry)===e&&p.remove(e);throw m(),e}i.owned=!0,T.set(e,u);let h=e.dispose,g=!0;e.dispose=()=>{if(g){g=!1;for(let e of u)p.remove(e);for(let e of a.values())e.close();m()}h()}}};export{k as textured,O as texturedAlphaMasks};
@@ -0,0 +1,81 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { type Engine, type EnginePlugin, type FrameGraph, type PassContext } from '@margoengine/core/extension';
4
+ import type { PBRModel, PBRTransmission } from './model.js';
5
+ import type { GLTFTransmissionPass } from './asset.js';
6
+ type Context = Extract<PassContext, {
7
+ backend: 'webgpu';
8
+ }>;
9
+ /** Options for `Transmission.attach()`: the frame graph `order` (default 3) and `depthWrite` (default false). */
10
+ export interface TransmissionPassOptions {
11
+ /** Frame graph order of the copy and the transmissive draws: after the opaque scene (1) and sky (2), before water (4), fog (5) and OIT (8). Default 3. */
12
+ order?: number;
13
+ /**
14
+ * True: OPAQUE and MASK glass draws unblended and writes depth, so a glass surface hides glass behind it (a solid
15
+ * sphere's back faces and their highlights) whatever the draw order, and later passes (water, fog, OIT) see the glass
16
+ * depth. BLEND glass stays blended without writes. Default false: every surface blends, depth read-only.
17
+ */
18
+ depthWrite?: boolean;
19
+ }
20
+ /**
21
+ * Real transmission: `transmission.add(model)` makes a gltf/pbr model's or materials mesh's transmissive surfaces refract
22
+ * the opaque scene behind them, blurred by roughness and attenuated through `thickness` of the volume, instead of tinting
23
+ * the background. It reads the view's scene capture: an HDR or display PostStack target, or gltf's native glass capture of
24
+ * the display target (decoded to linear light). A view with neither (an environment probe face, an external renderer
25
+ * pass) keeps the tinted blend (`takes`). The scene is copied (a mip chain) only on frames where a transmissive surface
26
+ * draws. WebGPU only.
27
+ */
28
+ export declare class Transmission implements EnginePlugin, PBRTransmission {
29
+ readonly name: string;
30
+ readonly order: number;
31
+ readonly depthWrite: boolean;
32
+ targets: readonly GPUColorTargetState[];
33
+ private engine?;
34
+ /** Device of the current GPU resources, so a release after device restoration retires them on their own device. */
35
+ private device?;
36
+ private disposed;
37
+ private readonly models;
38
+ private readonly code;
39
+ private readonly formats;
40
+ private texture?;
41
+ private view?;
42
+ private levels;
43
+ private reduceGroups;
44
+ private source?;
45
+ private sourceGroup?;
46
+ private sampler?;
47
+ private pipelines?;
48
+ private sourcePipeline?;
49
+ private context?;
50
+ private pass?;
51
+ /** Reused back-to-front list. Filled from the model map each frame so equal distances stay in insertion order. */
52
+ private readonly ordered;
53
+ static attach(engine: EngineKernel, options?: TransmissionPassOptions): Transmission;
54
+ constructor({ order, depthWrite }?: TransmissionPassOptions);
55
+ /** Refracts the scene through the model's transmissive primitives (gltf\/pbr model or materials mesh). Returns a remover. */
56
+ add(model: PBRModel): () => void;
57
+ setup(engine: Engine): void;
58
+ registerPasses(graph: FrameGraph): void;
59
+ /** @internal gltf\/pbr transmission hook. */
60
+ declarations(group: number): string;
61
+ /** @internal gltf\/pbr transmission hook. */
62
+ bindings(): GPUBindGroupEntry[];
63
+ /** @internal gltf\/pbr transmission hook: copies the scene, then begins the pass the transmissive surfaces draw in. */
64
+ begin(): GPURenderPassEncoder;
65
+ /** @internal gltf\/pbr transmission hook: whether this view has a scene to read (else its surfaces keep the tint). */
66
+ takes(c: Context): boolean;
67
+ private render;
68
+ private release;
69
+ onDeviceRestored(engine: Engine): void;
70
+ /** Restores the tinted blend on every added model and frees the scene copy. */
71
+ dispose(): void;
72
+ [Symbol.dispose]: () => void;
73
+ }
74
+ /**
75
+ * The default screen-space transmission of `loadGLTF` and `parseGLTFAsync` (`decoders.transmission`): every model
76
+ * whose file declares KHR_materials_transmission joins one `Transmission` per scene, created with `depthWrite: true`,
77
+ * which goes away with the last such model. Pass it to synchronous `parseGLTF` as
78
+ * `{materials: extendedMaterials, transmission: screenTransmission}`; `{transmission: false}` keeps the tinted blend.
79
+ */
80
+ export declare const screenTransmission: GLTFTransmissionPass;
81
+ export {};
@@ -0,0 +1,66 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const s=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import{n as e}from"./mipmaps-38NmjDc3.js";import{f as t,i as n,l as r,o as i,p as a,s as o}from"./native-glass-D85twud0.js";import{engineRuntime as __margoRuntime,margoError as c}from"@margoengine/core/extension";var l=((254.5/255+.055)/1.055)**2.4;.56+.0576/(1-l);var u=`fn pbrNeutralInverse(input:vec3f)->vec3f {let top=${l};var peak=max(input.r,max(input.g,input.b));var v=max(input*select(1.0,top/peak,peak>top),vec3f(0.0));peak=min(peak,top);if(peak>=0.76){let old=0.52+0.24*0.24/(1.0-peak);let keep=1.0/(0.15*(old-peak)+1.0);v=(v-peak*(1.0-keep))/keep*old/peak;}let m=min(v.r,min(v.g,v.b));return v+select(0.04,0.4*sqrt(max(m,0.0))-m,m<0.04);}
5
+ `,d=/* @__PURE__ */ Object.freeze({color:{srcFactor:`src-alpha`,dstFactor:`one-minus-src-alpha`,operation:`add`},alpha:{srcFactor:`one`,dstFactor:`one-minus-src-alpha`,operation:`add`}});function f(e,t,n){let r=e.get(t);return r===void 0&&e.set(t,r=n(t)),r}var p=124,m=e=>`
6
+ @group(${e}) @binding(${p}) var margoScene:texture_2d<f32>;
7
+ @group(${e}) @binding(125) var margoSceneSampler:sampler;
8
+ fn margoTransmissionBehind(i:Out,n:vec3f,v:vec3f,ior:f32,path:f32,level:f32)->vec3f {
9
+ let r=refract(-v,faceForward(n,-v,n),1.0/ior);
10
+ let c=f.camera*vec4f(i.position+r*path,1.0);
11
+ let uv=clamp(c.xy/max(c.w,0.000001)*vec2f(0.5,-0.5)+0.5,vec2f(0),vec2f(1));
12
+ return textureSampleLevel(margoScene,margoSceneSampler,uv,level).rgb;
13
+ }
14
+ fn margoTransmissionLevel(roughness:f32,ior:f32,path:f32)->f32 {
15
+ let size=vec2f(textureDimensions(margoScene,0));
16
+ let alpha=roughness*roughness;
17
+ let sinTilt=alpha*inverseSqrt(1.0+alpha*alpha);
18
+ let sinOut=sinTilt/ior;
19
+ let tanOut=sinOut*inverseSqrt(1.0-sinOut*sinOut);
20
+ let deviation=max((alpha-tanOut)/(1.0+alpha*tanOut),0.0);
21
+ let wRow=vec3f(f.camera[0].w,f.camera[1].w,f.camera[2].w);
22
+ let yRow=vec3f(f.camera[0].y,f.camera[1].y,f.camera[2].y);
23
+ let reach=select(path,1.0,dot(wRow,wRow)>0.0);
24
+ let texels=deviation*reach*length(yRow)*size.y;
25
+ return clamp(log2(max(texels,1.0)),0.0,f32(textureNumLevels(margoScene)-1u));
26
+ }
27
+ fn margoVolumeChord(i:Out,n:vec3f,v:vec3f,ior:f32)->f32 {
28
+ let m=mat3x3f(f.model[0].xyz,f.model[1].xyz,f.model[2].xyz);
29
+ let r=refract(-v,faceForward(n,-v,n),1.0/ior);
30
+ let c0=cross(m[1],m[2]); let c1=cross(m[2],m[0]); let c2=cross(m[0],m[1]);
31
+ let normal=normalize(vec3f(dot(m[0],i.normal),dot(m[1],i.normal),dot(m[2],i.normal)));
32
+ let projected=abs(dot(vec3f(dot(c0,r),dot(c1,r),dot(c2,r)),normal));
33
+ return select(abs(dot(m[0],c0))/projected,1e30,projected==0.0);
34
+ }
35
+ fn margoTransmission(s:Surface,v:vec3f,i:Out)->vec3f {
36
+ let ior=select(max(f.ext.y,1.0),1e30,f.ext.y==0.0);
37
+ let path=max(margoVolume.x*s.th*margoVolumeThickness(i)*margoVolumeChord(i,s.n,v,ior),0.0);
38
+ var behind=margoTransmissionBehind(i,s.n,v,ior,path,margoTransmissionLevel(s.roughness,ior,path));
39
+ if(f.ext.w>0.0&&path>0.0){
40
+ let spread=(ior-1.0)*0.025*f.ext.w;
41
+ let red=max(1.0,ior-spread); let blue=ior+spread;
42
+ behind=vec3f(margoTransmissionBehind(i,s.n,v,red,path,margoTransmissionLevel(s.roughness,red,path)).r,behind.g,margoTransmissionBehind(i,s.n,v,blue,path,margoTransmissionLevel(s.roughness,blue,path)).b);
43
+ }
44
+ var transmittance=vec3f(1.0);
45
+ if(path>0.0){
46
+ let t=margoVolume.yzw;
47
+ transmittance=select(select(pow(max(t,vec3f(0.000001)),vec3f(path)),vec3f(0.0),t<=vec3f(0.0)),vec3f(1.0),t>=vec3f(1.0));
48
+ }
49
+ let keep=1.0-margoFresnelPeak(margoDielectricFresnel(s.f0,s.sw,clamp(dot(s.n,v),0.0,1.0)));
50
+ return (1.0-s.metal)*s.tr*keep*s.base.rgb*transmittance*behind;
51
+ }
52
+ `,h=`
53
+ @group(0) @binding(0) var source:texture_2d<f32>;
54
+ @vertex fn vertex(@builtin(vertex_index) k:u32)->@builtin(position) vec4f {
55
+ let corner=vec2f(f32((k<<1u)&2u),f32(k&2u));
56
+ return vec4f(corner*2.0-1.0,0.0,1.0);
57
+ }
58
+ @fragment fn level0(@builtin(position) p:vec4f)->@location(0) vec4f {
59
+ return textureLoad(source,vec2i(p.xy),0);
60
+ }
61
+ @fragment fn level0Display(@builtin(position) p:vec4f)->@location(0) vec4f {
62
+ let c=textureLoad(source,vec2i(p.xy),0);
63
+ let x=clamp(c.rgb,vec3f(0.0),vec3f(1.0));
64
+ return vec4f(pbrNeutralInverse(select(x/12.92,pow((x+0.055)/1.055,vec3f(2.4)),x>vec3f(0.04045))),c.a);
65
+ }
66
+ ${u}`,g=d,_=0,v=class l{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static attach(e,t){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let n=new l(t);return s(e).use(n),n}constructor({order:e=3,depthWrite:t=!1}={}){if(this.name=`transmission:`+_++,this.targets=[],this.disposed=!1,this.models=/* @__PURE__ */ new Map,this.code=/* @__PURE__ */ new Map,this.formats=/* @__PURE__ */ new Map,this.levels=[],this.reduceGroups=[],this.ordered=[],!Number.isFinite(e)||e<=0)throw RangeError(`Transmission order must be a number > 0`);if(typeof t!=`boolean`)throw TypeError(`Transmission depthWrite must be true or false`);this.order=e,this.depthWrite=t}add(e){if(this.disposed||!this.engine)throw c(this.disposed?`disposed`:`state`,this.disposed?`Transmission is disposed; create a new Transmission.`:`Transmission.add needs Transmission.attach(engine) first`);let t=this.models.get(e);if(!t){let n=e.setTransmission(this),r=e.onDispose(()=>this.models.delete(e));t=()=>{this.models.get(e)===t&&(this.models.delete(e),r(),n())},this.models.set(e,t)}return t}setup(e){if(this.disposed)throw c(`disposed`,`Transmission is disposed; create a new Transmission.`);if(!e.gpu)throw c(`unsupported`,`Transmission requires WebGPU: create the engine with a WebGPU device; see https://margoengine.com/errors#webgpu`);this.engine=e,this.device=e.gpu}registerPasses(e){e.add({name:this.name,order:this.order,execute:e=>{e.backend===`webgpu`&&this.render(e)}})}declarations(e){return f(this.code,e,m)}bindings(){return[{binding:p,resource:this.view},{binding:125,resource:this.sampler}]}begin(){if(this.pass)return this.pass;let e=this.context,t=o(e),r=e.encoder,s=this.pipelines;t?.resolve(r);let c=t?t.resolvedColor:n(e).resolved(e);this.source!==c&&(this.source=c,this.sourcePipeline=i(c.format)||c.format.endsWith(`-srgb`)?s.level0:s.display,this.sourceGroup=e.device.createBindGroup({layout:this.sourcePipeline.getBindGroupLayout(0),entries:[{binding:0,resource:c.createView()}]}));for(let e=0;e<this.levels.length;e++){let t=r.beginRenderPass({label:`transmission:copy`,colorAttachments:[{view:this.levels[e],loadOp:`clear`,storeOp:`store`,clearValue:[0,0,0,0]}]});t.setPipeline(e?s.reduce:this.sourcePipeline),t.setBindGroup(0,e?this.reduceGroups[e-1]:this.sourceGroup),t.draw(3),t.end()}return this.pass=r.beginRenderPass({label:`transmission`,colorAttachments:[{view:e.color,loadOp:`load`,storeOp:`store`}],depthStencilAttachment:this.depthWrite?{view:e.depth,depthLoadOp:`load`,depthStoreOp:`store`,stencilReadOnly:!0}:{view:e.depth,depthReadOnly:!0,stencilReadOnly:!0}}),a(this.pass,e),this.pass}takes(e){return!this.disposed&&(!!o(e)||!!n(e)?.resolved?.(e,!1))}render(t){if(r(t.device,t.view??t),this.disposed||!this.models.size||!this.takes(t))return;let n=t.device;if(!this.pipelines){let t=(e,t)=>{let r=n.createShaderModule({code:e});return n.createRenderPipeline({label:`transmission:copy`,layout:`auto`,vertex:{module:r,entryPoint:`vertex`},fragment:{module:r,entryPoint:t,targets:[{format:`rgba16float`}]}})};this.pipelines={level0:t(h,`level0`),display:t(h,`level0Display`),reduce:t(e(!1),`fragment`)},this.sampler=n.createSampler({magFilter:`linear`,minFilter:`linear`,mipmapFilter:`linear`})}if(this.texture?.width!==t.width||this.texture.height!==t.height){this.release();let e=Math.floor(Math.log2(Math.max(t.width,t.height)))+1,r=this.texture=n.createTexture({label:`transmission:scene`,size:[t.width,t.height],format:`rgba16float`,mipLevelCount:e,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT});this.view=r.createView(),this.levels=Array.from({length:e},(e,t)=>r.createView({baseMipLevel:t,mipLevelCount:1})),this.reduceGroups=this.levels.slice(0,-1).map(e=>n.createBindGroup({layout:this.pipelines.reduce.getBindGroupLayout(0),entries:[{binding:0,resource:e}]}))}let i=this.formats.get(t.format);i||this.formats.set(t.format,i=[{format:t.format,blend:g}]),this.targets=i;let a=t.camera.position,o=e=>{let t=e.root.matrix;return Math.hypot(a[0]-t[12],a[1]-t[13],a[2]-t[14])};this.context=t,this.pass=void 0;let s=this.ordered;s.length=0;for(let e of this.models.keys())s.push(e);s.sort((e,t)=>o(t)-o(e));try{for(let e=0;e<s.length;e++)s[e].draw(t,`transmission`,t.color,t.depth)}finally{this.context=void 0,this.pass?.end(),this.pass=void 0,s.length=0}}release(){t(this.device,this.texture),this.texture=this.view=this.source=this.sourceGroup=this.sourcePipeline=void 0,this.levels=[],this.reduceGroups=[]}onDeviceRestored(e){this.release(),this.pipelines=void 0,this.setup(e)}dispose(){if(!this.disposed){this.disposed=!0;for(let e of[...this.models.values()])e();this.release(),this.pipelines=void 0,this.engine?.sceneOf(this)?.removePlugin(this.name)}}[Symbol.dispose??Symbol()](){this.dispose()}},y=/* @__PURE__ */ new WeakMap,b={attach(e,t,n){let r=y.get(n);if(!r){let e=new v({depthWrite:!0}),i;for(let e of t.scenes)e.frameGraph===n&&(i=e);i?t.use(e,i):t.use(e),y.set(n,r={pass:e,users:/* @__PURE__ */ new Set})}let i=r,a=i.pass.add(e);return i.users.add(e),()=>{a(),i.users.delete(e)&&!i.users.size&&(y.get(n)===i&&y.delete(n),i.pass.dispose())}}};export{v as Transmission,b as screenTransmission};
@@ -0,0 +1 @@
1
+ import{fault as e,margoError as t,typeError as n}from"@margoengine/math/helpers";var r=class{constructor(...e){this.failed=e.length>0,this.error=e[0]}run(e){try{e()}catch(e){this.failed||(this.error=e),this.failed=!0}return this}finish(){if(this.failed)throw this.error}};async function i(e,{maxBytes:t,signal:n,label:i=`Asset`,output:a=null,expected:o=0}){if(!Number.isSafeInteger(t)||t<0||a!==null&&(!(a instanceof Uint8Array)||a.length!==t))throw RangeError(`Invalid asset byte budget; pass maxBytes as an integer`);if(n?.throwIfAborted(),!e)throw TypeError(`Empty ${i} response; check the URL`);let s=e.getReader(),c=[],l=0,u=a,d=new r,f=e=>{try{Promise.resolve(s.cancel(e)).catch(()=>{})}catch{}},p=()=>f(n.reason);n?.addEventListener(`abort`,p,{once:!0});try{for(!a&&Number.isSafeInteger(o)&&o>0&&o<=t&&(u=new Uint8Array(o));;){n?.throwIfAborted();let{done:e,value:r}=await s.read();if(n?.throwIfAborted(),e)break;if(!(r instanceof Uint8Array))throw TypeError(`${i} stream requires byte chunks`);if(r.byteLength>t-l)throw RangeError(`${i} byte budget exceeded; raise maxBytes`);u&&r.length<=u.length-l?u.set(r,l):(u&&c.push(u.subarray(0,l)),u=null,c.push(r.length<r.buffer.byteLength||!(r.buffer instanceof ArrayBuffer)?r.slice():r)),l+=r.byteLength}}catch(e){f(e),d=new r(e)}if(d.run(()=>n?.removeEventListener(`abort`,p)).run(()=>s.releaseLock()).finish(),a)return a.subarray(0,l);if(u)return l<u.length?u.slice(0,l):u;let m=new Uint8Array(l),h=0;for(let e of c)m.set(e,h),h+=e.length;return m}async function a(e,n){try{if(n.signal?.throwIfAborted(),!e.ok)throw t(`failed`,`${n.label??`Asset`} request failed: HTTP ${e.status}; check the URL and that the server serves it`);let r=Number(e.headers.get(`content-length`));if(Number.isFinite(r)&&r>n.maxBytes)throw RangeError(`${n.label??`Asset`} byte budget exceeded; raise maxBytes`);let i=e.headers.get(`content-encoding`);(!i||i===`identity`)&&(n={...n,expected:r})}catch(t){try{Promise.resolve(e.body?.cancel(t)).catch(()=>{})}catch{}throw t}return i(e.body,n)}var o=/"(?:__proto__|constructor|prototype)"|\\u/,s=(e,t)=>e===`__proto__`||e===`constructor`||e===`prototype`?void 0:t,c=e=>o.test(e)?JSON.parse(e,s):JSON.parse(e),l=/%2f|%5c|%00|\u0000|(^|\/)(\.|%2e){1,2}(\/|$)/i;function u(e){for(let t=0;t<8;t++){if(l.test(e))return!0;let t=e.replace(/%[\da-f]{2}/gi,e=>String.fromCharCode(`0x${e.slice(1)}`));if(t===e)return!1;e=t}return!0}function d(e,t){let n;try{n=new URL(t)}catch{throw TypeError(`allowedURLs entry ${String(t)} is not an absolute URL; pass a full http(s) URL`)}if(n.origin!==e.origin||n.protocol!==`http:`&&n.protocol!==`https:`||n.search&&n.search!==e.search)return!1;let r=n.pathname;return r.endsWith(`/`)?e.pathname.startsWith(r):e.pathname===r||e.pathname.startsWith(`${r}/`)}function f(e,t,n=[],r=`Asset`){if(typeof e!=`string`||!e||e.length>8192)throw TypeError(`Invalid ${r} URI; pass a shorter string`);let i;try{i=new URL(e,t)}catch{throw TypeError(`Invalid ${r} URI; pass a valid URL`)}if((i.protocol===`http:`||i.protocol===`https:`)&&!u(i.pathname)){for(let e of n)if(d(i,e))return i;let e=t===void 0?void 0:new URL(`.`,t);if(e&&i.origin===e.origin&&i.pathname.startsWith(e.pathname))return i}throw TypeError(`${r} URI ${i.href} leaves the model's directory; add its prefix to allowedURLs to load it`)}function p(e,t,n=[],r=`Asset`){if(!e.url)return e;try{f(e.url,t,n,r)}catch{throw e.body?.cancel().catch(()=>{}),TypeError(`${r} URI redirected to ${e.url}, which leaves the model's directory; add its prefix to allowedURLs to load it`)}return e}var m=1179937895,h=1313821514,g=5130562,_=e=>n(`GLB ${e}; pass a whole glTF 2.0 GLB file`,`failed`);function v(t,n){if(Number.isSafeInteger(n)&&t>n+3)throw e(`failed`,`GLB BIN chunk holds ${t} bytes, more than buffer 0's byteLength ${n} plus 3 padding bytes; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`)}var y=e=>e.length>=4&&new DataView(e.buffer,e.byteOffset,4).getUint32(0,!0)===1179937895;function b(e){if(e.length<20)throw _(`needs at least 20 bytes for its 12-byte file header and 8-byte JSON chunk header; received ${e.length}`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0);if(n!==1179937895)throw _(`header magic 0x${n.toString(16)} is not glTF (0x46546c67)`);if(r!==2)throw _(`header version ${r} is unsupported; use version 2`);if(i!==e.length)throw _(`header total length ${i} bytes differs from the received ${e.length} bytes`);let a=[];for(let n=12;n<e.length;){if(n+8>e.length)throw _(`ends inside the 8-byte chunk header at byte ${n}`);let r=t.getUint32(n,!0),i=t.getUint32(n+4,!0),o=n+8+r;if(r%4)throw _(`chunk length ${r} at byte ${n} must have 4-byte alignment`);if(o>e.length)throw _(`chunk length ${r} at byte ${n} extends past the ${e.length}-byte file`);if(a.length===0!=(i===1313821514)||i===5130562&&a.length!==1)throw _(`chunks must be JSON first, then at most one BIN second; export the file again`);a.push({type:i,data:e.subarray(n+8,o)}),n=o}return a}function x(e){let t=/^(\d+)\.(\d+)$/,n=typeof e?.version==`string`?t.exec(e.version):null;if(!n||n[1]!==`2`)return!1;if(e.minVersion===void 0)return!0;let r=typeof e.minVersion==`string`?t.exec(e.minVersion):null;return!!r&&r[1]===`2`&&r[2]===`0`}export{v as a,f as c,a as d,r as f,m as i,p as l,g as n,b as o,h as r,y as s,x as t,c as u};
@@ -6,6 +6,12 @@ export interface VertexInputs {
6
6
  /** Those of `locations` whose `xyz` alone it reads: a three-float fetch fills them, w taking WebGPU's default 1. */
7
7
  readonly narrow: readonly number[];
8
8
  }
9
+ /**
10
+ * `code` with each missing map's texture read left as its constant, whole or as a normal's xyz*2-1, in a `const`:
11
+ * Firefox fails a pipeline with overrides over a `let` holding a constant composite read by component
12
+ * (KB-FF-CONSTLET5). Runs on the final text, after the patches that anchor on the `let`.
13
+ */
14
+ export declare function constantReads(code: string): string;
9
15
  /** Vertex buffer slot of the third and fourth UV sets, past the instance buffer's: unused slots between stay empty. */
10
16
  export declare const laterUVSlot = 2;
11
17
  /** Their layout: one vec4 a vertex, TEXCOORD_2 then TEXCOORD_3. */
@@ -1,24 +1,4 @@
1
- var e=e=>`
2
- @vertex fn vertex(@builtin(vertex_index) i:u32)->@builtin(position) vec4f {
3
- return vec4f(array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i],0,1);
4
- }
5
- @group(0) @binding(0) var image:texture_2d<f32>;
6
- @fragment fn fragment(@builtin(position) clip:vec4f)->@location(0) vec4f {
7
- let src=textureDimensions(image);
8
- let dst=max(src/2u,vec2u(1u));let g=vec2u(clip.xy);
9
- let a=vec2f(g*src)/vec2f(dst);let b=vec2f((g+1u)*src)/vec2f(dst);let end=min(src,((g+1u)*src+dst-1u)/dst);
10
- var sum=vec4f(0.0);var sc=vec3f(0.0);
11
- for(var y=g.y*src.y/dst.y;y<end.y;y++){
12
- let wy=min(b.y,f32(y+1u))-max(a.y,f32(y));
13
- for(var x=g.x*src.x/dst.x;x<end.x;x++){
14
- let w=(min(b.x,f32(x+1u))-max(a.x,f32(x)))*wy;let t=textureLoad(image,vec2u(x,y),0);
15
- sum+=w*t;sc+=(w*t.a)*t.rgb;
16
- }
17
- }
18
- let area=(b.x-a.x)*(b.y-a.y);
19
- ${e?`return vec4f(select(sum.rgb/area,sc/sum.a,sum.a>0.0),sum.a/area);`:`return sum/area;`}
20
- }
21
- `;function t(t,n,r,i,a=1,o=`plain`){if(r<2)return;let s=n.format,c=o===`weighted`,l=c?s+`:weighted`:s,u=i.get(l);if(!u){let n=t.createShaderModule({code:e(c)});i.set(l,u=t.createRenderPipeline({layout:`auto`,vertex:{module:n,entryPoint:`vertex`},fragment:{module:n,entryPoint:`fragment`,targets:[{format:s}]}}))}let d=t.createCommandEncoder();for(let e=0;e<a;e++)for(let i=1;i<r;i++){let r=t=>n.createView(a>1?{format:s,dimension:`2d`,baseMipLevel:t,mipLevelCount:1,baseArrayLayer:e,arrayLayerCount:1}:{baseMipLevel:t,mipLevelCount:1}),o=t.createBindGroup({layout:u.getBindGroupLayout(0),entries:[{binding:0,resource:r(i-1)}]}),c=d.beginRenderPass({colorAttachments:[{view:r(i),loadOp:`clear`,storeOp:`store`,clearValue:{r:0,g:0,b:0,a:0}}]});c.setPipeline(u),c.setBindGroup(0,o),c.draw(3),c.end()}t.queue.submit([d.finish()])}var n=7,r=`alpha-coverage`,i=`
1
+ import{t as e}from"./mipmaps-38NmjDc3.js";var t=7,n=`alpha-coverage`,r=`
22
2
  struct Params {srcW:u32,srcH:u32,dstW:u32,dstH:u32,rowWords:u32,fromTexture:u32,keep:u32,srgb:u32,total:u32,p0:u32,p1:u32,p2:u32}
23
3
  struct Control {goal:atomic<u32>,low:atomic<u32>,high:atomic<u32>,p0:u32,lo:f32,hi:f32,clo:u32,chi:u32,scale:f32,p1:u32,p2:u32,p3:u32,hist:array<atomic<u32>,65>}
24
4
  @group(0) @binding(0) var<uniform> p:Params;
@@ -106,4 +86,4 @@ fn gap(a:vec2u,b:vec2u)->vec2u {
106
86
  let b=vec3u(floor(c*255.0+0.5));
107
87
  bytes[g.y*p.rowWords+g.x]=b.x|(b.y<<8u)|(b.z<<16u)|(code(t.a,s)<<24u);
108
88
  }
109
- `;function a(e,t){let n=Math.fround;if(!(n(0)*n(t)<n(e)))return 0;for(let r=1;r<256;r++)if(n(n(r/255)*n(t))>=n(e))return r;return 0}function o(e,t){let n=t.get(r);if(n)return n;let a=e=>({visibility:4,buffer:{type:e}}),o=e.createBindGroupLayout({entries:[{binding:0,visibility:4,buffer:{type:`uniform`}},{binding:1,visibility:4,texture:{sampleType:`float`}},{binding:2,...a(`read-only-storage`)},{binding:3,...a(`storage`)},{binding:4,...a(`storage`)},{binding:5,...a(`storage`)}]}),s=e.createShaderModule({code:i}),c=e.createPipelineLayout({bindGroupLayouts:[o]}),l=t=>e.createComputePipeline({layout:c,compute:{module:s,entryPoint:t}});n={layout:o};for(let e of[`targetCount`,`reduce`,`begin`,`count`,`update`,`write`])n[e]=l(e);return t.set(r,n),n}function s(e,r,i,s,c,l){if(i<2)return;let u=a(c,l),{format:d,width:f,height:p}=r,m=Math.max(1,f>>1)*Math.max(1,p>>1)*16;if(!u||d!==`rgba8unorm`&&d!==`rgba8unorm-srgb`||m>e.limits.maxStorageBufferBindingSize||m>e.limits.maxBufferSize)return t(e,r,i,s);let h=o(e,s),g=[[f,p]];for(let e=1;e<i;e++)g.push(g[e-1].map(e=>Math.max(1,e>>1)));let _=e=>Math.ceil(e*4/256)*64,v=4,y=16;for(let e=1;e<i;e++)v=Math.max(v,_(g[e][0])*4*g[e][1]),e%2==0&&(y=Math.max(y,g[e][0]*g[e][1]*16));let b=(t,n)=>e.createBuffer({size:t,usage:n}),x=b(256*i,GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST),S=[b(y,GPUBufferUsage.STORAGE),b(m,GPUBufferUsage.STORAGE)],C=b(308,GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST),w=b(v,GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC),T=new Uint32Array(64*i),E=+!!d.endsWith(`-srgb`);for(let e=0;e<i;e++){let[t,n]=g[Math.max(0,e-1)],[r,i]=g[e];T.set([t,n,r,i,_(r),+(e===1),u,E,f*p],e*64)}e.queue.writeBuffer(x,0,T),e.queue.writeBuffer(C,0,new Uint32Array([0,255,0]));let D=r.createView({baseMipLevel:0,mipLevelCount:1}),O=t=>e.createBindGroup({layout:h.layout,entries:[{binding:0,resource:{buffer:x,offset:t*256,size:48}},{binding:1,resource:D},{binding:2,resource:{buffer:S[(t+1)%2]}},{binding:3,resource:{buffer:S[t%2]}},{binding:4,resource:{buffer:C}},{binding:5,resource:{buffer:w}}]}),k=e=>[Math.ceil(e[0]/8),Math.ceil(e[1]/8)],A=e.createCommandEncoder(),j=A.beginComputePass();j.setBindGroup(0,O(0)),j.setPipeline(h.targetCount),j.dispatchWorkgroups(...k(g[0])),j.end();for(let e=1;e<i;e++){j=A.beginComputePass(),j.setBindGroup(0,O(e)),j.setPipeline(h.reduce),j.dispatchWorkgroups(...k(g[e])),j.setPipeline(h.begin),j.dispatchWorkgroups(1);for(let t=0;t<n;t++)j.setPipeline(h.count),j.dispatchWorkgroups(...k(g[e])),j.setPipeline(h.update),j.dispatchWorkgroups(1);j.setPipeline(h.write),j.dispatchWorkgroups(...k(g[e])),j.end(),A.copyBufferToTexture({buffer:w,bytesPerRow:_(g[e][0])*4},{texture:r,mipLevel:e},g[e])}e.queue.submit([A.finish()]);for(let e of[x,...S,C,w])e.destroy()}function c(e,t,n){let r=Math.hypot(n[0],n[1],n[2]);e[t]=n[0]/r,e[t+1]=n[1]/r,e[t+2]=n[2]/r,e[t+3]=n[3]}export{t as i,s as n,a as r,c as t};
89
+ `;function i(e,t){let n=Math.fround;if(!(n(0)*n(t)<n(e)))return 0;for(let r=1;r<256;r++)if(n(n(r/255)*n(t))>=n(e))return r;return 0}function a(e,t){let i=t.get(n);if(i)return i;let a=e=>({visibility:4,buffer:{type:e}}),o=e.createBindGroupLayout({entries:[{binding:0,visibility:4,buffer:{type:`uniform`}},{binding:1,visibility:4,texture:{sampleType:`float`}},{binding:2,...a(`read-only-storage`)},{binding:3,...a(`storage`)},{binding:4,...a(`storage`)},{binding:5,...a(`storage`)}]}),s=e.createShaderModule({code:r}),c=e.createPipelineLayout({bindGroupLayouts:[o]}),l=t=>e.createComputePipeline({layout:c,compute:{module:s,entryPoint:t}});i={layout:o};for(let e of[`targetCount`,`reduce`,`begin`,`count`,`update`,`write`])i[e]=l(e);return t.set(n,i),i}function o(n,r,o,s,c,l){if(o<2)return;let u=i(c,l),{format:d,width:f,height:p}=r,m=Math.max(1,f>>1)*Math.max(1,p>>1)*16;if(!u||d!==`rgba8unorm`&&d!==`rgba8unorm-srgb`||m>n.limits.maxStorageBufferBindingSize||m>n.limits.maxBufferSize)return e(n,r,o,s);let h=a(n,s),g=[[f,p]];for(let e=1;e<o;e++)g.push(g[e-1].map(e=>Math.max(1,e>>1)));let _=e=>Math.ceil(e*4/256)*64,v=4,y=16;for(let e=1;e<o;e++)v=Math.max(v,_(g[e][0])*4*g[e][1]),e%2==0&&(y=Math.max(y,g[e][0]*g[e][1]*16));let b=(e,t)=>n.createBuffer({size:e,usage:t}),x=b(256*o,GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST),S=[b(y,GPUBufferUsage.STORAGE),b(m,GPUBufferUsage.STORAGE)],C=b(308,GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST),w=b(v,GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC),T=new Uint32Array(64*o),E=+!!d.endsWith(`-srgb`);for(let e=0;e<o;e++){let[t,n]=g[Math.max(0,e-1)],[r,i]=g[e];T.set([t,n,r,i,_(r),+(e===1),u,E,f*p],e*64)}n.queue.writeBuffer(x,0,T),n.queue.writeBuffer(C,0,new Uint32Array([0,255,0]));let D=r.createView({baseMipLevel:0,mipLevelCount:1}),O=e=>n.createBindGroup({layout:h.layout,entries:[{binding:0,resource:{buffer:x,offset:e*256,size:48}},{binding:1,resource:D},{binding:2,resource:{buffer:S[(e+1)%2]}},{binding:3,resource:{buffer:S[e%2]}},{binding:4,resource:{buffer:C}},{binding:5,resource:{buffer:w}}]}),k=e=>[Math.ceil(e[0]/8),Math.ceil(e[1]/8)],A=n.createCommandEncoder(),j=A.beginComputePass();j.setBindGroup(0,O(0)),j.setPipeline(h.targetCount),j.dispatchWorkgroups(...k(g[0])),j.end();for(let e=1;e<o;e++){j=A.beginComputePass(),j.setBindGroup(0,O(e)),j.setPipeline(h.reduce),j.dispatchWorkgroups(...k(g[e])),j.setPipeline(h.begin),j.dispatchWorkgroups(1);for(let n=0;n<t;n++)j.setPipeline(h.count),j.dispatchWorkgroups(...k(g[e])),j.setPipeline(h.update),j.dispatchWorkgroups(1);j.setPipeline(h.write),j.dispatchWorkgroups(...k(g[e])),j.end(),A.copyBufferToTexture({buffer:w,bytesPerRow:_(g[e][0])*4},{texture:r,mipLevel:e},g[e])}n.queue.submit([A.finish()]);for(let e of[x,...S,C,w])e.destroy()}function s(e,t,n){let r=Math.hypot(n[0],n[1],n[2]);e[t]=n[0]/r,e[t+1]=n[1]/r,e[t+2]=n[2]/r,e[t+3]=n[3]}function c(e,t,n,r){return{code:`missing-texcoord`,message:`${typeof t==`string`&&t?`glTF material ${e} ("${t}")`:`glTF material ${e}`} reads its ${n} from TEXCOORD_${r}, which a primitive using it lacks; that primitive draws without the map (glTF 2.0 section 5.24 textureInfo.texCoord). Add TEXCOORD_${r} to the mesh or point texCoord at a set it has`,material:e,map:n,texCoord:r}}function l(e,t){e.some(e=>e.code===t.code&&e.material===t.material&&e.map===t.map&&e.texCoord===t.texCoord)||e.push(t)}export{i as a,o as i,c as n,s as r,l as t};