@margoengine/gltf 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1753 -2
  4. package/dist/accessor-CU_1uSZ1.js +1 -0
  5. package/dist/accessor-DuqjpuxI.js +1 -0
  6. package/dist/accessor.d.ts +12 -0
  7. package/dist/asset-DN3ocEdY.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 +395 -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-CUOCmjmE.js +1 -0
  18. package/dist/compression.d.ts +21 -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 +10 -0
  26. package/dist/default-transmission.d.ts +13 -0
  27. package/dist/draco-state.d.ts +7 -0
  28. package/dist/draw-batch.d.ts +83 -0
  29. package/dist/draw-memo.d.ts +136 -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 +18 -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 +95 -0
  37. package/dist/index.js +1 -0
  38. package/dist/instanced-shader-C9ZMazvo.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-GKiHDb0p.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/mipmaps-38NmjDc3.js +21 -0
  61. package/dist/model-C77ATxi1.js +25 -0
  62. package/dist/model-entry.d.ts +2 -0
  63. package/dist/model-entry.js +1 -0
  64. package/dist/model.d.ts +1088 -0
  65. package/dist/native-glass-D85twud0.js +19 -0
  66. package/dist/node-image-decode.d.ts +6 -0
  67. package/dist/node-matrix-R9BipGnp.js +1 -0
  68. package/dist/node-matrix.d.ts +16 -0
  69. package/dist/occlusion.d.ts +8 -0
  70. package/dist/pack-DdxRO8k6.js +1 -0
  71. package/dist/pack.d.ts +27 -0
  72. package/dist/parts.d.ts +54 -0
  73. package/dist/pbr-instancing.d.ts +83 -0
  74. package/dist/pbr-instancing.js +1 -0
  75. package/dist/pbr.d.ts +13 -0
  76. package/dist/pbr.js +1 -0
  77. package/dist/physics.d.ts +148 -0
  78. package/dist/physics.js +1 -0
  79. package/dist/prepare.d.ts +26 -0
  80. package/dist/prepare.js +1 -0
  81. package/dist/progressive-lod.d.ts +13 -0
  82. package/dist/progressive.d.ts +62 -0
  83. package/dist/progressive.js +4 -0
  84. package/dist/progressive.worker.d.ts +1 -0
  85. package/dist/quantized.d.ts +8 -0
  86. package/dist/quantized.js +1 -0
  87. package/dist/render-state.d.ts +18 -0
  88. package/dist/replica.d.ts +37 -0
  89. package/dist/report.d.ts +128 -0
  90. package/dist/report.js +1 -0
  91. package/dist/scene-data.d.ts +61 -0
  92. package/dist/scene-data.js +1 -0
  93. package/dist/scene-scope-CZDEkd24.js +4 -0
  94. package/dist/scene.d.ts +61 -0
  95. package/dist/scene.js +4 -0
  96. package/dist/shader-C29RtPAw.js +409 -0
  97. package/dist/shader.d.ts +246 -0
  98. package/dist/shared/caster.d.ts +159 -0
  99. package/dist/shared/gltf.d.ts +257 -0
  100. package/dist/shared/iridescence.d.ts +2 -0
  101. package/dist/shared/prepared-geometry.d.ts +8 -0
  102. package/dist/side-shader.d.ts +1 -0
  103. package/dist/soft-mesh.d.ts +132 -0
  104. package/dist/soft-mesh.js +4 -0
  105. package/dist/spec-gloss.d.ts +21 -0
  106. package/dist/spec-gloss.js +18 -0
  107. package/dist/splat-state.d.ts +7 -0
  108. package/dist/splats.d.ts +18 -0
  109. package/dist/splats.js +1 -0
  110. package/dist/src-Btvz5f6i.js +4 -0
  111. package/dist/stream-CrfNNCRd.js +1 -0
  112. package/dist/stream.d.ts +104 -0
  113. package/dist/stroke-width-B2cnYGgn.js +1 -0
  114. package/dist/stroke-width.d.ts +18 -0
  115. package/dist/strokes.d.ts +12 -0
  116. package/dist/strokes.js +1 -0
  117. package/dist/texture-coordinates-XFsEMdU6.js +2 -0
  118. package/dist/texture-coordinates.d.ts +26 -0
  119. package/dist/texture-stream-Cu_XpyVO.js +4 -0
  120. package/dist/texture-stream.d.ts +88 -0
  121. package/dist/textured.d.ts +34 -0
  122. package/dist/textured.js +5 -0
  123. package/dist/transmission.d.ts +81 -0
  124. package/dist/transmission.js +66 -0
  125. package/dist/uniform-arena.d.ts +78 -0
  126. package/dist/version-B6NE5cJf.js +1 -0
  127. package/dist/version.d.ts +8 -0
  128. package/dist/vertex-inputs.d.ts +53 -0
  129. package/dist/view-uniform.d.ts +13 -0
  130. package/dist/visibility-C_Oqz9Sr.js +1 -0
  131. package/dist/warning-UqjZyyqW.js +89 -0
  132. package/dist/warning.d.ts +24 -0
  133. package/dist/worker-CY1TQnYX.js +1 -0
  134. package/dist/worker.d.ts +21 -0
  135. package/dist/worker.js +4 -0
  136. package/dist/workers/gltf.js +322 -0
  137. package/dist/workers/progressive.js +1 -0
  138. package/package.json +232 -4
@@ -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 1.0.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-CU_1uSZ1.js";import{r}from"./mesh-source-DvU8YvMc.js";import{t as i}from"./mipmaps-38NmjDc3.js";import{a,i as o,n as s,r as c,t as l}from"./warning-UqjZyyqW.js";import{uploadRows as u}from"@margoengine/core/extension";import{MargoError as d}from"@margoengine/math/errors";var f=`KHR_texture_transform`,p=e=>/* @__PURE__ */ TypeError(`Invalid glTF ${e}; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`),m=e=>new d(`unsupported`,`${e} is not on the light path; load the file with @margoengine/gltf/pbr`);function h(e){let t=Object.keys(e.extensions??{}).filter(e=>e!==f);if(t.length)throw m(`Texture extension ${t[0]}`);let n=e.extensions?.[f];if(!n)return;let[r,i]=n.scale??[1,1],[a,o]=n.offset??[0,0],s=n.rotation??0,c=[Math.cos(s)*r,Math.sin(s)*i,a,-Math.sin(s)*r,Math.cos(s)*i,o];if(!c.every(Number.isFinite))throw p(`texture transform`);return c}function g(t,r){let i=r.pbrMetallicRoughness??{},a=i.baseColorTexture,o=r.alphaMode===`MASK`;if(!a&&!o||!o&&(r.alphaMode??`OPAQUE`)!==`OPAQUE`)return;let s=i.baseColorFactor?.[3]??1,c=o?r.alphaCutoff??.5:0,l={texCoord:0,alpha:s,cutoff:c};if(!(s>=0&&s<=1)||!(c>=0))throw p(`alpha`);if(a){let r=n(t.textures,a.index,`texture`);if(r.extensions&&Object.keys(r.extensions).length)throw m(`A compressed or WebP texture`);l.image=e(r.source,`texture source`),n(t.images,l.image,`image`),r.sampler!==void 0&&n(t.samplers,l.sampler=r.sampler,`sampler`),l.transform=h(a);let i=a.extensions?.[f];l.texCoord=e(i?.texCoord??a.texCoord??0,`texCoord`)}return l}async function _(t,r){let i=n(t.doc.images,r,`image`);if(i.bufferView!==void 0){let r=n(t.doc.bufferViews,i.bufferView,`bufferView`),a=t.buffers[e(r.buffer,`buffer reference`)],o=e(r.byteOffset??0,`view offset`),s=e(r.byteLength,`view length`,1);if(!a||o+s>a.length)throw RangeError(`glTF image is outside its buffer; re-export the file`);return a.subarray(o,o+s)}if(typeof i.uri!=`string`)throw p(`image`);let a=/^data:image\/[a-z+.-]+;base64,([A-Za-z0-9+/]*={0,2})$/.exec(i.uri);if(a)try{return Uint8Array.from(atob(a[1]),e=>e.charCodeAt(0))}catch(e){throw TypeError(`glTF image ${r} has a data: URI with invalid base64; re-export the file`,{cause:e})}if(!t.fetch)throw TypeError(`glTF image URI needs the file location; use loadGLTF`);return t.fetch(i.uri)}async function v(e,t){try{return await createImageBitmap(new Blob([e]),{colorSpaceConversion:`none`,premultiplyAlpha:`none`})}catch(e){throw TypeError(`glTF image ${t} could not be decoded (${e?.message??e}); re-export it as PNG or JPEG`,{cause:e})}}var y=e=>e===33071?`clamp-to-edge`:e===33648?`mirror-repeat`:`repeat`,b=(e={})=>{let t=e.minFilter;return{addressModeU:y(e.wrapS),addressModeV:y(e.wrapT),magFilter:e.magFilter===9728?`nearest`:`linear`,minFilter:t===9728||t===9984||t===9986?`nearest`:`linear`,mipmapFilter:t===9984||t===9985?`nearest`:`linear`,lodMaxClamp:t===9728||t===9729?0:32}};function x(e){let t=`@group(1) @binding(0) var baseMap:texture_2d<f32>;@group(1) @binding(1) var baseSampler:sampler;@group(1) @binding(2) var<uniform> surface:vec4f;
5
+ `+e.replace(`struct Input {`,`struct Input { @location(15) uv:vec2f,`).replace(`struct Output {`,`struct Output { @location(14) uv:vec2f,`).replace(/(@vertex fn vertex\(i:Input\)[\s\S]*?)return o;/,`$1o.uv=i.uv;return o;`).replace(/@fragment fn fragment\(i:Output([^{]*)\{/,`@fragment fn fragment(source:Output$1{var i=source;let texel=textureSample(baseMap,baseSampler,i.uv);if(texel.a*surface.x<surface.y){discard;}i.color*=texel.rgb;`);if(!t.includes(`o.uv=i.uv`)||!t.includes(`var i=source`))throw new d(`failed`,`A package replaced the core shader parts @margoengine/gltf/textured patches; remove that package or load the file with @margoengine/gltf/pbr`);return t}var S=/* @__PURE__ */ new WeakMap,C=class{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);constructor(){this.name=`gltf-textured`,this.parts=/* @__PURE__ */ new Map,this.values=/* @__PURE__ */ new Float32Array(32),this.textures=/* @__PURE__ */ new Map,this.mips=/* @__PURE__ */ new Map,this.pipelines=/* @__PURE__ */ new Map,this.shaders=/* @__PURE__ */ new Map,this.frameGroups=/* @__PURE__ */ new WeakMap,this.color={view:null,loadOp:`load`,storeOp:`store`},this.depth={view:null}}setup(e){if(!e.gpu)throw new d(`unsupported`,`Textured glTF needs WebGPU or the WebGL2 compatibility layer; call install() from @margoengine/webgl2-compat before Engine.create where WebGPU is missing; see https://margoengine.com/errors#webgpu`);this.engine=e,this.frame=e.gpu.createBuffer({size:128,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST})}registerPasses(e){e.add({name:`gltf-textured:claim`,order:-1e6,execute:e=>{e.backend===`webgpu`&&this.claim(e)}}),e.add({name:`gltf-textured:draw`,order:.5,joins:!0,execute:e=>{e.backend===`webgpu`&&this.draw(e)}})}add(e){this.parts.set(e.geometry,e),this.upload(e)}remove(e){if(this.parts.delete(e.geometry),r(e.geometry,void 0),e.uvBuffer?.destroy(),e.block?.destroy(),e.casterBuffer?.destroy(),e.bitmap&&![...this.parts.values()].some(t=>t.bitmap===e.bitmap)){for(let t of this.textures.get(e.bitmap)?.values()??[])t.destroy();this.textures.delete(e.bitmap)}}texture(e,t,n=0){let r=this.engine.gpu,a=e?this.textures.get(e)?.get(n):this.white;if(a)return a;let{width:s,height:c}=e??{width:1,height:1},l=r.limits.maxTextureDimension2D;if(s>l||c>l)throw RangeError(`glTF image is ${s} x ${c}, over this GPU's ${l}; resize it`);let u=Math.floor(Math.log2(Math.max(s,c)))+1,d=r.createTexture({size:[s,c],format:`rgba8unorm-srgb`,mipLevelCount:u,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT});if(e){r.queue.copyExternalImageToTexture({source:e},{texture:d},[s,c]),n&&t?o(r,d,u,this.mips,t.cutoff,t.alpha):i(r,d,u,this.mips);let a=this.textures.get(e);a||this.textures.set(e,a=/* @__PURE__ */ new Map),a.set(n,d)}else r.queue.writeTexture({texture:d},new Uint8Array([255,255,255,255]),{},[1,1]),this.white=d;return d}upload(e){e.keep=e.bitmap&&e.sampler.lodMaxClamp!==0?a(e.surface.cutoff,e.surface.alpha):0;let t=this.engine.gpu,n=this.texture(e.bitmap,e.surface,e.keep);r(e.geometry,{uv:e.uv,caster:e.surface.cutoff>0?this.caster(e,n):void 0}),e.uvBuffer=t.createBuffer({size:e.uv.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),t.queue.writeBuffer(e.uvBuffer,0,e.uv),e.block=t.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),t.queue.writeBuffer(e.block,0,new Float32Array([e.surface.alpha,e.surface.cutoff,0,0])),e.groups=/* @__PURE__ */ new WeakMap,e.sent=!1}caster(e,t){let n=this.engine.gpu,r=e.geometry.vertices,i=r.length/6,a=new Float32Array(i*20);for(let t=0;t<i;t++)a.set(r.subarray(t*6,t*6+3),t*20),a.set(e.uv.subarray(t*2,t*2+2),t*20+12);return e.casterBuffer=n.createBuffer({size:a.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),n.queue.writeBuffer(e.casterBuffer,0,a),{vertex:e.casterBuffer,stride:80,alphaTexture:t.createView(),alphaSampler:n.createSampler(e.sampler),alpha:e.surface.alpha,cutoff:e.surface.cutoff,vertexAlpha:!1}}claim(e){let t=e.batches??[];for(let n=0;n<t.length;n++){let r=t[n],i=this.parts.get(r.geometry);i&&(!r.claimed&&(r.count||r.redirect)&&this.engine.stats.drawCalls--,r.claimed=!0,u(e.device.queue,this.engine.geometryBuffers(r.geometry).instance,r,!i.sent),i.sent=!0)}}pipeline(e){let t=e.descriptor,n=`${t.multisample?.count} ${e.format} ${t.depthStencil?.format} ${e.shader}`,r=this.pipelines.get(n);if(!r){let i=e.device.createShaderModule({code:this.shaderFor(e.shader)});r=e.device.createRenderPipeline({...t,vertex:{...t.vertex,module:i,buffers:[...t.vertex.buffers,{arrayStride:8,attributes:[{shaderLocation:15,offset:0,format:`float32x2`}]}]},fragment:{...t.fragment,module:i,targets:[{format:e.format}]}}),this.pipelines.set(n,r)}return r}shaderFor(e){let t=this.shaders.get(e);return t===void 0&&this.shaders.set(e,t=x(e)),t}frameGroup(e,t){let n=this.frameGroups.get(t),r=e.bindings;if(n&&n.bindings.length===r.length&&n.bindings.every((e,t)=>e.binding===r[t].binding&&e.resource===r[t].resource))return n.group;let i=e.device.createBindGroup({layout:t.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:this.frame}},...r]});return this.frameGroups.set(t,{group:i,bindings:[...r]}),i}surfaceGroup(e,t,n){let r=n.groups.get(t);return r||(r=e.device.createBindGroup({layout:t.getBindGroupLayout(1),entries:[{binding:0,resource:this.texture(n.bitmap,n.surface,n.keep).createView()},{binding:1,resource:e.device.createSampler(n.sampler)},{binding:2,resource:{buffer:n.block}}]}),n.groups.set(t,r)),r}draw(e){let t=e.batches??[],n,r;for(let i=0;i<t.length;i++){let a=t[i],o=this.parts.get(a.geometry);if(!o||!a.count&&!a.redirect)continue;if(!n){r=this.pipeline(e);let{direction:t,radiance:i,ambient:a}=this.engine.lighting,o=this.values;o.set(e.camera.matrix),o.set(e.camera.position,16),c(o,20,t),o.set(i,24),o.fill(1,28,31),a&&o.set(a,28),e.device.queue.writeBuffer(this.frame,0,o);let s=this.color,l=this.depth,u=e.descriptor.depthStencil.format.includes(`stencil`);s.view=e.color,s.loadOp=`load`,s.storeOp=`store`,s.resolveTarget=void 0,l.view=e.depth,l.depthLoadOp=`load`,l.depthStoreOp=`store`,l.stencilLoadOp=u?`load`:void 0,l.stencilStoreOp=u?`store`:void 0,e.attach?.(s,l,!0),n=e.encoder.beginRenderPass({colorAttachments:[s],depthStencilAttachment:l});let d=e.view;d&&(n.setViewport(...d.viewport,0,1),n.setScissorRect(...d.scissor??d.viewport)),n.setPipeline(r),n.setBindGroup(0,this.frameGroup(e,r))}let s=this.engine.geometryBuffers(a.geometry),l=a.redirect;n.setBindGroup(1,this.surfaceGroup(e,r,o)),n.setVertexBuffer(0,s.vertex),n.setVertexBuffer(1,l?.instances??s.instance),n.setVertexBuffer(2,o.uvBuffer),n.setIndexBuffer(s.index,`uint32`),l?n.drawIndexedIndirect(l.args,0):n.drawIndexed(a.geometry.indices.length,a.count),this.engine.stats.drawCalls++}n?.end()}onDeviceRestored(e){this.release(),this.setup(e);for(let e of this.parts.values())this.upload(e)}release(){this.frame?.destroy(),this.white?.destroy(),this.white=void 0;for(let e of this.textures.values())for(let t of e.values())t.destroy();this.textures.clear(),this.mips=/* @__PURE__ */ new Map,this.pipelines.clear()}dispose(){this.release();for(let e of this.parts.values())r(e.geometry,void 0),e.uvBuffer?.destroy(),e.block?.destroy(),e.casterBuffer?.destroy();this.parts.clear()}},w=/* @__PURE__ */ new WeakMap,T=/* @__PURE__ */ new WeakMap;function E(e){if(typeof OffscreenCanvas>`u`)throw TypeError(`texturedAlphaMasks needs OffscreenCanvas to read an image here; pass the pixels option.`);let t=new OffscreenCanvas(e.width,e.height).getContext(`2d`,{willReadFrequently:!0});return t.drawImage(e,0,0),t.getImageData(0,0,e.width,e.height)}var D=e=>e===`clamp-to-edge`?`clamp`:e===`mirror-repeat`?`mirror`:`repeat`;async function O(e,{signal:t,pixels:n=E}={}){let r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map;for(let a of T.get(e)??[]){t?.throwIfAborted();let{surface:e,bitmap:o,sampler:s,geometry:c}=a;if(!(e.cutoff>0))continue;let l={width:1,height:1,data:[255,255,255,255]};o&&(l=i.get(o)??await n(o),i.set(o,l)),r.set(c,{width:l.width,height:l.height,data:l.data,cutoff:e.cutoff,factor:e.alpha,wrap:[D(s.addressModeU),D(s.addressModeV)]})}return t?.throwIfAborted(),e=>r.get(e.mesh.geometry)??null}var k={handles:[f],async load(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map;w.set(e,{images:n,surfaces:t}),(e.doc.materials??[]).forEach((n,r)=>{let i=g(e.doc,n);i&&t.set(r,i)});let r=new Set([...t.values()].flatMap(({image:e})=>e===void 0?[]:[e])),i=(await Promise.allSettled([...r].map(async t=>{n.set(t,await v(await _(e,t),t))}))).find(e=>e.status===`rejected`);if(i)throw k.abandon(e),i.reason},abandon(e){let t=w.get(e);if(w.delete(e),t&&!t.owned)for(let e of t.images.values())e.close()},read(e){let{surfaces:t}=w.get(e);e.doc={...e.doc,materials:e.doc.materials?.map((e,n)=>{if(!t.has(n))return e;let{alphaMode:r,alphaCutoff:i,...a}=e,{baseColorTexture:o,baseColorFactor:s=[1,1,1,1],...c}=e.pbrMetallicRoughness??{};return{...a,pbrMetallicRoughness:{...c,baseColorFactor:[s[0],s[1],s[2],1]}}})}},finish(e,n,r){let i=w.get(n),{images:a,surfaces:o}=i,c=r.engine,u=[];for(let{geometry:i,source:c,expanded:d}of r.primitives){let r=c.material===void 0?void 0:o.get(c.material);if(!r)continue;let f=c.attributes?.[`TEXCOORD_${r.texCoord}`],p=r.image!==void 0&&f===void 0;p&&l(e.warnings,s(c.material,n.doc.materials?.[c.material]?.name,`baseColorTexture`,r.texCoord));let m=r.image===void 0||f===void 0?new Float32Array(i.vertices.length/6*2):t(n,f,2,e=>e.type===`VEC2`&&[5126,5120,5121,5122,5123].includes(e.componentType)),h=i.vertices.length/6,g=new Float32Array(h*2),_=r.transform??[1,0,0,0,1,0];for(let e=0;e<h;e++){let t=d?d[e]:e,n=m[t*2],r=m[t*2+1];if(n===void 0||r===void 0)throw RangeError(`glTF TEXCOORD has fewer vertices than POSITION; re-export the file`);g[e*2]=_[0]*n+_[1]*r+_[2],g[e*2+1]=_[3]*n+_[4]*r+_[5]}u.push({geometry:i,uv:g,surface:r,bitmap:r.image===void 0||p?void 0:a.get(r.image),sampler:b(r.sampler===void 0?void 0:n.doc.samplers?.[r.sampler]),keep:0,groups:/* @__PURE__ */ new WeakMap,sent:!1})}if(!u.length)return;let d=c.frameGraph,f=S.get(d);f||(f=new C,c.use(f),S.set(d,f));let p=f,m=()=>{p.parts.size||(S.delete(d),c.sceneOf(p)?.removePlugin(p.name))};try{for(let e of u)p.add(e)}catch(e){for(let e of u)p.parts.get(e.geometry)===e&&p.remove(e);throw m(),e}i.owned=!0,T.set(e,u);let h=e.dispose,g=!0;e.dispose=()=>{if(g){g=!1;for(let e of u)p.remove(e);for(let e of a.values())e.close();m()}h()}}};export{k as textured,O as texturedAlphaMasks};
@@ -0,0 +1,81 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel } from '@margoengine/core';
3
+ import { type Engine, type EnginePlugin, type FrameGraph, type PassContext } from '@margoengine/core/extension';
4
+ import type { PBRModel, PBRTransmission } from './model.js';
5
+ import type { GLTFTransmissionPass } from './asset.js';
6
+ type Context = Extract<PassContext, {
7
+ backend: 'webgpu';
8
+ }>;
9
+ /** Options for `Transmission.attach()`: the frame graph `order` (default 3) and `depthWrite` (default false). */
10
+ export interface TransmissionPassOptions {
11
+ /** Frame graph order of the copy and the transmissive draws: after the opaque scene (1) and sky (2), before water (4), fog (5) and OIT (8). Default 3. */
12
+ order?: number;
13
+ /**
14
+ * True: OPAQUE and MASK glass draws unblended and writes depth, so a glass surface hides glass behind it (a solid
15
+ * sphere's back faces and their highlights) whatever the draw order, and later passes (water, fog, OIT) see the glass
16
+ * depth. BLEND glass stays blended without writes. Default false: every surface blends, depth read-only.
17
+ */
18
+ depthWrite?: boolean;
19
+ }
20
+ /**
21
+ * Real transmission: `transmission.add(model)` makes a gltf/pbr model's or materials mesh's transmissive surfaces refract
22
+ * the opaque scene behind them, blurred by roughness and attenuated through `thickness` of the volume, instead of tinting
23
+ * the background. It reads the view's scene capture: an HDR or display PostStack target, or gltf's native glass capture of
24
+ * the display target (decoded to linear light). A view with neither (an environment probe face, an external renderer
25
+ * pass) keeps the tinted blend (`takes`). The scene is copied (a mip chain) only on frames where a transmissive surface
26
+ * draws. WebGPU only.
27
+ */
28
+ export declare class Transmission implements EnginePlugin, PBRTransmission {
29
+ readonly name: string;
30
+ readonly order: number;
31
+ readonly depthWrite: boolean;
32
+ targets: readonly GPUColorTargetState[];
33
+ private engine?;
34
+ /** Device of the current GPU resources, so a release after device restoration retires them on their own device. */
35
+ private device?;
36
+ private disposed;
37
+ private readonly models;
38
+ private readonly code;
39
+ private readonly formats;
40
+ private texture?;
41
+ private view?;
42
+ private levels;
43
+ private reduceGroups;
44
+ private source?;
45
+ private sourceGroup?;
46
+ private sampler?;
47
+ private pipelines?;
48
+ private sourcePipeline?;
49
+ private context?;
50
+ private pass?;
51
+ /** Reused back-to-front list. Filled from the model map each frame so equal distances stay in insertion order. */
52
+ private readonly ordered;
53
+ static attach(engine: EngineKernel, options?: TransmissionPassOptions): Transmission;
54
+ constructor({ order, depthWrite }?: TransmissionPassOptions);
55
+ /** Refracts the scene through the model's transmissive primitives (gltf\/pbr model or materials mesh). Returns a remover. */
56
+ add(model: PBRModel): () => void;
57
+ setup(engine: Engine): void;
58
+ registerPasses(graph: FrameGraph): void;
59
+ /** @internal gltf\/pbr transmission hook. */
60
+ declarations(group: number): string;
61
+ /** @internal gltf\/pbr transmission hook. */
62
+ bindings(): GPUBindGroupEntry[];
63
+ /** @internal gltf\/pbr transmission hook: copies the scene, then begins the pass the transmissive surfaces draw in. */
64
+ begin(): GPURenderPassEncoder;
65
+ /** @internal gltf\/pbr transmission hook: whether this view has a scene to read (else its surfaces keep the tint). */
66
+ takes(c: Context): boolean;
67
+ private render;
68
+ private release;
69
+ onDeviceRestored(engine: Engine): void;
70
+ /** Restores the tinted blend on every added model and frees the scene copy. */
71
+ dispose(): void;
72
+ [Symbol.dispose]: () => void;
73
+ }
74
+ /**
75
+ * The default screen-space transmission of `loadGLTF` and `parseGLTFAsync` (`decoders.transmission`): every model
76
+ * whose file declares KHR_materials_transmission joins one `Transmission` per scene, created with `depthWrite: true`,
77
+ * which goes away with the last such model. Pass it to synchronous `parseGLTF` as
78
+ * `{materials: extendedMaterials, transmission: screenTransmission}`; `{transmission: false}` keeps the tinted blend.
79
+ */
80
+ export declare const screenTransmission: GLTFTransmissionPass;
81
+ export {};
@@ -0,0 +1,66 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const s=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import{n as e}from"./mipmaps-38NmjDc3.js";import{f as t,i as n,l as r,o as i,p as a,s as o}from"./native-glass-D85twud0.js";import{engineRuntime as __margoRuntime,margoError as c}from"@margoengine/core/extension";var l=((254.5/255+.055)/1.055)**2.4;.56+.0576/(1-l);var u=`fn pbrNeutralInverse(input:vec3f)->vec3f {let top=${l};var peak=max(input.r,max(input.g,input.b));var v=max(input*select(1.0,top/peak,peak>top),vec3f(0.0));peak=min(peak,top);if(peak>=0.76){let old=0.52+0.24*0.24/(1.0-peak);let keep=1.0/(0.15*(old-peak)+1.0);v=(v-peak*(1.0-keep))/keep*old/peak;}let m=min(v.r,min(v.g,v.b));return v+select(0.04,0.4*sqrt(max(m,0.0))-m,m<0.04);}
5
+ `,d=/* @__PURE__ */ Object.freeze({color:{srcFactor:`src-alpha`,dstFactor:`one-minus-src-alpha`,operation:`add`},alpha:{srcFactor:`one`,dstFactor:`one-minus-src-alpha`,operation:`add`}});function f(e,t,n){let r=e.get(t);return r===void 0&&e.set(t,r=n(t)),r}var p=124,m=e=>`
6
+ @group(${e}) @binding(${p}) var margoScene:texture_2d<f32>;
7
+ @group(${e}) @binding(125) var margoSceneSampler:sampler;
8
+ fn margoTransmissionBehind(i:Out,n:vec3f,v:vec3f,ior:f32,path:f32,level:f32)->vec3f {
9
+ let r=refract(-v,faceForward(n,-v,n),1.0/ior);
10
+ let c=f.camera*vec4f(i.position+r*path,1.0);
11
+ let uv=clamp(c.xy/max(c.w,0.000001)*vec2f(0.5,-0.5)+0.5,vec2f(0),vec2f(1));
12
+ return textureSampleLevel(margoScene,margoSceneSampler,uv,level).rgb;
13
+ }
14
+ fn margoTransmissionLevel(roughness:f32,ior:f32,path:f32)->f32 {
15
+ let size=vec2f(textureDimensions(margoScene,0));
16
+ let alpha=roughness*roughness;
17
+ let sinTilt=alpha*inverseSqrt(1.0+alpha*alpha);
18
+ let sinOut=sinTilt/ior;
19
+ let tanOut=sinOut*inverseSqrt(1.0-sinOut*sinOut);
20
+ let deviation=max((alpha-tanOut)/(1.0+alpha*tanOut),0.0);
21
+ let wRow=vec3f(f.camera[0].w,f.camera[1].w,f.camera[2].w);
22
+ let yRow=vec3f(f.camera[0].y,f.camera[1].y,f.camera[2].y);
23
+ let reach=select(path,1.0,dot(wRow,wRow)>0.0);
24
+ let texels=deviation*reach*length(yRow)*size.y;
25
+ return clamp(log2(max(texels,1.0)),0.0,f32(textureNumLevels(margoScene)-1u));
26
+ }
27
+ fn margoVolumeChord(i:Out,n:vec3f,v:vec3f,ior:f32)->f32 {
28
+ let m=mat3x3f(f.model[0].xyz,f.model[1].xyz,f.model[2].xyz);
29
+ let r=refract(-v,faceForward(n,-v,n),1.0/ior);
30
+ let c0=cross(m[1],m[2]); let c1=cross(m[2],m[0]); let c2=cross(m[0],m[1]);
31
+ let normal=normalize(vec3f(dot(m[0],i.normal),dot(m[1],i.normal),dot(m[2],i.normal)));
32
+ let projected=abs(dot(vec3f(dot(c0,r),dot(c1,r),dot(c2,r)),normal));
33
+ return select(abs(dot(m[0],c0))/projected,1e30,projected==0.0);
34
+ }
35
+ fn margoTransmission(s:Surface,v:vec3f,i:Out)->vec3f {
36
+ let ior=select(max(f.ext.y,1.0),1e30,f.ext.y==0.0);
37
+ let path=max(margoVolume.x*s.th*margoVolumeThickness(i)*margoVolumeChord(i,s.n,v,ior),0.0);
38
+ var behind=margoTransmissionBehind(i,s.n,v,ior,path,margoTransmissionLevel(s.roughness,ior,path));
39
+ if(f.ext.w>0.0&&path>0.0){
40
+ let spread=(ior-1.0)*0.025*f.ext.w;
41
+ let red=max(1.0,ior-spread); let blue=ior+spread;
42
+ behind=vec3f(margoTransmissionBehind(i,s.n,v,red,path,margoTransmissionLevel(s.roughness,red,path)).r,behind.g,margoTransmissionBehind(i,s.n,v,blue,path,margoTransmissionLevel(s.roughness,blue,path)).b);
43
+ }
44
+ var transmittance=vec3f(1.0);
45
+ if(path>0.0){
46
+ let t=margoVolume.yzw;
47
+ transmittance=select(select(pow(max(t,vec3f(0.000001)),vec3f(path)),vec3f(0.0),t<=vec3f(0.0)),vec3f(1.0),t>=vec3f(1.0));
48
+ }
49
+ let keep=1.0-margoFresnelPeak(margoDielectricFresnel(s.f0,s.sw,clamp(dot(s.n,v),0.0,1.0)));
50
+ return (1.0-s.metal)*s.tr*keep*s.base.rgb*transmittance*behind;
51
+ }
52
+ `,h=`
53
+ @group(0) @binding(0) var source:texture_2d<f32>;
54
+ @vertex fn vertex(@builtin(vertex_index) k:u32)->@builtin(position) vec4f {
55
+ let corner=vec2f(f32((k<<1u)&2u),f32(k&2u));
56
+ return vec4f(corner*2.0-1.0,0.0,1.0);
57
+ }
58
+ @fragment fn level0(@builtin(position) p:vec4f)->@location(0) vec4f {
59
+ return textureLoad(source,vec2i(p.xy),0);
60
+ }
61
+ @fragment fn level0Display(@builtin(position) p:vec4f)->@location(0) vec4f {
62
+ let c=textureLoad(source,vec2i(p.xy),0);
63
+ let x=clamp(c.rgb,vec3f(0.0),vec3f(1.0));
64
+ return vec4f(pbrNeutralInverse(select(x/12.92,pow((x+0.055)/1.055,vec3f(2.4)),x>vec3f(0.04045))),c.a);
65
+ }
66
+ ${u}`,g=d,_=0,v=class l{coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);static attach(e,t){__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));let n=new l(t);return s(e).use(n),n}constructor({order:e=3,depthWrite:t=!1}={}){if(this.name=`transmission:`+_++,this.targets=[],this.disposed=!1,this.models=/* @__PURE__ */ new Map,this.code=/* @__PURE__ */ new Map,this.formats=/* @__PURE__ */ new Map,this.levels=[],this.reduceGroups=[],this.ordered=[],!Number.isFinite(e)||e<=0)throw RangeError(`Transmission order must be a number > 0`);if(typeof t!=`boolean`)throw TypeError(`Transmission depthWrite must be true or false`);this.order=e,this.depthWrite=t}add(e){if(this.disposed||!this.engine)throw c(this.disposed?`disposed`:`state`,this.disposed?`Transmission is disposed; create a new Transmission.`:`Transmission.add needs Transmission.attach(engine) first`);let t=this.models.get(e);if(!t){let n=e.setTransmission(this),r=e.onDispose(()=>this.models.delete(e));t=()=>{this.models.get(e)===t&&(this.models.delete(e),r(),n())},this.models.set(e,t)}return t}setup(e){if(this.disposed)throw c(`disposed`,`Transmission is disposed; create a new Transmission.`);if(!e.gpu)throw c(`unsupported`,`Transmission requires WebGPU: create the engine with a WebGPU device; see https://margoengine.com/errors#webgpu`);this.engine=e,this.device=e.gpu}registerPasses(e){e.add({name:this.name,order:this.order,execute:e=>{e.backend===`webgpu`&&this.render(e)}})}declarations(e){return f(this.code,e,m)}bindings(){return[{binding:p,resource:this.view},{binding:125,resource:this.sampler}]}begin(){if(this.pass)return this.pass;let e=this.context,t=o(e),r=e.encoder,s=this.pipelines;t?.resolve(r);let c=t?t.resolvedColor:n(e).resolved(e);this.source!==c&&(this.source=c,this.sourcePipeline=i(c.format)||c.format.endsWith(`-srgb`)?s.level0:s.display,this.sourceGroup=e.device.createBindGroup({layout:this.sourcePipeline.getBindGroupLayout(0),entries:[{binding:0,resource:c.createView()}]}));for(let e=0;e<this.levels.length;e++){let t=r.beginRenderPass({label:`transmission:copy`,colorAttachments:[{view:this.levels[e],loadOp:`clear`,storeOp:`store`,clearValue:[0,0,0,0]}]});t.setPipeline(e?s.reduce:this.sourcePipeline),t.setBindGroup(0,e?this.reduceGroups[e-1]:this.sourceGroup),t.draw(3),t.end()}return this.pass=r.beginRenderPass({label:`transmission`,colorAttachments:[{view:e.color,loadOp:`load`,storeOp:`store`}],depthStencilAttachment:this.depthWrite?{view:e.depth,depthLoadOp:`load`,depthStoreOp:`store`,stencilReadOnly:!0}:{view:e.depth,depthReadOnly:!0,stencilReadOnly:!0}}),a(this.pass,e),this.pass}takes(e){return!this.disposed&&(!!o(e)||!!n(e)?.resolved?.(e,!1))}render(t){if(r(t.device,t.view??t),this.disposed||!this.models.size||!this.takes(t))return;let n=t.device;if(!this.pipelines){let t=(e,t)=>{let r=n.createShaderModule({code:e});return n.createRenderPipeline({label:`transmission:copy`,layout:`auto`,vertex:{module:r,entryPoint:`vertex`},fragment:{module:r,entryPoint:t,targets:[{format:`rgba16float`}]}})};this.pipelines={level0:t(h,`level0`),display:t(h,`level0Display`),reduce:t(e(!1),`fragment`)},this.sampler=n.createSampler({magFilter:`linear`,minFilter:`linear`,mipmapFilter:`linear`})}if(this.texture?.width!==t.width||this.texture.height!==t.height){this.release();let e=Math.floor(Math.log2(Math.max(t.width,t.height)))+1,r=this.texture=n.createTexture({label:`transmission:scene`,size:[t.width,t.height],format:`rgba16float`,mipLevelCount:e,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.RENDER_ATTACHMENT});this.view=r.createView(),this.levels=Array.from({length:e},(e,t)=>r.createView({baseMipLevel:t,mipLevelCount:1})),this.reduceGroups=this.levels.slice(0,-1).map(e=>n.createBindGroup({layout:this.pipelines.reduce.getBindGroupLayout(0),entries:[{binding:0,resource:e}]}))}let i=this.formats.get(t.format);i||this.formats.set(t.format,i=[{format:t.format,blend:g}]),this.targets=i;let a=t.camera.position,o=e=>{let t=e.root.matrix;return Math.hypot(a[0]-t[12],a[1]-t[13],a[2]-t[14])};this.context=t,this.pass=void 0;let s=this.ordered;s.length=0;for(let e of this.models.keys())s.push(e);s.sort((e,t)=>o(t)-o(e));try{for(let e=0;e<s.length;e++)s[e].draw(t,`transmission`,t.color,t.depth)}finally{this.context=void 0,this.pass?.end(),this.pass=void 0,s.length=0}}release(){t(this.device,this.texture),this.texture=this.view=this.source=this.sourceGroup=this.sourcePipeline=void 0,this.levels=[],this.reduceGroups=[]}onDeviceRestored(e){this.release(),this.pipelines=void 0,this.setup(e)}dispose(){if(!this.disposed){this.disposed=!0;for(let e of[...this.models.values()])e();this.release(),this.pipelines=void 0,this.engine?.sceneOf(this)?.removePlugin(this.name)}}[Symbol.dispose??Symbol()](){this.dispose()}},y=/* @__PURE__ */ new WeakMap,b={attach(e,t,n){let r=y.get(n);if(!r){let e=new v({depthWrite:!0}),i;for(let e of t.scenes)e.frameGraph===n&&(i=e);i?t.use(e,i):t.use(e),y.set(n,r={pass:e,users:/* @__PURE__ */ new Set})}let i=r,a=i.pass.add(e);return i.users.add(e),()=>{a(),i.users.delete(e)&&!i.users.size&&(y.get(n)===i&&y.delete(n),i.pass.dispose())}}};export{v as Transmission,b as screenTransmission};
@@ -0,0 +1,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 @@
1
+ import{fault as e,margoError as t,typeError as n}from"@margoengine/math/helpers";var r=class{constructor(...e){this.failed=e.length>0,this.error=e[0]}run(e){try{e()}catch(e){this.failed||(this.error=e),this.failed=!0}return this}finish(){if(this.failed)throw this.error}};async function i(e,{maxBytes:t,signal:n,label:i=`Asset`,output:a=null,expected:o=0}){if(!Number.isSafeInteger(t)||t<0||a!==null&&(!(a instanceof Uint8Array)||a.length!==t))throw RangeError(`Invalid asset byte budget; pass maxBytes as an integer`);if(n?.throwIfAborted(),!e)throw TypeError(`Empty ${i} response; check the URL`);let s=e.getReader(),c=[],l=0,u=a,d=new r,f=e=>{try{Promise.resolve(s.cancel(e)).catch(()=>{})}catch{}},p=()=>f(n.reason);n?.addEventListener(`abort`,p,{once:!0});try{for(!a&&Number.isSafeInteger(o)&&o>0&&o<=t&&(u=new Uint8Array(o));;){n?.throwIfAborted();let{done:e,value:r}=await s.read();if(n?.throwIfAborted(),e)break;if(!(r instanceof Uint8Array))throw TypeError(`${i} stream requires byte chunks`);if(r.byteLength>t-l)throw RangeError(`${i} byte budget exceeded; raise maxBytes`);u&&r.length<=u.length-l?u.set(r,l):(u&&c.push(u.subarray(0,l)),u=null,c.push(r.length<r.buffer.byteLength||!(r.buffer instanceof ArrayBuffer)?r.slice():r)),l+=r.byteLength}}catch(e){f(e),d=new r(e)}if(d.run(()=>n?.removeEventListener(`abort`,p)).run(()=>s.releaseLock()).finish(),a)return a.subarray(0,l);if(u)return l<u.length?u.slice(0,l):u;let m=new Uint8Array(l),h=0;for(let e of c)m.set(e,h),h+=e.length;return m}async function a(e,n){try{if(n.signal?.throwIfAborted(),!e.ok)throw t(`failed`,`${n.label??`Asset`} request failed: HTTP ${e.status}; check the URL and that the server serves it`);let r=Number(e.headers.get(`content-length`));if(Number.isFinite(r)&&r>n.maxBytes)throw RangeError(`${n.label??`Asset`} byte budget exceeded; raise maxBytes`);let i=e.headers.get(`content-encoding`);(!i||i===`identity`)&&(n={...n,expected:r})}catch(t){try{Promise.resolve(e.body?.cancel(t)).catch(()=>{})}catch{}throw t}return i(e.body,n)}var o=/"(?:__proto__|constructor|prototype)"|\\u/,s=(e,t)=>e===`__proto__`||e===`constructor`||e===`prototype`?void 0:t,c=e=>o.test(e)?JSON.parse(e,s):JSON.parse(e),l=/%2f|%5c|%00|\u0000|(^|\/)(\.|%2e){1,2}(\/|$)/i;function u(e){for(let t=0;t<8;t++){if(l.test(e))return!0;let t=e.replace(/%[\da-f]{2}/gi,e=>String.fromCharCode(`0x${e.slice(1)}`));if(t===e)return!1;e=t}return!0}function d(e,t){let n;try{n=new URL(t)}catch{throw TypeError(`allowedURLs entry ${String(t)} is not an absolute URL; pass a full http(s) URL`)}if(n.origin!==e.origin||n.protocol!==`http:`&&n.protocol!==`https:`||n.search&&n.search!==e.search)return!1;let r=n.pathname;return r.endsWith(`/`)?e.pathname.startsWith(r):e.pathname===r||e.pathname.startsWith(`${r}/`)}function f(e,t,n=[],r=`Asset`){if(typeof e!=`string`||!e||e.length>8192)throw TypeError(`Invalid ${r} URI; pass a shorter string`);let i;try{i=new URL(e,t)}catch{throw TypeError(`Invalid ${r} URI; pass a valid URL`)}if((i.protocol===`http:`||i.protocol===`https:`)&&!u(i.pathname)){for(let e of n)if(d(i,e))return i;let e=t===void 0?void 0:new URL(`.`,t);if(e&&i.origin===e.origin&&i.pathname.startsWith(e.pathname))return i}throw TypeError(`${r} URI ${i.href} leaves the model's directory; add its prefix to allowedURLs to load it`)}function p(e,t,n=[],r=`Asset`){if(!e.url)return e;try{f(e.url,t,n,r)}catch{throw e.body?.cancel().catch(()=>{}),TypeError(`${r} URI redirected to ${e.url}, which leaves the model's directory; add its prefix to allowedURLs to load it`)}return e}var m=1179937895,h=1313821514,g=5130562,_=e=>n(`GLB ${e}; pass a whole glTF 2.0 GLB file`,`failed`);function v(t,n){if(Number.isSafeInteger(n)&&t>n+3)throw e(`failed`,`GLB BIN chunk holds ${t} bytes, more than buffer 0's byteLength ${n} plus 3 padding bytes; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`)}var y=e=>e.length>=4&&new DataView(e.buffer,e.byteOffset,4).getUint32(0,!0)===1179937895;function b(e){if(e.length<20)throw _(`needs at least 20 bytes for its 12-byte file header and 8-byte JSON chunk header; received ${e.length}`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=t.getUint32(0,!0),r=t.getUint32(4,!0),i=t.getUint32(8,!0);if(n!==1179937895)throw _(`header magic 0x${n.toString(16)} is not glTF (0x46546c67)`);if(r!==2)throw _(`header version ${r} is unsupported; use version 2`);if(i!==e.length)throw _(`header total length ${i} bytes differs from the received ${e.length} bytes`);let a=[];for(let n=12;n<e.length;){if(n+8>e.length)throw _(`ends inside the 8-byte chunk header at byte ${n}`);let r=t.getUint32(n,!0),i=t.getUint32(n+4,!0),o=n+8+r;if(r%4)throw _(`chunk length ${r} at byte ${n} must have 4-byte alignment`);if(o>e.length)throw _(`chunk length ${r} at byte ${n} extends past the ${e.length}-byte file`);if(a.length===0!=(i===1313821514)||i===5130562&&a.length!==1)throw _(`chunks must be JSON first, then at most one BIN second; export the file again`);a.push({type:i,data:e.subarray(n+8,o)}),n=o}return a}function x(e){let t=/^(\d+)\.(\d+)$/,n=typeof e?.version==`string`?t.exec(e.version):null;if(!n||n[1]!==`2`)return!1;if(e.minVersion===void 0)return!0;let r=typeof e.minVersion==`string`?t.exec(e.minVersion):null;return!!r&&r[1]===`2`&&r[2]===`0`}export{v as a,f as c,a as d,r as f,m as i,p as l,g as n,b as o,h as r,y as s,x as t,c as u};
@@ -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,53 @@
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
+ /**
10
+ * `code` with each missing map's texture read left as its constant, whole or as a normal's xyz*2-1, in a `const`:
11
+ * Firefox fails a pipeline with overrides over a `let` holding a constant composite read by component
12
+ * (KB-FF-CONSTLET5). Runs on the final text, after the patches that anchor on the `let`.
13
+ */
14
+ export declare function constantReads(code: string): string;
15
+ /** Vertex buffer slot of the third and fourth UV sets, past the instance buffer's: unused slots between stay empty. */
16
+ export declare const laterUVSlot = 2;
17
+ /** Their layout: one vec4 a vertex, TEXCOORD_2 then TEXCOORD_3. */
18
+ export declare const laterUVLayout: GPUVertexBufferLayout;
19
+ /**
20
+ * `code`, as trimmed by `vertexInputs`, reading TEXCOORD_2 and 3 as well: a second vertex buffer feeds `Out.uvs`, and every
21
+ * choice between the two sets of `Out.uv` becomes a choice among four. Only a draw whose material reads a later set
22
+ * compiles this. Output location 15 is free of every patch that adds outputs.
23
+ */
24
+ export declare function laterUVShader(code: string): string;
25
+ /**
26
+ * True when every vertex of `vertices` (80-byte PBR, 20 floats a vertex) from vertex `start` on, `count` of them, has
27
+ * the colour (1, 1, 1, 1): what a primitive without COLOR_0 packs. Stops at the first other colour.
28
+ */
29
+ export declare function whiteColours(vertices: Float32Array, start?: number, count?: number): boolean;
30
+ /** True when every vertex of `vertices` from vertex `start` on, `count` of them, has colour alpha 1 (COLOR_0 absent included). */
31
+ export declare function opaqueColours(vertices: Float32Array, start?: number, count?: number): boolean;
32
+ /**
33
+ * A MASK colour pass hands the colour's transparency (1 - alpha) from the vertex stage on, and the fragment reads
34
+ * 1 minus that. Interpolating a constant 0 is exact on every rasterizer; interpolating a constant 1 is not (perspective
35
+ * division leaves 0.99999994 in some pixels), and a texel alpha equal to `alphaCutoff` must stay opaque (glTF 2.0,
36
+ * 3.9.4) when the vertex alpha is 1 or COLOR_0 is absent. Code that names the stage output any other way than
37
+ * `i:Out` / `o.color` is returned unchanged.
38
+ */
39
+ export declare function exactAlphaShader(code: string): string;
40
+ /** Vertex buffer slot 0: the 80-byte vertex, one attribute per location `inputs` reads, three floats where xyz do. */
41
+ export declare function vertexLayout(inputs: VertexInputs): GPUVertexBufferLayout;
42
+ /**
43
+ * Instance buffer `layout` less the attributes finished shader `code` does not declare in its `Instance` struct (the
44
+ * UV row `vertexInputs` drops with the UVs): the same stride, nothing fetched that no input reads. One object per
45
+ * layout and kept set.
46
+ */
47
+ export declare function instanceInputs(code: string, layout: GPUVertexBufferLayout): GPUVertexBufferLayout;
48
+ /**
49
+ * Trims finished shader `source` to the vertex inputs it reads. Called once per pipeline built. `white`: every vertex
50
+ * of the drawn buffer has colour (1, 1, 1, 1) (`whiteColours`), so the vertex stage reads that constant in place of
51
+ * the colour input: the same value, without the 16-byte fetch.
52
+ */
53
+ 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,89 @@
1
+ import{t as e}from"./mipmaps-38NmjDc3.js";var t=7,n=`alpha-coverage`,r=`
2
+ struct Params {srcW:u32,srcH:u32,dstW:u32,dstH:u32,rowWords:u32,fromTexture:u32,keep:u32,srgb:u32,total:u32,p0:u32,p1:u32,p2:u32}
3
+ struct Control {goal:atomic<u32>,low:atomic<u32>,high:atomic<u32>,p0:u32,lo:f32,hi:f32,clo:u32,chi:u32,scale:f32,p1:u32,p2:u32,p3:u32,hist:array<atomic<u32>,65>}
4
+ @group(0) @binding(0) var<uniform> p:Params;
5
+ @group(0) @binding(1) var source:texture_2d<f32>;
6
+ @group(0) @binding(2) var<storage,read> stateIn:array<vec4f>;
7
+ @group(0) @binding(3) var<storage,read_write> stateOut:array<vec4f>;
8
+ @group(0) @binding(4) var<storage,read_write> ctl:Control;
9
+ @group(0) @binding(5) var<storage,read_write> bytes:array<u32>;
10
+ var<workgroup> wa:array<atomic<u32>,65>;
11
+ var<workgroup> wb:array<atomic<u32>,3>;
12
+ fn code(a:f32,s:f32)->u32 {return u32(floor(255.0*clamp(a*s,0.0,1.0)+0.5));}
13
+ fn candidate(lo:f32,hi:f32,j:u32)->f32 {return lo+(hi-lo)*(f32(j)/64.0);}
14
+ fn mul(a:u32,b:u32)->vec2u {
15
+ let ll=(a&0xffffu)*(b&0xffffu);let lh=(a&0xffffu)*(b>>16u);let hl=(a>>16u)*(b&0xffffu);
16
+ let mid=(ll>>16u)+(lh&0xffffu)+(hl&0xffffu);
17
+ return vec2u((a>>16u)*(b>>16u)+(lh>>16u)+(hl>>16u)+(mid>>16u),(ll&0xffffu)|(mid<<16u));
18
+ }
19
+ fn less(a:vec2u,b:vec2u)->bool {return a.x<b.x||(a.x==b.x&&a.y<b.y);}
20
+ fn gap(a:vec2u,b:vec2u)->vec2u {
21
+ if(less(a,b)){return vec2u(b.x-a.x-select(0u,1u,b.y<a.y),b.y-a.y);}
22
+ return vec2u(a.x-b.x-select(0u,1u,a.y<b.y),a.y-b.y);
23
+ }
24
+ @compute @workgroup_size(8,8) fn targetCount(@builtin(global_invocation_id) g:vec3u,@builtin(local_invocation_index) l:u32) {
25
+ if(l==0u){atomicStore(&wb[1],255u);}
26
+ workgroupBarrier();
27
+ if(g.x<p.srcW&&g.y<p.srcH){
28
+ let c=u32(floor(textureLoad(source,g.xy,0).a*255.0+0.5));
29
+ if(c>=p.keep){atomicAdd(&wb[0],1u);}
30
+ atomicMin(&wb[1],c);atomicMax(&wb[2],c);
31
+ }
32
+ workgroupBarrier();
33
+ if(l==0u){atomicAdd(&ctl.goal,atomicLoad(&wb[0]));atomicMin(&ctl.low,atomicLoad(&wb[1]));atomicMax(&ctl.high,atomicLoad(&wb[2]));}
34
+ }
35
+ @compute @workgroup_size(8,8) fn reduce(@builtin(global_invocation_id) g:vec3u) {
36
+ if(g.x>=p.dstW||g.y>=p.dstH){return;}
37
+ let x0=f32(g.x*p.srcW)/f32(p.dstW);let x1=f32((g.x+1u)*p.srcW)/f32(p.dstW);
38
+ let y0=f32(g.y*p.srcH)/f32(p.dstH);let y1=f32((g.y+1u)*p.srcH)/f32(p.dstH);
39
+ 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);
40
+ var sa=0.0;var sc=vec3f(0.0);var pc=vec3f(0.0);
41
+ for(var y=g.y*p.srcH/p.dstH;y<ey;y++){
42
+ let wy=min(y1,f32(y+1u))-max(y0,f32(y));
43
+ for(var x=g.x*p.srcW/p.dstW;x<ex;x++){
44
+ let w=(min(x1,f32(x+1u))-max(x0,f32(x)))*wy;
45
+ var t:vec4f;
46
+ if(p.fromTexture==1u){t=textureLoad(source,vec2u(x,y),0);}else{t=stateIn[y*p.srcW+x];}
47
+ sa+=w*t.a;sc+=(w*t.a)*t.rgb;pc+=w*t.rgb;
48
+ }
49
+ }
50
+ let area=(x1-x0)*(y1-y0);
51
+ stateOut[g.y*p.dstW+g.x]=vec4f(select(pc/area,sc/sa,sa>0.0),sa/area);
52
+ }
53
+ @compute @workgroup_size(1) fn begin() {ctl.lo=0.0;ctl.hi=4096.0;}
54
+ @compute @workgroup_size(8,8) fn count(@builtin(global_invocation_id) g:vec3u,@builtin(local_invocation_index) l:u32) {
55
+ let lo=ctl.lo;let hi=ctl.hi;
56
+ if(g.x<p.dstW&&g.y<p.dstH){
57
+ let a=stateOut[g.y*p.dstW+g.x].a;
58
+ if(code(a,candidate(lo,hi,64u))>=p.keep){
59
+ var b=0u;var e=64u;
60
+ 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;}}
61
+ atomicAdd(&wa[e],1u);
62
+ }
63
+ }
64
+ workgroupBarrier();
65
+ let v=atomicLoad(&wa[l]);if(v>0u){atomicAdd(&ctl.hist[l],v);}
66
+ if(l==0u){let u=atomicLoad(&wa[64]);if(u>0u){atomicAdd(&ctl.hist[64],u);}}
67
+ }
68
+ @compute @workgroup_size(1) fn update() {
69
+ let t=mul(atomicLoad(&ctl.goal),p.dstW*p.dstH);
70
+ var c:array<u32,65>;var run=0u;
71
+ for(var j=0u;j<65u;j++){run+=atomicLoad(&ctl.hist[j]);c[j]=run;atomicStore(&ctl.hist[j],0u);}
72
+ var j=0u;
73
+ loop{if(j>64u){break;}if(!less(mul(c[j],p.total),t)){break;}j++;}
74
+ let lo=ctl.lo;let hi=ctl.hi;
75
+ if(j==0u){ctl.hi=lo;ctl.clo=c[0];ctl.chi=c[0];}
76
+ else if(j>64u){ctl.lo=hi;ctl.clo=c[64];ctl.chi=c[64];}
77
+ else{ctl.lo=candidate(lo,hi,j-1u);ctl.hi=candidate(lo,hi,j);ctl.clo=c[j-1u];ctl.chi=c[j];}
78
+ ctl.scale=select(ctl.hi,ctl.lo,less(gap(mul(ctl.clo,p.total),t),gap(mul(ctl.chi,p.total),t)));
79
+ }
80
+ @compute @workgroup_size(8,8) fn write(@builtin(global_invocation_id) g:vec3u) {
81
+ if(g.x>=p.dstW||g.y>=p.dstH){return;}
82
+ let t=stateOut[g.y*p.dstW+g.x];
83
+ let s=select(ctl.scale,1.0,atomicLoad(&ctl.low)==atomicLoad(&ctl.high));
84
+ var c=clamp(t.rgb,vec3f(0.0),vec3f(1.0));
85
+ if(p.srgb==1u){c=select(1.055*pow(c,vec3f(1.0/2.4))-0.055,c*12.92,c<=vec3f(0.0031308));}
86
+ let b=vec3u(floor(c*255.0+0.5));
87
+ bytes[g.y*p.rowWords+g.x]=b.x|(b.y<<8u)|(b.z<<16u)|(code(t.a,s)<<24u);
88
+ }
89
+ `;function i(e,t){let n=Math.fround;if(!(n(0)*n(t)<n(e)))return 0;for(let r=1;r<256;r++)if(n(n(r/255)*n(t))>=n(e))return r;return 0}function a(e,t){let i=t.get(n);if(i)return i;let a=e=>({visibility:4,buffer:{type:e}}),o=e.createBindGroupLayout({entries:[{binding:0,visibility:4,buffer:{type:`uniform`}},{binding:1,visibility:4,texture:{sampleType:`float`}},{binding:2,...a(`read-only-storage`)},{binding:3,...a(`storage`)},{binding:4,...a(`storage`)},{binding:5,...a(`storage`)}]}),s=e.createShaderModule({code:r}),c=e.createPipelineLayout({bindGroupLayouts:[o]}),l=t=>e.createComputePipeline({layout:c,compute:{module:s,entryPoint:t}});i={layout:o};for(let e of[`targetCount`,`reduce`,`begin`,`count`,`update`,`write`])i[e]=l(e);return t.set(n,i),i}function o(n,r,o,s,c,l){if(o<2)return;let u=i(c,l),{format:d,width:f,height:p}=r,m=Math.max(1,f>>1)*Math.max(1,p>>1)*16;if(!u||d!==`rgba8unorm`&&d!==`rgba8unorm-srgb`||m>n.limits.maxStorageBufferBindingSize||m>n.limits.maxBufferSize)return e(n,r,o,s);let h=a(n,s),g=[[f,p]];for(let e=1;e<o;e++)g.push(g[e-1].map(e=>Math.max(1,e>>1)));let _=e=>Math.ceil(e*4/256)*64,v=4,y=16;for(let e=1;e<o;e++)v=Math.max(v,_(g[e][0])*4*g[e][1]),e%2==0&&(y=Math.max(y,g[e][0]*g[e][1]*16));let b=(e,t)=>n.createBuffer({size:e,usage:t}),x=b(256*o,GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST),S=[b(y,GPUBufferUsage.STORAGE),b(m,GPUBufferUsage.STORAGE)],C=b(308,GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST),w=b(v,GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC),T=new Uint32Array(64*o),E=+!!d.endsWith(`-srgb`);for(let e=0;e<o;e++){let[t,n]=g[Math.max(0,e-1)],[r,i]=g[e];T.set([t,n,r,i,_(r),+(e===1),u,E,f*p],e*64)}n.queue.writeBuffer(x,0,T),n.queue.writeBuffer(C,0,new Uint32Array([0,255,0]));let D=r.createView({baseMipLevel:0,mipLevelCount:1}),O=e=>n.createBindGroup({layout:h.layout,entries:[{binding:0,resource:{buffer:x,offset:e*256,size:48}},{binding:1,resource:D},{binding:2,resource:{buffer:S[(e+1)%2]}},{binding:3,resource:{buffer:S[e%2]}},{binding:4,resource:{buffer:C}},{binding:5,resource:{buffer:w}}]}),k=e=>[Math.ceil(e[0]/8),Math.ceil(e[1]/8)],A=n.createCommandEncoder(),j=A.beginComputePass();j.setBindGroup(0,O(0)),j.setPipeline(h.targetCount),j.dispatchWorkgroups(...k(g[0])),j.end();for(let e=1;e<o;e++){j=A.beginComputePass(),j.setBindGroup(0,O(e)),j.setPipeline(h.reduce),j.dispatchWorkgroups(...k(g[e])),j.setPipeline(h.begin),j.dispatchWorkgroups(1);for(let n=0;n<t;n++)j.setPipeline(h.count),j.dispatchWorkgroups(...k(g[e])),j.setPipeline(h.update),j.dispatchWorkgroups(1);j.setPipeline(h.write),j.dispatchWorkgroups(...k(g[e])),j.end(),A.copyBufferToTexture({buffer:w,bytesPerRow:_(g[e][0])*4},{texture:r,mipLevel:e},g[e])}n.queue.submit([A.finish()]);for(let e of[x,...S,C,w])e.destroy()}function s(e,t,n){let r=Math.hypot(n[0],n[1],n[2]);e[t]=n[0]/r,e[t+1]=n[1]/r,e[t+2]=n[2]/r,e[t+3]=n[3]}function c(e,t,n,r){return{code:`missing-texcoord`,message:`${typeof t==`string`&&t?`glTF material ${e} ("${t}")`:`glTF material ${e}`} reads its ${n} from TEXCOORD_${r}, which a primitive using it lacks; that primitive draws without the map (glTF 2.0 section 5.24 textureInfo.texCoord). Add TEXCOORD_${r} to the mesh or point texCoord at a set it has`,material:e,map:n,texCoord:r}}function l(e,t){e.some(e=>e.code===t.code&&e.material===t.material&&e.map===t.map&&e.texCoord===t.texCoord)||e.push(t)}export{i as a,o as i,c as n,s as r,l as t};
@@ -0,0 +1,24 @@
1
+ /**
2
+ * A problem in a glTF file that the loaders work around instead of refusing the file, listed once on
3
+ * `model.warnings` (both loaders). `code` says which kind; the other fields name what it concerns.
4
+ */
5
+ export interface GLTFWarning {
6
+ /**
7
+ * `'missing-texcoord'`: a material's map reads a TEXCOORD set that a primitive using the material lacks. glTF 2.0
8
+ * section 5.24 (`textureInfo.texCoord`) has the map read `TEXCOORD_<texCoord>`; the loaders draw that primitive with
9
+ * the map left out (its factor only), as other loaders do, instead of stopping the load (KB-GLTFA A2).
10
+ */
11
+ readonly code: 'missing-texcoord';
12
+ /** What happened and how to fix the file. */
13
+ readonly message: string;
14
+ /** The glTF material index. */
15
+ readonly material: number;
16
+ /** The map's glTF property, for example `'baseColorTexture'` or `'normalTexture'`. */
17
+ readonly map: string;
18
+ /** The TEXCOORD set the map reads and the primitive lacks. */
19
+ readonly texCoord: number;
20
+ }
21
+ /** The warning for material `material` whose `map` reads `TEXCOORD_<texCoord>`, which a primitive lacks. */
22
+ export declare function missingTexCoord(material: number, name: unknown, map: string, texCoord: number): GLTFWarning;
23
+ /** Adds `warning` to `list` unless one with the same code, material, map and set is there (each is reported once). */
24
+ export declare function addWarning(list: GLTFWarning[], warning: GLTFWarning): void;
@@ -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). Points and lines draw 1 px wide.
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 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+ const v=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
+ import{t as e}from"./scene-scope-CZDEkd24.js";import{t}from"./decoder-default-CxLH8Vz0.js";import{n,u as r}from"./model-C77ATxi1.js";import{M as i,_ as a,o,r as s,s as c,t as l}from"./asset-DN3ocEdY.js";import{t as u}from"./stroke-width-B2cnYGgn.js";import{i as d}from"./pack-DdxRO8k6.js";import{loadGLTF as f,parseGLTFAsync as p}from"./pbr.js";import{prepareAsset as m}from"./prepare.js";import{n as h,r as g,t as _}from"./worker-CY1TQnYX.js";import{engineRuntime as __margoRuntime,margoError as y}from"@margoengine/core/extension";var b=({decoders:e={},fetch:t,draco:n,ktx2:r})=>!!(t||n||r||e.draco||e.meshopt||e.ktx2);function x(e,t,n,r={}){return S(e,t,n,r)}function S(e,t,r,a,o=1){let u;try{if(r?.throwIfAborted(),t.deferred)throw y(`state`,`Compressed PreparedGLTF requires the asynchronous worker loader; call loadGLTF or parseGLTFAsync`);let c=new l(t.doc,t.buffers,void 0,a,t.maxDownloadBytes,t.maxNodes);s.set(c,o),c.baseURL=t.baseURL,t.maxPartVertices!==void 0&&(c.partVertices=i(t.maxPartVertices));for(let[e,n]of t.accessors)c.cache.set(e,n);return t.doc.meshes?.forEach((e,n)=>e?.primitives?.forEach((e,r)=>{let i=t.geometry[n]?.[r];i&&e&&typeof e==`object`&&d.set(e,Array.isArray(i)?i:[i])})),u=new n(e,c,t.images),v(e).use(u),u}catch(e){throw u?u.dispose():c(t.images),e}}async function C(e,i,o,s,l){if(i.deferred){let{asset:r,images:u}=await a(i.baseURL,t({...o,maxAnisotropy:l,buffers:i.buffers}),i.doc,{device:v(e).gpu??void 0,ktx2:o.ktx2},!1,i.downloadedBytes);if(r.hooks.splats){let t=s.run(()=>new n(e,r,u));try{return s.run(()=>v(e).use(t)),await s.run(()=>t.attachSplats(o.signal)),await s.run(()=>t.attachStrokes(o.signal)),t}catch(e){throw t.dispose(),e}}try{i=m(r,u)}catch(e){throw c(u),e}}let d=await r(i.doc,o.decoders??{}),f=d.strokes===void 0&&u(i.doc)?{...d,strokes:(await import(`./strokes.js`)).wideStrokes}:d,p=s.run(()=>S(e,i,o.signal,f,l));try{return await s.run(()=>p.attachStrokes(o.signal)),p}catch(e){throw p.dispose(),e}}var w=()=>new URL(`./workers/gltf.js?no-inline`,import.meta.url);async function T(t,n,r={}){if(!_()||b(r)||r.optimize)return f(t,n,r);let i=o(r.maxAnisotropy),a=e(t);return C(t,await g(w(),{url:new URL(n,globalThis.location.href).href,maxDownloadBytes:r.maxDownloadBytes,maxNodes:r.maxNodes,allowedURLs:r.allowedURLs,maxPartVertices:r.maxPartVertices},r.signal),r,a,i)}async function E(t,n,r={}){if(!_()||b(r))return p(t,n,r);let i=o(r.maxAnisotropy),a=e(t),s={url:globalThis.location.href,input:typeof n==`object`&&!(n instanceof ArrayBuffer)&&!ArrayBuffer.isView(n)?n:h(n),buffers:r.buffers?.map(h),maxDownloadBytes:r.maxDownloadBytes,maxNodes:r.maxNodes,allowedURLs:r.allowedURLs,maxPartVertices:r.maxPartVertices};return C(t,await g(w(),s,r.signal),r,a,i)}export{T as loadGLTFInWorker,x as modelFromPrepared,E as parseGLTFInWorker};