@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.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +1753 -2
- package/dist/accessor-CU_1uSZ1.js +1 -0
- package/dist/accessor-DuqjpuxI.js +1 -0
- package/dist/accessor.d.ts +12 -0
- package/dist/asset-DN3ocEdY.js +4 -0
- package/dist/asset-entry.d.ts +1 -0
- package/dist/asset-entry.js +1 -0
- package/dist/asset.d.ts +395 -0
- package/dist/audio.d.ts +47 -0
- package/dist/audio.js +1 -0
- package/dist/auto.d.ts +29 -0
- package/dist/auto.js +1 -0
- package/dist/base-textures.d.ts +20 -0
- package/dist/coalesce.d.ts +29 -0
- package/dist/compression-CUOCmjmE.js +1 -0
- package/dist/compression.d.ts +21 -0
- package/dist/coordinates.d.ts +1 -0
- package/dist/coordinates.js +1 -0
- package/dist/dds.d.ts +7 -0
- package/dist/dds.js +1 -0
- package/dist/decoder-default-CxLH8Vz0.js +1 -0
- package/dist/decoder-default.d.ts +5 -0
- package/dist/default-materials.d.ts +10 -0
- package/dist/default-transmission.d.ts +13 -0
- package/dist/draco-state.d.ts +7 -0
- package/dist/draw-batch.d.ts +83 -0
- package/dist/draw-memo.d.ts +136 -0
- package/dist/extended.d.ts +12 -0
- package/dist/extended.js +1 -0
- package/dist/gltf.worker.d.ts +1 -0
- package/dist/group.d.ts +18 -0
- package/dist/image-limit-DvFSfR5T.js +1 -0
- package/dist/image-limit.d.ts +6 -0
- package/dist/index.d.ts +95 -0
- package/dist/index.js +1 -0
- package/dist/instanced-shader-C9ZMazvo.js +5 -0
- package/dist/instanced-shader.d.ts +14 -0
- package/dist/instancing.d.ts +9 -0
- package/dist/instancing.js +1 -0
- package/dist/interactivity-graph.d.ts +193 -0
- package/dist/interactivity-model.d.ts +94 -0
- package/dist/interactivity-ops.d.ts +20 -0
- package/dist/interactivity.d.ts +33 -0
- package/dist/interactivity.js +1 -0
- package/dist/lights.d.ts +98 -0
- package/dist/lights.js +1 -0
- package/dist/limits-_LZ441oV.js +1 -0
- package/dist/material-draw-state-GKiHDb0p.js +1 -0
- package/dist/material-draw-state.d.ts +7 -0
- package/dist/material-draw.d.ts +18 -0
- package/dist/material-draw.js +1 -0
- package/dist/material-extension.d.ts +96 -0
- package/dist/mesh-source-DvU8YvMc.js +1 -0
- package/dist/meshopt.d.ts +9 -0
- package/dist/meshopt.js +1 -0
- package/dist/metadata.d.ts +114 -0
- package/dist/metadata.js +1 -0
- package/dist/mipmaps-38NmjDc3.js +21 -0
- package/dist/model-C77ATxi1.js +25 -0
- package/dist/model-entry.d.ts +2 -0
- package/dist/model-entry.js +1 -0
- package/dist/model.d.ts +1088 -0
- package/dist/native-glass-D85twud0.js +19 -0
- package/dist/node-image-decode.d.ts +6 -0
- package/dist/node-matrix-R9BipGnp.js +1 -0
- package/dist/node-matrix.d.ts +16 -0
- package/dist/occlusion.d.ts +8 -0
- package/dist/pack-DdxRO8k6.js +1 -0
- package/dist/pack.d.ts +27 -0
- package/dist/parts.d.ts +54 -0
- package/dist/pbr-instancing.d.ts +83 -0
- package/dist/pbr-instancing.js +1 -0
- package/dist/pbr.d.ts +13 -0
- package/dist/pbr.js +1 -0
- package/dist/physics.d.ts +148 -0
- package/dist/physics.js +1 -0
- package/dist/prepare.d.ts +26 -0
- package/dist/prepare.js +1 -0
- package/dist/progressive-lod.d.ts +13 -0
- package/dist/progressive.d.ts +62 -0
- package/dist/progressive.js +4 -0
- package/dist/progressive.worker.d.ts +1 -0
- package/dist/quantized.d.ts +8 -0
- package/dist/quantized.js +1 -0
- package/dist/render-state.d.ts +18 -0
- package/dist/replica.d.ts +37 -0
- package/dist/report.d.ts +128 -0
- package/dist/report.js +1 -0
- package/dist/scene-data.d.ts +61 -0
- package/dist/scene-data.js +1 -0
- package/dist/scene-scope-CZDEkd24.js +4 -0
- package/dist/scene.d.ts +61 -0
- package/dist/scene.js +4 -0
- package/dist/shader-C29RtPAw.js +409 -0
- package/dist/shader.d.ts +246 -0
- package/dist/shared/caster.d.ts +159 -0
- package/dist/shared/gltf.d.ts +257 -0
- package/dist/shared/iridescence.d.ts +2 -0
- package/dist/shared/prepared-geometry.d.ts +8 -0
- package/dist/side-shader.d.ts +1 -0
- package/dist/soft-mesh.d.ts +132 -0
- package/dist/soft-mesh.js +4 -0
- package/dist/spec-gloss.d.ts +21 -0
- package/dist/spec-gloss.js +18 -0
- package/dist/splat-state.d.ts +7 -0
- package/dist/splats.d.ts +18 -0
- package/dist/splats.js +1 -0
- package/dist/src-Btvz5f6i.js +4 -0
- package/dist/stream-CrfNNCRd.js +1 -0
- package/dist/stream.d.ts +104 -0
- package/dist/stroke-width-B2cnYGgn.js +1 -0
- package/dist/stroke-width.d.ts +18 -0
- package/dist/strokes.d.ts +12 -0
- package/dist/strokes.js +1 -0
- package/dist/texture-coordinates-XFsEMdU6.js +2 -0
- package/dist/texture-coordinates.d.ts +26 -0
- package/dist/texture-stream-Cu_XpyVO.js +4 -0
- package/dist/texture-stream.d.ts +88 -0
- package/dist/textured.d.ts +34 -0
- package/dist/textured.js +5 -0
- package/dist/transmission.d.ts +81 -0
- package/dist/transmission.js +66 -0
- package/dist/uniform-arena.d.ts +78 -0
- package/dist/version-B6NE5cJf.js +1 -0
- package/dist/version.d.ts +8 -0
- package/dist/vertex-inputs.d.ts +53 -0
- package/dist/view-uniform.d.ts +13 -0
- package/dist/visibility-C_Oqz9Sr.js +1 -0
- package/dist/warning-UqjZyyqW.js +89 -0
- package/dist/warning.d.ts +24 -0
- package/dist/worker-CY1TQnYX.js +1 -0
- package/dist/worker.d.ts +21 -0
- package/dist/worker.js +4 -0
- package/dist/workers/gltf.js +322 -0
- package/dist/workers/progressive.js +1 -0
- package/package.json +232 -4
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { Mesh } from '@margoengine/core/extension';
|
|
2
|
+
import type { PBRMaterial, PBRPrimitive } from './pbr.js';
|
|
3
|
+
/** One static part baked into a material batch, with the root-relative matrix and source arrays captured at bake time. */
|
|
4
|
+
export interface BatchPart {
|
|
5
|
+
primitive: PBRPrimitive;
|
|
6
|
+
stamp: Float32Array;
|
|
7
|
+
vertices: Float32Array;
|
|
8
|
+
indices: Uint32Array;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Several unskinned, unmorphed, non-instanced primitives that share one material, drawn as one mesh parented to the
|
|
12
|
+
* model root. Vertices are copied into root space. Callers draw the originals again when a part moves, hides, or
|
|
13
|
+
* changes material.
|
|
14
|
+
*/
|
|
15
|
+
export interface StaticBatch {
|
|
16
|
+
node: Mesh;
|
|
17
|
+
material: PBRMaterial;
|
|
18
|
+
primitive: PBRPrimitive;
|
|
19
|
+
parts: BatchPart[];
|
|
20
|
+
}
|
|
21
|
+
/** True for a primitive a static batch can hold, whatever it shares a material with. */
|
|
22
|
+
export declare function eligible(p: PBRPrimitive): boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Batches of a copy from `source`'s: the same baked arrays and part poses, with the copy's own primitives and nodes.
|
|
25
|
+
* `own` gives the copy's primitive for a source primitive.
|
|
26
|
+
*/
|
|
27
|
+
export declare function copyStaticBatches(source: readonly StaticBatch[], own: (primitive: PBRPrimitive) => PBRPrimitive, createNode: () => Mesh): StaticBatch[];
|
|
28
|
+
/** Groups of two or more static primitives that can share one draw. World matrices must already be published. */
|
|
29
|
+
export declare function buildStaticBatches(primitives: readonly PBRPrimitive[], root: Mesh, createNode: () => Mesh): StaticBatch[];
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{T as e,f as t,g as n,h as r,j as i}from"./asset-DN3ocEdY.js";import{margoError as a}from"@margoengine/core/extension";var o=3*i,s={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT4:16},c={POSITION:`positions`,NORMAL:`normals`,TEXCOORD_0:`uvs`,COLOR_0:`colors`},l={5120:127,5121:255,5122:32767,5123:65535};async function u(e,{signal:n,draco:r}={}){n?.throwIfAborted();let i,a=async()=>{if(!r){let{DracoDecoder:a}=await t(e,`Draco`)();n?.throwIfAborted(),r=i=new a}return r};try{for(let t of e.doc.meshes??[])for(let r of t.primitives??[])await d(e,r,a,n)}finally{i?.dispose()}}async function d(t,u,d,f){let p=e.get(t)??/* @__PURE__ */ new Map;e.set(t,p);let m=u.extensions?.KHR_draco_mesh_compression;if(!m||p.has(u))return;if((u.mode??4)!==4)throw a(`unsupported`,`PBR requires triangle primitives; re-export the mesh with mode 4 (TRIANGLES)`);if(!m.attributes||typeof m.attributes!=`object`||Array.isArray(m.attributes))throw TypeError(`Invalid glTF Draco attributes; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let h={},g={},_={},v=r(t.doc.accessors,u.attributes?.POSITION,`Draco POSITION`),y=n(v.count,`Draco vertex count`,3);if(y>16777216)throw a(`unsupported`,`glTF primitive has more than ${i} vertices, the most one primitive may hold; split the mesh into several primitives`);if(v.type!==`VEC3`)throw RangeError(`Invalid glTF Draco POSITION size; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let b=0;for(let[e,i]of Object.entries(m.attributes)){let a=r(t.doc.accessors,u.attributes?.[e],`Draco attribute`),o=n(a.count,`Draco accessor count`,1),c=Object.hasOwn(s,a.type)?s[a.type]:void 0;if(!c||o!==y)throw RangeError(`Invalid glTF Draco accessor size; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);b+=o*c*4,h[e]=n(a.componentType,`Draco component type`),g[e]=n(i,`Draco attribute id`),_[e]=c}let x=u.indices===void 0?void 0:r(t.doc.accessors,u.indices,`Draco indices`);if(x){if(x.type!==`SCALAR`||![5121,5123,5125].includes(x.componentType)||x.normalized)throw TypeError(`Invalid glTF Draco indices; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let e=n(x.count,`Draco index count`,1);if(e>o||e%3)throw RangeError(`Invalid glTF Draco index count; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);b+=e*4}if(b>t.maxBytes*4)throw RangeError(`Decoded glTF exceeds byte budget; load a smaller model, or reduce its textures and meshes`);let S=t.view(m.bufferView);if(b>t.remainingDecodedBytes)throw RangeError(`Decoded glTF exceeds byte budget; load a smaller model, or reduce its textures and meshes`);let C=x?x.count:Math.min(o,Math.floor((t.remainingDecodedBytes-b)/4));if(C<3)throw RangeError(`Decoded glTF exceeds index byte budget; load a smaller model, or reduce its textures and meshes`);let w=await d();f?.throwIfAborted();let T=await w.decode(S,{attributeIds:g,componentTypes:h,signal:f,limits:{maxVertices:y,maxIndices:C,maxDecodedBytes:t.remainingDecodedBytes,attributeWidths:_}});f?.throwIfAborted();let E=n(T.vertexCount,`Draco vertex count`,3),D=T.indices;if(E>16777216||!(D instanceof Uint16Array||D instanceof Uint32Array)||!D.length||D.length>o||D.length%3||D.some(e=>e>=E)||x&&D.length!==x.count)throw RangeError(`Invalid glTF Draco triangle indices; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);for(let e of Object.keys(g)){let n=u.attributes[e],i=r(t.doc.accessors,n,`Draco attribute`),a=Object.hasOwn(c,e)?c[e]:void 0,o=T.attributes?.[e],d=a?T[a]:o?.array;if(!ArrayBuffer.isView(d)||d instanceof DataView||i.count!==E||d.length!==E*s[i.type]||!a&&(o?.itemSize!==s[i.type]||o.componentType!==i.componentType))throw RangeError(`Mismatched glTF Draco attribute `+e+`; the accessor must match the Draco stream, re-export the model`);let f=Float32Array.from(d);if(i.normalized&&e!==`COLOR_0`){let e=l[i.componentType];if(!e)throw TypeError(`Invalid normalized Draco attribute; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);for(let t=0;t<f.length;t++)f[t]=Math.max(-1,f[t]/e)}t.setDecodedAccessor(n,f)}u.indices===void 0&&t.reserveDecodedBytes(D.length*4);let O=Float32Array.from(D);u.indices!==void 0&&t.setDecodedAccessor(u.indices,O),p.set(u,u.indices===void 0?O:t.accessor(u.indices,`SCALAR`))}export{d as decompressPrimitive,u as decompressPrimitives};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { GLTFPrimitive } from './shared/gltf.js';
|
|
2
|
+
import type { KTX2Decoder } from '@margoengine/decoders';
|
|
3
|
+
import { type GLTFAsset } from './asset.js';
|
|
4
|
+
/**
|
|
5
|
+
* Options for loading compressed glTF: an AbortSignal and optional reusable Draco, meshopt and KTX2 decoders the caller owns.
|
|
6
|
+
*/
|
|
7
|
+
export interface GLTFLoadOptions {
|
|
8
|
+
signal?: AbortSignal;
|
|
9
|
+
/** Optional reusable decoder. The caller retains ownership; otherwise a decoder is created and disposed per load. */
|
|
10
|
+
draco?: {
|
|
11
|
+
decode(data: Uint8Array, options: import('./asset.js').GLTFDracoDecodeOptions): Promise<import('./asset.js').GLTFDracoGeometry>;
|
|
12
|
+
};
|
|
13
|
+
/** Optional reusable Basis transcoder. Only files with KTX2 images create an automatic decoder. */
|
|
14
|
+
ktx2?: Pick<KTX2Decoder, 'transcode'>;
|
|
15
|
+
}
|
|
16
|
+
export declare function decompressPrimitives(asset: GLTFAsset, { signal, draco }?: GLTFLoadOptions): Promise<void>;
|
|
17
|
+
/**
|
|
18
|
+
* Decodes one primitive's KHR_draco_mesh_compression data into the asset's accessors; a primitive without the extension,
|
|
19
|
+
* or already decoded, is left alone. `decoder` is asked only when there is something to decode.
|
|
20
|
+
*/
|
|
21
|
+
export declare function decompressPrimitive(asset: GLTFAsset, p: GLTFPrimitive, decoder: () => Promise<NonNullable<GLTFLoadOptions['draco']>>, signal?: AbortSignal): Promise<void>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { textureCoordinates, type TextureTransform, type UVSet } from './texture-coordinates.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{r as textureCoordinates}from"./texture-coordinates-XFsEMdU6.js";
|
package/dist/dds.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { GLTFCompressedImage, GLTFDecoderHooks } from './asset.js';
|
|
2
|
+
/** Parse a single-layer 2D DDS, retaining every mip for upload, device restoration and model clones. */
|
|
3
|
+
export declare function decodeDDSImage(data: Uint8Array, options?: {
|
|
4
|
+
signal?: AbortSignal;
|
|
5
|
+
}): GLTFCompressedImage;
|
|
6
|
+
/** MSFT_texture_dds decoder hook. Async glTF loaders select it lazily when a file uses the extension. */
|
|
7
|
+
export declare const ddsTextures: NonNullable<GLTFDecoderHooks['dds']>;
|
package/dist/dds.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./image-limit-DvFSfR5T.js";import{margoError as e}from"@margoengine/core/extension";import{parseDDS as t,uploadTexture as n}from"@margoengine/decoders/dds";import{decodeBC as r,decodeBCFloat as i}from"@margoengine/decoders/bc";function a(e){let t=e<0?32768:0,n=Math.abs(e);if(!n)return t;let r=Math.max(-14,Math.floor(Math.log2(n))),i=n*2**(10-r),a=Math.floor(i),o=a+(i-a>.5||i-a===.5&&a%2?1:0);return t|(r===-14&&o<1024?o:(r+14<<10)+o)}function o(o,s={}){s.signal?.throwIfAborted();let c=t(o);if(c.dimension!==`2d`||c.layers!==1)throw e(`unsupported`,`glTF material DDS images must be single-layer 2D textures; export a 2D image`);if(c.width*c.height>67108864)throw RangeError(`glTF DDS image exceeds decoded size limit; export a smaller texture`);let l,u=e=>{if(!c.feature||e.features.has(c.feature)&&c.width%4==0&&c.height%4==0)return c;if(!l){let e=/^bc[456]/.test(c.format),t=c.mipmaps.map(t=>{let n=e?i(c.format,t.data,t.width,t.height):r(c.format,t.data,t.width,t.height),o=e?Uint16Array.from(n.data,a):n.data,s=new Uint8Array(o.buffer,o.byteOffset,o.byteLength);return{...t,data:s,byteLength:s.length}});l={...c,format:e?`rgba16float`:`rgba8unorm`,feature:void 0,mipmaps:t}}return l},d=(e,t)=>{let n=u(e).format.replace(/-srgb$/,``);return n+(t&&/^(rgba8unorm|bc[1237]-)/.test(n)?`-srgb`:``)};return{width:c.width,height:c.height,format:c.format,mipmaps:c.mipmaps,gpuFormat:d,upload(t,r){let i=u(t),a=d(t,r);if(/^(r|rg|rgba)32float$/.test(a)&&!t.features.has(`float32-filterable`))throw e(`unsupported`,`32-bit float DDS material textures require float32-filterable; request that device feature or export 16-bit float DDS`);return n(t,{...i,format:a})}}}var s={decode:o};export{s as ddsTextures,o as decodeDDSImage};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=()=>import(`@margoengine/decoders`),t=t=>({...t,decoders:{decoderModule:e,...t.decoders}});export{t};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { GLTFDocument } from './shared/gltf.js';
|
|
2
|
+
import type { GLTFDecoderHooks } from './asset.js';
|
|
3
|
+
/**
|
|
4
|
+
* Decoders with the physical material shader added when the file uses a physical material extension and the caller
|
|
5
|
+
* did not choose (`materials` undefined): imported on first need, so apps that never load such a file ship none of its
|
|
6
|
+
* WGSL. `materials: false` is kept as no shader. The same goes for `splats`, added when the file holds Gaussian splats,
|
|
7
|
+
* and `strokes`, added when a point or line asks for a width. The transmission pass is added on the main thread
|
|
8
|
+
* (default-transmission.ts), since the parsing workers bundle this file.
|
|
9
|
+
*/
|
|
10
|
+
export declare function withMaterials(doc: GLTFDocument, decoders?: GLTFDecoderHooks): Promise<GLTFDecoderHooks>;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { GLTFDocument } from './shared/gltf.js';
|
|
2
|
+
import type { GLTFAsset, GLTFDecoderHooks } from './asset.js';
|
|
3
|
+
/**
|
|
4
|
+
* `decoders` with `transmission` added when the caller did not choose (undefined), the physical shader reads the file
|
|
5
|
+
* (`materials` set) and a material declares KHR_materials_transmission (factor 0 included, for pointer animation).
|
|
6
|
+
* A file with KHR_materials_volume takes the pass too: on a display target the tint's multiply blend reads encoded light,
|
|
7
|
+
* so its Beer-Lambert was up to 20 levels off where the pass is exact (KB-VOL-TINT-DISPLAY1).
|
|
8
|
+
* `transmission: false` stays false (the tinted blend; gltf/pbr attaches only a pass), so a second call on the same
|
|
9
|
+
* hooks adds nothing either. The entry is imported on first need.
|
|
10
|
+
*/
|
|
11
|
+
export declare function withTransmission<T extends Pick<GLTFDecoderHooks, 'materials' | 'transmission'>>(doc: GLTFDocument, decoders: T): Promise<T>;
|
|
12
|
+
/** `withTransmission` on a loaded asset's hooks, before its model is made. */
|
|
13
|
+
export declare function addTransmission(asset: GLTFAsset): Promise<void>;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { GLTFPrimitive } from './shared/gltf.js';
|
|
2
|
+
import type { GLTFAsset } from './asset.js';
|
|
3
|
+
export declare const decoded: WeakMap<GLTFAsset, Map<object, Float32Array<ArrayBufferLike>>>;
|
|
4
|
+
/** Whether any mesh primitive of the asset uses KHR_draco_mesh_compression (walked like decompressPrimitives). */
|
|
5
|
+
export declare function hasDraco(asset: GLTFAsset): boolean;
|
|
6
|
+
/** Draco topology belongs to the primitive, including when no index accessor is declared. */
|
|
7
|
+
export declare function compressedIndices(asset: GLTFAsset, primitive: GLTFPrimitive): Float32Array | undefined;
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { UniformSlot } from './uniform-arena.js';
|
|
2
|
+
/**
|
|
3
|
+
* What gltf/pbr's derivation reads of a batch's instancing (as of a `PBRInstances`): the instance layout, the
|
|
4
|
+
* instanced vertex stage and whether the rows are mirrored. One per handedness, shared by every batch, so every batch
|
|
5
|
+
* of a material shares one derivation and pipeline.
|
|
6
|
+
*/
|
|
7
|
+
export declare class BatchKind {
|
|
8
|
+
readonly mirrored: boolean;
|
|
9
|
+
readonly rows: boolean;
|
|
10
|
+
readonly layout: GPUVertexBufferLayout;
|
|
11
|
+
/**
|
|
12
|
+
* @param rows - Each instance reads its own uniform block (`rowsShader`, applied by the derivation once the shader is
|
|
13
|
+
* finished): a batch of meshes whose materials share a pipeline and group 2 but not their uniform rows.
|
|
14
|
+
*/
|
|
15
|
+
constructor(mirrored: boolean, rows?: boolean);
|
|
16
|
+
shader(code: string): string;
|
|
17
|
+
}
|
|
18
|
+
/** The batch kind for draws whose node matrices are mirrored (negative determinant) or not; `rows`: see `BatchKind`. */
|
|
19
|
+
export declare const batchKind: (mirrored: boolean, rows?: boolean) => BatchKind;
|
|
20
|
+
/**
|
|
21
|
+
* The uniform blocks of a rows batch (`BatchKind.rows`), one per instance in draw order: `perBinding` blocks per
|
|
22
|
+
* binding, each binding 256-byte aligned. A block is written again only when its slot changes hands or its
|
|
23
|
+
* derivation's version changes (NaN versions compare the values).
|
|
24
|
+
*/
|
|
25
|
+
export declare class BatchRows {
|
|
26
|
+
data: Float32Array<ArrayBuffer>;
|
|
27
|
+
buffer?: GPUBuffer;
|
|
28
|
+
/** One binding per `perBinding` blocks; replaced (with the buffer) when the buffer grows. */
|
|
29
|
+
bindings: GPUBufferBinding[];
|
|
30
|
+
private floats;
|
|
31
|
+
private perBinding;
|
|
32
|
+
/** Floats from one binding's start to the next. */
|
|
33
|
+
private stride;
|
|
34
|
+
private readonly owners;
|
|
35
|
+
private readonly versions;
|
|
36
|
+
/**
|
|
37
|
+
* Writes block `blocks[i]` (with identity model rows and determinant 1: the instance rows place each mesh) into slot
|
|
38
|
+
* `i` and uploads what changed. `owners[i]` and `versions[i]` name where the block came from.
|
|
39
|
+
*/
|
|
40
|
+
write(device: GPUDevice, blocks: readonly Float32Array[], owners: readonly object[], versions: readonly number[], floats: number, perBinding: number): void;
|
|
41
|
+
destroy(device: GPUDevice): void;
|
|
42
|
+
}
|
|
43
|
+
/** The instance rows of a batch of several meshes. */
|
|
44
|
+
export declare class BatchInstances {
|
|
45
|
+
/** 24 floats a row: world matrix, tint (1), UV scale (1) and offset (0). */
|
|
46
|
+
data: Float32Array<ArrayBuffer>;
|
|
47
|
+
buffer?: GPUBuffer;
|
|
48
|
+
/** Rows the GPU buffer holds as uploaded. */
|
|
49
|
+
private uploaded;
|
|
50
|
+
/** True when the rows hold exactly `matrices` and `tints` (see `write`), as uploaded. */
|
|
51
|
+
holds(matrices: readonly ArrayLike<number>[], tints?: readonly ArrayLike<number>[]): boolean;
|
|
52
|
+
/**
|
|
53
|
+
* Writes the rows' world matrices and tints (each member's base colour when the batch folds several materials, else
|
|
54
|
+
* 1) and uploads the changed range. Returns the vertex buffer.
|
|
55
|
+
*/
|
|
56
|
+
write(device: GPUDevice, matrices: readonly ArrayLike<number>[], tints?: readonly ArrayLike<number>[]): GPUBuffer;
|
|
57
|
+
destroy(device: GPUDevice): void;
|
|
58
|
+
}
|
|
59
|
+
/** A batch's group 0 by pipeline, uniform binding and view block (index.ts `batchGroup`). */
|
|
60
|
+
export type BatchGroups = Map<GPURenderPipeline, Map<GPUBufferBinding, Map<GPUBufferBinding, GPUBindGroup>>>;
|
|
61
|
+
/** A rows batch's GPU state (`BatchKind.rows`), kept like `BatchState`. */
|
|
62
|
+
export interface RowsState {
|
|
63
|
+
instances: BatchInstances;
|
|
64
|
+
rows: BatchRows;
|
|
65
|
+
/** Group 0 by pipeline, rows binding and view block. */
|
|
66
|
+
groups: BatchGroups;
|
|
67
|
+
/** Group 1 by pipeline, made from the leading resource's texture views `texturesOf`. */
|
|
68
|
+
textures: Map<GPURenderPipeline, GPUBindGroup>;
|
|
69
|
+
texturesOf?: object;
|
|
70
|
+
frame: number;
|
|
71
|
+
view: object;
|
|
72
|
+
}
|
|
73
|
+
/** A batch's GPU state, kept on its first draw's resource across frames (one per derivation and view). */
|
|
74
|
+
export interface BatchState {
|
|
75
|
+
instances: BatchInstances;
|
|
76
|
+
/** The batch's uniform: the derivation's rows with identity model rows. */
|
|
77
|
+
uniform: UniformSlot;
|
|
78
|
+
/** Group 0 by pipeline, uniform binding and view block. */
|
|
79
|
+
groups: BatchGroups;
|
|
80
|
+
/** The frame and view that last drew it. */
|
|
81
|
+
frame: number;
|
|
82
|
+
view: object;
|
|
83
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import type { LightingEffect, PBRRenderState } from './pbr.js';
|
|
2
|
+
import type { PBRInstances } from './pbr-instancing.js';
|
|
3
|
+
import type { BatchKind, BatchState, RowsState } from './draw-batch.js';
|
|
4
|
+
import type { MaterialExtension } from './material-extension.js';
|
|
5
|
+
import type { GLTFExtendedMaterials } from './asset.js';
|
|
6
|
+
/** The context every primitive of one draw call shares, compared field by field to share derivations between calls. */
|
|
7
|
+
export interface DrawFrame {
|
|
8
|
+
mode: string;
|
|
9
|
+
depthCompare: GPUCompareFunction | undefined;
|
|
10
|
+
format: GPUTextureFormat;
|
|
11
|
+
samples: number | undefined;
|
|
12
|
+
depthFormat: GPUTextureFormat;
|
|
13
|
+
section: GPUBuffer | undefined;
|
|
14
|
+
/** The transparency or transmission hook, the capture hook and the asset's extended-material hooks. */
|
|
15
|
+
oit: object | undefined;
|
|
16
|
+
hook: object | undefined;
|
|
17
|
+
hooks: GLTFExtendedMaterials | undefined;
|
|
18
|
+
/** The model's lighting effects in order. */
|
|
19
|
+
lighting: readonly LightingEffect[];
|
|
20
|
+
/**
|
|
21
|
+
* True when a native glass capture lends this target its per-surface snapshot (materials native-glass.js). Part of
|
|
22
|
+
* the context: a derivation made before the capture began (blendSpace 'linear' first seen) is not reused once it has.
|
|
23
|
+
*/
|
|
24
|
+
glass: boolean;
|
|
25
|
+
}
|
|
26
|
+
/** A derivation, valid for draws under `frame` (identity: the same call or run); see the file comment. */
|
|
27
|
+
export interface DrawDerivation {
|
|
28
|
+
nativeGlass?: boolean;
|
|
29
|
+
frame: DrawFrame;
|
|
30
|
+
source: MaterialExtension | undefined;
|
|
31
|
+
instances: PBRInstances | BatchKind | undefined;
|
|
32
|
+
topology: GPUPrimitiveTopology | undefined;
|
|
33
|
+
/** Sign of the node matrix determinant: mirrored nodes cull the other face. */
|
|
34
|
+
sign: number;
|
|
35
|
+
/** False when derived for a batch member: no pipeline built and no lighting group (draw-batch.ts). */
|
|
36
|
+
complete: boolean;
|
|
37
|
+
compact: boolean;
|
|
38
|
+
floatCount: number;
|
|
39
|
+
replacesTextures: boolean;
|
|
40
|
+
/** Set when the primitive has a material extension: those draws keep per-resource state and never share. */
|
|
41
|
+
extension: MaterialExtension | undefined;
|
|
42
|
+
pipeline: GPURenderPipeline;
|
|
43
|
+
/** Transmission's tint pipeline (multiplies what is behind) when the draw is tinted. */
|
|
44
|
+
tint: GPURenderPipeline | undefined;
|
|
45
|
+
/** True when the draw first multiplies what is behind by its tint (transmission). */
|
|
46
|
+
tinted: boolean;
|
|
47
|
+
blend: boolean;
|
|
48
|
+
state: PBRRenderState | undefined;
|
|
49
|
+
/** True when group 2 (shading, lighting and transparency bindings) is bound. */
|
|
50
|
+
effectBindings: boolean;
|
|
51
|
+
effect: {
|
|
52
|
+
entries: GPUBindGroupEntry[];
|
|
53
|
+
group: GPUBindGroup;
|
|
54
|
+
} | undefined;
|
|
55
|
+
tintEffect: {
|
|
56
|
+
entries: GPUBindGroupEntry[];
|
|
57
|
+
group: GPUBindGroup;
|
|
58
|
+
} | undefined;
|
|
59
|
+
mappedTint: boolean;
|
|
60
|
+
/** @internal Whether it was derived for all-white instanced vertices (index.ts `whiteDraw`): part of its context. */
|
|
61
|
+
white?: boolean;
|
|
62
|
+
/** False when the finished shader reads the model rows itself, so instanced batches cannot draw it. */
|
|
63
|
+
modelFree: boolean;
|
|
64
|
+
/** True when the finished shader reads the base colour only as the vertex colour's factor (index.ts `tintableCode`). */
|
|
65
|
+
tintable?: boolean;
|
|
66
|
+
/** @internal The GPU states of this derivation's blended batches, one per batch drawn in a frame (index.ts `drawBatch`). */
|
|
67
|
+
blendStates?: BatchState[];
|
|
68
|
+
/** @internal The same for its blended rows batches (`BatchKind.rows`). */
|
|
69
|
+
blendRows?: RowsState[];
|
|
70
|
+
/**
|
|
71
|
+
* @internal What draws of other material records may share an instanced draw with this one's, each reading its own
|
|
72
|
+
* uniform block (`BatchKind.rows`): the same object for derivations with the same pipeline and group 2 resources
|
|
73
|
+
* (`drawGroup`); undefined until the derivation is complete.
|
|
74
|
+
*/
|
|
75
|
+
group?: object;
|
|
76
|
+
/**
|
|
77
|
+
* @internal Whether this derivation's rows variant drew as `rowsOf` (another record's rows variant) does, checked at
|
|
78
|
+
* this derivation's version `rowsAt` and `rowsOf`'s version `rowsOfAt` (index.ts `rowsFit`).
|
|
79
|
+
*/
|
|
80
|
+
rowsOf?: DrawDerivation;
|
|
81
|
+
rowsAt?: number;
|
|
82
|
+
rowsOfAt?: number;
|
|
83
|
+
rowsOk?: boolean;
|
|
84
|
+
/** @internal The batch (draw-batch.ts) this derivation's last draw joined in run `joinedRun`, until that run draws it. */
|
|
85
|
+
joined?: object;
|
|
86
|
+
joinedRun?: object;
|
|
87
|
+
/** The whole uniform as derived; draws copy it and write their own node rows (16-47) and determinant (97). */
|
|
88
|
+
block: Float32Array;
|
|
89
|
+
/**
|
|
90
|
+
* @internal What the shader and pipeline were composed from, beyond the context (`frame`) and the fields above: the
|
|
91
|
+
* record's `shading.shaderRevision`, its shading object and render state, and `structure` (structureFlags). A later
|
|
92
|
+
* frame whose draw finds all of them unchanged keeps `pipeline` and `tint` (see `PBRModel.derive`).
|
|
93
|
+
*/
|
|
94
|
+
revision?: number;
|
|
95
|
+
shading?: object;
|
|
96
|
+
renderState?: object;
|
|
97
|
+
structure?: number;
|
|
98
|
+
/** `plainShape` of a compact record with no hook (index.ts), -1 otherwise: its stand-in for `revision`. */
|
|
99
|
+
plain?: number;
|
|
100
|
+
/**
|
|
101
|
+
* @internal The record's `shading.version` when this derivation was last made complete under the conditions that
|
|
102
|
+
* keep its pipeline (no lighting effects, a beauty-like pass); NaN otherwise. A later frame whose record reports the
|
|
103
|
+
* same version reuses the derivation whole (`steadyDerivation`).
|
|
104
|
+
*/
|
|
105
|
+
version?: number;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* The record fields beyond the shading hooks that decide a draw's shader text and pipeline, as one number: alpha mode,
|
|
109
|
+
* side flag, the tangent-frame switch, transmission tint, physical rows and their map count, and the shading's
|
|
110
|
+
* texture flags. Two derivations with equal flags (and equal revision, shading, render state and context) compose the
|
|
111
|
+
* same shader and pipeline.
|
|
112
|
+
*/
|
|
113
|
+
export declare function structureFlags(alphaMode: number, side: number, tangent: boolean, tint: boolean, physical: boolean, physicalMaps: boolean, texturedTint: boolean, replacesTextures: boolean, laterUV: boolean): number;
|
|
114
|
+
/** Per device: shader ids, pipelines and derivations by material record, shared by every model on the device. */
|
|
115
|
+
export interface DeviceDraws {
|
|
116
|
+
codes: Map<string, number>;
|
|
117
|
+
codeCount: number;
|
|
118
|
+
pipelines: Map<string, GPURenderPipeline>;
|
|
119
|
+
derivations: WeakMap<object, DrawDerivation[]>;
|
|
120
|
+
/** Draw groups (`DrawDerivation.group`) by pipeline and group 2 resources. */
|
|
121
|
+
groups: Map<string, object>;
|
|
122
|
+
}
|
|
123
|
+
export declare function deviceDraws(device: GPUDevice): DeviceDraws;
|
|
124
|
+
/**
|
|
125
|
+
* The draw group (`DrawDerivation.group`) of complete derivation `d`: one object per pipeline, uniform size, texture
|
|
126
|
+
* replacement and group 2 resources, so derivations of different material records that draw alike share it.
|
|
127
|
+
*/
|
|
128
|
+
export declare function drawGroup(draws: DeviceDraws, d: DrawDerivation): object;
|
|
129
|
+
/** A small stable number for `value` (pipeline keys name hooks and layouts by it). */
|
|
130
|
+
export declare function objectId(value: object | undefined): number;
|
|
131
|
+
/** True when `a` and `b` describe the same draw context. */
|
|
132
|
+
export declare function sameFrame(a: DrawFrame, b: DrawFrame): boolean;
|
|
133
|
+
/** True when two models' lighting lists hold the same effects in order. */
|
|
134
|
+
export declare function sameLighting(a: readonly LightingEffect[], b: readonly LightingEffect[]): boolean;
|
|
135
|
+
/** Most recent first; bounded so animated contexts (probe faces, resizes) cannot grow a material's list forever. */
|
|
136
|
+
export declare const derivationLimit = 32;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { GLTFExtendedMaterials } from './asset.js';
|
|
2
|
+
export type { ExtendedPlan } from './shader.js';
|
|
3
|
+
export type { GLTFExtendedMaterials } from './asset.js';
|
|
4
|
+
/**
|
|
5
|
+
* KHR_materials_iridescence, KHR_materials_anisotropy, KHR_materials_diffuse_transmission,
|
|
6
|
+
* KHR_materials_diffuse_roughness (draft), EXT_materials_bump (draft)
|
|
7
|
+
* and KHR_materials_volume_scatter (draft)
|
|
8
|
+
* for gltf/pbr, passed like a decoder: `loadGLTF(engine, url, {decoders: {materials: extendedMaterials}})` (also parseGLTF, parseGLTFAsync, the worker
|
|
9
|
+
* and progressive loaders). Without it gltf/pbr ignores those extensions (a file that requires one is rejected), so apps
|
|
10
|
+
* that never load them ship none of this WGSL. README "Extended materials".
|
|
11
|
+
*/
|
|
12
|
+
export declare const extendedMaterials: GLTFExtendedMaterials;
|
package/dist/extended.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as e,b as t,o as n}from"./shader-C29RtPAw.js";var r=(e,t,n,r,i)=>{let a=e??t;if(typeof a!=`number`||!Number.isFinite(Math.fround(a))||a<n||a>r)throw TypeError(`Invalid glTF `+i+`; re-export the file and check it with the glTF Validator`);return a},i={parse(e){let n=e.KHR_materials_iridescence,i=e.KHR_materials_anisotropy,a=e.KHR_materials_diffuse_transmission,o=e.EXT_materials_bump,s=e.KHR_materials_volume,c=e.KHR_materials_volume_scatter,l=e.KHR_materials_unlit||e.KHR_materials_pbrSpecularGlossiness?void 0:e.KHR_materials_diffuse_roughness,u=r(l?.diffuseRoughnessFactor,0,0,1,`diffuse roughness`),d=r(n?.iridescenceFactor,0,0,1,`iridescence`),f=r(i?.anisotropyStrength,0,0,1,`anisotropy strength`),p=r(a?.diffuseTransmissionFactor,0,0,1,`diffuse transmission`),m=r(o?.bumpFactor,1,-1/0,1/0,`bump factor`),h=!!o?.bumpTexture&&m!==0;if(o?.heightSpace!==void 0&&o.heightSpace!==`world`&&o.heightSpace!==`object`)throw TypeError(`Invalid glTF bump height space; use "world" or "object", re-export the file and check it with the glTF Validator`);let g=c?.multiscatterColorFactor??[0,0,0],_=s?.attenuationDistance??1/0,v=s?.thicknessFactor??0,y=s?.attenuationColor??[1,1,1];if(!Array.isArray(g)||g.length!==3)throw TypeError(`Invalid glTF multi-scatter color; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let b=g.map(e=>r(e,0,0,1,`multi-scatter color`)),x=y.map(e=>t(e,_)),S=!!c&&b.some(e=>e>0)&&v>0&&x.some(e=>e>0)&&(!!p||!!e.KHR_materials_transmission?.transmissionFactor),C=!!s?.thicknessTexture&&!!e.KHR_materials_transmission;if(!d&&!f&&!p&&!h&&!S&&!u&&!C)return;let w=a?.diffuseTransmissionColorFactor??[1,1,1],T=r(i?.anisotropyRotation,0,-1/0,1/0,`anisotropy rotation`);if(!Array.isArray(w)||w.length!==3)throw TypeError(`Invalid glTF diffuse transmission color; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);return{features:{iridescence:!!d,anisotropy:!!f,diffuseTransmission:!!p,bump:h,scatter:S,...u?{diffuseRoughness:!0}:void 0},maps:[d?n.iridescenceTexture:void 0,d?n.iridescenceThicknessTexture:void 0,f?i.anisotropyTexture:void 0,p?a.diffuseTransmissionTexture:void 0,p?a.diffuseTransmissionColorTexture:void 0,h?o.bumpTexture:void 0,S?c.multiscatterColorTexture:void 0,S||C?s.thicknessTexture:void 0,...u&&l.diffuseRoughnessTexture?[l.diffuseRoughnessTexture]:[]],rows:[d,r(n?.iridescenceIor,1.3,1,1/0,`iridescence IOR`),r(n?.iridescenceThicknessMinimum,100,0,1/0,`iridescence thickness`),r(n?.iridescenceThicknessMaximum,400,0,1/0,`iridescence thickness`),f,Math.cos(T),Math.sin(T),u,p,...w.map(e=>r(e,0,0,1,`diffuse transmission color`)),m,+(o?.heightSpace===`object`),0,0,...b,r(c?.scatterAnisotropy,0,-1,1,`scatter anisotropy`),...x,v]}},plan:e,shader:n};export{i as extendedMaterials};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/group.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The bindings each group of `code` holds that `entries` (the pipeline's entry points) statically use: a resource is
|
|
3
|
+
* statically used when a function reachable from an entry point names it (WGSL, "Statically Accessed"), and a
|
|
4
|
+
* `layout: 'auto'` pipeline's group layouts hold only those (WebGPU, "default pipeline layout"). So a group built for
|
|
5
|
+
* that pipeline may bind no other: a material map that only another entry reads (the transmission tint's thickness
|
|
6
|
+
* map, KB-OIT-BLENDTHICK1) must stay out of a draw whose entry never reads it. Shader text ships without comments
|
|
7
|
+
* (KB-WGSL1), so a name in it is a use. Cached by code and entry points.
|
|
8
|
+
*/
|
|
9
|
+
export declare function staticBindings(code: string, entries: readonly string[]): Map<number, Set<number>>;
|
|
10
|
+
/** Records which bindings of each group `pipeline` (a `layout: 'auto'` pipeline of `code`) uses, for `pipelineGroup`. */
|
|
11
|
+
export declare function notePipeline(pipeline: GPURenderPipeline, code: string, descriptor: GPURenderPipelineDescriptor): void;
|
|
12
|
+
/**
|
|
13
|
+
* Bind group `index` of an auto-layout pipeline. Entries the pipeline's entry points do not use are left out when the
|
|
14
|
+
* pipeline was noted (`notePipeline`): its layout has no slot for them. With no entries it is one empty group of an
|
|
15
|
+
* explicit layout: WebKit gives an invalid layout for a group past the last one the shader uses, which a material
|
|
16
|
+
* without textures reaches, and the draw then fails. Every browser accepts the explicit empty group at any index.
|
|
17
|
+
*/
|
|
18
|
+
export declare function pipelineGroup(device: GPUDevice, pipeline: GPURenderPipeline, index: number, entries: GPUBindGroupEntry[]): GPUBindGroup;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=67108864;export{e as t};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Most pixels one glTF image may decode to: 8192 x 8192 (256 MiB as RGBA8), the side every WebGPU device supports
|
|
3
|
+
* (`maxTextureDimension2D` 8192). A film close-up's 8K map loads; a side over the device's limit is still refused at
|
|
4
|
+
* upload, and all images together stay within the decoded budget (4x `maxDownloadBytes`). 4096 x 4096 before 2026-11-17.
|
|
5
|
+
*/
|
|
6
|
+
export declare const MAX_IMAGE_PIXELS = 67108864;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import type { EngineKernel, Mesh as MeshHandle } from '@margoengine/core';
|
|
2
|
+
import { Geometry, type Engine } from '@margoengine/core/extension';
|
|
3
|
+
import type { GLTFWarning } from './warning.js';
|
|
4
|
+
export type { GLTFWarning } from './warning.js';
|
|
5
|
+
import type { GLTFDocument as Document, GLTFPrimitive } from './shared/gltf.js';
|
|
6
|
+
/** A parsed glTF scene: the root mesh handle, every mesh and node handle, and dispose() to release them. */
|
|
7
|
+
export interface Model {
|
|
8
|
+
root: MeshHandle;
|
|
9
|
+
/** The drawn meshes, one per triangle primitive, in the order of `nodes` and then primitive order. */
|
|
10
|
+
meshes: readonly MeshHandle[];
|
|
11
|
+
/**
|
|
12
|
+
* The loaded scene's nodes, depth first in file order: each node, then its children as the file lists them, then
|
|
13
|
+
* the next scene root (KB-GLTFA A7). Nodes outside the scene are not here; gltf/pbr's `nodes` is indexed by node.
|
|
14
|
+
*/
|
|
15
|
+
nodes: readonly MeshHandle[];
|
|
16
|
+
/** Problems in the file the loader worked around, each listed once (`code` says which; KB-GLTFA A2), as gltf/pbr's. */
|
|
17
|
+
readonly warnings: readonly GLTFWarning[];
|
|
18
|
+
dispose(): void;
|
|
19
|
+
/** The same as `dispose()`, so `using model = parseGLTF(...)` releases it (KB-GLTFA A8). */
|
|
20
|
+
[Symbol.dispose](): void;
|
|
21
|
+
}
|
|
22
|
+
/** A file on its way through the loader. An extension may replace `doc` and `buffers`, never change what they hold. */
|
|
23
|
+
export interface GLTFFile {
|
|
24
|
+
doc: Document;
|
|
25
|
+
/** Buffer data, in document order. */
|
|
26
|
+
buffers: readonly Uint8Array[];
|
|
27
|
+
/** The `maxNodes` option, if set. */
|
|
28
|
+
maxNodes?: number;
|
|
29
|
+
/** Fetches a URI found in the file, under `loadGLTF`'s rules. Absent when the file came from memory. */
|
|
30
|
+
fetch?(uri: string): Promise<Uint8Array>;
|
|
31
|
+
}
|
|
32
|
+
/** What the loader made of a file, for `GLTFExtension.finish`. */
|
|
33
|
+
export interface GLTFBuilt {
|
|
34
|
+
engine: Engine;
|
|
35
|
+
/** Each primitive in the file. `expanded` holds the source vertex of each geometry vertex when normals were generated. */
|
|
36
|
+
primitives: readonly {
|
|
37
|
+
geometry: Geometry;
|
|
38
|
+
source: GLTFPrimitive;
|
|
39
|
+
expanded?: Uint32Array;
|
|
40
|
+
}[];
|
|
41
|
+
/** The mesh of each node by node index; empty where a node is not in the loaded scene. */
|
|
42
|
+
nodes: readonly (MeshHandle | undefined)[];
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* One optional feature of the light loader, passed in `GLTFOptions.extensions`. Each lives in its own entry, so a file
|
|
46
|
+
* that needs none of them costs none of their bytes.
|
|
47
|
+
*/
|
|
48
|
+
export interface GLTFExtension {
|
|
49
|
+
/** The glTF extension names this one implements: `extensionsRequired` may list them. */
|
|
50
|
+
readonly handles: readonly string[];
|
|
51
|
+
/** Accept scenes without renderable meshes, for data-only imports. Default false. */
|
|
52
|
+
readonly allowEmptyScene?: boolean;
|
|
53
|
+
/** Reads vertex attribute `semantic` from accessor `id`, as float xyz; undefined leaves it to the loader. */
|
|
54
|
+
attribute?(file: GLTFFile, semantic: string, id: number): Float32Array | undefined;
|
|
55
|
+
/** Asynchronous work before anything is built. An extension with `load` needs `parseGLTFAsync` or `loadGLTF`. */
|
|
56
|
+
load?(file: GLTFFile, signal?: AbortSignal): Promise<void>;
|
|
57
|
+
/** Runs after every `load`, before the loader reads the document. */
|
|
58
|
+
read?(file: GLTFFile): void;
|
|
59
|
+
/** Runs on the finished model; may wrap `model.dispose`. A throw rolls the model back. */
|
|
60
|
+
finish?(model: Model, file: GLTFFile, built: GLTFBuilt): void;
|
|
61
|
+
/**
|
|
62
|
+
* Runs when an asynchronous load fails or is aborted after `load` ran: an extension releases what `load` holds for a
|
|
63
|
+
* model that will never take it (decoded images, for example). Not called after a load that succeeded.
|
|
64
|
+
*/
|
|
65
|
+
abandon?(file: GLTFFile): void;
|
|
66
|
+
}
|
|
67
|
+
/** Options for parseGLTF and loadGLTF. */
|
|
68
|
+
export interface GLTFOptions {
|
|
69
|
+
/** Optional features from the `@margoengine/gltf/*` entries, for example `[quantized]`. Default none. */
|
|
70
|
+
extensions?: readonly GLTFExtension[];
|
|
71
|
+
/** Most glTF nodes the file may have, each one a core mesh (default 100,000; up to core's 8,388,608 entities). */
|
|
72
|
+
maxNodes?: number;
|
|
73
|
+
/**
|
|
74
|
+
* URL prefixes (for example `https://cdn.example.com/models/`) that buffer URIs inside the file may point to besides
|
|
75
|
+
* the file's own directory, matched on a path-segment boundary. Default none: absolute, cross-origin and
|
|
76
|
+
* `../`-escaping URIs throw a TypeError, and so does a redirect that ends outside these places.
|
|
77
|
+
*/
|
|
78
|
+
allowedURLs?: readonly string[];
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Parses glTF JSON, an object or GLB bytes into core meshes, one per node. Rejects absolute, cross-origin and `../` buffer URIs unless allowed. @throws TypeError for a malformed file; RangeError over the size limits.
|
|
82
|
+
*/
|
|
83
|
+
export declare function parseGLTF(instance: EngineKernel, input: string | object | ArrayBuffer | ArrayBufferView, suppliedBuffers?: Array<ArrayBuffer | ArrayBufferView>, options?: GLTFOptions): Model;
|
|
84
|
+
/** parseGLTF for extensions with asynchronous work, such as `textured`. Aborts with `signal`. */
|
|
85
|
+
export declare function parseGLTFAsync(instance: EngineKernel, input: string | object | ArrayBuffer | ArrayBufferView, suppliedBuffers?: Array<ArrayBuffer | ArrayBufferView>, { signal, ...options }?: GLTFOptions & {
|
|
86
|
+
signal?: AbortSignal;
|
|
87
|
+
}): Promise<Model>;
|
|
88
|
+
/**
|
|
89
|
+
* Fetches a .gltf or .glb over HTTP(S), and its external buffers relative to it, through `fetch` (default
|
|
90
|
+
* `globalThis.fetch`; for example an AssetCache's or a LoadingManager's `fetch`), then parses it like parseGLTF.
|
|
91
|
+
*/
|
|
92
|
+
export declare function loadGLTF(engine: EngineKernel, url: string | URL, { signal, maxNodes, allowedURLs, extensions, fetch: get, }?: GLTFOptions & {
|
|
93
|
+
signal?: AbortSignal;
|
|
94
|
+
fetch?: typeof fetch;
|
|
95
|
+
}): Promise<Model>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{t as loadGLTF,n as parseGLTF,r as parseGLTFAsync}from"./src-Btvz5f6i.js";
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{margoError as e}from"@margoengine/core/extension";var t={arrayStride:96,stepMode:`instance`,attributes:[5,6,7,8,9,10].map((e,t)=>({shaderLocation:e,offset:t*16,format:`float32x4`}))};function n(e,t,n,r){let i=n*24;for(let n=0;n<4;n++)for(let a=0;a<4;a++)r[n*4+a]=e[a]*t[i+n*4]+e[4+a]*t[i+n*4+1]+e[8+a]*t[i+n*4+2]+e[12+a]*t[i+n*4+3];return r}var r=/* @__PURE__ */ new Map;function i(t){let n=r.get(t);if(n!==void 0)return n;let i=(t,r)=>{let i=n.replace(t,r);if(i===n)throw e(`failed`,`PBR instancing patch target missing; the shader source changed, update the patch: `+t);n=i};return n=t,i(/(struct Out \{[^}]*?)\n\}/,`$1, @location(5) @interpolate(flat) mirror:f32
|
|
2
|
+
}`),i(`@vertex fn vertex(i:Input)->Out {`,`struct Instance {@location(5) m0:vec4f, @location(6) m1:vec4f, @location(7) m2:vec4f, @location(8) m3:vec4f, @location(9) tint:vec4f, @location(10) uvt:vec4f}
|
|
3
|
+
@vertex fn vertex(i:Input,k:Instance)->Out {
|
|
4
|
+
let margoInstanceMatrix=mat4x4f(k.m0,k.m1,k.m2,k.m3);${t.includes(`margoInstanceColor`)?` let margoInstanceColor=k.tint;`:``}${t.includes(`margoInstanceUV`)?` let margoInstanceUV=k.uvt;`:``}
|
|
5
|
+
let margoI=f.model*margoInstanceMatrix; let margoS=select(-1.0,1.0,dot(margoI[0].xyz,cross(margoI[1].xyz,margoI[2].xyz))>=0);`),i(`let p=f.model*vec4f(`,`let p=margoI*vec4f(`),n=n.replace(`let margoObjectModel=f.model;`,`let margoObjectModel=margoI;`),i(/o\.normal=\(f\.normalMatrix\*vec4f\((i\.normal\.xyz|margoNormal),0\)\)\.xyz;/,`o.normal=mat3x3f(cross(margoI[1].xyz,margoI[2].xyz),cross(margoI[2].xyz,margoI[0].xyz),cross(margoI[0].xyz,margoI[1].xyz))*$1*margoS;`),i(`(f.model*vec4f(i.tangent.xyz,0)).xyz,i.tangent.w*f.coordsB.y)`,`(margoI*vec4f(i.tangent.xyz,0)).xyz,i.tangent.w*margoS)`),i(/o\.uv=i\.uv; o\.color=(i\.color|vec4f\(1\));/,`o.uv=i.uv*k.uvt.xyxy+k.uvt.zwzw; o.color=$1*k.tint; o.mirror=margoS;`),i(`let facing=front==(f.coordsB.y>0);`,`let facing=front==(i.mirror>0);`),r.size>=64&&r.clear(),r.set(t,n),n}var a=e=>Math.floor(65536/(e*4)),o=/* @__PURE__ */ new Map,s=`@group(0) @binding(0) var<uniform> f:Frame;`;function c(t,n){let r=n+`:`+t,i=o.get(r);if(i!==void 0)return i||void 0;if(i=t.includes(s)?t.replace(/(?<![\w.])f\.(?=[A-Za-z_])/g,`margoRows[margoK].`):``,i&&/(?<![\w.])f(?!\w)/.test(i.replace(s,``))&&(i=``),i){let t=(t,n)=>{let r=i.replace(t,n);if(r===i)throw e(`failed`,`PBR instance rows patch target missing; the shader source changed, update the patch: `+t);i=r};t(s,`@group(0) @binding(0) var<uniform> margoRows:array<Frame,${n}>;\nvar<private> margoK:u32;`),t(/(struct Out \{[^}]*?)\n\}/,(e,t)=>{let n=0;for(let[,e]of t.matchAll(/@location\((\d+)\)/g))n=Math.max(n,+e+1);return`${t}, @location(${n}) @interpolate(flat) margoK:u32\n}`}),t(`@vertex fn vertex(i:Input,k:Instance)->Out {`,i.includes(`ndInstance:u32`)?`@vertex fn vertex(i:Input,k:Instance)->Out {margoK=i.ndInstance%${n}u;`:`@vertex fn vertex(i:Input,k:Instance,@builtin(instance_index) margoN:u32)->Out {margoK=margoN%${n}u;`),t(`o.mirror=margoS;`,`o.mirror=margoS; o.margoK=margoK;`),t(/@fragment fn \w+\(i:Out[^)]*\)[^{]*\{/g,e=>e+`margoK=i.margoK;`)}return o.size>=64&&o.clear(),o.set(r,i),i||void 0}export{n as a,t as i,a as n,c as r,i as t};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Patches a PBR shader's WGSL source so it reads per-instance transforms; results are cached by source text. */
|
|
2
|
+
export declare function instancedShader(code: string): string;
|
|
3
|
+
/** Uniform blocks of `floats` floats one 64 KiB uniform binding holds (the WebGPU minimum of maxUniformBufferBindingSize). */
|
|
4
|
+
export declare const rowsPerBinding: (floats: number) => number;
|
|
5
|
+
/**
|
|
6
|
+
* Patches a finished instanced PBR shader (`instancedShader`, then every later edit) so each instance reads its own
|
|
7
|
+
* uniform block: binding 0 becomes an array of `count` blocks, every `f.` read becomes a read of block `margoK`, and
|
|
8
|
+
* the vertex stage and every fragment entry set `margoK` (`instance_index % count`, passed flat). A draw of more
|
|
9
|
+
* instances binds one array per `count` of them and starts each at a multiple of `count` (`firstInstance`). The reads
|
|
10
|
+
* go to the uniform array itself: copying the block into a private struct put its dynamically indexed UV rows in local
|
|
11
|
+
* memory and cost 1.5 ms of GPU time on 4,096 boxes. Undefined when the shader uses `f` other than as `f.field` (a
|
|
12
|
+
* local of that name, or `f` passed whole): such draws keep their own uniforms.
|
|
13
|
+
*/
|
|
14
|
+
export declare function rowsShader(code: string, count: number): string | undefined;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { GLTFExtension } from './index.js';
|
|
2
|
+
/**
|
|
3
|
+
* Lets the light loader read `EXT_mesh_gpu_instancing`: each instance becomes a child node of the instanced node, on the
|
|
4
|
+
* shared mesh, and core draws all of them as one instanced draw per primitive. TRANSLATION, ROTATION and SCALE are read,
|
|
5
|
+
* in float or quantized form; custom attributes are ignored. An instance costs one core mesh plus one per primitive, and
|
|
6
|
+
* every instance counts toward `maxNodes`. Instances show up in `model.meshes` and `model.nodes` like any node.
|
|
7
|
+
* @example const model = await loadGLTF(engine, '/forest.glb', { extensions: [instancing], maxNodes: 500_000 });
|
|
8
|
+
*/
|
|
9
|
+
export declare const instancing: GLTFExtension;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./limits-_LZ441oV.js";import{r as t}from"./accessor-CU_1uSZ1.js";import{MargoError as n}from"@margoengine/math/errors";var r=`EXT_mesh_gpu_instancing`,i=e=>/* @__PURE__ */ TypeError(`Invalid glTF ${e}; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`),a=e=>e.type===`VEC3`&&[5126,5120,5121,5122,5123].includes(e.componentType),o=e=>e.type===`VEC4`&&(e.componentType===5126||e.normalized===!0&&[5120,5122].includes(e.componentType));function s(e,n,r,a){if(n===void 0)return;let o=t(e,n,r,a);if(!o.every(Number.isFinite))throw i(`instance attributes`);return o}function c(e,t,c,l){let{attributes:u}=t.extensions[r];if(t.mesh===void 0||!u)throw i(`instanced node`);let d=s(e,u.TRANSLATION,3,a),f=s(e,u.ROTATION,4,o),p=s(e,u.SCALE,3,a),m=d?d.length/3:f?f.length/4:p?p.length/3:0;if(!m||d&&d.length!==m*3||f&&f.length!==m*4||p&&p.length!==m*3)throw i(`instance attributes`);if(c+m>l)throw new n(`unsupported`,`Too many glTF nodes (${c+m} > ${l}; raise the maxNodes option, or load it with @margoengine/gltf/pbr, which draws instances without nodes)`);let h=[];for(let e=0;e<m;e++){let n={mesh:t.mesh};if(d&&(n.translation=[...d.subarray(e*3,e*3+3)]),p&&(n.scale=[...p.subarray(e*3,e*3+3)]),f){let t=f.subarray(e*4,e*4+4),r=Math.hypot(...t);if(!(r>0))throw i(`instance rotation`);n.rotation=[...t].map(e=>e/r)}h.push(n)}let{mesh:g,extensions:_,...v}=t,{[r]:y,...b}=_,x={...v,children:[...t.children??[],...h.map((e,t)=>c+t)]};return Object.keys(b).length&&(x.extensions=b),{node:x,instances:h}}var l={handles:[r],read(t){let n=[...t.doc.nodes??[]],i=e(`maxNodes`,t.maxNodes);for(let e=0,a=n.length;e<a;e++){if(!n[e]?.extensions?.[r])continue;let{node:a,instances:o}=c(t,n[e],n.length,i);n[e]=a;for(let e of o)n.push(e)}t.doc={...t.doc,nodes:n}}};export{l as instancing};
|