@margoengine/gltf 0.0.0-stage → 0.1.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 (129) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1438 -3
  4. package/dist/accessor-DuqjpuxI.js +1 -0
  5. package/dist/accessor-nVsu_f1L.js +1 -0
  6. package/dist/accessor.d.ts +12 -0
  7. package/dist/asset-1b8ejkZX.js +4 -0
  8. package/dist/asset-entry.d.ts +1 -0
  9. package/dist/asset-entry.js +1 -0
  10. package/dist/asset.d.ts +319 -0
  11. package/dist/audio.d.ts +47 -0
  12. package/dist/audio.js +1 -0
  13. package/dist/auto.d.ts +29 -0
  14. package/dist/auto.js +1 -0
  15. package/dist/base-textures.d.ts +20 -0
  16. package/dist/coalesce.d.ts +29 -0
  17. package/dist/compression-D4IkO5vE.js +1 -0
  18. package/dist/compression.d.ts +15 -0
  19. package/dist/coordinates.d.ts +1 -0
  20. package/dist/coordinates.js +1 -0
  21. package/dist/dds.d.ts +7 -0
  22. package/dist/dds.js +1 -0
  23. package/dist/decoder-default-CxLH8Vz0.js +1 -0
  24. package/dist/decoder-default.d.ts +5 -0
  25. package/dist/default-materials.d.ts +8 -0
  26. package/dist/draco-state.d.ts +7 -0
  27. package/dist/draw-batch.d.ts +83 -0
  28. package/dist/draw-memo.d.ts +136 -0
  29. package/dist/errors-THVaUwlL.js +1 -0
  30. package/dist/extended.d.ts +12 -0
  31. package/dist/extended.js +1 -0
  32. package/dist/gltf.worker.d.ts +1 -0
  33. package/dist/group.d.ts +6 -0
  34. package/dist/image-limit-DvFSfR5T.js +1 -0
  35. package/dist/image-limit.d.ts +6 -0
  36. package/dist/index.d.ts +84 -0
  37. package/dist/index.js +1 -0
  38. package/dist/instanced-shader-BebTnbkj.js +5 -0
  39. package/dist/instanced-shader.d.ts +14 -0
  40. package/dist/instancing.d.ts +9 -0
  41. package/dist/instancing.js +1 -0
  42. package/dist/interactivity-graph.d.ts +193 -0
  43. package/dist/interactivity-model.d.ts +94 -0
  44. package/dist/interactivity-ops.d.ts +20 -0
  45. package/dist/interactivity.d.ts +33 -0
  46. package/dist/interactivity.js +1 -0
  47. package/dist/lights.d.ts +98 -0
  48. package/dist/lights.js +1 -0
  49. package/dist/limits-_LZ441oV.js +1 -0
  50. package/dist/material-draw-state-BHeTb1FP.js +1 -0
  51. package/dist/material-draw-state.d.ts +7 -0
  52. package/dist/material-draw.d.ts +18 -0
  53. package/dist/material-draw.js +1 -0
  54. package/dist/material-extension.d.ts +96 -0
  55. package/dist/mesh-source-DvU8YvMc.js +1 -0
  56. package/dist/meshopt.d.ts +9 -0
  57. package/dist/meshopt.js +1 -0
  58. package/dist/metadata.d.ts +114 -0
  59. package/dist/metadata.js +1 -0
  60. package/dist/model-entry.d.ts +2 -0
  61. package/dist/model-entry.js +1 -0
  62. package/dist/model-iRvuj19h.js +39 -0
  63. package/dist/model.d.ts +1011 -0
  64. package/dist/node-image-decode.d.ts +6 -0
  65. package/dist/node-matrix-R9BipGnp.js +1 -0
  66. package/dist/node-matrix.d.ts +16 -0
  67. package/dist/occlusion.d.ts +8 -0
  68. package/dist/optimize-7SEzNA23.js +1 -0
  69. package/dist/pack-BVDYuqZe.js +1 -0
  70. package/dist/pack.d.ts +27 -0
  71. package/dist/parts.d.ts +54 -0
  72. package/dist/pbr-instancing.d.ts +83 -0
  73. package/dist/pbr-instancing.js +1 -0
  74. package/dist/pbr.d.ts +13 -0
  75. package/dist/pbr.js +1 -0
  76. package/dist/physics.d.ts +148 -0
  77. package/dist/physics.js +1 -0
  78. package/dist/prepare.d.ts +26 -0
  79. package/dist/prepare.js +1 -0
  80. package/dist/progressive.d.ts +59 -0
  81. package/dist/progressive.js +4 -0
  82. package/dist/progressive.worker.d.ts +1 -0
  83. package/dist/quantized.d.ts +8 -0
  84. package/dist/quantized.js +1 -0
  85. package/dist/render-state.d.ts +18 -0
  86. package/dist/replica.d.ts +37 -0
  87. package/dist/report.d.ts +128 -0
  88. package/dist/report.js +1 -0
  89. package/dist/scene-data.d.ts +61 -0
  90. package/dist/scene-data.js +1 -0
  91. package/dist/scene-scope-CZDEkd24.js +4 -0
  92. package/dist/scene.d.ts +61 -0
  93. package/dist/scene.js +4 -0
  94. package/dist/shader-DPqfUcmp.js +405 -0
  95. package/dist/shader.d.ts +222 -0
  96. package/dist/shared/caster.d.ts +152 -0
  97. package/dist/shared/gltf.d.ts +257 -0
  98. package/dist/shared/iridescence.d.ts +2 -0
  99. package/dist/shared/prepared-geometry.d.ts +8 -0
  100. package/dist/side-shader.d.ts +1 -0
  101. package/dist/soft-mesh.d.ts +94 -0
  102. package/dist/soft-mesh.js +4 -0
  103. package/dist/spec-gloss.d.ts +21 -0
  104. package/dist/spec-gloss.js +18 -0
  105. package/dist/splat-state.d.ts +7 -0
  106. package/dist/splats.d.ts +18 -0
  107. package/dist/splats.js +1 -0
  108. package/dist/src-WMRHArDp.js +4 -0
  109. package/dist/stream-C3bKMy1B.js +1 -0
  110. package/dist/stream.d.ts +87 -0
  111. package/dist/texture-coordinates-XFsEMdU6.js +2 -0
  112. package/dist/texture-coordinates.d.ts +26 -0
  113. package/dist/texture-stream-Cu_XpyVO.js +4 -0
  114. package/dist/texture-stream.d.ts +88 -0
  115. package/dist/textured.d.ts +34 -0
  116. package/dist/textured.js +5 -0
  117. package/dist/uniform-arena.d.ts +78 -0
  118. package/dist/unit-light-DvtsuFYP.js +109 -0
  119. package/dist/version-BmU1nesQ.js +1 -0
  120. package/dist/version.d.ts +8 -0
  121. package/dist/vertex-inputs.d.ts +47 -0
  122. package/dist/view-uniform.d.ts +13 -0
  123. package/dist/visibility-C_Oqz9Sr.js +1 -0
  124. package/dist/worker-CY1TQnYX.js +1 -0
  125. package/dist/worker.d.ts +21 -0
  126. package/dist/worker.js +4 -0
  127. package/dist/workers/gltf.js +322 -0
  128. package/dist/workers/progressive.js +1 -0
  129. package/package.json +213 -6
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Image decoding where `createImageBitmap` is missing (Node), through `@margoengine/decoders/image`.
3
+ * Its own module so the classic parser workers, which always have `createImageBitmap`, swap it for a stub
4
+ * (scripts/build-workers.js) and never name the decoder package: an IIFE has no module URL to resolve it from.
5
+ */
6
+ export declare function decodeWithoutBrowser(data: Uint8Array, signal?: AbortSignal): Promise<import("@margoengine/decoders/image").DecodedImage>;
@@ -0,0 +1 @@
1
+ import{splitNodeMatrix as e}from"@margoengine/math/quat";var t=t=>e(t,{float32:!0});export{t};
@@ -0,0 +1,16 @@
1
+ /** What splitTRS returns, written here so the declarations of this package do not name @margoengine/math. */
2
+ type NodeSplit = {
3
+ ok: true;
4
+ position: [number, number, number];
5
+ rotation: [number, number, number, number];
6
+ scale: [number, number, number];
7
+ } | {
8
+ ok: false;
9
+ reason: 'singular' | 'shear';
10
+ };
11
+ /**
12
+ * `splitTRS` for a glTF node `matrix`, plus the zero scales glTF 2.0 section 3.5.3 allows: a column whose float32
13
+ * values are all zero is a zero scale on that axis (`splitNodeMatrix` of `@margoengine/math/quat`).
14
+ */
15
+ export declare const splitNodeMatrix: (m: ArrayLike<number>) => NodeSplit;
16
+ export {};
@@ -0,0 +1,8 @@
1
+ /**
2
+ * One fragment writes the SSAO normal target and the ambient target. An IBL shader keeps the `margoAmbient` expression.
3
+ * A shader whose return does not match falls back to `ambient()` rather than a one-output fragment in a two-target pass.
4
+ */
5
+ export declare function occlusionShader(code: string): {
6
+ code: string;
7
+ entry: string;
8
+ };
@@ -0,0 +1 @@
1
+ var e=32;function t(e,t,n){if(e.length%3)throw RangeError(`${n} needs whole triangles; pass 3 indices per face`);if(t!==void 0&&!(Number.isInteger(t)&&t>=0))throw RangeError(`${n} vertex count ${t} is invalid; pass an integer >= 0`);let r=-1;for(let t=0;t<e.length;t++){let i=e[t];if(!Number.isInteger(i)||i<0)throw RangeError(`${n} index ${i} is invalid; pass integers >= 0`);i>r&&(r=i)}if(t!==void 0&&r>=t)throw RangeError(`${n} index ${r} is past ${t} vertices; fix the indices`);return t??r+1}function n(e,t){if(!Number.isInteger(e)||e<3)throw RangeError(`${t} cache size ${e} is invalid; pass an integer >= 3`)}function r(e,r,i=16){let a=t(e,r,`analyzeVertexCache`);n(i,`analyzeVertexCache`);let o=new Float64Array(a).fill(-1/0),s=new Uint8Array(a),c=0,l=0,u=0;for(let t=0;t<e.length;t++){let n=e[t];s[n]||(s[n]=1,u++),!(c-o[n]<=i)&&(o[n]=++c,l++)}return{misses:l,acmr:e.length?l/(e.length/3):0,atvr:u?l/u:0}}var i=/* @__PURE__ */ Float64Array.from({length:e},(e,t)=>t<3?.75:(1-(t-3)/29)**1.5);function a(e,t){return t===0?-1:(e<0?0:i[e])+2/Math.sqrt(t)}function o(n,r){let i=t(n,r,`optimizeVertexCache`),o=n.length/3,s=new Uint32Array(n.length),c=new Uint32Array(i+1),l=new Uint32Array(i);for(let e=0;e<n.length;e++)c[n[e]+1]++;for(let e=0;e<i;e++)c[e+1]+=c[e];let u=new Uint32Array(n.length),d=c.slice(0,i);for(let e=0;e<n.length;e++){let t=n[e];u[d[t]++]=e/3|0,l[t]++}let f=new Float64Array(i),p=new Float64Array(o),m=new Uint8Array(o);for(let e=0;e<i;e++)f[e]=a(-1,l[e]);for(let e=0;e<o;e++)p[e]=f[n[e*3]]+f[n[e*3+1]]+f[n[e*3+2]];let h=/* @__PURE__ */ new Int32Array(35),g=/* @__PURE__ */ new Int32Array(35),_=0,v=0,y=-1;for(let t=0;t<o;t++){if(y<0){for(;m[v];)v++;y=v}let r=n[y*3],i=n[y*3+1],o=n[y*3+2];s[t*3]=r,s[t*3+1]=i,s[t*3+2]=o,m[y]=1;for(let e=0;e<3;e++){let t=n[y*3+e],r=c[t],i=r+l[t]-1;for(let e=r;e<=i;e++)if(u[e]===y){u[e]=u[i];break}l[t]--}let d=0;g[d++]=r,i!==r&&(g[d++]=i),o!==r&&o!==i&&(g[d++]=o);for(let e=0;e<_;e++){let t=h[e];if(t!==r&&t!==i&&t!==o&&(g[d++]=t),d===g.length)break}let b=h;h=g,g=b,_=d;for(let t=0;t<_;t++){let n=h[t],r=a(t<e?t:-1,l[n]),i=r-f[n];f[n]=r;for(let e=c[n],t=e+l[n];e<t;e++)p[u[e]]+=i}_>e&&(_=e);let x=-1/0;y=-1;for(let e=0;e<_;e++){let t=h[e];for(let e=c[t],n=e+l[t];e<n;e++)p[u[e]]>x&&(x=p[u[e]],y=u[e])}}return s}function s(e,i,a={}){let{threshold:o=1.05,cacheSize:s=16}=a;if(i.length%3)throw RangeError(`optimizeOverdraw positions must be xyz per vertex; fix the array`);let c=t(e,i.length/3,`optimizeOverdraw`);if(n(s,`optimizeOverdraw`),!(o>=1&&o<1/0))throw RangeError(`optimizeOverdraw threshold ${o} is invalid; pass a finite number >= 1`);let l=e.length/3,u=r(e,c,s).acmr*o,d=new Float64Array(c).fill(-1/0),f=[],p=0,m=0,h=0;for(let t=0;t<l;t++){t-h>=16&&m/(t-h)<=u&&(f.push(t),h=t,m=0,p+=s+1);let n=0;for(let r=0;r<3;r++){let i=e[t*3+r];p-d[i]<=s||(d[i]=++p,n++)}(t===0||t>h&&n===3)&&(f.push(t),h=t,m=0),m+=n}let g=f.length,_=new Float64Array(g*3),v=new Float64Array(g*3),y=new Float64Array(g),b=[0,0,0],x=0;for(let t=0;t<g;t++){let n=t+1<g?f[t+1]:l;for(let r=f[t];r<n;r++){let n=e[r*3]*3,a=e[r*3+1]*3,o=e[r*3+2]*3,s=i[a]-i[n],c=i[a+1]-i[n+1],l=i[a+2]-i[n+2],u=i[o]-i[n],d=i[o+1]-i[n+1],f=i[o+2]-i[n+2],p=c*f-l*d,m=l*u-s*f,h=s*d-c*u,g=Math.hypot(p,m,h);v[t*3]+=p,v[t*3+1]+=m,v[t*3+2]+=h,y[t]+=g;for(let e=0;e<3;e++){let r=(i[n+e]+i[a+e]+i[o+e])/3;_[t*3+e]+=r*g,b[e]+=r*g}x+=g}}let S=new Float64Array(g),C=Array.from({length:g},(e,t)=>t);for(let e=0;e<g;e++){let t=Math.hypot(v[e*3],v[e*3+1],v[e*3+2]);if(!(t>0&&y[e]>0&&x>0))continue;let n=0;for(let t=0;t<3;t++)n+=(_[e*3+t]/y[e]-b[t]/x)*v[e*3+t];S[e]=n/t}C.sort((e,t)=>S[t]-S[e]||e-t);let w=new Uint32Array(e.length),T=0;for(let t of C){let n=(t+1<g?f[t+1]:l)*3;for(let r=f[t]*3;r<n;r++)w[T++]=e[r]}return w}export{s as optimizeOverdraw,o as optimizeVertexCache};
@@ -0,0 +1 @@
1
+ import{n as e}from"./errors-THVaUwlL.js";import{C as t,j as n,k as r,m as i}from"./asset-1b8ejkZX.js";function a(e){if(!e||typeof e!=`object`)return!1;for(let[t,n]of Object.entries(e))if(t===`texCoord`?n>1:a(n))return!0;return!1}function o(e,t){let n=t.extensions?.KHR_materials_variants,r=[t.material,...(n?.mappings??[]).map(e=>e?.material)],i=/* @__PURE__ */ new Set;for(let t=0;t<r.length;t++){let n=r[t];if(n===void 0||i.has(n))continue;i.add(n);let o=e.materials?.[n];if(a(o))return!0;let s=(o?.extensions)?.MSFT_lod?.ids;if(Array.isArray(s))for(let t of s)Number.isInteger(t)&&t>=0&&t<(e.materials?.length??0)&&r.push(t)}return!1}var s=/* @__PURE__ */ new WeakMap;function c(e,n,r){t(e,n);try{return u(e,n,r)}catch(t){let r=e.doc.meshes??[],i=r.findIndex(e=>e?.primitives?.includes?.(n));throw t instanceof Error&&i>=0&&(t.message=`glTF mesh ${i}${r[i].name?` "${r[i].name}"`:``} primitive ${r[i].primitives.indexOf(n)}: ${t.message}`),t}}function l(e,t){let n=e.length;if(t===2||t===3){let r=n<2?0:t===2?n:n-1,i=new Uint32Array(r*2);for(let t=0;t<r;t++)i[t*2]=e[t],i[t*2+1]=e[(t+1)%n];return i}if(t===5||t===6){let r=new Uint32Array(Math.max(n-2,0)*3);for(let i=0,a=0;i<n-2;i++,a+=3)t===5?(r[a]=e[i],r[a+1]=e[i+1+i%2],r[a+2]=e[i+2-i%2]):(r[a]=e[i+1],r[a+1]=e[i+2],r[a+2]=e[0]);return r}return e}function u(a,s,c){let u=s.mode??4,d=u===0?1:u<4?2:3;if(!Number.isInteger(u)||u<0||u>6)throw TypeError(`Invalid glTF primitive mode; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let f=s.attributes??{},p=(e,t,n)=>{try{return a.accessor(t,n)}catch(n){throw n instanceof Error&&(n.message=`${e} (accessor ${t}): ${n.message}`),n}};if(i(a.doc.accessors,f.POSITION,`POSITION`).count>16777216)throw e(`unsupported`,`glTF primitive has more than ${r} vertices, the most one primitive may hold; split the mesh into several primitives`);let m=p(`POSITION`,f.POSITION,`VEC3`),h=m.length/3,g=a.doc.extensionsUsed?.includes(`KHR_mesh_quantization`),_=a.partVertices;if(h<d)throw RangeError(`Expected bounded triangle geometry`);for(let e of[`POSITION`,`NORMAL`,`TANGENT`])if(f[e]!==void 0&&!g){let t=i(a.doc.accessors,f[e],`attribute`);if(t.componentType!==5126||t.normalized)throw TypeError(`Expected Float32 `+e)}for(let e of[`TEXCOORD_0`,`TEXCOORD_1`,`TEXCOORD_2`,`TEXCOORD_3`,`COLOR_0`])if(f[e]!==void 0&&!(g&&e!==`COLOR_0`)){let t=i(a.doc.accessors,f[e],`attribute`);if(![5126,5121,5123].includes(t.componentType)||t.componentType!==5126&&!t.normalized)throw TypeError(`Invalid normalized `+e+`; re-export the file and check it with the glTF Validator`)}let v=f.NORMAL===void 0?new Float32Array(m.length):p(`NORMAL`,f.NORMAL,`VEC3`),y=t(a,s)??(s.indices===void 0?null:p(`indices`,s.indices,`SCALAR`));if(y)for(let e=0;e<y.length;e++){let t=y[e];if(!Number.isInteger(t)||t<0||t>=h)throw RangeError(`Invalid glTF triangle indices; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`)}let b=y?new Uint32Array(y):new Uint32Array(h);if(!y)for(let e=0;e<h;e++)b[e]=e;if(b=l(b,u),!b.length||b.length%d)throw RangeError(`Invalid glTF triangle indices; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);if(s.indices!==void 0&&(![5121,5123,5125].includes(i(a.doc.accessors,s.indices,`indices`).componentType)||a.doc.accessors[s.indices].normalized))throw TypeError(`Invalid index component type; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);if(f.NORMAL===void 0&&d===3)for(let e=0;e<b.length;e+=3){let t=b[e]*3,n=b[e+1]*3,r=b[e+2]*3,i=m[n]-m[t],a=m[n+1]-m[t+1],o=m[n+2]-m[t+2],s=m[r]-m[t],c=m[r+1]-m[t+1],l=m[r+2]-m[t+2],u=a*l-o*c,d=o*s-i*l,f=i*c-a*s;v[t]+=u,v[t+1]+=d,v[t+2]+=f,v[n]+=u,v[n+1]+=d,v[n+2]+=f,v[r]+=u,v[r+1]+=d,v[r+2]+=f}let x=a.doc.materials?.[s.material]?.alphaMode===`BLEND`,S=h>_?n(b,d,h,_,x?null:m):null;if(a.reorder&&d===3&&!x){if(!S)b=a.reorder(b,m,h);else for(let e of S){let t=e.vertexMap.length,n=new Float32Array(t*3);for(let r=0;r<t;r++){let t=e.vertexMap[r]*3;n[r*3]=m[t],n[r*3+1]=m[t+1],n[r*3+2]=m[t+2]}e.indices=a.reorder(e.indices,n,t)}}let C=f.TEXCOORD_0===void 0?null:p(`TEXCOORD_0`,f.TEXCOORD_0,`VEC2`),w=f.TEXCOORD_1===void 0?null:p(`TEXCOORD_1`,f.TEXCOORD_1,`VEC2`),T=o(a.doc,s),E=!T||f.TEXCOORD_2===void 0?null:p(`TEXCOORD_2`,f.TEXCOORD_2,`VEC2`),D=!T||f.TEXCOORD_3===void 0?null:p(`TEXCOORD_3`,f.TEXCOORD_3,`VEC2`),O=f.TANGENT===void 0?null:p(`TANGENT`,f.TANGENT,`VEC4`),k=f.COLOR_0===void 0?null:p(`COLOR_0`,f.COLOR_0),A=k?k.length/h:0;if(v.length!==h*3||C&&C.length!==h*2||w&&w.length!==h*2||E&&E.length!==h*2||D&&D.length!==h*2||O&&O.length!==h*4||k&&![3,4].includes(A))throw RangeError(`Mismatched glTF attributes; the file holds invalid numbers, re-export it and check it with the glTF Validator`);let j=(e,t,n)=>{let r=t*3,i=v[r],a=v[r+1],o=v[r+2],s=Math.hypot(i,a,o);if(e[n]=m[r],e[n+1]=m[r+1],e[n+2]=m[r+2],e[n+3]=1,!s||!Number.isFinite(s)){if(f.NORMAL!==void 0)throw RangeError(`Zero or non-finite glTF normal; the file holds invalid numbers, re-export it and check it with the glTF Validator`);e[n+6]=1}else e[n+4]=i/s,e[n+5]=a/s,e[n+6]=o/s;if(O){let r=t*4,i=Math.hypot(O[r],O[r+1],O[r+2]);i&&(e[n+8]=O[r]/i,e[n+9]=O[r+1]/i,e[n+10]=O[r+2]/i,e[n+11]=Math.sign(O[r+3]))}if(C&&(e[n+12]=C[t*2],e[n+13]=C[t*2+1]),w&&(e[n+14]=w[t*2],e[n+15]=w[t*2+1]),k){let r=t*A;e[n+16]=k[r],e[n+17]=k[r+1],e[n+18]=k[r+2],e[n+19]=A===3?1:k[r+3]}else e[n+16]=1,e[n+17]=1,e[n+18]=1,e[n+19]=1},M=(e,t,n)=>{E&&e.set(E.subarray(t*2,t*2+2),n),D&&e.set(D.subarray(t*2,t*2+2),n+2)},N=d<3?{topology:d===1?`point-list`:`line-list`}:{};if(!S){let e=new Float32Array(h*20),t=E||D?new Float32Array(h*4):void 0;for(let t=0;t<h;t++)j(e,t,t*20);if(t)for(let e=0;e<h;e++)M(t,e,e*4);let n={vertices:e,indices:b,...N,...t?{uvs:t}:{}};return c?(c(n),[]):[n]}let P=[];for(let e=0;e<S.length;e++){let{indices:t,vertexMap:n}=S[e],r=n.length,i=new Float32Array(r*20),a=E||D?new Float32Array(r*4):void 0;for(let e=0;e<r;e++)j(i,n[e],e*20);if(a)for(let e=0;e<r;e++)M(a,n[e],e*4);let o={vertices:i,indices:t,...N,...a?{uvs:a}:{},part:{index:e,count:S.length,vertexMap:n}};c?c(o):P.push(o)}return P}function d(e,t,n){let r=t.attributes??{},a=i(e.doc.accessors,r.POSITION,`POSITION`).count,o=r.TEXCOORD_2===void 0?null:e.accessor(r.TEXCOORD_2,`VEC2`),s=r.TEXCOORD_3===void 0?null:e.accessor(r.TEXCOORD_3,`VEC2`);if(!o&&!s)return;if(o&&o.length!==a*2||s&&s.length!==a*2)throw RangeError(`Mismatched glTF attributes; the file holds invalid numbers, re-export it and check it with the glTF Validator`);let c=new Float32Array(n.length*4);for(let e=0;e<n.length;e++){let t=n[e];o&&c.set(o.subarray(t*2,t*2+2),e*4),s&&c.set(s.subarray(t*2,t*2+2),e*4+2)}return c}function f(e){let t=e.doc,n=[];for(let e of t.skins??[])n.push(e?.inverseBindMatrices);for(let e of t.meshes??[])for(let t of e?.primitives??[]){n.push(t?.attributes?.JOINTS_0,t?.attributes?.WEIGHTS_0);for(let e of t?.targets??[])n.push(e?.POSITION,e?.NORMAL)}for(let e of t.animations??[])for(let t of e?.samplers??[])n.push(t?.input,t?.output);for(let e of t.nodes??[])n.push(...Object.values(e?.extensions?.EXT_mesh_gpu_instancing?.attributes??{}));let r=[];for(let t of n)if(t!==void 0)try{r.push([t,e.accessor(t)])}catch{}return r}var p=e=>(e.meshes??[]).flatMap(e=>Array.isArray(e?.primitives)?e.primitives:[]);export{p as a,s as i,d as n,o,c as r,f as t};
package/dist/pack.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ import type { GLTFDocument, GLTFPrimitive } from './shared/gltf.js';
2
+ import { type GLTFAsset } from './asset.js';
3
+ import type { PreparedGeometry } from './pbr.js';
4
+ /**
5
+ * True when a material of primitive `p`, its own or a KHR_materials_variants one, reads TEXCOORD_2 or 3: only then do those
6
+ * sets cost a read, a buffer and a shader, so files that merely carry them (common in exports) pay nothing.
7
+ */
8
+ export declare function usesLaterUV(doc: GLTFDocument, p: GLTFPrimitive): boolean;
9
+ /** Geometry already packed by a parse worker, keyed by primitive definition; PBRModel then skips decoding it. */
10
+ export declare const packed: WeakMap<object, readonly PreparedGeometry[]>;
11
+ /**
12
+ * Decode one primitive's accessors into gltf/pbr's 80-byte vertices and uint32 indices (main thread or worker): one
13
+ * element, or one per part when the primitive has more vertices than `asset.partVertices` (see parts.ts). With `each`,
14
+ * every element goes to `each` as soon as it is filled and none is kept (a stream holds one part at a time).
15
+ */
16
+ export declare function packPrimitive(asset: GLTFAsset, p: GLTFPrimitive, each?: (geometry: PreparedGeometry) => void): PreparedGeometry[];
17
+ /**
18
+ * glTF 2.0 section 3.7.2.1 topologies as lists: strips and fans become triangles, loops and strips become line pairs, so
19
+ * every primitive draws as a point, line or triangle list. Too few indices give an empty list.
20
+ */
21
+ export declare function listIndices(v: Uint32Array, mode: number): Uint32Array;
22
+ /** TEXCOORD_2 then TEXCOORD_3 of the vertices `vertexMap` names, four floats a vertex (a part's later UVs for a new material). */
23
+ export declare function laterUVs(asset: GLTFAsset, p: GLTFPrimitive, vertexMap: Uint32Array): Float32Array | undefined;
24
+ /** Decode the accessors read besides packed geometry (skins, morph targets, animation samplers, GPU instancing); failures are left for the reader. */
25
+ export declare function decodeExtras(asset: GLTFAsset): [number, Float32Array][];
26
+ /** Primitive definitions mesh by mesh: @margoengine/gltf/progressive and its worker key primitives by this list. */
27
+ export declare const primitiveDefs: (doc: GLTFAsset['doc']) => GLTFPrimitive[];
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Splits a primitive with more vertices than one GPU part may hold into parts of at most `max` vertices each, so a glTF
3
+ * primitive of any size (a 10M-triangle scan) loads, uploads and culls part by part. Clean room from:
4
+ * - Hoppe, Optimization of Mesh Locality for Transparent Vertex Caching, SIGGRAPH 1999, https://hhoppe.com/proj/tvc/
5
+ * - Sander, Nehab, Barczak, Fast Triangle Reordering for Vertex Locality and Reduced Overdraw, SIGGRAPH 2007
6
+ * - Yoon, Lindstrom, Pascucci, Manocha, Cache-Oblivious Mesh Layouts, SIGGRAPH 2005
7
+ * - Isenburg, Lindstrom, Streaming Meshes, IEEE Visualization 2005
8
+ * - Cignoni et al., Batched Multi Triangulation, IEEE Visualization 2005
9
+ * - Kerbl et al., Revisiting the Vertex Cache, HPG 2018, https://doi.org/10.1145/3233302
10
+ * - Karis, Stubbe, Wihlidal, A Deep Dive into Nanite Virtualized Geometry, SIGGRAPH 2021
11
+ * - glTF 2.0 sections 3.6.2 and 3.7.2, https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html
12
+ * - WebGPU limits (maxStorageBufferBindingSize, maxBufferSize), https://www.w3.org/TR/webgpu/#limits
13
+ *
14
+ * Elements (points, line pairs or triangles) are put in Morton order of their centroids (a 30-bit key, three 10-bit
15
+ * radix passes, O(n)) so each part is a compact piece of the surface with tight bounds, then walked greedily: a part
16
+ * closes when the element's new vertices would pass `max`. Vertices shared inside a part stay shared; only vertices on
17
+ * a cut are copied into both parts. Blended primitives skip the sort: their order decides how they layer.
18
+ */
19
+ /** Default vertices per part: 2^18, 20 MiB of 80-byte vertices, under every default WebGPU storage binding (128 MiB) and the WebGL2 layer's 2048-context one (64 MiB). */
20
+ export declare const PART_VERTICES = 262144;
21
+ /** Fewest and most vertices per part `maxPartVertices` accepts. */
22
+ export declare const MIN_PART_VERTICES = 1024, MAX_PART_VERTICES = 1048576;
23
+ /** Most vertices one primitive may have: index accessors decode through Float32, exact to 2^24. */
24
+ export declare const PRIMITIVE_VERTICES = 16777216;
25
+ /** One part of a split primitive: local indices and, for each local vertex, its vertex in the source primitive. */
26
+ export interface PartPlan {
27
+ indices: Uint32Array;
28
+ vertexMap: Uint32Array;
29
+ }
30
+ /** Validates a `maxPartVertices` option (default PART_VERTICES). */
31
+ export declare function partLimit(value?: number): number;
32
+ /**
33
+ * Splits `indices` (`per` = 1 points, 2 lines, 3 triangles) over `count` vertices into parts of at most `max` vertices.
34
+ * `positions` (x, y, z every `stride` floats) turns on the Morton order; null keeps the source order (blended primitives).
35
+ */
36
+ export declare function partition(indices: Uint32Array, per: number, count: number, max: number, positions: ArrayLike<number> | null, stride?: number): PartPlan[];
37
+ /** Packed geometry (20 floats a vertex) as parts split it; `part` as on PBRPrimitive. */
38
+ export interface SplitGeometry {
39
+ interpolatedDirections?: boolean;
40
+ vertices: Float32Array;
41
+ indices: Uint32Array;
42
+ uvs?: Float32Array;
43
+ topology?: 'point-list' | 'line-list';
44
+ part?: {
45
+ index: number;
46
+ count: number;
47
+ vertexMap: Uint32Array;
48
+ };
49
+ }
50
+ /**
51
+ * Packed triangles (prepared geometry, autoLOD levels) with more than `max` vertices as parts of at most `max`, Morton
52
+ * ordered unless `keepOrder` (blended materials); geometry within `max` comes back alone, unchanged.
53
+ */
54
+ export declare function splitPrepared<T extends SplitGeometry>(data: T, max: number, keepOrder?: boolean): (T | SplitGeometry)[];
@@ -0,0 +1,83 @@
1
+ import type { GLTFInstancing } from './shared/gltf.js';
2
+ import { instancedShader } from './instanced-shader.js';
3
+ import type { TextureTransform } from './pbr.js';
4
+ import type { GLTFAsset } from './asset.js';
5
+ /**
6
+ * Per-instance data for gltf/pbr primitives (a matrix, a tint and a UV transform per instance):
7
+ * assign one to `primitive.instances` and that primitive draws `count` instances in one instanced draw. Matrices are in the
8
+ * primitive's node space (world = node matrix x instance matrix, as glTF EXT_mesh_gpu_instancing). Each instance also has
9
+ * an RGBA tint (multiplies base colour, like vertex colour) and a UV scale + offset applied to both UV sets before the
10
+ * material's own texture transforms (an atlas region per instance). Setters mark the rows for upload; after writing `data`
11
+ * directly set `needsUpdate = true`. Primitives (also of other models) may share one PBRInstances.
12
+ */
13
+ export declare class PBRInstances {
14
+ /** 24 floats per instance: matrix (column-major), tint, UV scale x/y and offset x/y. */
15
+ readonly data: Float32Array;
16
+ private drawn;
17
+ private low;
18
+ private high;
19
+ private stale;
20
+ private revision;
21
+ private source?;
22
+ private gpu?;
23
+ private device?;
24
+ private flips?;
25
+ private flipCount;
26
+ readonly capacity: number;
27
+ constructor(capacity: number);
28
+ /** Instances drawn, the first `count` rows (default and maximum: `capacity`). */
29
+ get count(): number;
30
+ set count(n: number);
31
+ /**
32
+ * Bumped by every row write and by `needsUpdate = true` (shared by projections): a reader of `data`, such as shadows'
33
+ * cascade fit, reads the rows again only when it changes. `count` changes leave it as is.
34
+ */
35
+ get version(): number;
36
+ /** Set true after writing `data` directly: every row is uploaded before the next draw. */
37
+ get needsUpdate(): boolean;
38
+ set needsUpdate(v: boolean);
39
+ private index;
40
+ private row;
41
+ private determinant;
42
+ /** Column-major 4x4 (`Matrix4.elements` from @margoengine/math, `camera.matrix` layout); the last row must be 0, 0, 0, 1. */
43
+ setMatrixAt(i: number, m: ArrayLike<number>): this;
44
+ /**
45
+ * Writes `matrices.length / 16` instance matrices (column-major, each with last row 0, 0, 0, 1) from row `start`: the
46
+ * bulk form of `setMatrixAt` for many moving instances, one range check and one upload range for all of them.
47
+ */
48
+ setMatrices(start: number, matrices: ArrayLike<number>): this;
49
+ getMatrixAt<T extends {
50
+ [k: number]: number;
51
+ } = Float32Array>(i: number, out?: T): T;
52
+ /** Linear RGB or RGBA (0 or more; 1 = unchanged), multiplied into the base colour like a vertex colour. */
53
+ setColorAt(i: number, color: ArrayLike<number>): this;
54
+ /** UV offset and scale (an `packAtlas` region); rotation is not supported per instance. `null` restores the identity. */
55
+ setUVTransformAt(i: number, t: TextureTransform | null): this;
56
+ /** True when some drawn instance has a negative determinant (mirrored); such primitives draw without face culling. */
57
+ get mirrored(): boolean;
58
+ /** @internal The vertex buffer for `device` with pending rows uploaded (gltf\/pbr, shadows and staging call it before drawing). */
59
+ upload(device: GPUDevice): GPUBuffer;
60
+ /** @internal Shares live CPU rows and draw state, but owns an independently disposable GPU buffer. */
61
+ createProjection(): PBRInstances;
62
+ private scan;
63
+ /** Frees the GPU buffer; the next draw uploads everything again. */
64
+ dispose(): void;
65
+ [Symbol.dispose]: () => void;
66
+ /** @internal gltf\/pbr's instance vertex buffer layout (slot 1). */
67
+ get layout(): GPUVertexBufferLayout;
68
+ /** @internal gltf\/pbr's PBR shader with the instanced vertex stage. */
69
+ shader(code: string): string;
70
+ /** @internal Grows `out` (min xyz, max xyz) by the box of `vertices` (80-byte PBR) under each drawn instance's world matrix. */
71
+ bounds(node: ArrayLike<number>, vertices: Float32Array, out: Float32Array): void;
72
+ }
73
+ /**
74
+ * The EXT_mesh_gpu_instancing reader: pass it as `decoders: {instancing}` to loadGLTF, parseGLTFAsync, parseGLTF or the
75
+ * worker loaders, and each node carrying the extension draws its mesh once per instance through a PBRInstances. Without it
76
+ * a glTF that requires the extension is rejected and one that only uses it draws each mesh once at its node (the spec's
77
+ * fallback).
78
+ */
79
+ export declare const instancing: {
80
+ /** TRANSLATION/ROTATION/SCALE accessors as node-space instance matrices (T*R*S). */
81
+ read(asset: GLTFAsset, ext: GLTFInstancing): PBRInstances;
82
+ };
83
+ export { instancedShader };
@@ -0,0 +1 @@
1
+ import{a as e,i as t,t as n}from"./instanced-shader-BebTnbkj.js";import{composeMatrix as r}from"@margoengine/math/mat4";var i=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,1,1,1,1,1,1,0,0],a=class r{constructor(e){if(this.low=0,this.stale=!0,this.revision=0,this.flipCount=0,this.capacity=e,!Number.isInteger(e)||e<1||e>1e6)throw RangeError(`Invalid instance capacity; pass a whole number from 0 up to the capacity`);this.data=new Float32Array(e*24);for(let t=0;t<e;t++)this.data.set(i,t*24);this.drawn=this.high=e}get count(){return this.source?.count??this.drawn}set count(e){if(this.source)this.source.count=e;else{if(!Number.isInteger(e)||e<0||e>this.capacity)throw RangeError(`Invalid instance count; pass a whole number from 0 up to the capacity`);this.drawn=e,this.stale=!0}}get version(){return this.source?this.source.revision:this.revision}get needsUpdate(){return this.source?!this.gpu||this.revision!==this.source.revision:this.high>this.low}set needsUpdate(e){this.source?this.source.needsUpdate=e:e&&(this.low=0,this.high=this.capacity,this.stale=!0,this.revision++)}index(e){if(!Number.isInteger(e)||e<0||e>=this.capacity)throw RangeError(`Instance index out of range; use an index below the instance count`);return e*24}row(e,t,n,r,i=-1/0){if(this.source)return this.source.row(e,t,n,r,i),this;let a=this.index(e)+t,o=0;for(let e=0;e<r;e++)o+=Math.fround(n[e]);if(!Number.isFinite(o))throw RangeError(`Invalid instance value: pass finite float32 numbers`);if(i>-1/0||!ArrayBuffer.isView(n)){for(let e=0;e<r;e++)if(typeof n[e]!=`number`||n[e]<i)throw RangeError(`Invalid instance value: pass finite float32 numbers (tints 0 or more)`)}for(let e=0;e<r;e++)this.data[a+e]=n[e];if(e<this.low&&(this.low=e),e>=this.high&&(this.high=e+1),t===0&&!this.stale){let t=+(this.determinant(a)<0),n=this.flips;e<this.drawn&&(this.flipCount+=t-n[e]),n[e]=t}return this.revision++,this}determinant(e){let t=this.data;return t[e]*(t[e+5]*t[e+10]-t[e+6]*t[e+9])-t[e+4]*(t[e+1]*t[e+10]-t[e+2]*t[e+9])+t[e+8]*(t[e+1]*t[e+6]-t[e+2]*t[e+5])}setMatrixAt(e,t){if(t?.length!==16||t[3]||t[7]||t[11]||t[15]!==1)throw TypeError(`Invalid instance matrix; pass 16 finite numbers, column-major`);return this.row(e,0,t,16)}setMatrices(e,t){if(this.source)return this.source.setMatrices(e,t),this;let n=t?.length;if(!Number.isInteger(n)||n%16)throw TypeError(`Instance matrices: pass 16 numbers per instance`);let r=n/16;if(!Number.isInteger(e)||e<0||e+r>this.capacity)throw RangeError(`Instance index out of range; write rows from 0 to capacity - 1`);if(!r)return this;let i=0;for(let e=0;e<n;e++)i+=Math.fround(t[e]);if(!Number.isFinite(i))throw RangeError(`Invalid instance value: pass finite float32 numbers`);let a=!ArrayBuffer.isView(t);for(let e=0;e<r;e++){let n=e*16;if(t[n+3]||t[n+7]||t[n+11]||t[n+15]!==1)throw TypeError(`Invalid instance matrix: pass column-major affine matrices (last row 0, 0, 0, 1)`);if(a){for(let e=0;e<16;e++)if(typeof t[n+e]!=`number`)throw TypeError(`Invalid instance matrix: pass column-major affine matrices (last row 0, 0, 0, 1)`)}}let o=this.data,s=this.stale?void 0:this.flips;for(let n=0;n<r;n++){let r=e+n,i=r*24,a=n*16;for(let e=0;e<16;e++)o[i+e]=t[a+e];if(s){let e=+(this.determinant(i)<0);r<this.drawn&&(this.flipCount+=e-s[r]),s[r]=e}}return e<this.low&&(this.low=e),e+r>this.high&&(this.high=e+r),this.revision++,this}getMatrixAt(e,t=/* @__PURE__ */ new Float32Array(16)){let n=this.index(e);for(let e=0;e<16;e++)t[e]=this.data[n+e];return t}setColorAt(e,t){if(t?.length!==3&&t?.length!==4)throw TypeError(`Invalid instance color; pass finite RGB or RGBA numbers`);return this.row(e,16,t.length===3?[t[0],t[1],t[2],1]:t,4,0)}setUVTransformAt(e,t){let n=t?.offset??[0,0],r=t?.scale??[1,1];if(t?.rotation||n.length!==2||r.length!==2)throw TypeError(`Invalid instance UV transform; pass finite offset and scale numbers`);return this.row(e,20,[r[0],r[1],n[0],n[1]],4)}get mirrored(){return this.source?this.source.mirrored:(this.scan(),this.flipCount>0)}upload(e){return this.source&&this.revision!==this.source.revision&&(this.low=0,this.high=this.capacity),(this.device!==e||!this.gpu)&&(this.gpu?.destroy(),this.gpu=e.createBuffer({size:this.data.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST|GPUBufferUsage.STORAGE}),this.device=e,this.low=0,this.high=this.capacity),this.high>this.low&&(e.queue.writeBuffer(this.gpu,this.low*96,this.data,this.low*24,(this.high-this.low)*24),this.low=this.capacity,this.high=0,this.source&&(this.revision=this.source.revision)),this.source||this.scan(),this.gpu}createProjection(){let e=this.source??this;return Object.assign(Object.create(r.prototype),{data:e.data,capacity:e.capacity,source:e,revision:-1,low:0,high:e.capacity})}scan(){if(!this.stale)return;let e=this.flips??=new Uint8Array(this.capacity);this.stale=!1,this.flipCount=0;for(let t=0;t<this.capacity;t++)e[t]=+(this.determinant(t*24)<0),t<this.drawn&&(this.flipCount+=e[t])}dispose(){this.gpu?.destroy(),this.gpu=this.device=void 0}[Symbol.dispose??Symbol()](){this.dispose()}get layout(){return t}shader(e){return n(e)}bounds(t,n,r){let i=[1/0,1/0,1/0,-1/0,-1/0,-1/0],a=/* @__PURE__ */ new Float32Array(16);for(let e=0;e<n.length;e+=20)for(let t=0;t<3;t++)i[t]=Math.min(i[t],n[e+t]),i[t+3]=Math.max(i[t+3],n[e+t]);for(let n=0;n<this.count;n++){e(t,this.data,n,a);for(let e=0;e<8;e++)for(let t=0;t<3;t++){let n=a[t]*i[e&1?3:0]+a[4+t]*i[e&2?4:1]+a[8+t]*i[e&4?5:2]+a[12+t];r[t]=Math.min(r[t],n),r[t+3]=Math.max(r[t+3],n)}}}},o={read(e,t){let n=t?.attributes??{},i=(t,r)=>n[t]===void 0?null:e.accessor(n[t],r),o=i(`TRANSLATION`,`VEC3`),s=i(`ROTATION`,`VEC4`),c=i(`SCALE`,`VEC3`),l=o?o.length/3:s?s.length/4:c?c.length/3:0;if(!l||o&&o.length!==l*3||s&&s.length!==l*4||c&&c.length!==l*3)throw TypeError(`Invalid EXT_mesh_gpu_instancing attributes; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);e.reserveDecodedBytes(l*96);let u=new a(l),d=[0,0,0,1];for(let e=0;e<l;e++){if(s){let t=Math.hypot(s[e*4],s[e*4+1],s[e*4+2],s[e*4+3]);if(!t)throw RangeError(`Zero instance rotation; use a unit quaternion, not [0, 0, 0, 0]`);for(let n=0;n<4;n++)d[n]=s[e*4+n]/t}r(o?.subarray(e*3)??[0,0,0],d,c?.subarray(e*3)??[1,1,1],u.data.subarray(e*24,e*24+16))}return u}};export{a as PBRInstances,n as instancedShader,o as instancing};
package/dist/pbr.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import type { EngineKernel } from '@margoengine/core';
2
+ import type { AssetOptions, GLTFImage } from './asset.js';
3
+ import type { GLTFLoadOptions as CompressionOptions } from './compression.js';
4
+ import { type GLTFLoadOptions, type PBRModel } from './model.js';
5
+ export * from './model.js';
6
+ /** Loads a glTF or GLB file, including Draco, meshopt and KTX2, resolving its external files against the URL. */
7
+ export declare function loadGLTF(instance: EngineKernel, url: string | URL, options?: GLTFLoadOptions): Promise<PBRModel>;
8
+ /**
9
+ * Async in-memory JSON/GLB parsing, including Draco, meshopt and KTX2. With no third argument (or an options object),
10
+ * decodes embedded images and resolves external URIs against the `baseURL` option (a file in memory has no location: without it an external URI is refused). The positional buffers/images overload uses
11
+ * supplied ordinary bitmaps; an undefined buffers argument keeps that overload when images or later options are passed.
12
+ */
13
+ export declare function parseGLTFAsync(instance: EngineKernel, input: string | object | ArrayBuffer | ArrayBufferView, buffersOrOptions?: Array<ArrayBuffer | ArrayBufferView> | (AssetOptions & CompressionOptions), images?: readonly GLTFImage[], options?: GLTFLoadOptions): Promise<PBRModel>;
package/dist/pbr.js ADDED
@@ -0,0 +1 @@
1
+ import{t as e}from"./decoder-default-CxLH8Vz0.js";import{a as t,c as n,i as r,l as i,n as a,o,r as s,s as c,t as l,u}from"./model-iRvuj19h.js";import{o as d,t as f}from"./asset-1b8ejkZX.js";import{r as p}from"./texture-coordinates-XFsEMdU6.js";function m(t,n,i={}){return r(t,n,e(i))}function h(t,n,r,i=[],a={}){return r===void 0&&(r=arguments.length<4?{}:[]),Array.isArray(r)?o(t,n,r,i,e(a)):o(t,n,e(r))}export{f as GLTFAsset,l as PBRDrawRun,a as PBRModel,s as applyGLTFLights,d as closeImages,m as loadGLTF,t as parseGLTF,h as parseGLTFAsync,c as parsePreparedPBR,p as textureCoordinates,n as textureTransform,u as validatePreparedGeometry,i as viewGLTFCamera};
@@ -0,0 +1,148 @@
1
+ // @ts-ignore optional peer: its types apply when it is installed
2
+ import type { ColliderOptions, JointOptions, Physics, PhysicsBody, PhysicsJoint } from '@margoengine/physics';
3
+ import type { PBRModel } from './pbr.js';
4
+ type Vec3 = [number, number, number];
5
+ type GenericOptions = Extract<JointOptions, {
6
+ type: 'generic';
7
+ }>;
8
+ /** A shape of KHR_implicit_shapes as the file has it. */
9
+ interface ImplicitShape {
10
+ type?: string;
11
+ box?: {
12
+ size?: number[];
13
+ };
14
+ sphere?: {
15
+ radius?: number;
16
+ };
17
+ cylinder?: {
18
+ height?: number;
19
+ radiusTop?: number;
20
+ radiusBottom?: number;
21
+ };
22
+ capsule?: {
23
+ height?: number;
24
+ radiusTop?: number;
25
+ radiusBottom?: number;
26
+ };
27
+ plane?: {
28
+ sizeX?: number;
29
+ sizeZ?: number;
30
+ doubleSided?: boolean;
31
+ };
32
+ }
33
+ interface Filter {
34
+ collisionSystems?: string[];
35
+ collideWithSystems?: string[];
36
+ notCollideWithSystems?: string[];
37
+ }
38
+ interface Limit {
39
+ linearAxes?: number[];
40
+ angularAxes?: number[];
41
+ min?: number;
42
+ max?: number;
43
+ stiffness?: number;
44
+ damping?: number;
45
+ }
46
+ interface Drive {
47
+ type?: 'linear' | 'angular';
48
+ mode?: 'force' | 'acceleration';
49
+ axis?: number;
50
+ maxForce?: number;
51
+ positionTarget?: number;
52
+ velocityTarget?: number;
53
+ stiffness?: number;
54
+ damping?: number;
55
+ }
56
+ interface JointDef {
57
+ limits?: Limit[];
58
+ drives?: Drive[];
59
+ }
60
+ /** Options of {@link applyGLTFPhysics}. */
61
+ export interface GLTFPhysicsOptions {
62
+ /** The world to add to. Default: a new one on the model's engine, after `Physics.load()`. */
63
+ physics?: Physics;
64
+ }
65
+ /** A trigger volume of the file: its node, and the body that carries it. */
66
+ export interface GLTFTrigger {
67
+ nodeIndex: number;
68
+ body: PhysicsBody;
69
+ }
70
+ /** Something the file asks for that this physics world holds only approximately. */
71
+ export interface GLTFPhysicsNote {
72
+ /** The node it applies to, or -1 for the file as a whole. */
73
+ nodeIndex: number;
74
+ /** What differs from the file, in words. */
75
+ note: string;
76
+ }
77
+ /** A collider going into or out of a trigger. */
78
+ export interface GLTFTriggerEvent {
79
+ entered: boolean;
80
+ /** The trigger: its node, or the node of the compound trigger it is part of. */
81
+ nodeIndex: number;
82
+ /** The node of the collider that moved, or -1 for a collider the file does not hold. */
83
+ colliderNodeIndex: number;
84
+ /** The node with the motion that collider belongs to, or -1 for none. */
85
+ motionNodeIndex: number;
86
+ /** The body of that collider. */
87
+ body: PhysicsBody;
88
+ }
89
+ /** The physics of a model, made by {@link applyGLTFPhysics}. */
90
+ export interface GLTFPhysics {
91
+ readonly physics: Physics;
92
+ /** The body of each node with a motion or a static collider, by node index. */
93
+ readonly bodies: ReadonlyMap<number, PhysicsBody>;
94
+ /** The joint of each node with one, by node index. */
95
+ readonly joints: ReadonlyMap<number, PhysicsJoint>;
96
+ readonly triggers: readonly GLTFTrigger[];
97
+ /** Everything held approximately; empty means the file is represented as written. */
98
+ readonly notes: readonly GLTFPhysicsNote[];
99
+ /** The body that moves `nodeIndex`: its own, or the nearest parent's. */
100
+ bodyOf(nodeIndex: number): PhysicsBody | undefined;
101
+ /**
102
+ * Writes a property the draft's object model calls mutable: a joint drive's `maxForce`, `positionTarget`,
103
+ * `velocityTarget`, `stiffness` or `damping`, or a motion's `linearVelocity`, `angularVelocity` or `gravityFactor`.
104
+ * @returns false for a pointer this does not write.
105
+ */
106
+ setPointer(pointer: string, value: number | readonly number[]): boolean;
107
+ /** Calls `listener` as colliders enter and leave a trigger; returns a remover. */
108
+ onTrigger(listener: (event: GLTFTriggerEvent) => void): () => void;
109
+ /** Removes the bodies and joints, and the world too when it was made here. */
110
+ dispose(): void;
111
+ }
112
+ /**
113
+ * Packed interaction groups per filter, the last entry for colliders without one: one group for each distinct filter.
114
+ * Comparing whole filters pair by pair keeps the draft's test exact: `A` meets `B` only when each lets the other in, and a
115
+ * list is met when all of the other's systems are on it, which group masks alone could not say. A collider in no system
116
+ * is on no list: it meets whatever does not name its partners, as the draft's defaults intend.
117
+ * @throws RangeError past 15 distinct filters, as a world has 16 groups.
118
+ */
119
+ export declare function filterMasks(filters: readonly Filter[]): {
120
+ memberships: number;
121
+ filter: number;
122
+ }[];
123
+ /** What a shape of the file is at `scale`, in the world's collider terms, with a note where it cannot be exact. */
124
+ export declare function shapeCollider(shape: ImplicitShape, scale: Vec3): {
125
+ collider: ColliderOptions;
126
+ note?: string;
127
+ };
128
+ /**
129
+ * The file's limits and drives as one generic joint. A limit on one axis is exact, closed or a range. A limit on several
130
+ * axes at once is a distance or angle from rest: closed it is exact, otherwise a range on each axis, a box where the draft
131
+ * has a sphere or a cone. Limits are hard, so a limit's stiffness only adds a note. Limits on one axis narrow each other.
132
+ */
133
+ export declare function jointOptions(_arg0: JointDef, notes?: string[]): Pick<GenericOptions, 'locked' | 'limits' | 'motors'>;
134
+ /**
135
+ * Builds a model's KHR_physics_rigid_bodies in a physics world: a node with a motion is a body that moves it, with its
136
+ * descendants' colliders on it; a collider with no motion above it is fixed; triggers are sensors; joints connect the two
137
+ * attachment frames. Nodes the file animates are kinematic and follow their animation, scale included, and the file's
138
+ * KHR_animation_pointer channels on joint drives play on the world's clock. Loads `@margoengine/physics`.
139
+ *
140
+ * @example
141
+ * const model = await loadGLTF(engine, '/door.gltf');
142
+ * const world = await applyGLTFPhysics(model);
143
+ * world.onTrigger(({entered, nodeIndex}) => console.log(entered, nodeIndex));
144
+ * @throws TypeError for a file that breaks the extension's rules.
145
+ * @throws RangeError past 15 distinct collision filters.
146
+ */
147
+ export declare function applyGLTFPhysics(model: PBRModel, options?: GLTFPhysicsOptions): Promise<GLTFPhysics>;
148
+ export {};
@@ -0,0 +1 @@
1
+ import{n as e}from"./errors-THVaUwlL.js";import{n as t,t as n}from"./scene-scope-CZDEkd24.js";import{r}from"./pack-BVDYuqZe.js";import{normalizeQuaternion as i,rotationToQuaternion as a}from"@margoengine/math/quat";import{composeMatrix as o,invertMatrix as s,multiplyMatrices as c}from"@margoengine/math/mat4";var l=e=>/* @__PURE__ */ TypeError(`Invalid ${e}; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`),u={box:[1,1,1],sphere:.5,height:.5,radius:.25},d={friction:.6,restitution:0};function f(e){return e.matrix?Float64Array.from(e.matrix):o(e.translation??[0,0,0],e.rotation??[0,0,0,1],e.scale??[1,1,1],/* @__PURE__ */ new Float64Array(16))}function p(e){let t=[Math.hypot(e[0],e[1],e[2]),Math.hypot(e[4],e[5],e[6]),Math.hypot(e[8],e[9],e[10])];e[0]*(e[5]*e[10]-e[6]*e[9])-e[4]*(e[1]*e[10]-e[2]*e[9])+e[8]*(e[1]*e[6]-e[2]*e[5])<0&&(t[0]=-t[0]);let n=[0,0,0,1];return a(e,n,t[0]||1,t[1]||1,t[2]||1),i(n,n),{position:[e[12],e[13],e[14]],rotation:n,scale:t}}function m(e){let{position:t,rotation:n}=p(e);return o(t,n,[1,1,1],/* @__PURE__ */ new Float64Array(16))}function h(e,t){let n=s(m(e),/* @__PURE__ */ new Float64Array(16));if(!n)throw l(`KHR_physics_rigid_bodies node transform`);return c(n,t,/* @__PURE__ */ new Float64Array(16))}function g(e,t){let n=m(e);return[0,1,2].map(e=>n[e]*t[0]+n[4+e]*t[1]+n[8+e]*t[2])}function ee(e,t=[0,0,0,1]){return[e[3]*t[0]+e[0]*t[3]+e[1]*t[2]-e[2]*t[1],e[3]*t[1]-e[0]*t[2]+e[1]*t[3]+e[2]*t[0],e[3]*t[2]+e[0]*t[1]-e[1]*t[0]+e[2]*t[3],e[3]*t[3]-e[0]*t[0]-e[1]*t[1]-e[2]*t[2]]}function te(e,t,n=[0,0,0]){let[r,i,a,o]=t,[s,c,l]=n,u=2*(i*l-a*c),d=2*(a*s-r*l),f=2*(r*c-i*s);return[e[0]+s+o*u+i*f-a*d,e[1]+c+o*d+a*u-r*f,e[2]+l+o*f+r*d-i*u]}function _(e){let t=[...e,{}],n=e=>JSON.stringify([e.collisionSystems,e.collideWithSystems,e.notCollideWithSystems]),r=[...new Map(t.map(e=>[n(e),e])).values()];if(r.length>16)throw RangeError(`KHR_physics_rigid_bodies: more than 15 distinct collision filters; merge filters that act alike in the file`);let i=(e,t)=>!!e.collisionSystems?.length&&e.collisionSystems.every(e=>t.includes(e)),a=(e,t)=>(!e.collideWithSystems||i(t,e.collideWithSystems))&&(!e.notCollideWithSystems||!i(t,e.notCollideWithSystems)),o=r.map((e,t)=>({memberships:1<<t,filter:r.reduce((t,n,r)=>a(e,n)&&a(n,e)?t|1<<r:t,0)}));return t.map(e=>o[r.findIndex(t=>n(t)===n(e))])}var v=(e,t,n,r,i=16)=>{for(let a=0;a<i;a++){let o=a/i*Math.PI*2;r.push(Math.cos(o)*t*n[0],e*n[1],Math.sin(o)*t*n[2])}},y=(e,t,n,r)=>{for(let i of[1,-1])for(let a=0;a<=6;a++){let o=a/6*(Math.PI/2);a===6?r.push(0,(e+i*t)*n[1],0):v(e+i*Math.sin(o)*t,Math.cos(o)*t,n,r)}};function b(e,t){let[n,r,i]=t,a=(e,t)=>Math.abs(e-t)<=1e-6*Math.max(e,t),o=a(n,i),s=(e,t)=>({collider:{shape:`convexHull`,points:Float32Array.from(e)},note:t});switch(e.type){case`box`:{let[t,a,o]=e.box?.size??u.box;return{collider:{shape:`box`,halfExtents:[t*n/2,a*r/2,o*i/2]}}}case`sphere`:{let i=e.sphere?.radius??u.sphere;if(o&&a(n,r))return{collider:{shape:`sphere`,radius:i*n}};let c=[];return y(0,i,t,c),s(c,`a sphere under uneven scale is a convex hull of 194 points`)}case`cylinder`:{let i=e.cylinder?.height??u.height,c=e.cylinder?.radiusTop??u.radius,l=e.cylinder?.radiusBottom??u.radius,d=i/2*r;if(o&&a(c,l))return{collider:{shape:`cylinder`,halfHeight:d,radius:c*n}};if(o&&!c)return{collider:{shape:`cone`,halfHeight:d,radius:l*n}};if(o&&!l)return{collider:{shape:`cone`,halfHeight:d,radius:c*n,rotation:[1,0,0,0]}};let f=[];return v(i/2,c,t,f,32),v(-i/2,l,t,f,32),s(f,`a cylinder with two radii or uneven scale is a convex hull of 64 points`)}case`capsule`:{let i=e.capsule?.height??u.height,c=e.capsule?.radiusTop??u.radius,l=e.capsule?.radiusBottom??u.radius;if(o&&a(c,l)&&a(n,r))return{collider:{shape:`capsule`,halfHeight:i/2*r,radius:c*n}};let d=[];return y(i/2,c,t,d),y(-i/2,l,t,d),s(d,`a capsule with two radii or uneven scale is a convex hull of 388 points`)}case`plane`:{let{sizeX:t,sizeZ:r,doubleSided:a}=e.plane??{};if(t===void 0&&r===void 0&&!a)return{collider:{shape:`halfSpace`}};let o=1e3;return{collider:{shape:`box`,halfExtents:[t===void 0?o:t*n/2,.001,r===void 0?o:r*i/2],offset:[0,a?0:-.001,0]},note:`a finite or double sided plane is a box 2 mm thick`}}default:throw l(`KHR_implicit_shapes type ${String(e.type)}`)}}var x=[`linX`,`linY`,`linZ`,`angX`,`angY`,`angZ`],S=e=>{if(!(e.axis>=0&&e.axis<=2)||e.type!==`linear`&&e.type!==`angular`)throw l(`KHR_physics_rigid_bodies joint drive`);return x[(e.type===`linear`?0:3)+e.axis]},C=e=>({targetPosition:e.positionTarget??0,targetVelocity:e.velocityTarget??0,stiffness:e.stiffness??0,damping:e.damping??0,model:e.mode===`force`?`force`:`acceleration`,...e.maxForce===void 0?{}:{maxForce:e.maxForce}});function w({limits:e=[],drives:t=[]},n=[]){let r=/* @__PURE__ */ new Set,i={},a={};for(let t of e){let e=t.linearAxes??t.angularAxes;if(!e?.length||e.length>3||t.linearAxes&&t.angularAxes)throw l(`KHR_physics_rigid_bodies joint limit`);t.stiffness!==void 0&&n.push(`a soft joint limit is held hard`);let a=e.length>1,o=t.linearAxes?1e6:Math.PI;if(a&&t.max===void 0){t.min&&n.push(`a lower limit on several axes at once is not held`);continue}a&&t.min&&n.push(`a lower limit on several axes at once is not held`),a&&t.max&&n.push(`a limit on ${e.length} axes at once is a range on each axis`);let s=Math.min(t.max??o,o),c=a?-s:Math.max(t.min??-o,-o);for(let n of e){if(!(n>=0&&n<=2))throw l(`KHR_physics_rigid_bodies joint axis`);let e=x[(t.linearAxes?0:3)+n],a=i[e];c===0&&s===0?r.add(e):i[e]=a?[Math.max(a[0],c),Math.min(a[1],s)]:[c,s]}}for(let e of r)delete i[e];for(let e of t)a[S(e)]=C(e);return{locked:[...r],limits:i,motors:a}}function ne({times:e,values:t,mode:n},r){let i=n===`CUBICSPLINE`,a=e=>t[i?e*3+1:e],o=e.length-1;if(r<=e[0])return a(0);if(r>=e[o])return a(o);let s=0;for(;e[s+1]<=r;)s++;let c=e[s+1]-e[s],l=(r-e[s])/c;if(n===`STEP`)return a(s);if(!i)return a(s)+(a(s+1)-a(s))*l;let u=l*l,d=u*l;return(2*d-3*u+1)*a(s)+(d-2*u+l)*c*t[s*3+2]+(-2*d+3*u)*a(s+1)+(d-u)*c*t[(s+1)*3]}var T=/^\/extensions\/KHR_physics_rigid_bodies\/physicsJoints\/(\d+)\/drives\/(\d+)\/(maxForce|positionTarget|velocityTarget|stiffness|damping)$/,re=/^\/nodes\/(\d+)\/extensions\/KHR_physics_rigid_bodies\/motion\/(linearVelocity|angularVelocity|gravityFactor)$/;async function E(i,a={}){let s=i.engine,u=s?.sceneOf?.(i),m=u?t(s,u):n(s),{Physics:v,collisionGroups:y}=await import(`@margoengine/physics`).catch(t=>{throw e(`unsupported`,`glTF physics needs @margoengine/physics (${t instanceof Error?t.message:t}): install it to use @margoengine/gltf/physics`)});a.physics||await v.load();let x=!a.physics,E=a.physics??m.run(()=>v.attach(s)),D=i.asset.doc,O=D.nodes??[],k=D.extensions?.KHR_physics_rigid_bodies??{},ie=D.extensions?.KHR_implicit_shapes?.shapes??[],ae=k.physicsMaterials??[],A=k.collisionFilters??[],j=structuredClone(k.physicsJoints??[]),oe=_(A),M=new Int32Array(O.length).fill(-1),N=[],P=/* @__PURE__ */ new Map,F=/* @__PURE__ */ new Map,I=/* @__PURE__ */ new Map,L=[],R=[],z=[],B=/* @__PURE__ */ new Map,V=(e,t)=>{N.some(n=>n.nodeIndex===e&&n.note===t)||N.push({nodeIndex:e,note:t})};O.forEach((e,t)=>e?.children?.forEach(e=>M[e]=t));let H=e=>O[e]?.extensions?.KHR_physics_rigid_bodies;s?.store.tick(!1);let U=e=>{let t=i.nodes[e];if(t)return Float64Array.from(t.matrix);let n=M[e];return n<0?f(O[e]):c(U(n),f(O[e]),/* @__PURE__ */ new Float64Array(16))},W=e=>{for(let t=e;t>=0;t=M[t])if(H(t)?.motion)return t;return-1},G=/* @__PURE__ */ new Set,K=/* @__PURE__ */ new Set,q=[];for(let e of D.animations??[])for(let t of e.channels??[]){let n=t.target,r=n?.extensions?.KHR_animation_pointer?.pointer,a=r?/^\/nodes\/(\d+)\/(translation|rotation|scale|matrix)$/.exec(r):void 0,o=r?a?.[1]:n?.node,s=r?a?.[2]:n?.path;if(o!==void 0&&s!==`weights`&&(G.add(+o),(s===`scale`||s===`matrix`)&&K.add(+o)),r){if(T.exec(r)){let n=e.samplers[t.sampler];q.push({pointer:r,times:i.asset.accessor(n.input,`SCALAR`),values:i.asset.accessor(n.output,`SCALAR`),mode:n.interpolation??`LINEAR`})}else r.includes(`KHR_physics_rigid_bodies`)&&V(-1,`the animated property ${r} is not followed`)}}let J=(e,t)=>{for(let n=e;n>=0;n=M[n])if(t.has(n))return!0;return!1},Y=/* @__PURE__ */ new Map,se=e=>{let t=Y.get(e);if(!t){let n=D.meshes?.[e];if(!n)throw l(`KHR_physics_rigid_bodies geometry mesh`);t=n.primitives.filter(e=>(e.mode??4)>=4).flatMap(e=>r(i.asset,e).map(({vertices:e,indices:t})=>{let n=new Float32Array(e.length/20*3);for(let t=0,r=0;r<e.length;t+=3,r+=20)n.set(e.subarray(r,r+3),t);return{positions:n,indices:t}})),Y.set(e,t)}return t},ce=(e,t)=>{let n=[],r=[],i=(e,i)=>{for(let a of se(e)){let e=n.length/3;for(let e=0;e<a.positions.length;e+=3){let r=a.positions[e],o=a.positions[e+1],s=a.positions[e+2];for(let e=0;e<3;e++)n.push((i[e]*r+i[4+e]*o+i[8+e]*s+i[12+e])*t[e])}for(let t=0;t<a.indices.length;t++)r.push(e+a.indices[t])}},a=(e,t)=>{if(!O[e])throw l(`KHR_physics_rigid_bodies geometry node`);O[e].mesh!==void 0&&i(O[e].mesh,t);for(let n of O[e].children??[])a(n,c(t,f(O[n]),/* @__PURE__ */ new Float64Array(16)))},s=o([0,0,0],[0,0,0,1],[1,1,1],/* @__PURE__ */ new Float64Array(16));return e.node===void 0?i(e.mesh,s):a(e.node,s),{points:n,indices:r}},X=e=>{let{geometry:t,node:n}=e,{position:r,rotation:i,scale:a}=p(h(U(e.base),U(n))),o=a.map(Math.abs);if(e.size=o,o.some(e=>e===0))return;if(t.shape===void 0==(t.node===void 0&&t.mesh===void 0))throw l(`KHR_physics_rigid_bodies geometry`);let s;if(t.shape!==void 0){let e=ie[t.shape];if(!e)throw l(`KHR_implicit_shapes shape index`);let r=b(e,o);s=r.collider,r.note&&V(n,r.note)}else{let{points:e,indices:n}=ce(t,o);if(!e.length)return;s=t.convexHull?{shape:`convexHull`,points:Float32Array.from(e)}:{shape:`trimesh`,vertices:Float32Array.from(e),indices:Uint32Array.from(n)}}let c=s;return{...s,...e.extra,offset:te(r,i,c.offset),rotation:ee(i,c.rotation)}},le=(e,t,n)=>{let r={};if(A.length){let e=oe[t??A.length];if(!e)throw l(`KHR_physics_rigid_bodies collisionFilter`);r.collisionGroups=y(e.memberships,e.filter)}if(n!==void 0){let t=ae[n];if(!t)throw l(`KHR_physics_rigid_bodies physicsMaterial`);let i=e=>e===`minimum`?`min`:e===`maximum`?`max`:e,a=t.dynamicFriction??d.friction;(t.staticFriction??d.friction)!==a&&V(e,`static friction is not separate: the dynamic value is used`),r.friction=a,r.restitution=t.restitution??d.restitution,t.frictionCombine&&(r.frictionCombine=i(t.frictionCombine)),t.restitutionCombine&&(r.restitutionCombine=i(t.restitutionCombine))}return r},Z=/* @__PURE__ */ new Map,Q=/* @__PURE__ */ new Map,ue=(e,t,n)=>{if(!t)throw l(`KHR_physics_rigid_bodies geometry`);let r=W(e),i=r>=0?r:e;Z.has(i)||Z.set(i,[]),Z.get(i).push({node:e,base:i,geometry:t,extra:n})};O.forEach((e,t)=>{let{collider:n,trigger:r}=H(t)??{};if(n&&ue(t,n.geometry,le(t,n.collisionFilter,n.physicsMaterial)),r?.nodes)for(let e of r.nodes)Q.set(e,t);r?.geometry&&ue(t,r.geometry,{...le(t,r.collisionFilter),sensor:!0,density:0})});let de=/* @__PURE__ */ new Set;O.forEach((e,t)=>{let n=H(t)?.joint;if(n&&j[n.joint]?.drives?.length)for(let e of[t,n.connectedNode])de.add(W(e))});let $=(e,t)=>{let n=i.nodes[e],r=!!n&&J(e,G),a=(Z.get(e)??[]).map(e=>({part:e,collider:X(e)})).filter(e=>e.collider),o=a.map(e=>e.collider),{position:s,rotation:c}=p(U(e)),l=de.has(e)?{canSleep:!1}:{},u=n&&t!==`fixed`&&!r?E.addBody(n,{type:t,colliders:o,...l}):E.addBody(null,{type:r?`kinematicPosition`:t,position:s,rotation:c,colliders:o,...l});return a.forEach(({part:e},t)=>{e.made=u.colliders[t],B.set(u.colliders[t],e.node)}),r&&R.push({body:u,node:e}),P.set(e,u),u},fe=e=>{let t=W(e);return P.get(t>=0?t:e)},pe=e=>{let t=W(e),n=t>=0?t:e;return[P.get(n)??$(n,`fixed`),p(h(U(n),U(e)))]},me=(e,t,n)=>{let{mass:r,inertiaDiagonal:i,centerOfMass:a,inertiaOrientation:o}=t;(r!==void 0||i||a)&&e.setMassProperties({mass:r,centerOfMass:a&&a.map((e,t)=>e*n[t]),inertia:i,inertiaFrame:o})},he=()=>{for(let e of z.splice(0))e();for(let e of F.values())e.remove();for(let e of P.values())E.removeBody(e);x&&E.dispose()};try{O.forEach((e,t)=>{let n=H(t)?.motion;if(!n)return;let r=U(t),i=$(t,n.isKinematic?`kinematicVelocity`:`dynamic`);n.linearVelocity&&i.setLinearVelocity(g(r,n.linearVelocity)),n.angularVelocity&&i.setAngularVelocity(g(r,n.angularVelocity)),n.gravityFactor!==void 0&&(i.gravityScale=n.gravityFactor),n.isKinematic||me(i,n,p(r).scale)});for(let e of Z.keys())P.has(e)||$(e,`fixed`);O.forEach((e,t)=>{H(t)?.trigger?.geometry&&L.push({nodeIndex:t,body:fe(t)})}),O.forEach((e,t)=>{let n=H(t)?.joint;if(!n)return;let r=j[n.joint],i=n.connectedNode;if(!r||!O[i])throw l(`KHR_physics_rigid_bodies joint`);let a=[],o=w(r,a),[s,c]=pe(t),[u,d]=pe(i);for(let e of a)V(t,e);if(s===u)return V(t,`a joint between two nodes of one body has no effect`);let f=E.addJoint(s,u,{type:`generic`,...o,anchorA:c.position,frameA:c.rotation,anchorB:d.position,frameB:d.rotation,contactsEnabled:!!n.enableCollision});F.set(t,f),I.has(n.joint)||I.set(n.joint,[]),I.get(n.joint).push(f)})}catch(e){throw he(),e}let ge=(e,t)=>{let n=T.exec(e);if(n){let e=j[+n[1]]?.drives?.[+n[2]];if(!e||typeof t!=`number`)return!1;e[n[3]]=t;for(let t of I.get(+n[1])??[])t.setAxisMotor(S(e),C(e));return!0}let r=re.exec(e),i=r&&P.get(+r[1]);if(!r||!i)return!1;if(r[2]===`gravityFactor`)return typeof t==`number`&&(i.gravityScale=t,!0);if(typeof t==`number`)return!1;let a=g(U(+r[1]),t);return r[2]===`linearVelocity`?i.setLinearVelocity(a):i.setAngularVelocity(a),!0},_e=(e,t)=>{let n=e.size,{scale:r}=p(h(U(e.base),U(e.node)));if(r.every((e,t)=>Math.abs(Math.abs(e)-n[t])<=1e-6*n[t]))return;e.made&&=(B.delete(e.made),t.removeCollider(e.made),void 0);let i=X(e);i&&(e.made=t.addCollider(i),B.set(e.made,e.node))};if(R.length||q.length){let e=0,t=q.reduce((e,t)=>Math.max(e,t.times[t.times.length-1]),0);z.push(E.on(`beforestep`,n=>{if(q.length){e+=n;let r=t>0?e%t:0;for(let e of q)ge(e.pointer,ne(e,r))}for(let{body:e,node:t}of R){let{position:n,rotation:r}=p(U(t));e.setNextPosition(n),e.setNextRotation(r);for(let n of Z.get(t)??[])J(n.node,K)&&_e(n,e)}}))}let ve=e=>{let t=e;for(;Q.has(t);)t=Q.get(t);return t},ye=!1;return{physics:E,bodies:P,joints:F,triggers:L,notes:N,bodyOf:fe,setPointer:ge,onTrigger(e){let t=/* @__PURE__ */ new Map,n=n=>r=>{for(let[i,a,o]of[[r.colliderA,r.colliderB,r.bodyB],[r.colliderB,r.colliderA,r.bodyA]]){let r=B.get(i);if(r===void 0||!i.isSensor()||a.isSensor())continue;let s=ve(r),c=`${s}/${a.handle}`,l=(t.get(c)??0)+(n?1:-1);if(l?t.set(c,l):t.delete(c),l!==+!!n)continue;let u=B.get(a)??-1;e({entered:n,nodeIndex:s,colliderNodeIndex:u,motionNodeIndex:u<0?-1:W(u),body:o})}},r=[E.on(`intersectionstart`,n(!0)),E.on(`intersectionend`,n(!1))],i=()=>r.forEach(e=>e());return z.push(i),i},dispose(){ye||(ye=!0,he())}}}export{E as applyGLTFPhysics,_ as filterMasks,w as jointOptions,b as shapeCollider};
@@ -0,0 +1,26 @@
1
+ import { type GLTFAsset, type GLTFDocument, type GLTFImage } from './asset.js';
2
+ import type { PreparedGeometry } from './pbr.js';
3
+ /** A glTF parsed off the main thread: everything PBRModel needs except GPU uploads. Every buffer is transferable. */
4
+ export interface PreparedGLTF {
5
+ doc: GLTFDocument;
6
+ /** Compressed inputs are transferred back for automatic decoding on the GPU-owning thread. */
7
+ deferred?: boolean;
8
+ baseURL?: string;
9
+ downloadedBytes?: number;
10
+ buffers: Uint8Array[];
11
+ images: GLTFImage[];
12
+ /** Packed geometry per mesh and primitive; null where packing failed (the main thread repeats it and reports the error). */
13
+ geometry: (PreparedGeometry | readonly PreparedGeometry[] | null)[][];
14
+ /** Decoded accessors by index (geometry, skins, morph targets, animation samplers, GPU instancing), as GLTFAsset caches them. */
15
+ accessors: [number, Float32Array][];
16
+ /** The load's `maxDownloadBytes`, so the main thread's asset keeps the same budgets (absent: the default). */
17
+ maxDownloadBytes?: number;
18
+ /** The load's `maxNodes` (absent: the default). */
19
+ maxNodes?: number;
20
+ /** The load's `maxPartVertices` (absent: the default). */
21
+ maxPartVertices?: number;
22
+ }
23
+ /** Decode what PBRModel and @margoengine/animation read from an asset: packed primitives and their accessors. */
24
+ export declare function prepareAsset(asset: GLTFAsset, images: GLTFImage[]): PreparedGLTF;
25
+ /** Fetch (url) or parse (input) and prepare a glTF; no decoders (Draco, meshopt, KTX2 need the main-thread path). */
26
+ export declare function prepareGLTF(url: string | URL | undefined, input?: string | object | ArrayBuffer | ArrayBufferView, buffers?: Array<ArrayBuffer | ArrayBufferView>, maxDownloadBytes?: number, maxNodes?: number, allowedURLs?: readonly string[], optimize?: boolean, maxPartVertices?: number): Promise<PreparedGLTF>;
@@ -0,0 +1 @@
1
+ import{_ as e,g as t}from"./asset-1b8ejkZX.js";import{r as n,t as r}from"./pack-BVDYuqZe.js";function i(t,i){let a=t.doc,o=e=>{try{return e()}catch{return null}},s=0,c=(a.meshes??[]).map(r=>(Array.isArray(r?.primitives)?r.primitives:[]).map(r=>{let i=o(()=>n(t,r));for(let e of i??[])s+=e.vertices.byteLength+e.indices.byteLength+(e.uvs?.byteLength??0);if(s>t.maxBytes*4)throw e(`Decoded glTF geometry exceeds byte budget`,t.maxBytes*4);return i&&i.length===1?i[0]:i}));return r(t),{doc:a,buffers:t.buffers,images:i,geometry:c,accessors:[...t.cache],maxDownloadBytes:t.maxBytes,maxNodes:t.maxNodes,maxPartVertices:t.partVertices}}async function a(e,n,r,a,o,s,c,l){let{asset:u,images:d,deferred:f,baseURL:p,downloadedBytes:m}=await t(e,{buffers:r,maxDownloadBytes:a,maxNodes:o,allowedURLs:s,optimize:c,maxPartVertices:l},n,{},!0);return f?{doc:u.doc,buffers:u.buffers,images:d,geometry:[],accessors:[],maxDownloadBytes:u.maxBytes,maxNodes:u.maxNodes,maxPartVertices:u.partVertices,deferred:f,baseURL:p,downloadedBytes:m}:i(u,d)}export{i as prepareAsset,a as prepareGLTF};
@@ -0,0 +1,59 @@
1
+ import type { EngineKernel } from '@margoengine/core';
2
+ import { PBRModel, type GLTFLoadOptions } from './pbr.js';
3
+ import type { GLTFTextureStream, GLTFTextureStreamOptions } from './texture-stream.js';
4
+ export type { GLTFTextureStream, GLTFTextureStreamOptions } from './texture-stream.js';
5
+ /** A progress report of loadGLTFProgressive: the stage, bytes loaded and total, and primitives drawn and loaded. */
6
+ export interface ProgressiveGLTFProgress {
7
+ /** `ready`: placeholders drawn; `geometry`/`textures`: streaming; `complete`: equal to a plain `loadGLTF` model. */
8
+ stage: 'ready' | 'geometry' | 'textures' | 'complete';
9
+ bytesLoaded: number;
10
+ bytesTotal: number;
11
+ /** Distinct glTF primitives (mesh primitives) drawn by the scene, and how many have their real geometry. */
12
+ primitives: number;
13
+ primitivesLoaded: number;
14
+ images: number;
15
+ imagesLoaded: number;
16
+ }
17
+ /**
18
+ * Options of loadGLTFProgressive: the loadGLTF options, a progress callback and the per-frame upload budget in milliseconds.
19
+ */
20
+ export interface ProgressiveGLTFOptions extends GLTFLoadOptions {
21
+ onProgress?: (progress: ProgressiveGLTFProgress) => void;
22
+ /** Main-thread milliseconds per frame spent on GPU uploads (default 4); at least one upload step runs each frame. */
23
+ frameBudget?: number;
24
+ /**
25
+ * Upload steps per frame, a work count that replaces `frameBudget`: the same steps run on every pump on any machine,
26
+ * so the intermediate model of a film frame is the same on every run (`await load.complete` for the finished model,
27
+ * which is the same whatever the budget). 1 or more, Infinity for every waiting step. Default unset.
28
+ */
29
+ maxJobs?: number;
30
+ /** Clock in milliseconds for `frameBudget` and the view re-sort. Default `performance.now`; pass a simulation clock for replay. */
31
+ clock?: () => number;
32
+ /**
33
+ * Streams KTX2 textures: each starts from its smallest levels, and finer levels load only as its size on screen calls
34
+ * for them, inside `budgetBytes`. PNG and JPEG files hold no mips, so those load whole. Default off; off WebGPU it has no
35
+ * effect.
36
+ */
37
+ textures?: boolean | GLTFTextureStreamOptions;
38
+ }
39
+ /**
40
+ * A progressive load: `ready` resolves with placeholder boxes, `complete` with the full model, and abort() stops it.
41
+ */
42
+ export interface ProgressiveGLTF {
43
+ /** The model, as soon as the JSON is parsed: one box per primitive (its POSITION bounds, material colours), bounds valid. */
44
+ readonly ready: Promise<PBRModel>;
45
+ /** The same model once every primitive, image and byte has arrived: its GPU data then equals `loadGLTF`'s. */
46
+ readonly complete: Promise<PBRModel>;
47
+ /** Stop loading and dispose the model; both promises reject (disposing the model does the same). */
48
+ abort(reason?: unknown): void;
49
+ /** With the `textures` option: the live texture streams, which run for as long as the model lives. */
50
+ readonly textures?: Promise<GLTFTextureStream>;
51
+ }
52
+ /**
53
+ * Load a .glb/.gltf so it is interactive at once: `ready` resolves with the model drawn as one box per primitive (fit the
54
+ * camera to `model.bounds`), then real geometry streams in, most visible and largest on screen first (HTTP range requests
55
+ * where the server supports them, else the whole file parsed as it arrives), then textures. Network and decoding run in a
56
+ * worker (dist/workers/progressive.js; on this thread where Worker is unavailable); GPU uploads run here within
57
+ * `frameBudget` ms per animation frame. Draco, meshopt or KTX2 `decoders` fall back to `loadGLTF` (ready = complete).
58
+ */
59
+ export declare function loadGLTFProgressive(instance: EngineKernel, url: string | URL, options?: ProgressiveGLTFOptions): ProgressiveGLTF;
@@ -0,0 +1,4 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const p=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import{n as e}from"./errors-THVaUwlL.js";import{f as t}from"./version-BmU1nesQ.js";import{t as n}from"./scene-scope-CZDEkd24.js";import{n as r}from"./model-iRvuj19h.js";import{A as i,_ as a,f as o,n as s,t as c}from"./asset-1b8ejkZX.js";import{a as l,i as u}from"./pack-BVDYuqZe.js";import{loadGLTF as d}from"./pbr.js";import{t as f}from"./worker-CY1TQnYX.js";import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";function m(e,t,n,r=0,i=0,a=0){let o=e[t],s=e[t+1],c=e[t+2],l=e[t+4],u=e[t+5],d=e[t+6],f=e[t+8],p=e[t+9],m=e[t+10],h=o*o+s*s+c*c,ee=l*l+u*u+d*d,te=f*f+p*p+m*m,g=Math.abs(o*l+s*u+c*d),_=Math.abs(o*f+s*p+c*m),v=Math.abs(l*f+u*p+d*m),y=n*Math.sqrt(Math.max(h+g+_,ee+g+v,te+_+v));return y+1e-5*(Math.hypot(r,i,a)+y)}var h=Symbol.for(`margoengine.gltf/pbr.defer-static-batches`),ee=()=>new URL(`./workers/progressive.js?no-inline`,import.meta.url),te=1<<20,g=[`KHR_texture_basisu`,`EXT_texture_webp`,`EXT_texture_avif`],_={TypeError,RangeError,SyntaxError},v=t=>{let n=typeof t?.message==`string`?t.message:`Progressive glTF worker sent an invalid message`;return t?.name===`MargoError`&&typeof t.code==`string`?e(t.code,n):new(Object.hasOwn(_,t?.name??``)?_[t.name]:Error)(n)};function y(e,t){let n=e.accessors?.[t?.attributes?.POSITION],r=e=>Array.isArray(e)&&e.length===3&&e.every(Number.isFinite),i=n?.normalized?{5120:127,5121:255,5122:32767,5123:65535}[n.componentType]??1:1,a=e=>r(e)?e.map(e=>i>1?Math.max(-1,e/i):e):[0,0,0],o=a(n?.min),s=a(n?.max),c=/* @__PURE__ */ new Float32Array(480),l=/* @__PURE__ */ new Uint32Array(36);for(let e=0;e<6;e++){let t=e>>1,n=e&1?1:-1,r=(t+1)%3,i=(t+2)%3,a=e*4;for(let e=0;e<4;e++){let l=(a+e)*20;c[l+t]=n>0?s[t]:o[t],c[l+r]=e&1?s[r]:o[r],c[l+i]=e&2?s[i]:o[i],c[l+3]=1,c[l+4+t]=n,c.fill(1,l+16,l+20)}l.set(n>0?[a,a+1,a+3,a,a+3,a+2]:[a,a+3,a+1,a,a+2,a+3],e*6)}return{vertices:c,indices:l,lo:o,hi:s}}function b(e,_,b={}){let{decoders:x={},signal:S,onProgress:ne,frameBudget:re=4,maxJobs:C,clock:w=()=>performance.now()}=b,T=new AbortController;if(C!==void 0&&!(C>=1))throw RangeError(`Invalid maxJobs; pass a count, 1 or more`);if(typeof w!=`function`)throw TypeError(`Invalid clock; pass a function returning milliseconds`);let E=e=>T.abort(e);S?.aborted?E(S.reason):S?.addEventListener(`abort`,()=>E(S.reason),{once:!0});let D={stage:`ready`,bytesLoaded:0,bytesTotal:0,primitives:0,primitivesLoaded:0,images:0,imagesLoaded:0},O=(e=D.stage)=>{D.stage=e,ne?.({...D})},ie=n(e),k=p(e),A=()=>k.gpu,ae=b.textures===!0?{}:b.textures,j=ae&&k.gpu?import(`./texture-stream-Cu_XpyVO.js`).then(({GLTFTextureStream:t})=>ie.run(()=>t.attach(e,ae,T.signal))):void 0;j?.catch(()=>{});let oe=async()=>{let t=await j,n=await ie.run(()=>d(e,_,{...b,decoders:t?{...x,textureStream:t}:x,signal:T.signal}));return t?.attach(n),n};if(b.fetch||b.draco||b.ktx2||x.draco||x.meshopt||x.ktx2){let e=oe().then(e=>(O(`complete`),e));return e.catch(()=>{}),{ready:e,complete:e,abort:E,...j?{textures:j}:{}}}let M,se,N,ce,le=new Promise((e,t)=>{M=e,se=t}),ue=new Promise((e,t)=>{N=e,ce=t});le.catch(()=>{}),ue.catch(()=>{});let P,F,I,L,de,R=!1,z=[],B=[],V=/* @__PURE__ */ new Set,H=[],fe=[],U=/* @__PURE__ */ new Map,W=/* @__PURE__ */ new Map,pe=/* @__PURE__ */ new Set,G=/* @__PURE__ */ new Set,me=[],K=[],q={},he=0,ge=``,_e=-1/0,J=!1,Y=s,X=0,ve=0,Z,ye=()=>{if(!Z||ve)return;let e=Z;Z=void 0,e()},Q=e=>{if(!R){R=!0,L?.terminate(),T.abort(e);for(let e of G)e.destroy();if(G.clear(),P)P.dispose();else for(let e of z)e?.close?.();j?.then(e=>e.dispose(),()=>{}),se(e),ce(e)}};T.signal.addEventListener(`abort`,()=>Q(T.signal.reason),{once:!0});let be=e=>L?L.postMessage({order:e}):de?.setOrder(e),xe=()=>{k.store.tick(!1);let e=k.camera,t=e.planes,n=e.position,r=t.some(e=>e!==0),i=new Float64Array(H.length);return P.primitives.forEach(e=>{let a=W.get(e),[o,s]=fe[a],c=e.node.matrix,l=[0,1,2].map(e=>c[e]*(o[0]+s[0])/2+c[4+e]*(o[1]+s[1])/2+c[8+e]*(o[2]+s[2])/2+c[12+e]),u=m(c,0,Math.hypot(s[0]-o[0],s[1]-o[1],s[2]-o[2])/2,l[0],l[1],l[2]),d=1;if(r)for(let e=0;e<24;e+=4)t[e]*l[0]+t[e+1]*l[1]+t[e+2]*l[2]+t[e+3]<-u&&(d=0);let f=u/Math.max(Math.hypot(l[0]-n[0],l[1]-n[1],l[2]-n[2])-u,1e-9);i[a]=Math.max(i[a],d+f/(1+f))}),H.map((e,t)=>t).filter(e=>H[e].length&&!pe.has(e)).sort((e,t)=>i[t]-i[e])},Se=e=>{let t=[];try{return r.prototype.setup.call(Object.create(P,{primitives:{value:e},resources:{value:t}}),P.engine),t}catch(e){for(let e of t)e.uniform.destroy();throw e}},Ce=e=>{let n=Se(e),r=P.resources,i=new t;e.forEach((e,t)=>{let a=P.primitives.indexOf(e),o=r[a];i.run(()=>o.uniform.destroy()).run(()=>o.wireframe?.index.destroy()),r[a]=n[t]}),i.finish()},we=e=>{let t=U.get(e),n=t.maps,r=0;return()=>{for(;r<n.length&&!n[r];)r++;if(r<n.length){let i=r++;return Se([{...e,material:{...t,maps:n.map((e,t)=>t===i?e:void 0)}}])[0].uniform.destroy(),!1}return e.material=t,Ce([e]),O(`textures`),!0}},$=(e=!1)=>{for(let t of V){let n=U.get(t).maps.flatMap(e=>{let t=e&&I.textures?.[e.index];return t?[t.source,...g.map(e=>t.extensions?.[e]?.source)].filter(Number.isSafeInteger):[]});(e||n.every(e=>B[e]))&&(V.delete(t),K.push(we(t)))}},Te=(e,t,n,r,i)=>{let o=[{data:t,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.STORAGE,at:0,buffer:void 0},{data:n,usage:GPUBufferUsage.INDEX,at:0,buffer:void 0},...r?[{data:r,usage:GPUBufferUsage.VERTEX,at:0,buffer:void 0}]:[]];if(he+=t.byteLength+n.byteLength+(r?.byteLength??0),he>Y*4)throw a(`Decoded glTF geometry exceeds byte budget`,Y*4);return()=>{let a=o.find(e=>e.at<e.data.byteLength);if(a){if(!a.buffer){if(a.data.byteLength>A().limits.maxBufferSize)throw RangeError(`PBR buffer exceeds device limit; load a smaller model, or reduce its textures and meshes`);G.add(a.buffer=A().createBuffer({size:a.data.byteLength,usage:a.usage|GPUBufferUsage.COPY_DST}))}let e=new Uint8Array(a.data.buffer,a.data.byteOffset,a.data.byteLength),t=Math.min(a.at+te,e.length);return A().queue.writeBuffer(a.buffer,a.at,e.subarray(a.at,t)),a.at=t,!1}let s=P.gpuCache,c=/* @__PURE__ */ new Set;for(let{data:e,buffer:t}of o)s.set(e,t),G.delete(t);if(i?.index)H[e]=H[e].map(a=>{let o={node:a.node,nodeIndex:a.nodeIndex,vertices:t,indices:n,definition:a.definition,material:a.material,weights:Float32Array.from(a.weights),targetNames:a.targetNames,...r?{uvs:r}:{},part:i};return W.set(o,e),U.set(o,U.get(a)),o.material!==U.get(o)&&V.add(o),P.insertPart(a,o,Se([o])[0]),o}),$();else{for(let a of H[e])c.add(a.vertices),c.add(a.indices),a.vertices=t,a.indices=n,r&&(a.uvs=r),i&&(a.part=i);Ce(H[e]);for(let e of c){let t=s.get(e);t&&P.dropBuffer(A(),t)}}return(!i||i.index===i.count-1)&&D.primitivesLoaded++,ve--,O(`geometry`),ye(),!0}},Ee=(e,t)=>()=>{e.forEach((e,t)=>{F.buffers[t]=e});for(let[e,n]of t)F.cache.set(e,n);if(x.instancing){q.instancing=x.instancing;let e=/* @__PURE__ */ new Map;for(let t of P.primitives){let n=I.nodes[t.nodeIndex]?.extensions?.EXT_mesh_gpu_instancing;n&&(e.has(t.nodeIndex)||e.set(t.nodeIndex,x.instancing.read(F,n)),t.instances=e.get(t.nodeIndex))}}let n=P.gpuCache,r=new Set(P.primitives.flatMap(e=>e.material.maps.map((e,t)=>e?-1:t)));for(let[e,t]of n)typeof e==`string`&&e.startsWith(`default:`)&&!r.has(+e.slice(8))&&P.dropTexture(A(),e,t);return F[h]?.commit?.(),R=!0,L?.terminate(),O(`complete`),N(P),!0},De=()=>{if(J=!1,!R){try{let e=w(),t=k.camera,n=String(t.position)+t.target;P&&n!==ge&&e-_e>200&&(ge=n,_e=e,be(xe()));let r=0;do K.length&&K[0]()&&K.shift(),r++;while(K.length&&!R&&(C===void 0?w()-e<re:r<C))}catch(e){Q(e);return}Oe()}},Oe=()=>{if(J||R)return;J=!0;let e=typeof requestAnimationFrame==`function`?requestAnimationFrame(n):0,t=setTimeout(n,e?100:16);function n(){clearTimeout(t),e&&cancelAnimationFrame(e),J&&De()}},ke=t=>{I=t;let n=l(I),i=new Map(n.map((e,t)=>[e,t]));n.forEach((e,t)=>{let n=y(I,e);fe[t]=[n.lo,n.hi],e&&typeof e==`object`&&u.set(e,[n])}),x.instancing&&(q.instancing={read:()=>void 0}),x.materials&&(q.materials=x.materials);let o=(I.buffers??[]).map(e=>Number.isSafeInteger(e?.byteLength)&&e.byteLength>0?e.byteLength:0);if(o.reduce((e,t)=>e+t,0)>Y)throw a(`glTF buffers exceed byte budget`,Y);F=new c(I,o.map(e=>new Uint8Array(e)),void 0,q,Y,b.maxNodes),F.partVertices=X,F[h]={},z=Array.from(I.images??[],()=>void 0),B=z.map(()=>!1),D.images=z.length,P=new r(e,F,z),H=n.map(()=>[]);for(let e of P.primitives){let t=i.get(e.definition);H[t].push(e),W.set(e,t)}D.primitives=H.filter(e=>e.length).length;let s=/* @__PURE__ */ new Map;for(let e of P.primitives){let t=e.material;U.set(e,t),t.maps.some(Boolean)&&(s.has(t)||s.set(t,Object.defineProperties(Object.assign(Object.create(Object.getPrototypeOf(t),Object.getOwnPropertyDescriptors(t)),{maps:t.maps.map(()=>void 0)}),{side:Object.getOwnPropertyDescriptor(t,`side`),wireframe:{enumerable:!0,get:()=>t.wireframe,set:e=>{t.wireframe=e}}})),e.material=s.get(t),V.add(e))}k.use(P),P.onDispose(()=>E(new DOMException(`Model disposed while loading`,`AbortError`))),j?.then(e=>e.attach(P),Q),O(`ready`),M(P),Oe()},Ae=e=>{if(R)e.type===`image`&&e.image&&`close`in e.image&&e.image.close();else try{if(e.type===`fallback`)L?.terminate(),L=void 0,oe().then(e=>{R?e.dispose():(P=e,R=!0,O(`complete`),M(e),N(e))},Q);else if(e.type===`doc`)ie.run(()=>ke(e.doc));else if(e.type===`geometry`){if(e.error)throw v(e.error);pe.add(e.key),K.push(Te(e.key,e.vertices,e.indices,e.uvs,e.part)),ve++}else if(e.type===`image`){if(!Number.isInteger(e.index)||e.index<0||e.index>=z.length)throw RangeError(`Progressive glTF worker sent an invalid image index; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let{index:t,source:n}=e;n?me.push(j.then(e=>e.open(n)).then(e=>{R?e.close():(z[t]=e,B[t]=!0,D.imagesLoaded++,$())}).catch(Q)):(z[t]=e.image,B[t]=!0,e.image&&D.imagesLoaded++,$())}else if(e.type===`bytes`)D.bytesLoaded=e.loaded,D.bytesTotal=e.total,P&&O();else if(e.type===`done`){let{buffers:t,accessors:n}=e;Promise.all(me).then(()=>{R||(Z=()=>{$(!0),K.push(Ee(t,n))},ye())})}else throw v(e.error)}catch(e){Q(e)}};try{S?.throwIfAborted(),Y=o(b.maxDownloadBytes),X=i(b.maxPartVertices);let e=new URL(_,globalThis.location?.href).href;f()?(L=new Worker(ee(),{name:`margoengine-progressive`}),L.onmessage=({data:e})=>Ae(e&&typeof e==`object`?e:{type:`error`,error:{name:`TypeError`,message:`Progressive glTF worker sent an invalid message`}}),L.onerror=e=>{e.preventDefault?.(),Q(/* @__PURE__ */ Error(`Progressive glTF worker failed: `+(e.message||`unknown error`)))},L.onmessageerror=()=>Q(/* @__PURE__ */ Error(`Progressive glTF worker message could not be deserialized`)),L.postMessage({url:e,maxDownloadBytes:Y,maxNodes:b.maxNodes,allowedURLs:b.allowedURLs,textures:!!j,maxPartVertices:X})):import(`./stream-C3bKMy1B.js`).then(({GLTFStream:t})=>{R||(de=new t(new URL(e),Ae,T.signal,Y,b.maxNodes,b.allowedURLs,!!j,X)).run()},Q)}catch(e){Q(e)}return{ready:le,complete:ue,abort:E,...j?{textures:j}:{}}}export{b as loadGLTFProgressive};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,8 @@
1
+ import type { GLTFExtension } from './index.js';
2
+ /**
3
+ * Lets the light loader read quantized meshes: POSITION as signed or unsigned 8 or 16 bit integers, normalized or not,
4
+ * and NORMAL as normalized signed 8 or 16 bit integers. Values turn into floats on load, so a mesh takes the same memory
5
+ * on the GPU as a float one. Float attributes read as before. Other forms stay refused.
6
+ * @example const model = await loadGLTF(engine, '/packed.glb', { extensions: [quantized] });
7
+ */
8
+ export declare const quantized: GLTFExtension;
@@ -0,0 +1 @@
1
+ import{r as e,t}from"./accessor-nVsu_f1L.js";var n=5120,r=5121,i=5122,a=5123,o={handles:[`KHR_mesh_quantization`],attribute(o,s,c){let{componentType:l,normalized:u}=t(o.doc.accessors,c,`accessor`);return(s===`POSITION`?l===n||l===r||l===i||l===a:(l===n||l===i)&&u===!0)?e(o,c,3,e=>e.type===`VEC3`):void 0}};export{o as quantized};
@@ -0,0 +1,18 @@
1
+ import type { PBRRenderState } from './pbr.js';
2
+ /** Preserve feature-off command streams while resetting references left by another material on the same pass. */
3
+ export declare function applyStencilReference(pass: GPURenderPassEncoder, state: PBRRenderState | undefined): void;
4
+ /** Winding-normalized static batches cannot preserve different native raster-front and raster-back operations. */
5
+ export declare function asymmetricStencilFaces(state: PBRRenderState | undefined): boolean;
6
+ /**
7
+ * `code` with its MASK alpha test turned into a coverage alpha for `alphaToCoverage`: the alpha is sharpened to about one
8
+ * pixel around the cutoff (the distance to it over its screen rate), so the samples of an edge pixel split there and a
9
+ * mip-blurred map keeps its edge. Coverage zero writes nothing, depth included, so the discard goes. A surface with its
10
+ * own test (a hashed alpha) keeps that test, at full coverage.
11
+ */
12
+ export declare function alphaCoverageShader(code: string): string;
13
+ /** Validate optional native state before a cached pipeline or a dynamic reference can reach WebGPU. */
14
+ export declare function validateRenderState(state: PBRRenderState, format: GPUTextureFormat): void;
15
+ /** The reference is per draw; all other native overrides select the pipeline. */
16
+ export declare function renderStateKey(state: PBRRenderState | undefined): string;
17
+ /** Polygon bias has no effect on points and lines, and WebGPU requires those pipeline values to be zero. */
18
+ export declare function pipelineDepthState(state: PBRRenderState | undefined, triangles: boolean, forwardZ: boolean): Partial<GPUDepthStencilState>;