New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@gltf-transform/functions

Package Overview
Dependencies
Maintainers
1
Versions
146
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@gltf-transform/functions - npm Package Compare versions

Comparing version 2.0.4 to 2.0.5

dist/normals.d.ts

2

dist/functions.js

@@ -1,2 +0,2 @@

var e=require("@gltf-transform/core"),t=require("ndarray-pixels"),n=require("@gltf-transform/extensions"),r=require("gl-matrix/mat4"),o=require("gl-matrix/vec3"),s=require("ndarray"),i=require("ndarray-lanczos");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var c=/*#__PURE__*/a(s);const u=function(e,n,r){try{if(!e)return Promise.resolve(null);const o=e.getImage();return o?Promise.resolve(t.getPixels(o,e.getMimeType())).then(function(e){for(let t=0;t<e.shape[0];++t)for(let n=0;n<e.shape[1];++n)r(e,t,n);return Promise.resolve(t.savePixels(e,"image/png")).then(function(e){return n.setImage(e).setMimeType("image/png")})}):Promise.resolve(null)}catch(e){return Promise.reject(e)}};function l(e,t){return Object.defineProperty(t,"name",{value:e}),t}function f(t){const n=t.getIndices(),r=t.getAttribute("POSITION");switch(t.getMode()){case e.Primitive.Mode.POINTS:return r.getCount();case e.Primitive.Mode.LINES:return n?n.getCount()/2:r.getCount()/2;case e.Primitive.Mode.LINE_LOOP:return r.getCount();case e.Primitive.Mode.LINE_STRIP:return r.getCount()-1;case e.Primitive.Mode.TRIANGLES:return n?n.getCount()/3:r.getCount()/3;case e.Primitive.Mode.TRIANGLE_STRIP:case e.Primitive.Mode.TRIANGLE_FAN:return r.getCount()-2;default:throw new Error("Unexpected mode: "+t.getMode())}}class g{constructor(){this._map=new Map}get size(){return this._map.size}has(e){return this._map.has(e)}add(e,t){let n=this._map.get(e);return n||(n=new Set,this._map.set(e,n)),n.add(t),this}get(e){return this._map.get(e)||new Set}keys(){return this._map.keys()}}const p={pivot:"center"},m="colorspace",d={propertyTypes:[e.PropertyType.ACCESSOR,e.PropertyType.MESH,e.PropertyType.TEXTURE,e.PropertyType.MATERIAL]},h=function(t=d){const n={...d,...t},r=new Set(n.propertyTypes);for(const e of n.propertyTypes)if(!d.propertyTypes.includes(e))throw new Error(`dedup: Unsupported deduplication on type "${e}".`);return l("dedup",t=>{const n=t.getLogger();r.has(e.PropertyType.ACCESSOR)&&function(t,n){const r=new Set,o=new Set,s=new Set,i=new Set,a=n.getRoot().listMeshes();a.forEach(e=>{e.listPrimitives().forEach(e=>{e.listAttributes().forEach(e=>o.add(e));const t=e.getIndices();t&&r.add(t)})});for(const e of n.getRoot().listAnimations())for(const t of e.listSamplers()){const e=t.getInput(),n=t.getOutput();e&&s.add(e),n&&i.add(n)}function c(t){const n=new Map;for(let r=0;r<t.length;r++){const o=t[r],s=e.BufferUtils.toView(o.getArray());if(!n.has(o))for(let r=0;r<t.length;r++){const i=t[r];o!==i&&(n.has(i)||o.getType()===i.getType()&&o.getComponentType()===i.getComponentType()&&o.getCount()===i.getCount()&&o.getNormalized()===i.getNormalized()&&e.BufferUtils.equals(s,e.BufferUtils.toView(i.getArray()))&&n.set(i,o))}}return n}const u=c(Array.from(r));t.debug(`dedup: Found ${u.size} duplicates among ${r.size} indices.`);const l=c(Array.from(o));t.debug(`dedup: Found ${l.size} duplicates among ${o.size} attributes.`);const f=c(Array.from(s)),g=c(Array.from(i));t.debug(`dedup: Found ${f.size+g.size} duplicates among ${s.size+i.size} animation accessors.`),a.forEach(e=>{e.listPrimitives().forEach(e=>{e.listAttributes().forEach(t=>{l.has(t)&&e.swap(t,l.get(t))});const t=e.getIndices();t&&u.has(t)&&e.swap(t,u.get(t))})}),Array.from(u.keys()).forEach(e=>e.dispose()),Array.from(l.keys()).forEach(e=>e.dispose());for(const e of n.getRoot().listAnimations())for(const t of e.listSamplers()){const e=t.getInput(),n=t.getOutput();e&&f.has(e)&&t.swap(e,f.get(e)),n&&g.has(n)&&t.swap(n,g.get(n))}Array.from(f.keys()).forEach(e=>e.dispose()),Array.from(g.keys()).forEach(e=>e.dispose())}(n,t),r.has(e.PropertyType.MESH)&&function(t,n){const r=n.getRoot(),o=new Map;r.listAccessors().forEach((e,t)=>o.set(e,t)),r.listMaterials().forEach((e,t)=>o.set(e,t));const s=r.listMeshes().length,i=new Map;for(const t of r.listMeshes()){const n=[];for(const e of t.listPrimitives())n.push(y(e,o));const r=n.join(";");if(i.has(r)){const n=i.get(r);t.listParents().forEach(r=>{r.propertyType!==e.PropertyType.ROOT&&r.swap(t,n)}),t.dispose()}else i.set(r,t)}t.debug(`dedup: Found ${s-i.size} duplicates among ${s} meshes.`)}(n,t),r.has(e.PropertyType.TEXTURE)&&function(t,n){const r=n.getRoot(),o=r.listTextures(),s=new Map;for(let t=0;t<o.length;t++){const n=o[t],r=n.getImage();if(!s.has(n))for(let t=0;t<o.length;t++){const i=o[t],a=i.getImage();if(n===i)continue;if(s.has(i))continue;if(n.getMimeType()!==i.getMimeType())continue;const c=n.getSize(),u=i.getSize();c&&u&&c[0]===u[0]&&c[1]===u[1]&&r&&a&&e.BufferUtils.equals(r,a)&&s.set(i,n)}}t.debug(`dedup: Found ${s.size} duplicates among ${r.listTextures().length} textures.`),Array.from(s.entries()).forEach(([t,n])=>{t.listParents().forEach(r=>{r instanceof e.Root||r.swap(t,n)}),t.dispose()})}(n,t),r.has(e.PropertyType.MATERIAL)&&function(t,n){const r=n.getRoot(),o=r.listMaterials(),s=new Map;for(let e=0;e<o.length;e++){const t=o[e];if(!s.has(t))for(let e=0;e<o.length;e++){const n=o[e];t!==n&&(s.has(n)||t.equals(n)&&s.set(n,t))}}t.debug(`dedup: Found ${s.size} duplicates among ${r.listMaterials().length} materials.`),Array.from(s.entries()).forEach(([t,n])=>{t.listParents().forEach(r=>{r instanceof e.Root||r.swap(t,n)}),t.dispose()})}(n,t),n.debug("dedup: Complete.")})};function y(t,n){const r=[];for(const e of t.listSemantics()){const o=t.getAttribute(e);r.push(e+":"+n.get(o))}if(t instanceof e.Primitive){const e=t.getIndices();e&&r.push("indices:"+n.get(e));const o=t.getMaterial();o&&r.push("material:"+n.get(o)),r.push("mode:"+t.getMode());for(const e of t.listTargets())r.push("target:"+y(e,n))}return r.join(",")}const A={pattern:/^((?!JOINTS_).)*$/};function T(e,t){for(const n of e.listSemantics())E(n,e.getAttribute(n),t);for(const n of e.listTargets())for(const e of n.listSemantics())E(e,n.getAttribute(e),t)}function E(e,t,n){if(!t.getArray())return;if(!n.pattern.test(e))return;if(t.getComponentSize()>=4)return;const r=t.getArray(),o=new Float32Array(r.length);for(let e=0,n=t.getCount(),s=[];e<n;e++)s=t.getElement(e,s),t.setArray(o).setElement(e,s).setArray(r);t.setArray(o).setNormalized(!1)}function S(t){return{properties:t.getRoot().listScenes().map(t=>{const n=t.listChildren()[0],r=e.bounds(t);return{name:t.getName(),rootName:n?n.getName():"",bboxMin:M(r.min),bboxMax:M(r.max)}})}}function I(e){return{properties:e.getRoot().listMeshes().map(e=>{const t=e.listParents().filter(e=>"Root"!==e.propertyType).length;let n=0,r=0;const o=new Set,s=new Set,i=new Set;e.listPrimitives().forEach(e=>{for(const t of e.listSemantics()){const n=e.getAttribute(t);o.add(t+":"+N(n.getArray())),i.add(n)}for(const t of e.listTargets())t.listAttributes().forEach(e=>i.add(e));const t=e.getIndices();t&&(s.add(N(t.getArray())),i.add(t)),r+=e.listAttributes()[0].getCount(),n+=f(e)});let a=0;Array.from(i).forEach(e=>a+=e.getArray().byteLength);const c=e.listPrimitives().map(e=>w[e.getMode()]);return{name:e.getName(),mode:Array.from(new Set(c)),primitives:e.listPrimitives().length,glPrimitives:n,vertices:r,indices:Array.from(s).sort(),attributes:Array.from(o).sort(),instances:t,size:a}})}}function b(t){return{properties:t.getRoot().listMaterials().map(n=>{const r=n.listParents().filter(e=>"Root"!==e.propertyType).length,o=new Set(n.listExtensions()),s=t.getGraph().listEdges().filter(t=>{const r=t.getChild(),s=t.getParent();return r instanceof e.Texture&&s===n||!!(r instanceof e.Texture&&s instanceof e.ExtensionProperty&&o.has(s))}).map(e=>e.getName());return{name:n.getName(),instances:r,textures:s,alphaMode:n.getAlphaMode(),doubleSided:n.getDoubleSided()}})}}function P(t){return{properties:t.getRoot().listTextures().map(n=>{const r=n.listParents().filter(e=>"Root"!==e.propertyType).length,o=t.getGraph().listParentEdges(n).map(e=>e.getName()).filter(e=>"texture"!==e),s=e.ImageUtils.getSize(n.getImage(),n.getMimeType());return{name:n.getName(),uri:n.getURI(),slots:Array.from(new Set(o)),instances:r,mimeType:n.getMimeType(),resolution:s?s.join("x"):"",size:n.getImage().byteLength,gpuSize:e.ImageUtils.getMemSize(n.getImage(),n.getMimeType())}})}}function R(e){return{properties:e.getRoot().listAnimations().map(e=>{let t=Infinity,n=-Infinity;e.listSamplers().forEach(e=>{const r=e.getInput();r&&(t=Math.min(t,r.getMin([])[0]),n=Math.max(n,r.getMax([])[0]))});let r=0,o=0;const s=new Set;return e.listSamplers().forEach(e=>{const t=e.getInput(),n=e.getOutput();t&&(o+=t.getCount(),s.add(t),n&&s.add(n))}),Array.from(s).forEach(e=>{r+=e.getArray().byteLength}),{name:e.getName(),channels:e.listChannels().length,samplers:e.listSamplers().length,duration:Math.round(1e3*(n-t))/1e3,keyframes:o,size:r}})}}const w=["POINTS","LINES","LINE_LOOP","LINE_STRIP","TRIANGLES","TRIANGLE_STRIP","TRIANGLE_FAN"];function M(e){for(let t=0;t<e.length;t++)e[t].toFixed&&(e[t]=Number(e[t].toFixed(5)));return e}function N(e){return e.constructor.name.replace("Array","").toLowerCase()}const C={};function x(t,n){let r,o=0;for(;r=t.pop();){if(r.listChildren().length||r.getCamera()||r.getMesh()||r.getSkin()||r.listExtensions().length)continue;const n=r.getParent();n instanceof e.Node&&t.push(n),r.dispose(),o++}n.debug(`instance: Removed ${o} unused nodes.`)}function v(e,t,n,r){const o=n.listPrimitives()[0].getAttribute("POSITION").getBuffer(),s=e.createAccessor().setType("VEC3").setArray(new Float32Array(3*r)).setBuffer(o),i=e.createAccessor().setType("VEC4").setArray(new Float32Array(4*r)).setBuffer(o),a=e.createAccessor().setType("VEC3").setArray(new Float32Array(3*r)).setBuffer(o);return t.createInstancedMesh().setAttribute("TRANSLATION",s).setAttribute("ROTATION",i).setAttribute("SCALE",a)}const O=/*#__PURE__*/"undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function z(e,t,n){if(!e.s){if(n instanceof $){if(!n.s)return void(n.o=z.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(z.bind(null,e,t),z.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}const $=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){const r=new e,o=this.s;if(o){const e=1&o?t:n;if(e){try{z(r,1,e(this.v))}catch(e){z(r,2,e)}return r}return this}return this.o=function(e){try{const o=e.v;1&e.s?z(r,1,t?t(o):o):n?z(r,1,n(o)):z(r,2,o)}catch(e){z(r,2,e)}},r},e}();function L(e){return e instanceof $&&1&e.s}const _={},U={propertyTypes:[e.PropertyType.NODE,e.PropertyType.SKIN,e.PropertyType.MESH,e.PropertyType.CAMERA,e.PropertyType.PRIMITIVE,e.PropertyType.PRIMITIVE_TARGET,e.PropertyType.ANIMATION,e.PropertyType.MATERIAL,e.PropertyType.TEXTURE,e.PropertyType.ACCESSOR,e.PropertyType.BUFFER]},q=function(t=U){const n={...U,...t}.propertyTypes;return l("prune",t=>{const r=t.getLogger(),o=t.getRoot(),s=t.getGraph(),i={};if(n.includes(e.PropertyType.NODE)&&o.listNodes().forEach(a),n.includes(e.PropertyType.SKIN)&&o.listSkins().forEach(a),n.includes(e.PropertyType.MESH)&&o.listMeshes().forEach(a),n.includes(e.PropertyType.CAMERA)&&o.listCameras().forEach(a),n.includes(e.PropertyType.PRIMITIVE)&&c(s,e.PropertyType.PRIMITIVE),n.includes(e.PropertyType.PRIMITIVE_TARGET)&&c(s,e.PropertyType.PRIMITIVE_TARGET),n.includes(e.PropertyType.ANIMATION))for(const e of o.listAnimations()){for(const t of e.listChannels())t.getTargetNode()||(t.dispose(),u(t));if(e.listChannels().length)e.listSamplers().forEach(a);else{const t=e.listSamplers();a(e),t.forEach(a)}}if(n.includes(e.PropertyType.MATERIAL)&&o.listMaterials().forEach(a),n.includes(e.PropertyType.TEXTURE)&&o.listTextures().forEach(a),n.includes(e.PropertyType.ACCESSOR)&&o.listAccessors().forEach(a),n.includes(e.PropertyType.BUFFER)&&o.listBuffers().forEach(a),Object.keys(i).length){const e=Object.keys(i).map(e=>`${e} (${i[e]})`).join(", ");r.info(`prune: Removed types... ${e}`)}else r.info("prune: No unused properties found.");function a(t){t.listParents().filter(t=>!(t instanceof e.Root||t instanceof e.AnimationChannel)).length||(t.dispose(),u(t))}function c(e,t){e.listEdges().map(e=>e.getParent()).filter(e=>e.propertyType===t).forEach(a)}function u(e){i[e.propertyType]=i[e.propertyType]||0,i[e.propertyType]++}r.debug("prune: Complete.")})},F={animations:!0,meshes:!0};function k(e,t){let n=`${e}.bin`,r=1;for(;t.has(n);)n=`${e}_${r++}.bin`;return n}const G=[Int8Array,Int16Array,Int32Array],{TRANSLATION:B,ROTATION:j,SCALE:V,WEIGHTS:D}=e.AnimationChannel.TargetPath,H=[B,j,V],W={pattern:/.*/,quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeWeight:8,quantizeGeneric:12};function X(t,n,s,i){const a=t.getLogger();for(const t of n.listSemantics()){if(!i.pattern.test(t))continue;const c=n.getAttribute(t),{bits:u,ctor:l}=Y(t,c,a,i);if(!l)continue;if(u<8||u>16)throw new Error("quantize: Requires bits = 8–16.");if(c.getComponentSize()<=u/8)continue;const f=c.clone();if("POSITION"===t){const t=s.scale,i=[];n instanceof e.Primitive?r.invert(i,ne(s)):r.fromScaling(i,[1/t,1/t,1/t]);for(let e=0,t=[0,0,0],n=f.getCount();e<n;e++)f.getElement(e,t),f.setElement(e,o.transformMat4(t,t,i))}J(f,l,u),n.swap(c,f)}if(n.getAttribute("WEIGHTS_0")&&function(e){const t=e.getAttribute("POSITION").getCount(),n=[];for(let r=0;r<t;r++){let t,o=0,s=Infinity,i=-1,a=null,c=0;for(;t=e.getAttribute("WEIGHTS_"+c++);){t.getElement(r,n);for(let e=0;e<n.length;e++)o+=n[e],n[e]>0&&n[e]<s&&(a=t,s=n[e],i=e)}a&&1!==o&&(a.getElement(r,n),n[i]+=1-o,a.setElement(r,n))}}(n),n instanceof e.Primitive&&n.getIndices()&&n.listAttributes().length&&n.listAttributes()[0].getCount()<65535){const e=n.getIndices();e.setArray(new Uint16Array(e.getArray()))}}function K(e){const{min:t,max:n}=e,r=Math.max((n[0]-t[0])/2,(n[1]-t[1])/2,(n[2]-t[2])/2);return{offset:[t[0]+(n[0]-t[0])/2,t[1]+(n[1]-t[1])/2,t[2]+(n[2]-t[2])/2],scale:r}}function Z(t,n,o){const s=ne(o);for(const i of n.listParents())if(i instanceof e.Node){const a=i.listParents().filter(t=>t instanceof e.AnimationChannel),c=a.some(e=>H.includes(e.getTargetPath())),u=i.listChildren().length>0;if(i.getSkin()){i.setSkin(Q(i.getSkin(),o));continue}let l;u||c?(l=t.createNode("").setMesh(n),i.addChild(l).setMesh(null),a.filter(e=>e.getTargetPath()===D).forEach(e=>e.setTargetNode(l))):l=i;const f=l.getMatrix();r.multiply(f,f,s),l.setMatrix(f)}}function Q(e,t){e=e.clone();const n=ne(t),o=e.getInverseBindMatrices().clone(),s=[];for(let e=0,t=o.getCount();e<t;e++)o.getElement(e,s),r.multiply(s,s,n),o.setElement(e,s);return e.setInverseBindMatrices(o)}function J(e,t,n){const r=new t(e.getArray().length),o=G.includes(t)?1:0,s=n-o,i=8*t.BYTES_PER_ELEMENT-o,a=Math.pow(2,s)-1,c=i-s,u=2*s-i;for(let t=0,n=0,o=[];t<e.getCount();t++){e.getElement(t,o);for(let e=0;e<o.length;e++){let t=Math.round(Math.abs(o[e])*a);t=t<<c|t>>u,r[n++]=t*Math.sign(o[e])}}e.setArray(r).setNormalized(!0)}function Y(e,t,n,r){const o=t.getMinNormalized([]),s=t.getMaxNormalized([]);let i,a;if("POSITION"===e)i=r.quantizePosition,a=i<=8?Int8Array:Int16Array;else if("NORMAL"===e||"TANGENT"===e)i=r.quantizeNormal,a=i<=8?Int8Array:Int16Array;else if(e.startsWith("COLOR_"))i=r.quantizeColor,a=i<=8?Uint8Array:Uint16Array;else if(e.startsWith("TEXCOORD_")){if(o.some(e=>e<0)||s.some(e=>e>1))return n.warn(`quantize: Skipping ${e}; out of [0,1] range.`),{bits:-1};i=r.quantizeTexcoord,a=i<=8?Uint8Array:Uint16Array}else{if(e.startsWith("JOINTS_"))return i=Math.max(...t.getMax([]))<=255?8:16,a=i<=8?Uint8Array:Uint16Array,t.getComponentSize()>i/8&&t.setArray(new a(t.getArray())),{bits:-1};if(e.startsWith("WEIGHTS_")){if(o.some(e=>e<0)||s.some(e=>e>1))return n.warn(`quantize: Skipping ${e}; out of [0,1] range.`),{bits:-1};i=r.quantizeWeight,a=i<=8?Uint8Array:Uint16Array}else{if(!e.startsWith("_"))throw new Error(`quantize: Unexpected semantic, "${e}".`);if(o.some(e=>e<-1)||s.some(e=>e>1))return n.warn(`quantize: Skipping ${e}; out of [-1,1] range.`),{bits:-1};i=r.quantizeGeneric,a=a=o.some(e=>e<0)?i<=8?Int8Array:Int16Array:i<=8?Uint8Array:Uint16Array}}return{bits:i,ctor:a}}function ee(e){const t=[],n=[];for(const r of e.listPrimitives()){const e=r.getAttribute("POSITION");e&&t.push(e);for(const e of r.listTargets()){const t=e.getAttribute("POSITION");t&&n.push(t)}}if(0===t.length)throw new Error('quantize: Missing "POSITION" attribute.');const r=te(t,3);if(n.length>0){const{min:e,max:t}=te(n,3);o.min(r.min,r.min,o.min(e,o.scale(e,e,2),[0,0,0])),o.max(r.max,r.max,o.max(t,o.scale(t,t,2),[0,0,0]))}return r}function te(e,t){const n=new Array(t).fill(Infinity),r=new Array(t).fill(-Infinity),o=[],s=[];for(const i of e){i.getMinNormalized(o),i.getMaxNormalized(s);for(let e=0;e<t;e++)n[e]=Math.min(n[e],o[e]),r[e]=Math.max(r[e],s[e])}return{min:n,max:r}}function ne(e){return r.fromRotationTranslationScale([],[0,0,0,1],e.offset,[e.scale,e.scale,e.scale])}const re={tolerance:1e-4};function oe(e,t){const n=e.getInput().clone(),r=e.getOutput().clone(),o=t.tolerance,s=n.getCount()-1,i=[];let a=1;for(let t=1;t<s;++t){const s=n.getScalar(t),u=n.getScalar(t-1),l=n.getScalar(t+1),f=(s-u)/(l-u);let g=!1;if(s!==l&&(1!==t||s!==n.getScalar(0)))for(let n=0;n<r.getElementSize();n++){const s=r.getElement(t,i)[n],a=r.getElement(t-1,i)[n],u=r.getElement(t+1,i)[n];if("LINEAR"===e.getInterpolation()){if(Math.abs(s-(a*(1-(c=f))+u*c))>o){g=!0;break}}else if("STEP"===e.getInterpolation()&&(s!==a||s!==u)){g=!0;break}}g&&(t!==a&&(n.setScalar(a,n.getScalar(t)),r.setElement(a,r.getElement(t,i))),a++)}var c;s>0&&(n.setScalar(a,n.getScalar(s)),r.setElement(a,r.getElement(s,i)),a++),a!==n.getCount()?(n.setArray(n.getArray().slice(0,a)),r.setArray(r.getArray().slice(0,a*r.getElementSize())),e.setInput(n),e.setOutput(r)):(n.dispose(),r.dispose())}const se={target:"size"};function ie(e,t,n){const r=e.getElementSize(),o=e.getCount(),s=e.getArray(),i=s.slice(0,n*r);for(let e=0;e<o;e++)for(let n=0;n<r;n++)i[t[e]*r+n]=s[e*r+n];e.setArray(i)}function ae(e){const t=[];for(const n of e.listAttributes())t.push(n);for(const n of e.listTargets())for(const e of n.listAttributes())t.push(e);return Array.from(new Set(t))}const ce={name:"",fps:10,pattern:/.*/,sort:!0},ue={overwrite:!1};function le(e){const t=e.getMaterial();if(!t)return"TEXCOORD_0";const n=t.getNormalTextureInfo();if(!n)return"TEXCOORD_0";const r=`TEXCOORD_${n.getTexCoord()}`;return e.getAttribute(r)?r:"TEXCOORD_0"}function fe(t,n,r,o,s){return t.getMode()===e.Primitive.Mode.TRIANGLES&&t.getAttribute("POSITION")&&t.getAttribute("NORMAL")&&t.getAttribute("TEXCOORD_0")?t.getAttribute("TANGENT")&&!s?(n.debug(`tangents: Skipping primitive ${o} of mesh "${r}": TANGENT found.`),!1):!t.getIndices()||(n.warn(`tangents: Skipping primitive ${o} of mesh "${r}": primitives must be unwelded.`),!1):(n.debug(`tangents: Skipping primitive ${o} of mesh "${r}": primitives must have attributes=[POSITION, NORMAL, TEXCOORD_0] and mode=TRIANGLES.`),!1)}const ge=/*#__PURE__*/"undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function pe(e,t,n){if(!e.s){if(n instanceof me){if(!n.s)return void(n.o=pe.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(pe.bind(null,e,t),pe.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}const me=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){const r=new e,o=this.s;if(o){const e=1&o?t:n;if(e){try{pe(r,1,e(this.v))}catch(e){pe(r,2,e)}return r}return this}return this.o=function(e){try{const o=e.v;1&e.s?pe(r,1,t?t(o):o):n?pe(r,1,n(o)):pe(r,2,o)}catch(e){pe(r,2,e)}},r},e}();function de(e){return e instanceof me&&1&e.s}const he="textureResize";var ye;(ye=exports.TextureResizeFilter||(exports.TextureResizeFilter={})).LANCZOS3="lanczos3",ye.LANCZOS2="lanczos2";const Ae={size:[2048,2048],filter:exports.TextureResizeFilter.LANCZOS3,pattern:null},Te={};function Ee(e,t,n,r){if(r.has(e)&&r.get(e).has(t))return n.debug(`unweld: Cache hit for reused attribute, "${e.getName()}".`),r.get(e).get(t);const o=e.clone(),s=e.getArray().constructor;o.setArray(new s(t.getCount()*e.getElementSize()));const i=[];for(let n=0;n<t.getCount();n++)o.setElement(n,e.getElement(t.getScalar(n),i));return r.has(e)||r.set(e,new Map),r.get(e).set(t,o),o}const Se={tolerance:1e-4};function Ie(t,n){if(n.getIndices())return;const r=n.listAttributes()[0],o=r.getCount(),s=r.getBuffer(),i=o<=65534?new Uint16Array(3*f(n)):new Uint32Array(3*f(n)),a=t.createAccessor().setBuffer(s).setType(e.Accessor.Type.SCALAR).setArray(i);for(let e=0;e<a.getCount();e++)a.setScalar(e,e);n.setIndices(a)}function be(e,t,n){const r=Math.max(n.tolerance,Number.EPSILON),o=Math.log10(1/r),s=Math.pow(10,o),i={},a=t.getIndices(),c=a?a.getCount():t.listAttributes()[0].getCount(),u=new Map;t.listAttributes().forEach(e=>u.set(e,[])),t.listTargets().forEach(e=>{e.listAttributes().forEach(e=>u.set(e,[]))});const l=[];let f=0;for(let e=0;e<c;e++){const n=a?a.getScalar(e):e,r=[],o=[];for(const e of t.listAttributes())for(let t=0;t<e.getElementSize();t++)r.push(~~(e.getElement(n,o)[t]*s));const c=r.join("|");if(c in i)l.push(i[c]);else{for(const e of t.listAttributes())u.get(e).push(e.getElement(n,[]));for(const e of t.listTargets())for(const t of e.listAttributes())u.get(t).push(t.getElement(n,[]));i[c]=f,l.push(f),f++}}const g=t.listAttributes()[0].getCount(),p=u.get(t.getAttribute("POSITION")).length;e.getLogger().debug(`weld: ${g} → ${p} vertices.`);for(const e of t.listAttributes())Re(t,e,u.get(e)),1===e.listParents().length&&e.dispose();for(const e of t.listTargets())for(const t of e.listAttributes())Re(e,t,u.get(t)),1===t.listParents().length&&t.dispose();if(a){const e=Pe(a.getArray(),l.length);e.set(l),t.setIndices(a.clone().setArray(e)),1===a.listParents().length&&a.dispose()}else{const n=g<=65534?new Uint16Array(l):new Uint32Array(l);t.setIndices(e.createAccessor().setArray(n))}}function Pe(e,t){return new(0,e.constructor)(t)}function Re(e,t,n){const r=n.length*t.getElementSize(),o=Pe(t.getArray(),r),s=t.clone().setArray(o);for(let e=0;e<n.length;e++)s.setElement(e,n[e]);e.swap(t,s)}Object.defineProperty(exports,"bounds",{enumerable:!0,get:function(){return e.bounds}}),exports.QUANTIZE_DEFAULTS=W,exports.TEXTURE_RESIZE_DEFAULTS=Ae,exports.center=function(t=p){const n={...p,...t};return l("center",t=>{const r=t.getLogger(),o=t.getRoot(),s=o.listAnimations().length>0||o.listSkins().length>0;t.getRoot().listScenes().forEach((i,a)=>{let c;if(r.debug(`center: Scene ${a+1} / ${o.listScenes().length}.`),"string"==typeof n.pivot){const t=e.bounds(i);c=[(t.max[0]-t.min[0])/2+t.min[0],(t.max[1]-t.min[1])/2+t.min[1],(t.max[2]-t.min[2])/2+t.min[2]],"above"===n.pivot&&(c[1]=t.max[1]),"below"===n.pivot&&(c[1]=t.min[1])}else c=n.pivot;r.debug(`center: Pivot "${c.join(", ")}".`);const u=[-1*c[0],-1*c[1],-1*c[2]];if(s){r.debug("center: Model contains animation or skin. Adding a wrapper node.");const e=t.createNode("Pivot").setTranslation(u);i.listChildren().forEach(t=>e.addChild(t)),i.addChild(e)}else r.debug("center: Skipping wrapper, offsetting all root nodes."),i.listChildren().forEach(e=>{const t=e.getTranslation();e.setTranslation([t[0]+u[0],t[1]+u[1],t[2]+u[2]])})}),r.debug("center: Complete.")})},exports.colorspace=function(e){return l(m,t=>{const n=t.getLogger();if("linear"===e.inputEncoding)return void n.info(`${m}: Vertex colors already linear. Skipping conversion.`);if("sRGB"!==e.inputEncoding)return void n.error(`${m}: Unknown input encoding "${e.inputEncoding}" – should be "sRGB" or "linear". Skipping conversion.`);const r=new Set;function o(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function s(e){const t=[0,0,0];let n;for(let s=0;n=e.getAttribute(`COLOR_${s}`);s++)if(!r.has(n)){for(let e=0;e<n.getCount();e++)n.getElement(e,t),t[0]=o(t[0]),t[1]=o(t[1]),t[2]=o(t[2]),n.setElement(e,t);r.add(n)}}t.getRoot().listMeshes().forEach(e=>e.listPrimitives().forEach(s)),n.debug(`${m}: Complete.`)})},exports.dedup=h,exports.dequantize=function(e=A){const t={...A,...e};return l("dequantize",e=>{const r=e.getLogger();for(const n of e.getRoot().listMeshes())for(const e of n.listPrimitives())T(e,t);e.createExtension(n.MeshQuantization).dispose(),r.debug("dequantize: Complete.")})},exports.inspect=function(e){return{scenes:S(e),meshes:I(e),materials:b(e),textures:P(e),animations:R(e)}},exports.instance=function(t=C){return l("instance",t=>{const r=t.getLogger(),o=t.getRoot(),s=t.createExtension(n.MeshGPUInstancing);if(o.listAnimations().length)throw new Error("instance: Instancing is not currently supported for animated models.");let i=0,a=0;for(const n of o.listScenes()){const o=new Map;n.traverse(e=>{const t=e.getMesh();t&&o.set(t,(o.get(t)||new Set).add(e))});const c=[];for(const u of Array.from(o.keys())){const l=Array.from(o.get(u));if(l.length<2)continue;if(l.some(e=>e.getSkin()))continue;const f=v(t,s,u,l.length),g=f.getAttribute("TRANSLATION"),p=f.getAttribute("ROTATION"),m=f.getAttribute("SCALE"),d=t.createNode().setMesh(u).setExtension("EXT_mesh_gpu_instancing",f);n.addChild(d);let h=!1,y=!1,A=!1;for(let t=0;t<l.length;t++){let n,r,o;const s=l[t];g.setElement(t,n=s.getWorldTranslation()),p.setElement(t,r=s.getWorldRotation()),m.setElement(t,o=s.getWorldScale()),e.MathUtils.eq(n,[0,0,0])||(h=!0),e.MathUtils.eq(r,[0,0,0,1])||(y=!0),e.MathUtils.eq(o,[1,1,1])||(A=!0),s.setMesh(null),c.push(s)}h||g.dispose(),y||p.dispose(),A||m.dispose(),x(c,r),i++,a+=l.length}}i>0?r.info(`instance: Created ${i} batches, with ${a} total instances.`):(r.info("instance: No meshes with multiple parent nodes were found."),s.dispose()),r.debug("instance: Complete.")})},exports.metalRough=function(e=_){return l("metalRough",function(e){try{function t(){i.dispose();for(const e of a)e&&1===e.listParents().length&&e.dispose();r.debug("metalRough: Complete.")}const r=e.getLogger();if(!e.getRoot().listExtensionsUsed().map(e=>e.extensionName).includes("KHR_materials_pbrSpecularGlossiness"))return r.warn("metalRough: KHR_materials_pbrSpecularGlossiness not found on document."),Promise.resolve();const o=e.createExtension(n.MaterialsIOR),s=e.createExtension(n.MaterialsSpecular),i=e.createExtension(n.MaterialsPBRSpecularGlossiness),a=new Set,c=function(e,t,n){if("function"==typeof e[O]){var r,o,s,i=e[O]();if(function e(n){try{for(;!(r=i.next()).done;)if((n=t(r.value))&&n.then){if(!L(n))return void n.then(e,s||(s=z.bind(null,o=new $,2)));n=n.v}o?z(o,1,n):o=n}catch(e){z(o||(o=new $),2,e)}}(),i.return){var a=function(e){try{r.done||i.return()}catch(e){}return e};if(o&&o.then)return o.then(a,function(e){throw a(e)});a()}return o}if(!("length"in e))throw new TypeError("Object is not iterable");for(var c=[],u=0;u<e.length;u++)c.push(e[u]);return function(e,t,n){var r,o,s=-1;return function n(i){try{for(;++s<e.length;)if((i=t(s))&&i.then){if(!L(i))return void i.then(n,o||(o=z.bind(null,r=new $,2)));i=i.v}r?z(r,1,i):r=i}catch(e){z(r||(r=new $),2,e)}}(),r}(c,function(e){return t(c[e])})}(e.getRoot().listMaterials(),function(t){function n(){t.setExtension("KHR_materials_pbrSpecularGlossiness",null)}const r=t.getExtension("KHR_materials_pbrSpecularGlossiness");if(!r)return;const i=s.createSpecular().setSpecularFactor(1).setSpecularColorFactor(r.getSpecularFactor());a.add(r.getSpecularGlossinessTexture()),a.add(t.getBaseColorTexture()),a.add(t.getMetallicRoughnessTexture()),t.setBaseColorFactor(r.getDiffuseFactor()).setMetallicFactor(0).setRoughnessFactor(1).setExtension("KHR_materials_ior",o.createIOR().setIOR(1e3)).setExtension("KHR_materials_specular",i);const c=r.getDiffuseTexture();c&&(t.setBaseColorTexture(c),t.getBaseColorTextureInfo().copy(r.getDiffuseTextureInfo()));const l=r.getSpecularGlossinessTexture(),f=function(){if(l){const n=r.getSpecularGlossinessTextureInfo(),o=e.createTexture();return Promise.resolve(u(l,o,(e,t,n)=>{e.set(t,n,3,255)})).then(function(){i.setSpecularTexture(o),i.setSpecularColorTexture(o),i.getSpecularTextureInfo().copy(n),i.getSpecularColorTextureInfo().copy(n);const s=r.getGlossinessFactor(),a=e.createTexture();return Promise.resolve(u(l,a,(e,t,n)=>{const r=255-Math.round(e.get(t,n,3)*s);e.set(t,n,0,0),e.set(t,n,1,r),e.set(t,n,2,0),e.set(t,n,3,255)})).then(function(){t.setMetallicRoughnessTexture(a),t.getMetallicRoughnessTextureInfo().copy(n)})})}i.setSpecularColorFactor(r.getSpecularFactor()),t.setRoughnessFactor(1-r.getGlossinessFactor())}();return f&&f.then?f.then(n):n()});return Promise.resolve(c&&c.then?c.then(t):t())}catch(e){return Promise.reject(e)}})},exports.partition=(t=F)=>{const n={...F,...t};return l("partition",function(t){try{const r=t.getLogger();return!1!==n.meshes&&function(e,t,n){const r=new Set(e.getRoot().listBuffers().map(e=>e.getURI()));e.getRoot().listMeshes().forEach((o,s)=>{if(Array.isArray(n.meshes)&&!n.meshes.includes(o.getName()))return void t.debug(`partition: Skipping mesh #${s} with name "${o.getName()}".`);t.debug(`partition: Creating buffer for mesh "${o.getName()}".`);const i=e.createBuffer(o.getName()).setURI(k(o.getName()||"mesh",r));o.listPrimitives().forEach(e=>{const t=e.getIndices();t&&t.setBuffer(i),e.listAttributes().forEach(e=>e.setBuffer(i)),e.listTargets().forEach(e=>{e.listAttributes().forEach(e=>e.setBuffer(i))})})})}(t,r,n),!1!==n.animations&&function(e,t,n){const r=new Set(e.getRoot().listBuffers().map(e=>e.getURI()));e.getRoot().listAnimations().forEach((o,s)=>{if(Array.isArray(n.animations)&&!n.animations.includes(o.getName()))return void t.debug(`partition: Skipping animation #${s} with name "${o.getName()}".`);t.debug(`partition: Creating buffer for animation "${o.getName()}".`);const i=e.createBuffer(o.getName()).setURI(k(o.getName()||"animation",r));o.listSamplers().forEach(e=>{const t=e.getInput(),n=e.getOutput();t&&t.setBuffer(i),n&&n.setBuffer(i)})})}(t,r,n),n.meshes||n.animations||r.warn("partition: Select animations or meshes to create a partition."),Promise.resolve(t.transform(q({propertyTypes:[e.PropertyType.BUFFER]}))).then(function(){r.debug("partition: Complete.")})}catch(e){return Promise.reject(e)}})},exports.prune=q,exports.quantize=(t=W)=>{const r={...W,...t};return l("quantize",function(t){try{const s=t.getLogger(),i=t.getRoot();let a;t.createExtension(n.MeshQuantization).setRequired(!0),"scene"===r.quantizationVolume&&(a=K(function(e){const t=e[0];for(const n of e)o.min(t.min,t.min,n.min),o.max(t.max,t.max,n.max);return t}(i.listMeshes().map(ee))));for(const e of t.getRoot().listMeshes()){"mesh"===r.quantizationVolume&&(a=K(ee(e))),a&&r.pattern.test("POSITION")&&Z(t,e,a);for(const n of e.listPrimitives()){X(t,n,a,r);for(const e of n.listTargets())X(t,e,a,r)}}return Promise.resolve(t.transform(q({propertyTypes:[e.PropertyType.ACCESSOR,e.PropertyType.SKIN]}),h({propertyTypes:[e.PropertyType.ACCESSOR]}))).then(function(){s.debug("quantize: Complete.")})}catch(e){return Promise.reject(e)}})},exports.reorder=function(t=se){const n={...se,...t},r=n.encoder;return l("reorder",function(t){try{const o=t.getLogger();return Promise.resolve(r.ready).then(function(){const s=function(e){const t=new g,n=new Map,r=new g;for(const o of e.getRoot().listMeshes())for(const e of o.listPrimitives()){const o=e.getIndices();if(o){n.set(o,e.getMode());for(const n of ae(e))t.add(o,n),r.add(n,e)}}return{indicesToAttributes:t,indicesToMode:n,attributesToPrimitives:r}}(t);for(const t of s.indicesToAttributes.keys()){const o=t.clone();let i=o.getArray().slice();i instanceof Uint32Array||(i=new Uint32Array(i));const[a,c]=r.reorderMesh(i,s.indicesToMode.get(t)===e.Primitive.Mode.TRIANGLES,"size"===n.target);o.setArray(c<=65534?new Uint16Array(i):i);for(const e of s.indicesToAttributes.get(t)){const n=e.clone();ie(n,a,c);for(const r of s.attributesToPrimitives.get(e))if(r.getIndices()===t&&r.swap(t,o),r.getIndices()===o){r.swap(e,n);for(const t of r.listTargets())t.swap(e,n)}}}return Promise.resolve(t.transform(q({propertyTypes:[e.PropertyType.ACCESSOR]}))).then(function(){s.indicesToAttributes.size?o.debug("reorder: Complete."):o.warn("reorder: No qualifying primitives found; may need to weld first.")})})}catch(e){return Promise.reject(e)}})},exports.resample=(t=re)=>{const n={...re,...t};return l("resample",(t,r)=>{const o=new Set,s=t.getRoot().listAccessors().length,i=t.getLogger();let a=!1;for(const e of t.getRoot().listAnimations()){const t=new Set;for(const n of e.listChannels())n.getSampler()&&"weights"===n.getTargetPath()&&t.add(n.getSampler());for(const r of e.listSamplers())t.has(r)?a=!0:"STEP"!==r.getInterpolation()&&"LINEAR"!==r.getInterpolation()||(o.add(r.getInput()),o.add(r.getOutput()),oe(r,n))}for(const t of Array.from(o.values()))t.listParents().some(t=>!(t instanceof e.Root))||t.dispose();t.getRoot().listAccessors().length>s&&!function(e,t,n){return!!e&&e.stack.lastIndexOf("resample")<e.stack.lastIndexOf("dedup")}(r)&&i.warn('resample: Resampling required copying accessors, some of which may be duplicates. Consider using "dedup" to consolidate any duplicates.'),a&&i.warn("resample: Skipped optimizing morph target keyframes, not yet supported."),i.debug("resample: Complete.")})},exports.sequence=function(t=ce){const n={...ce,...t};return l("sequence",t=>{const r=t.getLogger(),o=t.getRoot(),s=n.fps,i=o.listNodes().filter(e=>e.getName().match(n.pattern));n.sort&&i.sort((e,t)=>e.getName()>t.getName()?1:-1);const a=t.createAnimation(n.name),c=o.listBuffers()[0];i.forEach((n,r)=>{let o,u;0===r?(o=[r/s,(r+1)/s],u=[1,1,1,0,0,0]):r===i.length-1?(o=[(r-1)/s,r/s],u=[0,0,0,1,1,1]):(o=[(r-1)/s,r/s,(r+1)/s],u=[0,0,0,1,1,1,0,0,0]);const l=t.createAccessor().setArray(new Float32Array(o)).setBuffer(c),f=t.createAccessor().setArray(new Float32Array(u)).setBuffer(c).setType(e.Accessor.Type.VEC3),g=t.createAnimationSampler().setInterpolation(e.AnimationSampler.Interpolation.STEP).setInput(l).setOutput(f),p=t.createAnimationChannel().setTargetNode(n).setTargetPath(e.AnimationChannel.TargetPath.SCALE).setSampler(g);a.addSampler(g).addChannel(p)}),r.debug("sequence: Complete.")})},exports.tangents=function(t=ue){if(!t.generateTangents)throw new Error('tangents: generateTangents callback required — install "mikktspace".');const n={...ue,...t};return l("tangents",t=>{const r=t.getLogger(),o=new Map,s=new Map;let i=0;for(const a of t.getRoot().listMeshes()){const c=a.getName(),u=a.listPrimitives();for(let a=0;a<u.length;a++){const l=u[a];if(!fe(l,r,c,a,n.overwrite))continue;const f=le(l),g=l.getAttribute("POSITION").getArray(),p=l.getAttribute("NORMAL").getArray(),m=l.getAttribute(f).getArray(),d=o.get(g)||e.uuid();o.set(g,d);const h=o.get(p)||e.uuid();o.set(p,h);const y=o.get(m)||e.uuid();o.set(m,y);const A=l.getAttribute("TANGENT");A&&2===A.listParents().length&&A.dispose();const T=`${d}|${h}|${y}`;let E=s.get(T);if(E){r.debug(`tangents: Found cache for primitive ${a} of mesh "${c}".`),l.setAttribute("TANGENT",E),i++;continue}r.debug(`tangents: Generating for primitive ${a} of mesh "${c}".`);const S=l.getAttribute("POSITION").getBuffer(),I=n.generateTangents(g instanceof Float32Array?g:new Float32Array(g),p instanceof Float32Array?p:new Float32Array(p),m instanceof Float32Array?m:new Float32Array(m));for(let e=3;e<I.length;e+=4)I[e]*=-1;E=t.createAccessor().setBuffer(S).setArray(I).setType("VEC4"),l.setAttribute("TANGENT",E),s.set(T,E),i++}}i?r.debug("tangents: Complete."):r.warn("tangents: No qualifying primitives found. See debug output.")})},exports.textureResize=function(e=Ae){const n={...Ae,...e};return l(he,function(e){try{let o;function r(e){s.debug(`${he}: Complete.`)}const s=e.getLogger(),a=function(e,t,n){if("function"==typeof e[ge]){var r,o,s,i=e[ge]();if(function e(a){try{for(;!((r=i.next()).done||n&&n());)if((a=t(r.value))&&a.then){if(!de(a))return void a.then(e,s||(s=pe.bind(null,o=new me,2)));a=a.v}o?pe(o,1,a):o=a}catch(e){pe(o||(o=new me),2,e)}}(),i.return){var a=function(e){try{r.done||i.return()}catch(e){}return e};if(o&&o.then)return o.then(a,function(e){throw a(e)});a()}return o}if(!("length"in e))throw new TypeError("Object is not iterable");for(var c=[],u=0;u<e.length;u++)c.push(e[u]);return function(e,t,n){var r,o,s=-1;return function i(a){try{for(;++s<e.length&&(!n||!n());)if((a=t(s))&&a.then){if(!de(a))return void a.then(i,o||(o=pe.bind(null,r=new me,2)));a=a.v}r?pe(r,1,a):r=a}catch(e){pe(r||(r=new me),2,e)}}(),r}(c,function(e){return t(c[e])},n)}(e.getRoot().listTextures(),function(e){const r=e.getName(),o=e.getURI();if(n.pattern&&!n.pattern.test(r)&&!n.pattern.test(o))return;if("image/png"!==e.getMimeType()&&"image/jpeg"!==e.getMimeType())return void s.warn(`Skipping unsupported texture type, "${e.getMimeType()}".`);const[a,u]=n.size,[l,f]=e.getSize();if(l<=a&&f<=u)return void s.debug(`${he}: Skipping "${o||r}", within size range.`);let g=l,p=f;g>a&&(p=Math.floor(p*(a/g)),g=a),p>u&&(g=Math.floor(g*(u/p)),p=u);const m=e.getImage();return Promise.resolve(t.getPixels(m,e.getMimeType())).then(function(a){const u=c.default(new Uint8Array(g*p*4),[g,p,4]);s.debug(`${he}: Resizing "${o||r}", ${a.shape} → ${u.shape}...`);try{n.filter===exports.TextureResizeFilter.LANCZOS3?i.lanczos3(a,u):i.lanczos2(a,u)}catch(e){if(e instanceof Error)return void s.warn(`${he}: Failed to resize "${o||r}": "${e.message}".`);throw e}const l=e.setImage;return Promise.resolve(t.savePixels(u,e.getMimeType())).then(function(t){l.call(e,t)})})},function(){return o});return Promise.resolve(a&&a.then?a.then(r):r())}catch(e){return Promise.reject(e)}})},exports.unweld=function(e=Te){return l("unweld",e=>{const t=e.getLogger(),n=new Map;for(const r of e.getRoot().listMeshes())for(const e of r.listPrimitives()){const r=e.getIndices();if(r){for(const o of e.listAttributes())e.swap(o,Ee(o,r,t,n)),1===o.listParents().length&&o.dispose();for(const o of e.listTargets())for(const e of o.listAttributes())o.swap(e,Ee(e,r,t,n)),1===e.listParents().length&&e.dispose();e.setIndices(null),1===r.listParents().length&&r.dispose()}}t.debug("unweld: Complete.")})},exports.weld=function(e=Se){const t={...Se,...e};return l("weld",e=>{const n=e.getLogger();for(const n of e.getRoot().listMeshes())for(const r of n.listPrimitives())0===t.tolerance?Ie(e,r):be(e,r,t);n.debug("weld: Complete.")})};
var e=require("@gltf-transform/core"),t=require("ndarray-pixels"),n=require("@gltf-transform/extensions"),r=require("gl-matrix/vec3"),o=require("gl-matrix/mat4"),s=require("ndarray"),i=require("ndarray-lanczos");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var c=/*#__PURE__*/a(s);const u=function(e,n,r){try{if(!e)return Promise.resolve(null);const o=e.getImage();return o?Promise.resolve(t.getPixels(o,e.getMimeType())).then(function(e){for(let t=0;t<e.shape[0];++t)for(let n=0;n<e.shape[1];++n)r(e,t,n);return Promise.resolve(t.savePixels(e,"image/png")).then(function(e){return n.setImage(e).setMimeType("image/png")})}):Promise.resolve(null)}catch(e){return Promise.reject(e)}};function l(e,t){return Object.defineProperty(t,"name",{value:e}),t}class g{constructor(){this._map=new Map}get size(){return this._map.size}has(e){return this._map.has(e)}add(e,t){let n=this._map.get(e);return n||(n=new Set,this._map.set(e,n)),n.add(t),this}get(e){return this._map.get(e)||new Set}keys(){return this._map.keys()}}const f={pivot:"center"},p="colorspace",m={propertyTypes:[e.PropertyType.ACCESSOR,e.PropertyType.MESH,e.PropertyType.TEXTURE,e.PropertyType.MATERIAL]},d=function(t=m){const n={...m,...t},r=new Set(n.propertyTypes);for(const e of n.propertyTypes)if(!m.propertyTypes.includes(e))throw new Error(`dedup: Unsupported deduplication on type "${e}".`);return l("dedup",t=>{const n=t.getLogger();r.has(e.PropertyType.ACCESSOR)&&function(t,n){const r=new Set,o=new Set,s=new Set,i=new Set,a=n.getRoot().listMeshes();a.forEach(e=>{e.listPrimitives().forEach(e=>{e.listAttributes().forEach(e=>o.add(e));const t=e.getIndices();t&&r.add(t)})});for(const e of n.getRoot().listAnimations())for(const t of e.listSamplers()){const e=t.getInput(),n=t.getOutput();e&&s.add(e),n&&i.add(n)}function c(t){const n=new Map;for(let r=0;r<t.length;r++){const o=t[r],s=e.BufferUtils.toView(o.getArray());if(!n.has(o))for(let r=0;r<t.length;r++){const i=t[r];o!==i&&(n.has(i)||o.getType()===i.getType()&&o.getComponentType()===i.getComponentType()&&o.getCount()===i.getCount()&&o.getNormalized()===i.getNormalized()&&e.BufferUtils.equals(s,e.BufferUtils.toView(i.getArray()))&&n.set(i,o))}}return n}const u=c(Array.from(r));t.debug(`dedup: Found ${u.size} duplicates among ${r.size} indices.`);const l=c(Array.from(o));t.debug(`dedup: Found ${l.size} duplicates among ${o.size} attributes.`);const g=c(Array.from(s)),f=c(Array.from(i));t.debug(`dedup: Found ${g.size+f.size} duplicates among ${s.size+i.size} animation accessors.`),a.forEach(e=>{e.listPrimitives().forEach(e=>{e.listAttributes().forEach(t=>{l.has(t)&&e.swap(t,l.get(t))});const t=e.getIndices();t&&u.has(t)&&e.swap(t,u.get(t))})}),Array.from(u.keys()).forEach(e=>e.dispose()),Array.from(l.keys()).forEach(e=>e.dispose());for(const e of n.getRoot().listAnimations())for(const t of e.listSamplers()){const e=t.getInput(),n=t.getOutput();e&&g.has(e)&&t.swap(e,g.get(e)),n&&f.has(n)&&t.swap(n,f.get(n))}Array.from(g.keys()).forEach(e=>e.dispose()),Array.from(f.keys()).forEach(e=>e.dispose())}(n,t),r.has(e.PropertyType.MESH)&&function(t,n){const r=n.getRoot(),o=new Map;r.listAccessors().forEach((e,t)=>o.set(e,t)),r.listMaterials().forEach((e,t)=>o.set(e,t));const s=r.listMeshes().length,i=new Map;for(const t of r.listMeshes()){const n=[];for(const e of t.listPrimitives())n.push(h(e,o));const r=n.join(";");if(i.has(r)){const n=i.get(r);t.listParents().forEach(r=>{r.propertyType!==e.PropertyType.ROOT&&r.swap(t,n)}),t.dispose()}else i.set(r,t)}t.debug(`dedup: Found ${s-i.size} duplicates among ${s} meshes.`)}(n,t),r.has(e.PropertyType.TEXTURE)&&function(t,n){const r=n.getRoot(),o=r.listTextures(),s=new Map;for(let t=0;t<o.length;t++){const n=o[t],r=n.getImage();if(!s.has(n))for(let t=0;t<o.length;t++){const i=o[t],a=i.getImage();if(n===i)continue;if(s.has(i))continue;if(n.getMimeType()!==i.getMimeType())continue;const c=n.getSize(),u=i.getSize();c&&u&&c[0]===u[0]&&c[1]===u[1]&&r&&a&&e.BufferUtils.equals(r,a)&&s.set(i,n)}}t.debug(`dedup: Found ${s.size} duplicates among ${r.listTextures().length} textures.`),Array.from(s.entries()).forEach(([t,n])=>{t.listParents().forEach(r=>{r instanceof e.Root||r.swap(t,n)}),t.dispose()})}(n,t),r.has(e.PropertyType.MATERIAL)&&function(t,n){const r=n.getRoot(),o=r.listMaterials(),s=new Map;for(let e=0;e<o.length;e++){const t=o[e];if(!s.has(t))for(let e=0;e<o.length;e++){const n=o[e];t!==n&&(s.has(n)||t.equals(n)&&s.set(n,t))}}t.debug(`dedup: Found ${s.size} duplicates among ${r.listMaterials().length} materials.`),Array.from(s.entries()).forEach(([t,n])=>{t.listParents().forEach(r=>{r instanceof e.Root||r.swap(t,n)}),t.dispose()})}(n,t),n.debug("dedup: Complete.")})};function h(t,n){const r=[];for(const e of t.listSemantics()){const o=t.getAttribute(e);r.push(e+":"+n.get(o))}if(t instanceof e.Primitive){const e=t.getIndices();e&&r.push("indices:"+n.get(e));const o=t.getMaterial();o&&r.push("material:"+n.get(o)),r.push("mode:"+t.getMode());for(const e of t.listTargets())r.push("target:"+h(e,n))}return r.join(",")}const y={pattern:/^((?!JOINTS_).)*$/};function A(e,t){for(const n of e.listSemantics())T(n,e.getAttribute(n),t);for(const n of e.listTargets())for(const e of n.listSemantics())T(e,n.getAttribute(e),t)}function T(e,t,n){if(!t.getArray())return;if(!n.pattern.test(e))return;if(t.getComponentSize()>=4)return;const r=t.getArray(),o=new Float32Array(r.length);for(let e=0,n=t.getCount(),s=[];e<n;e++)s=t.getElement(e,s),t.setArray(o).setElement(e,s).setArray(r);t.setArray(o).setNormalized(!1)}function E(t){return{properties:t.getRoot().listScenes().map(t=>{const n=t.listChildren()[0],r=e.bounds(t);return{name:t.getName(),rootName:n?n.getName():"",bboxMin:w(r.min),bboxMax:w(r.max)}})}}function S(t){return{properties:t.getRoot().listMeshes().map(t=>{const n=t.listParents().filter(e=>"Root"!==e.propertyType).length;let r=0,o=0;const s=new Set,i=new Set,a=new Set;t.listPrimitives().forEach(t=>{for(const e of t.listSemantics()){const n=t.getAttribute(e);s.add(e+":"+M(n.getArray())),a.add(n)}for(const e of t.listTargets())e.listAttributes().forEach(e=>a.add(e));const n=t.getIndices();n&&(i.add(M(n.getArray())),a.add(n)),o+=t.listAttributes()[0].getCount(),r+=function(t){const n=t.getIndices(),r=t.getAttribute("POSITION");switch(t.getMode()){case e.Primitive.Mode.POINTS:return r.getCount();case e.Primitive.Mode.LINES:return n?n.getCount()/2:r.getCount()/2;case e.Primitive.Mode.LINE_LOOP:return r.getCount();case e.Primitive.Mode.LINE_STRIP:return r.getCount()-1;case e.Primitive.Mode.TRIANGLES:return n?n.getCount()/3:r.getCount()/3;case e.Primitive.Mode.TRIANGLE_STRIP:case e.Primitive.Mode.TRIANGLE_FAN:return r.getCount()-2;default:throw new Error("Unexpected mode: "+t.getMode())}}(t)});let c=0;Array.from(a).forEach(e=>c+=e.getArray().byteLength);const u=t.listPrimitives().map(e=>R[e.getMode()]);return{name:t.getName(),mode:Array.from(new Set(u)),primitives:t.listPrimitives().length,glPrimitives:r,vertices:o,indices:Array.from(i).sort(),attributes:Array.from(s).sort(),instances:n,size:c}})}}function b(t){return{properties:t.getRoot().listMaterials().map(n=>{const r=n.listParents().filter(e=>"Root"!==e.propertyType).length,o=new Set(n.listExtensions()),s=t.getGraph().listEdges().filter(t=>{const r=t.getChild(),s=t.getParent();return r instanceof e.Texture&&s===n||!!(r instanceof e.Texture&&s instanceof e.ExtensionProperty&&o.has(s))}).map(e=>e.getName());return{name:n.getName(),instances:r,textures:s,alphaMode:n.getAlphaMode(),doubleSided:n.getDoubleSided()}})}}function I(t){return{properties:t.getRoot().listTextures().map(n=>{const r=n.listParents().filter(e=>"Root"!==e.propertyType).length,o=t.getGraph().listParentEdges(n).map(e=>e.getName()).filter(e=>"texture"!==e),s=e.ImageUtils.getSize(n.getImage(),n.getMimeType());return{name:n.getName(),uri:n.getURI(),slots:Array.from(new Set(o)),instances:r,mimeType:n.getMimeType(),resolution:s?s.join("x"):"",size:n.getImage().byteLength,gpuSize:e.ImageUtils.getMemSize(n.getImage(),n.getMimeType())}})}}function P(e){return{properties:e.getRoot().listAnimations().map(e=>{let t=Infinity,n=-Infinity;e.listSamplers().forEach(e=>{const r=e.getInput();r&&(t=Math.min(t,r.getMin([])[0]),n=Math.max(n,r.getMax([])[0]))});let r=0,o=0;const s=new Set;return e.listSamplers().forEach(e=>{const t=e.getInput(),n=e.getOutput();t&&(o+=t.getCount(),s.add(t),n&&s.add(n))}),Array.from(s).forEach(e=>{r+=e.getArray().byteLength}),{name:e.getName(),channels:e.listChannels().length,samplers:e.listSamplers().length,duration:Math.round(1e3*(n-t))/1e3,keyframes:o,size:r}})}}const R=["POINTS","LINES","LINE_LOOP","LINE_STRIP","TRIANGLES","TRIANGLE_STRIP","TRIANGLE_FAN"];function w(e){for(let t=0;t<e.length;t++)e[t].toFixed&&(e[t]=Number(e[t].toFixed(5)));return e}function M(e){return e.constructor.name.replace("Array","").toLowerCase()}const N={};function C(t,n){let r,o=0;for(;r=t.pop();){if(r.listChildren().length||r.getCamera()||r.getMesh()||r.getSkin()||r.listExtensions().length)continue;const n=r.getParent();n instanceof e.Node&&t.push(n),r.dispose(),o++}n.debug(`instance: Removed ${o} unused nodes.`)}function v(e,t,n,r){const o=n.listPrimitives()[0].getAttribute("POSITION").getBuffer(),s=e.createAccessor().setType("VEC3").setArray(new Float32Array(3*r)).setBuffer(o),i=e.createAccessor().setType("VEC4").setArray(new Float32Array(4*r)).setBuffer(o),a=e.createAccessor().setType("VEC3").setArray(new Float32Array(3*r)).setBuffer(o);return t.createInstancedMesh().setAttribute("TRANSLATION",s).setAttribute("ROTATION",i).setAttribute("SCALE",a)}const x=/*#__PURE__*/"undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function O(e,t,n){if(!e.s){if(n instanceof z){if(!n.s)return void(n.o=O.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(O.bind(null,e,t),O.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}const z=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){const r=new e,o=this.s;if(o){const e=1&o?t:n;if(e){try{O(r,1,e(this.v))}catch(e){O(r,2,e)}return r}return this}return this.o=function(e){try{const o=e.v;1&e.s?O(r,1,t?t(o):o):n?O(r,1,n(o)):O(r,2,o)}catch(e){O(r,2,e)}},r},e}();function L(e){return e instanceof z&&1&e.s}const $={},_={};function U(e=_){return l("unweld",e=>{const t=e.getLogger(),n=new Map;for(const r of e.getRoot().listMeshes())for(const e of r.listPrimitives()){const r=e.getIndices();if(r){for(const o of e.listAttributes())e.swap(o,q(o,r,t,n)),1===o.listParents().length&&o.dispose();for(const o of e.listTargets())for(const e of o.listAttributes())o.swap(e,q(e,r,t,n)),1===e.listParents().length&&e.dispose();e.setIndices(null),1===r.listParents().length&&r.dispose()}}t.debug("unweld: Complete.")})}function q(e,t,n,r){if(r.has(e)&&r.get(e).has(t))return n.debug(`unweld: Cache hit for reused attribute, "${e.getName()}".`),r.get(e).get(t);const o=e.clone(),s=e.getArray().constructor;o.setArray(new s(t.getCount()*e.getElementSize()));const i=[];for(let n=0;n<t.getCount();n++)o.setElement(n,e.getElement(t.getScalar(n),i));return r.has(e)||r.set(e,new Map),r.get(e).set(t,o),o}const F={overwrite:!1};function k(e,t,n){const o=[t[0]-e[0],t[1]-e[1],t[2]-e[2]],s=[n[0]-e[0],n[1]-e[1],n[2]-e[2]];return r.normalize([0,0,0],[o[1]*s[2]-o[2]*s[1],o[2]*s[0]-o[0]*s[2],o[0]*s[1]-o[1]*s[0]])}const G={propertyTypes:[e.PropertyType.NODE,e.PropertyType.SKIN,e.PropertyType.MESH,e.PropertyType.CAMERA,e.PropertyType.PRIMITIVE,e.PropertyType.PRIMITIVE_TARGET,e.PropertyType.ANIMATION,e.PropertyType.MATERIAL,e.PropertyType.TEXTURE,e.PropertyType.ACCESSOR,e.PropertyType.BUFFER]},B=function(t=G){const n={...G,...t}.propertyTypes;return l("prune",t=>{const r=t.getLogger(),o=t.getRoot(),s=t.getGraph(),i={};if(n.includes(e.PropertyType.NODE)&&o.listNodes().forEach(a),n.includes(e.PropertyType.SKIN)&&o.listSkins().forEach(a),n.includes(e.PropertyType.MESH)&&o.listMeshes().forEach(a),n.includes(e.PropertyType.CAMERA)&&o.listCameras().forEach(a),n.includes(e.PropertyType.PRIMITIVE)&&c(s,e.PropertyType.PRIMITIVE),n.includes(e.PropertyType.PRIMITIVE_TARGET)&&c(s,e.PropertyType.PRIMITIVE_TARGET),n.includes(e.PropertyType.ANIMATION))for(const e of o.listAnimations()){for(const t of e.listChannels())t.getTargetNode()||(t.dispose(),u(t));if(e.listChannels().length)e.listSamplers().forEach(a);else{const t=e.listSamplers();a(e),t.forEach(a)}}if(n.includes(e.PropertyType.MATERIAL)&&o.listMaterials().forEach(a),n.includes(e.PropertyType.TEXTURE)&&o.listTextures().forEach(a),n.includes(e.PropertyType.ACCESSOR)&&o.listAccessors().forEach(a),n.includes(e.PropertyType.BUFFER)&&o.listBuffers().forEach(a),Object.keys(i).length){const e=Object.keys(i).map(e=>`${e} (${i[e]})`).join(", ");r.info(`prune: Removed types... ${e}`)}else r.info("prune: No unused properties found.");function a(t){t.listParents().filter(t=>!(t instanceof e.Root||t instanceof e.AnimationChannel)).length||(t.dispose(),u(t))}function c(e,t){e.listEdges().map(e=>e.getParent()).filter(e=>e.propertyType===t).forEach(a)}function u(e){i[e.propertyType]=i[e.propertyType]||0,i[e.propertyType]++}r.debug("prune: Complete.")})},j={animations:!0,meshes:!0};function V(e,t){let n=`${e}.bin`,r=1;for(;t.has(n);)n=`${e}_${r++}.bin`;return n}const D=[Int8Array,Int16Array,Int32Array],{TRANSLATION:H,ROTATION:W,SCALE:X,WEIGHTS:K}=e.AnimationChannel.TargetPath,Z=[H,W,X],Q={pattern:/.*/,quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeWeight:8,quantizeGeneric:12};function J(t,n,s,i){const a=t.getLogger();for(const t of n.listSemantics()){if(!i.pattern.test(t))continue;const c=n.getAttribute(t),{bits:u,ctor:l}=re(t,c,a,i);if(!l)continue;if(u<8||u>16)throw new Error("quantize: Requires bits = 8–16.");if(c.getComponentSize()<=u/8)continue;const g=c.clone();if("POSITION"===t){const t=s.scale,i=[];n instanceof e.Primitive?o.invert(i,ie(s)):o.fromScaling(i,[1/t,1/t,1/t]);for(let e=0,t=[0,0,0],n=g.getCount();e<n;e++)g.getElement(e,t),g.setElement(e,r.transformMat4(t,t,i))}ne(g,l,u),n.swap(c,g)}if(n.getAttribute("WEIGHTS_0")&&function(e){const t=e.getAttribute("POSITION").getCount(),n=[];for(let r=0;r<t;r++){let t,o=0,s=Infinity,i=-1,a=null,c=0;for(;t=e.getAttribute("WEIGHTS_"+c++);){t.getElement(r,n);for(let e=0;e<n.length;e++)o+=n[e],n[e]>0&&n[e]<s&&(a=t,s=n[e],i=e)}a&&1!==o&&(a.getElement(r,n),n[i]+=1-o,a.setElement(r,n))}}(n),n instanceof e.Primitive&&n.getIndices()&&n.listAttributes().length&&n.listAttributes()[0].getCount()<65535){const e=n.getIndices();e.setArray(new Uint16Array(e.getArray()))}}function Y(e){const{min:t,max:n}=e,r=Math.max((n[0]-t[0])/2,(n[1]-t[1])/2,(n[2]-t[2])/2);return{offset:[t[0]+(n[0]-t[0])/2,t[1]+(n[1]-t[1])/2,t[2]+(n[2]-t[2])/2],scale:r}}function ee(t,n,r){const s=ie(r);for(const i of n.listParents())if(i instanceof e.Node){const a=i.listParents().filter(t=>t instanceof e.AnimationChannel),c=a.some(e=>Z.includes(e.getTargetPath())),u=i.listChildren().length>0;if(i.getSkin()){i.setSkin(te(i.getSkin(),r));continue}let l;u||c?(l=t.createNode("").setMesh(n),i.addChild(l).setMesh(null),a.filter(e=>e.getTargetPath()===K).forEach(e=>e.setTargetNode(l))):l=i;const g=l.getMatrix();o.multiply(g,g,s),l.setMatrix(g)}}function te(e,t){e=e.clone();const n=ie(t),r=e.getInverseBindMatrices().clone(),s=[];for(let e=0,t=r.getCount();e<t;e++)r.getElement(e,s),o.multiply(s,s,n),r.setElement(e,s);return e.setInverseBindMatrices(r)}function ne(e,t,n){const r=new t(e.getArray().length),o=D.includes(t)?1:0,s=n-o,i=8*t.BYTES_PER_ELEMENT-o,a=Math.pow(2,s)-1,c=i-s,u=2*s-i;for(let t=0,n=0,o=[];t<e.getCount();t++){e.getElement(t,o);for(let e=0;e<o.length;e++){let t=Math.round(Math.abs(o[e])*a);t=t<<c|t>>u,r[n++]=t*Math.sign(o[e])}}e.setArray(r).setNormalized(!0)}function re(e,t,n,r){const o=t.getMinNormalized([]),s=t.getMaxNormalized([]);let i,a;if("POSITION"===e)i=r.quantizePosition,a=i<=8?Int8Array:Int16Array;else if("NORMAL"===e||"TANGENT"===e)i=r.quantizeNormal,a=i<=8?Int8Array:Int16Array;else if(e.startsWith("COLOR_"))i=r.quantizeColor,a=i<=8?Uint8Array:Uint16Array;else if(e.startsWith("TEXCOORD_")){if(o.some(e=>e<0)||s.some(e=>e>1))return n.warn(`quantize: Skipping ${e}; out of [0,1] range.`),{bits:-1};i=r.quantizeTexcoord,a=i<=8?Uint8Array:Uint16Array}else{if(e.startsWith("JOINTS_"))return i=Math.max(...t.getMax([]))<=255?8:16,a=i<=8?Uint8Array:Uint16Array,t.getComponentSize()>i/8&&t.setArray(new a(t.getArray())),{bits:-1};if(e.startsWith("WEIGHTS_")){if(o.some(e=>e<0)||s.some(e=>e>1))return n.warn(`quantize: Skipping ${e}; out of [0,1] range.`),{bits:-1};i=r.quantizeWeight,a=i<=8?Uint8Array:Uint16Array}else{if(!e.startsWith("_"))throw new Error(`quantize: Unexpected semantic, "${e}".`);if(o.some(e=>e<-1)||s.some(e=>e>1))return n.warn(`quantize: Skipping ${e}; out of [-1,1] range.`),{bits:-1};i=r.quantizeGeneric,a=a=o.some(e=>e<0)?i<=8?Int8Array:Int16Array:i<=8?Uint8Array:Uint16Array}}return{bits:i,ctor:a}}function oe(e){const t=[],n=[];for(const r of e.listPrimitives()){const e=r.getAttribute("POSITION");e&&t.push(e);for(const e of r.listTargets()){const t=e.getAttribute("POSITION");t&&n.push(t)}}if(0===t.length)throw new Error('quantize: Missing "POSITION" attribute.');const o=se(t,3);if(n.length>0){const{min:e,max:t}=se(n,3);r.min(o.min,o.min,r.min(e,r.scale(e,e,2),[0,0,0])),r.max(o.max,o.max,r.max(t,r.scale(t,t,2),[0,0,0]))}return o}function se(e,t){const n=new Array(t).fill(Infinity),r=new Array(t).fill(-Infinity),o=[],s=[];for(const i of e){i.getMinNormalized(o),i.getMaxNormalized(s);for(let e=0;e<t;e++)n[e]=Math.min(n[e],o[e]),r[e]=Math.max(r[e],s[e])}return{min:n,max:r}}function ie(e){return o.fromRotationTranslationScale([],[0,0,0,1],e.offset,[e.scale,e.scale,e.scale])}const ae={tolerance:1e-4};function ce(e,t){const n=e.getInput().clone(),r=e.getOutput().clone(),o=t.tolerance,s=n.getCount()-1,i=[];let a=1;for(let t=1;t<s;++t){const s=n.getScalar(t),u=n.getScalar(t-1),l=n.getScalar(t+1),g=(s-u)/(l-u);let f=!1;if(s!==l&&(1!==t||s!==n.getScalar(0)))for(let n=0;n<r.getElementSize();n++){const s=r.getElement(t,i)[n],a=r.getElement(t-1,i)[n],u=r.getElement(t+1,i)[n];if("LINEAR"===e.getInterpolation()){if(Math.abs(s-(a*(1-(c=g))+u*c))>o){f=!0;break}}else if("STEP"===e.getInterpolation()&&(s!==a||s!==u)){f=!0;break}}f&&(t!==a&&(n.setScalar(a,n.getScalar(t)),r.setElement(a,r.getElement(t,i))),a++)}var c;s>0&&(n.setScalar(a,n.getScalar(s)),r.setElement(a,r.getElement(s,i)),a++),a!==n.getCount()?(n.setArray(n.getArray().slice(0,a)),r.setArray(r.getArray().slice(0,a*r.getElementSize())),e.setInput(n),e.setOutput(r)):(n.dispose(),r.dispose())}const ue={target:"size"};function le(e,t,n){const r=e.getElementSize(),o=e.getCount(),s=e.getArray(),i=s.slice(0,n*r);for(let e=0;e<o;e++)for(let n=0;n<r;n++)i[t[e]*r+n]=s[e*r+n];e.setArray(i)}function ge(e){const t=[];for(const n of e.listAttributes())t.push(n);for(const n of e.listTargets())for(const e of n.listAttributes())t.push(e);return Array.from(new Set(t))}const fe={name:"",fps:10,pattern:/.*/,sort:!0},pe={overwrite:!1};function me(e){const t=e.getMaterial();if(!t)return"TEXCOORD_0";const n=t.getNormalTextureInfo();if(!n)return"TEXCOORD_0";const r=`TEXCOORD_${n.getTexCoord()}`;return e.getAttribute(r)?r:"TEXCOORD_0"}function de(t,n,r,o,s){return t.getMode()===e.Primitive.Mode.TRIANGLES&&t.getAttribute("POSITION")&&t.getAttribute("NORMAL")&&t.getAttribute("TEXCOORD_0")?t.getAttribute("TANGENT")&&!s?(n.debug(`tangents: Skipping primitive ${o} of mesh "${r}": TANGENT found.`),!1):!t.getIndices()||(n.warn(`tangents: Skipping primitive ${o} of mesh "${r}": primitives must be unwelded.`),!1):(n.debug(`tangents: Skipping primitive ${o} of mesh "${r}": primitives must have attributes=[POSITION, NORMAL, TEXCOORD_0] and mode=TRIANGLES.`),!1)}const he=/*#__PURE__*/"undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function ye(e,t,n){if(!e.s){if(n instanceof Ae){if(!n.s)return void(n.o=ye.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(ye.bind(null,e,t),ye.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}const Ae=/*#__PURE__*/function(){function e(){}return e.prototype.then=function(t,n){const r=new e,o=this.s;if(o){const e=1&o?t:n;if(e){try{ye(r,1,e(this.v))}catch(e){ye(r,2,e)}return r}return this}return this.o=function(e){try{const o=e.v;1&e.s?ye(r,1,t?t(o):o):n?ye(r,1,n(o)):ye(r,2,o)}catch(e){ye(r,2,e)}},r},e}();function Te(e){return e instanceof Ae&&1&e.s}const Ee="textureResize";var Se;(Se=exports.TextureResizeFilter||(exports.TextureResizeFilter={})).LANCZOS3="lanczos3",Se.LANCZOS2="lanczos2";const be={size:[2048,2048],filter:exports.TextureResizeFilter.LANCZOS3,pattern:null},Ie={tolerance:1e-4};function Pe(t,n){if(n.getIndices())return;const r=n.listAttributes()[0],o=r.getCount(),s=r.getBuffer(),i=o<=65534?new Uint16Array(o):new Uint32Array(o),a=t.createAccessor().setBuffer(s).setType(e.Accessor.Type.SCALAR).setArray(i);for(let e=0;e<a.getCount();e++)a.setScalar(e,e);n.setIndices(a)}function Re(e,t,n){const r=Math.max(n.tolerance,Number.EPSILON),o=Math.log10(1/r),s=Math.pow(10,o),i={},a=t.getIndices(),c=a?a.getCount():t.listAttributes()[0].getCount(),u=new Map;t.listAttributes().forEach(e=>u.set(e,[])),t.listTargets().forEach(e=>{e.listAttributes().forEach(e=>u.set(e,[]))});const l=[];let g=0;for(let e=0;e<c;e++){const n=a?a.getScalar(e):e,r=[],o=[];for(const e of t.listAttributes())for(let t=0;t<e.getElementSize();t++)r.push(~~(e.getElement(n,o)[t]*s));const c=r.join("|");if(c in i)l.push(i[c]);else{for(const e of t.listAttributes())u.get(e).push(e.getElement(n,[]));for(const e of t.listTargets())for(const t of e.listAttributes())u.get(t).push(t.getElement(n,[]));i[c]=g,l.push(g),g++}}const f=t.listAttributes()[0].getCount(),p=u.get(t.getAttribute("POSITION")).length;e.getLogger().debug(`weld: ${f} → ${p} vertices.`);for(const e of t.listAttributes())Me(t,e,u.get(e)),1===e.listParents().length&&e.dispose();for(const e of t.listTargets())for(const t of e.listAttributes())Me(e,t,u.get(t)),1===t.listParents().length&&t.dispose();if(a){const e=we(a.getArray(),l.length);e.set(l),t.setIndices(a.clone().setArray(e)),1===a.listParents().length&&a.dispose()}else{const n=f<=65534?new Uint16Array(l):new Uint32Array(l);t.setIndices(e.createAccessor().setArray(n))}}function we(e,t){return new(0,e.constructor)(t)}function Me(e,t,n){const r=n.length*t.getElementSize(),o=we(t.getArray(),r),s=t.clone().setArray(o);for(let e=0;e<n.length;e++)s.setElement(e,n[e]);e.swap(t,s)}Object.defineProperty(exports,"bounds",{enumerable:!0,get:function(){return e.bounds}}),exports.QUANTIZE_DEFAULTS=Q,exports.TEXTURE_RESIZE_DEFAULTS=be,exports.center=function(t=f){const n={...f,...t};return l("center",t=>{const r=t.getLogger(),o=t.getRoot(),s=o.listAnimations().length>0||o.listSkins().length>0;t.getRoot().listScenes().forEach((i,a)=>{let c;if(r.debug(`center: Scene ${a+1} / ${o.listScenes().length}.`),"string"==typeof n.pivot){const t=e.bounds(i);c=[(t.max[0]-t.min[0])/2+t.min[0],(t.max[1]-t.min[1])/2+t.min[1],(t.max[2]-t.min[2])/2+t.min[2]],"above"===n.pivot&&(c[1]=t.max[1]),"below"===n.pivot&&(c[1]=t.min[1])}else c=n.pivot;r.debug(`center: Pivot "${c.join(", ")}".`);const u=[-1*c[0],-1*c[1],-1*c[2]];if(s){r.debug("center: Model contains animation or skin. Adding a wrapper node.");const e=t.createNode("Pivot").setTranslation(u);i.listChildren().forEach(t=>e.addChild(t)),i.addChild(e)}else r.debug("center: Skipping wrapper, offsetting all root nodes."),i.listChildren().forEach(e=>{const t=e.getTranslation();e.setTranslation([t[0]+u[0],t[1]+u[1],t[2]+u[2]])})}),r.debug("center: Complete.")})},exports.colorspace=function(e){return l(p,t=>{const n=t.getLogger();if("linear"===e.inputEncoding)return void n.info(`${p}: Vertex colors already linear. Skipping conversion.`);if("sRGB"!==e.inputEncoding)return void n.error(`${p}: Unknown input encoding "${e.inputEncoding}" – should be "sRGB" or "linear". Skipping conversion.`);const r=new Set;function o(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function s(e){const t=[0,0,0];let n;for(let s=0;n=e.getAttribute(`COLOR_${s}`);s++)if(!r.has(n)){for(let e=0;e<n.getCount();e++)n.getElement(e,t),t[0]=o(t[0]),t[1]=o(t[1]),t[2]=o(t[2]),n.setElement(e,t);r.add(n)}}t.getRoot().listMeshes().forEach(e=>e.listPrimitives().forEach(s)),n.debug(`${p}: Complete.`)})},exports.dedup=d,exports.dequantize=function(e=y){const t={...y,...e};return l("dequantize",e=>{const r=e.getLogger();for(const n of e.getRoot().listMeshes())for(const e of n.listPrimitives())A(e,t);e.createExtension(n.MeshQuantization).dispose(),r.debug("dequantize: Complete.")})},exports.inspect=function(e){return{scenes:E(e),meshes:S(e),materials:b(e),textures:I(e),animations:P(e)}},exports.instance=function(t=N){return l("instance",t=>{const r=t.getLogger(),o=t.getRoot(),s=t.createExtension(n.MeshGPUInstancing);if(o.listAnimations().length)throw new Error("instance: Instancing is not currently supported for animated models.");let i=0,a=0;for(const n of o.listScenes()){const o=new Map;n.traverse(e=>{const t=e.getMesh();t&&o.set(t,(o.get(t)||new Set).add(e))});const c=[];for(const u of Array.from(o.keys())){const l=Array.from(o.get(u));if(l.length<2)continue;if(l.some(e=>e.getSkin()))continue;const g=v(t,s,u,l.length),f=g.getAttribute("TRANSLATION"),p=g.getAttribute("ROTATION"),m=g.getAttribute("SCALE"),d=t.createNode().setMesh(u).setExtension("EXT_mesh_gpu_instancing",g);n.addChild(d);let h=!1,y=!1,A=!1;for(let t=0;t<l.length;t++){let n,r,o;const s=l[t];f.setElement(t,n=s.getWorldTranslation()),p.setElement(t,r=s.getWorldRotation()),m.setElement(t,o=s.getWorldScale()),e.MathUtils.eq(n,[0,0,0])||(h=!0),e.MathUtils.eq(r,[0,0,0,1])||(y=!0),e.MathUtils.eq(o,[1,1,1])||(A=!0),s.setMesh(null),c.push(s)}h||f.dispose(),y||p.dispose(),A||m.dispose(),C(c,r),i++,a+=l.length}}i>0?r.info(`instance: Created ${i} batches, with ${a} total instances.`):(r.info("instance: No meshes with multiple parent nodes were found."),s.dispose()),r.debug("instance: Complete.")})},exports.metalRough=function(e=$){return l("metalRough",function(e){try{function t(){i.dispose();for(const e of a)e&&1===e.listParents().length&&e.dispose();r.debug("metalRough: Complete.")}const r=e.getLogger();if(!e.getRoot().listExtensionsUsed().map(e=>e.extensionName).includes("KHR_materials_pbrSpecularGlossiness"))return r.warn("metalRough: KHR_materials_pbrSpecularGlossiness not found on document."),Promise.resolve();const o=e.createExtension(n.MaterialsIOR),s=e.createExtension(n.MaterialsSpecular),i=e.createExtension(n.MaterialsPBRSpecularGlossiness),a=new Set,c=function(e,t,n){if("function"==typeof e[x]){var r,o,s,i=e[x]();if(function e(n){try{for(;!(r=i.next()).done;)if((n=t(r.value))&&n.then){if(!L(n))return void n.then(e,s||(s=O.bind(null,o=new z,2)));n=n.v}o?O(o,1,n):o=n}catch(e){O(o||(o=new z),2,e)}}(),i.return){var a=function(e){try{r.done||i.return()}catch(e){}return e};if(o&&o.then)return o.then(a,function(e){throw a(e)});a()}return o}if(!("length"in e))throw new TypeError("Object is not iterable");for(var c=[],u=0;u<e.length;u++)c.push(e[u]);return function(e,t,n){var r,o,s=-1;return function n(i){try{for(;++s<e.length;)if((i=t(s))&&i.then){if(!L(i))return void i.then(n,o||(o=O.bind(null,r=new z,2)));i=i.v}r?O(r,1,i):r=i}catch(e){O(r||(r=new z),2,e)}}(),r}(c,function(e){return t(c[e])})}(e.getRoot().listMaterials(),function(t){function n(){t.setExtension("KHR_materials_pbrSpecularGlossiness",null)}const r=t.getExtension("KHR_materials_pbrSpecularGlossiness");if(!r)return;const i=s.createSpecular().setSpecularFactor(1).setSpecularColorFactor(r.getSpecularFactor());a.add(r.getSpecularGlossinessTexture()),a.add(t.getBaseColorTexture()),a.add(t.getMetallicRoughnessTexture()),t.setBaseColorFactor(r.getDiffuseFactor()).setMetallicFactor(0).setRoughnessFactor(1).setExtension("KHR_materials_ior",o.createIOR().setIOR(1e3)).setExtension("KHR_materials_specular",i);const c=r.getDiffuseTexture();c&&(t.setBaseColorTexture(c),t.getBaseColorTextureInfo().copy(r.getDiffuseTextureInfo()));const l=r.getSpecularGlossinessTexture(),g=function(){if(l){const n=r.getSpecularGlossinessTextureInfo(),o=e.createTexture();return Promise.resolve(u(l,o,(e,t,n)=>{e.set(t,n,3,255)})).then(function(){i.setSpecularTexture(o),i.setSpecularColorTexture(o),i.getSpecularTextureInfo().copy(n),i.getSpecularColorTextureInfo().copy(n);const s=r.getGlossinessFactor(),a=e.createTexture();return Promise.resolve(u(l,a,(e,t,n)=>{const r=255-Math.round(e.get(t,n,3)*s);e.set(t,n,0,0),e.set(t,n,1,r),e.set(t,n,2,0),e.set(t,n,3,255)})).then(function(){t.setMetallicRoughnessTexture(a),t.getMetallicRoughnessTextureInfo().copy(n)})})}i.setSpecularColorFactor(r.getSpecularFactor()),t.setRoughnessFactor(1-r.getGlossinessFactor())}();return g&&g.then?g.then(n):n()});return Promise.resolve(c&&c.then?c.then(t):t())}catch(e){return Promise.reject(e)}})},exports.normals=function(e=F){const t={...F,...e};return l("normals",function(e){try{const n=e.getLogger();let r=0;return Promise.resolve(e.transform(U())).then(function(){for(const o of e.getRoot().listMeshes())for(const s of o.listPrimitives()){const o=s.getAttribute("POSITION");let i=s.getAttribute("NORMAL");if(t.overwrite&&i)i.dispose();else if(i)return void n.debug("normals: Skipping primitive: NORMAL found.");i=e.createAccessor().setArray(new Float32Array(3*o.getCount())).setType("VEC3");const a=[0,0,0],c=[0,0,0],u=[0,0,0];for(let e=0;e<o.getCount();e+=3){o.getElement(e+0,a),o.getElement(e+1,c),o.getElement(e+2,u);const t=k(a,c,u);i.setElement(e+0,t),i.setElement(e+1,t),i.setElement(e+2,t)}s.setAttribute("NORMAL",i),r++}r?n.debug("normals: Complete."):n.warn("normals: No qualifying primitives found. See debug output.")})}catch(e){return Promise.reject(e)}})},exports.partition=(t=j)=>{const n={...j,...t};return l("partition",function(t){try{const r=t.getLogger();return!1!==n.meshes&&function(e,t,n){const r=new Set(e.getRoot().listBuffers().map(e=>e.getURI()));e.getRoot().listMeshes().forEach((o,s)=>{if(Array.isArray(n.meshes)&&!n.meshes.includes(o.getName()))return void t.debug(`partition: Skipping mesh #${s} with name "${o.getName()}".`);t.debug(`partition: Creating buffer for mesh "${o.getName()}".`);const i=e.createBuffer(o.getName()).setURI(V(o.getName()||"mesh",r));o.listPrimitives().forEach(e=>{const t=e.getIndices();t&&t.setBuffer(i),e.listAttributes().forEach(e=>e.setBuffer(i)),e.listTargets().forEach(e=>{e.listAttributes().forEach(e=>e.setBuffer(i))})})})}(t,r,n),!1!==n.animations&&function(e,t,n){const r=new Set(e.getRoot().listBuffers().map(e=>e.getURI()));e.getRoot().listAnimations().forEach((o,s)=>{if(Array.isArray(n.animations)&&!n.animations.includes(o.getName()))return void t.debug(`partition: Skipping animation #${s} with name "${o.getName()}".`);t.debug(`partition: Creating buffer for animation "${o.getName()}".`);const i=e.createBuffer(o.getName()).setURI(V(o.getName()||"animation",r));o.listSamplers().forEach(e=>{const t=e.getInput(),n=e.getOutput();t&&t.setBuffer(i),n&&n.setBuffer(i)})})}(t,r,n),n.meshes||n.animations||r.warn("partition: Select animations or meshes to create a partition."),Promise.resolve(t.transform(B({propertyTypes:[e.PropertyType.BUFFER]}))).then(function(){r.debug("partition: Complete.")})}catch(e){return Promise.reject(e)}})},exports.prune=B,exports.quantize=(t=Q)=>{const o={...Q,...t};return l("quantize",function(t){try{const s=t.getLogger(),i=t.getRoot();let a;t.createExtension(n.MeshQuantization).setRequired(!0),"scene"===o.quantizationVolume&&(a=Y(function(e){const t=e[0];for(const n of e)r.min(t.min,t.min,n.min),r.max(t.max,t.max,n.max);return t}(i.listMeshes().map(oe))));for(const e of t.getRoot().listMeshes()){"mesh"===o.quantizationVolume&&(a=Y(oe(e))),a&&o.pattern.test("POSITION")&&ee(t,e,a);for(const n of e.listPrimitives()){J(t,n,a,o);for(const e of n.listTargets())J(t,e,a,o)}}return Promise.resolve(t.transform(B({propertyTypes:[e.PropertyType.ACCESSOR,e.PropertyType.SKIN]}),d({propertyTypes:[e.PropertyType.ACCESSOR]}))).then(function(){s.debug("quantize: Complete.")})}catch(e){return Promise.reject(e)}})},exports.reorder=function(t=ue){const n={...ue,...t},r=n.encoder;return l("reorder",function(t){try{const o=t.getLogger();return Promise.resolve(r.ready).then(function(){const s=function(e){const t=new g,n=new Map,r=new g;for(const o of e.getRoot().listMeshes())for(const e of o.listPrimitives()){const o=e.getIndices();if(o){n.set(o,e.getMode());for(const n of ge(e))t.add(o,n),r.add(n,e)}}return{indicesToAttributes:t,indicesToMode:n,attributesToPrimitives:r}}(t);for(const t of s.indicesToAttributes.keys()){const o=t.clone();let i=o.getArray().slice();i instanceof Uint32Array||(i=new Uint32Array(i));const[a,c]=r.reorderMesh(i,s.indicesToMode.get(t)===e.Primitive.Mode.TRIANGLES,"size"===n.target);o.setArray(c<=65534?new Uint16Array(i):i);for(const e of s.indicesToAttributes.get(t)){const n=e.clone();le(n,a,c);for(const r of s.attributesToPrimitives.get(e))if(r.getIndices()===t&&r.swap(t,o),r.getIndices()===o){r.swap(e,n);for(const t of r.listTargets())t.swap(e,n)}}}return Promise.resolve(t.transform(B({propertyTypes:[e.PropertyType.ACCESSOR]}))).then(function(){s.indicesToAttributes.size?o.debug("reorder: Complete."):o.warn("reorder: No qualifying primitives found; may need to weld first.")})})}catch(e){return Promise.reject(e)}})},exports.resample=(t=ae)=>{const n={...ae,...t};return l("resample",(t,r)=>{const o=new Set,s=t.getRoot().listAccessors().length,i=t.getLogger();let a=!1;for(const e of t.getRoot().listAnimations()){const t=new Set;for(const n of e.listChannels())n.getSampler()&&"weights"===n.getTargetPath()&&t.add(n.getSampler());for(const r of e.listSamplers())t.has(r)?a=!0:"STEP"!==r.getInterpolation()&&"LINEAR"!==r.getInterpolation()||(o.add(r.getInput()),o.add(r.getOutput()),ce(r,n))}for(const t of Array.from(o.values()))t.listParents().some(t=>!(t instanceof e.Root))||t.dispose();t.getRoot().listAccessors().length>s&&!function(e,t,n){return!!e&&e.stack.lastIndexOf("resample")<e.stack.lastIndexOf("dedup")}(r)&&i.warn('resample: Resampling required copying accessors, some of which may be duplicates. Consider using "dedup" to consolidate any duplicates.'),a&&i.warn("resample: Skipped optimizing morph target keyframes, not yet supported."),i.debug("resample: Complete.")})},exports.sequence=function(t=fe){const n={...fe,...t};return l("sequence",t=>{const r=t.getLogger(),o=t.getRoot(),s=n.fps,i=o.listNodes().filter(e=>e.getName().match(n.pattern));n.sort&&i.sort((e,t)=>e.getName()>t.getName()?1:-1);const a=t.createAnimation(n.name),c=o.listBuffers()[0];i.forEach((n,r)=>{let o,u;0===r?(o=[r/s,(r+1)/s],u=[1,1,1,0,0,0]):r===i.length-1?(o=[(r-1)/s,r/s],u=[0,0,0,1,1,1]):(o=[(r-1)/s,r/s,(r+1)/s],u=[0,0,0,1,1,1,0,0,0]);const l=t.createAccessor().setArray(new Float32Array(o)).setBuffer(c),g=t.createAccessor().setArray(new Float32Array(u)).setBuffer(c).setType(e.Accessor.Type.VEC3),f=t.createAnimationSampler().setInterpolation(e.AnimationSampler.Interpolation.STEP).setInput(l).setOutput(g),p=t.createAnimationChannel().setTargetNode(n).setTargetPath(e.AnimationChannel.TargetPath.SCALE).setSampler(f);a.addSampler(f).addChannel(p)}),r.debug("sequence: Complete.")})},exports.tangents=function(t=pe){if(!t.generateTangents)throw new Error('tangents: generateTangents callback required — install "mikktspace".');const n={...pe,...t};return l("tangents",t=>{const r=t.getLogger(),o=new Map,s=new Map;let i=0;for(const a of t.getRoot().listMeshes()){const c=a.getName(),u=a.listPrimitives();for(let a=0;a<u.length;a++){const l=u[a];if(!de(l,r,c,a,n.overwrite))continue;const g=me(l),f=l.getAttribute("POSITION").getArray(),p=l.getAttribute("NORMAL").getArray(),m=l.getAttribute(g).getArray(),d=o.get(f)||e.uuid();o.set(f,d);const h=o.get(p)||e.uuid();o.set(p,h);const y=o.get(m)||e.uuid();o.set(m,y);const A=l.getAttribute("TANGENT");A&&2===A.listParents().length&&A.dispose();const T=`${d}|${h}|${y}`;let E=s.get(T);if(E){r.debug(`tangents: Found cache for primitive ${a} of mesh "${c}".`),l.setAttribute("TANGENT",E),i++;continue}r.debug(`tangents: Generating for primitive ${a} of mesh "${c}".`);const S=l.getAttribute("POSITION").getBuffer(),b=n.generateTangents(f instanceof Float32Array?f:new Float32Array(f),p instanceof Float32Array?p:new Float32Array(p),m instanceof Float32Array?m:new Float32Array(m));for(let e=3;e<b.length;e+=4)b[e]*=-1;E=t.createAccessor().setBuffer(S).setArray(b).setType("VEC4"),l.setAttribute("TANGENT",E),s.set(T,E),i++}}i?r.debug("tangents: Complete."):r.warn("tangents: No qualifying primitives found. See debug output.")})},exports.textureResize=function(e=be){const n={...be,...e};return l(Ee,function(e){try{let o;function r(e){s.debug(`${Ee}: Complete.`)}const s=e.getLogger(),a=function(e,t,n){if("function"==typeof e[he]){var r,o,s,i=e[he]();if(function e(a){try{for(;!((r=i.next()).done||n&&n());)if((a=t(r.value))&&a.then){if(!Te(a))return void a.then(e,s||(s=ye.bind(null,o=new Ae,2)));a=a.v}o?ye(o,1,a):o=a}catch(e){ye(o||(o=new Ae),2,e)}}(),i.return){var a=function(e){try{r.done||i.return()}catch(e){}return e};if(o&&o.then)return o.then(a,function(e){throw a(e)});a()}return o}if(!("length"in e))throw new TypeError("Object is not iterable");for(var c=[],u=0;u<e.length;u++)c.push(e[u]);return function(e,t,n){var r,o,s=-1;return function i(a){try{for(;++s<e.length&&(!n||!n());)if((a=t(s))&&a.then){if(!Te(a))return void a.then(i,o||(o=ye.bind(null,r=new Ae,2)));a=a.v}r?ye(r,1,a):r=a}catch(e){ye(r||(r=new Ae),2,e)}}(),r}(c,function(e){return t(c[e])},n)}(e.getRoot().listTextures(),function(e){const r=e.getName(),o=e.getURI();if(n.pattern&&!n.pattern.test(r)&&!n.pattern.test(o))return;if("image/png"!==e.getMimeType()&&"image/jpeg"!==e.getMimeType())return void s.warn(`Skipping unsupported texture type, "${e.getMimeType()}".`);const[a,u]=n.size,[l,g]=e.getSize();if(l<=a&&g<=u)return void s.debug(`${Ee}: Skipping "${o||r}", within size range.`);let f=l,p=g;f>a&&(p=Math.floor(p*(a/f)),f=a),p>u&&(f=Math.floor(f*(u/p)),p=u);const m=e.getImage();return Promise.resolve(t.getPixels(m,e.getMimeType())).then(function(a){const u=c.default(new Uint8Array(f*p*4),[f,p,4]);s.debug(`${Ee}: Resizing "${o||r}", ${a.shape} → ${u.shape}...`);try{n.filter===exports.TextureResizeFilter.LANCZOS3?i.lanczos3(a,u):i.lanczos2(a,u)}catch(e){if(e instanceof Error)return void s.warn(`${Ee}: Failed to resize "${o||r}": "${e.message}".`);throw e}const l=e.setImage;return Promise.resolve(t.savePixels(u,e.getMimeType())).then(function(t){l.call(e,t)})})},function(){return o});return Promise.resolve(a&&a.then?a.then(r):r())}catch(e){return Promise.reject(e)}})},exports.unweld=U,exports.weld=function(t=Ie){const n={...Ie,...t};return l("weld",t=>{const r=t.getLogger();for(const r of t.getRoot().listMeshes())for(const o of r.listPrimitives())o.getMode()!==e.Primitive.Mode.POINTS&&(0===n.tolerance?Pe(t,o):Re(t,o,n));r.debug("weld: Complete.")})};
//# sourceMappingURL=functions.js.map

@@ -1,2 +0,2 @@

import{Primitive as t,bounds as e,PropertyType as n,BufferUtils as s,Root as r,Texture as o,ExtensionProperty as i,ImageUtils as a,MathUtils as c,Node as l,AnimationChannel as g,Accessor as u,AnimationSampler as f,uuid as p}from"@gltf-transform/core";export{bounds}from"@gltf-transform/core";import{getPixels as m,savePixels as d}from"ndarray-pixels";import{MeshQuantization as h,MeshGPUInstancing as A,MaterialsIOR as y,MaterialsSpecular as E,MaterialsPBRSpecularGlossiness as T}from"@gltf-transform/extensions";import{invert as S,fromRotationTranslationScale as I,fromScaling as b,multiply as w}from"gl-matrix/mat4";import{transformMat4 as M,min as R,scale as N,max as C}from"gl-matrix/vec3";import O from"ndarray";import{lanczos3 as x,lanczos2 as P}from"ndarray-lanczos";function z(){return(z=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t}).apply(this,arguments)}function $(t,e){return Object.defineProperty(e,"name",{value:t}),e}async function L(t,e,n){if(!t)return null;const s=t.getImage();if(!s)return null;const r=await m(s,t.getMimeType());for(let t=0;t<r.shape[0];++t)for(let e=0;e<r.shape[1];++e)n(r,t,e);const o=await d(r,"image/png");return e.setImage(o).setMimeType("image/png")}function v(e){const n=e.getIndices(),s=e.getAttribute("POSITION");switch(e.getMode()){case t.Mode.POINTS:return s.getCount();case t.Mode.LINES:return n?n.getCount()/2:s.getCount()/2;case t.Mode.LINE_LOOP:return s.getCount();case t.Mode.LINE_STRIP:return s.getCount()-1;case t.Mode.TRIANGLES:return n?n.getCount()/3:s.getCount()/3;case t.Mode.TRIANGLE_STRIP:case t.Mode.TRIANGLE_FAN:return s.getCount()-2;default:throw new Error("Unexpected mode: "+e.getMode())}}class _{constructor(){this._map=new Map}get size(){return this._map.size}has(t){return this._map.has(t)}add(t,e){let n=this._map.get(t);return n||(n=new Set,this._map.set(t,n)),n.add(e),this}get(t){return this._map.get(t)||new Set}keys(){return this._map.keys()}}const k={pivot:"center"};function F(t=k){const n=z({},k,t);return $("center",t=>{const s=t.getLogger(),r=t.getRoot(),o=r.listAnimations().length>0||r.listSkins().length>0;t.getRoot().listScenes().forEach((i,a)=>{let c;if(s.debug(`center: Scene ${a+1} / ${r.listScenes().length}.`),"string"==typeof n.pivot){const t=e(i);c=[(t.max[0]-t.min[0])/2+t.min[0],(t.max[1]-t.min[1])/2+t.min[1],(t.max[2]-t.min[2])/2+t.min[2]],"above"===n.pivot&&(c[1]=t.max[1]),"below"===n.pivot&&(c[1]=t.min[1])}else c=n.pivot;s.debug(`center: Pivot "${c.join(", ")}".`);const l=[-1*c[0],-1*c[1],-1*c[2]];if(o){s.debug("center: Model contains animation or skin. Adding a wrapper node.");const e=t.createNode("Pivot").setTranslation(l);i.listChildren().forEach(t=>e.addChild(t)),i.addChild(e)}else s.debug("center: Skipping wrapper, offsetting all root nodes."),i.listChildren().forEach(t=>{const e=t.getTranslation();t.setTranslation([e[0]+l[0],e[1]+l[1],e[2]+l[2]])})}),s.debug("center: Complete.")})}const q="colorspace";function G(t){return $(q,e=>{const n=e.getLogger();if("linear"===t.inputEncoding)return void n.info(`${q}: Vertex colors already linear. Skipping conversion.`);if("sRGB"!==t.inputEncoding)return void n.error(`${q}: Unknown input encoding "${t.inputEncoding}" – should be "sRGB" or "linear". Skipping conversion.`);const s=new Set;function r(t){return t<.04045?.0773993808*t:Math.pow(.9478672986*t+.0521327014,2.4)}function o(t){const e=[0,0,0];let n;for(let o=0;n=t.getAttribute(`COLOR_${o}`);o++)if(!s.has(n)){for(let t=0;t<n.getCount();t++)n.getElement(t,e),e[0]=r(e[0]),e[1]=r(e[1]),e[2]=r(e[2]),n.setElement(t,e);s.add(n)}}e.getRoot().listMeshes().forEach(t=>t.listPrimitives().forEach(o)),n.debug(`${q}: Complete.`)})}const U={propertyTypes:[n.ACCESSOR,n.MESH,n.TEXTURE,n.MATERIAL]},B=function(t=U){const e=z({},U,t),o=new Set(e.propertyTypes);for(const t of e.propertyTypes)if(!U.propertyTypes.includes(t))throw new Error(`dedup: Unsupported deduplication on type "${t}".`);return $("dedup",t=>{const e=t.getLogger();o.has(n.ACCESSOR)&&function(t,e){const n=new Set,r=new Set,o=new Set,i=new Set,a=e.getRoot().listMeshes();a.forEach(t=>{t.listPrimitives().forEach(t=>{t.listAttributes().forEach(t=>r.add(t));const e=t.getIndices();e&&n.add(e)})});for(const t of e.getRoot().listAnimations())for(const e of t.listSamplers()){const t=e.getInput(),n=e.getOutput();t&&o.add(t),n&&i.add(n)}function c(t){const e=new Map;for(let n=0;n<t.length;n++){const r=t[n],o=s.toView(r.getArray());if(!e.has(r))for(let n=0;n<t.length;n++){const i=t[n];r!==i&&(e.has(i)||r.getType()===i.getType()&&r.getComponentType()===i.getComponentType()&&r.getCount()===i.getCount()&&r.getNormalized()===i.getNormalized()&&s.equals(o,s.toView(i.getArray()))&&e.set(i,r))}}return e}const l=c(Array.from(n));t.debug(`dedup: Found ${l.size} duplicates among ${n.size} indices.`);const g=c(Array.from(r));t.debug(`dedup: Found ${g.size} duplicates among ${r.size} attributes.`);const u=c(Array.from(o)),f=c(Array.from(i));t.debug(`dedup: Found ${u.size+f.size} duplicates among ${o.size+i.size} animation accessors.`),a.forEach(t=>{t.listPrimitives().forEach(t=>{t.listAttributes().forEach(e=>{g.has(e)&&t.swap(e,g.get(e))});const e=t.getIndices();e&&l.has(e)&&t.swap(e,l.get(e))})}),Array.from(l.keys()).forEach(t=>t.dispose()),Array.from(g.keys()).forEach(t=>t.dispose());for(const t of e.getRoot().listAnimations())for(const e of t.listSamplers()){const t=e.getInput(),n=e.getOutput();t&&u.has(t)&&e.swap(t,u.get(t)),n&&f.has(n)&&e.swap(n,f.get(n))}Array.from(u.keys()).forEach(t=>t.dispose()),Array.from(f.keys()).forEach(t=>t.dispose())}(e,t),o.has(n.MESH)&&function(t,e){const s=e.getRoot(),r=new Map;s.listAccessors().forEach((t,e)=>r.set(t,e)),s.listMaterials().forEach((t,e)=>r.set(t,e));const o=s.listMeshes().length,i=new Map;for(const t of s.listMeshes()){const e=[];for(const n of t.listPrimitives())e.push(V(n,r));const s=e.join(";");if(i.has(s)){const e=i.get(s);t.listParents().forEach(s=>{s.propertyType!==n.ROOT&&s.swap(t,e)}),t.dispose()}else i.set(s,t)}t.debug(`dedup: Found ${o-i.size} duplicates among ${o} meshes.`)}(e,t),o.has(n.TEXTURE)&&function(t,e){const n=e.getRoot(),o=n.listTextures(),i=new Map;for(let t=0;t<o.length;t++){const e=o[t],n=e.getImage();if(!i.has(e))for(let t=0;t<o.length;t++){const r=o[t],a=r.getImage();if(e===r)continue;if(i.has(r))continue;if(e.getMimeType()!==r.getMimeType())continue;const c=e.getSize(),l=r.getSize();c&&l&&c[0]===l[0]&&c[1]===l[1]&&n&&a&&s.equals(n,a)&&i.set(r,e)}}t.debug(`dedup: Found ${i.size} duplicates among ${n.listTextures().length} textures.`),Array.from(i.entries()).forEach(([t,e])=>{t.listParents().forEach(n=>{n instanceof r||n.swap(t,e)}),t.dispose()})}(e,t),o.has(n.MATERIAL)&&function(t,e){const n=e.getRoot(),s=n.listMaterials(),o=new Map;for(let t=0;t<s.length;t++){const e=s[t];if(!o.has(e))for(let t=0;t<s.length;t++){const n=s[t];e!==n&&(o.has(n)||e.equals(n)&&o.set(n,e))}}t.debug(`dedup: Found ${o.size} duplicates among ${n.listMaterials().length} materials.`),Array.from(o.entries()).forEach(([t,e])=>{t.listParents().forEach(n=>{n instanceof r||n.swap(t,e)}),t.dispose()})}(e,t),e.debug("dedup: Complete.")})};function V(e,n){const s=[];for(const t of e.listSemantics()){const r=e.getAttribute(t);s.push(t+":"+n.get(r))}if(e instanceof t){const t=e.getIndices();t&&s.push("indices:"+n.get(t));const r=e.getMaterial();r&&s.push("material:"+n.get(r)),s.push("mode:"+e.getMode());for(const t of e.listTargets())s.push("target:"+V(t,n))}return s.join(",")}const H={pattern:/^((?!JOINTS_).)*$/};function W(t=H){const e=z({},H,t);return $("dequantize",t=>{const n=t.getLogger();for(const n of t.getRoot().listMeshes())for(const t of n.listPrimitives())D(t,e);t.createExtension(h).dispose(),n.debug("dequantize: Complete.")})}function D(t,e){for(const n of t.listSemantics())j(n,t.getAttribute(n),e);for(const n of t.listTargets())for(const t of n.listSemantics())j(t,n.getAttribute(t),e)}function j(t,e,n){if(!e.getArray())return;if(!n.pattern.test(t))return;if(e.getComponentSize()>=4)return;const s=e.getArray(),r=new Float32Array(s.length);for(let t=0,n=e.getCount(),o=[];t<n;t++)o=e.getElement(t,o),e.setArray(r).setElement(t,o).setArray(s);e.setArray(r).setNormalized(!1)}function X(t){return{scenes:K(t),meshes:Z(t),materials:J(t),textures:Y(t),animations:Q(t)}}function K(t){return{properties:t.getRoot().listScenes().map(t=>{const n=t.listChildren()[0],s=e(t);return{name:t.getName(),rootName:n?n.getName():"",bboxMin:et(s.min),bboxMax:et(s.max)}})}}function Z(t){return{properties:t.getRoot().listMeshes().map(t=>{const e=t.listParents().filter(t=>"Root"!==t.propertyType).length;let n=0,s=0;const r=new Set,o=new Set,i=new Set;t.listPrimitives().forEach(t=>{for(const e of t.listSemantics()){const n=t.getAttribute(e);r.add(e+":"+nt(n.getArray())),i.add(n)}for(const e of t.listTargets())e.listAttributes().forEach(t=>i.add(t));const e=t.getIndices();e&&(o.add(nt(e.getArray())),i.add(e)),s+=t.listAttributes()[0].getCount(),n+=v(t)});let a=0;Array.from(i).forEach(t=>a+=t.getArray().byteLength);const c=t.listPrimitives().map(t=>tt[t.getMode()]);return{name:t.getName(),mode:Array.from(new Set(c)),primitives:t.listPrimitives().length,glPrimitives:n,vertices:s,indices:Array.from(o).sort(),attributes:Array.from(r).sort(),instances:e,size:a}})}}function J(t){return{properties:t.getRoot().listMaterials().map(e=>{const n=e.listParents().filter(t=>"Root"!==t.propertyType).length,s=new Set(e.listExtensions()),r=t.getGraph().listEdges().filter(t=>{const n=t.getChild(),r=t.getParent();return n instanceof o&&r===e||!!(n instanceof o&&r instanceof i&&s.has(r))}).map(t=>t.getName());return{name:e.getName(),instances:n,textures:r,alphaMode:e.getAlphaMode(),doubleSided:e.getDoubleSided()}})}}function Y(t){return{properties:t.getRoot().listTextures().map(e=>{const n=e.listParents().filter(t=>"Root"!==t.propertyType).length,s=t.getGraph().listParentEdges(e).map(t=>t.getName()).filter(t=>"texture"!==t),r=a.getSize(e.getImage(),e.getMimeType());return{name:e.getName(),uri:e.getURI(),slots:Array.from(new Set(s)),instances:n,mimeType:e.getMimeType(),resolution:r?r.join("x"):"",size:e.getImage().byteLength,gpuSize:a.getMemSize(e.getImage(),e.getMimeType())}})}}function Q(t){return{properties:t.getRoot().listAnimations().map(t=>{let e=Infinity,n=-Infinity;t.listSamplers().forEach(t=>{const s=t.getInput();s&&(e=Math.min(e,s.getMin([])[0]),n=Math.max(n,s.getMax([])[0]))});let s=0,r=0;const o=new Set;return t.listSamplers().forEach(t=>{const e=t.getInput(),n=t.getOutput();e&&(r+=e.getCount(),o.add(e),n&&o.add(n))}),Array.from(o).forEach(t=>{s+=t.getArray().byteLength}),{name:t.getName(),channels:t.listChannels().length,samplers:t.listSamplers().length,duration:Math.round(1e3*(n-e))/1e3,keyframes:r,size:s}})}}const tt=["POINTS","LINES","LINE_LOOP","LINE_STRIP","TRIANGLES","TRIANGLE_STRIP","TRIANGLE_FAN"];function et(t){for(let e=0;e<t.length;e++)t[e].toFixed&&(t[e]=Number(t[e].toFixed(5)));return t}function nt(t){return t.constructor.name.replace("Array","").toLowerCase()}const st={};function rt(t=st){return z({},st,t),$("instance",t=>{const e=t.getLogger(),n=t.getRoot(),s=t.createExtension(A);if(n.listAnimations().length)throw new Error("instance: Instancing is not currently supported for animated models.");let r=0,o=0;for(const i of n.listScenes()){const n=new Map;i.traverse(t=>{const e=t.getMesh();e&&n.set(e,(n.get(e)||new Set).add(t))});const a=[];for(const l of Array.from(n.keys())){const g=Array.from(n.get(l));if(g.length<2)continue;if(g.some(t=>t.getSkin()))continue;const u=it(t,s,l,g.length),f=u.getAttribute("TRANSLATION"),p=u.getAttribute("ROTATION"),m=u.getAttribute("SCALE"),d=t.createNode().setMesh(l).setExtension("EXT_mesh_gpu_instancing",u);i.addChild(d);let h=!1,A=!1,y=!1;for(let t=0;t<g.length;t++){let e,n,s;const r=g[t];f.setElement(t,e=r.getWorldTranslation()),p.setElement(t,n=r.getWorldRotation()),m.setElement(t,s=r.getWorldScale()),c.eq(e,[0,0,0])||(h=!0),c.eq(n,[0,0,0,1])||(A=!0),c.eq(s,[1,1,1])||(y=!0),r.setMesh(null),a.push(r)}h||f.dispose(),A||p.dispose(),y||m.dispose(),ot(a,e),r++,o+=g.length}}r>0?e.info(`instance: Created ${r} batches, with ${o} total instances.`):(e.info("instance: No meshes with multiple parent nodes were found."),s.dispose()),e.debug("instance: Complete.")})}function ot(t,e){let n,s=0;for(;n=t.pop();){if(n.listChildren().length||n.getCamera()||n.getMesh()||n.getSkin()||n.listExtensions().length)continue;const e=n.getParent();e instanceof l&&t.push(e),n.dispose(),s++}e.debug(`instance: Removed ${s} unused nodes.`)}function it(t,e,n,s){const r=n.listPrimitives()[0].getAttribute("POSITION").getBuffer(),o=t.createAccessor().setType("VEC3").setArray(new Float32Array(3*s)).setBuffer(r),i=t.createAccessor().setType("VEC4").setArray(new Float32Array(4*s)).setBuffer(r),a=t.createAccessor().setType("VEC3").setArray(new Float32Array(3*s)).setBuffer(r);return e.createInstancedMesh().setAttribute("TRANSLATION",o).setAttribute("ROTATION",i).setAttribute("SCALE",a)}const at={};function ct(t=at){return z({},at,t),$("metalRough",async t=>{const e=t.getLogger();if(!t.getRoot().listExtensionsUsed().map(t=>t.extensionName).includes("KHR_materials_pbrSpecularGlossiness"))return void e.warn("metalRough: KHR_materials_pbrSpecularGlossiness not found on document.");const n=t.createExtension(y),s=t.createExtension(E),r=t.createExtension(T),o=new Set;for(const e of t.getRoot().listMaterials()){const r=e.getExtension("KHR_materials_pbrSpecularGlossiness");if(!r)continue;const i=s.createSpecular().setSpecularFactor(1).setSpecularColorFactor(r.getSpecularFactor());o.add(r.getSpecularGlossinessTexture()),o.add(e.getBaseColorTexture()),o.add(e.getMetallicRoughnessTexture()),e.setBaseColorFactor(r.getDiffuseFactor()).setMetallicFactor(0).setRoughnessFactor(1).setExtension("KHR_materials_ior",n.createIOR().setIOR(1e3)).setExtension("KHR_materials_specular",i);const a=r.getDiffuseTexture();a&&(e.setBaseColorTexture(a),e.getBaseColorTextureInfo().copy(r.getDiffuseTextureInfo()));const c=r.getSpecularGlossinessTexture();if(c){const n=r.getSpecularGlossinessTextureInfo(),s=t.createTexture();await L(c,s,(t,e,n)=>{t.set(e,n,3,255)}),i.setSpecularTexture(s),i.setSpecularColorTexture(s),i.getSpecularTextureInfo().copy(n),i.getSpecularColorTextureInfo().copy(n);const o=r.getGlossinessFactor(),a=t.createTexture();await L(c,a,(t,e,n)=>{const s=255-Math.round(t.get(e,n,3)*o);t.set(e,n,0,0),t.set(e,n,1,s),t.set(e,n,2,0),t.set(e,n,3,255)}),e.setMetallicRoughnessTexture(a),e.getMetallicRoughnessTextureInfo().copy(n)}else i.setSpecularColorFactor(r.getSpecularFactor()),e.setRoughnessFactor(1-r.getGlossinessFactor());e.setExtension("KHR_materials_pbrSpecularGlossiness",null)}r.dispose();for(const t of o)t&&1===t.listParents().length&&t.dispose();e.debug("metalRough: Complete.")})}const lt={propertyTypes:[n.NODE,n.SKIN,n.MESH,n.CAMERA,n.PRIMITIVE,n.PRIMITIVE_TARGET,n.ANIMATION,n.MATERIAL,n.TEXTURE,n.ACCESSOR,n.BUFFER]},gt=function(t=lt){const e=z({},lt,t).propertyTypes;return $("prune",t=>{const s=t.getLogger(),o=t.getRoot(),i=t.getGraph(),a={};if(e.includes(n.NODE)&&o.listNodes().forEach(c),e.includes(n.SKIN)&&o.listSkins().forEach(c),e.includes(n.MESH)&&o.listMeshes().forEach(c),e.includes(n.CAMERA)&&o.listCameras().forEach(c),e.includes(n.PRIMITIVE)&&l(i,n.PRIMITIVE),e.includes(n.PRIMITIVE_TARGET)&&l(i,n.PRIMITIVE_TARGET),e.includes(n.ANIMATION))for(const t of o.listAnimations()){for(const e of t.listChannels())e.getTargetNode()||(e.dispose(),u(e));if(t.listChannels().length)t.listSamplers().forEach(c);else{const e=t.listSamplers();c(t),e.forEach(c)}}if(e.includes(n.MATERIAL)&&o.listMaterials().forEach(c),e.includes(n.TEXTURE)&&o.listTextures().forEach(c),e.includes(n.ACCESSOR)&&o.listAccessors().forEach(c),e.includes(n.BUFFER)&&o.listBuffers().forEach(c),Object.keys(a).length){const t=Object.keys(a).map(t=>`${t} (${a[t]})`).join(", ");s.info(`prune: Removed types... ${t}`)}else s.info("prune: No unused properties found.");function c(t){t.listParents().filter(t=>!(t instanceof r||t instanceof g)).length||(t.dispose(),u(t))}function l(t,e){t.listEdges().map(t=>t.getParent()).filter(t=>t.propertyType===e).forEach(c)}function u(t){a[t.propertyType]=a[t.propertyType]||0,a[t.propertyType]++}s.debug("prune: Complete.")})},ut={animations:!0,meshes:!0},ft=(t=ut)=>{const e=z({},ut,t);return $("partition",async t=>{const s=t.getLogger();!1!==e.meshes&&function(t,e,n){const s=new Set(t.getRoot().listBuffers().map(t=>t.getURI()));t.getRoot().listMeshes().forEach((r,o)=>{if(Array.isArray(n.meshes)&&!n.meshes.includes(r.getName()))return void e.debug(`partition: Skipping mesh #${o} with name "${r.getName()}".`);e.debug(`partition: Creating buffer for mesh "${r.getName()}".`);const i=t.createBuffer(r.getName()).setURI(pt(r.getName()||"mesh",s));r.listPrimitives().forEach(t=>{const e=t.getIndices();e&&e.setBuffer(i),t.listAttributes().forEach(t=>t.setBuffer(i)),t.listTargets().forEach(t=>{t.listAttributes().forEach(t=>t.setBuffer(i))})})})}(t,s,e),!1!==e.animations&&function(t,e,n){const s=new Set(t.getRoot().listBuffers().map(t=>t.getURI()));t.getRoot().listAnimations().forEach((r,o)=>{if(Array.isArray(n.animations)&&!n.animations.includes(r.getName()))return void e.debug(`partition: Skipping animation #${o} with name "${r.getName()}".`);e.debug(`partition: Creating buffer for animation "${r.getName()}".`);const i=t.createBuffer(r.getName()).setURI(pt(r.getName()||"animation",s));r.listSamplers().forEach(t=>{const e=t.getInput(),n=t.getOutput();e&&e.setBuffer(i),n&&n.setBuffer(i)})})}(t,s,e),e.meshes||e.animations||s.warn("partition: Select animations or meshes to create a partition."),await t.transform(gt({propertyTypes:[n.BUFFER]})),s.debug("partition: Complete.")})};function pt(t,e){let n=`${t}.bin`,s=1;for(;e.has(n);)n=`${t}_${s++}.bin`;return n}const mt=[Int8Array,Int16Array,Int32Array],{TRANSLATION:dt,ROTATION:ht,SCALE:At,WEIGHTS:yt}=g.TargetPath,Et=[dt,ht,At],Tt={pattern:/.*/,quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeWeight:8,quantizeGeneric:12},St=(t=Tt)=>{const e=z({},Tt,t);return $("quantize",async t=>{const s=t.getLogger(),r=t.getRoot();let o;t.createExtension(h).setRequired(!0),"scene"===e.quantizationVolume&&(o=bt(function(t){const e=t[0];for(const n of t)R(e.min,e.min,n.min),C(e.max,e.max,n.max);return e}(r.listMeshes().map(Ct))));for(const n of t.getRoot().listMeshes()){"mesh"===e.quantizationVolume&&(o=bt(Ct(n))),o&&e.pattern.test("POSITION")&&wt(t,n,o);for(const s of n.listPrimitives()){It(t,s,o,e);for(const n of s.listTargets())It(t,n,o,e)}}await t.transform(gt({propertyTypes:[n.ACCESSOR,n.SKIN]}),B({propertyTypes:[n.ACCESSOR]})),s.debug("quantize: Complete.")})};function It(e,n,s,r){const o=e.getLogger();for(const e of n.listSemantics()){if(!r.pattern.test(e))continue;const i=n.getAttribute(e),{bits:a,ctor:c}=Nt(e,i,o,r);if(!c)continue;if(a<8||a>16)throw new Error("quantize: Requires bits = 8–16.");if(i.getComponentSize()<=a/8)continue;const l=i.clone();if("POSITION"===e){const e=s.scale,r=[];n instanceof t?S(r,xt(s)):b(r,[1/e,1/e,1/e]);for(let t=0,e=[0,0,0],n=l.getCount();t<n;t++)l.getElement(t,e),l.setElement(t,M(e,e,r))}Rt(l,c,a),n.swap(i,l)}if(n.getAttribute("WEIGHTS_0")&&function(t){const e=t.getAttribute("POSITION").getCount(),n=[];for(let s=0;s<e;s++){let e,r=0,o=Infinity,i=-1,a=null,c=0;for(;e=t.getAttribute("WEIGHTS_"+c++);){e.getElement(s,n);for(let t=0;t<n.length;t++)r+=n[t],n[t]>0&&n[t]<o&&(a=e,o=n[t],i=t)}a&&1!==r&&(a.getElement(s,n),n[i]+=1-r,a.setElement(s,n))}}(n),n instanceof t&&n.getIndices()&&n.listAttributes().length&&n.listAttributes()[0].getCount()<65535){const t=n.getIndices();t.setArray(new Uint16Array(t.getArray()))}}function bt(t){const{min:e,max:n}=t,s=Math.max((n[0]-e[0])/2,(n[1]-e[1])/2,(n[2]-e[2])/2);return{offset:[e[0]+(n[0]-e[0])/2,e[1]+(n[1]-e[1])/2,e[2]+(n[2]-e[2])/2],scale:s}}function wt(t,e,n){const s=xt(n);for(const r of e.listParents())if(r instanceof l){const o=r.listParents().filter(t=>t instanceof g),i=o.some(t=>Et.includes(t.getTargetPath())),a=r.listChildren().length>0;if(r.getSkin()){r.setSkin(Mt(r.getSkin(),n));continue}let c;a||i?(c=t.createNode("").setMesh(e),r.addChild(c).setMesh(null),o.filter(t=>t.getTargetPath()===yt).forEach(t=>t.setTargetNode(c))):c=r;const l=c.getMatrix();w(l,l,s),c.setMatrix(l)}}function Mt(t,e){t=t.clone();const n=xt(e),s=t.getInverseBindMatrices().clone(),r=[];for(let t=0,e=s.getCount();t<e;t++)s.getElement(t,r),w(r,r,n),s.setElement(t,r);return t.setInverseBindMatrices(s)}function Rt(t,e,n){const s=new e(t.getArray().length),r=mt.includes(e)?1:0,o=n-r,i=8*e.BYTES_PER_ELEMENT-r,a=Math.pow(2,o)-1,c=i-o,l=2*o-i;for(let e=0,n=0,r=[];e<t.getCount();e++){t.getElement(e,r);for(let t=0;t<r.length;t++){let e=Math.round(Math.abs(r[t])*a);e=e<<c|e>>l,s[n++]=e*Math.sign(r[t])}}t.setArray(s).setNormalized(!0)}function Nt(t,e,n,s){const r=e.getMinNormalized([]),o=e.getMaxNormalized([]);let i,a;if("POSITION"===t)i=s.quantizePosition,a=i<=8?Int8Array:Int16Array;else if("NORMAL"===t||"TANGENT"===t)i=s.quantizeNormal,a=i<=8?Int8Array:Int16Array;else if(t.startsWith("COLOR_"))i=s.quantizeColor,a=i<=8?Uint8Array:Uint16Array;else if(t.startsWith("TEXCOORD_")){if(r.some(t=>t<0)||o.some(t=>t>1))return n.warn(`quantize: Skipping ${t}; out of [0,1] range.`),{bits:-1};i=s.quantizeTexcoord,a=i<=8?Uint8Array:Uint16Array}else{if(t.startsWith("JOINTS_"))return i=Math.max(...e.getMax([]))<=255?8:16,a=i<=8?Uint8Array:Uint16Array,e.getComponentSize()>i/8&&e.setArray(new a(e.getArray())),{bits:-1};if(t.startsWith("WEIGHTS_")){if(r.some(t=>t<0)||o.some(t=>t>1))return n.warn(`quantize: Skipping ${t}; out of [0,1] range.`),{bits:-1};i=s.quantizeWeight,a=i<=8?Uint8Array:Uint16Array}else{if(!t.startsWith("_"))throw new Error(`quantize: Unexpected semantic, "${t}".`);if(r.some(t=>t<-1)||o.some(t=>t>1))return n.warn(`quantize: Skipping ${t}; out of [-1,1] range.`),{bits:-1};i=s.quantizeGeneric,a=a=r.some(t=>t<0)?i<=8?Int8Array:Int16Array:i<=8?Uint8Array:Uint16Array}}return{bits:i,ctor:a}}function Ct(t){const e=[],n=[];for(const s of t.listPrimitives()){const t=s.getAttribute("POSITION");t&&e.push(t);for(const t of s.listTargets()){const e=t.getAttribute("POSITION");e&&n.push(e)}}if(0===e.length)throw new Error('quantize: Missing "POSITION" attribute.');const s=Ot(e,3);if(n.length>0){const{min:t,max:e}=Ot(n,3);R(s.min,s.min,R(t,N(t,t,2),[0,0,0])),C(s.max,s.max,C(e,N(e,e,2),[0,0,0]))}return s}function Ot(t,e){const n=new Array(e).fill(Infinity),s=new Array(e).fill(-Infinity),r=[],o=[];for(const i of t){i.getMinNormalized(r),i.getMaxNormalized(o);for(let t=0;t<e;t++)n[t]=Math.min(n[t],r[t]),s[t]=Math.max(s[t],o[t])}return{min:n,max:s}}function xt(t){return I([],[0,0,0,1],t.offset,[t.scale,t.scale,t.scale])}const Pt={tolerance:1e-4},zt=(t=Pt)=>{const e=z({},Pt,t);return $("resample",(t,n)=>{const s=new Set,o=t.getRoot().listAccessors().length,i=t.getLogger();let a=!1;for(const n of t.getRoot().listAnimations()){const t=new Set;for(const e of n.listChannels())e.getSampler()&&"weights"===e.getTargetPath()&&t.add(e.getSampler());for(const r of n.listSamplers())t.has(r)?a=!0:"STEP"!==r.getInterpolation()&&"LINEAR"!==r.getInterpolation()||(s.add(r.getInput()),s.add(r.getOutput()),$t(r,e))}for(const t of Array.from(s.values()))t.listParents().some(t=>!(t instanceof r))||t.dispose();t.getRoot().listAccessors().length>o&&!function(t,e,n){return!!t&&t.stack.lastIndexOf("resample")<t.stack.lastIndexOf("dedup")}(n)&&i.warn('resample: Resampling required copying accessors, some of which may be duplicates. Consider using "dedup" to consolidate any duplicates.'),a&&i.warn("resample: Skipped optimizing morph target keyframes, not yet supported."),i.debug("resample: Complete.")})};function $t(t,e){const n=t.getInput().clone(),s=t.getOutput().clone(),r=e.tolerance,o=n.getCount()-1,i=[];let a=1;for(let e=1;e<o;++e){const o=n.getScalar(e),l=n.getScalar(e-1),g=n.getScalar(e+1),u=(o-l)/(g-l);let f=!1;if(o!==g&&(1!==e||o!==n.getScalar(0)))for(let n=0;n<s.getElementSize();n++){const o=s.getElement(e,i)[n],a=s.getElement(e-1,i)[n],l=s.getElement(e+1,i)[n];if("LINEAR"===t.getInterpolation()){if(Math.abs(o-(a*(1-(c=u))+l*c))>r){f=!0;break}}else if("STEP"===t.getInterpolation()&&(o!==a||o!==l)){f=!0;break}}f&&(e!==a&&(n.setScalar(a,n.getScalar(e)),s.setElement(a,s.getElement(e,i))),a++)}var c;o>0&&(n.setScalar(a,n.getScalar(o)),s.setElement(a,s.getElement(o,i)),a++),a!==n.getCount()?(n.setArray(n.getArray().slice(0,a)),s.setArray(s.getArray().slice(0,a*s.getElementSize())),t.setInput(n),t.setOutput(s)):(n.dispose(),s.dispose())}const Lt={target:"size"};function vt(e=Lt){const s=z({},Lt,e),r=s.encoder;return $("reorder",async e=>{const o=e.getLogger();await r.ready;const i=function(t){const e=new _,n=new Map,s=new _;for(const r of t.getRoot().listMeshes())for(const t of r.listPrimitives()){const r=t.getIndices();if(r){n.set(r,t.getMode());for(const n of kt(t))e.add(r,n),s.add(n,t)}}return{indicesToAttributes:e,indicesToMode:n,attributesToPrimitives:s}}(e);for(const e of i.indicesToAttributes.keys()){const n=e.clone();let o=n.getArray().slice();o instanceof Uint32Array||(o=new Uint32Array(o));const[a,c]=r.reorderMesh(o,i.indicesToMode.get(e)===t.Mode.TRIANGLES,"size"===s.target);n.setArray(c<=65534?new Uint16Array(o):o);for(const t of i.indicesToAttributes.get(e)){const s=t.clone();_t(s,a,c);for(const r of i.attributesToPrimitives.get(t))if(r.getIndices()===e&&r.swap(e,n),r.getIndices()===n){r.swap(t,s);for(const e of r.listTargets())e.swap(t,s)}}}await e.transform(gt({propertyTypes:[n.ACCESSOR]})),i.indicesToAttributes.size?o.debug("reorder: Complete."):o.warn("reorder: No qualifying primitives found; may need to weld first.")})}function _t(t,e,n){const s=t.getElementSize(),r=t.getCount(),o=t.getArray(),i=o.slice(0,n*s);for(let t=0;t<r;t++)for(let n=0;n<s;n++)i[e[t]*s+n]=o[t*s+n];t.setArray(i)}function kt(t){const e=[];for(const n of t.listAttributes())e.push(n);for(const n of t.listTargets())for(const t of n.listAttributes())e.push(t);return Array.from(new Set(e))}const Ft={name:"",fps:10,pattern:/.*/,sort:!0};function qt(t=Ft){const e=z({},Ft,t);return $("sequence",t=>{const n=t.getLogger(),s=t.getRoot(),r=e.fps,o=s.listNodes().filter(t=>t.getName().match(e.pattern));e.sort&&o.sort((t,e)=>t.getName()>e.getName()?1:-1);const i=t.createAnimation(e.name),a=s.listBuffers()[0];o.forEach((e,n)=>{let s,c;0===n?(s=[n/r,(n+1)/r],c=[1,1,1,0,0,0]):n===o.length-1?(s=[(n-1)/r,n/r],c=[0,0,0,1,1,1]):(s=[(n-1)/r,n/r,(n+1)/r],c=[0,0,0,1,1,1,0,0,0]);const l=t.createAccessor().setArray(new Float32Array(s)).setBuffer(a),p=t.createAccessor().setArray(new Float32Array(c)).setBuffer(a).setType(u.Type.VEC3),m=t.createAnimationSampler().setInterpolation(f.Interpolation.STEP).setInput(l).setOutput(p),d=t.createAnimationChannel().setTargetNode(e).setTargetPath(g.TargetPath.SCALE).setSampler(m);i.addSampler(m).addChannel(d)}),n.debug("sequence: Complete.")})}const Gt={overwrite:!1};function Ut(t=Gt){if(!t.generateTangents)throw new Error('tangents: generateTangents callback required — install "mikktspace".');const e=z({},Gt,t);return $("tangents",t=>{const n=t.getLogger(),s=new Map,r=new Map;let o=0;for(const i of t.getRoot().listMeshes()){const a=i.getName(),c=i.listPrimitives();for(let i=0;i<c.length;i++){const l=c[i];if(!Vt(l,n,a,i,e.overwrite))continue;const g=Bt(l),u=l.getAttribute("POSITION").getArray(),f=l.getAttribute("NORMAL").getArray(),m=l.getAttribute(g).getArray(),d=s.get(u)||p();s.set(u,d);const h=s.get(f)||p();s.set(f,h);const A=s.get(m)||p();s.set(m,A);const y=l.getAttribute("TANGENT");y&&2===y.listParents().length&&y.dispose();const E=`${d}|${h}|${A}`;let T=r.get(E);if(T){n.debug(`tangents: Found cache for primitive ${i} of mesh "${a}".`),l.setAttribute("TANGENT",T),o++;continue}n.debug(`tangents: Generating for primitive ${i} of mesh "${a}".`);const S=l.getAttribute("POSITION").getBuffer(),I=e.generateTangents(u instanceof Float32Array?u:new Float32Array(u),f instanceof Float32Array?f:new Float32Array(f),m instanceof Float32Array?m:new Float32Array(m));for(let t=3;t<I.length;t+=4)I[t]*=-1;T=t.createAccessor().setBuffer(S).setArray(I).setType("VEC4"),l.setAttribute("TANGENT",T),r.set(E,T),o++}}o?n.debug("tangents: Complete."):n.warn("tangents: No qualifying primitives found. See debug output.")})}function Bt(t){const e=t.getMaterial();if(!e)return"TEXCOORD_0";const n=e.getNormalTextureInfo();if(!n)return"TEXCOORD_0";const s=`TEXCOORD_${n.getTexCoord()}`;return t.getAttribute(s)?s:"TEXCOORD_0"}function Vt(e,n,s,r,o){return e.getMode()===t.Mode.TRIANGLES&&e.getAttribute("POSITION")&&e.getAttribute("NORMAL")&&e.getAttribute("TEXCOORD_0")?e.getAttribute("TANGENT")&&!o?(n.debug(`tangents: Skipping primitive ${r} of mesh "${s}": TANGENT found.`),!1):!e.getIndices()||(n.warn(`tangents: Skipping primitive ${r} of mesh "${s}": primitives must be unwelded.`),!1):(n.debug(`tangents: Skipping primitive ${r} of mesh "${s}": primitives must have attributes=[POSITION, NORMAL, TEXCOORD_0] and mode=TRIANGLES.`),!1)}const Ht="textureResize";var Wt;!function(t){t.LANCZOS3="lanczos3",t.LANCZOS2="lanczos2"}(Wt||(Wt={}));const Dt={size:[2048,2048],filter:Wt.LANCZOS3,pattern:null};function jt(t=Dt){const e=z({},Dt,t);return $(Ht,async t=>{const n=t.getLogger();for(const s of t.getRoot().listTextures()){const t=s.getName(),r=s.getURI();if(e.pattern&&!e.pattern.test(t)&&!e.pattern.test(r))continue;if("image/png"!==s.getMimeType()&&"image/jpeg"!==s.getMimeType()){n.warn(`Skipping unsupported texture type, "${s.getMimeType()}".`);continue}const[o,i]=e.size,[a,c]=s.getSize();if(a<=o&&c<=i){n.debug(`${Ht}: Skipping "${r||t}", within size range.`);continue}let l=a,g=c;l>o&&(g=Math.floor(g*(o/l)),l=o),g>i&&(l=Math.floor(l*(i/g)),g=i);const u=s.getImage(),f=await m(u,s.getMimeType()),p=O(new Uint8Array(l*g*4),[l,g,4]);n.debug(`${Ht}: Resizing "${r||t}", ${f.shape} → ${p.shape}...`);try{e.filter===Wt.LANCZOS3?x(f,p):P(f,p)}catch(e){if(e instanceof Error){n.warn(`${Ht}: Failed to resize "${r||t}": "${e.message}".`);continue}throw e}s.setImage(await d(p,s.getMimeType()))}n.debug(`${Ht}: Complete.`)})}const Xt={};function Kt(t=Xt){return z({},Xt,t),$("unweld",t=>{const e=t.getLogger(),n=new Map;for(const s of t.getRoot().listMeshes())for(const t of s.listPrimitives()){const s=t.getIndices();if(s){for(const r of t.listAttributes())t.swap(r,Zt(r,s,e,n)),1===r.listParents().length&&r.dispose();for(const r of t.listTargets())for(const t of r.listAttributes())r.swap(t,Zt(t,s,e,n)),1===t.listParents().length&&t.dispose();t.setIndices(null),1===s.listParents().length&&s.dispose()}}e.debug("unweld: Complete.")})}function Zt(t,e,n,s){if(s.has(t)&&s.get(t).has(e))return n.debug(`unweld: Cache hit for reused attribute, "${t.getName()}".`),s.get(t).get(e);const r=t.clone(),o=t.getArray().constructor;r.setArray(new o(e.getCount()*t.getElementSize()));const i=[];for(let n=0;n<e.getCount();n++)r.setElement(n,t.getElement(e.getScalar(n),i));return s.has(t)||s.set(t,new Map),s.get(t).set(e,r),r}const Jt={tolerance:1e-4};function Yt(t=Jt){const e=z({},Jt,t);return $("weld",t=>{const n=t.getLogger();for(const n of t.getRoot().listMeshes())for(const s of n.listPrimitives())0===e.tolerance?Qt(t,s):te(t,s,e);n.debug("weld: Complete.")})}function Qt(t,e){if(e.getIndices())return;const n=e.listAttributes()[0],s=n.getCount(),r=n.getBuffer(),o=s<=65534?new Uint16Array(3*v(e)):new Uint32Array(3*v(e)),i=t.createAccessor().setBuffer(r).setType(u.Type.SCALAR).setArray(o);for(let t=0;t<i.getCount();t++)i.setScalar(t,t);e.setIndices(i)}function te(t,e,n){const s=Math.max(n.tolerance,Number.EPSILON),r=Math.log10(1/s),o=Math.pow(10,r),i={},a=e.getIndices(),c=a?a.getCount():e.listAttributes()[0].getCount(),l=new Map;e.listAttributes().forEach(t=>l.set(t,[])),e.listTargets().forEach(t=>{t.listAttributes().forEach(t=>l.set(t,[]))});const g=[];let u=0;for(let t=0;t<c;t++){const n=a?a.getScalar(t):t,s=[],r=[];for(const t of e.listAttributes())for(let e=0;e<t.getElementSize();e++)s.push(~~(t.getElement(n,r)[e]*o));const c=s.join("|");if(c in i)g.push(i[c]);else{for(const t of e.listAttributes())l.get(t).push(t.getElement(n,[]));for(const t of e.listTargets())for(const e of t.listAttributes())l.get(e).push(e.getElement(n,[]));i[c]=u,g.push(u),u++}}const f=e.listAttributes()[0].getCount(),p=l.get(e.getAttribute("POSITION")).length;t.getLogger().debug(`weld: ${f} → ${p} vertices.`);for(const t of e.listAttributes())ne(e,t,l.get(t)),1===t.listParents().length&&t.dispose();for(const t of e.listTargets())for(const e of t.listAttributes())ne(t,e,l.get(e)),1===e.listParents().length&&e.dispose();if(a){const t=ee(a.getArray(),g.length);t.set(g),e.setIndices(a.clone().setArray(t)),1===a.listParents().length&&a.dispose()}else{const n=f<=65534?new Uint16Array(g):new Uint32Array(g);e.setIndices(t.createAccessor().setArray(n))}}function ee(t,e){return new(0,t.constructor)(e)}function ne(t,e,n){const s=n.length*e.getElementSize(),r=ee(e.getArray(),s),o=e.clone().setArray(r);for(let t=0;t<n.length;t++)o.setElement(t,n[t]);t.swap(e,o)}export{Tt as QUANTIZE_DEFAULTS,Dt as TEXTURE_RESIZE_DEFAULTS,Wt as TextureResizeFilter,F as center,G as colorspace,B as dedup,W as dequantize,X as inspect,rt as instance,ct as metalRough,ft as partition,gt as prune,St as quantize,vt as reorder,zt as resample,qt as sequence,Ut as tangents,jt as textureResize,Kt as unweld,Yt as weld};
import{Primitive as t,bounds as e,PropertyType as n,BufferUtils as s,Root as r,Texture as o,ExtensionProperty as i,ImageUtils as a,MathUtils as c,Node as l,AnimationChannel as g,Accessor as u,AnimationSampler as f,uuid as p}from"@gltf-transform/core";export{bounds}from"@gltf-transform/core";import{getPixels as m,savePixels as d}from"ndarray-pixels";import{MeshQuantization as h,MeshGPUInstancing as A,MaterialsIOR as y,MaterialsSpecular as E,MaterialsPBRSpecularGlossiness as T}from"@gltf-transform/extensions";import{normalize as S,transformMat4 as I,min as b,scale as w,max as M}from"gl-matrix/vec3";import{invert as R,fromRotationTranslationScale as N,fromScaling as C,multiply as O}from"gl-matrix/mat4";import P from"ndarray";import{lanczos3 as x,lanczos2 as z}from"ndarray-lanczos";function L(){return(L=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t}).apply(this,arguments)}function $(t,e){return Object.defineProperty(e,"name",{value:t}),e}async function v(t,e,n){if(!t)return null;const s=t.getImage();if(!s)return null;const r=await m(s,t.getMimeType());for(let t=0;t<r.shape[0];++t)for(let e=0;e<r.shape[1];++e)n(r,t,e);const o=await d(r,"image/png");return e.setImage(o).setMimeType("image/png")}class _{constructor(){this._map=new Map}get size(){return this._map.size}has(t){return this._map.has(t)}add(t,e){let n=this._map.get(t);return n||(n=new Set,this._map.set(t,n)),n.add(e),this}get(t){return this._map.get(t)||new Set}keys(){return this._map.keys()}}const k={pivot:"center"};function F(t=k){const n=L({},k,t);return $("center",t=>{const s=t.getLogger(),r=t.getRoot(),o=r.listAnimations().length>0||r.listSkins().length>0;t.getRoot().listScenes().forEach((i,a)=>{let c;if(s.debug(`center: Scene ${a+1} / ${r.listScenes().length}.`),"string"==typeof n.pivot){const t=e(i);c=[(t.max[0]-t.min[0])/2+t.min[0],(t.max[1]-t.min[1])/2+t.min[1],(t.max[2]-t.min[2])/2+t.min[2]],"above"===n.pivot&&(c[1]=t.max[1]),"below"===n.pivot&&(c[1]=t.min[1])}else c=n.pivot;s.debug(`center: Pivot "${c.join(", ")}".`);const l=[-1*c[0],-1*c[1],-1*c[2]];if(o){s.debug("center: Model contains animation or skin. Adding a wrapper node.");const e=t.createNode("Pivot").setTranslation(l);i.listChildren().forEach(t=>e.addChild(t)),i.addChild(e)}else s.debug("center: Skipping wrapper, offsetting all root nodes."),i.listChildren().forEach(t=>{const e=t.getTranslation();t.setTranslation([e[0]+l[0],e[1]+l[1],e[2]+l[2]])})}),s.debug("center: Complete.")})}const q="colorspace";function G(t){return $(q,e=>{const n=e.getLogger();if("linear"===t.inputEncoding)return void n.info(`${q}: Vertex colors already linear. Skipping conversion.`);if("sRGB"!==t.inputEncoding)return void n.error(`${q}: Unknown input encoding "${t.inputEncoding}" – should be "sRGB" or "linear". Skipping conversion.`);const s=new Set;function r(t){return t<.04045?.0773993808*t:Math.pow(.9478672986*t+.0521327014,2.4)}function o(t){const e=[0,0,0];let n;for(let o=0;n=t.getAttribute(`COLOR_${o}`);o++)if(!s.has(n)){for(let t=0;t<n.getCount();t++)n.getElement(t,e),e[0]=r(e[0]),e[1]=r(e[1]),e[2]=r(e[2]),n.setElement(t,e);s.add(n)}}e.getRoot().listMeshes().forEach(t=>t.listPrimitives().forEach(o)),n.debug(`${q}: Complete.`)})}const U={propertyTypes:[n.ACCESSOR,n.MESH,n.TEXTURE,n.MATERIAL]},B=function(t=U){const e=L({},U,t),o=new Set(e.propertyTypes);for(const t of e.propertyTypes)if(!U.propertyTypes.includes(t))throw new Error(`dedup: Unsupported deduplication on type "${t}".`);return $("dedup",t=>{const e=t.getLogger();o.has(n.ACCESSOR)&&function(t,e){const n=new Set,r=new Set,o=new Set,i=new Set,a=e.getRoot().listMeshes();a.forEach(t=>{t.listPrimitives().forEach(t=>{t.listAttributes().forEach(t=>r.add(t));const e=t.getIndices();e&&n.add(e)})});for(const t of e.getRoot().listAnimations())for(const e of t.listSamplers()){const t=e.getInput(),n=e.getOutput();t&&o.add(t),n&&i.add(n)}function c(t){const e=new Map;for(let n=0;n<t.length;n++){const r=t[n],o=s.toView(r.getArray());if(!e.has(r))for(let n=0;n<t.length;n++){const i=t[n];r!==i&&(e.has(i)||r.getType()===i.getType()&&r.getComponentType()===i.getComponentType()&&r.getCount()===i.getCount()&&r.getNormalized()===i.getNormalized()&&s.equals(o,s.toView(i.getArray()))&&e.set(i,r))}}return e}const l=c(Array.from(n));t.debug(`dedup: Found ${l.size} duplicates among ${n.size} indices.`);const g=c(Array.from(r));t.debug(`dedup: Found ${g.size} duplicates among ${r.size} attributes.`);const u=c(Array.from(o)),f=c(Array.from(i));t.debug(`dedup: Found ${u.size+f.size} duplicates among ${o.size+i.size} animation accessors.`),a.forEach(t=>{t.listPrimitives().forEach(t=>{t.listAttributes().forEach(e=>{g.has(e)&&t.swap(e,g.get(e))});const e=t.getIndices();e&&l.has(e)&&t.swap(e,l.get(e))})}),Array.from(l.keys()).forEach(t=>t.dispose()),Array.from(g.keys()).forEach(t=>t.dispose());for(const t of e.getRoot().listAnimations())for(const e of t.listSamplers()){const t=e.getInput(),n=e.getOutput();t&&u.has(t)&&e.swap(t,u.get(t)),n&&f.has(n)&&e.swap(n,f.get(n))}Array.from(u.keys()).forEach(t=>t.dispose()),Array.from(f.keys()).forEach(t=>t.dispose())}(e,t),o.has(n.MESH)&&function(t,e){const s=e.getRoot(),r=new Map;s.listAccessors().forEach((t,e)=>r.set(t,e)),s.listMaterials().forEach((t,e)=>r.set(t,e));const o=s.listMeshes().length,i=new Map;for(const t of s.listMeshes()){const e=[];for(const n of t.listPrimitives())e.push(V(n,r));const s=e.join(";");if(i.has(s)){const e=i.get(s);t.listParents().forEach(s=>{s.propertyType!==n.ROOT&&s.swap(t,e)}),t.dispose()}else i.set(s,t)}t.debug(`dedup: Found ${o-i.size} duplicates among ${o} meshes.`)}(e,t),o.has(n.TEXTURE)&&function(t,e){const n=e.getRoot(),o=n.listTextures(),i=new Map;for(let t=0;t<o.length;t++){const e=o[t],n=e.getImage();if(!i.has(e))for(let t=0;t<o.length;t++){const r=o[t],a=r.getImage();if(e===r)continue;if(i.has(r))continue;if(e.getMimeType()!==r.getMimeType())continue;const c=e.getSize(),l=r.getSize();c&&l&&c[0]===l[0]&&c[1]===l[1]&&n&&a&&s.equals(n,a)&&i.set(r,e)}}t.debug(`dedup: Found ${i.size} duplicates among ${n.listTextures().length} textures.`),Array.from(i.entries()).forEach(([t,e])=>{t.listParents().forEach(n=>{n instanceof r||n.swap(t,e)}),t.dispose()})}(e,t),o.has(n.MATERIAL)&&function(t,e){const n=e.getRoot(),s=n.listMaterials(),o=new Map;for(let t=0;t<s.length;t++){const e=s[t];if(!o.has(e))for(let t=0;t<s.length;t++){const n=s[t];e!==n&&(o.has(n)||e.equals(n)&&o.set(n,e))}}t.debug(`dedup: Found ${o.size} duplicates among ${n.listMaterials().length} materials.`),Array.from(o.entries()).forEach(([t,e])=>{t.listParents().forEach(n=>{n instanceof r||n.swap(t,e)}),t.dispose()})}(e,t),e.debug("dedup: Complete.")})};function V(e,n){const s=[];for(const t of e.listSemantics()){const r=e.getAttribute(t);s.push(t+":"+n.get(r))}if(e instanceof t){const t=e.getIndices();t&&s.push("indices:"+n.get(t));const r=e.getMaterial();r&&s.push("material:"+n.get(r)),s.push("mode:"+e.getMode());for(const t of e.listTargets())s.push("target:"+V(t,n))}return s.join(",")}const H={pattern:/^((?!JOINTS_).)*$/};function W(t=H){const e=L({},H,t);return $("dequantize",t=>{const n=t.getLogger();for(const n of t.getRoot().listMeshes())for(const t of n.listPrimitives())D(t,e);t.createExtension(h).dispose(),n.debug("dequantize: Complete.")})}function D(t,e){for(const n of t.listSemantics())j(n,t.getAttribute(n),e);for(const n of t.listTargets())for(const t of n.listSemantics())j(t,n.getAttribute(t),e)}function j(t,e,n){if(!e.getArray())return;if(!n.pattern.test(t))return;if(e.getComponentSize()>=4)return;const s=e.getArray(),r=new Float32Array(s.length);for(let t=0,n=e.getCount(),o=[];t<n;t++)o=e.getElement(t,o),e.setArray(r).setElement(t,o).setArray(s);e.setArray(r).setNormalized(!1)}function X(t){return{scenes:K(t),meshes:Z(t),materials:J(t),textures:Y(t),animations:Q(t)}}function K(t){return{properties:t.getRoot().listScenes().map(t=>{const n=t.listChildren()[0],s=e(t);return{name:t.getName(),rootName:n?n.getName():"",bboxMin:et(s.min),bboxMax:et(s.max)}})}}function Z(e){return{properties:e.getRoot().listMeshes().map(e=>{const n=e.listParents().filter(t=>"Root"!==t.propertyType).length;let s=0,r=0;const o=new Set,i=new Set,a=new Set;e.listPrimitives().forEach(e=>{for(const t of e.listSemantics()){const n=e.getAttribute(t);o.add(t+":"+nt(n.getArray())),a.add(n)}for(const t of e.listTargets())t.listAttributes().forEach(t=>a.add(t));const n=e.getIndices();n&&(i.add(nt(n.getArray())),a.add(n)),r+=e.listAttributes()[0].getCount(),s+=function(e){const n=e.getIndices(),s=e.getAttribute("POSITION");switch(e.getMode()){case t.Mode.POINTS:return s.getCount();case t.Mode.LINES:return n?n.getCount()/2:s.getCount()/2;case t.Mode.LINE_LOOP:return s.getCount();case t.Mode.LINE_STRIP:return s.getCount()-1;case t.Mode.TRIANGLES:return n?n.getCount()/3:s.getCount()/3;case t.Mode.TRIANGLE_STRIP:case t.Mode.TRIANGLE_FAN:return s.getCount()-2;default:throw new Error("Unexpected mode: "+e.getMode())}}(e)});let c=0;Array.from(a).forEach(t=>c+=t.getArray().byteLength);const l=e.listPrimitives().map(t=>tt[t.getMode()]);return{name:e.getName(),mode:Array.from(new Set(l)),primitives:e.listPrimitives().length,glPrimitives:s,vertices:r,indices:Array.from(i).sort(),attributes:Array.from(o).sort(),instances:n,size:c}})}}function J(t){return{properties:t.getRoot().listMaterials().map(e=>{const n=e.listParents().filter(t=>"Root"!==t.propertyType).length,s=new Set(e.listExtensions()),r=t.getGraph().listEdges().filter(t=>{const n=t.getChild(),r=t.getParent();return n instanceof o&&r===e||!!(n instanceof o&&r instanceof i&&s.has(r))}).map(t=>t.getName());return{name:e.getName(),instances:n,textures:r,alphaMode:e.getAlphaMode(),doubleSided:e.getDoubleSided()}})}}function Y(t){return{properties:t.getRoot().listTextures().map(e=>{const n=e.listParents().filter(t=>"Root"!==t.propertyType).length,s=t.getGraph().listParentEdges(e).map(t=>t.getName()).filter(t=>"texture"!==t),r=a.getSize(e.getImage(),e.getMimeType());return{name:e.getName(),uri:e.getURI(),slots:Array.from(new Set(s)),instances:n,mimeType:e.getMimeType(),resolution:r?r.join("x"):"",size:e.getImage().byteLength,gpuSize:a.getMemSize(e.getImage(),e.getMimeType())}})}}function Q(t){return{properties:t.getRoot().listAnimations().map(t=>{let e=Infinity,n=-Infinity;t.listSamplers().forEach(t=>{const s=t.getInput();s&&(e=Math.min(e,s.getMin([])[0]),n=Math.max(n,s.getMax([])[0]))});let s=0,r=0;const o=new Set;return t.listSamplers().forEach(t=>{const e=t.getInput(),n=t.getOutput();e&&(r+=e.getCount(),o.add(e),n&&o.add(n))}),Array.from(o).forEach(t=>{s+=t.getArray().byteLength}),{name:t.getName(),channels:t.listChannels().length,samplers:t.listSamplers().length,duration:Math.round(1e3*(n-e))/1e3,keyframes:r,size:s}})}}const tt=["POINTS","LINES","LINE_LOOP","LINE_STRIP","TRIANGLES","TRIANGLE_STRIP","TRIANGLE_FAN"];function et(t){for(let e=0;e<t.length;e++)t[e].toFixed&&(t[e]=Number(t[e].toFixed(5)));return t}function nt(t){return t.constructor.name.replace("Array","").toLowerCase()}const st={};function rt(t=st){return L({},st,t),$("instance",t=>{const e=t.getLogger(),n=t.getRoot(),s=t.createExtension(A);if(n.listAnimations().length)throw new Error("instance: Instancing is not currently supported for animated models.");let r=0,o=0;for(const i of n.listScenes()){const n=new Map;i.traverse(t=>{const e=t.getMesh();e&&n.set(e,(n.get(e)||new Set).add(t))});const a=[];for(const l of Array.from(n.keys())){const g=Array.from(n.get(l));if(g.length<2)continue;if(g.some(t=>t.getSkin()))continue;const u=it(t,s,l,g.length),f=u.getAttribute("TRANSLATION"),p=u.getAttribute("ROTATION"),m=u.getAttribute("SCALE"),d=t.createNode().setMesh(l).setExtension("EXT_mesh_gpu_instancing",u);i.addChild(d);let h=!1,A=!1,y=!1;for(let t=0;t<g.length;t++){let e,n,s;const r=g[t];f.setElement(t,e=r.getWorldTranslation()),p.setElement(t,n=r.getWorldRotation()),m.setElement(t,s=r.getWorldScale()),c.eq(e,[0,0,0])||(h=!0),c.eq(n,[0,0,0,1])||(A=!0),c.eq(s,[1,1,1])||(y=!0),r.setMesh(null),a.push(r)}h||f.dispose(),A||p.dispose(),y||m.dispose(),ot(a,e),r++,o+=g.length}}r>0?e.info(`instance: Created ${r} batches, with ${o} total instances.`):(e.info("instance: No meshes with multiple parent nodes were found."),s.dispose()),e.debug("instance: Complete.")})}function ot(t,e){let n,s=0;for(;n=t.pop();){if(n.listChildren().length||n.getCamera()||n.getMesh()||n.getSkin()||n.listExtensions().length)continue;const e=n.getParent();e instanceof l&&t.push(e),n.dispose(),s++}e.debug(`instance: Removed ${s} unused nodes.`)}function it(t,e,n,s){const r=n.listPrimitives()[0].getAttribute("POSITION").getBuffer(),o=t.createAccessor().setType("VEC3").setArray(new Float32Array(3*s)).setBuffer(r),i=t.createAccessor().setType("VEC4").setArray(new Float32Array(4*s)).setBuffer(r),a=t.createAccessor().setType("VEC3").setArray(new Float32Array(3*s)).setBuffer(r);return e.createInstancedMesh().setAttribute("TRANSLATION",o).setAttribute("ROTATION",i).setAttribute("SCALE",a)}const at={};function ct(t=at){return L({},at,t),$("metalRough",async t=>{const e=t.getLogger();if(!t.getRoot().listExtensionsUsed().map(t=>t.extensionName).includes("KHR_materials_pbrSpecularGlossiness"))return void e.warn("metalRough: KHR_materials_pbrSpecularGlossiness not found on document.");const n=t.createExtension(y),s=t.createExtension(E),r=t.createExtension(T),o=new Set;for(const e of t.getRoot().listMaterials()){const r=e.getExtension("KHR_materials_pbrSpecularGlossiness");if(!r)continue;const i=s.createSpecular().setSpecularFactor(1).setSpecularColorFactor(r.getSpecularFactor());o.add(r.getSpecularGlossinessTexture()),o.add(e.getBaseColorTexture()),o.add(e.getMetallicRoughnessTexture()),e.setBaseColorFactor(r.getDiffuseFactor()).setMetallicFactor(0).setRoughnessFactor(1).setExtension("KHR_materials_ior",n.createIOR().setIOR(1e3)).setExtension("KHR_materials_specular",i);const a=r.getDiffuseTexture();a&&(e.setBaseColorTexture(a),e.getBaseColorTextureInfo().copy(r.getDiffuseTextureInfo()));const c=r.getSpecularGlossinessTexture();if(c){const n=r.getSpecularGlossinessTextureInfo(),s=t.createTexture();await v(c,s,(t,e,n)=>{t.set(e,n,3,255)}),i.setSpecularTexture(s),i.setSpecularColorTexture(s),i.getSpecularTextureInfo().copy(n),i.getSpecularColorTextureInfo().copy(n);const o=r.getGlossinessFactor(),a=t.createTexture();await v(c,a,(t,e,n)=>{const s=255-Math.round(t.get(e,n,3)*o);t.set(e,n,0,0),t.set(e,n,1,s),t.set(e,n,2,0),t.set(e,n,3,255)}),e.setMetallicRoughnessTexture(a),e.getMetallicRoughnessTextureInfo().copy(n)}else i.setSpecularColorFactor(r.getSpecularFactor()),e.setRoughnessFactor(1-r.getGlossinessFactor());e.setExtension("KHR_materials_pbrSpecularGlossiness",null)}r.dispose();for(const t of o)t&&1===t.listParents().length&&t.dispose();e.debug("metalRough: Complete.")})}const lt={};function gt(t=lt){return L({},lt,t),$("unweld",t=>{const e=t.getLogger(),n=new Map;for(const s of t.getRoot().listMeshes())for(const t of s.listPrimitives()){const s=t.getIndices();if(s){for(const r of t.listAttributes())t.swap(r,ut(r,s,e,n)),1===r.listParents().length&&r.dispose();for(const r of t.listTargets())for(const t of r.listAttributes())r.swap(t,ut(t,s,e,n)),1===t.listParents().length&&t.dispose();t.setIndices(null),1===s.listParents().length&&s.dispose()}}e.debug("unweld: Complete.")})}function ut(t,e,n,s){if(s.has(t)&&s.get(t).has(e))return n.debug(`unweld: Cache hit for reused attribute, "${t.getName()}".`),s.get(t).get(e);const r=t.clone(),o=t.getArray().constructor;r.setArray(new o(e.getCount()*t.getElementSize()));const i=[];for(let n=0;n<e.getCount();n++)r.setElement(n,t.getElement(e.getScalar(n),i));return s.has(t)||s.set(t,new Map),s.get(t).set(e,r),r}const ft={overwrite:!1};function pt(t=ft){const e=L({},ft,t);return $("normals",async t=>{const n=t.getLogger();let s=0;await t.transform(gt());for(const r of t.getRoot().listMeshes())for(const o of r.listPrimitives()){const r=o.getAttribute("POSITION");let i=o.getAttribute("NORMAL");if(e.overwrite&&i)i.dispose();else if(i){n.debug("normals: Skipping primitive: NORMAL found.");continue}i=t.createAccessor().setArray(new Float32Array(3*r.getCount())).setType("VEC3");const a=[0,0,0],c=[0,0,0],l=[0,0,0];for(let t=0;t<r.getCount();t+=3){r.getElement(t+0,a),r.getElement(t+1,c),r.getElement(t+2,l);const e=mt(a,c,l);i.setElement(t+0,e),i.setElement(t+1,e),i.setElement(t+2,e)}o.setAttribute("NORMAL",i),s++}s?n.debug("normals: Complete."):n.warn("normals: No qualifying primitives found. See debug output.")})}function mt(t,e,n){const s=[e[0]-t[0],e[1]-t[1],e[2]-t[2]],r=[n[0]-t[0],n[1]-t[1],n[2]-t[2]];return S([0,0,0],[s[1]*r[2]-s[2]*r[1],s[2]*r[0]-s[0]*r[2],s[0]*r[1]-s[1]*r[0]])}const dt={propertyTypes:[n.NODE,n.SKIN,n.MESH,n.CAMERA,n.PRIMITIVE,n.PRIMITIVE_TARGET,n.ANIMATION,n.MATERIAL,n.TEXTURE,n.ACCESSOR,n.BUFFER]},ht=function(t=dt){const e=L({},dt,t).propertyTypes;return $("prune",t=>{const s=t.getLogger(),o=t.getRoot(),i=t.getGraph(),a={};if(e.includes(n.NODE)&&o.listNodes().forEach(c),e.includes(n.SKIN)&&o.listSkins().forEach(c),e.includes(n.MESH)&&o.listMeshes().forEach(c),e.includes(n.CAMERA)&&o.listCameras().forEach(c),e.includes(n.PRIMITIVE)&&l(i,n.PRIMITIVE),e.includes(n.PRIMITIVE_TARGET)&&l(i,n.PRIMITIVE_TARGET),e.includes(n.ANIMATION))for(const t of o.listAnimations()){for(const e of t.listChannels())e.getTargetNode()||(e.dispose(),u(e));if(t.listChannels().length)t.listSamplers().forEach(c);else{const e=t.listSamplers();c(t),e.forEach(c)}}if(e.includes(n.MATERIAL)&&o.listMaterials().forEach(c),e.includes(n.TEXTURE)&&o.listTextures().forEach(c),e.includes(n.ACCESSOR)&&o.listAccessors().forEach(c),e.includes(n.BUFFER)&&o.listBuffers().forEach(c),Object.keys(a).length){const t=Object.keys(a).map(t=>`${t} (${a[t]})`).join(", ");s.info(`prune: Removed types... ${t}`)}else s.info("prune: No unused properties found.");function c(t){t.listParents().filter(t=>!(t instanceof r||t instanceof g)).length||(t.dispose(),u(t))}function l(t,e){t.listEdges().map(t=>t.getParent()).filter(t=>t.propertyType===e).forEach(c)}function u(t){a[t.propertyType]=a[t.propertyType]||0,a[t.propertyType]++}s.debug("prune: Complete.")})},At={animations:!0,meshes:!0},yt=(t=At)=>{const e=L({},At,t);return $("partition",async t=>{const s=t.getLogger();!1!==e.meshes&&function(t,e,n){const s=new Set(t.getRoot().listBuffers().map(t=>t.getURI()));t.getRoot().listMeshes().forEach((r,o)=>{if(Array.isArray(n.meshes)&&!n.meshes.includes(r.getName()))return void e.debug(`partition: Skipping mesh #${o} with name "${r.getName()}".`);e.debug(`partition: Creating buffer for mesh "${r.getName()}".`);const i=t.createBuffer(r.getName()).setURI(Et(r.getName()||"mesh",s));r.listPrimitives().forEach(t=>{const e=t.getIndices();e&&e.setBuffer(i),t.listAttributes().forEach(t=>t.setBuffer(i)),t.listTargets().forEach(t=>{t.listAttributes().forEach(t=>t.setBuffer(i))})})})}(t,s,e),!1!==e.animations&&function(t,e,n){const s=new Set(t.getRoot().listBuffers().map(t=>t.getURI()));t.getRoot().listAnimations().forEach((r,o)=>{if(Array.isArray(n.animations)&&!n.animations.includes(r.getName()))return void e.debug(`partition: Skipping animation #${o} with name "${r.getName()}".`);e.debug(`partition: Creating buffer for animation "${r.getName()}".`);const i=t.createBuffer(r.getName()).setURI(Et(r.getName()||"animation",s));r.listSamplers().forEach(t=>{const e=t.getInput(),n=t.getOutput();e&&e.setBuffer(i),n&&n.setBuffer(i)})})}(t,s,e),e.meshes||e.animations||s.warn("partition: Select animations or meshes to create a partition."),await t.transform(ht({propertyTypes:[n.BUFFER]})),s.debug("partition: Complete.")})};function Et(t,e){let n=`${t}.bin`,s=1;for(;e.has(n);)n=`${t}_${s++}.bin`;return n}const Tt=[Int8Array,Int16Array,Int32Array],{TRANSLATION:St,ROTATION:It,SCALE:bt,WEIGHTS:wt}=g.TargetPath,Mt=[St,It,bt],Rt={pattern:/.*/,quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeWeight:8,quantizeGeneric:12},Nt=(t=Rt)=>{const e=L({},Rt,t);return $("quantize",async t=>{const s=t.getLogger(),r=t.getRoot();let o;t.createExtension(h).setRequired(!0),"scene"===e.quantizationVolume&&(o=Ot(function(t){const e=t[0];for(const n of t)b(e.min,e.min,n.min),M(e.max,e.max,n.max);return e}(r.listMeshes().map($t))));for(const n of t.getRoot().listMeshes()){"mesh"===e.quantizationVolume&&(o=Ot($t(n))),o&&e.pattern.test("POSITION")&&Pt(t,n,o);for(const s of n.listPrimitives()){Ct(t,s,o,e);for(const n of s.listTargets())Ct(t,n,o,e)}}await t.transform(ht({propertyTypes:[n.ACCESSOR,n.SKIN]}),B({propertyTypes:[n.ACCESSOR]})),s.debug("quantize: Complete.")})};function Ct(e,n,s,r){const o=e.getLogger();for(const e of n.listSemantics()){if(!r.pattern.test(e))continue;const i=n.getAttribute(e),{bits:a,ctor:c}=Lt(e,i,o,r);if(!c)continue;if(a<8||a>16)throw new Error("quantize: Requires bits = 8–16.");if(i.getComponentSize()<=a/8)continue;const l=i.clone();if("POSITION"===e){const e=s.scale,r=[];n instanceof t?R(r,_t(s)):C(r,[1/e,1/e,1/e]);for(let t=0,e=[0,0,0],n=l.getCount();t<n;t++)l.getElement(t,e),l.setElement(t,I(e,e,r))}zt(l,c,a),n.swap(i,l)}if(n.getAttribute("WEIGHTS_0")&&function(t){const e=t.getAttribute("POSITION").getCount(),n=[];for(let s=0;s<e;s++){let e,r=0,o=Infinity,i=-1,a=null,c=0;for(;e=t.getAttribute("WEIGHTS_"+c++);){e.getElement(s,n);for(let t=0;t<n.length;t++)r+=n[t],n[t]>0&&n[t]<o&&(a=e,o=n[t],i=t)}a&&1!==r&&(a.getElement(s,n),n[i]+=1-r,a.setElement(s,n))}}(n),n instanceof t&&n.getIndices()&&n.listAttributes().length&&n.listAttributes()[0].getCount()<65535){const t=n.getIndices();t.setArray(new Uint16Array(t.getArray()))}}function Ot(t){const{min:e,max:n}=t,s=Math.max((n[0]-e[0])/2,(n[1]-e[1])/2,(n[2]-e[2])/2);return{offset:[e[0]+(n[0]-e[0])/2,e[1]+(n[1]-e[1])/2,e[2]+(n[2]-e[2])/2],scale:s}}function Pt(t,e,n){const s=_t(n);for(const r of e.listParents())if(r instanceof l){const o=r.listParents().filter(t=>t instanceof g),i=o.some(t=>Mt.includes(t.getTargetPath())),a=r.listChildren().length>0;if(r.getSkin()){r.setSkin(xt(r.getSkin(),n));continue}let c;a||i?(c=t.createNode("").setMesh(e),r.addChild(c).setMesh(null),o.filter(t=>t.getTargetPath()===wt).forEach(t=>t.setTargetNode(c))):c=r;const l=c.getMatrix();O(l,l,s),c.setMatrix(l)}}function xt(t,e){t=t.clone();const n=_t(e),s=t.getInverseBindMatrices().clone(),r=[];for(let t=0,e=s.getCount();t<e;t++)s.getElement(t,r),O(r,r,n),s.setElement(t,r);return t.setInverseBindMatrices(s)}function zt(t,e,n){const s=new e(t.getArray().length),r=Tt.includes(e)?1:0,o=n-r,i=8*e.BYTES_PER_ELEMENT-r,a=Math.pow(2,o)-1,c=i-o,l=2*o-i;for(let e=0,n=0,r=[];e<t.getCount();e++){t.getElement(e,r);for(let t=0;t<r.length;t++){let e=Math.round(Math.abs(r[t])*a);e=e<<c|e>>l,s[n++]=e*Math.sign(r[t])}}t.setArray(s).setNormalized(!0)}function Lt(t,e,n,s){const r=e.getMinNormalized([]),o=e.getMaxNormalized([]);let i,a;if("POSITION"===t)i=s.quantizePosition,a=i<=8?Int8Array:Int16Array;else if("NORMAL"===t||"TANGENT"===t)i=s.quantizeNormal,a=i<=8?Int8Array:Int16Array;else if(t.startsWith("COLOR_"))i=s.quantizeColor,a=i<=8?Uint8Array:Uint16Array;else if(t.startsWith("TEXCOORD_")){if(r.some(t=>t<0)||o.some(t=>t>1))return n.warn(`quantize: Skipping ${t}; out of [0,1] range.`),{bits:-1};i=s.quantizeTexcoord,a=i<=8?Uint8Array:Uint16Array}else{if(t.startsWith("JOINTS_"))return i=Math.max(...e.getMax([]))<=255?8:16,a=i<=8?Uint8Array:Uint16Array,e.getComponentSize()>i/8&&e.setArray(new a(e.getArray())),{bits:-1};if(t.startsWith("WEIGHTS_")){if(r.some(t=>t<0)||o.some(t=>t>1))return n.warn(`quantize: Skipping ${t}; out of [0,1] range.`),{bits:-1};i=s.quantizeWeight,a=i<=8?Uint8Array:Uint16Array}else{if(!t.startsWith("_"))throw new Error(`quantize: Unexpected semantic, "${t}".`);if(r.some(t=>t<-1)||o.some(t=>t>1))return n.warn(`quantize: Skipping ${t}; out of [-1,1] range.`),{bits:-1};i=s.quantizeGeneric,a=a=r.some(t=>t<0)?i<=8?Int8Array:Int16Array:i<=8?Uint8Array:Uint16Array}}return{bits:i,ctor:a}}function $t(t){const e=[],n=[];for(const s of t.listPrimitives()){const t=s.getAttribute("POSITION");t&&e.push(t);for(const t of s.listTargets()){const e=t.getAttribute("POSITION");e&&n.push(e)}}if(0===e.length)throw new Error('quantize: Missing "POSITION" attribute.');const s=vt(e,3);if(n.length>0){const{min:t,max:e}=vt(n,3);b(s.min,s.min,b(t,w(t,t,2),[0,0,0])),M(s.max,s.max,M(e,w(e,e,2),[0,0,0]))}return s}function vt(t,e){const n=new Array(e).fill(Infinity),s=new Array(e).fill(-Infinity),r=[],o=[];for(const i of t){i.getMinNormalized(r),i.getMaxNormalized(o);for(let t=0;t<e;t++)n[t]=Math.min(n[t],r[t]),s[t]=Math.max(s[t],o[t])}return{min:n,max:s}}function _t(t){return N([],[0,0,0,1],t.offset,[t.scale,t.scale,t.scale])}const kt={tolerance:1e-4},Ft=(t=kt)=>{const e=L({},kt,t);return $("resample",(t,n)=>{const s=new Set,o=t.getRoot().listAccessors().length,i=t.getLogger();let a=!1;for(const n of t.getRoot().listAnimations()){const t=new Set;for(const e of n.listChannels())e.getSampler()&&"weights"===e.getTargetPath()&&t.add(e.getSampler());for(const r of n.listSamplers())t.has(r)?a=!0:"STEP"!==r.getInterpolation()&&"LINEAR"!==r.getInterpolation()||(s.add(r.getInput()),s.add(r.getOutput()),qt(r,e))}for(const t of Array.from(s.values()))t.listParents().some(t=>!(t instanceof r))||t.dispose();t.getRoot().listAccessors().length>o&&!function(t,e,n){return!!t&&t.stack.lastIndexOf("resample")<t.stack.lastIndexOf("dedup")}(n)&&i.warn('resample: Resampling required copying accessors, some of which may be duplicates. Consider using "dedup" to consolidate any duplicates.'),a&&i.warn("resample: Skipped optimizing morph target keyframes, not yet supported."),i.debug("resample: Complete.")})};function qt(t,e){const n=t.getInput().clone(),s=t.getOutput().clone(),r=e.tolerance,o=n.getCount()-1,i=[];let a=1;for(let e=1;e<o;++e){const o=n.getScalar(e),l=n.getScalar(e-1),g=n.getScalar(e+1),u=(o-l)/(g-l);let f=!1;if(o!==g&&(1!==e||o!==n.getScalar(0)))for(let n=0;n<s.getElementSize();n++){const o=s.getElement(e,i)[n],a=s.getElement(e-1,i)[n],l=s.getElement(e+1,i)[n];if("LINEAR"===t.getInterpolation()){if(Math.abs(o-(a*(1-(c=u))+l*c))>r){f=!0;break}}else if("STEP"===t.getInterpolation()&&(o!==a||o!==l)){f=!0;break}}f&&(e!==a&&(n.setScalar(a,n.getScalar(e)),s.setElement(a,s.getElement(e,i))),a++)}var c;o>0&&(n.setScalar(a,n.getScalar(o)),s.setElement(a,s.getElement(o,i)),a++),a!==n.getCount()?(n.setArray(n.getArray().slice(0,a)),s.setArray(s.getArray().slice(0,a*s.getElementSize())),t.setInput(n),t.setOutput(s)):(n.dispose(),s.dispose())}const Gt={target:"size"};function Ut(e=Gt){const s=L({},Gt,e),r=s.encoder;return $("reorder",async e=>{const o=e.getLogger();await r.ready;const i=function(t){const e=new _,n=new Map,s=new _;for(const r of t.getRoot().listMeshes())for(const t of r.listPrimitives()){const r=t.getIndices();if(r){n.set(r,t.getMode());for(const n of Vt(t))e.add(r,n),s.add(n,t)}}return{indicesToAttributes:e,indicesToMode:n,attributesToPrimitives:s}}(e);for(const e of i.indicesToAttributes.keys()){const n=e.clone();let o=n.getArray().slice();o instanceof Uint32Array||(o=new Uint32Array(o));const[a,c]=r.reorderMesh(o,i.indicesToMode.get(e)===t.Mode.TRIANGLES,"size"===s.target);n.setArray(c<=65534?new Uint16Array(o):o);for(const t of i.indicesToAttributes.get(e)){const s=t.clone();Bt(s,a,c);for(const r of i.attributesToPrimitives.get(t))if(r.getIndices()===e&&r.swap(e,n),r.getIndices()===n){r.swap(t,s);for(const e of r.listTargets())e.swap(t,s)}}}await e.transform(ht({propertyTypes:[n.ACCESSOR]})),i.indicesToAttributes.size?o.debug("reorder: Complete."):o.warn("reorder: No qualifying primitives found; may need to weld first.")})}function Bt(t,e,n){const s=t.getElementSize(),r=t.getCount(),o=t.getArray(),i=o.slice(0,n*s);for(let t=0;t<r;t++)for(let n=0;n<s;n++)i[e[t]*s+n]=o[t*s+n];t.setArray(i)}function Vt(t){const e=[];for(const n of t.listAttributes())e.push(n);for(const n of t.listTargets())for(const t of n.listAttributes())e.push(t);return Array.from(new Set(e))}const Ht={name:"",fps:10,pattern:/.*/,sort:!0};function Wt(t=Ht){const e=L({},Ht,t);return $("sequence",t=>{const n=t.getLogger(),s=t.getRoot(),r=e.fps,o=s.listNodes().filter(t=>t.getName().match(e.pattern));e.sort&&o.sort((t,e)=>t.getName()>e.getName()?1:-1);const i=t.createAnimation(e.name),a=s.listBuffers()[0];o.forEach((e,n)=>{let s,c;0===n?(s=[n/r,(n+1)/r],c=[1,1,1,0,0,0]):n===o.length-1?(s=[(n-1)/r,n/r],c=[0,0,0,1,1,1]):(s=[(n-1)/r,n/r,(n+1)/r],c=[0,0,0,1,1,1,0,0,0]);const l=t.createAccessor().setArray(new Float32Array(s)).setBuffer(a),p=t.createAccessor().setArray(new Float32Array(c)).setBuffer(a).setType(u.Type.VEC3),m=t.createAnimationSampler().setInterpolation(f.Interpolation.STEP).setInput(l).setOutput(p),d=t.createAnimationChannel().setTargetNode(e).setTargetPath(g.TargetPath.SCALE).setSampler(m);i.addSampler(m).addChannel(d)}),n.debug("sequence: Complete.")})}const Dt={overwrite:!1};function jt(t=Dt){if(!t.generateTangents)throw new Error('tangents: generateTangents callback required — install "mikktspace".');const e=L({},Dt,t);return $("tangents",t=>{const n=t.getLogger(),s=new Map,r=new Map;let o=0;for(const i of t.getRoot().listMeshes()){const a=i.getName(),c=i.listPrimitives();for(let i=0;i<c.length;i++){const l=c[i];if(!Kt(l,n,a,i,e.overwrite))continue;const g=Xt(l),u=l.getAttribute("POSITION").getArray(),f=l.getAttribute("NORMAL").getArray(),m=l.getAttribute(g).getArray(),d=s.get(u)||p();s.set(u,d);const h=s.get(f)||p();s.set(f,h);const A=s.get(m)||p();s.set(m,A);const y=l.getAttribute("TANGENT");y&&2===y.listParents().length&&y.dispose();const E=`${d}|${h}|${A}`;let T=r.get(E);if(T){n.debug(`tangents: Found cache for primitive ${i} of mesh "${a}".`),l.setAttribute("TANGENT",T),o++;continue}n.debug(`tangents: Generating for primitive ${i} of mesh "${a}".`);const S=l.getAttribute("POSITION").getBuffer(),I=e.generateTangents(u instanceof Float32Array?u:new Float32Array(u),f instanceof Float32Array?f:new Float32Array(f),m instanceof Float32Array?m:new Float32Array(m));for(let t=3;t<I.length;t+=4)I[t]*=-1;T=t.createAccessor().setBuffer(S).setArray(I).setType("VEC4"),l.setAttribute("TANGENT",T),r.set(E,T),o++}}o?n.debug("tangents: Complete."):n.warn("tangents: No qualifying primitives found. See debug output.")})}function Xt(t){const e=t.getMaterial();if(!e)return"TEXCOORD_0";const n=e.getNormalTextureInfo();if(!n)return"TEXCOORD_0";const s=`TEXCOORD_${n.getTexCoord()}`;return t.getAttribute(s)?s:"TEXCOORD_0"}function Kt(e,n,s,r,o){return e.getMode()===t.Mode.TRIANGLES&&e.getAttribute("POSITION")&&e.getAttribute("NORMAL")&&e.getAttribute("TEXCOORD_0")?e.getAttribute("TANGENT")&&!o?(n.debug(`tangents: Skipping primitive ${r} of mesh "${s}": TANGENT found.`),!1):!e.getIndices()||(n.warn(`tangents: Skipping primitive ${r} of mesh "${s}": primitives must be unwelded.`),!1):(n.debug(`tangents: Skipping primitive ${r} of mesh "${s}": primitives must have attributes=[POSITION, NORMAL, TEXCOORD_0] and mode=TRIANGLES.`),!1)}const Zt="textureResize";var Jt;!function(t){t.LANCZOS3="lanczos3",t.LANCZOS2="lanczos2"}(Jt||(Jt={}));const Yt={size:[2048,2048],filter:Jt.LANCZOS3,pattern:null};function Qt(t=Yt){const e=L({},Yt,t);return $(Zt,async t=>{const n=t.getLogger();for(const s of t.getRoot().listTextures()){const t=s.getName(),r=s.getURI();if(e.pattern&&!e.pattern.test(t)&&!e.pattern.test(r))continue;if("image/png"!==s.getMimeType()&&"image/jpeg"!==s.getMimeType()){n.warn(`Skipping unsupported texture type, "${s.getMimeType()}".`);continue}const[o,i]=e.size,[a,c]=s.getSize();if(a<=o&&c<=i){n.debug(`${Zt}: Skipping "${r||t}", within size range.`);continue}let l=a,g=c;l>o&&(g=Math.floor(g*(o/l)),l=o),g>i&&(l=Math.floor(l*(i/g)),g=i);const u=s.getImage(),f=await m(u,s.getMimeType()),p=P(new Uint8Array(l*g*4),[l,g,4]);n.debug(`${Zt}: Resizing "${r||t}", ${f.shape} → ${p.shape}...`);try{e.filter===Jt.LANCZOS3?x(f,p):z(f,p)}catch(e){if(e instanceof Error){n.warn(`${Zt}: Failed to resize "${r||t}": "${e.message}".`);continue}throw e}s.setImage(await d(p,s.getMimeType()))}n.debug(`${Zt}: Complete.`)})}const te={tolerance:1e-4};function ee(e=te){const n=L({},te,e);return $("weld",e=>{const s=e.getLogger();for(const s of e.getRoot().listMeshes())for(const r of s.listPrimitives())r.getMode()!==t.Mode.POINTS&&(0===n.tolerance?ne(e,r):se(e,r,n));s.debug("weld: Complete.")})}function ne(t,e){if(e.getIndices())return;const n=e.listAttributes()[0],s=n.getCount(),r=n.getBuffer(),o=s<=65534?new Uint16Array(s):new Uint32Array(s),i=t.createAccessor().setBuffer(r).setType(u.Type.SCALAR).setArray(o);for(let t=0;t<i.getCount();t++)i.setScalar(t,t);e.setIndices(i)}function se(t,e,n){const s=Math.max(n.tolerance,Number.EPSILON),r=Math.log10(1/s),o=Math.pow(10,r),i={},a=e.getIndices(),c=a?a.getCount():e.listAttributes()[0].getCount(),l=new Map;e.listAttributes().forEach(t=>l.set(t,[])),e.listTargets().forEach(t=>{t.listAttributes().forEach(t=>l.set(t,[]))});const g=[];let u=0;for(let t=0;t<c;t++){const n=a?a.getScalar(t):t,s=[],r=[];for(const t of e.listAttributes())for(let e=0;e<t.getElementSize();e++)s.push(~~(t.getElement(n,r)[e]*o));const c=s.join("|");if(c in i)g.push(i[c]);else{for(const t of e.listAttributes())l.get(t).push(t.getElement(n,[]));for(const t of e.listTargets())for(const e of t.listAttributes())l.get(e).push(e.getElement(n,[]));i[c]=u,g.push(u),u++}}const f=e.listAttributes()[0].getCount(),p=l.get(e.getAttribute("POSITION")).length;t.getLogger().debug(`weld: ${f} → ${p} vertices.`);for(const t of e.listAttributes())oe(e,t,l.get(t)),1===t.listParents().length&&t.dispose();for(const t of e.listTargets())for(const e of t.listAttributes())oe(t,e,l.get(e)),1===e.listParents().length&&e.dispose();if(a){const t=re(a.getArray(),g.length);t.set(g),e.setIndices(a.clone().setArray(t)),1===a.listParents().length&&a.dispose()}else{const n=f<=65534?new Uint16Array(g):new Uint32Array(g);e.setIndices(t.createAccessor().setArray(n))}}function re(t,e){return new(0,t.constructor)(e)}function oe(t,e,n){const s=n.length*e.getElementSize(),r=re(e.getArray(),s),o=e.clone().setArray(r);for(let t=0;t<n.length;t++)o.setElement(t,n[t]);t.swap(e,o)}export{Rt as QUANTIZE_DEFAULTS,Yt as TEXTURE_RESIZE_DEFAULTS,Jt as TextureResizeFilter,F as center,G as colorspace,B as dedup,W as dequantize,X as inspect,rt as instance,ct as metalRough,pt as normals,yt as partition,ht as prune,Nt as quantize,Ut as reorder,Ft as resample,Wt as sequence,jt as tangents,Qt as textureResize,gt as unweld,ee as weld};
//# sourceMappingURL=functions.modern.js.map

@@ -47,2 +47,3 @@ /**

export * from './metal-rough';
export * from './normals';
export * from './partition';

@@ -49,0 +50,0 @@ export * from './prune';

{
"name": "@gltf-transform/functions",
"version": "2.0.4",
"version": "2.0.5",
"repository": "github:donmccurdy/glTF-Transform",

@@ -32,4 +32,4 @@ "homepage": "https://gltf-transform.donmccurdy.com/functions.html",

"dependencies": {
"@gltf-transform/core": "^2.0.4",
"@gltf-transform/extensions": "^2.0.4",
"@gltf-transform/core": "^2.0.5",
"@gltf-transform/extensions": "^2.0.5",
"gl-matrix": "~3.4.3",

@@ -50,3 +50,3 @@ "ndarray": "^1.0.19",

},
"gitHead": "ca187965eec975fc7027d473be39d84b0cff5b29"
"gitHead": "9431e3aeec7d1bac01c31090b2c20fe5227a8146"
}

@@ -48,2 +48,3 @@ /**

export * from './metal-rough';
export * from './normals';
export * from './partition';

@@ -50,0 +51,0 @@ export * from './prune';

@@ -24,6 +24,6 @@ import { NdArray } from 'ndarray';

export async function rewriteTexture(
source: Texture,
target: Texture,
fn: (pixels: NdArray, i: number, j: number) => void): Promise<Texture|null> {
source: Texture,
target: Texture,
fn: (pixels: NdArray, i: number, j: number) => void
): Promise<Texture | null> {
if (!source) return null;

@@ -36,4 +36,4 @@

for(let i = 0; i < pixels.shape[0]; ++i) {
for(let j = 0; j < pixels.shape[1]; ++j) {
for (let i = 0; i < pixels.shape[0]; ++i) {
for (let j = 0; j < pixels.shape[1]; ++j) {
fn(pixels, i, j);

@@ -56,5 +56,3 @@ }

case Primitive.Mode.LINES:
return indices
? indices.getCount() / 2
: position.getCount() / 2;
return indices ? indices.getCount() / 2 : position.getCount() / 2;
case Primitive.Mode.LINE_LOOP:

@@ -65,5 +63,3 @@ return position.getCount();

case Primitive.Mode.TRIANGLES:
return indices
? indices.getCount() / 3
: position.getCount() / 3;
return indices ? indices.getCount() / 3 : position.getCount() / 3;
case Primitive.Mode.TRIANGLE_STRIP:

@@ -70,0 +66,0 @@ case Primitive.Mode.TRIANGLE_FAN:

import { Accessor, Document, Primitive, PrimitiveTarget, Transform, TypedArray } from '@gltf-transform/core';
import { getGLPrimitiveCount, createTransform } from './utils';
import { createTransform } from './utils';

@@ -9,6 +9,6 @@ const NAME = 'weld';

/** Per-attribute tolerance used when merging similar vertices. */
tolerance?: number
tolerance?: number;
}
const WELD_DEFAULTS: Required<WeldOptions> = {tolerance: 1e-4};
const WELD_DEFAULTS: Required<WeldOptions> = { tolerance: 1e-4 };

@@ -18,4 +18,4 @@ /**

*/
export function weld (_options: WeldOptions = WELD_DEFAULTS): Transform {
const options = {...WELD_DEFAULTS, ..._options} as Required<WeldOptions>;
export function weld(_options: WeldOptions = WELD_DEFAULTS): Transform {
const options = { ...WELD_DEFAULTS, ..._options } as Required<WeldOptions>;

@@ -27,3 +27,5 @@ return createTransform(NAME, (doc: Document): void => {

for (const prim of mesh.listPrimitives()) {
if (options.tolerance === 0) {
if (prim.getMode() === Primitive.Mode.POINTS) {
continue;
} else if (options.tolerance === 0) {
weldOnly(doc, prim);

@@ -41,3 +43,3 @@ } else {

/** In-place weld, adds indices without changing number of vertices. */
function weldOnly (doc: Document, prim: Primitive): void {
function weldOnly(doc: Document, prim: Primitive): void {
if (prim.getIndices()) return;

@@ -47,9 +49,4 @@ const attr = prim.listAttributes()[0];

const buffer = attr.getBuffer();
const indicesArray = numVertices <= 65534
? new Uint16Array(getGLPrimitiveCount(prim) * 3)
: new Uint32Array(getGLPrimitiveCount(prim) * 3);
const indices = doc.createAccessor()
.setBuffer(buffer)
.setType(Accessor.Type.SCALAR)
.setArray(indicesArray);
const indicesArray = numVertices <= 65534 ? new Uint16Array(numVertices) : new Uint32Array(numVertices);
const indices = doc.createAccessor().setBuffer(buffer).setType(Accessor.Type.SCALAR).setArray(indicesArray);
for (let i = 0; i < indices.getCount(); i++) indices.setScalar(i, i);

@@ -63,3 +60,3 @@ prim.setIndices(indices);

*/
function weldAndMerge (doc: Document, prim: Primitive, options: Required<WeldOptions>): void {
function weldAndMerge(doc: Document, prim: Primitive, options: Required<WeldOptions>): void {
const tolerance = Math.max(options.tolerance, Number.EPSILON);

@@ -69,7 +66,5 @@ const decimalShift = Math.log10(1 / tolerance);

const hashToIndex: {[key: string]: number} = {};
const hashToIndex: { [key: string]: number } = {};
const srcIndices = prim.getIndices();
const vertexCount = srcIndices
? srcIndices.getCount()
: prim.listAttributes()[0].getCount();
const vertexCount = srcIndices ? srcIndices.getCount() : prim.listAttributes()[0].getCount();

@@ -95,3 +90,3 @@ // Prepare storage for new elements of each attribute.

for (let j = 0; j < attribute.getElementSize(); j++) {
hashElements.push(~ ~ (attribute.getElement(index, el)[j] * shiftFactor));
hashElements.push(~~(attribute.getElement(index, el)[j] * shiftFactor));
}

@@ -139,4 +134,3 @@ }

if (srcIndices) {
const dstIndicesTypedArray
= createArrayOfType(srcIndices.getArray()!, dstIndicesArray.length);
const dstIndicesTypedArray = createArrayOfType(srcIndices.getArray()!, dstIndicesArray.length);
dstIndicesTypedArray.set(dstIndicesArray);

@@ -148,5 +142,4 @@ prim.setIndices(srcIndices.clone().setArray(dstIndicesTypedArray));

} else {
const indicesArray = srcVertexCount <= 65534
? new Uint16Array(dstIndicesArray)
: new Uint32Array(dstIndicesArray);
const indicesArray =
srcVertexCount <= 65534 ? new Uint16Array(dstIndicesArray) : new Uint32Array(dstIndicesArray);
prim.setIndices(doc.createAccessor().setArray(indicesArray));

@@ -163,6 +156,3 @@ }

/** Replaces an {@link Attribute}, creating a new one with the given elements. */
function swapAttributes(
parent: Primitive | PrimitiveTarget,
srcAttr: Accessor,
dstAttrElements: number[][]): void {
function swapAttributes(parent: Primitive | PrimitiveTarget, srcAttr: Accessor, dstAttrElements: number[][]): void {
const dstAttrArrayLength = dstAttrElements.length * srcAttr.getElementSize();

@@ -169,0 +159,0 @@ const dstAttrArray = createArrayOfType(srcAttr.getArray()!, dstAttrArrayLength);

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc