From 6df3adfb4f108e603d2535ab118e5aa7c2799394 Mon Sep 17 00:00:00 2001 From: Takenori Oshima Date: Tue, 18 Jun 2024 15:31:00 +0900 Subject: [PATCH] Updates --- assets/{index-DZCpmCVa.js => index-DEPpnw7N.js} | 4 ++-- index.html | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) rename assets/{index-DZCpmCVa.js => index-DEPpnw7N.js} (99%) diff --git a/assets/index-DZCpmCVa.js b/assets/index-DEPpnw7N.js similarity index 99% rename from assets/index-DZCpmCVa.js rename to assets/index-DEPpnw7N.js index 2f6d25c..dcd34fb 100644 --- a/assets/index-DZCpmCVa.js +++ b/assets/index-DEPpnw7N.js @@ -12879,7 +12879,7 @@ clipPos=viewProjection*worldPos;previousClipPos=previousViewProjection*previousW #define CUSTOM_VERTEX_MAIN_END }`;G.ShadersStore[JV]=e3;class t3 extends ai{constructor(e,t,i,s=512){super("spacewarp rtt",s,i,!1,!0,2,!1,void 0,!1,!1,!0,void 0,!0),this._originalPairing=[],this._previousWorldMatrices=[],this._previousTransforms=[D.Identity(),D.Identity()],this._renderTarget=this.getScene().getEngine().createMultiviewRenderTargetTexture(this.getRenderWidth(),this.getRenderHeight(),e,t),this._renderTarget._disposeOnlyFramebuffers=!0,this._texture=this._renderTarget.texture,this._texture.isMultiview=!0,this._texture.format=5,i&&(this._velocityMaterial=new Dr("velocity shader material",i,{vertex:"velocity",fragment:"velocity"},{uniforms:["world","previousWorld","viewProjection","viewProjectionR","previousViewProjection","previousViewProjectionR"]}),this._velocityMaterial._materialHelperNeedsPreviousMatrices=!0,this._velocityMaterial.onBindObservable.add(r=>{this._previousWorldMatrices[r.uniqueId]=this._previousWorldMatrices[r.uniqueId]||r.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousWorld",this._previousWorldMatrices[r.uniqueId]),this._previousWorldMatrices[r.uniqueId]=r.getWorldMatrix(),this._velocityMaterial.getEffect().setMatrix("previousViewProjection",this._previousTransforms[0]),this._velocityMaterial.getEffect().setMatrix("previousViewProjectionR",this._previousTransforms[1]),this._previousTransforms[0].copyFrom(i.getTransformMatrix()),this._previousTransforms[1].copyFrom(i._transformMatrixR)}),this._velocityMaterial.freeze())}render(e=!1,t=!1){this._originalPairing.length=0;const i=this.getScene();i&&this._velocityMaterial&&i.getActiveMeshes().forEach(s=>{this._originalPairing.push([s,s.material]),s.material=this._velocityMaterial}),super.render(e,t),this._originalPairing.forEach(s=>{s[0].material=s[1]})}_bindFrameBuffer(){this._renderTarget&&this.getScene().getEngine().bindSpaceWarpFramebuffer(this._renderTarget)}getViewCount(){return 2}dispose(){super.dispose(),this._velocityMaterial.dispose(),this._previousTransforms.length=0,this._previousWorldMatrices.length=0,this._originalPairing.length=0}}class i3{constructor(e,t,i){this._scene=e,this._xrSessionManager=t,this._xrWebGLBinding=i,this._lastSubImages=new Map,this._renderTargetTextures=new Map,this._engine=e.getEngine()}_getSubImageForView(e){const t=this._xrSessionManager._getBaseLayerWrapper();if(!t)throw new Error("For Space Warp, the base layer should be a WebXR Projection Layer.");if(t.layerType!=="XRProjectionLayer")throw new Error('For Space Warp, the base layer type should "XRProjectionLayer".');const i=t.layer;return this._xrWebGLBinding.getViewSubImage(i,e)}_setViewportForSubImage(e,t){e.x=0,e.y=0,e.width=t.motionVectorTextureWidth,e.height=t.motionVectorTextureHeight}_createRenderTargetTexture(e,t,i,s,r){if(!this._engine)throw new Error("Engine is disposed");const n={width:e,height:t},o=new t3(s,r,this._scene,n),l=o.renderTarget;return i&&(l._framebuffer=i),l._colorTextureArray=s,l._depthStencilTextureArray=r,o.disableRescaling(),o.renderListPredicate=()=>!0,o}_getRenderTargetForSubImage(e,t){const i=this._lastSubImages.get(t);let s=this._renderTargetTextures.get(t.eye);const r=e.motionVectorTextureWidth,n=e.motionVectorTextureHeight;return(!s||(i==null?void 0:i.textureWidth)!==r||(i==null?void 0:i.textureHeight)!=n)&&(s=this._createRenderTargetTexture(r,n,null,e.motionVectorTexture,e.depthStencilTexture),this._renderTargetTextures.set(t.eye,s),this._framebufferDimensions={framebufferWidth:r,framebufferHeight:n}),this._lastSubImages.set(t,e),s}trySetViewportForView(e,t){const i=this._lastSubImages.get(t)||this._getSubImageForView(t);return i?(this._setViewportForSubImage(e,i),!0):!1}accessMotionVector(e){const t=this._getSubImageForView(e);t&&(t.motionVectorTexture,t.depthStencilTexture)}getRenderTargetTextureForEye(e){return null}getRenderTargetTextureForView(e){const t=this._getSubImageForView(e);return t?this._getRenderTargetForSubImage(t,e):null}dispose(){this._renderTargetTextures.forEach(e=>e.dispose()),this._renderTargetTextures.clear()}}class Cu extends bs{constructor(e){super(e),this._onAfterRenderObserver=null,this.dependsOn=[St.LAYERS],this.xrNativeFeatureName="space-warp",this._xrSessionManager.scene.needsPreviousWorldMatrices=!0}attach(){if(!super.attach())return!1;const e=this._xrSessionManager.scene.getEngine();return this._glContext=e._gl,this._xrWebGLBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),this.spaceWarpRTTProvider=new i3(this._xrSessionManager.scene,this._xrSessionManager,this._xrWebGLBinding),this._onAfterRenderObserver=this._xrSessionManager.scene.onAfterRenderObservable.add(()=>this._onAfterRender()),!0}detach(){return this._xrSessionManager.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver),super.detach()}_onAfterRender(){this.attached&&this._renderTargetTexture&&this._renderTargetTexture.render(!1,!1)}isCompatible(){return this._xrSessionManager.scene.getEngine().getCaps().colorBufferHalfFloat||!1}dispose(){super.dispose()}_onXRFrame(e){const t=e.getViewerPose(this._xrSessionManager.referenceSpace);if(!t)return;const i=t.views[0];this._renderTargetTexture=this._renderTargetTexture||this.spaceWarpRTTProvider.getRenderTargetTextureForView(i),this.spaceWarpRTTProvider.accessMotionVector(i)}}Cu.Name=St.SPACE_WARP;Cu.Version=1;Ti.AddWebXRFeature(Cu.Name,a=>()=>new Cu(a),Cu.Version,!1);class bu extends bs{constructor(e,t={}){super(e),this.options=t,this._cachedInternalTextures=[],this.texturesData=[],this.viewIndex=[],this.cameraIntrinsics=[],this.onTexturesUpdatedObservable=new z,this.xrNativeFeatureName="camera-access"}attach(e){return super.attach(e)?(this._glContext=this._xrSessionManager.scene.getEngine()._gl,this._glBinding=new XRWebGLBinding(this._xrSessionManager.session,this._glContext),!0):!1}detach(){return super.detach()?(this._glBinding=void 0,this.options.doNotDisposeOnDetach||(this._cachedInternalTextures.forEach(e=>e.dispose()),this.texturesData.forEach(e=>e.dispose()),this._cachedInternalTextures.length=0,this.texturesData.length=0,this.cameraIntrinsics.length=0),!0):!1}dispose(){super.dispose(),this.onTexturesUpdatedObservable.clear()}_updateCameraIntrinsics(e,t){const i={width:e.camera.width,height:e.camera.height,x:0,y:0},s=e.projectionMatrix,r=(1-s[8])*i.width/2+i.x,n=(1-s[9])*i.height/2+i.y,o=i.width/2*s[0],l=i.height/2*s[5],h=i.width/2*s[4];this.cameraIntrinsics[t]={u0:r,v0:n,ax:o,ay:l,gamma:h,width:i.width,height:i.height,viewportX:i.x,viewportY:i.y}}_updateInternalTextures(e,t=0){var s,r;if(!e.camera)return!1;this.viewIndex[t]=e.eye;const i=(s=this._glBinding)==null?void 0:s.getCameraImage(e.camera);if(this._cachedInternalTextures[t])(r=this._cachedInternalTextures[t]._hardwareTexture)==null||r.set(i);else{const n=new Rt(this._xrSessionManager.scene.getEngine(),it.Unknown,!0);n.isCube=!0,n.invertY=!1,n.format=5,n.generateMipMaps=!0,n.type=1,n.samplingMode=3,n.width=e.camera.width,n.height=e.camera.height,n._cachedWrapU=1,n._cachedWrapV=1,n._hardwareTexture=new Pc(i,this._glContext),this._cachedInternalTextures[t]=n;const o=new Mt(this._xrSessionManager.scene);o.name=`WebXR Raw Camera Access (${t})`,o._texture=this._cachedInternalTextures[t],this.texturesData[t]=o,this._updateCameraIntrinsics(e,t)}return this._cachedInternalTextures[t].isReady=!0,!0}_onXRFrame(e){const t=this._xrSessionManager.referenceSpace,i=e.getViewerPose(t);if(!i||!i.views)return;let s=!0;i.views.forEach((r,n)=>{s=s&&this._updateInternalTextures(r,n)}),s&&this.onTexturesUpdatedObservable.notifyObservers(this.texturesData)}}bu.Name=St.RAW_CAMERA_ACCESS;bu.Version=1;Ti.AddWebXRFeature(bu.Name,(a,e)=>()=>new bu(a,e),bu.Version,!1);class s3 extends Lc{constructor(e,t,i){super(e,r3[i],t,i,!0),this.profileId="generic-hand-select-grasp"}_getFilenameAndPath(){return{filename:"generic.babylon",path:"https://controllers.babylonjs.com/generic/"}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){}_setRootMesh(e){}_updateModel(){}}Ts.RegisterController("generic-hand-select-grasp",(a,e)=>new s3(e,a.gamepad,a.handedness));const r3={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-right",assetPath:"right.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr-standard-trigger",visualResponses:{}},grasp:{type:"trigger",gamepadIndices:{button:4},rootNodeName:"grasp",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"generic-hand-select-grasp-none",assetPath:"none.glb"}};class mo extends Lc{constructor(e,t,i){super(e,n3["left-right"],t,i),this._mapping={defaultButton:{valueNodeName:"VALUE",unpressedNodeName:"UNPRESSED",pressedNodeName:"PRESSED"},defaultAxis:{valueNodeName:"VALUE",minNodeName:"MIN",maxNodeName:"MAX"},buttons:{"xr-standard-trigger":{rootNodeName:"SELECT",componentProperty:"button",states:["default","touched","pressed"]},"xr-standard-squeeze":{rootNodeName:"GRASP",componentProperty:"state",states:["pressed"]},"xr-standard-touchpad":{rootNodeName:"TOUCHPAD_PRESS",labelAnchorNodeName:"squeeze-label",touchPointNodeName:"TOUCH"},"xr-standard-thumbstick":{rootNodeName:"THUMBSTICK_PRESS",componentProperty:"state",states:["pressed"]}},axes:{"xr-standard-touchpad":{"x-axis":{rootNodeName:"TOUCHPAD_TOUCH_X"},"y-axis":{rootNodeName:"TOUCHPAD_TOUCH_Y"}},"xr-standard-thumbstick":{"x-axis":{rootNodeName:"THUMBSTICK_X"},"y-axis":{rootNodeName:"THUMBSTICK_Y"}}}},this.profileId="microsoft-mixed-reality"}_getFilenameAndPath(){let e="";this.handedness==="left"?e=mo.MODEL_LEFT_FILENAME:e=mo.MODEL_RIGHT_FILENAME;const i=mo.MODEL_BASE_URL+"default"+"/";return{filename:e,path:i}}_getModelLoadingConstraints(){const e=st.IsPluginForExtensionAvailable(".glb");return e||N.Warn("glTF / glb loaded was not registered, using generic controller instead"),e}_processLoadedModel(e){this.rootMesh&&(this.getComponentIds().forEach((t,i)=>{if(!this.disableAnimation&&t&&this.rootMesh){const s=this._mapping.buttons[t],r=s.rootNodeName;if(!r){N.Log("Skipping unknown button at index: "+i+" with mapped name: "+t);return}const n=this._getChildByName(this.rootMesh,r);if(!n){N.Warn("Missing button mesh with name: "+r);return}if(s.valueMesh=this._getImmediateChildByName(n,this._mapping.defaultButton.valueNodeName),s.pressedMesh=this._getImmediateChildByName(n,this._mapping.defaultButton.pressedNodeName),s.unpressedMesh=this._getImmediateChildByName(n,this._mapping.defaultButton.unpressedNodeName),s.valueMesh&&s.pressedMesh&&s.unpressedMesh){const o=this.getComponent(t);o&&o.onButtonStateChangedObservable.add(l=>{this._lerpTransform(s,l.value)},void 0,!0)}else N.Warn("Missing button submesh under mesh with name: "+r)}}),this.getComponentIds().forEach(t=>{const i=this.getComponent(t);i.isAxes()&&["x-axis","y-axis"].forEach(s=>{if(!this.rootMesh)return;const r=this._mapping.axes[t][s],n=this._getChildByName(this.rootMesh,r.rootNodeName);if(!n){N.Warn("Missing axis mesh with name: "+r.rootNodeName);return}r.valueMesh=this._getImmediateChildByName(n,this._mapping.defaultAxis.valueNodeName),r.minMesh=this._getImmediateChildByName(n,this._mapping.defaultAxis.minNodeName),r.maxMesh=this._getImmediateChildByName(n,this._mapping.defaultAxis.maxNodeName),r.valueMesh&&r.minMesh&&r.maxMesh?i&&i.onAxisValueChangedObservable.add(o=>{const l=s==="x-axis"?o.x:o.y;this._lerpTransform(r,l,!0)},void 0,!0):N.Warn("Missing axis submesh under mesh with name: "+r.rootNodeName)})}))}_setRootMesh(e){this.rootMesh=new W(this.profileId+" "+this.handedness,this.scene),this.rootMesh.isPickable=!1;let t;for(let i=0;inew mo(e,a.gamepad,a.handedness));const n3={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{xr_standard_trigger_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_trigger_pressed_value",minNodeName:"xr_standard_trigger_pressed_min",maxNodeName:"xr_standard_trigger_pressed_max"}}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{xr_standard_squeeze_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_squeeze_pressed_value",minNodeName:"xr_standard_squeeze_pressed_min",maxNodeName:"xr_standard_squeeze_pressed_max"}}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{xr_standard_touchpad_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_pressed_value",minNodeName:"xr_standard_touchpad_pressed_min",maxNodeName:"xr_standard_touchpad_pressed_max"},xr_standard_touchpad_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_pressed_value",minNodeName:"xr_standard_touchpad_xaxis_pressed_min",maxNodeName:"xr_standard_touchpad_xaxis_pressed_max"},xr_standard_touchpad_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_pressed_value",minNodeName:"xr_standard_touchpad_yaxis_pressed_min",maxNodeName:"xr_standard_touchpad_yaxis_pressed_max"},xr_standard_touchpad_xaxis_touched:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_xaxis_touched_value",minNodeName:"xr_standard_touchpad_xaxis_touched_min",maxNodeName:"xr_standard_touchpad_xaxis_touched_max"},xr_standard_touchpad_yaxis_touched:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_touchpad_yaxis_touched_value",minNodeName:"xr_standard_touchpad_yaxis_touched_min",maxNodeName:"xr_standard_touchpad_yaxis_touched_max"},xr_standard_touchpad_axes_touched:{componentProperty:"state",states:["touched","pressed"],valueNodeProperty:"visibility",valueNodeName:"xr_standard_touchpad_axes_touched_value"}},touchPointNodeName:"xr_standard_touchpad_axes_touched_value"},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{xr_standard_thumbstick_pressed:{componentProperty:"button",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_pressed_value",minNodeName:"xr_standard_thumbstick_pressed_min",maxNodeName:"xr_standard_thumbstick_pressed_max"},xr_standard_thumbstick_xaxis_pressed:{componentProperty:"xAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_xaxis_pressed_value",minNodeName:"xr_standard_thumbstick_xaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_xaxis_pressed_max"},xr_standard_thumbstick_yaxis_pressed:{componentProperty:"yAxis",states:["default","touched","pressed"],valueNodeProperty:"transform",valueNodeName:"xr_standard_thumbstick_yaxis_pressed_value",minNodeName:"xr_standard_thumbstick_yaxis_pressed_min",maxNodeName:"xr_standard_thumbstick_yaxis_pressed_max"}}}},gamepadMapping:"xr-standard",rootNodeName:"microsoft-mixed-reality-right",assetPath:"right.glb"}};class Wn extends Lc{constructor(e,t,i,s=!1,r=!1){super(e,a3[i],t,i),this._forceLegacyControllers=r,this.profileId="oculus-touch"}_getFilenameAndPath(){let e="";this.handedness==="left"?e=Wn.MODEL_LEFT_FILENAME:e=Wn.MODEL_RIGHT_FILENAME;const t=this._isQuest()?Wn.QUEST_MODEL_BASE_URL:Wn.MODEL_BASE_URL;return{filename:e,path:t}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){const t=this._isQuest(),i=this.handedness==="right"?-1:1;this.getComponentIds().forEach(s=>{const r=s&&this.getComponent(s);r&&r.onButtonStateChangedObservable.add(n=>{if(!(!this.rootMesh||this.disableAnimation))switch(s){case"xr-standard-trigger":t||(this._modelRootNode.getChildren()[3].rotation.x=-n.value*.2,this._modelRootNode.getChildren()[3].position.y=-n.value*.005,this._modelRootNode.getChildren()[3].position.z=-n.value*.005);return;case"xr-standard-squeeze":t||(this._modelRootNode.getChildren()[4].position.x=i*n.value*.0035);return;case"xr-standard-thumbstick":return;case"a-button":case"x-button":t||(n.pressed?this._modelRootNode.getChildren()[1].position.y=-.001:this._modelRootNode.getChildren()[1].position.y=0);return;case"b-button":case"y-button":t||(n.pressed?this._modelRootNode.getChildren()[2].position.y=-.001:this._modelRootNode.getChildren()[2].position.y=0);return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new W(this.profileId+" "+this.handedness,this.scene),this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=Z.FromEulerAngles(0,Math.PI,0)),e.forEach(t=>{t.isPickable=!1}),this._isQuest()?this._modelRootNode=e[0]:(this._modelRootNode=e[1],this.rootMesh.position.y=.034,this.rootMesh.position.z=.052),this._modelRootNode.parent=this.rootMesh}_updateModel(){}_isQuest(){return!!navigator.userAgent.match(/Quest/gi)&&!this._forceLegacyControllers}}Wn.MODEL_BASE_URL="https://controllers.babylonjs.com/oculus/";Wn.MODEL_LEFT_FILENAME="left.babylon";Wn.MODEL_RIGHT_FILENAME="right.babylon";Wn.QUEST_MODEL_BASE_URL="https://controllers.babylonjs.com/oculusQuest/";Ts.RegisterController("oculus-touch",(a,e)=>new Wn(e,a.gamepad,a.handedness));Ts.RegisterController("oculus-touch-legacy",(a,e)=>new Wn(e,a.gamepad,a.handedness,!0));const a3={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"x-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"x_button",visualResponses:{}},"y-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"y_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-left",assetPath:"left.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-thumbstick":{type:"thumbstick",gamepadIndices:{button:3,xAxis:2,yAxis:3},rootNodeName:"xr_standard_thumbstick",visualResponses:{}},"a-button":{type:"button",gamepadIndices:{button:4},rootNodeName:"a_button",visualResponses:{}},"b-button":{type:"button",gamepadIndices:{button:5},rootNodeName:"b_button",visualResponses:{}},thumbrest:{type:"button",gamepadIndices:{button:6},rootNodeName:"thumbrest",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"oculus-touch-v2-right",assetPath:"right.glb"}};class ih extends Lc{constructor(e,t,i){super(e,o3[i],t,i),this.profileId="htc-vive"}_getFilenameAndPath(){const e=ih.MODEL_FILENAME,t=ih.MODEL_BASE_URL;return{filename:e,path:t}}_getModelLoadingConstraints(){return!0}_processLoadedModel(e){this.getComponentIds().forEach(t=>{const i=t&&this.getComponent(t);i&&i.onButtonStateChangedObservable.add(s=>{if(!(!this.rootMesh||this.disableAnimation))switch(t){case"xr-standard-trigger":this._modelRootNode.getChildren()[6].rotation.x=-s.value*.15;return;case"xr-standard-touchpad":return;case"xr-standard-squeeze":return}},void 0,!0)})}_setRootMesh(e){this.rootMesh=new W(this.profileId+" "+this.handedness,this.scene),e.forEach(t=>{t.isPickable=!1}),this._modelRootNode=e[1],this._modelRootNode.parent=this.rootMesh,this.scene.useRightHandedSystem||(this.rootMesh.rotationQuaternion=Z.FromEulerAngles(0,Math.PI,0))}_updateModel(){}}ih.MODEL_BASE_URL="https://controllers.babylonjs.com/vive/";ih.MODEL_FILENAME="wand.babylon";Ts.RegisterController("htc-vive",(a,e)=>new ih(e,a.gamepad,a.handedness));const o3={left:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},right:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc_vive_none",assetPath:"none.glb"},none:{selectComponentId:"xr-standard-trigger",components:{"xr-standard-trigger":{type:"trigger",gamepadIndices:{button:0},rootNodeName:"xr_standard_trigger",visualResponses:{}},"xr-standard-squeeze":{type:"squeeze",gamepadIndices:{button:1},rootNodeName:"xr_standard_squeeze",visualResponses:{}},"xr-standard-touchpad":{type:"touchpad",gamepadIndices:{button:2,xAxis:0,yAxis:1},rootNodeName:"xr_standard_touchpad",visualResponses:{}},menu:{type:"button",gamepadIndices:{button:4},rootNodeName:"menu",visualResponses:{}}},gamepadMapping:"xr-standard",rootNodeName:"htc-vive-none",assetPath:"none.glb"}};class l3{get session(){return this._nativeImpl.session}constructor(e){this._nativeImpl=e,this._xrTransform=new XRRigidTransform,this._xrPose={transform:this._xrTransform,emulatedPosition:!1},this._xrPoseVectorData=new Float32Array(8),this.fillPoses=this._nativeImpl.fillPoses.bind(this._nativeImpl),this.getViewerPose=this._nativeImpl.getViewerPose.bind(this._nativeImpl),this.getHitTestResults=this._nativeImpl.getHitTestResults.bind(this._nativeImpl),this.getHitTestResultsForTransientInput=()=>{throw new Error("XRFrame.getHitTestResultsForTransientInput not supported on native.")},this.createAnchor=this._nativeImpl.createAnchor.bind(this._nativeImpl),this.getJointPose=this._nativeImpl.getJointPose.bind(this._nativeImpl),this.fillJointRadii=this._nativeImpl.fillJointRadii.bind(this._nativeImpl),this.getLightEstimate=()=>{throw new Error("XRFrame.getLightEstimate not supported on native.")},this.getImageTrackingResults=()=>this._nativeImpl._imageTrackingResults??[]}getPose(e,t){if(!this._nativeImpl.getPoseData(e,t,this._xrPoseVectorData.buffer,this._xrTransform.matrix.buffer))return;const i=this._xrTransform.position;i.x=this._xrPoseVectorData[0],i.y=this._xrPoseVectorData[1],i.z=this._xrPoseVectorData[2],i.w=this._xrPoseVectorData[3];const s=this._xrTransform.orientation;return s.x=this._xrPoseVectorData[4],s.y=this._xrPoseVectorData[5],s.z=this._xrPoseVectorData[6],s.w=this._xrPoseVectorData[7],this._xrPose}get trackedAnchors(){return this._nativeImpl.trackedAnchors}get worldInformation(){return this._nativeImpl.worldInformation}get detectedPlanes(){return this._nativeImpl.detectedPlanes}get featurePointCloud(){return this._nativeImpl.featurePointCloud}getDepthInformation(e){throw new Error("This function is not available in Babylon Native")}}JI("NativeXRFrame",l3);var Zr;(function(a){a[a.Input=0]="Input",a[a.Output=1]="Output"})(Zr||(Zr={}));class w_{constructor(e,t,i){this._ownerBlock=i,this._connectedPoint=[],this.uniqueId=yn(),this.connectedPointIds=[],this.name=e,this._connectionType=t}get connectionType(){return this._connectionType}_isSingularConnection(){return!0}isConnected(){return this._connectedPoint.length>0}connectTo(e){if(this._connectionType===e._connectionType)throw new Error(`Cannot connect two points of type ${this.connectionType}`);if(this._isSingularConnection()&&this._connectedPoint.length>0||e._isSingularConnection()&&e._connectedPoint.length>0)throw new Error("Max number of connections for point reached");this._connectedPoint.push(e),e._connectedPoint.push(this)}serialize(e={}){e.uniqueId=this.uniqueId,e.name=this.name,e._connectionType=this._connectionType,e.connectedPointIds=[],e.className=this.getClassName();for(const t of this._connectedPoint)e.connectedPointIds.push(t.uniqueId)}getClassName(){return"FGConnection"}deserialize(e){this.uniqueId=e.uniqueId,this.name=e.name,this._connectionType=e._connectionType,this.connectedPointIds=e.connectedPointIds}static Parse(e={},t){const i=X.Instantiate(e.className),s=new i(e.name,e._connectionType,t);return s.deserialize(e),s}}class Oi{constructor(e){this.value=this._toInt(e)}_toInt(e){return e|0}add(e){return new Oi(this.value+e.value)}subtract(e){return new Oi(this.value-e.value)}multiply(e){return new Oi(Math.imul(this.value,e.value))}divide(e){return new Oi(this.value/e.value)}getClassName(){return Oi.ClassName}equals(e){return this.value===e.value}static Parse(e){return new Oi(e.value)}}Oi.ClassName="FlowGraphInteger";U("FlowGraphInteger",Oi);class Br{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new Br(e.typeName,e.defaultValue)}}const Te=new Br("any",void 0),h3=new Br("string",""),Kt=new Br("number",0),Ps=new Br("boolean",!1),F_=new Br("Vector2",Q.Zero()),Ba=new Br("Vector3",m.Zero()),c3=new Br("Vector4",ve.Zero()),go=new Br("Matrix",D.Identity()),u3=new Br("Color3",K.Black()),d3=new Br("Color4",new ge(0,0,0,0)),f3=new Br("Quaternion",Z.Identity()),Ni=new Br("FlowGraphInteger",new Oi(0));function p3(a){switch(typeof a){case"string":return h3;case"number":return Kt;case"boolean":return Ps;case"object":return a instanceof Q?F_:a instanceof m?Ba:a instanceof ve?c3:a instanceof K?u3:a instanceof ge?d3:a instanceof Z?f3:a instanceof Oi?Ni:Te;default:return Te}}class L_ extends w_{constructor(e,t,i,s){super(e,t,i),this.richType=s}_isSingularConnection(){return this.connectionType===Zr.Input}setValue(e,t){t._setConnectionValue(this,e)}connectTo(e){super.connectTo(e)}_getValueOrDefault(e){return e._hasConnectionValue(this)?e._getConnectionValue(this):this.richType.defaultValue}getValue(e){return this.connectionType===Zr.Output?(e._notifyExecuteNode(this._ownerBlock),this._ownerBlock._updateOutputs(e),this._getValueOrDefault(e)):this.isConnected()?this._connectedPoint[0].getValue(e):this._getValueOrDefault(e)}getClassName(){return"FGDataConnection"}serialize(e={}){super.serialize(e),e.richType={},this.richType.serialize(e.richType)}static Parse(e,t){const i=w_.Parse(e,t);return i.richType=Br.Parse(e.richType),i}}U("FGDataConnection",L_);function EC(a){return a==="Mesh"||a==="AbstractMesh"||a==="GroundMesh"||a==="InstanceMesh"||a==="LinesMesh"||a==="GoldbergMesh"||a==="GreasedLineMesh"||a==="TrailMesh"}function SC(a){return a==="Vector2"||a==="Vector3"||a==="Vector4"||a==="Quaternion"||a==="Color3"||a==="Color4"}function _3(a,e){if(a==="Vector2")return Q.FromArray(e);if(a==="Vector3")return m.FromArray(e);if(a==="Vector4")return ve.FromArray(e);if(a==="Quaternion")return Z.FromArray(e);if(a==="Color3")return new K(e[0],e[1],e[2]);if(a==="Color4")return new ge(e[0],e[1],e[2],e[3]);throw new Error(`Unknown vector class name ${a}`)}function jg(a,e,t){var s;const i=((s=e==null?void 0:e.getClassName)==null?void 0:s.call(e))??"";EC(i)?t[a]={name:e.name,className:i}:SC(i)?t[a]={value:e.asArray(),className:i}:t[a]=e}function Cp(a,e,t){const i=e[a];let s;const r=i==null?void 0:i.className;return EC(r)?s=t.getMeshByName(i.name):SC(r)?s=_3(r,i.value):r==="Matrix"?s=D.FromArray(i.value):r===Oi.ClassName?s=Oi.Parse(i):i&&i.value!==void 0?s=i.value:s=i,s}function m3(a){return a==="FGSetPropertyBlock"||a==="FGGetPropertyBlock"||a==="FGPlayAnimationBlock"||a==="FGMeshPickEventBlock"}class wo{constructor(e){var t;this.config=e,this.uniqueId=yn(),this.name=((t=this.config)==null?void 0:t.name)??this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){const i=new L_(e,Zr.Input,this,t);return this.dataInputs.push(i),i}registerDataOutput(e,t){const i=new L_(e,Zr.Output,this,t);return this.dataOutputs.push(i),i}getDataInput(e){return this.dataInputs.find(t=>t.name===e)}getDataOutput(e){return this.dataOutputs.find(t=>t.name===e)}serialize(e={},t=jg){e.uniqueId=this.uniqueId,e.config={},this.config&&(e.config.name=this.config.name),e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName();for(const i of this.dataInputs){const s={};i.serialize(s),e.dataInputs.push(s)}for(const i of this.dataOutputs){const s={};i.serialize(s),e.dataOutputs.push(s)}}getClassName(){return"FGBlock"}static Parse(e,t){const i=X.Instantiate(e.className),s={},r=t.valueParseFunction??Cp;if(e.config)for(const o in e.config)s[o]=r(o,e.config,t.scene);m3(e.className)&&(s.pathConverter=t.pathConverter);const n=new i(s);n.uniqueId=e.uniqueId;for(let o=0;ot.name===e)}getSignalOutput(e){return this.signalOutputs.find(t=>t.name===e)}serialize(e={}){super.serialize(e),e.signalInputs=[],e.signalOutputs=[];for(const t of this.signalInputs){const i={};t.serialize(i),e.signalInputs.push(i)}for(const t of this.signalOutputs){const i={};t.serialize(i),e.signalOutputs.push(i)}}deserialize(e){for(let t=0;t{var n,o,l;r.type===Pe.POINTERPICK&&((n=r.pickInfo)!=null&&n.pickedMesh)&&(((o=r.pickInfo)==null?void 0:o.pickedMesh)===i||qg((l=r.pickInfo)==null?void 0:l.pickedMesh,i))&&this._execute(e)});const s=i.onDisposeObservable.add(()=>this._onDispose);e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",s)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"mesh"),i=e._getExecutionVariable(this,"meshPickObserver"),s=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(i),t.onDisposeObservable.remove(s),e._deleteExecutionVariable(this,"mesh"),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return sh.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path}}sh.ClassName="FGMeshPickEventBlock";U(sh.ClassName,sh);var Xo;(function(a){a[a.Stopped=0]="Stopped",a[a.Started=1]="Started"})(Xo||(Xo={}));class rh{constructor(e){this._eventBlocks=[],this._executionContexts=[],this.state=Xo.Stopped,this._scene=e.scene,this._coordinator=e.coordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add(()=>this.dispose())}createContext(){const e=new U_({scene:this._scene,coordinator:this._coordinator});return this._executionContexts.push(e),e}getContext(e){return this._executionContexts[e]}addEventBlock(e){this._eventBlocks.push(e)}start(){if(this.state!==Xo.Started){this.state=Xo.Started,this._executionContexts.length===0&&this.createContext();for(const e of this._executionContexts){const t=this._getContextualOrder();for(const i of t)i._startPendingTasks(e)}}}_getContextualOrder(){const e=[];for(const t of this._eventBlocks)if(t.getClassName()===sh.ClassName){const i=t._getReferencedMesh();let s=0;for(;s0;){const s=t.pop();e(s);for(const r of s.dataInputs)for(const n of r._connectedPoint)i.has(n._ownerBlock.uniqueId)||(t.push(n._ownerBlock),i.add(n._ownerBlock.uniqueId));if(s instanceof pa)for(const r of s.signalOutputs)for(const n of r._connectedPoint)i.has(n._ownerBlock.uniqueId)||(t.push(n._ownerBlock),i.add(n._ownerBlock.uniqueId))}}serialize(e={},t){e.allBlocks=[],this.visitAllBlocks(i=>{const s={};i.serialize(s),e.allBlocks.push(s)}),e.executionContexts=[];for(const i of this._executionContexts){const s={};i.serialize(s,t),e.executionContexts.push(s)}}static GetDataOutConnectionByUniqueId(e,t){for(const i of e)for(const s of i.dataOutputs)if(s.uniqueId===t)return s;throw new Error("Could not find data out connection with unique id "+t)}static GetSignalInConnectionByUniqueId(e,t){for(const i of e)if(i instanceof pa){for(const s of i.signalInputs)if(s.uniqueId===t)return s}throw new Error("Could not find signal in connection with unique id "+t)}static Parse(e,t){const i=t.coordinator.createGraph(),s=[],r=t.valueParseFunction??Cp;for(const n of e.allBlocks){const o=wo.Parse(n,{scene:t.coordinator.config.scene,pathConverter:t.pathConverter,valueParseFunction:r});s.push(o),o instanceof gd&&i.addEventBlock(o)}for(const n of s){for(const o of n.dataInputs)for(const l of o.connectedPointIds){const h=rh.GetDataOutConnectionByUniqueId(s,l);o.connectTo(h)}if(n instanceof pa)for(const o of n.signalOutputs)for(const l of o.connectedPointIds){const h=rh.GetSignalInConnectionByUniqueId(s,l);o.connectTo(h)}}for(const n of e.executionContexts)U_.Parse(n,{graph:i,valueParseFunction:r});return i}}class Vl{constructor(e){this.config=e,this._flowGraphs=[],this._customEventsMap=new Map,this.config.scene.onDisposeObservable.add(()=>{this.dispose()}),(Vl.SceneCoordinators.get(this.config.scene)??[]).push(this)}createGraph(){const e=new rh({scene:this.config.scene,coordinator:this});return this._flowGraphs.push(e),e}removeGraph(e){const t=this._flowGraphs.indexOf(e);t!==-1&&(e.dispose(),this._flowGraphs.splice(t,1))}start(){this._flowGraphs.forEach(e=>e.start())}dispose(){this._flowGraphs.forEach(i=>i.dispose()),this._flowGraphs.length=0;const e=Vl.SceneCoordinators.get(this.config.scene)??[],t=e.indexOf(this);t!==-1&&e.splice(t,1)}serialize(e,t){e._flowGraphs=[],this._flowGraphs.forEach(i=>{const s={};i.serialize(s,t),e._flowGraphs.push(s)})}static Parse(e,t){var r;const i=t.valueParseFunction??Cp,s=new Vl({scene:t.scene});return(r=e._flowGraphs)==null||r.forEach(n=>{rh.Parse(n,{coordinator:s,valueParseFunction:i,pathConverter:t.pathConverter})}),s}get flowGraphs(){return this._flowGraphs}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new z,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){const i=this._customEventsMap.get(e);i&&i.notifyObservers(t)}}Vl.SceneCoordinators=new Map;class xn extends pa{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class nh extends xn{constructor(e){super(e),this.message=this.registerDataInput("message",Te)}_execute(e){const t=this.message.getValue(e);N.Log(t),this.out._activateSignal(e)}getClassName(){return nh.ClassName}}nh.ClassName="FGConsoleLogBlock";U(nh.ClassName,nh);class ah extends xn{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,Te)}_execute(e){const t=this.config.variableName,i=this.input.getValue(e);e.setVariable(t,i),this.out._activateSignal(e)}getClassName(){return ah.ClassName}}ah.ClassName="FGSetVariableBlock";U(ah.ClassName,ah);const nE=new RegExp(/\{(\w+)\}/g);class Rf{constructor(e,t){this.path=e,this.ownerBlock=t,this.templatedInputs=[];let i=nE.exec(e);for(;i;){const[,s]=i;this.templatedInputs.push(t.registerDataInput(s,Ni)),i=nE.exec(e)}}getAccessor(e,t){let i=this.path;for(const s of this.templatedInputs){const r=s.getValue(t).value;i=i.replace(`{${s.name}}`,r.toString())}return e.convert(i)}}class xd extends xn{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",Te),this.templateComponent=new Rf(e.path,this)}_execute(e){const t=this.a.getValue(e),i=this.templateComponent.getAccessor(this.config.pathConverter,e);i.info.set(t,i.object),this.out._activateSignal(e)}serialize(e={}){super.serialize(e),e.config.path=this.config.path}getClassName(){return xd.ClassName}}xd.ClassName="FGSetPropertyBlock";U("FGSetPropertyBlock",xd);class Td extends xn{constructor(e){super(e),this.config=e;for(let t=0;ts.getValue(e));e.configuration.coordinator.notifyCustomEvent(t,i),this.out._activateSignal(e)}getClassName(){return Td.ClassName}}Td.ClassName="FGSendCustomEventBlock";U("FGSendCustomEventBlock",Td);class g3 extends pa{constructor(e){super(e),this.condition=this.registerDataInput("condition",Ps),this.onTrue=this._registerSignalOutput("onTrue"),this.onFalse=this._registerSignalOutput("onFalse")}_execute(e){this.condition.getValue(e)?this.onTrue._activateSignal(e):this.onFalse._activateSignal(e)}getClassName(){return"FGBranchBlock"}}U("FGBranchBlock",g3);class oh extends xn{constructor(e={startIndex:new Oi(0)}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",Ni),this.value=this.registerDataOutput("value",Ni)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{const i=this.value.getValue(e);i.values)this.timeRemaining.setValue(0,e),this.out._activateSignal(e),e._setExecutionVariable(this,"lastExecutedTime",r);else{const n=s-(r-i);this.timeRemaining.setValue(n,e)}}getClassName(){return"FGThrottleBlock"}}U("FGThrottleBlock",T3);class Ed extends Kg{constructor(e){super(e),this.timeout=this.registerDataInput("timeout",Kt)}_preparePendingTasks(e){const t=this.timeout.getValue(e);if(t!==void 0&&t>=0){const i=e._getExecutionVariable(this,"runningTimers")||[],s=e.configuration.scene,r=new xN({timeout:t,contextObservable:s.onBeforeRenderObservable,onEnded:()=>this._onEnded(r,e)});r.start(),i.push(r),e._setExecutionVariable(this,"runningTimers",i)}}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onEnded(e,t){const i=t._getExecutionVariable(this,"runningTimers")||[],s=i.indexOf(e);s!==-1?i.splice(s,1):X.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningTimers")||[];for(const i of t)i.dispose();e._deleteExecutionVariable(this,"runningTimers")}getClassName(){return Ed.ClassName}}Ed.ClassName="FGTimerBlock";U("FGTimerBlock",Ed);class E3 extends pa{constructor(e){super(e),this.config=e,this._cachedUnusedIndexes=[],this.reset=this._registerSignalInput("reset"),this.currentIndex=this.registerDataOutput("currentIndex",Kt),this.config.startIndex=this.config.startIndex!==void 0?this.config.startIndex:0,this.config.startIndex=Math.max(0,Math.min(this.config.startIndex,this.config.numberOutputFlows-1)),this.outFlows=[];for(let t=0;t=this.config.numberOutputFlows&&this.config.loop)r=0;else if(r>=this.config.numberOutputFlows&&!this.config.loop)return;if(s=s.filter(n=>n!==r),s.length===0)for(let n=0;n=0&&(i[s+1]=!0)}if(e._setExecutionVariable(this,"activationState",i.slice()),i.every(s=>s)){this.out._activateSignal(e);for(let s=0;s=i&&(this.out._activateSignal(e),e._setExecutionVariable(this,"debounceCount",0))}getClassName(){return"FGDebounceBlock"}}U("FGDebounceBlock",b3);class y3 extends pa{constructor(e){super(e),this.onOn=this._registerSignalOutput("onOn"),this.onOff=this._registerSignalOutput("onOff"),this.isOn=this.registerDataOutput("isOn",Ps)}_execute(e,t){let i=e._getExecutionVariable(this,"value",!1);i=!i,e._setExecutionVariable(this,"value",i),this.isOn.setValue(i,e),i?this.onOn._activateSignal(e):this.onOff._activateSignal(e)}getClassName(){return"FGFlipFlopBlock"}}U("FGFlipFlopBlock",y3);class hh extends pa{constructor(e){super(e),this.config=e,this.outFlows=[];for(let t=0;tthis._onAnimationEnd(h,e));this.runningAnimatable.setValue(h,e),n.push(h)}e._setExecutionVariable(this,"runningAnimatables",n)}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onAnimationEnd(e,t){const i=t._getExecutionVariable(this,"runningAnimatables")??[],s=i.indexOf(e);s!==-1&&i.splice(s,1),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningAnimatables")??[];for(const i of t)i.stop();e._deleteExecutionVariable(this,"runningAnimatables")}getClassName(){return Yu.ClassName}serialize(e={}){super.serialize(e),e.config.targetPath=this.config.targetPath,e.config.animationPath=this.config.animationPath}}Yu.ClassName="FGPlayAnimationBlock";U(Yu.ClassName,Yu);class A3 extends xn{constructor(e){super(e),this.animationToStop=this.registerDataInput("animationToStop",Te)}_execute(e){this.animationToStop.getValue(e).stop(),this.out._activateSignal(e)}getClassName(){return"FGStopAnimationBlock"}}U("FGStopAnimationBlock",A3);class R3 extends xn{constructor(e){super(e),this.animationToPause=this.registerDataInput("animationToPause",Te)}_execute(e){this.animationToPause.getValue(e).pause(),this.out._activateSignal(e)}getClassName(){return"FGPauseAnimationBlock"}}U("FGPauseAnimationBlock",R3);class I3 extends wo{constructor(e){super(e),this.condition=this.registerDataInput("condition",Ps),this.trueValue=this.registerDataInput("trueValue",Te),this.falseValue=this.registerDataInput("falseValue",Te),this.output=this.registerDataOutput("output",Te)}_updateOutputs(e){this.output.setValue(this.condition.getValue(e)?this.trueValue.getValue(e):this.falseValue.getValue(e),e)}getClassName(){return"FGConditionalDataBlock"}}U("FGConditionalDataBlock",I3);class ch extends wo{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,Te)}_updateOutputs(e){const t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return ch.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}ch.ClassName="FGGetVariableBlock";U(ch.ClassName,ch);class P3 extends wo{constructor(e){super(e),this.sourceSystem=this.registerDataInput("sourceSystem",Te),this.destinationSystem=this.registerDataInput("destinationSystem",Te),this.inputCoordinates=this.registerDataInput("inputCoordinates",Ba),this.outputCoordinates=this.registerDataOutput("outputCoordinates",Ba)}_updateOutputs(e){const t=this.sourceSystem.getValue(e),i=this.destinationSystem.getValue(e),s=this.inputCoordinates.getValue(e),r=t.getWorldMatrix(),n=i.getWorldMatrix(),o=V.Matrix[0].copyFrom(n);o.invert();const l=V.Matrix[1];o.multiplyToRef(r,l);const h=this.outputCoordinates.getValue(e);m.TransformCoordinatesToRef(s,l,h)}getClassName(){return"FGCoordinateTransformBlock"}}U("FGCoordinateTransformBlock",P3);class M3 extends wo{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput("output",p3(e.value))}_updateOutputs(e){this.output.setValue(this.config.value,e)}getClassName(){return"FGConstantBlock"}serialize(e={},t=jg){super.serialize(e),t("value",this.config.value,e.config)}}U("FGConstantBlock",M3);class uh extends wo{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",Te),this.templateComponent=new Rf(e.path,this)}_updateOutputs(e){const t=this.templateComponent.getAccessor(this.config.pathConverter,e),i=t.info.get(t.object);this.value.setValue(i,e)}getClassName(){return uh.ClassName}serialize(e={}){super.serialize(e),e.config.path=this.config.path}}uh.ClassName="FGGetPropertyBlock";U(uh.ClassName,uh);const aE="cachedOperationValue",oE="cachedExecutionId";class bp extends wo{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){const t=e._getExecutionVariable(this,oE),i=e._getExecutionVariable(this,aE);if(i!==void 0&&t===e.executionId)this.value.setValue(i,e);else{const s=this._doOperation(e);e._setExecutionVariable(this,aE,s),e._setExecutionVariable(this,oE,e.executionId),this.value.setValue(s,e)}}}class Zi extends bp{constructor(e,t,i,s,r,n){super(i,n),this._operation=s,this._className=r,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e))}getClassName(){return this._className}}class Bt extends bp{constructor(e,t,i,s,r){super(t,r),this._operation=i,this._className=s,this.a=this.registerDataInput("a",e)}_doOperation(e){return this._operation(this.a.getValue(e))}getClassName(){return this._className}}const Xc="FGLogic",vC="AndBlock",CC="OrBlock",bC="NotBlock";class D3 extends Zi{constructor(e){super(Ps,Ps,Ps,(t,i)=>t&&i,`${Xc}${vC}`,e)}}U(`${Xc}${vC}`,D3);class O3 extends Zi{constructor(e){super(Ps,Ps,Ps,(t,i)=>t||i,`${Xc}${CC}`,e)}}U(`${Xc}${CC}`,O3);class N3 extends Bt{constructor(e){super(Ps,Ps,t=>!t,`${Xc}${bC}`,e)}}U(`${Xc}${bC}`,N3);class Sd extends bp{constructor(e,t,i,s){super(e,s),this._operation=t,this._className=i}_doOperation(e){return this._operation()}getClassName(){return this._className}}class Zg extends bp{constructor(e,t,i,s,r,n,o){super(s,o),this._operation=r,this._className=n,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t),this.c=this.registerDataInput("c",i)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e),this.c.getValue(e))}getClassName(){return this._className}}function Ls(a){return a.getClassName?a.getClassName():""}function vd(a,e){return a==="Vector2"&&e==="Vector2"||a==="Vector3"&&e==="Vector3"||a==="Vector4"&&e==="Vector4"}function Cd(a,e){return a==="Matrix"&&e==="Matrix"}function bd(a,e){return a==="FlowGraphInteger"&&e==="FlowGraphInteger"}class dh extends Zi{constructor(e){super(Te,Te,Te,(t,i)=>this._polymorphicAdd(t,i),dh.ClassName,e)}_polymorphicAdd(e,t){const i=Ls(e),s=Ls(t);return vd(i,s)||Cd(i,s)||bd(i,s)?e.add(t):e+t}}dh.ClassName="FGAddBlock";U(dh.ClassName,dh);class fh extends Zi{constructor(e){super(Te,Te,Te,(t,i)=>this._polymorphicAdd(t,i),fh.ClassName,e)}_polymorphicAdd(e,t){const i=Ls(e),s=Ls(t);return vd(i,s)||bd(i,s)?e.subtract(t):Cd(i,s)?e.add(t.scale(-1)):e-t}}fh.ClassName="FGSubBlock";U(fh.ClassName,fh);class ph extends Zi{constructor(e){super(Te,Te,Te,(t,i)=>this._polymorphicMultiply(t,i),ph.ClassName,e)}_polymorphicMultiply(e,t){const i=Ls(e),s=Ls(t);return vd(i,s)||bd(i,s)?e.multiply(t):Cd(i,s)?D.FromValues(e.m[0]*t.m[0],e.m[4]*t.m[4],e.m[8]*t.m[8],e.m[12]*t.m[12],e.m[1]*t.m[1],e.m[5]*t.m[5],e.m[9]*t.m[9],e.m[13]*t.m[13],e.m[2]*t.m[2],e.m[6]*t.m[6],e.m[10]*t.m[10],e.m[14]*t.m[14],e.m[3]*t.m[3],e.m[7]*t.m[7],e.m[11]*t.m[11],e.m[15]*t.m[15]):e*t}}ph.ClassName="FGMultiplyBlock";U(ph.ClassName,ph);class _h extends Zi{constructor(e){super(Te,Te,Te,(t,i)=>this._polymorphicDivide(t,i),_h.ClassName,e)}_polymorphicDivide(e,t){const i=Ls(e),s=Ls(t);return vd(i,s)||bd(i,s)?e.divide(t):Cd(i,s)?D.FromValues(e.m[0]/t.m[0],e.m[4]/t.m[4],e.m[8]/t.m[8],e.m[12]/t.m[12],e.m[1]/t.m[1],e.m[5]/t.m[5],e.m[9]/t.m[9],e.m[13]/t.m[13],e.m[2]/t.m[2],e.m[6]/t.m[6],e.m[10]/t.m[10],e.m[14]/t.m[14],e.m[3]/t.m[3],e.m[7]/t.m[7],e.m[11]/t.m[11],e.m[15]/t.m[15]):e/t}}_h.ClassName="FGDivideBlock";U(_h.ClassName,_h);class mh extends Sd{constructor(e){super(Kt,()=>Math.random(),mh.ClassName,e)}}mh.ClassName="FGRandomBlock";U(mh.ClassName,mh);class gh extends Zi{constructor(e){super(Te,Te,Kt,(t,i)=>this._polymorphicDot(t,i),gh.ClassName,e)}_polymorphicDot(e,t){switch(Ls(e)){case"Vector2":return Q.Dot(e,t);case"Vector3":return m.Dot(e,t);case"Vector4":return ve.Dot(e,t);default:throw new Error(`Cannot get dot product of ${e} and ${t}`)}}}gh.ClassName="FGDotBlock";U(gh.ClassName,gh);class xh extends Sd{constructor(e){super(Kt,()=>Math.E,xh.ClassName,e)}}xh.ClassName="FGEBlock";U(xh.ClassName,xh);class Th extends Sd{constructor(e){super(Kt,()=>Math.PI,Th.ClassName,e)}}Th.ClassName="FGPIBlock";U(Th.ClassName,Th);class Eh extends Sd{constructor(e){super(Kt,()=>Number.POSITIVE_INFINITY,Eh.ClassName,e)}}Eh.ClassName="FGInfBlock";U(Eh.ClassName,Eh);class Sh extends Sd{constructor(e){super(Kt,()=>Number.NaN,Sh.ClassName,e)}}Sh.ClassName="FGNaNBlock";U(Sh.ClassName,Sh);function Ri(a,e){switch(Ls(a)){case"FlowGraphInteger":return new Oi(e(a.value));case"Vector2":return new Q(e(a.x),e(a.y));case"Vector3":return new m(e(a.x),e(a.y),e(a.z));case"Vector4":return new ve(e(a.x),e(a.y),e(a.z),e(a.w));case"Matrix":return D.FromValues(e(a.m[0]),e(a.m[4]),e(a.m[8]),e(a.m[12]),e(a.m[1]),e(a.m[5]),e(a.m[9]),e(a.m[13]),e(a.m[2]),e(a.m[6]),e(a.m[10]),e(a.m[14]),e(a.m[3]),e(a.m[7]),e(a.m[11]),e(a.m[15]));default:return e(a)}}class vh extends Bt{constructor(e){super(Te,Te,t=>this._polymorphicAbs(t),vh.ClassName,e)}_polymorphicAbs(e){return Ri(e,Math.abs)}}vh.ClassName="FGAbsBlock";U(vh.ClassName,vh);class Ch extends Bt{constructor(e){super(Te,Te,t=>this._polymorphicSign(t),Ch.ClassName,e)}_polymorphicSign(e){return Ri(e,Math.sign)}}Ch.ClassName="FGSignBlock";U(Ch.ClassName,Ch);class bh extends Bt{constructor(e){super(Te,Te,t=>this._polymorphicTrunc(t),bh.ClassName,e)}_polymorphicTrunc(e){return Ri(e,Math.trunc)}}bh.ClassName="FGTruncBlock";U(bh.ClassName,bh);class yh extends Bt{constructor(e){super(Te,Te,t=>this._polymorphicFloor(t),yh.ClassName,e)}_polymorphicFloor(e){return Ri(e,Math.floor)}}yh.ClassName="FGFloorBlock";U(yh.ClassName,yh);class Ah extends Bt{constructor(e){super(Te,Te,t=>this._polymorphicCeiling(t),Ah.ClassName,e)}_polymorphicCeiling(e){return Ri(e,Math.ceil)}}Ah.ClassName="FGCeilBlock";U(Ah.ClassName,Ah);class Rh extends Bt{constructor(e){super(Te,Te,t=>this._polymorphicFract(t),Rh.ClassName,e)}_polymorphicFract(e){return Ri(e,t=>t-Math.floor(t))}}Rh.ClassName="FGFractBlock";U(Rh.ClassName,Rh);class Ih extends Bt{constructor(e){super(Te,Te,t=>this._polymorphicNeg(t),Ih.ClassName,e)}_polymorphicNeg(e){return Ri(e,t=>-t)}}Ih.ClassName="FGNegBlock";U(Ih.ClassName,Ih);function yd(a,e,t){switch(Ls(a)){case"FlowGraphInteger":return new Oi(t(a.value,e.value));case"Vector2":return new Q(t(a.x,e.x),t(a.y,e.y));case"Vector3":return new m(t(a.x,e.x),t(a.y,e.y),t(a.z,e.z));case"Vector4":return new ve(t(a.x,e.x),t(a.y,e.y),t(a.z,e.z),t(a.w,e.w));case"Matrix":return D.FromValues(t(a.m[0],e.m[0]),t(a.m[4],e.m[4]),t(a.m[8],e.m[8]),t(a.m[12],e.m[12]),t(a.m[1],e.m[1]),t(a.m[5],e.m[5]),t(a.m[9],e.m[9]),t(a.m[13],e.m[13]),t(a.m[2],e.m[2]),t(a.m[6],e.m[6]),t(a.m[10],e.m[10]),t(a.m[14],e.m[14]),t(a.m[3],e.m[3]),t(a.m[7],e.m[7]),t(a.m[11],e.m[11]),t(a.m[15],e.m[15]));default:return t(a,e)}}class Ph extends Zi{constructor(e){super(Te,Te,Te,(t,i)=>this._polymorphicRemainder(t,i),Ph.ClassName,e)}_polymorphicRemainder(e,t){return yd(e,t,(i,s)=>i%s)}}Ph.ClassName="FGRemainderBlock";U(Ph.ClassName,Ph);class Mh extends Zi{constructor(e){super(Te,Te,Te,(t,i)=>this._polymorphicMin(t,i),Mh.ClassName,e)}_polymorphicMin(e,t){return yd(e,t,Math.min)}}Mh.ClassName="FGMinBlock";U(Mh.ClassName,Mh);class Dh extends Zi{constructor(e){super(Te,Te,Te,(t,i)=>this._polymorphicMax(t,i),Dh.ClassName,e)}_polymorphicMax(e,t){return yd(e,t,Math.max)}}Dh.ClassName="FGMaxBlock";U(Dh.ClassName,Dh);function w3(a,e,t){return Math.min(Math.max(a,Math.min(e,t)),Math.max(e,t))}function yC(a,e,t,i){switch(Ls(a)){case"FlowGraphInteger":return new Oi(i(a.value,e.value,t.value));case"Vector2":return new Q(i(a.x,e.x,t.x),i(a.y,e.y,t.y));case"Vector3":return new m(i(a.x,e.x,t.x),i(a.y,e.y,t.y),i(a.z,e.z,t.z));case"Vector4":return new ve(i(a.x,e.x,t.x),i(a.y,e.y,t.y),i(a.z,e.z,t.z),i(a.w,e.w,t.w));case"Matrix":return D.FromValues(i(a.m[0],e.m[0],t.m[0]),i(a.m[4],e.m[4],t.m[4]),i(a.m[8],e.m[8],t.m[8]),i(a.m[12],e.m[12],t.m[12]),i(a.m[1],e.m[1],t.m[1]),i(a.m[5],e.m[5],t.m[5]),i(a.m[9],e.m[9],t.m[9]),i(a.m[13],e.m[13],t.m[13]),i(a.m[2],e.m[2],t.m[2]),i(a.m[6],e.m[6],t.m[6]),i(a.m[10],e.m[10],t.m[10]),i(a.m[14],e.m[14],t.m[14]),i(a.m[3],e.m[3],t.m[3]),i(a.m[7],e.m[7],t.m[7]),i(a.m[11],e.m[11],t.m[11]),i(a.m[15],e.m[15],t.m[15]));default:return i(a,e,t)}}class Oh extends Zg{constructor(e){super(Te,Te,Te,Te,(t,i,s)=>this._polymorphicClamp(t,i,s),Oh.ClassName,e)}_polymorphicClamp(e,t,i){return yC(e,t,i,w3)}}Oh.ClassName="FGClampBlock";U(Oh.ClassName,Oh);function F3(a){return Math.min(Math.max(a,0),1)}class Nh extends Bt{constructor(e){super(Te,Te,t=>this._polymorphicSaturate(t),Nh.ClassName,e)}_polymorphicSaturate(e){return Ri(e,F3)}}Nh.ClassName="FGSaturateBlock";U(Nh.ClassName,Nh);class wh extends Zg{constructor(e){super(Te,Te,Te,Te,(t,i,s)=>this._polymorphicInterpolate(t,i,s),wh.ClassName,e)}_interpolate(e,t,i){return(1-i)*e+i*t}_polymorphicInterpolate(e,t,i){return yC(e,t,i,this._interpolate)}}wh.ClassName="FGInterpolateBlock";U(wh.ClassName,wh);class Fh extends Zi{constructor(e){super(Te,Te,Ps,(t,i)=>this._polymorphicEq(t,i),Fh.ClassName,e)}_polymorphicEq(e,t){const i=Ls(e),s=Ls(t);return vd(i,s)||Cd(i,s)||bd(i,s)?e.equals(t):e===t}}Fh.ClassName="FGEqBlock";U(Fh.ClassName,Fh);function yp(a,e,t){const i=Ls(a),s=Ls(e);if(i===s){if(i==="")return t(a,e);if(i==="FlowGraphInteger")return t(a.value,e.value);throw new Error(`Cannot compare ${a} and ${e}`)}throw new Error(`${a} and ${e} are of different types.`)}class Lh extends Zi{constructor(e){super(Te,Te,Ps,(t,i)=>this._polymorphicLessThan(t,i),Lh.ClassName,e)}_polymorphicLessThan(e,t){return yp(e,t,(i,s)=>ithis._polymorphicLessThanOrEqual(t,i),Ap.ClassName,e)}_polymorphicLessThanOrEqual(e,t){return yp(e,t,(i,s)=>i<=s)}}Ap.ClassName="FGLessThanOrEqualBlock";class Bh extends Zi{constructor(e){super(Te,Te,Ps,(t,i)=>this._polymorphicGreaterThan(t,i),Bh.ClassName,e)}_polymorphicGreaterThan(e,t){return yp(e,t,(i,s)=>i>s)}}Bh.ClassName="FGGreaterThanBlock";U(Bh.ClassName,Bh);class Uh extends Zi{constructor(e){super(Te,Te,Ps,(t,i)=>this._polymorphicGreaterThanOrEqual(t,i),Uh.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){return yp(e,t,(i,s)=>i>=s)}}Uh.ClassName="FGGreaterThanOrEqualBlock";U(Uh.ClassName,Uh);class Vh extends Bt{constructor(e){super(Te,Ps,t=>this._polymorphicIsNan(t),Vh.ClassName,e)}_polymorphicIsNan(e){const t=Ls(e);if(t==="")return isNaN(e);if(t==="FlowGraphInteger")return isNaN(e.value);throw new Error(`Cannot get NaN of ${e}`)}}Vh.ClassName="FGIsNanBlock";U(Vh.ClassName,Vh);class Rp extends Bt{constructor(e){super(Te,Ps,t=>this._polymorphicIsInf(t),Rp.ClassName,e)}_polymorphicIsInf(e){const t=Ls(e);if(t==="")return!isFinite(e);if(t==="FlowGraphInteger")return!isFinite(e.value);throw new Error(`Cannot get isInf of ${e}`)}}Rp.ClassName="FGIsInfBlock";class kh extends Bt{constructor(e){super(Te,Te,t=>this._polymorphicDegToRad(t),kh.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return Ri(e,this._degToRad)}}kh.ClassName="FGDegToRadBlock";U(kh.ClassName,kh);class Gh extends Bt{constructor(e){super(Te,Te,t=>this._polymorphicRadToDeg(t),Gh.ClassName,e)}_radToDeg(e){return e*180/Math.PI}_polymorphicRadToDeg(e){return Ri(e,this._radToDeg)}}Gh.ClassName="FGRadToDegBlock";U(Gh.ClassName,Gh);class zh extends Bt{constructor(e){super(Te,Te,t=>this._polymorphicSin(t),zh.ClassName,e)}_polymorphicSin(e){return Ri(e,Math.sin)}}zh.ClassName="FGSinBlock";U(zh.ClassName,zh);class Wh extends Bt{constructor(e){super(Te,Te,t=>this._polymorphicCos(t),Wh.ClassName,e)}_polymorphicCos(e){return Ri(e,Math.cos)}}Wh.ClassName="FGCosBlock";U(Wh.ClassName,Wh);class Hh extends Bt{constructor(e){super(Te,Te,t=>this._polymorphicTan(t),Hh.ClassName,e)}_polymorphicTan(e){return Ri(e,Math.tan)}}Hh.ClassName="FGTanBlock";U(Hh.ClassName,Hh);class Xh extends Bt{constructor(e){super(Te,Te,t=>this._polymorphicAsin(t),Xh.ClassName,e)}_polymorphicAsin(e){return Ri(e,Math.asin)}}Xh.ClassName="FGAsinBlock";U(Xh.ClassName,Xh);class Yh extends Bt{constructor(e){super(Te,Te,t=>this._polymorphicAcos(t),Yh.ClassName,e)}_polymorphicAcos(e){return Ri(e,Math.acos)}}Yh.ClassName="FGAcosBlock";U(Yh.ClassName,Yh);class $h extends Bt{constructor(e){super(Te,Te,t=>this._polymorphicAtan(t),$h.ClassName,e)}_polymorphicAtan(e){return Ri(e,Math.atan)}}$h.ClassName="FGAtanBlock";U($h.ClassName,$h);class jh extends Zi{constructor(e){super(Te,Te,Te,(t,i)=>this._polymorphicAtan2(t,i),jh.ClassName,e)}_polymorphicAtan2(e,t){return yd(e,t,Math.atan2)}}jh.ClassName="FGAtan2Block";U(jh.ClassName,jh);class Kh extends Bt{constructor(e){super(Te,Te,t=>this._polymorphicSinh(t),Kh.ClassName,e)}_polymorphicSinh(e){return Ri(e,Math.sinh)}}Kh.ClassName="FGSinhBlock";U(Kh.ClassName,Kh);class qh extends Bt{constructor(e){super(Te,Te,t=>this._polymorphicCosh(t),qh.ClassName,e)}_polymorphicCosh(e){return Ri(e,Math.cosh)}}qh.ClassName="FGCoshBlock";U(qh.ClassName,qh);class Zh extends Bt{constructor(e){super(Te,Te,t=>this._polymorphicTanh(t),Zh.ClassName,e)}_polymorphicTanh(e){return Ri(e,Math.tanh)}}Zh.ClassName="FGTanhBlock";U(Zh.ClassName,Zh);class Qh extends Bt{constructor(e){super(Te,Kt,t=>this._polymorphicAsinh(t),Qh.ClassName,e)}_polymorphicAsinh(e){return Ri(e,Math.asinh)}}Qh.ClassName="FGAsinhBlock";U(Qh.ClassName,Qh);class Jh extends Bt{constructor(e){super(Te,Kt,t=>this._polymorphicAcosh(t),Jh.ClassName,e)}_polymorphicAcosh(e){return Ri(e,Math.acosh)}}Jh.ClassName="FGAcoshBlock";U(Jh.ClassName,Jh);class ec extends Bt{constructor(e){super(Te,Kt,t=>this._polymorphicAtanh(t),ec.ClassName,e)}_polymorphicAtanh(e){return Ri(e,Math.atanh)}}ec.ClassName="FGAtanhBlock";U(ec.ClassName,ec);class tc extends Bt{constructor(e){super(Te,Kt,t=>this._polymorphicExp(t),tc.ClassName,e)}_polymorphicExp(e){return Ri(e,Math.exp)}}tc.ClassName="FGExpBlock";U(tc.ClassName,tc);class ic extends Bt{constructor(e){super(Te,Kt,t=>this._polymorphicLog(t),ic.ClassName,e)}_polymorphicLog(e){return Ri(e,Math.log)}}ic.ClassName="FGLogBlock";U(ic.ClassName,ic);class sc extends Bt{constructor(e){super(Te,Kt,t=>this._polymorphicLog2(t),sc.ClassName,e)}_polymorphicLog2(e){return Ri(e,Math.log2)}}sc.ClassName="FGLog2Block";U(sc.ClassName,sc);class rc extends Bt{constructor(e){super(Te,Kt,t=>this._polymorphicLog10(t),rc.ClassName,e)}_polymorphicLog10(e){return Ri(e,Math.log10)}}rc.ClassName="FGLog10Block";U(rc.ClassName,rc);class nc extends Bt{constructor(e){super(Te,Kt,t=>this._polymorphicSqrt(t),nc.ClassName,e)}_polymorphicSqrt(e){return Ri(e,Math.sqrt)}}nc.ClassName="FGSqrtBlock";U(nc.ClassName,nc);class ac extends Bt{constructor(e){super(Te,Kt,t=>this._polymorphicCubeRoot(t),ac.ClassName,e)}_polymorphicCubeRoot(e){return Ri(e,Math.cbrt)}}ac.ClassName="FGCubeRootBlock";U(ac.ClassName,ac);class oc extends Zi{constructor(e){super(Te,Kt,Kt,(t,i)=>this._polymorphicPow(t,i),oc.ClassName,e)}_polymorphicPow(e,t){return yd(e,t,Math.pow)}}oc.ClassName="FGPowBlock";U(oc.ClassName,oc);class lc extends Bt{constructor(e){super(Te,Kt,t=>this._polymorphicLength(t),lc.ClassName,e)}_polymorphicLength(e){switch(Ls(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw new Error(`Cannot compute length of value ${e}`)}}}lc.ClassName="FGLengthBlock";U(lc.ClassName,lc);class hc extends Bt{constructor(e){super(Te,Te,t=>this._polymorphicNormalize(t),hc.ClassName,e)}_polymorphicNormalize(e){switch(Ls(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw new Error(`Cannot normalize value ${e}`)}}}hc.ClassName="FGNormalizeBlock";U(hc.ClassName,hc);class cc extends Zi{constructor(e){super(Ba,Ba,Ba,(t,i)=>m.Cross(t,i),cc.ClassName,e)}}cc.ClassName="FGCrossBlock";U(cc.ClassName,cc);class uc extends Zi{constructor(e){super(F_,Kt,F_,(t,i)=>Q.Transform(t,D.RotationZ(i)),uc.ClassName,e)}}uc.ClassName="FGRotate2DBlock";U(uc.ClassName,uc);class dc extends Zg{constructor(e){super(Ba,Ba,Kt,Ba,(t,i,s)=>m.TransformCoordinates(t,D.RotationAxis(i,s)),dc.ClassName,e)}}dc.ClassName="FGRotate3DBlock";U(dc.ClassName,dc);class fc extends Bt{constructor(e){super(go,go,t=>D.Transpose(t),fc.ClassName,e)}}fc.ClassName="FGTransposeBlock";U(fc.ClassName,fc);class pc extends Bt{constructor(e){super(go,Kt,t=>t.determinant(),pc.ClassName,e)}}pc.ClassName="FGDeterminantBlock";U(pc.ClassName,pc);class _c extends Bt{constructor(e){super(go,go,t=>D.Invert(t),_c.ClassName,e)}}_c.ClassName="FGInvertMatrixBlock";U(_c.ClassName,_c);class mc extends Zi{constructor(e){super(go,go,go,(t,i)=>i.multiply(t),mc.ClassName,e)}}mc.ClassName="FGMatMulBlock";U(mc.ClassName,mc);class gc extends Bt{constructor(e){super(Ni,Ni,t=>new Oi(~t.value),gc.ClassName,e)}}gc.ClassName="FGBitwiseNotBlock";U(gc.ClassName,gc);class xc extends Zi{constructor(e){super(Ni,Ni,Ni,(t,i)=>new Oi(t.value&i.value),xc.ClassName,e)}}xc.ClassName="FGBitwiseAndBlock";U(xc.ClassName,xc);class Tc extends Zi{constructor(e){super(Ni,Ni,Ni,(t,i)=>new Oi(t.value|i.value),Tc.ClassName,e)}}Tc.ClassName="FGBitwiseOrBlock";U(Tc.ClassName,Tc);class Ec extends Zi{constructor(e){super(Ni,Ni,Ni,(t,i)=>new Oi(t.value^i.value),Ec.ClassName,e)}}Ec.ClassName="FGBitwiseXorBlock";U(Ec.ClassName,Ec);class Sc extends Zi{constructor(e){super(Ni,Ni,Ni,(t,i)=>new Oi(t.value<new Oi(t.value>>i.value),vc.ClassName,e)}}vc.ClassName="FGBitwiseRightShiftBlock";U(vc.ClassName,vc);class Cc extends Bt{constructor(e){super(Ni,Ni,t=>new Oi(Math.clz32(t.value)),Cc.ClassName,e)}}Cc.ClassName="FGCountLeadingZerosBlock";U(Cc.ClassName,Cc);class bc extends Bt{constructor(e){super(Ni,Ni,t=>new Oi(t.value?31-Math.clz32(t.value&-t.value):32),bc.ClassName,e)}}bc.ClassName="FGCountTrailingZerosBlock";U(bc.ClassName,bc);function L3(a){let e=0;for(;a;)e+=a&1,a>>=1;return e}class yc extends Bt{constructor(e){super(Ni,Ni,t=>new Oi(L3(t.value)),yc.ClassName,e)}}yc.ClassName="FGCountOneBitsBlock";U(yc.ClassName,yc);class Ad extends gd{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){const i=e.configuration.scene.onReadyObservable.add(()=>{this._execute(e)});e._setExecutionVariable(this,"sceneReadyObserver",i)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneReadyObserver");e.configuration.scene.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return Ad.ClassName}}Ad.ClassName="FGSceneReadyEventBlock";U("FGSceneReadyEventBlock",Ad);class Ac extends gd{constructor(e){super(e),this.config=e;for(let t=0;t{for(let s=0;s{this._execute(e)});e._setExecutionVariable(this,"sceneBeforeRender",i)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneBeforeRender");e.configuration.scene.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}getClassName(){return Rc.ClassName}}Rc.ClassName="FGSceneTickEventBlock";U(Rc.ClassName,Rc);function V_(a,e,t,i){const s={externalResourceFunction:i};return t&&(s.uri=e==="file:"?t:e+t),ArrayBuffer.isView(a)?GLTFValidator.validateBytes(a,s):GLTFValidator.validateString(a,s)}function B3(){const a=[];onmessage=e=>{const t=e.data;switch(t.id){case"init":{importScripts(t.url);break}case"validate":{V_(t.data,t.rootUrl,t.fileName,i=>new Promise((s,r)=>{const n=a.length;a.push({resolve:s,reject:r}),postMessage({id:"getExternalResource",index:n,uri:i})})).then(i=>{postMessage({id:"validate.resolve",value:i})},i=>{postMessage({id:"validate.reject",reason:i})});break}case"getExternalResource.resolve":{a[t.index].resolve(t.value);break}case"getExternalResource.reject":{a[t.index].reject(t.reason);break}}}}class AC{static ValidateAsync(e,t,i,s){return typeof Worker=="function"?new Promise((r,n)=>{const o=`${V_}(${B3})()`,l=URL.createObjectURL(new Blob([o],{type:"application/javascript"})),h=new Worker(l),c=d=>{h.removeEventListener("error",c),h.removeEventListener("message",u),n(d)},u=d=>{const f=d.data;switch(f.id){case"getExternalResource":{s(f.uri).then(p=>{h.postMessage({id:"getExternalResource.resolve",index:f.index,value:p},[p.buffer])},p=>{h.postMessage({id:"getExternalResource.reject",index:f.index,reason:p})});break}case"validate.resolve":{h.removeEventListener("error",c),h.removeEventListener("message",u),r(f.value),h.terminate();break}case"validate.reject":h.removeEventListener("error",c),h.removeEventListener("message",u),n(f.reason),h.terminate()}};if(h.addEventListener("error",c),h.addEventListener("message",u),h.postMessage({id:"init",url:X.GetBabylonScriptURL(this.Configuration.url)}),ArrayBuffer.isView(e)){const d=e.slice();h.postMessage({id:"validate",data:d,rootUrl:t,fileName:i},[d.buffer])}else h.postMessage({id:"validate",data:e,rootUrl:t,fileName:i})}):(this._LoadScriptPromise||(this._LoadScriptPromise=X.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then(()=>V_(e,t,i,s)))}}AC.Configuration={url:`${X._DefaultCdnUrl}/gltf_validator.js`};function lE(a,e,t){try{return Promise.resolve(new Uint8Array(a,e,t))}catch(i){return Promise.reject(i)}}function U3(a,e,t){try{if(e<0||e>=a.byteLength)throw new RangeError("Offset is out of range.");if(e+t>a.byteLength)throw new RangeError("Length is out of range.");return Promise.resolve(new Uint8Array(a.buffer,a.byteOffset+e,t))}catch(i){return Promise.reject(i)}}var $u;(function(a){a[a.AUTO=0]="AUTO",a[a.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"})($u||($u={}));var kl;(function(a){a[a.NONE=0]="NONE",a[a.FIRST=1]="FIRST",a[a.ALL=2]="ALL"})(kl||(kl={}));var Gr;(function(a){a[a.LOADING=0]="LOADING",a[a.READY=1]="READY",a[a.COMPLETE=2]="COMPLETE"})(Gr||(Gr={}));class bi{constructor(){this.onParsedObservable=new z,this.coordinateSystemMode=$u.AUTO,this.animationStartMode=kl.FIRST,this.compileMaterials=!1,this.useClipPlane=!1,this.compileShadowGenerators=!1,this.transparencyAsCoverage=!1,this.useRangeRequests=!1,this.createInstances=!0,this.alwaysComputeBoundingBox=!1,this.loadAllMaterials=!1,this.loadOnlyMaterials=!1,this.skipMaterials=!1,this.useSRGBBuffers=!0,this.targetFps=60,this.alwaysComputeSkeletonRootNode=!1,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable=new z,this.onSkinLoadedObservable=new z,this.onTextureLoadedObservable=new z,this.onMaterialLoadedObservable=new z,this.onCameraLoadedObservable=new z,this.onCompleteObservable=new z,this.onErrorObservable=new z,this.onDisposeObservable=new z,this.onExtensionLoadedObservable=new z,this.validate=!1,this.onValidatedObservable=new z,this._loader=null,this._state=null,this._requests=new Array,this.name="gltf",this.extensions={".gltf":{isBinary:!1},".glb":{isBinary:!0}},this.onLoaderStateChangedObservable=new z,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),this._onParsedObserver=this.onParsedObservable.add(e)}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e)}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e)}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e)}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e)}set onComplete(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)}set onError(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onExtensionLoaded(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)}get loggingEnabled(){return this._loggingEnabled}set loggingEnabled(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)}get capturePerformanceCounters(){return this._capturePerformanceCounters}set capturePerformanceCounters(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))}set onValidated(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)}dispose(){this._loader&&(this._loader.dispose(),this._loader=null);for(const e of this._requests)e.abort();this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable.clear(),this.onSkinLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()}loadFile(e,t,i,s,r,n,o,l){if(ArrayBuffer.isView(t))return this._loadBinary(e,t,i,s,o,l),null;this._progressCallback=r;const h=t.name||X.GetFilename(t);if(n){if(this.useRangeRequests){this.validate&&N.Warn("glTF validation is not supported when range requests are enabled");const c={abort:()=>{},onCompleteObservable:new z},u={readAsync:(d,f)=>new Promise((p,_)=>{this._loadFile(e,t,g=>{p(new Uint8Array(g))},!0,g=>{_(g)},g=>{g.setRequestHeader("Range",`bytes=${d}-${d+f-1}`)})}),byteLength:0};return this._unpackBinaryAsync(new zd(u)).then(d=>{c.onCompleteObservable.notifyObservers(c),s(d)},o?d=>o(void 0,d):void 0),c}return this._loadFile(e,t,c=>{this._validate(e,new Uint8Array(c,0,c.byteLength),i,h),this._unpackBinaryAsync(new zd({readAsync:(u,d)=>lE(c,u,d),byteLength:c.byteLength})).then(u=>{s(u)},o?u=>o(void 0,u):void 0)},!0,o)}else return this._loadFile(e,t,c=>{this._validate(e,c,i,h),s({json:this._parseJson(c)})},!1,o)}_loadBinary(e,t,i,s,r,n){this._validate(e,new Uint8Array(t.buffer,t.byteOffset,t.byteLength),i,n),this._unpackBinaryAsync(new zd({readAsync:(o,l)=>U3(t,o,l),byteLength:t.byteLength})).then(o=>{s(o)},r?o=>r(void 0,o):void 0)}importMeshAsync(e,t,i,s,r,n){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(i),this.onParsedObservable.clear(),this._log(`Loading ${n||""}`),this._loader=this._getLoader(i),this._loader.importMeshAsync(e,t,null,i,s,r,n)))}loadAsync(e,t,i,s,r){return Promise.resolve().then(()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,i,s,r)))}loadAssetContainerAsync(e,t,i,s,r){return Promise.resolve().then(()=>{this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(t);const n=new yS(e),o=[];this.onMaterialLoadedObservable.add(u=>{o.push(u)});const l=[];this.onTextureLoadedObservable.add(u=>{l.push(u)});const h=[];this.onCameraLoadedObservable.add(u=>{h.push(u)});const c=[];return this.onMeshLoadedObservable.add(u=>{u.morphTargetManager&&c.push(u.morphTargetManager)}),this._loader.importMeshAsync(null,e,n,t,i,s,r).then(u=>(Array.prototype.push.apply(n.geometries,u.geometries),Array.prototype.push.apply(n.meshes,u.meshes),Array.prototype.push.apply(n.particleSystems,u.particleSystems),Array.prototype.push.apply(n.skeletons,u.skeletons),Array.prototype.push.apply(n.animationGroups,u.animationGroups),Array.prototype.push.apply(n.materials,o),Array.prototype.push.apply(n.textures,l),Array.prototype.push.apply(n.lights,u.lights),Array.prototype.push.apply(n.transformNodes,u.transformNodes),Array.prototype.push.apply(n.cameras,h),Array.prototype.push.apply(n.morphTargetManagers,c),n))})}canDirectLoad(e){return e.indexOf("asset")!==-1&&e.indexOf("version")!==-1||e.startsWith("data:base64,"+bi._MagicBase64Encoded)||e.startsWith("data:;base64,"+bi._MagicBase64Encoded)||e.startsWith("data:application/octet-stream;base64,"+bi._MagicBase64Encoded)||e.startsWith("data:model/gltf-binary;base64,"+bi._MagicBase64Encoded)}directLoad(e,t){if(t.startsWith("base64,"+bi._MagicBase64Encoded)||t.startsWith(";base64,"+bi._MagicBase64Encoded)||t.startsWith("application/octet-stream;base64,"+bi._MagicBase64Encoded)||t.startsWith("model/gltf-binary;base64,"+bi._MagicBase64Encoded)){const i=td(t);return this._validate(e,new Uint8Array(i,0,i.byteLength)),this._unpackBinaryAsync(new zd({readAsync:(s,r)=>lE(i,s,r),byteLength:i.byteLength}))}return this._validate(e,t),Promise.resolve({json:this._parseJson(t)})}createPlugin(){return new bi}get loaderState(){return this._state}whenCompleteAsync(){return new Promise((e,t)=>{this.onCompleteObservable.addOnce(()=>{e()}),this.onErrorObservable.addOnce(i=>{t(i)})})}_setState(e){this._state!==e&&(this._state=e,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(Gr[this._state]))}_loadFile(e,t,i,s,r,n){const o=e._loadFile(t,i,l=>{this._onProgress(l,o)},!0,s,r,n);return o.onCompleteObservable.add(l=>{this._requests.splice(this._requests.indexOf(l),1)}),this._requests.push(o),o}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let i=!0,s=0,r=0;for(const n of this._requests){if(n._lengthComputable===void 0||n._loaded===void 0||n._total===void 0)return;i=i&&n._lengthComputable,s+=n._loaded,r+=n._total}this._progressCallback({lengthComputable:i,loaded:s,total:i?r:0})}_validate(e,t,i="",s=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),AC.ValidateAsync(t,i,s,r=>this.preprocessUrlAsync(i+r).then(n=>e._loadFileAsync(n,void 0,!0,!0).then(o=>new Uint8Array(o,0,o.byteLength)))).then(r=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(r),this.onValidatedObservable.clear()},r=>{this._endPerformanceCounter("Validate JSON"),X.Warn(`Failed to validate: ${r.message}`),this.onValidatedObservable.clear()}))}_getLoader(e){const t=e.json.asset||{};this._log(`Asset version: ${t.version}`),t.minVersion&&this._log(`Asset minimum version: ${t.minVersion}`),t.generator&&this._log(`Asset generator: ${t.generator}`);const i=bi._parseVersion(t.version);if(!i)throw new Error("Invalid version: "+t.version);if(t.minVersion!==void 0){const n=bi._parseVersion(t.minVersion);if(!n)throw new Error("Invalid minimum version: "+t.minVersion);if(bi._compareVersion(n,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const r={1:bi._CreateGLTF1Loader,2:bi._CreateGLTF2Loader}[i.major];if(!r)throw new Error("Unsupported version: "+t.version);return r(this)}_parseJson(e){this._startPerformanceCounter("Parse JSON"),this._log(`JSON length: ${e.length}`);const t=JSON.parse(e);return this._endPerformanceCounter("Parse JSON"),t}_unpackBinaryAsync(e){return this._startPerformanceCounter("Unpack Binary"),e.loadAsync(20).then(()=>{const t={Magic:1179937895},i=e.readUint32();if(i!==t.Magic)throw new Xn("Unexpected magic: "+i,wa.GLTFLoaderUnexpectedMagicError);const s=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${s}`);const r=e.readUint32();!this.useRangeRequests&&r!==e.buffer.byteLength&&N.Warn(`Length in header does not match actual data length: ${r} != ${e.buffer.byteLength}`);let n;switch(s){case 1:{n=this._unpackBinaryV1Async(e,r);break}case 2:{n=this._unpackBinaryV2Async(e,r);break}default:throw new Error("Unsupported version: "+s)}return this._endPerformanceCounter("Unpack Binary"),n})}_unpackBinaryV1Async(e,t){const i={JSON:0},s=e.readUint32(),r=e.readUint32();if(r!==i.JSON)throw new Error(`Unexpected content format: ${r}`);const n=t-e.byteOffset,o={json:this._parseJson(e.readString(s)),bin:null};if(n!==0){const l=e.byteOffset;o.bin={readAsync:(h,c)=>e.buffer.readAsync(l+h,c),byteLength:n}}return Promise.resolve(o)}_unpackBinaryV2Async(e,t){const i={JSON:1313821514,BIN:5130562},s=e.readUint32();if(e.readUint32()!==i.JSON)throw new Error("First chunk format is not JSON");return e.byteOffset+s===t?e.loadAsync(s).then(()=>({json:this._parseJson(e.readString(s)),bin:null})):e.loadAsync(s+8).then(()=>{const n={json:this._parseJson(e.readString(s)),bin:null},o=()=>{const l=e.readUint32();switch(e.readUint32()){case i.JSON:throw new Error("Unexpected JSON chunk");case i.BIN:{const c=e.byteOffset;n.bin={readAsync:(u,d)=>e.buffer.readAsync(c+u,d),byteLength:l},e.skipBytes(l);break}default:{e.skipBytes(l);break}}return e.byteOffset!==t?e.loadAsync(8).then(o):Promise.resolve(n)};return o()})}static _parseVersion(e){if(e==="1.0"||e==="1.0.1")return{major:1,minor:0};const t=(e+"").match(/^(\d+)\.(\d+)/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null}static _compareVersion(e,t){return e.major>t.major?1:e.majort.minor?1:e.minorn.byteLength)throw new Error("Buffer access is out of range");const o=n.buffer;switch(i+=n.byteOffset,r){case ao.BYTE:return new Int8Array(o,i,s);case ao.UNSIGNED_BYTE:return new Uint8Array(o,i,s);case ao.SHORT:return new Int16Array(o,i,s);case ao.UNSIGNED_SHORT:return new Uint16Array(o,i,s);default:return new Float32Array(o,i,s)}}static GetBufferFromAccessor(e,t){const i=e.bufferViews[t.bufferView],s=t.count*Es.GetByteStrideFromType(t);return Es.GetBufferFromBufferView(e,i,t.byteOffset,s,t.componentType)}static DecodeBufferToText(e){let t="";const i=e.byteLength;for(let s=0;s=this._maxPos}}const RC=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],IC=["world","view","projection","worldView","worldViewProjection","mBones"],V3=["translation","rotation","scale"],k3=["position","rotationQuaternion","scaling"],G3=(a,e)=>{for(const t in a){const i=a[t];e.buffers[t]=i,e.buffersCount++}},z3=(a,e)=>{for(const t in a){const i=a[t];e.shaders[t]=i,e.shaderscount++}},fr=(a,e,t)=>{for(const i in a){const s=a[i];t[e][i]=s}},W3=a=>{if(a)for(let e=0;e{if(a.semantic==="NORMAL")return"normal";if(a.semantic==="POSITION")return"position";if(a.semantic==="JOINT")return"matricesIndices";if(a.semantic==="WEIGHT")return"matricesWeights";if(a.semantic==="COLOR")return"color";if(a.semantic&&a.semantic.indexOf("TEXCOORD_")!==-1){const e=Number(a.semantic.split("_")[1]);return"uv"+(e===0?"":e+1)}return null},H3=a=>{for(const e in a.animations){const t=a.animations[e];if(!t.channels||!t.samplers)continue;let i=null;for(let s=0;s{let e=null;if(a.translation||a.rotation||a.scale){const t=m.FromArray(a.scale||[1,1,1]),i=Z.FromArray(a.rotation||[0,0,0,1]),s=m.FromArray(a.translation||[0,0,0]);e=D.Compose(t,i,s)}else e=D.FromArray(a.matrix);return e},PC=(a,e,t,i)=>{for(let r=0;r{for(let t=0;t{const t=a.nodes;let i=t[e];if(i)return{node:i,id:e};for(const s in t)if(i=t[s],i.jointName===e)return{node:i,id:s};return null},Y3=(a,e)=>{for(let t=0;t{for(const s in a.nodes){const r=a.nodes[s],n=s;if(!r.jointName||Y3(t,r.jointName))continue;const o=Qg(r),l=new Xt(r.name||"",e,null,o);l.id=n,i.push({bone:l,node:r,id:n})}for(let s=0;s{if(i||(i=new So(e.name||"","",a.scene)),!e.babylonSkeleton)return i;const s=[],r=[];$3(a,i,e,s),i.bones=[];for(let o=0;o0&&(f=X3(s,c),f&&r.indexOf(f)===-1&&r.push(f));const _=new Xt(h.jointName||"",i,f,p);_.id=c}const n=i.bones;i.bones=[];for(let o=0;o{if(s||(a.scene._blockEntityCollection=!!a.assetContainer,s=new W(e.name||"",a.scene),s._parentContainer=a.assetContainer,a.scene._blockEntityCollection=!1,s.id=i),!e.babylonNode)return s;const r=[];let n=null;const o=[],l=[],h=[],c=[];for(let f=0;f1?(u=new Ua("multimat"+i,a.scene),u.subMaterials=r):u=new fe("multimat"+i,a.scene),r.length===1&&(u=r[0]),u._parentContainer=a.assetContainer,s.material||(s.material=u),new xs(i,a.scene,n,!1,s),s.computeWorldMatrix(!0),a.scene._blockEntityCollection=!1,s.subMeshes=[];let d=0;for(let f=0;f{a.position&&(a.position=e),(a.rotationQuaternion||a.rotation)&&(a.rotationQuaternion=t),a.scaling&&(a.scaling=i)},K3=(a,e)=>{if(e.matrix){const t=new m(0,0,0),i=new Z,s=new m(0,0,0);D.FromArray(e.matrix).decompose(s,i,t),z_(a,t,i,s)}else e.translation&&e.rotation&&e.scale&&z_(a,m.FromArray(e.translation),Z.FromArray(e.rotation),m.FromArray(e.scale));a.computeWorldMatrix(!0)},q3=(a,e,t)=>{let i=null;if(a.importOnlyMeshes&&(e.skin||e.meshes)&&a.importMeshesNames&&a.importMeshesNames.length>0&&a.importMeshesNames.indexOf(e.name||"")===-1)return null;if(e.skin){if(e.meshes){const s=a.skins[e.skin],r=dE(a,e,e.meshes,t,e.babylonNode);r.skeleton=a.scene.getLastSkeletonById(e.skin),r.skeleton===null&&(r.skeleton=j3(a,s,r,s.babylonSkeleton),s.babylonSkeleton||(s.babylonSkeleton=r.skeleton)),i=r}}else if(e.meshes)i=dE(a,e,e.mesh?[e.mesh]:e.meshes,t,e.babylonNode);else if(e.light&&!e.babylonNode&&!a.importOnlyMeshes){const s=a.lights[e.light];if(s){if(s.type==="ambient"){const r=s[s.type],n=new Xa(e.light,m.Zero(),a.scene);n.name=e.name||"",r.color&&(n.diffuse=K.FromArray(r.color)),i=n}else if(s.type==="directional"){const r=s[s.type],n=new en(e.light,m.Zero(),a.scene);n.name=e.name||"",r.color&&(n.diffuse=K.FromArray(r.color)),i=n}else if(s.type==="point"){const r=s[s.type],n=new Mo(e.light,m.Zero(),a.scene);n.name=e.name||"",r.color&&(n.diffuse=K.FromArray(r.color)),i=n}else if(s.type==="spot"){const r=s[s.type],n=new ar(e.light,m.Zero(),m.Zero(),0,0,a.scene);n.name=e.name||"",r.color&&(n.diffuse=K.FromArray(r.color)),r.fallOfAngle&&(n.angle=r.fallOfAngle),r.fallOffExponent&&(n.exponent=r.fallOffExponent),i=n}}}else if(e.camera&&!e.babylonNode&&!a.importOnlyMeshes){const s=a.cameras[e.camera];if(s){if(a.scene._blockEntityCollection=!!a.assetContainer,s.type==="orthographic"){const r=new nr(e.camera,m.Zero(),a.scene,!1);r.name=e.name||"",r.mode=Se.ORTHOGRAPHIC_CAMERA,r.attachControl(),i=r,r._parentContainer=a.assetContainer}else if(s.type==="perspective"){const r=s[s.type],n=new nr(e.camera,m.Zero(),a.scene,!1);n.name=e.name||"",n.attachControl(),r.aspectRatio||(r.aspectRatio=a.scene.getEngine().getRenderWidth()/a.scene.getEngine().getRenderHeight()),r.znear&&r.zfar&&(n.maxZ=r.zfar,n.minZ=r.znear),i=n,n._parentContainer=a.assetContainer}a.scene._blockEntityCollection=!1}}if(!e.jointName){if(e.babylonNode)return e.babylonNode;if(i===null){a.scene._blockEntityCollection=!!a.assetContainer;const s=new W(e.name||"",a.scene);s._parentContainer=a.assetContainer,a.scene._blockEntityCollection=!1,e.babylonNode=s,i=s}}if(i!==null){if(e.matrix&&i instanceof W)K3(i,e);else{const s=e.translation||[0,0,0],r=e.rotation||[0,0,0,1],n=e.scale||[1,1,1];z_(i,m.FromArray(s),Z.FromArray(r),m.FromArray(n))}i.updateCache(!0),e.babylonNode=i}return i},ju=(a,e,t,i=!1)=>{const s=a.nodes[e];let r=null;if(a.importOnlyMeshes&&!i&&a.importMeshesNames?a.importMeshesNames.indexOf(s.name||"")!==-1||a.importMeshesNames.length===0?i=!0:i=!1:i=!0,!s.jointName&&i&&(r=q3(a,s,e),r!==null&&(r.id=e,r.parent=t)),s.children)for(let n=0;n{let e=a.currentScene;if(e)for(let t=0;t{const o=r.values||s.parameters;for(const l in t){const h=t[l],c=h.type;if(c===Rr.FLOAT_MAT2||c===Rr.FLOAT_MAT3||c===Rr.FLOAT_MAT4){if(h.semantic&&!h.source&&!h.node)Es.SetMatrix(e.scene,a,h,l,i.getEffect());else if(h.semantic&&(h.source||h.node)){let u=e.scene.getNodeByName(h.source||h.node||"");if(u===null&&(u=e.scene.getNodeById(h.source||h.node||"")),u===null)continue;Es.SetMatrix(e.scene,u,h,l,i.getEffect())}}else{const u=o[s.uniforms[l]];if(!u)continue;if(c===Rr.SAMPLER_2D){const d=e.textures[r.values?u:h.value].babylonTexture;if(d==null)continue;i.getEffect().setTexture(l,d)}else Es.SetUniform(i.getEffect(),l,u,c)}}n(i)},Q3=(a,e,t,i,s)=>{const r=i.values||t.parameters,n=t.uniforms;for(const o in s){const l=s[o],h=l.type;let c=r[n[o]];if(c===void 0&&(c=l.value),!c)continue;const u=d=>f=>{l.value&&d&&(e.setTexture(d,f),delete s[d])};h===Rr.SAMPLER_2D?Hs.LoadTextureAsync(a,i.values?c:l.value,u(o),()=>u(null)):l.value&&Es.SetUniform(e,o,i.values?c:l.value,h)&&delete s[o]}},J3=(a,e,t)=>(i,s)=>{e.dispose(!0),t("Cannot compile program named "+a.name+". Error: "+s+". Default material will be applied")},ek=(a,e,t,i,s,r)=>n=>{Q3(a,e,t,i,s),e.onBind=o=>{Z3(o,a,s,e,t,i,r)}},pE=(a,e,t)=>{for(const i in e.uniforms){const s=e.uniforms[i],r=e.parameters[s];if(a.currentIdentifier===i&&r.semantic&&!r.source&&!r.node){const n=RC.indexOf(r.semantic);if(n!==-1)return delete t[i],IC[n]}}return a.currentIdentifier},_E=a=>{for(const e in a.materials)Hs.LoadMaterialAsync(a,e,()=>{},()=>{})};class Ra{static CreateRuntime(e,t,i){const s={extensions:{},accessors:{},buffers:{},bufferViews:{},meshes:{},lights:{},cameras:{},nodes:{},images:{},textures:{},shaders:{},programs:{},samplers:{},techniques:{},materials:{},animations:{},skins:{},extensionsUsed:[],scenes:{},buffersCount:0,shaderscount:0,scene:t,rootUrl:i,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[],assetContainer:null};return e.extensions&&fr(e.extensions,"extensions",s),e.extensionsUsed&&fr(e.extensionsUsed,"extensionsUsed",s),e.buffers&&G3(e.buffers,s),e.bufferViews&&fr(e.bufferViews,"bufferViews",s),e.accessors&&fr(e.accessors,"accessors",s),e.meshes&&fr(e.meshes,"meshes",s),e.lights&&fr(e.lights,"lights",s),e.cameras&&fr(e.cameras,"cameras",s),e.nodes&&fr(e.nodes,"nodes",s),e.images&&fr(e.images,"images",s),e.textures&&fr(e.textures,"textures",s),e.shaders&&z3(e.shaders,s),e.programs&&fr(e.programs,"programs",s),e.samplers&&fr(e.samplers,"samplers",s),e.techniques&&fr(e.techniques,"techniques",s),e.materials&&fr(e.materials,"materials",s),e.animations&&fr(e.animations,"animations",s),e.skins&&fr(e.skins,"skins",s),e.scenes&&(s.scenes=e.scenes),e.scene&&e.scenes&&(s.currentScene=e.scenes[e.scene]),s}static LoadBufferAsync(e,t,i,s,r){const n=e.buffers[t];X.IsBase64(n.uri)?setTimeout(()=>i(new Uint8Array(X.DecodeBase64(n.uri)))):X.LoadFile(e.rootUrl+n.uri,o=>i(new Uint8Array(o)),r,void 0,!0,o=>{o&&s(o.status+" "+o.statusText)})}static LoadTextureBufferAsync(e,t,i,s){const r=e.textures[t];if(!r||!r.source){s("");return}if(r.babylonTexture){i(null);return}const n=e.images[r.source];X.IsBase64(n.uri)?setTimeout(()=>i(new Uint8Array(X.DecodeBase64(n.uri)))):X.LoadFile(e.rootUrl+n.uri,o=>i(new Uint8Array(o)),void 0,void 0,!0,o=>{o&&s(o.status+" "+o.statusText)})}static CreateTextureAsync(e,t,i,s){const r=e.textures[t];if(r.babylonTexture){s(r.babylonTexture);return}const n=e.samplers[r.sampler],o=n.minFilter===zn.NEAREST_MIPMAP_NEAREST||n.minFilter===zn.NEAREST_MIPMAP_LINEAR||n.minFilter===zn.LINEAR_MIPMAP_NEAREST||n.minFilter===zn.LINEAR_MIPMAP_LINEAR,l=k.BILINEAR_SAMPLINGMODE,h=i==null?new Blob:new Blob([i]),c=URL.createObjectURL(h),u=()=>URL.revokeObjectURL(c),d=new k(c,e.scene,!o,!0,l,u,u);n.wrapS!==void 0&&(d.wrapU=Es.GetWrapMode(n.wrapS)),n.wrapT!==void 0&&(d.wrapV=Es.GetWrapMode(n.wrapT)),d.name=t,r.babylonTexture=d,s(d)}static LoadShaderStringAsync(e,t,i,s){const r=e.shaders[t];if(X.IsBase64(r.uri)){const n=atob(r.uri.split(",")[1]);i&&i(n)}else X.LoadFile(e.rootUrl+r.uri,i,void 0,void 0,!1,n=>{n&&s&&s(n.status+" "+n.statusText)})}static LoadMaterialAsync(e,t,i,s){const r=e.materials[t];if(!r.technique){s&&s("No technique found.");return}const n=e.techniques[r.technique];if(!n){e.scene._blockEntityCollection=!!e.assetContainer;const A=new fe(t,e.scene);A._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,A.diffuseColor=new K(.5,.5,.5),A.sideOrientation=ee.CounterClockWiseSideOrientation,i(A);return}const o=e.programs[n.program],l=n.states,h=xt.ShadersStore[o.vertexShader+"VertexShader"],c=xt.ShadersStore[o.fragmentShader+"PixelShader"];let u="",d="";const f=new cE(h),p=new cE(c),_={},g=[],T=[],E=[];for(const A in n.uniforms){const R=n.uniforms[A],P=n.parameters[R];if(_[A]=P,P.semantic&&!P.node&&!P.source){const L=RC.indexOf(P.semantic);L!==-1?(g.push(IC[L]),delete _[A]):g.push(A)}else P.type===Rr.SAMPLER_2D?E.push(A):g.push(A)}for(const A in n.attributes){const R=n.attributes[A],P=n.parameters[R];if(P.semantic){const L=uE(P);L&&T.push(L)}}for(;!f.isEnd()&&f.getNextToken();){if(f.currentToken!==oo.IDENTIFIER){u+=f.currentString;continue}let R=!1;for(const P in n.attributes){const L=n.attributes[P],O=n.parameters[L];if(f.currentIdentifier===P&&O.semantic){u+=uE(O),R=!0;break}}R||(u+=pE(f,n,_))}for(;!p.isEnd()&&p.getNextToken();){if(p.currentToken!==oo.IDENTIFIER){d+=p.currentString;continue}d+=pE(p,n,_)}const S={vertex:o.vertexShader+t,fragment:o.fragmentShader+t},v={attributes:T,uniforms:g,samplers:E,needAlphaBlending:l&&l.enable&&l.enable.indexOf(3042)!==-1};xt.ShadersStore[o.vertexShader+t+"VertexShader"]=u,xt.ShadersStore[o.fragmentShader+t+"PixelShader"]=d;const y=new Dr(t,e.scene,S,v);if(y.onError=J3(o,y,s),y.onCompiled=ek(e,y,n,r,_,i),y.sideOrientation=ee.CounterClockWiseSideOrientation,l&&l.functions){const A=l.functions;A.cullFace&&A.cullFace[0]!==G_.BACK&&(y.backFaceCulling=!1);const R=A.blendFuncSeparate;R&&(R[0]===Vi.SRC_ALPHA&&R[1]===Vi.ONE_MINUS_SRC_ALPHA&&R[2]===Vi.ONE&&R[3]===Vi.ONE?y.alphaMode=H.ALPHA_COMBINE:R[0]===Vi.ONE&&R[1]===Vi.ONE&&R[2]===Vi.ZERO&&R[3]===Vi.ONE?y.alphaMode=H.ALPHA_ONEONE:R[0]===Vi.SRC_ALPHA&&R[1]===Vi.ONE&&R[2]===Vi.ZERO&&R[3]===Vi.ONE?y.alphaMode=H.ALPHA_ADD:R[0]===Vi.ZERO&&R[1]===Vi.ONE_MINUS_SRC_COLOR&&R[2]===Vi.ONE&&R[3]===Vi.ONE?y.alphaMode=H.ALPHA_SUBTRACT:R[0]===Vi.DST_COLOR&&R[1]===Vi.ZERO&&R[2]===Vi.ONE&&R[3]===Vi.ONE?y.alphaMode=H.ALPHA_MULTIPLY:R[0]===Vi.SRC_ALPHA&&R[1]===Vi.ONE_MINUS_SRC_COLOR&&R[2]===Vi.ONE&&R[3]===Vi.ONE&&(y.alphaMode=H.ALPHA_MAXIMIZED))}}}let Ic=class W_{static RegisterExtension(e){if(W_.Extensions[e.name]){X.Error('Tool with the same name "'+e.name+'" already exists');return}W_.Extensions[e.name]=e}dispose(){}_importMeshAsync(e,t,i,s,r,n,o,l){return t.useRightHandedSystem=!0,Hs.LoadRuntimeAsync(t,i,s,h=>{h.assetContainer=r,h.importOnlyMeshes=!0,e===""?h.importMeshesNames=[]:typeof e=="string"?h.importMeshesNames=[e]:e&&!(e instanceof Array)?h.importMeshesNames=[e]:(h.importMeshesNames=[],X.Warn("Argument meshesNames must be of type string or string[]")),this._createNodes(h);const c=[],u=[];for(const d in h.nodes){const f=h.nodes[d];f.babylonNode instanceof gt&&c.push(f.babylonNode)}for(const d in h.skins){const f=h.skins[d];f.babylonSkeleton instanceof So&&u.push(f.babylonSkeleton)}this._loadBuffersAsync(h,()=>{this._loadShadersAsync(h,()=>{_E(h),fE(h),!bi.IncrementalLoading&&n&&n(c,u)})}),bi.IncrementalLoading&&n&&n(c,u)},l),!0}importMeshAsync(e,t,i,s,r,n){return new Promise((o,l)=>{this._importMeshAsync(e,t,s,r,i,(h,c)=>{o({meshes:h,particleSystems:[],skeletons:c,animationGroups:[],lights:[],transformNodes:[],geometries:[],spriteManagers:[]})},n,h=>{l(new Error(h))})})}_loadAsync(e,t,i,s,r,n){e.useRightHandedSystem=!0,Hs.LoadRuntimeAsync(e,t,i,o=>{Hs.LoadRuntimeExtensionsAsync(o,()=>{this._createNodes(o),this._loadBuffersAsync(o,()=>{this._loadShadersAsync(o,()=>{_E(o),fE(o),bi.IncrementalLoading||s()})}),bi.IncrementalLoading&&s()},n)},n)}loadAsync(e,t,i,s){return new Promise((r,n)=>{this._loadAsync(e,t,i,()=>{r()},s,o=>{n(new Error(o))})})}_loadShadersAsync(e,t){let i=!1;const s=(r,n)=>{Hs.LoadShaderStringAsync(e,r,o=>{o instanceof ArrayBuffer||(e.loadedShaderCount++,o&&(xt.ShadersStore[r+(n.type===k_.VERTEX?"VertexShader":"PixelShader")]=o),e.loadedShaderCount===e.shaderscount&&t())},()=>{X.Error("Error when loading shader program named "+r+" located at "+n.uri)})};for(const r in e.shaders){i=!0;const n=e.shaders[r];n?s.bind(this,r,n)():X.Error("No shader named: "+r)}i||t()}_loadBuffersAsync(e,t){let i=!1;const s=(r,n)=>{Hs.LoadBufferAsync(e,r,o=>{e.loadedBufferCount++,o&&(o.byteLength!=e.buffers[r].byteLength&&X.Error("Buffer named "+r+" is length "+o.byteLength+". Expected: "+n.byteLength),e.loadedBufferViews[r]=o),e.loadedBufferCount===e.buffersCount&&t()},()=>{X.Error("Error when loading buffer named "+r+" located at "+n.uri)})};for(const r in e.buffers){i=!0;const n=e.buffers[r];n?s.bind(this,r,n)():X.Error("No buffer named: "+r)}i||t()}_createNodes(e){let t=e.currentScene;if(t)for(let i=0;in.loadRuntimeAsync(e,t,i,s,r),()=>{setTimeout(()=>{s&&s(Ra.CreateRuntime(t.json,e,i))})})}static LoadRuntimeExtensionsAsync(e,t,i){Hs._ApplyExtensions(s=>s.loadRuntimeExtensionsAsync(e,t,i),()=>{setTimeout(()=>{t()})})}static LoadBufferAsync(e,t,i,s,r){Hs._ApplyExtensions(n=>n.loadBufferAsync(e,t,i,s,r),()=>{Ra.LoadBufferAsync(e,t,i,s,r)})}static LoadTextureAsync(e,t,i,s){Hs._LoadTextureBufferAsync(e,t,r=>{r&&Hs._CreateTextureAsync(e,t,r,i,s)},s)}static LoadShaderStringAsync(e,t,i,s){Hs._ApplyExtensions(r=>r.loadShaderStringAsync(e,t,i,s),()=>{Ra.LoadShaderStringAsync(e,t,i,s)})}static LoadMaterialAsync(e,t,i,s){Hs._ApplyExtensions(r=>r.loadMaterialAsync(e,t,i,s),()=>{Ra.LoadMaterialAsync(e,t,i,s)})}static _LoadTextureBufferAsync(e,t,i,s){Hs._ApplyExtensions(r=>r.loadTextureBufferAsync(e,t,i,s),()=>{Ra.LoadTextureBufferAsync(e,t,i,s)})}static _CreateTextureAsync(e,t,i,s,r){Hs._ApplyExtensions(n=>n.createTextureAsync(e,t,i,s,r),()=>{Ra.CreateTextureAsync(e,t,i,s)})}static _ApplyExtensions(e,t){for(const i in Ic.Extensions){const s=Ic.Extensions[i];if(e(s))return}t()}}bi._CreateGLTF1Loader=()=>new Ic;const tk="binary_glTF";class ik extends Hs{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,i,s){const r=t.json.extensionsUsed;return!r||r.indexOf(this.name)===-1||!t.bin?!1:(this._bin=t.bin,s(Ra.CreateRuntime(t.json,e,i)),!0)}loadBufferAsync(e,t,i,s){return e.extensionsUsed.indexOf(this.name)===-1||t!==tk?!1:(this._bin.readAsync(0,this._bin.byteLength).then(i,r=>s(r.message)),!0)}loadTextureBufferAsync(e,t,i){const s=e.textures[t],r=e.images[s.source];if(!r.extensions||!(this.name in r.extensions))return!1;const n=r.extensions[this.name],o=e.bufferViews[n.bufferView],l=Es.GetBufferFromBufferView(e,o,0,o.byteLength,ao.UNSIGNED_BYTE);return i(l),!0}loadShaderStringAsync(e,t,i){const s=e.shaders[t];if(!s.extensions||!(this.name in s.extensions))return!1;const r=s.extensions[this.name],n=e.bufferViews[r.bufferView],o=Es.GetBufferFromBufferView(e,n,0,n.byteLength,ao.UNSIGNED_BYTE);return setTimeout(()=>{const l=Es.DecodeBufferToText(o);i(l)}),!0}}Ic.RegisterExtension(new ik);class sk extends Hs{constructor(){super("KHR_materials_common")}loadRuntimeExtensionsAsync(e){if(!e.extensions)return!1;const t=e.extensions[this.name];if(!t)return!1;const i=t.lights;if(i)for(const s in i){const r=i[s];switch(r.type){case"ambient":{const n=new Xa(r.name,new m(0,1,0),e.scene),o=r.ambient;o&&(n.diffuse=K.FromArray(o.color||[1,1,1]));break}case"point":{const n=new Mo(r.name,new m(10,10,10),e.scene),o=r.point;o&&(n.diffuse=K.FromArray(o.color||[1,1,1]));break}case"directional":{const n=new en(r.name,new m(0,-1,0),e.scene),o=r.directional;o&&(n.diffuse=K.FromArray(o.color||[1,1,1]));break}case"spot":{const n=r.spot;if(n){const o=new ar(r.name,new m(0,10,0),new m(0,-1,0),n.fallOffAngle||Math.PI,n.fallOffExponent||0,e.scene);o.diffuse=K.FromArray(n.color||[1,1,1])}break}default:X.Warn('GLTF Material Common extension: light type "'+r.type+"” not supported");break}}return!1}loadMaterialAsync(e,t,i,s){const r=e.materials[t];if(!r||!r.extensions)return!1;const n=r.extensions[this.name];if(!n)return!1;const o=new fe(t,e.scene);return o.sideOrientation=ee.CounterClockWiseSideOrientation,n.technique==="CONSTANT"&&(o.disableLighting=!0),o.backFaceCulling=n.doubleSided===void 0?!1:!n.doubleSided,o.alpha=n.values.transparency===void 0?1:n.values.transparency,o.specularPower=n.values.shininess===void 0?0:n.values.shininess,typeof n.values.ambient=="string"?this._loadTexture(e,n.values.ambient,o,"ambientTexture",s):o.ambientColor=K.FromArray(n.values.ambient||[0,0,0]),typeof n.values.diffuse=="string"?this._loadTexture(e,n.values.diffuse,o,"diffuseTexture",s):o.diffuseColor=K.FromArray(n.values.diffuse||[0,0,0]),typeof n.values.emission=="string"?this._loadTexture(e,n.values.emission,o,"emissiveTexture",s):o.emissiveColor=K.FromArray(n.values.emission||[0,0,0]),typeof n.values.specular=="string"?this._loadTexture(e,n.values.specular,o,"specularTexture",s):o.specularColor=K.FromArray(n.values.specular||[0,0,0]),!0}_loadTexture(e,t,i,s,r){Ra.LoadTextureBufferAsync(e,t,n=>{Ra.CreateTextureAsync(e,t,n,o=>i[s]=o)},r)}}Ic.RegisterExtension(new sk);function mE(a,e,t,i){return m.FromArray(e,t).scaleInPlace(i)}function rk(a,e,t,i){return Z.FromArray(e,t).scaleInPlace(i)}function nk(a,e,t,i){const s=new Array(a._numMorphTargets);for(let r=0;r({frame:l.frame,inTangent:l.inTangent?l.inTangent[n]:void 0,value:l.value[n],outTangent:l.outTangent?l.outTangent[n]:void 0,interpolation:l.interpolation}))),e._primitiveBabylonMeshes){for(const l of e._primitiveBabylonMeshes)if(l.morphTargetManager){const h=l.morphTargetManager.getTarget(n),c=o.clone();h.animations.push(c),r(h,c)}}}}}const iu={translation:[new o_(j.ANIMATIONTYPE_VECTOR3,"position",mE,()=>3)],rotation:[new o_(j.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",rk,()=>4)],scale:[new o_(j.ANIMATIONTYPE_VECTOR3,"scaling",mE,()=>3)],weights:[new ak(j.ANIMATIONTYPE_FLOAT,"influence",nk,a=>a._numMorphTargets)]};function MC(...a){const e=t=>t&&typeof t=="object";return a.reduce((t,i)=>(Object.keys(i).forEach(s=>{const r=t[s],n=i[s];Array.isArray(r)&&Array.isArray(n)?t[s]=r.concat(...n):e(r)&&e(n)?t[s]=MC(r,n):t[s]=n}),t),{})}class et{static Get(e,t,i){if(!t||i==null||!t[i])throw new Error(`${e}: Failed to find index (${i})`);return t[i]}static TryGet(e,t){return!e||t==null||!e[t]?null:e[t]}static Assign(e){if(e)for(let t=0;te.dispose&&e.dispose()),this._extensions.length=0,this._gltf=null,this._bin=null,this._babylonScene=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions.length=0,this._parent.dispose())}importMeshAsync(e,t,i,s,r,n,o=""){return Promise.resolve().then(()=>{this._babylonScene=t,this._assetContainer=i,this._loadData(s);let l=null;if(e){const h={};if(this._gltf.nodes)for(const u of this._gltf.nodes)u.name&&(h[u.name]=u.index);l=(e instanceof Array?e:[e]).map(u=>{const d=h[u];if(d===void 0)throw new Error(`Failed to find node '${u}'`);return d})}return this._loadAsync(r,o,l,()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]}))})}loadAsync(e,t,i,s,r=""){return Promise.resolve().then(()=>(this._babylonScene=e,this._loadData(t),this._loadAsync(i,r,null,()=>{})))}_loadAsync(e,t,i,s){return Promise.resolve().then(()=>{this._rootUrl=e,this._uniqueRootUrl=!e.startsWith("file:")&&t?e:`${e}${Date.now()}/`,this._fileName=t,this._allMaterialsDirtyRequired=!1,this._loadExtensions(),this._checkExtensions();const r=`${Gr[Gr.LOADING]} => ${Gr[Gr.READY]}`,n=`${Gr[Gr.LOADING]} => ${Gr[Gr.COMPLETE]}`;this._parent._startPerformanceCounter(r),this._parent._startPerformanceCounter(n),this._parent._setState(Gr.LOADING),this._extensionsOnLoading();const o=new Array,l=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials){if(i)o.push(this.loadSceneAsync("/nodes",{nodes:i,index:-1}));else if(this._gltf.scene!=null||this._gltf.scenes&&this._gltf.scenes[0]){const c=et.Get("/scene",this._gltf.scenes,this._gltf.scene||0);o.push(this.loadSceneAsync(`/scenes/${c.index}`,c))}}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let c=0;c{}))}return this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=l:this._babylonScene._forceBlockMaterialDirtyMechanism(l),this._parent.compileMaterials&&o.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&o.push(this._compileShadowGeneratorsAsync()),Promise.all(o).then(()=>(this._rootBabylonMesh&&this._rootBabylonMesh!==this._parent.customRootNode&&this._rootBabylonMesh.setEnabled(!0),this._extensionsOnReady(),this._parent._setState(Gr.READY),this._startAnimations(),s())).then(c=>(this._parent._endPerformanceCounter(r),X.SetImmediate(()=>{this._disposed||Promise.all(this._completePromises).then(()=>{this._parent._endPerformanceCounter(n),this._parent._setState(Gr.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()},u=>{this._parent.onErrorObservable.notifyObservers(u),this._parent.onErrorObservable.clear(),this.dispose()})}),c))}).catch(r=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(r),this._parent.onErrorObservable.clear(),this.dispose()),r})}_loadData(e){if(this._gltf=e.json,this._setupData(),e.bin){const t=this._gltf.buffers;if(t&&t[0]&&!t[0].uri){const i=t[0];(i.byteLengthe.bin.byteLength)&&N.Warn(`Binary buffer length (${i.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else N.Warn("Unexpected BIN chunk")}}_setupData(){if(et.Assign(this._gltf.accessors),et.Assign(this._gltf.animations),et.Assign(this._gltf.buffers),et.Assign(this._gltf.bufferViews),et.Assign(this._gltf.cameras),et.Assign(this._gltf.images),et.Assign(this._gltf.materials),et.Assign(this._gltf.meshes),et.Assign(this._gltf.nodes),et.Assign(this._gltf.samplers),et.Assign(this._gltf.scenes),et.Assign(this._gltf.skins),et.Assign(this._gltf.textures),this._gltf.nodes){const e={};for(const i of this._gltf.nodes)if(i.children)for(const s of i.children)e[s]=i.index;const t=this._createRootNode();for(const i of this._gltf.nodes){const s=e[i.index];i.parent=s===void 0?t:this._gltf.nodes[s]}}}_loadExtensions(){for(const e in Ie._RegisteredExtensions){const t=Ie._RegisteredExtensions[e].factory(this);t.name!==e&&N.Warn(`The name of the glTF loader extension instance does not match the registered name: ${t.name} !== ${e}`),this._extensions.push(t),this._parent.onExtensionLoadedObservable.notifyObservers(t)}this._extensions.sort((e,t)=>(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE)),this._parent.onExtensionLoadedObservable.clear()}_checkExtensions(){if(this._gltf.extensionsRequired){for(const e of this._gltf.extensionsRequired)if(!this._extensions.some(i=>i.name===e&&i.enabled))throw new Error(`Required extension ${e} is not available`)}}_createRootNode(){if(this._parent.customRootNode!==void 0)return this._rootBabylonMesh=this._parent.customRootNode,{_babylonTransformNode:this._rootBabylonMesh===null?void 0:this._rootBabylonMesh,index:-1};this._babylonScene._blockEntityCollection=!!this._assetContainer;const e=new W("__root__",this._babylonScene);this._rootBabylonMesh=e,this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);const t={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case $u.AUTO:{this._babylonScene.useRightHandedSystem||(t.rotation=[0,1,0,0],t.scale=[1,1,-1],Ie._LoadTransform(t,this._rootBabylonMesh));break}case $u.FORCE_RIGHT_HANDED:{this._babylonScene.useRightHandedSystem=!0;break}default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(e),t}loadSceneAsync(e,t){const i=this._extensionsLoadSceneAsync(e,t);if(i)return i;const s=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const r of t.nodes){const n=et.Get(`${e}/nodes/${r}`,this._gltf.nodes,r);s.push(this.loadNodeAsync(`/nodes/${n.index}`,n,o=>{o.parent=this._rootBabylonMesh}))}for(const r of this._postSceneLoadActions)r();return s.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(s).then(()=>{})}_forEachPrimitive(e,t){if(e._primitiveBabylonMeshes)for(const i of e._primitiveBabylonMeshes)t(i)}_getGeometries(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,s=>{const r=s.geometry;r&&e.indexOf(r)===-1&&e.push(r)});return e}_getMeshes(){const e=[];this._rootBabylonMesh instanceof gt&&e.push(this._rootBabylonMesh);const t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,s=>{e.push(s)});return e}_getTransformNodes(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)i._babylonTransformNode&&i._babylonTransformNode.getClassName()==="TransformNode"&&e.push(i._babylonTransformNode),i._babylonTransformNodeForSkin&&e.push(i._babylonTransformNodeForSkin);return e}_getSkeletons(){const e=[],t=this._gltf.skins;if(t)for(const i of t)i._data&&e.push(i._data.babylonSkeleton);return e}_getAnimationGroups(){const e=[],t=this._gltf.animations;if(t)for(const i of t)i._babylonAnimationGroup&&e.push(i._babylonAnimationGroup);return e}_startAnimations(){switch(this._parent.animationStartMode){case kl.NONE:break;case kl.FIRST:{const e=this._getAnimationGroups();e.length!==0&&e[0].start(!0);break}case kl.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:{N.Error(`Invalid animation start mode (${this._parent.animationStartMode})`);return}}}loadNodeAsync(e,t,i=()=>{}){const s=this._extensionsLoadNodeAsync(e,t,i);if(s)return s;if(t._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const r=new Array;this.logOpen(`${e} ${t.name||""}`);const n=o=>{if(Ie.AddPointerMetadata(o,e),Ie._LoadTransform(t,o),t.camera!=null){const l=et.Get(`${e}/camera`,this._gltf.cameras,t.camera);r.push(this.loadCameraAsync(`/cameras/${l.index}`,l,h=>{h.parent=o}))}if(t.children)for(const l of t.children){const h=et.Get(`${e}/children/${l}`,this._gltf.nodes,l);r.push(this.loadNodeAsync(`/nodes/${h.index}`,h,c=>{c.parent=o}))}i(o)};if(t.mesh==null||t.skin!=null){const o=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const l=new Ke(o,this._babylonScene);l._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t.mesh==null?t._babylonTransformNode=l:t._babylonTransformNodeForSkin=l,n(l)}if(t.mesh!=null)if(t.skin==null){const o=et.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);r.push(this._loadMeshAsync(`/meshes/${o.index}`,t,o,n))}else{const o=et.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);r.push(this._loadMeshAsync(`/meshes/${o.index}`,t,o,l=>{const h=t._babylonTransformNodeForSkin;l.metadata=MC(h.metadata,l.metadata||{});const c=et.Get(`${e}/skin`,this._gltf.skins,t.skin);r.push(this._loadSkinAsync(`/skins/${c.index}`,t,c,u=>{this._forEachPrimitive(t,d=>{d.skeleton=u}),this._postSceneLoadActions.push(()=>{if(c.skeleton!=null){const d=et.Get(`/skins/${c.index}/skeleton`,this._gltf.nodes,c.skeleton).parent;t.index===d.index?l.parent=h.parent:l.parent=d._babylonTransformNode}else l.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:h,skinnedNode:l})})}))}))}return this.logClose(),Promise.all(r).then(()=>(this._forEachPrimitive(t,o=>{o.geometry&&o.geometry.useBoundingInfoFromGeometry?o._updateBoundingInfo():o.refreshBoundingInfo(!0,!0)}),t._babylonTransformNode))}_loadMeshAsync(e,t,i,s){const r=i.primitives;if(!r||!r.length)throw new Error(`${e}: Primitives are missing`);r[0].index==null&&et.Assign(r);const n=new Array;this.logOpen(`${e} ${i.name||""}`);const o=t.name||`node${t.index}`;if(r.length===1){const l=i.primitives[0];n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${l.index}`,o,t,i,l,h=>{t._babylonTransformNode=h,t._primitiveBabylonMeshes=[h]}))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new Ke(o,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(const l of r)n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${l.index}`,`${o}_primitive${l.index}`,t,i,l,h=>{h.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(h)}))}return s(t._babylonTransformNode),this.logClose(),Promise.all(n).then(()=>t._babylonTransformNode)}_loadMeshPrimitiveAsync(e,t,i,s,r,n){const o=this._extensionsLoadMeshPrimitiveAsync(e,t,i,s,r,n);if(o)return o;this.logOpen(`${e}`);const l=this._disableInstancedMesh===0&&this._parent.createInstances&&i.skin==null&&!s.primitives[0].targets;let h,c;if(l&&r._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,h=r._instanceData.babylonSourceMesh.createInstance(t),h._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,c=r._instanceData.promise;else{const u=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const d=new W(t,this._babylonScene);d._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,d.overrideMaterialSideOrientation=this._babylonScene.useRightHandedSystem?ee.CounterClockWiseSideOrientation:ee.ClockWiseSideOrientation,this._createMorphTargets(e,i,s,r,d),u.push(this._loadVertexDataAsync(e,r,d).then(p=>this._loadMorphTargetsAsync(e,r,d,p).then(()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,p.applyToMesh(d),p._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})));const f=Ie._GetDrawMode(e,r.mode);if(r.material==null){let p=this._defaultBabylonMaterialData[f];p||(p=this._createDefaultMaterial("__GLTFLoader._default",f),this._parent.onMaterialLoadedObservable.notifyObservers(p),this._defaultBabylonMaterialData[f]=p),d.material=p}else if(!this.parent.skipMaterials){const p=et.Get(`${e}/material`,this._gltf.materials,r.material);u.push(this._loadMaterialAsync(`/materials/${p.index}`,p,d,f,_=>{d.material=_}))}c=Promise.all(u),l&&(r._instanceData={babylonSourceMesh:d,promise:c}),h=d}return Ie.AddPointerMetadata(h,e),this._parent.onMeshLoadedObservable.notifyObservers(h),n(h),this.logClose(),c.then(()=>h)}_loadVertexDataAsync(e,t,i){const s=this._extensionsLoadVertexDataAsync(e,t,i);if(s)return s;const r=t.attributes;if(!r)throw new Error(`${e}: Attributes are missing`);const n=new Array,o=new xs(i.name,this._babylonScene);if(t.indices==null)i.isUnIndexed=!0;else{const h=et.Get(`${e}/indices`,this._gltf.accessors,t.indices);n.push(this._loadIndicesAccessorAsync(`/accessors/${h.index}`,h).then(c=>{o.setIndices(c)}))}const l=(h,c,u)=>{if(r[h]==null)return;i._delayInfo=i._delayInfo||[],i._delayInfo.indexOf(c)===-1&&i._delayInfo.push(c);const d=et.Get(`${e}/attributes/${h}`,this._gltf.accessors,r[h]);n.push(this._loadVertexAccessorAsync(`/accessors/${d.index}`,d,c).then(f=>{if(f.getKind()===C.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!i.skeleton&&d.min&&d.max){const p=V.Vector3[0].copyFromFloats(...d.min),_=V.Vector3[1].copyFromFloats(...d.max);if(d.normalized&&d.componentType!==5126){let g=1;switch(d.componentType){case 5120:g=127;break;case 5121:g=255;break;case 5122:g=32767;break;case 5123:g=65535;break}const T=1/g;p.scaleInPlace(T),_.scaleInPlace(T)}o._boundingInfo=new Pr(p,_),o.useBoundingInfoFromGeometry=!0}o.setVerticesBuffer(f,d.count)})),c==C.MatricesIndicesExtraKind&&(i.numBoneInfluencers=8),u&&u(d)};return l("POSITION",C.PositionKind),l("NORMAL",C.NormalKind),l("TANGENT",C.TangentKind),l("TEXCOORD_0",C.UVKind),l("TEXCOORD_1",C.UV2Kind),l("TEXCOORD_2",C.UV3Kind),l("TEXCOORD_3",C.UV4Kind),l("TEXCOORD_4",C.UV5Kind),l("TEXCOORD_5",C.UV6Kind),l("JOINTS_0",C.MatricesIndicesKind),l("WEIGHTS_0",C.MatricesWeightsKind),l("JOINTS_1",C.MatricesIndicesExtraKind),l("WEIGHTS_1",C.MatricesWeightsExtraKind),l("COLOR_0",C.ColorKind,h=>{h.type==="VEC4"&&(i.hasVertexAlpha=!0)}),Promise.all(n).then(()=>o)}_createMorphTargets(e,t,i,s,r){if(!s.targets)return;if(t._numMorphTargets==null)t._numMorphTargets=s.targets.length;else if(s.targets.length!==t._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);const n=i.extras?i.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,r.morphTargetManager=new ca(this._babylonScene),r.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,r.morphTargetManager.areUpdatesFrozen=!0;for(let o=0;o{n.areUpdatesFrozen=!1})}_loadMorphTargetVertexDataAsync(e,t,i,s){const r=new Array,n=(o,l,h)=>{if(i[o]==null)return;const c=t.getVertexBuffer(l);if(!c)return;const u=et.Get(`${e}/${o}`,this._gltf.accessors,i[o]);r.push(this._loadFloatAccessorAsync(`/accessors/${u.index}`,u).then(d=>{h(c,d)}))};return n("POSITION",C.PositionKind,(o,l)=>{const h=new Float32Array(l.length);o.forEach(l.length,(c,u)=>{h[u]=l[u]+c}),s.setPositions(h)}),n("NORMAL",C.NormalKind,(o,l)=>{const h=new Float32Array(l.length);o.forEach(h.length,(c,u)=>{h[u]=l[u]+c}),s.setNormals(h)}),n("TANGENT",C.TangentKind,(o,l)=>{const h=new Float32Array(l.length/3*4);let c=0;o.forEach(l.length/3*4,(u,d)=>{(d+1)%4!==0&&(h[c]=l[c]+u,c++)}),s.setTangents(h)}),Promise.all(r).then(()=>{})}static _LoadTransform(e,t){if(e.skin!=null)return;let i=m.Zero(),s=Z.Identity(),r=m.One();e.matrix?D.FromArray(e.matrix).decompose(r,s,i):(e.translation&&(i=m.FromArray(e.translation)),e.rotation&&(s=Z.FromArray(e.rotation)),e.scale&&(r=m.FromArray(e.scale))),t.position=i,t.rotationQuaternion=s,t.scaling=r}_loadSkinAsync(e,t,i,s){const r=this._extensionsLoadSkinAsync(e,t,i);if(r)return r;if(i._data)return s(i._data.babylonSkeleton),i._data.promise;const n=`skeleton${i.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new So(i.name||n,n,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,i,o);const l=this._loadSkinInverseBindMatricesDataAsync(e,i).then(h=>{this._updateBoneMatrices(o,h)});return i._data={babylonSkeleton:o,promise:l},s(o),l}_loadBones(e,t,i){if(t.skeleton==null||this._parent.alwaysComputeSkeletonRootNode){const r=this._findSkeletonRootNode(`${e}/joints`,t.joints);if(r)if(t.skeleton===void 0)t.skeleton=r.index;else{const n=(l,h)=>{for(;h.parent;h=h.parent)if(h.parent===l)return!0;return!1},o=et.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);o!==r&&!n(o,r)&&(N.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=r.index)}else N.Warn(`${e}: Failed to find common root`)}const s={};for(const r of t.joints){const n=et.Get(`${e}/joints/${r}`,this._gltf.nodes,r);this._loadBone(n,t,i,s)}}_findSkeletonRootNode(e,t){if(t.length===0)return null;const i={};for(const r of t){const n=[];let o=et.Get(`${e}/${r}`,this._gltf.nodes,r);for(;o.index!==-1;)n.unshift(o),o=o.parent;i[r]=n}let s=null;for(let r=0;;++r){let n=i[t[0]];if(r>=n.length)return s;const o=n[r];for(let l=1;l=n.length||o!==n[r])return s;s=o}}_loadBone(e,t,i,s){let r=s[e.index];if(r)return r;let n=null;e.index!==t.skeleton&&(e.parent&&e.parent.index!==-1?n=this._loadBone(e.parent,t,i,s):t.skeleton!==void 0&&N.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));const o=t.joints.indexOf(e.index);return r=new Xt(e.name||`joint${e.index}`,i,n,this._getNodeMatrix(e),null,null,o),s[e.index]=r,this._postSceneLoadActions.push(()=>{r.linkTransformNode(e._babylonTransformNode)}),r}_loadSkinInverseBindMatricesDataAsync(e,t){if(t.inverseBindMatrices==null)return Promise.resolve(null);const i=et.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${i.index}`,i)}_updateBoneMatrices(e,t){for(const i of e.bones){const s=D.Identity(),r=i._index;t&&r!==-1&&(D.FromArrayToRef(t,r*16,s),s.invertToRef(s));const n=i.getParent();n&&s.multiplyToRef(n.getAbsoluteInverseBindMatrix(),s),i.updateMatrix(s,!1,!1),i._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?D.FromArray(e.matrix):D.Compose(e.scale?m.FromArray(e.scale):m.One(),e.rotation?Z.FromArray(e.rotation):Z.Identity(),e.translation?m.FromArray(e.translation):m.Zero())}loadCameraAsync(e,t,i=()=>{}){const s=this._extensionsLoadCameraAsync(e,t,i);if(s)return s;const r=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const n=new nr(t.name||`camera${t.index}`,m.Zero(),this._babylonScene,!1);switch(n._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n.ignoreParentScaling=!0,t._babylonCamera=n,n.rotation.set(0,Math.PI,0),t.type){case"perspective":{const o=t.perspective;if(!o)throw new Error(`${e}: Camera perspective properties are missing`);n.fov=o.yfov,n.minZ=o.znear,n.maxZ=o.zfar||0;break}case"orthographic":{if(!t.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);n.mode=Se.ORTHOGRAPHIC_CAMERA,n.orthoLeft=-t.orthographic.xmag,n.orthoRight=t.orthographic.xmag,n.orthoBottom=-t.orthographic.ymag,n.orthoTop=t.orthographic.ymag,n.minZ=t.orthographic.znear,n.maxZ=t.orthographic.zfar;break}default:throw new Error(`${e}: Invalid camera type (${t.type})`)}return Ie.AddPointerMetadata(n,e),this._parent.onCameraLoadedObservable.notifyObservers(n),i(n),this.logClose(),Promise.all(r).then(()=>n)}_loadAnimationsAsync(){const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let i=0;i{r.targetedAnimations.length===0&&r.dispose()}))}return Promise.all(t).then(()=>{})}loadAnimationAsync(e,t){const i=this._extensionsLoadAnimationAsync(e,t);if(i)return i;this._babylonScene._blockEntityCollection=!!this._assetContainer;const s=new ta(t.name||`animation${t.index}`,this._babylonScene);s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=s;const r=new Array;et.Assign(t.channels),et.Assign(t.samplers);for(const n of t.channels)r.push(this._loadAnimationChannelAsync(`${e}/channels/${n.index}`,e,t,n,(o,l)=>{o.animations=o.animations||[],o.animations.push(l),s.addTargetedAnimation(l,o)}));return Promise.all(r).then(()=>(s.normalize(0),s))}_loadAnimationChannelAsync(e,t,i,s,r){const n=this._extensionsLoadAnimationChannelAsync(e,t,i,s,r);if(n)return n;if(s.target.node==null)return Promise.resolve();const o=et.Get(`${e}/target/node`,this._gltf.nodes,s.target.node);if(s.target.path==="weights"&&!o._numMorphTargets||s.target.path!=="weights"&&!o._babylonTransformNode)return Promise.resolve();let l;switch(s.target.path){case"translation":{l=iu.translation;break}case"rotation":{l=iu.rotation;break}case"scale":{l=iu.scale;break}case"weights":{l=iu.weights;break}default:throw new Error(`${e}/target/path: Invalid value (${s.target.path})`)}const h={object:o,info:l};return this._loadAnimationChannelFromTargetInfoAsync(e,t,i,s,h,r)}_loadAnimationChannelFromTargetInfoAsync(e,t,i,s,r,n){const o=this.parent.targetFps,l=1/o,h=et.Get(`${e}/sampler`,i.samplers,s.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${s.sampler}`,h).then(c=>{let u=0;const d=r.object,f=r.info;for(const p of f){const _=p.getStride(d),g=c.input,T=c.output,E=new Array(g.length);let S=0;switch(c.interpolation){case"STEP":{for(let v=0;v0){const v=`${i.name||`animation${i.index}`}_channel${s.index}_${u}`;p.buildAnimations(d,v,o,E,(y,A)=>{++u,n(y,A)})}}})}_loadAnimationSamplerAsync(e,t){if(t._data)return t._data;const i=t.interpolation||"LINEAR";switch(i){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(`${e}/interpolation: Invalid value (${t.interpolation})`)}const s=et.Get(`${e}/input`,this._gltf.accessors,t.input),r=et.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${s.index}`,s),this._loadFloatAccessorAsync(`/accessors/${r.index}`,r)]).then(([n,o])=>({input:n,interpolation:i,output:o})),t._data}loadBufferAsync(e,t,i,s){const r=this._extensionsLoadBufferAsync(e,t,i,s);if(r)return r;if(!t._data)if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);t._data=this._bin.readAsync(0,t.byteLength)}return t._data.then(n=>{try{return new Uint8Array(n.buffer,n.byteOffset+i,s)}catch(o){throw new Error(`${e}: ${o.message}`)}})}loadBufferViewAsync(e,t){const i=this._extensionsLoadBufferViewAsync(e,t);if(i)return i;if(t._data)return t._data;const s=et.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${s.index}`,s,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,t,i){if(t._data)return t._data;const s=Ie._GetNumComponents(e,t.type),r=s*C.GetTypeByteLength(t.componentType),n=s*t.count;if(t.bufferView==null)t._data=Promise.resolve(new i(n));else{const o=et.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${o.index}`,o).then(l=>{if(t.componentType===5126&&!t.normalized&&(!o.byteStride||o.byteStride===r))return Ie._GetTypedArray(e,t.componentType,l,t.byteOffset,n);{const h=new i(n);return C.ForEach(l,t.byteOffset||0,o.byteStride||r,s,t.componentType,h.length,t.normalized||!1,(c,u)=>{h[u]=c}),h}})}if(t.sparse){const o=t.sparse;t._data=t._data.then(l=>{const h=l,c=et.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,o.indices.bufferView),u=et.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,o.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${c.index}`,c),this.loadBufferViewAsync(`/bufferViews/${u.index}`,u)]).then(([d,f])=>{const p=Ie._GetTypedArray(`${e}/sparse/indices`,o.indices.componentType,d,o.indices.byteOffset,o.count),_=s*o.count;let g;if(t.componentType===5126&&!t.normalized)g=Ie._GetTypedArray(`${e}/sparse/values`,t.componentType,f,o.values.byteOffset,_);else{const E=Ie._GetTypedArray(`${e}/sparse/values`,t.componentType,f,o.values.byteOffset,_);g=new i(_),C.ForEach(E,0,r,s,t.componentType,g.length,t.normalized||!1,(S,v)=>{g[v]=S})}let T=0;for(let E=0;EIe._GetTypedArray(e,t.componentType,s,t.byteOffset,t.count))}return t._data}_loadVertexBufferViewAsync(e){if(e._babylonBuffer)return e._babylonBuffer;const t=this._babylonScene.getEngine();return e._babylonBuffer=this.loadBufferViewAsync(`/bufferViews/${e.index}`,e).then(i=>new cs(t,i,!1)),e._babylonBuffer}_loadVertexAccessorAsync(e,t,i){var r;if((r=t._babylonVertexBuffer)!=null&&r[i])return t._babylonVertexBuffer[i];t._babylonVertexBuffer||(t._babylonVertexBuffer={});const s=this._babylonScene.getEngine();if(t.sparse||t.bufferView==null)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then(n=>new C(s,n,i,!1));else{const n=et.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[i]=this._loadVertexBufferViewAsync(n).then(o=>{const l=Ie._GetNumComponents(e,t.type);return new C(s,o,i,!1,void 0,n.byteStride,void 0,t.byteOffset,l,t.componentType,t.normalized,!0,void 0,!0)})}return t._babylonVertexBuffer[i]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const s=new Array;return t&&(t.baseColorFactor?(i.albedoColor=K.FromArray(t.baseColorFactor),i.alpha=t.baseColorFactor[3]):i.albedoColor=K.White(),i.metallic=t.metallicFactor==null?1:t.metallicFactor,i.roughness=t.roughnessFactor==null?1:t.roughnessFactor,t.baseColorTexture&&s.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,t.baseColorTexture,r=>{r.name=`${i.name} (Base Color)`,i.albedoTexture=r})),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,t.metallicRoughnessTexture,r=>{r.name=`${i.name} (Metallic Roughness)`,i.metallicTexture=r})),i.useMetallnessFromMetallicTextureBlue=!0,i.useRoughnessFromMetallicTextureGreen=!0,i.useRoughnessFromMetallicTextureAlpha=!1)),Promise.all(s).then(()=>{})}_loadMaterialAsync(e,t,i,s,r=()=>{}){const n=this._extensionsLoadMaterialAsync(e,t,i,s,r);if(n)return n;t._data=t._data||{};let o=t._data[s];if(!o){this.logOpen(`${e} ${t.name||""}`);const l=this.createMaterial(e,t,s);o={babylonMaterial:l,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,l)},t._data[s]=o,Ie.AddPointerMetadata(l,e),this._parent.onMaterialLoadedObservable.notifyObservers(l),this.logClose()}return i&&(o.babylonMeshes.push(i),i.onDisposeObservable.addOnce(()=>{const l=o.babylonMeshes.indexOf(i);l!==-1&&o.babylonMeshes.splice(l,1)})),r(o.babylonMaterial),o.promise.then(()=>o.babylonMaterial)}_createDefaultMaterial(e,t){this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new Ae(e,this._babylonScene);return i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,i.fillMode=t,i.enableSpecularAntiAliasing=!0,i.useRadianceOverAlpha=!this._parent.transparencyAsCoverage,i.useSpecularOverAlpha=!this._parent.transparencyAsCoverage,i.transparencyMode=Ae.PBRMATERIAL_OPAQUE,i.metallic=1,i.roughness=1,i}createMaterial(e,t,i){const s=this._extensionsCreateMaterial(e,t,i);if(s)return s;const r=t.name||`material${t.index}`;return this._createDefaultMaterial(r,i)}loadMaterialPropertiesAsync(e,t,i){const s=this._extensionsLoadMaterialPropertiesAsync(e,t,i);if(s)return s;const r=new Array;return r.push(this.loadMaterialBasePropertiesAsync(e,t,i)),t.pbrMetallicRoughness&&r.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,i)),this.loadMaterialAlphaProperties(e,t,i),Promise.all(r).then(()=>{})}loadMaterialBasePropertiesAsync(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.emissiveColor=t.emissiveFactor?K.FromArray(t.emissiveFactor):new K(0,0,0),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),t.normalTexture&&(t.normalTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/normalTexture`,t.normalTexture,r=>{r.name=`${i.name} (Normal)`,i.bumpTexture=r})),i.invertNormalMapX=!this._babylonScene.useRightHandedSystem,i.invertNormalMapY=this._babylonScene.useRightHandedSystem,t.normalTexture.scale!=null&&i.bumpTexture&&(i.bumpTexture.level=t.normalTexture.scale),i.forceIrradianceInFragment=!0),t.occlusionTexture&&(t.occlusionTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,t.occlusionTexture,r=>{r.name=`${i.name} (Occlusion)`,i.ambientTexture=r})),i.useAmbientInGrayScale=!0,t.occlusionTexture.strength!=null&&(i.ambientTextureStrength=t.occlusionTexture.strength)),t.emissiveTexture&&s.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,t.emissiveTexture,r=>{r.name=`${i.name} (Emissive)`,i.emissiveTexture=r})),Promise.all(s).then(()=>{})}loadMaterialAlphaProperties(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);switch(t.alphaMode||"OPAQUE"){case"OPAQUE":{i.transparencyMode=Ae.PBRMATERIAL_OPAQUE,i.alpha=1;break}case"MASK":{i.transparencyMode=Ae.PBRMATERIAL_ALPHATEST,i.alphaCutOff=t.alphaCutoff==null?.5:t.alphaCutoff,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0);break}case"BLEND":{i.transparencyMode=Ae.PBRMATERIAL_ALPHABLEND,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0,i.useAlphaFromAlbedoTexture=!0);break}default:throw new Error(`${e}/alphaMode: Invalid value (${t.alphaMode})`)}}loadTextureInfoAsync(e,t,i=()=>{}){const s=this._extensionsLoadTextureInfoAsync(e,t,i);if(s)return s;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const r=et.Get(`${e}/index`,this._gltf.textures,t.index);r._textureInfo=t;const n=this._loadTextureAsync(`/textures/${t.index}`,r,o=>{o.coordinatesIndex=t.texCoord||0,Ie.AddPointerMetadata(o,e),this._parent.onTextureLoadedObservable.notifyObservers(o),i(o)});return this.logClose(),n}_loadTextureAsync(e,t,i=()=>{}){const s=this._extensionsLoadTextureAsync(e,t,i);if(s)return s;this.logOpen(`${e} ${t.name||""}`);const r=t.sampler==null?Ie.DefaultSampler:et.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),n=et.Get(`${e}/source`,this._gltf.images,t.source),o=this._createTextureAsync(e,r,n,i,void 0,!t._textureInfo.nonColorData);return this.logClose(),o}_createTextureAsync(e,t,i,s=()=>{},r,n){const o=this._loadSampler(`/samplers/${t.index}`,t),l=new Array,h=new tu;this._babylonScene._blockEntityCollection=!!this._assetContainer;const c={noMipmap:o.noMipMaps,invertY:!1,samplingMode:o.samplingMode,onLoad:()=>{this._disposed||h.resolve()},onError:(d,f)=>{this._disposed||h.reject(new Error(`${e}: ${f&&f.message?f.message:d||"Failed to load texture"}`))},mimeType:i.mimeType,loaderOptions:r,useSRGBBuffer:!!n&&this._parent.useSRGBBuffers},u=new k(null,this._babylonScene,c);return u._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,l.push(h.promise),l.push(this.loadImageAsync(`/images/${i.index}`,i).then(d=>{const f=i.uri||`${this._fileName}#image${i.index}`,p=`data:${this._uniqueRootUrl}${f}`;u.updateURL(p,d)})),u.wrapU=o.wrapU,u.wrapV=o.wrapV,s(u),Promise.all(l).then(()=>u)}_loadSampler(e,t){return t._data||(t._data={noMipMaps:t.minFilter===9728||t.minFilter===9729,samplingMode:Ie._GetTextureSamplingMode(e,t),wrapU:Ie._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:Ie._GetTextureWrapMode(`${e}/wrapT`,t.wrapT)}),t._data}loadImageAsync(e,t){if(!t._data){if(this.logOpen(`${e} ${t.name||""}`),t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{const i=et.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${i.index}`,i)}this.logClose()}return t._data}loadUriAsync(e,t,i){const s=this._extensionsLoadUriAsync(e,t,i);if(s)return s;if(!Ie._ValidateUri(i))throw new Error(`${e}: '${i}' is invalid`);if(Df(i)){const r=new Uint8Array(td(i));return this.log(`${e}: Decoded ${i.substr(0,64)}... (${r.length} bytes)`),Promise.resolve(r)}return this.log(`${e}: Loading ${i}`),this._parent.preprocessUrlAsync(this._rootUrl+i).then(r=>new Promise((n,o)=>{this._parent._loadFile(this._babylonScene,r,l=>{this._disposed||(this.log(`${e}: Loaded ${i} (${l.byteLength} bytes)`),n(new Uint8Array(l)))},!0,l=>{o(new Iu(`${e}: Failed to load '${i}'${l?": "+l.status+" "+l.statusText:""}`,l))})}))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};const i=e._internalMetadata=e._internalMetadata||{},s=i.gltf=i.gltf||{};(s.pointers=s.pointers||[]).push(t)}static _GetTextureWrapMode(e,t){switch(t=t??10497,t){case 33071:return k.CLAMP_ADDRESSMODE;case 33648:return k.MIRROR_ADDRESSMODE;case 10497:return k.WRAP_ADDRESSMODE;default:return N.Warn(`${e}: Invalid value (${t})`),k.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,t){const i=t.magFilter==null?9729:t.magFilter,s=t.minFilter==null?9987:t.minFilter;if(i===9729)switch(s){case 9728:return k.LINEAR_NEAREST;case 9729:return k.LINEAR_LINEAR;case 9984:return k.LINEAR_NEAREST_MIPNEAREST;case 9985:return k.LINEAR_LINEAR_MIPNEAREST;case 9986:return k.LINEAR_NEAREST_MIPLINEAR;case 9987:return k.LINEAR_LINEAR_MIPLINEAR;default:return N.Warn(`${e}/minFilter: Invalid value (${s})`),k.LINEAR_LINEAR_MIPLINEAR}else switch(i!==9728&&N.Warn(`${e}/magFilter: Invalid value (${i})`),s){case 9728:return k.NEAREST_NEAREST;case 9729:return k.NEAREST_LINEAR;case 9984:return k.NEAREST_NEAREST_MIPNEAREST;case 9985:return k.NEAREST_LINEAR_MIPNEAREST;case 9986:return k.NEAREST_NEAREST_MIPLINEAR;case 9987:return k.NEAREST_LINEAR_MIPLINEAR;default:return N.Warn(`${e}/minFilter: Invalid value (${s})`),k.NEAREST_NEAREST_MIPNEAREST}}static _GetTypedArrayConstructor(e,t){switch(t){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:throw new Error(`${e}: Invalid component type ${t}`)}}static _GetTypedArray(e,t,i,s,r){const n=i.buffer;s=i.byteOffset+(s||0);const o=Ie._GetTypedArrayConstructor(`${e}/componentType`,t),l=C.GetTypeByteLength(t);return s%l!==0?(N.Warn(`${e}: Copying buffer as byte offset (${s}) is not a multiple of component type byte length (${l})`),new o(n.slice(s,s+r*l),0)):new o(n,s,r)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":return 4;case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return X.IsBase64(e)||e.indexOf("..")===-1}static _GetDrawMode(e,t){switch(t==null&&(t=4),t){case 0:return ee.PointListDrawMode;case 1:return ee.LineListDrawMode;case 2:return ee.LineLoopDrawMode;case 3:return ee.LineStripDrawMode;case 4:return ee.TriangleFillMode;case 5:return ee.TriangleStripDrawMode;case 6:return ee.TriangleFanDrawMode}throw new Error(`${e}: Invalid mesh primitive mode (${t})`)}_compileMaterialsAsync(){this._parent._startPerformanceCounter("Compile materials");const e=new Array;if(this._gltf.materials){for(const t of this._gltf.materials)if(t._data)for(const i in t._data){const s=t._data[i];for(const r of s.babylonMeshes){r.computeWorldMatrix(!0);const n=s.babylonMaterial;e.push(n.forceCompilationAsync(r)),e.push(n.forceCompilationAsync(r,{useInstances:!0})),this._parent.useClipPlane&&(e.push(n.forceCompilationAsync(r,{clipPlane:!0})),e.push(n.forceCompilationAsync(r,{clipPlane:!0,useInstances:!0})))}}}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile materials")})}_compileShadowGeneratorsAsync(){this._parent._startPerformanceCounter("Compile shadow generators");const e=new Array,t=this._babylonScene.lights;for(const i of t){const s=i.getShadowGenerator();s&&e.push(s.forceCompilationAsync())}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile shadow generators")})}_forEachExtensions(e){for(const t of this._extensions)t.enabled&&e(t)}_applyExtensions(e,t,i){for(const s of this._extensions)if(s.enabled){const r=`${s.name}.${t}`,n=e;n._activeLoaderExtensionFunctions=n._activeLoaderExtensionFunctions||{};const o=n._activeLoaderExtensionFunctions;if(!o[r]){o[r]=!0;try{const l=i(s);if(l)return l}finally{delete o[r]}}}return null}_extensionsOnLoading(){this._forEachExtensions(e=>e.onLoading&&e.onLoading())}_extensionsOnReady(){this._forEachExtensions(e=>e.onReady&&e.onReady())}_extensionsLoadSceneAsync(e,t){return this._applyExtensions(t,"loadScene",i=>i.loadSceneAsync&&i.loadSceneAsync(e,t))}_extensionsLoadNodeAsync(e,t,i){return this._applyExtensions(t,"loadNode",s=>s.loadNodeAsync&&s.loadNodeAsync(e,t,i))}_extensionsLoadCameraAsync(e,t,i){return this._applyExtensions(t,"loadCamera",s=>s.loadCameraAsync&&s.loadCameraAsync(e,t,i))}_extensionsLoadVertexDataAsync(e,t,i){return this._applyExtensions(t,"loadVertexData",s=>s._loadVertexDataAsync&&s._loadVertexDataAsync(e,t,i))}_extensionsLoadMeshPrimitiveAsync(e,t,i,s,r,n){return this._applyExtensions(r,"loadMeshPrimitive",o=>o._loadMeshPrimitiveAsync&&o._loadMeshPrimitiveAsync(e,t,i,s,r,n))}_extensionsLoadMaterialAsync(e,t,i,s,r){return this._applyExtensions(t,"loadMaterial",n=>n._loadMaterialAsync&&n._loadMaterialAsync(e,t,i,s,r))}_extensionsCreateMaterial(e,t,i){return this._applyExtensions(t,"createMaterial",s=>s.createMaterial&&s.createMaterial(e,t,i))}_extensionsLoadMaterialPropertiesAsync(e,t,i){return this._applyExtensions(t,"loadMaterialProperties",s=>s.loadMaterialPropertiesAsync&&s.loadMaterialPropertiesAsync(e,t,i))}_extensionsLoadTextureInfoAsync(e,t,i){return this._applyExtensions(t,"loadTextureInfo",s=>s.loadTextureInfoAsync&&s.loadTextureInfoAsync(e,t,i))}_extensionsLoadTextureAsync(e,t,i){return this._applyExtensions(t,"loadTexture",s=>s._loadTextureAsync&&s._loadTextureAsync(e,t,i))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",i=>i.loadAnimationAsync&&i.loadAnimationAsync(e,t))}_extensionsLoadAnimationChannelAsync(e,t,i,s,r){return this._applyExtensions(i,"loadAnimationChannel",n=>n._loadAnimationChannelAsync&&n._loadAnimationChannelAsync(e,t,i,s,r))}_extensionsLoadSkinAsync(e,t,i){return this._applyExtensions(i,"loadSkin",s=>s._loadSkinAsync&&s._loadSkinAsync(e,t,i))}_extensionsLoadUriAsync(e,t,i){return this._applyExtensions(t,"loadUri",s=>s._loadUriAsync&&s._loadUriAsync(e,t,i))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",i=>i.loadBufferViewAsync&&i.loadBufferViewAsync(e,t))}_extensionsLoadBufferAsync(e,t,i,s){return this._applyExtensions(t,"loadBuffer",r=>r.loadBufferAsync&&r.loadBufferAsync(e,t,i,s))}static LoadExtensionAsync(e,t,i,s){if(!t.extensions)return null;const n=t.extensions[i];return n?s(`${e}/extensions/${i}`,n):null}static LoadExtraAsync(e,t,i,s){if(!t.extras)return null;const n=t.extras[i];return n?s(`${e}/extras/${i}`,n):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&this._gltf.extensionsUsed.indexOf(e)!==-1}logOpen(e){this._parent._logOpen(e)}logClose(){this._parent._logClose()}log(e){this._parent._log(e)}startPerformanceCounter(e){this._parent._startPerformanceCounter(e)}endPerformanceCounter(e){this._parent._endPerformanceCounter(e)}}Ie._RegisteredExtensions={};Ie.DefaultSampler={index:-1};bi._CreateGLTF2Loader=a=>new Ie(a);const H_="EXT_lights_image_based";class ok{constructor(e){this.name=H_,this._loader=e,this.enabled=this._loader.isExtensionUsed(H_)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights}}loadSceneAsync(e,t){return Ie.LoadExtensionAsync(e,t,this.name,(i,s)=>{this._loader._allMaterialsDirtyRequired=!0;const r=new Array;r.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${i}`);const n=et.Get(`${i}/light`,this._lights,s.light);return r.push(this._loadLightAsync(`/extensions/${this.name}/lights/${s.light}`,n).then(o=>{this._loader.babylonScene.environmentTexture=o})),this._loader.logClose(),Promise.all(r).then(()=>{})})}_loadLightAsync(e,t){if(!t._loaded){const i=new Array;this._loader.logOpen(`${e}`);const s=new Array(t.specularImages.length);for(let r=0;r{s[r][o]=u})),this._loader.logClose()}}this._loader.logClose(),t._loaded=Promise.all(i).then(()=>{const r=new Dg(this._loader.babylonScene,null,t.specularImageSize);if(r.name=t.name||"environment",t._babylonTexture=r,t.intensity!=null&&(r.level=t.intensity),t.rotation){let h=Z.FromArray(t.rotation);this._loader.babylonScene.useRightHandedSystem||(h=Z.Inverse(h)),D.FromQuaternionToRef(h,r.getReflectionTextureMatrix())}if(!t.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const n=tl.FromArray(t.irradianceCoefficients);n.scaleInPlace(t.intensity),n.convertIrradianceToLambertianRadiance();const o=_a.FromHarmonics(n),l=(s.length-1)/Ee.Log2(t.specularImageSize);return r.updateRGBDAsync(s,o,l)})}return t._loaded.then(()=>t._babylonTexture)}}Ie.RegisterExtension(H_,a=>new ok(a));const X_="EXT_mesh_gpu_instancing";class lk{constructor(e){this.name=X_,this._loader=e,this.enabled=this._loader.isExtensionUsed(X_)}dispose(){this._loader=null}loadNodeAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{this._loader._disableInstancedMesh++;const n=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,i);if(this._loader._disableInstancedMesh--,!t._primitiveBabylonMeshes)return n;const o=new Array;let l=0;const h=c=>{if(r.attributes[c]==null){o.push(Promise.resolve(null));return}const u=et.Get(`${s}/attributes/${c}`,this._loader.gltf.accessors,r.attributes[c]);if(o.push(this._loader._loadFloatAccessorAsync(`/accessors/${u.bufferView}`,u)),l===0)l=u.count;else if(l!==u.count)throw new Error(`${s}/attributes: Instance buffer accessors do not have the same count.`)};return h("TRANSLATION"),h("ROTATION"),h("SCALE"),n.then(c=>Promise.all(o).then(([u,d,f])=>{const p=new Float32Array(l*16);V.Vector3[0].copyFromFloats(0,0,0),V.Quaternion[0].copyFromFloats(0,0,0,1),V.Vector3[1].copyFromFloats(1,1,1);for(let _=0;_new lk(a));const Y_="EXT_meshopt_compression";class hk{constructor(e){this.name=Y_,this.enabled=e.isExtensionUsed(Y_),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,t){return Ie.LoadExtensionAsync(e,t,this.name,(i,s)=>{const r=t;if(r._meshOptData)return r._meshOptData;const n=et.Get(`${e}/buffer`,this._loader.gltf.buffers,s.buffer);return r._meshOptData=this._loader.loadBufferAsync(`/buffers/${n.index}`,n,s.byteOffset||0,s.byteLength).then(o=>Ia.Default.decodeGltfBufferAsync(o,s.count,s.byteStride,s.mode,s.filter)),r._meshOptData})}}Ie.RegisterExtension(Y_,a=>new hk(a));const $_="EXT_texture_webp";class ck{constructor(e){this.name=$_,this._loader=e,this.enabled=e.isExtensionUsed($_)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=t.sampler==null?Ie.DefaultSampler:et.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=et.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,l=>{i(l)},void 0,!t._textureInfo.nonColorData)})}}Ie.RegisterExtension($_,a=>new ck(a));const j_="EXT_texture_avif";class uk{constructor(e){this.name=j_,this._loader=e,this.enabled=e.isExtensionUsed(j_)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=t.sampler==null?Ie.DefaultSampler:et.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=et.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,l=>{i(l)},void 0,!t._textureInfo.nonColorData)})}}Ie.RegisterExtension(j_,a=>new uk(a));const K_="KHR_draco_mesh_compression";class dk{constructor(e){this.name=K_,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=ir.DecoderAvailable&&this._loader.isExtensionUsed(K_)}dispose(){delete this.dracoCompression,this._loader=null}_loadVertexDataAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{if(t.mode!=null&&t.mode!==4&&t.mode!==5)throw new Error(`${e}: Unsupported mode ${t.mode}`);const n={},o={},l=(c,u)=>{const d=r.attributes[c];if(d!=null&&(i._delayInfo=i._delayInfo||[],i._delayInfo.indexOf(u)===-1&&i._delayInfo.push(u),n[u]=d,this.useNormalizedFlagFromAccessor)){const f=et.TryGet(this._loader.gltf.accessors,t.attributes[c]);f&&(o[u]=f.normalized||!1)}};l("POSITION",C.PositionKind),l("NORMAL",C.NormalKind),l("TANGENT",C.TangentKind),l("TEXCOORD_0",C.UVKind),l("TEXCOORD_1",C.UV2Kind),l("TEXCOORD_2",C.UV3Kind),l("TEXCOORD_3",C.UV4Kind),l("TEXCOORD_4",C.UV5Kind),l("TEXCOORD_5",C.UV6Kind),l("JOINTS_0",C.MatricesIndicesKind),l("WEIGHTS_0",C.MatricesWeightsKind),l("COLOR_0",C.ColorKind);const h=et.Get(s,this._loader.gltf.bufferViews,r.bufferView);return h._dracoBabylonGeometry||(h._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${h.index}`,h).then(c=>(this.dracoCompression||ir.Default)._decodeMeshToGeometryForGltfAsync(i.name,this._loader.babylonScene,c,n,o).catch(d=>{throw new Error(`${e}: ${d.message}`)}))),h._dracoBabylonGeometry})}}Ie.RegisterExtension(K_,a=>new dk(a));const q_="KHR_lights_punctual";class fk{constructor(e){this.name=q_,this._loader=e,this.enabled=this._loader.isExtensionUsed(q_)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,et.Assign(this._lights)}}loadNodeAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>(this._loader._allMaterialsDirtyRequired=!0,this._loader.loadNodeAsync(e,t,n=>{let o;const l=et.Get(s,this._lights,r.light),h=l.name||n.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,l.type){case"directional":{const c=new en(h,m.Backward(),this._loader.babylonScene);c.position.setAll(0),o=c;break}case"point":{o=new Mo(h,m.Zero(),this._loader.babylonScene);break}case"spot":{const c=new ar(h,m.Zero(),m.Backward(),0,1,this._loader.babylonScene);c.angle=(l.spot&&l.spot.outerConeAngle||Math.PI/4)*2,c.innerAngle=(l.spot&&l.spot.innerConeAngle||0)*2,o=c;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${s}: Invalid light type (${l.type})`)}o._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,l._babylonLight=o,o.falloffType=lt.FALLOFF_GLTF,o.diffuse=l.color?K.FromArray(l.color):K.White(),o.intensity=l.intensity==null?1:l.intensity,o.range=l.range==null?Number.MAX_VALUE:l.range,o.parent=n,this._loader._babylonLights.push(o),Ie.AddPointerMetadata(o,s),i(n)})))}}Ie.RegisterExtension(q_,a=>new fk(a));const Z_="KHR_materials_pbrSpecularGlossiness";class pk{constructor(e){this.name=Z_,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(Z_)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loadSpecularGlossinessPropertiesAsync(s,r,i)),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(n).then(()=>{})})}_loadSpecularGlossinessPropertiesAsync(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.metallic=null,i.roughness=null,t.diffuseFactor?(i.albedoColor=K.FromArray(t.diffuseFactor),i.alpha=t.diffuseFactor[3]):i.albedoColor=K.White(),i.reflectivityColor=t.specularFactor?K.FromArray(t.specularFactor):K.White(),i.microSurface=t.glossinessFactor==null?1:t.glossinessFactor,t.diffuseTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,t.diffuseTexture,r=>{r.name=`${i.name} (Diffuse)`,i.albedoTexture=r})),t.specularGlossinessTexture&&(s.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,t.specularGlossinessTexture,r=>{r.name=`${i.name} (Specular Glossiness)`,i.reflectivityTexture=r,i.reflectivityTexture.hasAlpha=!0})),i.useMicroSurfaceFromReflectivityMapAlpha=!0),Promise.all(s).then(()=>{})}}Ie.RegisterExtension(Z_,a=>new pk(a));const Q_="KHR_materials_unlit";class _k{constructor(e){this.name=Q_,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(Q_)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,()=>this._loadUnlitPropertiesAsync(e,t,i))}_loadUnlitPropertiesAsync(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const s=new Array;i.unlit=!0;const r=t.pbrMetallicRoughness;return r&&(r.baseColorFactor?(i.albedoColor=K.FromArray(r.baseColorFactor),i.alpha=r.baseColorFactor[3]):i.albedoColor=K.White(),r.baseColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,r.baseColorTexture,n=>{n.name=`${i.name} (Base Color)`,i.albedoTexture=n}))),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(s).then(()=>{})}}Ie.RegisterExtension(Q_,a=>new _k(a));const J_="KHR_materials_clearcoat";class mk{constructor(e){this.name=J_,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(J_)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadClearCoatPropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadClearCoatPropertiesAsync(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.clearCoat.isEnabled=!0,i.clearCoat.useRoughnessFromMainTexture=!1,i.clearCoat.remapF0OnInterfaceChange=!1,t.clearcoatFactor!=null?i.clearCoat.intensity=t.clearcoatFactor:i.clearCoat.intensity=0,t.clearcoatTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,r=>{r.name=`${i.name} (ClearCoat Intensity)`,i.clearCoat.texture=r})),t.clearcoatRoughnessFactor!=null?i.clearCoat.roughness=t.clearcoatRoughnessFactor:i.clearCoat.roughness=0,t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatRoughnessTexture`,t.clearcoatRoughnessTexture,r=>{r.name=`${i.name} (ClearCoat Roughness)`,i.clearCoat.textureRoughness=r}))),t.clearcoatNormalTexture&&(t.clearcoatNormalTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatNormalTexture`,t.clearcoatNormalTexture,r=>{r.name=`${i.name} (ClearCoat Normal)`,i.clearCoat.bumpTexture=r})),i.invertNormalMapX=!i.getScene().useRightHandedSystem,i.invertNormalMapY=i.getScene().useRightHandedSystem,t.clearcoatNormalTexture.scale!=null&&(i.clearCoat.bumpTexture.level=t.clearcoatNormalTexture.scale)),Promise.all(s).then(()=>{})}}Ie.RegisterExtension(J_,a=>new mk(a));const em="KHR_materials_iridescence";class gk{constructor(e){this.name=em,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(em)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIridescencePropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.iridescence.isEnabled=!0,i.iridescence.intensity=t.iridescenceFactor??0,i.iridescence.indexOfRefraction=t.iridescenceIor??t.iridescenceIOR??1.3,i.iridescence.minimumThickness=t.iridescenceThicknessMinimum??100,i.iridescence.maximumThickness=t.iridescenceThicknessMaximum??400,t.iridescenceTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,r=>{r.name=`${i.name} (Iridescence Intensity)`,i.iridescence.texture=r})),t.iridescenceThicknessTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,r=>{r.name=`${i.name} (Iridescence Thickness)`,i.iridescence.thicknessTexture=r})),Promise.all(s).then(()=>{})}}Ie.RegisterExtension(em,a=>new gk(a));const tm="KHR_materials_anisotropy";class xk{constructor(e){this.name=tm,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(tm)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIridescencePropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.anisotropy.isEnabled=!0,i.anisotropy.intensity=t.anisotropyStrength??0,i.anisotropy.angle=t.anisotropyRotation??0,t.anisotropyTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,r=>{r.name=`${i.name} (Anisotropy Intensity)`,i.anisotropy.texture=r})),Promise.all(s).then(()=>{})}}Ie.RegisterExtension(tm,a=>new xk(a));const im="KHR_materials_emissive_strength";class Tk{constructor(e){this.name=im,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(im)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>this._loader.loadMaterialPropertiesAsync(e,t,i).then(()=>{this._loadEmissiveProperties(s,r,i)}))}_loadEmissiveProperties(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);t.emissiveStrength!==void 0&&(i.emissiveIntensity=t.emissiveStrength)}}Ie.RegisterExtension(im,a=>new Tk(a));const sm="KHR_materials_sheen";class Ek{constructor(e){this.name=sm,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(sm)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadSheenPropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadSheenPropertiesAsync(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.sheen.isEnabled=!0,i.sheen.intensity=1,t.sheenColorFactor!=null?i.sheen.color=K.FromArray(t.sheenColorFactor):i.sheen.color=K.Black(),t.sheenColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/sheenColorTexture`,t.sheenColorTexture,r=>{r.name=`${i.name} (Sheen Color)`,i.sheen.texture=r})),t.sheenRoughnessFactor!==void 0?i.sheen.roughness=t.sheenRoughnessFactor:i.sheen.roughness=0,t.sheenRoughnessTexture&&(t.sheenRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/sheenRoughnessTexture`,t.sheenRoughnessTexture,r=>{r.name=`${i.name} (Sheen Roughness)`,i.sheen.textureRoughness=r}))),i.sheen.albedoScaling=!0,i.sheen.useRoughnessFromMainTexture=!1,Promise.all(s).then(()=>{})}}Ie.RegisterExtension(sm,a=>new Ek(a));const rm="KHR_materials_specular";class Sk{constructor(e){this.name=rm,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(rm)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadSpecularPropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadSpecularPropertiesAsync(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const s=new Array;return t.specularFactor!==void 0&&(i.metallicF0Factor=t.specularFactor),t.specularColorFactor!==void 0&&(i.metallicReflectanceColor=K.FromArray(t.specularColorFactor)),t.specularTexture&&(t.specularTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,t.specularTexture,r=>{r.name=`${i.name} (Specular F0 Strength)`,i.metallicReflectanceTexture=r,i.useOnlyMetallicFromMetallicReflectanceTexture=!0}))),t.specularColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,t.specularColorTexture,r=>{r.name=`${i.name} (Specular F0 Color)`,i.reflectanceTexture=r})),Promise.all(s).then(()=>{})}}Ie.RegisterExtension(rm,a=>new Sk(a));const nm="KHR_materials_ior";class Ip{constructor(e){this.name=nm,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(nm)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIorPropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadIorPropertiesAsync(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);return t.ior!==void 0?i.indexOfRefraction=t.ior:i.indexOfRefraction=Ip._DEFAULT_IOR,Promise.resolve()}}Ip._DEFAULT_IOR=1.5;Ie.RegisterExtension(nm,a=>new Ip(a));const yr="KHR_materials_variants";class to{constructor(e){this.name=yr,this._loader=e,this.enabled=this._loader.isExtensionUsed(yr)}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return to.GetAvailableVariants(e)}static SelectVariant(e,t){const i=this._GetExtensionMetadata(e);if(!i)throw new Error(`Cannot select variant on a glTF mesh that does not have the ${yr} extension`);const s=r=>{const n=i.variants[r];if(n)for(const o of n)o.mesh.material=o.material};if(t instanceof Array)for(const r of t)s(r);else s(t);i.lastSelected=t}selectVariant(e,t){to.SelectVariant(e,t)}static Reset(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot reset on a glTF mesh that does not have the ${yr} extension`);for(const i of t.original)i.mesh.material=i.material;t.lastSelected=null}reset(e){to.Reset(e)}static GetLastSelectedVariant(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot get the last selected variant on a glTF mesh that does not have the ${yr} extension`);return t.lastSelected}getLastSelectedVariant(e){return to.GetLastSelectedVariant(e)}static _GetExtensionMetadata(e){var t,i;return((i=(t=e==null?void 0:e._internalMetadata)==null?void 0:t.gltf)==null?void 0:i[yr])||null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._variants=t.variants}}_loadMeshPrimitiveAsync(e,t,i,s,r,n){return Ie.LoadExtensionAsync(e,r,this.name,(o,l)=>{const h=new Array;return h.push(this._loader._loadMeshPrimitiveAsync(e,t,i,s,r,c=>{if(n(c),c instanceof W){const u=Ie._GetDrawMode(e,r.mode),d=this._loader.rootBabylonMesh,f=d?d._internalMetadata=d._internalMetadata||{}:{},p=f.gltf=f.gltf||{},_=p[yr]=p[yr]||{lastSelected:null,original:[],variants:{}};_.original.push({mesh:c,material:c.material});for(let g=0;g{for(let v=0;v{const P=R;let L=null,O=P;do{if(O=O.parent,!O)return;L=to._GetExtensionMetadata(O)}while(L===null);if(d&&L===to._GetExtensionMetadata(d)){O._internalMetadata={};for(const Y in d._internalMetadata)O._internalMetadata[Y]=d._internalMetadata[Y];O._internalMetadata.gltf=[];for(const Y in d._internalMetadata.gltf)O._internalMetadata.gltf[Y]=d._internalMetadata.gltf[Y];O._internalMetadata.gltf[yr]={lastSelected:null,original:[],variants:{}};for(const Y of L.original)O._internalMetadata.gltf[yr].original.push({mesh:Y.mesh,material:Y.material});for(const Y in L.variants)if(Object.prototype.hasOwnProperty.call(L.variants,Y)){O._internalMetadata.gltf[yr].variants[Y]=[];for(const te of L.variants[Y])O._internalMetadata.gltf[yr].variants[Y].push({mesh:te.mesh,material:te.material})}L=O._internalMetadata.gltf[yr]}for(const Y of L.original)Y.mesh===c&&(Y.mesh=P);for(const Y of L.variants[A.name])Y.mesh===c&&(Y.mesh=P)})}}))}}})),Promise.all(h).then(([c])=>c)})}}Ie.RegisterExtension(yr,a=>new to(a));class Jg{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:H.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,t){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._options={...Jg._GetDefaultOptions(),...e},this._scene=t,this._scene._transmissionHelper=this,this.onErrorObservable=new z,this._scene.onDisposeObservable.addOnce(()=>{this.dispose()}),this._parseScene(),this._setupRenderTargets()}updateOptions(e){if(!Object.keys(e).filter(r=>this._options[r]!==e[r]).length)return;const i={...this._options,...e},s=this._options;this._options=i,i.renderSize!==s.renderSize||i.renderTargetTextureType!==s.renderTargetTextureType||i.generateMipmaps!==s.generateMipmaps||!this._opaqueRenderTarget?this._setupRenderTargets():(this._opaqueRenderTarget.samples=i.samples,this._opaqueRenderTarget.lodGenerationScale=i.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=i.lodGenerationOffset)}getOpaqueTarget(){return this._opaqueRenderTarget}_shouldRenderAsTransmission(e){return e?!!(e instanceof Ae&&e.subSurface.isRefractionEnabled):!1}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),X.SetImmediate(()=>{this._shouldRenderAsTransmission(e.material)?(e.material.refractionTexture=this._opaqueRenderTarget,this._transparentMeshesCache.indexOf(e)===-1&&this._transparentMeshesCache.push(e)):this._opaqueMeshesCache.indexOf(e)===-1&&this._opaqueMeshesCache.push(e)})}_removeMesh(e){e.onMaterialChangedObservable.remove(this._materialObservers[e.uniqueId]),delete this._materialObservers[e.uniqueId];let t=this._transparentMeshesCache.indexOf(e);t!==-1&&this._transparentMeshesCache.splice(t,1),t=this._opaqueMeshesCache.indexOf(e),t!==-1&&this._opaqueMeshesCache.splice(t,1)}_parseScene(){this._scene.meshes.forEach(this._addMesh.bind(this)),this._scene.onNewMeshAddedObservable.add(this._addMesh.bind(this)),this._scene.onMeshRemovedObservable.add(this._removeMesh.bind(this))}_onMeshMaterialChanged(e){const t=this._transparentMeshesCache.indexOf(e),i=this._opaqueMeshesCache.indexOf(e);this._shouldRenderAsTransmission(e.material)?(e.material instanceof Ae&&(e.material.subSurface.refractionTexture=this._opaqueRenderTarget),i!==-1?(this._opaqueMeshesCache.splice(i,1),this._transparentMeshesCache.push(e)):t===-1&&this._transparentMeshesCache.push(e)):t!==-1?(this._transparentMeshesCache.splice(t,1),this._opaqueMeshesCache.push(e)):i===-1&&this._opaqueMeshesCache.push(e)}_isRenderTargetValid(){var e;return((e=this._opaqueRenderTarget)==null?void 0:e.getInternalTexture())!==null}_setupRenderTargets(){var i;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new ai("opaqueSceneTexture",this._options.renderSize,this._scene,this._options.generateMipmaps,void 0,this._options.renderTargetTextureType),this._opaqueRenderTarget.ignoreCameraViewport=!0,this._opaqueRenderTarget.renderList=this._opaqueMeshesCache,this._opaqueRenderTarget.clearColor=((i=this._options.clearColor)==null?void 0:i.clone())??this._scene.clearColor.clone(),this._opaqueRenderTarget.gammaSpace=!1,this._opaqueRenderTarget.lodGenerationScale=this._options.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=this._options.lodGenerationOffset,this._opaqueRenderTarget.samples=this._options.samples,this._opaqueRenderTarget.renderSprites=!0,this._opaqueRenderTarget.renderParticles=!0;let e,t;this._opaqueRenderTarget.onBeforeBindObservable.add(s=>{t=this._scene.environmentIntensity,this._scene.environmentIntensity=1,e=this._scene.imageProcessingConfiguration.applyByPostProcess,this._options.clearColor?s.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(s.clearColor,this._scene.getEngine().useExactSrgbConversions),this._scene.imageProcessingConfiguration._applyByPostProcess=!0}),this._opaqueRenderTarget.onAfterUnbindObservable.add(()=>{this._scene.environmentIntensity=t,this._scene.imageProcessingConfiguration._applyByPostProcess=e}),this._transparentMeshesCache.forEach(s=>{this._shouldRenderAsTransmission(s.material)&&(s.material.refractionTexture=this._opaqueRenderTarget)})}dispose(){this._scene._transmissionHelper=void 0,this._opaqueRenderTarget&&(this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=null),this._transparentMeshesCache=[],this._opaqueMeshesCache=[]}}const am="KHR_materials_transmission";class vk{constructor(e){this.name=am,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(am),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadTransparentPropertiesAsync(s,t,i,r)),Promise.all(n).then(()=>{})})}_loadTransparentPropertiesAsync(e,t,i,s){var n,o;if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const r=i;if(r.subSurface.isRefractionEnabled=!0,r.subSurface.volumeIndexOfRefraction=1,r.subSurface.useAlbedoToTintRefraction=!0,s.transmissionFactor!==void 0){r.subSurface.refractionIntensity=s.transmissionFactor;const l=r.getScene();r.subSurface.refractionIntensity&&!l._transmissionHelper?new Jg({},r.getScene()):r.subSurface.refractionIntensity&&!((n=l._transmissionHelper)!=null&&n._isRenderTargetValid())&&((o=l._transmissionHelper)==null||o._setupRenderTargets())}else return r.subSurface.refractionIntensity=0,r.subSurface.isRefractionEnabled=!1,Promise.resolve();return r.subSurface.minimumThickness=0,r.subSurface.maximumThickness=0,s.transmissionTexture?(s.transmissionTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,s.transmissionTexture,void 0).then(l=>{r.subSurface.refractionIntensityTexture=l,r.subSurface.useGltfStyleTextures=!0})):Promise.resolve()}}Ie.RegisterExtension(am,a=>new vk(a));const om="KHR_materials_diffuse_transmission";class Ck{constructor(e){this.name=om,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(om),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadTranslucentPropertiesAsync(s,t,i,r)),Promise.all(n).then(()=>{})})}_loadTranslucentPropertiesAsync(e,t,i,s){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const r=i;if(r.subSurface.isTranslucencyEnabled=!0,r.subSurface.volumeIndexOfRefraction=1,r.subSurface.minimumThickness=0,r.subSurface.maximumThickness=0,r.subSurface.useAlbedoToTintTranslucency=!1,s.diffuseTransmissionFactor!==void 0)r.subSurface.translucencyIntensity=s.diffuseTransmissionFactor;else return r.subSurface.translucencyIntensity=0,r.subSurface.isTranslucencyEnabled=!1,Promise.resolve();const n=new Array;return r.subSurface.useGltfStyleTextures=!0,s.diffuseTransmissionTexture&&(s.diffuseTransmissionTexture.nonColorData=!0,n.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionTexture`,s.diffuseTransmissionTexture).then(o=>{r.subSurface.translucencyIntensityTexture=o}))),s.diffuseTransmissionColorFactor!==void 0?r.subSurface.translucencyColor=K.FromArray(s.diffuseTransmissionColorFactor):r.subSurface.translucencyColor=K.White(),s.diffuseTransmissionColorTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionColorTexture`,s.diffuseTransmissionColorTexture).then(o=>{r.subSurface.translucencyColorTexture=o})),Promise.all(n).then(()=>{})}}Ie.RegisterExtension(om,a=>new Ck(a));const lm="KHR_materials_volume";class bk{constructor(e){this.name=lm,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(lm),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadVolumePropertiesAsync(s,t,i,r)),Promise.all(n).then(()=>{})})}_loadVolumePropertiesAsync(e,t,i,s){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);if(!i.subSurface.isRefractionEnabled&&!i.subSurface.isTranslucencyEnabled||!s.thicknessFactor)return Promise.resolve();i.subSurface.volumeIndexOfRefraction=i.indexOfRefraction;const r=s.attenuationDistance!==void 0?s.attenuationDistance:Number.MAX_VALUE;return i.subSurface.tintColorAtDistance=r,s.attenuationColor!==void 0&&s.attenuationColor.length==3&&i.subSurface.tintColor.copyFromFloats(s.attenuationColor[0],s.attenuationColor[1],s.attenuationColor[2]),i.subSurface.minimumThickness=0,i.subSurface.maximumThickness=s.thicknessFactor,i.subSurface.useThicknessAsDepth=!0,s.thicknessTexture?(s.thicknessTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,s.thicknessTexture).then(n=>{i.subSurface.thicknessTexture=n,i.subSurface.useGltfStyleTextures=!0})):Promise.resolve()}}Ie.RegisterExtension(lm,a=>new bk(a));const hm="KHR_materials_dispersion";class yk{constructor(e){this.name=hm,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(hm)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadDispersionPropertiesAsync(s,t,i,r)),Promise.all(n).then(()=>{})})}_loadDispersionPropertiesAsync(e,t,i,s){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);return!i.subSurface.isRefractionEnabled||!s.dispersion||(i.subSurface.isDispersionEnabled=!0,i.subSurface.dispersion=s.dispersion),Promise.resolve()}}Ie.RegisterExtension(hm,a=>new yk(a));const cm="KHR_mesh_quantization";class Ak{constructor(e){this.name=cm,this.enabled=e.isExtensionUsed(cm)}dispose(){}}Ie.RegisterExtension(cm,a=>new Ak(a));const um="KHR_texture_basisu";class Rk{constructor(e){this.name=um,this._loader=e,this.enabled=e.isExtensionUsed(um)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=t.sampler==null?Ie.DefaultSampler:et.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=et.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,l=>{i(l)},t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)})}}Ie.RegisterExtension(um,a=>new Rk(a));const dm="KHR_texture_transform";class Ik{constructor(e){this.name=dm,this._loader=e,this.enabled=this._loader.isExtensionUsed(dm)}dispose(){this._loader=null}loadTextureInfoAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>this._loader.loadTextureInfoAsync(e,t,n=>{if(!(n instanceof k))throw new Error(`${s}: Texture type not supported`);r.offset&&(n.uOffset=r.offset[0],n.vOffset=r.offset[1]),n.uRotationCenter=0,n.vRotationCenter=0,r.rotation&&(n.wAng=-r.rotation),r.scale&&(n.uScale=r.scale[0],n.vScale=r.scale[1]),r.texCoord!=null&&(n.coordinatesIndex=r.texCoord),i(n)}))}}Ie.RegisterExtension(dm,a=>new Ik(a));const fm="KHR_xmp_json_ld";class Pk{constructor(e){this.name=fm,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(fm)}dispose(){this._loader=null}onLoading(){var i,s,r;if(this._loader.rootBabylonMesh===null)return;const e=(i=this._loader.gltf.extensions)==null?void 0:i.KHR_xmp_json_ld,t=(r=(s=this._loader.gltf.asset)==null?void 0:s.extensions)==null?void 0:r.KHR_xmp_json_ld;if(e&&t){const n=+t.packet;e.packets&&nnew Pk(a));function Uo(a,e,t,i){return K.FromArray(e,t).scale(i)}function Mk(a,e,t,i){return e[t+3]*i}function pi(a,e,t,i){return e[t]*i}function pm(a,e,t,i){return-e[t]*i}function If(a,e,t,i){return e[t+1]*i}function gE(a,e,t,i){return e[t]*i*2}function Gs(a){return{scale:[new ti(j.ANIMATIONTYPE_FLOAT,`${a}.uScale`,pi,()=>2),new ti(j.ANIMATIONTYPE_FLOAT,`${a}.vScale`,If,()=>2)],offset:[new ti(j.ANIMATIONTYPE_FLOAT,`${a}.uOffset`,pi,()=>2),new ti(j.ANIMATIONTYPE_FLOAT,`${a}.vOffset`,If,()=>2)],rotation:[new ti(j.ANIMATIONTYPE_FLOAT,`${a}.wAng`,pm,()=>1)]}}class va extends Rd{buildAnimations(e,t,i,s,r){r(e._babylonCamera,this._buildAnimation(t,i,s))}}class ti extends Rd{buildAnimations(e,t,i,s,r){for(const n in e._data)r(e._data[n].babylonMaterial,this._buildAnimation(t,i,s))}}class Jc extends Rd{buildAnimations(e,t,i,s,r){r(e._babylonLight,this._buildAnimation(t,i,s))}}const Dk={__array__:{__target__:!0,...iu}},Ok={__array__:{__target__:!0,orthographic:{xmag:[new va(j.ANIMATIONTYPE_FLOAT,"orthoLeft",pm,()=>1),new va(j.ANIMATIONTYPE_FLOAT,"orthoRight",If,()=>1)],ymag:[new va(j.ANIMATIONTYPE_FLOAT,"orthoBottom",pm,()=>1),new va(j.ANIMATIONTYPE_FLOAT,"orthoTop",If,()=>1)],zfar:[new va(j.ANIMATIONTYPE_FLOAT,"maxZ",pi,()=>1)],znear:[new va(j.ANIMATIONTYPE_FLOAT,"minZ",pi,()=>1)]},perspective:{yfov:[new va(j.ANIMATIONTYPE_FLOAT,"fov",pi,()=>1)],zfar:[new va(j.ANIMATIONTYPE_FLOAT,"maxZ",pi,()=>1)],znear:[new va(j.ANIMATIONTYPE_FLOAT,"minZ",pi,()=>1)]}}},Nk={__array__:{__target__:!0,pbrMetallicRoughness:{baseColorFactor:[new ti(j.ANIMATIONTYPE_COLOR3,"albedoColor",Uo,()=>4),new ti(j.ANIMATIONTYPE_FLOAT,"alpha",Mk,()=>4)],metallicFactor:[new ti(j.ANIMATIONTYPE_FLOAT,"metallic",pi,()=>1)],roughnessFactor:[new ti(j.ANIMATIONTYPE_FLOAT,"roughness",pi,()=>1)],baseColorTexture:{extensions:{KHR_texture_transform:Gs("albedoTexture")}},metallicRoughnessTexture:{extensions:{KHR_texture_transform:Gs("metallicTexture")}}},emissiveFactor:[new ti(j.ANIMATIONTYPE_COLOR3,"emissiveColor",Uo,()=>3)],normalTexture:{scale:[new ti(j.ANIMATIONTYPE_FLOAT,"bumpTexture.level",pi,()=>1)],extensions:{KHR_texture_transform:Gs("bumpTexture")}},occlusionTexture:{strength:[new ti(j.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",pi,()=>1)],extensions:{KHR_texture_transform:Gs("ambientTexture")}},emissiveTexture:{extensions:{KHR_texture_transform:Gs("emissiveTexture")}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:[new ti(j.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",pi,()=>1)],anisotropyRotation:[new ti(j.ANIMATIONTYPE_FLOAT,"anisotropy.angle",pi,()=>1)],anisotropyTexture:{extensions:{KHR_texture_transform:Gs("anisotropy.texture")}}},KHR_materials_clearcoat:{clearcoatFactor:[new ti(j.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",pi,()=>1)],clearcoatRoughnessFactor:[new ti(j.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",pi,()=>1)],clearcoatTexture:{extensions:{KHR_texture_transform:Gs("clearCoat.texture")}},clearcoatNormalTexture:{scale:[new ti(j.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",pi,()=>1)],extensions:{KHR_texture_transform:Gs("clearCoat.bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:Gs("clearCoat.textureRoughness")}}},KHR_materials_dispersion:{dispersion:[new ti(j.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",pi,()=>1)]},KHR_materials_emissive_strength:{emissiveStrength:[new ti(j.ANIMATIONTYPE_FLOAT,"emissiveIntensity",pi,()=>1)]},KHR_materials_ior:{ior:[new ti(j.ANIMATIONTYPE_FLOAT,"indexOfRefraction",pi,()=>1)]},KHR_materials_iridescence:{iridescenceFactor:[new ti(j.ANIMATIONTYPE_FLOAT,"iridescence.intensity",pi,()=>1)],iridescenceIor:[new ti(j.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",pi,()=>1)],iridescenceThicknessMinimum:[new ti(j.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",pi,()=>1)],iridescenceThicknessMaximum:[new ti(j.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",pi,()=>1)],iridescenceTexture:{extensions:{KHR_texture_transform:Gs("iridescence.texture")}},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:Gs("iridescence.thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:[new ti(j.ANIMATIONTYPE_COLOR3,"sheen.color",Uo,()=>3)],sheenRoughnessFactor:[new ti(j.ANIMATIONTYPE_FLOAT,"sheen.roughness",pi,()=>1)],sheenColorTexture:{extensions:{KHR_texture_transform:Gs("sheen.texture")}},sheenRoughnessTexture:{extensions:{KHR_texture_transform:Gs("sheen.textureRoughness")}}},KHR_materials_specular:{specularFactor:[new ti(j.ANIMATIONTYPE_FLOAT,"metallicF0Factor",pi,()=>1)],specularColorFactor:[new ti(j.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",Uo,()=>3)],specularTexture:{extensions:{KHR_texture_transform:Gs("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:Gs("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:[new ti(j.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",pi,()=>1)],transmissionTexture:{extensions:{KHR_texture_transform:Gs("subSurface.refractionIntensityTexture")}}},KHR_materials_volume:{attenuationColor:[new ti(j.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",Uo,()=>3)],attenuationDistance:[new ti(j.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",pi,()=>1)],thicknessFactor:[new ti(j.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",pi,()=>1)],thicknessTexture:{extensions:{KHR_texture_transform:Gs("subSurface.thicknessTexture")}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:[new ti(j.ANIMATIONTYPE_FLOAT,"subSurface.translucencyIntensity",pi,()=>1)],diffuseTransmissionTexture:{extensions:{KHR_texture_transform:Gs("subSurface.translucencyIntensityTexture")}},diffuseTransmissionColorFactor:[new ti(j.ANIMATIONTYPE_COLOR3,"subSurface.translucencyColor",Uo,()=>3)],diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:Gs("subSurface.translucencyColorTexture")}}}}}},wk={KHR_lights_punctual:{lights:{__array__:{__target__:!0,color:[new Jc(j.ANIMATIONTYPE_COLOR3,"diffuse",Uo,()=>3)],intensity:[new Jc(j.ANIMATIONTYPE_FLOAT,"intensity",pi,()=>1)],range:[new Jc(j.ANIMATIONTYPE_FLOAT,"range",pi,()=>1)],spot:{innerConeAngle:[new Jc(j.ANIMATIONTYPE_FLOAT,"innerAngle",gE,()=>1)],outerConeAngle:[new Jc(j.ANIMATIONTYPE_FLOAT,"angle",gE,()=>1)]}}}}},Fk={nodes:Dk,materials:Nk,cameras:Ok,extensions:wk};class DC{constructor(e,t){this._gltf=e,this._infoTree=t}convert(e){let t=this._gltf,i=this._infoTree,s;if(!e.startsWith("/"))throw new Error("Path must start with a /");const r=e.split("/");r.shift();for(const n of r){if(i.__array__)i=i.__array__;else if(i=i[n],!i)throw new Error(`Path ${e} is invalid`);if(t===void 0)throw new Error(`Path ${e} is invalid`);t=t[n],i.__target__&&(s=t)}return{object:s,info:i}}}const _m="KHR_animation_pointer";class Lk extends DC{constructor(e){super(e,Fk)}}class Bk{constructor(e){this.name=_m,this._loader=e,this._pathToObjectConverter=new Lk(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(_m)}dispose(){this._loader=null,delete this._pathToObjectConverter}_loadAnimationChannelAsync(e,t,i,s,r){var h;const n=(h=s.target.extensions)==null?void 0:h.KHR_animation_pointer;if(!n||!this._pathToObjectConverter)return null;s.target.path!=="pointer"&&N.Warn(`${e}/target/path: Value (${s.target.path}) must be (pointer) when using the ${this.name} extension`),s.target.node!=null&&N.Warn(`${e}/target/node: Value (${s.target.node}) must not be present when using the ${this.name} extension`);const o=`${e}/extensions/${this.name}`,l=n.pointer;if(!l)throw new Error(`${o}: Pointer is missing`);try{const c=this._pathToObjectConverter.convert(l);return this._loader._loadAnimationChannelFromTargetInfoAsync(e,t,i,s,c,r)}catch{return N.Warn(`${o}/pointer: Invalid pointer (${l}) skipped`),null}}}Ie.RegisterExtension(_m,a=>new Bk(a));const mm="MSFT_audio_emitter";class Uk{constructor(e){this.name=mm,this._loader=e,this.enabled=this._loader.isExtensionUsed(mm)}dispose(){this._loader=null,this._clips=null,this._emitters=null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._clips=t.clips,this._emitters=t.emitters,et.Assign(this._clips),et.Assign(this._emitters)}}loadSceneAsync(e,t){return Ie.LoadExtensionAsync(e,t,this.name,(i,s)=>{const r=new Array;r.push(this._loader.loadSceneAsync(e,t));for(const n of s.emitters){const o=et.Get(`${i}/emitters`,this._emitters,n);if(o.refDistance!=null||o.maxDistance!=null||o.rolloffFactor!=null||o.distanceModel!=null||o.innerAngle!=null||o.outerAngle!=null)throw new Error(`${i}: Direction or Distance properties are not allowed on emitters attached to a scene`);r.push(this._loadEmitterAsync(`${i}/emitters/${o.index}`,o))}return Promise.all(r).then(()=>{})})}loadNodeAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return this._loader.loadNodeAsync(s,t,o=>{for(const l of r.emitters){const h=et.Get(`${s}/emitters`,this._emitters,l);n.push(this._loadEmitterAsync(`${s}/emitters/${h.index}`,h).then(()=>{for(const c of h._babylonSounds)c.attachToMesh(o),(h.innerAngle!=null||h.outerAngle!=null)&&(c.setLocalDirectionToMesh(m.Forward()),c.setDirectionalCone(2*X.ToDegrees(h.innerAngle==null?Math.PI:h.innerAngle),2*X.ToDegrees(h.outerAngle==null?Math.PI:h.outerAngle),0))}))}i(o)}).then(o=>Promise.all(n).then(()=>o))})}loadAnimationAsync(e,t){return Ie.LoadExtensionAsync(e,t,this.name,(i,s)=>this._loader.loadAnimationAsync(e,t).then(r=>{const n=new Array;et.Assign(s.events);for(const o of s.events)n.push(this._loadAnimationEventAsync(`${i}/events/${o.index}`,e,t,o,r));return Promise.all(n).then(()=>r)}))}_loadClipAsync(e,t){if(t._objectURL)return t._objectURL;let i;if(t.uri)i=this._loader.loadUriAsync(e,t,t.uri);else{const s=et.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,t.bufferView);i=this._loader.loadBufferViewAsync(`/bufferViews/${s.index}`,s)}return t._objectURL=i.then(s=>URL.createObjectURL(new Blob([s],{type:t.mimeType}))),t._objectURL}_loadEmitterAsync(e,t){if(t._babylonSounds=t._babylonSounds||[],!t._babylonData){const i=new Array,s=t.name||`emitter${t.index}`,r={loop:!1,autoplay:!1,volume:t.volume==null?1:t.volume};for(let o=0;o{const u=t._babylonSounds[o]=new An(s,c,this._loader.babylonScene,null,r);u.refDistance=t.refDistance||1,u.maxDistance=t.maxDistance||256,u.rolloffFactor=t.rolloffFactor||1,u.distanceModel=t.distanceModel||"exponential"}))}const n=Promise.all(i).then(()=>{const o=t.clips.map(h=>h.weight||1),l=new by(t.loop||!1,t._babylonSounds,o);t.innerAngle&&(l.directionalConeInnerAngle=2*X.ToDegrees(t.innerAngle)),t.outerAngle&&(l.directionalConeOuterAngle=2*X.ToDegrees(t.outerAngle)),t.volume&&(l.volume=t.volume),t._babylonData.sound=l});t._babylonData={loaded:n}}return t._babylonData.loaded}_getEventAction(e,t,i,s,r){switch(i){case"play":return n=>{const o=(r||0)+(n-s);t.play(o)};case"stop":return()=>{t.stop()};case"pause":return()=>{t.pause()};default:throw new Error(`${e}: Unsupported action ${i}`)}}_loadAnimationEventAsync(e,t,i,s,r){if(r.targetedAnimations.length==0)return Promise.resolve();const n=r.targetedAnimations[0],o=s.emitter,l=et.Get(`/extensions/${this.name}/emitters`,this._emitters,o);return this._loadEmitterAsync(e,l).then(()=>{const h=l._babylonData.sound;if(h){const c=new Nm(s.time,this._getEventAction(e,h,s.action,s.time,s.startOffset));n.animation.addEvent(c),r.onAnimationGroupEndObservable.add(()=>{h.stop()}),r.onAnimationGroupPauseObservable.add(()=>{h.pause()})}})}}Ie.RegisterExtension(mm,a=>new Uk(a));const gm="MSFT_lod";class Vk{constructor(e){this.name=gm,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new z,this.onMaterialLODsLoadedObservable=new z,this._bufferLODs=new Array,this._nodeIndexLOD=null,this._nodeSignalLODs=new Array,this._nodePromiseLODs=new Array,this._nodeBufferLODs=new Array,this._materialIndexLOD=null,this._materialSignalLODs=new Array,this._materialPromiseLODs=new Array,this._materialBufferLODs=new Array,this._loader=e,this.enabled=this._loader.isExtensionUsed(gm)}dispose(){this._loader=null,this._nodeIndexLOD=null,this._nodeSignalLODs.length=0,this._nodePromiseLODs.length=0,this._nodeBufferLODs.length=0,this._materialIndexLOD=null,this._materialSignalLODs.length=0,this._materialPromiseLODs.length=0,this._materialBufferLODs.length=0,this.onMaterialLODsLoadedObservable.clear(),this.onNodeLODsLoadedObservable.clear()}onReady(){for(let e=0;e{e!==0&&(this._loader.endPerformanceCounter(`Node LOD ${e}`),this._loader.log(`Loaded node LOD ${e}`)),this.onNodeLODsLoadedObservable.notifyObservers(e),e!==this._nodePromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Node LOD ${e+1}`),this._loadBufferLOD(this._nodeBufferLODs,e+1),this._nodeSignalLODs[e]&&this._nodeSignalLODs[e].resolve())});this._loader._completePromises.push(t)}for(let e=0;e{e!==0&&(this._loader.endPerformanceCounter(`Material LOD ${e}`),this._loader.log(`Loaded material LOD ${e}`)),this.onMaterialLODsLoadedObservable.notifyObservers(e),e!==this._materialPromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Material LOD ${e+1}`),this._loadBufferLOD(this._materialBufferLODs,e+1),this._materialSignalLODs[e]&&this._materialSignalLODs[e].resolve())});this._loader._completePromises.push(t)}}loadSceneAsync(e,t){const i=this._loader.loadSceneAsync(e,t);return this._loadBufferLOD(this._bufferLODs,0),i}loadNodeAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{let n;const o=this._getLODs(s,t,this._loader.gltf.nodes,r.ids);this._loader.logOpen(`${s}`);for(let l=0;l{i(d),d.setEnabled(!1)},u=this._loader.loadNodeAsync(`/nodes/${h.index}`,h,c).then(d=>{if(l!==0){const f=o[l-1];f._babylonTransformNode&&(this._disposeTransformNode(f._babylonTransformNode),delete f._babylonTransformNode)}return d.setEnabled(!0),d});this._nodePromiseLODs[l]=this._nodePromiseLODs[l]||[],l===0?n=u:(this._nodeIndexLOD=null,this._nodePromiseLODs[l].push(u))}return this._loader.logClose(),n})}_loadMaterialAsync(e,t,i,s,r){return this._nodeIndexLOD?null:Ie.LoadExtensionAsync(e,t,this.name,(n,o)=>{let l;const h=this._getLODs(n,t,this._loader.gltf.materials,o.ids);this._loader.logOpen(`${n}`);for(let c=0;c{c===0&&r(f)}).then(f=>{if(c!==0){r(f);const p=h[c-1]._data;p[s]&&(this._disposeMaterials([p[s].babylonMaterial]),delete p[s])}return f});this._materialPromiseLODs[c]=this._materialPromiseLODs[c]||[],c===0?l=d:(this._materialIndexLOD=null,this._materialPromiseLODs[c].push(d))}return this._loader.logClose(),l})}_loadUriAsync(e,t,i){if(this._nodeIndexLOD!==null){this._loader.log("deferred");const s=this._nodeIndexLOD-1;return this._nodeSignalLODs[s]=this._nodeSignalLODs[s]||new tu,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then(()=>this._loader.loadUriAsync(e,t,i))}else if(this._materialIndexLOD!==null){this._loader.log("deferred");const s=this._materialIndexLOD-1;return this._materialSignalLODs[s]=this._materialSignalLODs[s]||new tu,this._materialSignalLODs[s].promise.then(()=>this._loader.loadUriAsync(e,t,i))}return null}loadBufferAsync(e,t,i,s){if(this._loader.parent.useRangeRequests&&!t.uri){if(!this._loader.bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);const r=(n,o)=>{const l=i,h=l+s-1;let c=n[o];return c?(c.start=Math.min(c.start,l),c.end=Math.max(c.end,h)):(c={start:l,end:h,loaded:new tu},n[o]=c),c.loaded.promise.then(u=>new Uint8Array(u.buffer,u.byteOffset+i-c.start,s))};return this._loader.log("deferred"),this._nodeIndexLOD!==null?r(this._nodeBufferLODs,this._nodeIndexLOD):this._materialIndexLOD!==null?r(this._materialBufferLODs,this._materialIndexLOD):r(this._bufferLODs,0)}return null}_loadBufferLOD(e,t){const i=e[t];i&&(this._loader.log(`Loading buffer range [${i.start}-${i.end}]`),this._loader.bin.readAsync(i.start,i.end-i.start+1).then(s=>{i.loaded.resolve(s)},s=>{i.loaded.reject(s)}))}_getLODs(e,t,i,s){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const r=[];for(let n=s.length-1;n>=0;n--)if(r.push(et.Get(`${e}/ids/${s[n]}`,i,s[n])),r.length===this.maxLODsToLoad)return r;return r.push(t),r}_disposeTransformNode(e){const t=[],i=e.material;i&&t.push(i);for(const r of e.getChildMeshes())r.material&&t.push(r.material);e.dispose();const s=t.filter(r=>this._loader.babylonScene.meshes.every(n=>n.material!=r));this._disposeMaterials(s)}_disposeMaterials(e){const t={};for(const i of e){for(const s of i.getActiveTextures())t[s.uniqueId]=s;i.dispose()}for(const i in t)for(const s of this._loader.babylonScene.materials)s.hasTexture(t[i])&&delete t[i];for(const i in t)t[i].dispose()}}Ie.RegisterExtension(gm,a=>new Vk(a));const xm="MSFT_minecraftMesh";class kk{constructor(e){this.name=xm,this._loader=e,this.enabled=this._loader.isExtensionUsed(xm)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtraAsync(e,t,this.name,(s,r)=>{if(r){if(!(i instanceof Ae))throw new Error(`${s}: Material type not supported`);const n=this._loader.loadMaterialPropertiesAsync(e,t,i);return i.needAlphaBlending()&&(i.forceDepthWrite=!0,i.separateCullingPass=!0),i.backFaceCulling=i.forceDepthWrite,i.twoSidedLighting=!0,n}return null})}}Ie.RegisterExtension(xm,a=>new kk(a));const Tm="MSFT_sRGBFactors";class Gk{constructor(e){this.name=Tm,this._loader=e,this.enabled=this._loader.isExtensionUsed(Tm)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtraAsync(e,t,this.name,(s,r)=>{if(r){if(!(i instanceof Ae))throw new Error(`${s}: Material type not supported`);const n=this._loader.loadMaterialPropertiesAsync(e,t,i),o=i.getScene().getEngine().useExactSrgbConversions;return i.albedoTexture||i.albedoColor.toLinearSpaceToRef(i.albedoColor,o),i.reflectivityTexture||i.reflectivityColor.toLinearSpaceToRef(i.reflectivityColor,o),n}return null})}}Ie.RegisterExtension(Tm,a=>new Gk(a));const zk={"lifecycle/onStart":Ad.ClassName,"lifecycle/onTick":Rc.ClassName,log:nh.ClassName,"flow/delay":Ed.ClassName,"customEvent/send":Td.ClassName,"customEvent/receive":Ac.ClassName,"flow/sequence":hh.ClassName,"world/get":uh.ClassName,"world/set":xd.ClassName,"flow/doN":oh.ClassName,"variable/get":ch.ClassName,"variable/set":ah.ClassName,"flow/whileLoop":lh.ClassName,"math/random":mh.ClassName,"math/e":xh.ClassName,"math/pi":Th.ClassName,"math/inf":Eh.ClassName,"math/nan":Sh.ClassName,"math/abs":vh.ClassName,"math/sign":Ch.ClassName,"math/trunc":bh.ClassName,"math/floor":yh.ClassName,"math/ceil":Ah.ClassName,"math/fract":Rh.ClassName,"math/neg":Ih.ClassName,"math/add":dh.ClassName,"math/sub":fh.ClassName,"math/mul":ph.ClassName,"math/div":_h.ClassName,"math/rem":Ph.ClassName,"math/min":Mh.ClassName,"math/max":Dh.ClassName,"math/clamp":Oh.ClassName,"math/saturate":Nh.ClassName,"math/mix":wh.ClassName,"math/eq":Fh.ClassName,"math/lt":Lh.ClassName,"math/le":Ap.ClassName,"math/gt":Bh.ClassName,"math/ge":Uh.ClassName,"math/isnan":Vh.ClassName,"math/isinf":Rp.ClassName,"math/rad":kh.ClassName,"math/deg":Gh.ClassName,"math/sin":zh.ClassName,"math/cos":Wh.ClassName,"math/tan":Hh.ClassName,"math/asin":Xh.ClassName,"math/acos":Yh.ClassName,"math/atan":$h.ClassName,"math/atan2":jh.ClassName,"math/sinh":Kh.ClassName,"math/cosh":qh.ClassName,"math/tanh":Zh.ClassName,"math/asinh":Qh.ClassName,"math/acosh":Jh.ClassName,"math/atanh":ec.ClassName,"math/exp":tc.ClassName,"math/log":ic.ClassName,"math/log2":sc.ClassName,"math/log10":rc.ClassName,"math/sqrt":nc.ClassName,"math/cbrt":ac.ClassName,"math/pow":oc.ClassName,"math/length":lc.ClassName,"math/normalize":hc.ClassName,"math/dot":gh.ClassName,"math/cross":cc.ClassName,"math/rotate2d":uc.ClassName,"math/rotate3d":dc.ClassName,"math/transpose":fc.ClassName,"math/determinant":pc.ClassName,"math/inverse":_c.ClassName,"math/matmul":mc.ClassName,"math/not":gc.ClassName,"math/and":xc.ClassName,"math/or":Tc.ClassName,"math/xor":Ec.ClassName,"math/asr":vc.ClassName,"math/lsl":Sc.ClassName,"math/clz":Cc.ClassName,"math/ctz":bc.ClassName,"math/popcnt":yc.ClassName},Wk={float2:"Vector2",float3:"Vector3",float4:"Vector4",float4x4:"Matrix",int:"FlowGraphInteger"};function Em(a,e,t){if(a.type!==void 0){const i=e.types&&e.types[a.type];if(!i)throw new Error(`${t}: Unknown type: ${a.type}`);const s=i.signature;if(!s)throw new Error(`${t}: Type ${a.type} has no signature`);const r=Wk[s];return{value:a.value,className:r}}else return a.value}function Hk(a,e,t){const i={},s=a.configuration??[];for(const r of s)if(r.id==="customEvent"){const n=e.customEvents&&e.customEvents[r.value];if(!n)throw new Error(`/extensions/KHR_interactivity/nodes/${t}: Unknown custom event: ${r.value}`);i.eventId=n.id,i.eventData=n.values.map(o=>o.id)}else if(r.id==="variable"){const n=e.variables&&e.variables[r.value];if(!n)throw new Error(`/extensions/KHR_interactivity/nodes/${t}: Unknown variable: ${r.value}`);i.variableName=n.id}else if(r.id==="path"){const n=r.value;i.path=n}else i[r.id]=Em(r,e,`/extensions/KHR_interactivity/nodes/${t}`);return i}function Xk(a,e,t){const i=zk[e.type];if(!i)throw new Error(`/extensions/KHR_interactivity/nodes/${a}: Unknown block type: ${e.type}`);const s=a.toString(),r=Hk(e,t,s),n=e.metadata;return{className:i,config:r,uniqueId:s,metadata:n,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[]}}function Yk(a){const e={uniqueId:yn(),_userVariables:{},_connectionValues:{}},t=[e],i=[];for(let r=0;rT.name===p);g||(g={uniqueId:yn(),name:p,_connectionType:Zr.Input,connectedPointIds:[]},_.signalInputs.push(g)),g.connectedPointIds.push(d.uniqueId),d.connectedPointIds.push(g.uniqueId)}const h=n.values??[];for(const c of h){const u=c.id,d={uniqueId:yn(),name:u,_connectionType:Zr.Input,connectedPointIds:[]};if(o.dataInputs.push(d),c.value!==void 0){const f=Em(c,a,`/extensions/KHR_interactivity/nodes/${r}`);e._connectionValues[d.uniqueId]=f}else if(c.node!==void 0&&c.socket!==void 0){const f=c.node,p=c.socket,_=i[f];if(!_)throw new Error(`/extensions/KHR_interactivity/nodes/${r}: Could not find node with id ${f} that connects its output with node${r}'s input ${u}`);let g=_.dataOutputs.find(T=>T.name===p);g||(g={uniqueId:yn(),name:p,_connectionType:Zr.Output,connectedPointIds:[]},_.dataOutputs.push(g)),d.connectedPointIds.push(g.uniqueId),g.connectedPointIds.push(d.uniqueId)}else throw new Error(`/extensions/KHR_interactivity/nodes/${r}: Invalid socket ${u} in node ${r}`)}}const s=a.variables??[];for(let r=0;ra._babylonTransformNode.position,set:(a,e)=>{const t=e._babylonTransformNode;t.position=a},getObject(a){return a._babylonTransformNode}}}},Kk={nodes:jk},Sm="KHR_interactivity";class qk{constructor(e){this._loader=e,this.name=Sm,this.enabled=this._loader.isExtensionUsed(Sm),this._pathConverter=new $k(this._loader.gltf)}dispose(){this._loader=null,delete this._pathConverter}onReady(){var r;if(!this._loader.babylonScene||!this._pathConverter)return;const e=this._loader.babylonScene,t=(r=this._loader.gltf.extensions)==null?void 0:r.KHR_interactivity,i=Yk(t),s=new Vl({scene:e});rh.Parse(i,{coordinator:s,pathConverter:this._pathConverter}),s.start()}}Ie.RegisterExtension(Sm,a=>new qk(a));const OC="ExtrasAsMetadata";class Zk{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){const i=e.metadata=e.metadata||{},s=i.gltf=i.gltf||{};s.extras=t.extras}}constructor(e){this.name=OC,this.enabled=!0,this._loader=e}dispose(){this._loader=null}loadNodeAsync(e,t,i){return this._loader.loadNodeAsync(e,t,s=>{this._assignExtras(s,t),i(s)})}loadCameraAsync(e,t,i){return this._loader.loadCameraAsync(e,t,s=>{this._assignExtras(s,t),i(s)})}createMaterial(e,t,i){const s=this._loader.createMaterial(e,t,i);return this._assignExtras(s,t),s}}Ie.RegisterExtension(OC,a=>new Zk(a));class Qk extends gt{constructor(t){super("kotatsu",t);Vt(this,"isLoaded");Vt(this,"root");Vt(this,"tabletop");Vt(this,"tableBase");Vt(this,"futon");Vt(this,"futonPolyester");Vt(this,"heater");Vt(this,"heaterLight");Vt(this,"legTL");Vt(this,"legTR");Vt(this,"legBL");Vt(this,"legBR");Vt(this,"spotLight");this.scene=t,st.ImportMeshAsync("","./models/","kotatsu.glb",t).then(i=>{this.root=i.meshes[0],this.root.scaling=m.One(),this.root.metadata={isShuffled:!1,isNormalMaterial:!1},this.tabletop=new Ke("tabletop"),this.tabletop.metadata={isRotated:!1},this.tabletop.parent=this.root;const s=t.getMeshByName("tabletopBase"),r=t.getMeshByName("tabletopPicture");s.parent=this.tabletop,r.parent=this.tabletop,this.futon=t.getMeshByName("futon"),this.futonPolyester=t.getMeshByName("futonPolyester"),this.tableBase=t.getMeshByName("tableBase"),this.tableBase.parent=this.root,t.getMeshByName("lattice").parent=this.tableBase,t.getMeshByName("tableBasePanel").parent=this.tableBase,this.legTL=t.getMeshByName("legTL"),this.legTR=t.getMeshByName("legTR"),this.legBL=t.getMeshByName("legBL"),this.legBR=t.getMeshByName("legBR"),this.legTL.parent=this.tableBase,this.legTR.parent=this.tableBase,this.legBL.parent=this.tableBase,this.legBR.parent=this.tableBase,this.heater=t.getMeshByName("heater");const n=new fe("heaterMaterial");n.emissiveColor=new K(1,0,0),this.heater.material=n,t.getMeshByName("heaterCase").parent=this.heater,t.getMeshByName("heaterPanel").parent=this.heater,t.getMeshByName("meshLarge").parent=this.heater,t.getMeshByName("meshSmall").parent=this.heater,this.heater.parent=this.tableBase,this.heaterLight=new Mo("heaterLight",new m(0,.15,0),t),this.heaterLight.diffuse=new K(1,0,0),this.heaterLight.intensity=1,this.heaterLight.parent=this.heater,this.spotLight=new ar("spotLight",new m(0,3,.7),new m(0,-1,-.25),Math.PI/3,2,t),this.spotLight.diffuse=new K(.4,.4,.7),this.spotLight.intensity=50,this.spotLight.parent=this.root,this.spotLight.setEnabled(!1),this.root.getChildMeshes().forEach(l=>{l.metadata={initialMaterial:l.material.clone("initialMaterial")}}),this.futonPolyester.setEnabled(!1),this.root.scaling=m.Zero(),this.heaterLight.setEnabled(!1)}).catch(console.error)}}class Jk extends gt{constructor(t){super("embroidery",t);Vt(this,"root");Vt(this,"take");Vt(this,"oreo");Vt(this,"toreko");Vt(this,"o1");Vt(this,"cha");Vt(this,"no");Vt(this,"ma");Vt(this,"to");Vt(this,"ri");Vt(this,"o2");this.scene=t,st.ImportMeshAsync("","./models/","embroidery.glb",t).then(i=>{this.root=i.meshes[0],this.take=t.getTransformNodeByName("take"),this.oreo=t.getTransformNodeByName("oreo"),this.toreko=t.getTransformNodeByName("toreko"),this.o1=t.getMeshByName("o1"),this.cha=t.getMeshByName("cha"),this.no=t.getMeshByName("no"),this.ma=t.getMeshByName("ma"),this.to=t.getMeshByName("to"),this.ri=t.getMeshByName("ri"),this.o2=t.getMeshByName("o2"),this.root.metadata={isWireframe:!1},this.root.getChildTransformNodes(!0).forEach(r=>{r.metadata={initialPosition:r.position.clone()}})}).catch(console.error)}}const eG="cellPixelShader",tG=`precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW; +`);const t={vertex:"GLTFDefaultMaterial",fragment:"GLTFDefaultMaterial"},i={attributes:["position"],uniforms:["worldView","projection","u_emission"],samplers:new Array,needAlphaBlending:!1};Es._DefaultMaterial=new Dr("GLTFDefaultMaterial",e,t,i),Es._DefaultMaterial.setColor4("u_emission",new ge(.5,.5,.5,1))}return Es._DefaultMaterial}}Es._DefaultMaterial=null;var oo;(function(a){a[a.IDENTIFIER=1]="IDENTIFIER",a[a.UNKNOWN=2]="UNKNOWN",a[a.END_OF_INPUT=3]="END_OF_INPUT"})(oo||(oo={}));class cE{constructor(e){this._pos=0,this.currentToken=oo.UNKNOWN,this.currentIdentifier="",this.currentString="",this.isLetterOrDigitPattern=/^[a-zA-Z0-9]+$/,this._toParse=e,this._maxPos=e.length}getNextToken(){if(this.isEnd())return oo.END_OF_INPUT;if(this.currentString=this.read(),this.currentToken=oo.UNKNOWN,this.currentString==="_"||this.isLetterOrDigitPattern.test(this.currentString))for(this.currentToken=oo.IDENTIFIER,this.currentIdentifier=this.currentString;!this.isEnd()&&(this.isLetterOrDigitPattern.test(this.currentString=this.peek())||this.currentString==="_");)this.currentIdentifier+=this.currentString,this.forward();return this.currentToken}peek(){return this._toParse[this._pos]}read(){return this._toParse[this._pos++]}forward(){this._pos++}isEnd(){return this._pos>=this._maxPos}}const RC=["MODEL","VIEW","PROJECTION","MODELVIEW","MODELVIEWPROJECTION","JOINTMATRIX"],IC=["world","view","projection","worldView","worldViewProjection","mBones"],V3=["translation","rotation","scale"],k3=["position","rotationQuaternion","scaling"],G3=(a,e)=>{for(const t in a){const i=a[t];e.buffers[t]=i,e.buffersCount++}},z3=(a,e)=>{for(const t in a){const i=a[t];e.shaders[t]=i,e.shaderscount++}},fr=(a,e,t)=>{for(const i in a){const s=a[i];t[e][i]=s}},W3=a=>{if(a)for(let e=0;e{if(a.semantic==="NORMAL")return"normal";if(a.semantic==="POSITION")return"position";if(a.semantic==="JOINT")return"matricesIndices";if(a.semantic==="WEIGHT")return"matricesWeights";if(a.semantic==="COLOR")return"color";if(a.semantic&&a.semantic.indexOf("TEXCOORD_")!==-1){const e=Number(a.semantic.split("_")[1]);return"uv"+(e===0?"":e+1)}return null},H3=a=>{for(const e in a.animations){const t=a.animations[e];if(!t.channels||!t.samplers)continue;let i=null;for(let s=0;s{let e=null;if(a.translation||a.rotation||a.scale){const t=m.FromArray(a.scale||[1,1,1]),i=Z.FromArray(a.rotation||[0,0,0,1]),s=m.FromArray(a.translation||[0,0,0]);e=D.Compose(t,i,s)}else e=D.FromArray(a.matrix);return e},PC=(a,e,t,i)=>{for(let r=0;r{for(let t=0;t{const t=a.nodes;let i=t[e];if(i)return{node:i,id:e};for(const s in t)if(i=t[s],i.jointName===e)return{node:i,id:s};return null},Y3=(a,e)=>{for(let t=0;t{for(const s in a.nodes){const r=a.nodes[s],n=s;if(!r.jointName||Y3(t,r.jointName))continue;const o=Qg(r),l=new Xt(r.name||"",e,null,o);l.id=n,i.push({bone:l,node:r,id:n})}for(let s=0;s{if(i||(i=new So(e.name||"","",a.scene)),!e.babylonSkeleton)return i;const s=[],r=[];$3(a,i,e,s),i.bones=[];for(let o=0;o0&&(f=X3(s,c),f&&r.indexOf(f)===-1&&r.push(f));const _=new Xt(h.jointName||"",i,f,p);_.id=c}const n=i.bones;i.bones=[];for(let o=0;o{if(s||(a.scene._blockEntityCollection=!!a.assetContainer,s=new W(e.name||"",a.scene),s._parentContainer=a.assetContainer,a.scene._blockEntityCollection=!1,s.id=i),!e.babylonNode)return s;const r=[];let n=null;const o=[],l=[],h=[],c=[];for(let f=0;f1?(u=new Ua("multimat"+i,a.scene),u.subMaterials=r):u=new fe("multimat"+i,a.scene),r.length===1&&(u=r[0]),u._parentContainer=a.assetContainer,s.material||(s.material=u),new xs(i,a.scene,n,!1,s),s.computeWorldMatrix(!0),a.scene._blockEntityCollection=!1,s.subMeshes=[];let d=0;for(let f=0;f{a.position&&(a.position=e),(a.rotationQuaternion||a.rotation)&&(a.rotationQuaternion=t),a.scaling&&(a.scaling=i)},K3=(a,e)=>{if(e.matrix){const t=new m(0,0,0),i=new Z,s=new m(0,0,0);D.FromArray(e.matrix).decompose(s,i,t),z_(a,t,i,s)}else e.translation&&e.rotation&&e.scale&&z_(a,m.FromArray(e.translation),Z.FromArray(e.rotation),m.FromArray(e.scale));a.computeWorldMatrix(!0)},q3=(a,e,t)=>{let i=null;if(a.importOnlyMeshes&&(e.skin||e.meshes)&&a.importMeshesNames&&a.importMeshesNames.length>0&&a.importMeshesNames.indexOf(e.name||"")===-1)return null;if(e.skin){if(e.meshes){const s=a.skins[e.skin],r=dE(a,e,e.meshes,t,e.babylonNode);r.skeleton=a.scene.getLastSkeletonById(e.skin),r.skeleton===null&&(r.skeleton=j3(a,s,r,s.babylonSkeleton),s.babylonSkeleton||(s.babylonSkeleton=r.skeleton)),i=r}}else if(e.meshes)i=dE(a,e,e.mesh?[e.mesh]:e.meshes,t,e.babylonNode);else if(e.light&&!e.babylonNode&&!a.importOnlyMeshes){const s=a.lights[e.light];if(s){if(s.type==="ambient"){const r=s[s.type],n=new Xa(e.light,m.Zero(),a.scene);n.name=e.name||"",r.color&&(n.diffuse=K.FromArray(r.color)),i=n}else if(s.type==="directional"){const r=s[s.type],n=new en(e.light,m.Zero(),a.scene);n.name=e.name||"",r.color&&(n.diffuse=K.FromArray(r.color)),i=n}else if(s.type==="point"){const r=s[s.type],n=new Mo(e.light,m.Zero(),a.scene);n.name=e.name||"",r.color&&(n.diffuse=K.FromArray(r.color)),i=n}else if(s.type==="spot"){const r=s[s.type],n=new ar(e.light,m.Zero(),m.Zero(),0,0,a.scene);n.name=e.name||"",r.color&&(n.diffuse=K.FromArray(r.color)),r.fallOfAngle&&(n.angle=r.fallOfAngle),r.fallOffExponent&&(n.exponent=r.fallOffExponent),i=n}}}else if(e.camera&&!e.babylonNode&&!a.importOnlyMeshes){const s=a.cameras[e.camera];if(s){if(a.scene._blockEntityCollection=!!a.assetContainer,s.type==="orthographic"){const r=new nr(e.camera,m.Zero(),a.scene,!1);r.name=e.name||"",r.mode=Se.ORTHOGRAPHIC_CAMERA,r.attachControl(),i=r,r._parentContainer=a.assetContainer}else if(s.type==="perspective"){const r=s[s.type],n=new nr(e.camera,m.Zero(),a.scene,!1);n.name=e.name||"",n.attachControl(),r.aspectRatio||(r.aspectRatio=a.scene.getEngine().getRenderWidth()/a.scene.getEngine().getRenderHeight()),r.znear&&r.zfar&&(n.maxZ=r.zfar,n.minZ=r.znear),i=n,n._parentContainer=a.assetContainer}a.scene._blockEntityCollection=!1}}if(!e.jointName){if(e.babylonNode)return e.babylonNode;if(i===null){a.scene._blockEntityCollection=!!a.assetContainer;const s=new W(e.name||"",a.scene);s._parentContainer=a.assetContainer,a.scene._blockEntityCollection=!1,e.babylonNode=s,i=s}}if(i!==null){if(e.matrix&&i instanceof W)K3(i,e);else{const s=e.translation||[0,0,0],r=e.rotation||[0,0,0,1],n=e.scale||[1,1,1];z_(i,m.FromArray(s),Z.FromArray(r),m.FromArray(n))}i.updateCache(!0),e.babylonNode=i}return i},ju=(a,e,t,i=!1)=>{const s=a.nodes[e];let r=null;if(a.importOnlyMeshes&&!i&&a.importMeshesNames?a.importMeshesNames.indexOf(s.name||"")!==-1||a.importMeshesNames.length===0?i=!0:i=!1:i=!0,!s.jointName&&i&&(r=q3(a,s,e),r!==null&&(r.id=e,r.parent=t)),s.children)for(let n=0;n{let e=a.currentScene;if(e)for(let t=0;t{const o=r.values||s.parameters;for(const l in t){const h=t[l],c=h.type;if(c===Rr.FLOAT_MAT2||c===Rr.FLOAT_MAT3||c===Rr.FLOAT_MAT4){if(h.semantic&&!h.source&&!h.node)Es.SetMatrix(e.scene,a,h,l,i.getEffect());else if(h.semantic&&(h.source||h.node)){let u=e.scene.getNodeByName(h.source||h.node||"");if(u===null&&(u=e.scene.getNodeById(h.source||h.node||"")),u===null)continue;Es.SetMatrix(e.scene,u,h,l,i.getEffect())}}else{const u=o[s.uniforms[l]];if(!u)continue;if(c===Rr.SAMPLER_2D){const d=e.textures[r.values?u:h.value].babylonTexture;if(d==null)continue;i.getEffect().setTexture(l,d)}else Es.SetUniform(i.getEffect(),l,u,c)}}n(i)},Q3=(a,e,t,i,s)=>{const r=i.values||t.parameters,n=t.uniforms;for(const o in s){const l=s[o],h=l.type;let c=r[n[o]];if(c===void 0&&(c=l.value),!c)continue;const u=d=>f=>{l.value&&d&&(e.setTexture(d,f),delete s[d])};h===Rr.SAMPLER_2D?Hs.LoadTextureAsync(a,i.values?c:l.value,u(o),()=>u(null)):l.value&&Es.SetUniform(e,o,i.values?c:l.value,h)&&delete s[o]}},J3=(a,e,t)=>(i,s)=>{e.dispose(!0),t("Cannot compile program named "+a.name+". Error: "+s+". Default material will be applied")},ek=(a,e,t,i,s,r)=>n=>{Q3(a,e,t,i,s),e.onBind=o=>{Z3(o,a,s,e,t,i,r)}},pE=(a,e,t)=>{for(const i in e.uniforms){const s=e.uniforms[i],r=e.parameters[s];if(a.currentIdentifier===i&&r.semantic&&!r.source&&!r.node){const n=RC.indexOf(r.semantic);if(n!==-1)return delete t[i],IC[n]}}return a.currentIdentifier},_E=a=>{for(const e in a.materials)Hs.LoadMaterialAsync(a,e,()=>{},()=>{})};class Ra{static CreateRuntime(e,t,i){const s={extensions:{},accessors:{},buffers:{},bufferViews:{},meshes:{},lights:{},cameras:{},nodes:{},images:{},textures:{},shaders:{},programs:{},samplers:{},techniques:{},materials:{},animations:{},skins:{},extensionsUsed:[],scenes:{},buffersCount:0,shaderscount:0,scene:t,rootUrl:i,loadedBufferCount:0,loadedBufferViews:{},loadedShaderCount:0,importOnlyMeshes:!1,dummyNodes:[],assetContainer:null};return e.extensions&&fr(e.extensions,"extensions",s),e.extensionsUsed&&fr(e.extensionsUsed,"extensionsUsed",s),e.buffers&&G3(e.buffers,s),e.bufferViews&&fr(e.bufferViews,"bufferViews",s),e.accessors&&fr(e.accessors,"accessors",s),e.meshes&&fr(e.meshes,"meshes",s),e.lights&&fr(e.lights,"lights",s),e.cameras&&fr(e.cameras,"cameras",s),e.nodes&&fr(e.nodes,"nodes",s),e.images&&fr(e.images,"images",s),e.textures&&fr(e.textures,"textures",s),e.shaders&&z3(e.shaders,s),e.programs&&fr(e.programs,"programs",s),e.samplers&&fr(e.samplers,"samplers",s),e.techniques&&fr(e.techniques,"techniques",s),e.materials&&fr(e.materials,"materials",s),e.animations&&fr(e.animations,"animations",s),e.skins&&fr(e.skins,"skins",s),e.scenes&&(s.scenes=e.scenes),e.scene&&e.scenes&&(s.currentScene=e.scenes[e.scene]),s}static LoadBufferAsync(e,t,i,s,r){const n=e.buffers[t];X.IsBase64(n.uri)?setTimeout(()=>i(new Uint8Array(X.DecodeBase64(n.uri)))):X.LoadFile(e.rootUrl+n.uri,o=>i(new Uint8Array(o)),r,void 0,!0,o=>{o&&s(o.status+" "+o.statusText)})}static LoadTextureBufferAsync(e,t,i,s){const r=e.textures[t];if(!r||!r.source){s("");return}if(r.babylonTexture){i(null);return}const n=e.images[r.source];X.IsBase64(n.uri)?setTimeout(()=>i(new Uint8Array(X.DecodeBase64(n.uri)))):X.LoadFile(e.rootUrl+n.uri,o=>i(new Uint8Array(o)),void 0,void 0,!0,o=>{o&&s(o.status+" "+o.statusText)})}static CreateTextureAsync(e,t,i,s){const r=e.textures[t];if(r.babylonTexture){s(r.babylonTexture);return}const n=e.samplers[r.sampler],o=n.minFilter===zn.NEAREST_MIPMAP_NEAREST||n.minFilter===zn.NEAREST_MIPMAP_LINEAR||n.minFilter===zn.LINEAR_MIPMAP_NEAREST||n.minFilter===zn.LINEAR_MIPMAP_LINEAR,l=k.BILINEAR_SAMPLINGMODE,h=i==null?new Blob:new Blob([i]),c=URL.createObjectURL(h),u=()=>URL.revokeObjectURL(c),d=new k(c,e.scene,!o,!0,l,u,u);n.wrapS!==void 0&&(d.wrapU=Es.GetWrapMode(n.wrapS)),n.wrapT!==void 0&&(d.wrapV=Es.GetWrapMode(n.wrapT)),d.name=t,r.babylonTexture=d,s(d)}static LoadShaderStringAsync(e,t,i,s){const r=e.shaders[t];if(X.IsBase64(r.uri)){const n=atob(r.uri.split(",")[1]);i&&i(n)}else X.LoadFile(e.rootUrl+r.uri,i,void 0,void 0,!1,n=>{n&&s&&s(n.status+" "+n.statusText)})}static LoadMaterialAsync(e,t,i,s){const r=e.materials[t];if(!r.technique){s&&s("No technique found.");return}const n=e.techniques[r.technique];if(!n){e.scene._blockEntityCollection=!!e.assetContainer;const A=new fe(t,e.scene);A._parentContainer=e.assetContainer,e.scene._blockEntityCollection=!1,A.diffuseColor=new K(.5,.5,.5),A.sideOrientation=ee.CounterClockWiseSideOrientation,i(A);return}const o=e.programs[n.program],l=n.states,h=xt.ShadersStore[o.vertexShader+"VertexShader"],c=xt.ShadersStore[o.fragmentShader+"PixelShader"];let u="",d="";const f=new cE(h),p=new cE(c),_={},g=[],T=[],E=[];for(const A in n.uniforms){const R=n.uniforms[A],P=n.parameters[R];if(_[A]=P,P.semantic&&!P.node&&!P.source){const L=RC.indexOf(P.semantic);L!==-1?(g.push(IC[L]),delete _[A]):g.push(A)}else P.type===Rr.SAMPLER_2D?E.push(A):g.push(A)}for(const A in n.attributes){const R=n.attributes[A],P=n.parameters[R];if(P.semantic){const L=uE(P);L&&T.push(L)}}for(;!f.isEnd()&&f.getNextToken();){if(f.currentToken!==oo.IDENTIFIER){u+=f.currentString;continue}let R=!1;for(const P in n.attributes){const L=n.attributes[P],O=n.parameters[L];if(f.currentIdentifier===P&&O.semantic){u+=uE(O),R=!0;break}}R||(u+=pE(f,n,_))}for(;!p.isEnd()&&p.getNextToken();){if(p.currentToken!==oo.IDENTIFIER){d+=p.currentString;continue}d+=pE(p,n,_)}const S={vertex:o.vertexShader+t,fragment:o.fragmentShader+t},v={attributes:T,uniforms:g,samplers:E,needAlphaBlending:l&&l.enable&&l.enable.indexOf(3042)!==-1};xt.ShadersStore[o.vertexShader+t+"VertexShader"]=u,xt.ShadersStore[o.fragmentShader+t+"PixelShader"]=d;const y=new Dr(t,e.scene,S,v);if(y.onError=J3(o,y,s),y.onCompiled=ek(e,y,n,r,_,i),y.sideOrientation=ee.CounterClockWiseSideOrientation,l&&l.functions){const A=l.functions;A.cullFace&&A.cullFace[0]!==G_.BACK&&(y.backFaceCulling=!1);const R=A.blendFuncSeparate;R&&(R[0]===Vi.SRC_ALPHA&&R[1]===Vi.ONE_MINUS_SRC_ALPHA&&R[2]===Vi.ONE&&R[3]===Vi.ONE?y.alphaMode=H.ALPHA_COMBINE:R[0]===Vi.ONE&&R[1]===Vi.ONE&&R[2]===Vi.ZERO&&R[3]===Vi.ONE?y.alphaMode=H.ALPHA_ONEONE:R[0]===Vi.SRC_ALPHA&&R[1]===Vi.ONE&&R[2]===Vi.ZERO&&R[3]===Vi.ONE?y.alphaMode=H.ALPHA_ADD:R[0]===Vi.ZERO&&R[1]===Vi.ONE_MINUS_SRC_COLOR&&R[2]===Vi.ONE&&R[3]===Vi.ONE?y.alphaMode=H.ALPHA_SUBTRACT:R[0]===Vi.DST_COLOR&&R[1]===Vi.ZERO&&R[2]===Vi.ONE&&R[3]===Vi.ONE?y.alphaMode=H.ALPHA_MULTIPLY:R[0]===Vi.SRC_ALPHA&&R[1]===Vi.ONE_MINUS_SRC_COLOR&&R[2]===Vi.ONE&&R[3]===Vi.ONE&&(y.alphaMode=H.ALPHA_MAXIMIZED))}}}let Ic=class W_{static RegisterExtension(e){if(W_.Extensions[e.name]){X.Error('Tool with the same name "'+e.name+'" already exists');return}W_.Extensions[e.name]=e}dispose(){}_importMeshAsync(e,t,i,s,r,n,o,l){return t.useRightHandedSystem=!0,Hs.LoadRuntimeAsync(t,i,s,h=>{h.assetContainer=r,h.importOnlyMeshes=!0,e===""?h.importMeshesNames=[]:typeof e=="string"?h.importMeshesNames=[e]:e&&!(e instanceof Array)?h.importMeshesNames=[e]:(h.importMeshesNames=[],X.Warn("Argument meshesNames must be of type string or string[]")),this._createNodes(h);const c=[],u=[];for(const d in h.nodes){const f=h.nodes[d];f.babylonNode instanceof gt&&c.push(f.babylonNode)}for(const d in h.skins){const f=h.skins[d];f.babylonSkeleton instanceof So&&u.push(f.babylonSkeleton)}this._loadBuffersAsync(h,()=>{this._loadShadersAsync(h,()=>{_E(h),fE(h),!bi.IncrementalLoading&&n&&n(c,u)})}),bi.IncrementalLoading&&n&&n(c,u)},l),!0}importMeshAsync(e,t,i,s,r,n){return new Promise((o,l)=>{this._importMeshAsync(e,t,s,r,i,(h,c)=>{o({meshes:h,particleSystems:[],skeletons:c,animationGroups:[],lights:[],transformNodes:[],geometries:[],spriteManagers:[]})},n,h=>{l(new Error(h))})})}_loadAsync(e,t,i,s,r,n){e.useRightHandedSystem=!0,Hs.LoadRuntimeAsync(e,t,i,o=>{Hs.LoadRuntimeExtensionsAsync(o,()=>{this._createNodes(o),this._loadBuffersAsync(o,()=>{this._loadShadersAsync(o,()=>{_E(o),fE(o),bi.IncrementalLoading||s()})}),bi.IncrementalLoading&&s()},n)},n)}loadAsync(e,t,i,s){return new Promise((r,n)=>{this._loadAsync(e,t,i,()=>{r()},s,o=>{n(new Error(o))})})}_loadShadersAsync(e,t){let i=!1;const s=(r,n)=>{Hs.LoadShaderStringAsync(e,r,o=>{o instanceof ArrayBuffer||(e.loadedShaderCount++,o&&(xt.ShadersStore[r+(n.type===k_.VERTEX?"VertexShader":"PixelShader")]=o),e.loadedShaderCount===e.shaderscount&&t())},()=>{X.Error("Error when loading shader program named "+r+" located at "+n.uri)})};for(const r in e.shaders){i=!0;const n=e.shaders[r];n?s.bind(this,r,n)():X.Error("No shader named: "+r)}i||t()}_loadBuffersAsync(e,t){let i=!1;const s=(r,n)=>{Hs.LoadBufferAsync(e,r,o=>{e.loadedBufferCount++,o&&(o.byteLength!=e.buffers[r].byteLength&&X.Error("Buffer named "+r+" is length "+o.byteLength+". Expected: "+n.byteLength),e.loadedBufferViews[r]=o),e.loadedBufferCount===e.buffersCount&&t()},()=>{X.Error("Error when loading buffer named "+r+" located at "+n.uri)})};for(const r in e.buffers){i=!0;const n=e.buffers[r];n?s.bind(this,r,n)():X.Error("No buffer named: "+r)}i||t()}_createNodes(e){let t=e.currentScene;if(t)for(let i=0;in.loadRuntimeAsync(e,t,i,s,r),()=>{setTimeout(()=>{s&&s(Ra.CreateRuntime(t.json,e,i))})})}static LoadRuntimeExtensionsAsync(e,t,i){Hs._ApplyExtensions(s=>s.loadRuntimeExtensionsAsync(e,t,i),()=>{setTimeout(()=>{t()})})}static LoadBufferAsync(e,t,i,s,r){Hs._ApplyExtensions(n=>n.loadBufferAsync(e,t,i,s,r),()=>{Ra.LoadBufferAsync(e,t,i,s,r)})}static LoadTextureAsync(e,t,i,s){Hs._LoadTextureBufferAsync(e,t,r=>{r&&Hs._CreateTextureAsync(e,t,r,i,s)},s)}static LoadShaderStringAsync(e,t,i,s){Hs._ApplyExtensions(r=>r.loadShaderStringAsync(e,t,i,s),()=>{Ra.LoadShaderStringAsync(e,t,i,s)})}static LoadMaterialAsync(e,t,i,s){Hs._ApplyExtensions(r=>r.loadMaterialAsync(e,t,i,s),()=>{Ra.LoadMaterialAsync(e,t,i,s)})}static _LoadTextureBufferAsync(e,t,i,s){Hs._ApplyExtensions(r=>r.loadTextureBufferAsync(e,t,i,s),()=>{Ra.LoadTextureBufferAsync(e,t,i,s)})}static _CreateTextureAsync(e,t,i,s,r){Hs._ApplyExtensions(n=>n.createTextureAsync(e,t,i,s,r),()=>{Ra.CreateTextureAsync(e,t,i,s)})}static _ApplyExtensions(e,t){for(const i in Ic.Extensions){const s=Ic.Extensions[i];if(e(s))return}t()}}bi._CreateGLTF1Loader=()=>new Ic;const tk="binary_glTF";class ik extends Hs{constructor(){super("KHR_binary_glTF")}loadRuntimeAsync(e,t,i,s){const r=t.json.extensionsUsed;return!r||r.indexOf(this.name)===-1||!t.bin?!1:(this._bin=t.bin,s(Ra.CreateRuntime(t.json,e,i)),!0)}loadBufferAsync(e,t,i,s){return e.extensionsUsed.indexOf(this.name)===-1||t!==tk?!1:(this._bin.readAsync(0,this._bin.byteLength).then(i,r=>s(r.message)),!0)}loadTextureBufferAsync(e,t,i){const s=e.textures[t],r=e.images[s.source];if(!r.extensions||!(this.name in r.extensions))return!1;const n=r.extensions[this.name],o=e.bufferViews[n.bufferView],l=Es.GetBufferFromBufferView(e,o,0,o.byteLength,ao.UNSIGNED_BYTE);return i(l),!0}loadShaderStringAsync(e,t,i){const s=e.shaders[t];if(!s.extensions||!(this.name in s.extensions))return!1;const r=s.extensions[this.name],n=e.bufferViews[r.bufferView],o=Es.GetBufferFromBufferView(e,n,0,n.byteLength,ao.UNSIGNED_BYTE);return setTimeout(()=>{const l=Es.DecodeBufferToText(o);i(l)}),!0}}Ic.RegisterExtension(new ik);class sk extends Hs{constructor(){super("KHR_materials_common")}loadRuntimeExtensionsAsync(e){if(!e.extensions)return!1;const t=e.extensions[this.name];if(!t)return!1;const i=t.lights;if(i)for(const s in i){const r=i[s];switch(r.type){case"ambient":{const n=new Xa(r.name,new m(0,1,0),e.scene),o=r.ambient;o&&(n.diffuse=K.FromArray(o.color||[1,1,1]));break}case"point":{const n=new Mo(r.name,new m(10,10,10),e.scene),o=r.point;o&&(n.diffuse=K.FromArray(o.color||[1,1,1]));break}case"directional":{const n=new en(r.name,new m(0,-1,0),e.scene),o=r.directional;o&&(n.diffuse=K.FromArray(o.color||[1,1,1]));break}case"spot":{const n=r.spot;if(n){const o=new ar(r.name,new m(0,10,0),new m(0,-1,0),n.fallOffAngle||Math.PI,n.fallOffExponent||0,e.scene);o.diffuse=K.FromArray(n.color||[1,1,1])}break}default:X.Warn('GLTF Material Common extension: light type "'+r.type+"” not supported");break}}return!1}loadMaterialAsync(e,t,i,s){const r=e.materials[t];if(!r||!r.extensions)return!1;const n=r.extensions[this.name];if(!n)return!1;const o=new fe(t,e.scene);return o.sideOrientation=ee.CounterClockWiseSideOrientation,n.technique==="CONSTANT"&&(o.disableLighting=!0),o.backFaceCulling=n.doubleSided===void 0?!1:!n.doubleSided,o.alpha=n.values.transparency===void 0?1:n.values.transparency,o.specularPower=n.values.shininess===void 0?0:n.values.shininess,typeof n.values.ambient=="string"?this._loadTexture(e,n.values.ambient,o,"ambientTexture",s):o.ambientColor=K.FromArray(n.values.ambient||[0,0,0]),typeof n.values.diffuse=="string"?this._loadTexture(e,n.values.diffuse,o,"diffuseTexture",s):o.diffuseColor=K.FromArray(n.values.diffuse||[0,0,0]),typeof n.values.emission=="string"?this._loadTexture(e,n.values.emission,o,"emissiveTexture",s):o.emissiveColor=K.FromArray(n.values.emission||[0,0,0]),typeof n.values.specular=="string"?this._loadTexture(e,n.values.specular,o,"specularTexture",s):o.specularColor=K.FromArray(n.values.specular||[0,0,0]),!0}_loadTexture(e,t,i,s,r){Ra.LoadTextureBufferAsync(e,t,n=>{Ra.CreateTextureAsync(e,t,n,o=>i[s]=o)},r)}}Ic.RegisterExtension(new sk);function mE(a,e,t,i){return m.FromArray(e,t).scaleInPlace(i)}function rk(a,e,t,i){return Z.FromArray(e,t).scaleInPlace(i)}function nk(a,e,t,i){const s=new Array(a._numMorphTargets);for(let r=0;r({frame:l.frame,inTangent:l.inTangent?l.inTangent[n]:void 0,value:l.value[n],outTangent:l.outTangent?l.outTangent[n]:void 0,interpolation:l.interpolation}))),e._primitiveBabylonMeshes){for(const l of e._primitiveBabylonMeshes)if(l.morphTargetManager){const h=l.morphTargetManager.getTarget(n),c=o.clone();h.animations.push(c),r(h,c)}}}}}const iu={translation:[new o_(j.ANIMATIONTYPE_VECTOR3,"position",mE,()=>3)],rotation:[new o_(j.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",rk,()=>4)],scale:[new o_(j.ANIMATIONTYPE_VECTOR3,"scaling",mE,()=>3)],weights:[new ak(j.ANIMATIONTYPE_FLOAT,"influence",nk,a=>a._numMorphTargets)]};function MC(...a){const e=t=>t&&typeof t=="object";return a.reduce((t,i)=>(Object.keys(i).forEach(s=>{const r=t[s],n=i[s];Array.isArray(r)&&Array.isArray(n)?t[s]=r.concat(...n):e(r)&&e(n)?t[s]=MC(r,n):t[s]=n}),t),{})}class et{static Get(e,t,i){if(!t||i==null||!t[i])throw new Error(`${e}: Failed to find index (${i})`);return t[i]}static TryGet(e,t){return!e||t==null||!e[t]?null:e[t]}static Assign(e){if(e)for(let t=0;te.dispose&&e.dispose()),this._extensions.length=0,this._gltf=null,this._bin=null,this._babylonScene=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions.length=0,this._parent.dispose())}importMeshAsync(e,t,i,s,r,n,o=""){return Promise.resolve().then(()=>{this._babylonScene=t,this._assetContainer=i,this._loadData(s);let l=null;if(e){const h={};if(this._gltf.nodes)for(const u of this._gltf.nodes)u.name&&(h[u.name]=u.index);l=(e instanceof Array?e:[e]).map(u=>{const d=h[u];if(d===void 0)throw new Error(`Failed to find node '${u}'`);return d})}return this._loadAsync(r,o,l,()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]}))})}loadAsync(e,t,i,s,r=""){return Promise.resolve().then(()=>(this._babylonScene=e,this._loadData(t),this._loadAsync(i,r,null,()=>{})))}_loadAsync(e,t,i,s){return Promise.resolve().then(()=>{this._rootUrl=e,this._uniqueRootUrl=!e.startsWith("file:")&&t?e:`${e}${Date.now()}/`,this._fileName=t,this._allMaterialsDirtyRequired=!1,this._loadExtensions(),this._checkExtensions();const r=`${Gr[Gr.LOADING]} => ${Gr[Gr.READY]}`,n=`${Gr[Gr.LOADING]} => ${Gr[Gr.COMPLETE]}`;this._parent._startPerformanceCounter(r),this._parent._startPerformanceCounter(n),this._parent._setState(Gr.LOADING),this._extensionsOnLoading();const o=new Array,l=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials){if(i)o.push(this.loadSceneAsync("/nodes",{nodes:i,index:-1}));else if(this._gltf.scene!=null||this._gltf.scenes&&this._gltf.scenes[0]){const c=et.Get("/scene",this._gltf.scenes,this._gltf.scene||0);o.push(this.loadSceneAsync(`/scenes/${c.index}`,c))}}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let c=0;c{}))}return this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=l:this._babylonScene._forceBlockMaterialDirtyMechanism(l),this._parent.compileMaterials&&o.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&o.push(this._compileShadowGeneratorsAsync()),Promise.all(o).then(()=>(this._rootBabylonMesh&&this._rootBabylonMesh!==this._parent.customRootNode&&this._rootBabylonMesh.setEnabled(!0),this._extensionsOnReady(),this._parent._setState(Gr.READY),this._startAnimations(),s())).then(c=>(this._parent._endPerformanceCounter(r),X.SetImmediate(()=>{this._disposed||Promise.all(this._completePromises).then(()=>{this._parent._endPerformanceCounter(n),this._parent._setState(Gr.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()},u=>{this._parent.onErrorObservable.notifyObservers(u),this._parent.onErrorObservable.clear(),this.dispose()})}),c))}).catch(r=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(r),this._parent.onErrorObservable.clear(),this.dispose()),r})}_loadData(e){if(this._gltf=e.json,this._setupData(),e.bin){const t=this._gltf.buffers;if(t&&t[0]&&!t[0].uri){const i=t[0];(i.byteLengthe.bin.byteLength)&&N.Warn(`Binary buffer length (${i.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else N.Warn("Unexpected BIN chunk")}}_setupData(){if(et.Assign(this._gltf.accessors),et.Assign(this._gltf.animations),et.Assign(this._gltf.buffers),et.Assign(this._gltf.bufferViews),et.Assign(this._gltf.cameras),et.Assign(this._gltf.images),et.Assign(this._gltf.materials),et.Assign(this._gltf.meshes),et.Assign(this._gltf.nodes),et.Assign(this._gltf.samplers),et.Assign(this._gltf.scenes),et.Assign(this._gltf.skins),et.Assign(this._gltf.textures),this._gltf.nodes){const e={};for(const i of this._gltf.nodes)if(i.children)for(const s of i.children)e[s]=i.index;const t=this._createRootNode();for(const i of this._gltf.nodes){const s=e[i.index];i.parent=s===void 0?t:this._gltf.nodes[s]}}}_loadExtensions(){for(const e in Ie._RegisteredExtensions){const t=Ie._RegisteredExtensions[e].factory(this);t.name!==e&&N.Warn(`The name of the glTF loader extension instance does not match the registered name: ${t.name} !== ${e}`),this._extensions.push(t),this._parent.onExtensionLoadedObservable.notifyObservers(t)}this._extensions.sort((e,t)=>(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE)),this._parent.onExtensionLoadedObservable.clear()}_checkExtensions(){if(this._gltf.extensionsRequired){for(const e of this._gltf.extensionsRequired)if(!this._extensions.some(i=>i.name===e&&i.enabled))throw new Error(`Required extension ${e} is not available`)}}_createRootNode(){if(this._parent.customRootNode!==void 0)return this._rootBabylonMesh=this._parent.customRootNode,{_babylonTransformNode:this._rootBabylonMesh===null?void 0:this._rootBabylonMesh,index:-1};this._babylonScene._blockEntityCollection=!!this._assetContainer;const e=new W("__root__",this._babylonScene);this._rootBabylonMesh=e,this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);const t={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case $u.AUTO:{this._babylonScene.useRightHandedSystem||(t.rotation=[0,1,0,0],t.scale=[1,1,-1],Ie._LoadTransform(t,this._rootBabylonMesh));break}case $u.FORCE_RIGHT_HANDED:{this._babylonScene.useRightHandedSystem=!0;break}default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(e),t}loadSceneAsync(e,t){const i=this._extensionsLoadSceneAsync(e,t);if(i)return i;const s=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const r of t.nodes){const n=et.Get(`${e}/nodes/${r}`,this._gltf.nodes,r);s.push(this.loadNodeAsync(`/nodes/${n.index}`,n,o=>{o.parent=this._rootBabylonMesh}))}for(const r of this._postSceneLoadActions)r();return s.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(s).then(()=>{})}_forEachPrimitive(e,t){if(e._primitiveBabylonMeshes)for(const i of e._primitiveBabylonMeshes)t(i)}_getGeometries(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,s=>{const r=s.geometry;r&&e.indexOf(r)===-1&&e.push(r)});return e}_getMeshes(){const e=[];this._rootBabylonMesh instanceof gt&&e.push(this._rootBabylonMesh);const t=this._gltf.nodes;if(t)for(const i of t)this._forEachPrimitive(i,s=>{e.push(s)});return e}_getTransformNodes(){const e=[],t=this._gltf.nodes;if(t)for(const i of t)i._babylonTransformNode&&i._babylonTransformNode.getClassName()==="TransformNode"&&e.push(i._babylonTransformNode),i._babylonTransformNodeForSkin&&e.push(i._babylonTransformNodeForSkin);return e}_getSkeletons(){const e=[],t=this._gltf.skins;if(t)for(const i of t)i._data&&e.push(i._data.babylonSkeleton);return e}_getAnimationGroups(){const e=[],t=this._gltf.animations;if(t)for(const i of t)i._babylonAnimationGroup&&e.push(i._babylonAnimationGroup);return e}_startAnimations(){switch(this._parent.animationStartMode){case kl.NONE:break;case kl.FIRST:{const e=this._getAnimationGroups();e.length!==0&&e[0].start(!0);break}case kl.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:{N.Error(`Invalid animation start mode (${this._parent.animationStartMode})`);return}}}loadNodeAsync(e,t,i=()=>{}){const s=this._extensionsLoadNodeAsync(e,t,i);if(s)return s;if(t._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const r=new Array;this.logOpen(`${e} ${t.name||""}`);const n=o=>{if(Ie.AddPointerMetadata(o,e),Ie._LoadTransform(t,o),t.camera!=null){const l=et.Get(`${e}/camera`,this._gltf.cameras,t.camera);r.push(this.loadCameraAsync(`/cameras/${l.index}`,l,h=>{h.parent=o}))}if(t.children)for(const l of t.children){const h=et.Get(`${e}/children/${l}`,this._gltf.nodes,l);r.push(this.loadNodeAsync(`/nodes/${h.index}`,h,c=>{c.parent=o}))}i(o)};if(t.mesh==null||t.skin!=null){const o=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const l=new Ke(o,this._babylonScene);l._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t.mesh==null?t._babylonTransformNode=l:t._babylonTransformNodeForSkin=l,n(l)}if(t.mesh!=null)if(t.skin==null){const o=et.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);r.push(this._loadMeshAsync(`/meshes/${o.index}`,t,o,n))}else{const o=et.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);r.push(this._loadMeshAsync(`/meshes/${o.index}`,t,o,l=>{const h=t._babylonTransformNodeForSkin;l.metadata=MC(h.metadata,l.metadata||{});const c=et.Get(`${e}/skin`,this._gltf.skins,t.skin);r.push(this._loadSkinAsync(`/skins/${c.index}`,t,c,u=>{this._forEachPrimitive(t,d=>{d.skeleton=u}),this._postSceneLoadActions.push(()=>{if(c.skeleton!=null){const d=et.Get(`/skins/${c.index}/skeleton`,this._gltf.nodes,c.skeleton).parent;t.index===d.index?l.parent=h.parent:l.parent=d._babylonTransformNode}else l.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:h,skinnedNode:l})})}))}))}return this.logClose(),Promise.all(r).then(()=>(this._forEachPrimitive(t,o=>{o.geometry&&o.geometry.useBoundingInfoFromGeometry?o._updateBoundingInfo():o.refreshBoundingInfo(!0,!0)}),t._babylonTransformNode))}_loadMeshAsync(e,t,i,s){const r=i.primitives;if(!r||!r.length)throw new Error(`${e}: Primitives are missing`);r[0].index==null&&et.Assign(r);const n=new Array;this.logOpen(`${e} ${i.name||""}`);const o=t.name||`node${t.index}`;if(r.length===1){const l=i.primitives[0];n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${l.index}`,o,t,i,l,h=>{t._babylonTransformNode=h,t._primitiveBabylonMeshes=[h]}))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new Ke(o,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(const l of r)n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${l.index}`,`${o}_primitive${l.index}`,t,i,l,h=>{h.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(h)}))}return s(t._babylonTransformNode),this.logClose(),Promise.all(n).then(()=>t._babylonTransformNode)}_loadMeshPrimitiveAsync(e,t,i,s,r,n){const o=this._extensionsLoadMeshPrimitiveAsync(e,t,i,s,r,n);if(o)return o;this.logOpen(`${e}`);const l=this._disableInstancedMesh===0&&this._parent.createInstances&&i.skin==null&&!s.primitives[0].targets;let h,c;if(l&&r._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,h=r._instanceData.babylonSourceMesh.createInstance(t),h._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,c=r._instanceData.promise;else{const u=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const d=new W(t,this._babylonScene);d._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,d.overrideMaterialSideOrientation=this._babylonScene.useRightHandedSystem?ee.CounterClockWiseSideOrientation:ee.ClockWiseSideOrientation,this._createMorphTargets(e,i,s,r,d),u.push(this._loadVertexDataAsync(e,r,d).then(p=>this._loadMorphTargetsAsync(e,r,d,p).then(()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,p.applyToMesh(d),p._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})));const f=Ie._GetDrawMode(e,r.mode);if(r.material==null){let p=this._defaultBabylonMaterialData[f];p||(p=this._createDefaultMaterial("__GLTFLoader._default",f),this._parent.onMaterialLoadedObservable.notifyObservers(p),this._defaultBabylonMaterialData[f]=p),d.material=p}else if(!this.parent.skipMaterials){const p=et.Get(`${e}/material`,this._gltf.materials,r.material);u.push(this._loadMaterialAsync(`/materials/${p.index}`,p,d,f,_=>{d.material=_}))}c=Promise.all(u),l&&(r._instanceData={babylonSourceMesh:d,promise:c}),h=d}return Ie.AddPointerMetadata(h,e),this._parent.onMeshLoadedObservable.notifyObservers(h),n(h),this.logClose(),c.then(()=>h)}_loadVertexDataAsync(e,t,i){const s=this._extensionsLoadVertexDataAsync(e,t,i);if(s)return s;const r=t.attributes;if(!r)throw new Error(`${e}: Attributes are missing`);const n=new Array,o=new xs(i.name,this._babylonScene);if(t.indices==null)i.isUnIndexed=!0;else{const h=et.Get(`${e}/indices`,this._gltf.accessors,t.indices);n.push(this._loadIndicesAccessorAsync(`/accessors/${h.index}`,h).then(c=>{o.setIndices(c)}))}const l=(h,c,u)=>{if(r[h]==null)return;i._delayInfo=i._delayInfo||[],i._delayInfo.indexOf(c)===-1&&i._delayInfo.push(c);const d=et.Get(`${e}/attributes/${h}`,this._gltf.accessors,r[h]);n.push(this._loadVertexAccessorAsync(`/accessors/${d.index}`,d,c).then(f=>{if(f.getKind()===C.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!i.skeleton&&d.min&&d.max){const p=V.Vector3[0].copyFromFloats(...d.min),_=V.Vector3[1].copyFromFloats(...d.max);if(d.normalized&&d.componentType!==5126){let g=1;switch(d.componentType){case 5120:g=127;break;case 5121:g=255;break;case 5122:g=32767;break;case 5123:g=65535;break}const T=1/g;p.scaleInPlace(T),_.scaleInPlace(T)}o._boundingInfo=new Pr(p,_),o.useBoundingInfoFromGeometry=!0}o.setVerticesBuffer(f,d.count)})),c==C.MatricesIndicesExtraKind&&(i.numBoneInfluencers=8),u&&u(d)};return l("POSITION",C.PositionKind),l("NORMAL",C.NormalKind),l("TANGENT",C.TangentKind),l("TEXCOORD_0",C.UVKind),l("TEXCOORD_1",C.UV2Kind),l("TEXCOORD_2",C.UV3Kind),l("TEXCOORD_3",C.UV4Kind),l("TEXCOORD_4",C.UV5Kind),l("TEXCOORD_5",C.UV6Kind),l("JOINTS_0",C.MatricesIndicesKind),l("WEIGHTS_0",C.MatricesWeightsKind),l("JOINTS_1",C.MatricesIndicesExtraKind),l("WEIGHTS_1",C.MatricesWeightsExtraKind),l("COLOR_0",C.ColorKind,h=>{h.type==="VEC4"&&(i.hasVertexAlpha=!0)}),Promise.all(n).then(()=>o)}_createMorphTargets(e,t,i,s,r){if(!s.targets)return;if(t._numMorphTargets==null)t._numMorphTargets=s.targets.length;else if(s.targets.length!==t._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);const n=i.extras?i.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,r.morphTargetManager=new ca(this._babylonScene),r.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,r.morphTargetManager.areUpdatesFrozen=!0;for(let o=0;o{n.areUpdatesFrozen=!1})}_loadMorphTargetVertexDataAsync(e,t,i,s){const r=new Array,n=(o,l,h)=>{if(i[o]==null)return;const c=t.getVertexBuffer(l);if(!c)return;const u=et.Get(`${e}/${o}`,this._gltf.accessors,i[o]);r.push(this._loadFloatAccessorAsync(`/accessors/${u.index}`,u).then(d=>{h(c,d)}))};return n("POSITION",C.PositionKind,(o,l)=>{const h=new Float32Array(l.length);o.forEach(l.length,(c,u)=>{h[u]=l[u]+c}),s.setPositions(h)}),n("NORMAL",C.NormalKind,(o,l)=>{const h=new Float32Array(l.length);o.forEach(h.length,(c,u)=>{h[u]=l[u]+c}),s.setNormals(h)}),n("TANGENT",C.TangentKind,(o,l)=>{const h=new Float32Array(l.length/3*4);let c=0;o.forEach(l.length/3*4,(u,d)=>{(d+1)%4!==0&&(h[c]=l[c]+u,c++)}),s.setTangents(h)}),Promise.all(r).then(()=>{})}static _LoadTransform(e,t){if(e.skin!=null)return;let i=m.Zero(),s=Z.Identity(),r=m.One();e.matrix?D.FromArray(e.matrix).decompose(r,s,i):(e.translation&&(i=m.FromArray(e.translation)),e.rotation&&(s=Z.FromArray(e.rotation)),e.scale&&(r=m.FromArray(e.scale))),t.position=i,t.rotationQuaternion=s,t.scaling=r}_loadSkinAsync(e,t,i,s){const r=this._extensionsLoadSkinAsync(e,t,i);if(r)return r;if(i._data)return s(i._data.babylonSkeleton),i._data.promise;const n=`skeleton${i.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const o=new So(i.name||n,n,this._babylonScene);o._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,i,o);const l=this._loadSkinInverseBindMatricesDataAsync(e,i).then(h=>{this._updateBoneMatrices(o,h)});return i._data={babylonSkeleton:o,promise:l},s(o),l}_loadBones(e,t,i){if(t.skeleton==null||this._parent.alwaysComputeSkeletonRootNode){const r=this._findSkeletonRootNode(`${e}/joints`,t.joints);if(r)if(t.skeleton===void 0)t.skeleton=r.index;else{const n=(l,h)=>{for(;h.parent;h=h.parent)if(h.parent===l)return!0;return!1},o=et.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);o!==r&&!n(o,r)&&(N.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=r.index)}else N.Warn(`${e}: Failed to find common root`)}const s={};for(const r of t.joints){const n=et.Get(`${e}/joints/${r}`,this._gltf.nodes,r);this._loadBone(n,t,i,s)}}_findSkeletonRootNode(e,t){if(t.length===0)return null;const i={};for(const r of t){const n=[];let o=et.Get(`${e}/${r}`,this._gltf.nodes,r);for(;o.index!==-1;)n.unshift(o),o=o.parent;i[r]=n}let s=null;for(let r=0;;++r){let n=i[t[0]];if(r>=n.length)return s;const o=n[r];for(let l=1;l=n.length||o!==n[r])return s;s=o}}_loadBone(e,t,i,s){let r=s[e.index];if(r)return r;let n=null;e.index!==t.skeleton&&(e.parent&&e.parent.index!==-1?n=this._loadBone(e.parent,t,i,s):t.skeleton!==void 0&&N.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));const o=t.joints.indexOf(e.index);return r=new Xt(e.name||`joint${e.index}`,i,n,this._getNodeMatrix(e),null,null,o),s[e.index]=r,this._postSceneLoadActions.push(()=>{r.linkTransformNode(e._babylonTransformNode)}),r}_loadSkinInverseBindMatricesDataAsync(e,t){if(t.inverseBindMatrices==null)return Promise.resolve(null);const i=et.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${i.index}`,i)}_updateBoneMatrices(e,t){for(const i of e.bones){const s=D.Identity(),r=i._index;t&&r!==-1&&(D.FromArrayToRef(t,r*16,s),s.invertToRef(s));const n=i.getParent();n&&s.multiplyToRef(n.getAbsoluteInverseBindMatrix(),s),i.updateMatrix(s,!1,!1),i._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?D.FromArray(e.matrix):D.Compose(e.scale?m.FromArray(e.scale):m.One(),e.rotation?Z.FromArray(e.rotation):Z.Identity(),e.translation?m.FromArray(e.translation):m.Zero())}loadCameraAsync(e,t,i=()=>{}){const s=this._extensionsLoadCameraAsync(e,t,i);if(s)return s;const r=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const n=new nr(t.name||`camera${t.index}`,m.Zero(),this._babylonScene,!1);switch(n._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n.ignoreParentScaling=!0,t._babylonCamera=n,n.rotation.set(0,Math.PI,0),t.type){case"perspective":{const o=t.perspective;if(!o)throw new Error(`${e}: Camera perspective properties are missing`);n.fov=o.yfov,n.minZ=o.znear,n.maxZ=o.zfar||0;break}case"orthographic":{if(!t.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);n.mode=Se.ORTHOGRAPHIC_CAMERA,n.orthoLeft=-t.orthographic.xmag,n.orthoRight=t.orthographic.xmag,n.orthoBottom=-t.orthographic.ymag,n.orthoTop=t.orthographic.ymag,n.minZ=t.orthographic.znear,n.maxZ=t.orthographic.zfar;break}default:throw new Error(`${e}: Invalid camera type (${t.type})`)}return Ie.AddPointerMetadata(n,e),this._parent.onCameraLoadedObservable.notifyObservers(n),i(n),this.logClose(),Promise.all(r).then(()=>n)}_loadAnimationsAsync(){const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let i=0;i{r.targetedAnimations.length===0&&r.dispose()}))}return Promise.all(t).then(()=>{})}loadAnimationAsync(e,t){const i=this._extensionsLoadAnimationAsync(e,t);if(i)return i;this._babylonScene._blockEntityCollection=!!this._assetContainer;const s=new ta(t.name||`animation${t.index}`,this._babylonScene);s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=s;const r=new Array;et.Assign(t.channels),et.Assign(t.samplers);for(const n of t.channels)r.push(this._loadAnimationChannelAsync(`${e}/channels/${n.index}`,e,t,n,(o,l)=>{o.animations=o.animations||[],o.animations.push(l),s.addTargetedAnimation(l,o)}));return Promise.all(r).then(()=>(s.normalize(0),s))}_loadAnimationChannelAsync(e,t,i,s,r){const n=this._extensionsLoadAnimationChannelAsync(e,t,i,s,r);if(n)return n;if(s.target.node==null)return Promise.resolve();const o=et.Get(`${e}/target/node`,this._gltf.nodes,s.target.node);if(s.target.path==="weights"&&!o._numMorphTargets||s.target.path!=="weights"&&!o._babylonTransformNode)return Promise.resolve();let l;switch(s.target.path){case"translation":{l=iu.translation;break}case"rotation":{l=iu.rotation;break}case"scale":{l=iu.scale;break}case"weights":{l=iu.weights;break}default:throw new Error(`${e}/target/path: Invalid value (${s.target.path})`)}const h={object:o,info:l};return this._loadAnimationChannelFromTargetInfoAsync(e,t,i,s,h,r)}_loadAnimationChannelFromTargetInfoAsync(e,t,i,s,r,n){const o=this.parent.targetFps,l=1/o,h=et.Get(`${e}/sampler`,i.samplers,s.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${s.sampler}`,h).then(c=>{let u=0;const d=r.object,f=r.info;for(const p of f){const _=p.getStride(d),g=c.input,T=c.output,E=new Array(g.length);let S=0;switch(c.interpolation){case"STEP":{for(let v=0;v0){const v=`${i.name||`animation${i.index}`}_channel${s.index}_${u}`;p.buildAnimations(d,v,o,E,(y,A)=>{++u,n(y,A)})}}})}_loadAnimationSamplerAsync(e,t){if(t._data)return t._data;const i=t.interpolation||"LINEAR";switch(i){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(`${e}/interpolation: Invalid value (${t.interpolation})`)}const s=et.Get(`${e}/input`,this._gltf.accessors,t.input),r=et.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${s.index}`,s),this._loadFloatAccessorAsync(`/accessors/${r.index}`,r)]).then(([n,o])=>({input:n,interpolation:i,output:o})),t._data}loadBufferAsync(e,t,i,s){const r=this._extensionsLoadBufferAsync(e,t,i,s);if(r)return r;if(!t._data)if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);t._data=this._bin.readAsync(0,t.byteLength)}return t._data.then(n=>{try{return new Uint8Array(n.buffer,n.byteOffset+i,s)}catch(o){throw new Error(`${e}: ${o.message}`)}})}loadBufferViewAsync(e,t){const i=this._extensionsLoadBufferViewAsync(e,t);if(i)return i;if(t._data)return t._data;const s=et.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${s.index}`,s,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,t,i){if(t._data)return t._data;const s=Ie._GetNumComponents(e,t.type),r=s*C.GetTypeByteLength(t.componentType),n=s*t.count;if(t.bufferView==null)t._data=Promise.resolve(new i(n));else{const o=et.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${o.index}`,o).then(l=>{if(t.componentType===5126&&!t.normalized&&(!o.byteStride||o.byteStride===r))return Ie._GetTypedArray(e,t.componentType,l,t.byteOffset,n);{const h=new i(n);return C.ForEach(l,t.byteOffset||0,o.byteStride||r,s,t.componentType,h.length,t.normalized||!1,(c,u)=>{h[u]=c}),h}})}if(t.sparse){const o=t.sparse;t._data=t._data.then(l=>{const h=l,c=et.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,o.indices.bufferView),u=et.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,o.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${c.index}`,c),this.loadBufferViewAsync(`/bufferViews/${u.index}`,u)]).then(([d,f])=>{const p=Ie._GetTypedArray(`${e}/sparse/indices`,o.indices.componentType,d,o.indices.byteOffset,o.count),_=s*o.count;let g;if(t.componentType===5126&&!t.normalized)g=Ie._GetTypedArray(`${e}/sparse/values`,t.componentType,f,o.values.byteOffset,_);else{const E=Ie._GetTypedArray(`${e}/sparse/values`,t.componentType,f,o.values.byteOffset,_);g=new i(_),C.ForEach(E,0,r,s,t.componentType,g.length,t.normalized||!1,(S,v)=>{g[v]=S})}let T=0;for(let E=0;EIe._GetTypedArray(e,t.componentType,s,t.byteOffset,t.count))}return t._data}_loadVertexBufferViewAsync(e){if(e._babylonBuffer)return e._babylonBuffer;const t=this._babylonScene.getEngine();return e._babylonBuffer=this.loadBufferViewAsync(`/bufferViews/${e.index}`,e).then(i=>new cs(t,i,!1)),e._babylonBuffer}_loadVertexAccessorAsync(e,t,i){var r;if((r=t._babylonVertexBuffer)!=null&&r[i])return t._babylonVertexBuffer[i];t._babylonVertexBuffer||(t._babylonVertexBuffer={});const s=this._babylonScene.getEngine();if(t.sparse||t.bufferView==null)t._babylonVertexBuffer[i]=this._loadFloatAccessorAsync(e,t).then(n=>new C(s,n,i,!1));else{const n=et.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[i]=this._loadVertexBufferViewAsync(n).then(o=>{const l=Ie._GetNumComponents(e,t.type);return new C(s,o,i,!1,void 0,n.byteStride,void 0,t.byteOffset,l,t.componentType,t.normalized,!0,void 0,!0)})}return t._babylonVertexBuffer[i]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const s=new Array;return t&&(t.baseColorFactor?(i.albedoColor=K.FromArray(t.baseColorFactor),i.alpha=t.baseColorFactor[3]):i.albedoColor=K.White(),i.metallic=t.metallicFactor==null?1:t.metallicFactor,i.roughness=t.roughnessFactor==null?1:t.roughnessFactor,t.baseColorTexture&&s.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,t.baseColorTexture,r=>{r.name=`${i.name} (Base Color)`,i.albedoTexture=r})),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,t.metallicRoughnessTexture,r=>{r.name=`${i.name} (Metallic Roughness)`,i.metallicTexture=r})),i.useMetallnessFromMetallicTextureBlue=!0,i.useRoughnessFromMetallicTextureGreen=!0,i.useRoughnessFromMetallicTextureAlpha=!1)),Promise.all(s).then(()=>{})}_loadMaterialAsync(e,t,i,s,r=()=>{}){const n=this._extensionsLoadMaterialAsync(e,t,i,s,r);if(n)return n;t._data=t._data||{};let o=t._data[s];if(!o){this.logOpen(`${e} ${t.name||""}`);const l=this.createMaterial(e,t,s);o={babylonMaterial:l,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,l)},t._data[s]=o,Ie.AddPointerMetadata(l,e),this._parent.onMaterialLoadedObservable.notifyObservers(l),this.logClose()}return i&&(o.babylonMeshes.push(i),i.onDisposeObservable.addOnce(()=>{const l=o.babylonMeshes.indexOf(i);l!==-1&&o.babylonMeshes.splice(l,1)})),r(o.babylonMaterial),o.promise.then(()=>o.babylonMaterial)}_createDefaultMaterial(e,t){this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new Ae(e,this._babylonScene);return i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,i.fillMode=t,i.enableSpecularAntiAliasing=!0,i.useRadianceOverAlpha=!this._parent.transparencyAsCoverage,i.useSpecularOverAlpha=!this._parent.transparencyAsCoverage,i.transparencyMode=Ae.PBRMATERIAL_OPAQUE,i.metallic=1,i.roughness=1,i}createMaterial(e,t,i){const s=this._extensionsCreateMaterial(e,t,i);if(s)return s;const r=t.name||`material${t.index}`;return this._createDefaultMaterial(r,i)}loadMaterialPropertiesAsync(e,t,i){const s=this._extensionsLoadMaterialPropertiesAsync(e,t,i);if(s)return s;const r=new Array;return r.push(this.loadMaterialBasePropertiesAsync(e,t,i)),t.pbrMetallicRoughness&&r.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,i)),this.loadMaterialAlphaProperties(e,t,i),Promise.all(r).then(()=>{})}loadMaterialBasePropertiesAsync(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.emissiveColor=t.emissiveFactor?K.FromArray(t.emissiveFactor):new K(0,0,0),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),t.normalTexture&&(t.normalTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/normalTexture`,t.normalTexture,r=>{r.name=`${i.name} (Normal)`,i.bumpTexture=r})),i.invertNormalMapX=!this._babylonScene.useRightHandedSystem,i.invertNormalMapY=this._babylonScene.useRightHandedSystem,t.normalTexture.scale!=null&&i.bumpTexture&&(i.bumpTexture.level=t.normalTexture.scale),i.forceIrradianceInFragment=!0),t.occlusionTexture&&(t.occlusionTexture.nonColorData=!0,s.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,t.occlusionTexture,r=>{r.name=`${i.name} (Occlusion)`,i.ambientTexture=r})),i.useAmbientInGrayScale=!0,t.occlusionTexture.strength!=null&&(i.ambientTextureStrength=t.occlusionTexture.strength)),t.emissiveTexture&&s.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,t.emissiveTexture,r=>{r.name=`${i.name} (Emissive)`,i.emissiveTexture=r})),Promise.all(s).then(()=>{})}loadMaterialAlphaProperties(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);switch(t.alphaMode||"OPAQUE"){case"OPAQUE":{i.transparencyMode=Ae.PBRMATERIAL_OPAQUE,i.alpha=1;break}case"MASK":{i.transparencyMode=Ae.PBRMATERIAL_ALPHATEST,i.alphaCutOff=t.alphaCutoff==null?.5:t.alphaCutoff,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0);break}case"BLEND":{i.transparencyMode=Ae.PBRMATERIAL_ALPHABLEND,i.albedoTexture&&(i.albedoTexture.hasAlpha=!0,i.useAlphaFromAlbedoTexture=!0);break}default:throw new Error(`${e}/alphaMode: Invalid value (${t.alphaMode})`)}}loadTextureInfoAsync(e,t,i=()=>{}){const s=this._extensionsLoadTextureInfoAsync(e,t,i);if(s)return s;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const r=et.Get(`${e}/index`,this._gltf.textures,t.index);r._textureInfo=t;const n=this._loadTextureAsync(`/textures/${t.index}`,r,o=>{o.coordinatesIndex=t.texCoord||0,Ie.AddPointerMetadata(o,e),this._parent.onTextureLoadedObservable.notifyObservers(o),i(o)});return this.logClose(),n}_loadTextureAsync(e,t,i=()=>{}){const s=this._extensionsLoadTextureAsync(e,t,i);if(s)return s;this.logOpen(`${e} ${t.name||""}`);const r=t.sampler==null?Ie.DefaultSampler:et.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),n=et.Get(`${e}/source`,this._gltf.images,t.source),o=this._createTextureAsync(e,r,n,i,void 0,!t._textureInfo.nonColorData);return this.logClose(),o}_createTextureAsync(e,t,i,s=()=>{},r,n){const o=this._loadSampler(`/samplers/${t.index}`,t),l=new Array,h=new tu;this._babylonScene._blockEntityCollection=!!this._assetContainer;const c={noMipmap:o.noMipMaps,invertY:!1,samplingMode:o.samplingMode,onLoad:()=>{this._disposed||h.resolve()},onError:(d,f)=>{this._disposed||h.reject(new Error(`${e}: ${f&&f.message?f.message:d||"Failed to load texture"}`))},mimeType:i.mimeType,loaderOptions:r,useSRGBBuffer:!!n&&this._parent.useSRGBBuffers},u=new k(null,this._babylonScene,c);return u._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,l.push(h.promise),l.push(this.loadImageAsync(`/images/${i.index}`,i).then(d=>{const f=i.uri||`${this._fileName}#image${i.index}`,p=`data:${this._uniqueRootUrl}${f}`;u.updateURL(p,d)})),u.wrapU=o.wrapU,u.wrapV=o.wrapV,s(u),Promise.all(l).then(()=>u)}_loadSampler(e,t){return t._data||(t._data={noMipMaps:t.minFilter===9728||t.minFilter===9729,samplingMode:Ie._GetTextureSamplingMode(e,t),wrapU:Ie._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:Ie._GetTextureWrapMode(`${e}/wrapT`,t.wrapT)}),t._data}loadImageAsync(e,t){if(!t._data){if(this.logOpen(`${e} ${t.name||""}`),t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{const i=et.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${i.index}`,i)}this.logClose()}return t._data}loadUriAsync(e,t,i){const s=this._extensionsLoadUriAsync(e,t,i);if(s)return s;if(!Ie._ValidateUri(i))throw new Error(`${e}: '${i}' is invalid`);if(Df(i)){const r=new Uint8Array(td(i));return this.log(`${e}: Decoded ${i.substr(0,64)}... (${r.length} bytes)`),Promise.resolve(r)}return this.log(`${e}: Loading ${i}`),this._parent.preprocessUrlAsync(this._rootUrl+i).then(r=>new Promise((n,o)=>{this._parent._loadFile(this._babylonScene,r,l=>{this._disposed||(this.log(`${e}: Loaded ${i} (${l.byteLength} bytes)`),n(new Uint8Array(l)))},!0,l=>{o(new Iu(`${e}: Failed to load '${i}'${l?": "+l.status+" "+l.statusText:""}`,l))})}))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};const i=e._internalMetadata=e._internalMetadata||{},s=i.gltf=i.gltf||{};(s.pointers=s.pointers||[]).push(t)}static _GetTextureWrapMode(e,t){switch(t=t??10497,t){case 33071:return k.CLAMP_ADDRESSMODE;case 33648:return k.MIRROR_ADDRESSMODE;case 10497:return k.WRAP_ADDRESSMODE;default:return N.Warn(`${e}: Invalid value (${t})`),k.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,t){const i=t.magFilter==null?9729:t.magFilter,s=t.minFilter==null?9987:t.minFilter;if(i===9729)switch(s){case 9728:return k.LINEAR_NEAREST;case 9729:return k.LINEAR_LINEAR;case 9984:return k.LINEAR_NEAREST_MIPNEAREST;case 9985:return k.LINEAR_LINEAR_MIPNEAREST;case 9986:return k.LINEAR_NEAREST_MIPLINEAR;case 9987:return k.LINEAR_LINEAR_MIPLINEAR;default:return N.Warn(`${e}/minFilter: Invalid value (${s})`),k.LINEAR_LINEAR_MIPLINEAR}else switch(i!==9728&&N.Warn(`${e}/magFilter: Invalid value (${i})`),s){case 9728:return k.NEAREST_NEAREST;case 9729:return k.NEAREST_LINEAR;case 9984:return k.NEAREST_NEAREST_MIPNEAREST;case 9985:return k.NEAREST_LINEAR_MIPNEAREST;case 9986:return k.NEAREST_NEAREST_MIPLINEAR;case 9987:return k.NEAREST_LINEAR_MIPLINEAR;default:return N.Warn(`${e}/minFilter: Invalid value (${s})`),k.NEAREST_NEAREST_MIPNEAREST}}static _GetTypedArrayConstructor(e,t){switch(t){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:throw new Error(`${e}: Invalid component type ${t}`)}}static _GetTypedArray(e,t,i,s,r){const n=i.buffer;s=i.byteOffset+(s||0);const o=Ie._GetTypedArrayConstructor(`${e}/componentType`,t),l=C.GetTypeByteLength(t);return s%l!==0?(N.Warn(`${e}: Copying buffer as byte offset (${s}) is not a multiple of component type byte length (${l})`),new o(n.slice(s,s+r*l),0)):new o(n,s,r)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":return 4;case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return X.IsBase64(e)||e.indexOf("..")===-1}static _GetDrawMode(e,t){switch(t==null&&(t=4),t){case 0:return ee.PointListDrawMode;case 1:return ee.LineListDrawMode;case 2:return ee.LineLoopDrawMode;case 3:return ee.LineStripDrawMode;case 4:return ee.TriangleFillMode;case 5:return ee.TriangleStripDrawMode;case 6:return ee.TriangleFanDrawMode}throw new Error(`${e}: Invalid mesh primitive mode (${t})`)}_compileMaterialsAsync(){this._parent._startPerformanceCounter("Compile materials");const e=new Array;if(this._gltf.materials){for(const t of this._gltf.materials)if(t._data)for(const i in t._data){const s=t._data[i];for(const r of s.babylonMeshes){r.computeWorldMatrix(!0);const n=s.babylonMaterial;e.push(n.forceCompilationAsync(r)),e.push(n.forceCompilationAsync(r,{useInstances:!0})),this._parent.useClipPlane&&(e.push(n.forceCompilationAsync(r,{clipPlane:!0})),e.push(n.forceCompilationAsync(r,{clipPlane:!0,useInstances:!0})))}}}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile materials")})}_compileShadowGeneratorsAsync(){this._parent._startPerformanceCounter("Compile shadow generators");const e=new Array,t=this._babylonScene.lights;for(const i of t){const s=i.getShadowGenerator();s&&e.push(s.forceCompilationAsync())}return Promise.all(e).then(()=>{this._parent._endPerformanceCounter("Compile shadow generators")})}_forEachExtensions(e){for(const t of this._extensions)t.enabled&&e(t)}_applyExtensions(e,t,i){for(const s of this._extensions)if(s.enabled){const r=`${s.name}.${t}`,n=e;n._activeLoaderExtensionFunctions=n._activeLoaderExtensionFunctions||{};const o=n._activeLoaderExtensionFunctions;if(!o[r]){o[r]=!0;try{const l=i(s);if(l)return l}finally{delete o[r]}}}return null}_extensionsOnLoading(){this._forEachExtensions(e=>e.onLoading&&e.onLoading())}_extensionsOnReady(){this._forEachExtensions(e=>e.onReady&&e.onReady())}_extensionsLoadSceneAsync(e,t){return this._applyExtensions(t,"loadScene",i=>i.loadSceneAsync&&i.loadSceneAsync(e,t))}_extensionsLoadNodeAsync(e,t,i){return this._applyExtensions(t,"loadNode",s=>s.loadNodeAsync&&s.loadNodeAsync(e,t,i))}_extensionsLoadCameraAsync(e,t,i){return this._applyExtensions(t,"loadCamera",s=>s.loadCameraAsync&&s.loadCameraAsync(e,t,i))}_extensionsLoadVertexDataAsync(e,t,i){return this._applyExtensions(t,"loadVertexData",s=>s._loadVertexDataAsync&&s._loadVertexDataAsync(e,t,i))}_extensionsLoadMeshPrimitiveAsync(e,t,i,s,r,n){return this._applyExtensions(r,"loadMeshPrimitive",o=>o._loadMeshPrimitiveAsync&&o._loadMeshPrimitiveAsync(e,t,i,s,r,n))}_extensionsLoadMaterialAsync(e,t,i,s,r){return this._applyExtensions(t,"loadMaterial",n=>n._loadMaterialAsync&&n._loadMaterialAsync(e,t,i,s,r))}_extensionsCreateMaterial(e,t,i){return this._applyExtensions(t,"createMaterial",s=>s.createMaterial&&s.createMaterial(e,t,i))}_extensionsLoadMaterialPropertiesAsync(e,t,i){return this._applyExtensions(t,"loadMaterialProperties",s=>s.loadMaterialPropertiesAsync&&s.loadMaterialPropertiesAsync(e,t,i))}_extensionsLoadTextureInfoAsync(e,t,i){return this._applyExtensions(t,"loadTextureInfo",s=>s.loadTextureInfoAsync&&s.loadTextureInfoAsync(e,t,i))}_extensionsLoadTextureAsync(e,t,i){return this._applyExtensions(t,"loadTexture",s=>s._loadTextureAsync&&s._loadTextureAsync(e,t,i))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",i=>i.loadAnimationAsync&&i.loadAnimationAsync(e,t))}_extensionsLoadAnimationChannelAsync(e,t,i,s,r){return this._applyExtensions(i,"loadAnimationChannel",n=>n._loadAnimationChannelAsync&&n._loadAnimationChannelAsync(e,t,i,s,r))}_extensionsLoadSkinAsync(e,t,i){return this._applyExtensions(i,"loadSkin",s=>s._loadSkinAsync&&s._loadSkinAsync(e,t,i))}_extensionsLoadUriAsync(e,t,i){return this._applyExtensions(t,"loadUri",s=>s._loadUriAsync&&s._loadUriAsync(e,t,i))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",i=>i.loadBufferViewAsync&&i.loadBufferViewAsync(e,t))}_extensionsLoadBufferAsync(e,t,i,s){return this._applyExtensions(t,"loadBuffer",r=>r.loadBufferAsync&&r.loadBufferAsync(e,t,i,s))}static LoadExtensionAsync(e,t,i,s){if(!t.extensions)return null;const n=t.extensions[i];return n?s(`${e}/extensions/${i}`,n):null}static LoadExtraAsync(e,t,i,s){if(!t.extras)return null;const n=t.extras[i];return n?s(`${e}/extras/${i}`,n):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&this._gltf.extensionsUsed.indexOf(e)!==-1}logOpen(e){this._parent._logOpen(e)}logClose(){this._parent._logClose()}log(e){this._parent._log(e)}startPerformanceCounter(e){this._parent._startPerformanceCounter(e)}endPerformanceCounter(e){this._parent._endPerformanceCounter(e)}}Ie._RegisteredExtensions={};Ie.DefaultSampler={index:-1};bi._CreateGLTF2Loader=a=>new Ie(a);const H_="EXT_lights_image_based";class ok{constructor(e){this.name=H_,this._loader=e,this.enabled=this._loader.isExtensionUsed(H_)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights}}loadSceneAsync(e,t){return Ie.LoadExtensionAsync(e,t,this.name,(i,s)=>{this._loader._allMaterialsDirtyRequired=!0;const r=new Array;r.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${i}`);const n=et.Get(`${i}/light`,this._lights,s.light);return r.push(this._loadLightAsync(`/extensions/${this.name}/lights/${s.light}`,n).then(o=>{this._loader.babylonScene.environmentTexture=o})),this._loader.logClose(),Promise.all(r).then(()=>{})})}_loadLightAsync(e,t){if(!t._loaded){const i=new Array;this._loader.logOpen(`${e}`);const s=new Array(t.specularImages.length);for(let r=0;r{s[r][o]=u})),this._loader.logClose()}}this._loader.logClose(),t._loaded=Promise.all(i).then(()=>{const r=new Dg(this._loader.babylonScene,null,t.specularImageSize);if(r.name=t.name||"environment",t._babylonTexture=r,t.intensity!=null&&(r.level=t.intensity),t.rotation){let h=Z.FromArray(t.rotation);this._loader.babylonScene.useRightHandedSystem||(h=Z.Inverse(h)),D.FromQuaternionToRef(h,r.getReflectionTextureMatrix())}if(!t.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const n=tl.FromArray(t.irradianceCoefficients);n.scaleInPlace(t.intensity),n.convertIrradianceToLambertianRadiance();const o=_a.FromHarmonics(n),l=(s.length-1)/Ee.Log2(t.specularImageSize);return r.updateRGBDAsync(s,o,l)})}return t._loaded.then(()=>t._babylonTexture)}}Ie.RegisterExtension(H_,a=>new ok(a));const X_="EXT_mesh_gpu_instancing";class lk{constructor(e){this.name=X_,this._loader=e,this.enabled=this._loader.isExtensionUsed(X_)}dispose(){this._loader=null}loadNodeAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{this._loader._disableInstancedMesh++;const n=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,i);if(this._loader._disableInstancedMesh--,!t._primitiveBabylonMeshes)return n;const o=new Array;let l=0;const h=c=>{if(r.attributes[c]==null){o.push(Promise.resolve(null));return}const u=et.Get(`${s}/attributes/${c}`,this._loader.gltf.accessors,r.attributes[c]);if(o.push(this._loader._loadFloatAccessorAsync(`/accessors/${u.bufferView}`,u)),l===0)l=u.count;else if(l!==u.count)throw new Error(`${s}/attributes: Instance buffer accessors do not have the same count.`)};return h("TRANSLATION"),h("ROTATION"),h("SCALE"),n.then(c=>Promise.all(o).then(([u,d,f])=>{const p=new Float32Array(l*16);V.Vector3[0].copyFromFloats(0,0,0),V.Quaternion[0].copyFromFloats(0,0,0,1),V.Vector3[1].copyFromFloats(1,1,1);for(let _=0;_new lk(a));const Y_="EXT_meshopt_compression";class hk{constructor(e){this.name=Y_,this.enabled=e.isExtensionUsed(Y_),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,t){return Ie.LoadExtensionAsync(e,t,this.name,(i,s)=>{const r=t;if(r._meshOptData)return r._meshOptData;const n=et.Get(`${e}/buffer`,this._loader.gltf.buffers,s.buffer);return r._meshOptData=this._loader.loadBufferAsync(`/buffers/${n.index}`,n,s.byteOffset||0,s.byteLength).then(o=>Ia.Default.decodeGltfBufferAsync(o,s.count,s.byteStride,s.mode,s.filter)),r._meshOptData})}}Ie.RegisterExtension(Y_,a=>new hk(a));const $_="EXT_texture_webp";class ck{constructor(e){this.name=$_,this._loader=e,this.enabled=e.isExtensionUsed($_)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=t.sampler==null?Ie.DefaultSampler:et.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=et.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,l=>{i(l)},void 0,!t._textureInfo.nonColorData)})}}Ie.RegisterExtension($_,a=>new ck(a));const j_="EXT_texture_avif";class uk{constructor(e){this.name=j_,this._loader=e,this.enabled=e.isExtensionUsed(j_)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=t.sampler==null?Ie.DefaultSampler:et.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=et.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,l=>{i(l)},void 0,!t._textureInfo.nonColorData)})}}Ie.RegisterExtension(j_,a=>new uk(a));const K_="KHR_draco_mesh_compression";class dk{constructor(e){this.name=K_,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=ir.DecoderAvailable&&this._loader.isExtensionUsed(K_)}dispose(){delete this.dracoCompression,this._loader=null}_loadVertexDataAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{if(t.mode!=null&&t.mode!==4&&t.mode!==5)throw new Error(`${e}: Unsupported mode ${t.mode}`);const n={},o={},l=(c,u)=>{const d=r.attributes[c];if(d!=null&&(i._delayInfo=i._delayInfo||[],i._delayInfo.indexOf(u)===-1&&i._delayInfo.push(u),n[u]=d,this.useNormalizedFlagFromAccessor)){const f=et.TryGet(this._loader.gltf.accessors,t.attributes[c]);f&&(o[u]=f.normalized||!1)}};l("POSITION",C.PositionKind),l("NORMAL",C.NormalKind),l("TANGENT",C.TangentKind),l("TEXCOORD_0",C.UVKind),l("TEXCOORD_1",C.UV2Kind),l("TEXCOORD_2",C.UV3Kind),l("TEXCOORD_3",C.UV4Kind),l("TEXCOORD_4",C.UV5Kind),l("TEXCOORD_5",C.UV6Kind),l("JOINTS_0",C.MatricesIndicesKind),l("WEIGHTS_0",C.MatricesWeightsKind),l("COLOR_0",C.ColorKind);const h=et.Get(s,this._loader.gltf.bufferViews,r.bufferView);return h._dracoBabylonGeometry||(h._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${h.index}`,h).then(c=>(this.dracoCompression||ir.Default)._decodeMeshToGeometryForGltfAsync(i.name,this._loader.babylonScene,c,n,o).catch(d=>{throw new Error(`${e}: ${d.message}`)}))),h._dracoBabylonGeometry})}}Ie.RegisterExtension(K_,a=>new dk(a));const q_="KHR_lights_punctual";class fk{constructor(e){this.name=q_,this._loader=e,this.enabled=this._loader.isExtensionUsed(q_)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,et.Assign(this._lights)}}loadNodeAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>(this._loader._allMaterialsDirtyRequired=!0,this._loader.loadNodeAsync(e,t,n=>{let o;const l=et.Get(s,this._lights,r.light),h=l.name||n.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,l.type){case"directional":{const c=new en(h,m.Backward(),this._loader.babylonScene);c.position.setAll(0),o=c;break}case"point":{o=new Mo(h,m.Zero(),this._loader.babylonScene);break}case"spot":{const c=new ar(h,m.Zero(),m.Backward(),0,1,this._loader.babylonScene);c.angle=(l.spot&&l.spot.outerConeAngle||Math.PI/4)*2,c.innerAngle=(l.spot&&l.spot.innerConeAngle||0)*2,o=c;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${s}: Invalid light type (${l.type})`)}o._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,l._babylonLight=o,o.falloffType=lt.FALLOFF_GLTF,o.diffuse=l.color?K.FromArray(l.color):K.White(),o.intensity=l.intensity==null?1:l.intensity,o.range=l.range==null?Number.MAX_VALUE:l.range,o.parent=n,this._loader._babylonLights.push(o),Ie.AddPointerMetadata(o,s),i(n)})))}}Ie.RegisterExtension(q_,a=>new fk(a));const Z_="KHR_materials_pbrSpecularGlossiness";class pk{constructor(e){this.name=Z_,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(Z_)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loadSpecularGlossinessPropertiesAsync(s,r,i)),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(n).then(()=>{})})}_loadSpecularGlossinessPropertiesAsync(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.metallic=null,i.roughness=null,t.diffuseFactor?(i.albedoColor=K.FromArray(t.diffuseFactor),i.alpha=t.diffuseFactor[3]):i.albedoColor=K.White(),i.reflectivityColor=t.specularFactor?K.FromArray(t.specularFactor):K.White(),i.microSurface=t.glossinessFactor==null?1:t.glossinessFactor,t.diffuseTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,t.diffuseTexture,r=>{r.name=`${i.name} (Diffuse)`,i.albedoTexture=r})),t.specularGlossinessTexture&&(s.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,t.specularGlossinessTexture,r=>{r.name=`${i.name} (Specular Glossiness)`,i.reflectivityTexture=r,i.reflectivityTexture.hasAlpha=!0})),i.useMicroSurfaceFromReflectivityMapAlpha=!0),Promise.all(s).then(()=>{})}}Ie.RegisterExtension(Z_,a=>new pk(a));const Q_="KHR_materials_unlit";class _k{constructor(e){this.name=Q_,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(Q_)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,()=>this._loadUnlitPropertiesAsync(e,t,i))}_loadUnlitPropertiesAsync(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const s=new Array;i.unlit=!0;const r=t.pbrMetallicRoughness;return r&&(r.baseColorFactor?(i.albedoColor=K.FromArray(r.baseColorFactor),i.alpha=r.baseColorFactor[3]):i.albedoColor=K.White(),r.baseColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,r.baseColorTexture,n=>{n.name=`${i.name} (Base Color)`,i.albedoTexture=n}))),t.doubleSided&&(i.backFaceCulling=!1,i.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,t,i),Promise.all(s).then(()=>{})}}Ie.RegisterExtension(Q_,a=>new _k(a));const J_="KHR_materials_clearcoat";class mk{constructor(e){this.name=J_,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(J_)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadClearCoatPropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadClearCoatPropertiesAsync(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.clearCoat.isEnabled=!0,i.clearCoat.useRoughnessFromMainTexture=!1,i.clearCoat.remapF0OnInterfaceChange=!1,t.clearcoatFactor!=null?i.clearCoat.intensity=t.clearcoatFactor:i.clearCoat.intensity=0,t.clearcoatTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,r=>{r.name=`${i.name} (ClearCoat Intensity)`,i.clearCoat.texture=r})),t.clearcoatRoughnessFactor!=null?i.clearCoat.roughness=t.clearcoatRoughnessFactor:i.clearCoat.roughness=0,t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatRoughnessTexture`,t.clearcoatRoughnessTexture,r=>{r.name=`${i.name} (ClearCoat Roughness)`,i.clearCoat.textureRoughness=r}))),t.clearcoatNormalTexture&&(t.clearcoatNormalTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatNormalTexture`,t.clearcoatNormalTexture,r=>{r.name=`${i.name} (ClearCoat Normal)`,i.clearCoat.bumpTexture=r})),i.invertNormalMapX=!i.getScene().useRightHandedSystem,i.invertNormalMapY=i.getScene().useRightHandedSystem,t.clearcoatNormalTexture.scale!=null&&(i.clearCoat.bumpTexture.level=t.clearcoatNormalTexture.scale)),Promise.all(s).then(()=>{})}}Ie.RegisterExtension(J_,a=>new mk(a));const em="KHR_materials_iridescence";class gk{constructor(e){this.name=em,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(em)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIridescencePropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.iridescence.isEnabled=!0,i.iridescence.intensity=t.iridescenceFactor??0,i.iridescence.indexOfRefraction=t.iridescenceIor??t.iridescenceIOR??1.3,i.iridescence.minimumThickness=t.iridescenceThicknessMinimum??100,i.iridescence.maximumThickness=t.iridescenceThicknessMaximum??400,t.iridescenceTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,r=>{r.name=`${i.name} (Iridescence Intensity)`,i.iridescence.texture=r})),t.iridescenceThicknessTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,r=>{r.name=`${i.name} (Iridescence Thickness)`,i.iridescence.thicknessTexture=r})),Promise.all(s).then(()=>{})}}Ie.RegisterExtension(em,a=>new gk(a));const tm="KHR_materials_anisotropy";class xk{constructor(e){this.name=tm,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(tm)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIridescencePropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadIridescencePropertiesAsync(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.anisotropy.isEnabled=!0,i.anisotropy.intensity=t.anisotropyStrength??0,i.anisotropy.angle=t.anisotropyRotation??0,t.anisotropyTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,r=>{r.name=`${i.name} (Anisotropy Intensity)`,i.anisotropy.texture=r})),Promise.all(s).then(()=>{})}}Ie.RegisterExtension(tm,a=>new xk(a));const im="KHR_materials_emissive_strength";class Tk{constructor(e){this.name=im,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(im)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>this._loader.loadMaterialPropertiesAsync(e,t,i).then(()=>{this._loadEmissiveProperties(s,r,i)}))}_loadEmissiveProperties(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);t.emissiveStrength!==void 0&&(i.emissiveIntensity=t.emissiveStrength)}}Ie.RegisterExtension(im,a=>new Tk(a));const sm="KHR_materials_sheen";class Ek{constructor(e){this.name=sm,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(sm)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadSheenPropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadSheenPropertiesAsync(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const s=new Array;return i.sheen.isEnabled=!0,i.sheen.intensity=1,t.sheenColorFactor!=null?i.sheen.color=K.FromArray(t.sheenColorFactor):i.sheen.color=K.Black(),t.sheenColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/sheenColorTexture`,t.sheenColorTexture,r=>{r.name=`${i.name} (Sheen Color)`,i.sheen.texture=r})),t.sheenRoughnessFactor!==void 0?i.sheen.roughness=t.sheenRoughnessFactor:i.sheen.roughness=0,t.sheenRoughnessTexture&&(t.sheenRoughnessTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/sheenRoughnessTexture`,t.sheenRoughnessTexture,r=>{r.name=`${i.name} (Sheen Roughness)`,i.sheen.textureRoughness=r}))),i.sheen.albedoScaling=!0,i.sheen.useRoughnessFromMainTexture=!1,Promise.all(s).then(()=>{})}}Ie.RegisterExtension(sm,a=>new Ek(a));const rm="KHR_materials_specular";class Sk{constructor(e){this.name=rm,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(rm)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadSpecularPropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadSpecularPropertiesAsync(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const s=new Array;return t.specularFactor!==void 0&&(i.metallicF0Factor=t.specularFactor),t.specularColorFactor!==void 0&&(i.metallicReflectanceColor=K.FromArray(t.specularColorFactor)),t.specularTexture&&(t.specularTexture.nonColorData=!0,s.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,t.specularTexture,r=>{r.name=`${i.name} (Specular F0 Strength)`,i.metallicReflectanceTexture=r,i.useOnlyMetallicFromMetallicReflectanceTexture=!0}))),t.specularColorTexture&&s.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,t.specularColorTexture,r=>{r.name=`${i.name} (Specular F0 Color)`,i.reflectanceTexture=r})),Promise.all(s).then(()=>{})}}Ie.RegisterExtension(rm,a=>new Sk(a));const nm="KHR_materials_ior";class Ip{constructor(e){this.name=nm,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(nm)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadIorPropertiesAsync(s,r,i)),Promise.all(n).then(()=>{})})}_loadIorPropertiesAsync(e,t,i){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);return t.ior!==void 0?i.indexOfRefraction=t.ior:i.indexOfRefraction=Ip._DEFAULT_IOR,Promise.resolve()}}Ip._DEFAULT_IOR=1.5;Ie.RegisterExtension(nm,a=>new Ip(a));const yr="KHR_materials_variants";class to{constructor(e){this.name=yr,this._loader=e,this.enabled=this._loader.isExtensionUsed(yr)}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return to.GetAvailableVariants(e)}static SelectVariant(e,t){const i=this._GetExtensionMetadata(e);if(!i)throw new Error(`Cannot select variant on a glTF mesh that does not have the ${yr} extension`);const s=r=>{const n=i.variants[r];if(n)for(const o of n)o.mesh.material=o.material};if(t instanceof Array)for(const r of t)s(r);else s(t);i.lastSelected=t}selectVariant(e,t){to.SelectVariant(e,t)}static Reset(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot reset on a glTF mesh that does not have the ${yr} extension`);for(const i of t.original)i.mesh.material=i.material;t.lastSelected=null}reset(e){to.Reset(e)}static GetLastSelectedVariant(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot get the last selected variant on a glTF mesh that does not have the ${yr} extension`);return t.lastSelected}getLastSelectedVariant(e){return to.GetLastSelectedVariant(e)}static _GetExtensionMetadata(e){var t,i;return((i=(t=e==null?void 0:e._internalMetadata)==null?void 0:t.gltf)==null?void 0:i[yr])||null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._variants=t.variants}}_loadMeshPrimitiveAsync(e,t,i,s,r,n){return Ie.LoadExtensionAsync(e,r,this.name,(o,l)=>{const h=new Array;return h.push(this._loader._loadMeshPrimitiveAsync(e,t,i,s,r,c=>{if(n(c),c instanceof W){const u=Ie._GetDrawMode(e,r.mode),d=this._loader.rootBabylonMesh,f=d?d._internalMetadata=d._internalMetadata||{}:{},p=f.gltf=f.gltf||{},_=p[yr]=p[yr]||{lastSelected:null,original:[],variants:{}};_.original.push({mesh:c,material:c.material});for(let g=0;g{for(let v=0;v{const P=R;let L=null,O=P;do{if(O=O.parent,!O)return;L=to._GetExtensionMetadata(O)}while(L===null);if(d&&L===to._GetExtensionMetadata(d)){O._internalMetadata={};for(const Y in d._internalMetadata)O._internalMetadata[Y]=d._internalMetadata[Y];O._internalMetadata.gltf=[];for(const Y in d._internalMetadata.gltf)O._internalMetadata.gltf[Y]=d._internalMetadata.gltf[Y];O._internalMetadata.gltf[yr]={lastSelected:null,original:[],variants:{}};for(const Y of L.original)O._internalMetadata.gltf[yr].original.push({mesh:Y.mesh,material:Y.material});for(const Y in L.variants)if(Object.prototype.hasOwnProperty.call(L.variants,Y)){O._internalMetadata.gltf[yr].variants[Y]=[];for(const te of L.variants[Y])O._internalMetadata.gltf[yr].variants[Y].push({mesh:te.mesh,material:te.material})}L=O._internalMetadata.gltf[yr]}for(const Y of L.original)Y.mesh===c&&(Y.mesh=P);for(const Y of L.variants[A.name])Y.mesh===c&&(Y.mesh=P)})}}))}}})),Promise.all(h).then(([c])=>c)})}}Ie.RegisterExtension(yr,a=>new to(a));class Jg{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:H.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,t){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._options={...Jg._GetDefaultOptions(),...e},this._scene=t,this._scene._transmissionHelper=this,this.onErrorObservable=new z,this._scene.onDisposeObservable.addOnce(()=>{this.dispose()}),this._parseScene(),this._setupRenderTargets()}updateOptions(e){if(!Object.keys(e).filter(r=>this._options[r]!==e[r]).length)return;const i={...this._options,...e},s=this._options;this._options=i,i.renderSize!==s.renderSize||i.renderTargetTextureType!==s.renderTargetTextureType||i.generateMipmaps!==s.generateMipmaps||!this._opaqueRenderTarget?this._setupRenderTargets():(this._opaqueRenderTarget.samples=i.samples,this._opaqueRenderTarget.lodGenerationScale=i.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=i.lodGenerationOffset)}getOpaqueTarget(){return this._opaqueRenderTarget}_shouldRenderAsTransmission(e){return e?!!(e instanceof Ae&&e.subSurface.isRefractionEnabled):!1}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),X.SetImmediate(()=>{this._shouldRenderAsTransmission(e.material)?(e.material.refractionTexture=this._opaqueRenderTarget,this._transparentMeshesCache.indexOf(e)===-1&&this._transparentMeshesCache.push(e)):this._opaqueMeshesCache.indexOf(e)===-1&&this._opaqueMeshesCache.push(e)})}_removeMesh(e){e.onMaterialChangedObservable.remove(this._materialObservers[e.uniqueId]),delete this._materialObservers[e.uniqueId];let t=this._transparentMeshesCache.indexOf(e);t!==-1&&this._transparentMeshesCache.splice(t,1),t=this._opaqueMeshesCache.indexOf(e),t!==-1&&this._opaqueMeshesCache.splice(t,1)}_parseScene(){this._scene.meshes.forEach(this._addMesh.bind(this)),this._scene.onNewMeshAddedObservable.add(this._addMesh.bind(this)),this._scene.onMeshRemovedObservable.add(this._removeMesh.bind(this))}_onMeshMaterialChanged(e){const t=this._transparentMeshesCache.indexOf(e),i=this._opaqueMeshesCache.indexOf(e);this._shouldRenderAsTransmission(e.material)?(e.material instanceof Ae&&(e.material.subSurface.refractionTexture=this._opaqueRenderTarget),i!==-1?(this._opaqueMeshesCache.splice(i,1),this._transparentMeshesCache.push(e)):t===-1&&this._transparentMeshesCache.push(e)):t!==-1?(this._transparentMeshesCache.splice(t,1),this._opaqueMeshesCache.push(e)):i===-1&&this._opaqueMeshesCache.push(e)}_isRenderTargetValid(){var e;return((e=this._opaqueRenderTarget)==null?void 0:e.getInternalTexture())!==null}_setupRenderTargets(){var i;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new ai("opaqueSceneTexture",this._options.renderSize,this._scene,this._options.generateMipmaps,void 0,this._options.renderTargetTextureType),this._opaqueRenderTarget.ignoreCameraViewport=!0,this._opaqueRenderTarget.renderList=this._opaqueMeshesCache,this._opaqueRenderTarget.clearColor=((i=this._options.clearColor)==null?void 0:i.clone())??this._scene.clearColor.clone(),this._opaqueRenderTarget.gammaSpace=!1,this._opaqueRenderTarget.lodGenerationScale=this._options.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=this._options.lodGenerationOffset,this._opaqueRenderTarget.samples=this._options.samples,this._opaqueRenderTarget.renderSprites=!0,this._opaqueRenderTarget.renderParticles=!0;let e,t;this._opaqueRenderTarget.onBeforeBindObservable.add(s=>{t=this._scene.environmentIntensity,this._scene.environmentIntensity=1,e=this._scene.imageProcessingConfiguration.applyByPostProcess,this._options.clearColor?s.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(s.clearColor,this._scene.getEngine().useExactSrgbConversions),this._scene.imageProcessingConfiguration._applyByPostProcess=!0}),this._opaqueRenderTarget.onAfterUnbindObservable.add(()=>{this._scene.environmentIntensity=t,this._scene.imageProcessingConfiguration._applyByPostProcess=e}),this._transparentMeshesCache.forEach(s=>{this._shouldRenderAsTransmission(s.material)&&(s.material.refractionTexture=this._opaqueRenderTarget)})}dispose(){this._scene._transmissionHelper=void 0,this._opaqueRenderTarget&&(this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=null),this._transparentMeshesCache=[],this._opaqueMeshesCache=[]}}const am="KHR_materials_transmission";class vk{constructor(e){this.name=am,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed(am),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadTransparentPropertiesAsync(s,t,i,r)),Promise.all(n).then(()=>{})})}_loadTransparentPropertiesAsync(e,t,i,s){var n,o;if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const r=i;if(r.subSurface.isRefractionEnabled=!0,r.subSurface.volumeIndexOfRefraction=1,r.subSurface.useAlbedoToTintRefraction=!0,s.transmissionFactor!==void 0){r.subSurface.refractionIntensity=s.transmissionFactor;const l=r.getScene();r.subSurface.refractionIntensity&&!l._transmissionHelper?new Jg({},r.getScene()):r.subSurface.refractionIntensity&&!((n=l._transmissionHelper)!=null&&n._isRenderTargetValid())&&((o=l._transmissionHelper)==null||o._setupRenderTargets())}else return r.subSurface.refractionIntensity=0,r.subSurface.isRefractionEnabled=!1,Promise.resolve();return r.subSurface.minimumThickness=0,r.subSurface.maximumThickness=0,s.transmissionTexture?(s.transmissionTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,s.transmissionTexture,void 0).then(l=>{r.subSurface.refractionIntensityTexture=l,r.subSurface.useGltfStyleTextures=!0})):Promise.resolve()}}Ie.RegisterExtension(am,a=>new vk(a));const om="KHR_materials_diffuse_transmission";class Ck{constructor(e){this.name=om,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(om),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadTranslucentPropertiesAsync(s,t,i,r)),Promise.all(n).then(()=>{})})}_loadTranslucentPropertiesAsync(e,t,i,s){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);const r=i;if(r.subSurface.isTranslucencyEnabled=!0,r.subSurface.volumeIndexOfRefraction=1,r.subSurface.minimumThickness=0,r.subSurface.maximumThickness=0,r.subSurface.useAlbedoToTintTranslucency=!1,s.diffuseTransmissionFactor!==void 0)r.subSurface.translucencyIntensity=s.diffuseTransmissionFactor;else return r.subSurface.translucencyIntensity=0,r.subSurface.isTranslucencyEnabled=!1,Promise.resolve();const n=new Array;return r.subSurface.useGltfStyleTextures=!0,s.diffuseTransmissionTexture&&(s.diffuseTransmissionTexture.nonColorData=!0,n.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionTexture`,s.diffuseTransmissionTexture).then(o=>{r.subSurface.translucencyIntensityTexture=o}))),s.diffuseTransmissionColorFactor!==void 0?r.subSurface.translucencyColor=K.FromArray(s.diffuseTransmissionColorFactor):r.subSurface.translucencyColor=K.White(),s.diffuseTransmissionColorTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionColorTexture`,s.diffuseTransmissionColorTexture).then(o=>{r.subSurface.translucencyColorTexture=o})),Promise.all(n).then(()=>{})}}Ie.RegisterExtension(om,a=>new Ck(a));const lm="KHR_materials_volume";class bk{constructor(e){this.name=lm,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(lm),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadVolumePropertiesAsync(s,t,i,r)),Promise.all(n).then(()=>{})})}_loadVolumePropertiesAsync(e,t,i,s){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);if(!i.subSurface.isRefractionEnabled&&!i.subSurface.isTranslucencyEnabled||!s.thicknessFactor)return Promise.resolve();i.subSurface.volumeIndexOfRefraction=i.indexOfRefraction;const r=s.attenuationDistance!==void 0?s.attenuationDistance:Number.MAX_VALUE;return i.subSurface.tintColorAtDistance=r,s.attenuationColor!==void 0&&s.attenuationColor.length==3&&i.subSurface.tintColor.copyFromFloats(s.attenuationColor[0],s.attenuationColor[1],s.attenuationColor[2]),i.subSurface.minimumThickness=0,i.subSurface.maximumThickness=s.thicknessFactor,i.subSurface.useThicknessAsDepth=!0,s.thicknessTexture?(s.thicknessTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,s.thicknessTexture).then(n=>{i.subSurface.thicknessTexture=n,i.subSurface.useGltfStyleTextures=!0})):Promise.resolve()}}Ie.RegisterExtension(lm,a=>new bk(a));const hm="KHR_materials_dispersion";class yk{constructor(e){this.name=hm,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(hm)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,i)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,i)),n.push(this._loadDispersionPropertiesAsync(s,t,i,r)),Promise.all(n).then(()=>{})})}_loadDispersionPropertiesAsync(e,t,i,s){if(!(i instanceof Ae))throw new Error(`${e}: Material type not supported`);return!i.subSurface.isRefractionEnabled||!s.dispersion||(i.subSurface.isDispersionEnabled=!0,i.subSurface.dispersion=s.dispersion),Promise.resolve()}}Ie.RegisterExtension(hm,a=>new yk(a));const cm="KHR_mesh_quantization";class Ak{constructor(e){this.name=cm,this.enabled=e.isExtensionUsed(cm)}dispose(){}}Ie.RegisterExtension(cm,a=>new Ak(a));const um="KHR_texture_basisu";class Rk{constructor(e){this.name=um,this._loader=e,this.enabled=e.isExtensionUsed(um)}dispose(){this._loader=null}_loadTextureAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=t.sampler==null?Ie.DefaultSampler:et.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),o=et.Get(`${s}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,o,l=>{i(l)},t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)})}}Ie.RegisterExtension(um,a=>new Rk(a));const dm="KHR_texture_transform";class Ik{constructor(e){this.name=dm,this._loader=e,this.enabled=this._loader.isExtensionUsed(dm)}dispose(){this._loader=null}loadTextureInfoAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>this._loader.loadTextureInfoAsync(e,t,n=>{if(!(n instanceof k))throw new Error(`${s}: Texture type not supported`);r.offset&&(n.uOffset=r.offset[0],n.vOffset=r.offset[1]),n.uRotationCenter=0,n.vRotationCenter=0,r.rotation&&(n.wAng=-r.rotation),r.scale&&(n.uScale=r.scale[0],n.vScale=r.scale[1]),r.texCoord!=null&&(n.coordinatesIndex=r.texCoord),i(n)}))}}Ie.RegisterExtension(dm,a=>new Ik(a));const fm="KHR_xmp_json_ld";class Pk{constructor(e){this.name=fm,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(fm)}dispose(){this._loader=null}onLoading(){var i,s,r;if(this._loader.rootBabylonMesh===null)return;const e=(i=this._loader.gltf.extensions)==null?void 0:i.KHR_xmp_json_ld,t=(r=(s=this._loader.gltf.asset)==null?void 0:s.extensions)==null?void 0:r.KHR_xmp_json_ld;if(e&&t){const n=+t.packet;e.packets&&nnew Pk(a));function Uo(a,e,t,i){return K.FromArray(e,t).scale(i)}function Mk(a,e,t,i){return e[t+3]*i}function pi(a,e,t,i){return e[t]*i}function pm(a,e,t,i){return-e[t]*i}function If(a,e,t,i){return e[t+1]*i}function gE(a,e,t,i){return e[t]*i*2}function Gs(a){return{scale:[new ti(j.ANIMATIONTYPE_FLOAT,`${a}.uScale`,pi,()=>2),new ti(j.ANIMATIONTYPE_FLOAT,`${a}.vScale`,If,()=>2)],offset:[new ti(j.ANIMATIONTYPE_FLOAT,`${a}.uOffset`,pi,()=>2),new ti(j.ANIMATIONTYPE_FLOAT,`${a}.vOffset`,If,()=>2)],rotation:[new ti(j.ANIMATIONTYPE_FLOAT,`${a}.wAng`,pm,()=>1)]}}class va extends Rd{buildAnimations(e,t,i,s,r){r(e._babylonCamera,this._buildAnimation(t,i,s))}}class ti extends Rd{buildAnimations(e,t,i,s,r){for(const n in e._data)r(e._data[n].babylonMaterial,this._buildAnimation(t,i,s))}}class Jc extends Rd{buildAnimations(e,t,i,s,r){r(e._babylonLight,this._buildAnimation(t,i,s))}}const Dk={__array__:{__target__:!0,...iu}},Ok={__array__:{__target__:!0,orthographic:{xmag:[new va(j.ANIMATIONTYPE_FLOAT,"orthoLeft",pm,()=>1),new va(j.ANIMATIONTYPE_FLOAT,"orthoRight",If,()=>1)],ymag:[new va(j.ANIMATIONTYPE_FLOAT,"orthoBottom",pm,()=>1),new va(j.ANIMATIONTYPE_FLOAT,"orthoTop",If,()=>1)],zfar:[new va(j.ANIMATIONTYPE_FLOAT,"maxZ",pi,()=>1)],znear:[new va(j.ANIMATIONTYPE_FLOAT,"minZ",pi,()=>1)]},perspective:{yfov:[new va(j.ANIMATIONTYPE_FLOAT,"fov",pi,()=>1)],zfar:[new va(j.ANIMATIONTYPE_FLOAT,"maxZ",pi,()=>1)],znear:[new va(j.ANIMATIONTYPE_FLOAT,"minZ",pi,()=>1)]}}},Nk={__array__:{__target__:!0,pbrMetallicRoughness:{baseColorFactor:[new ti(j.ANIMATIONTYPE_COLOR3,"albedoColor",Uo,()=>4),new ti(j.ANIMATIONTYPE_FLOAT,"alpha",Mk,()=>4)],metallicFactor:[new ti(j.ANIMATIONTYPE_FLOAT,"metallic",pi,()=>1)],roughnessFactor:[new ti(j.ANIMATIONTYPE_FLOAT,"roughness",pi,()=>1)],baseColorTexture:{extensions:{KHR_texture_transform:Gs("albedoTexture")}},metallicRoughnessTexture:{extensions:{KHR_texture_transform:Gs("metallicTexture")}}},emissiveFactor:[new ti(j.ANIMATIONTYPE_COLOR3,"emissiveColor",Uo,()=>3)],normalTexture:{scale:[new ti(j.ANIMATIONTYPE_FLOAT,"bumpTexture.level",pi,()=>1)],extensions:{KHR_texture_transform:Gs("bumpTexture")}},occlusionTexture:{strength:[new ti(j.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",pi,()=>1)],extensions:{KHR_texture_transform:Gs("ambientTexture")}},emissiveTexture:{extensions:{KHR_texture_transform:Gs("emissiveTexture")}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:[new ti(j.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",pi,()=>1)],anisotropyRotation:[new ti(j.ANIMATIONTYPE_FLOAT,"anisotropy.angle",pi,()=>1)],anisotropyTexture:{extensions:{KHR_texture_transform:Gs("anisotropy.texture")}}},KHR_materials_clearcoat:{clearcoatFactor:[new ti(j.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",pi,()=>1)],clearcoatRoughnessFactor:[new ti(j.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",pi,()=>1)],clearcoatTexture:{extensions:{KHR_texture_transform:Gs("clearCoat.texture")}},clearcoatNormalTexture:{scale:[new ti(j.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",pi,()=>1)],extensions:{KHR_texture_transform:Gs("clearCoat.bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:Gs("clearCoat.textureRoughness")}}},KHR_materials_dispersion:{dispersion:[new ti(j.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",pi,()=>1)]},KHR_materials_emissive_strength:{emissiveStrength:[new ti(j.ANIMATIONTYPE_FLOAT,"emissiveIntensity",pi,()=>1)]},KHR_materials_ior:{ior:[new ti(j.ANIMATIONTYPE_FLOAT,"indexOfRefraction",pi,()=>1)]},KHR_materials_iridescence:{iridescenceFactor:[new ti(j.ANIMATIONTYPE_FLOAT,"iridescence.intensity",pi,()=>1)],iridescenceIor:[new ti(j.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",pi,()=>1)],iridescenceThicknessMinimum:[new ti(j.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",pi,()=>1)],iridescenceThicknessMaximum:[new ti(j.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",pi,()=>1)],iridescenceTexture:{extensions:{KHR_texture_transform:Gs("iridescence.texture")}},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:Gs("iridescence.thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:[new ti(j.ANIMATIONTYPE_COLOR3,"sheen.color",Uo,()=>3)],sheenRoughnessFactor:[new ti(j.ANIMATIONTYPE_FLOAT,"sheen.roughness",pi,()=>1)],sheenColorTexture:{extensions:{KHR_texture_transform:Gs("sheen.texture")}},sheenRoughnessTexture:{extensions:{KHR_texture_transform:Gs("sheen.textureRoughness")}}},KHR_materials_specular:{specularFactor:[new ti(j.ANIMATIONTYPE_FLOAT,"metallicF0Factor",pi,()=>1)],specularColorFactor:[new ti(j.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",Uo,()=>3)],specularTexture:{extensions:{KHR_texture_transform:Gs("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:Gs("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:[new ti(j.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",pi,()=>1)],transmissionTexture:{extensions:{KHR_texture_transform:Gs("subSurface.refractionIntensityTexture")}}},KHR_materials_volume:{attenuationColor:[new ti(j.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",Uo,()=>3)],attenuationDistance:[new ti(j.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",pi,()=>1)],thicknessFactor:[new ti(j.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",pi,()=>1)],thicknessTexture:{extensions:{KHR_texture_transform:Gs("subSurface.thicknessTexture")}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:[new ti(j.ANIMATIONTYPE_FLOAT,"subSurface.translucencyIntensity",pi,()=>1)],diffuseTransmissionTexture:{extensions:{KHR_texture_transform:Gs("subSurface.translucencyIntensityTexture")}},diffuseTransmissionColorFactor:[new ti(j.ANIMATIONTYPE_COLOR3,"subSurface.translucencyColor",Uo,()=>3)],diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:Gs("subSurface.translucencyColorTexture")}}}}}},wk={KHR_lights_punctual:{lights:{__array__:{__target__:!0,color:[new Jc(j.ANIMATIONTYPE_COLOR3,"diffuse",Uo,()=>3)],intensity:[new Jc(j.ANIMATIONTYPE_FLOAT,"intensity",pi,()=>1)],range:[new Jc(j.ANIMATIONTYPE_FLOAT,"range",pi,()=>1)],spot:{innerConeAngle:[new Jc(j.ANIMATIONTYPE_FLOAT,"innerAngle",gE,()=>1)],outerConeAngle:[new Jc(j.ANIMATIONTYPE_FLOAT,"angle",gE,()=>1)]}}}}},Fk={nodes:Dk,materials:Nk,cameras:Ok,extensions:wk};class DC{constructor(e,t){this._gltf=e,this._infoTree=t}convert(e){let t=this._gltf,i=this._infoTree,s;if(!e.startsWith("/"))throw new Error("Path must start with a /");const r=e.split("/");r.shift();for(const n of r){if(i.__array__)i=i.__array__;else if(i=i[n],!i)throw new Error(`Path ${e} is invalid`);if(t===void 0)throw new Error(`Path ${e} is invalid`);t=t[n],i.__target__&&(s=t)}return{object:s,info:i}}}const _m="KHR_animation_pointer";class Lk extends DC{constructor(e){super(e,Fk)}}class Bk{constructor(e){this.name=_m,this._loader=e,this._pathToObjectConverter=new Lk(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(_m)}dispose(){this._loader=null,delete this._pathToObjectConverter}_loadAnimationChannelAsync(e,t,i,s,r){var h;const n=(h=s.target.extensions)==null?void 0:h.KHR_animation_pointer;if(!n||!this._pathToObjectConverter)return null;s.target.path!=="pointer"&&N.Warn(`${e}/target/path: Value (${s.target.path}) must be (pointer) when using the ${this.name} extension`),s.target.node!=null&&N.Warn(`${e}/target/node: Value (${s.target.node}) must not be present when using the ${this.name} extension`);const o=`${e}/extensions/${this.name}`,l=n.pointer;if(!l)throw new Error(`${o}: Pointer is missing`);try{const c=this._pathToObjectConverter.convert(l);return this._loader._loadAnimationChannelFromTargetInfoAsync(e,t,i,s,c,r)}catch{return N.Warn(`${o}/pointer: Invalid pointer (${l}) skipped`),null}}}Ie.RegisterExtension(_m,a=>new Bk(a));const mm="MSFT_audio_emitter";class Uk{constructor(e){this.name=mm,this._loader=e,this.enabled=this._loader.isExtensionUsed(mm)}dispose(){this._loader=null,this._clips=null,this._emitters=null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._clips=t.clips,this._emitters=t.emitters,et.Assign(this._clips),et.Assign(this._emitters)}}loadSceneAsync(e,t){return Ie.LoadExtensionAsync(e,t,this.name,(i,s)=>{const r=new Array;r.push(this._loader.loadSceneAsync(e,t));for(const n of s.emitters){const o=et.Get(`${i}/emitters`,this._emitters,n);if(o.refDistance!=null||o.maxDistance!=null||o.rolloffFactor!=null||o.distanceModel!=null||o.innerAngle!=null||o.outerAngle!=null)throw new Error(`${i}: Direction or Distance properties are not allowed on emitters attached to a scene`);r.push(this._loadEmitterAsync(`${i}/emitters/${o.index}`,o))}return Promise.all(r).then(()=>{})})}loadNodeAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{const n=new Array;return this._loader.loadNodeAsync(s,t,o=>{for(const l of r.emitters){const h=et.Get(`${s}/emitters`,this._emitters,l);n.push(this._loadEmitterAsync(`${s}/emitters/${h.index}`,h).then(()=>{for(const c of h._babylonSounds)c.attachToMesh(o),(h.innerAngle!=null||h.outerAngle!=null)&&(c.setLocalDirectionToMesh(m.Forward()),c.setDirectionalCone(2*X.ToDegrees(h.innerAngle==null?Math.PI:h.innerAngle),2*X.ToDegrees(h.outerAngle==null?Math.PI:h.outerAngle),0))}))}i(o)}).then(o=>Promise.all(n).then(()=>o))})}loadAnimationAsync(e,t){return Ie.LoadExtensionAsync(e,t,this.name,(i,s)=>this._loader.loadAnimationAsync(e,t).then(r=>{const n=new Array;et.Assign(s.events);for(const o of s.events)n.push(this._loadAnimationEventAsync(`${i}/events/${o.index}`,e,t,o,r));return Promise.all(n).then(()=>r)}))}_loadClipAsync(e,t){if(t._objectURL)return t._objectURL;let i;if(t.uri)i=this._loader.loadUriAsync(e,t,t.uri);else{const s=et.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,t.bufferView);i=this._loader.loadBufferViewAsync(`/bufferViews/${s.index}`,s)}return t._objectURL=i.then(s=>URL.createObjectURL(new Blob([s],{type:t.mimeType}))),t._objectURL}_loadEmitterAsync(e,t){if(t._babylonSounds=t._babylonSounds||[],!t._babylonData){const i=new Array,s=t.name||`emitter${t.index}`,r={loop:!1,autoplay:!1,volume:t.volume==null?1:t.volume};for(let o=0;o{const u=t._babylonSounds[o]=new An(s,c,this._loader.babylonScene,null,r);u.refDistance=t.refDistance||1,u.maxDistance=t.maxDistance||256,u.rolloffFactor=t.rolloffFactor||1,u.distanceModel=t.distanceModel||"exponential"}))}const n=Promise.all(i).then(()=>{const o=t.clips.map(h=>h.weight||1),l=new by(t.loop||!1,t._babylonSounds,o);t.innerAngle&&(l.directionalConeInnerAngle=2*X.ToDegrees(t.innerAngle)),t.outerAngle&&(l.directionalConeOuterAngle=2*X.ToDegrees(t.outerAngle)),t.volume&&(l.volume=t.volume),t._babylonData.sound=l});t._babylonData={loaded:n}}return t._babylonData.loaded}_getEventAction(e,t,i,s,r){switch(i){case"play":return n=>{const o=(r||0)+(n-s);t.play(o)};case"stop":return()=>{t.stop()};case"pause":return()=>{t.pause()};default:throw new Error(`${e}: Unsupported action ${i}`)}}_loadAnimationEventAsync(e,t,i,s,r){if(r.targetedAnimations.length==0)return Promise.resolve();const n=r.targetedAnimations[0],o=s.emitter,l=et.Get(`/extensions/${this.name}/emitters`,this._emitters,o);return this._loadEmitterAsync(e,l).then(()=>{const h=l._babylonData.sound;if(h){const c=new Nm(s.time,this._getEventAction(e,h,s.action,s.time,s.startOffset));n.animation.addEvent(c),r.onAnimationGroupEndObservable.add(()=>{h.stop()}),r.onAnimationGroupPauseObservable.add(()=>{h.pause()})}})}}Ie.RegisterExtension(mm,a=>new Uk(a));const gm="MSFT_lod";class Vk{constructor(e){this.name=gm,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new z,this.onMaterialLODsLoadedObservable=new z,this._bufferLODs=new Array,this._nodeIndexLOD=null,this._nodeSignalLODs=new Array,this._nodePromiseLODs=new Array,this._nodeBufferLODs=new Array,this._materialIndexLOD=null,this._materialSignalLODs=new Array,this._materialPromiseLODs=new Array,this._materialBufferLODs=new Array,this._loader=e,this.enabled=this._loader.isExtensionUsed(gm)}dispose(){this._loader=null,this._nodeIndexLOD=null,this._nodeSignalLODs.length=0,this._nodePromiseLODs.length=0,this._nodeBufferLODs.length=0,this._materialIndexLOD=null,this._materialSignalLODs.length=0,this._materialPromiseLODs.length=0,this._materialBufferLODs.length=0,this.onMaterialLODsLoadedObservable.clear(),this.onNodeLODsLoadedObservable.clear()}onReady(){for(let e=0;e{e!==0&&(this._loader.endPerformanceCounter(`Node LOD ${e}`),this._loader.log(`Loaded node LOD ${e}`)),this.onNodeLODsLoadedObservable.notifyObservers(e),e!==this._nodePromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Node LOD ${e+1}`),this._loadBufferLOD(this._nodeBufferLODs,e+1),this._nodeSignalLODs[e]&&this._nodeSignalLODs[e].resolve())});this._loader._completePromises.push(t)}for(let e=0;e{e!==0&&(this._loader.endPerformanceCounter(`Material LOD ${e}`),this._loader.log(`Loaded material LOD ${e}`)),this.onMaterialLODsLoadedObservable.notifyObservers(e),e!==this._materialPromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Material LOD ${e+1}`),this._loadBufferLOD(this._materialBufferLODs,e+1),this._materialSignalLODs[e]&&this._materialSignalLODs[e].resolve())});this._loader._completePromises.push(t)}}loadSceneAsync(e,t){const i=this._loader.loadSceneAsync(e,t);return this._loadBufferLOD(this._bufferLODs,0),i}loadNodeAsync(e,t,i){return Ie.LoadExtensionAsync(e,t,this.name,(s,r)=>{let n;const o=this._getLODs(s,t,this._loader.gltf.nodes,r.ids);this._loader.logOpen(`${s}`);for(let l=0;l{i(d),d.setEnabled(!1)},u=this._loader.loadNodeAsync(`/nodes/${h.index}`,h,c).then(d=>{if(l!==0){const f=o[l-1];f._babylonTransformNode&&(this._disposeTransformNode(f._babylonTransformNode),delete f._babylonTransformNode)}return d.setEnabled(!0),d});this._nodePromiseLODs[l]=this._nodePromiseLODs[l]||[],l===0?n=u:(this._nodeIndexLOD=null,this._nodePromiseLODs[l].push(u))}return this._loader.logClose(),n})}_loadMaterialAsync(e,t,i,s,r){return this._nodeIndexLOD?null:Ie.LoadExtensionAsync(e,t,this.name,(n,o)=>{let l;const h=this._getLODs(n,t,this._loader.gltf.materials,o.ids);this._loader.logOpen(`${n}`);for(let c=0;c{c===0&&r(f)}).then(f=>{if(c!==0){r(f);const p=h[c-1]._data;p[s]&&(this._disposeMaterials([p[s].babylonMaterial]),delete p[s])}return f});this._materialPromiseLODs[c]=this._materialPromiseLODs[c]||[],c===0?l=d:(this._materialIndexLOD=null,this._materialPromiseLODs[c].push(d))}return this._loader.logClose(),l})}_loadUriAsync(e,t,i){if(this._nodeIndexLOD!==null){this._loader.log("deferred");const s=this._nodeIndexLOD-1;return this._nodeSignalLODs[s]=this._nodeSignalLODs[s]||new tu,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then(()=>this._loader.loadUriAsync(e,t,i))}else if(this._materialIndexLOD!==null){this._loader.log("deferred");const s=this._materialIndexLOD-1;return this._materialSignalLODs[s]=this._materialSignalLODs[s]||new tu,this._materialSignalLODs[s].promise.then(()=>this._loader.loadUriAsync(e,t,i))}return null}loadBufferAsync(e,t,i,s){if(this._loader.parent.useRangeRequests&&!t.uri){if(!this._loader.bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);const r=(n,o)=>{const l=i,h=l+s-1;let c=n[o];return c?(c.start=Math.min(c.start,l),c.end=Math.max(c.end,h)):(c={start:l,end:h,loaded:new tu},n[o]=c),c.loaded.promise.then(u=>new Uint8Array(u.buffer,u.byteOffset+i-c.start,s))};return this._loader.log("deferred"),this._nodeIndexLOD!==null?r(this._nodeBufferLODs,this._nodeIndexLOD):this._materialIndexLOD!==null?r(this._materialBufferLODs,this._materialIndexLOD):r(this._bufferLODs,0)}return null}_loadBufferLOD(e,t){const i=e[t];i&&(this._loader.log(`Loading buffer range [${i.start}-${i.end}]`),this._loader.bin.readAsync(i.start,i.end-i.start+1).then(s=>{i.loaded.resolve(s)},s=>{i.loaded.reject(s)}))}_getLODs(e,t,i,s){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const r=[];for(let n=s.length-1;n>=0;n--)if(r.push(et.Get(`${e}/ids/${s[n]}`,i,s[n])),r.length===this.maxLODsToLoad)return r;return r.push(t),r}_disposeTransformNode(e){const t=[],i=e.material;i&&t.push(i);for(const r of e.getChildMeshes())r.material&&t.push(r.material);e.dispose();const s=t.filter(r=>this._loader.babylonScene.meshes.every(n=>n.material!=r));this._disposeMaterials(s)}_disposeMaterials(e){const t={};for(const i of e){for(const s of i.getActiveTextures())t[s.uniqueId]=s;i.dispose()}for(const i in t)for(const s of this._loader.babylonScene.materials)s.hasTexture(t[i])&&delete t[i];for(const i in t)t[i].dispose()}}Ie.RegisterExtension(gm,a=>new Vk(a));const xm="MSFT_minecraftMesh";class kk{constructor(e){this.name=xm,this._loader=e,this.enabled=this._loader.isExtensionUsed(xm)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtraAsync(e,t,this.name,(s,r)=>{if(r){if(!(i instanceof Ae))throw new Error(`${s}: Material type not supported`);const n=this._loader.loadMaterialPropertiesAsync(e,t,i);return i.needAlphaBlending()&&(i.forceDepthWrite=!0,i.separateCullingPass=!0),i.backFaceCulling=i.forceDepthWrite,i.twoSidedLighting=!0,n}return null})}}Ie.RegisterExtension(xm,a=>new kk(a));const Tm="MSFT_sRGBFactors";class Gk{constructor(e){this.name=Tm,this._loader=e,this.enabled=this._loader.isExtensionUsed(Tm)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,i){return Ie.LoadExtraAsync(e,t,this.name,(s,r)=>{if(r){if(!(i instanceof Ae))throw new Error(`${s}: Material type not supported`);const n=this._loader.loadMaterialPropertiesAsync(e,t,i),o=i.getScene().getEngine().useExactSrgbConversions;return i.albedoTexture||i.albedoColor.toLinearSpaceToRef(i.albedoColor,o),i.reflectivityTexture||i.reflectivityColor.toLinearSpaceToRef(i.reflectivityColor,o),n}return null})}}Ie.RegisterExtension(Tm,a=>new Gk(a));const zk={"lifecycle/onStart":Ad.ClassName,"lifecycle/onTick":Rc.ClassName,log:nh.ClassName,"flow/delay":Ed.ClassName,"customEvent/send":Td.ClassName,"customEvent/receive":Ac.ClassName,"flow/sequence":hh.ClassName,"world/get":uh.ClassName,"world/set":xd.ClassName,"flow/doN":oh.ClassName,"variable/get":ch.ClassName,"variable/set":ah.ClassName,"flow/whileLoop":lh.ClassName,"math/random":mh.ClassName,"math/e":xh.ClassName,"math/pi":Th.ClassName,"math/inf":Eh.ClassName,"math/nan":Sh.ClassName,"math/abs":vh.ClassName,"math/sign":Ch.ClassName,"math/trunc":bh.ClassName,"math/floor":yh.ClassName,"math/ceil":Ah.ClassName,"math/fract":Rh.ClassName,"math/neg":Ih.ClassName,"math/add":dh.ClassName,"math/sub":fh.ClassName,"math/mul":ph.ClassName,"math/div":_h.ClassName,"math/rem":Ph.ClassName,"math/min":Mh.ClassName,"math/max":Dh.ClassName,"math/clamp":Oh.ClassName,"math/saturate":Nh.ClassName,"math/mix":wh.ClassName,"math/eq":Fh.ClassName,"math/lt":Lh.ClassName,"math/le":Ap.ClassName,"math/gt":Bh.ClassName,"math/ge":Uh.ClassName,"math/isnan":Vh.ClassName,"math/isinf":Rp.ClassName,"math/rad":kh.ClassName,"math/deg":Gh.ClassName,"math/sin":zh.ClassName,"math/cos":Wh.ClassName,"math/tan":Hh.ClassName,"math/asin":Xh.ClassName,"math/acos":Yh.ClassName,"math/atan":$h.ClassName,"math/atan2":jh.ClassName,"math/sinh":Kh.ClassName,"math/cosh":qh.ClassName,"math/tanh":Zh.ClassName,"math/asinh":Qh.ClassName,"math/acosh":Jh.ClassName,"math/atanh":ec.ClassName,"math/exp":tc.ClassName,"math/log":ic.ClassName,"math/log2":sc.ClassName,"math/log10":rc.ClassName,"math/sqrt":nc.ClassName,"math/cbrt":ac.ClassName,"math/pow":oc.ClassName,"math/length":lc.ClassName,"math/normalize":hc.ClassName,"math/dot":gh.ClassName,"math/cross":cc.ClassName,"math/rotate2d":uc.ClassName,"math/rotate3d":dc.ClassName,"math/transpose":fc.ClassName,"math/determinant":pc.ClassName,"math/inverse":_c.ClassName,"math/matmul":mc.ClassName,"math/not":gc.ClassName,"math/and":xc.ClassName,"math/or":Tc.ClassName,"math/xor":Ec.ClassName,"math/asr":vc.ClassName,"math/lsl":Sc.ClassName,"math/clz":Cc.ClassName,"math/ctz":bc.ClassName,"math/popcnt":yc.ClassName},Wk={float2:"Vector2",float3:"Vector3",float4:"Vector4",float4x4:"Matrix",int:"FlowGraphInteger"};function Em(a,e,t){if(a.type!==void 0){const i=e.types&&e.types[a.type];if(!i)throw new Error(`${t}: Unknown type: ${a.type}`);const s=i.signature;if(!s)throw new Error(`${t}: Type ${a.type} has no signature`);const r=Wk[s];return{value:a.value,className:r}}else return a.value}function Hk(a,e,t){const i={},s=a.configuration??[];for(const r of s)if(r.id==="customEvent"){const n=e.customEvents&&e.customEvents[r.value];if(!n)throw new Error(`/extensions/KHR_interactivity/nodes/${t}: Unknown custom event: ${r.value}`);i.eventId=n.id,i.eventData=n.values.map(o=>o.id)}else if(r.id==="variable"){const n=e.variables&&e.variables[r.value];if(!n)throw new Error(`/extensions/KHR_interactivity/nodes/${t}: Unknown variable: ${r.value}`);i.variableName=n.id}else if(r.id==="path"){const n=r.value;i.path=n}else i[r.id]=Em(r,e,`/extensions/KHR_interactivity/nodes/${t}`);return i}function Xk(a,e,t){const i=zk[e.type];if(!i)throw new Error(`/extensions/KHR_interactivity/nodes/${a}: Unknown block type: ${e.type}`);const s=a.toString(),r=Hk(e,t,s),n=e.metadata;return{className:i,config:r,uniqueId:s,metadata:n,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[]}}function Yk(a){const e={uniqueId:yn(),_userVariables:{},_connectionValues:{}},t=[e],i=[];for(let r=0;rT.name===p);g||(g={uniqueId:yn(),name:p,_connectionType:Zr.Input,connectedPointIds:[]},_.signalInputs.push(g)),g.connectedPointIds.push(d.uniqueId),d.connectedPointIds.push(g.uniqueId)}const h=n.values??[];for(const c of h){const u=c.id,d={uniqueId:yn(),name:u,_connectionType:Zr.Input,connectedPointIds:[]};if(o.dataInputs.push(d),c.value!==void 0){const f=Em(c,a,`/extensions/KHR_interactivity/nodes/${r}`);e._connectionValues[d.uniqueId]=f}else if(c.node!==void 0&&c.socket!==void 0){const f=c.node,p=c.socket,_=i[f];if(!_)throw new Error(`/extensions/KHR_interactivity/nodes/${r}: Could not find node with id ${f} that connects its output with node${r}'s input ${u}`);let g=_.dataOutputs.find(T=>T.name===p);g||(g={uniqueId:yn(),name:p,_connectionType:Zr.Output,connectedPointIds:[]},_.dataOutputs.push(g)),d.connectedPointIds.push(g.uniqueId),g.connectedPointIds.push(d.uniqueId)}else throw new Error(`/extensions/KHR_interactivity/nodes/${r}: Invalid socket ${u} in node ${r}`)}}const s=a.variables??[];for(let r=0;ra._babylonTransformNode.position,set:(a,e)=>{const t=e._babylonTransformNode;t.position=a},getObject(a){return a._babylonTransformNode}}}},Kk={nodes:jk},Sm="KHR_interactivity";class qk{constructor(e){this._loader=e,this.name=Sm,this.enabled=this._loader.isExtensionUsed(Sm),this._pathConverter=new $k(this._loader.gltf)}dispose(){this._loader=null,delete this._pathConverter}onReady(){var r;if(!this._loader.babylonScene||!this._pathConverter)return;const e=this._loader.babylonScene,t=(r=this._loader.gltf.extensions)==null?void 0:r.KHR_interactivity,i=Yk(t),s=new Vl({scene:e});rh.Parse(i,{coordinator:s,pathConverter:this._pathConverter}),s.start()}}Ie.RegisterExtension(Sm,a=>new qk(a));const OC="ExtrasAsMetadata";class Zk{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){const i=e.metadata=e.metadata||{},s=i.gltf=i.gltf||{};s.extras=t.extras}}constructor(e){this.name=OC,this.enabled=!0,this._loader=e}dispose(){this._loader=null}loadNodeAsync(e,t,i){return this._loader.loadNodeAsync(e,t,s=>{this._assignExtras(s,t),i(s)})}loadCameraAsync(e,t,i){return this._loader.loadCameraAsync(e,t,s=>{this._assignExtras(s,t),i(s)})}createMaterial(e,t,i){const s=this._loader.createMaterial(e,t,i);return this._assignExtras(s,t),s}}Ie.RegisterExtension(OC,a=>new Zk(a));class Qk extends gt{constructor(t){super("kotatsu",t);Vt(this,"isLoaded");Vt(this,"root");Vt(this,"tabletop");Vt(this,"tableBase");Vt(this,"futon");Vt(this,"futonPolyester");Vt(this,"heater");Vt(this,"heaterLight");Vt(this,"legTL");Vt(this,"legTR");Vt(this,"legBL");Vt(this,"legBR");Vt(this,"spotLight");this.scene=t,st.ImportMeshAsync("","./models/","kotatsu.glb",t).then(i=>{this.root=i.meshes[0],this.root.scaling=m.One(),this.root.metadata={isShuffled:!1,isNormalMaterial:!1},this.tabletop=new Ke("tabletop"),this.tabletop.metadata={isRotated:!1},this.tabletop.parent=this.root;const s=t.getMeshByName("tabletopBase"),r=t.getMeshByName("tabletopPicture");s.parent=this.tabletop,r.parent=this.tabletop,this.futon=t.getMeshByName("futon"),this.futonPolyester=t.getMeshByName("futonPolyester"),this.tableBase=t.getMeshByName("tableBase"),this.tableBase.parent=this.root,t.getMeshByName("lattice").parent=this.tableBase,t.getMeshByName("tableBasePanel").parent=this.tableBase,this.legTL=t.getMeshByName("legTL"),this.legTR=t.getMeshByName("legTR"),this.legBL=t.getMeshByName("legBL"),this.legBR=t.getMeshByName("legBR"),this.legTL.parent=this.tableBase,this.legTR.parent=this.tableBase,this.legBL.parent=this.tableBase,this.legBR.parent=this.tableBase,this.heater=t.getMeshByName("heater");const n=new fe("heaterMaterial");n.emissiveColor=new K(1,0,0),this.heater.material=n,t.getMeshByName("heaterCase").parent=this.heater,t.getMeshByName("heaterPanel").parent=this.heater,t.getMeshByName("meshLarge").parent=this.heater,t.getMeshByName("meshSmall").parent=this.heater,this.heater.parent=this.tableBase,this.heaterLight=new Mo("heaterLight",new m(0,.15,0),t),this.heaterLight.diffuse=new K(1,0,0),this.heaterLight.intensity=1,this.heaterLight.parent=this.heater,this.spotLight=new ar("spotLight",new m(0,3,.7),new m(0,-1,-.25),Math.PI/3,2,t),this.spotLight.diffuse=new K(.4,.4,.7),this.spotLight.intensity=50,this.spotLight.parent=this.root,this.spotLight.setEnabled(!1),this.root.getChildMeshes().forEach(l=>{l.metadata={initialMaterial:l.material.clone("initialMaterial")}}),this.futonPolyester.setEnabled(!1)}).catch(console.error)}}class Jk extends gt{constructor(t){super("embroidery",t);Vt(this,"root");Vt(this,"take");Vt(this,"oreo");Vt(this,"toreko");Vt(this,"o1");Vt(this,"cha");Vt(this,"no");Vt(this,"ma");Vt(this,"to");Vt(this,"ri");Vt(this,"o2");this.scene=t,st.ImportMeshAsync("","./models/","embroidery.glb",t).then(i=>{this.root=i.meshes[0],this.take=t.getTransformNodeByName("take"),this.oreo=t.getTransformNodeByName("oreo"),this.toreko=t.getTransformNodeByName("toreko"),this.o1=t.getMeshByName("o1"),this.cha=t.getMeshByName("cha"),this.no=t.getMeshByName("no"),this.ma=t.getMeshByName("ma"),this.to=t.getMeshByName("to"),this.ri=t.getMeshByName("ri"),this.o2=t.getMeshByName("o2"),this.root.metadata={isWireframe:!1},this.root.getChildTransformNodes(!0).forEach(r=>{r.metadata={initialPosition:r.position.clone()}}),this.root.scaling=m.Zero()}).catch(console.error)}}const eG="cellPixelShader",tG=`precision highp float;uniform vec4 vEyePosition;uniform vec4 vDiffuseColor;varying vec3 vPositionW; #ifdef NORMAL varying vec3 vNormalW; #endif @@ -14754,7 +14754,7 @@ vRefractionMapTexCoord.x=0.5*(gl_Position.w+gl_Position.x);vRefractionMapTexCoor #include #define CUSTOM_VERTEX_MAIN_END } -`;G.ShadersStore[_z]=mz;class gz extends ui{constructor(){super(),this.BUMP=!1,this.REFLECTION=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.SPECULARTERM=!1,this.LOGARITHMICDEPTH=!1,this.USE_REVERSE_DEPTHBUFFER=!1,this.FRESNELSEPARATE=!1,this.BUMPSUPERIMPOSE=!1,this.BUMPAFFECTSREFLECTION=!1,this.USE_WORLD_COORDINATES=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class oi extends Bs{get hasRenderTargetTextures(){return!0}constructor(e,t,i=new Q(512,512)){super(e,t),this.renderTargetSize=i,this.diffuseColor=new K(1,1,1),this.specularColor=new K(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4,this.windForce=6,this.windDirection=new Q(0,1),this.waveHeight=.4,this.bumpHeight=.4,this._bumpSuperimpose=!1,this._fresnelSeparate=!1,this._bumpAffectsReflection=!1,this.waterColor=new K(.1,.1,.6),this.colorBlendFactor=.2,this.waterColor2=new K(.1,.1,.6),this.colorBlendFactor2=.2,this.waveLength=.1,this.waveSpeed=1,this.waveCount=20,this.disableClipPlane=!1,this._useWorldCoordinatesForWaveDeformation=!1,this._renderTargets=new Xi(16),this._mesh=null,this._reflectionTransform=D.Zero(),this._lastTime=0,this._lastDeltaTime=0,this._createRenderTargets(this.getScene(),i),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._renderTargets.push(this._reflectionRTT),this._renderTargets.push(this._refractionRTT),this._renderTargets),this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()}))}get refractionTexture(){return this._refractionRTT}get reflectionTexture(){return this._reflectionRTT}addToRenderList(e){this._refractionRTT&&this._refractionRTT.renderList&&this._refractionRTT.renderList.push(e),this._reflectionRTT&&this._reflectionRTT.renderList&&this._reflectionRTT.renderList.push(e)}removeFromRenderList(e){if(this._refractionRTT&&this._refractionRTT.renderList){const t=this._refractionRTT.renderList.indexOf(e);t!==-1&&this._refractionRTT.renderList.splice(t,1)}if(this._reflectionRTT&&this._reflectionRTT.renderList){const t=this._reflectionRTT.renderList.indexOf(e);t!==-1&&this._reflectionRTT.renderList.splice(t,1)}}enableRenderTargets(e){const t=e?1:0;this._refractionRTT&&(this._refractionRTT.refreshRate=t),this._reflectionRTT&&(this._reflectionRTT.refreshRate=t)}getRenderList(){return this._refractionRTT?this._refractionRTT.renderList:[]}get renderTargetsEnabled(){return!(this._refractionRTT&&this._refractionRTT.refreshRate===0)}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new gz);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled)){if(this.bumpTexture&&ie.BumpTextureEnabled)if(this.bumpTexture.isReady())r._needUVs=!0,r.BUMP=!0;else return!1;ie.ReflectionTextureEnabled&&(r.REFLECTION=!0)}if(ur(n,o,this,r,!!i),cr(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._areMiscDirty&&(r.FRESNELSEPARATE=this._fresnelSeparate,r.BUMPSUPERIMPOSE=this._bumpSuperimpose,r.BUMPAFFECTSREFLECTION=this._bumpAffectsReflection,r.USE_WORLD_COORDINATES=this._useWorldCoordinatesForWaveDeformation),r._needNormals=Sr(n,e,r,!0,this._maxSimultaneousLights,this._disableLighting),r._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(r),r.IS_REFLECTION_LINEAR=this.reflectionTexture!=null&&!this.reflectionTexture.gammaSpace,r.IS_REFRACTION_LINEAR=this.refractionTexture!=null&&!this.refractionTexture.gammaSpace}if(tr(e,r,!0,!0),this._mesh=e,this._waitingRenderList){for(let l=0;l0&&l.addCPUSkinningFallback(0,e);const h=[C.PositionKind];r.NORMAL&&h.push(C.NormalKind),r.UV1&&h.push(C.UVKind),r.UV2&&h.push(C.UV2Kind),r.VERTEXCOLOR&&h.push(C.ColorKind),Nr(h,e,r,l),hr(h,r);const c="water",u=r.toString(),d=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vNormalInfos","mBones","normalMatrix","logarithmicDepthConstant","reflectionViewProjection","windDirection","waveLength","time","windForce","cameraPosition","bumpHeight","waveHeight","waterColor","waterColor2","colorBlendFactor","colorBlendFactor2","waveSpeed","waveCount"],f=["normalSampler","refractionSampler","reflectionSampler"],p=[];ct&&(ct.PrepareUniforms(d,r),ct.PrepareSamplers(f,r)),qi(d),wr({uniformsNames:d,uniformBuffersNames:p,samplers:f,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(c,{attributes:h,uniformsNames:d,uniformBuffersNames:p,samplers:f,defines:u,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},o),r,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,!0)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n||!this._mesh)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),lr(t,this._activeEffect),this._mustRebind(s,n,i)&&(this.bumpTexture&&ie.BumpTextureEnabled&&(this._activeEffect.setTexture("normalSampler",this.bumpTexture),this._activeEffect.setFloat2("vNormalInfos",this.bumpTexture.coordinatesIndex,this.bumpTexture.level),this._activeEffect.setMatrix("normalMatrix",this.bumpTexture.getTextureMatrix())),zi(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&is(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&Er(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==pe.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Ms(s,t,this._activeEffect),is(r,this._activeEffect,s),ie.ReflectionTextureEnabled&&(this._activeEffect.setTexture("refractionSampler",this._refractionRTT),this._activeEffect.setTexture("reflectionSampler",this._reflectionRTT));const o=this._reflectionTransform.multiply(s.getProjectionMatrix()),l=s.getEngine().getDeltaTime();l!==this._lastDeltaTime&&(this._lastDeltaTime=l,this._lastTime+=this._lastDeltaTime),this._activeEffect.setMatrix("reflectionViewProjection",o),this._activeEffect.setVector2("windDirection",this.windDirection),this._activeEffect.setFloat("waveLength",this.waveLength),this._activeEffect.setFloat("time",this._lastTime/1e5),this._activeEffect.setFloat("windForce",this.windForce),this._activeEffect.setFloat("waveHeight",this.waveHeight),this._activeEffect.setFloat("bumpHeight",this.bumpHeight),this._activeEffect.setColor4("waterColor",this.waterColor,1),this._activeEffect.setFloat("colorBlendFactor",this.colorBlendFactor),this._activeEffect.setColor4("waterColor2",this.waterColor2,1),this._activeEffect.setFloat("colorBlendFactor2",this.colorBlendFactor2),this._activeEffect.setFloat("waveSpeed",this.waveSpeed),this._activeEffect.setFloat("waveCount",this.waveCount),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect),this._afterBind(t,this._activeEffect,i)}_createRenderTargets(e,t){this._refractionRTT=new ai(name+"_refraction",{width:t.x,height:t.y},e,!1,!0),this._refractionRTT.wrapU=H.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.wrapV=H.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.ignoreCameraViewport=!0;let i=!1;this._refractionRTT.onBeforeRenderObservable.add(()=>{i=e.getBoundingBoxRenderer().enabled,e.getBoundingBoxRenderer().enabled=!1}),this._refractionRTT.onAfterRenderObservable.add(()=>{e.getBoundingBoxRenderer().enabled=i}),this._reflectionRTT=new ai(name+"_reflection",{width:t.x,height:t.y},e,!1,!0),this._reflectionRTT.wrapU=H.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.wrapV=H.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.ignoreCameraViewport=!0;let s,r=null,n;const o=D.Zero();this._refractionRTT.onBeforeRender=()=>{if(this._mesh&&(s=this._mesh.isVisible,this._mesh.isVisible=!1),!this.disableClipPlane){r=e.clipPlane;const l=this._mesh?this._mesh.absolutePosition.y:0;e.clipPlane=Qs.FromPositionAndNormal(new m(0,l+.05,0),new m(0,1,0))}},this._refractionRTT.onAfterRender=()=>{this._mesh&&(this._mesh.isVisible=s),this.disableClipPlane||(e.clipPlane=r)},this._reflectionRTT.onBeforeRender=()=>{if(this._mesh&&(s=this._mesh.isVisible,this._mesh.isVisible=!1),!this.disableClipPlane){r=e.clipPlane;const l=this._mesh?this._mesh.absolutePosition.y:0;e.clipPlane=Qs.FromPositionAndNormal(new m(0,l-.05,0),new m(0,-1,0)),D.ReflectionToRef(e.clipPlane,o)}n=e.getViewMatrix(),o.multiplyToRef(n,this._reflectionTransform),e.setTransformMatrix(this._reflectionTransform,e.getProjectionMatrix()),e._mirroredCameraPosition=m.TransformCoordinates(e.activeCamera.position,o)},this._reflectionRTT.onAfterRender=()=>{this._mesh&&(this._mesh.isVisible=s),e.clipPlane=r,e.setTransformMatrix(n,e.getProjectionMatrix()),e._mirroredCameraPosition=null}}getAnimatables(){const e=[];return this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0&&e.push(this.bumpTexture),this._reflectionRTT&&this._reflectionRTT.animations&&this._reflectionRTT.animations.length>0&&e.push(this._reflectionRTT),this._refractionRTT&&this._refractionRTT.animations&&this._refractionRTT.animations.length>0&&e.push(this._refractionRTT),e}getActiveTextures(){const e=super.getActiveTextures();return this._bumpTexture&&e.push(this._bumpTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._bumpTexture===e)}dispose(e){this.bumpTexture&&this.bumpTexture.dispose();let t=this.getScene().customRenderTargets.indexOf(this._refractionRTT);t!=-1&&this.getScene().customRenderTargets.splice(t,1),t=-1,t=this.getScene().customRenderTargets.indexOf(this._reflectionRTT),t!=-1&&this.getScene().customRenderTargets.splice(t,1),this._reflectionRTT&&this._reflectionRTT.dispose(),this._refractionRTT&&this._refractionRTT.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return ce.Clone(()=>new oi(e,this.getScene()),this)}serialize(){const e=super.serialize();if(e.customType="BABYLON.WaterMaterial",e.renderList=[],this._refractionRTT&&this._refractionRTT.renderList)for(let t=0;tnew oi(e.name,t),e,t,i);return s._waitingRenderList=e.renderList,s}static CreateDefaultMesh(e,t){return Jf(e,{width:512,height:512,subdivisions:32,updatable:!1},t)}}x([Ue("bumpTexture")],oi.prototype,"_bumpTexture",void 0);x([q("_markAllSubMeshesAsTexturesDirty")],oi.prototype,"bumpTexture",void 0);x([mt()],oi.prototype,"diffuseColor",void 0);x([mt()],oi.prototype,"specularColor",void 0);x([I()],oi.prototype,"specularPower",void 0);x([I("disableLighting")],oi.prototype,"_disableLighting",void 0);x([q("_markAllSubMeshesAsLightsDirty")],oi.prototype,"disableLighting",void 0);x([I("maxSimultaneousLights")],oi.prototype,"_maxSimultaneousLights",void 0);x([q("_markAllSubMeshesAsLightsDirty")],oi.prototype,"maxSimultaneousLights",void 0);x([I()],oi.prototype,"windForce",void 0);x([Mf()],oi.prototype,"windDirection",void 0);x([I()],oi.prototype,"waveHeight",void 0);x([I()],oi.prototype,"bumpHeight",void 0);x([I("bumpSuperimpose")],oi.prototype,"_bumpSuperimpose",void 0);x([q("_markAllSubMeshesAsMiscDirty")],oi.prototype,"bumpSuperimpose",void 0);x([I("fresnelSeparate")],oi.prototype,"_fresnelSeparate",void 0);x([q("_markAllSubMeshesAsMiscDirty")],oi.prototype,"fresnelSeparate",void 0);x([I("bumpAffectsReflection")],oi.prototype,"_bumpAffectsReflection",void 0);x([q("_markAllSubMeshesAsMiscDirty")],oi.prototype,"bumpAffectsReflection",void 0);x([mt()],oi.prototype,"waterColor",void 0);x([I()],oi.prototype,"colorBlendFactor",void 0);x([mt()],oi.prototype,"waterColor2",void 0);x([I()],oi.prototype,"colorBlendFactor2",void 0);x([I()],oi.prototype,"waveLength",void 0);x([I()],oi.prototype,"waveSpeed",void 0);x([I()],oi.prototype,"waveCount",void 0);x([I()],oi.prototype,"disableClipPlane",void 0);x([I("useWorldCoordinatesForWaveDeformation")],oi.prototype,"_useWorldCoordinatesForWaveDeformation",void 0);x([q("_markAllSubMeshesAsMiscDirty")],oi.prototype,"useWorldCoordinatesForWaveDeformation",void 0);U("BABYLON.WaterMaterial",oi);class xz{constructor(e,t,i,s,r){Vt(this,"clearColorIndex");Vt(this,"fps");Vt(this,"easeOutFunction");Vt(this,"hemiLight");Vt(this,"zoomToMeshIndex");Vt(this,"activeModel");this.kotatsu=e,this.embroidery=t,this.scene=i,this.camera=s,this.engine=r,this.clearColorIndex=0,this.zoomToMeshIndex=0,this.activeModel="embroidery",this.fps=60,this.easeOutFunction=new aS,this.easeOutFunction.setEasingMode(Ys.EASINGMODE_EASEOUT),this.hemiLight=this.scene.getLightByName("hemiLight")}changeClearColor(){const e=["#33BF4F","#DC4829","#FFD000","#2D94CE","#B7BC9B","#000000"];this.scene.clearColor=ge.FromHexString(e[this.clearColorIndex]),this.clearColorIndex===5?(this.hemiLight.intensity=.05,this.kotatsu.spotLight.setEnabled(!0)):(this.hemiLight.intensity=1,this.kotatsu.spotLight.setEnabled(!1)),this.clearColorIndex++,this.clearColorIndex>=e.length&&(this.clearColorIndex=0)}moveCamera(){const e=this.camera,t=Math.random()*Math.PI*2,i=Math.random()*Math.PI,s=Math.random()*3+4;this._animate("moveCameraAlpha",e,"alpha",20,e.alpha,t),this._animate("moveCameraBeta",e,"beta",20,e.beta,i),this._animate("moveCameraRadius",e,"radius",20,e.radius,s)}heat(){const e=this.kotatsu.heaterLight,t=Math.random()*15+30;this._animate("heat",e,"intensity",10,t,1)}dissolve(){let e=!1;this.kotatsu.root.metadata.isShuffled&&Math.random()<.3?(e=!0,this.kotatsu.root.metadata.isShuffled=!1):this.kotatsu.root.metadata.isShuffled=!0,this._moveScaleAndRotate(this.kotatsu.futon,e),this._moveScaleAndRotate(this.kotatsu.tabletop,e),this._moveScaleAndRotate(this.kotatsu.tableBase,e)}rotateTabletop(){const e=this.kotatsu.tabletop,t=e.metadata.isRotated?0:Math.PI*3,i=this.kotatsu.root.metadata.isShuffled?e.scaling.x:1,s=new m(i*1.4,i*1.4,i*1.4),r=new m(i,i,i);e.metadata.isRotated=!e.metadata.isRotated,this._animate("rotation",e,"rotation.y",15,e.rotation.y,t),this._animate("scaling",e,"scaling",15,s,r)}changeMaterials(e=!1){const t=this.kotatsu.root,i=t.getChildMeshes();t.metadata.isNormalMaterial?i.forEach(n=>{n.material=n.metadata.initialMaterial,n.material.wireframe=!1,t.metadata.isNormalMaterial=!1}):i.forEach(n=>{n.material=new Pn("normalMaterial",this.scene),n.material.wireframe=!!e,t.metadata.isNormalMaterial=!0});const s=this.embroidery.root;s.getChildMeshes().forEach(n=>{s.metadata.isWireframe?n.material.wireframe=!1:n.material.wireframe=!0}),s.metadata.isWireframe=!s.metadata.isWireframe}zoomToMesh(){const e=["take","oreo","toreko","o1","cha","no","ma","to","ri","o2"],t=e[this.zoomToMeshIndex];e.forEach(i=>{if(i===t){const s=this.embroidery[i];this._animate("position",s,"position",10,s.position,m.Zero),i.length<4?this._animate("scaling",s,"scaling",10,s.scaling,new m(5,5,5)):this._animate("scaling",s,"scaling",10,s.scaling,new m(2,2,2))}else{const s=this.embroidery[i];this._animate("position",s,"position",10,s.position,this._randomVector3(4)),this._animate("rotation",s,"rotation",10,s.rotation,this._randomVector3),this._animate("scaling",s,"scaling",10,s.scaling,new m(1,1,1))}}),this.zoomToMeshIndex++,this.zoomToMeshIndex>=e.length&&(this.zoomToMeshIndex=0)}bounce(){const e=this[this.activeModel].root;this._animate("bounce",e,"scaling",15,new m(1.2,1.2,1.2),m.One)}reset(){this._moveScaleAndRotate(this.kotatsu.futon,!0),this._moveScaleAndRotate(this.kotatsu.tabletop,!0),this._moveScaleAndRotate(this.kotatsu.tableBase,!0),this.embroidery.root.getChildTransformNodes(!0).forEach(n=>{this._animate("scaling",n,"scaling",10,n.scaling,m.One),this._animate("rotation",n,"rotation",10,n.rotation,m.Zero),this._animate("position",n,"position",10,n.position,n.metadata.initialPosition)}),this.kotatsu.root.getChildMeshes().forEach(n=>{n.material=n.metadata.initialMaterial,n.material.wireframe=!1});const s=this.embroidery.root;s.getChildMeshes().forEach(n=>{n.material.wireframe=!1}),s.metadata.isNormalMaterial=!1,s.metadata.isShuffled=!1,s.metadata.isWireframe=!1}scaleFromVelocity(e){const t=this[this.activeModel].root,i=new m(1+e,1+e,1+e);this._animate("scaleFromVelocity",t,"scaling",10,t.scaling,i)}floatFuton(e){const t=this.kotatsu.tabletop,i=this.kotatsu.tableBase,s=this.kotatsu.futon;typeof e=="number"&&(t.position.y=e/2,i.position.y=-e/2,s.rotation=new m(0,Math.PI*e/2,0))}moveCameraBeta(e){const t=this.camera;if(typeof e=="number")if(e===0)this._animate("cameraBeta",t,"beta",10,t.beta,Math.PI*.25);else{const o=(e-1)*1/2+1;t.beta=Math.PI*o}}changeModel(){this.activeModel=="kotatsu"?(this._animate("scaling",this.embroidery.root,"scaling",20,this.embroidery.root.scaling,m.One),this._animate("scaling",this.kotatsu.root,"scaling",20,this.kotatsu.root.scaling,m.Zero),this.kotatsu.heaterLight.setEnabled(!1),this.activeModel="embroidery"):this.activeModel=="embroidery"&&(this._animate("scaling",this.embroidery.root,"scaling",20,this.embroidery.root.scaling,m.Zero),this._animate("scaling",this.kotatsu.root,"scaling",20,this.kotatsu.root.scaling,m.One),this.kotatsu.heaterLight.setEnabled(!0),this.activeModel="kotatsu")}_animate(e,t,i,s,r,n,o){o=o||this.easeOutFunction,j.CreateAndStartAnimation(e,t,i,this.fps,s,r,n,0,o)}_randomVector3(e=2){return new m(Math.random()*(e+1)-e,Math.random()*(e+1)-e,Math.random()*(e+1)-e)}_moveScaleAndRotate(e,t=!1){const i=t?m.Zero():this._randomVector3(.5),s=t?m.Zero():this._randomVector3(2),r=Math.random()*1.5+.3,n=t?m.One():new m(r,r,r);this._animate("position",e,"position",20,e.position,i),this._animate("rotation",e,"rotation",20,e.rotation,s),this._animate("scaling",e,"scaling",20,e.scaling,n)}}class Hn{constructor(e=!1){this.eventMap={},this.eventsSuspended=e==!0}addListener(e,t,i={}){if(typeof e=="string"&&e.length<1||e instanceof String&&e.length<1||typeof e!="string"&&!(e instanceof String)&&e!==Hn.ANY_EVENT)throw new TypeError("The 'event' parameter must be a string or EventEmitter.ANY_EVENT.");if(typeof t!="function")throw new TypeError("The callback must be a function.");const s=new xE(e,this,t,i);return this.eventMap[e]||(this.eventMap[e]=[]),i.prepend?this.eventMap[e].unshift(s):this.eventMap[e].push(s),s}addOneTimeListener(e,t,i={}){i.remaining=1,this.addListener(e,t,i)}static get ANY_EVENT(){return Symbol.for("Any event")}hasListener(e,t){return e===void 0?this.eventMap[Hn.ANY_EVENT]&&this.eventMap[Hn.ANY_EVENT].length>0?!0:Object.entries(this.eventMap).some(([,i])=>i.length>0):this.eventMap[e]&&this.eventMap[e].length>0?t instanceof xE?this.eventMap[e].filter(s=>s===t).length>0:typeof t=="function"?this.eventMap[e].filter(s=>s.callback===t).length>0:t==null:!1}get eventNames(){return Object.keys(this.eventMap)}getListeners(e){return this.eventMap[e]||[]}suspendEvent(e){this.getListeners(e).forEach(t=>{t.suspended=!0})}unsuspendEvent(e){this.getListeners(e).forEach(t=>{t.suspended=!1})}getListenerCount(e){return this.getListeners(e).length}emit(e,...t){if(typeof e!="string"&&!(e instanceof String))throw new TypeError("The 'event' parameter must be a string.");if(this.eventsSuspended)return;let i=[],s=this.eventMap[Hn.ANY_EVENT]||[];return this.eventMap[e]&&(s=s.concat(this.eventMap[e])),s.forEach(r=>{if(r.suspended)return;let n=[...t];Array.isArray(r.arguments)&&(n=n.concat(r.arguments)),r.remaining>0&&(i.push(r.callback.apply(r.context,n)),r.count++),--r.remaining<1&&r.remove()}),i}removeListener(e,t,i={}){if(e===void 0){this.eventMap={};return}else if(!this.eventMap[e])return;let s=this.eventMap[e].filter(r=>t&&r.callback!==t||i.remaining&&i.remaining!==r.remaining||i.context&&i.context!==r.context);s.length?this.eventMap[e]=s:delete this.eventMap[e]}async waitFor(e,t={}){return t.duration=parseInt(t.duration),(isNaN(t.duration)||t.duration<=0)&&(t.duration=1/0),new Promise((i,s)=>{let r,n=this.addListener(e,()=>{clearTimeout(r),i()},{remaining:1});t.duration!==1/0&&(r=setTimeout(()=>{n.remove(),s("The duration expired before the event was emitted.")},t.duration))})}get eventCount(){return Object.keys(this.eventMap).length}}class xE{constructor(e,t,i,s={}){if(typeof e!="string"&&!(e instanceof String)&&e!==Hn.ANY_EVENT)throw new TypeError("The 'event' parameter must be a string or EventEmitter.ANY_EVENT.");if(!t)throw new ReferenceError("The 'target' parameter is mandatory.");if(typeof i!="function")throw new TypeError("The 'callback' must be a function.");s.arguments!==void 0&&!Array.isArray(s.arguments)&&(s.arguments=[s.arguments]),s=Object.assign({context:t,remaining:1/0,arguments:void 0,duration:1/0},s),s.duration!==1/0&&setTimeout(()=>this.remove(),s.duration),this.arguments=s.arguments,this.callback=i,this.context=s.context,this.count=0,this.event=e,this.remaining=parseInt(s.remaining)>=1?parseInt(s.remaining):1/0,this.suspended=!1,this.target=t}remove(){this.target.removeListener(this.event,this.callback,{context:this.context,remaining:this.remaining})}}/** +`;G.ShadersStore[_z]=mz;class gz extends ui{constructor(){super(),this.BUMP=!1,this.REFLECTION=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.POINTSIZE=!1,this.FOG=!1,this.NORMAL=!1,this.UV1=!1,this.UV2=!1,this.VERTEXCOLOR=!1,this.VERTEXALPHA=!1,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.INSTANCES=!1,this.INSTANCESCOLOR=!1,this.SPECULARTERM=!1,this.LOGARITHMICDEPTH=!1,this.USE_REVERSE_DEPTHBUFFER=!1,this.FRESNELSEPARATE=!1,this.BUMPSUPERIMPOSE=!1,this.BUMPAFFECTSREFLECTION=!1,this.USE_WORLD_COORDINATES=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.EXPOSURE=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.rebuild()}}class oi extends Bs{get hasRenderTargetTextures(){return!0}constructor(e,t,i=new Q(512,512)){super(e,t),this.renderTargetSize=i,this.diffuseColor=new K(1,1,1),this.specularColor=new K(0,0,0),this.specularPower=64,this._disableLighting=!1,this._maxSimultaneousLights=4,this.windForce=6,this.windDirection=new Q(0,1),this.waveHeight=.4,this.bumpHeight=.4,this._bumpSuperimpose=!1,this._fresnelSeparate=!1,this._bumpAffectsReflection=!1,this.waterColor=new K(.1,.1,.6),this.colorBlendFactor=.2,this.waterColor2=new K(.1,.1,.6),this.colorBlendFactor2=.2,this.waveLength=.1,this.waveSpeed=1,this.waveCount=20,this.disableClipPlane=!1,this._useWorldCoordinatesForWaveDeformation=!1,this._renderTargets=new Xi(16),this._mesh=null,this._reflectionTransform=D.Zero(),this._lastTime=0,this._lastDeltaTime=0,this._createRenderTargets(this.getScene(),i),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),this._renderTargets.push(this._reflectionRTT),this._renderTargets.push(this._refractionRTT),this._renderTargets),this._imageProcessingConfiguration=this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add(()=>{this._markAllSubMeshesAsImageProcessingDirty()}))}get refractionTexture(){return this._refractionRTT}get reflectionTexture(){return this._reflectionRTT}addToRenderList(e){this._refractionRTT&&this._refractionRTT.renderList&&this._refractionRTT.renderList.push(e),this._reflectionRTT&&this._reflectionRTT.renderList&&this._reflectionRTT.renderList.push(e)}removeFromRenderList(e){if(this._refractionRTT&&this._refractionRTT.renderList){const t=this._refractionRTT.renderList.indexOf(e);t!==-1&&this._refractionRTT.renderList.splice(t,1)}if(this._reflectionRTT&&this._reflectionRTT.renderList){const t=this._reflectionRTT.renderList.indexOf(e);t!==-1&&this._reflectionRTT.renderList.splice(t,1)}}enableRenderTargets(e){const t=e?1:0;this._refractionRTT&&(this._refractionRTT.refreshRate=t),this._reflectionRTT&&(this._reflectionRTT.refreshRate=t)}getRenderList(){return this._refractionRTT?this._refractionRTT.renderList:[]}get renderTargetsEnabled(){return!(this._refractionRTT&&this._refractionRTT.refreshRate===0)}needAlphaBlending(){return this.alpha<1}needAlphaTesting(){return!1}getAlphaTestTexture(){return null}isReadyForSubMesh(e,t,i){const s=t._drawWrapper;if(this.isFrozen&&s.effect&&s._wasPreviouslyReady&&s._wasPreviouslyUsingInstances===i)return!0;t.materialDefines||(t.materialDefines=new gz);const r=t.materialDefines,n=this.getScene();if(this._isReadyForSubMesh(t))return!0;const o=n.getEngine();if(r._areTexturesDirty&&(r._needUVs=!1,n.texturesEnabled)){if(this.bumpTexture&&ie.BumpTextureEnabled)if(this.bumpTexture.isReady())r._needUVs=!0,r.BUMP=!0;else return!1;ie.ReflectionTextureEnabled&&(r.REFLECTION=!0)}if(ur(n,o,this,r,!!i),cr(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e),r),r._areMiscDirty&&(r.FRESNELSEPARATE=this._fresnelSeparate,r.BUMPSUPERIMPOSE=this._bumpSuperimpose,r.BUMPAFFECTSREFLECTION=this._bumpAffectsReflection,r.USE_WORLD_COORDINATES=this._useWorldCoordinatesForWaveDeformation),r._needNormals=Sr(n,e,r,!0,this._maxSimultaneousLights,this._disableLighting),r._areImageProcessingDirty&&this._imageProcessingConfiguration){if(!this._imageProcessingConfiguration.isReady())return!1;this._imageProcessingConfiguration.prepareDefines(r),r.IS_REFLECTION_LINEAR=this.reflectionTexture!=null&&!this.reflectionTexture.gammaSpace,r.IS_REFRACTION_LINEAR=this.refractionTexture!=null&&!this.refractionTexture.gammaSpace}if(tr(e,r,!0,!0),this._mesh=e,this._waitingRenderList){for(let l=0;l0&&l.addCPUSkinningFallback(0,e);const h=[C.PositionKind];r.NORMAL&&h.push(C.NormalKind),r.UV1&&h.push(C.UVKind),r.UV2&&h.push(C.UV2Kind),r.VERTEXCOLOR&&h.push(C.ColorKind),Nr(h,e,r,l),hr(h,r);const c="water",u=r.toString(),d=["world","view","viewProjection","vEyePosition","vLightsType","vDiffuseColor","vSpecularColor","vFogInfos","vFogColor","pointSize","vNormalInfos","mBones","normalMatrix","logarithmicDepthConstant","reflectionViewProjection","windDirection","waveLength","time","windForce","cameraPosition","bumpHeight","waveHeight","waterColor","waterColor2","colorBlendFactor","colorBlendFactor2","waveSpeed","waveCount"],f=["normalSampler","refractionSampler","reflectionSampler"],p=[];ct&&(ct.PrepareUniforms(d,r),ct.PrepareSamplers(f,r)),qi(d),wr({uniformsNames:d,uniformBuffersNames:p,samplers:f,defines:r,maxSimultaneousLights:this.maxSimultaneousLights}),t.setEffect(n.getEngine().createEffect(c,{attributes:h,uniformsNames:d,uniformBuffersNames:p,samplers:f,defines:u,fallbacks:l,onCompiled:this.onCompiled,onError:this.onError,indexParameters:{maxSimultaneousLights:this._maxSimultaneousLights}},o),r,this._materialContext)}return!t.effect||!t.effect.isReady()?!1:(r._renderId=n.getRenderId(),s._wasPreviouslyReady=!0,s._wasPreviouslyUsingInstances=!!i,!0)}bindForSubMesh(e,t,i){const s=this.getScene(),r=i.materialDefines;if(!r)return;const n=i.effect;if(!n||!this._mesh)return;this._activeEffect=n,this.bindOnlyWorldMatrix(e),this._activeEffect.setMatrix("viewProjection",s.getTransformMatrix()),lr(t,this._activeEffect),this._mustRebind(s,n,i)&&(this.bumpTexture&&ie.BumpTextureEnabled&&(this._activeEffect.setTexture("normalSampler",this.bumpTexture),this._activeEffect.setFloat2("vNormalInfos",this.bumpTexture.coordinatesIndex,this.bumpTexture.level),this._activeEffect.setMatrix("normalMatrix",this.bumpTexture.getTextureMatrix())),zi(n,this,s),this.pointsCloud&&this._activeEffect.setFloat("pointSize",this.pointSize),this._useLogarithmicDepth&&is(r,n,s),s.bindEyePosition(n)),this._activeEffect.setColor4("vDiffuseColor",this.diffuseColor,this.alpha*t.visibility),r.SPECULARTERM&&this._activeEffect.setColor4("vSpecularColor",this.specularColor,this.specularPower),s.lightsEnabled&&!this.disableLighting&&Er(s,t,this._activeEffect,r,this.maxSimultaneousLights),s.fogEnabled&&t.applyFog&&s.fogMode!==pe.FOGMODE_NONE&&this._activeEffect.setMatrix("view",s.getViewMatrix()),Ms(s,t,this._activeEffect),is(r,this._activeEffect,s),ie.ReflectionTextureEnabled&&(this._activeEffect.setTexture("refractionSampler",this._refractionRTT),this._activeEffect.setTexture("reflectionSampler",this._reflectionRTT));const o=this._reflectionTransform.multiply(s.getProjectionMatrix()),l=s.getEngine().getDeltaTime();l!==this._lastDeltaTime&&(this._lastDeltaTime=l,this._lastTime+=this._lastDeltaTime),this._activeEffect.setMatrix("reflectionViewProjection",o),this._activeEffect.setVector2("windDirection",this.windDirection),this._activeEffect.setFloat("waveLength",this.waveLength),this._activeEffect.setFloat("time",this._lastTime/1e5),this._activeEffect.setFloat("windForce",this.windForce),this._activeEffect.setFloat("waveHeight",this.waveHeight),this._activeEffect.setFloat("bumpHeight",this.bumpHeight),this._activeEffect.setColor4("waterColor",this.waterColor,1),this._activeEffect.setFloat("colorBlendFactor",this.colorBlendFactor),this._activeEffect.setColor4("waterColor2",this.waterColor2,1),this._activeEffect.setFloat("colorBlendFactor2",this.colorBlendFactor2),this._activeEffect.setFloat("waveSpeed",this.waveSpeed),this._activeEffect.setFloat("waveCount",this.waveCount),this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.applyByPostProcess&&this._imageProcessingConfiguration.bind(this._activeEffect),this._afterBind(t,this._activeEffect,i)}_createRenderTargets(e,t){this._refractionRTT=new ai(name+"_refraction",{width:t.x,height:t.y},e,!1,!0),this._refractionRTT.wrapU=H.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.wrapV=H.TEXTURE_MIRROR_ADDRESSMODE,this._refractionRTT.ignoreCameraViewport=!0;let i=!1;this._refractionRTT.onBeforeRenderObservable.add(()=>{i=e.getBoundingBoxRenderer().enabled,e.getBoundingBoxRenderer().enabled=!1}),this._refractionRTT.onAfterRenderObservable.add(()=>{e.getBoundingBoxRenderer().enabled=i}),this._reflectionRTT=new ai(name+"_reflection",{width:t.x,height:t.y},e,!1,!0),this._reflectionRTT.wrapU=H.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.wrapV=H.TEXTURE_MIRROR_ADDRESSMODE,this._reflectionRTT.ignoreCameraViewport=!0;let s,r=null,n;const o=D.Zero();this._refractionRTT.onBeforeRender=()=>{if(this._mesh&&(s=this._mesh.isVisible,this._mesh.isVisible=!1),!this.disableClipPlane){r=e.clipPlane;const l=this._mesh?this._mesh.absolutePosition.y:0;e.clipPlane=Qs.FromPositionAndNormal(new m(0,l+.05,0),new m(0,1,0))}},this._refractionRTT.onAfterRender=()=>{this._mesh&&(this._mesh.isVisible=s),this.disableClipPlane||(e.clipPlane=r)},this._reflectionRTT.onBeforeRender=()=>{if(this._mesh&&(s=this._mesh.isVisible,this._mesh.isVisible=!1),!this.disableClipPlane){r=e.clipPlane;const l=this._mesh?this._mesh.absolutePosition.y:0;e.clipPlane=Qs.FromPositionAndNormal(new m(0,l-.05,0),new m(0,-1,0)),D.ReflectionToRef(e.clipPlane,o)}n=e.getViewMatrix(),o.multiplyToRef(n,this._reflectionTransform),e.setTransformMatrix(this._reflectionTransform,e.getProjectionMatrix()),e._mirroredCameraPosition=m.TransformCoordinates(e.activeCamera.position,o)},this._reflectionRTT.onAfterRender=()=>{this._mesh&&(this._mesh.isVisible=s),e.clipPlane=r,e.setTransformMatrix(n,e.getProjectionMatrix()),e._mirroredCameraPosition=null}}getAnimatables(){const e=[];return this.bumpTexture&&this.bumpTexture.animations&&this.bumpTexture.animations.length>0&&e.push(this.bumpTexture),this._reflectionRTT&&this._reflectionRTT.animations&&this._reflectionRTT.animations.length>0&&e.push(this._reflectionRTT),this._refractionRTT&&this._refractionRTT.animations&&this._refractionRTT.animations.length>0&&e.push(this._refractionRTT),e}getActiveTextures(){const e=super.getActiveTextures();return this._bumpTexture&&e.push(this._bumpTexture),e}hasTexture(e){return!!(super.hasTexture(e)||this._bumpTexture===e)}dispose(e){this.bumpTexture&&this.bumpTexture.dispose();let t=this.getScene().customRenderTargets.indexOf(this._refractionRTT);t!=-1&&this.getScene().customRenderTargets.splice(t,1),t=-1,t=this.getScene().customRenderTargets.indexOf(this._reflectionRTT),t!=-1&&this.getScene().customRenderTargets.splice(t,1),this._reflectionRTT&&this._reflectionRTT.dispose(),this._refractionRTT&&this._refractionRTT.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e)}clone(e){return ce.Clone(()=>new oi(e,this.getScene()),this)}serialize(){const e=super.serialize();if(e.customType="BABYLON.WaterMaterial",e.renderList=[],this._refractionRTT&&this._refractionRTT.renderList)for(let t=0;tnew oi(e.name,t),e,t,i);return s._waitingRenderList=e.renderList,s}static CreateDefaultMesh(e,t){return Jf(e,{width:512,height:512,subdivisions:32,updatable:!1},t)}}x([Ue("bumpTexture")],oi.prototype,"_bumpTexture",void 0);x([q("_markAllSubMeshesAsTexturesDirty")],oi.prototype,"bumpTexture",void 0);x([mt()],oi.prototype,"diffuseColor",void 0);x([mt()],oi.prototype,"specularColor",void 0);x([I()],oi.prototype,"specularPower",void 0);x([I("disableLighting")],oi.prototype,"_disableLighting",void 0);x([q("_markAllSubMeshesAsLightsDirty")],oi.prototype,"disableLighting",void 0);x([I("maxSimultaneousLights")],oi.prototype,"_maxSimultaneousLights",void 0);x([q("_markAllSubMeshesAsLightsDirty")],oi.prototype,"maxSimultaneousLights",void 0);x([I()],oi.prototype,"windForce",void 0);x([Mf()],oi.prototype,"windDirection",void 0);x([I()],oi.prototype,"waveHeight",void 0);x([I()],oi.prototype,"bumpHeight",void 0);x([I("bumpSuperimpose")],oi.prototype,"_bumpSuperimpose",void 0);x([q("_markAllSubMeshesAsMiscDirty")],oi.prototype,"bumpSuperimpose",void 0);x([I("fresnelSeparate")],oi.prototype,"_fresnelSeparate",void 0);x([q("_markAllSubMeshesAsMiscDirty")],oi.prototype,"fresnelSeparate",void 0);x([I("bumpAffectsReflection")],oi.prototype,"_bumpAffectsReflection",void 0);x([q("_markAllSubMeshesAsMiscDirty")],oi.prototype,"bumpAffectsReflection",void 0);x([mt()],oi.prototype,"waterColor",void 0);x([I()],oi.prototype,"colorBlendFactor",void 0);x([mt()],oi.prototype,"waterColor2",void 0);x([I()],oi.prototype,"colorBlendFactor2",void 0);x([I()],oi.prototype,"waveLength",void 0);x([I()],oi.prototype,"waveSpeed",void 0);x([I()],oi.prototype,"waveCount",void 0);x([I()],oi.prototype,"disableClipPlane",void 0);x([I("useWorldCoordinatesForWaveDeformation")],oi.prototype,"_useWorldCoordinatesForWaveDeformation",void 0);x([q("_markAllSubMeshesAsMiscDirty")],oi.prototype,"useWorldCoordinatesForWaveDeformation",void 0);U("BABYLON.WaterMaterial",oi);class xz{constructor(e,t,i,s,r){Vt(this,"clearColorIndex");Vt(this,"fps");Vt(this,"easeOutFunction");Vt(this,"hemiLight");Vt(this,"zoomToMeshIndex");Vt(this,"activeModel");this.kotatsu=e,this.embroidery=t,this.scene=i,this.camera=s,this.engine=r,this.clearColorIndex=0,this.zoomToMeshIndex=0,this.activeModel="kotatsu",this.fps=60,this.easeOutFunction=new aS,this.easeOutFunction.setEasingMode(Ys.EASINGMODE_EASEOUT),this.hemiLight=this.scene.getLightByName("hemiLight")}changeClearColor(){const e=["#33BF4F","#DC4829","#FFD000","#2D94CE","#B7BC9B","#000000"];this.scene.clearColor=ge.FromHexString(e[this.clearColorIndex]),this.clearColorIndex===5?(this.hemiLight.intensity=.05,this.kotatsu.spotLight.setEnabled(!0)):(this.hemiLight.intensity=1,this.kotatsu.spotLight.setEnabled(!1)),this.clearColorIndex++,this.clearColorIndex>=e.length&&(this.clearColorIndex=0)}moveCamera(){const e=this.camera,t=Math.random()*Math.PI*2,i=Math.random()*Math.PI,s=Math.random()*3+4;this._animate("moveCameraAlpha",e,"alpha",20,e.alpha,t),this._animate("moveCameraBeta",e,"beta",20,e.beta,i),this._animate("moveCameraRadius",e,"radius",20,e.radius,s)}heat(){const e=this.kotatsu.heaterLight,t=Math.random()*15+30;this._animate("heat",e,"intensity",10,t,1)}dissolve(){let e=!1;this.kotatsu.root.metadata.isShuffled&&Math.random()<.3?(e=!0,this.kotatsu.root.metadata.isShuffled=!1):this.kotatsu.root.metadata.isShuffled=!0,this._moveScaleAndRotate(this.kotatsu.futon,e),this._moveScaleAndRotate(this.kotatsu.tabletop,e),this._moveScaleAndRotate(this.kotatsu.tableBase,e)}rotateTabletop(){const e=this.kotatsu.tabletop,t=e.metadata.isRotated?0:Math.PI*3,i=this.kotatsu.root.metadata.isShuffled?e.scaling.x:1,s=new m(i*1.4,i*1.4,i*1.4),r=new m(i,i,i);e.metadata.isRotated=!e.metadata.isRotated,this._animate("rotation",e,"rotation.y",15,e.rotation.y,t),this._animate("scaling",e,"scaling",15,s,r)}changeMaterials(e=!1){const t=this.kotatsu.root,i=t.getChildMeshes();t.metadata.isNormalMaterial?i.forEach(n=>{n.material=n.metadata.initialMaterial,n.material.wireframe=!1,t.metadata.isNormalMaterial=!1}):i.forEach(n=>{n.material=new Pn("normalMaterial",this.scene),n.material.wireframe=!!e,t.metadata.isNormalMaterial=!0});const s=this.embroidery.root;s.getChildMeshes().forEach(n=>{s.metadata.isWireframe?n.material.wireframe=!1:n.material.wireframe=!0}),s.metadata.isWireframe=!s.metadata.isWireframe}zoomToMesh(){const e=["take","oreo","toreko","o1","cha","no","ma","to","ri","o2"],t=e[this.zoomToMeshIndex];e.forEach(i=>{if(i===t){const s=this.embroidery[i];this._animate("position",s,"position",10,s.position,m.Zero),i.length<4?this._animate("scaling",s,"scaling",10,s.scaling,new m(5,5,5)):this._animate("scaling",s,"scaling",10,s.scaling,new m(2,2,2))}else{const s=this.embroidery[i];this._animate("position",s,"position",10,s.position,this._randomVector3(4)),this._animate("rotation",s,"rotation",10,s.rotation,this._randomVector3),this._animate("scaling",s,"scaling",10,s.scaling,new m(1,1,1))}}),this.zoomToMeshIndex++,this.zoomToMeshIndex>=e.length&&(this.zoomToMeshIndex=0)}bounce(){const e=this[this.activeModel].root;this._animate("bounce",e,"scaling",15,new m(1.2,1.2,1.2),m.One)}reset(){this._moveScaleAndRotate(this.kotatsu.futon,!0),this._moveScaleAndRotate(this.kotatsu.tabletop,!0),this._moveScaleAndRotate(this.kotatsu.tableBase,!0),this.embroidery.root.getChildTransformNodes(!0).forEach(n=>{this._animate("scaling",n,"scaling",10,n.scaling,m.One),this._animate("rotation",n,"rotation",10,n.rotation,m.Zero),this._animate("position",n,"position",10,n.position,n.metadata.initialPosition)}),this.kotatsu.root.getChildMeshes().forEach(n=>{n.material=n.metadata.initialMaterial,n.material.wireframe=!1});const s=this.embroidery.root;s.getChildMeshes().forEach(n=>{n.material.wireframe=!1}),s.metadata.isNormalMaterial=!1,s.metadata.isShuffled=!1,s.metadata.isWireframe=!1}scaleFromVelocity(e){const t=this[this.activeModel].root,i=new m(1+e,1+e,1+e);this._animate("scaleFromVelocity",t,"scaling",10,t.scaling,i)}floatFuton(e){const t=this.kotatsu.tabletop,i=this.kotatsu.tableBase,s=this.kotatsu.futon;typeof e=="number"&&(t.position.y=e/2,i.position.y=-e/2,s.rotation=new m(0,Math.PI*e/2,0))}moveCameraBeta(e){const t=this.camera;if(typeof e=="number")if(e===0)this._animate("cameraBeta",t,"beta",10,t.beta,Math.PI*.25);else{const o=(e-1)*1/2+1;t.beta=Math.PI*o}}changeModel(){this.activeModel=="kotatsu"?(this._animate("scaling",this.embroidery.root,"scaling",20,this.embroidery.root.scaling,m.One),this._animate("scaling",this.kotatsu.root,"scaling",20,this.kotatsu.root.scaling,m.Zero),this.kotatsu.heaterLight.setEnabled(!1),this.activeModel="embroidery"):this.activeModel=="embroidery"&&(this._animate("scaling",this.embroidery.root,"scaling",20,this.embroidery.root.scaling,m.Zero),this._animate("scaling",this.kotatsu.root,"scaling",20,this.kotatsu.root.scaling,m.One),this.kotatsu.heaterLight.setEnabled(!0),this.activeModel="kotatsu")}_animate(e,t,i,s,r,n,o){o=o||this.easeOutFunction,j.CreateAndStartAnimation(e,t,i,this.fps,s,r,n,0,o)}_randomVector3(e=2){return new m(Math.random()*(e+1)-e,Math.random()*(e+1)-e,Math.random()*(e+1)-e)}_moveScaleAndRotate(e,t=!1){const i=t?m.Zero():this._randomVector3(.5),s=t?m.Zero():this._randomVector3(2),r=Math.random()*1.5+.3,n=t?m.One():new m(r,r,r);this._animate("position",e,"position",20,e.position,i),this._animate("rotation",e,"rotation",20,e.rotation,s),this._animate("scaling",e,"scaling",20,e.scaling,n)}}class Hn{constructor(e=!1){this.eventMap={},this.eventsSuspended=e==!0}addListener(e,t,i={}){if(typeof e=="string"&&e.length<1||e instanceof String&&e.length<1||typeof e!="string"&&!(e instanceof String)&&e!==Hn.ANY_EVENT)throw new TypeError("The 'event' parameter must be a string or EventEmitter.ANY_EVENT.");if(typeof t!="function")throw new TypeError("The callback must be a function.");const s=new xE(e,this,t,i);return this.eventMap[e]||(this.eventMap[e]=[]),i.prepend?this.eventMap[e].unshift(s):this.eventMap[e].push(s),s}addOneTimeListener(e,t,i={}){i.remaining=1,this.addListener(e,t,i)}static get ANY_EVENT(){return Symbol.for("Any event")}hasListener(e,t){return e===void 0?this.eventMap[Hn.ANY_EVENT]&&this.eventMap[Hn.ANY_EVENT].length>0?!0:Object.entries(this.eventMap).some(([,i])=>i.length>0):this.eventMap[e]&&this.eventMap[e].length>0?t instanceof xE?this.eventMap[e].filter(s=>s===t).length>0:typeof t=="function"?this.eventMap[e].filter(s=>s.callback===t).length>0:t==null:!1}get eventNames(){return Object.keys(this.eventMap)}getListeners(e){return this.eventMap[e]||[]}suspendEvent(e){this.getListeners(e).forEach(t=>{t.suspended=!0})}unsuspendEvent(e){this.getListeners(e).forEach(t=>{t.suspended=!1})}getListenerCount(e){return this.getListeners(e).length}emit(e,...t){if(typeof e!="string"&&!(e instanceof String))throw new TypeError("The 'event' parameter must be a string.");if(this.eventsSuspended)return;let i=[],s=this.eventMap[Hn.ANY_EVENT]||[];return this.eventMap[e]&&(s=s.concat(this.eventMap[e])),s.forEach(r=>{if(r.suspended)return;let n=[...t];Array.isArray(r.arguments)&&(n=n.concat(r.arguments)),r.remaining>0&&(i.push(r.callback.apply(r.context,n)),r.count++),--r.remaining<1&&r.remove()}),i}removeListener(e,t,i={}){if(e===void 0){this.eventMap={};return}else if(!this.eventMap[e])return;let s=this.eventMap[e].filter(r=>t&&r.callback!==t||i.remaining&&i.remaining!==r.remaining||i.context&&i.context!==r.context);s.length?this.eventMap[e]=s:delete this.eventMap[e]}async waitFor(e,t={}){return t.duration=parseInt(t.duration),(isNaN(t.duration)||t.duration<=0)&&(t.duration=1/0),new Promise((i,s)=>{let r,n=this.addListener(e,()=>{clearTimeout(r),i()},{remaining:1});t.duration!==1/0&&(r=setTimeout(()=>{n.remove(),s("The duration expired before the event was emitted.")},t.duration))})}get eventCount(){return Object.keys(this.eventMap).length}}class xE{constructor(e,t,i,s={}){if(typeof e!="string"&&!(e instanceof String)&&e!==Hn.ANY_EVENT)throw new TypeError("The 'event' parameter must be a string or EventEmitter.ANY_EVENT.");if(!t)throw new ReferenceError("The 'target' parameter is mandatory.");if(typeof i!="function")throw new TypeError("The 'callback' must be a function.");s.arguments!==void 0&&!Array.isArray(s.arguments)&&(s.arguments=[s.arguments]),s=Object.assign({context:t,remaining:1/0,arguments:void 0,duration:1/0},s),s.duration!==1/0&&setTimeout(()=>this.remove(),s.duration),this.arguments=s.arguments,this.callback=i,this.context=s.context,this.count=0,this.event=e,this.remaining=parseInt(s.remaining)>=1?parseInt(s.remaining):1/0,this.suspended=!1,this.target=t}remove(){this.target.removeListener(this.event,this.callback,{context:this.context,remaining:this.remaining})}}/** * The `Enumerations` class contains enumerations and arrays of elements used throughout the * library. All its properties are static and should be referenced using the class name. For * example: `Enumerations.CHANNEL_MESSAGES`. diff --git a/index.html b/index.html index f622a24..567df6d 100644 --- a/index.html +++ b/index.html @@ -4,7 +4,7 @@ 3d-midi-kotatsu - +