@margoengine/gltf 0.1.0 → 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 -201
- package/NOTICE +4 -4
- package/README.md +1754 -1438
- package/dist/accessor-CU_1uSZ1.js +1 -0
- package/dist/asset-DN3ocEdY.js +4 -0
- package/dist/asset-entry.js +1 -1
- package/dist/asset.d.ts +76 -0
- package/dist/audio.js +1 -1
- package/dist/auto.js +1 -1
- package/dist/compression-CUOCmjmE.js +1 -0
- package/dist/compression.d.ts +6 -0
- package/dist/dds.js +1 -1
- package/dist/default-materials.d.ts +3 -1
- package/dist/default-transmission.d.ts +13 -0
- package/dist/extended.js +1 -1
- package/dist/group.d.ts +15 -3
- package/dist/index.d.ts +11 -0
- package/dist/index.js +1 -1
- package/dist/{instanced-shader-BebTnbkj.js → instanced-shader-C9ZMazvo.js} +1 -1
- package/dist/instancing.js +1 -1
- package/dist/lights.js +1 -1
- package/dist/material-draw-state-GKiHDb0p.js +1 -0
- package/dist/material-draw.js +1 -1
- package/dist/meshopt.js +1 -1
- package/dist/mipmaps-38NmjDc3.js +21 -0
- package/dist/model-C77ATxi1.js +25 -0
- package/dist/model-entry.js +1 -1
- package/dist/model.d.ts +84 -7
- package/dist/native-glass-D85twud0.js +19 -0
- package/dist/pack-DdxRO8k6.js +1 -0
- package/dist/pbr-instancing.js +1 -1
- package/dist/pbr.js +1 -1
- package/dist/physics.js +1 -1
- package/dist/prepare.js +1 -1
- package/dist/progressive-lod.d.ts +13 -0
- package/dist/progressive.d.ts +5 -2
- package/dist/progressive.js +3 -3
- package/dist/quantized.js +1 -1
- package/dist/report.js +1 -1
- package/dist/scene-data.js +1 -1
- package/dist/scene-scope-CZDEkd24.js +2 -2
- package/dist/scene.js +3 -3
- package/dist/{shader-DPqfUcmp.js → shader-C29RtPAw.js} +43 -39
- package/dist/shader.d.ts +24 -0
- package/dist/shared/caster.d.ts +159 -152
- package/dist/shared/gltf.d.ts +257 -257
- package/dist/shared/iridescence.d.ts +2 -2
- package/dist/shared/prepared-geometry.d.ts +8 -8
- package/dist/soft-mesh.d.ts +39 -1
- package/dist/soft-mesh.js +2 -2
- package/dist/spec-gloss.js +2 -2
- package/dist/splats.js +1 -1
- package/dist/src-Btvz5f6i.js +4 -0
- package/dist/stream-CrfNNCRd.js +1 -0
- package/dist/stream.d.ts +20 -3
- 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-stream-Cu_XpyVO.js +3 -3
- package/dist/textured.js +3 -3
- package/dist/transmission.d.ts +81 -0
- package/dist/transmission.js +66 -0
- package/dist/version-B6NE5cJf.js +1 -0
- package/dist/vertex-inputs.d.ts +6 -0
- package/dist/{unit-light-DvtsuFYP.js → warning-UqjZyyqW.js} +2 -22
- package/dist/warning.d.ts +24 -0
- package/dist/worker.d.ts +1 -1
- package/dist/worker.js +3 -3
- package/dist/workers/gltf.js +36 -36
- package/dist/workers/progressive.js +1 -1
- package/package.json +234 -213
- package/dist/accessor-nVsu_f1L.js +0 -1
- package/dist/asset-1b8ejkZX.js +0 -4
- package/dist/compression-D4IkO5vE.js +0 -1
- package/dist/errors-THVaUwlL.js +0 -1
- package/dist/material-draw-state-BHeTb1FP.js +0 -1
- package/dist/model-iRvuj19h.js +0 -39
- package/dist/optimize-7SEzNA23.js +0 -1
- package/dist/pack-BVDYuqZe.js +0 -1
- package/dist/src-WMRHArDp.js +0 -4
- package/dist/stream-C3bKMy1B.js +0 -1
- package/dist/version-BmU1nesQ.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e,t}from"./accessor-DuqjpuxI.js";import{fault as n,rangeError as r,typeError as i}from"@margoengine/math/helpers";var a=(e,t,n=0)=>{if(typeof e!=`number`||!Number.isSafeInteger(e)||e<n)throw i(`Invalid glTF ${t}`,`gltf-invalid`);return e},o=(e,t,n)=>{let r=e?.[a(t,n)];if(!r||typeof r!=`object`||Array.isArray(r))throw i(`Missing glTF ${n}`,`gltf-invalid`);return r},s=/* @__PURE__ */ new Map([[5120,127],[5121,255],[5122,32767],[5123,65535]]);function c({doc:i,buffers:c},l,u,d,f=!1){let p=o(i.accessors,l,`accessor`);if(p.bufferView===void 0&&!p.sparse){if(!d(p))throw n(`unsupported`,`Unsupported glTF accessor for the light loader`,`gltf-light`);let e=a(p.count,`accessor count`,1);if(e>1e6)throw n(`unsupported`,`glTF accessor holds over one million values, the light loader limit`,`gltf-light`);return f?new Uint32Array(e):new Float32Array(e*u)}let m=o(i.bufferViews,p.bufferView,`bufferView`),h=c[a(m.buffer,`buffer reference`)];if(!h||p.sparse||!d(p))throw n(`unsupported`,`Unsupported glTF accessor for the light loader`,`gltf-light`);let g=t[p.componentType],_=a(p.count,`accessor count`,1),v=a(p.byteOffset??0,`accessor offset`),y=a(m.byteOffset??0,`view offset`),b=a(m.byteLength,`view length`,1),x=a(m.byteStride??g*u,`stride`,g*u);if(_>1e6)throw n(`unsupported`,`glTF accessor holds over one million values, the light loader limit`,`gltf-light`);if(y+b>h.length||v+(_-1)*x+u*g>b||y%g||v%g||x%g||x>252||f&&m.byteStride!==void 0)throw r(`Invalid glTF accessor bounds/stride`,`gltf-invalid`);let S=new DataView(h.buffer,h.byteOffset+y,b),C=f?new Uint32Array(_):new Float32Array(_*u),w=p.normalized?s.get(p.componentType):void 0;for(let t=0;t<_;t++)for(let n=0;n<u;n++){let r=e(S,v+t*x+n*g,p.componentType);C[t*u+n]=w?Math.max(r/w,-1):r}return C}export{a as n,c as r,o as t};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{a as e,c as t,d as n,l as r,o as i,s as a,t as o,u as s}from"./version-B6NE5cJf.js";import{n as c,t as l}from"./limits-_LZ441oV.js";import{n as u,t as d}from"./accessor-DuqjpuxI.js";import"./image-limit-DvFSfR5T.js";import{t as f}from"./stroke-width-B2cnYGgn.js";import{margoError as p}from"@margoengine/math/helpers";var m=262144,h=1024,g=1048576,_=16777216;function v(e=m){if(!Number.isInteger(e)||e<1024||e>1048576)throw RangeError(`maxPartVertices must be an integer from ${h} to ${g} (default ${m})`);return e}function y(e,t,n,r,i){let a=e.length/t,o=1/0,s=1/0,c=1/0,l=-1/0,u=-1/0,d=-1/0;for(let e=0;e<r*i;e+=i){let t=n[e],r=n[e+1],i=n[e+2];t<o&&(o=t),t>l&&(l=t),r<s&&(s=r),r>u&&(u=r),i<c&&(c=i),i>d&&(d=i)}let f=1023.999/(Math.max(l-o,u-s,d-c)||1),p=f,m=f,h=new Uint32Array(a),g=e=>(e=(e|e<<16)&50331903,e=(e|e<<8)&50393103,e=(e|e<<4)&51130563,(e|e<<2)&153391689);for(let r=0,l=0;r<a;r++,l+=t){let a=0,u=0,d=0;for(let r=0;r<t;r++){let t=e[l+r]*i;a+=n[t],u+=n[t+1],d+=n[t+2]}h[r]=(g((a/t-o)*f|0)<<2|g((u/t-s)*p|0)<<1|g((d/t-c)*m|0))>>>0}let _=new Uint32Array(a),v=new Uint32Array(a);for(let e=0;e<a;e++)_[e]=e;let y=/* @__PURE__ */ new Uint32Array(1024);for(let e=0;e<30;e+=10){y.fill(0);for(let t=0;t<a;t++)y[h[t]>>>e&1023]++;for(let e=0,t=0;e<1024;e++){let n=y[e];y[e]=t,t+=n}for(let t=0;t<a;t++){let n=_[t];v[y[h[n]>>>e&1023]++]=n}[_,v]=[v,_]}return _}function b(e,t,n,r,i,a=3){let o=e.length/t,s=i?y(e,t,i,n,a):null,c=new Int32Array(n).fill(-1),l=new Uint32Array(r),u=new Uint32Array(e.length),d=[],f=0,p=0,m=0,h=()=>{d.push({indices:u.slice(p,m),vertexMap:l.slice(0,f)});for(let e=0;e<f;e++)c[l[e]]=-1;f=0,p=m};for(let n=0;n<o;n++){let i=(s?s[n]:n)*t,a=0;for(let n=0;n<t;n++){let t=e[i+n];if(c[t]>=0)continue;let r=!1;for(let a=0;a<n;a++)e[i+a]===t&&(r=!0);r||a++}f+a>r&&h();for(let n=0;n<t;n++){let t=e[i+n];c[t]<0&&(c[t]=f,l[f++]=t),u[m++]=c[t]}}return m>p&&h(),d}function ee(e,t,n=!1){let{vertices:r,indices:i,uvs:a}=e,o=r.length/20;if(!(o>t)||!(r instanceof Float32Array)||!(i instanceof Uint32Array)||i.length%3)return[e];if(o>16777216)throw RangeError(`Prepared PBR geometry has more than ${_} vertices; split it into several primitives`);for(let e=0;e<i.length;e++)if(i[e]>=o)throw RangeError(`Invalid prepared PBR geometry; run prepareAsset again`);let s=b(i,3,o,t,n?null:r,20);return s.map(({indices:t,vertexMap:n},i)=>{let o=n.length,c=new Float32Array(o*20),l=a?new Float32Array(o*4):void 0;for(let e=0;e<o;e++)c.set(r.subarray(n[e]*20,n[e]*20+20),e*20),l&&l.set(a.subarray(n[e]*4,n[e]*4+4),e*4);return{...e.interpolatedDirections?{interpolatedDirections:!0}:{},vertices:c,indices:t,...e.topology?{topology:e.topology}:{},...l?{uvs:l}:{},part:{index:i,count:s.length,vertexMap:n}}})}var x=e=>!!e?.extensions&&typeof e.extensions==`object`&&`KHR_gaussian_splatting`in e.extensions,S=e=>!!e.meshes?.some(e=>e?.primitives?.some(x)),te=[`KHR_materials_clearcoat`,`KHR_materials_transmission`,`KHR_materials_ior`,`KHR_materials_dispersion`,`KHR_materials_volume`,`KHR_materials_sheen`,`KHR_materials_specular`,`KHR_materials_iridescence`,`KHR_materials_anisotropy`,`KHR_materials_diffuse_transmission`,`KHR_materials_diffuse_roughness`,`EXT_materials_bump`,`KHR_materials_volume_scatter`];async function ne(e,t={}){return t.dds===void 0&&e.textures?.some(e=>e?.extensions?.MSFT_texture_dds!==void 0)&&(t={...t,dds:(await import(`./dds.js`)).ddsTextures}),t.splats===void 0&&S(e)?t={...t,splats:(await import(`./splats.js`)).gaussianSplats}:t.splats===!1&&(t={...t,splats:void 0}),t.strokes===void 0&&f(e)?t={...t,strokes:(await import(`./strokes.js`)).wideStrokes}:t.strokes===!1&&(t={...t,strokes:void 0}),t.materials===void 0?e.materials?.some(e=>e?.extensions?.KHR_materials_pbrSpecularGlossiness!==void 0)?{...t,materials:(await import(`./spec-gloss.js`)).specGlossMaterials}:(e.materials??[]).some(e=>!!e?.extensions&&typeof e.extensions==`object`&&te.some(t=>t in e.extensions))?{...t,materials:(await import(`./extended.js`)).extendedMaterials}:t:t.materials?t:{...t,materials:void 0}}var C=/* @__PURE__ */ new WeakMap;function w(e){for(let t of e.doc.meshes??[])for(let e of t.primitives??[])if(e.extensions?.KHR_draco_mesh_compression)return!0;return!1}function T(e,t){if(!t.extensions?.KHR_draco_mesh_compression)return;let n=C.get(e)?.get(t);if(!n)throw p(`state`,`Draco geometry requires parseGLTFAsync or loadGLTF`);return n}async function E(e,t){let{decodeImage:n}=await import(
|
|
2
|
+
/* @vite-ignore */
|
|
3
|
+
/* webpackIgnore: true */
|
|
4
|
+
`@margoengine/decoders/image`);return n(e,{signal:t})}function D(e){return{decode:async(t,n)=>{let r=await e.decode(t,n),i=r.vertexCount??r.positions?.length/3,a=r.attributes&&Object.fromEntries(Object.entries(r.attributes).map(([e,t])=>{let r=t;return[e,{...r,itemSize:r.itemSize??r.array.length/i,componentType:r.componentType??n.componentTypes[e]}]}));return{...r,vertexCount:i,attributes:a,indices:r.indices??(Number.isSafeInteger(i)&&i>=3&&i<=16777216?Uint32Array.from({length:i},(e,t)=>t):void 0)}}}}var O=e=>!!e.meshes?.some(e=>e?.primitives?.some(e=>e?.extensions?.KHR_draco_mesh_compression))||S(e),re=e=>O(e)||!!e.textures?.some(e=>e?.extensions?.KHR_texture_basisu)||!!e.images?.some(e=>e?.mimeType===`image/ktx2`),k=536870912,A=(e,t)=>/* @__PURE__ */ RangeError(`${e} (${t} bytes; raise the maxDownloadBytes option)`),j=`version https://git-lfs`;function M(e,t){if(!(e.length<23)){for(let t=0;t<23;t++)if(e[t]!==j.charCodeAt(t))return;throw p(`failed`,`${t} is a Git LFS pointer file, not the asset; run git lfs pull and serve the real file; see https://margoengine.com/errors#git-lfs`)}}function ie(e=k){if(!Number.isSafeInteger(e)||e<=0)throw RangeError(`maxDownloadBytes must be a positive integer`);return e}var N=/* @__PURE__ */ new Set(/* @__PURE__ */ `KHR_mesh_quantization.KHR_texture_transform.KHR_materials_emissive_strength.KHR_materials_unlit.KHR_lights_punctual.KHR_node_visibility.KHR_materials_clearcoat.KHR_materials_transmission.KHR_materials_ior.KHR_materials_dispersion.KHR_materials_volume.KHR_materials_sheen.KHR_materials_specular.KHR_materials_variants.KHR_node_visibility.EXT_texture_webp.EXT_texture_avif.EXT_mesh_gpu_instancing.VRMC_materials_mtoon.VRMC_node_constraint.EXT_lights_ies.EXT_lights_image_based.KHR_physics_rigid_bodies.KHR_audio_emitter.MSFT_audio_emitter.KHR_interactivity.KHR_node_selectability.KHR_node_hoverability.KHR_implicit_shapes.KHR_xmp_json_ld.KHR_animation_pointer`.split(`.`)),P={KHR_draco_mesh_compression:`draco`,EXT_meshopt_compression:`meshopt`,KHR_meshopt_compression:`meshopt`,KHR_texture_basisu:`ktx2`,MSFT_texture_dds:`dds`,KHR_materials_iridescence:`materials`,KHR_materials_anisotropy:`materials`,KHR_materials_diffuse_transmission:`materials`,KHR_materials_diffuse_roughness:`materials`,EXT_materials_bump:`materials`,KHR_materials_volume_scatter:`materials`,KHR_gaussian_splatting:`splats`,KHR_gaussian_splatting_compression_spz_2:`splats`},F,I=[`EXT_meshopt_compression`,`KHR_meshopt_compression`],L=e=>{let t=e?.extensions;if(t?.EXT_meshopt_compression!==void 0&&t?.KHR_meshopt_compression!==void 0)throw TypeError(`Invalid glTF meshopt extensions; use only EXT or KHR on each buffer or bufferView`);return t?.EXT_meshopt_compression??t?.KHR_meshopt_compression};function R(e,t,n=0){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<n)throw TypeError(`Invalid glTF `+t+`; re-export the file and check it with the glTF Validator`);return e}function z(e,t,n){let r=e?.[R(t,n)];if(!r||typeof r!=`object`||Array.isArray(r))throw TypeError(`Missing glTF `+n+`; re-export the file and check it with the glTF Validator`);return r}function ae(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{throw TypeError(`Invalid glTF JSON: not UTF-8; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`)}}function B(e){let t=typeof e==`string`?e:ae(e);for(let e=0,n=0,r=!1;e<t.length;e++){let i=t.charCodeAt(e);if(r)i===92?e++:i===34&&(r=!1);else if(i===34)r=!0;else if(i===91||i===123){if(++n>256)throw TypeError(`Invalid glTF JSON: nested deeper than 256 levels; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`)}else(i===93||i===125)&&n--}try{return s(t)}catch(e){throw e instanceof SyntaxError?/* @__PURE__ */ TypeError(`Invalid glTF JSON: `+e.message):e}}var V=[`buffers`,`bufferViews`,`accessors`,`meshes`,`nodes`,`scenes`,`materials`,`textures`,`images`];V.push(`samplers`,`skins`,`animations`,`cameras`);var H=e=>e===void 0||Array.isArray(e)&&e.every(e=>!!e&&typeof e==`object`&&!Array.isArray(e));function U(e){if(!e||typeof e!=`object`||!o(e.asset))throw TypeError(`Expected glTF 2.0`);let t=e;for(let e of V)if(!H(t[e]))throw TypeError(`Invalid glTF `+e+`; re-export the file and check it with the glTF Validator`);for(let t of e.meshes??[])if(!H(t.primitives)||!(t.primitives??[]).every(e=>H(e.targets)))throw TypeError(`Invalid glTF primitives; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);for(let t of e.animations??[])if(!H(t.samplers)||!H(t.channels))throw TypeError(`Invalid glTF animation; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);for(let e of[`extensionsRequired`,`extensionsUsed`])if(t[e]!==void 0&&!Array.isArray(t[e]))throw TypeError(`Invalid glTF `+e+`; re-export the file and check it with the glTF Validator`)}function W(e,t=k){if(typeof e==`string`){if(e.length>t)throw A(`glTF JSON exceeds byte budget`,t);let n=new TextEncoder().encode(e).byteLength;if(n>t)throw A(`glTF JSON exceeds byte budget`,t);return{doc:B(e),sourceBytes:n}}if(!(e instanceof ArrayBuffer)&&!ArrayBuffer.isView(e))return{doc:e,sourceBytes:0};let n=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(M(n,`The glTF input`),n.length>=4&&!a(n)){if(n.length>t)throw A(`glTF JSON exceeds byte budget`,t);return{...W(ae(n),t),sourceBytes:n.byteLength}}if(n.length>t)throw A(`glTF exceeds download budget`,t);let r=i(n);return{doc:B(r[0].data),binary:r[1]?.type===5130562?r[1].data:void 0,sourceBytes:n.byteLength}}function G(e,t=k){let n=/^data:[^;,]+;base64,([A-Za-z0-9+/]*={0,2})$/.exec(e);if(n&&n[1].length>t*4/3+4)throw A(`glTF exceeds download budget`,t);if(!n)throw TypeError(`Invalid glTF data URI; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let r;try{r=atob(n[1])}catch{throw TypeError(`Invalid glTF data URI; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`)}return Uint8Array.from(r,e=>e.charCodeAt(0))}var K={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT4:16},oe=`EXT_meshopt_compression`,q=`KHR_draco_mesh_compression`,J=`KHR_texture_basisu`;function Y(e,t=!1){let n=e.extensions,r=n?.[J]!==void 0||!t||n?.MSFT_texture_dds===void 0?J:`MSFT_texture_dds`,i=n?.[r];if(i!==void 0&&(!i||typeof i!=`object`||Array.isArray(i)))throw TypeError(`Invalid glTF ${r}; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);return R(i===void 0?e.source:i.source,`image source`)}function X(e,t,n){let r=R(t,`accessor`),i=z(e.accessors,r,`accessor`);if(n&&i.type!==n)throw TypeError(`Invalid glTF accessor type; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let a=typeof i.componentType==`number`?d[i.componentType]:void 0,o=typeof i.type==`string`&&Object.hasOwn(K,i.type)?K[i.type]:void 0,s=R(i.count,`accessor count`,1);if(!a||!o||i.normalized!==void 0&&typeof i.normalized!=`boolean`||i.normalized&&[5125,5126].includes(i.componentType))throw TypeError(`Unsupported glTF accessor ${r} (componentType ${i.componentType}, type ${i.type}${i.normalized?`, normalized`:``}); re-export the model without it, or convert the texture format`);return{index:r,def:i,size:a,width:o,count:s}}var se={5120:127,5121:255,5122:32767,5123:65535},ce=class{get remainingDecodedBytes(){return this.maxBytes*4-this.decoded}reserveDecodedBytes(e){if(R(e,`decoded byte length`),this.decoded+e>this.maxBytes*4)throw RangeError(`Decoded glTF exceeds byte budget; load a smaller model, or reduce its textures and meshes`);this.decoded+=e}constructor(t,n,r,i={},a=k,o=1e5){this.doc=t,this.hooks=i,this.maxBytes=a,this.maxNodes=o,this.cache=/* @__PURE__ */ new Map,this.viewCache=/* @__PURE__ */ new Map,this.decoded=0,this.partVertices=m,ie(a),c(`maxNodes`,o),U(t);let s=(t.extensionsRequired??[]).filter(e=>!N.has(e)&&![q,oe,`KHR_meshopt_compression`,J].includes(e)&&!i[P[e]]&&!(i.materials&&i.materials.extensions?.includes(e)));if(s.length)throw p(`unsupported`,`Required glTF extensions are unsupported: `+s.map(e=>P[e]?e+` (pass a `+P[e]+` decoder)`:e).join(`, `)+`; pass the listed decoders or re-export the model without them`);l(`Too many glTF nodes`,t.nodes?.length??0,o,`maxNodes`);let u=0;this.buffers=(t.buffers??[]).map((i,o)=>{if(!i||typeof i!=`object`||Array.isArray(i))throw TypeError(`Invalid glTF buffer; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let s=R(i.byteLength,`buffer length`,1),c=L(i)?.fallback;if(c!==void 0&&typeof c!=`boolean`)throw TypeError(`Invalid glTF meshopt fallback; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let l=n[o],d=(!l||l.byteLength===0)&&!i.uri&&(o!==0||!r);if(c===!0||d&&I.some(e=>t.extensionsRequired?.includes(e))){let e=I.find(e=>i.extensions?.[e]!==void 0),n=(t.bufferViews??[]).filter(e=>e?.buffer===o);if(!n.length||n.some(t=>!L(t)||e!==void 0&&!t.extensions?.[e])||t.bufferViews?.some(e=>L(e)?.buffer===o))throw TypeError(`Invalid glTF meshopt fallback references; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);return/* @__PURE__ */ new Uint8Array}let f=l?l instanceof ArrayBuffer?new Uint8Array(l):new Uint8Array(l.buffer,l.byteOffset,l.byteLength):i.uri?G(i.uri,a):o===0?r:void 0;if(!f||s>f.length)throw RangeError(`Truncated glTF buffer; download the file again, it is incomplete`);if(o===0&&r&&(l===r||f===r)&&e(r.length,s),u+=f.byteLength,u>a)throw A(`glTF buffers exceed byte budget`,a);return f.subarray(0,s)})}view(e){let t=R(e,`bufferView`),n=z(this.doc.bufferViews,t,`bufferView`),r=R(n.buffer,`buffer reference`),i=this.buffers[r],a=R(n.byteOffset??0,`view offset`),o=R(n.byteLength,`view length`,1),s=R(z(this.doc.buffers,r,`buffer`).byteLength,`buffer length`,1);if(o>s||a>s-o)throw RangeError(`Invalid glTF bufferView bounds; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let c=L(n);if(c!==void 0){let e=this.viewCache.get(t);if(e)return e;if(!c||typeof c!=`object`||Array.isArray(c))throw TypeError(`Invalid glTF meshopt extension; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let r=this.buffers[R(c.buffer,`meshopt buffer reference`)],i=R(c.byteOffset??0,`meshopt offset`),a=R(c.byteLength,`meshopt length`,1),s=R(c.count,`meshopt count`,1),l=R(c.byteStride,`meshopt stride`,1),u=c.mode,d=c.filter??`NONE`;if(!r||a>r.length||i>r.length-a)throw RangeError(`Invalid glTF meshopt source bounds; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);if(!Number.isSafeInteger(s*l)||s*l!==o||n.byteStride!==void 0&&n.byteStride!==l)throw RangeError(`Invalid glTF meshopt decoded layout; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);if(u===`ATTRIBUTES`?l>256||l%4!=0:![`TRIANGLES`,`INDICES`].includes(u)||![2,4].includes(l)||u===`TRIANGLES`&&s%3!=0)throw TypeError(`Invalid glTF meshopt mode/stride/count; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);if(![`NONE`,`OCTAHEDRAL`,`QUATERNION`,`EXPONENTIAL`,`COLOR`].includes(d)||d!==`NONE`&&u!==`ATTRIBUTES`||[`OCTAHEDRAL`,`COLOR`].includes(d)&&![4,8].includes(l)||d===`QUATERNION`&&l!==8||d===`EXPONENTIAL`&&l%4!=0)throw TypeError(`Invalid glTF meshopt filter; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);if(this.decoded+o>this.maxBytes*4)throw RangeError(`Decoded glTF exceeds byte budget; load a smaller model, or reduce its textures and meshes`);let f=r.subarray(i,i+a),m;if(this.hooks.meshopt)m=new Uint8Array(o),this.hooks.meshopt.decodeGltfBuffer(m,s,l,f,u,d);else{if(!F)throw p(`state`,`Meshopt geometry requires parseGLTFAsync or loadGLTF, or a meshopt decoder passed in decoders (or asset.decode() first)`);m=F(f,s,l,u,d)}return this.reserveDecodedBytes(m.byteLength),this.viewCache.set(t,m),m}if(!i||a+o>i.length)throw RangeError(`Invalid glTF bufferView bounds; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);return i.subarray(a,a+o)}setDecodedAccessor(e,t){let{index:n,width:r,count:i}=X(this.doc,e);if(!(t instanceof Float32Array)||t.length!==i*r)throw RangeError(`Mismatched decoded glTF accessor; the file holds invalid numbers, re-export it and check it with the glTF Validator`);if(t.some(e=>!Number.isFinite(e)))throw RangeError(`Non-finite decoded glTF accessor; the file holds invalid numbers, re-export it and check it with the glTF Validator`);let a=this.cache.get(n);if(a){if(a!==t&&a.some((e,n)=>e!==t[n]))throw TypeError(`Conflicting decoded glTF accessor; the file holds invalid numbers, re-export it and check it with the glTF Validator`)}else this.reserveDecodedBytes(t.byteLength),this.cache.set(n,t)}async prepareMeshopt(){F||this.hooks.meshopt||this.doc.bufferViews?.some(e=>e?.extensions?.EXT_meshopt_compression||e?.extensions?.KHR_meshopt_compression)&&(F=(await import(`@margoengine/decoders/meshopt`)).meshoptDecodeGltfBuffer)}async decode(e){if(await this.prepareMeshopt(),!w(this))return e?.throwIfAborted();let{decompressPrimitives:t}=await import(`./compression-CUOCmjmE.js`);await t(this,{signal:e,draco:this.hooks.draco&&D(this.hooks.draco)})}accessor(e,t,n=!0){let{index:r,def:i,size:a,width:o,count:s}=X(this.doc,e,t),c=this.cache.get(r);if(c)return c;this.reserveDecodedBytes(s*o*4);let l=new Float32Array(s*o);if(i.bufferView!==void 0){let e=z(this.doc.bufferViews,i.bufferView,`bufferView`),t=R(e.byteStride??a*o,`stride`,a*o);if(t>252||R(e.byteOffset??0,`view offset`)%a)throw RangeError(`Invalid glTF stride/alignment; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);Z(i,a,o,l,this.view(i.bufferView),R(i.byteOffset??0,`accessor offset`),t,s,n)}else{if(this.dracoOwned(r))throw p(`state`,`Draco geometry requires parseGLTFAsync or loadGLTF`);if(i.byteOffset)throw TypeError(`Accessor has no data or invalid offset; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`)}if(i.sparse){let e=this.sparseIds(i,s),t=i.sparse.values;Z(i,a,o,l,this.view(t.bufferView),R(t.byteOffset??0,`sparse values offset`),a*o,e.length,n,e)}return n&&this.cache.set(r,l),l}sparseAccessor(e,t){let{index:n,def:r,size:i,width:a,count:o}=X(this.doc,e,t);if(!r.sparse&&r.bufferView===void 0&&!r.byteOffset&&!this.cache.has(n)&&!this.dracoOwned(n))return{count:o,width:a,rows:/* @__PURE__ */ new Uint32Array,values:/* @__PURE__ */ new Float32Array};if(r.bufferView===void 0&&r.sparse&&!r.byteOffset&&!this.cache.has(n)){let e=Uint32Array.from(this.sparseIds(r,o)),t=new Float32Array(e.length*a),n=r.sparse.values;return Z(r,i,a,t,this.view(n.bufferView),R(n.byteOffset??0,`sparse values offset`),i*a,e.length,!0),{count:o,width:a,rows:e,values:t}}let s=this.accessor(e,t),c=[];for(let e=0;e<o;e++)for(let t=0;t<a;t++)if(s[e*a+t]!==0){c.push(e);break}let l=Uint32Array.from(c),u=new Float32Array(l.length*a);return l.forEach((e,t)=>u.set(s.subarray(e*a,e*a+a),t*a)),{count:o,width:a,rows:l,values:u}}dracoOwned(e){return!!this.doc.meshes?.some(t=>t?.primitives?.some(t=>t?.extensions?.[q]&&(t.indices===e||Object.keys(t.extensions[q].attributes??{}).some(n=>t.attributes?.[n]===e))))}sparseIds(e,t){let n=e.sparse,r=R(n.count,`sparse count`,1),i=n.indices,a=n.values,o=d[i?.componentType];if(r>t||![5121,5123,5125].includes(i?.componentType))throw TypeError(`Invalid glTF sparse indices; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let s=this.view(i.bufferView),c=R(i.byteOffset??0,`sparse offset`);if(c%o||c+r*o>s.length||z(this.doc.bufferViews,i.bufferView,`sparse indices`).byteStride!==void 0||z(this.doc.bufferViews,a?.bufferView,`sparse values`).byteStride!==void 0)throw RangeError(`Invalid sparse bounds/stride; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let l=new DataView(s.buffer,s.byteOffset,s.byteLength),u=[],f=-1;for(let e=0;e<r;e++){let n=c+e*o,r=o===1?l.getUint8(n):o===2?l.getUint16(n,!0):l.getUint32(n,!0);if(r<=f||r>=t)throw RangeError(`Invalid sparse index order/bounds; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);u.push(r),f=r}return u}};function Z(e,t,n,r,i,a,o,s,c,l){if(a%t||o%t||a+(s-1)*o+n*t>i.length)throw RangeError(`Invalid glTF accessor bounds/alignment; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let d=new DataView(i.buffer,i.byteOffset,i.byteLength),f=e.componentType,p=e.normalized?se[f]??1:0;for(let e=0;e<s;e++){let i=(l?l[e]:e)*n;for(let s=0,l=a+e*o;s<n;s++,l+=t){let e=u(d,l,f);if(p&&(e=Math.max(-1,e/p)),c&&!Number.isFinite(Math.fround(e)))throw RangeError(`Non-finite glTF accessor; the file holds invalid numbers, re-export it and check it with the glTF Validator`);r[i+s]=e}}}function le(e){let t=/* @__PURE__ */ new Set;for(let n of e.textures??[])if(n?.extensions?.[J]!==void 0){let r=Y(n),i=z(e.images,r,`KTX2 image`);if(i.mimeType!==void 0&&i.mimeType!==`image/ktx2`||i.bufferView!==void 0&&i.mimeType!==`image/ktx2`)throw TypeError(`KHR_texture_basisu requires image/ktx2`);t.add(r)}for(let n=0;n<(e.images?.length??0);n++)e.images[n]?.mimeType===`image/ktx2`&&t.add(n);return t}function ue(e,t=!1){let n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set;for(let i of e.textures??[])i?.extensions?.[J]!==void 0||t&&i?.extensions?.MSFT_texture_dds!==void 0?(r.add(Y(i,t)),Number.isSafeInteger(i.source)&&i.source>=0&&n.add(i.source)):(Number.isSafeInteger(i?.source)&&i.source>=0&&r.add(i.source),!t&&i?.extensions?.MSFT_texture_dds&&n.add(R(i.extensions.MSFT_texture_dds.source,`DDS image`)));for(let e of r)n.delete(e);return n}function de(e,t,n){if(e.length<80||[171,75,84,88,32,50,48,187,13,10,26,10].some((t,n)=>e[n]!==t))throw TypeError(`Invalid glTF KTX2 header; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let r=new DataView(e.buffer,e.byteOffset,e.byteLength),i=r.getUint32(20,!0),a=r.getUint32(24,!0),o=r.getUint32(40,!0);if(!i||!a||i%4||a%4||i*a>67108864||i>(n?.limits.maxTextureDimension2D??16384)||a>(n?.limits.maxTextureDimension2D??16384)||r.getUint32(28,!0)||r.getUint32(32,!0)||r.getUint32(36,!0)!==1||!o||o>Math.floor(Math.log2(Math.max(i,a)))+1)throw RangeError(`Invalid glTF KTX2 dimensions or mip levels; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let s=0;for(let e=0;e<o;e++)s+=Math.max(1,i>>e)*Math.max(1,a>>e)*4;if(s>t.remainingDecodedBytes)throw RangeError(`glTF KTX2 exceeds decoded byte budget; load a smaller model, or reduce its textures and meshes`);return{width:i,height:a,levels:o}}function fe(e,t,n){let r={rgba8:[`rgba8unorm`,1,4],bc7:[`bc7-rgba-unorm`,4,16],"astc-4x4":[`astc-4x4-unorm`,4,16],etc2:[`etc2-rgba8unorm`,4,16]},i=e&&Object.hasOwn(r,e.target)?r[e.target]:void 0,a=typeof e?.format==`string`?e.format.replace(/-srgb$/,``):void 0;if(!i||a!==i[0]||e.width!==t.width||e.height!==t.height||!Array.isArray(e.mipmaps)||e.mipmaps.length!==t.levels||typeof e.srgb!=`boolean`||typeof e.hasAlpha!=`boolean`)throw TypeError(`Invalid transcoded glTF KTX2 image; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);let o=0;for(let n=0;n<e.mipmaps.length;n++){let r=e.mipmaps[n],a=Math.max(1,t.width>>n),s=Math.max(1,t.height>>n),c=Math.ceil(a/i[1])*Math.ceil(s/i[1])*i[2];if(!r||r.width!==a||r.height!==s||!(r.data instanceof Uint8Array)||r.data.byteLength!==c||r.byteLength!==c)throw RangeError(`Invalid transcoded glTF KTX2 mip; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);o+=c}return n.reserveDecodedBytes(o),{ktx2:e,width:e.width,height:e.height,close(){}}}function pe(e,t){let n=e.hooks.decoderModule;if(!n)throw p(`unsupported`,t===`Draco`?`This file needs the Draco decoder; load it with loadGLTF from @margoengine/gltf/pbr, or pass decoders.decoderModule`:`This file needs the KTX2 decoder; load it with loadGLTF from @margoengine/gltf/pbr, or pass decoders.decoderModule`);return n}function me(e,t){let n=t.ktx2,r;return{async decode(i){t.signal?.throwIfAborted();let a=de(i,e,t.device);if(!n){let{KTX2Decoder:i}=await pe(e,`KTX2`)();t.signal?.throwIfAborted(),n=r=new i({device:t.device})}let o=await n.transcode(i,{signal:t.signal});return t.signal?.throwIfAborted(),fe(o,a,e)},close(){r?.dispose()}}}async function he(e,t=[],n={}){n.signal?.throwIfAborted();let r=le(e.doc),i=/* @__PURE__ */ new Set;if(e.hooks.dds)for(let t of e.doc.textures??[])!t.extensions?.KHR_texture_basisu&&t.extensions?.MSFT_texture_dds!==void 0&&i.add(Y(t,!0));if(!r.size&&!i.size)return t;let a=t.slice(),o=me(e,n);try{for(let t of i){if(n.signal?.throwIfAborted(),a[t])continue;let r=z(e.doc.images,t,`DDS image`);if(r.mimeType!==void 0&&r.mimeType!==`image/vnd-ms.dds`||r.bufferView!==void 0&&r.mimeType!==`image/vnd-ms.dds`)throw TypeError(`MSFT_texture_dds requires image/vnd-ms.dds`);let i=r.bufferView===void 0?typeof r.uri==`string`&&r.uri.startsWith(`data:`)?G(r.uri,e.maxBytes):void 0:e.view(r.bufferView);if(!i)throw p(`state`,`External DDS images require loadGLTF`);a[t]=e.hooks.dds.decode(i,n)}for(let t of r){if(a[t]){if(!(`ktx2`in a[t]))throw TypeError(`KHR_texture_basisu requires decoded KTX2 images`);continue}let n=z(e.doc.images,t,`KTX2 image`),r=n.bufferView===void 0?typeof n.uri==`string`&&n.uri.startsWith(`data:`)?G(n.uri,e.maxBytes):void 0:e.view(n.bufferView);if(!r)throw p(`state`,`External KTX2 images require loadGLTF`);a[t]=await o.decode(r)}return a}catch(e){throw $(a.filter((e,n)=>e&&e!==t[n])),e}finally{o.close()}}var ge=/* @__PURE__ */ new WeakMap;function _e(e=1){if(!Number.isInteger(e)||e<1||e>16)throw p(`unsupported`,`Invalid glTF maxAnisotropy; pass an integer from 1 to 16, or omit it for 1`);return e}async function ve(){let{optimizeOverdraw:e,optimizeVertexCache:t}=await import(`@margoengine/geometry/optimize`);return(n,r,i)=>e(t(n,i),r)}async function ye(e,i={},a,o={},s=!1,c=0){let l=`aborted`in i?{signal:i}:i,{signal:u,decoders:d={},buffers:f=[],fetch:m=globalThis.fetch,maxDownloadBytes:h,maxNodes:g,optimize:_,allowedURLs:y,maxPartVertices:b}=l,ee=typeof a==`function`?a:void 0,x=typeof a==`function`?void 0:a,S=ie(h),te=v(b),C=_e(l.maxAnisotropy);u?.throwIfAborted();let w=e===void 0?l.baseURL===void 0?void 0:new URL(l.baseURL,globalThis.location?.href):new URL(e,globalThis.location?.href),T=c,E=async(e,t=!1)=>{if(![`http:`,`https:`].includes(e.protocol))throw TypeError(`glTF URL must use HTTP(S); for a blob: or file: source, read its bytes (await file.arrayBuffer()) and pass them to parseGLTFAsync`);let i=await m(e,{signal:u});t&&i.url?w=new URL(i.url):t||r(i,w??globalThis.location?.href,y,`glTF resource`);let a=await n(i,{maxBytes:S-T,signal:u,label:`glTF download`}).catch(e=>{throw e instanceof RangeError?A(e.message,S):e});return M(a,e.href),T+=a.length,a},D=n=>{if(w===void 0&&e===void 0)throw p(`state`,`glTF URI ${n} needs the file location, which a file in memory does not have; pass the baseURL option to parseGLTFAsync or load the file with loadGLTF`);return t(n,w??globalThis.location?.href,y,`glTF resource`)},{doc:O,binary:k,sourceBytes:j}=W(x??await E(w,!0),S),N=[],P=[];if(x!=null){if(j>S-T)throw A(`glTF exceeds download budget`,S);T+=j}U(O);for(let e=0;e<(O.buffers?.length??0);e++){let t=z(O.buffers,e,`buffer`);if(f[e]){let t=f[e];N[e]=t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}else if(L(t)?.fallback!==!0){if(!t.uri)e===0&&k&&(N[e]=k);else if(typeof t.uri!=`string`)throw TypeError(`Invalid glTF buffer uri; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);else if(t.uri.startsWith(`data:`)){let n=G(t.uri,S);if(T+=n.length,T>S)throw A(`glTF exceeds download budget`,S);N[e]=n}else N[e]=await E(D(t.uri))}}let F=new ce(O,N,k,await ne(O,d),S,g);ge.set(F,C);let I=F.hooks;if(F.baseURL=w?.href,F.partVertices=te,_&&(F.reorder=await ve()),s&&re(O))return{asset:F,images:P,deferred:!0,baseURL:w?.href,downloadedBytes:T};let R=le(O),ae=ue(O,!!I.dds),B=me(F,{...o,ktx2:o.ktx2??I.ktx2,signal:u}),V=0;await F.decode(u);try{u?.throwIfAborted(),await ee?.(F),u?.throwIfAborted();let e=[],t=async()=>{let[t,n]=e.shift(),r=await n;if(P[t]=r,V+=r.width*r.height*4,r.width*r.height>67108864||V>S*4)throw RangeError(`glTF images exceed decoded size limit; load a smaller model, or reduce its textures and meshes`);u?.throwIfAborted()};try{for(let n=0;n<(O.images?.length??0);n++){if(ae.has(n))continue;let r=z(O.images,n,`image`);if(R.has(n)&&I.textureStream){P[n]=await I.textureStream.open(r.bufferView===void 0?typeof r.uri==`string`&&r.uri.startsWith(`data:`)?{bytes:G(r.uri,S)}:{url:D(r.uri).href}:{bytes:F.view(r.bufferView)},n);continue}let i;if(r.bufferView!==void 0)i=F.view(r.bufferView);else if(typeof r.uri==`string`&&r.uri.startsWith(`data:`)){if(i=G(r.uri,S),T+=i.length,T>S)throw A(`glTF exceeds download budget`,S)}else if(typeof r.uri==`string`)i=await E(D(r.uri));else throw TypeError(`Invalid glTF image; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`);if(I.dds&&O.textures?.some(e=>!e.extensions?.KHR_texture_basisu&&e.extensions?.MSFT_texture_dds?.source===n)){if(r.mimeType!==void 0&&r.mimeType!==`image/vnd-ms.dds`||r.bufferView!==void 0&&r.mimeType!==`image/vnd-ms.dds`)throw TypeError(`MSFT_texture_dds requires image/vnd-ms.dds`);for(;e.length;)await t();e.push([n,Promise.resolve(I.dds.decode(i,{signal:u}))]),await t()}else if(R.has(n)){for(;e.length;)await t();e.push([n,B.decode(i)]),await t()}else{let a=xe(i,r.mimeType,n,u);a.catch(()=>{}),e.push([n,a]),e.length>=be&&await t()}}for(;e.length;)await t()}finally{for(let[,t]of e.splice(0))t.then(e=>$([e]),()=>{})}return{asset:F,images:P}}catch(e){throw $(P),e}finally{B.close()}}var be=8;async function xe(e,t,n,r){r?.throwIfAborted();try{if(typeof createImageBitmap!=`function`)return await E(e,r);let n=e.buffer instanceof ArrayBuffer?e:new Uint8Array(e);return await createImageBitmap(new Blob([n],{type:t}),{colorSpaceConversion:`none`,premultiplyAlpha:`none`})}catch(e){throw r?.throwIfAborted(),TypeError(`glTF image ${n} could not be decoded (${e instanceof Error?e.message:e}); check the file`)}}var Q=/* @__PURE__ */ new WeakMap;function Se(e){for(let t of e)t&&Q.set(t,(Q.get(t)??0)+1)}function $(e){for(let t of e){if(!t)continue;let e=Q.get(t);e?Q.set(t,e-1):`close`in t&&t.close?.()}}export{m as A,ue as C,ne as D,w as E,v as M,b as N,S as O,ee as P,ve as S,C as T,ye as _,U as a,M as b,K as c,he as d,pe as f,R as g,z as h,k as i,_ as j,x as k,W as l,G as m,D as n,_e as o,ie as p,ge as r,$ as s,ce as t,xe as u,A as v,T as w,Se as x,B as y};
|
package/dist/asset-entry.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{t as GLTFAsset}from"./asset-
|
|
1
|
+
export{t as GLTFAsset}from"./asset-DN3ocEdY.js";
|
package/dist/asset.d.ts
CHANGED
|
@@ -54,6 +54,8 @@ export interface GLTFImageOptions {
|
|
|
54
54
|
}): Promise<GLTFCompressedImage | TranscodedKTX2Result>;
|
|
55
55
|
};
|
|
56
56
|
}
|
|
57
|
+
/** A caller's Draco hook, with the metadata it may omit (vertex count, attribute widths, indices) filled in. */
|
|
58
|
+
export declare function adaptDraco(hook: NonNullable<GLTFDecoderHooks['draco']>): NonNullable<GLTFDecoderHooks['draco']>;
|
|
57
59
|
/** Async codecs stay on the owning thread; meshopt is synchronous and can be packed in a parser worker. */
|
|
58
60
|
export declare const asyncGeometry: (doc: GLTFDocument) => boolean;
|
|
59
61
|
export declare const asyncCompression: (doc: GLTFDocument) => boolean;
|
|
@@ -142,6 +144,51 @@ export interface GLTFDecoderHooks {
|
|
|
142
144
|
* point cloud fallback the extension defines. Synchronous `parseGLTF` draws the fallback.
|
|
143
145
|
*/
|
|
144
146
|
splats?: GLTFSplatReader | false;
|
|
147
|
+
/**
|
|
148
|
+
* Wide points and lines (`wideStrokes`, an internal entry of gltf/pbr): `loadGLTF` and `parseGLTFAsync` import it on
|
|
149
|
+
* their own when a POINTS or LINES primitive asks for a width (its `extras` `pointSize` or `lineWidth`, or a
|
|
150
|
+
* `BENTLEY_materials_point_style` or `BENTLEY_materials_line_style` material), and draw those primitives with
|
|
151
|
+
* @margoengine/points and @margoengine/lines. `false` draws every point and line 1 px wide. Synchronous `parseGLTF`
|
|
152
|
+
* draws them 1 px wide.
|
|
153
|
+
*/
|
|
154
|
+
strokes?: GLTFStrokeReader | false;
|
|
155
|
+
/**
|
|
156
|
+
* Screen-space transmission (`screenTransmission` from @margoengine/gltf/transmission): `loadGLTF` and
|
|
157
|
+
* `parseGLTFAsync` import it on their own when a material declares KHR_materials_transmission, so glass refracts and
|
|
158
|
+
* blurs the scene behind it; `false` keeps the tinted blend. Synchronous `parseGLTF` uses it only when passed.
|
|
159
|
+
*/
|
|
160
|
+
transmission?: GLTFTransmissionPass | false;
|
|
161
|
+
}
|
|
162
|
+
/** What gltf/pbr needs to refract the scene through a model (`screenTransmission` from @margoengine/gltf/transmission implements it). */
|
|
163
|
+
export interface GLTFTransmissionPass {
|
|
164
|
+
/** Draws `model`'s transmissive primitives from a scene copy in the scene whose frame graph is `graph`. Returns a remover. */
|
|
165
|
+
attach(model: import('./model.js').PBRModel, engine: Engine, graph: import('@margoengine/core/extension').FrameGraph): () => void;
|
|
166
|
+
}
|
|
167
|
+
/** One POINTS or LINES primitive that asks for a width, as gltf/pbr hands it to `GLTFStrokeReader.attach`. */
|
|
168
|
+
export interface GLTFStrokeItem {
|
|
169
|
+
readonly width: import('./stroke-width.js').StrokeWidth;
|
|
170
|
+
/** gltf/pbr's packed vertices, 20 floats each: position at 0, linear RGBA colour at 16. */
|
|
171
|
+
readonly vertices: Float32Array;
|
|
172
|
+
/** Point indices, or index pairs for lines (strips and loops decoded to pairs). */
|
|
173
|
+
readonly indices: Uint32Array;
|
|
174
|
+
/** Per-vertex `_WIDTH` multipliers, when the primitive has them. */
|
|
175
|
+
readonly widths?: Float32Array;
|
|
176
|
+
/** The primitive's extras, which hold a line's style (join, cap, dashes, draw state). */
|
|
177
|
+
readonly extras?: unknown;
|
|
178
|
+
readonly material: {
|
|
179
|
+
readonly base: readonly number[];
|
|
180
|
+
readonly alphaMode?: unknown;
|
|
181
|
+
readonly extensions?: object;
|
|
182
|
+
};
|
|
183
|
+
/** The node mesh the drawing follows: its world matrix and visibility. */
|
|
184
|
+
readonly node: import('@margoengine/core').Mesh;
|
|
185
|
+
}
|
|
186
|
+
/** What gltf/pbr needs to draw wide points and lines (`wideStrokes`, gltf/pbr's internal strokes entry, implements it). */
|
|
187
|
+
export interface GLTFStrokeReader {
|
|
188
|
+
/** Draws `items` in `engine`'s current scene until the returned handle's `dispose`. */
|
|
189
|
+
attach(engine: Engine, items: readonly GLTFStrokeItem[], signal?: AbortSignal): Promise<{
|
|
190
|
+
dispose(): void;
|
|
191
|
+
}>;
|
|
145
192
|
}
|
|
146
193
|
/** One Gaussian cloud of a file, attached to the engine; `bounds` holds min xyz, max xyz of its centres in world space. */
|
|
147
194
|
export interface GLTFSplatCloud {
|
|
@@ -255,12 +302,39 @@ export declare class GLTFAsset {
|
|
|
255
302
|
* reports them (gltf/report).
|
|
256
303
|
*/
|
|
257
304
|
accessor(id: unknown, type?: string, finite?: boolean): Float32Array;
|
|
305
|
+
/**
|
|
306
|
+
* The accessor's elements that are not all zero, as row numbers (ascending) and their values (`width` floats each,
|
|
307
|
+
* normalized integers scaled). A sparse accessor without a bufferView (glTF 2.0 section 3.6.2.3, how morph targets
|
|
308
|
+
* are usually written) is read as stored, so a morph target of a 395-target face never becomes a dense array; its
|
|
309
|
+
* sparse values are kept even where they are zero. Any other accessor is read with {@link GLTFAsset.accessor} and its
|
|
310
|
+
* all-zero rows dropped. Not cached; a NaN or infinity throws.
|
|
311
|
+
*/
|
|
312
|
+
sparseAccessor(id: unknown, type?: string): SparseValues;
|
|
313
|
+
/** True when a KHR_draco_mesh_compression primitive owns the accessor: the Draco decoder fills it. */
|
|
314
|
+
private dracoOwned;
|
|
315
|
+
/** A sparse accessor's indices, checked: strictly increasing, below `count`, tightly packed and in bounds. */
|
|
316
|
+
private sparseIds;
|
|
317
|
+
}
|
|
318
|
+
/** An accessor's non-zero elements, from {@link GLTFAsset.sparseAccessor}. */
|
|
319
|
+
export interface SparseValues {
|
|
320
|
+
/** Elements of the accessor, zeros included. */
|
|
321
|
+
count: number;
|
|
322
|
+
/** Floats per element (3 for VEC3). */
|
|
323
|
+
width: number;
|
|
324
|
+
/** Row numbers of the kept elements, ascending. */
|
|
325
|
+
rows: Uint32Array;
|
|
326
|
+
/** `width` floats per kept element, in the order of `rows`. */
|
|
327
|
+
values: Float32Array;
|
|
258
328
|
}
|
|
259
329
|
export declare function unusedBasisuFallbacks(doc: GLTFDocument, dds?: boolean): Set<number>;
|
|
260
330
|
/** The module holding the built-in decoders; a file that needs one without a way to reach it is refused by name. */
|
|
261
331
|
export declare function decoderSource(asset: GLTFAsset, format: string): NonNullable<GLTFDecoderHooks['decoderModule']>;
|
|
262
332
|
/** Async only for requested KTX2 images; caller-supplied ordinary bitmaps retain their synchronous path. */
|
|
263
333
|
export declare function decodeKTX2Images(asset: GLTFAsset, images?: readonly GLTFImage[], options?: GLTFImageOptions): Promise<GLTFImage[]>;
|
|
334
|
+
/** Requested sampler quality follows the retained asset across device restoration and model copies. */
|
|
335
|
+
export declare const assetAnisotropy: WeakMap<GLTFAsset, number>;
|
|
336
|
+
/** Normalize the PBR sampler option before loading its resources. */
|
|
337
|
+
export declare function checkMaxAnisotropy(value?: number): number;
|
|
264
338
|
export interface AssetOptions {
|
|
265
339
|
signal?: AbortSignal;
|
|
266
340
|
decoders?: GLTFDecoderHooks;
|
|
@@ -287,6 +361,8 @@ export interface AssetOptions {
|
|
|
287
361
|
maxDownloadBytes?: number;
|
|
288
362
|
/** Most glTF nodes the file may have, each one a core mesh (default 100,000; up to core's 8,388,608 entities). */
|
|
289
363
|
maxNodes?: number;
|
|
364
|
+
/** Maximum anisotropy for PBR textures with trilinear sampling and multiple mips. An integer from 1 to 16, default 1. */
|
|
365
|
+
maxAnisotropy?: number;
|
|
290
366
|
/**
|
|
291
367
|
* Reorders each opaque primitive's triangles for the GPU's vertex cache and for early depth rejection, as
|
|
292
368
|
* `@margoengine/geometry/optimize` does (needs that package). Same triangles, same picture, more time spent loading.
|
package/dist/audio.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{c as e,d as t,l as n}from"./version-B6NE5cJf.js";import{i as r,m as i}from"./asset-DN3ocEdY.js";import{margoError as a}from"@margoengine/core/extension";var o=e=>/* @__PURE__ */ TypeError(`Invalid glTF audio `+e+`; re-export the file and check its audio extension`),s=(e,t)=>{if(!e||typeof e!=`object`||Array.isArray(e))throw o(t);return e},c=(e,t)=>{if(!Array.isArray(e))throw o(t);return e},l=(e,t,n,r=1/0)=>{let i=e??t;if(typeof i!=`number`||!Number.isFinite(i)||i<0||i>r)throw o(n);return i},u=(e,t)=>{if(e!==void 0&&typeof e!=`boolean`)throw o(t);return e===!0},d=(e,t)=>{let n=l(e,-1,t);if(!Number.isSafeInteger(n))throw o(t);return n},f=(e,t,n)=>s(c(e,n)[d(t,n)],n);async function p(e,t){if(t?.throwIfAborted(),!t)return e;let n=()=>{};try{return await new Promise((r,i)=>{n=()=>i(t.reason),t.addEventListener(`abort`,n,{once:!0}),e.then(r,i)})}finally{t.removeEventListener(`abort`,n)}}async function m(m,h,g={}){if(g.signal?.throwIfAborted(),m.disposed)throw a(`disposed`,`Cannot attach audio to a disposed model; load it again`);let{Audio:_,PositionalAudio:v,decodeAudio:y}=await import(`@margoengine/audio`).catch(e=>{throw a(`unsupported`,`glTF audio needs @margoengine/audio (${e instanceof Error?e.message:e}); install that optional package`)});g.signal?.throwIfAborted();let b=m.asset.doc,x=l(g.maxDownloadBytes,r,`maxDownloadBytes`);if(!Number.isSafeInteger(x)||x<1)throw o(`maxDownloadBytes`);let S=l(g.maxSources,256,`maxSources`);if(!Number.isSafeInteger(S)||S<1)throw o(`maxSources`);g.autoplay!==void 0&&u(g.autoplay,`autoplay`);let C=g.random??Math.random;if(typeof C!=`function`)throw o(`random`);let w=[],T=[],E=[],D=[],O=0,k=0,A=!1,j=/* @__PURE__ */ new Map,M=d(g.scene??b.scene??0,`scene`),N=b.scenes?.length?s(b.scenes[M],`scene`):void 0,P=/* @__PURE__ */ new Set,F=e=>{let t=d(e,`node`);if(P.has(t))return;P.add(t);let n=s(b.nodes?.[t],`node`);for(let e of n.children===void 0?[]:c(n.children,`children`))F(e)};if(N)for(let e of N.nodes===void 0?[]:c(N.nodes,`scene nodes`))F(e);else for(let e=0;e<(b.nodes?.length??0);e++)P.add(e);let I=(r,a,s)=>{let c=d(s,`clip`),l=r+`:`+c,u=j.get(l);return u||(u=(async()=>{let s=f(r===`KHR_audio_emitter`?a.audio:a.clips,c,`audio data`),l=s.mimeType;if(s.bufferView!==void 0&&typeof l!=`string`||l!==void 0&&![`audio/wav`,`audio/mpeg`].includes(String(l)))throw o(`MIME type`);let u;if(s.bufferView!==void 0)u=m.asset.view(d(s.bufferView,`bufferView`));else if(typeof s.uri!=`string`)throw o(`URI`);else if(s.uri.startsWith(`data:`))u=i(s.uri,x-O);else{let r=g.baseURL??m.asset.baseURL,i=e(s.uri,r?.toString(),g.allowedURLs,`glTF audio`),a=await(g.fetch??globalThis.fetch)(i,{signal:g.signal});n(a,r?.toString(),g.allowedURLs,`glTF audio`),u=await t(a,{maxBytes:x-O,signal:g.signal,label:`glTF audio`})}if(O+=u.length,O>x)throw RangeError(`glTF audio exceeds download budget; raise maxDownloadBytes`);let _=new Uint8Array(u).buffer,v=await p(y(h.context,_),g.signal);if(k+=v.length*v.numberOfChannels*4,k>x*4)throw RangeError(`glTF audio exceeds decoded PCM budget; raise maxDownloadBytes`);return v})(),j.set(l,u),u)},L=async(e,t,n,r)=>{g.signal?.throwIfAborted();let i=d(n,`emitter`),p=f(t.emitters,i,`emitter`),y=e===`KHR_audio_emitter`,b=y?p.type===`positional`:r!==void 0;if(y&&p.type!==`positional`&&p.type!==`global`)throw o(`emitter type`);if(b&&r===void 0)throw o(`positional scene emitter`);let x=y?p.positional===void 0?{}:s(p.positional,`positional`):p;if(!b&&(y?p.positional!==void 0:[`distanceModel`,`refDistance`,`maxDistance`,`rolloffFactor`,`innerAngle`,`outerAngle`].some(e=>p[e]!==void 0)))throw o(`global emitter spatial properties`);let O=l(y?p.gain:p.volume,1,`emitter gain`),k=x.distanceModel??(y?`inverse`:`exponential`);if(![`linear`,`inverse`,`exponential`].includes(String(k)))throw o(`distance model`);let j=l(x.refDistance,1,`reference distance`);if(!j)throw o(`reference distance`);let M=l(x.maxDistance,y?0:256,`maximum distance`)||34028234663852886e22;if(k===`linear`&&M<=j)throw o(`linear maximum distance`);let N=l(x.rolloffFactor,1,`rolloff`,k===`linear`?1:1/0),P=x.shapeType??`omnidirectional`;if(y&&![`cone`,`omnidirectional`].includes(String(P)))throw o(`emitter shape`);let F=y?P===`cone`:x.innerAngle!==void 0||x.outerAngle!==void 0,L=y?180/Math.PI:360/Math.PI,R=y?Math.PI*2:Math.PI,z=F?l(y?x.coneInnerAngle:x.innerAngle,R,`inner cone angle`,R)*L:360,B=F?l(y?x.coneOuterAngle:x.outerAngle,R,`outer cone angle`,R)*L:360;if(B<z)throw o(`cone angle order`);let V={volume:O,direction:y?[0,0,-1]:[0,0,1],mesh:r===void 0?void 0:m.nodes[r],distanceModel:k,refDistance:j,maxDistance:M,rolloffFactor:N,coneInnerAngle:z,coneOuterAngle:B,coneOuterGain:y?l(x.coneOuterGain,0,`cone outer gain`,1):0},H=c(y?p.sources??[]:p.clips,`emitter sources`);if((y?H.length:1)>S-E.length)throw RangeError(`glTF audio exceeds source budget; raise maxSources`);if(!y&&!H.length)throw o(`empty MSFT clips`);let U=y?H.map(e=>f(t.sources,e,`source`)):H.map(e=>s(e,`clip reference`)),W=[];for(let n of U)W.push(await I(e,t,y?n.audio:n.clip));let G=y?[]:U.map(e=>l(e.weight,1,`clip weight`)),K=G.reduce((e,t)=>e+t,0);if(!y&&(!Number.isFinite(K)||K<=0))throw o(`clip weights`);let q=[];for(let e=0;e<(y?U.length:1);e++){let t=U[e],n={...V,loop:u(y?t.loop:p.loop,`loop`),volume:O*(y?l(t.gain,1,`source gain`):1)},r=b?new v(h,n):new _(h,n);E.push(r),q.push(r),r.setBuffer(W[e])}let J=/* @__PURE__ */ new WeakMap,Y=e=>{if(y)return;let t=e&&J.get(e);if(t===void 0){let n=C();if(!Number.isFinite(n)||n<0||n>=1)throw o(`random sample`);let r=n*K,i=0;for(t=G.length-1;G[t]===0;)t--;for(let e=0;e<G.length;e++)if(r<(i+=G[e])){t=e;break}e&&J.set(e,t)}q[0].buffer!==W[t]&&(q[0].stop(),q[0].setBuffer(W[t]))},X=()=>{if(A)throw a(`disposed`,`glTF audio is disposed; apply the audio extension again`)},Z={extension:e,emitterIndex:i,nodeIndex:r,name:typeof p.name==`string`?p.name:``,sources:q,play(e=0){X(),l(e,0,`play offset`),Y();for(let t of q)t.stop(),t.offset=e,t.play()},pause(){X();for(let e of q)e.pause()},stop(){X();for(let e of q)e.stop()}};T.push(Z),D.push({emitter:Z,choose:Y});for(let e=0;e<q.length;e++){let t=y&&u(U[e].autoPlay,`autoPlay`);g.autoplay!==!1&&(g.autoplay===!0||t)&&w.push({sound:q[e],choose:y?void 0:Y})}},R=()=>{},z=()=>{if(!A){A=!0,R();for(let e of E)e.dispose();j.clear()}};try{for(let e of[`KHR_audio_emitter`,`MSFT_audio_emitter`]){let t=b.extensions?.[e];if(t===void 0)continue;let n=s(t,e);for(let t of P){let r=b.nodes?.[t]?.extensions?.[e];if(r===void 0)continue;let i=s(r,`node emitter`),a=e===`KHR_audio_emitter`?[i.emitter]:c(i.emitters,`node emitters`);for(let r of a)await L(e,n,r,t)}let r=N&&N.extensions?.[e];if(r!==void 0)for(let t of c(s(r,`scene emitter`).emitters,`scene emitters`))await L(e,n,t)}if(g.signal?.throwIfAborted(),m.disposed)throw a(`disposed`,`Model was disposed while audio loaded; load it again`);let e={emitters:T,dispose:z,[Symbol.dispose]:z,sync(e,t,n=0){if(A)throw a(`disposed`,`glTF audio is disposed; apply the audio extension again`);if(l(e,0,`timeline time`),typeof t!=`boolean`)throw o(`playing`);let r=(b.animations?.[d(n,`animation`)])?.extensions?.MSFT_audio_emitter,i=(r===void 0?[]:c(s(r,`animation events`).events,`events`).map(e=>s(e,`event`))).map((e,t)=>({event:e,order:t,time:l(e.time,NaN,`event time`)})).sort((e,t)=>e.time-t.time||e.order-t.order);for(let{emitter:n,choose:r}of D){if(n.extension!==`MSFT_audio_emitter`)continue;let a=!1,c=!1,u=0,p=0,m;for(let{event:t,time:r}of i){let i=d(t.emitter,`event emitter`);if(f(s(b.extensions?.MSFT_audio_emitter,`MSFT_audio_emitter`).emitters,i,`event emitter`),![`play`,`pause`,`stop`].includes(String(t.action)))throw o(`event action`);r>e||i!==n.emitterIndex||(t.action===`play`?(c||(u=l(t.startOffset,0,`start offset`),m=t),a=!0,c=!1,p=r):t.action===`pause`?(a&&(u+=r-p),a=!1,c=!0):(u=0,a=!1,c=!1,m=void 0))}a&&(u+=e-p),m&&r(m);for(let e of n.sources)e.offset=0,e.sync(u,a&&t)}}};R=m.onDispose(z);for(let{sound:e,choose:t}of w)t?.(),e.play();return e}catch(e){throw z(),e}}export{m as applyGLTFAudio};
|
package/dist/auto.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as e,o as t,s as n,u as r}from"./version-
|
|
1
|
+
import{d as e,o as t,s as n,u as r}from"./version-B6NE5cJf.js";import{i,t as a}from"./src-Btvz5f6i.js";import{t as o}from"./scene-scope-CZDEkd24.js";import{MargoError as s}from"@margoengine/math/errors";var c=e=>Array.isArray(e)?e:[],l=(e,t)=>c(e.extensionsUsed).includes(t)||c(e.extensionsRequired).includes(t);async function u(e){let t=c(e.meshes).flatMap(e=>c(e?.primitives)),n=[];return(l(e,`EXT_meshopt_compression`)||l(e,`KHR_meshopt_compression`)||c(e.bufferViews).some(e=>e?.extensions))&&n.push(import(`./meshopt.js`).then(e=>e.meshopt)),(l(e,`KHR_mesh_quantization`)||t.some(t=>[t?.attributes?.POSITION,t?.attributes?.NORMAL].some(t=>t!==void 0&&c(e.accessors)[t]?.componentType!==5126)))&&n.push(import(`./quantized.js`).then(e=>e.quantized)),c(e.materials).some(e=>e?.pbrMetallicRoughness?.baseColorTexture||e?.alphaMode===`MASK`)&&n.push(import(`./textured.js`).then(e=>e.textured)),l(e,`EXT_mesh_gpu_instancing`)&&n.push(import(`./instancing.js`).then(e=>e.instancing)),(l(e,`KHR_lights_punctual`)||c(e.nodes).some(e=>e?.camera!==void 0))&&n.push(import(`./scene-data.js`).then(e=>e.sceneExtras)),Promise.all(n)}function d(e){let i=n(e)?t(e)[0].data:e;try{return r(new TextDecoder().decode(i))??{}}catch(e){throw TypeError(`Invalid glTF JSON: ${e.message}; the file is not valid glTF 2.0, re-export it and check it with the glTF Validator`)}}var f=536870912,p=()=>/* @__PURE__ */ RangeError(`glTF download byte budget exceeded; raise maxBytes`);function m({response:e,chunks:t,error:n},r){let i=0,a=e.body===null||[204,205,304].includes(e.status)?null:new ReadableStream({pull(e){i<t.length?(e.enqueue(t[i]),r&&(t[i]=void 0),i++):n===void 0?e.close():e.error(n)}}),o=new Response(a,{status:e.status,statusText:e.statusText,headers:e.headers});return Object.defineProperties(o,{url:{value:e.url},redirected:{value:e.redirected}})}function h(e){let t=/* @__PURE__ */ new Map,n=0,r=!0,i=async(t,r)=>{let i=await e(t,r),a={response:i,chunks:[],size:0};if(!i.ok||!i.body)return i.body?.cancel().catch(()=>{}),a;let o=i.body.getReader(),s=r?.signal??void 0,c=()=>o.cancel(s?.reason).catch(()=>{});s?.addEventListener(`abort`,c,{once:!0});try{if(Number(i.headers.get(`content-length`))>f-n)throw p();for(let e=await o.read();!e.done;e=await o.read()){if(s?.throwIfAborted(),!(e.value instanceof Uint8Array))throw TypeError(`glTF download stream requires byte chunks; have fetch return a Response whose body yields Uint8Array`);if(e.value.byteLength>f-n-a.size)throw p();a.chunks.push(e.value),a.size+=e.value.byteLength}s?.throwIfAborted(),n+=a.size}catch(e){o.cancel(e).catch(()=>{}),a.error=e,a.chunks=[],a.size=0}finally{s?.removeEventListener(`abort`,c)}return a};return Object.assign((n,a)=>{let o=String(n instanceof Request?n.url:n),s=t.get(o);if(!s){if(!r)return e(n,a);t.set(o,s=i(n,a))}let c=!r;return c&&t.delete(o),s.then(e=>m(e,c))},{release(e){r=!1,e&&t.clear()}})}async function g(e,t,{signal:n,fetch:r=globalThis.fetch,maxNodes:i,allowedURLs:a}={}){n?.throwIfAborted();let s=new URL(t,globalThis.location?.href);if(![`http:`,`https:`].includes(s.protocol))throw TypeError(`glTF URL must use HTTP(S); for a blob: or file: source, read its bytes (await file.arrayBuffer()) and pass them to parseGLTFAsync`);let c=h(r);try{return await _(e,s,o(e),{signal:n,fetch:c,maxNodes:i,allowedURLs:a})}finally{c.release(!0)}}async function _(t,n,r,o){let{signal:c,fetch:f}=o,p=async(e,i)=>{f.release(!1);let a=await import(`@margoengine/gltf/pbr`),c=!i||l(i,`EXT_mesh_gpu_instancing`)?{instancing:(await import(`@margoengine/gltf/pbr-instancing`)).instancing}:void 0;try{return{loader:`gltf/pbr`,model:await r.run(()=>a.loadGLTF(t,n,c?{...o,decoders:c}:o)),reason:e}}catch(t){throw t instanceof s&&t.code===`unsupported`&&!t.message.includes(e)?new s(`unsupported`,`${e}; gltf/pbr cannot load it here either: ${t.message}`):t}},m;try{m=await e(await f(n,{signal:c}),{maxBytes:67108864,signal:c,label:`glTF download`})}catch(e){if(!(e instanceof RangeError))throw e;return p(`The file is over the light loader's 64 MiB`)}i(m,n.href);let h=d(m);try{let e=await u(h);return{loader:`gltf`,model:await r.run(()=>a(t,n,{...o,extensions:e}))}}catch(e){if(!(e instanceof s)||e.code!==`unsupported`)throw e;return p(e.message,h)}}export{g as loadAuto};
|
|
@@ -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};
|
package/dist/compression.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { GLTFPrimitive } from './shared/gltf.js';
|
|
1
2
|
import type { KTX2Decoder } from '@margoengine/decoders';
|
|
2
3
|
import { type GLTFAsset } from './asset.js';
|
|
3
4
|
/**
|
|
@@ -13,3 +14,8 @@ export interface GLTFLoadOptions {
|
|
|
13
14
|
ktx2?: Pick<KTX2Decoder, 'transcode'>;
|
|
14
15
|
}
|
|
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>;
|
package/dist/dds.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"./errors-THVaUwlL.js";import"./image-limit-DvFSfR5T.js";var t=(e,t)=>Object.assign(Error(e,t===void 0?void 0:{cause:t}),{name:`MargoError`,code:`failed`}),n=e=>Object.assign(Error(e),{name:`MargoError`,code:`unsupported`}),r={r8unorm:1,r8snorm:1,rg8unorm:2,rg8snorm:2,rgba8unorm:4,"rgba8unorm-srgb":4,rgba8snorm:4,bgra8unorm:4,"bgra8unorm-srgb":4,r16float:2,rg16float:4,rgba16float:8,r32float:4,rg32float:8,rgba32float:16,rgb10a2unorm:4,rg11b10ufloat:4,rgb9e5ufloat:4};function i(e){if(r[e])return[1,1,r[e]];if(/^bc[1-7]h?-/.test(e))return[4,4,/^bc[14]-/.test(e)?8:16,`texture-compression-bc`];if(/^(etc2|eac)-/.test(e))return[4,4,/^(etc2-rgb8|eac-r11)/.test(e)?8:16,`texture-compression-etc2`];let t=/^astc-(\d+)x(\d+)-/.exec(e);if(t)return[+t[1],+t[2],16,`texture-compression-astc`]}function a(e,t,n){let r=Math.ceil(t/e[0])*e[2];return[r*Math.ceil(n/e[1]),r]}function o(e,t,n){return e[0].map((r,i)=>{let a=e[0][i].length,o=new Uint8Array(a*e.length);return e.forEach((e,t)=>o.set(e[i],t*a)),{data:o,width:Math.max(1,t>>i),height:Math.max(1,n>>i),byteLength:o.byteLength}})}function s(e,t,r={}){let o=i(t.format);if(!o)throw TypeError(`Texture format ${String(t.format)} is unknown; pass a parseDDS or parseKTX result`);let[s,c,,l]=o;if(l&&!e.features.has(l))throw n(`Texture format ${t.format} needs the device feature ${l}; request it with adapter.requestDevice({requiredFeatures: ['${l}']}) where adapter.features has it, or convert the file to an uncompressed format`);if(t.width%s||t.height%c)throw RangeError(`Texture ${t.width}x${t.height} is not a whole number of ${s}x${c} ${t.format} blocks; resize the source to a multiple of ${s}x${c}`);if(Math.max(t.width,t.height)>e.limits.maxTextureDimension2D)throw RangeError(`Texture ${t.width}x${t.height} exceeds the device's maxTextureDimension2D; use a smaller file`);if(t.layers>e.limits.maxTextureArrayLayers)throw RangeError(`Texture of ${t.layers} layers exceeds the device's maxTextureArrayLayers; request a higher limit or use fewer layers`);let u=e.createTexture({label:r.label,size:[t.width,t.height,t.layers],mipLevelCount:t.mipmaps.length,format:t.format,usage:r.usage??GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST});try{for(let[n,r]of t.mipmaps.entries()){let i=Math.ceil(r.height/c);e.queue.writeTexture({texture:u,mipLevel:n},r.data,{bytesPerRow:a(o,r.width,r.height)[1],rowsPerImage:i},[Math.ceil(r.width/s)*s,i*c,t.layers])}}catch(e){throw u.destroy(),e}return u}var c={DXT1:`bc1-rgba-unorm`,DXT2:`bc2-rgba-unorm`,DXT3:`bc2-rgba-unorm`,DXT4:`bc3-rgba-unorm`,DXT5:`bc3-rgba-unorm`,ATI1:`bc4-r-unorm`,BC4U:`bc4-r-unorm`,BC4S:`bc4-r-snorm`,ATI2:`bc5-rg-unorm`,BC5U:`bc5-rg-unorm`,BC5S:`bc5-rg-snorm`,111:`r16float`,112:`rg16float`,113:`rgba16float`,114:`r32float`,115:`rg32float`,116:`rgba32float`},l={2:`rgba32float`,10:`rgba16float`,16:`rg32float`,24:`rgb10a2unorm`,26:`rg11b10ufloat`,28:`rgba8unorm`,29:`rgba8unorm-srgb`,31:`rgba8snorm`,34:`rg16float`,41:`r32float`,49:`rg8unorm`,51:`rg8snorm`,54:`r16float`,61:`r8unorm`,63:`r8snorm`,67:`rgb9e5ufloat`,71:`bc1-rgba-unorm`,72:`bc1-rgba-unorm-srgb`,74:`bc2-rgba-unorm`,75:`bc2-rgba-unorm-srgb`,77:`bc3-rgba-unorm`,78:`bc3-rgba-unorm-srgb`,80:`bc4-r-unorm`,81:`bc4-r-snorm`,83:`bc5-rg-unorm`,84:`bc5-rg-snorm`,95:`bc6h-rgb-ufloat`,96:`bc6h-rgb-float`,98:`bc7-rgba-unorm`,99:`bc7-rgba-unorm-srgb`},u={85:[16,63488,2016,31,0],86:[16,31744,992,31,32768],87:[32,16711680,65280,255,4278190080],88:[32,16711680,65280,255,0],91:[32,16711680,65280,255,4278190080,!0],93:[32,16711680,65280,255,0,!0],115:[16,3840,240,15,61440]},d=e=>t(`DDS ${e}; pass the complete bytes of a valid DDS file`),f=e=>t(`DDS ${e} is not supported; convert the file to a 2D, cube or array texture in a WebGPU format`);function p(e,t,n,r,i){let a=new Uint8Array(t*4),o=[0,1,2,3].map(e=>r[i&&e<3?0:e]>>>0);for(let r=0;r<t;r++){let t=0;for(let i=0;i<n;i++)t+=e[r*n+i]*2**(8*i);for(let e=0;e<4;e++){let n=o[e];a[r*4+e]=n?Math.round(((t&n)>>>0)/n*255):e===3?255:0}}return a}function m(e){if(!(e instanceof Uint8Array))throw TypeError(`parseDDS needs the DDS file as a Uint8Array`);let t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=e=>t.getUint32(e,!0);if(e.length<128||n(0)!==542327876||n(4)!==124||n(76)!==32)throw d(`header is missing`);let r=n(12),s=n(16),m=n(80),h=n(112),g=String.fromCharCode(e[84],e[85],e[86],e[87]),_=Math.max(1,n(28));if(!s||!r||s>65536||r>65536)throw d(`size ${s}x${r} is invalid`);if(_>32-Math.clz32(Math.max(s,r)))throw d(`has ${_} mip levels, too many for its size`);if(h&2097152||n(8)&8388608&&n(24)>1)throw f(`volume texture`);let v,y,b=0,x=!1,S=!0,C=!!(h&512),w=1,T=128;if(C&&(h&64512)!=64512)throw f(`cube map without all six faces`);if(m&4&&g===`DX10`){if(e.length<148)throw d(`DX10 header is missing`);let t=n(128),r=u[t];if(n(132)!==3&&n(132)!==0)throw f(`resource dimension ${n(132)} (only 2D textures)`);if(C=!!(n(136)&4),w=n(140)||1,S=(n(144)&7)!=3,T=148,r?([b]=r,b/=8,y=r.slice(1,5),v=r[5]?`rgba8unorm-srgb`:`rgba8unorm`,S&&=!!r[4]):v=l[t],!v)throw f(`DXGI format ${t}`)}else if(m&4){let e=/^[\x20-\x7e]{4}$/.test(g)?g:String(n(84));if(v=c[e],!v)throw f(`FourCC ${e}`)}else if(m&131138){let e=n(88),t=m&3?n(104):0;if(x=!!(m&131072),y=m&131136?[n(92),n(96),n(100),t]:[0,0,0,t],![8,16,24,32].includes(e)||y.every(e=>!e))throw d(`pixel format of ${e} bits is invalid`);b=e/8,S=!!t,v=`rgba8unorm`,e===32&&!x&&y.join()===[255,65280,16711680,t?4278190080:0].join()&&t&&(y=void 0)}else throw f(`pixel format (YUV or unknown)`);let E=i(v),D=w*(C?6:1),O=[];(/^bc[456]/.test(v)||/^(r|rg)\d/.test(v))&&(S=!1);for(let t=0;t<D;t++){let n=[];for(let i=0;i<_;i++){let o=Math.max(1,s>>i),c=Math.max(1,r>>i),l=y?o*c*b:a(E,o,c)[0];if(T+l>e.length)throw d(`ends inside layer ${t} mip ${i}`);let u=e.subarray(T,T+=l);n.push(y?p(u,o*c,b,y,x):u)}O.push(n)}return{width:s,height:r,layers:D,dimension:C?w>1?`cube-array`:`cube`:D>1?`2d-array`:`2d`,mipmaps:o(O,s,r),format:v,...E[3]?{feature:E[3]}:{},target:`dds`,srgb:v.endsWith(`-srgb`),hasAlpha:S}}var h=`0011001100110011000100010001000101110111011101110001001100110111000000010001001100110111011111110001001101111111000000010011011100000000000100110011011111111111000000010111111100000000000101110001011111111111000000001111111100001111111111110000000000001111000010001110111101110001000000000000000010001110011100110001000000110001000000000000100011001110000000001000110001110011001100010011000100010000000010001000110001100110011001100011011001101100000101111110100000001111111100000111000110001110001110011001110001010101010101010000111100001111010110100101101000110011110011000011110000111100010101011010101001101001011010010101101010100101011100111100111000010011110010000011001001001100001110111101110001101001100101100011110011000011011001101001100100000110011000000100111001000000001001110010000000000010011100100000010011100100011011001001001100110110110010010110001110011100001110011100011001101100110010010110001100111001011111101000000100011000111001110000111100110011001100111111000000100010111011100100010001110111`,g=`0011001102212222000100112211222100002001221122110222002200110111000000001122112200110011002200220022002211111111001100112211221100000000111122220000111111112222000011112222222200120012001200120112011201120112012201220122012200110112112212220011200122002220000100110112112201110011200122000000112211221122002200220022111101110111022202220001000122212221000000110122012200001100221022100122012200110000001200121122222201101221122101100000011012211221002211021102002201100110200222220011012201220011000020002211222100000002112212220222002200120011001100120022022201200120012001200000111122220000012012012012012001202012120101200011220011220011001111222200001101010101222222220000000021212121002211220022112200220011002200110220122102201221010122222222010100002121212121210101010101012222022201110222011100021112000211120000211221122112022201110111022200021112111200020110011001102222000000002112211201100110222222220022001100110022002211221122002200000000000021120002000100020001022212220222122201012222222222220111201122012220`,_=[15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,2,8,2,2,8,8,15,2,8,2,2,8,8,2,2,15,15,6,8,2,8,15,15,2,8,2,2,2,15,15,6,6,2,6,8,15,15,2,2,15,15,15,15,15,2,2,15],v=[3,3,15,15,8,3,15,15,8,8,6,6,6,5,3,3,3,3,8,15,3,3,6,10,5,8,8,6,8,5,15,15,8,15,3,5,6,10,8,15,15,3,15,5,15,15,15,15,3,15,5,5,5,8,5,10,5,10,8,13,15,12,3,3],y=[15,8,8,3,15,15,3,8,15,15,15,15,15,15,15,8,15,8,15,3,15,8,15,8,3,15,6,10,15,15,10,8,15,3,15,10,10,8,9,10,6,15,8,15,3,6,6,8,15,3,15,15,15,15,15,15,15,15,15,15,3,15,15,8],b=e=>Math.round((Math.max(e,-127)+127)/254*255),x=e=>e<<3|e>>2,S=e=>e<<2|e>>4;function C(e,t,n,r){let i=e[t]|e[t+1]<<8,a=e[t+2]|e[t+3]<<8,o=[x(i>>11),S(i>>5&63),x(i&31),255,x(a>>11),S(a>>5&63),x(a&31),255],s=!r||i>a;for(let e=0;e<3;e++){let t=o[e],n=o[4+e];s?(o[8+e]=Math.round((2*t+n)/3),o[12+e]=Math.round((t+2*n)/3)):(o[8+e]=t+n+1>>1,o[12+e]=0)}o[11]=255,o[15]=s?255:0;for(let r=0;r<16;r++){let i=(e[t+4+(r>>2)]>>(r&3)*2&3)*4;n[r*4]=o[i],n[r*4+1]=o[i+1],n[r*4+2]=o[i+2],n[r*4+3]=o[i+3]}}function w(e,t,n,r,i){let a=e=>i?Math.max(e<<24>>24,-127):e,o=a(e[t]),s=a(e[t+1]),c=[o,s,0,0,0,0,0,0],l=i?127:255,u=i?-127:0;if(o>s)for(let e=1;e<7;e++)c[e+1]=((7-e)*o+e*s)/7;else{for(let e=1;e<5;e++)c[e+1]=((5-e)*o+e*s)/5;c[6]=u,c[7]=l}for(let a=0;a<16;a++){let o=a*3,s=t+2+(o>>3),u=c[(e[s]|e[s+1]<<8)>>(o&7)&7];n[a*4+r]=n instanceof Float32Array?u/l:i?b(u):Math.round(u)}}var T=(e,t,n)=>C(e,t,n,!0),E=(e,t,n)=>{C(e,t+8,n,!1);for(let r=0;r<16;r++)n[r*4+3]=(e[t+(r>>1)]>>(r&1)*4&15)*17},D=(e,t,n)=>{C(e,t+8,n,!1),w(e,t,n,3,!1)},O=e=>(t,n,r)=>{w(t,n,r,0,e);for(let t=0;t<16;t++)r[t*4+1]=r[t*4+2]=r instanceof Float32Array?0:e?128:0,r[t*4+3]=r instanceof Float32Array?1:255},k=e=>(t,n,r)=>{w(t,n,r,0,e),w(t,n+8,r,1,e);for(let t=0;t<16;t++)r[t*4+2]=r instanceof Float32Array?0:e?128:0,r[t*4+3]=r instanceof Float32Array?1:255};function A(e,t,n,r){let i=0;for(let a=0;a<r;a++,n++)i|=(e[t+(n>>3)]>>(n&7)&1)<<a;return i}var j={2:[0,21,43,64],3:[0,9,18,27,37,46,55,64],4:[0,4,9,13,17,21,26,30,34,38,43,47,51,55,60,64]},M=[[3,4,0,0,4,0,1,0,3,0],[2,6,0,0,6,0,0,1,3,0],[3,6,0,0,5,0,0,0,2,0],[2,6,0,0,7,0,1,0,2,0],[1,0,2,1,5,6,0,0,2,3],[1,0,2,0,7,8,0,0,2,2],[1,0,0,0,7,7,1,0,4,0],[2,6,0,0,5,5,1,0,2,0]],N=(e,t)=>{let n=e<<8-t;return n|n>>t},P=(e,t,n)=>{let r=0;for(;r<8&&!(e[t]>>r&1);)r++;if(r===8){n.fill(0);return}let[i,a,o,s,c,l,u,d,f,p]=M[r],m=r+1,b=n=>{let r=A(e,t,m,n);return m+=n,r},x=b(a),S=b(o),C=b(s),w=i*2,T=new Uint8Array(w*4);for(let e=0;e<3;e++)for(let t=0;t<w;t++)T[t*4+e]=b(c);if(l)for(let e=0;e<w;e++)T[e*4+3]=b(l);let E=new Uint8Array(w);if(u)for(let e=0;e<w;e++)E[e]=b(1);if(d)for(let e=0;e<i;e++)E[e*2]=E[e*2+1]=b(1);let D=u||d?1:0;for(let e=0;e<w;e++)for(let t=0;t<4;t++){if(t===3&&!l){T[e*4+3]=255;continue}let n=(t===3?l:c)+D;T[e*4+t]=N(D?T[e*4+t]<<1|E[e]:T[e*4+t],n)}let O=e=>i===1?0:(i===2?h:g).charCodeAt(x*16+e)-48,k=e=>e===0||i===2&&e===_[x]||i===3&&(e===v[x]||e===y[x]),P=/* @__PURE__ */ new Uint8Array(16),F=/* @__PURE__ */ new Uint8Array(16);for(let e=0;e<16;e++)P[e]=b(k(e)?f-1:f);if(p)for(let e=0;e<16;e++)F[e]=b(e===0?p-1:p);let I=C?F:P,L=C?P:p?F:P,R=j[C?p:f],z=j[C?f:p||f];for(let e=0;e<16;e++){let t=O(e)*8,r=R[I[e]],i=z[L[e]],a=(e,n)=>(64-n)*T[t+e]+n*T[t+4+e]+32>>6,o=a(0,r),s=a(1,r),c=a(2,r),l=a(3,i),u=e*4;n[u]=S===1?l:o,n[u+1]=S===2?l:s,n[u+2]=S===3?l:c,n[u+3]=S===1?o:S===2?s:S===3?c:l}},F={0:`G24 B24 B34 R09..0 G09..0 B09..0 R14..0 G34 G23..0 G14..0 B30 G33..0 B14..0 B31 B23..0 R24..0 B32 R34..0 B33`,1:`G25 G34 G35 R06..0 B30 B31 B24 G06..0 B25 B32 G24 B06..0 B33 B35 B34 R15..0 G23..0 G15..0 G33..0 B15..0 B23..0 R25..0 R35..0`,2:`R09..0 G09..0 B09..0 R14..0 R010 G23..0 G13..0 G010 B30 G33..0 B13..0 B010 B31 B23..0 R24..0 B32 R34..0 B33`,6:`R09..0 G09..0 B09..0 R13..0 R010 G34 G23..0 G14..0 G010 G33..0 B13..0 B010 B31 B23..0 R23..0 B30 B32 R33..0 G24 B33`,10:`R09..0 G09..0 B09..0 R13..0 R010 B24 G23..0 G13..0 G010 B30 G33..0 B14..0 B010 B23..0 R23..0 B31 B32 R33..0 B34 B33`,14:`R08..0 B24 G08..0 G24 B08..0 B34 R14..0 G34 G23..0 G14..0 B30 G33..0 B14..0 B31 B23..0 R24..0 B32 R34..0 B33`,18:`R07..0 G34 B24 G07..0 B32 G24 B07..0 B33 B34 R15..0 G23..0 G14..0 B30 G33..0 B14..0 B31 B23..0 R25..0 R35..0`,22:`R07..0 B30 B24 G07..0 G25 G24 B07..0 G35 B34 R14..0 G34 G23..0 G15..0 G33..0 B14..0 B31 B23..0 R24..0 B32 R34..0 B33`,26:`R07..0 B31 B24 G07..0 B25 G24 B07..0 B35 B34 R14..0 G34 G23..0 G14..0 B30 G33..0 B15..0 B23..0 R24..0 B32 R34..0 B33`,30:`R05..0 G34 B30 B31 B24 G05..0 G25 B25 B32 G24 B05..0 G35 B33 B35 B34 R15..0 G23..0 G15..0 G33..0 B15..0 B23..0 R25..0 R35..0`,3:`R09..0 G09..0 B09..0 R19..0 G19..0 B19..0`,7:`R09..0 G09..0 B09..0 R18..0 R010 G18..0 G010 B18..0 B010`,11:`R09..0 G09..0 B09..0 R17..0 R010..11 G17..0 G010..11 B17..0 B010..11`,15:`R09..0 G09..0 B09..0 R13..0 R010..15 G13..0 G010..15 B13..0 B010..15`},I={0:[!0,10,5,5,5],1:[!0,7,6,6,6],2:[!0,11,5,4,4],6:[!0,11,4,5,4],10:[!0,11,4,4,5],14:[!0,9,5,5,5],18:[!0,8,6,5,5],22:[!0,8,5,6,5],26:[!0,8,5,5,6],30:[!1,6,6,6,6],3:[!1,10,10,10,10],7:[!0,11,9,9,9],11:[!0,12,8,8,8],15:[!0,16,4,4,4]},L=/* @__PURE__ */ new Map;function R(e){let t=L.get(e);return t||(t=F[e].split(` `).map(e=>{let[,t,n,r,i]=/^([RGB])(\d)(\d+)(?:\.\.(\d+))?$/.exec(e),a=Number(i??r),o=Number(r),s=[];for(let e=a;s.push(e),e!==o;e+=o>=a?1:-1);return[Number(n),`RGB`.indexOf(t),s]}),L.set(e,t)),t}var z=(e,t)=>t>=32?e:e<<32-t>>32-t;function B(e,t,n){if(!n)return t>=15?e:e===0?0:e===(1<<t)-1?65535:(e<<15)+16384>>t-1;if(t>=16)return e;let r=e<0,i=r?-e:e,a;return a=i===0?0:i>=(1<<t-1)-1?32767:(i<<15)+16384>>t-1,r?-a:a}var V=e=>{let t=e>>10&31,n=e&1023,r=t===0?n/16777216:t===31?n?NaN:1/0:(1+n/1024)*2**(t-15);return e&32768?-r:r},H=e=>{let t=e<=0?0:e>=1?1:e;return Math.round((t<=.0031308?t*12.92:1.055*t**(1/2.4)-.055)*255)},U=e=>(t,n,r)=>{let i=A(t,n,0,2),a=i<2?i:A(t,n,0,5),o=I[a];if(!o){for(let e=0;e<16;e++)r.set([0,0,0,r instanceof Float32Array?1:255],e*4);return}let[s,c,...l]=o,u=a<3||(a&3)==2,d=/* @__PURE__ */ new Int32Array(12),f=i<2?2:5;for(let[e,r,i]of R(a))for(let a of i)t[n+(f>>3)]>>(f&7)&1&&(d[e*3+r]|=1<<a),f++;let p=u?A(t,n,f,5):0;f+=u?5:0;let m=u?4:2;for(let t=0;t<3;t++){e&&(d[t]=z(d[t],c));for(let n=1;n<m;n++){let r=n*3+t;s&&(d[r]=z(d[r],l[t])+d[t]&(1<<c)-1),e&&(d[r]=z(d[r],c))}for(let n=0;n<m;n++)d[n*3+t]=B(d[n*3+t],c,e)}let g=u?3:4,v=j[g];for(let i=0;i<16;i++){let a=u?h.charCodeAt(p*16+i)-48:0,o=i===0||u&&i===_[p]?g-1:g,s=v[A(t,n,f,o)];f+=o;for(let t=0;t<3;t++){let n=d[a*6+t],o=d[a*6+3+t],c=(64-s)*n+s*o+32>>6,l=e?c<0?-c*31>>5|32768:c*31>>5:c*31>>6;r[i*4+t]=r instanceof Float32Array?V(l):H(V(l))}r[i*4+3]=r instanceof Float32Array?1:255}},W={"bc1-rgba":[T,8],"bc2-rgba":[E,16],"bc3-rgba":[D,16],"bc4-r-unorm":[O(!1),8],"bc4-r-snorm":[O(!0),8],"bc5-rg-unorm":[k(!1),16],"bc5-rg-snorm":[k(!0),16],"bc6h-rgb-ufloat":[U(!1),16],"bc6h-rgb-float":[U(!0),16],"bc7-rgba":[P,16]};function G(e,n,r,i){let a=W[e.replace(/-unorm(-srgb)?$/,t=>/^bc[45]/.test(e)?t:``)];if(!a)throw TypeError(`${e} is not a BC format; pass one of bc1-rgba-unorm to bc7-rgba-unorm-srgb`);let[o,s]=a,c=r+3>>2,l=i+3>>2;if(n.length<c*l*s)throw t(`${e}: ${n.length} bytes hold too few blocks for ${r}x${i}; pass the whole level`);let u=new Uint8Array(r*i*4),d=/* @__PURE__ */ new Uint8Array(64);for(let e=0;e<l;e++)for(let t=0;t<c;t++){o(n,(e*c+t)*s,d);for(let n=0;n<4&&e*4+n<i;n++){let i=Math.min(4,r-t*4);u.set(d.subarray(n*16,n*16+i*4),((e*4+n)*r+t*4)*4)}}return{width:r,height:i,data:u}}function K(e,n,r,i){if(!/^bc[456]/.test(e)){let t=G(e,n,r,i);return{width:r,height:i,data:Float32Array.from(t.data,e=>e/255)}}let a=W[e];if(!a)throw TypeError(`Unknown BC float format `+e+`; pass a BC4, BC5 or BC6H WebGPU format`);let[o,s]=a,c=Math.ceil(r/4),l=Math.ceil(i/4);if(n.length<c*l*s)throw t(`BC float image has too few blocks; pass the complete mip level`);let u=new Float32Array(r*i*4),d=/* @__PURE__ */ new Float32Array(64);for(let e=0;e<l;e++)for(let t=0;t<c;t++){o(n,(e*c+t)*s,d);for(let n=0;n<4&&e*4+n<i;n++){let i=Math.min(4,r-t*4);u.set(d.subarray(n*16,n*16+i*4),((e*4+n)*r+t*4)*4)}}return{width:r,height:i,data:u}}function q(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 J(t,n={}){n.signal?.throwIfAborted();let r=m(t);if(r.dimension!==`2d`||r.layers!==1)throw e(`unsupported`,`glTF material DDS images must be single-layer 2D textures; export a 2D image`);if(r.width*r.height>67108864)throw RangeError(`glTF DDS image exceeds decoded size limit; export a smaller texture`);let i,a=e=>{if(!r.feature||e.features.has(r.feature)&&r.width%4==0&&r.height%4==0)return r;if(!i){let e=/^bc[456]/.test(r.format),t=r.mipmaps.map(t=>{let n=e?K(r.format,t.data,t.width,t.height):G(r.format,t.data,t.width,t.height),i=e?Uint16Array.from(n.data,q):n.data,a=new Uint8Array(i.buffer,i.byteOffset,i.byteLength);return{...t,data:a,byteLength:a.length}});i={...r,format:e?`rgba16float`:`rgba8unorm`,feature:void 0,mipmaps:t}}return i},o=(e,t)=>{let n=a(e).format.replace(/-srgb$/,``);return n+(t&&/^(rgba8unorm|bc[1237]-)/.test(n)?`-srgb`:``)};return{width:r.width,height:r.height,format:r.format,mipmaps:r.mipmaps,gpuFormat:o,upload(t,n){let r=a(t),i=o(t,n);if(/^(r|rg|rgba)32float$/.test(i)&&!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 s(t,{...r,format:i})}}}var Y={decode:J};export{Y as ddsTextures,J as decodeDDSImage};
|
|
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};
|
|
@@ -3,6 +3,8 @@ import type { GLTFDecoderHooks } from './asset.js';
|
|
|
3
3
|
/**
|
|
4
4
|
* Decoders with the physical material shader added when the file uses a physical material extension and the caller
|
|
5
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
|
|
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.
|
|
7
9
|
*/
|
|
8
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>;
|
package/dist/extended.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,
|
|
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};
|
package/dist/group.d.ts
CHANGED
|
@@ -1,6 +1,18 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
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.
|
|
5
17
|
*/
|
|
6
18
|
export declare function pipelineGroup(device: GPUDevice, pipeline: GPURenderPipeline, index: number, entries: GPUBindGroupEntry[]): GPUBindGroup;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,23 @@
|
|
|
1
1
|
import type { EngineKernel, Mesh as MeshHandle } from '@margoengine/core';
|
|
2
2
|
import { Geometry, type Engine } from '@margoengine/core/extension';
|
|
3
|
+
import type { GLTFWarning } from './warning.js';
|
|
4
|
+
export type { GLTFWarning } from './warning.js';
|
|
3
5
|
import type { GLTFDocument as Document, GLTFPrimitive } from './shared/gltf.js';
|
|
4
6
|
/** A parsed glTF scene: the root mesh handle, every mesh and node handle, and dispose() to release them. */
|
|
5
7
|
export interface Model {
|
|
6
8
|
root: MeshHandle;
|
|
9
|
+
/** The drawn meshes, one per triangle primitive, in the order of `nodes` and then primitive order. */
|
|
7
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
|
+
*/
|
|
8
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[];
|
|
9
18
|
dispose(): void;
|
|
19
|
+
/** The same as `dispose()`, so `using model = parseGLTF(...)` releases it (KB-GLTFA A8). */
|
|
20
|
+
[Symbol.dispose](): void;
|
|
10
21
|
}
|
|
11
22
|
/** A file on its way through the loader. An extension may replace `doc` and `buffers`, never change what they hold. */
|
|
12
23
|
export interface GLTFFile {
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{t as loadGLTF,n as parseGLTF,r as parseGLTFAsync}from"./src-
|
|
1
|
+
export{t as loadGLTF,n as parseGLTF,r as parseGLTFAsync}from"./src-Btvz5f6i.js";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
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
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
3
|
@vertex fn vertex(i:Input,k:Instance)->Out {
|
|
4
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;`:``}
|
package/dist/instancing.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"./limits-_LZ441oV.js";import{r as t}from"./accessor-
|
|
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};
|
package/dist/lights.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{margoError as e}from"@margoengine/core/extension";import{decodePNG as t}from"@margoengine/decoders/png";var n=e=>/* @__PURE__ */ TypeError(`Invalid glTF ${e}; the file is not valid, re-export it and check it with the glTF Validator`),r=(t,n)=>t.catch(t=>{throw e(`unsupported`,`glTF light extensions need ${n} (${t instanceof Error?t.message:t}): install it to use @margoengine/gltf/lights`)});async function i(t,r,{baseURL:i=t.asset.baseURL,fetch:a=globalThis.fetch,signal:o}){if(r.bufferView!==void 0){let e=t.asset.doc.bufferViews?.[r.bufferView],i=e&&t.asset.buffers[e.buffer];if(!e||!i)throw n(`light bufferView`);return i.subarray(e.byteOffset??0,(e.byteOffset??0)+e.byteLength)}if(typeof r.uri!=`string`)throw n(`light file: it needs a uri or a bufferView`);if(!r.uri.startsWith(`data:`)&&i===void 0&&!/^[a-z]+:/i.test(r.uri))throw e(`state`,`glTF light file ${r.uri} is relative and the model has no base URL; pass baseURL`);let s=await a(new URL(r.uri,i),{signal:o});if(!s.ok)throw e(`failed`,`glTF light file ${r.uri} answered ${s.status}; check that it is there`);return new Uint8Array(await s.arrayBuffer())}async function a(e,t={}){let a=e.asset.doc,o=a.extensions?.EXT_lights_ies?.lights,s=a.nodes??[];if(!s.some(e=>e?.extensions?.EXT_lights_ies))return[];if(!Array.isArray(o))throw n(`EXT_lights_ies: it has no lights`);let{parseIES:c}=await r(import(`@margoengine/clustered/ies`),`@margoengine/clustered`),l=/* @__PURE__ */ new Map,u=[];for(let r=0;r<s.length;r++){let a=s[r]?.extensions?.EXT_lights_ies;if(!a||!e.nodes[r])continue;let d=a.light;if(d===void 0)throw n(`EXT_lights_ies light index`);let f=o[d],p=a.multiplier??1,m=a.color??[1,1,1];if(!f)throw n(`EXT_lights_ies light index`);if(typeof p!=`number`||!Number.isFinite(p)||p<0)throw n(`EXT_lights_ies multiplier`);if(!Array.isArray(m)||m.length!==3||m.some(e=>typeof e!=`number`||!Number.isFinite(e)))throw n(`EXT_lights_ies color`);if(f.bufferView!==void 0&&f.mimeType!==`application/x-ies-lm-63`)throw n(`EXT_lights_ies mimeType`);let h=l.get(d);h||l.set(d,h=i(e,f,t).then(e=>c(new TextDecoder().decode(e)))),u.push({name:f.name??``,profile:await h,nodeIndex:r,multiplier:p,color:m.map(e=>Math.min(1,Math.max(0,e)))})}return u}function o([e,t,n,r],i){let a=2*(t*i[2]-n*i[1]),o=2*(n*i[0]-e*i[2]),s=2*(e*i[1]-t*i[0]);return[i[0]+r*a+t*s-n*o,i[1]+r*o+n*a-e*s,i[2]+r*s+e*o-t*a]}var s=1,c=5;function l(e,t,n){let r=180/Math.PI,i=Array.from({length:181},(e,t)=>t*s),a=Array.from({length:73},(e,t)=>t*c),o=(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],l=a.map(a=>i.map(i=>{let s=i/r,c=a/r,l=[Math.sin(s)*Math.cos(c),-Math.cos(s),-Math.sin(s)*Math.sin(c)],u=o(l,n[0]),d=o(l,n[1]),f=o(l,n[2]);return t(e,Math.acos(Math.min(1,Math.max(-1,-f)))*r,Math.atan2(d,u)*r)}));return{...e,vertical:i,horizontal:a,candela:l,peak:Math.max(...l.map(e=>Math.max(...e)))}}var u=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4;async function d(e,n){if(n===`image/png`||e[0]===137&&e[1]===80)return t(e);let r=await createImageBitmap(new Blob([e],{type:n??`image/jpeg`}),{colorSpaceConversion:`none`}),i=new OffscreenCanvas(r.width,r.height),a=i.getContext(`2d`);return a.drawImage(r,0,0),r.close(),{width:i.width,height:i.height,data:new Uint8Array(a.getImageData(0,0,i.width,i.height).data.buffer)}}function f({width:e,data:t}){let n=new Float32Array(e*e*4);for(let r=0;r<e;r++)for(let i=0;i<e;i++){let a=((e-1-r)*e+i)*4,o=(r*e+i)*4,s=Math.max(t[a+3],1);for(let e=0;e<3;e++)n[o+e]=u(t[a+e]/s);n[o+3]=1}return n}var p=(e,t,n)=>[[1,-n,-t],[-1,-n,t],[t,1,n],[t,-1,-n],[t,-n,1],[-t,-n,-1]][e];function m({size:e,faces:t},n,r,i){let[a,o,s]=n.map(Math.abs),c=a>=o&&a>=s?n[0]>0?0:1:o>=s?n[1]>0?2:3:n[2]>0?4:5,l=Math.max(a,o,s),[u,d]=[[-n[2],-n[1]],[n[2],-n[1]],[n[0],n[2]],[n[0],-n[2]],[n[0],-n[1]],[-n[0],-n[1]]][c],f=Math.min(e-1,Math.max(0,(u/l+1)*e/2-.5)),p=Math.min(e-1,Math.max(0,(d/l+1)*e/2-.5)),m=Math.floor(f),h=Math.floor(p),g=Math.min(e-1,m+1),_=Math.min(e-1,h+1),v=f-m,y=p-h,b=t[c];for(let t=0;t<4;t++){let n=b[(h*e+m)*4+t]*(1-v)+b[(h*e+g)*4+t]*v,a=b[(_*e+m)*4+t]*(1-v)+b[(_*e+g)*4+t]*v;r[i+t]=n*(1-y)+a*y}}function h(e,[t,n,r,i]){if(t===0&&n===0&&r===0)return e;let a=[-t,-n,-r,i],{size:s}=e;return{size:s,faces:e.faces.map((t,n)=>{let r=new Float32Array(s*s*4);for(let t=0;t<s;t++)for(let i=0;i<s;i++)m(e,o(a,p(n,(i+.5)/s*2-1,(t+.5)/s*2-1)),r,(t*s+i)*4);return r})}}async function g(e,t={}){let r=e.asset.doc,a=(r.scenes?.[t.scene??r.scene??0])?.extensions?.EXT_lights_image_based?.light;if(a===void 0)return;let o=r.extensions?.EXT_lights_image_based?.lights?.[a];if(!o)throw n(`EXT_lights_image_based light index`);let{specularImages:s,specularImageSize:c,irradianceCoefficients:l,intensity:u=1}=o,p=o.rotation??[0,0,0,1];if(!Array.isArray(s)||!Array.isArray(s[0])||s[0].length!==6||!Number.isInteger(c)||c<1||c&c-1)throw n(`EXT_lights_image_based specular images`);if(!Array.isArray(l)||l.length!==9)throw n(`EXT_lights_image_based irradiance coefficients`);if(!Array.isArray(p)||p.length!==4||Math.abs(Math.hypot(...p)-1)>.001)throw n(`EXT_lights_image_based rotation`);if(typeof u!=`number`||!Number.isFinite(u)||u<0)throw n(`EXT_lights_image_based intensity`);let m=[p[0],p[1],p[2],p[3]],g=await Promise.all(s[0].map(async a=>{let o=r.images?.[a];if(!o)throw n(`EXT_lights_image_based image index`);let s=await d(await i(e,o,t),o.mimeType);if(s.width!==c||s.height!==c)throw n(`EXT_lights_image_based image: it must be specularImageSize square`);return f(s)}));return{name:o.name??``,intensity:u,rotation:m,faces:h({size:c,faces:g},m),irradianceCoefficients:l}}function _(e,t,n,r=1){let i=/* @__PURE__ */ new Map,a=[],o=[];for(let s of e){let e=t(s.nodeIndex),c=t=>{let n=Math.hypot(e[t],e[t+1],e[t+2])||1;return[e[t]/n,e[t+1]/n,e[t+2]/n]},u=[c(0),c(4),c(8)],d=u.flat().map(e=>e.toFixed(3)).join(),f=i.get(s.profile);f||i.set(s.profile,f=/* @__PURE__ */ new Map);let p=f.get(d);p||f.set(d,p=l(s.profile,n,u));let m=p.peak*s.multiplier*r;a.push({position:[e[12],e[13],e[14]],range:Math.sqrt(m*256)||1,color:s.color,intensity:m,decay:2}),o.push(p)}return{fixtures:a,profiles:o}}async function v(e,t={}){let{exposure:n=1,background:i=!1}=t;if(!Number.isFinite(n)||n<0)throw RangeError(`applyGLTFLightExtensions: exposure must be a finite number of 0 or more; pass a number such as 1`);let o=e.engine,[s,c]=await Promise.all([a(e,t),g(e,t)]),l=[],u={},d=()=>{for(let e of l.splice(0).reverse())e()};try{if(s.length){let[{Clustered:i},{IESLights:a,iesCandela:c}]=await Promise.all([r(import(`@margoengine/clustered`),`@margoengine/clustered`),r(import(`@margoengine/clustered/ies`),`@margoengine/clustered`)]),d=t.clustered??i.attach(o);t.clustered||l.push(()=>d.dispose());let f=a.attach(o,{lights:d});l.push(()=>f.dispose()),o.store.tick(!1);let p=e.clusteredLights(),{fixtures:m,profiles:h}=_(s,t=>e.nodes[t].matrix,c,n);d.setLights([...p,...m]),f.setProfiles([...p.map(()=>null),...h]),l.push(d.add(e)),Object.assign(u,{clustered:d,ies:f})}if(c){let{Environment:t,EnvironmentBackground:n,EnvironmentLighting:a}=await r(import(`@margoengine/environment`),`@margoengine/environment`),s=await t.attach(o,c.faces,{intensity:c.intensity}),d=a.attach(o,s);if(l.push(()=>s.dispose()),l.push(()=>d.dispose()),d.add(e),Object.assign(u,{environment:s,lighting:d}),i){let e=n.attach(o,s);l.push(()=>e.dispose()),u.background=e}}}catch(e){throw d(),e}return{iesLights:s,imageLight:c,...u,dispose:d,[Symbol.dispose]:d}}export{v as applyGLTFLightExtensions,a as gltfIESLights,g as gltfImageLight,l as orientIES,_ as placeIESLights,h as rotateCube};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{typeError as e}from"@margoengine/core/extension";var t=/* @__PURE__ */ new WeakMap,n=/* @__PURE__ */ new WeakSet;function r(e){return n.delete(e)?void 0:t.get(e)}function i(t,r,i,a){let o=r({model:t,context:i[0],mode:i[1],phase:i[4]??`all`,draw(){n.add(t);try{a()}finally{n.delete(t)}}});if(o&&typeof o.then==`function`)throw e(`Material draw adapters must complete synchronously; do not return a promise`,`material`)}function a(e,n){let r=t.get(e);r?t.set(n,r):t.delete(n)}export{i,a as n,t as r,r as t};
|
package/dist/material-draw.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{r as e}from"./material-draw-state-GKiHDb0p.js";import{fault as t}from"@margoengine/core/extension";function n(n,r){if(n.disposed)throw t(`disposed`,`Material drawing needs a live model; load the model again`);if(typeof r!=`function`)throw TypeError(`Material draw adapter must be a synchronous function; see https://margoengine.com/errors#material`);if(e.has(n))throw t(`attached`,`A material draw adapter is already installed; remove it before installing another`,`material`);let i,a=()=>{e.get(n)===r&&e.delete(n),i?.(),i=void 0};e.set(n,r);try{i=n.onDispose(a)}catch(e){throw a(),e}return a}export{n as setMaterialDraw};
|
package/dist/meshopt.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"./accessor-
|
|
1
|
+
import{n as e}from"./accessor-CU_1uSZ1.js";import{MargoError as t}from"@margoengine/math/errors";var n=[`EXT_meshopt_compression`,`KHR_meshopt_compression`],r=67108864,i=e=>e.extensions?.[n[0]]??e.extensions?.[n[1]];async function a(){try{return await import(`@margoengine/decoders/meshopt`)}catch(e){throw/Cannot find|Failed to resolve|dynamically imported module/i.test(e.message)?new t(`failed`,`Meshopt glTF needs a decoder; install @margoengine/decoders`):e}}var o={handles:n,async load(t){let o=t.doc.bufferViews??[];if(!o.some(i))return;let{meshoptDecodeGltfBuffer:s}=await a(),c=[...t.buffers],l=[...t.doc.buffers??[]],u=0,d=o.map(t=>{let a=i(t);if(!a)return t;let o=c[e(a.buffer,`meshopt buffer`)],d=e(a.byteOffset??0,`meshopt offset`),f=e(a.byteLength,`meshopt length`,1),p=e(a.count,`meshopt count`,1),m=e(a.byteStride,`meshopt stride`,1);if(!o||d+f>o.length)throw RangeError(`glTF meshopt data is outside its buffer; re-export the file`);if(u+=p*m,u>r)throw RangeError(`glTF meshopt data decodes past 64 MiB; load a smaller file or split it`);let h=s(o.subarray(d,d+f),p,m,a.mode,a.filter);if(h.length<e(t.byteLength,`view length`,1))throw RangeError(`glTF meshopt data is shorter than its bufferView; re-export the file`);let{extensions:g,..._}=t,v=Object.fromEntries(Object.entries(g).filter(([e])=>!n.includes(e)));return c.push(h),l.push({byteLength:h.length}),{..._,buffer:c.length-1,byteOffset:0,...Object.keys(v).length?{extensions:v}:{}}});t.buffers=c,t.doc={...t.doc,buffers:l,bufferViews:d}}};export{o as meshopt};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
var e=e=>`
|
|
2
|
+
@vertex fn vertex(@builtin(vertex_index) i:u32)->@builtin(position) vec4f {
|
|
3
|
+
return vec4f(array<vec2f,3>(vec2f(-1,-1),vec2f(3,-1),vec2f(-1,3))[i],0,1);
|
|
4
|
+
}
|
|
5
|
+
@group(0) @binding(0) var image:texture_2d<f32>;
|
|
6
|
+
@fragment fn fragment(@builtin(position) clip:vec4f)->@location(0) vec4f {
|
|
7
|
+
let src=textureDimensions(image);
|
|
8
|
+
let dst=max(src/2u,vec2u(1u));let g=vec2u(clip.xy);
|
|
9
|
+
let a=vec2f(g*src)/vec2f(dst);let b=vec2f((g+1u)*src)/vec2f(dst);let end=min(src,((g+1u)*src+dst-1u)/dst);
|
|
10
|
+
var sum=vec4f(0.0);var sc=vec3f(0.0);
|
|
11
|
+
for(var y=g.y*src.y/dst.y;y<end.y;y++){
|
|
12
|
+
let wy=min(b.y,f32(y+1u))-max(a.y,f32(y));
|
|
13
|
+
for(var x=g.x*src.x/dst.x;x<end.x;x++){
|
|
14
|
+
let w=(min(b.x,f32(x+1u))-max(a.x,f32(x)))*wy;let t=textureLoad(image,vec2u(x,y),0);
|
|
15
|
+
sum+=w*t;sc+=(w*t.a)*t.rgb;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
let area=(b.x-a.x)*(b.y-a.y);
|
|
19
|
+
${e?`return vec4f(select(sum.rgb/area,sc/sum.a,sum.a>0.0),sum.a/area);`:`return sum/area;`}
|
|
20
|
+
}
|
|
21
|
+
`;function t(t,n,r,i,a=1,o=`plain`){if(r<2)return;let s=n.format,c=o===`weighted`,l=c?s+`:weighted`:s,u=i.get(l);if(!u){let n=t.createShaderModule({code:e(c)});i.set(l,u=t.createRenderPipeline({layout:`auto`,vertex:{module:n,entryPoint:`vertex`},fragment:{module:n,entryPoint:`fragment`,targets:[{format:s}]}}))}let d=t.createCommandEncoder();for(let e=0;e<a;e++)for(let i=1;i<r;i++){let r=t=>n.createView(a>1?{format:s,dimension:`2d`,baseMipLevel:t,mipLevelCount:1,baseArrayLayer:e,arrayLayerCount:1}:{baseMipLevel:t,mipLevelCount:1}),o=t.createBindGroup({layout:u.getBindGroupLayout(0),entries:[{binding:0,resource:r(i-1)}]}),c=d.beginRenderPass({colorAttachments:[{view:r(i),loadOp:`clear`,storeOp:`store`,clearValue:{r:0,g:0,b:0,a:0}}]});c.setPipeline(u),c.setBindGroup(0,o),c.draw(3),c.end()}t.queue.submit([d.finish()])}export{e as n,t};
|