UNPKG

@animech-public/playcanvas

Version:
2 lines (1 loc) 34.4 kB
import{path as e}from"../../core/path.js";import{Color as t}from"../../core/math/color.js";import{Mat4 as n}from"../../core/math/mat4.js";import{math as s}from"../../core/math/math.js";import{Vec2 as r}from"../../core/math/vec2.js";import{Vec3 as o}from"../../core/math/vec3.js";import{BoundingBox as a}from"../../core/shape/bounding-box.js";import{CULLFACE_NONE as i,CULLFACE_BACK as l,INDEXFORMAT_UINT32 as c,INDEXFORMAT_UINT16 as u,INDEXFORMAT_UINT8 as p,BUFFER_STATIC as h,FILTER_LINEAR_MIPMAP_LINEAR as f,FILTER_NEAREST_MIPMAP_LINEAR as m,FILTER_LINEAR_MIPMAP_NEAREST as d,FILTER_NEAREST_MIPMAP_NEAREST as y,FILTER_LINEAR as g,FILTER_NEAREST as w,ADDRESS_REPEAT as v,ADDRESS_MIRRORED_REPEAT as O,ADDRESS_CLAMP_TO_EDGE as x,PRIMITIVE_TRIANGLES as P,PRIMITIVE_TRIFAN as b,PRIMITIVE_TRISTRIP as T,PRIMITIVE_LINESTRIP as M,PRIMITIVE_LINELOOP as C,PRIMITIVE_LINES as _,PRIMITIVE_POINTS as R,SEMANTIC_NORMAL as A,SEMANTIC_COLOR as k,TYPE_UINT8 as E,TYPE_UINT16 as F,TYPE_FLOAT32 as j,TYPE_UINT32 as S,TYPE_INT32 as I,TYPE_INT16 as V,TYPE_INT8 as D,SEMANTIC_POSITION as U,SEMANTIC_TANGENT as H,SEMANTIC_BLENDINDICES as L,SEMANTIC_BLENDWEIGHT as K,SEMANTIC_TEXCOORD0 as N,SEMANTIC_TEXCOORD1 as $,SEMANTIC_TEXCOORD2 as G,SEMANTIC_TEXCOORD3 as z,SEMANTIC_TEXCOORD4 as B,SEMANTIC_TEXCOORD5 as X,SEMANTIC_TEXCOORD6 as W,SEMANTIC_TEXCOORD7 as J,typedArrayTypesByteSize as Y,typedArrayTypes as q}from"../../platform/graphics/constants.js";import{IndexBuffer as Q}from"../../platform/graphics/index-buffer.js";import{Texture as Z}from"../../platform/graphics/texture.js";import{VertexBuffer as ee}from"../../platform/graphics/vertex-buffer.js";import{VertexFormat as te}from"../../platform/graphics/vertex-format.js";import{http as ne}from"../../platform/net/http.js";import{SPECOCC_AO as se,BLEND_NONE as re,BLEND_NORMAL as oe,PROJECTION_ORTHOGRAPHIC as ae,PROJECTION_PERSPECTIVE as ie,ASPECT_AUTO as le,LIGHTFALLOFF_INVERSESQUARED as ce,ASPECT_MANUAL as ue}from"../../scene/constants.js";import{GraphNode as pe}from"../../scene/graph-node.js";import{Light as he,lightTypes as fe}from"../../scene/light.js";import{Mesh as me}from"../../scene/mesh.js";import{Morph as de}from"../../scene/morph.js";import{MorphTarget as ye}from"../../scene/morph-target.js";import{calculateNormals as ge}from"../../scene/geometry/geometry-utils.js";import{Render as we}from"../../scene/render.js";import{Skin as ve}from"../../scene/skin.js";import{StandardMaterial as Oe}from"../../scene/materials/standard-material.js";import{Entity as xe}from"../entity.js";import{INTERPOLATION_LINEAR as Pe,INTERPOLATION_CUBIC as be,INTERPOLATION_STEP as Te}from"../anim/constants.js";import{AnimCurve as Me}from"../anim/evaluator/anim-curve.js";import{AnimData as Ce}from"../anim/evaluator/anim-data.js";import{AnimTrack as _e}from"../anim/evaluator/anim-track.js";import{Asset as Re}from"../asset/asset.js";import{ABSOLUTE_URL as Ae}from"../asset/constants.js";import{dracoDecode as ke}from"./draco-decoder.js";class Ee{constructor(){this.gltf=void 0,this.nodes=void 0,this.scenes=void 0,this.animations=void 0,this.textures=void 0,this.materials=void 0,this.variants=void 0,this.meshVariants=void 0,this.meshDefaultMaterials=void 0,this.renders=void 0,this.skins=void 0,this.lights=void 0,this.cameras=void 0}destroy(){this.renders&&this.renders.forEach((e=>{e.meshes=null}))}}const Fe=e=>/^data:[^\n\r,\u2028\u2029]*,.*$/i.test(e),je=e=>{switch(e){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":default:return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}},Se=e=>{switch(e){case 5120:return D;case 5121:return E;case 5122:return V;case 5123:return F;case 5124:return I;case 5125:return S;case 5126:return j;default:return 0}},Ie=e=>{switch(e){case 5120:case 5121:return 1;case 5122:case 5123:return 2;case 5124:case 5125:case 5126:return 4;default:return 0}},Ve={POSITION:U,NORMAL:A,TANGENT:H,COLOR_0:k,JOINTS_0:L,WEIGHTS_0:K,TEXCOORD_0:N,TEXCOORD_1:$,TEXCOORD_2:G,TEXCOORD_3:z,TEXCOORD_4:B,TEXCOORD_5:X,TEXCOORD_6:W,TEXCOORD_7:J},De={[U]:0,[A]:1,[H]:2,[k]:3,[L]:4,[K]:5,[N]:6,[$]:7,[G]:8,[z]:9,[B]:10,[X]:11,[W]:12,[J]:13},Ue=(e,t,n)=>{const s=(e=>{switch(e){case D:return e=>Math.max(e/127,-1);case E:return e=>e/255;case V:return e=>Math.max(e/32767,-1);case F:return e=>e/65535;default:return e=>e}})(n),r=t.length;for(let n=0;n<r;++n)e[n]=s(t[n]);return e},He=(e,t,n=!1)=>{const s=je(e.type),r=(e=>{switch(e){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5124:return Int32Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:return null}})(e.componentType);if(!r)return null;let o;if(e.sparse){const n=e.sparse,a={count:n.count,type:"SCALAR"},i=He(Object.assign(a,n.indices),t,!0),l={count:n.count,type:e.type,componentType:e.componentType},c=He(Object.assign(l,n.values),t,!0);if(e.hasOwnProperty("bufferView")){const n={bufferView:e.bufferView,byteOffset:e.byteOffset,componentType:e.componentType,count:e.count,type:e.type};o=He(n,t,!0).slice()}else o=new r(e.count*s);for(let e=0;e<n.count;++e){const t=i[e];for(let n=0;n<s;++n)o[t*s+n]=c[e*s+n]}}else if(e.hasOwnProperty("bufferView")){const a=t[e.bufferView];if(n&&a.hasOwnProperty("byteStride")){const t=s*r.BYTES_PER_ELEMENT,n=new ArrayBuffer(e.count*t),i=new Uint8Array(n);let l=0;for(let n=0;n<e.count;++n){let s=(e.byteOffset||0)+n*a.byteStride;for(let e=0;e<t;++e)i[l++]=a[s++]}o=new r(n)}else o=new r(a.buffer,a.byteOffset+(e.byteOffset||0),e.count*s)}else o=new r(e.count*s);return o},Le=(e,t)=>{const n=He(e,t,!0);if(n instanceof Float32Array||!e.normalized)return n;const s=new Float32Array(n.length);return Ue(s,n,Se(e.componentType)),s},Ke=e=>{let t=e.min,n=e.max;if(!t||!n)return null;if(e.normalized){const s=Se(e.componentType);t=Ue([],t,s),n=Ue([],n,s)}return new a(new o(.5*(n[0]+t[0]),.5*(n[1]+t[1]),.5*(n[2]+t[2])),new o(.5*(n[0]-t[0]),.5*(n[1]-t[1]),.5*(n[2]-t[2])))},Ne=e=>{if(!e.hasOwnProperty("mode"))return P;switch(e.mode){case 0:return R;case 1:return _;case 2:return C;case 3:return M;case 4:default:return P;case 5:return T;case 6:return b}},$e=(e,t)=>{const n=e[U];if(!n||3!==n.components)return;let s;if(n.size!==n.stride){const e=n.stride/Y[n.type],t=new q[n.type](n.buffer,n.offset,n.count*e);s=new q[n.type](3*n.count);for(let r=0;r<n.count;++r)s[3*r+0]=t[r*e+0],s[3*r+1]=t[r*e+1],s[3*r+2]=t[r*e+2]}else s=new q[n.type](n.buffer,n.offset,3*n.count);const r=n.count;t||(t=(e=>{const t=new Uint16Array(e);for(let n=0;n<e;n++)t[n]=n;return t})(r));const o=ge(s,t),a=new Float32Array(o.length);a.set(o),e[A]={buffer:a.buffer,size:12,offset:0,stride:12,count:r,components:3,type:j}},Ge=e=>{const t=new Re(`${e.name}_clone`,e.type,e.file,e.data,e.options);return t.loaded=!0,t.resource=(e=>{const t=new Z(e.device,e);return t._levels=(e=>{const t=[];for(let n=0;n<e._levels.length;++n){let s=[];if(e.cubemap)for(let t=0;t<6;++t)s.push(e._levels[n][t]);else s=e._levels[n];t.push(s)}return t})(e),t})(e.resource),e.registry.add(t),t},ze=(e,t,n)=>{const s=t[U];if(!s)return null;const r=s.count,o=[];for(const n in t)if(t.hasOwnProperty(n)){const s={semantic:n,components:t[n].components,type:t[n].type,normalize:!!t[n].normalize};te.isElementValid(e,s)||s.components++,o.push(s)}let a,i,l,c,u,p;o.sort(((e,t)=>De[e.semantic]-De[t.semantic]));const h=new te(e,o);let f=!0;for(a=0;a<h.elements.length;++a)if(u=h.elements[a],c=t[u.name],p=c.offset-s.offset,c.buffer!==s.buffer||c.stride!==u.stride||c.size!==u.size||p!==u.offset){f=!1;break}const m=new ee(e,h,r),d=m.lock(),y=new Uint32Array(d);let g;if(f)g=new Uint32Array(s.buffer,s.offset,r*m.format.size/4),y.set(g);else{let e,n;for(a=0;a<m.format.elements.length;++a){u=m.format.elements[a],e=u.stride/4,c=t[u.name],n=c.stride/4,g=new Uint32Array(c.buffer,c.offset,(c.count-1)*n+(c.size+3)/4);let s=0,o=u.offset/4;const p=Math.floor((c.size+3)/4);for(i=0;i<r;++i){for(l=0;l<p;++l)y[o+l]=g[s+l];s+=n,o+=e}}}return n&&(e=>{let t,n;const s=[],r=[],o=[];for(t=0;t<e.format.elements.length;++t){const n=e.format.elements[t];if(n.name===N||n.name===$)switch(n.dataType){case j:s.push({offset:n.offset/4+1,stride:n.stride/4});break;case F:r.push({offset:n.offset/2+1,stride:n.stride/2});break;case E:o.push({offset:n.offset+1,stride:n.stride})}}const a=(s,r,o)=>{const a=new r(e.storage);for(t=0;t<s.length;++t){let r=s[t].offset;const i=s[t].stride;for(n=0;n<e.numVertices;++n)a[r]=o-a[r],r+=i}};s.length>0&&a(s,Float32Array,1),r.length>0&&a(r,Uint16Array,65535),o.length>0&&a(o,Uint8Array,255)})(m),m.unlock(),m},Be=(e,t,n,s,r,o,a,i,l,f)=>{const m=[];return t.primitives.forEach((d=>{var y;if(null!=(y=d.extensions)&&y.KHR_draco_mesh_compression)m.push(((e,t,n,s,r,o,a)=>{var i;const l=new me(e);l.aabb=Ke(n[t.attributes.POSITION]);const p=[];for(const[e,s]of Object.entries(t.attributes)){var f;const t=n[s],r=Ve[e],o=Se(t.componentType);p.push({semantic:r,components:je(t.type),type:o,normalize:null!=(f=t.normalized)?f:r===k&&(o===E||o===F)})}if(a.push(new Promise(((n,r)=>{const o=t.extensions.KHR_draco_mesh_compression;ke(s[o.bufferView].slice().buffer,((s,a)=>{if(s)console.log(s),r(s);else{var i;const s={};for(const[e,t]of Object.entries(o.attributes))s[Ve[e]]=a.attributes.indexOf(t);p.sort(((e,t)=>s[e.semantic]-s[t.semantic])),null!=(i=t.attributes)&&i.NORMAL||p.splice(1,0,{semantic:"NORMAL",components:3,type:j});const r=new te(e,p),f=a.vertices.byteLength/r.size,m=f<=65535?u:c,d=a.indices.byteLength/(f<=65535?2:4),y=new ee(e,r,f,{data:a.vertices}),g=new Q(e,m,d,h,a.indices);l.vertexBuffer=y,l.indexBuffer[0]=g,l.primitive[0].type=Ne(t),l.primitive[0].base=0,l.primitive[0].count=g?d:f,l.primitive[0].indexed=!!g,n()}}))}))),null!=t&&null!=(i=t.extensions)&&i.KHR_materials_variants){const e=t.extensions.KHR_materials_variants,n={};e.mappings.forEach((e=>{e.variants.forEach((t=>{n[t]=e.material}))})),r[l.id]=n}return o[l.id]=t.material,l})(e,d,n,s,a,i,f));else{let f=d.hasOwnProperty("indices")?He(n[d.indices],s,!0):null;const y=((e,t,n,s,r,o,a)=>{const i={},l=[];for(const e in t)t.hasOwnProperty(e)&&Ve.hasOwnProperty(e)&&(i[e]=t[e],l.push(`${e}:${t[e]}`));l.sort();const c=l.join();let u=a[c];if(!u){const l={};for(const e in i){const n=s[t[e]],o=He(n,r),a=r[n.bufferView],i=Ve[e],c=je(n.type)*Ie(n.componentType),u=a&&a.hasOwnProperty("byteStride")?a.byteStride:c;l[i]={buffer:o.buffer,size:c,offset:o.byteOffset,stride:u,count:n.count,components:je(n.type),type:Se(n.componentType),normalize:n.normalized}}l.hasOwnProperty(A)||$e(l,n),u=ze(e,l,o),a[c]=u}return u})(e,d.attributes,f,n,s,r,o),g=Ne(d),w=new me(e);if(w.vertexBuffer=y,w.primitive[0].type=g,w.primitive[0].base=0,w.primitive[0].indexed=null!==f,null!==f){let t;t=f instanceof Uint8Array?p:f instanceof Uint16Array?u:c,t!==c||e.extUintElement||(t=u,f=new Uint16Array(f)),t===p&&e.isWebGPU&&(t=u,f=new Uint16Array(f));const n=new Q(e,t,f.length,h,f);w.indexBuffer[0]=n,w.primitive[0].count=f.length}else w.primitive[0].count=y.numVertices;if(d.hasOwnProperty("extensions")&&d.extensions.hasOwnProperty("KHR_materials_variants")){const e=d.extensions.KHR_materials_variants,t={};e.mappings.forEach((e=>{e.variants.forEach((n=>{t[n]=e.material}))})),a[w.id]=t}i[w.id]=d.material;let v=n[d.attributes.POSITION];if(w.aabb=Ke(v),d.hasOwnProperty("targets")){const r=[];d.targets.forEach(((e,o)=>{const a={};e.hasOwnProperty("POSITION")&&(v=n[e.POSITION],a.deltaPositions=Le(v,s),a.deltaPositionsType=j,a.aabb=Ke(v)),e.hasOwnProperty("NORMAL")&&(v=n[e.NORMAL],a.deltaNormals=Le(v,s),a.deltaNormalsType=j),t.hasOwnProperty("extras")&&t.extras.hasOwnProperty("targetNames")?a.name=t.extras.targetNames[o]:a.name=o.toString(10),t.hasOwnProperty("weights")&&(a.defaultWeight=t.weights[o]),a.preserveData=l.morphPreserveData,r.push(new ye(a))})),w.morph=new de(r,e,{preferHighPrecision:l.morphPreferHighPrecision})}m.push(w)}})),m},Xe=(e,t,n)=>{var o;let a;const i=e.texCoord;if(i)for(a=0;a<n.length;++a)t[`${n[a]}MapUv`]=i;const l=[0,0],c=[1,1],u=null==(o=e.extensions)?void 0:o.KHR_texture_transform;if(u){const e=u.offset||l,o=u.scale||c,i=u.rotation?-u.rotation*s.RAD_TO_DEG:0,p=new r(o[0],o[1]),h=new r(e[0],1-o[1]-e[1]);for(a=0;a<n.length;++a)t[`${n[a]}MapTiling`]=p,t[`${n[a]}MapOffset`]=h,t[`${n[a]}MapRotation`]=i}},We=(e,t,n)=>{let s,r;if(e.hasOwnProperty("diffuseFactor")?(s=e.diffuseFactor,t.diffuse.set(Math.pow(s[0],1/2.2),Math.pow(s[1],1/2.2),Math.pow(s[2],1/2.2)),t.opacity=s[3]):(t.diffuse.set(1,1,1),t.opacity=1),e.hasOwnProperty("diffuseTexture")){const s=e.diffuseTexture;r=n[s.index],t.diffuseMap=r,t.diffuseMapChannel="rgb",t.opacityMap=r,t.opacityMapChannel="a",Xe(s,t,["diffuse","opacity"])}if(t.useMetalness=!1,e.hasOwnProperty("specularFactor")?(s=e.specularFactor,t.specular.set(Math.pow(s[0],1/2.2),Math.pow(s[1],1/2.2),Math.pow(s[2],1/2.2))):t.specular.set(1,1,1),e.hasOwnProperty("glossinessFactor")?t.gloss=e.glossinessFactor:t.gloss=1,e.hasOwnProperty("specularGlossinessTexture")){const s=e.specularGlossinessTexture;t.specularEncoding="srgb",t.specularMap=t.glossMap=n[s.index],t.specularMapChannel="rgb",t.glossMapChannel="a",Xe(s,t,["gloss","metalness"])}},Je=(e,t,n)=>{if(e.hasOwnProperty("clearcoatFactor")?t.clearCoat=.25*e.clearcoatFactor:t.clearCoat=0,e.hasOwnProperty("clearcoatTexture")){const s=e.clearcoatTexture;t.clearCoatMap=n[s.index],t.clearCoatMapChannel="r",Xe(s,t,["clearCoat"])}if(e.hasOwnProperty("clearcoatRoughnessFactor")?t.clearCoatGloss=e.clearcoatRoughnessFactor:t.clearCoatGloss=0,e.hasOwnProperty("clearcoatRoughnessTexture")){const s=e.clearcoatRoughnessTexture;t.clearCoatGlossMap=n[s.index],t.clearCoatGlossMapChannel="g",Xe(s,t,["clearCoatGloss"])}if(e.hasOwnProperty("clearcoatNormalTexture")){const s=e.clearcoatNormalTexture;t.clearCoatNormalMap=n[s.index],Xe(s,t,["clearCoatNormal"]),s.hasOwnProperty("scale")&&(t.clearCoatBumpiness=s.scale)}t.clearCoatGlossInvert=!0},Ye=(e,t,n)=>{t.useLighting=!1,t.emissive.copy(t.diffuse),t.emissiveTint=t.diffuseTint,t.emissiveMap=t.diffuseMap,t.emissiveMapUv=t.diffuseMapUv,t.emissiveMapTiling.copy(t.diffuseMapTiling),t.emissiveMapOffset.copy(t.diffuseMapOffset),t.emissiveMapRotation=t.diffuseMapRotation,t.emissiveMapChannel=t.diffuseMapChannel,t.emissiveVertexColor=t.diffuseVertexColor,t.emissiveVertexColorChannel=t.diffuseVertexColorChannel,t.useLighting=!1,t.useSkybox=!1,t.diffuse.set(0,0,0),t.diffuseTint=!1,t.diffuseMap=null,t.diffuseVertexColor=!1},qe=(e,t,n)=>{if(t.useMetalnessSpecularColor=!0,e.hasOwnProperty("specularColorTexture")&&(t.specularEncoding="srgb",t.specularMap=n[e.specularColorTexture.index],t.specularMapChannel="rgb",Xe(e.specularColorTexture,t,["specular"])),e.hasOwnProperty("specularColorFactor")){const n=e.specularColorFactor;t.specular.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2))}else t.specular.set(1,1,1);e.hasOwnProperty("specularFactor")?t.specularityFactor=e.specularFactor:t.specularityFactor=1,e.hasOwnProperty("specularTexture")&&(t.specularityFactorMapChannel="a",t.specularityFactorMap=n[e.specularTexture.index],Xe(e.specularTexture,t,["specularityFactor"]))},Qe=(e,t,n)=>{e.hasOwnProperty("ior")&&(t.refractionIndex=1/e.ior)},Ze=(e,t,n)=>{e.hasOwnProperty("dispersion")&&(t.dispersion=e.dispersion)},et=(e,t,n)=>{t.blendType=oe,t.useDynamicRefraction=!0,e.hasOwnProperty("transmissionFactor")&&(t.refraction=e.transmissionFactor),e.hasOwnProperty("transmissionTexture")&&(t.refractionMapChannel="r",t.refractionMap=n[e.transmissionTexture.index],Xe(e.transmissionTexture,t,["refraction"]))},tt=(e,t,n)=>{if(t.useSheen=!0,e.hasOwnProperty("sheenColorFactor")){const n=e.sheenColorFactor;t.sheen.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2))}else t.sheen.set(1,1,1);e.hasOwnProperty("sheenColorTexture")&&(t.sheenMap=n[e.sheenColorTexture.index],t.sheenEncoding="srgb",Xe(e.sheenColorTexture,t,["sheen"])),e.hasOwnProperty("sheenRoughnessFactor")?t.sheenGloss=e.sheenRoughnessFactor:t.sheenGloss=0,e.hasOwnProperty("sheenRoughnessTexture")&&(t.sheenGlossMap=n[e.sheenRoughnessTexture.index],t.sheenGlossMapChannel="a",Xe(e.sheenRoughnessTexture,t,["sheenGloss"])),t.sheenGlossInvert=!0},nt=(e,t,n)=>{if(t.blendType=oe,t.useDynamicRefraction=!0,e.hasOwnProperty("thicknessFactor")&&(t.thickness=e.thicknessFactor),e.hasOwnProperty("thicknessTexture")&&(t.thicknessMap=n[e.thicknessTexture.index],t.thicknessMapChannel="g",Xe(e.thicknessTexture,t,["thickness"])),e.hasOwnProperty("attenuationDistance")&&(t.attenuationDistance=e.attenuationDistance),e.hasOwnProperty("attenuationColor")){const n=e.attenuationColor;t.attenuation.set(Math.pow(n[0],1/2.2),Math.pow(n[1],1/2.2),Math.pow(n[2],1/2.2))}},st=(e,t,n)=>{e.hasOwnProperty("emissiveStrength")&&(t.emissiveIntensity=e.emissiveStrength)},rt=(e,t,n)=>{t.useIridescence=!0,e.hasOwnProperty("iridescenceFactor")&&(t.iridescence=e.iridescenceFactor),e.hasOwnProperty("iridescenceTexture")&&(t.iridescenceMapChannel="r",t.iridescenceMap=n[e.iridescenceTexture.index],Xe(e.iridescenceTexture,t,["iridescence"])),e.hasOwnProperty("iridescenceIor")&&(t.iridescenceRefractionIndex=e.iridescenceIor),e.hasOwnProperty("iridescenceThicknessMinimum")&&(t.iridescenceThicknessMin=e.iridescenceThicknessMinimum),e.hasOwnProperty("iridescenceThicknessMaximum")&&(t.iridescenceThicknessMax=e.iridescenceThicknessMaximum),e.hasOwnProperty("iridescenceThicknessTexture")&&(t.iridescenceThicknessMapChannel="g",t.iridescenceThicknessMap=n[e.iridescenceThicknessTexture.index],Xe(e.iridescenceThicknessTexture,t,["iridescenceThickness"]))},ot=(e,t,n)=>{const s=new Oe;let r,o;if(s.occludeSpecular=se,s.diffuseTint=!0,s.diffuseVertexColor=!0,s.specularTint=!0,s.specularVertexColor=!0,e.hasOwnProperty("name")&&(s.name=e.name),e.hasOwnProperty("pbrMetallicRoughness")){const n=e.pbrMetallicRoughness;if(n.hasOwnProperty("baseColorFactor")?(r=n.baseColorFactor,s.diffuse.set(Math.pow(r[0],1/2.2),Math.pow(r[1],1/2.2),Math.pow(r[2],1/2.2)),s.opacity=r[3]):(s.diffuse.set(1,1,1),s.opacity=1),n.hasOwnProperty("baseColorTexture")){const e=n.baseColorTexture;o=t[e.index],s.diffuseMap=o,s.diffuseMapChannel="rgb",s.opacityMap=o,s.opacityMapChannel="a",Xe(e,s,["diffuse","opacity"])}if(s.useMetalness=!0,s.specular.set(1,1,1),n.hasOwnProperty("metallicFactor")?s.metalness=n.metallicFactor:s.metalness=1,n.hasOwnProperty("roughnessFactor")?s.gloss=n.roughnessFactor:s.gloss=1,s.glossInvert=!0,n.hasOwnProperty("metallicRoughnessTexture")){const e=n.metallicRoughnessTexture;s.metalnessMap=s.glossMap=t[e.index],s.metalnessMapChannel="b",s.glossMapChannel="g",Xe(e,s,["gloss","metalness"])}}if(e.hasOwnProperty("normalTexture")){const n=e.normalTexture;s.normalMap=t[n.index],Xe(n,s,["normal"]),n.hasOwnProperty("scale")&&(s.bumpiness=n.scale)}if(e.hasOwnProperty("occlusionTexture")){const n=e.occlusionTexture;s.aoMap=t[n.index],s.aoMapChannel="r",Xe(n,s,["ao"])}if(e.hasOwnProperty("emissiveFactor")?(r=e.emissiveFactor,s.emissive.set(Math.pow(r[0],1/2.2),Math.pow(r[1],1/2.2),Math.pow(r[2],1/2.2)),s.emissiveTint=!0):(s.emissive.set(0,0,0),s.emissiveTint=!1),e.hasOwnProperty("emissiveTexture")){const n=e.emissiveTexture;s.emissiveMap=t[n.index],Xe(n,s,["emissive"])}if(e.hasOwnProperty("alphaMode"))switch(e.alphaMode){case"MASK":s.blendType=re,e.hasOwnProperty("alphaCutoff")?s.alphaTest=e.alphaCutoff:s.alphaTest=.5;break;case"BLEND":s.blendType=oe,s.depthWrite=!1;break;default:s.blendType=re}else s.blendType=re;e.hasOwnProperty("doubleSided")?(s.twoSidedLighting=e.doubleSided,s.cull=e.doubleSided?i:l):(s.twoSidedLighting=!1,s.cull=l);const a={KHR_materials_clearcoat:Je,KHR_materials_emissive_strength:st,KHR_materials_ior:Qe,KHR_materials_dispersion:Ze,KHR_materials_iridescence:rt,KHR_materials_pbrSpecularGlossiness:We,KHR_materials_sheen:tt,KHR_materials_specular:qe,KHR_materials_transmission:et,KHR_materials_unlit:Ye,KHR_materials_volume:nt};if(e.hasOwnProperty("extensions"))for(const n in e.extensions){const r=a[n];void 0!==r&&r(e.extensions[n],s,t)}return s.update(),s},at=new n,it=new o,lt=(e,t)=>{const n=new pe;if(e.hasOwnProperty("name")&&e.name.length>0?n.name=e.name:n.name=`node_${t}`,e.hasOwnProperty("matrix")&&(at.data.set(e.matrix),at.getTranslation(it),n.setLocalPosition(it),at.getEulerAngles(it),n.setLocalEulerAngles(it),at.getScale(it),n.setLocalScale(it)),e.hasOwnProperty("rotation")){const t=e.rotation;n.setLocalRotation(t[0],t[1],t[2],t[3])}if(e.hasOwnProperty("translation")){const t=e.translation;n.setLocalPosition(t[0],t[1],t[2])}if(e.hasOwnProperty("scale")){const t=e.scale;n.setLocalScale(t[0],t[1],t[2])}return n},ct=(e,t)=>{const n="orthographic"===e.type?ae:ie,r=n===ae?e.orthographic:e.perspective,o={enabled:!1,projection:n,nearClip:r.znear,aspectRatioMode:le};r.zfar&&(o.farClip=r.zfar),n===ae?(o.orthoHeight=.5*r.ymag,r.ymag&&(o.aspectRatioMode=ue,o.aspectRatio=r.xmag/r.ymag)):(o.fov=r.yfov*s.RAD_TO_DEG,r.aspectRatio&&(o.aspectRatioMode=ue,o.aspectRatio=r.aspectRatio));const a=new xe(e.name);return a.addComponent("camera",o),a},ut=(e,n)=>{const r={enabled:!1,type:"point"===e.type?"omni":e.type,color:e.hasOwnProperty("color")?new t(e.color):t.WHITE,range:e.hasOwnProperty("range")?e.range:9999,falloffMode:ce,intensity:e.hasOwnProperty("intensity")?s.clamp(e.intensity,0,2):1};e.hasOwnProperty("spot")&&(r.innerConeAngle=e.spot.hasOwnProperty("innerConeAngle")?e.spot.innerConeAngle*s.RAD_TO_DEG:0,r.outerConeAngle=e.spot.hasOwnProperty("outerConeAngle")?e.spot.outerConeAngle*s.RAD_TO_DEG:Math.PI/4),e.hasOwnProperty("intensity")&&(r.luminance=e.intensity*he.getLightUnitConversion(fe[r.type],r.outerConeAngle,r.innerConeAngle));const o=new xe(n.name);return o.rotateLocal(90,0,0),o.addComponent("light",r),o},pt=(e,t,s,r)=>{if(!t.hasOwnProperty("skins")||0===t.skins.length)return[];const o=new Map;return t.skins.map((a=>((e,t,s,r,o,a)=>{let i,l,c;const u=t.joints,p=u.length,h=[];if(t.hasOwnProperty("inverseBindMatrices")){const e=t.inverseBindMatrices,o=He(s[e],r,!0),a=[];for(i=0;i<p;i++){for(l=0;l<16;l++)a[l]=o[16*i+l];c=new n,c.set(a),h.push(c)}}else for(i=0;i<p;i++)c=new n,h.push(c);const f=[];for(i=0;i<p;i++)f[i]=o[u[i]].name;const m=f.join("#");let d=a.get(m);return d||(d=new ve(e,h,f),a.set(m,d)),d})(e,a,t.accessors,r,s,o)))},ht=(e,t,n,s)=>{var r,o;if(!e.hasOwnProperty("animations")||0===e.animations.length)return[];const a=null==s||null==(r=s.animation)?void 0:r.preprocess,i=null==s||null==(o=s.animation)?void 0:o.postprocess;return e.animations.map(((s,r)=>{a&&a(s);const o=((e,t,n,s,r,o,a)=>{const i=e=>new Ce(je(e.type),Le(e,s)),l={STEP:Te,LINEAR:Pe,CUBICSPLINE:be},c={},u={},p={};let h,f=1;for(h=0;h<e.samplers.length;++h){const t=e.samplers[h];c.hasOwnProperty(t.input)||(c[t.input]=i(n[t.input])),u.hasOwnProperty(t.output)||(u[t.output]=i(n[t.output]));const s=t.hasOwnProperty("interpolation")&&l.hasOwnProperty(t.interpolation)?l[t.interpolation]:Pe,r={paths:[],input:t.input,output:t.output,interpolation:s};p[h]=r}const m=[],d={translation:"localPosition",rotation:"localRotation",scale:"localScale"},y=e=>{const t=[];for(;e;)t.unshift(e.name),e=e.parent;return t},g=(e,t,n)=>{const s=u[e.output];if(!s)return;let r;if(o&&o[t.mesh]){const e=o[t.mesh];e.hasOwnProperty("extras")&&e.extras.hasOwnProperty("targetNames")&&(r=e.extras.targetNames)}const a=s.data,i=a.length/c[e.input].data.length,l=a.length/i,m=4*l,d=new ArrayBuffer(m*i);for(let t=0;t<i;t++){var y;const s=new Float32Array(d,m*t,l);for(let e=0;e<l;e++)s[e]=a[e*i+t];const o=new Ce(1,s),c=null!=(y=r)&&y[t]?`name.${r[t]}`:t;u[-f]=o;const g={paths:[{entityPath:n,component:"graph",propertyPath:[`weight.${c}`]}],input:e.input,output:-f,interpolation:e.interpolation};f++,p[`morphCurve-${h}-${t}`]=g}};for(h=0;h<e.channels.length;++h){const t=e.channels[h],n=t.target,s=p[t.sampler],o=r[n.node],i=a[n.node],l=y(o);n.path.startsWith("weights")?(g(s,i,l),p[t.sampler].morphCurve=!0):s.paths.push({entityPath:l,component:"graph",propertyPath:[d[n.path]]})}const w=[],v=[],O=[];for(const e in c)w.push(c[e]),c[e]=w.length-1;for(const e in u)v.push(u[e]),u[e]=v.length-1;for(const e in p){const t=p[e];t.morphCurve||(O.push(new Me(t.paths,c[t.input],u[t.output],t.interpolation)),t.paths.length>0&&"localRotation"===t.paths[0].propertyPath[0]&&t.interpolation!==be&&m.push(O[O.length-1].output))}m.sort();let x,P=null;for(h=0;h<m.length;++h){const e=m[h];if(0===h||e!==P){if(x=v[e],4===x.components){const e=x.data,t=e.length-4;for(let n=0;n<t;n+=4)e[n+0]*e[n+4]+e[n+1]*e[n+5]+e[n+2]*e[n+6]+e[n+3]*e[n+7]<0&&(e[n+4]*=-1,e[n+5]*=-1,e[n+6]*=-1,e[n+7]*=-1)}P=e}}let b=0;for(h=0;h<w.length;h++)x=w[h]._data,b=Math.max(b,0===x.length?0:x[x.length-1]);return new _e(e.hasOwnProperty("name")?e.name:`animation_${t}`,b,w,v,O)})(s,r,e.accessors,n,t,e.meshes,e.nodes);return i&&i(s,o),o}))},ft=async(e,t,n,s,r)=>{var o,a;const i=null==r||null==(o=r.global)?void 0:o.preprocess,l=null==r||null==(a=r.global)?void 0:a.postprocess;i&&i(t);const c=t.asset&&"PlayCanvas"===t.asset.generator,u=((e,t)=>{var n,s,r,o;if(!e.hasOwnProperty("nodes")||0===e.nodes.length)return[];const a=null==t||null==(n=t.node)?void 0:n.preprocess,i=null!=(s=null==t||null==(r=t.node)?void 0:r.process)?s:lt,l=null==t||null==(o=t.node)?void 0:o.postprocess,c=e.nodes.map(((e,t)=>{a&&a(e);const n=i(e,t);return l&&l(e,n),n}));for(let t=0;t<e.nodes.length;++t){const n=e.nodes[t];if(n.hasOwnProperty("children")){const e=c[t],s={};for(let t=0;t<n.children.length;++t){const r=c[n.children[t]];r.parent||(s.hasOwnProperty(r.name)?r.name+=s[r.name]++:s[r.name]=1,e.addChild(r))}}}return c})(t,r),p=((e,t)=>{var n;const s=[],r=e.scenes.length;if(1===r&&1===(null==(n=e.scenes[0].nodes)?void 0:n.length)){const n=e.scenes[0].nodes[0];s.push(t[n])}else for(let n=0;n<r;n++){const r=e.scenes[n];if(r.nodes){const e=new pe(r.name);for(let n=0;n<r.nodes.length;n++){const s=t[r.nodes[n]];e.addChild(s)}s.push(e)}}return s})(t,u),h=((e,t,n)=>{let s=null;if(e.hasOwnProperty("nodes")&&e.hasOwnProperty("extensions")&&e.extensions.hasOwnProperty("KHR_lights_punctual")&&e.extensions.KHR_lights_punctual.hasOwnProperty("lights")){const l=e.extensions.KHR_lights_punctual.lights;if(l.length){var r,o,a,i;const c=null==n||null==(r=n.light)?void 0:r.preprocess,u=null!=(o=null==n||null==(a=n.light)?void 0:a.process)?o:ut,p=null==n||null==(i=n.light)?void 0:i.postprocess;e.nodes.forEach(((e,n)=>{if(e.hasOwnProperty("extensions")&&e.extensions.hasOwnProperty("KHR_lights_punctual")&&e.extensions.KHR_lights_punctual.hasOwnProperty("light")){const r=e.extensions.KHR_lights_punctual.light,o=l[r];if(o){c&&c(o);const r=u(o,t[n]);p&&p(o,r),r&&(s||(s=new Map),s.set(e,r))}}}))}}return s})(t,u,r),f=((e,t,n)=>{let s=null;if(e.hasOwnProperty("nodes")&&e.hasOwnProperty("cameras")&&e.cameras.length>0){var r,o,a,i;const l=null==n||null==(r=n.camera)?void 0:r.preprocess,c=null!=(o=null==n||null==(a=n.camera)?void 0:a.process)?o:ct,u=null==n||null==(i=n.camera)?void 0:i.postprocess;e.nodes.forEach(((n,r)=>{if(n.hasOwnProperty("camera")){const o=e.cameras[n.camera];if(o){l&&l(o);const e=c(o,t[r]);u&&u(o,e),e&&(s||(s=new Map),s.set(n,e))}}}))}return s})(t,u,r),m=(e=>{if(!e.hasOwnProperty("extensions")||!e.extensions.hasOwnProperty("KHR_materials_variants"))return null;const t=e.extensions.KHR_materials_variants.variants,n={};for(let e=0;e<t.length;e++)n[t[e].name]=e;return n})(t),d=await Promise.all(n),{meshes:y,meshVariants:g,meshDefaultMaterials:w,promises:v}=((e,t,n,s,r)=>{var o,a,i;const l={},c={},u={},p=[];return{meshes:!r.skipMeshes&&(null==t||null==(o=t.meshes)?void 0:o.length)&&(null==t||null==(a=t.accessors)?void 0:a.length)&&(null==t||null==(i=t.bufferViews)?void 0:i.length)?t.meshes.map((o=>Be(e,o,t.accessors,n,s,l,c,u,r,p))):[],meshVariants:c,meshDefaultMaterials:u,promises:p}})(e,t,d,c,r),O=ht(t,u,d,r),x=await Promise.all(s),P=((e,t,n,s)=>{var r,o,a,i;if(!e.hasOwnProperty("materials")||0===e.materials.length)return[];const l=null==n||null==(r=n.material)?void 0:r.preprocess,c=null!=(o=null==n||null==(a=n.material)?void 0:a.process)?o:ot,u=null==n||null==(i=n.material)?void 0:i.postprocess;return e.materials.map((e=>{l&&l(e);const n=c(e,t,s);return u&&u(e,n),n}))})(t,x.map((e=>e.resource)),r,c),b=pt(e,t,u,d),T=[];for(let e=0;e<y.length;e++)T[e]=new we,T[e].meshes=y[e];((e,t,n)=>{e.nodes.forEach((e=>{e.hasOwnProperty("mesh")&&e.hasOwnProperty("skin")&&t[e.mesh].meshes.forEach((t=>{t.skin=n[e.skin]}))}))})(t,T,b);const M=new Ee;return M.gltf=t,M.nodes=u,M.scenes=p,M.animations=O,M.textures=x,M.materials=P,M.variants=m,M.meshVariants=g,M.meshDefaultMaterials=w,M.renders=T,M.skins=b,M.lights=h,M.cameras=f,l&&l(t,M),await Promise.all(v),M};let mt=0;const dt=(e,t,n)=>{var s,r,o,a,i;if(null==e||null==(s=e.images)||!s.length||null==e||null==(r=e.textures)||!r.length)return[];const l=null==n||null==(o=n.texture)?void 0:o.preprocess,c=null==n||null==(a=n.texture)?void 0:a.processAsync,u=null==n||null==(i=n.texture)?void 0:i.postprocess,p=new Set;return e.textures.map((n=>{let s;return l&&l(n),s=new Promise(c?(t,s)=>{c(n,e.images,((e,n)=>{e?s(e):t(n)}))}:e=>{e(null)}),s=s.then((s=>{var r,o,a,i,l;s=null!=(r=null!=(o=null!=(a=s)?a:null==n||null==(i=n.extensions)||null==(i=i.KHR_texture_basisu)?void 0:i.source)?o:null==n||null==(l=n.extensions)||null==(l=l.EXT_texture_webp)?void 0:l.source)?r:n.source;const c=p.has(s);return p.add(s),t[s].then((t=>{var s;const r=c?Ge(t):t;return((e,t)=>{const n=(e,t)=>{switch(e){case 9728:return w;case 9729:return g;case 9984:return y;case 9985:return d;case 9986:return m;case 9987:return f;default:return t}},s=(e,t)=>{switch(e){case 33071:return x;case 33648:return O;case 10497:return v;default:return t}};var r;e&&(t=null!=(r=t)?r:{},e.minFilter=n(t.minFilter,f),e.magFilter=n(t.magFilter,g),e.addressU=s(t.wrapS,v),e.addressV=s(t.wrapT,v))})(r.resource,(null!=(s=e.samplers)?s:[])[n.sampler]),r}))})),u&&(s=s.then((e=>(u(n,e),e)))),s}))},yt=(e,t,n)=>{e&&e.toLowerCase().endsWith(".glb")||(()=>{const e=new Uint8Array(t);return 103===e[0]&&108===e[1]&&84===e[2]&&70===e[3]})()?((e,t)=>{const n=e instanceof ArrayBuffer?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),s=n.getUint32(0,!0),r=n.getUint32(4,!0),o=n.getUint32(8,!0);if(1179937895!==s)return void t(`Invalid magic number found in glb header. Expected 0x46546C67, found 0x${s.toString(16)}`);if(2!==r)return void t(`Invalid version number found in glb header. Expected 2, found ${r}`);if(o<=0||o>n.byteLength)return void t(`Invalid length found in glb header. Found ${o}`);const a=[];let i=12;for(;i<o;){const e=n.getUint32(i,!0);i+e+8>n.byteLength&&t(`Invalid chunk length found in glb. Found ${e}`);const s=n.getUint32(i+4,!0),r=new Uint8Array(n.buffer,n.byteOffset+i+8,e);a.push({length:e,type:s,data:r}),i+=e+8}1===a.length||2===a.length?1313821514===a[0].type?a.length>1&&5130562!==a[1].type?t(`Invalid chunk type found in glb file. Expected 0x004E4942, found 0x${a[1].type.toString(16)}`):t(null,{gltfChunk:a[0].data,binaryChunk:2===a.length?a[1].data:null}):t(`Invalid chunk type found in glb file. Expected 0x4E4F534A, found 0x${a[0].type.toString(16)}`):t("Invalid number of chunks found in glb file.")})(t,n):n(null,{gltfChunk:t,binaryChunk:null})};class gt{static parse(t,n,s,r,o,a,i){yt(t,s,((t,s)=>{t?i(t):((e,t)=>{const n=JSON.parse((e=>{if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return decodeURIComponent(escape(t))})(e));n.asset&&n.asset.version&&parseFloat(n.asset.version)<2?t(`Invalid gltf version. Expected version 2.0 or above but found version '${n.asset.version}'.`):t(null,n)})(s.gltfChunk,((t,l)=>{if(t)return void i(t);const c=((t,n,s,r)=>{var o,a,i;if(!t.buffers||0===t.buffers.length)return[];const l=null==r||null==(o=r.buffer)?void 0:o.preprocess,c=null==r||null==(a=r.buffer)?void 0:a.processAsync,u=null==r||null==(i=r.buffer)?void 0:i.postprocess;return t.buffers.map(((r,o)=>{let a;return l&&l(r),a=new Promise(c?(e,t)=>{c(r,((n,s)=>{n?t(n):e(s)}))}:e=>{e(null)}),a=a.then((t=>{if(t)return t;if(r.hasOwnProperty("uri")){if(Fe(r.uri)){const e=atob(r.uri.split(",")[1]),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}return new Promise(((t,n)=>{ne.get(Ae.test(r.uri)?r.uri:e.join(s,r.uri),{cache:!0,responseType:"arraybuffer",retry:!1},((e,s)=>{e?n(e):t(new Uint8Array(s))}))}))}return n})),u&&(a=a.then((e=>(u(t.buffers[o],e),e)))),a}))})(l,s.binaryChunk,n,a),u=((e,t,n)=>{var s,r,o,a;const i=[],l=null==n||null==(s=n.bufferView)?void 0:s.preprocess,c=null==n||null==(r=n.bufferView)?void 0:r.processAsync,u=null==n||null==(o=n.bufferView)?void 0:o.postprocess;if(null==(a=e.bufferViews)||!a.length)return i;for(let n=0;n<e.bufferViews.length;++n){const s=e.bufferViews[n];let r;l&&l(s),r=new Promise(c?(e,n)=>{c(s,t,((t,s)=>{t?n(t):e(s)}))}:e=>{e(null)}),r=r.then((e=>e||t[s.buffer].then((e=>new Uint8Array(e.buffer,e.byteOffset+(s.byteOffset||0),s.byteLength))))),s.hasOwnProperty("byteStride")&&(r=r.then((e=>(e.byteStride=s.byteStride,e)))),u&&(r=r.then((e=>(u(s,e),e)))),i.push(r)}return i})(l,c,a),p=((t,n,s,r,o)=>{var a,i,l;if(!t.images||0===t.images.length)return[];const c=null==o||null==(a=o.image)?void 0:a.preprocess,u=null==o||null==(i=o.image)?void 0:i.processAsync,p=null==o||null==(l=o.image)?void 0:l.postprocess,h={"image/png":"png","image/jpeg":"jpg","image/basis":"basis","image/ktx":"ktx","image/ktx2":"ktx2","image/vnd-ms.dds":"dds"},f=(e,t,n,s,o)=>new Promise(((a,i)=>{const l=n=>{const l=`${e.name||"gltf-texture"}-${mt++}`,c={url:t||l};if(n&&(c.contents=n.slice(0).buffer),s){const e=h[s];e&&(c.filename=`${c.url}.${e}`)}const u=new Re(l,"texture",c,null,o);u.on("load",(e=>a(e))),u.on("error",(e=>i(e))),r.add(u),r.load(u)};n?n.then((e=>l(e))):l(null)}));return t.images.map(((t,r)=>{let o;return c&&c(t),o=new Promise(u?(e,n)=>{u(t,((t,s)=>{t?n(t):e(s)}))}:e=>{e(null)}),o=o.then((o=>{return o||(t.hasOwnProperty("uri")?Fe(t.uri)?f(t,t.uri,null,(a=t.uri).substring(a.indexOf(":")+1,a.indexOf(";")),null):f(t,Ae.test(t.uri)?t.uri:e.join(s,t.uri),null,null,{crossOrigin:"anonymous"}):t.hasOwnProperty("bufferView")&&t.hasOwnProperty("mimeType")?f(t,null,n[t.bufferView],t.mimeType,null):Promise.reject(new Error(`Invalid image found in gltf (neither uri or bufferView found). index=${r}`)));var a})),p&&(o=o.then((e=>(p(t,e),e)))),o}))})(l,u,n,o,a),h=dt(l,p,a);ft(r,l,u,h,a).then((e=>i(null,e))).catch((e=>i(e)))}))}))}static createDefaultMaterial(){return ot({name:"defaultGlbMaterial"},[])}}export{gt as GlbParser};