@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,78 @@
1
+ interface Chunk {
2
+ buffer: GPUBuffer;
3
+ cpu: Float32Array<ArrayBuffer>;
4
+ /** Slots handed out so far (bump pointer, in units) and slots in use. */
5
+ used: number;
6
+ live: number;
7
+ units: number;
8
+ /** Changed float range [lo, hi) since the last flush. */
9
+ lo: number;
10
+ hi: number;
11
+ free: Map<number, number[]>;
12
+ }
13
+ declare class Arena {
14
+ readonly device: GPUDevice;
15
+ readonly unit: number;
16
+ readonly chunks: Chunk[];
17
+ dirty: boolean;
18
+ /** Slots held by draws (not shared view blocks); when the last goes, `idle` runs (shared resources let go). */
19
+ draws: number;
20
+ readonly idle: (() => void)[];
21
+ constructor(device: GPUDevice);
22
+ allocate(floats: number, shared: boolean): UniformSlot;
23
+ /**
24
+ * Returns a slot. Callers go through `retire`, which defers this while commands that read the slot wait for submit,
25
+ * exactly as it does for a buffer of its own. A chunk nothing uses any more goes back to the device.
26
+ */
27
+ free(slot: UniformSlot): void;
28
+ }
29
+ /**
30
+ * One draw's uniform block: a window `binding` of an arena chunk. `destroy()` returns it (after the current task, so
31
+ * commands recorded but not yet submitted keep reading the values they were recorded with).
32
+ */
33
+ export declare class UniformSlot {
34
+ private readonly arena;
35
+ readonly chunk: Chunk;
36
+ readonly offset: number;
37
+ readonly floats: number;
38
+ readonly units: number;
39
+ /** A view block shared by draws (view-uniform.ts) rather than one draw's own. */
40
+ readonly shared: boolean;
41
+ /** What a bind group binds. */
42
+ readonly binding: GPUBufferBinding;
43
+ /** The values the GPU holds for this slot once flushed. */
44
+ private readonly shadow;
45
+ private readonly start;
46
+ private frame;
47
+ private view;
48
+ private uses;
49
+ private extras;
50
+ private gone;
51
+ constructor(arena: Arena, chunk: Chunk, offset: number, floats: number, units: number,
52
+ /** A view block shared by draws (view-uniform.ts) rather than one draw's own. */
53
+ shared: boolean);
54
+ /**
55
+ * Stages `data` for a draw in `view`. The first write of a frame, and every write from that same view, go to the
56
+ * slot itself and return undefined (uploaded by `flushUniforms`); a write with other values from another view of
57
+ * the same frame (a second viewport, a probe face) goes to a reused copy whose binding is returned, so the earlier
58
+ * view's draws keep their values.
59
+ */
60
+ write(data: Float32Array, view: object): GPUBufferBinding | undefined;
61
+ /** @internal The floats the GPU holds for this slot once the pending upload ran (tests read them). */
62
+ get contents(): Float32Array;
63
+ /** @internal True once `destroy()` returned the slot. */
64
+ get destroyed(): boolean;
65
+ destroy(): void;
66
+ }
67
+ /** A uniform block of `floats` floats on `device`: a draw's own, or (`shared`) one that draws share. */
68
+ export declare function acquireUniform(device: GPUDevice, floats: number, shared?: boolean): UniformSlot;
69
+ /**
70
+ * Runs `release` when the last draw slot on `device` goes (the device's shared blocks are then unused).
71
+ */
72
+ export declare function onUniformsIdle(device: GPUDevice, release: () => void): void;
73
+ /**
74
+ * Uploads every changed uniform range of `device`'s arena, one `queue.writeBuffer` per chunk. Call it after the last
75
+ * `UniformSlot.write` of a run of draws and before the frame is submitted.
76
+ */
77
+ export declare function flushUniforms(device: GPUDevice): void;
78
+ export {};
@@ -0,0 +1,109 @@
1
+ var e=e=>`
2
+ @vertex fn vertex(@builtin(vertex_index) i:u32)->@builtin(position) vec4f {
3
+ return vec4f(array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i],0,1);
4
+ }
5
+ @group(0) @binding(0) var image:texture_2d<f32>;
6
+ @fragment fn fragment(@builtin(position) clip:vec4f)->@location(0) vec4f {
7
+ let src=textureDimensions(image);
8
+ let dst=max(src/2u,vec2u(1u));let g=vec2u(clip.xy);
9
+ let a=vec2f(g*src)/vec2f(dst);let b=vec2f((g+1u)*src)/vec2f(dst);let end=min(src,((g+1u)*src+dst-1u)/dst);
10
+ var sum=vec4f(0.0);var sc=vec3f(0.0);
11
+ for(var y=g.y*src.y/dst.y;y<end.y;y++){
12
+ let wy=min(b.y,f32(y+1u))-max(a.y,f32(y));
13
+ for(var x=g.x*src.x/dst.x;x<end.x;x++){
14
+ let w=(min(b.x,f32(x+1u))-max(a.x,f32(x)))*wy;let t=textureLoad(image,vec2u(x,y),0);
15
+ sum+=w*t;sc+=(w*t.a)*t.rgb;
16
+ }
17
+ }
18
+ let area=(b.x-a.x)*(b.y-a.y);
19
+ ${e?`return vec4f(select(sum.rgb/area,sc/sum.a,sum.a>0.0),sum.a/area);`:`return sum/area;`}
20
+ }
21
+ `;function t(t,n,r,i,a=1,o=`plain`){if(r<2)return;let s=n.format,c=o===`weighted`,l=c?s+`:weighted`:s,u=i.get(l);if(!u){let n=t.createShaderModule({code:e(c)});i.set(l,u=t.createRenderPipeline({layout:`auto`,vertex:{module:n,entryPoint:`vertex`},fragment:{module:n,entryPoint:`fragment`,targets:[{format:s}]}}))}let d=t.createCommandEncoder();for(let e=0;e<a;e++)for(let i=1;i<r;i++){let r=t=>n.createView(a>1?{format:s,dimension:`2d`,baseMipLevel:t,mipLevelCount:1,baseArrayLayer:e,arrayLayerCount:1}:{baseMipLevel:t,mipLevelCount:1}),o=t.createBindGroup({layout:u.getBindGroupLayout(0),entries:[{binding:0,resource:r(i-1)}]}),c=d.beginRenderPass({colorAttachments:[{view:r(i),loadOp:`clear`,storeOp:`store`,clearValue:{r:0,g:0,b:0,a:0}}]});c.setPipeline(u),c.setBindGroup(0,o),c.draw(3),c.end()}t.queue.submit([d.finish()])}var n=7,r=`alpha-coverage`,i=`
22
+ struct Params {srcW:u32,srcH:u32,dstW:u32,dstH:u32,rowWords:u32,fromTexture:u32,keep:u32,srgb:u32,total:u32,p0:u32,p1:u32,p2:u32}
23
+ struct Control {goal:atomic<u32>,low:atomic<u32>,high:atomic<u32>,p0:u32,lo:f32,hi:f32,clo:u32,chi:u32,scale:f32,p1:u32,p2:u32,p3:u32,hist:array<atomic<u32>,65>}
24
+ @group(0) @binding(0) var<uniform> p:Params;
25
+ @group(0) @binding(1) var source:texture_2d<f32>;
26
+ @group(0) @binding(2) var<storage,read> stateIn:array<vec4f>;
27
+ @group(0) @binding(3) var<storage,read_write> stateOut:array<vec4f>;
28
+ @group(0) @binding(4) var<storage,read_write> ctl:Control;
29
+ @group(0) @binding(5) var<storage,read_write> bytes:array<u32>;
30
+ var<workgroup> wa:array<atomic<u32>,65>;
31
+ var<workgroup> wb:array<atomic<u32>,3>;
32
+ fn code(a:f32,s:f32)->u32 {return u32(floor(255.0*clamp(a*s,0.0,1.0)+0.5));}
33
+ fn candidate(lo:f32,hi:f32,j:u32)->f32 {return lo+(hi-lo)*(f32(j)/64.0);}
34
+ fn mul(a:u32,b:u32)->vec2u {
35
+ let ll=(a&0xffffu)*(b&0xffffu);let lh=(a&0xffffu)*(b>>16u);let hl=(a>>16u)*(b&0xffffu);
36
+ let mid=(ll>>16u)+(lh&0xffffu)+(hl&0xffffu);
37
+ return vec2u((a>>16u)*(b>>16u)+(lh>>16u)+(hl>>16u)+(mid>>16u),(ll&0xffffu)|(mid<<16u));
38
+ }
39
+ fn less(a:vec2u,b:vec2u)->bool {return a.x<b.x||(a.x==b.x&&a.y<b.y);}
40
+ fn gap(a:vec2u,b:vec2u)->vec2u {
41
+ if(less(a,b)){return vec2u(b.x-a.x-select(0u,1u,b.y<a.y),b.y-a.y);}
42
+ return vec2u(a.x-b.x-select(0u,1u,a.y<b.y),a.y-b.y);
43
+ }
44
+ @compute @workgroup_size(8,8) fn targetCount(@builtin(global_invocation_id) g:vec3u,@builtin(local_invocation_index) l:u32) {
45
+ if(l==0u){atomicStore(&wb[1],255u);}
46
+ workgroupBarrier();
47
+ if(g.x<p.srcW&&g.y<p.srcH){
48
+ let c=u32(floor(textureLoad(source,g.xy,0).a*255.0+0.5));
49
+ if(c>=p.keep){atomicAdd(&wb[0],1u);}
50
+ atomicMin(&wb[1],c);atomicMax(&wb[2],c);
51
+ }
52
+ workgroupBarrier();
53
+ if(l==0u){atomicAdd(&ctl.goal,atomicLoad(&wb[0]));atomicMin(&ctl.low,atomicLoad(&wb[1]));atomicMax(&ctl.high,atomicLoad(&wb[2]));}
54
+ }
55
+ @compute @workgroup_size(8,8) fn reduce(@builtin(global_invocation_id) g:vec3u) {
56
+ if(g.x>=p.dstW||g.y>=p.dstH){return;}
57
+ let x0=f32(g.x*p.srcW)/f32(p.dstW);let x1=f32((g.x+1u)*p.srcW)/f32(p.dstW);
58
+ let y0=f32(g.y*p.srcH)/f32(p.dstH);let y1=f32((g.y+1u)*p.srcH)/f32(p.dstH);
59
+ let ex=min(p.srcW,((g.x+1u)*p.srcW+p.dstW-1u)/p.dstW);let ey=min(p.srcH,((g.y+1u)*p.srcH+p.dstH-1u)/p.dstH);
60
+ var sa=0.0;var sc=vec3f(0.0);var pc=vec3f(0.0);
61
+ for(var y=g.y*p.srcH/p.dstH;y<ey;y++){
62
+ let wy=min(y1,f32(y+1u))-max(y0,f32(y));
63
+ for(var x=g.x*p.srcW/p.dstW;x<ex;x++){
64
+ let w=(min(x1,f32(x+1u))-max(x0,f32(x)))*wy;
65
+ var t:vec4f;
66
+ if(p.fromTexture==1u){t=textureLoad(source,vec2u(x,y),0);}else{t=stateIn[y*p.srcW+x];}
67
+ sa+=w*t.a;sc+=(w*t.a)*t.rgb;pc+=w*t.rgb;
68
+ }
69
+ }
70
+ let area=(x1-x0)*(y1-y0);
71
+ stateOut[g.y*p.dstW+g.x]=vec4f(select(pc/area,sc/sa,sa>0.0),sa/area);
72
+ }
73
+ @compute @workgroup_size(1) fn begin() {ctl.lo=0.0;ctl.hi=4096.0;}
74
+ @compute @workgroup_size(8,8) fn count(@builtin(global_invocation_id) g:vec3u,@builtin(local_invocation_index) l:u32) {
75
+ let lo=ctl.lo;let hi=ctl.hi;
76
+ if(g.x<p.dstW&&g.y<p.dstH){
77
+ let a=stateOut[g.y*p.dstW+g.x].a;
78
+ if(code(a,candidate(lo,hi,64u))>=p.keep){
79
+ var b=0u;var e=64u;
80
+ loop{if(b>=e){break;}let m=(b+e)/2u;if(code(a,candidate(lo,hi,m))>=p.keep){e=m;}else{b=m+1u;}}
81
+ atomicAdd(&wa[e],1u);
82
+ }
83
+ }
84
+ workgroupBarrier();
85
+ let v=atomicLoad(&wa[l]);if(v>0u){atomicAdd(&ctl.hist[l],v);}
86
+ if(l==0u){let u=atomicLoad(&wa[64]);if(u>0u){atomicAdd(&ctl.hist[64],u);}}
87
+ }
88
+ @compute @workgroup_size(1) fn update() {
89
+ let t=mul(atomicLoad(&ctl.goal),p.dstW*p.dstH);
90
+ var c:array<u32,65>;var run=0u;
91
+ for(var j=0u;j<65u;j++){run+=atomicLoad(&ctl.hist[j]);c[j]=run;atomicStore(&ctl.hist[j],0u);}
92
+ var j=0u;
93
+ loop{if(j>64u){break;}if(!less(mul(c[j],p.total),t)){break;}j++;}
94
+ let lo=ctl.lo;let hi=ctl.hi;
95
+ if(j==0u){ctl.hi=lo;ctl.clo=c[0];ctl.chi=c[0];}
96
+ else if(j>64u){ctl.lo=hi;ctl.clo=c[64];ctl.chi=c[64];}
97
+ else{ctl.lo=candidate(lo,hi,j-1u);ctl.hi=candidate(lo,hi,j);ctl.clo=c[j-1u];ctl.chi=c[j];}
98
+ ctl.scale=select(ctl.hi,ctl.lo,less(gap(mul(ctl.clo,p.total),t),gap(mul(ctl.chi,p.total),t)));
99
+ }
100
+ @compute @workgroup_size(8,8) fn write(@builtin(global_invocation_id) g:vec3u) {
101
+ if(g.x>=p.dstW||g.y>=p.dstH){return;}
102
+ let t=stateOut[g.y*p.dstW+g.x];
103
+ let s=select(ctl.scale,1.0,atomicLoad(&ctl.low)==atomicLoad(&ctl.high));
104
+ var c=clamp(t.rgb,vec3f(0.0),vec3f(1.0));
105
+ if(p.srgb==1u){c=select(1.055*pow(c,vec3f(1.0/2.4))-0.055,c*12.92,c<=vec3f(0.0031308));}
106
+ let b=vec3u(floor(c*255.0+0.5));
107
+ bytes[g.y*p.rowWords+g.x]=b.x|(b.y<<8u)|(b.z<<16u)|(code(t.a,s)<<24u);
108
+ }
109
+ `;function a(e,t){let n=Math.fround;if(!(n(0)*n(t)<n(e)))return 0;for(let r=1;r<256;r++)if(n(n(r/255)*n(t))>=n(e))return r;return 0}function o(e,t){let n=t.get(r);if(n)return n;let a=e=>({visibility:4,buffer:{type:e}}),o=e.createBindGroupLayout({entries:[{binding:0,visibility:4,buffer:{type:`uniform`}},{binding:1,visibility:4,texture:{sampleType:`float`}},{binding:2,...a(`read-only-storage`)},{binding:3,...a(`storage`)},{binding:4,...a(`storage`)},{binding:5,...a(`storage`)}]}),s=e.createShaderModule({code:i}),c=e.createPipelineLayout({bindGroupLayouts:[o]}),l=t=>e.createComputePipeline({layout:c,compute:{module:s,entryPoint:t}});n={layout:o};for(let e of[`targetCount`,`reduce`,`begin`,`count`,`update`,`write`])n[e]=l(e);return t.set(r,n),n}function s(e,r,i,s,c,l){if(i<2)return;let u=a(c,l),{format:d,width:f,height:p}=r,m=Math.max(1,f>>1)*Math.max(1,p>>1)*16;if(!u||d!==`rgba8unorm`&&d!==`rgba8unorm-srgb`||m>e.limits.maxStorageBufferBindingSize||m>e.limits.maxBufferSize)return t(e,r,i,s);let h=o(e,s),g=[[f,p]];for(let e=1;e<i;e++)g.push(g[e-1].map(e=>Math.max(1,e>>1)));let _=e=>Math.ceil(e*4/256)*64,v=4,y=16;for(let e=1;e<i;e++)v=Math.max(v,_(g[e][0])*4*g[e][1]),e%2==0&&(y=Math.max(y,g[e][0]*g[e][1]*16));let b=(t,n)=>e.createBuffer({size:t,usage:n}),x=b(256*i,GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST),S=[b(y,GPUBufferUsage.STORAGE),b(m,GPUBufferUsage.STORAGE)],C=b(308,GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST),w=b(v,GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC),T=new Uint32Array(64*i),E=+!!d.endsWith(`-srgb`);for(let e=0;e<i;e++){let[t,n]=g[Math.max(0,e-1)],[r,i]=g[e];T.set([t,n,r,i,_(r),+(e===1),u,E,f*p],e*64)}e.queue.writeBuffer(x,0,T),e.queue.writeBuffer(C,0,new Uint32Array([0,255,0]));let D=r.createView({baseMipLevel:0,mipLevelCount:1}),O=t=>e.createBindGroup({layout:h.layout,entries:[{binding:0,resource:{buffer:x,offset:t*256,size:48}},{binding:1,resource:D},{binding:2,resource:{buffer:S[(t+1)%2]}},{binding:3,resource:{buffer:S[t%2]}},{binding:4,resource:{buffer:C}},{binding:5,resource:{buffer:w}}]}),k=e=>[Math.ceil(e[0]/8),Math.ceil(e[1]/8)],A=e.createCommandEncoder(),j=A.beginComputePass();j.setBindGroup(0,O(0)),j.setPipeline(h.targetCount),j.dispatchWorkgroups(...k(g[0])),j.end();for(let e=1;e<i;e++){j=A.beginComputePass(),j.setBindGroup(0,O(e)),j.setPipeline(h.reduce),j.dispatchWorkgroups(...k(g[e])),j.setPipeline(h.begin),j.dispatchWorkgroups(1);for(let t=0;t<n;t++)j.setPipeline(h.count),j.dispatchWorkgroups(...k(g[e])),j.setPipeline(h.update),j.dispatchWorkgroups(1);j.setPipeline(h.write),j.dispatchWorkgroups(...k(g[e])),j.end(),A.copyBufferToTexture({buffer:w,bytesPerRow:_(g[e][0])*4},{texture:r,mipLevel:e},g[e])}e.queue.submit([A.finish()]);for(let e of[x,...S,C,w])e.destroy()}function c(e,t,n){let r=Math.hypot(n[0],n[1],n[2]);e[t]=n[0]/r,e[t+1]=n[1]/r,e[t+2]=n[2]/r,e[t+3]=n[3]}export{t as i,s as n,a as r,c as t};
@@ -0,0 +1 @@
1
+ import{n as e,r as t,t as n}from"./errors-THVaUwlL.js";var r=class{constructor(...e){this.failed=e.length>0,this.error=e[0]}run(e){try{e()}catch(e){this.failed||(this.error=e),this.failed=!0}return this}finish(){if(this.failed)throw this.error}};async function i(e,{maxBytes:t,signal:n,label:i=`Asset`,output:a=null,expected:o=0}){if(!Number.isSafeInteger(t)||t<0||a!==null&&(!(a instanceof Uint8Array)||a.length!==t))throw RangeError(`Invalid asset byte budget; pass maxBytes as an integer`);if(n?.throwIfAborted(),!e)throw TypeError(`Empty ${i} response; check the URL`);let s=e.getReader(),c=[],l=0,u=a,d=new r,f=e=>{try{Promise.resolve(s.cancel(e)).catch(()=>{})}catch{}},p=()=>f(n.reason);n?.addEventListener(`abort`,p,{once:!0});try{for(!a&&Number.isSafeInteger(o)&&o>0&&o<=t&&(u=new Uint8Array(o));;){n?.throwIfAborted();let{done:e,value:r}=await s.read();if(n?.throwIfAborted(),e)break;if(!(r instanceof Uint8Array))throw TypeError(`${i} stream requires byte chunks`);if(r.byteLength>t-l)throw RangeError(`${i} byte budget exceeded; raise maxBytes`);u&&r.length<=u.length-l?u.set(r,l):(u&&c.push(u.subarray(0,l)),u=null,c.push(r.length<r.buffer.byteLength||!(r.buffer instanceof ArrayBuffer)?r.slice():r)),l+=r.byteLength}}catch(e){f(e),d=new r(e)}if(d.run(()=>n?.removeEventListener(`abort`,p)).run(()=>s.releaseLock()).finish(),a)return a.subarray(0,l);if(u)return l<u.length?u.slice(0,l):u;let m=new Uint8Array(l),h=0;for(let e of c)m.set(e,h),h+=e.length;return m}async function a(t,n){try{if(n.signal?.throwIfAborted(),!t.ok)throw e(`failed`,`${n.label??`Asset`} request failed: HTTP ${t.status}; check the URL and that the server serves it`);let r=Number(t.headers.get(`content-length`));if(Number.isFinite(r)&&r>n.maxBytes)throw RangeError(`${n.label??`Asset`} byte budget exceeded; raise maxBytes`);let i=t.headers.get(`content-encoding`);(!i||i===`identity`)&&(n={...n,expected:r})}catch(e){try{Promise.resolve(t.body?.cancel(e)).catch(()=>{})}catch{}throw e}return i(t.body,n)}var o=/"(?:__proto__|constructor|prototype)"|\\u/,s=(e,t)=>e===`__proto__`||e===`constructor`||e===`prototype`?void 0:t,c=e=>o.test(e)?JSON.parse(e,s):JSON.parse(e),l=/%2f|%5c|%00|\u0000|(^|\/)(\.|%2e){1,2}(\/|$)/i;function u(e){for(let t=0;t<8;t++){if(l.test(e))return!0;let t=e.replace(/%[\da-f]{2}/gi,e=>String.fromCharCode(`0x${e.slice(1)}`));if(t===e)return!1;e=t}return!0}function d(e,t){let n;try{n=new URL(t)}catch{throw TypeError(`allowedURLs entry ${String(t)} is not an absolute URL; pass a full http(s) URL`)}if(n.origin!==e.origin||n.protocol!==`http:`&&n.protocol!==`https:`||n.search&&n.search!==e.search)return!1;let r=n.pathname;return r.endsWith(`/`)?e.pathname.startsWith(r):e.pathname===r||e.pathname.startsWith(`${r}/`)}function f(e,t,n=[],r=`Asset`){if(typeof e!=`string`||!e||e.length>8192)throw TypeError(`Invalid ${r} URI; pass a shorter string`);let i;try{i=new URL(e,t)}catch{throw TypeError(`Invalid ${r} URI; pass a valid URL`)}if((i.protocol===`http:`||i.protocol===`https:`)&&!u(i.pathname)){for(let e of n)if(d(i,e))return i;let e=t===void 0?void 0:new URL(`.`,t);if(e&&i.origin===e.origin&&i.pathname.startsWith(e.pathname))return i}throw TypeError(`${r} URI ${i.href} leaves the model's directory; add its prefix to allowedURLs to load it`)}function p(e,t,n=[],r=`Asset`){if(!e.url)return e;try{f(e.url,t,n,r)}catch{throw e.body?.cancel().catch(()=>{}),TypeError(`${r} URI redirected to ${e.url}, which leaves the model's directory; add its prefix to allowedURLs to load it`)}return e}var m=1179937895,h=1313821514,g=5130562,_=e=>t(`GLB ${e}; pass a whole glTF 2.0 GLB file`,`failed`);function v(e,t){if(Number.isSafeInteger(t)&&e>t+3)throw n(`failed`,`GLB BIN chunk holds ${e} bytes, more than buffer 0's byteLength ${t} plus 3 padding bytes; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`)}var y=e=>e.length>=4&&new DataView(e.buffer,e.byteOffset,4).getUint32(0,!0)===1179937895;function b(e){if(e.length<20)throw _(`needs at least 20 bytes for its 12-byte file header and 8-byte JSON chunk header; received ${e.length}`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0);if(n!==1179937895)throw _(`header magic 0x${n.toString(16)} is not glTF (0x46546c67)`);if(r!==2)throw _(`header version ${r} is unsupported; use version 2`);if(i!==e.length)throw _(`header total length ${i} bytes differs from the received ${e.length} bytes`);let a=[];for(let n=12;n<e.length;){if(n+8>e.length)throw _(`ends inside the 8-byte chunk header at byte ${n}`);let r=t.getUint32(n,!0),i=t.getUint32(n+4,!0),o=n+8+r;if(r%4)throw _(`chunk length ${r} at byte ${n} must have 4-byte alignment`);if(o>e.length)throw _(`chunk length ${r} at byte ${n} extends past the ${e.length}-byte file`);if(a.length===0!=(i===1313821514)||i===5130562&&a.length!==1)throw _(`chunks must be JSON first, then at most one BIN second; export the file again`);a.push({type:i,data:e.subarray(n+8,o)}),n=o}return a}function x(e){let t=/^(\d+)\.(\d+)$/,n=typeof e?.version==`string`?t.exec(e.version):null;if(!n||n[1]!==`2`)return!1;if(e.minVersion===void 0)return!0;let r=typeof e.minVersion==`string`?t.exec(e.minVersion):null;return!!r&&r[1]===`2`&&r[2]===`0`}export{v as a,f as c,a as d,r as f,m as i,p as l,g as n,b as o,h as r,y as s,x as t,c as u};
@@ -0,0 +1,8 @@
1
+ /**
2
+ * glTF 2.0 section 3.2: with no `minVersion` a client checks the major version of `version`; with one, that its major
3
+ * and minor are supported. This loader supports 2.0, so `version: '2.1'` loads, and so does `minVersion: '2.0'`.
4
+ */
5
+ export declare function supportedVersion(asset: {
6
+ version?: unknown;
7
+ minVersion?: unknown;
8
+ } | undefined): boolean;
@@ -0,0 +1,47 @@
1
+ export interface VertexInputs {
2
+ /** The shader to compile. */
3
+ readonly code: string;
4
+ /** The vertex locations it reads, ascending. */
5
+ readonly locations: readonly number[];
6
+ /** Those of `locations` whose `xyz` alone it reads: a three-float fetch fills them, w taking WebGPU's default 1. */
7
+ readonly narrow: readonly number[];
8
+ }
9
+ /** Vertex buffer slot of the third and fourth UV sets, past the instance buffer's: unused slots between stay empty. */
10
+ export declare const laterUVSlot = 2;
11
+ /** Their layout: one vec4 a vertex, TEXCOORD_2 then TEXCOORD_3. */
12
+ export declare const laterUVLayout: GPUVertexBufferLayout;
13
+ /**
14
+ * `code`, as trimmed by `vertexInputs`, reading TEXCOORD_2 and 3 as well: a second vertex buffer feeds `Out.uvs`, and every
15
+ * choice between the two sets of `Out.uv` becomes a choice among four. Only a draw whose material reads a later set
16
+ * compiles this. Output location 15 is free of every patch that adds outputs.
17
+ */
18
+ export declare function laterUVShader(code: string): string;
19
+ /**
20
+ * True when every vertex of `vertices` (80-byte PBR, 20 floats a vertex) from vertex `start` on, `count` of them, has
21
+ * the colour (1, 1, 1, 1): what a primitive without COLOR_0 packs. Stops at the first other colour.
22
+ */
23
+ export declare function whiteColours(vertices: Float32Array, start?: number, count?: number): boolean;
24
+ /** True when every vertex of `vertices` from vertex `start` on, `count` of them, has colour alpha 1 (COLOR_0 absent included). */
25
+ export declare function opaqueColours(vertices: Float32Array, start?: number, count?: number): boolean;
26
+ /**
27
+ * A MASK colour pass hands the colour's transparency (1 - alpha) from the vertex stage on, and the fragment reads
28
+ * 1 minus that. Interpolating a constant 0 is exact on every rasterizer; interpolating a constant 1 is not (perspective
29
+ * division leaves 0.99999994 in some pixels), and a texel alpha equal to `alphaCutoff` must stay opaque (glTF 2.0,
30
+ * 3.9.4) when the vertex alpha is 1 or COLOR_0 is absent. Code that names the stage output any other way than
31
+ * `i:Out` / `o.color` is returned unchanged.
32
+ */
33
+ export declare function exactAlphaShader(code: string): string;
34
+ /** Vertex buffer slot 0: the 80-byte vertex, one attribute per location `inputs` reads, three floats where xyz do. */
35
+ export declare function vertexLayout(inputs: VertexInputs): GPUVertexBufferLayout;
36
+ /**
37
+ * Instance buffer `layout` less the attributes finished shader `code` does not declare in its `Instance` struct (the
38
+ * UV row `vertexInputs` drops with the UVs): the same stride, nothing fetched that no input reads. One object per
39
+ * layout and kept set.
40
+ */
41
+ export declare function instanceInputs(code: string, layout: GPUVertexBufferLayout): GPUVertexBufferLayout;
42
+ /**
43
+ * Trims finished shader `source` to the vertex inputs it reads. Called once per pipeline built. `white`: every vertex
44
+ * of the drawn buffer has colour (1, 1, 1, 1) (`whiteColours`), so the vertex stage reads that constant in place of
45
+ * the colour input: the same value, without the 16-byte fetch.
46
+ */
47
+ export declare function vertexInputs(source: string, white?: boolean): VertexInputs;
@@ -0,0 +1,13 @@
1
+ /** Floats in a view block: camera and view matrices, eye, light direction, radiance, flags (x: HDR target). */
2
+ export declare const viewFloats = 48;
3
+ /** Pipelines whose shader binds `margoView`. */
4
+ export declare const viewPipelines: WeakSet<GPURenderPipeline>;
5
+ /**
6
+ * The binding of the view block that `view`'s draws bind this frame on `device`, holding `data` (`viewFloats` floats).
7
+ * Every draw of a view shares one block, as a draw's own uniform used to be shared by all its views' passes: a second
8
+ * view of a frame (a viewport, a probe face) has a block of its own, and a later write from the same view replaces the
9
+ * values, as before. `owner` separates draws with a caller-supplied view matrix (stereo eyes), each of which kept its
10
+ * own uniforms. A view keeps its block frame after frame, so bind groups stay the same, a steady view uploads nothing
11
+ * and a moving camera uploads its 192 bytes once.
12
+ */
13
+ export declare function viewBinding(device: GPUDevice, data: Float32Array, view: object, owner?: object): GPUBufferBinding;
@@ -0,0 +1 @@
1
+ function e(e,t){for(let n=t;n>=0;n=e.parents?.[n]??-1)if(e.hidden[n])return!0;return!1}export{e as t};
@@ -0,0 +1 @@
1
+ function e(e,t=/* @__PURE__ */ new Set,n=/* @__PURE__ */ new Set){let r=[e];for(;r.length;){let e=r.pop();if(e&&typeof e==`object`&&!n.has(e)){if(n.add(e),ArrayBuffer.isView(e))e.buffer instanceof ArrayBuffer&&t.add(e.buffer);else if(e instanceof ArrayBuffer)t.add(e);else if(typeof ImageBitmap<`u`&&e instanceof ImageBitmap)t.add(e);else if(e instanceof Map)for(let[t,n]of e)r.push(t,n);else for(let t in e)r.push(e[t])}}return t}function t(e){if(e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e))return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);if(typeof e==`string`)return e;throw TypeError(`Expected an ArrayBuffer, typed array or string`)}var n=()=>typeof Worker==`function`&&globalThis.location!==void 0,r={TypeError,RangeError,SyntaxError},i=({name:e,message:t})=>new(Object.hasOwn(r,e)?r[e]:Error)(typeof t==`string`?t:`Parser worker failed`);function a(t,n,r,a){return r?.throwIfAborted(),new Promise((o,s)=>{let c=new Worker(t,{name:`margoengine-parser`}),l=()=>{c.onmessage=c.onerror=c.onmessageerror=null,c.terminate(),r?.removeEventListener(`abort`,d)},u=e=>{l(),s(e)},d=()=>u(r.reason??new DOMException(`Aborted`,`AbortError`));r?.addEventListener(`abort`,d,{once:!0}),c.onerror=e=>{e.preventDefault?.(),u(/* @__PURE__ */ Error(`Parser worker failed: `+(e.message||`unknown error`)))},c.onmessageerror=()=>u(/* @__PURE__ */ Error(`Parser worker reply could not be deserialized`)),c.onmessage=({data:e})=>{l(),!e||typeof e!=`object`?s(/* @__PURE__ */ TypeError(`Parser worker sent an invalid reply`)):e.error?s(a?.(e.error)??i(e.error)):o(e.result)};try{c.postMessage(n,[...e(n)])}catch(e){u(e)}})}export{t as n,a as r,n as t};
@@ -0,0 +1,21 @@
1
+ import type { EngineKernel } from '@margoengine/core';
2
+ import { type AssetOptions, type GLTFDecoderHooks } from './asset.js';
3
+ import { PBRModel, type GLTFLoadOptions } from './pbr.js';
4
+ import { type PreparedGLTF } from './prepare.js';
5
+ export type { PreparedGLTF } from './prepare.js';
6
+ /**
7
+ * Build a PBRModel from a worker's PreparedGLTF on this thread (GPU uploads happen here, at the model's setup).
8
+ * `decoders` takes only the `instancing` reader (@margoengine/gltf/pbr-instancing) for EXT_mesh_gpu_instancing and the
9
+ * `materials` shaders (@margoengine/gltf/extended-materials).
10
+ */
11
+ export declare function modelFromPrepared(instance: EngineKernel, prepared: PreparedGLTF, signal?: AbortSignal, decoders?: Pick<GLTFDecoderHooks, 'instancing' | 'materials'>): PBRModel;
12
+ /**
13
+ * loadGLTF with fetching, JSON parsing, accessor decoding, vertex packing and image decoding in a worker. Same model as
14
+ * loadGLTF. Runs on this thread instead when Workers are unavailable, when Draco, meshopt or KTX2 `decoders` or `fetch` are passed, or with `optimize`.
15
+ */
16
+ export declare function loadGLTFInWorker(instance: EngineKernel, url: string | URL, options?: GLTFLoadOptions): Promise<PBRModel>;
17
+ /**
18
+ * parseGLTFAsync in a worker. A whole ArrayBuffer input (and whole `buffers`) moves to the worker and is detached here;
19
+ * pass a copy to keep it. External URIs resolve against the page.
20
+ */
21
+ export declare function parseGLTFInWorker(instance: EngineKernel, input: string | object | ArrayBuffer | ArrayBufferView, options?: AssetOptions & GLTFLoadOptions): Promise<PBRModel>;
package/dist/worker.js ADDED
@@ -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 h=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import{n as e}from"./errors-THVaUwlL.js";import{t}from"./scene-scope-CZDEkd24.js";import{t as n}from"./decoder-default-CxLH8Vz0.js";import{n as r}from"./model-iRvuj19h.js";import{A as i,g as a,o,t as s}from"./asset-1b8ejkZX.js";import{i as c}from"./pack-BVDYuqZe.js";import{loadGLTF as l,parseGLTFAsync as u}from"./pbr.js";import{prepareAsset as d}from"./prepare.js";import{n as f,r as p,t as m}from"./worker-CY1TQnYX.js";import{engineRuntime as __margoRuntime}from"@margoengine/core/extension";var g=({decoders:e={},fetch:t,draco:n,ktx2:r})=>!!(t||n||r||e.draco||e.meshopt||e.ktx2);function _(t,n,a,l={}){let u;try{if(a?.throwIfAborted(),n.deferred)throw e(`state`,`Compressed PreparedGLTF requires the asynchronous worker loader; call loadGLTF or parseGLTFAsync`);let o=new s(n.doc,n.buffers,void 0,l,n.maxDownloadBytes,n.maxNodes);o.baseURL=n.baseURL,n.maxPartVertices!==void 0&&(o.partVertices=i(n.maxPartVertices));for(let[e,t]of n.accessors)o.cache.set(e,t);return n.doc.meshes?.forEach((e,t)=>e?.primitives?.forEach((e,r)=>{let i=n.geometry[t]?.[r];i&&e&&typeof e==`object`&&c.set(e,Array.isArray(i)?i:[i])})),u=new r(t,o,n.images),h(t).use(u),u}catch(e){throw u?u.dispose():o(n.images),e}}async function v(e,t,i,s){if(t.deferred){let{asset:c,images:l}=await a(t.baseURL,n({...i,buffers:t.buffers}),t.doc,{device:h(e).gpu??void 0,ktx2:i.ktx2},!1,t.downloadedBytes);if(c.hooks.splats){let t=s.run(()=>new r(e,c,l));try{return s.run(()=>h(e).use(t)),await s.run(()=>t.attachSplats(i.signal)),t}catch(e){throw t.dispose(),e}}try{t=d(c,l)}catch(e){throw o(l),e}}return s.run(()=>_(e,t,i.signal,i.decoders))}var y=()=>new URL(`./workers/gltf.js?no-inline`,import.meta.url);async function b(e,n,r={}){if(!m()||g(r)||r.optimize)return l(e,n,r);let i=t(e);return v(e,await p(y(),{url:new URL(n,globalThis.location.href).href,maxDownloadBytes:r.maxDownloadBytes,maxNodes:r.maxNodes,allowedURLs:r.allowedURLs,maxPartVertices:r.maxPartVertices},r.signal),r,i)}async function x(e,n,r={}){if(!m()||g(r))return u(e,n,r);let i=t(e),a={url:globalThis.location.href,input:typeof n==`object`&&!(n instanceof ArrayBuffer)&&!ArrayBuffer.isView(n)?n:f(n),buffers:r.buffers?.map(f),maxDownloadBytes:r.maxDownloadBytes,maxNodes:r.maxNodes,allowedURLs:r.allowedURLs,maxPartVertices:r.maxPartVertices};return v(e,await p(y(),a,r.signal),r,i)}export{b as loadGLTFInWorker,_ as modelFromPrepared,x as parseGLTFInWorker};