@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,94 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import type { Engine, EnginePlugin } from '@margoengine/core/extension';
4
+ // @ts-ignore optional peer: its types apply when it is installed
5
+ import type { SoftBody } from '@margoengine/physics/soft';
6
+ import { type GLTFDocument, type GLTFImage } from './asset.js';
7
+ import { PBRModel } from './model.js';
8
+ /** A glTF 2.0 material (`materials[i]` of a glTF file). */
9
+ export type SoftMeshMaterial = NonNullable<GLTFDocument['materials']>[number];
10
+ /** Options for {@link SoftSurface}. */
11
+ export interface SoftSurfaceOptions {
12
+ /**
13
+ * Texture coordinates, two a particle (two a skin vertex for a skinned body). Default: the grid of a body built by
14
+ * `cloth`, `clothAnisotropic` or `clothTube` (particle (i, j) at (i / (nu - 1), j / (nv - 1)), a tube's seam doubled so
15
+ * u runs 0 to 1 around it), else the body's shape where the surface is made, laid flat on the plane of its two largest
16
+ * extents and scaled to 0..1.
17
+ */
18
+ uvs?: ArrayLike<number>;
19
+ }
20
+ /**
21
+ * The surface of a soft body as packed PBR vertices (`STRIDE` = 20 floats: position and 1, normal and 0, tangent with
22
+ * its handedness, two UV sets, colour) and triangles. `update()` copies the particles (or the skin) and recomputes the
23
+ * normals, each the area-weighted sum of its triangles' normals, and the tangents from the UVs (Lengyel 2001).
24
+ */
25
+ export declare class SoftSurface {
26
+ readonly body: SoftBody;
27
+ /** 20 floats a vertex, in the layout `PBRModel` draws. */
28
+ readonly vertices: Float32Array;
29
+ /** Three vertex indices a triangle, wound as the body's triangles are. */
30
+ readonly indices: Uint32Array;
31
+ /** Two floats a vertex. */
32
+ readonly uvs: Float32Array;
33
+ /** The particle each vertex copies (a tube's seam vertices copy the first ring); empty for a skinned body. */
34
+ private readonly source;
35
+ /** Pairs of vertices that are one particle (a tube's first ring and its seam copy). */
36
+ private readonly twins;
37
+ private readonly skinned;
38
+ private readonly scratch;
39
+ private readonly normal;
40
+ private readonly tangent;
41
+ private readonly bitangent;
42
+ constructor(body: SoftBody, _arg0?: SoftSurfaceOptions);
43
+ /** The number of vertices (a tube has one more ring of them than of particles around). */
44
+ get vertexCount(): number;
45
+ /** Copies the body's particles (or its skin) into the vertices and recomputes the normals and tangents. */
46
+ update(): this;
47
+ }
48
+ /** Options for {@link drawSoftBody}. */
49
+ export interface SoftBodyMeshOptions extends SoftSurfaceOptions {
50
+ /**
51
+ * The glTF material it is drawn with. Default `{doubleSided: true, pbrMetallicRoughness: {metallicFactor: 0,
52
+ * roughnessFactor: 0.8}}`: a matte sheet seen from both sides. `doubleSided` stays true unless the material says false.
53
+ * Its textures name `images` by index: texture `i` is image `i`.
54
+ */
55
+ material?: SoftMeshMaterial;
56
+ /** The images its textures read (an `ImageBitmap`, or `{width, height, data}` RGBA8 pixels). Default none. */
57
+ images?: readonly GLTFImage[];
58
+ }
59
+ /**
60
+ * A soft body drawn as a PBR mesh: each frame, before the engine draws, the vertices follow the body (when it is awake)
61
+ * and upload in place. Make it after the body's `Physics` is on the engine, so the frame's step runs first. A body that is
62
+ * removed (or splits on a tear) stops it at its last pose: draw the pieces with `drawSoftBody` from `soft.onTear`.
63
+ */
64
+ export declare class SoftBodyMesh implements EnginePlugin {
65
+ readonly name: string;
66
+ /**
67
+ * Copies the particles after physics has stepped them this frame (physics is a `late` plugin, KB-PHYS-FRAMEORDER1):
68
+ * a late plugin added after the physics world runs after it, so the mesh drawn is the step just taken, not the one
69
+ * before (KB-SOFTMESH-LAG1).
70
+ */
71
+ readonly late = true;
72
+ /** The model it draws with: `model.setVisible`, picking and the PBR model API work on it. */
73
+ readonly model: PBRModel;
74
+ /** The CPU surface it uploads. */
75
+ readonly surface: SoftSurface;
76
+ private engine?;
77
+ private disposed;
78
+ /** The vertices the model holds, and the array the next frame writes. */
79
+ private held;
80
+ private spare;
81
+ constructor(engine: EngineKernel, body: SoftBody, _arg1?: SoftBodyMeshOptions);
82
+ setup(engine: Engine): void;
83
+ onPreUpdate(): void;
84
+ /** Moves the mesh to where the body is now, at once (the frame does this by itself). */
85
+ sync(): this;
86
+ /** Removes the mesh from the engine and frees its buffers. The body is not touched. */
87
+ dispose(): void;
88
+ [Symbol.dispose]: () => void;
89
+ }
90
+ /**
91
+ * Draws a soft body with one call: `const mesh = drawSoftBody(engine, cloth, {material})`. The mesh follows the body every
92
+ * frame with recomputed normals and tangents and grid texture coordinates; `mesh.dispose()` (or `using`) removes it.
93
+ */
94
+ export declare function drawSoftBody(engine: EngineKernel, body: SoftBody, options?: SoftBodyMeshOptions): SoftBodyMesh;
@@ -0,0 +1,4 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import{n as e}from"./model-iRvuj19h.js";import{t}from"./asset-1b8ejkZX.js";import{MargoError as n}from"@margoengine/math/errors";var r=20,i=0,a=class{constructor(e,{uvs:t}={}){if(this.body=e,!e.valid)throw new n(`state`,`Soft body was removed; draw a body that is still in its world.`);this.skinned=e.meshIndices().length>0;let i=this.skinned?e.meshIndices():e.triangles();if(i.length===0)throw TypeError(`This soft body has no triangles to draw (a rope or a bare particle set); draw a rope with @margoengine/lines, or build the body with cloth, trimesh, sphere or setSkin.`);let a=this.skinned?e.meshVertices().length/3:e.numParticles(),s=this.skinned||t?null:e.grid,c,l,u;if(s?.wrap){let{nu:e,nv:t}=s;c=new Uint32Array((e+1)*t),u=new Float32Array(c.length*2);for(let n=0;n<=e;n++)for(let r=0;r<t;r++)c[n*t+r]=n%e*t+r,u[(n*t+r)*2]=n/e,u[(n*t+r)*2+1]=r/(t-1);l=new Uint32Array(i.length);for(let n=0;n<i.length;n+=3){let r=[0,1,2].map(e=>Math.floor(i[n+e]/t)),a=r.includes(e-1)&&r.includes(0);for(let o=0;o<3;o++)l[n+o]=a&&r[o]===0?e*t+i[n+o]%t:i[n+o]}}else if(c=this.skinned?/* @__PURE__ */ new Uint32Array:Uint32Array.from({length:a},(e,t)=>t),l=i,t){if(t.length!==a*2)throw RangeError(`Soft surface uvs need two numbers a vertex: ${a*2}, not ${t.length}.`);if(u=Float32Array.from(t),!u.every(Number.isFinite))throw RangeError(`Soft surface uvs must be finite numbers.`)}else if(s){u=new Float32Array(a*2);for(let e=0;e<s.nu;e++)for(let t=0;t<s.nv;t++)u[(e*s.nv+t)*2]=e/(s.nu-1),u[(e*s.nv+t)*2+1]=t/(s.nv-1)}else u=o(this.skinned?e.meshVertices():e.particlePositions());this.source=c;let d=[];if(s?.wrap)for(let e=0;e<s.nv;e++)d.push(e,s.nu*s.nv+e);this.twins=Uint32Array.from(d),this.indices=l,this.uvs=u;let f=this.vertices=new Float32Array(u.length/2*r);for(let e=0;e<u.length/2;e++){let t=e*r;f[t+3]=1,f[t+12]=f[t+14]=u[e*2],f[t+13]=f[t+15]=u[e*2+1],f[t+16]=f[t+17]=f[t+18]=f[t+19]=1}this.scratch=new Float32Array(a*3),this.normal=new Float32Array(u.length/2*3),this.tangent=new Float32Array(this.normal.length),this.bitangent=new Float32Array(this.normal.length),this.update()}get vertexCount(){return this.uvs.length/2}update(){if(!this.body.valid)throw new n(`state`,`Soft body was removed; draw the bodies that replaced it with drawSoftBody.`);let e=this.skinned?this.body.meshVertices():this.body.particlePositions(this.scratch),t=this.vertices,i=this.normal,a=this.tangent,o=this.bitangent,s=this.uvs,c=this.indices,l=this.vertexCount;for(let n=0;n<l;n++){let i=(this.skinned?n:this.source[n])*3,a=n*r;t[a]=e[i],t[a+1]=e[i+1],t[a+2]=e[i+2]}i.fill(0),a.fill(0),o.fill(0);for(let e=0;e<c.length;e+=3){let n=c[e],l=c[e+1],u=c[e+2],d=n*r,f=t[l*r]-t[d],p=t[l*r+1]-t[d+1],m=t[l*r+2]-t[d+2],h=t[u*r]-t[d],g=t[u*r+1]-t[d+1],_=t[u*r+2]-t[d+2],v=p*_-m*g,y=m*h-f*_,b=f*g-p*h,x=s[l*2]-s[n*2],S=s[l*2+1]-s[n*2+1],C=s[u*2]-s[n*2],w=s[u*2+1]-s[n*2+1],T=x*w-C*S,E=T===0?0:1/T,D=(f*w-h*S)*E,O=(p*w-g*S)*E,k=(m*w-_*S)*E,A=(h*x-f*C)*E,j=(g*x-p*C)*E,M=(_*x-m*C)*E;for(let e of[n,l,u])i[e*3]=i[e*3]+v,i[e*3+1]=i[e*3+1]+y,i[e*3+2]=i[e*3+2]+b,a[e*3]=a[e*3]+D,a[e*3+1]=a[e*3+1]+O,a[e*3+2]=a[e*3+2]+k,o[e*3]=o[e*3]+A,o[e*3+1]=o[e*3+1]+j,o[e*3+2]=o[e*3+2]+M}for(let e=0;e<this.twins.length;e+=2){let t=this.twins[e]*3,n=this.twins[e+1]*3;for(let e of[i,a,o])for(let r=0;r<3;r++)e[t+r]=e[n+r]=e[t+r]+e[n+r]}for(let e=0;e<l;e++){let n=e*r,s=i[e*3],c=i[e*3+1],l=i[e*3+2],u=Math.hypot(s,c,l);u>0?(s/=u,c/=u,l/=u):(s=t[n+4],c=t[n+5],l=t[n+6]||+(s===0&&c===0)),t[n+4]=s,t[n+5]=c,t[n+6]=l;let d=a[e*3],f=a[e*3+1],p=a[e*3+2],m=d*s+f*c+p*l;d-=s*m,f-=c*m,p-=l*m;let h=Math.hypot(d,f,p);h>1e-12||([d,f,p]=Math.abs(s)<.9?[0,-l,c]:[l,0,-s],h=Math.hypot(d,f,p)),t[n+8]=d/h,t[n+9]=f/h,t[n+10]=p/h;let g=c*p-l*f,_=l*d-s*p,v=s*f-c*d;t[n+11]=g*o[e*3]+_*o[e*3+1]+v*o[e*3+2]<0?-1:1}return this}};function o(e){let t=[1/0,1/0,1/0],n=[-1/0,-1/0,-1/0];for(let r=0;r<e.length;r++)t[r%3]=Math.min(t[r%3],e[r]),n[r%3]=Math.max(n[r%3],e[r]);let r=[0,1,2].map(e=>n[e]-t[e]),[i,a]=[0,1,2].sort((e,t)=>r[t]-r[e]||e-t),o=new Float32Array(e.length/3*2);for(let n=0;n<e.length/3;n++)o[n*2]=r[i]>0?(e[n*3+i]-t[i])/r[i]:0,o[n*2+1]=r[a]>0?(e[n*3+a]-t[a])/r[a]:0;return o}var s=class{coreRequirement=__margoCoreRequirement("0.1.0",import.meta.url);constructor(n,r,{material:o,images:s=[],...c}={}){this.name=`soft-mesh:`+i++,this.late=!0,this.disposed=!1,this.surface=new a(r,c),this.held=this.surface.vertices.slice(),this.spare=this.surface.vertices.slice();let l=s.map((e,t)=>({source:t}));this.model=new e(n,new t({asset:{version:`2.0`},materials:[{doubleSided:!0,pbrMetallicRoughness:{metallicFactor:0,roughnessFactor:.8},...o}],...l.length?{textures:l,images:s.map(()=>({}))}:{},meshes:[{primitives:[{attributes:{POSITION:0},material:0}]}],nodes:[{mesh:0}]},[]),s,[[{vertices:this.held,indices:this.surface.indices}]]),n.use(this.model);try{n.use(this)}catch(e){throw this.model.dispose(),e}}setup(e){this.engine=e}onPreUpdate(){let e=this.surface.body;this.disposed||!e.valid||e.sleeping||this.sync()}sync(){if(this.disposed)throw new n(`disposed`,`SoftBodyMesh is disposed; draw the body again with drawSoftBody.`);this.surface.update();let e=this.spare;return e.set(this.surface.vertices),this.model.writeGeometry([{vertices:e,indices:this.surface.indices}],{start:0,count:this.surface.vertexCount}),this.spare=this.held,this.held=e,this}dispose(){this.disposed||(this.disposed=!0,this.engine?.sceneOf(this)?.removePlugin(this.name),this.model.dispose())}[Symbol.dispose??Symbol()](){this.dispose()}};function c(e,t,n){return new s(e,t,n)}export{s as SoftBodyMesh,a as SoftSurface,c as drawSoftBody};
@@ -0,0 +1,21 @@
1
+ import type { GLTFMaterial } from './shared/gltf.js';
2
+ import type { GLTFExtendedMaterials } from './asset.js';
3
+ /** Metal/rough factors derived from one linear-light spec/gloss sample. */
4
+ export interface MetalRoughSample {
5
+ /** Linear RGBA; opacity is copied from diffuse alpha. */
6
+ readonly baseColor: readonly number[];
7
+ readonly metallic: number;
8
+ readonly roughness: number;
9
+ }
10
+ /**
11
+ * Converts linear diffuse RGBA, specular RGB and glossiness to metal/rough. Defaults are the extension's white/white/1.
12
+ * Conversion is an approximation for nonphysical spec/gloss colours; saturated endpoints remain finite.
13
+ */
14
+ export declare function specGlossToMetalRough(diffuse?: readonly number[], specular?: readonly number[], glossiness?: number): MetalRoughSample;
15
+ /** Converts the authored factors/map routing without changing the input document or baking mismatched UV sets. */
16
+ export declare function convertSpecGlossMaterial(material: GLTFMaterial): GLTFMaterial;
17
+ /**
18
+ * Optional reader for loadGLTF/parseGLTFAsync (selected automatically) and synchronous parseGLTF's materials hook.
19
+ * Retains per-map UV sets, transforms, filters, alpha, normal/occlusion/emission maps and material variants.
20
+ */
21
+ export declare const specGlossMaterials: GLTFExtendedMaterials;
@@ -0,0 +1,18 @@
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=`
2
+ fn margoSpecGloss(d:vec3f,s:vec3f)->vec4f {
3
+ let weights=vec3f(0.299,0.587,0.114);
4
+ let db=sqrt(dot(d*d,weights)); let sb=sqrt(dot(s*s,weights));
5
+ let share=1-max(s.r,max(s.g,s.b)); let qb=db*share/0.96+sb-0.08;
6
+ let metal=select(clamp((-qb+sqrt(max(0.0,qb*qb-0.16*(0.04-sb))))/0.08,0.0,1.0),0.0,sb<0.04);
7
+ let bd=d*share/(0.96*max(1-metal,0.000001));
8
+ let bs=(s-vec3f(0.04*(1-metal)))/max(metal,0.000001);
9
+ return vec4f(clamp(mix(bd,bs,metal*metal),vec3f(0),vec3f(1)),metal);
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,`
12
+ if(f.ext.x<0.5){
13
+ let converted=margoSpecGloss(s.base.rgb,s.f0);
14
+ s.base=vec4f(converted.rgb,s.base.a); s.metal=converted.a;
15
+ s.roughness=clamp(1-f.factors.x*${a},0.045,1.0);
16
+ s.f0=vec3f(0.04); s.sw=1;
17
+ }
18
+ ${o}`)}};export{u as convertSpecGlossMaterial,f as specGlossMaterials,l as specGlossToMetalRough};
@@ -0,0 +1,7 @@
1
+ import type { GLTFDocument } from './shared/gltf.js';
2
+ /** True for a mesh primitive whose data is Gaussian splats (KHR_gaussian_splatting). */
3
+ export declare const isSplatPrimitive: (primitive: {
4
+ extensions?: unknown;
5
+ } | undefined) => boolean;
6
+ /** True when any mesh of the file holds Gaussian splats. */
7
+ export declare const hasSplats: (doc: GLTFDocument) => boolean;
@@ -0,0 +1,18 @@
1
+ // @ts-ignore optional peer: its types apply when it is installed
2
+ import type { SplatData } from '@margoengine/splats/data';
3
+ import type { GLTFPrimitive } from './shared/gltf.js';
4
+ import type { GLTFAsset, GLTFSplatReader } from './asset.js';
5
+ /**
6
+ * The splats of mesh primitive `primitive`, in the primitive's local space, as `SplatData` for @margoengine/splats: its
7
+ * glTF attributes or its KHR_gaussian_splatting_compression_spz_2 payload. Needs no GPU.
8
+ * @throws TypeError when the primitive breaks the extension's rules, RangeError on values @margoengine/splats refuses,
9
+ * MargoError `'unsupported'` for a kernel or colour space the extension does not define.
10
+ */
11
+ export declare function readGaussianSplats(asset: GLTFAsset, primitive: GLTFPrimitive, _arg0?: {
12
+ signal?: AbortSignal;
13
+ }): Promise<SplatData>;
14
+ /**
15
+ * The reader `loadGLTF` and `parseGLTFAsync` import when a file holds splats: each primitive read, placed by its node's
16
+ * world matrix, the clouds of the file merged so that they sort together, in clouds of at most 3,000,000 splats.
17
+ */
18
+ export declare const gaussianSplats: GLTFSplatReader;
package/dist/splats.js ADDED
@@ -0,0 +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};
@@ -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 v=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import{t as e}from"./node-matrix-R9BipGnp.js";import{t}from"./errors-THVaUwlL.js";import{a as n,c as r,d as i,l as a,o,s,t as c,u as l}from"./version-BmU1nesQ.js";import{n as u,t as d}from"./limits-_LZ441oV.js";import{t as f}from"./scene-scope-CZDEkd24.js";import{n as p,r as m,t as h}from"./accessor-nVsu_f1L.js";import{Geometry as g,PbrMaterial as _,engineRuntime as __margoRuntime}from"@margoengine/core/extension";import{MargoError as y}from"@margoengine/math/errors";var b=`version https://git-lfs`;function x(e,n){if(!(e.length<23)){for(let t=0;t<23;t++)if((typeof e==`string`?e.charCodeAt(t):e[t])!==b.charCodeAt(t))return;throw t(`failed`,`${n} is a Git LFS pointer file, not the asset; run git lfs pull and serve the real file`,`git-lfs`)}}var S=67108864,C=e=>new y(`unsupported`,`${e} over the light loader's 64 MiB; use @margoengine/gltf/pbr (512 MiB by default) or loadAuto`),w=e=>!!e&&typeof e==`object`&&!Array.isArray(e);function T(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{throw TypeError(`Invalid glTF JSON: not UTF-8; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`)}}function E(e){try{return l(e)}catch(e){throw TypeError(`Invalid glTF JSON: ${e.message}; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`)}}function D(e){return e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function O(e){if(typeof e==`string`){if(x(e,`The glTF input`),e.length>S||new TextEncoder().encode(e).length>S)throw RangeError(`glTF JSON exceeds 64 MiB; load a smaller file or split it`);return{doc:E(e)}}if(!(e instanceof ArrayBuffer)&&!ArrayBuffer.isView(e))return{doc:e};let t=D(e);if(x(t,`The glTF input`),t.length>S)throw RangeError(`GLB exceeds 64 MiB; load a smaller file or split it`);let r=o(t),i=E(T(r[0].data)),a=r[1]?.type===5130562?r[1].data:void 0,s=i.buffers?.[0];return a&&s&&typeof s==`object`&&s.uri===void 0&&n(a.length,s.byteLength),{doc:i,binary:a}}function k(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 A(e,t,n){let r=u(`maxNodes`,t);if(!e||!c(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(w))throw TypeError(`Invalid glTF ${t} entry; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`)}if(e.extensionsRequired?.some(e=>!n.some(t=>t.handles.includes(e)))||e.skins?.length||e.animations?.length)throw new y(`unsupported`,`Minimal glTF supports static uncompressed models; required extensions, skins and animations are unsupported; use @margoengine/gltf/pbr`);d(`Too many glTF nodes`,e.nodes?.length??0,r,`maxNodes`)}function j(t,n){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 TypeError(`Invalid glTF matrix; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let r=n.matrix;if(r[3]!==0||r[7]!==0||r[11]!==0||r[15]!==1)throw TypeError(`glTF matrix must be affine`);let i=e(r);if(!i.ok)throw i.reason===`singular`?/* @__PURE__ */ RangeError(`Singular glTF matrix`):/* @__PURE__ */ Error(`Sheared glTF matrices are unsupported`);t.setPosition(i.position).setScale(i.scale).setQuaternion(i.rotation)}else t.setPosition(n.translation??[0,0,0]).setScale(n.scale??[1,1,1]).setQuaternion(n.rotation??[0,0,0,1])}var M=(e,t)=>e.some(e=>e.handles.some(e=>t?.extensions?.[e]!==void 0)),N=(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=>M(n,e))};function P(e,t,{maxNodes:n,extensions:r=[]}){let{doc:i,binary:a}=O(e);A(i,n,r);let o=0;return{doc:i,buffers:(i.buffers??[]).map((e,n)=>{let s=p(e.byteLength,`buffer length`,1);if(N(i,n,r,(t[n]?.byteLength??0)>0||n===0&&!!a&&!e.uri))return/* @__PURE__ */ new Uint8Array;let c=t[n]?D(t[n]):e.uri?k(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>S)throw C(`glTF buffers are`);return c.subarray(0,s)}),maxNodes:n}}function F(e,t,{maxNodes:n,extensions:r=[]}){let i=v(e);for(let e of r)e.read?.(t);let{doc:a}=t;r.length&&A(a,n,r);let o=0,s=(e,n)=>{for(let i of r){let r=i.attribute?.(t,e,p(n,`accessor`));if(r)return r}return m(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 new y(`unsupported`,`Minimal PBR supports opaque constant colors; add @margoengine/gltf/textured for a base colour map or MASK; other maps, emission and transparency require @margoengine/gltf/pbr`);return new _({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(w))throw TypeError(`Missing glTF primitives; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);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 new y(`unsupported`,`Minimal glTF requires rigid triangles without vertex colors; use @margoengine/gltf/pbr`);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):m(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 new y(`unsupported`,`glTF exceeds one million vertices, the limit of the light loader; use @margoengine/gltf/pbr, or split it`);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 _({color:[1,1,1],roughness:1,metalness:1,doubleSided:!1}):a.materials?.[p(e.material,`material reference`)]&&(c[e.material]??=l(a.materials[e.material]));if(!d)throw TypeError(`Missing material; point the primitive at an existing material index`);return[{geometry:new g(n,r,i),material:d,source:e,expanded:u}]})}),d=a.nodes??[],f=new Int32Array(d.length).fill(-1);d.forEach((e,t)=>{if(!e||e.skin!==void 0||e.camera!==void 0||e.extensions)throw new y(`unsupported`,`Unsupported glTF node; add @margoengine/gltf/instancing for EXT_mesh_gpu_instancing or @margoengine/gltf/scene-data for cameras and lights, or use @margoengine/gltf/pbr`);if(e.children!==void 0&&!Array.isArray(e.children))throw TypeError(`Invalid glTF children; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);for(let n of e.children??[]){let e=p(n,`child reference`);if(e>=d.length||f[e]!==-1||e===t)throw TypeError(`Invalid glTF hierarchy; give each node one parent and valid child indices`);f[e]=t}});for(let e=0;e<d.length;e++){let t=0;for(let n=e;n!==-1;n=f[n])if(++t>62)throw RangeError(`glTF hierarchy cycle or depth limit; remove the cycle or flatten the nodes to 62 levels or fewer`)}let b=a.scenes?h(a.scenes,a.scene??0,`scene`).nodes??[]:d.map((e,t)=>t).filter(e=>f[e]===-1);if(!Array.isArray(b)||new Set(b).size!==b.length)throw TypeError(`Invalid glTF scene roots; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let x=[],S=[],C=[],T=[],E;try{let e=i.createMesh();x.push(e);let n=b.map(t=>({id:p(t,`root`),parent:e}));for(;n.length;){let{id:t,parent:r}=n.pop(),a=h(d,t,`node`);if(r===e&&f[t]!==-1)throw TypeError(`Scene root has a parent; list only top-level nodes in the scene`);let o=i.createMesh(r);if(x.push(o),C.push(o),T[t]=o,o.name=typeof a.name==`string`?a.name:``,j(o,a),a.mesh!==void 0){let e=u[p(a.mesh,`mesh reference`)];if(!e)throw TypeError(`Missing glTF mesh; point the node at an existing mesh index`);for(let t of e){let e=i.createMesh(o);x.push(e),e.setGeometry(t.geometry).setMaterial(t.material),S.push(e)}}for(let e of a.children??[])n.push({id:e,parent:o})}if(!S.length&&!r.some(e=>e.allowEmptyScene))throw new y(`failed`,`glTF contains no renderable meshes; add a mesh with triangle primitives`);E={root:e,meshes:S,nodes:C,dispose:()=>{for(let e=x.length-1;e>=0;e--)x[e].dispose()}};for(let e of r)e.finish?.(E,t,{engine:i,primitives:u.flat(),nodes:T});return E}catch(e){if(E)E.dispose();else for(let e=x.length-1;e>=0;e--)x[e].dispose();throw e}}async function I(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(()=>F(e,t,n))}catch(e){for(let e of o)e.abandon?.(t);throw e}}function L(e,t,n=[],r={}){if(r.extensions?.some(e=>e.load))throw new y(`unsupported`,`This glTF extension loads asynchronously; use parseGLTFAsync or loadGLTF`);return F(e,P(t,n,r),r)}async function R(e,t,n=[],{signal:r,...i}={}){return r?.throwIfAborted(),I(e,P(t,n,i),i,r,f(e))}async function z(e,t,{signal:n,maxNodes:o,allowedURLs:c,extensions:l=[],fetch:u=globalThis.fetch}={}){n?.throwIfAborted();let d=f(e),p=new URL(t,globalThis.location?.href),m=0;async function h(e,t=!1){if(![`http:`,`https:`].includes(e.protocol))throw TypeError(`glTF URL must use HTTP(S)`);let r=await u(e,{signal:n});t&&r.url?p=new URL(r.url):t||a(r,p,c,`glTF buffer`);let o=await i(r,{maxBytes:S-m,signal:n,label:`glTF download`}).catch(e=>{throw e instanceof RangeError?C(`glTF download is`):e});if(x(o,e.href),(m+=o.byteLength)>S)throw C(`glTF download is`);return o}let g=await h(p,!0),{doc:_,binary:v}=O(s(g)?g:T(g));A(_,o,l);let y=[];for(let[e,t]of(_.buffers??[]).entries())if(N(_,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=k(t.uri);if(m+=e.length,m>S)throw C(`glTF download is`);y.push(e)}else y.push(await h(r(t.uri,p,c,`glTF buffer`)));n?.throwIfAborted();let b={maxNodes:o,extensions:l},w=P(_,y,b);return w.fetch=e=>h(r(e,p,c,`glTF image`)),I(e,w,b,n,d)}export{x as i,L as n,R as r,z as t};
@@ -0,0 +1 @@
1
+ import{n as e}from"./errors-THVaUwlL.js";import{a as t,c as n,d as r,l as i}from"./version-BmU1nesQ.js";import{t as a}from"./accessor-DuqjpuxI.js";import"./image-limit-DvFSfR5T.js";import{O as o,S as s,_ as c,a as l,i as u,l as d,m as f,n as p,p as m,r as h,s as g,t as _,v,y}from"./asset-1b8ejkZX.js";import{a as b,o as x,r as S,t as C}from"./pack-BVDYuqZe.js";var w=1<<20,T=262144,E=4;function D(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 O(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 k=(e,t,n)=>!O(e,t,n).length,A=e=>{let{name:t=`Error`,code:n}=e??{};return{name:t,message:e instanceof Error?e.message:String(e),...typeof n==`string`?{code:n}:{}}},j=class{constructor(e,t,n,r=p,i,a,s=!1,c=o){this.url=e,this.post=t,this.signal=n,this.limit=r,this.maxNodes=i,this.allowedURLs=a,this.textures=s,this.partVertices=c,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.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),(this.textures?u(e):h(e))||e.bufferViews?.some(e=>e?.extensions?.EXT_meshopt_compression||e?.extensions?.KHR_meshopt_compression)){this.post({type:`fallback`});return}for(this.post({type:`doc`,doc:e}),this.buffers(e);!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=O(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<=T;)i=n[t++][1];this.request(e,r,i)}}for(;this.inflight||this.sources.some(e=>!k(e.got,0,e.data?.length??0));)await this.next();this.bytes(!0),this.post({type:`done`,buffers:this.asset.buffers,accessors:C(this.asset)})}catch(e){this.signal.aborted||this.post({type:`error`,error:A(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(t,n,r=!1){if(![`http:`,`https:`].includes(t.url.protocol))throw TypeError(`glTF URL must use HTTP(S)`);return fetch(t.url,{signal:this.signal,headers:n}).then(t=>{if(r||i(t,this.base,this.allowedURLs,`glTF`),!t.ok)throw e(`failed`,`glTF download request failed: HTTP ${t.status}; check the URL and that the server allows the request`);return t})}allocate(e,t){if(!Number.isSafeInteger(t)||t>this.limit-this.sources.reduce((e,t)=>e+(t.data?.length??0),0))throw c(`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),D(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),n=/^bytes 0-\d+\/(\d+|\*)$/.exec(t.headers.get(`content-range`)??``),i=n&&n[1]!==`*`?Number(n[1]):void 0;t.url&&(e.url=this.base=new URL(t.url)),e.ranged=t.status===206&&!!n;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 l=new Uint8Array(s);o.reduce((e,t)=>(l.set(t,e),e+t.length),0);let u=new DataView(l.buffer);if(s<12||u.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(()=>{}),c(`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 r(await this.fetch(e,{Range:`bytes=${t}-`}),{maxBytes:this.limit-t,signal:this.signal,label:`glTF JSON`}).catch(e=>{throw e instanceof RangeError?c(`glTF JSON exceeds byte budget`,this.limit):e})).subarray(s-t));let n=new Uint8Array(o.reduce((e,t)=>e+t.length,0));if(o.reduce((e,t)=>(n.set(t,e),e+t.length),0),this.loaded+=n.length,n.length>this.limit)throw c(`glTF JSON exceeds byte budget`,this.limit);return this.sources.length=0,y(n,e.url.href),v(n)}let d=u.getUint32(8,!0);if(u.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(l.subarray(0,d)),D(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),D(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(D(e.asked,0,e.ranged?Math.min(65536,d):d),e.ranged&&(await p,!this.failure&&!k(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(;!k(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 O(e.got,0,h()))this.request(0,t,n);for(;!k(e.got,0,h());)await this.next();return v(e.data.subarray(20,20+m()))}buffers(e){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&&k(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=(e.buffers??[]).map((e,c)=>{if(e?.uri===void 0)return c===0&&r&&o?(t(s,e.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 e.uri==`string`&&e.uri.startsWith(`data:`)){this.map.push({source:-1,offset:0});let t=m(e.uri,this.limit);return this.loaded+=t.length,t}let l=n(e.uri,this.base,this.allowedURLs,`glTF`).href,u=i.get(l);if(u===void 0){u=this.sources.length,i.set(l,u);let t={url:new URL(l),got:[],asked:[]};this.sources.push(t),this.allocate(t,Number.isSafeInteger(e.byteLength)&&e.byteLength>0?e.byteLength:0)}return this.map.push({source:u,offset:0}),this.sources[u].data});this.asset=new _(e,c,void 0,{},this.limit,this.maxNodes),this.asset.partVertices=this.partVertices,this.needs=b(e).map(t=>{let n=[],r=t?.attributes??{};try{let i=x(e,t)?[r.TEXCOORD_2,r.TEXCOORD_3]:[];for(let a of[r.POSITION,r.NORMAL,r.TANGENT,r.TEXCOORD_0,r.TEXCOORD_1,...i,r.COLOR_0,t.indices])a!==void 0&&this.ranges(e,a,n)}catch{for(let[e,t]of this.map.entries())t.source>=0&&n.push([t.source,t.offset,t.offset+this.asset.buffers[e].length])}return n})}ranges(e,t,n){let r=f(e.accessors,t,`accessor`),i=a[r.componentType],o=g[r.type],s=r.count,c=(t,r,i)=>{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??i*o)+i*o),r.sparse){let e=r.sparse.count;c(r.sparse.indices.bufferView,r.sparse.indices.byteOffset??0,e*a[r.sparse.indices.componentType]),c(r.sparse.values.bufferView,r.sparse.values.byteOffset??0,e*i*o)}}request(e,t,n){let r=this.sources[e],i={left:n-t};D(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),!k(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,D(r.asked,0,r.data.length),await this.read(r,e,0,i),!k(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])=>k(this.sources[e].got,t,n))}async geometry(e){let t=b(e);for(;;){if(this.failure)throw this.failure;let e=this.order.filter(e=>!this.posted.has(e));for(let n of e)if(this.ready(n)){this.posted.add(n);try{S(this.asset,t[n],({vertices:e,indices:t,uvs:r,part:i})=>this.post({type:`geometry`,key:n,vertices:e,indices:t,uvs:r,...i?{part:i}:{}}))}catch(e){this.post({type:`geometry`,key:n,error:A(e)})}}if(this.order.every(e=>this.posted.has(e)))return;let n=w,r=[];for(let t of e){if(this.inflight>=E||n<=0||this.pending>=w)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 O(t.asked,i-i%T,Math.min(t.data.length,Math.ceil(a/T)*T)))if(r.push([e,o,s]),D(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()}}async textureSource(e,t){if(t.bufferView===void 0){if(typeof t.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 t.uri.startsWith(`data:`)?{bytes:m(t.uri,this.limit)}:{url:n(t.uri,this.base,this.allowedURLs,`glTF`).href}}this.asset.view(t.bufferView);let r=f(e.bufferViews,t.bufferView,`bufferView`),i=this.map[r.buffer];if(i?.source>=0){let e=this.sources[i.source],t=i.offset+(r.byteOffset??0),n=t+r.byteLength;for(;e.ranged===void 0;)e.probing||this.request(i.source,t,Math.min(n,t+1)),await this.next();if(e.ranged)return D(e.asked,t,n),D(e.got,t,n),{url:e.url.href,offset:t,length:r.byteLength};for(;!k(e.got,t,Math.min(n,e.data.length));)await this.next()}return{bytes:this.asset.view(t.bufferView).slice()}}async images(e){let t=b(e),i=[],a=e.images??[],o=t=>e.materials?.[t?.material],l=(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))l(r,t,n+1)}return t};for(let n of this.order)for(let r of l(o(t[n]))){let t=e.textures?.[r];for(let e of[t?.source,...Object.values(t?.extensions??{}).map(e=>e?.source)])Number.isInteger(e)&&!i.includes(e)&&i.push(e)}let u=[...i,...a.map((e,t)=>t).filter(e=>!i.includes(e))].filter(e=>e<a.length),p=0,h=this.textures?s(e):/* @__PURE__ */ new Set,g=async t=>{let i=a[t],o=i.mimeType===`image/ktx2`||/\.ktx2$/i.test(i.uri??``);if(o&&this.textures){this.post({type:`image`,index:t,source:await this.textureSource(e,i)});return}if(o||h.has(t)){this.post({type:`image`,index:t});return}let s;if(i.bufferView!==void 0){this.asset.view(i.bufferView);let t=f(e.bufferViews,i.bufferView,`bufferView`),n=this.map[t.buffer];if(n?.source>=0){let e=this.sources[n.source],r=n.offset+(t.byteOffset??0),i=r+t.byteLength;if(e.ranged){let t=O(e.asked,r,i);for(let[e,r]of t)this.request(n.source,e,r)}for(;!k(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:n(i.uri,this.base,this.allowedURLs,`glTF`),got:[],asked:[]});s=await r(e,{maxBytes:Math.max(0,this.limit-this.loaded),signal:this.signal,label:`glTF image`}).catch(e=>{throw e instanceof RangeError?c(`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 l=await d(s,i.mimeType,t,this.signal);if(p+=l.width*l.height*4,l.width*l.height>67108864)throw`close`in l&&l.close(),RangeError(`glTF images exceed decoded size limit; load a smaller model, or reduce its textures and meshes`);if(p>this.limit*4)throw`close`in l&&l.close(),c(`glTF images exceed decoded size limit`,this.limit*4);this.post({type:`image`,index:t,image:l})},_=Array.from({length:E},async()=>{for(let e;(e=u.shift())!==void 0;)await g(e)});await Promise.all(_)}};export{j as GLTFStream};
@@ -0,0 +1,87 @@
1
+ import type { PrimitivePart } from './model.js';
2
+ import type { GLTFDocument, GLTFStreamSource } from './asset.js';
3
+ /** An error as it crosses to the main thread; `code` keeps a MargoError's code. */
4
+ export type StreamError = {
5
+ name: string;
6
+ message: string;
7
+ code?: string;
8
+ };
9
+ export type StreamMessage = {
10
+ type: 'fallback';
11
+ } | {
12
+ type: 'doc';
13
+ doc: GLTFDocument;
14
+ } | {
15
+ type: 'geometry';
16
+ key: number;
17
+ vertices?: Float32Array;
18
+ indices?: Uint32Array;
19
+ uvs?: Float32Array;
20
+ /** Set on each part of a split primitive; parts arrive in order, one message each. */
21
+ part?: PrimitivePart;
22
+ error?: StreamError;
23
+ } | {
24
+ type: 'image';
25
+ index: number;
26
+ image?: ImageBitmap | import('./asset.js').GLTFPixelImage;
27
+ source?: GLTFStreamSource;
28
+ } | {
29
+ type: 'bytes';
30
+ loaded: number;
31
+ total: number;
32
+ } | {
33
+ type: 'done';
34
+ buffers: Uint8Array[];
35
+ accessors: [number, Float32Array][];
36
+ } | {
37
+ type: 'error';
38
+ error: StreamError;
39
+ };
40
+ export declare class GLTFStream {
41
+ private readonly url;
42
+ private readonly post;
43
+ private readonly signal;
44
+ private readonly limit;
45
+ private readonly maxNodes?;
46
+ private readonly allowedURLs?;
47
+ private readonly textures;
48
+ private readonly partVertices;
49
+ private order?;
50
+ private readonly sources;
51
+ private map;
52
+ private needs;
53
+ private asset?;
54
+ private readonly posted;
55
+ private waiters;
56
+ private failure;
57
+ private inflight;
58
+ /** Requested bytes not yet received: new batches wait until under BATCH, so bandwidth goes to the first keys. */
59
+ private pending;
60
+ private loaded;
61
+ private reported;
62
+ private base;
63
+ /**
64
+ * `limit`: maxDownloadBytes, already validated by the caller; `maxNodes`: the load's maxNodes; `textures`: KTX2 images
65
+ * 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.
67
+ */
68
+ constructor(url: URL, post: (message: StreamMessage) => void, signal: AbortSignal, limit?: number, maxNodes?: number | undefined, allowedURLs?: readonly string[] | undefined, textures?: boolean, partVertices?: number);
69
+ /** Primitive keys still wanted, most important first (the main thread re-sends this as the camera moves). */
70
+ setOrder(order: number[]): void;
71
+ private notify;
72
+ private next;
73
+ run(): Promise<void>;
74
+ private bytes;
75
+ /** `root`: the model's own first request, whose final URL becomes the base; every other response must stay in it. */
76
+ private fetch;
77
+ private allocate;
78
+ private read;
79
+ private head;
80
+ private buffers;
81
+ private ranges;
82
+ private request;
83
+ private ready;
84
+ private geometry;
85
+ private textureSource;
86
+ private images;
87
+ }
@@ -0,0 +1,2 @@
1
+ function e(e){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(`Invalid texture coordinates; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let t=e?.extensions?.KHR_texture_transform;if(t!==void 0&&(!t||typeof t!=`object`||Array.isArray(t)))throw TypeError(`Invalid KHR_texture_transform; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let n=t?.texCoord===void 0?e.texCoord===void 0?0:e.texCoord:t.texCoord;if(n!==0&&n!==1&&n!==2&&n!==3)throw RangeError(`Texture requires TEXCOORD_0 to TEXCOORD_3`);if(t===void 0)return{texCoord:n};let r=(e,t,n)=>{if(e===void 0)return t;if(!Array.isArray(e)||e.length!==2||Array.from(e).some(e=>typeof e!=`number`||!Number.isFinite(Math.fround(e))))throw TypeError(`Invalid texture transform `+n+`; re-export the file and check it with the glTF Validator`);return e},i=r(t.offset,[0,0],`offset`),a=r(t.scale,[1,1],`scale`),o=t.rotation===void 0?0:t.rotation;if(typeof o!=`number`||!Number.isFinite(Math.fround(o)))throw TypeError(`Invalid texture transform rotation; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);if(o===0&&i[0]===0&&i[1]===0&&a[0]===1&&a[1]===1)return{texCoord:n};let s=Math.cos(o),c=Math.sin(o);return{texCoord:n,transform:new Float32Array([s*a[0],c*a[1],i[0],0,-c*a[0],s*a[1],i[1],0])}}var t=[`f.coordsA.x`,`f.coordsA.y`,`f.coordsA.z`,`f.coordsA.w`,`f.coordsB.x`];function n(t,n,r){if(!t.some(e=>e?.extensions?.KHR_texture_transform!==void 0))return;let i=t.map(t=>t?.extensions?.KHR_texture_transform===void 0?void 0:e(t).transform);if(!i.some(Boolean))return;let a=n?.factors?.length??0;if(n?.factors!==void 0&&(!(n.factors instanceof Float32Array)||!a||a%4||n.factors.some(e=>!Number.isFinite(e))))throw TypeError(`Material extension factors require finite vec4 values`);let o=r;if(!o||o.source!==n||o.length!==a||i.some((e,t)=>!!e!=!!o.transforms[t])){let e=new Float32Array(a+i.filter(Boolean).length*8);o={extension:{...n,factors:e},source:n,length:a,transforms:i}}let s=o.extension,c=s.factors;Object.assign(s,n),s.factors=c;for(let e of[`wgsl`,`direct`,`ambient`,`output`,`lighting`,`declarations`,`textures`,`transmission`,`afterOpaque`])n?.[e]===void 0&&delete s[e];n?.factors&&c.set(n.factors);let l=a;for(let e of i)e&&(c.set(e,l),l+=8);return o.transforms=i,o}function r(e,t,n=!1){let r=0;for(let e=0;e<5;e++)t?.transforms[e]&&(r|=1<<e);let o=t?`${t.length}:${r}:${+!!t.source?.declarations?.includes(`fn materialUV(`)}:${+n}`:`-:${+n}`,s=i.get(e);s||(i.size>=64&&i.clear(),i.set(e,s=/* @__PURE__ */ new Map));let c=s.get(o);return c===void 0&&(s.size>=64&&s.clear(),s.set(o,c=a(e,t,n))),c}var i=/* @__PURE__ */ new Map;function a(e,n,r){if(n){let r=n.length/4;for(let i=0;i<5;i++)n.transforms[i]&&(e=e.replaceAll(`uv(i,`+t[i]+`)`,`materialUV(uv(i,${t[i]}),materialFactors[${r}],materialFactors[${r+1}])`),r+=2);n.source?.declarations?.includes(`fn materialUV(`)||(e=`fn materialUV(p:vec2f,a:vec4f,b:vec4f)->vec2f{return vec2f(dot(a.xy,p)+a.z,dot(b.xy,p)+b.z);}
2
+ `+e)}return(r||n?.transforms[2])&&(e=e.replace(`if(abs(i.tangent.w)<0.5)`,`if(true)`)),e}export{r as n,e as r,n as t};
@@ -0,0 +1,26 @@
1
+ import type { GLTFTextureInfo } from './shared/gltf.js';
2
+ import type { MaterialExtension } from './material-extension.js';
3
+ /** A glTF UV set a texture may read: TEXCOORD_0 to TEXCOORD_3. */
4
+ export type UVSet = 0 | 1 | 2 | 3;
5
+ /** glTF texture coordinates: scale, then rotation about the origin, then offset. */
6
+ export interface TextureTransform {
7
+ offset?: readonly [number, number];
8
+ rotation?: number;
9
+ scale?: readonly [number, number];
10
+ texCoord?: UVSet;
11
+ }
12
+ /** A texture's UV set and, with KHR_texture_transform, its affine rows; throws on invalid values or a fifth UV set. */
13
+ export declare function textureCoordinates(info: Pick<GLTFTextureInfo, 'texCoord' | 'extensions'>): {
14
+ texCoord: UVSet;
15
+ transform?: Float32Array;
16
+ };
17
+ export declare const textureTransformWGSL = "fn materialUV(p:vec2f,a:vec4f,b:vec4f)->vec2f{return vec2f(dot(a.xy,p)+a.z,dot(b.xy,p)+b.z);}\n";
18
+ export interface CoordinateExtension {
19
+ extension: MaterialExtension;
20
+ source?: MaterialExtension;
21
+ length: number;
22
+ transforms: readonly (Float32Array | undefined)[];
23
+ }
24
+ /** Append affine rows to the optional slot without changing caller-owned factors. */
25
+ export declare function coordinateExtension(maps: readonly (GLTFTextureInfo | undefined)[], source?: MaterialExtension, previous?: CoordinateExtension): CoordinateExtension | undefined;
26
+ export declare function coordinateShader(code: string, coordinates?: CoordinateExtension, normalUV1?: boolean): string;
@@ -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 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};
@@ -0,0 +1,88 @@
1
+ import type { EngineKernel } from '@margoengine/core';
2
+ import type { KTX2StreamerOptions, StreamedKTX2 } from '@margoengine/decoders/ktx2-stream';
3
+ import type { GLTFStreamedImage, GLTFStreamSource, GLTFTextureOpener } from './asset.js';
4
+ import type { PBRModel } from './pbr.js';
5
+ /** `textures` of `loadGLTFProgressive`: the memory budget and loading of its KTX2 textures. */
6
+ export interface GLTFTextureStreamOptions extends Pick<KTX2StreamerOptions, 'budgetBytes' | 'concurrency' | 'headBytes' | 'decoder' | 'hdrDecoder'> {
7
+ /** Called when a finer level fails to load; the texture keeps the levels it has. Default: `console.error`. */
8
+ onError?: (error: unknown) => void;
9
+ }
10
+ /** One image of a model: a stream that hands the current view to whoever draws it. */
11
+ declare class StreamedImage implements GLTFStreamedImage {
12
+ private readonly owner;
13
+ readonly source: GLTFStreamSource;
14
+ readonly streamed = true;
15
+ readonly users: Set<{
16
+ rebindStreamed(image: GLTFStreamedImage): void;
17
+ }>;
18
+ stream?: StreamedKTX2;
19
+ width: number;
20
+ height: number;
21
+ /** On-screen size for the next update. */
22
+ wanted: number;
23
+ private views;
24
+ constructor(owner: GLTFTextureStream, source: GLTFStreamSource);
25
+ view(device: GPUDevice, srgb: boolean): GPUTextureView | undefined;
26
+ viewSize(): {
27
+ width: number;
28
+ height: number;
29
+ levels: number;
30
+ } | undefined;
31
+ /** Takes on a newly opened stream and tells the models. */
32
+ use(stream: StreamedKTX2): void;
33
+ private changed;
34
+ /** Lets go of the stream only, for a restart on a new device. */
35
+ drop(): void;
36
+ close(): void;
37
+ }
38
+ /**
39
+ * The live texture side of one progressive load (`load.textures`). It reads how large each KTX2 texture is on screen about
40
+ * five times a second and asks for the levels that need, inside `budgetBytes`, for as long as the model lives.
41
+ */
42
+ export declare class GLTFTextureStream implements GLTFTextureOpener {
43
+ private readonly options;
44
+ private readonly signal;
45
+ private readonly engine;
46
+ private readonly name;
47
+ private readonly images;
48
+ private readonly models;
49
+ private readonly uses;
50
+ private streamer;
51
+ private since;
52
+ private closed;
53
+ private plugin;
54
+ /** Creates the stream on `engine` (preferred over the constructor); the `textures` option of `/progressive` calls this. */
55
+ static attach(engine: EngineKernel, options?: GLTFTextureStreamOptions, signal?: AbortSignal): GLTFTextureStream;
56
+ constructor(instance: EngineKernel, options?: GLTFTextureStreamOptions, signal?: AbortSignal);
57
+ private start;
58
+ /** The device the streams live on. */
59
+ get device(): GPUDevice;
60
+ /** Most bytes of GPU memory the textures may hold; lower it under memory pressure. */
61
+ get budgetBytes(): number;
62
+ set budgetBytes(bytes: number);
63
+ /** GPU bytes the textures hold now. */
64
+ get usedBytes(): number;
65
+ /** Textures streaming, with the finest level each holds (0 is full size), its level count and size on screen in pixels. */
66
+ get textures(): {
67
+ width: number;
68
+ height: number;
69
+ level: number;
70
+ levels: number;
71
+ pixels: number;
72
+ }[];
73
+ private begin;
74
+ /** Opens one image; resolves once its smallest levels are on the GPU. */
75
+ open(source: GLTFStreamSource): Promise<GLTFStreamedImage>;
76
+ /** Follows `model`, which then rebinds as its textures change. */
77
+ attach(model: PBRModel): void;
78
+ /** Forgets a closed image; with the last one gone, the stream closes. */
79
+ forget(image: StreamedImage): void;
80
+ private mapsOf;
81
+ private measure;
82
+ /** Reads every texture's size on screen and starts the loads that calls for; runs by itself about five times a second. */
83
+ update(): void;
84
+ private restart;
85
+ /** Stops loading and frees every texture; disposing the model does this. */
86
+ dispose(): void;
87
+ }
88
+ export {};
@@ -0,0 +1,34 @@
1
+ import type { GLTFExtension, Model } from './index.js';
2
+ /** Top-left row-major RGBA8 pixels, as `getImageData` gives. */
3
+ export interface TexturedPixels {
4
+ width: number;
5
+ height: number;
6
+ data: ArrayLike<number>;
7
+ }
8
+ /** One cut-out's mask, in the shape `AlphaMask` of `@margoengine/bvh/alpha` reads. */
9
+ export interface TexturedAlphaMask extends TexturedPixels {
10
+ cutoff: number;
11
+ factor: number;
12
+ wrap: readonly ['repeat' | 'mirror' | 'clamp', 'repeat' | 'mirror' | 'clamp'];
13
+ }
14
+ /**
15
+ * The masks of a model loaded with {@link textured}, for `AlphaRaycaster.alphaMask` from `@margoengine/bvh/alpha`, so a
16
+ * ray passes through the holes of its cut-outs. The GPU picks of `engine.pick` and `Picking` see a cut-out as solid. The
17
+ * pixels are read once, here, so call it before `model.dispose`. Hits on anything else answer null.
18
+ * @example ray.alphaMask = await texturedAlphaMasks(model);
19
+ */
20
+ export declare function texturedAlphaMasks(model: Model, { signal, pixels, }?: {
21
+ signal?: AbortSignal;
22
+ pixels?: (image: ImageBitmap) => TexturedPixels | Promise<TexturedPixels>;
23
+ }): Promise<(hit: {
24
+ mesh: object;
25
+ }) => TexturedAlphaMask | null>;
26
+ /**
27
+ * Lets the light loader draw a base colour texture and MASK cut-outs: `baseColorTexture` on any TEXCOORD set, with
28
+ * `KHR_texture_transform`, multiplied by `baseColorFactor`, and an alpha test against `alphaCutoff`. WebGPU only. Other
29
+ * maps, BLEND and compressed textures stay refused. The mesh stays a core mesh, so transforms, picking and `dispose` work
30
+ * as for any other. A cut-out casts its outline in `@margoengine/shadows`; GPU picks see it as solid, and a ray sees
31
+ * through it with {@link texturedAlphaMasks}. Needs `loadGLTF` or `parseGLTFAsync`, since images decode asynchronously.
32
+ * @example const model = await loadGLTF(engine, '/prop.glb', { extensions: [textured] });
33
+ */
34
+ export declare const textured: GLTFExtension;
@@ -0,0 +1,5 @@
1
+ // @margo/core-built 0.1.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
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};