babylon.glTF2Serializer.min.js 16 KB

1
  1. var BABYLON;!(function(e){var t=(function(){function t(){}return t.GLTF=function(t,r,a){var i=r.replace(/\.[^\/.]+$/,""),n=new e.GLTF2._Exporter(t,a);if(t.isReady)return n._generateGLTF(i);throw new Error("glTF Serializer: Scene is not ready!")},t.GLB=function(t,r,a){var i=r.replace(/\.[^\/.]+$/,""),n=new e.GLTF2._Exporter(t,a);if(t.isReady)return n._generateGLB(i);throw new Error("glTF Serializer: Scene is not ready!")},t})();e.GLTF2Export=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(t){var r=(function(){function r(e,t){this.asset={generator:"BabylonJS",version:"2.0"},this.babylonScene=e,this.bufferViews=new Array,this.accessors=new Array,this.meshes=new Array,this.scenes=new Array,this.nodes=new Array,this.images=new Array,this.materials=new Array,this.textures=new Array,this.imageData={},this.convertToRightHandedSystem=!this.babylonScene.useRightHandedSystem,t&&(this.options=t)}return r.prototype.createBufferView=function(e,t,r,a,i){var n={buffer:e,byteLength:r};return t&&(n.byteOffset=t),i&&(n.name=i),a&&(n.byteStride=a),n},r.prototype.createAccessor=function(e,t,r,a,i,n,s,o){var l={name:t,bufferView:e,componentType:a,count:i,type:r};return s&&(l.min=s),o&&(l.max=o),n&&(l.byteOffset=n),l},r.prototype.calculateMinMaxPositions=function(t,a,i){var n=[1/0,1/0,1/0],s=[-1/0,-1/0,-1/0],o=a+i;if(i)for(var l=a;l<o;++l)for(var u=3*l,h=e.Vector3.FromArray(t,u),c=this.convertToRightHandedSystem?r.GetRightHandedVector3(h).asArray():h.asArray(),f=0;f<3;++f){var d=c[f];d<n[f]&&(n[f]=d),d>s[f]&&(s[f]=d),++u}return{min:n,max:s}},r.GetRightHandedVector3=function(t){return new e.Vector3(t.x,t.y,-t.z)},r.GetRightHandedVector4=function(t){return new e.Vector4(t.x,t.y,-t.z,-t.w)},r.GetRightHandedQuaternion=function(t){return new e.Quaternion(-t.x,-t.y,t.z,t.w)},r.prototype.writeAttributeData=function(t,a,i,n,s,o){for(var l=s,u=a.length/i,h=0;h<u;++h){var c=h*i,f=[];if(t===e.VertexBuffer.PositionKind||t===e.VertexBuffer.NormalKind){var d=e.Vector3.FromArray(a,c);f=this.convertToRightHandedSystem?r.GetRightHandedVector3(d).asArray():d.asArray()}else if(t===e.VertexBuffer.TangentKind||t===e.VertexBuffer.ColorKind){var d=e.Vector4.FromArray(a,c);f=this.convertToRightHandedSystem&&t!==e.VertexBuffer.ColorKind?r.GetRightHandedVector4(d).asArray():d.asArray()}else t===e.VertexBuffer.UVKind||t===e.VertexBuffer.UV2Kind?f=[a[c],a[c+1]]:e.Tools.Warn("Unsupported Vertex Buffer Type: "+t);for(var g=0;g<f.length;++g)o.setFloat32(l,f[g],!0),l+=4}return 4*a.length},r.prototype.generateJSON=function(e,t,r){var a={byteLength:this.totalByteLength},i={asset:this.asset};if(a.byteLength&&(i.buffers=[a]),this.nodes&&this.nodes.length&&(i.nodes=this.nodes),this.meshes&&this.meshes.length&&(i.meshes=this.meshes),this.scenes&&this.scenes.length&&(i.scenes=this.scenes,i.scene=0),this.bufferViews&&this.bufferViews.length&&(i.bufferViews=this.bufferViews),this.accessors&&this.accessors.length&&(i.accessors=this.accessors),this.materials&&this.materials.length&&(i.materials=this.materials),this.textures&&this.textures.length&&(i.textures=this.textures),this.images&&this.images.length)if(e){i.images=[];for(var n=this.images.length,s=this.totalByteLength,o=0;o<n;++o){var l=this.images[o];if(l.uri){var u=this.imageData[l.uri],h=l.uri.split(".")[0]+" image",c=this.createBufferView(0,s,u.data.length,void 0,h);s+=u.data.buffer.byteLength,this.bufferViews.push(c),l.bufferView=this.bufferViews.length-1,l.name=h,l.mimeType=u.mimeType,l.uri=void 0,i.images.push(l)}}a.byteLength=s}else i.images=this.images;return e||(a.uri=t+".bin"),r?JSON.stringify(i,null,2):JSON.stringify(i)},r.prototype._generateGLTF=function(t){var r=this.generateBinary(),a=this.generateJSON(!1,t,!0),i=new Blob([r],{type:"application/octet-stream"}),n=t+".gltf",s=t+".bin",o=new e._GLTFData;if(o.glTFFiles[n]=a,o.glTFFiles[s]=i,this.imageData)for(var l in this.imageData)o.glTFFiles[l]=new Blob([this.imageData[l].data],{type:this.imageData[l].mimeType});return o},r.prototype.generateBinary=function(){var e=0;return e=this.createScene(this.babylonScene,e),this.binaryBuffer},r.prototype._getPadding=function(e){var t=e%4;return 0===t?t:4-t},r.prototype._generateGLB=function(t){var r=this.generateBinary(),a=this.generateJSON(!0),i=t+".glb",n=a.length,s=0;for(var o in this.imageData)s+=this.imageData[o].data.byteLength;var l=this._getPadding(n),u=this._getPadding(r.byteLength),h=this._getPadding(s),c=28+n+l+r.byteLength+u+s+h,f=new ArrayBuffer(12),d=new DataView(f);d.setUint32(0,1179937895,!0),d.setUint32(4,2,!0),d.setUint32(8,c,!0);var g=new ArrayBuffer(8+n+l),p=new DataView(g);p.setUint32(0,n+l,!0),p.setUint32(4,1313821514,!0);for(var m=new Uint8Array(g,8),v=0;v<n;++v)m[v]=a.charCodeAt(v);for(var y=new Uint8Array(g,8+n),v=0;v<l;++v)y[v]=32;var T=new ArrayBuffer(8),x=new DataView(T);x.setUint32(0,r.byteLength+s+h,!0),x.setUint32(4,5130562,!0);for(var b=new ArrayBuffer(u),B=new Uint8Array(b),v=0;v<u;++v)B[v]=0;for(var w=new ArrayBuffer(h),A=new Uint8Array(w),v=0;v<h;++v)A[v]=0;var V=[f,g,T,r];for(var o in this.imageData)V.push(this.imageData[o].data.buffer);V.push(b),V.push(w);var M=new Blob(V,{type:"application/octet-stream"}),L=new e._GLTFData;return L.glTFFiles[i]=M,L},r.prototype.setNodeTransformation=function(t,a){0===a.position.x&&0===a.position.y&&0===a.position.z||(t.translation=this.convertToRightHandedSystem?r.GetRightHandedVector3(a.position).asArray():a.position.asArray()),1===a.scaling.x&&1===a.scaling.y&&1===a.scaling.z||(t.scale=a.scaling.asArray());var i=e.Quaternion.RotationYawPitchRoll(a.rotation.y,a.rotation.x,a.rotation.z);a.rotationQuaternion&&(i=i.multiply(a.rotationQuaternion)),0===i.x&&0===i.y&&0===i.z&&1===i.w||(t.rotation=this.convertToRightHandedSystem?r.GetRightHandedQuaternion(i).asArray():i.asArray())},r.prototype.createBufferViewKind=function(t,r,a,i){var n=null,s=0;if(r instanceof e.Mesh?n=r:r instanceof e.InstancedMesh&&(n=r.sourceMesh),n){var o=null,l=null,u=null,h=null;if(n.isVerticesDataPresent(t)&&(o=n.getVertexBuffer(t))&&(l=o.getOffset(),u=o.getData()))if(h=o.getStrideSize(),i&&u)s=this.writeAttributeData(t,u,h,l,a,i),a+=s;else{s=4*u.length;var c=this.createBufferView(0,a,s,4*h,t+" - "+n.name);a+=s,this.bufferViews.push(c)}}return s},r.prototype.setPrimitiveAttributes=function(t,r,a,i){var n=null;r instanceof e.Mesh?n=r:r instanceof e.InstancedMesh&&(n=r.sourceMesh);var s=[{kind:e.VertexBuffer.PositionKind,accessorType:"VEC3"},{kind:e.VertexBuffer.NormalKind,accessorType:"VEC3"},{kind:e.VertexBuffer.ColorKind,accessorType:"VEC4"},{kind:e.VertexBuffer.TangentKind,accessorType:"VEC4"},{kind:e.VertexBuffer.UVKind,accessorType:"VEC2"},{kind:e.VertexBuffer.UV2Kind,accessorType:"VEC2"}],o=null;if(n){for(var l=0,u=s;l<u.length;l++){var h=u[l],c=h.kind;n.isVerticesDataPresent(c)&&(a+=this.createBufferViewKind(c,r,a,i),h.bufferViewIndex=this.bufferViews.length-1)}if(n.getTotalIndices()){var f=n.getIndices();if(f)if(i){for(var d=f.length,g=a,p=0;p<d;++p)i.setUint32(g,f[p],!0),g+=4;a=g}else{var m=4*f.length,v=this.createBufferView(0,a,m,void 0,"Indices - "+n.name);a+=m,this.bufferViews.push(v),o=this.bufferViews.length-1}}if(r.subMeshes)for(var y=0,T=r.subMeshes;y<T.length;y++){var x=T[y],b={attributes:{}};if(!i){for(var B=0,w=s;B<w.length;B++){var h=w[B],c=h.kind;if(n.isVerticesDataPresent(c)){var A=n.getVertexBuffer(c);if(A){var V=A.getData();if(V){var M=A.getStrideSize(),L=void 0,S=null,F=null,R=h.bufferViewIndex;if(void 0!=R){c==e.VertexBuffer.PositionKind&&(L=this.calculateMinMaxPositions(V,0,V.length/M),S=L.min,F=L.max);var E=this.createAccessor(R,c+" - "+r.name,h.accessorType,5126,V.length/M,0,S,F);switch(this.accessors.push(E),c){case e.VertexBuffer.PositionKind:b.attributes.POSITION=this.accessors.length-1;break;case e.VertexBuffer.NormalKind:b.attributes.NORMAL=this.accessors.length-1;break;case e.VertexBuffer.ColorKind:b.attributes.COLOR_0=this.accessors.length-1;break;case e.VertexBuffer.TangentKind:b.attributes.TANGENT=this.accessors.length-1;break;case e.VertexBuffer.UVKind:b.attributes.TEXCOORD_0=this.accessors.length-1;break;case e.VertexBuffer.UV2Kind:b.attributes.TEXCOORD_1=this.accessors.length-1;break;default:e.Tools.Warn("Unsupported Vertex Buffer Type: "+c)}}}}}}if(o){var E=this.createAccessor(o,"indices - "+r.name,"SCALAR",5125,x.indexCount,4*x.indexStart,null,null);this.accessors.push(E),b.indices=this.accessors.length-1}}if(n.material)if(n.material instanceof e.StandardMaterial||n.material instanceof e.PBRMetallicRoughnessMaterial){var C=r.getScene().materials.indexOf(n.material);b.material=C}else if(n.material instanceof e.MultiMaterial){var P=n.material,O=P.subMaterials[x.materialIndex];if(O){var C=r.getScene().materials.indexOf(O);b.material=C}}else e.Tools.Warn("Material type "+n.material.getClassName()+" for material "+n.material.name+" is not yet implemented in glTF serializer.");t.primitives.push(b)}}return a},r.prototype.createScene=function(e,r){if(e.meshes.length){var a=e.meshes,i={nodes:new Array};t._GLTFMaterial.ConvertMaterialsToGLTF(e.materials,"image/jpeg",this.images,this.textures,this.materials,this.imageData,!0);var n=this.createNodeMap(e,r);this.nodeMap=n.nodeMap,this.totalByteLength=n.byteOffset,this.binaryBuffer=new ArrayBuffer(this.totalByteLength);for(var s=new DataView(this.binaryBuffer),o=0;o<a.length;++o)if(!this.options||void 0==this.options.shouldExportMesh||this.options.shouldExportMesh(a[o])){var l=a[o],u=this.nodeMap[l.uniqueId],h=this.nodes[u];l.parent||i.nodes.push(u);var c=l.getDescendants(!0);if(!h.children&&c&&c.length){h.children=[];for(var f=0,d=c;f<d.length;f++){var g=d[f];h.children.push(this.nodeMap[g.uniqueId])}}var p={primitives:new Array};r=this.setPrimitiveAttributes(p,l,r,s)}this.scenes.push(i)}return r},r.prototype.createNodeMap=function(e,t){for(var r={},a=0,i=e.meshes;a<i.length;a++){var n=i[a],s=this.createNode(n,t,null);this.nodes.push(s.node),r[n.uniqueId]=this.nodes.length-1,t=s.byteOffset}return{nodeMap:r,byteOffset:t}},r.prototype.createNode=function(e,t,r){var a={};e.name&&(a.name=e.name),this.setNodeTransformation(a,e);var i={primitives:new Array};return i.primitives=[],t=this.setPrimitiveAttributes(i,e,t,r),i.primitives.length&&(this.meshes.push(i),a.mesh=this.meshes.length-1),{node:a,byteOffset:t}},r})();t._Exporter=r})(e.GLTF2||(e.GLTF2={}))})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){var t=(function(){function e(){this.glTFFiles={}}return e.prototype.downloadFiles=function(){function e(e,t){return-1!==e.indexOf(t,e.length-t.length)}for(var t in this.glTFFiles){var r=document.createElement("a");document.body.appendChild(r),r.setAttribute("type","hidden"),r.download=t;var a=this.glTFFiles[t],i=void 0;e(t,".glb")?i={type:"model/gltf-binary"}:e(t,".bin")?i={type:"application/octet-stream"}:e(t,".gltf")?i={type:"model/gltf+json"}:e(t,".jpeg")?i={type:"image/jpeg"}:e(t,".png")&&(i={type:"image/png"}),r.href=window.URL.createObjectURL(new Blob([a],i)),r.click()}},e})();e._GLTFData=t})(BABYLON||(BABYLON={}));var BABYLON;!(function(e){!(function(t){var r=(function(){function t(){}return t.ConvertMaterialsToGLTF=function(r,a,i,n,s,o,l){for(var u=0;u<r.length;++u){var h=r[u];h instanceof e.StandardMaterial?t.ConvertStandardMaterial(h,a,i,n,s,o,l):h instanceof e.PBRMetallicRoughnessMaterial&&t.ConvertPBRMetallicRoughnessMaterial(h,a,i,n,s,o,l)}},t.ConvertToGLTFPBRMetallicRoughness=function(t){function r(e,t,r,a,i){return(1-e)*(1-e)*(1-e)*t+3*(1-e)*(1-e)*e*r+3*(1-e)*e*e*a+e*e*e*i}var a=new e.Vector2(0,1),i=new e.Vector2(0,.1),n=new e.Vector2(0,.1),s=new e.Vector2(1300,.1),o=t.diffuseColor.toLinearSpace().scale(.5),l=t.alpha,u=e.Scalar.Clamp(t.specularPower,0,this.maxSpecularPower),h=(function(e){return r(Math.pow(e/s.x,.333333),a.y,i.y,n.y,s.y)})(u);return{baseColorFactor:[o.r,o.g,o.b,l],metallicFactor:0,roughnessFactor:h}},t.SolveMetallic=function(r,a,i){if(a<t.dielectricSpecular.r)return t.dielectricSpecular,0;var n=t.dielectricSpecular.r,s=r*i/(1-t.dielectricSpecular.r)+a-2*t.dielectricSpecular.r,o=t.dielectricSpecular.r-a,l=s*s-4*n*o;return e.Scalar.Clamp((-s+Math.sqrt(l))/(2*n),0,1)},t.GetAlphaMode=function(t){if(t instanceof e.StandardMaterial){var r=t;return 1!=r.alpha||null!=r.diffuseTexture&&r.diffuseTexture.hasAlpha||null!=r.opacityTexture?"BLEND":"OPAQUE"}if(!(t instanceof e.PBRMetallicRoughnessMaterial))throw new Error("Unsupported Babylon material type");var a=t;switch(a.transparencyMode){case e.PBRMaterial.PBRMATERIAL_OPAQUE:return"OPAQUE";case e.PBRMaterial.PBRMATERIAL_ALPHABLEND:return"BLEND";case e.PBRMaterial.PBRMATERIAL_ALPHATEST:return"MASK";case e.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND:return e.Tools.Warn(t.name+": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead."),"BLEND";default:throw new Error("Unsupported alpha mode "+a.transparencyMode)}},t.ConvertStandardMaterial=function(r,a,i,n,s,o,l){e.Tools.Warn(r.name+": Standard Material is currently not fully supported/implemented in glTF serializer");var u=t.ConvertToGLTFPBRMetallicRoughness(r),h={name:r.name};if(r.backFaceCulling&&(r.twoSidedLighting||e.Tools.Warn(r.name+": Back-face culling enabled and two-sided lighting disabled is not supported in glTF."),h.doubleSided=!0),l){if(r.diffuseTexture){var c=t.ExportTexture(r.diffuseTexture,a,i,n,o);null!=c&&(u.baseColorTexture=c)}if(r.bumpTexture){var c=t.ExportTexture(r.bumpTexture,a,i,n,o);c&&(h.normalTexture=c)}if(r.emissiveTexture){var f=t.ExportTexture(r.emissiveTexture,a,i,n,o);f&&(h.emissiveTexture=f),h.emissiveFactor=[1,1,1]}if(r.ambientTexture){var d=t.ExportTexture(r.ambientTexture,a,i,n,o);d&&(h.occlusionTexture=d)}}(r.alpha<1||r.opacityTexture)&&(r.alphaMode===e.Engine.ALPHA_COMBINE?h.alphaMode="BLEND":e.Tools.Warn(r.name+": glTF 2.0 does not support alpha mode: "+r.alphaMode.toString())),r.emissiveColor&&(h.emissiveFactor=r.emissiveColor.asArray()),h.pbrMetallicRoughness=u,s.push(h)},t.ConvertPBRMetallicRoughnessMaterial=function(e,r,a,i,n,s,o){var l={};e.baseColor&&(l.baseColorFactor=[e.baseColor.r,e.baseColor.g,e.baseColor.b,e.alpha]),null!=e.metallic&&(l.metallicFactor=e.metallic),null!=e.roughness&&(l.roughnessFactor=e.roughness);var u={name:e.name};if(e.doubleSided&&(u.doubleSided=e.doubleSided),o){if(null!=e.baseTexture){var h=t.ExportTexture(e.baseTexture,r,a,i,s);null!=h&&(l.baseColorTexture=h)}if(e.normalTexture){var h=t.ExportTexture(e.normalTexture,r,a,i,s);h&&(u.normalTexture=h)}if(e.occlusionTexture){var h=t.ExportTexture(e.occlusionTexture,r,a,i,s);h&&(u.occlusionTexture=h,null!=e.occlusionStrength&&(u.occlusionTexture.strength=e.occlusionStrength))}if(e.emissiveTexture){var h=t.ExportTexture(e.emissiveTexture,r,a,i,s);null!=h&&(u.emissiveTexture=h)}}if(e.emissiveColor.equalsFloats(0,0,0)&&(u.emissiveFactor=e.emissiveColor.asArray()),null!=e.transparencyMode){var c=t.GetAlphaMode(e);"OPAQUE"!==c&&(u.alphaMode=c,"BLEND"===c&&(u.alphaCutoff=e.alphaCutOff))}u.pbrMetallicRoughness=l,n.push(u)},t.ExportTexture=function(t,r,a,i,n){var s=null,o={source:a.length},l="texture_"+(i.length-1).toString(),u=t.getInternalTexture();null!=u&&(l=u.url),l=e.Tools.GetFilename(l);var h=l.split(".")[0],c="";"image/jpeg"===r?c=".jpg":"image/png"===r?c=".png":e.Tools.Error("Unsupported mime type "+r),l=h+c;var f=t.readPixels(),d=document.createElement("canvas");d.id="ImageCanvas";var g=d.getContext("2d"),p=t.getSize();d.width=p.width,d.height=p.height;var m=g.createImageData(p.width,p.height);m.data.set(f),g.putImageData(m,0,0);for(var v=d.toDataURL(r),y=atob(v.split(",")[1]),T=new Uint8Array(y.length),x=0;x<y.length;++x)T[x]=y.charCodeAt(x);var b={data:T,mimeType:r};if(n[l]=b,"image/jpeg"===r){for(var B={uri:l},w=-1,x=0;x<a.length;++x)if(a[x].uri===l){w=x;break}-1===w?(a.push(B),o.source=a.length-1,i.push({source:a.length-1}),s={index:a.length-1}):(o.source=w,s={index:w})}return s},t.dielectricSpecular=new e.Color3(.04,.04,.04),t.maxSpecularPower=1024,t})();t._GLTFMaterial=r})(e.GLTF2||(e.GLTF2={}))})(BABYLON||(BABYLON={}));