@gltf-transform/functions
Advanced tools
Comparing version 0.12.8 to 0.12.9
@@ -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("ndarray"),o=require("ndarray-lanczos");function a(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=a(i);function u(){return(u=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 l(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 f(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 l(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)?l(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 c="center",g={pivot:"center"},p={propertyTypes:[e.PropertyType.ACCESSOR,e.PropertyType.MESH,e.PropertyType.TEXTURE]},d=function(t){void 0===t&&(t=p);for(var r,n=u({},p,t),i=new Set(n.propertyTypes),o=f(n.propertyTypes);!(r=o()).done;){var a=r.value;if(!p.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=r.getRoot().listMeshes();function a(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}o.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)})});var s=a(Array.from(n));t.debug("dedup: Found "+s.size+" duplicates among "+n.size+" indices.");var u=a(Array.from(i));t.debug("dedup: Found "+u.size+" duplicates among "+i.size+" attributes."),o.forEach(function(e){e.listPrimitives().forEach(function(e){e.listAttributes().forEach(function(t){u.has(t)&&e.swap(t,u.get(t))});var t=e.getIndices();t&&s.has(t)&&e.swap(t,s.get(t))})}),Array.from(s.keys()).forEach(function(e){return e.dispose()}),Array.from(u.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){i.set(e,t)});for(var o,a=n.listMeshes().length,s=new Map,u=function(){for(var t,r=o.value,n=[],a=f(r.listPrimitives());!(t=a()).done;){for(var u,l=t.value,c=[],g=f(l.listSemantics());!(u=g()).done;){var p=u.value,d=l.getAttribute(p);c.push(p+":"+i.get(d))}var v=l.getIndices();v&&c.push("indices:"+i.get(v)),n.push(c.join(","))}var m=n.join(";");if(s.has(m)){var h=s.get(m);r.listParents().forEach(function(t){t.propertyType!==e.PropertyType.ROOT&&t.swap(r,h)}),r.dispose()}else s.set(m,r)},l=f(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.")}},v=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 m(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 h=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 y(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:I(n.min),bboxMax:I(n.max)}})}}function A(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=f(e.listSemantics());!(t=s()).done;){var u=t.value,l=e.getAttribute(u);i.add(u+":"+P(l.getArray())),a.add(l)}for(var c,g=f(e.listTargets());!(c=g()).done;)c.value.listAttributes().forEach(function(e){return a.add(e)});var p=e.getIndices();p&&(o.add(P(p.getArray())),a.add(p)),n+=e.listAttributes()[0].getCount(),r+=m(e)});var s=0;Array.from(a).forEach(function(e){return s+=e.getArray().byteLength});var u=e.listPrimitives().map(function(e){return b[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 T(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 E(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 S(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 b=["POINTS","LINES","LINE_LOOP","LINE_STRIP","TRIANGLES","TRIANGLE_STRIP","TRIANGLE_FAN"];function I(e){for(var t=0;t<e.length;t++)e[t].toFixed&&(e[t]=Number(e[t].toFixed(5)));return e}function P(e){return e.constructor.name.replace("Array","").toLowerCase()}var w="instance",M={};function R(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(w+": Removed "+i+" unused nodes.")}function N(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 C="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function x(e,t,r){if(!e.s){if(r instanceof O){if(!r.s)return void(r.o=x.bind(null,e,t));1&t&&(t=r.s),r=r.v}if(r&&r.then)return void r.then(x.bind(null,e,t),x.bind(null,e,2));e.s=t,e.v=r;var n=e.o;n&&n(e)}}var O=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{x(n,1,o(this.v))}catch(e){x(n,2,e)}return n}return this}return this.o=function(e){try{var i=e.v;1&e.s?x(n,1,t?t(i):i):r?x(n,1,r(i)):x(n,2,i)}catch(e){x(n,2,e)}},n},e}();function z(e){return e instanceof O&&1&e.s}var L={},U={propertyTypes:[e.PropertyType.NODE,e.PropertyType.SKIN,e.PropertyType.MESH,e.PropertyType.CAMERA,e.PropertyType.PRIMITIVE,e.PropertyType.PRIMITIVE_TARGET,e.PropertyType.ANIMATION,e.PropertyType.MATERIAL,e.PropertyType.TEXTURE,e.PropertyType.ACCESSOR,e.PropertyType.BUFFER]},F=function(t){void 0===t&&(t=U);var r=u({},U,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=f(i.listAnimations());!(s=u()).done;){for(var l,c=s.value,g=f(c.listChannels());!(l=g()).done;){var p=l.value;p.getTargetNode()||(p.dispose(),y(p))}if(c.listChannels().length)c.listSamplers().forEach(m);else{var d=c.listSamplers();m(c),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.")}},_="partition",k={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 G="quantize",q=[Int8Array,Int16Array,Int32Array],j={excludeAttributes:[],quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeWeight:8,quantizeGeneric:12};function V(t,r,n,i){for(var o,a=t.getLogger(),s=f(r.listSemantics());!(o=s()).done;){var u=o.value;if(!i.excludeAttributes.includes(u)){var l=r.getAttribute(u),c=Q(u,l,a,i),g=c.bits,p=c.ctor;if(p){if(g<8||g>16)throw new Error(G+": Requires bits = 8–16.");if(!(l.getComponentSize()<=g/8)){var d=l.clone();if("POSITION"===u)for(var v=0,m=[0,0,0],h=d.getCount();v<h;v++)d.setElement(v,n.remap(d.getElement(v,m)));Z(d,p,g),r.swap(l,d)}}}}if(r instanceof e.Primitive&&r.getIndices()&&r.listAttributes().length&&r.listAttributes()[0].getCount()<65535){var y=r.getIndices();y.setArray(new Uint16Array(y.getArray()))}}function D(e,t){for(var r,n=new Array(t).fill(Infinity),i=new Array(t).fill(-Infinity),o=[],a=[],s=f(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 W(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),i=[t[0]+(r[0]-t[0])/2,t[1]+(r[1]-t[1])/2,t[2]+(r[2]-t[2])/2];return{remap:function(e){return[(e[0]-i[0])/n,(e[1]-i[1])/n,(e[2]-i[2])/n]},offset:i,scale:n}}function X(e){for(var t,r=[],n=f(e.listPrimitives());!(t=n()).done;){var i=t.value,o=i.getAttribute("POSITION");o&&r.push(o);for(var a,s=f(i.listTargets());!(a=s()).done;){var u=a.value.getAttribute("POSITION");u&&r.push(u)}}if(0===r.length)throw new Error(G+': Missing "POSITION" attribute.');return r}function H(t,r,i){for(var o,a=J(i),s=f(r.listParents());!(o=s()).done;){var u=o.value;if(u instanceof e.Node){var l=u.listChildren().length>0,c=!!u.listParents().find(function(t){return t instanceof e.Animation});if(u.getSkin()){u.setSkin(K(u.getSkin(),i));continue}var g=void 0;l||c?(g=t.createNode("").setMesh(r),u.addChild(g).setMesh(null)):g=u;var p=g.getMatrix();n.multiply(p,p,a),g.setMatrix(p)}}}function K(e,t){e=e.clone();for(var r=J(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 Z(e,t,r){for(var n=new t(e.getArray().length),i=q.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 Q(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(G+": 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(G+": Skipping "+e+"; out of [0,1] range."),{bits:-1};o=(i=n.quantizeWeight)<=8?Uint8Array:Uint16Array}else{if(!e.startsWith("_"))throw new Error(G+': Unexpected semantic, "'+e+'".');if(a.some(function(e){return e<-1})||s.some(function(e){return e>1}))return r.warn(G+": 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 J(e){return n.fromRotationTranslationScale([],[0,0,0,1],e.offset,[e.scale,e.scale,e.scale])}var Y={tolerance:1e-4};function $(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 ee={target:"size"};function te(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 re(e){for(var t,r=[],n=f(e.listAttributes());!(t=n()).done;)r.push(t.value);for(var i,o=f(e.listTargets());!(i=o()).done;)for(var a,s=f(i.value.listAttributes());!(a=s()).done;)r.push(a.value);return Array.from(new Set(r))}var ne={name:"",fps:10,pattern:/.*/,sort:!0},ie="tangents",oe={overwrite:!1};function ae(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(ie+": Skipping primitive "+i+' of mesh "'+n+'": TANGENT found.'),!1):!t.getIndices()||(r.warn(ie+": Skipping primitive "+i+' of mesh "'+n+'": primitives must be unwelded.'),!1):(r.debug(ie+": Skipping primitive "+i+' of mesh "'+n+'": primitives must have attributes=[POSITION, NORMAL, TEXCOORD_0] and mode=TRIANGLES.'),!1)}var se="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function ue(e,t,r){if(!e.s){if(r instanceof le){if(!r.s)return void(r.o=ue.bind(null,e,t));1&t&&(t=r.s),r=r.v}if(r&&r.then)return void r.then(ue.bind(null,e,t),ue.bind(null,e,2));e.s=t,e.v=r;var n=e.o;n&&n(e)}}var le=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{ue(n,1,o(this.v))}catch(e){ue(n,2,e)}return n}return this}return this.o=function(e){try{var i=e.v;1&e.s?ue(n,1,t?t(i):i):r?ue(n,1,r(i)):ue(n,2,i)}catch(e){ue(n,2,e)}},n},e}();function fe(e){return e instanceof le&&1&e.s}var ce,ge="textureResize";(ce=exports.TextureResizeFilter||(exports.TextureResizeFilter={})).LANCZOS3="lanczos3",ce.LANCZOS2="lanczos2";var pe={size:[2048,2048],filter:exports.TextureResizeFilter.LANCZOS3,pattern:null},de={};function ve(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 me={tolerance:1e-4};function he(t,r){if(!r.getIndices()){for(var n=r.listAttributes()[0],i=n.getCount(),o=n.getBuffer(),a=i<=65534?new Uint16Array(3*m(r)):new Uint32Array(3*m(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 ye(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 c=[],g=0,p=0;p<u;p++){for(var d,v=s?s.getScalar(p):p,m=[],h=[],y=f(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)c.push(a[E]);else{for(var S,b=f(t.listAttributes());!(S=b()).done;){var I=S.value;l.get(I).push(I.getElement(v,[]))}for(var P,w=f(t.listTargets());!(P=w()).done;)for(var M,R=f(P.value.listAttributes());!(M=R()).done;){var N=M.value;l.get(N).push(N.getElement(v,[]))}a[E]=g,c.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=f(t.listAttributes());!(O=z()).done;){var L=O.value;Te(t,L,l.get(L)),1===L.listParents().length&&L.dispose()}for(var U,F=f(t.listTargets());!(U=F()).done;)for(var _,k=U.value,B=f(k.listAttributes());!(_=B()).done;){var G=_.value;Te(k,G,l.get(G)),1===G.listParents().length&&G.dispose()}if(s){var q=Ae(s.getArray(),c.length);q.set(c),t.setIndices(s.clone().setArray(q)),1===s.listParents().length&&s.dispose()}else{var j=C<=65534?new Uint16Array(c):new Uint32Array(c);t.setIndices(e.createAccessor().setArray(j))}}function Ae(e,t){return new(0,e.constructor)(t)}function Te(e,t,r){for(var n=r.length*t.getElementSize(),i=Ae(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=j,exports.TEXTURE_RESIZE_DEFAULTS=pe,exports.center=function(t){void 0===t&&(t=g);var r=u({},g,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(c+": 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(c+': Pivot "'+u.join(", ")+'".');var f=[-1*u[0],-1*u[1],-1*u[2]];if(o){n.debug(c+": Model contains animation or skin. Adding a wrapper node.");var g=t.createNode("Pivot").setTranslation(f);a.listChildren().forEach(function(e){return g.addChild(e)}),a.addChild(g)}else n.debug(c+": 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(c+": 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:y(e),meshes:A(e),materials:T(e),textures:E(e),animations:S(e)}},exports.instance=function(t){return void 0===t&&(t=M),u({},M,t),function(t){var n=t.getLogger(),i=t.getRoot(),o=t.createExtension(r.MeshGPUInstancing);if(i.listAnimations().length)throw new Error(w+": 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=N(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(),R(l,n),s++,u+=p.length}}},c=f(i.listScenes());!(a=c()).done;)l();s>0?n.info(w+": Created "+s+" batches, with "+u+" total instances."):(n.info(w+": No meshes with multiple parent nodes were found."),o.dispose()),n.debug(w+": Complete.")}},exports.metalRough=function(e){return void 0===e&&(e=L),u({},L,e),function(e){try{var t=function(){s.dispose();for(var e,t=f(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[C]){var n,i,o,a=e[C]();if(function e(r){try{for(;!(n=a.next()).done;)if((r=t(n.value))&&r.then){if(!z(r))return void r.then(e,o||(o=x.bind(null,i=new O,2)));r=r.v}i?x(i,1,r):i=r}catch(e){x(i||(i=new O),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(!z(a))return void a.then(r,i||(i=x.bind(null,n=new O,2)));a=a.v}n?x(n,1,a):n=a}catch(e){x(n||(n=new O),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(v(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(v(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=k);var r=u({},k,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(_+': 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(_+": 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(_+': 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(_+": Skipping animation #"+o+' with name "'+i.getName()+'".')})}(t,n,r),r.meshes||r.animations||n.warn(_+": Select animations or meshes to create a partition."),Promise.resolve(t.transform(F({propertyTypes:[e.PropertyType.BUFFER]}))).then(function(){n.debug(_+": Complete.")})}catch(e){return Promise.reject(e)}}},exports.prune=F,exports.quantize=function(t){void 0===t&&(t=j);var n=u({},j,t);return function(t){try{var i=t.getLogger(),o=t.getRoot();t.createExtension(r.MeshQuantization).setRequired(!0);var a=void 0;if("scene"===n.quantizationVolume){for(var s,u=[],l=f(o.listMeshes());!(s=l()).done;)u.push.apply(u,X(s.value));a=W(D(u,3))}for(var c,g=f(t.getRoot().listMeshes());!(c=g()).done;){var p=c.value;"mesh"===n.quantizationVolume&&(a=W(D(X(p),3))),a&&!n.excludeAttributes.includes("POSITION")&&H(t,p,a);for(var v,m=f(p.listPrimitives());!(v=m()).done;){var h=v.value;V(t,h,a,n);for(var y,A=f(h.listTargets());!(y=A()).done;)V(t,y.value,a,n)}}return Promise.resolve(t.transform(F({propertyTypes:[e.PropertyType.ACCESSOR,e.PropertyType.SKIN]}),d({propertyTypes:[e.PropertyType.ACCESSOR]}))).then(function(){i.debug(G+": Complete.")})}catch(e){return Promise.reject(e)}}},exports.reorder=function(t){void 0===t&&(t=ee);var r=u({},ee,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 h,n=new Map,i=new h,o=f(e.getRoot().listMeshes());!(t=o()).done;)for(var a,s=f(t.value.listPrimitives());!(a=s()).done;){var u=a.value,l=u.getIndices();if(l){n.set(l,u.getMode());for(var c,g=f(re(u));!(c=g()).done;){var p=c.value;r.add(l,p),i.add(p,u)}}}return{indicesToAttributes:r,indicesToMode:n,attributesToPrimitives:i}}(t),s=f(a.indicesToAttributes.keys());!(o=s()).done;){var u=o.value,l=u.clone(),c=l.getArray().slice();c instanceof Uint32Array||(c=new Uint32Array(c));var g=n.reorderMesh(c,a.indicesToMode.get(u)===e.Primitive.Mode.TRIANGLES,"size"===r.target),p=g[0],d=g[1];l.setArray(d<=65534?new Uint16Array(c):c);for(var v,m=f(a.indicesToAttributes.get(u));!(v=m()).done;){var y=v.value,A=y.clone();te(A,p,d);for(var T,E=f(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=f(S.listTargets());!(b=I()).done;)b.value.swap(y,A)}}}}return Promise.resolve(t.transform(F({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=Y);var r=u({},Y,t);return function(t){for(var n,i=new Set,o=t.getRoot().listAccessors().length,a=t.getLogger(),s=!1,u=f(t.getRoot().listAnimations());!(n=u()).done;){for(var l,c=n.value,g=new Set,p=f(c.listChannels());!(l=p()).done;){var d=l.value;d.getSampler()&&"weights"===d.getTargetPath()&&g.add(d.getSampler())}for(var v,m=f(c.listSamplers());!(v=m()).done;){var h=v.value;g.has(h)?s=!0:"STEP"!==h.getInterpolation()&&"LINEAR"!==h.getInterpolation()||(i.add(h.getInput()),i.add(h.getOutput()),$(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=ne);var r=u({},ne,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=oe),!t.generateTangents)throw new Error(ie+': generateTangents callback required — install "mikktspace".');var r=u({},oe,t);return function(t){for(var n,i=t.getLogger(),o=new Map,a=new Map,s=0,u=f(t.getRoot().listMeshes());!(n=u()).done;)for(var l=n.value,c=l.getName(),g=l.listPrimitives(),p=0;p<g.length;p++){var d=g[p];if(ae(d,i,c,p,r.overwrite)){var v=d.getAttribute("POSITION").getArray(),m=d.getAttribute("NORMAL").getArray(),h=d.getAttribute("TEXCOORD_0").getArray(),y=o.get(v)||e.uuid();o.set(v,y);var A=o.get(m)||e.uuid();o.set(m,A);var T=o.get(h)||e.uuid();o.set(h,T);var E=d.getAttribute("TANGENT");E&&2===E.listParents().length&&E.dispose();var S=y+"|"+A+"|"+T,b=a.get(S);if(b)i.debug(ie+": Found cache for primitive "+p+' of mesh "'+c+'".'),d.setAttribute("TANGENT",b),s++;else{i.debug(ie+": Generating for primitive "+p+' of mesh "'+c+'".');for(var I=d.getAttribute("POSITION").getBuffer(),P=r.generateTangents(v instanceof Float32Array?v:new Float32Array(v),m instanceof Float32Array?m:new Float32Array(m),h instanceof Float32Array?h:new Float32Array(h)),w=3;w<P.length;w+=4)P[w]*=-1;b=t.createAccessor().setBuffer(I).setArray(P).setType("VEC4"),d.setAttribute("TANGENT",b),a.set(S,b),s++}}}s?i.debug(ie+": Complete."):i.warn(ie+": No qualifying primitives found. See debug output.")}},exports.textureResize=function(e){void 0===e&&(e=pe);var r=u({},pe,e);return function(e){try{var n=function(){i.debug(ge+": Complete.")},i=e.getLogger(),a=function(e,t,r){if("function"==typeof e[se]){var n,i,o,a=e[se]();if(function e(r){try{for(;!(n=a.next()).done;)if((r=t(n.value))&&r.then){if(!fe(r))return void r.then(e,o||(o=ue.bind(null,i=new le,2)));r=r.v}i?ue(i,1,r):i=r}catch(e){ue(i||(i=new le),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(!fe(a))return void a.then(r,i||(i=ue.bind(null,n=new le,2)));a=a.v}n?ue(n,1,a):n=a}catch(e){ue(n||(n=new le),2,e)}}(),n}(u,function(e){return t(u[e])})}(e.getRoot().listTextures(),function(e){var n=e.getName(),a=e.getURI();if(!r.pattern||r.pattern.test(n)||r.pattern.test(a))if("image/png"===e.getMimeType()||"image/jpeg"===e.getMimeType()){var u=r.size,l=u[0],f=u[1],c=e.getSize(),g=c[0],p=c[1];if(!(g<=l&&p<=f)){var d=g,v=p;d>l&&(d=l,v=Math.floor(v*(d/g))),v>f&&(v=f,d=Math.floor(d*(v/p)));var m=new Uint8Array(e.getImage());return Promise.resolve(t.getPixels(m,e.getMimeType())).then(function(u){var l=s.default(new Uint8Array(d*v*4),[d,v,4]);i.debug(ge+': Resizing "'+(a||n)+'", '+u.shape+" → "+l.shape+"...");try{r.filter===exports.TextureResizeFilter.LANCZOS3?o.lanczos3(u,l):o.lanczos2(u,l)}catch(e){return void i.warn(ge+': Failed to resize "'+(a||n)+'": "'+e.message+'".')}var f=e.setImage;return Promise.resolve(t.savePixels(l,e.getMimeType())).then(function(t){f.call(e,t.buffer)})})}i.debug(ge+': Skipping "'+(a||n)+'", within size range.')}else i.warn('Skipping unsupported texture type, "'+e.getMimeType()+'".')});return Promise.resolve(a&&a.then?a.then(n):n())}catch(e){return Promise.reject(e)}}},exports.unweld=function(e){return void 0===e&&(e=de),u({},de,e),function(e){for(var t,r=e.getLogger(),n=new Map,i=f(e.getRoot().listMeshes());!(t=i()).done;)for(var o,a=f(t.value.listPrimitives());!(o=a()).done;){var s=o.value,u=s.getIndices();if(u){for(var l,c=f(s.listAttributes());!(l=c()).done;){var g=l.value;s.swap(g,ve(g,u,r,n)),1===g.listParents().length&&g.dispose()}for(var p,d=f(s.listTargets());!(p=d()).done;)for(var v,m=p.value,h=f(m.listAttributes());!(v=h()).done;){var y=v.value;m.swap(y,ve(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=me);var t=u({},me,e);return function(e){for(var r,n=e.getLogger(),i=f(e.getRoot().listMeshes());!(r=i()).done;)for(var o,a=f(r.value.listPrimitives());!(o=a()).done;){var s=o.value;0===t.tolerance?he(e,s):ye(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=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=r.getRoot().listMeshes();function a(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}o.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)})});var s=a(Array.from(n));t.debug("dedup: Found "+s.size+" duplicates among "+n.size+" indices.");var u=a(Array.from(i));t.debug("dedup: Found "+u.size+" duplicates among "+i.size+" attributes."),o.forEach(function(e){e.listPrimitives().forEach(function(e){e.listAttributes().forEach(function(t){u.has(t)&&e.swap(t,u.get(t))});var t=e.getIndices();t&&s.has(t)&&e.swap(t,s.get(t))})}),Array.from(s.keys()).forEach(function(e){return e.dispose()}),Array.from(u.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){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;){for(var u,l=t.value,f=[],g=c(l.listSemantics());!(u=g()).done;){var p=u.value,v=l.getAttribute(p);f.push(p+":"+i.get(v))}var d=l.getIndices();d&&f.push("indices:"+i.get(d)),n.push(f.join(","))}var m=n.join(";");if(s.has(m)){var h=s.get(m);r.listParents().forEach(function(t){t.propertyType!==e.PropertyType.ROOT&&t.swap(r,h)}),r.dispose()}else s.set(m,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.")}},m=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 h(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 y=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 A(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:P(n.min),bboxMax:P(n.max)}})}}function T(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+":"+w(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(w(p.getArray())),a.add(p)),n+=e.listAttributes()[0].getCount(),r+=h(e)});var s=0;Array.from(a).forEach(function(e){return s+=e.getArray().byteLength});var u=e.listPrimitives().map(function(e){return I[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 E(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 b(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 I=["POINTS","LINES","LINE_LOOP","LINE_STRIP","TRIANGLES","TRIANGLE_STRIP","TRIANGLE_FAN"];function P(e){for(var t=0;t<e.length;t++)e[t].toFixed&&(e[t]=Number(e[t].toFixed(5)));return e}function w(e){return e.constructor.name.replace("Array","").toLowerCase()}var M="instance",R={};function x(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(M+": Removed "+i+" unused nodes.")}function N(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 C="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function O(e,t,r){if(!e.s){if(r instanceof z){if(!r.s)return void(r.o=O.bind(null,e,t));1&t&&(t=r.s),r=r.v}if(r&&r.then)return void r.then(O.bind(null,e,t),O.bind(null,e,2));e.s=t,e.v=r;var n=e.o;n&&n(e)}}var z=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{O(n,1,o(this.v))}catch(e){O(n,2,e)}return n}return this}return this.o=function(e){try{var i=e.v;1&e.s?O(n,1,t?t(i):i):r?O(n,1,r(i)):O(n,2,i)}catch(e){O(n,2,e)}},n},e}();function L(e){return e instanceof z&&1&e.s}var U={},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]},_=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.")}},k="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 G="quantize",j=[Int8Array,Int16Array,Int32Array],V={excludeAttributes:[],quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeWeight:8,quantizeGeneric:12};function D(t,r,o,a){for(var s,u=t.getLogger(),l=c(r.listSemantics());!(s=l()).done;){var f=s.value;if(!a.excludeAttributes.includes(f)){var g=r.getAttribute(f),p=Z(f,g,u,a),v=p.bits,d=p.ctor;if(d){if(v<8||v>16)throw new Error(G+": 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,Y(o)):n.fromScaling(y,[1/h,1/h,1/h]);for(var A=0,T=[0,0,0],S=m.getCount();A<S;A++)m.getElement(A,T),m.setElement(A,i.transformMat4(T,T,y))}K(m,d,v),r.swap(g,m)}}}}if(r instanceof e.Primitive&&r.getIndices()&&r.listAttributes().length&&r.listAttributes()[0].getCount()<65535){var E=r.getIndices();E.setArray(new Uint16Array(E.getArray()))}}function W(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 X(t,r,i){for(var o,a=Y(i),s=c(r.listParents());!(o=s()).done;){var u=o.value;if(u instanceof e.Node){var l=u.listChildren().length>0,f=!!u.listParents().find(function(t){return t instanceof e.Animation});if(u.getSkin()){u.setSkin(H(u.getSkin(),i));continue}var g=void 0;l||f?(g=t.createNode("").setMesh(r),u.addChild(g).setMesh(null)):g=u;var p=g.getMatrix();n.multiply(p,p,a),g.setMatrix(p)}}}function H(e,t){e=e.clone();for(var r=Y(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 K(e,t,r){for(var n=new t(e.getArray().length),i=j.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 Z(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(G+": 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(G+": Skipping "+e+"; out of [0,1] range."),{bits:-1};o=(i=n.quantizeWeight)<=8?Uint8Array:Uint16Array}else{if(!e.startsWith("_"))throw new Error(G+': Unexpected semantic, "'+e+'".');if(a.some(function(e){return e<-1})||s.some(function(e){return e>1}))return r.warn(G+": 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 Q(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(G+': Missing "POSITION" attribute.');var g=J(r,3);if(n.length>0){var p=J(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 J(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 Y(e){return n.fromRotationTranslationScale([],[0,0,0,1],e.offset,[e.scale,e.scale,e.scale])}var $={tolerance:1e-4};function ee(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 te={target:"size"};function re(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 ne(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 ie={name:"",fps:10,pattern:/.*/,sort:!0},oe="tangents",ae={overwrite:!1};function se(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(oe+": Skipping primitive "+i+' of mesh "'+n+'": TANGENT found.'),!1):!t.getIndices()||(r.warn(oe+": Skipping primitive "+i+' of mesh "'+n+'": primitives must be unwelded.'),!1):(r.debug(oe+": Skipping primitive "+i+' of mesh "'+n+'": primitives must have attributes=[POSITION, NORMAL, TEXCOORD_0] and mode=TRIANGLES.'),!1)}var ue="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function le(e,t,r){if(!e.s){if(r instanceof fe){if(!r.s)return void(r.o=le.bind(null,e,t));1&t&&(t=r.s),r=r.v}if(r&&r.then)return void r.then(le.bind(null,e,t),le.bind(null,e,2));e.s=t,e.v=r;var n=e.o;n&&n(e)}}var fe=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{le(n,1,o(this.v))}catch(e){le(n,2,e)}return n}return this}return this.o=function(e){try{var i=e.v;1&e.s?le(n,1,t?t(i):i):r?le(n,1,r(i)):le(n,2,i)}catch(e){le(n,2,e)}},n},e}();function ce(e){return e instanceof fe&&1&e.s}var ge,pe="textureResize";(ge=exports.TextureResizeFilter||(exports.TextureResizeFilter={})).LANCZOS3="lanczos3",ge.LANCZOS2="lanczos2";var ve={size:[2048,2048],filter:exports.TextureResizeFilter.LANCZOS3,pattern:null},de={};function me(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 he={tolerance:1e-4};function ye(t,r){if(!r.getIndices()){for(var n=r.listAttributes()[0],i=n.getCount(),o=n.getBuffer(),a=i<=65534?new Uint16Array(3*h(r)):new Uint32Array(3*h(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 Ae(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 S=m.join("|");if(S in a)f.push(a[S]);else{for(var E,b=c(t.listAttributes());!(E=b()).done;){var I=E.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 x=M.value;l.get(x).push(x.getElement(d,[]))}a[S]=g,f.push(g),g++}}var N=t.listAttributes()[0].getCount(),C=l.get(t.getAttribute("POSITION")).length;e.getLogger().debug("weld: "+N+" → "+C+" vertices.");for(var O,z=c(t.listAttributes());!(O=z()).done;){var L=O.value;Se(t,L,l.get(L)),1===L.listParents().length&&L.dispose()}for(var U,F=c(t.listTargets());!(U=F()).done;)for(var _,k=U.value,q=c(k.listAttributes());!(_=q()).done;){var B=_.value;Se(k,B,l.get(B)),1===B.listParents().length&&B.dispose()}if(s){var G=Te(s.getArray(),f.length);G.set(f),t.setIndices(s.clone().setArray(G)),1===s.listParents().length&&s.dispose()}else{var j=N<=65534?new Uint16Array(f):new Uint32Array(f);t.setIndices(e.createAccessor().setArray(j))}}function Te(e,t){return new(0,e.constructor)(t)}function Se(e,t,r){for(var n=r.length*t.getElementSize(),i=Te(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=V,exports.TEXTURE_RESIZE_DEFAULTS=ve,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:A(e),meshes:T(e),materials:S(e),textures:E(e),animations:b(e)}},exports.instance=function(t){return void 0===t&&(t=R),l({},R,t),function(t){var n=t.getLogger(),i=t.getRoot(),o=t.createExtension(r.MeshGPUInstancing);if(i.listAnimations().length)throw new Error(M+": 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=N(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,S=!1,E=0;E<p.length;E++){var b,I,P,w=p[E];d.setElement(E,b=w.getWorldTranslation()),m.setElement(E,I=w.getWorldRotation()),h.setElement(E,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])||(S=!0),w.setMesh(null),l.push(w)}A||d.dispose(),T||m.dispose(),S||h.dispose(),x(l,n),s++,u+=p.length}}},f=c(i.listScenes());!(a=f()).done;)l();s>0?n.info(M+": Created "+s+" batches, with "+u+" total instances."):(n.info(M+": No meshes with multiple parent nodes were found."),o.dispose()),n.debug(M+": Complete.")}},exports.metalRough=function(e){return void 0===e&&(e=U),l({},U,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[C]){var n,i,o,a=e[C]();if(function e(r){try{for(;!(n=a.next()).done;)if((r=t(n.value))&&r.then){if(!L(r))return void r.then(e,o||(o=O.bind(null,i=new z,2)));r=r.v}i?O(i,1,r):i=r}catch(e){O(i||(i=new z),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(!L(a))return void a.then(r,i||(i=O.bind(null,n=new z,2)));a=a.v}n?O(n,1,a):n=a}catch(e){O(n||(n=new z),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(m(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(m(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(k+': 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(k+": 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(k+': 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(k+": Skipping animation #"+o+' with name "'+i.getName()+'".')})}(t,n,r),r.meshes||r.animations||n.warn(k+": Select animations or meshes to create a partition."),Promise.resolve(t.transform(_({propertyTypes:[e.PropertyType.BUFFER]}))).then(function(){n.debug(k+": Complete.")})}catch(e){return Promise.reject(e)}}},exports.prune=_,exports.quantize=function(t){void 0===t&&(t=V);var n=l({},V,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=W(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(Q))));for(var u,l=c(t.getRoot().listMeshes());!(u=l()).done;){var f=u.value;"mesh"===n.quantizationVolume&&(s=W(Q(f))),s&&!n.excludeAttributes.includes("POSITION")&&X(t,f,s);for(var g,p=c(f.listPrimitives());!(g=p()).done;){var v=g.value;D(t,v,s,n);for(var m,h=c(v.listTargets());!(m=h()).done;)D(t,m.value,s,n)}}return Promise.resolve(t.transform(_({propertyTypes:[e.PropertyType.ACCESSOR,e.PropertyType.SKIN]}),d({propertyTypes:[e.PropertyType.ACCESSOR]}))).then(function(){o.debug(G+": Complete.")})}catch(e){return Promise.reject(e)}}},exports.reorder=function(t){void 0===t&&(t=te);var r=l({},te,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 y,n=new Map,i=new y,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(ne(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,A=h.clone();re(A,p,v);for(var T,S=c(a.attributesToPrimitives.get(h));!(T=S()).done;){var E=T.value;if(E.getIndices()===u&&E.swap(u,l),E.getIndices()===l){E.swap(h,A);for(var b,I=c(E.listTargets());!(b=I()).done;)b.value.swap(h,A)}}}}return Promise.resolve(t.transform(_({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=$);var r=l({},$,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()),ee(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=ie);var r=l({},ie,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=ae),!t.generateTangents)throw new Error(oe+': generateTangents callback required — install "mikktspace".');var r=l({},ae,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(se(v,i,f,p,r.overwrite)){var d=v.getAttribute("POSITION").getArray(),m=v.getAttribute("NORMAL").getArray(),h=v.getAttribute("TEXCOORD_0").getArray(),y=o.get(d)||e.uuid();o.set(d,y);var A=o.get(m)||e.uuid();o.set(m,A);var T=o.get(h)||e.uuid();o.set(h,T);var S=v.getAttribute("TANGENT");S&&2===S.listParents().length&&S.dispose();var E=y+"|"+A+"|"+T,b=a.get(E);if(b)i.debug(oe+": Found cache for primitive "+p+' of mesh "'+f+'".'),v.setAttribute("TANGENT",b),s++;else{i.debug(oe+": Generating for primitive "+p+' of mesh "'+f+'".');for(var I=v.getAttribute("POSITION").getBuffer(),P=r.generateTangents(d instanceof Float32Array?d:new Float32Array(d),m instanceof Float32Array?m:new Float32Array(m),h instanceof Float32Array?h:new Float32Array(h)),w=3;w<P.length;w+=4)P[w]*=-1;b=t.createAccessor().setBuffer(I).setArray(P).setType("VEC4"),v.setAttribute("TANGENT",b),a.set(E,b),s++}}}s?i.debug(oe+": Complete."):i.warn(oe+": No qualifying primitives found. See debug output.")}},exports.textureResize=function(e){void 0===e&&(e=ve);var r=l({},ve,e);return function(e){try{var n=function(){i.debug(pe+": Complete.")},i=e.getLogger(),o=function(e,t,r){if("function"==typeof e[ue]){var n,i,o,a=e[ue]();if(function e(r){try{for(;!(n=a.next()).done;)if((r=t(n.value))&&r.then){if(!ce(r))return void r.then(e,o||(o=le.bind(null,i=new fe,2)));r=r.v}i?le(i,1,r):i=r}catch(e){le(i||(i=new fe),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(!ce(a))return void a.then(r,i||(i=le.bind(null,n=new fe,2)));a=a.v}n?le(n,1,a):n=a}catch(e){le(n||(n=new fe),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&&(v=l,d=Math.floor(d*(v/g))),d>f&&(d=f,v=Math.floor(v*(d/p)));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(pe+': Resizing "'+(o||n)+'", '+s.shape+" → "+l.shape+"...");try{r.filter===exports.TextureResizeFilter.LANCZOS3?a.lanczos3(s,l):a.lanczos2(s,l)}catch(e){return void i.warn(pe+': Failed to resize "'+(o||n)+'": "'+e.message+'".')}var f=e.setImage;return Promise.resolve(t.savePixels(l,e.getMimeType())).then(function(t){f.call(e,t.buffer)})})}i.debug(pe+': 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=de),l({},de,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,me(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,me(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=he);var t=l({},he,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?ye(e,s):Ae(e,s,t)}n.debug("weld: Complete.")}}; | ||
//# sourceMappingURL=functions.js.map |
@@ -1,2 +0,2 @@ | ||
import{bounds as e,PropertyType as t,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,Animation as u,Accessor as f,AnimationSampler as p,uuid as m}from"@gltf-transform/core";export{bounds}from"@gltf-transform/core";import{getPixels as d,savePixels as h}from"ndarray-pixels";import{MeshGPUInstancing as A,MaterialsIOR as y,MaterialsSpecular as E,MaterialsPBRSpecularGlossiness as T,MeshQuantization as S}from"@gltf-transform/extensions";import{fromRotationTranslationScale as I,multiply as b}from"gl-matrix/mat4";import w from"ndarray";import{lanczos3 as M,lanczos2 as N}from"ndarray-lanczos";function R(){return(R=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e}).apply(this,arguments)}const C={pivot:"center"};function O(t=C){const n=R({},C,t);return 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(e=>{const t=e.getTranslation();e.setTranslation([t[0]+l[0],t[1]+l[1],t[2]+l[2]])})}),s.debug("center: Complete.")}}function x(e){return t=>{const n=t.getLogger();if("linear"===e.inputEncoding)return void n.info("colorspace: Vertex colors already linear. Skipping conversion.");if("sRGB"!==e.inputEncoding)return void n.error(`colorspace: Unknown input encoding "${e.inputEncoding}" – should be "sRGB" or "linear". Skipping conversion.`);const s=new Set;function r(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function o(e){const t=[0,0,0];let n;for(let o=0;n=e.getAttribute(`COLOR_${o}`);o++)if(!s.has(n)){for(let e=0;e<n.getCount();e++)n.getElement(e,t),t[0]=r(t[0]),t[1]=r(t[1]),t[2]=r(t[2]),n.setElement(e,t);s.add(n)}}t.getRoot().listMeshes().forEach(e=>e.listPrimitives().forEach(o)),n.debug("colorspace: Complete.")}}const P={propertyTypes:[t.ACCESSOR,t.MESH,t.TEXTURE]},z=function(e=P){const r=R({},P,e),o=new Set(r.propertyTypes);for(const e of r.propertyTypes)if(!P.propertyTypes.includes(e))throw new Error(`dedup: Unsupported deduplication on type "${e}".`);return e=>{const r=e.getLogger();o.has(t.ACCESSOR)&&function(e,t){const s=new Set,r=new Set,o=t.getRoot().listMeshes();function i(e){const t=new Map;for(let s=0;s<e.length;s++){const r=e[s],o=r.getArray().slice().buffer;if(!t.has(r))for(let s=0;s<e.length;s++){const i=e[s];r!==i&&(t.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)&&t.set(i,r))}}return t}o.forEach(e=>{e.listPrimitives().forEach(e=>{e.listAttributes().forEach(e=>r.add(e));const t=e.getIndices();t&&s.add(t)})});const a=i(Array.from(s));e.debug(`dedup: Found ${a.size} duplicates among ${s.size} indices.`);const c=i(Array.from(r));e.debug(`dedup: Found ${c.size} duplicates among ${r.size} attributes.`),o.forEach(e=>{e.listPrimitives().forEach(e=>{e.listAttributes().forEach(t=>{c.has(t)&&e.swap(t,c.get(t))});const t=e.getIndices();t&&a.has(t)&&e.swap(t,a.get(t))})}),Array.from(a.keys()).forEach(e=>e.dispose()),Array.from(c.keys()).forEach(e=>e.dispose())}(r,e),o.has(t.MESH)&&function(e,n){const s=n.getRoot(),r=new Map;s.listAccessors().forEach((e,t)=>{r.set(e,t)});const o=s.listMeshes().length,i=new Map;for(const e of s.listMeshes()){const n=[];for(const t of e.listPrimitives()){const e=[];for(const n of t.listSemantics()){const s=t.getAttribute(n);e.push(n+":"+r.get(s))}const s=t.getIndices();s&&e.push("indices:"+r.get(s)),n.push(e.join(","))}const s=n.join(";");if(i.has(s)){const n=i.get(s);e.listParents().forEach(s=>{s.propertyType!==t.ROOT&&s.swap(e,n)}),e.dispose()}else i.set(s,e)}e.debug(`dedup: Found ${o-i.size} duplicates among ${o} meshes.`)}(r,e),o.has(t.TEXTURE)&&function(e,t){const r=t.getRoot(),o=r.listTextures(),i=new Map;for(let e=0;e<o.length;e++){const t=o[e],s=t.getImage();if(!i.has(t))for(let e=0;e<o.length;e++){const r=o[e],a=r.getImage();if(t===r)continue;if(i.has(r))continue;if(t.getMimeType()!==r.getMimeType())continue;const c=t.getSize(),l=r.getSize();c&&l&&c[0]===l[0]&&c[1]===l[1]&&s&&a&&n.equals(s,a)&&i.set(r,t)}}e.debug(`dedup: Found ${i.size} duplicates among ${r.listTextures().length} textures.`),Array.from(i.entries()).forEach(([e,t])=>{e.listParents().forEach(n=>{n instanceof s||n.swap(e,t)}),e.dispose()})}(r,e),r.debug("dedup: Complete.")}};async function L(e,t,n){if(!e)return null;const s=e.getImage();if(!s)return null;const r=await d(new Uint8Array(s),e.getMimeType());for(let e=0;e<r.shape[0];++e)for(let t=0;t<r.shape[1];++t)n(r,e,t);const o=(await h(r,"image/png")).buffer;return t.setImage(o).setMimeType("image/png")}function $(e){const t=e.getIndices(),n=e.getAttribute("POSITION");switch(e.getMode()){case r.Mode.POINTS:return n.getCount();case r.Mode.LINES:return t?t.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 t?t.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: "+e.getMode())}}class v{constructor(){this._map=new Map}get size(){return this._map.size}has(e){return this._map.has(e)}add(e,t){let n=this._map.get(e);return n||(n=new Set,this._map.set(e,n)),n.add(t),this}get(e){return this._map.get(e)||new Set}keys(){return this._map.keys()}}function _(e){return{scenes:k(e),meshes:F(e),materials:U(e),textures:q(e),animations:G(e)}}function k(t){return{properties:t.getRoot().listScenes().map(t=>{const n=t.listChildren()[0],s=e(t);return{name:t.getName(),rootName:n?n.getName():"",bboxMin:V(s.min),bboxMax:V(s.max)}})}}function F(e){return{properties:e.getRoot().listMeshes().map(e=>{const t=e.listParents().filter(e=>"Root"!==e.propertyType).length;let n=0,s=0;const r=new Set,o=new Set,i=new Set;e.listPrimitives().forEach(e=>{for(const t of e.listSemantics()){const n=e.getAttribute(t);r.add(t+":"+j(n.getArray())),i.add(n)}for(const t of e.listTargets())t.listAttributes().forEach(e=>i.add(e));const t=e.getIndices();t&&(o.add(j(t.getArray())),i.add(t)),s+=e.listAttributes()[0].getCount(),n+=$(e)});let a=0;Array.from(i).forEach(e=>a+=e.getArray().byteLength);const c=e.listPrimitives().map(e=>B[e.getMode()]);return{name:e.getName(),mode:Array.from(new Set(c)),primitives:e.listPrimitives().length,glPrimitives:n,vertices:s,indices:Array.from(o).sort(),attributes:Array.from(r).sort(),instances:t,size:a}})}}function U(e){return{properties:e.getRoot().listMaterials().map(t=>{const n=t.listParents().filter(e=>"Root"!==e.propertyType).length,s=new Set(t.listExtensions()),r=e.getGraph().getLinks().filter(e=>{const n=e.getChild(),r=e.getParent();return n instanceof o&&r===t||!!(n instanceof o&&r instanceof i&&s.has(r))}).map(e=>e.getName());return{name:t.getName(),instances:n,textures:r,alphaMode:t.getAlphaMode(),doubleSided:t.getDoubleSided()}})}}function q(e){return{properties:e.getRoot().listTextures().map(t=>{const n=t.listParents().filter(e=>"Root"!==e.propertyType).length,s=e.getGraph().listParentLinks(t).map(e=>e.getName()).filter(e=>"texture"!==e),r=a.getSize(t.getImage(),t.getMimeType());return{name:t.getName(),uri:t.getURI(),slots:Array.from(new Set(s)),instances:n,mimeType:t.getMimeType(),resolution:r?r.join("x"):"",size:t.getImage().byteLength,gpuSize:a.getMemSize(t.getImage(),t.getMimeType())}})}}function G(e){return{properties:e.getRoot().listAnimations().map(e=>{let t=Infinity,n=-Infinity;e.listSamplers().forEach(e=>{const s=e.getInput();s&&(t=Math.min(t,s.getMin([])[0]),n=Math.max(n,s.getMax([])[0]))});let s=0,r=0;const o=new Set;return e.listSamplers().forEach(e=>{const t=e.getInput(),n=e.getOutput();t&&(r+=t.getCount(),o.add(t),n&&o.add(n))}),Array.from(o).forEach(e=>{s+=e.getArray().byteLength}),{name:e.getName(),channels:e.listChannels().length,samplers:e.listSamplers().length,duration:Math.round(1e3*(n-t))/1e3,keyframes:r,size:s}})}}const B=["POINTS","LINES","LINE_LOOP","LINE_STRIP","TRIANGLES","TRIANGLE_STRIP","TRIANGLE_FAN"];function V(e){for(let t=0;t<e.length;t++)e[t].toFixed&&(e[t]=Number(e[t].toFixed(5)));return e}function j(e){return e.constructor.name.replace("Array","").toLowerCase()}const W={};function D(e=W){return R({},W,e),e=>{const t=e.getLogger(),n=e.getRoot(),s=e.createExtension(A);if(n.listAnimations().length)throw new Error("instance: Instancing is not currently supported for animated models.");let r=0,o=0;for(const i of n.listScenes()){const n=new Map;i.traverse(e=>{const t=e.getMesh();t&&n.set(t,(n.get(t)||new Set).add(e))});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(e=>e.getSkin()))continue;const u=H(e,s,l,g.length),f=u.getAttribute("TRANSLATION"),p=u.getAttribute("ROTATION"),m=u.getAttribute("SCALE"),d=e.createNode().setMesh(l).setExtension("EXT_mesh_gpu_instancing",u);i.addChild(d);let h=!1,A=!1,y=!1;for(let e=0;e<g.length;e++){let t,n,s;const r=g[e];f.setElement(e,t=r.getWorldTranslation()),p.setElement(e,n=r.getWorldRotation()),m.setElement(e,s=r.getWorldScale()),c.eq(t,[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(),X(a,t),r++,o+=g.length}}r>0?t.info(`instance: Created ${r} batches, with ${o} total instances.`):(t.info("instance: No meshes with multiple parent nodes were found."),s.dispose()),t.debug("instance: Complete.")}}function X(e,t){let n,s=0;for(;n=e.pop();){if(n.listChildren().length||n.getCamera()||n.getMesh()||n.getSkin()||n.listExtensions().length)continue;const t=n.getParent();t instanceof l&&e.push(t),n.dispose(),s++}t.debug(`instance: Removed ${s} unused nodes.`)}function H(e,t,n,s){const r=n.listPrimitives()[0].getAttribute("POSITION").getBuffer(),o=e.createAccessor().setType("VEC3").setArray(new Float32Array(3*s)).setBuffer(r),i=e.createAccessor().setType("VEC4").setArray(new Float32Array(4*s)).setBuffer(r),a=e.createAccessor().setType("VEC3").setArray(new Float32Array(3*s)).setBuffer(r);return t.createInstancedMesh().setAttribute("TRANSLATION",o).setAttribute("ROTATION",i).setAttribute("SCALE",a)}const K={};function Z(e=K){return R({},K,e),async e=>{const t=e.getLogger(),n=T.EXTENSION_NAME;if(!e.getRoot().listExtensionsUsed().map(e=>e.extensionName).includes(n))return void t.warn(`metalRough: Extension ${n} not found on given document.`);const s=e.createExtension(y),r=e.createExtension(E),o=e.createExtension(T),i=new Set;for(const t of e.getRoot().listMaterials()){const n=t.getExtension("KHR_materials_pbrSpecularGlossiness");if(!n)continue;const o=r.createSpecular().setSpecularFactor(1).setSpecularColorFactor(n.getSpecularFactor());i.add(n.getSpecularGlossinessTexture()),i.add(t.getBaseColorTexture()),i.add(t.getMetallicRoughnessTexture()),t.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&&(t.setBaseColorTexture(a),t.getBaseColorTextureInfo().copy(n.getDiffuseTextureInfo()));const c=n.getSpecularGlossinessTexture();if(c){const s=n.getSpecularGlossinessTextureInfo(),r=e.createTexture();await L(c,r,(e,t,n)=>{e.set(t,n,3,255)}),o.setSpecularTexture(r),o.setSpecularColorTexture(r),o.getSpecularTextureInfo().copy(s),o.getSpecularColorTextureInfo().copy(s);const i=n.getGlossinessFactor(),a=e.createTexture();await L(c,a,(e,t,n)=>{const s=255-Math.round(e.get(t,n,3)*i);e.set(t,n,0,0),e.set(t,n,1,s),e.set(t,n,2,0),e.set(t,n,3,255)}),t.setMetallicRoughnessTexture(a),t.getMetallicRoughnessTextureInfo().copy(s)}else o.setSpecularColorFactor(n.getSpecularFactor()),t.setRoughnessFactor(1-n.getGlossinessFactor());t.setExtension("KHR_materials_pbrSpecularGlossiness",null)}o.dispose();for(const e of i)e&&1===e.listParents().length&&e.dispose();t.debug("metalRough: Complete.")}}const J={propertyTypes:[t.NODE,t.SKIN,t.MESH,t.CAMERA,t.PRIMITIVE,t.PRIMITIVE_TARGET,t.ANIMATION,t.MATERIAL,t.TEXTURE,t.ACCESSOR,t.BUFFER]},Y=function(e=J){const n=R({},J,e).propertyTypes;return e=>{const r=e.getLogger(),o=e.getRoot(),i=e.getGraph(),a={};if(n.includes(t.NODE)&&o.listNodes().forEach(c),n.includes(t.SKIN)&&o.listSkins().forEach(c),n.includes(t.MESH)&&o.listMeshes().forEach(c),n.includes(t.CAMERA)&&o.listCameras().forEach(c),n.includes(t.PRIMITIVE)&&l(i,t.PRIMITIVE),n.includes(t.PRIMITIVE_TARGET)&&l(i,t.PRIMITIVE_TARGET),n.includes(t.ANIMATION))for(const e of o.listAnimations()){for(const t of e.listChannels())t.getTargetNode()||(t.dispose(),u(t));if(e.listChannels().length)e.listSamplers().forEach(c);else{const t=e.listSamplers();c(e),t.forEach(c)}}if(n.includes(t.MATERIAL)&&o.listMaterials().forEach(c),n.includes(t.TEXTURE)&&o.listTextures().forEach(c),n.includes(t.ACCESSOR)&&o.listAccessors().forEach(c),n.includes(t.BUFFER)&&o.listBuffers().forEach(c),Object.keys(a).length){const e=Object.keys(a).map(e=>`${e} (${a[e]})`).join(", ");r.info(`prune: Removed types... ${e}`)}else r.info("prune: No unused properties found.");function c(e){e.listParents().filter(e=>!(e instanceof s||e instanceof g)).length||(e.dispose(),u(e))}function l(e,t){e.getLinks().map(e=>e.getParent()).filter(e=>e.propertyType===t).forEach(c)}function u(e){a[e.propertyType]=a[e.propertyType]||0,a[e.propertyType]++}r.debug("prune: Complete.")}},Q={animations:!0,meshes:!0},ee=(e=Q)=>{const n=R({},Q,e);return async e=>{const s=e.getLogger();!1!==n.meshes&&function(e,t,n){const s=new Set(e.getRoot().listBuffers().map(e=>e.getURI()));e.getRoot().listMeshes().forEach((r,o)=>{if(Array.isArray(n.meshes)&&!n.meshes.includes(r.getName()))return void t.debug(`partition: Skipping mesh #${o} with name "${r.getName()}".`);t.debug(`partition: Creating buffer for mesh "${r.getName()}".`);const i=e.createBuffer(r.getName()).setURI(te(r.getName()||"mesh",s));r.listPrimitives().forEach(e=>{const t=e.getIndices();t&&t.setBuffer(i),e.listAttributes().forEach(e=>e.setBuffer(i)),e.listTargets().forEach(e=>{e.listAttributes().forEach(e=>e.setBuffer(i))})})})}(e,s,n),!1!==n.animations&&function(e,t,n){const s=new Set(e.getRoot().listBuffers().map(e=>e.getURI()));e.getRoot().listAnimations().forEach((r,o)=>{if(Array.isArray(n.animations)&&!n.animations.includes(r.getName()))return void t.debug(`partition: Skipping animation #${o} with name "${r.getName()}".`);t.debug(`partition: Creating buffer for animation "${r.getName()}".`);const i=e.createBuffer(r.getName()).setURI(te(r.getName()||"animation",s));r.listSamplers().forEach(e=>{const t=e.getInput(),n=e.getOutput();t&&t.setBuffer(i),n&&n.setBuffer(i)})})}(e,s,n),n.meshes||n.animations||s.warn("partition: Select animations or meshes to create a partition."),await e.transform(Y({propertyTypes:[t.BUFFER]})),s.debug("partition: Complete.")}};function te(e,t){let n=`${e}.bin`,s=1;for(;t.has(n);)n=`${e}_${s++}.bin`;return n}const ne=[Int8Array,Int16Array,Int32Array],se={excludeAttributes:[],quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeWeight:8,quantizeGeneric:12},re=(e=se)=>{const n=R({},se,e);return async e=>{const s=e.getLogger(),r=e.getRoot();let o;if(e.createExtension(S).setRequired(!0),"scene"===n.quantizationVolume){const e=[];for(const t of r.listMeshes())e.push(...ce(t));o=ae(ie(e,3))}for(const t of e.getRoot().listMeshes()){"mesh"===n.quantizationVolume&&(o=ae(ie(ce(t),3))),o&&!n.excludeAttributes.includes("POSITION")&&le(e,t,o);for(const s of t.listPrimitives()){oe(e,s,o,n);for(const t of s.listTargets())oe(e,t,o,n)}}await e.transform(Y({propertyTypes:[t.ACCESSOR,t.SKIN]}),z({propertyTypes:[t.ACCESSOR]})),s.debug("quantize: Complete.")}};function oe(e,t,n,s){const o=e.getLogger();for(const e of t.listSemantics()){if(s.excludeAttributes.includes(e))continue;const r=t.getAttribute(e),{bits:i,ctor:a}=fe(e,r,o,s);if(!a)continue;if(i<8||i>16)throw new Error("quantize: Requires bits = 8–16.");if(r.getComponentSize()<=i/8)continue;const c=r.clone();if("POSITION"===e)for(let e=0,t=[0,0,0],s=c.getCount();e<s;e++)c.setElement(e,n.remap(c.getElement(e,t)));ue(c,a,i),t.swap(r,c)}if(t instanceof r&&t.getIndices()&&t.listAttributes().length&&t.listAttributes()[0].getCount()<65535){const e=t.getIndices();e.setArray(new Uint16Array(e.getArray()))}}function ie(e,t){const n=new Array(t).fill(Infinity),s=new Array(t).fill(-Infinity),r=[],o=[];for(const i of e){i.getMinNormalized(r),i.getMaxNormalized(o);for(let e=0;e<t;e++)n[e]=Math.min(n[e],r[e]),s[e]=Math.max(s[e],o[e])}return{min:n,max:s}}function ae(e){const{min:t,max:n}=e,s=Math.max((n[0]-t[0])/2,(n[1]-t[1])/2,(n[2]-t[2])/2),r=[t[0]+(n[0]-t[0])/2,t[1]+(n[1]-t[1])/2,t[2]+(n[2]-t[2])/2];return{remap:e=>[(e[0]-r[0])/s,(e[1]-r[1])/s,(e[2]-r[2])/s],offset:r,scale:s}}function ce(e){const t=[];for(const n of e.listPrimitives()){const e=n.getAttribute("POSITION");e&&t.push(e);for(const e of n.listTargets()){const n=e.getAttribute("POSITION");n&&t.push(n)}}if(0===t.length)throw new Error('quantize: Missing "POSITION" attribute.');return t}function le(e,t,n){const s=pe(n);for(const r of t.listParents())if(r instanceof l){const o=r.listChildren().length>0,i=!!r.listParents().find(e=>e instanceof u);if(r.getSkin()){r.setSkin(ge(r.getSkin(),n));continue}let a;o||i?(a=e.createNode("").setMesh(t),r.addChild(a).setMesh(null)):a=r;const c=a.getMatrix();b(c,c,s),a.setMatrix(c)}}function ge(e,t){e=e.clone();const n=pe(t),s=e.getInverseBindMatrices().clone(),r=[];for(let e=0,t=s.getCount();e<t;e++)s.getElement(e,r),b(r,r,n),s.setElement(e,r);return e.setInverseBindMatrices(s)}function ue(e,t,n){const s=new t(e.getArray().length),r=ne.includes(t)?1:0,o=n-r,i=8*t.BYTES_PER_ELEMENT-r,a=Math.pow(2,o)-1,c=i-o,l=2*o-i;for(let t=0,n=0,r=[];t<e.getCount();t++){e.getElement(t,r);for(let e=0;e<r.length;e++){let t=Math.round(Math.abs(r[e])*a);t=t<<c|t>>l,s[n++]=t*Math.sign(r[e])}}e.setArray(s).setNormalized(!0)}function fe(e,t,n,s){const r=t.getMinNormalized([]),o=t.getMaxNormalized([]);let i,a;if("POSITION"===e)i=s.quantizePosition,a=i<=8?Int8Array:Int16Array;else if("NORMAL"===e||"TANGENT"===e)i=s.quantizeNormal,a=i<=8?Int8Array:Int16Array;else if(e.startsWith("COLOR_"))i=s.quantizeColor,a=i<=8?Uint8Array:Uint16Array;else if(e.startsWith("TEXCOORD_")){if(r.some(e=>e<0)||o.some(e=>e>1))return n.warn(`quantize: Skipping ${e}; out of [0,1] range.`),{bits:-1};i=s.quantizeTexcoord,a=i<=8?Uint8Array:Uint16Array}else{if(e.startsWith("JOINTS_"))return i=Math.max(...t.getMax([]))<=255?8:16,a=i<=8?Uint8Array:Uint16Array,t.getComponentSize()>i/8&&t.setArray(new a(t.getArray())),{bits:-1};if(e.startsWith("WEIGHTS_")){if(r.some(e=>e<0)||o.some(e=>e>1))return n.warn(`quantize: Skipping ${e}; out of [0,1] range.`),{bits:-1};i=s.quantizeWeight,a=i<=8?Uint8Array:Uint16Array}else{if(!e.startsWith("_"))throw new Error(`quantize: Unexpected semantic, "${e}".`);if(r.some(e=>e<-1)||o.some(e=>e>1))return n.warn(`quantize: Skipping ${e}; out of [-1,1] range.`),{bits:-1};i=s.quantizeGeneric,a=a=r.some(e=>e<0)?i<=8?Int8Array:Int16Array:i<=8?Uint8Array:Uint16Array}}return{bits:i,ctor:a}}function pe(e){return I([],[0,0,0,1],e.offset,[e.scale,e.scale,e.scale])}const me={tolerance:1e-4},de=(e=me)=>{const t=R({},me,e);return e=>{const n=new Set,r=e.getRoot().listAccessors().length,o=e.getLogger();let i=!1;for(const s of e.getRoot().listAnimations()){const e=new Set;for(const t of s.listChannels())t.getSampler()&&"weights"===t.getTargetPath()&&e.add(t.getSampler());for(const r of s.listSamplers())e.has(r)?i=!0:"STEP"!==r.getInterpolation()&&"LINEAR"!==r.getInterpolation()||(n.add(r.getInput()),n.add(r.getOutput()),he(r,t))}for(const e of Array.from(n.values()))e.listParents().some(e=>!(e instanceof s))||e.dispose();e.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 he(e,t){const n=e.getInput().clone(),s=e.getOutput().clone(),r=t.tolerance,o=n.getCount()-1,i=[];let a=1;for(let t=1;t<o;++t){const o=n.getScalar(t),l=n.getScalar(t-1),g=n.getScalar(t+1),u=(o-l)/(g-l);let f=!1;if(o!==g&&(1!==t||o!==n.getScalar(0)))for(let n=0;n<s.getElementSize();n++){const o=s.getElement(t,i)[n],a=s.getElement(t-1,i)[n],l=s.getElement(t+1,i)[n];if("LINEAR"===e.getInterpolation()){if(Math.abs(o-(a*(1-(c=u))+l*c))>r){f=!0;break}}else if("STEP"===e.getInterpolation()&&(o!==a||o!==l)){f=!0;break}}f&&(t!==a&&(n.setScalar(a,n.getScalar(t)),s.setElement(a,s.getElement(t,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())),e.setInput(n),e.setOutput(s)):(n.dispose(),s.dispose())}const Ae={target:"size"};function ye(e=Ae){const n=R({},Ae,e),s=n.encoder;return async e=>{const o=e.getLogger();await s.ready;const i=function(e){const t=new v,n=new Map,s=new v;for(const r of e.getRoot().listMeshes())for(const e of r.listPrimitives()){const r=e.getIndices();if(r){n.set(r,e.getMode());for(const n of Te(e))t.add(r,n),s.add(n,e)}}return{indicesToAttributes:t,indicesToMode:n,attributesToPrimitives:s}}(e);for(const e of i.indicesToAttributes.keys()){const t=e.clone();let o=t.getArray().slice();o instanceof Uint32Array||(o=new Uint32Array(o));const[a,c]=s.reorderMesh(o,i.indicesToMode.get(e)===r.Mode.TRIANGLES,"size"===n.target);t.setArray(c<=65534?new Uint16Array(o):o);for(const n of i.indicesToAttributes.get(e)){const s=n.clone();Ee(s,a,c);for(const r of i.attributesToPrimitives.get(n))if(r.getIndices()===e&&r.swap(e,t),r.getIndices()===t){r.swap(n,s);for(const e of r.listTargets())e.swap(n,s)}}}await e.transform(Y({propertyTypes:[t.ACCESSOR]})),i.indicesToAttributes.size?o.debug("reorder: Complete."):o.warn("reorder: No qualifying primitives found; may need to weld first.")}}function Ee(e,t,n){const s=e.getElementSize(),r=e.getCount(),o=e.getArray(),i=o.slice(0,n*s);for(let e=0;e<r;e++)for(let n=0;n<s;n++)i[t[e]*s+n]=o[e*s+n];e.setArray(i)}function Te(e){const t=[];for(const n of e.listAttributes())t.push(n);for(const n of e.listTargets())for(const e of n.listAttributes())t.push(e);return Array.from(new Set(t))}const Se={name:"",fps:10,pattern:/.*/,sort:!0};function Ie(e=Se){const t=R({},Se,e);return e=>{const n=e.getLogger(),s=e.getRoot(),r=t.fps,o=s.listNodes().filter(e=>e.getName().match(t.pattern));t.sort&&o.sort((e,t)=>e.getName()>t.getName()?1:-1);const i=e.createAnimation(t.name),a=s.listBuffers()[0];o.forEach((t,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=e.createAccessor().setArray(new Float32Array(s)).setBuffer(a),u=e.createAccessor().setArray(new Float32Array(c)).setBuffer(a).setType(f.Type.VEC3),m=e.createAnimationSampler().setInterpolation(p.Interpolation.STEP).setInput(l).setOutput(u),d=e.createAnimationChannel().setTargetNode(t).setTargetPath(g.TargetPath.SCALE).setSampler(m);i.addSampler(m).addChannel(d)}),n.debug("sequence: Complete.")}}const be={overwrite:!1};function we(e=be){if(!e.generateTangents)throw new Error('tangents: generateTangents callback required — install "mikktspace".');const t=R({},be,e);return e=>{const n=e.getLogger(),s=new Map,r=new Map;let o=0;for(const i of e.getRoot().listMeshes()){const a=i.getName(),c=i.listPrimitives();for(let i=0;i<c.length;i++){const l=c[i];if(!Me(l,n,a,i,t.overwrite))continue;const g=l.getAttribute("POSITION").getArray(),u=l.getAttribute("NORMAL").getArray(),f=l.getAttribute("TEXCOORD_0").getArray(),p=s.get(g)||m();s.set(g,p);const d=s.get(u)||m();s.set(u,d);const h=s.get(f)||m();s.set(f,h);const A=l.getAttribute("TANGENT");A&&2===A.listParents().length&&A.dispose();const y=`${p}|${d}|${h}`;let E=r.get(y);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 T=l.getAttribute("POSITION").getBuffer(),S=t.generateTangents(g instanceof Float32Array?g:new Float32Array(g),u instanceof Float32Array?u:new Float32Array(u),f instanceof Float32Array?f:new Float32Array(f));for(let e=3;e<S.length;e+=4)S[e]*=-1;E=e.createAccessor().setBuffer(T).setArray(S).setType("VEC4"),l.setAttribute("TANGENT",E),r.set(y,E),o++}}o?n.debug("tangents: Complete."):n.warn("tangents: No qualifying primitives found. See debug output.")}}function Me(e,t,n,s,o){return e.getMode()===r.Mode.TRIANGLES&&e.getAttribute("POSITION")&&e.getAttribute("NORMAL")&&e.getAttribute("TEXCOORD_0")?e.getAttribute("TANGENT")&&!o?(t.debug(`tangents: Skipping primitive ${s} of mesh "${n}": TANGENT found.`),!1):!e.getIndices()||(t.warn(`tangents: Skipping primitive ${s} of mesh "${n}": primitives must be unwelded.`),!1):(t.debug(`tangents: Skipping primitive ${s} of mesh "${n}": primitives must have attributes=[POSITION, NORMAL, TEXCOORD_0] and mode=TRIANGLES.`),!1)}const Ne="textureResize";var Re;!function(e){e.LANCZOS3="lanczos3",e.LANCZOS2="lanczos2"}(Re||(Re={}));const Ce={size:[2048,2048],filter:Re.LANCZOS3,pattern:null};function Oe(e=Ce){const t=R({},Ce,e);return async e=>{const n=e.getLogger();for(const s of e.getRoot().listTextures()){const e=s.getName(),r=s.getURI();if(t.pattern&&!t.pattern.test(e)&&!t.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]=t.size,[a,c]=s.getSize();if(a<=o&&c<=i){n.debug(`${Ne}: Skipping "${r||e}", within size range.`);continue}let l=a,g=c;l>o&&(l=o,g=Math.floor(g*(l/a))),g>i&&(g=i,l=Math.floor(l*(g/c)));const u=new Uint8Array(s.getImage()),f=await d(u,s.getMimeType()),p=w(new Uint8Array(l*g*4),[l,g,4]);n.debug(`${Ne}: Resizing "${r||e}", ${f.shape} → ${p.shape}...`);try{t.filter===Re.LANCZOS3?M(f,p):N(f,p)}catch(t){n.warn(`${Ne}: Failed to resize "${r||e}": "${t.message}".`);continue}s.setImage((await h(p,s.getMimeType())).buffer)}n.debug(`${Ne}: Complete.`)}}const xe={};function Pe(e=xe){return R({},xe,e),e=>{const t=e.getLogger(),n=new Map;for(const s of e.getRoot().listMeshes())for(const e of s.listPrimitives()){const s=e.getIndices();if(s){for(const r of e.listAttributes())e.swap(r,ze(r,s,t,n)),1===r.listParents().length&&r.dispose();for(const r of e.listTargets())for(const e of r.listAttributes())r.swap(e,ze(e,s,t,n)),1===e.listParents().length&&e.dispose();e.setIndices(null),1===s.listParents().length&&s.dispose()}}t.debug("unweld: Complete.")}}function ze(e,t,n,s){if(s.has(e)&&s.get(e).has(t))return n.debug(`unweld: Cache hit for reused attribute, "${e.getName()}".`),s.get(e).get(t);const r=e.clone(),o=e.getArray().constructor;r.setArray(new o(t.getCount()*e.getElementSize()));const i=[];for(let n=0;n<t.getCount();n++)r.setElement(n,e.getElement(t.getScalar(n),i));return s.has(e)||s.set(e,new Map),s.get(e).set(t,r),r}const Le={tolerance:1e-4};function $e(e=Le){const t=R({},Le,e);return e=>{const n=e.getLogger();for(const n of e.getRoot().listMeshes())for(const s of n.listPrimitives())0===t.tolerance?ve(e,s):_e(e,s,t);n.debug("weld: Complete.")}}function ve(e,t){if(t.getIndices())return;const n=t.listAttributes()[0],s=n.getCount(),r=n.getBuffer(),o=s<=65534?new Uint16Array(3*$(t)):new Uint32Array(3*$(t)),i=e.createAccessor().setBuffer(r).setType(f.Type.SCALAR).setArray(o);for(let e=0;e<i.getCount();e++)i.setScalar(e,e);t.setIndices(i)}function _e(e,t,n){const s=Math.max(n.tolerance,Number.EPSILON),r=Math.log10(1/s),o=Math.pow(10,r),i={},a=t.getIndices(),c=a?a.getCount():t.listAttributes()[0].getCount(),l=new Map;t.listAttributes().forEach(e=>l.set(e,[])),t.listTargets().forEach(e=>{e.listAttributes().forEach(e=>l.set(e,[]))});const g=[];let u=0;for(let e=0;e<c;e++){const n=a?a.getScalar(e):e,s=[],r=[];for(const e of t.listAttributes())for(let t=0;t<e.getElementSize();t++)s.push(~~(e.getElement(n,r)[t]*o));const c=s.join("|");if(c in i)g.push(i[c]);else{for(const e of t.listAttributes())l.get(e).push(e.getElement(n,[]));for(const e of t.listTargets())for(const t of e.listAttributes())l.get(t).push(t.getElement(n,[]));i[c]=u,g.push(u),u++}}const f=t.listAttributes()[0].getCount(),p=l.get(t.getAttribute("POSITION")).length;e.getLogger().debug(`weld: ${f} → ${p} vertices.`);for(const e of t.listAttributes())Fe(t,e,l.get(e)),1===e.listParents().length&&e.dispose();for(const e of t.listTargets())for(const t of e.listAttributes())Fe(e,t,l.get(t)),1===t.listParents().length&&t.dispose();if(a){const e=ke(a.getArray(),g.length);e.set(g),t.setIndices(a.clone().setArray(e)),1===a.listParents().length&&a.dispose()}else{const n=f<=65534?new Uint16Array(g):new Uint32Array(g);t.setIndices(e.createAccessor().setArray(n))}}function ke(e,t){return new(0,e.constructor)(t)}function Fe(e,t,n){const s=n.length*t.getElementSize(),r=ke(t.getArray(),s),o=t.clone().setArray(r);for(let e=0;e<n.length;e++)o.setElement(e,n[e]);e.swap(t,o)}export{se as QUANTIZE_DEFAULTS,Ce as TEXTURE_RESIZE_DEFAULTS,Re as TextureResizeFilter,O as center,x as colorspace,z as dedup,_ as inspect,D as instance,Z as metalRough,ee as partition,Y as prune,re as quantize,ye as reorder,de as resample,Ie as sequence,we as tangents,Oe as textureResize,Pe as unweld,$e as weld}; | ||
import{bounds as e,PropertyType as t,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,Animation as u,Accessor as f,AnimationSampler as p,uuid as m}from"@gltf-transform/core";export{bounds}from"@gltf-transform/core";import{getPixels as d,savePixels as h}from"ndarray-pixels";import{MeshGPUInstancing as A,MaterialsIOR as y,MaterialsSpecular as E,MaterialsPBRSpecularGlossiness as T,MeshQuantization as S}from"@gltf-transform/extensions";import{invert as I,fromRotationTranslationScale as b,fromScaling as w,multiply as M}from"gl-matrix/mat4";import{transformMat4 as N,min as R,scale as C,max as x}from"gl-matrix/vec3";import O from"ndarray";import{lanczos3 as P,lanczos2 as z}from"ndarray-lanczos";function L(){return(L=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e}).apply(this,arguments)}const v={pivot:"center"};function $(t=v){const n=L({},v,t);return 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(e=>{const t=e.getTranslation();e.setTranslation([t[0]+l[0],t[1]+l[1],t[2]+l[2]])})}),s.debug("center: Complete.")}}function _(e){return t=>{const n=t.getLogger();if("linear"===e.inputEncoding)return void n.info("colorspace: Vertex colors already linear. Skipping conversion.");if("sRGB"!==e.inputEncoding)return void n.error(`colorspace: Unknown input encoding "${e.inputEncoding}" – should be "sRGB" or "linear". Skipping conversion.`);const s=new Set;function r(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function o(e){const t=[0,0,0];let n;for(let o=0;n=e.getAttribute(`COLOR_${o}`);o++)if(!s.has(n)){for(let e=0;e<n.getCount();e++)n.getElement(e,t),t[0]=r(t[0]),t[1]=r(t[1]),t[2]=r(t[2]),n.setElement(e,t);s.add(n)}}t.getRoot().listMeshes().forEach(e=>e.listPrimitives().forEach(o)),n.debug("colorspace: Complete.")}}const k={propertyTypes:[t.ACCESSOR,t.MESH,t.TEXTURE]},F=function(e=k){const r=L({},k,e),o=new Set(r.propertyTypes);for(const e of r.propertyTypes)if(!k.propertyTypes.includes(e))throw new Error(`dedup: Unsupported deduplication on type "${e}".`);return e=>{const r=e.getLogger();o.has(t.ACCESSOR)&&function(e,t){const s=new Set,r=new Set,o=t.getRoot().listMeshes();function i(e){const t=new Map;for(let s=0;s<e.length;s++){const r=e[s],o=r.getArray().slice().buffer;if(!t.has(r))for(let s=0;s<e.length;s++){const i=e[s];r!==i&&(t.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)&&t.set(i,r))}}return t}o.forEach(e=>{e.listPrimitives().forEach(e=>{e.listAttributes().forEach(e=>r.add(e));const t=e.getIndices();t&&s.add(t)})});const a=i(Array.from(s));e.debug(`dedup: Found ${a.size} duplicates among ${s.size} indices.`);const c=i(Array.from(r));e.debug(`dedup: Found ${c.size} duplicates among ${r.size} attributes.`),o.forEach(e=>{e.listPrimitives().forEach(e=>{e.listAttributes().forEach(t=>{c.has(t)&&e.swap(t,c.get(t))});const t=e.getIndices();t&&a.has(t)&&e.swap(t,a.get(t))})}),Array.from(a.keys()).forEach(e=>e.dispose()),Array.from(c.keys()).forEach(e=>e.dispose())}(r,e),o.has(t.MESH)&&function(e,n){const s=n.getRoot(),r=new Map;s.listAccessors().forEach((e,t)=>{r.set(e,t)});const o=s.listMeshes().length,i=new Map;for(const e of s.listMeshes()){const n=[];for(const t of e.listPrimitives()){const e=[];for(const n of t.listSemantics()){const s=t.getAttribute(n);e.push(n+":"+r.get(s))}const s=t.getIndices();s&&e.push("indices:"+r.get(s)),n.push(e.join(","))}const s=n.join(";");if(i.has(s)){const n=i.get(s);e.listParents().forEach(s=>{s.propertyType!==t.ROOT&&s.swap(e,n)}),e.dispose()}else i.set(s,e)}e.debug(`dedup: Found ${o-i.size} duplicates among ${o} meshes.`)}(r,e),o.has(t.TEXTURE)&&function(e,t){const r=t.getRoot(),o=r.listTextures(),i=new Map;for(let e=0;e<o.length;e++){const t=o[e],s=t.getImage();if(!i.has(t))for(let e=0;e<o.length;e++){const r=o[e],a=r.getImage();if(t===r)continue;if(i.has(r))continue;if(t.getMimeType()!==r.getMimeType())continue;const c=t.getSize(),l=r.getSize();c&&l&&c[0]===l[0]&&c[1]===l[1]&&s&&a&&n.equals(s,a)&&i.set(r,t)}}e.debug(`dedup: Found ${i.size} duplicates among ${r.listTextures().length} textures.`),Array.from(i.entries()).forEach(([e,t])=>{e.listParents().forEach(n=>{n instanceof s||n.swap(e,t)}),e.dispose()})}(r,e),r.debug("dedup: Complete.")}};async function U(e,t,n){if(!e)return null;const s=e.getImage();if(!s)return null;const r=await d(new Uint8Array(s),e.getMimeType());for(let e=0;e<r.shape[0];++e)for(let t=0;t<r.shape[1];++t)n(r,e,t);const o=(await h(r,"image/png")).buffer;return t.setImage(o).setMimeType("image/png")}function q(e){const t=e.getIndices(),n=e.getAttribute("POSITION");switch(e.getMode()){case r.Mode.POINTS:return n.getCount();case r.Mode.LINES:return t?t.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 t?t.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: "+e.getMode())}}class G{constructor(){this._map=new Map}get size(){return this._map.size}has(e){return this._map.has(e)}add(e,t){let n=this._map.get(e);return n||(n=new Set,this._map.set(e,n)),n.add(t),this}get(e){return this._map.get(e)||new Set}keys(){return this._map.keys()}}function B(e){return{scenes:V(e),meshes:j(e),materials:W(e),textures:D(e),animations:X(e)}}function V(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:K(s.min),bboxMax:K(s.max)}})}}function j(e){return{properties:e.getRoot().listMeshes().map(e=>{const t=e.listParents().filter(e=>"Root"!==e.propertyType).length;let n=0,s=0;const r=new Set,o=new Set,i=new Set;e.listPrimitives().forEach(e=>{for(const t of e.listSemantics()){const n=e.getAttribute(t);r.add(t+":"+Z(n.getArray())),i.add(n)}for(const t of e.listTargets())t.listAttributes().forEach(e=>i.add(e));const t=e.getIndices();t&&(o.add(Z(t.getArray())),i.add(t)),s+=e.listAttributes()[0].getCount(),n+=q(e)});let a=0;Array.from(i).forEach(e=>a+=e.getArray().byteLength);const c=e.listPrimitives().map(e=>H[e.getMode()]);return{name:e.getName(),mode:Array.from(new Set(c)),primitives:e.listPrimitives().length,glPrimitives:n,vertices:s,indices:Array.from(o).sort(),attributes:Array.from(r).sort(),instances:t,size:a}})}}function W(e){return{properties:e.getRoot().listMaterials().map(t=>{const n=t.listParents().filter(e=>"Root"!==e.propertyType).length,s=new Set(t.listExtensions()),r=e.getGraph().getLinks().filter(e=>{const n=e.getChild(),r=e.getParent();return n instanceof o&&r===t||!!(n instanceof o&&r instanceof i&&s.has(r))}).map(e=>e.getName());return{name:t.getName(),instances:n,textures:r,alphaMode:t.getAlphaMode(),doubleSided:t.getDoubleSided()}})}}function D(e){return{properties:e.getRoot().listTextures().map(t=>{const n=t.listParents().filter(e=>"Root"!==e.propertyType).length,s=e.getGraph().listParentLinks(t).map(e=>e.getName()).filter(e=>"texture"!==e),r=a.getSize(t.getImage(),t.getMimeType());return{name:t.getName(),uri:t.getURI(),slots:Array.from(new Set(s)),instances:n,mimeType:t.getMimeType(),resolution:r?r.join("x"):"",size:t.getImage().byteLength,gpuSize:a.getMemSize(t.getImage(),t.getMimeType())}})}}function X(e){return{properties:e.getRoot().listAnimations().map(e=>{let t=Infinity,n=-Infinity;e.listSamplers().forEach(e=>{const s=e.getInput();s&&(t=Math.min(t,s.getMin([])[0]),n=Math.max(n,s.getMax([])[0]))});let s=0,r=0;const o=new Set;return e.listSamplers().forEach(e=>{const t=e.getInput(),n=e.getOutput();t&&(r+=t.getCount(),o.add(t),n&&o.add(n))}),Array.from(o).forEach(e=>{s+=e.getArray().byteLength}),{name:e.getName(),channels:e.listChannels().length,samplers:e.listSamplers().length,duration:Math.round(1e3*(n-t))/1e3,keyframes:r,size:s}})}}const H=["POINTS","LINES","LINE_LOOP","LINE_STRIP","TRIANGLES","TRIANGLE_STRIP","TRIANGLE_FAN"];function K(e){for(let t=0;t<e.length;t++)e[t].toFixed&&(e[t]=Number(e[t].toFixed(5)));return e}function Z(e){return e.constructor.name.replace("Array","").toLowerCase()}const J={};function Y(e=J){return L({},J,e),e=>{const t=e.getLogger(),n=e.getRoot(),s=e.createExtension(A);if(n.listAnimations().length)throw new Error("instance: Instancing is not currently supported for animated models.");let r=0,o=0;for(const i of n.listScenes()){const n=new Map;i.traverse(e=>{const t=e.getMesh();t&&n.set(t,(n.get(t)||new Set).add(e))});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(e=>e.getSkin()))continue;const u=ee(e,s,l,g.length),f=u.getAttribute("TRANSLATION"),p=u.getAttribute("ROTATION"),m=u.getAttribute("SCALE"),d=e.createNode().setMesh(l).setExtension("EXT_mesh_gpu_instancing",u);i.addChild(d);let h=!1,A=!1,y=!1;for(let e=0;e<g.length;e++){let t,n,s;const r=g[e];f.setElement(e,t=r.getWorldTranslation()),p.setElement(e,n=r.getWorldRotation()),m.setElement(e,s=r.getWorldScale()),c.eq(t,[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,t),r++,o+=g.length}}r>0?t.info(`instance: Created ${r} batches, with ${o} total instances.`):(t.info("instance: No meshes with multiple parent nodes were found."),s.dispose()),t.debug("instance: Complete.")}}function Q(e,t){let n,s=0;for(;n=e.pop();){if(n.listChildren().length||n.getCamera()||n.getMesh()||n.getSkin()||n.listExtensions().length)continue;const t=n.getParent();t instanceof l&&e.push(t),n.dispose(),s++}t.debug(`instance: Removed ${s} unused nodes.`)}function ee(e,t,n,s){const r=n.listPrimitives()[0].getAttribute("POSITION").getBuffer(),o=e.createAccessor().setType("VEC3").setArray(new Float32Array(3*s)).setBuffer(r),i=e.createAccessor().setType("VEC4").setArray(new Float32Array(4*s)).setBuffer(r),a=e.createAccessor().setType("VEC3").setArray(new Float32Array(3*s)).setBuffer(r);return t.createInstancedMesh().setAttribute("TRANSLATION",o).setAttribute("ROTATION",i).setAttribute("SCALE",a)}const te={};function ne(e=te){return L({},te,e),async e=>{const t=e.getLogger(),n=T.EXTENSION_NAME;if(!e.getRoot().listExtensionsUsed().map(e=>e.extensionName).includes(n))return void t.warn(`metalRough: Extension ${n} not found on given document.`);const s=e.createExtension(y),r=e.createExtension(E),o=e.createExtension(T),i=new Set;for(const t of e.getRoot().listMaterials()){const n=t.getExtension("KHR_materials_pbrSpecularGlossiness");if(!n)continue;const o=r.createSpecular().setSpecularFactor(1).setSpecularColorFactor(n.getSpecularFactor());i.add(n.getSpecularGlossinessTexture()),i.add(t.getBaseColorTexture()),i.add(t.getMetallicRoughnessTexture()),t.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&&(t.setBaseColorTexture(a),t.getBaseColorTextureInfo().copy(n.getDiffuseTextureInfo()));const c=n.getSpecularGlossinessTexture();if(c){const s=n.getSpecularGlossinessTextureInfo(),r=e.createTexture();await U(c,r,(e,t,n)=>{e.set(t,n,3,255)}),o.setSpecularTexture(r),o.setSpecularColorTexture(r),o.getSpecularTextureInfo().copy(s),o.getSpecularColorTextureInfo().copy(s);const i=n.getGlossinessFactor(),a=e.createTexture();await U(c,a,(e,t,n)=>{const s=255-Math.round(e.get(t,n,3)*i);e.set(t,n,0,0),e.set(t,n,1,s),e.set(t,n,2,0),e.set(t,n,3,255)}),t.setMetallicRoughnessTexture(a),t.getMetallicRoughnessTextureInfo().copy(s)}else o.setSpecularColorFactor(n.getSpecularFactor()),t.setRoughnessFactor(1-n.getGlossinessFactor());t.setExtension("KHR_materials_pbrSpecularGlossiness",null)}o.dispose();for(const e of i)e&&1===e.listParents().length&&e.dispose();t.debug("metalRough: Complete.")}}const se={propertyTypes:[t.NODE,t.SKIN,t.MESH,t.CAMERA,t.PRIMITIVE,t.PRIMITIVE_TARGET,t.ANIMATION,t.MATERIAL,t.TEXTURE,t.ACCESSOR,t.BUFFER]},re=function(e=se){const n=L({},se,e).propertyTypes;return e=>{const r=e.getLogger(),o=e.getRoot(),i=e.getGraph(),a={};if(n.includes(t.NODE)&&o.listNodes().forEach(c),n.includes(t.SKIN)&&o.listSkins().forEach(c),n.includes(t.MESH)&&o.listMeshes().forEach(c),n.includes(t.CAMERA)&&o.listCameras().forEach(c),n.includes(t.PRIMITIVE)&&l(i,t.PRIMITIVE),n.includes(t.PRIMITIVE_TARGET)&&l(i,t.PRIMITIVE_TARGET),n.includes(t.ANIMATION))for(const e of o.listAnimations()){for(const t of e.listChannels())t.getTargetNode()||(t.dispose(),u(t));if(e.listChannels().length)e.listSamplers().forEach(c);else{const t=e.listSamplers();c(e),t.forEach(c)}}if(n.includes(t.MATERIAL)&&o.listMaterials().forEach(c),n.includes(t.TEXTURE)&&o.listTextures().forEach(c),n.includes(t.ACCESSOR)&&o.listAccessors().forEach(c),n.includes(t.BUFFER)&&o.listBuffers().forEach(c),Object.keys(a).length){const e=Object.keys(a).map(e=>`${e} (${a[e]})`).join(", ");r.info(`prune: Removed types... ${e}`)}else r.info("prune: No unused properties found.");function c(e){e.listParents().filter(e=>!(e instanceof s||e instanceof g)).length||(e.dispose(),u(e))}function l(e,t){e.getLinks().map(e=>e.getParent()).filter(e=>e.propertyType===t).forEach(c)}function u(e){a[e.propertyType]=a[e.propertyType]||0,a[e.propertyType]++}r.debug("prune: Complete.")}},oe={animations:!0,meshes:!0},ie=(e=oe)=>{const n=L({},oe,e);return async e=>{const s=e.getLogger();!1!==n.meshes&&function(e,t,n){const s=new Set(e.getRoot().listBuffers().map(e=>e.getURI()));e.getRoot().listMeshes().forEach((r,o)=>{if(Array.isArray(n.meshes)&&!n.meshes.includes(r.getName()))return void t.debug(`partition: Skipping mesh #${o} with name "${r.getName()}".`);t.debug(`partition: Creating buffer for mesh "${r.getName()}".`);const i=e.createBuffer(r.getName()).setURI(ae(r.getName()||"mesh",s));r.listPrimitives().forEach(e=>{const t=e.getIndices();t&&t.setBuffer(i),e.listAttributes().forEach(e=>e.setBuffer(i)),e.listTargets().forEach(e=>{e.listAttributes().forEach(e=>e.setBuffer(i))})})})}(e,s,n),!1!==n.animations&&function(e,t,n){const s=new Set(e.getRoot().listBuffers().map(e=>e.getURI()));e.getRoot().listAnimations().forEach((r,o)=>{if(Array.isArray(n.animations)&&!n.animations.includes(r.getName()))return void t.debug(`partition: Skipping animation #${o} with name "${r.getName()}".`);t.debug(`partition: Creating buffer for animation "${r.getName()}".`);const i=e.createBuffer(r.getName()).setURI(ae(r.getName()||"animation",s));r.listSamplers().forEach(e=>{const t=e.getInput(),n=e.getOutput();t&&t.setBuffer(i),n&&n.setBuffer(i)})})}(e,s,n),n.meshes||n.animations||s.warn("partition: Select animations or meshes to create a partition."),await e.transform(re({propertyTypes:[t.BUFFER]})),s.debug("partition: Complete.")}};function ae(e,t){let n=`${e}.bin`,s=1;for(;t.has(n);)n=`${e}_${s++}.bin`;return n}const ce=[Int8Array,Int16Array,Int32Array],le={excludeAttributes:[],quantizationVolume:"mesh",quantizePosition:14,quantizeNormal:10,quantizeTexcoord:12,quantizeColor:8,quantizeWeight:8,quantizeGeneric:12},ge=(e=le)=>{const n=L({},le,e);return async e=>{const s=e.getLogger(),r=e.getRoot();let o;e.createExtension(S).setRequired(!0),"scene"===n.quantizationVolume&&(o=fe(function(e){const t=e[0];for(const n of e)R(t.min,t.min,n.min),x(t.max,t.max,n.max);return t}(r.listMeshes().map(Ae))));for(const t of e.getRoot().listMeshes()){"mesh"===n.quantizationVolume&&(o=fe(Ae(t))),o&&!n.excludeAttributes.includes("POSITION")&&pe(e,t,o);for(const s of t.listPrimitives()){ue(e,s,o,n);for(const t of s.listTargets())ue(e,t,o,n)}}await e.transform(re({propertyTypes:[t.ACCESSOR,t.SKIN]}),F({propertyTypes:[t.ACCESSOR]})),s.debug("quantize: Complete.")}};function ue(e,t,n,s){const o=e.getLogger();for(const e of t.listSemantics()){if(s.excludeAttributes.includes(e))continue;const i=t.getAttribute(e),{bits:a,ctor:c}=he(e,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"===e){const e=n.scale,s=[];t instanceof r?I(s,Ee(n)):w(s,[1/e,1/e,1/e]);for(let e=0,t=[0,0,0],n=l.getCount();e<n;e++)l.getElement(e,t),l.setElement(e,N(t,t,s))}de(l,c,a),t.swap(i,l)}if(t instanceof r&&t.getIndices()&&t.listAttributes().length&&t.listAttributes()[0].getCount()<65535){const e=t.getIndices();e.setArray(new Uint16Array(e.getArray()))}}function fe(e){const{min:t,max:n}=e,s=Math.max((n[0]-t[0])/2,(n[1]-t[1])/2,(n[2]-t[2])/2);return{offset:[t[0]+(n[0]-t[0])/2,t[1]+(n[1]-t[1])/2,t[2]+(n[2]-t[2])/2],scale:s}}function pe(e,t,n){const s=Ee(n);for(const r of t.listParents())if(r instanceof l){const o=r.listChildren().length>0,i=!!r.listParents().find(e=>e instanceof u);if(r.getSkin()){r.setSkin(me(r.getSkin(),n));continue}let a;o||i?(a=e.createNode("").setMesh(t),r.addChild(a).setMesh(null)):a=r;const c=a.getMatrix();M(c,c,s),a.setMatrix(c)}}function me(e,t){e=e.clone();const n=Ee(t),s=e.getInverseBindMatrices().clone(),r=[];for(let e=0,t=s.getCount();e<t;e++)s.getElement(e,r),M(r,r,n),s.setElement(e,r);return e.setInverseBindMatrices(s)}function de(e,t,n){const s=new t(e.getArray().length),r=ce.includes(t)?1:0,o=n-r,i=8*t.BYTES_PER_ELEMENT-r,a=Math.pow(2,o)-1,c=i-o,l=2*o-i;for(let t=0,n=0,r=[];t<e.getCount();t++){e.getElement(t,r);for(let e=0;e<r.length;e++){let t=Math.round(Math.abs(r[e])*a);t=t<<c|t>>l,s[n++]=t*Math.sign(r[e])}}e.setArray(s).setNormalized(!0)}function he(e,t,n,s){const r=t.getMinNormalized([]),o=t.getMaxNormalized([]);let i,a;if("POSITION"===e)i=s.quantizePosition,a=i<=8?Int8Array:Int16Array;else if("NORMAL"===e||"TANGENT"===e)i=s.quantizeNormal,a=i<=8?Int8Array:Int16Array;else if(e.startsWith("COLOR_"))i=s.quantizeColor,a=i<=8?Uint8Array:Uint16Array;else if(e.startsWith("TEXCOORD_")){if(r.some(e=>e<0)||o.some(e=>e>1))return n.warn(`quantize: Skipping ${e}; out of [0,1] range.`),{bits:-1};i=s.quantizeTexcoord,a=i<=8?Uint8Array:Uint16Array}else{if(e.startsWith("JOINTS_"))return i=Math.max(...t.getMax([]))<=255?8:16,a=i<=8?Uint8Array:Uint16Array,t.getComponentSize()>i/8&&t.setArray(new a(t.getArray())),{bits:-1};if(e.startsWith("WEIGHTS_")){if(r.some(e=>e<0)||o.some(e=>e>1))return n.warn(`quantize: Skipping ${e}; out of [0,1] range.`),{bits:-1};i=s.quantizeWeight,a=i<=8?Uint8Array:Uint16Array}else{if(!e.startsWith("_"))throw new Error(`quantize: Unexpected semantic, "${e}".`);if(r.some(e=>e<-1)||o.some(e=>e>1))return n.warn(`quantize: Skipping ${e}; out of [-1,1] range.`),{bits:-1};i=s.quantizeGeneric,a=a=r.some(e=>e<0)?i<=8?Int8Array:Int16Array:i<=8?Uint8Array:Uint16Array}}return{bits:i,ctor:a}}function Ae(e){const t=[],n=[];for(const s of e.listPrimitives()){const e=s.getAttribute("POSITION");e&&t.push(e);for(const e of s.listTargets()){const t=e.getAttribute("POSITION");t&&n.push(t)}}if(0===t.length)throw new Error('quantize: Missing "POSITION" attribute.');const s=ye(t,3);if(n.length>0){const{min:e,max:t}=ye(n,3);R(s.min,s.min,R(e,C(e,e,2),[0,0,0])),x(s.max,s.max,x(t,C(t,t,2),[0,0,0]))}return s}function ye(e,t){const n=new Array(t).fill(Infinity),s=new Array(t).fill(-Infinity),r=[],o=[];for(const i of e){i.getMinNormalized(r),i.getMaxNormalized(o);for(let e=0;e<t;e++)n[e]=Math.min(n[e],r[e]),s[e]=Math.max(s[e],o[e])}return{min:n,max:s}}function Ee(e){return b([],[0,0,0,1],e.offset,[e.scale,e.scale,e.scale])}const Te={tolerance:1e-4},Se=(e=Te)=>{const t=L({},Te,e);return e=>{const n=new Set,r=e.getRoot().listAccessors().length,o=e.getLogger();let i=!1;for(const s of e.getRoot().listAnimations()){const e=new Set;for(const t of s.listChannels())t.getSampler()&&"weights"===t.getTargetPath()&&e.add(t.getSampler());for(const r of s.listSamplers())e.has(r)?i=!0:"STEP"!==r.getInterpolation()&&"LINEAR"!==r.getInterpolation()||(n.add(r.getInput()),n.add(r.getOutput()),Ie(r,t))}for(const e of Array.from(n.values()))e.listParents().some(e=>!(e instanceof s))||e.dispose();e.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 Ie(e,t){const n=e.getInput().clone(),s=e.getOutput().clone(),r=t.tolerance,o=n.getCount()-1,i=[];let a=1;for(let t=1;t<o;++t){const o=n.getScalar(t),l=n.getScalar(t-1),g=n.getScalar(t+1),u=(o-l)/(g-l);let f=!1;if(o!==g&&(1!==t||o!==n.getScalar(0)))for(let n=0;n<s.getElementSize();n++){const o=s.getElement(t,i)[n],a=s.getElement(t-1,i)[n],l=s.getElement(t+1,i)[n];if("LINEAR"===e.getInterpolation()){if(Math.abs(o-(a*(1-(c=u))+l*c))>r){f=!0;break}}else if("STEP"===e.getInterpolation()&&(o!==a||o!==l)){f=!0;break}}f&&(t!==a&&(n.setScalar(a,n.getScalar(t)),s.setElement(a,s.getElement(t,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())),e.setInput(n),e.setOutput(s)):(n.dispose(),s.dispose())}const be={target:"size"};function we(e=be){const n=L({},be,e),s=n.encoder;return async e=>{const o=e.getLogger();await s.ready;const i=function(e){const t=new G,n=new Map,s=new G;for(const r of e.getRoot().listMeshes())for(const e of r.listPrimitives()){const r=e.getIndices();if(r){n.set(r,e.getMode());for(const n of Ne(e))t.add(r,n),s.add(n,e)}}return{indicesToAttributes:t,indicesToMode:n,attributesToPrimitives:s}}(e);for(const e of i.indicesToAttributes.keys()){const t=e.clone();let o=t.getArray().slice();o instanceof Uint32Array||(o=new Uint32Array(o));const[a,c]=s.reorderMesh(o,i.indicesToMode.get(e)===r.Mode.TRIANGLES,"size"===n.target);t.setArray(c<=65534?new Uint16Array(o):o);for(const n of i.indicesToAttributes.get(e)){const s=n.clone();Me(s,a,c);for(const r of i.attributesToPrimitives.get(n))if(r.getIndices()===e&&r.swap(e,t),r.getIndices()===t){r.swap(n,s);for(const e of r.listTargets())e.swap(n,s)}}}await e.transform(re({propertyTypes:[t.ACCESSOR]})),i.indicesToAttributes.size?o.debug("reorder: Complete."):o.warn("reorder: No qualifying primitives found; may need to weld first.")}}function Me(e,t,n){const s=e.getElementSize(),r=e.getCount(),o=e.getArray(),i=o.slice(0,n*s);for(let e=0;e<r;e++)for(let n=0;n<s;n++)i[t[e]*s+n]=o[e*s+n];e.setArray(i)}function Ne(e){const t=[];for(const n of e.listAttributes())t.push(n);for(const n of e.listTargets())for(const e of n.listAttributes())t.push(e);return Array.from(new Set(t))}const Re={name:"",fps:10,pattern:/.*/,sort:!0};function Ce(e=Re){const t=L({},Re,e);return e=>{const n=e.getLogger(),s=e.getRoot(),r=t.fps,o=s.listNodes().filter(e=>e.getName().match(t.pattern));t.sort&&o.sort((e,t)=>e.getName()>t.getName()?1:-1);const i=e.createAnimation(t.name),a=s.listBuffers()[0];o.forEach((t,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=e.createAccessor().setArray(new Float32Array(s)).setBuffer(a),u=e.createAccessor().setArray(new Float32Array(c)).setBuffer(a).setType(f.Type.VEC3),m=e.createAnimationSampler().setInterpolation(p.Interpolation.STEP).setInput(l).setOutput(u),d=e.createAnimationChannel().setTargetNode(t).setTargetPath(g.TargetPath.SCALE).setSampler(m);i.addSampler(m).addChannel(d)}),n.debug("sequence: Complete.")}}const xe={overwrite:!1};function Oe(e=xe){if(!e.generateTangents)throw new Error('tangents: generateTangents callback required — install "mikktspace".');const t=L({},xe,e);return e=>{const n=e.getLogger(),s=new Map,r=new Map;let o=0;for(const i of e.getRoot().listMeshes()){const a=i.getName(),c=i.listPrimitives();for(let i=0;i<c.length;i++){const l=c[i];if(!Pe(l,n,a,i,t.overwrite))continue;const g=l.getAttribute("POSITION").getArray(),u=l.getAttribute("NORMAL").getArray(),f=l.getAttribute("TEXCOORD_0").getArray(),p=s.get(g)||m();s.set(g,p);const d=s.get(u)||m();s.set(u,d);const h=s.get(f)||m();s.set(f,h);const A=l.getAttribute("TANGENT");A&&2===A.listParents().length&&A.dispose();const y=`${p}|${d}|${h}`;let E=r.get(y);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 T=l.getAttribute("POSITION").getBuffer(),S=t.generateTangents(g instanceof Float32Array?g:new Float32Array(g),u instanceof Float32Array?u:new Float32Array(u),f instanceof Float32Array?f:new Float32Array(f));for(let e=3;e<S.length;e+=4)S[e]*=-1;E=e.createAccessor().setBuffer(T).setArray(S).setType("VEC4"),l.setAttribute("TANGENT",E),r.set(y,E),o++}}o?n.debug("tangents: Complete."):n.warn("tangents: No qualifying primitives found. See debug output.")}}function Pe(e,t,n,s,o){return e.getMode()===r.Mode.TRIANGLES&&e.getAttribute("POSITION")&&e.getAttribute("NORMAL")&&e.getAttribute("TEXCOORD_0")?e.getAttribute("TANGENT")&&!o?(t.debug(`tangents: Skipping primitive ${s} of mesh "${n}": TANGENT found.`),!1):!e.getIndices()||(t.warn(`tangents: Skipping primitive ${s} of mesh "${n}": primitives must be unwelded.`),!1):(t.debug(`tangents: Skipping primitive ${s} of mesh "${n}": primitives must have attributes=[POSITION, NORMAL, TEXCOORD_0] and mode=TRIANGLES.`),!1)}const ze="textureResize";var Le;!function(e){e.LANCZOS3="lanczos3",e.LANCZOS2="lanczos2"}(Le||(Le={}));const ve={size:[2048,2048],filter:Le.LANCZOS3,pattern:null};function $e(e=ve){const t=L({},ve,e);return async e=>{const n=e.getLogger();for(const s of e.getRoot().listTextures()){const e=s.getName(),r=s.getURI();if(t.pattern&&!t.pattern.test(e)&&!t.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]=t.size,[a,c]=s.getSize();if(a<=o&&c<=i){n.debug(`${ze}: Skipping "${r||e}", within size range.`);continue}let l=a,g=c;l>o&&(l=o,g=Math.floor(g*(l/a))),g>i&&(g=i,l=Math.floor(l*(g/c)));const u=new Uint8Array(s.getImage()),f=await d(u,s.getMimeType()),p=O(new Uint8Array(l*g*4),[l,g,4]);n.debug(`${ze}: Resizing "${r||e}", ${f.shape} → ${p.shape}...`);try{t.filter===Le.LANCZOS3?P(f,p):z(f,p)}catch(t){n.warn(`${ze}: Failed to resize "${r||e}": "${t.message}".`);continue}s.setImage((await h(p,s.getMimeType())).buffer)}n.debug(`${ze}: Complete.`)}}const _e={};function ke(e=_e){return L({},_e,e),e=>{const t=e.getLogger(),n=new Map;for(const s of e.getRoot().listMeshes())for(const e of s.listPrimitives()){const s=e.getIndices();if(s){for(const r of e.listAttributes())e.swap(r,Fe(r,s,t,n)),1===r.listParents().length&&r.dispose();for(const r of e.listTargets())for(const e of r.listAttributes())r.swap(e,Fe(e,s,t,n)),1===e.listParents().length&&e.dispose();e.setIndices(null),1===s.listParents().length&&s.dispose()}}t.debug("unweld: Complete.")}}function Fe(e,t,n,s){if(s.has(e)&&s.get(e).has(t))return n.debug(`unweld: Cache hit for reused attribute, "${e.getName()}".`),s.get(e).get(t);const r=e.clone(),o=e.getArray().constructor;r.setArray(new o(t.getCount()*e.getElementSize()));const i=[];for(let n=0;n<t.getCount();n++)r.setElement(n,e.getElement(t.getScalar(n),i));return s.has(e)||s.set(e,new Map),s.get(e).set(t,r),r}const Ue={tolerance:1e-4};function qe(e=Ue){const t=L({},Ue,e);return e=>{const n=e.getLogger();for(const n of e.getRoot().listMeshes())for(const s of n.listPrimitives())0===t.tolerance?Ge(e,s):Be(e,s,t);n.debug("weld: Complete.")}}function Ge(e,t){if(t.getIndices())return;const n=t.listAttributes()[0],s=n.getCount(),r=n.getBuffer(),o=s<=65534?new Uint16Array(3*q(t)):new Uint32Array(3*q(t)),i=e.createAccessor().setBuffer(r).setType(f.Type.SCALAR).setArray(o);for(let e=0;e<i.getCount();e++)i.setScalar(e,e);t.setIndices(i)}function Be(e,t,n){const s=Math.max(n.tolerance,Number.EPSILON),r=Math.log10(1/s),o=Math.pow(10,r),i={},a=t.getIndices(),c=a?a.getCount():t.listAttributes()[0].getCount(),l=new Map;t.listAttributes().forEach(e=>l.set(e,[])),t.listTargets().forEach(e=>{e.listAttributes().forEach(e=>l.set(e,[]))});const g=[];let u=0;for(let e=0;e<c;e++){const n=a?a.getScalar(e):e,s=[],r=[];for(const e of t.listAttributes())for(let t=0;t<e.getElementSize();t++)s.push(~~(e.getElement(n,r)[t]*o));const c=s.join("|");if(c in i)g.push(i[c]);else{for(const e of t.listAttributes())l.get(e).push(e.getElement(n,[]));for(const e of t.listTargets())for(const t of e.listAttributes())l.get(t).push(t.getElement(n,[]));i[c]=u,g.push(u),u++}}const f=t.listAttributes()[0].getCount(),p=l.get(t.getAttribute("POSITION")).length;e.getLogger().debug(`weld: ${f} → ${p} vertices.`);for(const e of t.listAttributes())je(t,e,l.get(e)),1===e.listParents().length&&e.dispose();for(const e of t.listTargets())for(const t of e.listAttributes())je(e,t,l.get(t)),1===t.listParents().length&&t.dispose();if(a){const e=Ve(a.getArray(),g.length);e.set(g),t.setIndices(a.clone().setArray(e)),1===a.listParents().length&&a.dispose()}else{const n=f<=65534?new Uint16Array(g):new Uint32Array(g);t.setIndices(e.createAccessor().setArray(n))}}function Ve(e,t){return new(0,e.constructor)(t)}function je(e,t,n){const s=n.length*t.getElementSize(),r=Ve(t.getArray(),s),o=t.clone().setArray(r);for(let e=0;e<n.length;e++)o.setElement(e,n[e]);e.swap(t,o)}export{le as QUANTIZE_DEFAULTS,ve as TEXTURE_RESIZE_DEFAULTS,Le as TextureResizeFilter,$ as center,_ as colorspace,F as dedup,B as inspect,Y as instance,ne as metalRough,ie as partition,re as prune,ge as quantize,we as reorder,Se as resample,Ce as sequence,Oe as tangents,$e as textureResize,ke as unweld,qe as weld}; | ||
//# sourceMappingURL=functions.modern.js.map |
@@ -21,3 +21,3 @@ import { Transform } from '@gltf-transform/core'; | ||
* ```ts | ||
* import { MeshoptEncoder } from 'path/to/meshopt_encoder.module.js'; | ||
* import { MeshoptEncoder } from 'meshoptimizer'; | ||
* import { reorder } from '@gltf-transform/functions'; | ||
@@ -24,0 +24,0 @@ * |
{ | ||
"name": "@gltf-transform/functions", | ||
"version": "0.12.8", | ||
"version": "0.12.9", | ||
"repository": "github:donmccurdy/glTF-Transform", | ||
@@ -27,4 +27,4 @@ "homepage": "https://gltf-transform.donmccurdy.com/functions.html", | ||
"dependencies": { | ||
"@gltf-transform/core": "^0.12.8", | ||
"@gltf-transform/extensions": "^0.12.8", | ||
"@gltf-transform/core": "^0.12.9", | ||
"@gltf-transform/extensions": "^0.12.9", | ||
"gl-matrix": "^3.3.0", | ||
@@ -45,3 +45,3 @@ "ndarray": "^1.0.19", | ||
}, | ||
"gitHead": "bc16859dafe98c06b1171a088b1861c9f3a1ff05" | ||
"gitHead": "f1746a34aaafa39ccbed30521d71f9ee1b647d6c" | ||
} |
@@ -1,5 +0,6 @@ | ||
import { Accessor, Animation, Document, Logger, Mesh, Node, Primitive, PrimitiveTarget, Transform, vec3, mat4, Skin, bbox, PropertyType, vec2, vec4 } from '@gltf-transform/core'; | ||
import { Accessor, Animation, bbox, Document, Logger, mat4, Mesh, Node, Primitive, PrimitiveTarget, PropertyType, Skin, Transform, vec2, vec3, vec4 } from '@gltf-transform/core'; | ||
import { dedup } from './dedup'; | ||
import { fromRotationTranslationScale, fromScaling, invert, multiply as multiplyMat4 } from 'gl-matrix/mat4'; | ||
import { max, min, scale, transformMat4 } from 'gl-matrix/vec3'; | ||
import { MeshQuantization } from '@gltf-transform/extensions'; | ||
import { fromRotationTranslationScale, multiply as multiplyMat4 } from 'gl-matrix/mat4'; | ||
import { dedup } from './dedup'; | ||
import { prune } from './prune'; | ||
@@ -71,7 +72,5 @@ | ||
if (options.quantizationVolume === 'scene') { | ||
const positions: Accessor[] = []; | ||
for (const mesh of root.listMeshes()) { | ||
positions.push(...listPositionAttributes(mesh)); | ||
} | ||
nodeTransform = getNodeTransform(flatBounds(positions, 3)); | ||
nodeTransform = getNodeTransform( | ||
expandBounds(root.listMeshes().map(getPositionQuantizationVolume)) | ||
); | ||
} | ||
@@ -82,3 +81,3 @@ | ||
if (options.quantizationVolume === 'mesh') { | ||
nodeTransform = getNodeTransform(flatBounds(listPositionAttributes(mesh), 3)); | ||
nodeTransform = getNodeTransform(getPositionQuantizationVolume(mesh)); | ||
} | ||
@@ -129,4 +128,11 @@ | ||
if (semantic === 'POSITION') { | ||
const scale = nodeTransform.scale; | ||
const transform: mat4 = [] as unknown as mat4; | ||
// Morph targets are relative offsets, don't translate them. | ||
prim instanceof Primitive | ||
? invert(transform, fromTransform(nodeTransform)) | ||
: fromScaling(transform, [1 / scale, 1 / scale, 1 / scale]); | ||
for (let i = 0, el: vec3 = [0, 0, 0], il = dstAttribute.getCount(); i < il; i++) { | ||
dstAttribute.setElement(i, nodeTransform.remap(dstAttribute.getElement(i, el))); | ||
dstAttribute.getElement(i, el); | ||
dstAttribute.setElement(i, transformMat4(el, el, transform) as vec3); | ||
} | ||
@@ -149,28 +155,2 @@ } | ||
interface VectorTransform<T = vec2|vec3|vec4> { | ||
remap: (v: number[]) => number[]; | ||
offset: T; | ||
scale: number; | ||
} | ||
/** Computes total min and max of all Accessors in a list. */ | ||
function flatBounds<T = vec2|vec3>(accessors: Accessor[], elementSize: number): ({min: T, max: T}) { | ||
const min: number[] = new Array(elementSize).fill(Infinity); | ||
const max: number[] = new Array(elementSize).fill(-Infinity); | ||
const tmpMin: number[] = []; | ||
const tmpMax: number[] = []; | ||
for (const accessor of accessors) { | ||
accessor.getMinNormalized(tmpMin); | ||
accessor.getMaxNormalized(tmpMax); | ||
for (let i = 0; i < elementSize; i++) { | ||
min[i] = Math.min(min[i], tmpMin[i]); | ||
max[i] = Math.max(max[i], tmpMax[i]); | ||
} | ||
} | ||
return {min, max} as unknown as {min: T, max: T}; | ||
} | ||
/** Computes node quantization transforms in local space. */ | ||
@@ -195,28 +175,5 @@ function getNodeTransform(volume: bbox): VectorTransform<vec3> { | ||
// Transforms mesh vertices to a [-1,1] AABB centered at the origin. | ||
const remap = (v: number[]) => [ | ||
(v[0] - offset[0]) / scale, | ||
(v[1] - offset[1]) / scale, | ||
(v[2] - offset[2]) / scale, | ||
]; | ||
return {remap, offset, scale}; | ||
return {offset, scale}; | ||
} | ||
function listPositionAttributes(mesh: Mesh): Accessor[] { | ||
const positions: Accessor[] = []; | ||
for (const prim of mesh.listPrimitives()) { | ||
const attribute = prim.getAttribute('POSITION'); | ||
if (attribute) positions.push(attribute); | ||
for (const target of prim.listTargets()) { | ||
const attribute = target.getAttribute('POSITION'); | ||
if (attribute) positions.push(attribute); | ||
} | ||
} | ||
if (positions.length === 0) { | ||
throw new Error(`${NAME}: Missing "POSITION" attribute.`); | ||
} | ||
return positions; | ||
} | ||
/** Applies corrective scale and offset to nodes referencing a quantized Mesh. */ | ||
@@ -367,2 +324,67 @@ function transformMeshParents( | ||
function getPositionQuantizationVolume(mesh: Mesh): bbox { | ||
const positions: Accessor[] = []; | ||
const relativePositions: Accessor[] = []; | ||
for (const prim of mesh.listPrimitives()) { | ||
const attribute = prim.getAttribute('POSITION'); | ||
if (attribute) positions.push(attribute); | ||
for (const target of prim.listTargets()) { | ||
const attribute = target.getAttribute('POSITION'); | ||
if (attribute) relativePositions.push(attribute); | ||
} | ||
} | ||
if (positions.length === 0) { | ||
throw new Error(`${NAME}: Missing "POSITION" attribute.`); | ||
} | ||
const bbox = flatBounds<vec3>(positions, 3); | ||
// Morph target quantization volume is computed differently. First, ensure that the origin | ||
// <0, 0, 0> is in the quantization volume. Because we can't offset target positions (they're | ||
// relative deltas), default remapping will only map to a [-2, 2] AABB. Double the bounding box | ||
// to ensure scaling puts them within a [-1, 1] AABB instead. | ||
if (relativePositions.length > 0) { | ||
const {min: relMin, max: relMax} = flatBounds<vec3>(relativePositions, 3); | ||
min(bbox.min, bbox.min, min(relMin, scale(relMin, relMin, 2), [0, 0, 0])); | ||
max(bbox.max, bbox.max, max(relMax, scale(relMax, relMax, 2), [0, 0, 0])); | ||
} | ||
return bbox; | ||
} | ||
/** Computes total min and max of all Accessors in a list. */ | ||
function flatBounds<T = vec2|vec3>(accessors: Accessor[], elementSize: number): ({min: T, max: T}) { | ||
const min: number[] = new Array(elementSize).fill(Infinity); | ||
const max: number[] = new Array(elementSize).fill(-Infinity); | ||
const tmpMin: number[] = []; | ||
const tmpMax: number[] = []; | ||
for (const accessor of accessors) { | ||
accessor.getMinNormalized(tmpMin); | ||
accessor.getMaxNormalized(tmpMax); | ||
for (let i = 0; i < elementSize; i++) { | ||
min[i] = Math.min(min[i], tmpMin[i]); | ||
max[i] = Math.max(max[i], tmpMax[i]); | ||
} | ||
} | ||
return {min, max} as unknown as {min: T, max: T}; | ||
} | ||
function expandBounds(bboxes: bbox[]): bbox { | ||
const result = bboxes[0]; | ||
for (const bbox of bboxes) { | ||
min(result.min, result.min, bbox.min); | ||
max(result.max, result.max, bbox.max); | ||
} | ||
return result; | ||
} | ||
interface VectorTransform<T = vec2|vec3|vec4> { | ||
offset: T; | ||
scale: number; | ||
} | ||
function fromTransform(transform: VectorTransform<vec3>): mat4 { | ||
@@ -369,0 +391,0 @@ return fromRotationTranslationScale( |
@@ -37,3 +37,3 @@ import { Accessor, Document, GLTF, Primitive, PropertyType, Transform } from '@gltf-transform/core'; | ||
* ```ts | ||
* import { MeshoptEncoder } from 'path/to/meshopt_encoder.module.js'; | ||
* import { MeshoptEncoder } from 'meshoptimizer'; | ||
* import { reorder } from '@gltf-transform/functions'; | ||
@@ -40,0 +40,0 @@ * |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
432963
2897