Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@gltf-transform/functions

Package Overview
Dependencies
Maintainers
1
Versions
144
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 1.0.1 to 1.1.1

3

dist/dedup.d.ts

@@ -7,3 +7,4 @@ import { Transform } from '@gltf-transform/core';

/**
* Removes duplicate {@link Accessor}, {@link Mesh}, and {@link Texture} properties. Based on a
* Removes duplicate {@link Accessor}, {@link Mesh}, {@link Texture}, and {@link Material}
* properties. Partially based on a
* [gist by mattdesl](https://gist.github.com/mattdesl/aea40285e2d73916b6b9101b36d84da8). Only

@@ -10,0 +11,0 @@ * accessors in mesh primitives, morph targets, and animation samplers are processed.

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

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

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

import{bounds as t,PropertyType as e,BufferUtils as n,Root as s,Primitive 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{MeshGPUInstancing as h,MaterialsIOR as A,MaterialsSpecular as y,MaterialsPBRSpecularGlossiness as T,MeshQuantization as E}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 N,scale as R,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)}const L={pivot:"center"};function $(e=L){const n=z({},L,e);return e=>{const s=e.getLogger(),r=e.getRoot(),o=r.listAnimations().length>0||r.listSkins().length>0;e.getRoot().listScenes().forEach((i,a)=>{let c;if(s.debug(`center: Scene ${a+1} / ${r.listScenes().length}.`),"string"==typeof n.pivot){const e=t(i);c=[(e.max[0]-e.min[0])/2+e.min[0],(e.max[1]-e.min[1])/2+e.min[1],(e.max[2]-e.min[2])/2+e.min[2]],"above"===n.pivot&&(c[1]=e.max[1]),"below"===n.pivot&&(c[1]=e.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 t=e.createNode("Pivot").setTranslation(l);i.listChildren().forEach(e=>t.addChild(e)),i.addChild(t)}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.")}}function v(t){return e=>{const n=e.getLogger();if("linear"===t.inputEncoding)return void n.info("colorspace: Vertex colors already linear. Skipping conversion.");if("sRGB"!==t.inputEncoding)return void n.error(`colorspace: 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("colorspace: Complete.")}}const _={propertyTypes:[e.ACCESSOR,e.MESH,e.TEXTURE]},k=function(t=_){const r=z({},_,t),o=new Set(r.propertyTypes);for(const t of r.propertyTypes)if(!_.propertyTypes.includes(t))throw new Error(`dedup: Unsupported deduplication on type "${t}".`);return t=>{const r=t.getLogger();o.has(e.ACCESSOR)&&function(t,e){const s=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&&s.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 s=0;s<t.length;s++){const r=t[s],o=r.getArray().slice().buffer;if(!e.has(r))for(let s=0;s<t.length;s++){const i=t[s];r!==i&&(e.has(i)||r.getType()===i.getType()&&r.getComponentType()===i.getComponentType()&&r.getCount()===i.getCount()&&r.getNormalized()===i.getNormalized()&&n.equals(o,i.getArray().slice().buffer)&&e.set(i,r))}}return e}const l=c(Array.from(s));t.debug(`dedup: Found ${l.size} duplicates among ${s.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())}(r,t),o.has(e.MESH)&&function(t,n){const s=n.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 n=[];for(const e of t.listPrimitives())n.push(F(e,r));const s=n.join(";");if(i.has(s)){const n=i.get(s);t.listParents().forEach(s=>{s.propertyType!==e.ROOT&&s.swap(t,n)}),t.dispose()}else i.set(s,t)}t.debug(`dedup: Found ${o-i.size} duplicates among ${o} meshes.`)}(r,t),o.has(e.TEXTURE)&&function(t,e){const r=e.getRoot(),o=r.listTextures(),i=new Map;for(let t=0;t<o.length;t++){const e=o[t],s=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]&&s&&a&&n.equals(s,a)&&i.set(r,e)}}t.debug(`dedup: Found ${i.size} duplicates among ${r.listTextures().length} textures.`),Array.from(i.entries()).forEach(([t,e])=>{t.listParents().forEach(n=>{n instanceof s||n.swap(t,e)}),t.dispose()})}(r,t),r.debug("dedup: Complete.")}};function F(t,e){const n=[];for(const s of t.listSemantics()){const r=t.getAttribute(s);n.push(s+":"+e.get(r))}if(t instanceof r){const s=t.getIndices();s&&n.push("indices:"+e.get(s));const r=t.getMaterial();r&&n.push("material:"+e.get(r)),n.push("mode:"+t.getMode());for(const s of t.listTargets())n.push("target:"+F(s,e))}return n.join(",")}async function U(t,e,n){if(!t)return null;const s=t.getImage();if(!s)return null;const r=await m(new Uint8Array(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")).buffer;return e.setImage(o).setMimeType("image/png")}function G(t){const e=t.getIndices(),n=t.getAttribute("POSITION");switch(t.getMode()){case r.Mode.POINTS:return n.getCount();case r.Mode.LINES:return e?e.getCount()/2:n.getCount()/2;case r.Mode.LINE_LOOP:return n.getCount();case r.Mode.LINE_STRIP:return n.getCount()-1;case r.Mode.TRIANGLES:return e?e.getCount()/3:n.getCount()/3;case r.Mode.TRIANGLE_STRIP:case r.Mode.TRIANGLE_FAN:return n.getCount()-2;default:throw new Error("Unexpected mode: "+t.getMode())}}class q{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()}}function B(t){return{scenes:V(t),meshes:W(t),materials:D(t),textures:X(t),animations:H(t)}}function V(e){return{properties:e.getRoot().listScenes().map(e=>{const n=e.listChildren()[0],s=t(e);return{name:e.getName(),rootName:n?n.getName():"",bboxMin:K(s.min),bboxMax:K(s.max)}})}}function W(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+":"+Z(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(Z(e.getArray())),i.add(e)),s+=t.listAttributes()[0].getCount(),n+=G(t)});let a=0;Array.from(i).forEach(t=>a+=t.getArray().byteLength);const c=t.listPrimitives().map(t=>j[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 D(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().getLinks().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 X(t){return{properties:t.getRoot().listTextures().map(e=>{const n=e.listParents().filter(t=>"Root"!==t.propertyType).length,s=t.getGraph().listParentLinks(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 H(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 j=["POINTS","LINES","LINE_LOOP","LINE_STRIP","TRIANGLES","TRIANGLE_STRIP","TRIANGLE_FAN"];function K(t){for(let e=0;e<t.length;e++)t[e].toFixed&&(t[e]=Number(t[e].toFixed(5)));return t}function Z(t){return t.constructor.name.replace("Array","").toLowerCase()}const J={};function Y(t=J){return z({},J,t),t=>{const e=t.getLogger(),n=t.getRoot(),s=t.createExtension(h);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=tt(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(),Q(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 Q(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 tt(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 et={};function nt(t=et){return z({},et,t),async t=>{const e=t.getLogger(),n=T.EXTENSION_NAME;if(!t.getRoot().listExtensionsUsed().map(t=>t.extensionName).includes(n))return void e.warn(`metalRough: Extension ${n} not found on given document.`);const s=t.createExtension(A),r=t.createExtension(y),o=t.createExtension(T),i=new Set;for(const e of t.getRoot().listMaterials()){const n=e.getExtension("KHR_materials_pbrSpecularGlossiness");if(!n)continue;const o=r.createSpecular().setSpecularFactor(1).setSpecularColorFactor(n.getSpecularFactor());i.add(n.getSpecularGlossinessTexture()),i.add(e.getBaseColorTexture()),i.add(e.getMetallicRoughnessTexture()),e.setBaseColorFactor(n.getDiffuseFactor()).setMetallicFactor(0).setRoughnessFactor(1).setExtension("KHR_materials_ior",s.createIOR().setIOR(1e3)).setExtension("KHR_materials_specular",o);const a=n.getDiffuseTexture();a&&(e.setBaseColorTexture(a),e.getBaseColorTextureInfo().copy(n.getDiffuseTextureInfo()));const c=n.getSpecularGlossinessTexture();if(c){const s=n.getSpecularGlossinessTextureInfo(),r=t.createTexture();await U(c,r,(t,e,n)=>{t.set(e,n,3,255)}),o.setSpecularTexture(r),o.setSpecularColorTexture(r),o.getSpecularTextureInfo().copy(s),o.getSpecularColorTextureInfo().copy(s);const i=n.getGlossinessFactor(),a=t.createTexture();await U(c,a,(t,e,n)=>{const s=255-Math.round(t.get(e,n,3)*i);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(s)}else o.setSpecularColorFactor(n.getSpecularFactor()),e.setRoughnessFactor(1-n.getGlossinessFactor());e.setExtension("KHR_materials_pbrSpecularGlossiness",null)}o.dispose();for(const t of i)t&&1===t.listParents().length&&t.dispose();e.debug("metalRough: Complete.")}}const st={propertyTypes:[e.NODE,e.SKIN,e.MESH,e.CAMERA,e.PRIMITIVE,e.PRIMITIVE_TARGET,e.ANIMATION,e.MATERIAL,e.TEXTURE,e.ACCESSOR,e.BUFFER]},rt=function(t=st){const n=z({},st,t).propertyTypes;return t=>{const r=t.getLogger(),o=t.getRoot(),i=t.getGraph(),a={};if(n.includes(e.NODE)&&o.listNodes().forEach(c),n.includes(e.SKIN)&&o.listSkins().forEach(c),n.includes(e.MESH)&&o.listMeshes().forEach(c),n.includes(e.CAMERA)&&o.listCameras().forEach(c),n.includes(e.PRIMITIVE)&&l(i,e.PRIMITIVE),n.includes(e.PRIMITIVE_TARGET)&&l(i,e.PRIMITIVE_TARGET),n.includes(e.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(n.includes(e.MATERIAL)&&o.listMaterials().forEach(c),n.includes(e.TEXTURE)&&o.listTextures().forEach(c),n.includes(e.ACCESSOR)&&o.listAccessors().forEach(c),n.includes(e.BUFFER)&&o.listBuffers().forEach(c),Object.keys(a).length){const t=Object.keys(a).map(t=>`${t} (${a[t]})`).join(", ");r.info(`prune: Removed types... ${t}`)}else r.info("prune: No unused properties found.");function c(t){t.listParents().filter(t=>!(t instanceof s||t instanceof g)).length||(t.dispose(),u(t))}function l(t,e){t.getLinks().map(t=>t.getParent()).filter(t=>t.propertyType===e).forEach(c)}function u(t){a[t.propertyType]=a[t.propertyType]||0,a[t.propertyType]++}r.debug("prune: Complete.")}},ot={animations:!0,meshes:!0},it=(t=ot)=>{const n=z({},ot,t);return async t=>{const s=t.getLogger();!1!==n.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(at(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,n),!1!==n.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(at(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,n),n.meshes||n.animations||s.warn("partition: Select animations or meshes to create a partition."),await t.transform(rt({propertyTypes:[e.BUFFER]})),s.debug("partition: Complete.")}};function at(t,e){let n=`${t}.bin`,s=1;for(;e.has(n);)n=`${t}_${s++}.bin`;return n}const ct=[Int8Array,Int16Array,Int32Array],{TRANSLATION:lt,ROTATION:gt,SCALE:ut,WEIGHTS:ft}=g.TargetPath,pt=[lt,gt,ut],mt={pattern:/.*/,quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeWeight:8,quantizeGeneric:12},dt=(t=mt)=>{const n=z({},mt,t);return async t=>{const s=t.getLogger(),r=t.getRoot();let o;t.createExtension(E).setRequired(!0),"scene"===n.quantizationVolume&&(o=At(function(t){const e=t[0];for(const n of t)N(e.min,e.min,n.min),C(e.max,e.max,n.max);return e}(r.listMeshes().map(It))));for(const e of t.getRoot().listMeshes()){"mesh"===n.quantizationVolume&&(o=At(It(e))),o&&n.pattern.test("POSITION")&&yt(t,e,o);for(const s of e.listPrimitives()){ht(t,s,o,n);for(const e of s.listTargets())ht(t,e,o,n)}}await t.transform(rt({propertyTypes:[e.ACCESSOR,e.SKIN]}),k({propertyTypes:[e.ACCESSOR]})),s.debug("quantize: Complete.")}};function ht(t,e,n,s){const o=t.getLogger();for(const t of e.listSemantics()){if(!s.pattern.test(t))continue;const i=e.getAttribute(t),{bits:a,ctor:c}=St(t,i,o,s);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"===t){const t=n.scale,s=[];e instanceof r?S(s,wt(n)):b(s,[1/t,1/t,1/t]);for(let t=0,e=[0,0,0],n=l.getCount();t<n;t++)l.getElement(t,e),l.setElement(t,M(e,e,s))}Et(l,c,a),e.swap(i,l)}if(e.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))}}(e),e instanceof r&&e.getIndices()&&e.listAttributes().length&&e.listAttributes()[0].getCount()<65535){const t=e.getIndices();t.setArray(new Uint16Array(t.getArray()))}}function At(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 yt(t,e,n){const s=wt(n);for(const r of e.listParents())if(r instanceof l){const o=r.listParents().filter(t=>t instanceof g),i=o.some(t=>pt.includes(t.getTargetPath())),a=r.listChildren().length>0;if(r.getSkin()){r.setSkin(Tt(r.getSkin(),n));continue}let c;a||i?(c=t.createNode("").setMesh(e),r.addChild(c).setMesh(null),o.filter(t=>t.getTargetPath()===ft).forEach(t=>t.setTargetNode(c))):c=r;const l=c.getMatrix();w(l,l,s),c.setMatrix(l)}}function Tt(t,e){t=t.clone();const n=wt(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 Et(t,e,n){const s=new e(t.getArray().length),r=ct.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 St(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 It(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=bt(e,3);if(n.length>0){const{min:t,max:e}=bt(n,3);N(s.min,s.min,N(t,R(t,t,2),[0,0,0])),C(s.max,s.max,C(e,R(e,e,2),[0,0,0]))}return s}function bt(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 wt(t){return I([],[0,0,0,1],t.offset,[t.scale,t.scale,t.scale])}const Mt={tolerance:1e-4},Nt=(t=Mt)=>{const e=z({},Mt,t);return t=>{const n=new Set,r=t.getRoot().listAccessors().length,o=t.getLogger();let i=!1;for(const s of t.getRoot().listAnimations()){const t=new Set;for(const e of s.listChannels())e.getSampler()&&"weights"===e.getTargetPath()&&t.add(e.getSampler());for(const r of s.listSamplers())t.has(r)?i=!0:"STEP"!==r.getInterpolation()&&"LINEAR"!==r.getInterpolation()||(n.add(r.getInput()),n.add(r.getOutput()),Rt(r,e))}for(const t of Array.from(n.values()))t.listParents().some(t=>!(t instanceof s))||t.dispose();t.getRoot().listAccessors().length>r&&o.warn('resample: Resampling required copying accessors, some of which may be duplicates. Consider using "dedup" to consolidate any duplicates.'),i&&o.warn("resample: Skipped optimizing morph target keyframes, not yet supported."),o.debug("resample: Complete.")}};function Rt(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 Ct={target:"size"};function Ot(t=Ct){const n=z({},Ct,t),s=n.encoder;return async t=>{const o=t.getLogger();await s.ready;const i=function(t){const e=new q,n=new Map,s=new q;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 Pt(t))e.add(r,n),s.add(n,t)}}return{indicesToAttributes:e,indicesToMode:n,attributesToPrimitives:s}}(t);for(const t of i.indicesToAttributes.keys()){const e=t.clone();let o=e.getArray().slice();o instanceof Uint32Array||(o=new Uint32Array(o));const[a,c]=s.reorderMesh(o,i.indicesToMode.get(t)===r.Mode.TRIANGLES,"size"===n.target);e.setArray(c<=65534?new Uint16Array(o):o);for(const n of i.indicesToAttributes.get(t)){const s=n.clone();xt(s,a,c);for(const r of i.attributesToPrimitives.get(n))if(r.getIndices()===t&&r.swap(t,e),r.getIndices()===e){r.swap(n,s);for(const t of r.listTargets())t.swap(n,s)}}}await t.transform(rt({propertyTypes:[e.ACCESSOR]})),i.indicesToAttributes.size?o.debug("reorder: Complete."):o.warn("reorder: No qualifying primitives found; may need to weld first.")}}function xt(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 Pt(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 zt={name:"",fps:10,pattern:/.*/,sort:!0};function Lt(t=zt){const e=z({},zt,t);return 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 $t={overwrite:!1};function vt(t=$t){if(!t.generateTangents)throw new Error('tangents: generateTangents callback required — install "mikktspace".');const e=z({},$t,t);return 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=_t(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 T=`${d}|${h}|${A}`;let E=r.get(T);if(E){n.debug(`tangents: Found cache for primitive ${i} of mesh "${a}".`),l.setAttribute("TANGENT",E),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;E=t.createAccessor().setBuffer(S).setArray(I).setType("VEC4"),l.setAttribute("TANGENT",E),r.set(T,E),o++}}o?n.debug("tangents: Complete."):n.warn("tangents: No qualifying primitives found. See debug output.")}}function _t(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(t,e,n,s,o){return t.getMode()===r.Mode.TRIANGLES&&t.getAttribute("POSITION")&&t.getAttribute("NORMAL")&&t.getAttribute("TEXCOORD_0")?t.getAttribute("TANGENT")&&!o?(e.debug(`tangents: Skipping primitive ${s} of mesh "${n}": TANGENT found.`),!1):!t.getIndices()||(e.warn(`tangents: Skipping primitive ${s} of mesh "${n}": primitives must be unwelded.`),!1):(e.debug(`tangents: Skipping primitive ${s} of mesh "${n}": primitives must have attributes=[POSITION, NORMAL, TEXCOORD_0] and mode=TRIANGLES.`),!1)}const Ft="textureResize";var Ut;!function(t){t.LANCZOS3="lanczos3",t.LANCZOS2="lanczos2"}(Ut||(Ut={}));const Gt={size:[2048,2048],filter:Ut.LANCZOS3,pattern:null};function qt(t=Gt){const e=z({},Gt,t);return 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(`${Ft}: 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=new Uint8Array(s.getImage()),f=await m(u,s.getMimeType()),p=O(new Uint8Array(l*g*4),[l,g,4]);n.debug(`${Ft}: Resizing "${r||t}", ${f.shape} → ${p.shape}...`);try{e.filter===Ut.LANCZOS3?x(f,p):P(f,p)}catch(e){if(e instanceof Error){n.warn(`${Ft}: Failed to resize "${r||t}": "${e.message}".`);continue}throw e}s.setImage((await d(p,s.getMimeType())).buffer)}n.debug(`${Ft}: Complete.`)}}const Bt={};function Vt(t=Bt){return z({},Bt,t),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,Wt(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,Wt(t,s,e,n)),1===t.listParents().length&&t.dispose();t.setIndices(null),1===s.listParents().length&&s.dispose()}}e.debug("unweld: Complete.")}}function Wt(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 Dt={tolerance:1e-4};function Xt(t=Dt){const e=z({},Dt,t);return t=>{const n=t.getLogger();for(const n of t.getRoot().listMeshes())for(const s of n.listPrimitives())0===e.tolerance?Ht(t,s):jt(t,s,e);n.debug("weld: Complete.")}}function Ht(t,e){if(e.getIndices())return;const n=e.listAttributes()[0],s=n.getCount(),r=n.getBuffer(),o=s<=65534?new Uint16Array(3*G(e)):new Uint32Array(3*G(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 jt(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())Zt(e,t,l.get(t)),1===t.listParents().length&&t.dispose();for(const t of e.listTargets())for(const e of t.listAttributes())Zt(t,e,l.get(e)),1===e.listParents().length&&e.dispose();if(a){const t=Kt(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 Kt(t,e){return new(0,t.constructor)(e)}function Zt(t,e,n){const s=n.length*e.getElementSize(),r=Kt(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{mt as QUANTIZE_DEFAULTS,Gt as TEXTURE_RESIZE_DEFAULTS,Ut as TextureResizeFilter,$ as center,v as colorspace,k as dedup,B as inspect,Y as instance,nt as metalRough,it as partition,rt as prune,dt as quantize,Ot as reorder,Nt as resample,Lt as sequence,vt as tangents,qt as textureResize,Vt as unweld,Xt 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{MeshGPUInstancing as h,MaterialsIOR as A,MaterialsSpecular as y,MaterialsPBRSpecularGlossiness as T,MeshQuantization as E}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(new Uint8Array(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")).buffer;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 G="colorspace";function U(t){return $(G,e=>{const n=e.getLogger();if("linear"===t.inputEncoding)return void n.info(`${G}: Vertex colors already linear. Skipping conversion.`);if("sRGB"!==t.inputEncoding)return void n.error(`${G}: 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(`${G}: Complete.`)})}const q={propertyTypes:[n.ACCESSOR,n.MESH,n.TEXTURE,n.MATERIAL]},B=function(t=q){const e=z({},q,t),o=new Set(e.propertyTypes);for(const t of e.propertyTypes)if(!q.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=r.getArray().slice().buffer;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,i.getArray().slice().buffer)&&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(",")}function H(t){return{scenes:W(t),meshes:D(t),materials:j(t),textures:X(t),animations:K(t)}}function W(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:J(s.min),bboxMax:J(s.max)}})}}function D(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+":"+Y(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(Y(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=>Z[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().getLinks().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 X(t){return{properties:t.getRoot().listTextures().map(e=>{const n=e.listParents().filter(t=>"Root"!==t.propertyType).length,s=t.getGraph().listParentLinks(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 K(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 Z=["POINTS","LINES","LINE_LOOP","LINE_STRIP","TRIANGLES","TRIANGLE_STRIP","TRIANGLE_FAN"];function J(t){for(let e=0;e<t.length;e++)t[e].toFixed&&(t[e]=Number(t[e].toFixed(5)));return t}function Y(t){return t.constructor.name.replace("Array","").toLowerCase()}const Q={};function tt(t=Q){return z({},Q,t),$("instance",t=>{const e=t.getLogger(),n=t.getRoot(),s=t.createExtension(h);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=nt(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(),et(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 et(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 nt(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 st={};function rt(t=st){return z({},st,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(A),s=t.createExtension(y),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 ot={propertyTypes:[n.NODE,n.SKIN,n.MESH,n.CAMERA,n.PRIMITIVE,n.PRIMITIVE_TARGET,n.ANIMATION,n.MATERIAL,n.TEXTURE,n.ACCESSOR,n.BUFFER]},it=function(t=ot){const e=z({},ot,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.getLinks().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},ct=(t=at)=>{const e=z({},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(lt(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(lt(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(it({propertyTypes:[n.BUFFER]})),s.debug("partition: Complete.")})};function lt(t,e){let n=`${t}.bin`,s=1;for(;e.has(n);)n=`${t}_${s++}.bin`;return n}const gt=[Int8Array,Int16Array,Int32Array],{TRANSLATION:ut,ROTATION:ft,SCALE:pt,WEIGHTS:mt}=g.TargetPath,dt=[ut,ft,pt],ht={pattern:/.*/,quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeWeight:8,quantizeGeneric:12},At=(t=ht)=>{const e=z({},ht,t);return $("quantize",async t=>{const s=t.getLogger(),r=t.getRoot();let o;t.createExtension(E).setRequired(!0),"scene"===e.quantizationVolume&&(o=Tt(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(wt))));for(const n of t.getRoot().listMeshes()){"mesh"===e.quantizationVolume&&(o=Tt(wt(n))),o&&e.pattern.test("POSITION")&&Et(t,n,o);for(const s of n.listPrimitives()){yt(t,s,o,e);for(const n of s.listTargets())yt(t,n,o,e)}}await t.transform(it({propertyTypes:[n.ACCESSOR,n.SKIN]}),B({propertyTypes:[n.ACCESSOR]})),s.debug("quantize: Complete.")})};function yt(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}=bt(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,Rt(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))}It(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 Tt(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 Et(t,e,n){const s=Rt(n);for(const r of e.listParents())if(r instanceof l){const o=r.listParents().filter(t=>t instanceof g),i=o.some(t=>dt.includes(t.getTargetPath())),a=r.listChildren().length>0;if(r.getSkin()){r.setSkin(St(r.getSkin(),n));continue}let c;a||i?(c=t.createNode("").setMesh(e),r.addChild(c).setMesh(null),o.filter(t=>t.getTargetPath()===mt).forEach(t=>t.setTargetNode(c))):c=r;const l=c.getMatrix();w(l,l,s),c.setMatrix(l)}}function St(t,e){t=t.clone();const n=Rt(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 It(t,e,n){const s=new e(t.getArray().length),r=gt.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 bt(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 wt(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=Mt(e,3);if(n.length>0){const{min:t,max:e}=Mt(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 Mt(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 Rt(t){return I([],[0,0,0,1],t.offset,[t.scale,t.scale,t.scale])}const Nt={tolerance:1e-4},Ct=(t=Nt)=>{const e=z({},Nt,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()),Ot(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 Ot(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 xt={target:"size"};function Pt(e=xt){const s=z({},xt,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 $t(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();zt(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(it({propertyTypes:[n.ACCESSOR]})),i.indicesToAttributes.size?o.debug("reorder: Complete."):o.warn("reorder: No qualifying primitives found; may need to weld first.")})}function zt(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 $t(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 Lt={name:"",fps:10,pattern:/.*/,sort:!0};function vt(t=Lt){const e=z({},Lt,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 _t={overwrite:!1};function kt(t=_t){if(!t.generateTangents)throw new Error('tangents: generateTangents callback required — install "mikktspace".');const e=z({},_t,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(!Gt(l,n,a,i,e.overwrite))continue;const g=Ft(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 T=`${d}|${h}|${A}`;let E=r.get(T);if(E){n.debug(`tangents: Found cache for primitive ${i} of mesh "${a}".`),l.setAttribute("TANGENT",E),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;E=t.createAccessor().setBuffer(S).setArray(I).setType("VEC4"),l.setAttribute("TANGENT",E),r.set(T,E),o++}}o?n.debug("tangents: Complete."):n.warn("tangents: No qualifying primitives found. See debug output.")})}function Ft(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 Gt(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 Ut="textureResize";var qt;!function(t){t.LANCZOS3="lanczos3",t.LANCZOS2="lanczos2"}(qt||(qt={}));const Bt={size:[2048,2048],filter:qt.LANCZOS3,pattern:null};function Vt(t=Bt){const e=z({},Bt,t);return $(Ut,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(`${Ut}: 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=new Uint8Array(s.getImage()),f=await m(u,s.getMimeType()),p=O(new Uint8Array(l*g*4),[l,g,4]);n.debug(`${Ut}: Resizing "${r||t}", ${f.shape} → ${p.shape}...`);try{e.filter===qt.LANCZOS3?x(f,p):P(f,p)}catch(e){if(e instanceof Error){n.warn(`${Ut}: Failed to resize "${r||t}": "${e.message}".`);continue}throw e}s.setImage((await d(p,s.getMimeType())).buffer)}n.debug(`${Ut}: Complete.`)})}const Ht={};function Wt(t=Ht){return z({},Ht,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,Dt(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,Dt(t,s,e,n)),1===t.listParents().length&&t.dispose();t.setIndices(null),1===s.listParents().length&&s.dispose()}}e.debug("unweld: Complete.")})}function Dt(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 Xt(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?Kt(t,s):Zt(t,s,e);n.debug("weld: Complete.")})}function Kt(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 Zt(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())Yt(e,t,l.get(t)),1===t.listParents().length&&t.dispose();for(const t of e.listTargets())for(const e of t.listAttributes())Yt(t,e,l.get(e)),1===e.listParents().length&&e.dispose();if(a){const t=Jt(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 Jt(t,e){return new(0,t.constructor)(e)}function Yt(t,e,n){const s=n.length*e.getElementSize(),r=Jt(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{ht as QUANTIZE_DEFAULTS,Bt as TEXTURE_RESIZE_DEFAULTS,qt as TextureResizeFilter,F as center,U as colorspace,B as dedup,H as inspect,tt as instance,rt as metalRough,ct as partition,it as prune,At as quantize,Pt as reorder,Ct as resample,vt as sequence,kt as tangents,Vt as textureResize,Wt as unweld,Xt as weld};
//# sourceMappingURL=functions.modern.js.map
import { NdArray } from 'ndarray';
import { Primitive, Texture } from '@gltf-transform/core';
import { Primitive, Texture, Transform, TransformContext } from '@gltf-transform/core';
/**
* Prepares a function used in an {@link Document.transform} pipeline. Use of this wrapper is
* optional, and plain functions may be used in transform pipelines just as well. The wrapper is
* used internally so earlier pipeline stages can detect and optimize based on later stages.
*/
export declare function createTransform(name: string, fn: Transform): Transform;
export declare function isTransformPending(context: TransformContext | undefined, initial: string, pending: string): boolean;
/** Maps pixels from source to target textures, with a per-pixel callback. */

@@ -4,0 +11,0 @@ export declare function rewriteTexture(source: Texture, target: Texture, fn: (pixels: NdArray, i: number, j: number) => void): Promise<Texture | null>;

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

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

"dependencies": {
"@gltf-transform/core": "^1.0.1",
"@gltf-transform/extensions": "^1.0.1",
"gl-matrix": "~3.3.0",
"@gltf-transform/core": "^1.1.1",
"@gltf-transform/extensions": "^1.1.1",
"gl-matrix": "~3.4.3",
"ndarray": "^1.0.19",

@@ -45,3 +45,3 @@ "ndarray-lanczos": "^0.1.2",

},
"gitHead": "884969a51a4ad1366c568f6b928a87f0b811452b"
"gitHead": "8d1eba3de55b93e1f3a656f1701c37dea48b3af1"
}
import { Document, Transform, vec3 } from '@gltf-transform/core';
import { bounds } from '@gltf-transform/core';
import { createTransform } from './utils';

@@ -27,3 +28,3 @@ const NAME = 'center';

return (doc: Document): void => {
return createTransform(NAME, (doc: Document): void => {
const logger = doc.getLogger();

@@ -73,4 +74,4 @@ const root = doc.getRoot();

logger.debug(`${NAME}: Complete.`);
};
});
}
};
import { Accessor, Document, Primitive, Transform, vec3 } from '@gltf-transform/core';
import { createTransform } from './utils';

@@ -18,3 +19,3 @@ const NAME = 'colorspace';

return (doc: Document): void => {
return createTransform(NAME, (doc: Document): void => {

@@ -71,4 +72,4 @@ const logger = doc.getLogger();

};
});
}
};
import { Accessor, BufferUtils, Document, Logger, Material, Mesh, Primitive, PrimitiveTarget, PropertyType, Root, Texture, Transform } from '@gltf-transform/core';
import { createTransform } from './utils';
const NAME = 'dedup';
export interface DedupOptions {

@@ -13,7 +12,13 @@ /** List of {@link PropertyType} identifiers to be de-duplicated.*/

const DEDUP_DEFAULTS: Required<DedupOptions> = {
propertyTypes: [PropertyType.ACCESSOR, PropertyType.MESH, PropertyType.TEXTURE],
propertyTypes: [
PropertyType.ACCESSOR,
PropertyType.MESH,
PropertyType.TEXTURE,
PropertyType.MATERIAL,
],
};
/**
* Removes duplicate {@link Accessor}, {@link Mesh}, and {@link Texture} properties. Based on a
* Removes duplicate {@link Accessor}, {@link Mesh}, {@link Texture}, and {@link Material}
* properties. Partially based on a
* [gist by mattdesl](https://gist.github.com/mattdesl/aea40285e2d73916b6b9101b36d84da8). Only

@@ -42,3 +47,3 @@ * accessors in mesh primitives, morph targets, and animation samplers are processed.

return (doc: Document): void => {
return createTransform(NAME, (doc: Document): void => {
const logger = doc.getLogger();

@@ -49,5 +54,6 @@

if (propertyTypes.has(PropertyType.TEXTURE)) dedupImages(logger, doc);
if (propertyTypes.has(PropertyType.MATERIAL)) dedupMaterials(logger, doc);
logger.debug(`${NAME}: Complete.`);
};
});

@@ -206,2 +212,3 @@ };

// Compare each texture to every other texture — O(n²) — and mark duplicates for replacement.
for (let i = 0; i < textures.length; i++) {

@@ -247,2 +254,38 @@ const a = textures[i];

function dedupMaterials(logger: Logger, doc: Document): void {
const root = doc.getRoot();
const materials = root.listMaterials();
const duplicates: Map<Material, Material> = new Map();
// Compare each material to every other material — O(n²) — and mark duplicates for replacement.
for (let i = 0; i < materials.length; i++){
const a = materials[i];
if (duplicates.has(a)) continue;
for (let j = 0; j < materials.length; j++){
const b = materials[j];
if (a === b) continue;
if (duplicates.has(b)) continue;
if (a.equals(b)) {
duplicates.set(b, a);
}
}
}
logger.debug(
// eslint-disable-next-line max-len
`${NAME}: Found ${duplicates.size} duplicates among ${root.listMaterials().length} materials.`
);
Array.from(duplicates.entries()).forEach(([src, dst]) => {
src.listParents().forEach((property) => {
if (!(property instanceof Root)) property.swap(src, dst);
});
src.dispose();
});
}
/** Generates a key unique to the content of a primitive or target. */

@@ -249,0 +292,0 @@ function createPrimitiveKey(

import { Document, Logger, MathUtils, Mesh, Node, Transform, vec3, vec4 } from '@gltf-transform/core';
import { InstancedMesh, MeshGPUInstancing } from '@gltf-transform/extensions';
import { createTransform } from './utils';

@@ -19,3 +20,3 @@ const NAME = 'instance';

return (doc: Document): void => {
return createTransform(NAME, (doc: Document): void => {
const logger = doc.getLogger();

@@ -101,3 +102,3 @@ const root = doc.getRoot();

logger.debug(`${NAME}: Complete.`);
};
});

@@ -104,0 +105,0 @@ }

import { Document, Texture, Transform } from '@gltf-transform/core';
import { MaterialsIOR, MaterialsPBRSpecularGlossiness, MaterialsSpecular, PBRSpecularGlossiness } from '@gltf-transform/extensions';
import { rewriteTexture } from './utils';
import { createTransform, rewriteTexture } from './utils';

@@ -24,17 +24,15 @@ const NAME = 'metalRough';

return async (doc: Document): Promise<void> => {
return createTransform(NAME, async (doc: Document): Promise<void> => {
const logger = doc.getLogger();
const extensionName = MaterialsPBRSpecularGlossiness.EXTENSION_NAME;
const extensionsUsed = doc.getRoot().listExtensionsUsed().map((ext) => ext.extensionName);
if (!extensionsUsed.includes(extensionName)) {
logger.warn(`${NAME}: Extension ${extensionName} not found on given document.`);
if (!extensionsUsed.includes('KHR_materials_pbrSpecularGlossiness')) {
logger.warn(`${NAME}: KHR_materials_pbrSpecularGlossiness not found on document.`);
return;
}
const iorExtension = doc.createExtension(MaterialsIOR) as MaterialsIOR;
const specExtension = doc.createExtension(MaterialsSpecular) as MaterialsSpecular;
const specGlossExtension = doc.createExtension(MaterialsPBRSpecularGlossiness) as
MaterialsPBRSpecularGlossiness;
const iorExtension = doc.createExtension(MaterialsIOR);
const specExtension = doc.createExtension(MaterialsSpecular);
const specGlossExtension = doc.createExtension(MaterialsPBRSpecularGlossiness);

@@ -44,4 +42,4 @@ const inputTextures = new Set<Texture | null>();

for (const material of doc.getRoot().listMaterials()) {
const specGloss = material.getExtension('KHR_materials_pbrSpecularGlossiness') as
PBRSpecularGlossiness;
const specGloss = material
.getExtension<PBRSpecularGlossiness>('KHR_materials_pbrSpecularGlossiness');
if (!specGloss) continue;

@@ -124,4 +122,4 @@

};
});
}
import { Document, Logger, PropertyType, Transform } from '@gltf-transform/core';
import { prune } from './prune';
import { createTransform } from './utils';

@@ -35,3 +36,3 @@ const NAME = 'partition';

return async (doc: Document): Promise<void> => {
return createTransform(NAME, async (doc: Document): Promise<void> => {
const logger = doc.getLogger();

@@ -49,3 +50,3 @@

logger.debug(`${NAME}: Complete.`);
};
});

@@ -52,0 +53,0 @@ };

import { AnimationChannel, Document, Graph, Property, PropertyType, Root, Transform } from '@gltf-transform/core';
import { createTransform } from './utils';

@@ -47,3 +48,3 @@ const NAME = 'prune';

return (doc: Document): void => {
return createTransform(NAME, (doc: Document): void => {
const logger = doc.getLogger();

@@ -143,4 +144,4 @@ const root = doc.getRoot();

};
});
};

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

import { Accessor, AnimationChannel, bbox, Document, Logger, mat4, Mesh, Node, Primitive, PrimitiveTarget, PropertyType, Skin, Transform, vec2, vec3, vec4 } from '@gltf-transform/core';
import {
Accessor,
AnimationChannel,
bbox,
Document,
Logger,
mat4,
Mesh,
Node,
Primitive,
PrimitiveTarget,
PropertyType,
Skin,
Transform,
vec2,
vec3,
vec4,
} from '@gltf-transform/core';
import { dedup } from './dedup';

@@ -7,6 +24,8 @@ import { fromRotationTranslationScale, fromScaling, invert, multiply as multiplyMat4 } from 'gl-matrix/mat4';

import { prune } from './prune';
import { createTransform } from './utils';
const NAME = 'quantize';
type TypedArrayConstructor = Int8ArrayConstructor
type TypedArrayConstructor =
| Int8ArrayConstructor
| Int16ArrayConstructor

@@ -40,3 +59,3 @@ | Uint8ArrayConstructor

export const QUANTIZE_DEFAULTS: Required<QuantizeOptions> = {
export const QUANTIZE_DEFAULTS: Required<QuantizeOptions> = {
pattern: /.*/,

@@ -65,6 +84,5 @@ quantizationVolume: 'mesh',

const quantize = (_options: QuantizeOptions = QUANTIZE_DEFAULTS): Transform => {
const options = { ...QUANTIZE_DEFAULTS, ..._options } as Required<QuantizeOptions>;
const options = {...QUANTIZE_DEFAULTS, ..._options} as Required<QuantizeOptions>;
return async (doc: Document): Promise<void> => {
return createTransform(NAME, async (doc: Document): Promise<void> => {
const logger = doc.getLogger();

@@ -78,5 +96,3 @@ const root = doc.getRoot();

if (options.quantizationVolume === 'scene') {
nodeTransform = getNodeTransform(
expandBounds(root.listMeshes().map(getPositionQuantizationVolume))
);
nodeTransform = getNodeTransform(expandBounds(root.listMeshes().map(getPositionQuantizationVolume)));
}

@@ -103,16 +119,16 @@

await doc.transform(
prune({propertyTypes: [PropertyType.ACCESSOR, PropertyType.SKIN]}),
dedup({propertyTypes: [PropertyType.ACCESSOR]}),
prune({ propertyTypes: [PropertyType.ACCESSOR, PropertyType.SKIN] }),
dedup({ propertyTypes: [PropertyType.ACCESSOR] })
);
logger.debug(`${NAME}: Complete.`);
};
});
};
function quantizePrimitive(
doc: Document,
prim: Primitive | PrimitiveTarget,
nodeTransform: VectorTransform<vec3>,
options: Required<QuantizeOptions>): void {
doc: Document,
prim: Primitive | PrimitiveTarget,
nodeTransform: VectorTransform<vec3>,
options: Required<QuantizeOptions>
): void {
const logger = doc.getLogger();

@@ -124,3 +140,3 @@

const srcAttribute = prim.getAttribute(semantic)!;
const {bits, ctor} = getQuantizationSettings(semantic, srcAttribute, logger, options);
const { bits, ctor } = getQuantizationSettings(semantic, srcAttribute, logger, options);

@@ -157,6 +173,8 @@ if (!ctor) continue;

if (prim instanceof Primitive
&& prim.getIndices()
&& prim.listAttributes().length
&& prim.listAttributes()[0]!.getCount() < 65535) {
if (
prim instanceof Primitive &&
prim.getIndices() &&
prim.listAttributes().length &&
prim.listAttributes()[0]!.getCount() < 65535
) {
const indices = prim.getIndices()!;

@@ -169,3 +187,3 @@ indices.setArray(new Uint16Array(indices.getArray()!));

function getNodeTransform(volume: bbox): VectorTransform<vec3> {
const {min, max} = volume;
const { min, max } = volume;

@@ -177,3 +195,3 @@ // Scaling factor transforms [-1,1] box to the mesh AABB in local space.

(max[1] - min[1]) / 2,
(max[2] - min[2]) / 2,
(max[2] - min[2]) / 2
);

@@ -188,18 +206,14 @@

return {offset, scale};
return { offset, scale };
}
/** Applies corrective scale and offset to nodes referencing a quantized Mesh. */
function transformMeshParents(
doc: Document,
mesh: Mesh,
nodeTransform: VectorTransform<vec3>
): void {
function transformMeshParents(doc: Document, mesh: Mesh, nodeTransform: VectorTransform<vec3>): void {
const transformMatrix = fromTransform(nodeTransform);
for (const parent of mesh.listParents()) {
if (parent instanceof Node) {
const animChannels = parent.listParents()
const animChannels = parent
.listParents()
.filter((p) => p instanceof AnimationChannel) as AnimationChannel[];
const isAnimated = animChannels
.some((channel) => TRS_CHANNELS.includes(channel.getTargetPath()!));
const isAnimated = animChannels.some((channel) => TRS_CHANNELS.includes(channel.getTargetPath()!));
const isParentNode = parent.listChildren().length > 0;

@@ -252,8 +266,3 @@

*/
function quantizeAttribute(
attribute: Accessor,
ctor: TypedArrayConstructor,
bits: number
): void {
function quantizeAttribute(attribute: Accessor, ctor: TypedArrayConstructor, bits: number): void {
const dstArray = new ctor(attribute.getArray()!.length);

@@ -287,7 +296,7 @@

function getQuantizationSettings(
semantic: string,
attribute: Accessor,
logger: Logger,
options: Required<QuantizeOptions>): {bits: number; ctor?: TypedArrayConstructor} {
semantic: string,
attribute: Accessor,
logger: Logger,
options: Required<QuantizeOptions>
): { bits: number; ctor?: TypedArrayConstructor } {
const min = attribute.getMinNormalized([]);

@@ -309,5 +318,5 @@ const max = attribute.getMaxNormalized([]);

} else if (semantic.startsWith('TEXCOORD_')) {
if (min.some(v => v < 0) || max.some(v => v > 1)) {
if (min.some((v) => v < 0) || max.some((v) => v > 1)) {
logger.warn(`${NAME}: Skipping ${semantic}; out of [0,1] range.`);
return {bits: -1};
return { bits: -1 };
}

@@ -322,7 +331,7 @@ bits = options.quantizeTexcoord;

}
return {bits: -1};
return { bits: -1 };
} else if (semantic.startsWith('WEIGHTS_')) {
if (min.some(v => v < 0) || max.some(v => v > 1)) {
if (min.some((v) => v < 0) || max.some((v) => v > 1)) {
logger.warn(`${NAME}: Skipping ${semantic}; out of [0,1] range.`);
return {bits: -1};
return { bits: -1 };
}

@@ -332,8 +341,8 @@ bits = options.quantizeWeight;

} else if (semantic.startsWith('_')) {
if (min.some(v => v < -1) || max.some(v => v > 1)) {
if (min.some((v) => v < -1) || max.some((v) => v > 1)) {
logger.warn(`${NAME}: Skipping ${semantic}; out of [-1,1] range.`);
return {bits: -1};
return { bits: -1 };
}
bits = options.quantizeGeneric;
ctor = min.some(v => v < 0)
ctor = min.some((v) => v < 0)
? (ctor = bits <= 8 ? Int8Array : Int16Array)

@@ -345,3 +354,3 @@ : (ctor = bits <= 8 ? Uint8Array : Uint16Array);

return {bits, ctor};
return { bits, ctor };
}

@@ -372,3 +381,3 @@

if (relativePositions.length > 0) {
const {min: relMin, max: relMax} = flatBounds<vec3>(relativePositions, 3);
const { min: relMin, max: relMax } = flatBounds<vec3>(relativePositions, 3);
min(bbox.min, bbox.min, min(relMin, scale(relMin, relMin, 2), [0, 0, 0]));

@@ -382,3 +391,3 @@ max(bbox.max, bbox.max, max(relMax, scale(relMax, relMax, 2), [0, 0, 0]));

/** Computes total min and max of all Accessors in a list. */
function flatBounds<T = vec2|vec3>(accessors: Accessor[], elementSize: number): ({min: T, max: T}) {
function flatBounds<T = vec2 | vec3>(accessors: Accessor[], elementSize: number): { min: T; max: T } {
const min: number[] = new Array(elementSize).fill(Infinity);

@@ -399,3 +408,3 @@ const max: number[] = new Array(elementSize).fill(-Infinity);

return {min, max} as unknown as {min: T, max: T};
return { min, max } as unknown as { min: T; max: T };
}

@@ -412,3 +421,3 @@

interface VectorTransform<T = vec2|vec3|vec4> {
interface VectorTransform<T = vec2 | vec3 | vec4> {
offset: T;

@@ -419,8 +428,7 @@ scale: number;

function fromTransform(transform: VectorTransform<vec3>): mat4 {
return fromRotationTranslationScale(
[] as unknown as mat4,
[0, 0, 0, 1],
transform.offset,
[transform.scale, transform.scale, transform.scale],
) as mat4;
return fromRotationTranslationScale([] as unknown as mat4, [0, 0, 0, 1], transform.offset, [
transform.scale,
transform.scale,
transform.scale,
]) as mat4;
}

@@ -427,0 +435,0 @@

import { Accessor, Document, GLTF, Primitive, PropertyType, Transform } from '@gltf-transform/core';
import { prune } from './prune';
import { SetMap } from './utils';
import { createTransform, SetMap } from './utils';
import type { MeshoptEncoder } from 'meshoptimizer';

@@ -49,3 +49,3 @@

return async (doc: Document): Promise<void> => {
return createTransform(NAME, async (doc: Document): Promise<void> => {
const logger = doc.getLogger();

@@ -99,3 +99,3 @@

}
};
});
}

@@ -102,0 +102,0 @@

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

import { Accessor, AnimationSampler, Document, Root, Transform } from '@gltf-transform/core';
import { Accessor, AnimationSampler, Document, Root, Transform, TransformContext } from '@gltf-transform/core';
import { createTransform, isTransformPending } from './utils';

@@ -20,3 +21,3 @@ const NAME = 'resample';

return (doc: Document): void => {
return createTransform(NAME, (doc: Document, context?: TransformContext): void => {
const accessorsVisited = new Set<Accessor>();

@@ -56,3 +57,3 @@ const accessorsCountPrev = doc.getRoot().listAccessors().length;

if (doc.getRoot().listAccessors().length > accessorsCountPrev) {
if (doc.getRoot().listAccessors().length > accessorsCountPrev && !isTransformPending(context, NAME, 'dedup')) {
logger.warn(

@@ -69,3 +70,3 @@ `${NAME}: Resampling required copying accessors, some of which may be duplicates.`

logger.debug(`${NAME}: Complete.`);
};
});

@@ -72,0 +73,0 @@ };

import { Accessor, AnimationChannel, AnimationSampler, Document, Transform } from '@gltf-transform/core';
import { createTransform } from './utils';

@@ -29,3 +30,3 @@ const NAME = 'sequence';

return (doc: Document): void => {
return createTransform(NAME, (doc: Document): void => {

@@ -84,4 +85,4 @@ const logger = doc.getLogger();

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

@@ -45,3 +46,3 @@ const NAME = 'tangents';

return (doc: Document): void => {
return createTransform(NAME, (doc: Document): void => {
const logger = doc.getLogger();

@@ -121,3 +122,3 @@ const attributeIDs = new Map<TypedArray, string>();

}
};
});
}

@@ -124,0 +125,0 @@

@@ -5,2 +5,3 @@ import ndarray from 'ndarray';

import { Document, Transform, vec2 } from '@gltf-transform/core';
import { createTransform } from './utils';

@@ -44,3 +45,3 @@ const NAME = 'textureResize';

return async (doc: Document): Promise<void> => {
return createTransform(NAME, async (doc: Document): Promise<void> => {

@@ -110,4 +111,4 @@ const logger = doc.getLogger();

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

@@ -22,3 +23,3 @@ const NAME = 'unweld';

return (doc: Document): void => {
return createTransform(NAME, (doc: Document): void => {

@@ -64,3 +65,3 @@ const logger = doc.getLogger();

logger.debug(`${NAME}: Complete.`);
};
});
}

@@ -67,0 +68,0 @@

import { NdArray } from 'ndarray';
import { getPixels, savePixels } from 'ndarray-pixels';
import { Primitive, Texture } from '@gltf-transform/core';
import { Primitive, Texture, Transform, TransformContext } from '@gltf-transform/core';
/**
* Prepares a function used in an {@link Document.transform} pipeline. Use of this wrapper is
* optional, and plain functions may be used in transform pipelines just as well. The wrapper is
* used internally so earlier pipeline stages can detect and optimize based on later stages.
*/
export function createTransform(name: string, fn: Transform): Transform {
Object.defineProperty(fn, 'name', { value: name });
return fn;
}
export function isTransformPending(context: TransformContext | undefined, initial: string, pending: string): boolean {
if (!context) return false;
const initialIndex = context.stack.lastIndexOf(initial);
const pendingIndex = context.stack.lastIndexOf(pending);
return initialIndex < pendingIndex;
}
/** Maps pixels from source to target textures, with a per-pixel callback. */

@@ -6,0 +23,0 @@ export async function rewriteTexture(

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

@@ -20,3 +20,3 @@ const NAME = 'weld';

return (doc: Document): void => {
return createTransform(NAME, (doc: Document): void => {
const logger = doc.getLogger();

@@ -35,3 +35,3 @@

logger.debug(`${NAME}: Complete.`);
};
});
}

@@ -38,0 +38,0 @@

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