babylonjs-toolkit 9.6.2 → 9.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.TOOLKIT=t():e.TOOLKIT=t()}(this,()=>(()=>{"use strict";var e={d:(t,n)=>{for(var i in n)e.o(n,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:n[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};e.d(t,{default:()=>u});var n,i,r=(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),o=function(){return o=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},o.apply(this,arguments)},a=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{l(i.next(e))}catch(e){o(e)}}function s(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}l((i=i.apply(e,t||[])).next())})},s=function(e,t){var n,i,r,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(l){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(n=1,i&&(r=2&s[0]?i.return:s[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,s[1])).done)return r;switch(i=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,i=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((r=(r=o.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){o.label=s[1];break}if(6===s[0]&&o.label<r[1]){o.label=r[1],r=s;break}if(r&&o.label<r[2]){o.label=r[2],o.ops.push(s);break}r[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],i=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,l])}}},l=function(e,t,n){if(n||2===arguments.length)for(var i,r=0,o=t.length;r<o;r++)!i&&r in t||(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))};!function(e){var t=function(){function t(){}return Object.defineProperty(t,"Version",{get:function(){return"9.6.2 - R1"},enumerable:!1,configurable:!0}),Object.defineProperty(t,"Copyright",{get:function(){return"All rights reserved (c) 2024 Mackey Kinard"},enumerable:!1,configurable:!0}),t.GetEngine=function(e){var t=null,n=e.getEngine();return null!=n&&(n instanceof BABYLON.Engine||n instanceof BABYLON.WebGPUEngine)&&(t=n),t},t.GetClass=function(e){return BABYLON.GetClass(e)},t.RegisterClass=function(e,t){BABYLON.RegisterClass(e,t)},t.GetAuxiliaryData=function(e){var t;return null===(t=null==e?void 0:e.metadata)||void 0===t?void 0:t.auxiliary},t.SetAuxiliaryData=function(e,t){e.metadata=o(o({},e.metadata),{auxiliary:t})},Object.defineProperty(t,"EventBus",{get:function(){return null==e.SceneManager._EventBus&&(e.SceneManager._EventBus=new e.GlobalMessageBus),e.SceneManager._EventBus},enumerable:!1,configurable:!0}),Object.defineProperty(t,"PlaygroundCdn",{get:function(){return"https://cdn.jsdelivr.net/gh/BabylonJS/BabylonToolkit@master/Runtime/"},enumerable:!1,configurable:!0}),Object.defineProperty(t,"PlaygroundRepo",{get:function(){return"https://www.babylontoolkit.com/playground/"},enumerable:!1,configurable:!0}),t.InitializePlayground=function(t){return a(this,arguments,void 0,function(t,n,i,r){return void 0===n&&(n=null),void 0===i&&(i=null),void 0===r&&(r=null),s(this,function(o){return[2,e.SceneManager.InitializeRuntime(t,n,i,r)]})})},t.InitializeRuntime=function(t){return a(this,arguments,void 0,function(t,n,i,r){var o,a,l,u,c,d,h,p,m;return void 0===n&&(n=null),void 0===i&&(i=null),void 0===r&&(r=null),s(this,function(s){switch(s.label){case 0:BABYLON.Tools.Log("Babylon.js Toolkit v"+e.SceneManager.Version),e.AudioSource.IsLegacyEngine()&&BABYLON.Tools.Log("Legacy audio engine detected"),o=null!=n&&null!=n.hardwareScalingLevel?n.hardwareScalingLevel:e.WindowManager.GetHardwareScalingLevel(),null==n||null==n.initSceneFileLoaders||n.initSceneFileLoaders,null==n||null==n.loadAsyncRuntimeLibs||n.loadAsyncRuntimeLibs,a=null!=n&&null!=n.enableUserInput&&n.enableUserInput,l=e.SceneManager.PlaygroundCdn+"default.playground.js",u=null!=n&&null!=n.loadProjectScriptBundle&&n.loadProjectScriptBundle,c=null!=n&&null!=n.projectScriptBundleUrl?n.projectScriptBundleUrl:l,d=null!=n&&null!=n.showDefaultLoadingScreen&&n.showDefaultLoadingScreen,h=null==n||null==n.hideLoadingUIWithEngine||n.hideLoadingUIWithEngine,p=null!=n&&null!=n.defaultLoadingUIMarginTop?n.defaultLoadingUIMarginTop:"150px",!0===d&&e.SceneManager.ShowLoadingScreen(t,h,p),null!=o&&o>0&&t.setHardwareScalingLevel(o),!0===a&&e.InputController.EnableUserInput(t,i,r),e.SceneManager.UniversalModuleDefinition=!0;try{e.SceneManager.InitializeSceneLoaderPlugin()}catch(e){console.warn("Babylon Toolkit: Failed to initialize loader plugin:",e)}try{BABYLON&&BABYLON.GLTF2&&BABYLON.GLTF2.registerGLTFExtension?(e.SceneManager.CVTOOLS_NAME_REGISTERED||(BABYLON.GLTF2.registerGLTFExtension(e.SceneManager.CVTOOLS_NAME,!0,function(t){return new e.CVTOOLS_unity_metadata(t)}),e.SceneManager.CVTOOLS_NAME_REGISTERED=!0),e.SceneManager.CVTOOLS_MESH_REGISTERED||(BABYLON.GLTF2.registerGLTFExtension(e.SceneManager.CVTOOLS_MESH,!0,function(t){return new e.CVTOOLS_babylon_mesh(t)}),e.SceneManager.CVTOOLS_MESH_REGISTERED=!0),e.SceneManager.CVTOOLS_HAND_REGISTERED||(BABYLON.GLTF2.registerGLTFExtension(e.SceneManager.CVTOOLS_HAND,!0,function(t){return new e.CVTOOLS_left_handed(t)}),e.SceneManager.CVTOOLS_HAND_REGISTERED=!0)):console.warn("Babylon Toolkit: UMD GLTF Parser not registered because BABYLON.GLTF2 or RegisterGLTFExtension is not available.")}catch(e){console.warn("Babylon Toolkit: Failed to initialize GLTF extensions:",e)}return!0!==u||null==c||""===c?[3,2]:(m=c.substring(c.lastIndexOf("/")+1).toLowerCase(),[4,BABYLON.Tools.LoadScriptAsync(c,m)]);case 1:s.sent(),s.label=2;case 2:return[2]}})})},t.InitializeSceneLoaderPlugin=function(){BABYLON.SceneLoader.OnPluginActivatedObservable.add(function(t){null!=t&&"gltf"===t.name&&t instanceof BABYLON.GLTFFileLoader&&(t.extensions,t.animationStartMode=e.SceneManager.AnimationStartMode,t.targetFps=e.SceneManager.AnimationTargetFps,t.onSkinLoadedObservable&&t.onSkinLoadedObservable.add(function(e){if(null!=e){try{null!=e.skinnedNode&&(e.skinnedNode.id+=".Skin")}catch(e){console.warn(e)}try{null!=e.skinnedNode&&(e.skinnedNode.name+=".Skin")}catch(e){console.warn(e)}try{if(null!=e.node&&null!=e.skinnedNode){var t=BABYLON.Tags.GetTags(e.node);null!=t&&BABYLON.Tags.AddTagsTo(e.skinnedNode,t),e.node._skinnedMesh=e.skinnedNode}else console.warn("Babylon Toolkit: Skinned node not found in scene loader plugin: ",e)}catch(e){console.warn(e)}}}))})},t.LoadRuntimeAssets=function(t,n,i){return a(this,arguments,void 0,function(t,n,i,r,o){return void 0===r&&(r=60),void 0===o&&(o=!1),s(this,function(a){switch(a.label){case 0:return e.SceneManager.SetOnSceneReadyHandler(n,i,r,o),null==t?[3,2]:[4,t.loadAsync()];case 1:a.sent(),a.label=2;case 2:return[2]}})})},t.ShowLoadingScreen=function(t,n,i){if(void 0===n&&(n=!0),void 0===i&&(i="150px"),null!=t.loadingScreen){e.SceneManager._HideLoadingScreen=t.loadingScreen.hideLoadingUI.bind(t.loadingScreen),!1===n&&(t.loadingScreen.hideLoadingUI=function(){});var r=t.loadingScreen;r._loadingDivBackgroundColor="#2A2342",t.displayLoadingUI(),null!=r._loadingTextDiv&&null!=r._loadingTextDiv.style&&(r._loadingTextDiv.style.marginTop=i)}},t.HideLoadingScreen=function(t,n){if(void 0===n&&(n=!0),null!=t.loadingScreen){if(!1===n){var i=t.loadingScreen;i._loadingDivToRenderingCanvasMap&&i._loadingDivToRenderingCanvasMap.forEach(function(e,t){t&&t.style&&(t.style.transition="none",t.style.opacity="0")})}null!=e.SceneManager._HideLoadingScreen?e.SceneManager._HideLoadingScreen():t.hideLoadingUI()}else e.SceneManager.ForceHideLoadingScreen()},t.ForceHideLoadingScreen=function(){try{e.SceneManager.DoForceHideLoadingScreen()}catch(e){console.warn(e)}finally{try{e.SceneManager.DoForceHideLoadingScreen()}catch(e){console.warn(e)}finally{try{e.SceneManager.DoForceHideLoadingScreen()}catch(e){console.warn(e)}}}},t.DoForceHideLoadingScreen=function(){var e=document.getElementById("babylonjsLoadingDiv"),t=document.getElementById("babylonjsLoadingText"),n=document.getElementById("babylonjsLoadingDivStyle");try{null!=t&&(t.remove(),t=null)}catch(e){console.warn(e)}try{null!=e&&(e.remove(),e=null)}catch(e){console.warn(e)}try{null!=n&&n.remove()}catch(e){console.warn(e)}},t.FocusRenderCanvas=function(e){e.getEngine().getRenderingCanvas().focus()},t.ShowSplashScreen=function(){try{var e=document.getElementById("xbabylonjsSplashScreen");e&&(e.style.display="block")}catch(e){console.warn(e)}},t.HideSplashScreen=function(t,n){void 0===t&&(t=null),void 0===n&&(n=0),e.WindowManager.SetTimeout(n,function(){if(null!=t&&!t.isDisposed){try{e.SceneManager.HideLoadingScreen(t.getEngine())}catch(e){console.warn(e)}try{e.SceneManager.FocusRenderCanvas(t)}catch(e){console.warn(e)}}try{var n=document.getElementById("xbabylonjsSplashScreen");if(n){n.style.opacity="0";var i=function(){n.style.display="none",n.removeEventListener("transitionend",i)};n.addEventListener("transitionend",i)}}catch(e){console.warn(e)}})},t.UpdateSplashScreenStatus=function(e){try{var t=document.getElementById("xbabylonjsSplashScreen");if(t){t.style.display="block";var n=t.querySelector("#xbabylonjsStatusTextDiv");n&&(n.textContent=e)}}catch(e){console.warn(e)}},t.SetOnSceneReadyHandler=function(t,n,i,r){void 0===i&&(i=60),void 0===r&&(r=!1),e.SceneManager.SceneLoaderPropertyBag={},e.SceneManager.SceneLoaderHandledFlag=!1,e.SceneManager.SceneLoaderFileNames=t,e.SceneManager.SceneLoaderFileNames.forEach(function(t){e.SceneManager.SceneLoaderPropertyBag[t.toLowerCase()]=!1}),e.SceneManager.OnSceneReadyObservable.clear(),e.SceneManager.OnSceneReadyObservable.add(function(t){if(!0===r&&console.log("OnSceneReady(): "+t),e.SceneManager.SceneLoaderPropertyBag[t.toLowerCase()]=!0,!0===Object.values(e.SceneManager.SceneLoaderPropertyBag).every(function(e){return!0===e}))try{n&&n()}catch(e){console.warn(e)}finally{e.SceneManager.SceneLoaderHandledFlag=!0}}),e.WindowManager.SetTimeout(1e3*i,function(){if(!1===e.SceneManager.SceneLoaderHandledFlag)try{n&&n()}catch(e){console.warn(e)}finally{e.SceneManager.SceneLoaderHandledFlag=!0,e.SceneManager.ForceHideLoadingScreen()}})},t.EnableSceneParsing=function(t){e.SceneManager.SceneParsingEnabled=t},t.IsSceneParsingEnabled=function(){return e.SceneManager.SceneParsingEnabled},t.HasSceneBeenPreLoaded=function(e){var t=e;return null!=t._preloaded&&!0===t._preloaded},t.GetDefaultSkybox=function(e){return e.getMeshById("Default Skybox")},t.GetIntensityFactor=function(){return null!=e.SceneManager.GlobalOptions.intensityFactor?e.SceneManager.GlobalOptions.intensityFactor:2},t.GetRenderQuality=function(){var t=e.RenderQuality.High,n=e.SceneManager.GlobalOptions.renderQuality;return null!=n&&(t=n),t},t.SetRenderQuality=function(t){e.SceneManager.GlobalOptions.renderQuality=t},t.GetEngineVersionString=function(t){var n="Unknown",i=t||BABYLON.EngineStore.LastCreatedScene;if(null!=i){var r=e.SceneManager.GetEngine(i);if(null!=r){var o=r.getInfo();null!=o&&(n=o.version+" - "+o.renderer)}}return n},t.GetImageBasedLighting=function(e){return e.globalSphericalPolynomial},t.SetWindowState=function(t,n){e.SceneManager.WindowState[t]=n},t.GetWindowState=function(t){var n=e.SceneManager.WindowState[t];return null!=n?n:null},t.IsDebugMode=function(){return!0},t.ConsoleLog=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];e.SceneManager.IsDebugMode()&&console.log.apply(console,t)},t.ConsoleInfo=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];e.SceneManager.IsDebugMode()&&console.info.apply(console,t)},t.ConsoleWarn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];e.SceneManager.IsDebugMode()&&console.warn.apply(console,t)},t.ConsoleError=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.error.apply(console,e)},t.LogMessage=function(t){e.SceneManager.IsDebugMode()&&BABYLON.Tools.Log(t)},t.LogWarning=function(t){e.SceneManager.IsDebugMode()&&BABYLON.Tools.Warn(t)},t.LogError=function(e){BABYLON.Tools.Error(e)},t.GetTime=function(){return.001*e.SceneManager.GetTimeMilliseconds()},t.GetTimeMs=function(){return e.SceneManager.GetTimeMilliseconds()},t.GetGameTime=function(){return.001*(e.SceneManager.GetTimeMilliseconds()-e.SceneManager.GameTimeMilliseconds)},t.GetGameTimeMs=function(){return e.SceneManager.GetTimeMilliseconds()-e.SceneManager.GameTimeMilliseconds},t.GetDeltaTime=function(t,n){return void 0===n&&(n=!1),e.SceneManager.GetDeltaSeconds(t,n)},t.GetDeltaSeconds=function(e,t){void 0===t&&(t=!1);var n=e||BABYLON.EngineStore.LastCreatedScene,i=.001*Math.max(BABYLON.Scene.MinDeltaTime,Math.min(n.getEngine().getDeltaTime(),BABYLON.Scene.MaxDeltaTime));return!0===t&&(i*=n.getAnimationRatio()),i},t.GetDeltaMilliseconds=function(e,t){void 0===t&&(t=!1);var n=e||BABYLON.EngineStore.LastCreatedScene,i=Math.max(BABYLON.Scene.MinDeltaTime,Math.min(n.getEngine().getDeltaTime(),BABYLON.Scene.MaxDeltaTime));return!0===t&&(i*=n.getAnimationRatio()),i},t.GetTimeMilliseconds=function(){var e=0;return"undefined"!=typeof window&&window.performance?e=window.performance.now():"undefined"!=typeof window&&window.Date?e=window.Date.now():null!=Date&&(e=Date.now()),e},t.GetAnimationRatio=function(e){return(e||BABYLON.EngineStore.LastCreatedScene).getAnimationRatio()},t.RunOnce=function(e,t,n){e.executeOnceBeforeRender(t,n)},t.DisposeScene=function(e,t){void 0===t&&(t=new BABYLON.Color4(0,0,0,1));var n=e.getEngine();e.dispose(),n.clear(t,!0,!0,!0)},t.SafeDestroy=function(t,n,i){void 0===n&&(n=5),void 0===i&&(i=!1),n>0?(!0===i&&t.setEnabled(!1),e.WindowManager.SetTimeout(n,function(){t.dispose(!1,!1)})):t.dispose(!1,!1)},t.GetRootUrl=function(e){return null!=e._rootUrl&&""!==e._rootUrl?e._rootUrl:"/"},t.SetRootUrl=function(e,t){e._rootUrl=t},t.GetSceneFile=function(e){return null!=e._fileName&&""!==e._fileName?e._fileName:null},t.SetSceneFile=function(e,t){e._fileName=t},t.AddShadowCaster=function(e,t,n){void 0===n&&(n=!1);var i=null==e?void 0:e.getShadowGenerator();if(null!=i){var r=i.getShadowMap();if(null!=r&&(null==r.renderList&&(r.renderList=[]),t instanceof BABYLON.AbstractMesh&&r.renderList.indexOf(t)<0&&r.renderList.push(t),!0===n)){var o=t.getChildMeshes(!1);null!=o&&o.forEach(function(e){r.renderList.indexOf(e)<0&&r.renderList.push(e)})}}},t.AddShadowCastersToLight=function(e,t,n){void 0===n&&(n=!1);var i=e.getShadowGenerator();if(null!=i){var r=i.getShadowMap();if(null!=r)for(var o=0;o<t.length;o++){var a=t[o];if(a instanceof BABYLON.AbstractMesh&&(null!=e.includedOnlyMeshes&&e.includedOnlyMeshes.length>0&&e.includedOnlyMeshes.indexOf(a)<0&&e.includedOnlyMeshes.push(a),null==r.renderList&&(r.renderList=[]),r.renderList.indexOf(a)<0&&r.renderList.push(a)),!0===n){var s=a.getChildMeshes();null!=s&&s.length>0&&s.forEach(function(t){null!=e.includedOnlyMeshes&&e.includedOnlyMeshes.length>0&&e.includedOnlyMeshes.indexOf(t)<0&&e.includedOnlyMeshes.push(t),null==r.renderList&&(r.renderList=[]),r.renderList.indexOf(t)<0&&r.renderList.push(t)})}}}},t.RefreshShadowCascades=function(e){var t=null==e?void 0:e.getShadowGenerator();if(null!=t&&t instanceof BABYLON.CascadedShadowGenerator){try{t.shadowMaxZ++}catch(e){}try{t.shadowMaxZ--}catch(e){}}},t.RefreshAllShadowCascades=function(t){null!=t.lights&&t.lights.length>0&&t.lights.forEach(function(t){t instanceof BABYLON.ShadowLight&&e.SceneManager.RefreshShadowCascades(t)})},t.IsPhysicsViewerEnabled=function(){return e.SceneManager.PhysicsViewersEnabled},t.TogglePhysicsViewer=function(t){if(e.SceneManager.PhysicsViewersEnabled=!e.SceneManager.PhysicsViewersEnabled,e.SceneManager.PhysicsViewersEnabled){var n=new BABYLON.Debug.PhysicsViewer(t);null==t.reservedDataStore&&(t.reservedDataStore={}),t.reservedDataStore.physicsViewer=n;for(var i=0,r=t.meshes;i<r.length;i++){var o=r[i];o.physicsImpostor?(l=n.showImpostor(o.physicsImpostor,o))&&(l.reservedDataStore={hidden:!0},l.material&&(l.material.reservedDataStore={hidden:!0})):o.physicsBody&&(l=n.showBody(o.physicsBody))&&(l.reservedDataStore={hidden:!0},l.material&&(l.material.reservedDataStore={hidden:!0}))}for(var a=0,s=t.transformNodes;a<s.length;a++){var l,u=s[a];u.physicsBody&&(l=n.showBody(u.physicsBody))&&(l.reservedDataStore={hidden:!0},l.material&&(l.material.reservedDataStore={hidden:!0}))}}else t.reservedDataStore&&t.reservedDataStore.physicsViewer&&(t.reservedDataStore.physicsViewer.dispose(),t.reservedDataStore.physicsViewer=null)},t.GetImportMeshes=function(e,t){return null==e||null==t||""===t?null:null!=e.importMeshes?e.importMeshes.get(t.toLowerCase()):null},t.GetImportMeshesMap=function(e){return null==e?null:null!=e.importMeshes?e.importMeshes:null},t.ClearImportMeshes=function(e){if(null==e)return null;e.importMeshes,e.importMeshes=new Map},t.RegisterImportMeshes=function(e,t,n){null!=e&&null!=t&&""!==t&&null!=n&&(null==e.importMeshes&&(e.importMeshes=new Map),e.importMeshes.set(t.toLowerCase(),n))},t.LoadImportMeshes=function(t,n,i,r,o,a,s,l,u){var c=null,d=n+i,h=e.SceneManager.GetImportMeshes(r,d);return null!=h?o&&o(h):c=BABYLON.SceneLoader.ImportMesh(t,n,i,r,function(t){e.SceneManager.RegisterImportMeshes(r,d,t),o&&o(t)},a,s,l,u),c},t.LoadImportMeshesAsync=function(t,n,i,r,o,l,u){return a(this,void 0,void 0,function(){var a,c,d,h;return s(this,function(s){switch(s.label){case 0:return a=n+i,null==(c=e.SceneManager.GetImportMeshes(r,a))?[3,1]:[2,c];case 1:return d=null,[4,BABYLON.SceneLoader.ImportMeshAsync(t,n,i,r,o,l,u)];case 2:return null!=(h=s.sent())&&null!=h.meshes&&(d=h.meshes),e.SceneManager.RegisterImportMeshes(r,a,d),[2,d]}})})},t.GetAssetContainer=function(e,t){return null==e||null==t||""===t?null:null!=e.assetContainers?e.assetContainers.get(t.toLowerCase()):null},t.GetAssetContainerMap=function(e){return null==e?null:null!=e.assetContainers?e.assetContainers:null},t.ClearAssetContainers=function(e){if(null==e)return null;e.assetContainers,e.assetContainers=new Map},t.RegisterAssetContainer=function(e,t,n){null!=e&&null!=t&&""!==t&&null!=n&&(null==e.assetContainers&&(e.assetContainers=new Map),e.assetContainers.set(t.toLowerCase(),n))},t.LoadAssetContainer=function(t,n,i,r,o,a,s,l){var u=t+n,c=e.SceneManager.GetAssetContainer(i,u);null!=c?r&&r(c):BABYLON.SceneLoader.LoadAssetContainer(t,n,i,function(t){e.SceneManager.RegisterAssetContainer(i,u,t),r&&r(t)},o,a,s,l)},t.LoadAssetContainerAsync=function(t,n,i,r,o,l){return a(this,void 0,void 0,function(){var a,u,c;return s(this,function(s){switch(s.label){case 0:return a=t+n,null==(u=e.SceneManager.GetAssetContainer(i,a))?[3,1]:[2,u];case 1:return[4,BABYLON.SceneLoader.LoadAssetContainerAsync(t,n,i,r,o,l)];case 2:return c=s.sent(),e.SceneManager.RegisterAssetContainer(i,a,c),[2,c]}})})},t.GetMesh=function(e,t){return null==e?null:e.getNodeByName(t)},t.GetMeshByID=function(e,t){return null==e?null:e.getNodeById(t)},t.GetAbstractMesh=function(e,t){return null==e?null:e.getNodeByName(t)},t.GetAbstractMeshByID=function(e,t){return null==e?null:e.getNodeById(t)},t.GetTransformNode=function(e,t){return null==e?null:e.getNodeByName(t)},t.GetTransformNodeByID=function(e,t){return null==e?null:e.getNodeById(t)},t.GetTransformDetailMesh=function(e){var t=null,n=e.name+".Detail",i=e.getChildren(function(e){return e.name===n&&e instanceof BABYLON.AbstractMesh},!0);return null!=i&&i.length>0&&(t=i[0]),t},t.GetSkinnedMesh=function(e){return null!=e._skinnedMesh?e._skinnedMesh:null},t.GetPrimitiveMeshes=function(e){return e.getChildMeshes(!0,function(e){return e.name.indexOf("_primitive")>=0})},t.GetTransformLayer=function(e){return null!=e.metadata&&null!=e.metadata.toolkit&&null!=e.metadata.toolkit.layer?e.metadata.toolkit.layer:0},t.GetTransformLayerMask=function(e){return null!=e.metadata&&null!=e.metadata.toolkit&&null!=e.metadata.toolkit.layermask?e.metadata.toolkit.layermask:1},t.GetTransformLayerName=function(e){return null!=e.metadata&&null!=e.metadata.toolkit&&null!=e.metadata.toolkit.layername&&""!==e.metadata.toolkit.layername?e.metadata.toolkit.layername:"Default"},t.GetTransformTag=function(e){return null!=e.metadata&&null!=e.metadata.toolkit&&null!=e.metadata.toolkit.group&&""!==e.metadata.toolkit.group?e.metadata.toolkit.group:"Untagged"},t.HasTransformTags=function(e,t){return BABYLON.Tags.MatchesQuery(e,t)},t.HasSoundManager=function(){return null!=PROJECT&&null!=PROJECT.SceneSoundSystem},t.IsSoundEffectPlaying=function(e){return null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.SFX&&PROJECT.SceneSoundSystem.SFX.isPlaying(e)},t.IsMusicTrackPlaying=function(e){return null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.MUSIC&&PROJECT.SceneSoundSystem.MUSIC.isPlaying(e)},t.PlayOneShot=function(e,t,n,i){return a(this,void 0,void 0,function(){return s(this,function(r){return null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.SFX?[2,PROJECT.SceneSoundSystem.SFX.playTrack(e,t,n,i)]:[2,!1]})})},t.PlayMusicTrack=function(e,t,n,i){return a(this,void 0,void 0,function(){return s(this,function(r){return null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.MUSIC?[2,PROJECT.SceneSoundSystem.MUSIC.playTrack(e,t,n,i)]:[2,!1]})})},t.PauseMusicTrack=function(e){return null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.MUSIC&&PROJECT.SceneSoundSystem.MUSIC.pauseTrack(e)},t.MuteMusicTrack=function(e,t){return null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.MUSIC&&PROJECT.SceneSoundSystem.MUSIC.muteTrack(e,t,offset,length)},t.UnmuteMusicTrack=function(e,t){return null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.MUSIC&&PROJECT.SceneSoundSystem.MUSIC.unmuteTrack(e,t)},t.StopMusicTrack=function(e,t){return null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.MUSIC&&PROJECT.SceneSoundSystem.MUSIC.stopTrack(e,t)},t.StopAllMusicTracks=function(){null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.MUSIC&&PROJECT.SceneSoundSystem.MUSIC.stopAllTracks()},t.PauseAllMusicTracks=function(){null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.MUSIC&&PROJECT.SceneSoundSystem.MUSIC.pauseAllTracks()},t.MuteAllMusicTracks=function(e){null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.MUSIC&&PROJECT.SceneSoundSystem.MUSIC.muteAllTracks(e)},t.UnmuteAllMusicTracks=function(e){null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.MUSIC&&PROJECT.SceneSoundSystem.MUSIC.unmuteAllTracks(e)},t.TextureFloatSupported=function(e){var t=!1,n=!1,i=e.getEngine().getCaps();return i.textureHalfFloatRender&&i.textureHalfFloatLinearFiltering?t=!0:i.textureFloatRender&&i.textureFloatLinearFiltering&&(n=!0),t||n},t.RegisterClickAction=function(e,t,n){var i=null;return null!=t&&(t.isPickable=!0,null==t.actionManager&&(t.actionManager=new BABYLON.ActionManager(e)),i=t.actionManager.registerAction(new BABYLON.ExecuteCodeAction({trigger:BABYLON.ActionManager.OnPickTrigger},n))),i},t.UnregisterClickAction=function(e,t){var n=!1;return null!=e&&null!=t&&(n=e.actionManager.unregisterAction(t)),n},t.GetMaterialWithName=function(e,t){var n=null;if(null!=e.materials&&e.materials.length>0){e.materials.length;for(var i=0;i<e.materials.length;i++){var r=e.materials[i];if(r.name.startsWith(t)){n=r;break}}}return n},t.GetAllMaterialsWithName=function(e,t){var n=null;if(null!=e.materials&&e.materials.length>0){e.materials.length;for(var i=0;i<e.materials.length;i++){var r=e.materials[i];r.name.startsWith(t)&&(null==n&&(n=[]),n.push(r))}}return n},t.InstantiatePrefabFromScene=function(t,n,i,r,o,a,s,l){void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),void 0===l&&(l=!0);var u=null;if(null!=t&&null!=n&&""!==n){var c=t.getNodeByName(n);if(null!=c)if(null!=(u=c.clone(i,r,!1))){null!=o&&(u.position=o.clone()),null!=a&&(u.rotationQuaternion=a.clone()),null!=s&&(u.scaling=s.clone());var d=null,h=u.getChildren(null,!1);null!=h&&(d=h),null==d?d=[u]:d.unshift(u),d.forEach(function(e){if(e.setEnabled(!0),e instanceof BABYLON.AbstractMesh&&null!=e.metadata&&null!=e.metadata.shadowCastingMode&&0!==e.metadata.shadowCastingMode&&t.lights.forEach(function(t){var n=t.getShadowGenerator();if(null!=n&&!1==(null!=t.includedOnlyMeshes&&t.includedOnlyMeshes.length>0)){var i=n.getShadowMap();null==i.renderList&&(i.renderList=[]),i.renderList.indexOf(e)<0&&i.renderList.push(e)}}),e instanceof BABYLON.Mesh)if(null!=e.source){if(null==e.skeleton&&null!=e.source.skeleton){var n=e.source.skeleton.name+".Skeleton",i=n+"."+e.source.skeleton.id;if(e.skeleton=e.source.skeleton.clone(n,i),null!=e.skeleton&&null!=e.skeleton.bones&&null!=e.source.skeleton.bones&&e.skeleton.bones.length===e.source.skeleton.bones.length)for(var r=e.skeleton.bones.length,o=0;o<r;o++)null==e.skeleton.bones[o].metadata&&null!=e.source.skeleton.bones[o].metadata&&(e.skeleton.bones[o].metadata=e.source.skeleton.bones[o].metadata)}}else BABYLON.Tools.Warn("Babylon.js encountered a null clone source for: "+e.name)});var p=[];if(d.forEach(function(e){p.push(e)}),null!=p&&p.length>0){var m=[];e.Utilities.PostParseSceneComponents(t,p,null,m),t.onAfterRenderObservable.addOnce(function(){if(null!=m&&m.length>0)for(var e=0;e<m.length;e++){var t=m[e];null!=t&&t.delayComponentInstance&&t.delayComponentInstance(t)}})}}else BABYLON.Tools.Warn("Failed to create prefab of: "+n);else BABYLON.Tools.Warn("Failed to lookup prefab map: "+n)}else BABYLON.Tools.Warn("Unable to locate prefab master: "+n);return u},t.InstantiatePrefabFromContainer=function(t,n,i,r,o,a,s,l,u){void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),void 0===l&&(l=!0),void 0===u&&(u=!1);var c=e.Utilities.CloneAssetContainerItem(t,n,function(e){return e},r,u,l);if(null!=c){null!=i&&""!==i&&(c.name=i),null!=o&&(c.position=o.clone()),null!=a&&(c.rotationQuaternion=a.clone()),null!=s&&(c.scaling=s.clone());var d=[];d.push(c);var h=c.getChildren(null,!1);null!=h&&h.length>0&&h.forEach(function(e){d.push(e)}),d.forEach(function(t){t.id=e.Utilities.CreateGuid(),t.setEnabled(!0)});var p=[];e.Utilities.PostParseSceneComponents(t.scene,d,null,p),t.scene.onAfterRenderObservable.addOnce(function(){if(null!=p&&p.length>0)for(var e=0;e<p.length;e++){var t=p[e];null!=t&&t.delayComponentInstance&&t.delayComponentInstance(t)}})}return c},t.InstantiateModelsFromContainer=function(t,n,i,r,o,a){void 0===n&&(n=null),void 0===i&&(i=!1),void 0===r&&(r=!1),void 0===o&&(o=!1),void 0===a&&(a=null);var s=null,u=t.instantiateModelsToScene(n,r,{doNotInstantiate:!i,predicate:a});if(null!=u&&null!=u.rootNodes&&u.rootNodes.length>0){var c=u.rootNodes[0],d=c.getChildren(null,!1);!0===o&&e.SceneManager.RebuildBoundingBoxInfo(d),s=l([c],d,!0)}return s},t.CreateInstancedModelsFromContainer=function(t,n,i,r,o,a,s,l,u){void 0===n&&(n=null),void 0===i&&(i=null),void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=!0),void 0===l&&(l=!1),void 0===u&&(u=!1);var c=null,d=null,h=null,p=t.instantiateModelsToScene(function(e){return e},l,{doNotInstantiate:!1});if(null!=p&&(null!=p.rootNodes&&p.rootNodes.length>0&&(d=p.rootNodes[0].getChildren(null,!1),!0===u&&e.SceneManager.RebuildBoundingBoxInfo(d)),null!=p.animationGroups&&(h=p.animationGroups)),null!=d){if(c=d[0],null!=i&&(c.parent=i),null!=n&&""!==n&&(c.name=n),null!=r&&(c.position=r.clone()),null!=o&&(c.rotationQuaternion=o.clone()),null!=a&&(c.scaling=a.clone()),d.forEach(function(t){t.id=e.Utilities.CreateGuid(),t.setEnabled(!0)}),!0===s){var m=null;h.forEach(function(e){var t=e,n=null!=t.metadata&&null!=t.metadata.toolkit&&null!=t.metadata.toolkit.source&&""!==t.metadata.toolkit.source?t.metadata.toolkit.source:null;if(null!=n&&""!==n){var i=e.clone(e.name),r=n;null!=t.metadata&&(i.metadata={},i.metadata.toolkit={},i.metadata.toolkit.id=t.metadata.toolkit.id,i.metadata.toolkit.clip=t.metadata.toolkit.clip,i.metadata.toolkit.source=r,i.metadata.toolkit.legacy=t.metadata.toolkit.legacy,i.metadata.toolkit.length=t.metadata.toolkit.length,i.metadata.toolkit.looping=t.metadata.toolkit.looping,i.metadata.toolkit.settings=t.metadata.toolkit.settings,i.metadata.toolkit.behavior=t.metadata.toolkit.behavior,i.metadata.toolkit.wrapmode=t.metadata.toolkit.wrapmode,i.metadata.toolkit.framerate=t.metadata.toolkit.framerate,i.metadata.toolkit.humanmotion=t.metadata.toolkit.humanmotion,i.metadata.toolkit.averagespeed=t.metadata.toolkit.averagespeed,i.metadata.toolkit.averageduration=t.metadata.toolkit.averageduration,i.metadata.toolkit.averageangularspeed=t.metadata.toolkit.averageangularspeed),null==m&&(m=[]),m.push(i)}}),null!=c&&null!=m&&e.Utilities.AssignAnimationGroupsToInstance(c,m)}var f=[];e.Utilities.PostParseSceneComponents(t.scene,d,null,f),t.scene.onAfterRenderObservable.addOnce(function(){if(null!=f&&f.length>0)for(var e=0;e<f.length;e++){var t=f[e];null!=t&&t.delayComponentInstance&&t.delayComponentInstance(t)}})}return p},t.CloneTransformNode=function(t,n,i,r,o,a,s){void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null);var l=e.Utilities.GetAssetContainerNode(t,n).clone(i,r,!0);return null!=l&&(null!=o&&(l.position=o.clone()),null!=a&&(l.rotationQuaternion=a.clone()),null!=s&&(l.scaling=s.clone()),l.setEnabled(!0)),l},t.CloneAbstractMesh=function(t,n,i,r,o,a,s){void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null);var l=e.Utilities.GetAssetContainerMesh(t,n).clone(i,r,!0);return null!=l&&(null!=o&&(l.position=o.clone()),null!=a&&(l.rotationQuaternion=a.clone()),null!=s&&(l.scaling=s.clone()),l.setEnabled(!0)),l},t.CreateInstancedMesh=function(t,n,i,r,o,a,s){void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null);var l=e.Utilities.GetAssetContainerMesh(t,n).createInstance(i);return null!=l&&(null!=r&&(l.parent=r),null!=o&&(l.position=o.clone()),null!=a&&(l.rotationQuaternion=a.clone()),null!=s&&(l.scaling=s.clone()),l.setEnabled(!0)),l},t.RebuildBoundingBoxInfo=function(e){null!=e&&e.length>0&&e.forEach(function(e){var t,n;if(e instanceof BABYLON.InstancedMesh){var i=null===(t=e.sourceMesh.getBoundingInfo())||void 0===t?void 0:t.boundingBox;null!=i&&null!=i.minimum&&null!=i.maximum&&e.setBoundingInfo(new BABYLON.BoundingInfo(i.minimum,i.maximum))}else if(e instanceof BABYLON.AbstractMesh){var r=null===(n=e.getBoundingInfo())||void 0===n?void 0:n.boundingBox;null!=r&&null!=r.minimum&&null!=r.maximum&&e.setBoundingInfo(new BABYLON.BoundingInfo(r.minimum,r.maximum))}})},t.AttachScriptComponent=function(e,t,n){void 0===n&&(n=!0),null!=e&&e.registerComponentInstance&&e.registerComponentInstance(e,t,n)},t.DestroyScriptComponent=function(e){null!=e&&e.destroyComponentInstance&&e.destroyComponentInstance(e)},t.DestroyGameObject=function(t){if(null!=t){var n=e.SceneManager.FindScriptComponents(t,!0);if(null!=n&&n.length>0)for(var i=0;i<n.length;i++){var r=n[i];e.SceneManager.DestroyScriptComponent(r)}e.SceneManager.SafeDestroy(t)}},t.GetComponent=function(t,n,i){return void 0===i&&(i=!1),e.SceneManager.FindScriptComponent(t,n,i)},t.GetComponents=function(t,n){return void 0===n&&(n=!1),e.SceneManager.FindScriptComponents(t,n)},t.FindGameObject=function(e,t){if(!t||""===t.trim())return null;var n=t.split("/").filter(function(e){return""!==e.trim()});if(0===n.length)return null;for(var i=null,r=e.rootNodes,o=function(e){var t=n[e];if(0===e)i=r.find(function(e){return e.name===t})||null;else{if(!i)return"break";var o=i.getChildren(null,!1);i=o.find(function(e){return e.name===t})||null}if(!i)return"break"},a=0;a<n.length&&"break"!==o(a);a++);if(i&&i instanceof BABYLON.TransformNode)return i;for(var s=0,l=r;s<l.length;s++){var u=l[s];if(u.name&&u.getChildren){var c,d="".concat(u.name,"/").concat(t);if(d!==t&&(c=this.FindGameObjectExactPath(e,d)))return c}}return 1===n.length&&(c=this.FindGameObjectRecursive(e,n[0]))?c:null},t.FindGameObjectExactPath=function(e,t){for(var n=t.split("/").filter(function(e){return""!==e.trim()}),i=null,r=e.rootNodes,o=function(e){var t=n[e];if(0===e)i=r.find(function(e){return e.name===t})||null;else{if(!i)return{value:null};var o=i.getChildren(null,!1);i=o.find(function(e){return e.name===t})||null}if(!i)return{value:null}},a=0;a<n.length;a++){var s=o(a);if("object"==typeof s)return s.value}return i instanceof BABYLON.TransformNode?i:null},t.FindGameObjectRecursive=function(e,t){for(var n=function(e){if(e.name===t&&e instanceof BABYLON.TransformNode)return e;if(e.getChildren)for(var i=0,r=e.getChildren(null,!1);i<r.length;i++){var o=r[i],a=n(o);if(a)return a}return null},i=0,r=e.rootNodes;i<r.length;i++){var o=r[i],a=n(o);if(a)return a}return null},t.DebugSceneHierarchy=function(e,t){void 0===t&&(t=3),console.log("=== SCENE HIERARCHY DEBUG ===");var n=function(e,i,r){if(void 0===r&&(r=""),!(i>t)){var o=" ".repeat(i),a=e instanceof BABYLON.TransformNode?"TransformNode":e instanceof BABYLON.AbstractMesh?"Mesh":e instanceof BABYLON.Camera?"Camera":e instanceof BABYLON.Light?"Light":e.constructor.name;if(console.log("".concat(o).concat(r).concat(e.name," (").concat(a,")")),e instanceof BABYLON.TransformNode||e instanceof BABYLON.AbstractMesh){var s=e.getChildren(null,!1);s.forEach(function(e,t){var r=t===s.length-1;n(e,i+1,r?"└─ ":"├─ ")})}}};console.log("Root nodes:"),e.rootNodes.forEach(function(t,i){var r=i===e.rootNodes.length-1;n(t,0,r?"└─ ":"├─ ")}),console.log("=== END HIERARCHY DEBUG ===")},t.LegacySearchForGameObject=function(e,t){for(var n=t.split("/"),i=null,r=e.rootNodes,o=function(e){var t=n[e];if(0===e)i=r.find(function(e){return e.name===t})||null;else{if(!(i&&i instanceof BABYLON.TransformNode))return{value:null};i=i.getChildren(function(e){return e.name===t},!1)[0]||null}if(!i)return{value:null}},a=0;a<n.length;a++){var s=o(a);if("object"==typeof s)return s.value}return i},t.FindGameObjectWithTag=function(t,n){for(var i=function(t){if(e.SceneManager.GetTransformTag(t)===n)return t;if(t instanceof BABYLON.TransformNode)for(var r=0,o=t.getChildren();r<o.length;r++){var a=o[r];if(a instanceof BABYLON.TransformNode){var s=i(a);if(s)return s}}return null},r=0,o=t.rootNodes;r<o.length;r++){var a=o[r];if(a instanceof BABYLON.TransformNode){var s=i(a);if(s)return s}}return null},t.FindGameObjectsWithTag=function(t,n){for(var i=[],r=function(t){if(e.SceneManager.GetTransformTag(t)===n&&i.push(t),t instanceof BABYLON.TransformNode)for(var o=0,a=t.getChildren();o<a.length;o++){var s=a[o];s instanceof BABYLON.TransformNode&&r(s)}},o=0,a=t.rootNodes;o<a.length;o++){var s=a[o];s instanceof BABYLON.TransformNode&&r(s)}return i},t.FindScriptComponents=function(t,n){if(void 0===n&&(n=!1),null==t)return null;var i=null;if(null!=t.metadata&&t.metadata.toolkit){var r=t.metadata.toolkit;if(null!=r.components&&r.components.length>0)for(var o=0;o<r.components.length;o++){var a=r.components[o];null==i&&(i=[]),i.push(a.instance)}}if(!0===n){var s=t.getChildren(null,!1);if(null!=s)for(var l=0;l<s.length;l++){var u=s[l],c=e.SceneManager.FindScriptComponents(u,!1);null!=c&&(null==i&&(i=[]),i.push.apply(i,c))}}return null!=i?i:null},t.FindScriptComponent=function(t,n,i){if(void 0===i&&(i=!1),null==t)return null;var r=null;if(null!=t.metadata&&t.metadata.toolkit){var o=t.metadata.toolkit;if(null!=o.components&&o.components.length>0)for(var a=0;a<o.components.length;a++){var s=o.components[a];if(null!=s.instance&&s.klass===n){r=s.instance;break}}}if(null==r&&!0===i){var l=t.getChildren(null,!1);if(null!=l)for(var u=0;u<l.length;u++){var c=l[u];if(null!=(r=e.SceneManager.FindScriptComponent(c,n,!1)))break}}return null!=r?r:null},t.FindAllScriptComponents=function(t,n,i){if(void 0===i&&(i=!1),null==t)return null;var r=null;if(null!=t.metadata&&t.metadata.toolkit){var o=t.metadata.toolkit;if(null!=o.components&&o.components.length>0)for(var a=0;a<o.components.length;a++){var s=o.components[a];null!=s.instance&&s.klass===n&&(null==r&&(r=[]),r.push(s.instance))}}if(!0===i){var l=t.getChildren(null,!1);if(null!=l)for(var u=0;u<l.length;u++){var c=l[u],d=e.SceneManager.FindAllScriptComponents(c,n,!1);null!=d&&(null==r&&(r=[]),r.push.apply(r,d))}}return null!=r?r:null},t.FindSceneMetadata=function(e){return null==e?null:null!=e.metadata&&e.metadata.toolkit?e.metadata.toolkit:null},t.FindSceneCameraRig=function(e){return null==e?null:null!=e.cameraRig?e.cameraRig:null},t.FindSceneLightRig=function(e){return null==e?null:null!=e.lightRig?e.lightRig:null},t.FindTransformWithScript=function(t,n){var i=t.getNodes();return e.Utilities.SearchTransformNodeForScript(n,i)},t.FindAllTransformsWithScript=function(t,n){var i=t.getNodes();return e.Utilities.SearchAllTransformNodesForScript(n,i)},t.FindChildTransformNode=function(t,n,i,r,o){if(void 0===i&&(i=e.SearchType.ExactMatch),void 0===r&&(r=!0),void 0===o&&(o=null),null==t)return null;var a=null!=i?i:e.SearchType.ExactMatch,s=t.getChildren(o,r);return e.Utilities.SearchTransformNodes(n,s,a)},t.FindChildTransformWithTags=function(t,n,i,r){if(void 0===i&&(i=!0),void 0===r&&(r=null),null==t)return null;var o=t.getChildren(r,i);return e.Utilities.SearchTransformNodeForTags(n,o)},t.FindAllChildTransformsWithTags=function(t,n,i,r){if(void 0===i&&(i=!0),void 0===r&&(r=null),null==t)return null;var o=t.getChildren(r,i);return e.Utilities.SearchAllTransformNodesForTags(n,o)},t.FindChildTransformWithScript=function(t,n,i,r){if(void 0===i&&(i=!0),void 0===r&&(r=null),null==t)return null;var o=t.getChildren(r,i);return e.Utilities.SearchTransformNodeForScript(n,o)},t.FindAllChildTransformsWithScript=function(t,n,i,r){if(void 0===i&&(i=!0),void 0===r&&(r=null),null==t)return null;var o=t.getChildren(r,i);return e.Utilities.SearchAllTransformNodesForScript(n,o)},t.FindComponentInParent=function(t,n,i){var r=null!=n.parent?[n,n.parent]:[n],o=e.Utilities.SearchTransformNodeForScript(i,r);return e.SceneManager.FindScriptComponent(o,i)},t.FindComponentsInParent=function(t,n,i){var r=null,o=n.getChildren(null,!1),a=null!=o?l([n],o,!0):[n],s=e.Utilities.SearchAllTransformNodesForScript(i,a);return null!=s&&s.length>0&&s.forEach(function(t){var n=e.SceneManager.FindScriptComponent(t,i);null!=n&&(null==r&&(r=[]),r.push(n))}),null!=r?r:null},t.FindComponentInChildren=function(t,n,i){var r=n.getChildren(null,!1),o=null!=r?l([n],r,!0):[n],a=e.Utilities.SearchTransformNodeForScript(i,o);return e.SceneManager.FindScriptComponent(a,i)},t.FindComponentsInChildren=function(t,n,i){var r=null,o=n.getChildren(null,!1),a=null!=o?l([n],o,!0):[n],s=e.Utilities.SearchAllTransformNodesForScript(i,a);return null!=s&&s.length>0&&s.forEach(function(t){var n=e.SceneManager.FindScriptComponent(t,i);null!=n&&(null==r&&(r=[]),r.push(n))}),null!=r?r:null},t.SearchForScriptComponentByName=function(t,n){var i=t.getNodes(),r=e.Utilities.SearchTransformNodeForScript(n,i);return e.SceneManager.FindScriptComponent(r,n)},t.SearchForAllScriptComponentsByName=function(t,n){var i=null,r=t.getNodes(),o=e.Utilities.SearchAllTransformNodesForScript(n,r);return null!=o&&o.length>0&&o.forEach(function(t){var r=e.SceneManager.FindScriptComponent(t,n);null!=r&&(null==i&&(i=[]),i.push(r))}),null!=i?i:null},t.MoveWithCollisions=function(e,t){if(null==e)return null;null!=t&&e.moveWithCollisions(t)},t.MoveWithTranslation=function(e,t){if(null==e)return null;null!=t&&e.position.addInPlace(t)},t.TurnWithRotation=function(e,t,n){if(void 0===n&&(n=BABYLON.Space.LOCAL),null==e)return null;0!=t&&e.rotate(BABYLON.Axis.Y,t,n)},t.HasNavigationData=function(){return null!=e.SceneManager.NavMeshPlugin&&null!=e.SceneManager.NavMeshPlugin.navMesh},t.GetNavigationData=function(){return null!=e.SceneManager.NavMeshPlugin&&null!=e.SceneManager.NavMeshPlugin.navMesh?e.SceneManager.NavMeshPlugin.navMesh:null},t.GetNavigationMesh=function(){return null!=e.SceneManager.NavMeshSurface?e.SceneManager.NavMeshSurface:null},t.GetNavigationDebug=function(){return null!=e.SceneManager.NavMeshDebugger?e.SceneManager.NavMeshDebugger:null},t.GetNavigationPlugin=function(){return null!=e.SceneManager.NavMeshPlugin?e.SceneManager.NavMeshPlugin:null},t.GetCrowdInterface=function(t){if(null!=e.SceneManager.NavMeshPlugin&&null!=e.SceneManager.NavMeshPlugin.navMesh){var n=e.SceneManager.GetNavigationPlugin();return null!=n&&null==e.SceneManager.CrowdInterface&&(e.SceneManager.CrowdInterface=n.createCrowd(e.SceneManager.MAX_AGENT_COUNT,e.SceneManager.MAX_AGENT_RADIUS,t)),e.SceneManager.CrowdInterface}return null},t.LoadNavigationMeshDataAsync=function(t,n){return a(this,arguments,void 0,function(t,n,i,r){var o,l,u=this;return void 0===i&&(i=null),void 0===r&&(r=!1),s(this,function(c){switch(c.label){case 0:return e.SceneManager.DestroyNavigationMeshData(),o=new BABYLON.AssetsManager(t),(l=o.addBinaryFileTask("System.NavigationMeshTask",n)).onSuccess=function(o){return a(u,void 0,void 0,function(){var a;return s(this,function(s){switch(s.label){case 0:return null==o.data?[3,2]:(a=new Uint8Array(o.data),[4,e.SceneManager.BuildNavigationMeshDataAsync(t,a,i,r)]);case 1:return s.sent(),[3,3];case 2:console.error("Failed to load navigation mesh task: "+n),s.label=3;case 3:return[2]}})})},l.onError=function(e,t,n){console.error(t,n)},[4,o.loadAsync()];case 1:return c.sent(),[2]}})})},t.BuildNavigationMeshDataAsync=function(t,n){return a(this,arguments,void 0,function(t,n,i,r){var o;return void 0===i&&(i=null),void 0===r&&(r=!1),s(this,function(a){switch(a.label){case 0:return null==n?[2]:(e.SceneManager.DestroyNavigationMeshData(),e.SceneManager.NavMeshSurface=i,null!=e.SceneManager.NavMeshPlugin?[3,2]:(o=e.SceneManager,[4,ADDONS.CreateNavigationPluginAsync()]));case 1:o.NavMeshPlugin=a.sent(),a.label=2;case 2:return null!=e.SceneManager.NavMeshPlugin&&(e.SceneManager.NavMeshPlugin.buildFromNavmeshData(n),!0===r&&(e.SceneManager.NavMeshDebugger=e.SceneManager.NavMeshPlugin.createDebugNavMesh(t),null!=e.SceneManager.NavMeshDebugger&&(e.SceneManager.NavMeshDebugger.checkCollisions=!1,e.SceneManager.NavMeshDebugger.isPickable=!1,e.SceneManager.NavMeshDebugger.isVisible=!0,e.SceneManager.NavMeshDebugger.visibility=1,null==e.SceneManager.NavMeshMaterial&&(e.SceneManager.NavMeshMaterial=new BABYLON.StandardMaterial("Navmesh-Debug-Material",t),e.SceneManager.NavMeshMaterial.transparencyMode=BABYLON.Material.MATERIAL_ALPHABLEND,e.SceneManager.NavMeshMaterial.backFaceCulling=!1,e.SceneManager.NavMeshMaterial.diffuseColor=new BABYLON.Color3(0,.75,1),e.SceneManager.NavMeshMaterial.alpha=.5),e.SceneManager.NavMeshDebugger.material=e.SceneManager.NavMeshMaterial)),e.SceneManager.OnNavMeshReadyObservable.hasObservers()&&e.SceneManager.OnNavMeshReadyObservable.notifyObservers(e.SceneManager.GetNavigationMesh())),[2]}})})},t.BuildNavigationMeshTileCacheAsync=function(t,n){return a(this,arguments,void 0,function(t,n,i,r,o){var a;return void 0===i&&(i=null),void 0===r&&(r=null),void 0===o&&(o=!1),s(this,function(s){switch(s.label){case 0:return null==n?[2]:(e.SceneManager.DestroyNavigationMeshData(),e.SceneManager.NavMeshSurface=r,null!=e.SceneManager.NavMeshPlugin?[3,2]:(a=e.SceneManager,[4,ADDONS.CreateNavigationPluginAsync()]));case 1:a.NavMeshPlugin=s.sent(),s.label=2;case 2:return null!=e.SceneManager.NavMeshPlugin&&(null==i&&(i=function(e,t,n){for(var i=0;i<e.polyCount();i++)t.set(i,0),n.set(i,1)}),e.SceneManager.NavMeshPlugin.buildFromTileCacheData(n,i),!0===o&&(e.SceneManager.NavMeshDebugger=e.SceneManager.NavMeshPlugin.createDebugNavMesh(t),null!=e.SceneManager.NavMeshDebugger&&(e.SceneManager.NavMeshDebugger.checkCollisions=!1,e.SceneManager.NavMeshDebugger.isPickable=!1,e.SceneManager.NavMeshDebugger.isVisible=!0,e.SceneManager.NavMeshDebugger.visibility=1,null==e.SceneManager.NavMeshMaterial&&(e.SceneManager.NavMeshMaterial=new BABYLON.StandardMaterial("Navmesh-Debug-Material",t),e.SceneManager.NavMeshMaterial.transparencyMode=BABYLON.Material.MATERIAL_ALPHABLEND,e.SceneManager.NavMeshMaterial.backFaceCulling=!1,e.SceneManager.NavMeshMaterial.diffuseColor=new BABYLON.Color3(0,.75,1),e.SceneManager.NavMeshMaterial.alpha=.5),e.SceneManager.NavMeshDebugger.material=e.SceneManager.NavMeshMaterial)),e.SceneManager.OnNavMeshReadyObservable.hasObservers()&&e.SceneManager.OnNavMeshReadyObservable.notifyObservers(e.SceneManager.GetNavigationMesh())),[2]}})})},t.CreateNavigationMeshSceneDataAsync=function(t,n,i){return a(this,arguments,void 0,function(t,n,i,r,o){var a,l;return void 0===r&&(r=null),void 0===o&&(o=!1),s(this,function(s){switch(s.label){case 0:return null==n||null==i||0===i.length?[2]:(e.SceneManager.DestroyNavigationMeshData(),e.SceneManager.NavMeshSurface=r,null!=e.SceneManager.NavMeshPlugin?[3,2]:(a=e.SceneManager,[4,ADDONS.CreateNavigationPluginAsync()]));case 1:a.NavMeshPlugin=s.sent(),s.label=2;case 2:return null==e.SceneManager.NavMeshPlugin?[3,4]:(l={cs:n.cs||.2,ch:n.ch||.2,walkableSlopeAngle:n.walkableslopeangle||45,walkableHeight:n.walkableheight||2,walkableClimb:n.walkableclimb||1,walkableRadius:n.walkableradius||.5,maxEdgeLen:n.maxedgelen||12,maxSimplificationError:n.maxsimplificationerror||1.3,minRegionArea:n.minregionarea||2,mergeRegionArea:n.mergeregionarea||20,maxVertsPerPoly:n.maxvertsperpoly||6,detailSampleDist:n.detailsampledist||6,detailSampleMaxError:n.detailsamplemaxerror||1,tileSize:n.tilesize||32,borderSize:0,offMeshConnections:null,keepIntermediates:!1,maxObstacles:0,expectedLayersPerTile:32,tileCacheMeshProcess:null,doNotReverseIndices:!1},[4,e.SceneManager.NavMeshPlugin.createNavMeshAsync(i,l)]);case 3:s.sent(),!0===o&&(e.SceneManager.NavMeshDebugger=e.SceneManager.NavMeshPlugin.createDebugNavMesh(t),null!=e.SceneManager.NavMeshDebugger&&(e.SceneManager.NavMeshDebugger.checkCollisions=!1,e.SceneManager.NavMeshDebugger.isPickable=!1,e.SceneManager.NavMeshDebugger.isVisible=!0,e.SceneManager.NavMeshDebugger.visibility=1,null==e.SceneManager.NavMeshMaterial&&(e.SceneManager.NavMeshMaterial=new BABYLON.StandardMaterial("Navmesh-Debug-Material",t),e.SceneManager.NavMeshMaterial.transparencyMode=BABYLON.Material.MATERIAL_ALPHABLEND,e.SceneManager.NavMeshMaterial.backFaceCulling=!1,e.SceneManager.NavMeshMaterial.diffuseColor=new BABYLON.Color3(0,.75,1),e.SceneManager.NavMeshMaterial.alpha=.5),e.SceneManager.NavMeshDebugger.material=e.SceneManager.NavMeshMaterial)),e.SceneManager.OnNavMeshReadyObservable.hasObservers()&&e.SceneManager.OnNavMeshReadyObservable.notifyObservers(e.SceneManager.GetNavigationMesh()),s.label=4;case 4:return[2]}})})},t.DestroyNavigationMeshData=function(){if(e.SceneManager.NavMeshSurface=null,null!=e.SceneManager.NavMeshDebugger){try{e.SceneManager.NavMeshDebugger.dispose()}catch(e){console.warn("Failed to dispose previous NavMesh debugger: ",e)}e.SceneManager.NavMeshDebugger=null}if(null!=e.SceneManager.NavMeshPlugin&&null!=e.SceneManager.NavMeshPlugin.navMesh){try{e.SceneManager.NavMeshPlugin.navMesh.destroy()}catch(e){console.warn("Failed to destroy previous navMesh data object: ",e)}e.SceneManager.NavMeshPlugin.navMesh=null}if(null!=e.SceneManager.NavMeshPlugin&&null!=e.SceneManager.NavMeshPlugin.navMeshQuery){try{e.SceneManager.NavMeshPlugin.navMeshQuery.destroy()}catch(e){console.warn("Failed to destroy previous navMesh query object: ",e)}if(e.SceneManager.NavMeshPlugin._navMeshQuery)try{e.SceneManager.NavMeshPlugin._navMeshQuery=null}catch(e){console.warn("Failed to set previous navMesh query object to null: ",e)}}},t.ToggleFullscreenMode=function(e,t){void 0===t&&(t=!0),e.getEngine().switchFullscreen(t)},t.EnterFullscreenMode=function(t,n){void 0===n&&(n=!0),e.SceneManager.GotoFullscreenBrowser(t,n)},t.ExitFullscreenMode=function(t){e.SceneManager.ExitFromFullscreenBrowser(t)},t.GotoFullscreenBrowser=function(t,n){void 0===n&&(n=!0);var i=document.documentElement;i.requestFullscreen?i.requestFullscreen().then(function(){!0===n&&e.SceneManager.RequestBrowserPointerLock(i)}).catch(function(e){console.error("Error attempting to enable full-screen mode: ".concat(e.message," (").concat(e.name,")"))}):i.mozRequestFullScreen?(i.mozRequestFullScreen(),!0===n&&e.SceneManager.RequestBrowserPointerLock(i)):i.webkitRequestFullscreen?(i.webkitRequestFullscreen(),!0===n&&e.SceneManager.RequestBrowserPointerLock(i)):i.msRequestFullscreen?(i.msRequestFullscreen(),!0===n&&e.SceneManager.RequestBrowserPointerLock(i)):t.getEngine().enterFullscreen(n)},t.RequestBrowserPointerLock=function(e){e.requestPointerLock?e.requestPointerLock():e.mozRequestPointerLock?e.mozRequestPointerLock():e.webkitRequestPointerLock&&e.webkitRequestPointerLock()},t.ExitFromFullscreenBrowser=function(e){var t=document;t.exitFullscreen?t.exitFullscreen():t.mozCancelFullScreen?t.mozCancelFullScreen():t.webkitExitFullscreen?t.webkitExitFullscreen():t.msExitFullscreen?t.msExitFullscreen():e.getEngine().exitFullscreen()},t.CreateEasingFunction=function(e){if(!e)return null;if("string"==typeof e){var t=void 0;switch(e.toLowerCase()){case"linear":case"sineout":default:return(t=new BABYLON.SineEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEOUT),t;case"sinein":return(t=new BABYLON.SineEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN),t;case"sineinout":return(t=new BABYLON.SineEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT),t;case"quadin":return(t=new BABYLON.QuadraticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN),t;case"quadout":return(t=new BABYLON.QuadraticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEOUT),t;case"quadinout":return(t=new BABYLON.QuadraticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT),t;case"cubicin":return(t=new BABYLON.CubicEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN),t;case"cubicout":return(t=new BABYLON.CubicEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEOUT),t;case"cubicinout":return(t=new BABYLON.CubicEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT),t;case"quartin":return(t=new BABYLON.QuarticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN),t;case"quartout":return(t=new BABYLON.QuarticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEOUT),t;case"quartinout":return(t=new BABYLON.QuarticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT),t;case"quintin":return(t=new BABYLON.QuinticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN),t;case"quintout":return(t=new BABYLON.QuinticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEOUT),t;case"quintinout":return(t=new BABYLON.QuinticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT),t;case"expoin":return(t=new BABYLON.ExponentialEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN),t;case"expoout":return(t=new BABYLON.ExponentialEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEOUT),t;case"expoinout":return(t=new BABYLON.ExponentialEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT),t;case"circlein":return(t=new BABYLON.CircleEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN),t;case"circleout":return(t=new BABYLON.CircleEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEOUT),t;case"circleinout":return(t=new BABYLON.CircleEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT),t;case"backin":return(t=new BABYLON.BackEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN),t;case"backout":return(t=new BABYLON.BackEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEOUT),t;case"backinout":return(t=new BABYLON.BackEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT),t;case"elasticin":return(t=new BABYLON.ElasticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN),t;case"elasticout":return(t=new BABYLON.ElasticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEOUT),t;case"elasticinout":return(t=new BABYLON.ElasticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT),t;case"bouncein":return(t=new BABYLON.BounceEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN),t;case"bounceout":return(t=new BABYLON.BounceEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEOUT),t;case"bounceinout":return(t=new BABYLON.BounceEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT),t}}return e},t.GetPropertyValue=function(e,t){for(var n=e,i=0,r=t.split(".");i<r.length;i++){var o=r[i];if(!n||"object"!=typeof n||!(o in n))return;n=n[o]}return n},t.SetPropertyValue=function(e,t,n){for(var i=t.split("."),r=e,o=0;o<i.length-1;o++){var a=i[o];a in r&&"object"==typeof r[a]||(r[a]={}),r=r[a]}r[i[i.length-1]]=n},t.IsGUIControl=function(e){if(!e)return!1;if(e.getClassName&&"function"==typeof e.getClassName){var t=e.getClassName();if(t&&t.includes("GUI"))return!0}return!!(e._host&&e._currentMeasure&&e._markAsDirty)||!!(e.constructor&&e.constructor.name&&e.constructor.name.includes("Control"))},t.IsGUIPositionProperty=function(e){return["left","top","width","height","paddingLeft","paddingTop","paddingRight","paddingBottom"].includes(e)},t.ExtractGUINumericValue=function(e,t){if(!e||!t)return 0;var n=t+"InPixels";if(void 0!==e[n]){var i=e[n];if("number"==typeof i&&!isNaN(i))return i}var r=e[t];return"string"==typeof r?r.endsWith("px")||r.endsWith("%")?parseFloat(r):parseFloat(r)||0:"number"==typeof r?r:0},t.CreateGUIAnimationProxy=function(t,n){var i={_control:t,_property:n,animations:[]};return Object.defineProperty(i,n,{get:function(){return e.SceneManager.ExtractGUINumericValue(i._control,i._property)},set:function(e){var t=i._property+"InPixels";void 0!==i._control[t]?i._control[t]=e:i._control[i._property]=e+"px"},enumerable:!0,configurable:!0}),i},t.GetAnimationType=function(e){if("number"==typeof e)return BABYLON.Animation.ANIMATIONTYPE_FLOAT;if(e&&"object"==typeof e){if(void 0!==e.x&&void 0!==e.y)return void 0!==e.z?BABYLON.Animation.ANIMATIONTYPE_VECTOR3:BABYLON.Animation.ANIMATIONTYPE_VECTOR2;if(void 0!==e.r&&void 0!==e.g&&void 0!==e.b)return BABYLON.Animation.ANIMATIONTYPE_COLOR3;if(void 0!==e.w&&void 0!==e.x&&void 0!==e.y&&void 0!==e.z)return BABYLON.Animation.ANIMATIONTYPE_QUATERNION}return BABYLON.Animation.ANIMATIONTYPE_FLOAT},t.CreateTweenAnimations=function(t,n,i,r,o){var a=[],s=[],l=60*(r.duration||1),u=e.SceneManager.IsGUIControl(t);for(var c in r.yoyo&&r.loop||r.yoyo&&r.yoyoCount&&r.yoyoCount>0&&r.yoyoCount,i){var d=i[c],h=n?n[c]:e.SceneManager.GetPropertyValue(t,c),p=t,m=c;if(u&&e.SceneManager.IsGUIPositionProperty(c)){p=e.SceneManager.CreateGUIAnimationProxy(t,c),m=c,h=n?"string"==typeof n[c]?parseFloat(n[c]):n[c]:e.SceneManager.ExtractGUINumericValue(t,c);var f="string"==typeof d?parseFloat(d):d,g=BABYLON.Animation.ANIMATIONTYPE_FLOAT,v=new BABYLON.Animation("tween_".concat(c),m,60,g,r.loop?BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT),y=e.SceneManager.CreateEasingFunction(r.ease);y&&v.setEasingFunction(y);var _=[],S=0;if(_.push({frame:S,value:h}),S+=l,_.push({frame:S,value:f}),r.yoyo&&r.loop)S+=l,_.push({frame:S,value:h});else if(r.yoyo&&r.yoyoCount&&r.yoyoCount>0){S+=l,_.push({frame:S,value:h});for(var A=1;A<r.yoyoCount;A++)S+=l,_.push({frame:S,value:f}),S+=l,_.push({frame:S,value:h})}v.setKeys(_),a.push(v),s.push(p)}else if(void 0!==h&&void 0!==d){var b=e.SceneManager.GetAnimationType(d),M=new BABYLON.Animation("tween_".concat(c),c,60,b,r.loop?BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT),B=e.SceneManager.CreateEasingFunction(r.ease);B&&M.setEasingFunction(B);var C=[],T=0;if(C.push({frame:T,value:h}),T+=l,C.push({frame:T,value:d}),r.yoyo&&r.loop)T+=l,C.push({frame:T,value:h});else if(r.yoyo&&r.yoyoCount&&r.yoyoCount>0)for(T+=l,C.push({frame:T,value:h}),A=1;A<r.yoyoCount;A++)T+=l,C.push({frame:T,value:d}),T+=l,C.push({frame:T,value:h});M.setKeys(C),a.push(M),s.push(p)}}return{animations:a,targets:s}},t.TweenTo=function(t,n,i,r){var o;void 0===i&&(i={}),r=r||BABYLON.EngineStore.LastCreatedScene;var a,s=e.SceneManager.CreateTweenAnimations(t,null,n,i,r),l=s.animations,u=s.targets,c=e.SceneManager.IsGUIControl(t);if(c)for(var d=0;d<l.length;d++){var h=l[d];(A=u[d])!==t?(A.animations=A.animations||[],A.animations.push(h)):(t.animations=t.animations||[],t.animations.push(h))}else t.animations=t.animations||[],(o=t.animations).push.apply(o,l);var p,m=new Promise(function(e){a=e}),f=function(){i.onComplete&&i.onComplete(),a()},g=1e3*(i.delay||0),v=i.speed||1,y=60*(i.duration||1);i.yoyo&&i.loop?y*=2:i.yoyo&&i.yoyoCount&&i.yoyoCount>0&&(y*=1+i.yoyoCount);var _=[];if(c&&u.some(function(e){return e!==t})){var S=[];if(g>0)setTimeout(function(){i.onStart&&i.onStart();for(var e=0;e<u.length;e++){var t=u[e],n=r.beginAnimation(t,0,y,i.loop||!1,v,e===u.length-1?f:void 0);n&&(S.push(n),_.push(n))}p=S[0]},g);else{for(i.onStart&&i.onStart(),d=0;d<u.length;d++){var A=u[d],b=r.beginAnimation(A,0,y,i.loop||!1,v,d===u.length-1?f:void 0);b&&(S.push(b),_.push(b))}p=S[0]}}else g>0?setTimeout(function(){i.onStart&&i.onStart(),(p=r.beginAnimation(t,0,y,i.loop||!1,v,f))&&_.push(p)},g):(i.onStart&&i.onStart(),(p=r.beginAnimation(t,0,y,i.loop||!1,v,f))&&_.push(p));return{animations:_,finished:m}},t.TweenToAsync=function(t,n){return a(this,arguments,void 0,function(t,n,i,r){return void 0===i&&(i={}),s(this,function(o){return[2,e.SceneManager.TweenTo(t,n,i,r).finished]})})},t.TweenFromTo=function(t,n,i,r,o){for(var a in void 0===r&&(r={}),n)e.SceneManager.SetPropertyValue(t,a,n[a]);return e.SceneManager.TweenTo(t,i,r,o)},t.TweenFromToAsync=function(t,n,i){return a(this,arguments,void 0,function(t,n,i,r,o){return void 0===r&&(r={}),s(this,function(a){return[2,e.SceneManager.TweenFromTo(t,n,i,r,o).finished]})})},t.TweenGroupAsync=function(e){return a(this,arguments,void 0,function(e,t,n){var i,r,o,a,l,u,c,d,h;return void 0===t&&(t={}),s(this,function(s){switch(s.label){case 0:if(n=n||BABYLON.EngineStore.LastCreatedScene,i=t.mode||"all",r=t.stagger||0,"sequence"!==i)return[3,7];o=0,a=e,s.label=1;case 1:return o<a.length?(l=a[o],(u=l())&&u.finished?[4,u.finished]:[3,3]):[3,6];case 2:return s.sent(),[3,5];case 3:return u&&u.then?[4,u]:[3,5];case 4:s.sent(),s.label=5;case 5:return o++,[3,1];case 6:return[3,9];case 7:for(c=[],d=function(t){var n=e[t];if(r>0&&t>0)c.push(new Promise(function(e){setTimeout(function(){var t=n();t&&t.finished?t.finished.then(e):t&&t.then?t.then(e):e()},t*r)}));else{var i=n();i&&i.finished?c.push(i.finished):i&&i.then&&c.push(i)}},h=0;h<e.length;h++)d(h);return[4,Promise.all(c)];case 8:s.sent(),s.label=9;case 9:return t.onComplete&&t.onComplete(),[2]}})})},t.GlobalOptions={},t.WindowState={},t.ServerEndPoint="http://127.0.0.1:2567",t.EnableDebugMode=!1,t.EnableUserInput=!0,t.RenderLoopReady=!0,t.PauseRenderLoop=!1,t.LostRenderContext=!1,t.AutoUpdateProgress=!0,t.PhysicsCapsuleShape=0,t.SupportSRGBBuffers=!1,t.AnimationStartMode=0,t.AnimationTargetFps=60,t.DefaultConvexHullMargin=.001,t.DefaultHeightFieldMargin=.001,t.AmbientLightIntensity=1,t.PointLightIntensity=1,t.SpotLightIntensity=1,t.DirectionalLightIntensity=1,t.FogExpDensityScale=1,t.FogExp2DensityScale=1,t.FogLinearDensityScale=1,t.TerrainColorCorrection=2.2,t.AllowCameraMovement=!0,t.AllowCameraRotation=!0,t.VirtualJoystickEnabled=!1,t.GameTimeMilliseconds=0,t.ParseScriptComponents=!0,t.AutoLoadScriptBundles=!0,t.AutoStripNamespacePrefix=!0,t.UniversalModuleDefinition=!0,t.WaitForSeconds=function(t){return new Promise(function(n){return e.WindowManager.SetTimeout(1e3*t,n)})},t.OnPreRenderLoopObservable=new BABYLON.Observable,t.OnPostRenderLoopObservable=new BABYLON.Observable,t.OnSceneReadyObservable=new BABYLON.Observable,t.OnEngineResizeObservable=new BABYLON.Observable,t.OnLoadCompleteObservable=new BABYLON.Observable,t.OnRebuildContextObservable=new BABYLON.Observable,t.OnAssetManagerProgress=null,t.AllLayerMask=4294967295,t.DefaultLayerMask=268435455,t.HiddenLayerMask=268435456,t._HideLoadingScreen=null,t.CVTOOLS_NAME="CVTOOLS_unity_metadata",t.CVTOOLS_MESH="CVTOOLS_babylon_mesh",t.CVTOOLS_HAND="CVTOOLS_left_handed",t.CVTOOLS_NAME_REGISTERED=!1,t.CVTOOLS_MESH_REGISTERED=!1,t.CVTOOLS_HAND_REGISTERED=!1,t._EventBus=null,t.SceneLoaderFileNames=[],t.SceneLoaderPropertyBag={},t.SceneLoaderHandledFlag=!1,t.SceneParsingEnabled=!0,t.PhysicsViewersEnabled=!1,t.MAX_AGENT_COUNT=200,t.MAX_AGENT_RADIUS=2,t.OnNavMeshReadyObservable=new BABYLON.Observable,t.NavMeshPlugin=null,t.NavMeshSurface=null,t.NavMeshDebugger=null,t.NavMeshMaterial=null,t.CrowdInterface=null,t}();e.SceneManager=t}(i||(i={})),i.SceneManager.GameTimeMilliseconds=i.SceneManager.GetTimeMilliseconds(),function(e){var t=function(){function t(t,n,i,r){if(void 0===i&&(i={}),void 0===r&&(r=null),this._update=null,this._late=null,this._step=null,this._fixed=null,this._after=null,this._ready=null,this._lateUpdate=!1,this._properties=null,this._awoken=!1,this._started=!1,this._scene=null,this._delyed=!1,this._transform=null,this._scriptReady=!1,this._registeredClassname=null,this._registerComponentAlias=!0,this._lateUpdateObserver=null,this.resetScriptComponent=null,this._bodyCollisionObserver=null,this._bodyCollisionEndedObserver=null,this._worldTriggerEventObserver=null,this.onCollisionEnterObservable=new BABYLON.Observable,this.onCollisionStayObservable=new BABYLON.Observable,this.onCollisionExitObservable=new BABYLON.Observable,this.onTriggerEnterObservable=new BABYLON.Observable,this.onTriggerExitObservable=new BABYLON.Observable,null==t)throw new Error("Null transform object specified.");if(null==n)throw new Error("Null host scene object specified.");this._scene=n,this._transform=t,this._properties=i||{},null!=this._properties._scriptComponentAlias&&""!==this._properties._scriptComponentAlias?this._registeredClassname=this._properties._scriptComponentAlias:this._registeredClassname=r||this.constructor.name||"Unknown",null!=this._properties._registerComponentAlias?this._registerComponentAlias=this._properties._registerComponentAlias:this._registerComponentAlias=!0;var o=this;o._update=function(){e.ScriptComponent.UpdateInstance(o)},o._late=function(){e.ScriptComponent.LateInstance(o)},o._step=function(){e.ScriptComponent.StepInstance(o)},o._fixed=function(){e.ScriptComponent.FixedInstance(o)},o._after=function(){e.ScriptComponent.AfterInstance(o)},o._ready=function(){e.ScriptComponent.ReadyInstance(o)},o.resetScriptComponent=function(){e.ScriptComponent.ResetInstance(o)},o.registerComponentInstance&&o.destroyComponentInstance||BABYLON.Tools.Warn("Invalid component registration handlers for: "+this._transform.name),!0===this._registerComponentAlias&&null!=o.registerComponentInstance&&o.registerComponentInstance(o,this._registeredClassname,!0)}return t.prototype.isReady=function(){return this._scriptReady},Object.defineProperty(t.prototype,"scene",{get:function(){return this._scene},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"transform",{get:function(){return this._transform},enumerable:!1,configurable:!0}),t.prototype.dispose=function(){},t.prototype.getClassName=function(){return this._registeredClassname},t.prototype.getProperties=function(){return this._properties},t.prototype.getProperty=function(e,t){void 0===t&&(t=null);var n=null;return null!=this._properties&&null==(n=this._properties[e])&&(n=this._properties["auto__"+e]),null==n&&(n=t),null!=n?n:null},t.prototype.setProperty=function(e,t){null==this._properties&&(this._properties={}),this._properties[e]=t},t.prototype.getTime=function(){return e.SceneManager.GetTime()},t.prototype.getTimeMs=function(){return e.SceneManager.GetTimeMs()},t.prototype.getGameTime=function(){return e.SceneManager.GetGameTime()},t.prototype.getGameTimeMs=function(){return e.SceneManager.GetGameTimeMs()},t.prototype.getDeltaTime=function(){return e.SceneManager.GetDeltaTime(this.scene)},t.prototype.getDeltaSeconds=function(){return e.SceneManager.GetDeltaSeconds(this.scene)},t.prototype.getDeltaMilliseconds=function(){return e.SceneManager.GetDeltaMilliseconds(this.scene)},t.prototype.getAnimationRatio=function(){return e.SceneManager.GetAnimationRatio(this.scene)},t.prototype.hasSkinnedMesh=function(){return null!=this.getSkinnedMesh()},t.prototype.getSkinnedMesh=function(){return e.SceneManager.GetSkinnedMesh(this.transform)},t.prototype.getTransformMesh=function(){return this._transform instanceof BABYLON.Mesh?this._transform:null},t.prototype.getAbstractMesh=function(){return this._transform instanceof BABYLON.AbstractMesh?this._transform:null},t.prototype.getInstancedMesh=function(){return this._transform instanceof BABYLON.InstancedMesh?this._transform:null},t.prototype.getPrimitiveMeshes=function(){return e.SceneManager.GetPrimitiveMeshes(this.transform)},t.prototype.getMetadata=function(){return e.SceneManager.FindSceneMetadata(this._transform)},t.prototype.getComponent=function(t,n){void 0===n&&(n=!1);var i=e.SceneManager.FindScriptComponent(this._transform,t,n);return null!=i?i:null},t.prototype.getComponents=function(t,n){void 0===n&&(n=!1);var i=e.SceneManager.FindAllScriptComponents(this._transform,t,n);return null!=i?i:null},t.prototype.getLightRig=function(){return e.SceneManager.FindSceneLightRig(this._transform)},t.prototype.getCameraRig=function(){return e.SceneManager.FindSceneCameraRig(this._transform)},t.prototype.getTransformTag=function(){return e.SceneManager.GetTransformTag(this.transform)},t.prototype.hasTransformTags=function(t){return e.SceneManager.HasTransformTags(this._transform,t)},t.prototype.getChildNode=function(t,n,i,r){return void 0===n&&(n=e.SearchType.ExactMatch),void 0===i&&(i=!0),void 0===r&&(r=null),e.SceneManager.FindChildTransformNode(this._transform,t,n,i,r)},t.prototype.getChildWithTags=function(t,n,i){return void 0===n&&(n=!0),void 0===i&&(i=null),e.SceneManager.FindChildTransformWithTags(this._transform,t,n,i)},t.prototype.getChildrenWithTags=function(t,n,i){return void 0===n&&(n=!0),void 0===i&&(i=null),e.SceneManager.FindAllChildTransformsWithTags(this._transform,t,n,i)},t.prototype.getChildWithScript=function(t,n,i){return void 0===n&&(n=!0),void 0===i&&(i=null),e.SceneManager.FindChildTransformWithScript(this._transform,t,n,i)},t.prototype.getChildrenWithScript=function(t,n,i){return void 0===n&&(n=!0),void 0===i&&(i=null),e.SceneManager.FindAllChildTransformsWithScript(this._transform,t,n,i)},t.prototype.enableCollisionEvents=function(){var t=this,n=e.Utilities.GetHavokPlugin();if(null!=n&&null!=this.transform.physicsBody){if(this.transform.physicsBody.setCollisionCallbackEnabled(!0),this.transform.physicsBody.setCollisionEndedCallbackEnabled(!0),null==this._bodyCollisionObserver){var i=this.transform.physicsBody.getCollisionObservable();null!=i&&(this._bodyCollisionObserver=i.add(function(e){null!=e.collidedAgainst&&null!=e.collidedAgainst.transformNode&&("COLLISION_STARTED"===e.type?t.onCollisionEnterObservable.notifyObservers(e.collidedAgainst.transformNode):"COLLISION_CONTINUED"===e.type&&t.onCollisionStayObservable.notifyObservers(e.collidedAgainst.transformNode))}))}if(null==this._bodyCollisionEndedObserver){var r=this.transform.physicsBody.getCollisionEndedObservable();null!=r&&(this._bodyCollisionEndedObserver=r.add(function(e){null!=e.collidedAgainst&&null!=e.collidedAgainst.transformNode&&"COLLISION_FINISHED"===e.type&&t.onCollisionExitObservable.notifyObservers(e.collidedAgainst.transformNode)}))}null==this._worldTriggerEventObserver&&(this._worldTriggerEventObserver=n.onTriggerCollisionObservable.add(function(e){if(e.collider===t.transform.physicsBody||e.collidedAgainst===t.transform.physicsBody){var n=e.collider===t.transform.physicsBody?e.collidedAgainst:e.collider;"TRIGGER_ENTERED"===e.type?t.onTriggerEnterObservable.notifyObservers(n.transformNode):"TRIGGER_EXITED"===e.type&&t.onTriggerExitObservable.notifyObservers(n.transformNode)}}))}},t.prototype.disableCollisionEvents=function(){null!=e.Utilities.GetHavokPlugin()&&null!=this.transform.physicsBody&&(this.transform.physicsBody.setCollisionCallbackEnabled(!1),this.transform.physicsBody.setCollisionEndedCallbackEnabled(!1))},t.prototype.setTransformPosition=function(e){this.transform.physicsBody&&0!=this.transform.physicsBody.disablePreStep&&(this.transform.physicsBody.disablePreStep=!1),null!=this.transform.position&&this.transform.position.copyFrom(e)},t.prototype.setTransformRotation=function(e){this.transform.physicsBody&&0!=this.transform.physicsBody.disablePreStep&&(this.transform.physicsBody.disablePreStep=!1),null!=this.transform.rotationQuaternion&&this.transform.rotationQuaternion.copyFrom(e)},t.prototype.registerOnClickAction=function(t){var n=null;return this.transform instanceof BABYLON.AbstractMesh&&(n=e.SceneManager.RegisterClickAction(this.scene,this.transform,t)),n},t.prototype.unregisterOnClickAction=function(t){var n=!1;return this.transform instanceof BABYLON.AbstractMesh&&(n=e.SceneManager.UnregisterClickAction(this.transform,t)),n},t.prototype.registerComponentInstance=function(t,n,i){if(void 0===i&&(i=!0),null!=n&&""!==n&&"Unknown"!==n){if(!0===i){e.Utilities.ValidateTransformMetadata(this._transform);var r={alias:"script",order:0,klass:n,properties:null,instance:t};null==this._transform.metadata.toolkit.components&&(this._transform.metadata.toolkit.components=[]),this._transform.metadata.toolkit.components.push(r)}e.ScriptComponent.RegisterInstance(t),!0===i&&t.scene.onAfterRenderObservable.addOnce(function(){t.delayComponentInstance(t)})}else console.warn("Failed to register unknown component instance: ",t)},t.prototype.delayComponentInstance=function(t){e.WindowManager.SetTimeout(100,function(){t._delyed=!0})},t.prototype.destroyComponentInstance=function(t){e.ScriptComponent.DestroyInstance(t)},t.prototype.setupStepComponentInstance=function(e){e.scene.onBeforePhysicsObservable&&e.scene.onBeforePhysicsObservable.add(e._step)},t.prototype.removeStepComponentInstance=function(e){e.scene.onBeforePhysicsObservable&&e.scene.onBeforePhysicsObservable.removeCallback(e._step)},t.prototype.setupFixedComponentInstance=function(e){e.scene.onAfterPhysicsObservable&&e.scene.onAfterPhysicsObservable.add(e._fixed)},t.prototype.removeFixedComponentInstance=function(e){e.scene.onAfterPhysicsObservable&&e.scene.onAfterPhysicsObservable.removeCallback(e._fixed)},t.RegisterInstance=function(e){null!=e&&(null!=e._update&&e.scene.registerBeforeRender(e._update),e.late&&null!=e._late&&null!=e.scene.onBeforeRenderTargetsRenderObservable&&(e._lateUpdateObserver=e.scene.onBeforeRenderTargetsRenderObservable.add(e._late)),e.after&&null!=e._after&&e.scene.registerAfterRender(e._after),e.step&&null!=e._step&&e.setupStepComponentInstance(e),e.fixed&&null!=e._fixed&&e.setupFixedComponentInstance(e))},t.UpdateInstance=function(t){null!=t&&null!=t.transform&&t.transform.isEnabled(!1)&&(!1===t._awoken?(t._awoken=!0,e.ScriptComponent.ParseAutoProperties(t),t.awake&&t.awake()):!1===t._started?(t._started=!0,t.start&&t.start()):!0===t._awoken&&!0===t._started&&(!0===t._delyed&&(t._delyed=!1,e.ScriptComponent.ReadyInstance(t)),t.update&&t.update(),t._lateUpdate=!0))},t.LateInstance=function(e){null!=e&&null!=e.transform&&e.transform.isEnabled(!1)&&!0===e._lateUpdate&&(e._lateUpdate=!1,!0===e._started&&e.late&&e.late())},t.AfterInstance=function(e){null!=e&&null!=e.transform&&e.transform.isEnabled(!1)&&!0===e._started&&e.after&&e.after()},t.StepInstance=function(e){null!=e&&null!=e.transform&&!0===e._started&&e.step&&e.step()},t.FixedInstance=function(e){null!=e&&null!=e.transform&&!0===e._started&&e.fixed&&e.fixed()},t.ReadyInstance=function(e){null!=e&&null!=e.transform&&!1===e._scriptReady&&(e._scriptReady=!0,e.ready&&e.ready())},t.ResetInstance=function(e){null!=e&&null!=e.transform&&!0===e._started&&e.reset&&e.reset()},t.DestroyInstance=function(t){if(null!=t){t.scene.unregisterBeforeRender(t._update),null!=t._lateUpdateObserver&&null!=t.scene.onBeforeRenderTargetsRenderObservable&&t.scene.onBeforeRenderTargetsRenderObservable.remove(t._lateUpdateObserver),t.after&&null!=t._after&&t.scene.unregisterAfterRender(t._after),t.step&&null!=t._step&&t.removeStepComponentInstance(t),t.fixed&&null!=t._fixed&&t.removeFixedComponentInstance(t);var n=e.Utilities.GetHavokPlugin();if(null!=n){if(null!=t._bodyCollisionObserver)try{t._bodyCollisionObserver.remove()}catch(e){}if(null!=t._bodyCollisionEndedObserver)try{t._bodyCollisionEndedObserver.remove()}catch(e){}if(null!=t._worldTriggerEventObserver)try{n.onTriggerCollisionObservable.remove(t._worldTriggerEventObserver)}catch(e){}}try{t.onCollisionEnterObservable.clear()}catch(e){}try{t.onCollisionStayObservable.clear()}catch(e){}try{t.onCollisionExitObservable.clear()}catch(e){}try{t.onTriggerEnterObservable.clear()}catch(e){}try{t.onTriggerExitObservable.clear()}catch(e){}try{t.destroy&&t.destroy()}catch(e){}t._scriptReady=!1,t._transform=null,t._properties=null,t._started=!1,t._delyed=!1,t._update=null,t._late=null,t._step=null,t._fixed=null,t._after=null,t._ready=null,t._scene=null}},t.ParseAutoProperties=function(t){var n=Object.keys(t._properties);if(null!=n&&n.length>0)for(var i=function(i){var r=n[i];if(e.Utilities.StartsWith(r,"auto__")){var o=r.replace("auto__","");if(e.Utilities.HasOwnProperty(t,o)){var a=t.getProperty(r);if(null!=a){var s=typeof a;if(null!=s&&""!==s)if("object"===s)if(Array.isArray(a)){var l=[];a.forEach(function(n){null!=n&&("object"==typeof n?l.push(e.ScriptComponent.UnpackObjectProperty(n,t.scene)):l.push(n))}),t[o]=l}else{var u=t[o],c=e.ScriptComponent.UnpackObjectProperty(a,t.scene);u instanceof BABYLON.Color3&&c instanceof BABYLON.Color4?t[o]=new BABYLON.Color3(c.r,c.g,c.b):t[o]=c}else t[o]=a;else t[o]=a}else t[o]=a}else BABYLON.Tools.Warn(t.getClassName()||"Unregistered Class: Auto property '"+o+"' not found for transform '"+t.transform.name+"'")}},r=0;r<n.length;r++)i(r)},t.UnpackObjectProperty=function(t,n){var i=null;if(null!=t)if(void 0!==t.x&&void 0!==t.y)i=void 0!==t.z?void 0!==t.w?new BABYLON.Vector4(t.x,t.y,t.z,t.w):new BABYLON.Vector3(t.x,t.y,t.z):new BABYLON.Vector2(t.x,t.y);else if(void 0!==t.r&&void 0!==t.g&&void 0!==t.b){var r=1;void 0!==t.a&&(r=t.a),i=new BABYLON.Color4(t.r,t.g,t.b,r)}else if(void 0!==t.type)switch(t.type){case"UnityEngine.AnimationCurve":var o=t;i=BABYLON.Animation.Parse(o.animation);break;case"UnityEngine.Transform":var a=t;i=e.Utilities.ParseTransformByID(a,n);break;case"UnityEngine.Material":var s=t;i=n.getMaterialByName(s.name);break;case"UnityEngine.Texture2D":var l=t;i=e.Utilities.ParseTexture(l,n);break;case"UnityEngine.Cubemap":var u=t;i=e.Utilities.ParseCubemap(u,n);break;case"UnityEngine.AudioClip":case"UnityEngine.Video.VideoClip":case"UnityEngine.Font":default:i=t;break;case"UnityEngine.TextAsset":var c=t;i=null!=c.base64?!0===c.json?JSON.parse(e.WindowManager.Atob(c.base64)):e.WindowManager.Atob(c.base64):c;break;case"UnityEditor.DefaultAsset":var d=t;i=null!=d.base64?!0===d.json?JSON.parse(e.WindowManager.Atob(d.base64)):e.WindowManager.Atob(d.base64):d}else i=t;return i},t}();e.ScriptComponent=t;var n=function(t){function n(e,n,i,r){void 0===i&&(i={}),void 0===r&&(r=null);var o=t.call(this,e,n,i,r)||this;return o.autoHideSplashScreen=!0,o.postCreateSceneDelayMs=1e3,o.hideSplashScreenDelayMs=3e3,o.createSceneHandled=!1,o}return r(n,t),n.prototype.preCreateScene=function(t){return a(this,void 0,void 0,function(){var n=this;return s(this,function(i){return this.createSceneHandled||(this.createSceneHandled=!0,e.WindowManager.SetTimeout(this.postCreateSceneDelayMs,function(){return a(n,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return[4,this.postCreateScene(t)];case 1:return e.sent(),[2]}})})})),[2]})})},n.prototype.postCreateScene=function(t){return a(this,void 0,void 0,function(){var n;return s(this,function(i){switch(i.label){case 0:return i.trys.push([0,3,4,5]),this.createScene?[4,this.createScene(t)]:[3,2];case 1:i.sent(),i.label=2;case 2:return[3,5];case 3:return n=i.sent(),console.error("Failed to initialize game mode",n),[3,5];case 4:return this.autoHideSplashScreen&&e.SceneManager.HideSplashScreen(this.scene,this.hideSplashScreenDelayMs),[7];case 5:return[2]}})})},n}(e.ScriptComponent);e.GameModeController=n}(i||(i={})),function(e){var t,n,i,o,a,s,l,u,c,d,h,p,m,f,g,v,y;(y=e.System||(e.System={}))[y.Deg2Rad=2*Math.PI/360]="Deg2Rad",y[y.Rad2Deg=1/e.System.Deg2Rad]="Rad2Deg",y[y.Epsilon=1e-6]="Epsilon",y[y.SingleEpsilon=1401298e-51]="SingleEpsilon",y[y.EpsilonNormalSqrt=1e-15]="EpsilonNormalSqrt",y[y.Kph2Mph=.621371]="Kph2Mph",y[y.Mph2Kph=1.60934]="Mph2Kph",y[y.Mps2Kph=3.6]="Mps2Kph",y[y.Mps2Mph=2.23694]="Mps2Mph",y[y.Meter2Inch=39.3701]="Meter2Inch",y[y.Inch2Meter=.0254]="Inch2Meter",y[y.Gravity=9.81]="Gravity",y[y.Gravity3G=29.400000000000002]="Gravity3G",y[y.SkidFactor=.25]="SkidFactor",y[y.MaxInteger=2147483647]="MaxInteger",y[y.WalkingVelocity=4.4]="WalkingVelocity",y[y.TerminalVelocity=55]="TerminalVelocity",y[y.SmoothDeltaFactor=.2]="SmoothDeltaFactor",y[y.ToLinearSpace=2.2]="ToLinearSpace",y[y.ToGammaSpace=.45454545454545453]="ToGammaSpace",(v=e.Handedness||(e.Handedness={}))[v.Default=-1]="Default",v[v.Right=0]="Right",v[v.Left=1]="Left",(g=e.SearchType||(e.SearchType={}))[g.ExactMatch=0]="ExactMatch",g[g.StartsWith=1]="StartsWith",g[g.EndsWith=2]="EndsWith",g[g.IndexOf=3]="IndexOf",(f=e.PlayerNumber||(e.PlayerNumber={}))[f.Auto=0]="Auto",f[f.One=1]="One",f[f.Two=2]="Two",f[f.Three=3]="Three",f[f.Four=4]="Four",(m=e.PlayerControl||(e.PlayerControl={}))[m.FirstPerson=0]="FirstPerson",m[m.ThirdPerson=1]="ThirdPerson",(p=e.RenderQuality||(e.RenderQuality={}))[p.High=0]="High",p[p.Medium=1]="Medium",p[p.Low=2]="Low",(h=e.GamepadType||(e.GamepadType={}))[h.None=-1]="None",h[h.Generic=0]="Generic",h[h.Xbox360=1]="Xbox360",h[h.DualShock=2]="DualShock",h[h.PoseController=3]="PoseController",(d=e.Xbox360Trigger||(e.Xbox360Trigger={}))[d.Left=0]="Left",d[d.Right=1]="Right",(c=e.MovementType||(e.MovementType={}))[c.DirectVelocity=0]="DirectVelocity",c[c.AppliedForces=1]="AppliedForces",(u=e.CollisionContact||(e.CollisionContact={}))[u.Top=0]="Top",u[u.Left=1]="Left",u[u.Right=2]="Right",u[u.Bottom=3]="Bottom",(l=e.IntersectionPrecision||(e.IntersectionPrecision={}))[l.AABB=0]="AABB",l[l.OBB=1]="OBB",(s=e.CollisionFilters||(e.CollisionFilters={}))[s.DefaultFilter=1]="DefaultFilter",s[s.StaticFilter=2]="StaticFilter",s[s.KinematicFilter=4]="KinematicFilter",s[s.DebrisFilter=8]="DebrisFilter",s[s.SensorTrigger=16]="SensorTrigger",s[s.CharacterFilter=32]="CharacterFilter",s[s.AllFilter=-1]="AllFilter",(a=e.CollisionState||(e.CollisionState={}))[a.ACTIVE_TAG=1]="ACTIVE_TAG",a[a.ISLAND_SLEEPING=2]="ISLAND_SLEEPING",a[a.WANTS_DEACTIVATION=3]="WANTS_DEACTIVATION",a[a.DISABLE_DEACTIVATION=4]="DISABLE_DEACTIVATION",a[a.DISABLE_SIMULATION=5]="DISABLE_SIMULATION",(o=e.CollisionFlags||(e.CollisionFlags={}))[o.CF_STATIC_OBJECT=1]="CF_STATIC_OBJECT",o[o.CF_KINEMATIC_OBJECT=2]="CF_KINEMATIC_OBJECT",o[o.CF_NO_CONTACT_RESPONSE=4]="CF_NO_CONTACT_RESPONSE",o[o.CF_CUSTOM_MATERIAL_CALLBACK=8]="CF_CUSTOM_MATERIAL_CALLBACK",o[o.CF_CHARACTER_OBJECT=16]="CF_CHARACTER_OBJECT",o[o.CF_DISABLE_VISUALIZE_OBJECT=32]="CF_DISABLE_VISUALIZE_OBJECT",o[o.CF_DISABLE_SPU_COLLISION_PROCESSING=64]="CF_DISABLE_SPU_COLLISION_PROCESSING",o[o.CF_HAS_CONTACT_STIFFNESS_DAMPING=128]="CF_HAS_CONTACT_STIFFNESS_DAMPING",o[o.CF_HAS_CUSTOM_DEBUG_RENDERING_COLOR=256]="CF_HAS_CUSTOM_DEBUG_RENDERING_COLOR",o[o.CF_HAS_FRICTION_ANCHOR=512]="CF_HAS_FRICTION_ANCHOR",o[o.CF_HAS_COLLISION_SOUND_TRIGGER=1024]="CF_HAS_COLLISION_SOUND_TRIGGER",(i=e.UserInputPointer||(e.UserInputPointer={}))[i.Left=0]="Left",i[i.Middle=1]="Middle",i[i.Right=2]="Right",(n=e.UserInputAxis||(e.UserInputAxis={}))[n.Horizontal=0]="Horizontal",n[n.Vertical=1]="Vertical",n[n.ClientX=2]="ClientX",n[n.ClientY=3]="ClientY",n[n.MouseX=4]="MouseX",n[n.MouseY=5]="MouseY",n[n.Wheel=6]="Wheel",(t=e.UserInputKey||(e.UserInputKey={}))[t.BackSpace=8]="BackSpace",t[t.Tab=9]="Tab",t[t.Enter=13]="Enter",t[t.Shift=16]="Shift",t[t.Ctrl=17]="Ctrl",t[t.Alt=18]="Alt",t[t.Pause=19]="Pause",t[t.Break=19]="Break",t[t.CapsLock=20]="CapsLock",t[t.Escape=27]="Escape",t[t.SpaceBar=32]="SpaceBar",t[t.PageUp=33]="PageUp",t[t.PageDown=34]="PageDown",t[t.End=35]="End",t[t.Home=36]="Home",t[t.LeftArrow=37]="LeftArrow",t[t.UpArrow=38]="UpArrow",t[t.RightArrow=39]="RightArrow",t[t.DownArrow=40]="DownArrow",t[t.Insert=45]="Insert",t[t.Delete=46]="Delete",t[t.Num0=48]="Num0",t[t.Num1=49]="Num1",t[t.Num2=50]="Num2",t[t.Num3=51]="Num3",t[t.Num4=52]="Num4",t[t.Num5=53]="Num5",t[t.Num6=54]="Num6",t[t.Num7=55]="Num7",t[t.Num8=56]="Num8",t[t.Num9=57]="Num9",t[t.A=65]="A",t[t.B=66]="B",t[t.C=67]="C",t[t.D=68]="D",t[t.E=69]="E",t[t.F=70]="F",t[t.G=71]="G",t[t.H=72]="H",t[t.I=73]="I",t[t.J=74]="J",t[t.K=75]="K",t[t.L=76]="L",t[t.M=77]="M",t[t.N=78]="N",t[t.O=79]="O",t[t.P=80]="P",t[t.Q=81]="Q",t[t.R=82]="R",t[t.S=83]="S",t[t.T=84]="T",t[t.U=85]="U",t[t.V=86]="V",t[t.W=87]="W",t[t.X=88]="X",t[t.Y=89]="Y",t[t.Z=90]="Z",t[t.LeftWindowKey=91]="LeftWindowKey",t[t.RightWindowKey=92]="RightWindowKey",t[t.SelectKey=93]="SelectKey",t[t.Numpad0=96]="Numpad0",t[t.Numpad1=97]="Numpad1",t[t.Numpad2=98]="Numpad2",t[t.Numpad3=99]="Numpad3",t[t.Numpad4=100]="Numpad4",t[t.Numpad5=101]="Numpad5",t[t.Numpad6=102]="Numpad6",t[t.Numpad7=103]="Numpad7",t[t.Numpad8=104]="Numpad8",t[t.Numpad9=105]="Numpad9",t[t.Multiply=106]="Multiply",t[t.Add=107]="Add",t[t.Subtract=109]="Subtract",t[t.DecimalPoint=110]="DecimalPoint",t[t.Divide=111]="Divide",t[t.F1=112]="F1",t[t.F2=113]="F2",t[t.F3=114]="F3",t[t.F4=115]="F4",t[t.F5=116]="F5",t[t.F6=117]="F6",t[t.F7=118]="F7",t[t.F8=119]="F8",t[t.F9=120]="F9",t[t.F10=121]="F10",t[t.F11=122]="F11",t[t.F12=123]="F12",t[t.NumLock=144]="NumLock",t[t.ScrollLock=145]="ScrollLock",t[t.SemiColon=186]="SemiColon",t[t.EqualSign=187]="EqualSign",t[t.Comma=188]="Comma",t[t.Dash=189]="Dash",t[t.Period=190]="Period",t[t.ForwardSlash=191]="ForwardSlash",t[t.GraveAccent=192]="GraveAccent",t[t.OpenBracket=219]="OpenBracket",t[t.BackSlash=220]="BackSlash",t[t.CloseBraket=221]="CloseBraket",t[t.SingleQuote=222]="SingleQuote";var _=function(){function e(){}return e.KeyboardSmoothing=!1,e.KeyboardMoveSensibility=3,e.KeyboardArrowSensibility=1,e.KeyboardMoveDeadZone=.001,e.GamepadDeadStickValue=.15,e.GamepadLStickXInverted=!1,e.GamepadLStickYInverted=!1,e.GamepadRStickXInverted=!1,e.GamepadRStickYInverted=!0,e.GamepadLStickSensibility=1,e.GamepadRStickSensibility=1,e.SupportedInputDevices=null,e.BabylonAngularSensibility=2e3,e.DefaultAngularSensibility=.5,e.PointerWheelDeadZone=.1,e.PointerMouseDeadZone=.1,e.PointerMouseInverted=!0,e.UseCanvasElement=!0,e.UseArrowKeyRotation=!1,e.EnableBabylonRotation=!1,e}();e.UserInputOptions=_;e.RequestHeader=function(){};e.TriggerVolume=function(){this.mesh=null,this.state=0};e.RoomErrorMessage=function(){};var S=function(){function e(e,t,n,i,r){void 0===n&&(n=!0),void 0===i&&(i=null),void 0===r&&(r=null),this.loadingDivId=e,this.loadingUIText=t,this.hideLoadingUIWithEngine=n,this.customInnerHtml=i,this.customInnerCss=r,this.loadingUIBackgroundColor="#000000",null!=this.loadingDivId&&""!==this.loadingDivId||(this.loadingDivId="customLoadingScreen"),null!=this.loadingUIText&&""!==this.loadingUIText||(this.loadingUIText="Please Wait")}return e.prototype.displayLoadingUI=function(){if(this.hasLoadingDiv())this.showLoadingDiv(!0);else{var e=document.createElement("style");e.type="text/css",e.innerHTML=this.customInnerCss||"",document.getElementsByTagName("head")[0].appendChild(e);var t=this.loadingUIText,n=document.createElement("div");n.id=this.loadingDivId,n.innerHTML=this.customInnerHtml||t,document.body.appendChild(n)}},e.prototype.hideLoadingUI=function(){!0===this.hideLoadingUIWithEngine&&this.showLoadingDiv(!1)},e.prototype.showLoadingDiv=function(e){var t=this.getLoadingDiv();null!=t&&(t.style.display=e?"initial":"none")},e.prototype.getLoadingDiv=function(){return document.getElementById(this.loadingDivId)},e.prototype.hasLoadingDiv=function(){return null!=document.getElementById(this.loadingDivId)},e}();e.CustomLoadingScreen=S;var A=function(){function e(){this.ListenerDictionary={}}return e.prototype.OnMessage=function(e,t){var n;null==this.ListenerDictionary[e]?(n=[],this.ListenerDictionary[e]=n):n=this.ListenerDictionary[e],n.findIndex(function(e){return t==e})<0&&n.push(t)},e.prototype.PostMessage=function(e,t){void 0===t&&(t=null);var n=this.ListenerDictionary[e];null!=n&&n.forEach(function(e){try{e&&e(t)}catch(e){console.warn(e)}})},e.prototype.RemoveHandler=function(e,t){var n=this.ListenerDictionary[e];if(null!=n){var i=n.findIndex(function(e){return t==e});i>=0&&n.splice(i,1)}},e.prototype.ResetHandlers=function(){this.ListenerDictionary={}},e.prototype.Dispose=function(){this.ResetHandlers()},e}();e.LocalMessageBus=A;var b=function(){function e(){this.ListenerDictionary={},window&&window.top?(this.HandleWindowMessage=this.HandleWindowMessage.bind(this),window.top.addEventListener("message",this.HandleWindowMessage)):console.warn("GlobalMessageBus: No Top Window Available")}return e.prototype.OnMessage=function(e,t){var n;null==this.ListenerDictionary[e]?(n=[],this.ListenerDictionary[e]=n):n=this.ListenerDictionary[e],n.findIndex(function(e){return t==e})<0&&n.push(t)},e.prototype.PostMessage=function(e,t,n,i){void 0===t&&(t=null),void 0===n&&(n="*"),window&&window.top?window.top.postMessage({source:"eventbus",message:e,data:t},n,i):console.warn("GlobalMessageBus: No Top Window Available")},e.prototype.RemoveHandler=function(e,t){var n=this.ListenerDictionary[e];if(null!=n){var i=n.findIndex(function(e){return t==e});i>=0&&n.splice(i,1)}},e.prototype.ResetHandlers=function(){this.ListenerDictionary={}},e.prototype.Dispose=function(){this.ResetHandlers(),window&&window.top&&window.top.removeEventListener("message",this.HandleWindowMessage)},e.prototype.HandleWindowMessage=function(e){null!=e&&null!=e.data&&null!=e.data.message&&null!=e.data.source&&"eventbus"==e.data.source&&this.OnDispatchMessage(e.data.message,null!=e.data.data?e.data.data:null)},e.prototype.OnDispatchMessage=function(e,t){void 0===t&&(t=null);var n=this.ListenerDictionary[e];null!=n&&n.forEach(function(e){try{e&&e(t)}catch(e){console.warn(e)}})},e}();e.GlobalMessageBus=b;var M=function(){function t(e,t,n,i,r,o){void 0===n&&(n=1),void 0===i&&(i=!0),void 0===r&&(r=!1),void 0===o&&(o=!0),this.prefabName=null,this.allowGrowth=!0,this.assetContainer=null,this.cloneAnimations=!0,this.makeNewMaterials=!1,this.availableInstances=null,this.prefabName=t,this.allowGrowth=i,this.assetContainer=e,this.cloneAnimations=o,this.makeNewMaterials=r,this.availableInstances=[],this.populatePool(n)}return t.prototype.getAvailableCount=function(){return this.availableInstances.length},t.prototype.populatePool=function(e){if(e>0)for(var t=0;t<e;t++){var n=this.createNewInstance();null!=n&&this.freeInstance(n)}},t.prototype.getInstance=function(e,t){void 0===e&&(e=null),void 0===t&&(t=null);var n=this.availableInstances.length>0?this.availableInstances.pop():this.appendNewInstance();return null!=n&&(null!=e?n.position.copyFrom(e):n.position.set(0,0,0),null!=t?null!=n.rotationQuaternion?n.rotationQuaternion.copyFrom(t):n.rotationQuaternion=t.clone():null!=n.rotationQuaternion?n.rotationQuaternion.set(0,0,0,1):n.rotationQuaternion=new BABYLON.Quaternion(0,0,0,1),n.name=this.prefabName+".Instance",n.setEnabled(!0)),n},t.prototype.freeInstance=function(e){null!=e&&(e.setEnabled(!1),e.position.set(0,0,0),null!=e.rotationQuaternion?e.rotationQuaternion.set(0,0,0,1):e.rotationQuaternion=new BABYLON.Quaternion(0,0,0,1),null!=e.metadata&&null!=e.metadata.toolkit&&null!=e.metadata.toolkit.components&&e.metadata.toolkit.components.forEach(function(e){if(null!=e)try{e.resetScriptComponent()}catch(e){}}),e.name=this.prefabName+".Unassigned",this.availableInstances.push(e))},t.prototype.appendNewInstance=function(){var e=null;return!0===this.allowGrowth&&(e=this.createNewInstance()),e},t.prototype.createNewInstance=function(t,n,i,r){void 0===t&&(t=null),void 0===n&&(n=null),void 0===i&&(i=null),void 0===r&&(r=null);var o=null;return null!=this.assetContainer&&null!=this.prefabName&&""!==this.prefabName&&(this.assetContainer instanceof BABYLON.AssetContainer?o=e.SceneManager.InstantiatePrefabFromContainer(this.assetContainer,this.prefabName,this.prefabName+".Instance",t,n,i,r,this.cloneAnimations,this.makeNewMaterials):this.assetContainer instanceof BABYLON.Scene&&(o=e.SceneManager.InstantiatePrefabFromScene(this.assetContainer,this.prefabName,this.prefabName+".Instance",t,n,i,r,this.cloneAnimations))),o},t}();e.PrefabObjectPool=M;var B=function(){function e(){this._hit=!1,this._dest=new BABYLON.Vector3(0,0,0),this._origin=new BABYLON.Vector3(0,0,0),this._hitPoint=new BABYLON.Vector3(0,0,0),this._hitNormal=new BABYLON.Vector3(0,0,0),this._hitDistance=0,this._collisionObject=null,this.reset(BABYLON.Vector3.Zero(),BABYLON.Vector3.Zero())}return Object.defineProperty(e.prototype,"hasHit",{get:function(){return this._hit},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hitPoint",{get:function(){return this._hitPoint},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hitNormal",{get:function(){return this._hitNormal},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hitDistance",{get:function(){return this._hitDistance},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"collisionObject",{get:function(){return this._collisionObject},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"rayDestination",{get:function(){return this._dest},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"rayOrigin",{get:function(){return this._origin},enumerable:!1,configurable:!0}),e.prototype.reset=function(e,t){this._hit=!1,this._hitPoint.set(0,0,0),this._hitNormal.set(0,0,0),this._hitDistance=0,this._collisionObject=null,this._origin.copyFrom(e),this._dest.copyFrom(t)},e.prototype.update=function(e,t,n,i,r,o,a,s){void 0===s&&(s=null),this._hit=e,this._hitPoint.set(t,n,i),this._hitNormal.set(r,o,a),this._hitDistance=BABYLON.Vector3.Distance(this._origin,this.hitPoint),this._collisionObject=s},e}();e.RaycastHitResult=B;var C=function(){function t(e,t,n,i){void 0===n&&(n=0),void 0===i&&(i=.5),this._numPoints=-1,this._pointMesh=null,this._pointSize=.5,this._pointType=0,this._linesName="MeshLines",this._linesMesh=null,this._babylonScene=null,this._pointMesh=null,this._linesMesh=null,this._linesName=e,this._babylonScene=t,this._pointType=n,this._pointSize=i}return Object.defineProperty(t.prototype,"pointMesh",{get:function(){return this._pointMesh},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"linesMesh",{get:function(){return this._linesMesh},enumerable:!1,configurable:!0}),t.prototype.dispose=function(e){void 0===e&&(e=!0),this._babylonScene=null,this._linesName=null,null!=this._pointMesh&&(this._pointMesh.dispose(e),this._pointMesh=null),null!=this._linesMesh&&(this._linesMesh.dispose(e),this._linesMesh=null)},t.prototype.hidePoint=function(e){void 0===e&&(e=!0),null!=this._pointMesh&&(this._pointMesh.isVisible=!e)},t.prototype.drawPoint=function(t){null==this._pointMesh&&(1===this._pointType?(this._pointMesh=BABYLON.MeshBuilder.CreateBox(this._linesName+".EndPoint",{size:2*this._pointSize},this._babylonScene),this._pointMesh.renderingGroupId=e.Utilities.DefaultRenderGroup(),this._pointMesh.visibility=.25):(this._pointMesh=BABYLON.MeshBuilder.CreateSphere(this._linesName+".EndPoint",{segments:24,diameter:2*this._pointSize},this._babylonScene),this._pointMesh.renderingGroupId=e.Utilities.DefaultRenderGroup(),this._pointMesh.visibility=.25)),null!=this._pointMesh&&(this._pointMesh.isVisible=!0,this._pointMesh.position.copyFrom(t))},t.prototype.drawLine=function(t,n){void 0===n&&(n=null),null==this._linesMesh?(this._numPoints=t.length,this._linesMesh=BABYLON.MeshBuilder.CreateLines(this._linesName,{points:t,updatable:!0},this._babylonScene),this._linesMesh.renderingGroupId=e.Utilities.DefaultRenderGroup(),null!=n&&(this._linesMesh.color=n),this._linesMesh.refreshBoundingInfo(!1)):t.length===this._numPoints?(this._linesMesh=BABYLON.MeshBuilder.CreateLines(this._linesName,{points:t,instance:this._linesMesh},this._babylonScene),this._linesMesh.renderingGroupId=e.Utilities.DefaultRenderGroup(),null!=n&&(this._linesMesh.color=n),this._linesMesh.refreshBoundingInfo(!1)):BABYLON.Tools.Warn("Dynamic line mesh point count mismatch for "+this._linesName)},t}();e.LinesMeshRenderer=C;var T=function(t){function n(){return null!==t&&t.apply(this,arguments)||this}return r(n,t),n.prototype.addContainerTask=function(e,t,n,i){var r=this,o=new BABYLON.ContainerAssetTask(e,t,n,i),a=o;return a._lengthComputable=0,a._loaded=0,a._total=0,a.runTask=function(e,t,n){BABYLON.SceneLoader.LoadAssetContainer(o.rootUrl,o.sceneFilename,e,function(e){o.loadedContainer=e,o.loadedMeshes=e.meshes,o.loadedParticleSystems=e.particleSystems,o.loadedSkeletons=e.skeletons,o.loadedAnimationGroups=e.animationGroups,t()},function(e){a._lengthComputable=e.lengthComputable,a._loaded=e.loaded,a._total=e.total,r.handlePreloadingProgress()},function(e,t,i){n(t,i)})},this._tasks.push(o),o},n.prototype.addMeshTask=function(e,t,n,i){var r=this,o=new BABYLON.MeshAssetTask(e,t,n,i),a=o;return a._lengthComputable=0,a._loaded=0,a._total=0,a.runTask=function(e,t,n){BABYLON.SceneLoader.ImportMesh(o.meshesNames,o.rootUrl,o.sceneFilename,e,function(e,n,i,r){o.loadedMeshes=e,o.loadedParticleSystems=n,o.loadedSkeletons=i,o.loadedAnimationGroups=r,t()},function(e){a._lengthComputable=e.lengthComputable,a._loaded=e.loaded,a._total=e.total,r.handlePreloadingProgress()},function(e,t,i){n(t,i)})},this._tasks.push(o),o},n.prototype.addTextFileTask=function(e,t){var n=this,i=new BABYLON.TextFileAssetTask(e,t),r=i;return r._lengthComputable=0,r._loaded=0,r._total=0,r.runTask=function(e,t,o){e._loadFile(i.url,function(e){i.text=e,t()},function(e){r._lengthComputable=e.lengthComputable,r._loaded=e.loaded,r._total=e.total,n.handlePreloadingProgress()},!1,!1,function(e,t){e&&o(e.status+" "+e.statusText,t)})},this._tasks.push(i),i},n.prototype.addBinaryFileTask=function(e,t){var n=this,i=new BABYLON.BinaryFileAssetTask(e,t),r=i;return r._lengthComputable=0,r._loaded=0,r._total=0,r.runTask=function(e,t,o){e._loadFile(i.url,function(e){i.data=e,t()},function(e){r._lengthComputable=e.lengthComputable,r._loaded=e.loaded,r._total=e.total,n.handlePreloadingProgress()},!0,!0,function(e,t){e&&o(e.status+" "+e.statusText,t)})},this._tasks.push(i),i},n.prototype.addImageTask=function(e,t){var n=this,i=new BABYLON.ImageAssetTask(e,t),r=i;return r._lengthComputable=0,r._loaded=0,r._total=0,r.runTask=function(e,t,o){var a=new HTMLImageElement;BABYLON.Tools.SetCorsBehavior(i.url,a),a.onload=function(){i.image=a,t()},a.onerror=function(e){o("Error loading image",e)},a.onprogress=function(e){r._lengthComputable=e.lengthComputable,r._loaded=e.loaded,r._total=e.total,n.handlePreloadingProgress()},a.src=i.url},this._tasks.push(i),i},n.prototype.handlePreloadingProgress=function(){var t=!0,n=0,i=0;if(null!=this._tasks&&this._tasks.length>0)for(var r=0;r<this._tasks.length;r++){var o=this._tasks[r];null!=o._lengthComputable&&null!=o._loaded&&null!=o._total&&(t=t&&o._lengthComputable,n+=o._loaded,i+=o._total)}if(null!=e.SceneManager.OnAssetManagerProgress){var a={lengthComputable:t,loaded:n,total:t?i:0};e.SceneManager.OnAssetManagerProgress(a)}},n}(BABYLON.AssetsManager);e.PreloadAssetsManager=T;var x=function(){function e(){}return e.HasNetworkEntity=function(e){return null!=e&&null!=e.networkEntity},e.GetNetworkEntityId=function(e){return null==e?null:null!=e.networkEntity?e.networkEntity.id:null},e.GetNetworkEntityType=function(e){return null==e?0:null!=e.networkEntityType?e.networkEntityType:0},e.GetNetworkEntitySessionId=function(e){return null==e?null:null!=e.networkEntity?e.networkEntity.ownerId:null},e.QueryNetworkAttribute=function(e,t){var n=null;return null!=e&&null!=e.networkEntity&&null!=e.networkEntity.attributes&&(n=e.networkEntity.attributes.get(t)),n},e.QueryBufferedAttribute=function(e,t){var n=0;return null!=e&&null!=e.networkEntityAttributeBuffer&&(n=e.networkEntityAttributeBuffer[t.toFixed(0)]),n},e.PostBufferedAttribute=function(e,t,n){null==e.networkEntityBatch&&(e.networkEntityBatch={}),e.networkEntityBatch[t.toFixed(0)]=n},e}();e.EntityController=x}(i||(i={})),BABYLON.Bone.prototype.linkTransformNode=function(e){e._linkedBone=this,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++},function(e){var t;(t=e.MaterialAlphaMode||(e.MaterialAlphaMode={})).OPAQUE="OPAQUE",t.MASK="MASK",t.BLEND="BLEND";e.CubeTextureLoader=function(){};var n=function(){function t(t){this.name=e.SceneManager.CVTOOLS_NAME,this.enabled=!1,this._webgpu=!1,this._babylonScene=null,this._metadataParser=null,this._loaderScene=null,this._assetsManager=null,this._materialMap=null,this._lightmapMap=null,this._reflectionMap=null,this._reflectionCache=null,this._assetContainer=!1,this._activeMeshes=!1,this._parseScene=!1,this._leftHanded=!1,this._disposeRoot=!1,this._sceneParsed=!1,this._preWarmTime=1,this._hideLoader=!1,this._rootUrl=null,this._fileName="Unknown",this._licenseName="Unknown",this._licenseType="standard",this._pendingReflectionTextures=null,this._loader=t,this._pendingReflectionTextures=new Map,this.enabled=this._loader.isExtensionUsed(e.SceneManager.CVTOOLS_NAME)||this._loader.isExtensionUsed(e.SceneManager.CVTOOLS_HAND)||this._loader.isExtensionUsed(e.SceneManager.CVTOOLS_MESH),this._parseScene=this._leftHanded=this._disposeRoot=this._sceneParsed=!1,this._rootUrl=null,this._masterList=null,this._detailList=null,this._parserList=null,this._shaderList=null,this._readyList=null,this._preloadList=null,this._materialMap=null,this._lightmapMap=null,this._preWarmTime=1,this._hideLoader=!1,this._loaderScene=null,this._assetsManager=null,this._reflectionMap=null,this._reflectionCache=null,this._animationGroups=null,this._metadataParser=null,this._babylonScene=null,this.order=100}return t.prototype.dispose=function(){delete this._loader},t.prototype.onLoading=function(){var t=this;e.Utilities.LoadingState=0,this._assetContainer=null!=this._loader._assetContainer,this._metadataParser=null,this._babylonScene=this._loader.babylonScene,this._loaderScene=null,this._assetsManager=null,this._rootUrl=this._loader.rootUrl?this._loader.rootUrl:"/",this._fileName=this._loader._fileName?this._loader._fileName:"Unknown",this._fileName.indexOf("?")>=0&&(this._fileName=this._fileName.split("?")[0]),e.SceneManager.SetRootUrl(this._babylonScene,this._rootUrl),e.SceneManager.SetSceneFile(this._babylonScene,this._fileName),this._loader.parent.onCompleteObservable.addOnce(function(){t.onComplete()}),this._loader.parent.onValidatedObservable.addOnce(function(){t.onValidate()}),this._parseScene=this._loader.isExtensionUsed(e.SceneManager.CVTOOLS_NAME)&&!0===e.SceneManager.IsSceneParsingEnabled(),this._leftHanded=this._loader.isExtensionUsed(e.SceneManager.CVTOOLS_HAND),this._disposeRoot=this._sceneParsed=!1,this._animationGroups=[],this._masterList=[],this._detailList=[],this._parserList=[],this._shaderList=[],this._readyList=[],this._preloadList=[],this._materialMap=new Map,this._lightmapMap=new Map,this._preWarmTime=1,this._hideLoader=!1,this._reflectionMap={},this._reflectionCache={},e.Utilities.ResetLoaderItemsMarkedForDisposal(),this._webgpu=this._babylonScene.getEngine()instanceof BABYLON.WebGPUEngine,this._babylonScene.getEngine().getCaps().supportSRGBBuffers=e.SceneManager.SupportSRGBBuffers,!0===this._leftHanded&&null!=this._loader.rootBabylonMesh&&(this._loader.rootBabylonMesh.rotationQuaternion=BABYLON.Quaternion.Identity(),this._loader.rootBabylonMesh.scaling=BABYLON.Vector3.One()),!0===this._parseScene&&(e.SceneManager.RenderLoopReady=!1,null!=this._loader.rootBabylonMesh&&(this._loader.rootBabylonMesh.name="Root."+this._fileName.replace(".gltf","").replace(".glb","")),this.setupLoader())},t.prototype.onReady=function(){!0===this._parseScene&&!0===this._disposeRoot&&null!=this._loader.rootBabylonMesh&&this._loader.rootBabylonMesh.dispose(!0)},t.prototype.onComplete=function(){this._parseScene,this.finishComplete()},t.prototype.getScriptBundleTag=function(){var e=null,t=this._loaderScene,n=null!=t&&null!=t.extras&&null!=t.extras.metadata?t.extras.metadata:null;if(null!=n){null!=this._rootUrl&&this._rootUrl;var i=null!=n.script?n.script:null,r=null!=n.project?n.project:null;null!=i&&""!==i&&null!=r&&""!==r&&(e=r.toLocaleLowerCase())}return e},t.prototype.getScriptBundleUrl=function(){var e=null,t=this._loaderScene,n=null!=t&&null!=t.extras&&null!=t.extras.metadata?t.extras.metadata:null;if(null!=n){var i=null!=this._rootUrl?this._rootUrl:"/",r=null!=n.script?n.script:null,o=null!=n.project?n.project:null;null!=r&&""!==r&&null!=o&&""!==o&&(e=i+o)}return e},t.prototype.finishComplete=function(){var t=this;!0===this._parseScene&&(this.startParsing(),e.SceneManager.RenderLoopReady=!0,this._babylonScene.onAfterRenderObservable.addOnce(function(){e.Utilities.LoadingState=3,t._processPreloadTimeout()}))},t.prototype.onValidate=function(){this._parseScene},t.prototype.onCleanup=function(){this._fileName=null,this._rootUrl=null,this._parseScene=this._leftHanded=this._disposeRoot=this._sceneParsed=!1,this._masterList=null,this._detailList=null,this._parserList=null,this._shaderList=null,this._preWarmTime=1,this._readyList=null,this._preloadList=null,this._hideLoader=!1,this._animationGroups=null,null!=this._materialMap&&(this._materialMap.clear(),this._materialMap=null),null!=this._lightmapMap&&(this._lightmapMap.clear(),this._lightmapMap=null),this._loaderScene=null,this._assetsManager=null,this._reflectionMap=null,this._reflectionCache=null,this._metadataParser=null,this._babylonScene=null,null!=this._pendingReflectionTextures&&(this._pendingReflectionTextures.clear(),this._pendingReflectionTextures=null)},t.prototype.setupLoader=function(){var t=this,n=this._fileName;!0===this._parseScene&&(this._assetsManager=new e.PreloadAssetsManager(this._babylonScene),this._assetsManager.onProgress=function(t,n,i){if(!0===e.SceneManager.AutoUpdateProgress){var r="LOADING "+(n-t)+" OF "+n+(1===n?" ASSET":" ASSETS");e.WindowManager.UpdateLoaderDetails(r,e.Utilities.LoadingState)}else null!=e.Utilities.OnPreloaderProgress&&e.Utilities.OnPreloaderProgress(t,n,i)},this._assetsManager.onFinish=function(i){e.WindowManager.SetTimeout(100,function(){e.Utilities.LoadingState=4,!0===e.SceneManager.AutoUpdateProgress&&e.WindowManager.UpdateLoaderStatus("PLEASE WAIT","PREPARING SCENE VIEW",e.Utilities.LoadingState);var r=t._preWarmTime>0?1e3*t._preWarmTime:100;e.WindowManager.SetTimeout(r,function(){if(null!=e.Utilities.OnPreloaderComplete&&e.Utilities.OnPreloaderComplete(i),t._processShaderMaterials(t._babylonScene,t._shaderList),e.Utilities.RemoveLoaderItemsMarkedForDisposal(),null!=t._readyList&&t._readyList.length>0)for(var r=0;r<t._readyList.length;r++){var o=t._readyList[r];null!=o&&o._ready&&o._ready()}t._babylonScene.onAfterRenderObservable.addOnce(function(){var i=null!=n&&""!==n?n:"Unknown";null!=e.SceneManager.OnSceneReadyObservable&&e.SceneManager.OnSceneReadyObservable.notifyObservers(i),1==t._hideLoader&&e.WindowManager.HideSceneLoader(),t.onCleanup()})})})})},t.prototype.startParsing=function(){!0===this._parseScene&&(e.Utilities.LoadingState=2,this._processLevelOfDetail(this._babylonScene,this._detailList),this._processActiveMeshes(this._babylonScene,this._activeMeshes),this._processUnityMeshes(this._masterList),null!=this._loaderScene&&(this.preProcessSceneProperties(this._loaderScene,this._babylonScene),this.postProcessSceneProperties(this._rootUrl,this._loaderScene,this._babylonScene)),!1===this._assetContainer&&null!=this._parserList&&this._parserList.length>0&&(this._metadataParser=e.Utilities.PostParseSceneComponents(this._babylonScene,this._parserList,this._preloadList,this._readyList)),null!=this._loaderScene&&this.lateProcessSceneProperties(this._rootUrl,this._loaderScene,this._babylonScene))},t.prototype._processActiveMeshes=function(e,t){!0===t&&e.freeActiveMeshes()},t.prototype._processUnityMeshes=function(t){null!=t&&t.length>0&&t.forEach(function(t){e.Utilities.RegisterInstancedMeshBuffers(t)})},t.prototype._processPreloadTimeout=function(){if(null!=this._assetsManager){if(null!=this._preloadList&&this._preloadList.length>0)for(var e=0;e<this._preloadList.length;e++){var t=this._preloadList[e];null!=t&&t.addPreloaderTasks&&t.addPreloaderTasks(this._assetsManager)}this._babylonScene._preloaded=!0,this._assetsManager.load()}},t.prototype.loadSceneAsync=function(t,n){var i;return!0===this._parseScene&&(this._loaderScene=n,e.Utilities.LoadingState=1),this._parseScene&&(null===(i=n.extras)||void 0===i?void 0:i.metadata)?this._loadSceneInternalAsync(t,n):null},t.prototype._loadSceneInternalAsync=function(e,t){return a(this,void 0,void 0,function(){var n,i,r;return s(this,function(o){switch(o.label){case 0:return o.trys.push([0,3,,4]),n=t.extras.metadata,(null===(r=null==n?void 0:n.skybox)||void 0===r?void 0:r.environment)&&this.updateSkyboxEnvironment(n.skybox,this._babylonScene),[4,this._loader.loadSceneAsync(e,t)];case 1:return o.sent(),[4,this._loadSceneExAsync(e,t)];case 2:return o.sent(),[3,4];case 3:return i=o.sent(),console.error("CVTOOLS: Error in loadSceneAsync:",i),[3,4];case 4:return[2]}})})},t.prototype._loadSceneExAsync=function(t,n){return a(this,void 0,void 0,function(){var t,n,i,r,o,a,l,u,c,d=this;return s(this,function(s){if(t=this._loader,n=new Array,t._gltf.nodes)for(i=0,r=t._gltf.nodes;i<r.length;i++)(o=r[i])._babylonTransformNode&&this._animationGroups&&e.Utilities.AssignAnimationGroupsToNode(o._babylonTransformNode,this._animationGroups);if(null!=this._reflectionMap&&null!=this._reflectionCache)for(c in a=0,l=function(t){if(a++,u._reflectionMap.hasOwnProperty(t)){var n=t;if(null!=u._assetsManager){var i=u._assetsManager.addBinaryFileTask("Material.ReflectionTextureTask"+a.toFixed(0),n);i.onSuccess=function(t){if(null!=t.data){new Blob([t.data]);var i=d._reflectionMap[n];null!=i&&i.forEach(function(i){if(null!=i&&null!=i.mapkey){var r=d._reflectionCache[i.mapkey];if(null!=r)null!=i.material&&e.Utilities.HasOwnProperty(i.material,"reflectionTexture")&&(i.material.reflectionTexture=r);else{var o=d._babylonScene,a=t.data instanceof ArrayBuffer?new Uint8Array(t.data):t.data,s=".env"===(i.extension||"").toLowerCase()||i.mapkey&&i.mapkey.toLowerCase().endsWith(".env")?".env":".dds",l=new BABYLON.CubeTexture(n,o,{buffer:a,prefiltered:!0,forcedExtension:s,createPolynomials:!0,onLoad:function(){},onError:function(e,t){return console.error(e,t)}});l.name=i.name,l.level=i.reflectionProbePower*e.CVTOOLS_unity_metadata.IBL_PROBE_FACTOR,l.gammaSpace=!1,null!=i.boundingBoxSize&&(l.boundingBoxSize=i.boundingBoxSize),null!=i.boundingBoxPosition&&(l.boundingBoxPosition=i.boundingBoxPosition),d._reflectionCache[i.mapkey]=l,null!=i.material&&e.Utilities.HasOwnProperty(i.material,"reflectionTexture")&&(i.material.reflectionTexture=l)}}})}else console.error("Failed to load reflection texture task: "+n)},i.onError=function(e,t,n){console.error(t,n)}}}},u=this,this._reflectionMap)l(c);return t.logClose(),[2,Promise.all(n).then(function(){})]})})},t.prototype.loadNodeAsync=function(t,n,i){var r,o=this;if(!this._parseScene||!(null===(r=n.extras)||void 0===r?void 0:r.metadata))return null;try{return this._loader.loadNodeAsync(t,n,function(t){try{var r=t,a=n.extras.metadata;null==r.metadata&&(r.metadata={}),r.metadata.toolkit=a,e.Utilities.ValidateTransformGuid(r),e.Utilities.ValidateTransformMetadata(r),e.Utilities.ValidateTransformQuaternion(r),r.layerMask=null!=r.metadata.toolkit.layermask?r.metadata.toolkit.layermask:e.SceneManager.DefaultLayerMask,r.isVisible=null==r.metadata.toolkit.visible||r.metadata.toolkit.visible,r.visibility=null!=r.metadata.toolkit.visibility?r.metadata.toolkit.visibility:1,r.billboardMode=null!=r.metadata.toolkit.billboard?r.metadata.toolkit.billboard:0,!0===o._assetContainer&&(r.metadata.toolkit.prefab=!0),!0===r.metadata.toolkit.prefab?r.setEnabled(!1):(o._parserList.push(r),null!=n.extras.metadata.lods&&null!=n.extras.metadata.distances&&null!=o._detailList&&o._detailList.push(r)),o._masterList.push(r),i(r)}catch(e){console.error("CVTOOLS: Error in node assignment callback:",e),i(t)}})}catch(e){return console.error("CVTOOLS: Error in loadNodeAsync:",e),null}},t.prototype.loadMaterialPropertiesAsync=function(e,t,n){var i=this;return this.enabled?this._loader.loadMaterialPropertiesAsync(e,t,n).then(function(){var r,o=[];try{i._parseCommonConstantProperties(o,e,t,n)}catch(e){BABYLON.Tools.Warn("[CVTOOLS] _parseCommonConstantProperties threw for ".concat(null!==(r=null==t?void 0:t.name)&&void 0!==r?r:"material",": ").concat(e))}if(0!==o.length)return Promise.all(o.map(function(e){return e.catch(function(e){var n;BABYLON.Tools.Warn("[CVTOOLS] Extra material async failed for ".concat(null!==(n=null==t?void 0:t.name)&&void 0!==n?n:"material",": ").concat(e))})})).then(function(){})}):null},t.prototype._getCachedMaterialByIndex=function(e){var t=null;return e>=0&&null!=this._materialMap&&(t=this._materialMap.get(e)||null),t},t.prototype._getCachedLightmapByIndex=function(e){var t=null;return e>=0&&null!=this._lightmapMap&&(t=this._lightmapMap.get(e)||null),t},t.prototype.createMaterial=function(t,n,i){if(!0===this._parseScene&&n.index){var r=n.index;if(r>=0){var o=this._getCachedMaterialByIndex(r);if(null!=o)return o}}if(!0===this._parseScene){var a=null,s=n.name||"No Name";if(null!=n.extras&&null!=n.extras.metadata&&null!=n.extras.metadata.customMaterial){var l=n.extras.metadata,u=l.customMaterial,c=(l.customShader,e.Utilities.InstantiateClass(u));if(null!=c){var d=new c(s,this._loader.babylonScene);null!=d?!0==d instanceof BABYLON.Material?(a=d).fillMode=i:BABYLON.Tools.Warn("Non material instantiated class: "+u):BABYLON.Tools.Warn("Failed to instantiate material class: "+u)}else BABYLON.Tools.Warn("Failed to locate material class: "+u)}return null==a&&((a=new e.UniversalShaderMaterial(s,this._loader.babylonScene)).fillMode=i),null!=a&&this._parseUniformAndSamplerProperties(t,n,a),a}return null},t.prototype.loadAnimationAsync=function(e,t){if(!0===this._parseScene){this._loader;var n=t;this._babylonScene._blockEntityCollection=!!this._assetContainer;var i=new BABYLON.AnimationGroup(t.name||"animation".concat(n.index),this._babylonScene);i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n._babylonAnimationGroup=i,this._animationGroups.push(i);var r=new Array;BABYLON.GLTF2.ArrayItem.Assign(n.channels),BABYLON.GLTF2.ArrayItem.Assign(n.samplers);for(var o=0,a=t.channels;o<a.length;o++){var s=a[o],l=s;r.push(this._loader._loadAnimationChannelAsync("".concat(e,"/channels/").concat(l.index),e,t,s,function(e,t){e.animations=e.animations||[],e.animations.push(t),i.addTargetedAnimation(t,e)}))}return Promise.all(r).then(function(){if(null!=t.extras&&null!=t.extras.metadata){var e={};e.toolkit=t.extras.metadata,i.metadata=e,null!=e.label&&""!==e.label&&(i.name=e.label)}return i.normalize(0),i})}return null},t.prototype._loadMeshPrimitiveAsync=function(e,t,n,i,r,o){var a=this;if(!0===this._parseScene){var s=this._loader;s.logOpen("".concat(e));var l,u=0===s._disableInstancedMesh&&s._parent.createInstances&&null==n.skin&&!i.primitives[0].targets,c=void 0;if(u&&r._instanceData)s._babylonScene._blockEntityCollection=!!s._assetContainer,(l=r._instanceData.babylonSourceMesh.createInstance(t))._parentContainer=s._assetContainer,s._babylonScene._blockEntityCollection=!1,c=r._instanceData.promise;else{var d=new Array;s._babylonScene._blockEntityCollection=!!s._assetContainer;var h=new BABYLON.Mesh(t,s._babylonScene);h._parentContainer=s._assetContainer,s._babylonScene._blockEntityCollection=!1,!0===this._leftHanded?h.sideOrientation=BABYLON.Material.CounterClockWiseSideOrientation:h.sideOrientation=s._babylonScene.useRightHandedSystem?BABYLON.Material.ClockWiseSideOrientation:BABYLON.Material.CounterClockWiseSideOrientation,s._createMorphTargets(e,n,i,r,h),d.push(s._loadVertexDataAsync(e,r,h).then(function(t){return s._loadMorphTargetsAsync(e,r,h,t).then(function(){s._disposed||(s._babylonScene._blockEntityCollection=!!s._assetContainer,t.applyToMesh(h),a._setupBabylonMesh(h,n,i,r),t._parentContainer=s._assetContainer,s._babylonScene._blockEntityCollection=!1)})}));var p=BABYLON.GLTF2.GLTFLoader._GetDrawMode(e,r.mode);if(null!=r.extras&&null!=r.extras.metadata&&null!=r.extras.metadata.multimaterial&&null!=r.extras.metadata.submeshes)this._setupBabylonMultiMaterials(e,d,p,h,i,r);else if(null==r.material){var m=s._defaultBabylonMaterialData[p];m||(m=s._createDefaultMaterial("__GLTFLoader._default",p),s._parent.onMaterialLoadedObservable.notifyObservers(m),s._defaultBabylonMaterialData[p]=m),h.material=m}else if(!s.parent.skipMaterials){var f=BABYLON.GLTF2.ArrayItem.Get("".concat(e,"/material"),s._gltf.materials,r.material);d.push(s._loadMaterialAsync("/materials/".concat(f.index),f,h,p,function(e){h.material=e}))}c=Promise.all(d),u&&(r._instanceData={babylonSourceMesh:h,promise:c}),l=h}return BABYLON.GLTF2.GLTFLoader.AddPointerMetadata(l,e),s._parent.onMeshLoadedObservable.notifyObservers(l),o(l),s.logClose(),c.then(function(){return l})}return null},t.prototype._setupBabylonMesh=function(e,t,n,i){if(!0===this._parseScene){if(this._loader,null!=i.extras&&null!=i.extras.metadata&&null!=i.extras.metadata.multimaterial&&null!=i.extras.metadata.submeshes){var r=i.extras.metadata.submeshes;e.subMeshes=[];for(var o=0;o<r.length;o++){var a=r[o];BABYLON.SubMesh.AddToMesh(a.materialIndex,a.verticesStart,a.verticesCount,a.indexStart,a.indexCount,e)}}e.computeWorldMatrix(!0)}},t.prototype._setupBabylonMultiMaterials=function(e,t,n,i,r,o){if(!0===this._parseScene){var a=this._loader,s=o.extras.metadata.multimaterial,l=s.materials,u=[],c=s.id||"MM_"+r.name,d=s.name||"MM_"+r.name,h=new BABYLON.MultiMaterial("["+d+"]",a._babylonScene);h.id=c,l.forEach(function(t){if(null!=t){var n=parseInt(t);if(n>=0){var r=BABYLON.GLTF2.ArrayItem.Get("".concat(e,"/material"),a._gltf.materials,n);u.push(r)}else console.warn("Invalid Submesh Material Index Encountered For: "+i.name)}else console.warn("Null Submesh Material Encountered For: "+i.name)}),t.push(this._parseMultiMaterialAsync("/materials/".concat(d),u,i,n,function(e){h.subMaterials=e,i.material=h}))}},t.prototype._processLevelOfDetail=function(e,t){null!=t&&t.length>0&&t.forEach(function(e){})},t.prototype._processShaderMaterials=function(e,t){null!=t&&t.length>0&&t.forEach(function(e){e.freeze()})},t.prototype.preProcessSceneProperties=function(t,n){var i,r,o;if(!0!==this._assetContainer&&!1===this._sceneParsed&&null!=t.extras&&null!=t.extras.metadata&&null!=t.extras.metadata.properties&&!0===t.extras.metadata.properties){this._sceneParsed=!0,null!=this._rootUrl&&this._rootUrl;var a=t.extras.metadata;if(null==n.metadata&&(n.metadata={}),null==n.metadata.toolkit&&(n.metadata.toolkit={}),n.metadata.toolkit=a,this._disposeRoot=null!=a.disposeroot&&!0===a.disposeroot,this._hideLoader=null!=a.hideloader&&!0===a.hideloader,this._preWarmTime=null!=a.prewarmup?a.prewarmup:0,this._licenseType=null!=a.license?a.license:"standard",this._licenseName=null!=a.licensee?a.licensee:"Unknown",e.SceneManager.EnableUserInput=!0,null!=this._licenseName&&""!==this._licenseName&&"Unknown"!==this._licenseName&&"DefaultCompany"!==this._licenseName&&"Default Company"!==this._licenseName&&BABYLON.Tools.Log(e.Utilities.MakeProper(this._fileName)+" licensed to "+this._licenseName),e.SceneManager.GlobalOptions.ktxtextures=null!=a.ktxtextures&&a.ktxtextures,e.SceneManager.GlobalOptions.ktxlightmaps=null!=a.ktxlightmaps&&a.ktxlightmaps,e.SceneManager.GlobalOptions.intensityFactor=null!=a.intensity?a.intensity:1,e.SceneManager.GlobalOptions.debugModeEnabled=null!=a.debugging&&a.debugging,e.SceneManager.GlobalOptions.showDebugColliders=null!=a.showdebugcolliders&&a.showdebugcolliders,e.SceneManager.GlobalOptions.colliderVisibility=null!=a.collidervisibility?a.collidervisibility:0,e.SceneManager.GlobalOptions.colliderRenderGroup=null!=a.colliderrendergroup?a.colliderrendergroup:0,e.SceneManager.GlobalOptions.defaultRenderGroup=null!=a.defaultrendergroup?a.defaultrendergroup:0,e.SceneManager.GlobalOptions.collisionWireframe=null!=a.collisionwireframe&&a.collisionwireframe,e.SceneManager.GlobalOptions.useTriangleNormals=null!=a.trianglenormals&&a.trianglenormals,e.SceneManager.GlobalOptions.useConvexTriangles=null==a.convextriangles||a.convextriangles,e.SceneManager.GlobalOptions.colliderInstances=null==a.colliderinstances||a.colliderinstances,e.SceneManager.GlobalOptions.reparentColliders=null==a.reparentcolliders||a.reparentcolliders,e.SceneManager.GlobalOptions.enablelegacyaudio=null!=a.enablelegacyaudio&&a.enablelegacyaudio,e.SceneManager.GlobalOptions.globalillumination=null!=a.globalillumination&&a.globalillumination,null!=a.clearcolor&&(n.clearColor=e.Utilities.ParseColor4(a.clearcolor)),null!=a.autoclear&&!0===a.autoclear&&(n.autoClear=!0,n.autoClearDepthAndStencil=!0),null!=a.rendergroups&&(BABYLON.RenderingManager.MAX_RENDERINGGROUPS=a.rendergroups),null!=a.imageprocessing){var s=a.imageprocessing,l=null!=s.contrast?s.contrast:1,u=null!=s.exposure?s.exposure:1;null!=n.imageProcessingConfiguration&&(n.imageProcessingConfiguration.contrast=l,n.imageProcessingConfiguration.exposure=u)}var c=null!=a.ambientlightmap?a.ambientlightmap:0;if(null!=a.ambientcoloring&&(n.ambientColor=e.Utilities.ParseColor3(a.ambientcoloring)),null!=a.ambientlighting&&1===a.ambientlighting){var d=n;if(null==d._AmbientLight)switch(d._AmbientLight=new BABYLON.HemisphericLight("Ambient Lighting",new BABYLON.Vector3(0,1,0),n),d._AmbientLight.falloffType=BABYLON.Light.FALLOFF_STANDARD,c){case 2:d._AmbientLight.lightmapMode=BABYLON.Light.LIGHTMAP_SHADOWSONLY;break;case 1:d._AmbientLight.lightmapMode=BABYLON.Light.LIGHTMAP_SPECULAR;break;default:d._AmbientLight.lightmapMode=BABYLON.Light.LIGHTMAP_DEFAULT}null!=d._AmbientLight&&("skybox"===a.ambientskymode||!1===a.ambientoverride?(d._AmbientLight.name="Ambient Blacklight",d._AmbientLight.diffuse=BABYLON.Color3.Black(),d._AmbientLight.specular=BABYLON.Color3.Black(),d._AmbientLight.groundColor=BABYLON.Color3.Black(),null!=a.ambientlightintensity&&(d._AmbientLight.intensity=a.ambientlightintensity),d._AmbientLight.intensity*=e.SceneManager.AmbientLightIntensity,d._AmbientLight.intensityMode=BABYLON.Light.INTENSITYMODE_ILLUMINANCE):(null!=a.ambientskycolor&&(d._AmbientLight.diffuse=e.Utilities.ParseColor3(a.ambientskycolor,BABYLON.Color3.Gray())),null!=a.ambientspecularcolor&&(d._AmbientLight.specular=e.Utilities.ParseColor3(a.ambientspecularcolor,BABYLON.Color3.Black())),null!=a.ambientgroundcolor&&(d._AmbientLight.groundColor=e.Utilities.ParseColor3(a.ambientgroundcolor,BABYLON.Color3.Gray())),null!=a.ambientlightintensity&&(d._AmbientLight.intensity=a.ambientlightintensity),d._AmbientLight.intensity*=e.SceneManager.AmbientLightIntensity,d._AmbientLight.intensityMode=BABYLON.Light.INTENSITYMODE_ILLUMINANCE))}if(null!=a.fogmode){var h=a.fogmode,p=1,m=BABYLON.Scene.FOGMODE_NONE;switch(h){case 1:m=BABYLON.Scene.FOGMODE_EXP,p=null!==(i=e.SceneManager.FogExpDensityScale)&&void 0!==i?i:1;break;case 2:m=BABYLON.Scene.FOGMODE_EXP2,p=null!==(r=e.SceneManager.FogExp2DensityScale)&&void 0!==r?r:1;break;case 3:m=BABYLON.Scene.FOGMODE_LINEAR,p=null!==(o=e.SceneManager.FogLinearDensityScale)&&void 0!==o?o:1;break;default:m=BABYLON.Scene.FOGMODE_NONE}m!==BABYLON.Scene.FOGMODE_NONE?(n.fogMode=m,n.fogEnabled=!0,null==a.fogdensity||m!==BABYLON.Scene.FOGMODE_EXP&&m!==BABYLON.Scene.FOGMODE_EXP2||(n.fogDensity=Math.max(0,a.fogdensity*p)),m===BABYLON.Scene.FOGMODE_LINEAR&&(null!=a.fogstart&&(n.fogStart=a.fogstart||0),null!=a.fogend&&(n.fogEnd=2*(a.fogend||300))),null!=a.fogcolor&&(n.fogColor=e.Utilities.ParseColor3(a.fogcolor))):n.fogEnabled=!1}var f=new BABYLON.Vector3(0,-9.81,0),g=null!=a.defaultgravity?e.Utilities.ParseVector3(a.defaultgravity,f):f;if(n.gravity=g.clone(),n.collisionsEnabled=!0,null!=a.enablephysics&&!0===a.enablephysics){var v=null==a.ccdenabled||a.ccdenabled,y=null!=a.ccdpenetration?a.ccdpenetration:1e-4,_=null!=a.subtimestep?a.subtimestep:0,S=null!=a.maxworldsweep?a.maxworldsweep:0,A=null==a.deltaworldstep||a.deltaworldstep;e.RigidbodyPhysics.ConfigurePhysicsEngine(n,!A,_,S,v,y,g)}if(null!=a.userinput){var b=a.userinput;e.UserInputOptions.KeyboardSmoothing=b.keyboardSmoothing,e.UserInputOptions.KeyboardMoveSensibility=b.keyboardSensitivity,e.UserInputOptions.KeyboardArrowSensibility=1,e.UserInputOptions.KeyboardMoveDeadZone=b.keyboardDeadZone,e.UserInputOptions.GamepadDeadStickValue=b.padDeadStick,e.UserInputOptions.GamepadLStickXInverted=b.padLStickXInvert,e.UserInputOptions.GamepadLStickYInverted=b.padLStickYInvert,e.UserInputOptions.GamepadRStickXInverted=b.padRStickXInvert,e.UserInputOptions.GamepadRStickYInverted=b.padRStickYInvert,e.UserInputOptions.GamepadLStickSensibility=b.padLStickLevel,e.UserInputOptions.GamepadRStickSensibility=b.padRStickLevel,e.UserInputOptions.SupportedInputDevices=b.supportedDevices,e.UserInputOptions.BabylonAngularSensibility=2e3,e.UserInputOptions.DefaultAngularSensibility=b.mouseSensitivity,e.UserInputOptions.PointerWheelDeadZone=b.wheelDeadZone,e.UserInputOptions.PointerMouseDeadZone=b.mouseDeadZone,e.UserInputOptions.PointerMouseInverted=b.mouseMoveInvert,e.UserInputOptions.UseCanvasElement=b.useCanvasElement,e.UserInputOptions.UseArrowKeyRotation=b.arrowKeyRotation,e.UserInputOptions.EnableBabylonRotation=!1}if(null!=a.enableinput&&!0===a.enableinput){var M={contextMenu:null==a.contextmenu||a.contextmenu,pointerLock:null!=a.pointerlock&&a.pointerlock,preventDefault:null!=a.preventdefault&&a.preventdefault,useCapture:null!=a.usecapture&&a.usecapture};e.InputController.ConfigureUserInput(n.getEngine(),n,M)}null!=a.freezeactivemeshes&&!0===a.freezeactivemeshes&&(this._activeMeshes=!0),null!=a.performancepriority&&(n.performancePriority=a.performancepriority)}},t.prototype.postProcessSceneProperties=function(t,n,i){return a(this,void 0,void 0,function(){var r,o,a,l,u,c,d,h,p,m,f,g,v,y,_,S,A,b,M;return s(this,function(s){if(!0===this._assetContainer)return[2];if(null!=n.extras&&null!=n.extras.metadata&&null!=n.extras.metadata.properties&&!0===n.extras.metadata.properties&&null!=(r=n.extras.metadata).skybox){null!=(o=r.skybox).skyurl&&o.skyurl,a=null!=o.skyres?o.skyres:512,l=null!=o.skyfog&&o.skyfog,u=null!=o.skytags?o.skytags:"Untagged",c=null!=o.skysize?o.skysize:1e3,d=null!=o.rotation?o.rotation:0,h=null!=o.basename&&""!==o.basename?t+o.basename:null,p=null!=o.skyfaces?o.skyfaces:null,m=null==o.sixsided||o.sixsided,f=null!=o.rendergroup?o.rendergroup:0,g=null!=o.extensions&&o.extensions.length>0?o.extensions:null,null==o.polynomial||o.polynomial;try{null!=p&&""!==p&&null!=h&&""!==h&&(v=null,"png"===p||"webp"===p?!0===m?(v=new BABYLON.CubeTexture(h,i,g),h.indexOf("_rgbd")>=0?(v.isRGBD=!0,v.gammaSpace=!0):(v.isRGBD=!1,v.gammaSpace=!0)):(y=h+"."+p,(v=new BABYLON.Texture(y,i,!0,!1)).isRGBD=h.indexOf("_rgbd")>=0,v.gammaSpace=!0):"hdr"===p?(_=h+"."+p,(v=new BABYLON.HDRCubeTexture(_,i,a,!0,!1,!0,!1)).isRGBD=!1,v.gammaSpace=!0):"exr"===p?(S=h+"."+p,(v=new BABYLON.EXRCubeTexture(S,i,a,!0,!1,!0,!1)).isRGBD=!1,v.gammaSpace=!0):((v=new BABYLON.CubeTexture(h,i,g)).isRGBD=!1,v.gammaSpace=!0),v.name=o.basename,v.coordinatesMode=BABYLON.Texture.SKYBOX_MODE,v.rotationY=BABYLON.Tools.ToRadians(d),A="Default Skybox",(b=BABYLON.MeshBuilder.CreateBox(A,{size:c},i)).renderingGroupId=e.Utilities.DefaultRenderGroup(),b.id=A,b.infiniteDistance=!0,b.applyFog=l,b.renderingGroupId=f,null!=u&&""!==u&&BABYLON.Tags.AddTagsTo(b,u),!0===i.useRightHandedSystem&&(b.scaling.x*=-1),(M=new BABYLON.StandardMaterial("Skybox-Material",i)).backFaceCulling=!1,M.disableLighting=!0,M.diffuseColor=new BABYLON.Color3(0,0,0),M.emissiveColor=new BABYLON.Color3(0,0,0),M.specularColor=new BABYLON.Color3(0,0,0),M.ambientColor=new BABYLON.Color3(0,0,0),M.reflectionTexture=v,b.material=M)}catch(e){console.warn(e)}}return[2]})})},t.prototype.updateSkyboxEnvironment=function(t,n){if(null!=t.environment){var i=t.environment,r=null!=i.info&&""!==i.info?i.info:null,o=null!=i.ibl?i.ibl:1,a=null!=i.level?i.level:1,s=null!=i.refl?i.refl:null,l=null!=i.scale?i.scale:1,u=null!=i.mode?i.mode:0;o=Math.max(0,o);var c=null!=s?s:o*a,d=BABYLON.Scalar.Clamp(o,0,10),h=BABYLON.Scalar.Clamp(c,0,1e3),p=Array.isArray(i.sh)&&27===i.sh.length,m="skybox"===i.sky&&!0===p;if(m&&this.generateSphericalHarmonics(n,i.sh,d),null!=r&&""!==r)try{var f=(null!=this._rootUrl?this._rootUrl:"/")+r.rooturl+r.name;if(null!=this._assetsManager){var g=this._assetsManager.addBinaryFileTask("Global.EnvironmentTextureTask",f);g.onSuccess=function(t){if(null!=t.data){var i=t.data instanceof ArrayBuffer?new Uint8Array(t.data):t.data,o=f.toLowerCase().endsWith(".env")?".env":".dds",a=new BABYLON.CubeTexture(f,n,{buffer:i,prefiltered:!0,forcedExtension:o,createPolynomials:1===u,onLoad:function(){},onError:function(e,t){return console.error(e,t)}});if(n.environmentTexture=a,n.environmentTexture.name="assets/"+r.name,n.environmentTexture.level=m?h*l:h,m)if(a.isReady()){var s=e.SceneManager.GetImageBasedLighting(n);null!=s&&(0===u&&(n.environmentTexture.sphericalPolynomial=s),n.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag))}else a.onLoadObservable.addOnce(function(){var t=e.SceneManager.GetImageBasedLighting(n);null!=t&&(0===u&&(n.environmentTexture.sphericalPolynomial=t),n.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag))})}else console.error("❌ Failed to load environment texture task: "+f)},g.onError=function(e,t,n){console.error("❌ Environment texture error:",t,n)}}}catch(e){console.warn("⚠️ Error setting up environment texture:",e)}}},t.prototype.generateSphericalHarmonics=function(e,t,n){try{var i=t.slice(0,9),r=t.slice(9,18),o=t.slice(18,27),a=new BABYLON.SphericalHarmonics;a.l00=new BABYLON.Vector3(i[0],r[0],o[0]),a.l1_1=new BABYLON.Vector3(i[1],r[1],o[1]),a.l10=new BABYLON.Vector3(i[2],r[2],o[2]),a.l11=new BABYLON.Vector3(i[3],r[3],o[3]),a.l2_2=new BABYLON.Vector3(i[4],r[4],o[4]),a.l2_1=new BABYLON.Vector3(i[5],r[5],o[5]),a.l20=new BABYLON.Vector3(i[6],r[6],o[6]),a.l21=new BABYLON.Vector3(i[7],r[7],o[7]),a.l22=new BABYLON.Vector3(i[8],r[8],o[8]),a.preScaled=!0,1!==n&&a.scaleInPlace(n);var s=BABYLON.SphericalPolynomial.FromHarmonics(a);e.globalSphericalPolynomial=s}catch(e){console.error("Failed to apply Unity SH to scene environment:",e)}},t.prototype.lateProcessSceneProperties=function(t,n,i){return a(this,void 0,void 0,function(){var t,r,o,a;return s(this,function(s){switch(s.label){case 0:return!0===this._assetContainer?[2]:null==n.extras||null==n.extras.metadata||null==n.extras.metadata.properties||!0!==n.extras.metadata.properties||null==(t=n.extras.metadata).navigation||null==t.navigation.prebaked||""===t.navigation.prebaked?[3,2]:(r=null!=t.navigation.prebaked&&""!==t.navigation.prebaked?t.navigation.prebaked:null,o=null!=t.navigation.showdebug&&!0===t.navigation.showdebug,a=null,null!=t.navigation.heightmesh&&""!==t.navigation.heightmesh&&null!=(a=i.getMeshByName(t.navigation.heightmesh))&&(a.material.transparencyMode=BABYLON.Material.MATERIAL_ALPHABLEND,a.checkCollisions=!1,a.visibility=o?.3:0,a.isVisible=!0,a.isPickable=!0),[4,e.SceneManager.LoadNavigationMeshDataAsync(i,r,a,o)]);case 1:s.sent(),s.label=2;case 2:return[2]}})})},t.prototype._preloadRawMaterialsAsync=function(e,t,n){var i=this._loader,r=new Array,o=BABYLON.Material.TriangleFillMode;return n.forEach(function(n){var a=BABYLON.GLTF2.ArrayItem.Get("".concat(e,"/material"),t,n);if(null!=a){var s=i.createMaterial(e,a,o);BABYLON.GLTF2.GLTFLoader.AddPointerMetadata(s,e),i._parent.onMaterialLoadedObservable.notifyObservers(s),r.push(i.loadMaterialPropertiesAsync(e,a,s))}}),Promise.all(r).then(function(){})},t.prototype._parseMultiMaterialAsync=function(e,t,n,i,r){var o=this;void 0===r&&(r=function(){});var a=this._loader,s=t;s._data=s._data||{};var l=s._data[i];if(!l){a.logOpen("".concat(e," ").concat(n.name||""));var u=[],c=new Array;t.forEach(function(t){var n=null;if(t.index){var r=t.index;r>=0&&(n=o._getCachedMaterialByIndex(r))}null==n&&(n=a.createMaterial(e,t,i),BABYLON.GLTF2.GLTFLoader.AddPointerMetadata(n,e),a._parent.onMaterialLoadedObservable.notifyObservers(n),c.push(a.loadMaterialPropertiesAsync(e,t,n))),u.push(n)}),l={babylonMaterials:u,babylonMeshes:[],promises:c},s._data[i]=l,a.logClose()}return l.babylonMeshes.push(n),n.onDisposeObservable.addOnce(function(){var e=l.babylonMeshes.indexOf(n);-1!==e&&l.babylonMeshes.splice(e,1)}),r(l.babylonMaterials),Promise.all(l.promises).then(function(){return l.babylonMaterials})},t.prototype._parseCommonConstantProperties=function(n,i,r,o){var a=this,s=null!=r.extras&&null!=r.extras.metadata?r.extras.metadata:null;if(null!=s){var l=o;e.Utilities.HasOwnProperty(l,"alphaMode")&&(l.alphaMode=null!=s&&s.alphaMode?s.alphaMode:BABYLON.Engine.ALPHA_COMBINE),e.Utilities.HasOwnProperty(l,"ambientColor")&&(l.ambientColor=null!=s&&s.ambientColorFactor?BABYLON.Color3.FromArray(s.ambientColorFactor):BABYLON.Color3.Black()),e.Utilities.HasOwnProperty(l,"backFaceCulling")&&(l.backFaceCulling=null==s||null==s.backFaceCulling||s.backFaceCulling);var u=!1,c=!1;if(o instanceof BABYLON.PBRMaterial){switch(u=!(!r.extensions||!r.extensions.KHR_materials_pbrSpecularGlossiness),!r.extensions||r.extensions.KHR_materials_specular,!0!==(c=u)&&(o.useMetallnessFromMetallicTextureBlue=!0,o.useRoughnessFromMetallicTextureGreen=!0,o.useRoughnessFromMetallicTextureAlpha=!1,o.useAmbientOcclusionFromMetallicTextureRed=!1),!0===c&&(o.useMicroSurfaceFromReflectivityMapAlpha=!0),o.directIntensity=null!=s.directIntensity?s.directIntensity:1,o.specularIntensity=null!=s.specularIntensity?s.specularIntensity:1,o.emissiveIntensity=null!=s.emissiveIntensity?s.emissiveIntensity:1,o.environmentIntensity=null!=s.environmentIntensity?s.environmentIntensity:1,o.indexOfRefraction=null!=s.indexOfRefraction?s.indexOfRefraction:1.5,e.Utilities.MarkGamma(o.albedoTexture),e.Utilities.MarkGamma(o.emissiveTexture),!0!==c&&e.Utilities.MarkLinear(o.metallicTexture),e.Utilities.MarkLinear(o.ambientTexture),e.Utilities.MarkLinear(o.opacityTexture),e.Utilities.MarkLinear(o.bumpTexture),!0===c&&e.Utilities.MarkGamma(o.reflectivityTexture),r.alphaMode||e.MaterialAlphaMode.OPAQUE){case e.MaterialAlphaMode.OPAQUE:o.alpha=1,o.transparencyMode=BABYLON.ShaderMaterial.MATERIAL_OPAQUE;break;case e.MaterialAlphaMode.MASK:o.transparencyMode=BABYLON.ShaderMaterial.MATERIAL_ALPHATEST;break;case e.MaterialAlphaMode.BLEND:o.transparencyMode=BABYLON.ShaderMaterial.MATERIAL_ALPHABLEND;break;default:o.alpha=1,o.transparencyMode=BABYLON.ShaderMaterial.MATERIAL_OPAQUE}var d=null!=s.clearCoatIntensity?s.clearCoatIntensity:0;d>0&&(o.clearCoat.isEnabled=!0,o.clearCoat.intensity=d),null!=s.useAlphaFromAlbedoTexture&&(o.useAlphaFromAlbedoTexture=s.useAlphaFromAlbedoTexture),null!=s.parallaxBias&&s.parallaxBias>0&&(o.useParallax=!0,o.parallaxScaleBias=s.parallaxBias)}if(e.Utilities.HasOwnProperty(l,"unlit")&&(l.unlit=null!=s.unlitMaterial&&s.unlitMaterial),e.Utilities.HasOwnProperty(l,"wireframe")&&(l.wireframe=null!=s.useWireframe&&s.useWireframe),e.Utilities.HasOwnProperty(l,"disableLighting")&&(l.disableLighting=null!=s.disableLighting&&s.disableLighting),e.Utilities.HasOwnProperty(l,"maxSimultaneousLights")&&(l.maxSimultaneousLights=null!=s.maxSimultaneousLights?s.maxSimultaneousLights:4),e.Utilities.HasOwnProperty(l,"needDepthPrePass")&&(l.needDepthPrePass=null!=s.depthPrepass&&s.depthPrepass),e.Utilities.HasOwnProperty(l,"lightmapTexture")&&s.lightmapTexture){s.lightmapTexture.nonColorData=!0;var h=!0;e.Utilities.HasOwnProperty(l,"useLightmapAsShadowmap")&&(h=null==s.useLightmapAsShadowmap||s.useLightmapAsShadowmap);var p=null,m=null!=s.lightmapTexture.index?s.lightmapTexture.index:-1;m>=0&&(p=this._getCachedLightmapByIndex(m)),null!=p?(l.lightmapTexture=p,l.useLightmapAsShadowmap=h,e.Utilities.HasOwnProperty(l,"ambientColor")&&(l.ambientColor=BABYLON.Color3.White())):n.push(this._loader.loadTextureInfoAsync(i+"/lightmapTexture",s.lightmapTexture,function(t){t.name="assets/LightmapTexture-".concat(m),t.level=s.lightmapLevel?s.lightmapLevel:1;var n=t;n.onLoadObservable.addOnce(function(){n.isReady()?(n.isRGBD=!0,n.gammaSpace=!1):BABYLON.Tools.Warn("[LM] Failed to register RGBD lightmap (not ready): "+n.name)}),l.lightmapTexture=t,l.useLightmapAsShadowmap=h,m>=0&&null!=a._lightmapMap&&(a._lightmapMap.has(m)||a._lightmapMap.set(m,n)),e.Utilities.HasOwnProperty(l,"ambientColor")&&(l.ambientColor=BABYLON.Color3.White())}))}o instanceof BABYLON.PBRMaterial&&s.detailMapTexture&&(s.detailMapTexture.nonColorData=!0,n.push(this._loader.loadTextureInfoAsync(i+"/detailMapTexture",s.detailMapTexture,function(e){e.name="".concat(o.name," (Detail Map)"),e.level=1;var t=e;t.gammaSpace=!1,o.detailMap.texture=t,o.detailMap.bumpLevel=null!=s.detailBumpLevel?s.detailBumpLevel:1,o.detailMap.diffuseBlendLevel=null!=s.detailBlendLevel?s.detailBlendLevel:.75,o.detailMap.roughnessBlendLevel=null!=s.detailRoughLevel?s.detailRoughLevel:.5,null!=BABYLON.Material.MATERIAL_NORMALBLENDMETHOD_RNM&&(o.detailMap.normalBlendMethod=BABYLON.Material.MATERIAL_NORMALBLENDMETHOD_RNM),o.detailMap.isEnabled=!0})));var f=e.SceneManager.GetRenderQuality(),g=f===e.RenderQuality.High||f===e.RenderQuality.Medium;if(!0===g&&e.Utilities.HasOwnProperty(l,"reflectionColor")&&(l.reflectionColor=null!=s&&s.reflectionColorFactor?BABYLON.Color3.FromArray(s.reflectionColorFactor):BABYLON.Color3.White()),!0===g&&e.Utilities.HasOwnProperty(l,"reflectionTexture")&&s.reflectionCubemapInfo){var v=(this._loader._rootUrl+s.reflectionCubemapInfo.rooturl+s.reflectionCubemapInfo.name).toLowerCase(),y=v.lastIndexOf("."),_=y>-1?v.substring(y).toLowerCase():"",S=null!=s.reflectionCubemapInfo.size?s.reflectionCubemapInfo.size:128,A=null!=s.reflectionProbePower?s.reflectionProbePower:1,b=new e.CubeTextureLoader;b.name="assets/"+s.reflectionCubemapInfo.name,b.size=S,b.mapkey=v,b.material=l,b.extension=_,b.prefiltered=!0,b.reflectionProbePower=A,s.reflectionCubemapInfo.boundingBoxSize&&(b.boundingBoxSize=BABYLON.Vector3.FromArray(s.reflectionCubemapInfo.boundingBoxSize),b.name+=" ("+b.boundingBoxSize.x.toString()+" "+b.boundingBoxSize.y.toString()+" "+b.boundingBoxSize.z.toString()+")",b.mapkey+="_"+b.boundingBoxSize.x.toString()+"_"+b.boundingBoxSize.y.toString()+"_"+b.boundingBoxSize.z.toString()),s.reflectionCubemapInfo.boundingBoxPosition&&(b.boundingBoxPosition=BABYLON.Vector3.FromArray(s.reflectionCubemapInfo.boundingBoxPosition),b.name+=" ("+b.boundingBoxPosition.x.toString()+" "+b.boundingBoxPosition.y.toString()+" "+b.boundingBoxPosition.z.toString()+")",b.mapkey+="_"+b.boundingBoxPosition.x.toString()+"_"+b.boundingBoxPosition.y.toString()+"_"+b.boundingBoxPosition.z.toString());var M=this._reflectionMap[v];null==M?(M=[b],this._reflectionMap[v]=M):M.push(b)}if(e.Utilities.HasOwnProperty(l,"terrainInfo")&&(l.terrainInfo=null!=s.terrainInfo?s.terrainInfo:null),e.Utilities.HasOwnProperty(o,"universalMaterial")){var B=o;if(s.customTextures){var C=function(e){var t=s.customTextures[e];null!=t&&(B.checkSampler(e),n.push(T._loader.loadTextureInfoAsync(i+"/"+e,t,function(t){t.name="".concat(o.name,"detailsSampler"===e||"normalsSampler"===e?" (Atlas)":" (Custom)"),B.setTextureValue(e,t)})))},T=this;for(var x in s.customTextures)C(x)}if(s.customVectors)for(var I in s.customVectors)null!=(P=s.customVectors[I])&&B.addVector4Uniform(I,BABYLON.Vector4.FromArray(P),!0);if(s.customColors)for(var O in s.customColors)null!=(R=s.customColors[O])&&B.addVector4Uniform(O,BABYLON.Vector4.FromArray(R),!0);if(s.customFloats)for(var L in s.customFloats)null!=(E=s.customFloats[L])&&B.addFloatUniform(L,E,!0)}else{if(s.customTextures){var w=function(t){var r=s.customTextures[t];null!=r&&e.Utilities.HasOwnProperty(l,t)&&n.push(N._loader.loadTextureInfoAsync(i+"/"+t,r,function(e){e.name="".concat(o.name,"detailsSampler"===t||"normalsSampler"===t?" (Atlas)":" (Custom)"),l[t]=e}))},N=this;for(var x in s.customTextures)w(x)}if(s.customVectors)for(var I in s.customVectors){var P;null!=(P=s.customVectors[I])&&e.Utilities.HasOwnProperty(l,I)&&(l[I]=BABYLON.Vector4.FromArray(P))}if(s.customColors)for(var O in s.customColors){var R;null!=(R=s.customColors[O])&&e.Utilities.HasOwnProperty(l,O)&&(l[O]instanceof BABYLON.Vector4?l[O]=BABYLON.Vector4.FromArray(R):l[O]instanceof BABYLON.Color4?l[O]=BABYLON.Color4.FromArray(R):l[O]=BABYLON.Color3.FromArray(R))}if(s.customFloats)for(var L in s.customFloats){var E;null!=(E=s.customFloats[L])&&e.Utilities.HasOwnProperty(l,L)&&(l[L]instanceof Boolean?l[L]=E>0:l[L]=E)}}if(o instanceof e.CustomShaderMaterial){var k=null==s.enableGlossyReflections||s.enableGlossyReflections,D=null!=s.specularIntensityScale?s.specularIntensityScale:1,F=null!=s.lightmapTexture?t.IBL_TINY_VALUE:1,U=!0===k?t.IBL_SPEC_FACTOR*D:t.IBL_TINY_VALUE;o.splitLighting(F,U),o.initMaterial()}else o instanceof e.StandardShaderMaterial&&o.initMaterial();null!=s.freezeMaterial&&!0===s.freezeMaterial&&null!=this._shaderList&&this._shaderList.push(o)}},t.prototype._parseUniformAndSamplerProperties=function(t,n,i){var r=null!=n.extras&&null!=n.extras.metadata?n.extras.metadata:null;if(null!=r&&e.Utilities.HasOwnProperty(i,"universalMaterial")){var o=i;if(r.customTextures)for(var a in r.customTextures)null!=r.customTextures[a]&&o.checkSampler(a);if(r.customVectors)for(var s in r.customVectors){var l=r.customVectors[s];null!=l&&o.checkUniform(s,"vec4",BABYLON.Vector4.FromArray(l))}if(r.customColors)for(var u in r.customColors){var c=r.customColors[u];null!=c&&o.checkUniform(u,"vec4",BABYLON.Vector4.FromArray(c))}if(r.customFloats)for(var d in r.customFloats){var h=r.customFloats[d];null!=h&&o.checkUniform(d,"float",h)}}},t.IBL_TINY_VALUE=.001,t.IBL_SPEC_FACTOR=1,t.IBL_PROBE_FACTOR=1,t.ScriptBundleCache={},t}();e.CVTOOLS_unity_metadata=n;var i=function(){function t(t){this.name=e.SceneManager.CVTOOLS_MESH,this.enabled=!1,this._loader=t,this.enabled=this._loader.isExtensionUsed(e.SceneManager.CVTOOLS_MESH),this.order=101}return t.prototype.dispose=function(){delete this._loader},t}();e.CVTOOLS_babylon_mesh=i;var r=function(){function t(t){this.name=e.SceneManager.CVTOOLS_HAND,this.enabled=!1,this._loader=t,this.enabled=this._loader.isExtensionUsed(e.SceneManager.CVTOOLS_HAND),this.order=102}return t.prototype.dispose=function(){delete this._loader},t}();e.CVTOOLS_left_handed=r}(i||(i={})),function(e){var t=function(t){function n(n,i){var r=t.call(this,n,i)||this;return r.universalMaterial=!0,r._defines={},r._uniforms=[],r._samplers=[],r._attributes=[],r._textures={},r._vectors4={},r._vectors3={},r._vectors2={},r._floats={},r._bools={},r._ubos=null,r._wgslSamplers=null,r._noMatrixTextures=null,r.shader=null,r.plugin=null,r._unityLightingPlugin=null,r.shader="CustomShaderMaterial",r.addFloatUniform("tkIblDiffuseScale",1),r.addFloatUniform("tkIblSpecularScale",1),r._unityLightingPlugin=new e.UnityStyleLightingPlugin(r,r.shader),r}return r(n,t),n.prototype.getPlugin=function(){return this.plugin},n.prototype.getClassName=function(){return"PBRMaterial"},n.prototype.initMaterial=function(){this.awake&&this.awake()},n.prototype.addAttribute=function(e){-1===this._attributes.indexOf(e)&&this._attributes.push(e)},n.prototype.checkUniform=function(e,t,n){void 0===n&&(n=null),-1===this._uniforms.indexOf(e)&&(this._uniforms.push(e),this._defines[e.toUpperCase()]=!0,this.buildUniformProperty(e,t,n))},n.prototype.checkSampler=function(e,t){void 0===t&&(t=null),-1===this._samplers.indexOf(e)&&(this._samplers.push(e),this._defines[e.toUpperCase()]=!0,this.buildUniformProperty(e,"sampler2D",t),this.checkUniform(e+"Infos","vec2",BABYLON.Vector2.Zero()),this.checkUniform(e+"Matrix","mat4",BABYLON.Matrix.Identity()))},n.prototype.splitLighting=function(e,t){var n,i;this.setFloatValue("tkIblDiffuseScale",e),this.setFloatValue("tkIblSpecularScale",t),this.markAsDirty(BABYLON.Constants.MATERIAL_AllDirtyFlag),null===(n=this.plugin)||void 0===n||n.markAllDefinesAsDirty(),null===(i=this._unityLightingPlugin)||void 0===i||i.markAllDefinesAsDirty()},n.prototype.addTextureUniform=function(e,t){return this.checkSampler(e,t),this._textures[e]=t,this},n.prototype.setTextureValue=function(e,t){return this._textures[e]=t,this},n.prototype.markTextureAsRaw=function(e){this._noMatrixTextures||(this._noMatrixTextures=new Set),this._noMatrixTextures.add(e)},n.prototype.getTextureValue=function(e){return this._textures[e]},n.prototype.addVector4Uniform=function(e,t){return this.checkUniform(e,"vec4",t),this._vectors4[e]=t,this},n.prototype.setVector4Value=function(e,t){return this._vectors4[e]=t,this},n.prototype.getVector4Value=function(e){return this._vectors4[e]},n.prototype.addVector3Uniform=function(e,t){return this.checkUniform(e,"vec3",t),this._vectors3[e]=t,this},n.prototype.setVector3Value=function(e,t){return this._vectors3[e]=t,this},n.prototype.getVector3Value=function(e){return this._vectors3[e]},n.prototype.addVector2Uniform=function(e,t){return this.checkUniform(e,"vec2",t),this._vectors2[e]=t,this},n.prototype.setVector2Value=function(e,t){return this._vectors2[e]=t,this},n.prototype.getVector2Value=function(e){return this._vectors2[e]},n.prototype.addFloatUniform=function(e,t){return this.checkUniform(e,"float",t),this._floats[e]=t,this},n.prototype.setFloatValue=function(e,t){return this._floats[e]=t,this},n.prototype.getFloatValue=function(e){return this._floats[e]},n.prototype.addBoolUniform=function(e,t){return this.checkUniform(e,"bool",t),this._bools[e]=t,this},n.prototype.setBoolValue=function(e,t){return this._bools[e]=t,this},n.prototype.getBoolValue=function(e){return this._bools[e]},n.prototype.getAnimatables=function(){var e=t.prototype.getAnimatables.call(this);for(var n in this._textures){var i=this._textures[n];i&&i.animations&&i.animations.length>0&&e.push(i)}return e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);for(var n in this._textures){var i=this._textures[n];i&&e.push(i)}return e},n.prototype.hasTexture=function(e){if(t.prototype.hasTexture.call(this,e))return!0;for(var n in this._textures)if(this._textures[n]===e)return!0;return!1},n.prototype.getCustomUniforms=function(e){var t={};return null!=this._ubos&&this._ubos.length>0&&(t.ubo=this._ubos.filter(function(e){return"sampler2D"!==e.type})),!1===e&&(t.fragment=this.getCustomFragmentCode(!1)),t},n.prototype.getCustomSamplers=function(){return this._samplers},n.prototype.getCustomAttributes=function(){return this._attributes},n.prototype.getCustomVertexCode=function(e){return null},n.prototype.getCustomFragmentCode=function(e){var t=this,n=null;return null!=this._ubos&&this._ubos.length>0&&(n="#ifdef "+this.shader.toUpperCase()+"\n",this._ubos.forEach(function(i){if(!0===e)"sampler2D"===i.type&&(null==t._wgslSamplers&&(t._wgslSamplers=new Set),t._wgslSamplers.has(i.name)||(n+="\tvar "+i.name+": texture_2d<f32>;\n",n+="\tvar "+i.name+"Sampler: sampler;\n",t._wgslSamplers.add(i.name)));else{var r=i.name.toUpperCase()+"_DEFINED";"float"===i.type||"bool"===i.type||"int"===i.type?(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform float "+i.name+";\n",n+="\t#endif\n"):"vec2"===i.type?(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform vec2 "+i.name+";\n",n+="\t#endif\n"):"vec3"===i.type?(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform vec3 "+i.name+";\n",n+="\t#endif\n"):"vec4"===i.type?(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform vec4 "+i.name+";\n",n+="\t#endif\n"):"mat4"===i.type?(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform mat4 "+i.name+";\n",n+="\t#endif\n"):"sampler2D"===i.type&&(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform sampler2D "+i.name+";\n",n+="\t#endif\n")}}),n+="#endif\n"),n},n.prototype.prepareCustomDefines=function(e){if(this._wgslSamplers&&this._wgslSamplers.clear(),e[this.shader.toUpperCase()]=!0,null!=this._defines){var t=Object.keys(this._defines);if(null!=t&&t.length>0)for(var n=0,i=t;n<i.length;n++){var r=i[n];e[r]=this._defines[r]}}e.isDirty&&e.rebuild()},n.prototype.updateCustomBindings=function(e){var t,n=this.getScene();this.update&&this.update();var i=null!=e&&"function"==typeof e.getUniformNames,r=i?e.getUniformNames():[],o=function(e){return i&&-1!==r.indexOf(e)};if(n.texturesEnabled)for(t in this._textures){var a=this._textures[t];null!=a&&a.isReady&&a.isReady()&&(null==a.isChecked&&(a.isChecked=!0,("detailsSampler"===t||"normalsSampler"===t||t.indexOf("(Atlas)")>=0)&&a.updateSamplingMode(8)),e.setTexture&&e.setTexture(t,a),this._noMatrixTextures&&this._noMatrixTextures.has(t)||(o(t+"Infos")&&e.updateFloat2?e.updateFloat2(t+"Infos",a.coordinatesIndex,a.level):e.setFloat2?e.setFloat2(t+"Infos",a.coordinatesIndex,a.level):e.setFloat&&e.setFloat(t+"Infos",a.coordinatesIndex),o(t+"Matrix")&&e.updateMatrix?e.updateMatrix(t+"Matrix",a.getTextureMatrix()):e.setMatrix&&e.setMatrix(t+"Matrix",a.getTextureMatrix())))}for(t in this._vectors4){var s=this._vectors4[t];o(t)&&e.updateVector4?e.updateVector4(t,s):e.setVector4?e.setVector4(t,s):e.setFloat4&&e.setFloat4(t,s.x,s.y,s.z,s.w)}for(t in this._vectors3)s=this._vectors3[t],o(t)&&e.updateVector3?e.updateVector3(t,s):e.setVector3?e.setVector3(t,s):e.setFloat3&&e.setFloat3(t,s.x,s.y,s.z);for(t in this._vectors2)s=this._vectors2[t],o(t)&&e.updateFloat2?e.updateFloat2(t,s.x,s.y):e.setFloat2?e.setFloat2(t,s.x,s.y):e.setFloat&&e.setFloat(t,s.x);for(t in this._floats){var l=this._floats[t];o(t)&&e.updateFloat?e.updateFloat(t,l):e.setFloat&&e.setFloat(t,l)}for(t in this._bools)l=this._bools[t]?1:0,o(t)&&e.updateFloat?e.updateFloat(t,l):e.setFloat&&e.setFloat(t,l)},n.prototype.legacyUpdateCustomBindings=function(e){var t,n=this.getScene();if(this.update&&this.update(),n.texturesEnabled)for(t in this._textures){var i=this._textures[t];null!=i&&i.isReady&&i.isReady()&&(null==i.isChecked&&(i.isChecked=!0,("detailsSampler"===t||"normalsSampler"===t||t.indexOf("(Atlas)")>=0)&&i.updateSamplingMode(8)),e.setTexture(t,i),e.updateFloat2(t+"Infos",i.coordinatesIndex,i.level),e.updateMatrix(t+"Matrix",i.getTextureMatrix()))}for(t in this._vectors4)e.updateVector4(t,this._vectors4[t]);for(t in this._vectors3)e.updateVector3(t,this._vectors3[t]);for(t in this._vectors2)e.updateFloat2(t,this._vectors2[t].x,this._vectors2[t].y);for(t in this._floats)e.updateFloat(t,this._floats[t]);for(t in this._bools)e.updateFloat(t,this._bools[t]?1:0);e.update()},n.prototype.buildUniformProperty=function(e,t,n){var i=1;switch(t){case"float":case"bool":case"int":i=1;break;case"vec2":i=2;break;case"vec3":i=3;break;case"vec4":i=4;break;case"mat4":i=16}null==this._ubos&&(this._ubos=[]),this._ubos.push({name:e,size:i,type:t})},n}(BABYLON.PBRMaterial);e.CustomShaderMaterial=t;var n=function(e){function t(t,n,i,r,o,a,s){void 0===o&&(o=!0),void 0===a&&(a=!0),void 0===s&&(s=!1);var l=e.call(this,t,n,i,r,o,a,s)||this;return l._isEnabled=!1,l.vertexDefinitions=null,l.fragmentDefinitions=null,l.setIsEnabled(a),l}return r(t,e),t.prototype.getClassName=function(){return"MaterialPluginBase"},t.prototype.getIsEnabled=function(){return this._isEnabled},t.prototype.setIsEnabled=function(e){this._isEnabled=e,this._material.markAsDirty(BABYLON.Constants.MATERIAL_AllDirtyFlag),this.markAllDefinesAsDirty(),this._enable(this._isEnabled)},t.prototype.getCustomShaderMaterial=function(){return this._material},t}(BABYLON.MaterialPluginBase);e.CustomShaderMaterialPlugin=n;var i=function(e){function t(t,n){return e.call(this,t,n,10,{UNITYSTYLELIGHTINGPLUGIN:!1},!0,!0,!1)||this}return r(t,e),t.prototype.isCompatible=function(e){return e===BABYLON.ShaderLanguage.WGSL||e===BABYLON.ShaderLanguage.GLSL},t.prototype.getClassName=function(){return"UnityStyleLightingPlugin"},t.prototype.getCustomCode=function(e,t){var n=t===BABYLON.ShaderLanguage.WGSL;if("fragment"===e){var i=n?"\n // Unity-Style IBL split scaling (WGSL)\n #if defined(REFLECTION) && defined(UNITYSTYLELIGHTINGPLUGIN) && !defined(UNLIT)\n finalIrradiance = finalIrradiance * uniforms.tkIblDiffuseScale;\n finalRadiance = finalRadiance * uniforms.tkIblSpecularScale;\n finalRadianceScaled = finalRadianceScaled * uniforms.tkIblSpecularScale;\n #endif\n ":"\n // Unity-Style IBL split scaling (GLSL)\n #if defined(REFLECTION) && defined(UNITYSTYLELIGHTINGPLUGIN) && !defined(UNLIT)\n finalIrradiance = finalIrradiance * tkIblDiffuseScale;\n finalRadiance = finalRadiance * tkIblSpecularScale;\n finalRadianceScaled = finalRadianceScaled * tkIblSpecularScale;\n #endif\n ";return{CUSTOM_FRAGMENT_DEFINITIONS:this.fragmentDefinitions,CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:i}}return null},t.prototype.getUniforms=function(e){var t=e===BABYLON.ShaderLanguage.WGSL;return this.vertexDefinitions=this.getCustomShaderMaterial().getCustomVertexCode(t),this.fragmentDefinitions=!0===t?this.getCustomShaderMaterial().getCustomFragmentCode(t):null,this.getCustomShaderMaterial().getCustomUniforms(t)},t.prototype.prepareDefines=function(e,t,n){this.getIsEnabled()&&(e.UNITYSTYLELIGHTINGPLUGIN=!0,this.getCustomShaderMaterial().prepareCustomDefines(e))},t.prototype.bindForSubMesh=function(e,t,n,i){this.getIsEnabled()&&this.getCustomShaderMaterial().updateCustomBindings(e)},t}(e.CustomShaderMaterialPlugin);e.UnityStyleLightingPlugin=i;var o=function(e){function t(t,n){var i=e.call(this,t,n)||this;return i.shader=i.getShaderName(),i}return r(t,e),t.prototype.getShaderName=function(){return"UniversalShaderMaterial"},t}(e.CustomShaderMaterial);e.UniversalShaderMaterial=o,e.SceneManager.RegisterClass("TOOLKIT.CustomShaderMaterial",t),e.SceneManager.RegisterClass("TOOLKIT.UniversalShaderMaterial",o),e.SceneManager.RegisterClass("TOOLKIT.UnityStyleLightingPlugin",i),e.SceneManager.RegisterClass("TOOLKIT.CustomShaderMaterialPlugin",n)}(i||(i={})),function(e){var t=function(){function t(e){this._babylonScene=e,this._physicList=[],this._shadowList=[],this._scriptList=[],this._freezeList=[]}return t.prototype.parseSceneComponents=function(t){e.MetadataParser.DoParseSceneComponents(this._babylonScene,t,this._physicList,this._shadowList,this._scriptList,this._freezeList)},t.prototype.postProcessSceneComponents=function(t,n){e.MetadataParser.DoProcessPendingPhysics(this._babylonScene,this._physicList),e.MetadataParser.DoProcessPendingShadows(this._babylonScene,this._shadowList),e.MetadataParser.DoProcessPendingScripts(this._babylonScene,this._scriptList,t,n),e.MetadataParser.DoProcessPendingFreezes(this._freezeList),this._babylonScene=null,this._physicList=null,this._shadowList=null,this._scriptList=null,this._freezeList=null},t.DoParseSceneComponents=function(t,n,i,r,o,a){if(null!=n&&null!=n.metadata&&null!=n.metadata.toolkit&&null!=n.metadata.toolkit.parsed&&!1===n.metadata.toolkit.parsed){n.onDisposeObservable.addOnce(function(){e.Utilities.DisposeEntity(n)}),n.metadata.toolkit.parsed=!0,n.metadata.toolkit.prefab=!1;var s=n.metadata.toolkit,l=null==n.metadata.toolkit.visible||n.metadata.toolkit.visible,u=null!=n.metadata.toolkit.visibility?n.metadata.toolkit.visibility:1,c=null!=n.metadata.toolkit.billboard?n.metadata.toolkit.billboard:0,d=n instanceof BABYLON.AbstractMesh,h=(null!=n.metadata.toolkit.lightmapped&&n.metadata.toolkit.lightmapped,s.tags);if(null!=h&&""!==h&&(BABYLON.Tags.AddTagsTo(n,h),h.indexOf("NavigationMesh")>=0&&(n.isVisible=!1,n.isPickable=!1,n.useVertexColors=!1)),null!=s.physics&&null!=i&&i.push(n),null!=s.renderer)if(!0===d)n.isPickable=!0,n.useVertexColors=!1,n.isVisible=l,n.visibility=u,n.billboardMode=c,n.cullingStrategy=BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD,null!=s.renderer.cullingstrategy&&s.renderer.cullingstrategy!==BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD&&(n.cullingStrategy=s.renderer.cullingstrategy),null!=s.renderer.castshadows&&!0===s.renderer.castshadows&&null!=r&&r.push(n),null!=s.renderer.receiveshadows&&!0===s.renderer.receiveshadows&&(n.receiveShadows=!0),null!=s.renderer.checkcollisions&&!0===s.renderer.checkcollisions&&(n.checkCollisions=!0),null!=s.renderer.istriggervolume&&!0===s.renderer.istriggervolume&&(n.collisionResponse=!1),null!=s.renderer.usevertexcolors&&(n.useVertexColors=s.renderer.usevertexcolors),null!=s.renderer.setmeshpickable&&(n.isPickable=s.renderer.setmeshpickable),null!=s.renderer.showboundingbox&&(n.showBoundingBox=s.renderer.showboundingbox),null!=s.renderer.defaultellipsoid&&(n.ellipsoid=e.Utilities.ParseVector3(s.renderer.defaultellipsoid)),null!=s.renderer.ellipsoidoffset&&(n.ellipsoidOffset=e.Utilities.ParseVector3(s.renderer.ellipsoidoffset)),null!=s.renderer.rendergroupid&&(n.renderingGroupId=s.renderer.rendergroupid),null!=s.renderer.freezeworldmatrix&&!0===s.renderer.freezeworldmatrix&&null!=a&&a.push(n),null!=s.renderer.snapshotrendering&&s.renderer.snapshotrendering>0&&(e.Utilities.PrepareSkeletonForRendering(n.skeleton),n.alwaysSelectAsActiveMesh=!0);else{var p=e.SceneManager.GetSkinnedMesh(n);if(null!=p)p.isPickable=!0,p.useVertexColors=!1,p.isVisible=l,p.visibility=u,p.billboardMode=c,p.cullingStrategy=BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD,p.alwaysSelectAsActiveMesh=!0,null!=s.renderer.cullingstrategy&&s.renderer.cullingstrategy!==BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD&&(p.cullingStrategy=s.renderer.cullingstrategy),null!=s.renderer.castshadows&&!0===s.renderer.castshadows&&null!=r&&r.push(p),null!=s.renderer.receiveshadows&&!0===s.renderer.receiveshadows&&(p.receiveShadows=!0),null!=s.renderer.checkcollisions&&!0===s.renderer.checkcollisions&&(p.checkCollisions=!0),null!=s.renderer.istriggervolume&&!0===s.renderer.istriggervolume&&(p.collisionResponse=!1),null!=s.renderer.usevertexcolors&&(p.useVertexColors=s.renderer.usevertexcolors),null!=s.renderer.setmeshpickable&&(p.isPickable=s.renderer.setmeshpickable),null!=s.renderer.showboundingbox&&(p.showBoundingBox=s.renderer.showboundingbox),null!=s.renderer.defaultellipsoid&&(p.ellipsoid=e.Utilities.ParseVector3(s.renderer.defaultellipsoid)),null!=s.renderer.ellipsoidoffset&&(p.ellipsoidOffset=e.Utilities.ParseVector3(s.renderer.ellipsoidoffset)),null!=s.renderer.rendergroupid&&(p.renderingGroupId=s.renderer.rendergroupid),null!=s.renderer.freezeworldmatrix&&!0===s.renderer.freezeworldmatrix&&null!=a&&a.push(p),null!=s.renderer.snapshotrendering&&s.renderer.snapshotrendering>0&&e.Utilities.PrepareSkeletonForRendering(p.skeleton);else{var m=e.SceneManager.GetPrimitiveMeshes(n);null!=m&&m.length>0&&m.forEach(function(t){var n=e.SceneManager.GetSkinnedMesh(t);null!=n?(n.isPickable=!0,n.useVertexColors=!1,n.isVisible=l,n.visibility=u,n.billboardMode=c,n.cullingStrategy=BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD,n.alwaysSelectAsActiveMesh=!0,null!=s.renderer.cullingstrategy&&s.renderer.cullingstrategy!==BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD&&(n.cullingStrategy=s.renderer.cullingstrategy),null!=s.renderer.castshadows&&!0===s.renderer.castshadows&&null!=r&&r.push(n),null!=s.renderer.receiveshadows&&!0===s.renderer.receiveshadows&&(n.receiveShadows=!0),null!=s.renderer.checkcollisions&&!0===s.renderer.checkcollisions&&(n.checkCollisions=!0),null!=s.renderer.istriggervolume&&!0===s.renderer.istriggervolume&&(n.collisionResponse=!1),null!=s.renderer.usevertexcolors&&(n.useVertexColors=s.renderer.usevertexcolors),null!=s.renderer.setmeshpickable&&(n.isPickable=s.renderer.setmeshpickable),null!=s.renderer.showboundingbox&&(n.showBoundingBox=s.renderer.showboundingbox),null!=s.renderer.defaultellipsoid&&(n.ellipsoid=e.Utilities.ParseVector3(s.renderer.defaultellipsoid)),null!=s.renderer.ellipsoidoffset&&(n.ellipsoidOffset=e.Utilities.ParseVector3(s.renderer.ellipsoidoffset)),null!=s.renderer.rendergroupid&&(n.renderingGroupId=s.renderer.rendergroupid),null!=s.renderer.freezeworldmatrix&&!0===s.renderer.freezeworldmatrix&&null!=a&&a.push(n),null!=s.renderer.snapshotrendering&&s.renderer.snapshotrendering>0&&e.Utilities.PrepareSkeletonForRendering(n.skeleton)):(t.isPickable=!0,t.useVertexColors=!1,t.isVisible=l,t.visibility=u,t.billboardMode=c,t.cullingStrategy=BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD,null!=s.renderer.cullingstrategy&&s.renderer.cullingstrategy!==BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD&&(t.cullingStrategy=s.renderer.cullingstrategy),null!=s.renderer.castshadows&&!0===s.renderer.castshadows&&null!=r&&r.push(t),null!=s.renderer.receiveshadows&&!0===s.renderer.receiveshadows&&(t.receiveShadows=!0),null!=s.renderer.checkcollisions&&!0===s.renderer.checkcollisions&&(t.checkCollisions=!0),null!=s.renderer.istriggervolume&&!0===s.renderer.istriggervolume&&(t.collisionResponse=!1),null!=s.renderer.usevertexcolors&&(t.useVertexColors=s.renderer.usevertexcolors),null!=s.renderer.setmeshpickable&&(t.isPickable=s.renderer.setmeshpickable),null!=s.renderer.showboundingbox&&(t.showBoundingBox=s.renderer.showboundingbox),null!=s.renderer.defaultellipsoid&&(t.ellipsoid=e.Utilities.ParseVector3(s.renderer.defaultellipsoid)),null!=s.renderer.ellipsoidoffset&&(t.ellipsoidOffset=e.Utilities.ParseVector3(s.renderer.ellipsoidoffset)),null!=s.renderer.rendergroupid&&(t.renderingGroupId=s.renderer.rendergroupid),null!=s.renderer.freezeworldmatrix&&!0===s.renderer.freezeworldmatrix&&null!=a&&a.push(t),null!=s.renderer.snapshotrendering&&s.renderer.snapshotrendering>0&&(e.Utilities.PrepareSkeletonForRendering(t.skeleton),t.alwaysSelectAsActiveMesh=!0))})}}if(null!=s.components){var f=s.components;null!=f&&f.length>0&&f.forEach(function(i){if(null!=i)switch(i.alias){case"camera":e.MetadataParser.SetupCameraComponent(t,n,i);break;case"light":e.MetadataParser.SetupLightComponent(t,n,i);break;case"script":null!=o&&o.push({mesh:n,comp:i})}})}}},t.DoProcessPendingScripts=function(t,n,i,r){null!=n&&n.length>0&&(n.sort(function(e,t){return e.comp.order<t.comp.order?-1:e.comp.order>t.comp.order?1:0}),n.forEach(function(n){if(null!=n.comp.klass&&""!==n.comp.klass){if(!0===e.SceneManager.AutoStripNamespacePrefix&&!1===e.SceneManager.UniversalModuleDefinition){var o=n.comp.klass.lastIndexOf(".");-1!==o&&(n.comp.klass=n.comp.klass.substring(o+1))}if("TOOLKIT.ScriptComponent"!==n.comp.klass){var a=n.comp.klass;null==n.comp.properties&&(n.comp.properties={}),n.comp.properties._scriptComponentAlias=a,n.comp.properties._registerComponentAlias=!1;var s=e.Utilities.InstantiateClass(a);if(null!=s){var l=new s(n.mesh,t,n.comp.properties);null!=l?(n.comp.instance=l,null!=r&&r.push(n.comp.instance),n.comp.instance.addPreloaderTasks&&null!=i&&i.push(n.comp.instance),e.SceneManager.AttachScriptComponent(n.comp.instance,a,!1)):BABYLON.Tools.Warn("Failed to instantiate script class: "+a)}else BABYLON.Tools.Warn("Failed to locate script class: "+a)}}}))},t.DoProcessPendingShadows=function(e,t){null!=t&&t.length>0&&null!=e.lights&&e.lights.length>0&&e.lights.forEach(function(e){var n=e.getShadowGenerator();null!=n&&null!=e.metadata&&null!=e.metadata.toolkit&&!0===e.metadata.toolkit.autorender&&t.forEach(function(t){!0==(!(null!=e.includedOnlyMeshes&&e.includedOnlyMeshes.length>0)||e.includedOnlyMeshes.indexOf(t)>=0)&&n.addShadowCaster(t,!1)})})},t.DoProcessPendingPhysics=function(t,n){if(null!=n&&n.length>0){var i=t.isPhysicsEnabled(),r=!0===i?t.getPhysicsEngine():null;!0==(!0===i&&null!=r)?n.forEach(function(n){e.RigidbodyPhysics.SetupPhysicsComponent(t,n)}):BABYLON.Tools.Warn("Physics engine not loaded. Physics impostors will not be created.")}},t.DoProcessPendingFreezes=function(e){null!=e&&e.length>0&&e.forEach(function(e){e.freezeWorldMatrix()})},t.SetupCameraComponent=function(t,n,i){n.checkCollisions=!1;var r=0,o=n.name+".Rig",a=null!=i.culling?i.culling:-1,s=null!=i.camerabase?i.camerabase:0,l=(null!=i.clearflags&&i.clearflags,null!=i.renderlist?i.renderlist:null),u=null!=i.maincamera&&i.maincamera,c=4===s?new BABYLON.FreeCamera(o,BABYLON.Vector3.Zero(),t):new BABYLON.UniversalCamera(o,BABYLON.Vector3.Zero(),t);switch(c.layerMask=~e.SceneManager.HiddenLayerMask,c.checkCollisions=!1,c.rotationQuaternion=BABYLON.Quaternion.FromEulerAngles(0,0,0),c.parent=n,!0===u&&(t.activeCamera=c),null!=i.type?i.type:0){case 0:c.mode=BABYLON.Camera.PERSPECTIVE_CAMERA,null!=i.perspectiveyfov&&(c.fov=i.perspectiveyfov),null!=i.perspectiveznear&&(c.minZ=i.perspectiveznear),null!=i.perspectivezfar&&(c.maxZ=i.perspectivezfar);break;case 1:c.mode=BABYLON.Camera.ORTHOGRAPHIC_CAMERA,null!=i.orthoxmag&&(c.orthoLeft=-i.orthoxmag,c.orthoRight=i.orthoxmag),null!=i.orthoymag&&(c.orthoBottom=-i.orthoymag,c.orthoTop=i.orthoymag),null!=i.orthoznear&&(c.minZ=i.orthoznear),null!=i.orthozfar&&(c.maxZ=i.orthozfar)}if(-1===a);else if(0===a);else{var d=l;if(null!=d&&d.length>0){var h=function(){var n=d[r],i=e.SceneManager.GetMeshByID(t,n);if(null!=i){var o=i.name+".Detail",a=i.getChildren(function(e){return e.name===o},!0);null!=a&&a.length}};for(r=0;r<d.length;r++)h()}}n.cameraRig=c},t.SetupLightComponent=function(t,n,i){n.checkCollisions=!1;var r,o=n.name+".Rig",a=0,s=BABYLON.Light.INTENSITYMODE_AUTOMATIC,l=1,u=null!=i.culling?i.culling:-1,c=(null!=i.clearflags&&i.clearflags,null!=i.renderlist?i.renderlist:null),d=null!=i.type?i.type:0,h=e.SceneManager.GetRenderQuality(),p=null!=i.exponentdecayspeed?i.exponentdecayspeed:1,m=!1;switch(d){case 0:var f=BABYLON.Vector3.Forward(),g=null!=i.orthoscale?i.orthoscale:.1,v=null!=i.ortholeft?i.ortholeft:Number.MAX_VALUE,y=null!=i.orthoright?i.orthoright:Number.MAX_VALUE,_=null!=i.orthotop?i.orthotop:Number.MAX_VALUE,S=null!=i.orthobottom?i.orthobottom:Number.MAX_VALUE,A=null!=i.calczbounds&&i.calczbounds,b=null!=i.updateextends&&i.updateextends,M=null!=i.shadowfrustumsize?i.shadowfrustumsize:0,B=new BABYLON.DirectionalLight(o,f,t);B.shadowFrustumSize=M,B.shadowOrthoScale=g,B.autoCalcShadowZBounds=A,B.autoUpdateExtends=b,B.orthoLeft=v,B.orthoRight=y,B.orthoTop=_,B.orthoBottom=S,(r=B).falloffType=BABYLON.Light.FALLOFF_STANDARD,m=h===e.RenderQuality.High||h===e.RenderQuality.Medium,s=BABYLON.Light.INTENSITYMODE_ILLUMINANCE,l=e.SceneManager.DirectionalLightIntensity;break;case 1:var C=r=new BABYLON.PointLight(o,BABYLON.Vector3.Zero(),t);(r=C).falloffType=BABYLON.Light.FALLOFF_STANDARD,m=h===e.RenderQuality.High||h===e.RenderQuality.Medium,s=BABYLON.Light.INTENSITYMODE_LUMINOUSPOWER,l=e.SceneManager.PointLightIntensity;break;case 2:f=BABYLON.Vector3.Forward();var T=null!=i.spotangle?i.spotangle:Math.PI/4,x=new BABYLON.SpotLight(o,BABYLON.Vector3.Zero(),f,0,p,t);x.angle=.966*BABYLON.Tools.ToRadians(T),x.innerAngle=.8*x.angle,(r=x).falloffType=BABYLON.Light.FALLOFF_GLTF,m=h===e.RenderQuality.High||h===e.RenderQuality.Medium,s=BABYLON.Light.INTENSITYMODE_LUMINOUSPOWER,l=e.SceneManager.SpotLightIntensity}if(null!=r){var I=null!=i.range?i.range:Number.MAX_VALUE,O=null!=i.color?e.Utilities.ParseColor3(i.color,BABYLON.Color3.White()):BABYLON.Color3.White(),L=null!=i.specular?e.Utilities.ParseColor3(i.specular,BABYLON.Color3.White()):BABYLON.Color3.White(),w=null!=i.lightmapmode?i.lightmapmode:0;switch(null!=i.lightmaptype&&i.lightmaptype,r.parent=n,r.range=I,r.diffuse=O,r.specular=L,r.intensity=(null!=i.intensity?i.intensity:1)*l,w){case 2:r.lightmapMode=BABYLON.Light.LIGHTMAP_SHADOWSONLY;break;case 1:r.lightmapMode=BABYLON.Light.LIGHTMAP_SPECULAR;break;default:r.lightmapMode=BABYLON.Light.LIGHTMAP_DEFAULT}r.intensityMode=s,r.shadowEnabled=!1;var N=null==i.autorender||i.autorender,P=null!=i.softshadows&&i.softshadows,R=null!=i.numcascades?i.numcascades:0,E=null!=i.cascadelambda?i.cascadelambda:1,k=null!=i.setdepthclamp&&i.setdepthclamp,D=null!=i.blendpertecntage?i.blendpertecntage:1e-8,F=null!=i.boundsrefreshrate?i.boundsrefreshrate:1,U=null!=i.lightcontactratio?i.lightcontactratio:.1,Y=null!=i.stabilizecascades&&i.stabilizecascades,V=null!=i.penumbradarkness?i.penumbradarkness:1,G=null!=i.softshadowsfilter?i.softshadowsfilter:99,z=null!=i.freezeshadows&&i.freezeshadows,W=null!=i.calcdepths&&i.calcdepths,H=null!=i.depthscaling?i.depthscaling:50,X=null!=i.blurscaling?i.blurscaling:2,K=null==i.kernelblur||i.kernelblur,Q=null!=i.blurkernelsize?i.blurkernelsize:1,j=null!=i.blurboxoffset?i.blurboxoffset:1,Z=null!=i.shadowmapsize?i.shadowmapsize:1024,q=null!=i.generateshadows&&i.generateshadows,J=null!=i.shadowbiasfactor?i.shadowbiasfactor:.01,$=null!=i.normalbiasfactor?i.normalbiasfactor:.01,ee=null!=i.shadowmapbias?i.shadowmapbias:.05,te=null!=i.normalmapbias?i.normalmapbias:.4,ne=null!=i.shadowstrength?i.shadowstrength:1,ie=null!=i.shadowdistance?i.shadowdistance:150,re=null!=i.shadownearplane?i.shadownearplane:.2,oe=null!=i.shadowfilterquality?i.shadowfilterquality:"Medium",ae=null!=i.transparencyshadow&&i.transparencyshadow,se=null!=i.softtransparency&&i.softtransparency,le=null==i.forcebackfacesonly||i.forcebackfacesonly,ue=null!=i.frustumedgefalloff?i.frustumedgefalloff:0,ce=null!=i.usefullfloatfirst&&i.usefullfloatfirst;if(!0===m&&!0===q){var de=r,he=e.SceneManager.GetEngine(t),pe=he instanceof BABYLON.Engine?he.webGLVersion:0,me=he instanceof BABYLON.WebGPUEngine?1:0,fe=0===d&&R>=2&&(pe>=2||me>=1),ge=!0===fe?new BABYLON.CascadedShadowGenerator(Z,r,ce):new BABYLON.ShadowGenerator(Z,de,ce);if(ge.bias=ee*J,ge.normalBias=te*$,ge.depthScale=H,ge.useKernelBlur=K,ge.blurKernel=Q,ge.blurScale=X,ge.blurBoxOffset=j,ge.frustumEdgeFalloff=ue,ge.forceBackFacesOnly=le,ge.transparencyShadow=ae,ge.enableSoftTransparentShadow=se,ge.contactHardeningLightSizeUVRatio=U,!0===P)if(pe<=1&&me<=0)ge.usePoissonSampling=!0;else if(!0===fe)ge.usePercentageCloserFiltering=!0;else switch(G){case 0:default:ge.usePoissonSampling=!0;break;case 1:ge.useExponentialShadowMap=!0;break;case 2:ge.useBlurExponentialShadowMap=!0;break;case 3:ge.useCloseExponentialShadowMap=!0;break;case 4:ge.useBlurCloseExponentialShadowMap=!0;break;case 5:ge.useContactHardeningShadow=!0;break;case 99:ge.usePercentageCloserFiltering=!0}switch(oe){case"High":ge.filteringQuality=BABYLON.ShadowGenerator.QUALITY_HIGH;break;case"Medium":ge.filteringQuality=BABYLON.ShadowGenerator.QUALITY_MEDIUM;break;case"Low":ge.filteringQuality=BABYLON.ShadowGenerator.QUALITY_LOW}if(!0===fe){var ve=ge;ve.lambda=E,ve.depthClamp=k,ve.shadowMaxZ=ie,ve.numCascades=R,ve.penumbraDarkness=V,ve.autoCalcDepthBounds=W,ve.stabilizeCascades=Y,ve.cascadeBlendPercentage=D,ve.autoCalcDepthBoundsRefreshRate=F,ve.freezeShadowCastersBoundingInfo=z,ve.setDarkness(1-BABYLON.Scalar.Clamp(ne)),de.shadowEnabled=!0,ve.splitFrustum()}else ge.setDarkness(1-BABYLON.Scalar.Clamp(ne)),de.shadowEnabled=!0,de.shadowMinZ=re,de.shadowMaxZ=ie;null==r.metadata&&(r.metadata={}),null==r.metadata.toolkit&&(r.metadata.toolkit={}),r.metadata.toolkit.autorender=N}var ye=n.name+".Holder";if(-1===u)r.includedOnlyMeshes=[];else if(0===u)r.includedOnlyMeshes=[new BABYLON.Mesh(ye,t)];else{r.includedOnlyMeshes=[new BABYLON.Mesh(ye,t)];var _e=c;if(null!=_e&&_e.length>0){var Se=function(){var n=_e[a],i=e.SceneManager.GetMeshByID(t,n);if(null!=i){var o=i.name+".Detail",s=i.getChildren(function(e){return e.name===o},!0);null!=s&&s.length>0?r.includedOnlyMeshes.push(s[0]):r.includedOnlyMeshes.push(i)}};for(a=0;a<_e.length;a++)Se()}}n.lightRig=r}},t}();e.MetadataParser=t}(i||(i={})),function(e){var t=function(){function e(e){for(var t=new Array(256),n=0;n<256;n++)t[n]=n;var i=(0|e)>>>0,r=function(){return(i=16807*i%2147483647)/2147483647};for(n=255;n>0;n--){var o=Math.floor(r()*(n+1)),a=t[n];t[n]=t[o],t[o]=a}for(this.perm=new Array(512),n=0;n<512;n++)this.perm[n]=t[255&n]}return e.prototype.fade=function(e){return e*e*e*(e*(6*e-15)+10)},e.prototype.lerp=function(e,t,n){return e+n*(t-e)},e.prototype.grad=function(e,t,n){var i=7&e,r=i<4?t:n,o=i<4?n:t;return(1&i?-r:r)+(2&i?-o:o)},e.prototype.noise=function(e,t){var n=255&Math.floor(e),i=255&Math.floor(t),r=e-Math.floor(e),o=t-Math.floor(t),a=this.fade(r),s=this.fade(o),l=this.perm[n]+i,u=this.perm[n+1]+i;return this.lerp(this.lerp(this.grad(this.perm[l],r,o),this.grad(this.perm[u],r-1,o),a),this.lerp(this.grad(this.perm[l+1],r,o-1),this.grad(this.perm[u+1],r-1,o-1),a),s)},e}();e.Perlin2D=t;var n=function(){function e(){}return e.fastFloor=function(e){return 0|Math.floor(e)},e.createNoise2D=function(t){void 0===t&&(t=Math.random);var n=e.buildPermutationTable(t),i=new Float64Array(n).map(function(t){return e.grad2[t%12*2]}),r=new Float64Array(n).map(function(t){return e.grad2[t%12*2+1]});return function(t,o){var a,s,l=0,u=0,c=0,d=(t+o)*e.F2,h=e.fastFloor(t+d),p=e.fastFloor(o+d),m=(h+p)*e.G2,f=t-(h-m),g=o-(p-m);f>g?(a=1,s=0):(a=0,s=1);var v=f-a+e.G2,y=g-s+e.G2,_=f-1+2*e.G2,S=g-1+2*e.G2,A=255&h,b=255&p,M=.5-f*f-g*g;if(M>=0){var B=A+n[b];l=(M*=M)*M*(i[B]*f+r[B]*g)}var C=.5-v*v-y*y;if(C>=0){var T=A+a+n[b+s];u=(C*=C)*C*(i[T]*v+r[T]*y)}var x=.5-_*_-S*S;if(x>=0){var I=A+1+n[b+1];c=(x*=x)*x*(i[I]*_+r[I]*S)}return 70*(l+u+c)}},e.createNoise3D=function(t){void 0===t&&(t=Math.random);var n=e.buildPermutationTable(t),i=new Float64Array(n).map(function(t){return e.grad3[t%12*3]}),r=new Float64Array(n).map(function(t){return e.grad3[t%12*3+1]}),o=new Float64Array(n).map(function(t){return e.grad3[t%12*3+2]});return function(t,a,s){var l,u,c,d,h,p,m,f,g,v,y=(t+a+s)*e.F3,_=e.fastFloor(t+y),S=e.fastFloor(a+y),A=e.fastFloor(s+y),b=(_+S+A)*e.G3,M=t-(_-b),B=a-(S-b),C=s-(A-b);M>=B?B>=C?(h=1,p=0,m=0,f=1,g=1,v=0):M>=C?(h=1,p=0,m=0,f=1,g=0,v=1):(h=0,p=0,m=1,f=1,g=0,v=1):B<C?(h=0,p=0,m=1,f=0,g=1,v=1):M<C?(h=0,p=1,m=0,f=0,g=1,v=1):(h=0,p=1,m=0,f=1,g=1,v=0);var T=M-h+e.G3,x=B-p+e.G3,I=C-m+e.G3,O=M-f+2*e.G3,L=B-g+2*e.G3,w=C-v+2*e.G3,N=M-1+3*e.G3,P=B-1+3*e.G3,R=C-1+3*e.G3,E=255&_,k=255&S,D=255&A,F=.6-M*M-B*B-C*C;if(F<0)l=0;else{var U=E+n[k+n[D]];l=(F*=F)*F*(i[U]*M+r[U]*B+o[U]*C)}var Y=.6-T*T-x*x-I*I;if(Y<0)u=0;else{var V=E+h+n[k+p+n[D+m]];u=(Y*=Y)*Y*(i[V]*T+r[V]*x+o[V]*I)}var G=.6-O*O-L*L-w*w;if(G<0)c=0;else{var z=E+f+n[k+g+n[D+v]];c=(G*=G)*G*(i[z]*O+r[z]*L+o[z]*w)}var W=.6-N*N-P*P-R*R;if(W<0)d=0;else{var H=E+1+n[k+1+n[D+1]];d=(W*=W)*W*(i[H]*N+r[H]*P+o[H]*R)}return 32*(l+u+c+d)}},e.createNoise4D=function(t){void 0===t&&(t=Math.random);var n=e.buildPermutationTable(t),i=new Float64Array(n).map(function(t){return e.grad4[t%32*4]}),r=new Float64Array(n).map(function(t){return e.grad4[t%32*4+1]}),o=new Float64Array(n).map(function(t){return e.grad4[t%32*4+2]}),a=new Float64Array(n).map(function(t){return e.grad4[t%32*4+3]});return function(t,s,l,u){var c,d,h,p,m,f=(t+s+l+u)*e.F4,g=e.fastFloor(t+f),v=e.fastFloor(s+f),y=e.fastFloor(l+f),_=e.fastFloor(u+f),S=(g+v+y+_)*e.G4,A=t-(g-S),b=s-(v-S),M=l-(y-S),B=u-(_-S),C=0,T=0,x=0,I=0;A>b?C++:T++,A>M?C++:x++,A>B?C++:I++,b>M?T++:x++,b>B?T++:I++,M>B?x++:I++;var O=C>=3?1:0,L=T>=3?1:0,w=x>=3?1:0,N=I>=3?1:0,P=C>=2?1:0,R=T>=2?1:0,E=x>=2?1:0,k=I>=2?1:0,D=C>=1?1:0,F=T>=1?1:0,U=x>=1?1:0,Y=I>=1?1:0,V=A-O+e.G4,G=b-L+e.G4,z=M-w+e.G4,W=B-N+e.G4,H=A-P+2*e.G4,X=b-R+2*e.G4,K=M-E+2*e.G4,Q=B-k+2*e.G4,j=A-D+3*e.G4,Z=b-F+3*e.G4,q=M-U+3*e.G4,J=B-Y+3*e.G4,$=A-1+4*e.G4,ee=b-1+4*e.G4,te=M-1+4*e.G4,ne=B-1+4*e.G4,ie=255&g,re=255&v,oe=255&y,ae=255&_,se=.6-A*A-b*b-M*M-B*B;if(se<0)c=0;else{var le=ie+n[re+n[oe+n[ae]]];c=(se*=se)*se*(i[le]*A+r[le]*b+o[le]*M+a[le]*B)}var ue=.6-V*V-G*G-z*z-W*W;if(ue<0)d=0;else{var ce=ie+O+n[re+L+n[oe+w+n[ae+N]]];d=(ue*=ue)*ue*(i[ce]*V+r[ce]*G+o[ce]*z+a[ce]*W)}var de=.6-H*H-X*X-K*K-Q*Q;if(de<0)h=0;else{var he=ie+P+n[re+R+n[oe+E+n[ae+k]]];h=(de*=de)*de*(i[he]*H+r[he]*X+o[he]*K+a[he]*Q)}var pe=.6-j*j-Z*Z-q*q-J*J;if(pe<0)p=0;else{var me=ie+D+n[re+F+n[oe+U+n[ae+Y]]];p=(pe*=pe)*pe*(i[me]*j+r[me]*Z+o[me]*q+a[me]*J)}var fe=.6-$*$-ee*ee-te*te-ne*ne;if(fe<0)m=0;else{var ge=ie+1+n[re+1+n[oe+1+n[ae+1]]];m=(fe*=fe)*fe*(i[ge]*$+r[ge]*ee+o[ge]*te+a[ge]*ne)}return 27*(c+d+h+p+m)}},e.buildPermutationTable=function(e){for(var t=new Uint8Array(512),n=0;n<256;n++)t[n]=n;for(n=0;n<255;n++){var i=n+~~(e()*(256-n)),r=t[n];t[n]=t[i],t[i]=r}for(n=256;n<512;n++)t[n]=t[n-256];return t},e.F2=.5*(Math.sqrt(3)-1),e.G2=(3-Math.sqrt(3))/6,e.F3=1/3,e.G3=1/6,e.F4=(Math.sqrt(5)-1)/4,e.G4=(5-Math.sqrt(5))/20,e.grad2=new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,1,0,-1,0,0,1,0,-1,0,1,0,-1]),e.grad3=new Float64Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0,1,0,1,-1,0,1,1,0,-1,-1,0,-1,0,1,1,0,-1,1,0,1,-1,0,-1,-1]),e.grad4=new Float64Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]),e}();e.SimplexNoise=n}(i||(i={})),function(e){var t=function(e){function t(t,n){var i=e.call(this,t,n)||this;return i.universalMaterial=!0,i._defines={},i._uniforms=[],i._samplers=[],i._attributes=[],i._textures={},i._vectors4={},i._vectors3={},i._vectors2={},i._floats={},i._bools={},i._ubos=null,i._wgslSamplers=null,i.shader=null,i.plugin=null,i.shader="StandardShaderMaterial",i.specularColor=new BABYLON.Color3(0,0,0),i}return r(t,e),t.prototype.getClassName=function(){return"StandardMaterial"},t.prototype.initMaterial=function(){this.awake&&this.awake()},t.prototype.addAttribute=function(e){-1===this._attributes.indexOf(e)&&this._attributes.push(e)},t.prototype.checkUniform=function(e,t,n){void 0===n&&(n=null),-1===this._uniforms.indexOf(e)&&(this._uniforms.push(e),this._defines[e.toUpperCase()]=!0,this.buildUniformProperty(e,t,n))},t.prototype.checkSampler=function(e,t){void 0===t&&(t=null),-1===this._samplers.indexOf(e)&&(this._samplers.push(e),this._defines[e.toUpperCase()]=!0,this.buildUniformProperty(e,"sampler2D",t),this.checkUniform(e+"Infos","vec2",BABYLON.Vector2.Zero()),this.checkUniform(e+"Matrix","mat4",BABYLON.Matrix.Identity()))},t.prototype.addTextureUniform=function(e,t){return this.checkSampler(e,t),this._textures[e]=t,this},t.prototype.setTextureValue=function(e,t){return this._textures[e]=t,this},t.prototype.getTextureValue=function(e){return this._textures[e]},t.prototype.addVector4Uniform=function(e,t){return this.checkUniform(e,"vec4",t),this._vectors4[e]=t,this},t.prototype.setVector4Value=function(e,t){return this._vectors4[e]=t,this},t.prototype.getVector4Value=function(e){return this._vectors4[e]},t.prototype.addVector3Uniform=function(e,t){return this.checkUniform(e,"vec3",t),this._vectors3[e]=t,this},t.prototype.setVector3Value=function(e,t){return this._vectors3[e]=t,this},t.prototype.getVector3Value=function(e){return this._vectors3[e]},t.prototype.addVector2Uniform=function(e,t){return this.checkUniform(e,"vec2",t),this._vectors2[e]=t,this},t.prototype.setVector2Value=function(e,t){return this._vectors2[e]=t,this},t.prototype.getVector2Value=function(e){return this._vectors2[e]},t.prototype.addFloatUniform=function(e,t){return this.checkUniform(e,"float",t),this._floats[e]=t,this},t.prototype.setFloatValue=function(e,t){return this._floats[e]=t,this},t.prototype.getFloatValue=function(e){return this._floats[e]},t.prototype.addBoolUniform=function(e,t){return this.checkUniform(e,"bool",t),this._bools[e]=t,this},t.prototype.setBoolValue=function(e,t){return this._bools[e]=t,this},t.prototype.getBoolValue=function(e){return this._bools[e]},t.prototype.getAnimatables=function(){var t=e.prototype.getAnimatables.call(this);for(var n in this._textures){var i=this._textures[n];i&&i.animations&&i.animations.length>0&&t.push(i)}return t},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);for(var n in this._textures){var i=this._textures[n];i&&t.push(i)}return t},t.prototype.hasTexture=function(t){if(e.prototype.hasTexture.call(this,t))return!0;for(var n in this._textures)if(this._textures[n]===t)return!0;return!1},t.prototype.getCustomUniforms=function(e){var t={};return null!=this._ubos&&this._ubos.length>0&&(t.ubo=this._ubos.filter(function(e){return"sampler2D"!==e.type})),!1===e&&(t.fragment=this.getCustomFragmentCode(!1)),t},t.prototype.getCustomSamplers=function(){return this._samplers},t.prototype.getCustomAttributes=function(){return this._attributes},t.prototype.getCustomVertexCode=function(e){return null},t.prototype.getCustomFragmentCode=function(e){var t=this,n=null;return null!=this._ubos&&this._ubos.length>0&&(n="#ifdef "+this.shader.toUpperCase()+"\n",this._ubos.forEach(function(i){if(!0===e)"sampler2D"===i.type&&(null==t._wgslSamplers&&(t._wgslSamplers=new Set),t._wgslSamplers.has(i.name)||(n+="\tvar "+i.name+": texture_2d<f32>;\n",n+="\tvar "+i.name+"Sampler: sampler;\n",t._wgslSamplers.add(i.name)));else{var r=i.name.toUpperCase()+"_DEFINED";"float"===i.type||"bool"===i.type||"int"===i.type?(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform float "+i.name+";\n",n+="\t#endif\n"):"vec2"===i.type?(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform vec2 "+i.name+";\n",n+="\t#endif\n"):"vec3"===i.type?(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform vec3 "+i.name+";\n",n+="\t#endif\n"):"vec4"===i.type?(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform vec4 "+i.name+";\n",n+="\t#endif\n"):"mat4"===i.type?(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform mat4 "+i.name+";\n",n+="\t#endif\n"):"sampler2D"===i.type&&(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform sampler2D "+i.name+";\n",n+="\t#endif\n")}}),n+="#endif\n"),n},t.prototype.prepareCustomDefines=function(e){if(this._wgslSamplers&&this._wgslSamplers.clear(),e[this.shader.toUpperCase()]=!0,null!=this._defines){var t=Object.keys(this._defines);if(null!=t&&t.length>0)for(var n=0,i=t;n<i.length;n++){var r=i[n];e[r]=this._defines[r]}}e.isDirty&&e.rebuild()},t.prototype.updateCustomBindings=function(e){var t,n=this.getScene();this.update&&this.update();var i=null!=e&&"function"==typeof e.getUniformNames,r=i?e.getUniformNames():[],o=function(e){return i&&-1!==r.indexOf(e)};if(n.texturesEnabled)for(t in this._textures){var a=this._textures[t];null!=a&&a.isReady&&a.isReady()&&(null==a.isChecked&&(a.isChecked=!0,("detailsSampler"===t||"normalsSampler"===t||t.indexOf("(Atlas)")>=0)&&a.updateSamplingMode(8)),e.setTexture&&e.setTexture(t,a),o(t+"Infos")&&e.updateFloat2?e.updateFloat2(t+"Infos",a.coordinatesIndex,a.level):e.setFloat2?e.setFloat2(t+"Infos",a.coordinatesIndex,a.level):e.setFloat&&e.setFloat(t+"Infos",a.coordinatesIndex),o(t+"Matrix")&&e.updateMatrix?e.updateMatrix(t+"Matrix",a.getTextureMatrix()):e.setMatrix&&e.setMatrix(t+"Matrix",a.getTextureMatrix()))}for(t in this._vectors4){var s=this._vectors4[t];o(t)&&e.updateVector4?e.updateVector4(t,s):e.setVector4?e.setVector4(t,s):e.setFloat4&&e.setFloat4(t,s.x,s.y,s.z,s.w)}for(t in this._vectors3)s=this._vectors3[t],o(t)&&e.updateVector3?e.updateVector3(t,s):e.setVector3?e.setVector3(t,s):e.setFloat3&&e.setFloat3(t,s.x,s.y,s.z);for(t in this._vectors2)s=this._vectors2[t],o(t)&&e.updateFloat2?e.updateFloat2(t,s.x,s.y):e.setFloat2?e.setFloat2(t,s.x,s.y):e.setFloat&&e.setFloat(t,s.x);for(t in this._floats){var l=this._floats[t];o(t)&&e.updateFloat?e.updateFloat(t,l):e.setFloat&&e.setFloat(t,l)}for(t in this._bools)l=this._bools[t]?1:0,o(t)&&e.updateFloat?e.updateFloat(t,l):e.setFloat&&e.setFloat(t,l);i&&e.update&&e.update()},t.prototype.legacyUpdateCustomBindings=function(e){var t,n=this.getScene();if(this.update&&this.update(),n.texturesEnabled)for(t in this._textures){var i=this._textures[t];null!=i&&i.isReady&&i.isReady()&&(null==i.isChecked&&(i.isChecked=!0,("detailsSampler"===t||"normalsSampler"===t||t.indexOf("(Atlas)")>=0)&&i.updateSamplingMode(8)),e.setTexture(t,i),e.updateFloat2(t+"Infos",i.coordinatesIndex,i.level),e.updateMatrix(t+"Matrix",i.getTextureMatrix()))}for(t in this._vectors4)e.updateVector4(t,this._vectors4[t]);for(t in this._vectors3)e.updateVector3(t,this._vectors3[t]);for(t in this._vectors2)e.updateFloat2(t,this._vectors2[t].x,this._vectors2[t].y);for(t in this._floats)e.updateFloat(t,this._floats[t]);for(t in this._bools)e.updateFloat(t,this._bools[t]?1:0);e.update()},t.prototype.buildUniformProperty=function(e,t,n){var i=1;switch(t){case"float":case"bool":case"int":i=1;break;case"vec2":i=2;break;case"vec3":i=3;break;case"vec4":i=4;break;case"mat4":i=16}null==this._ubos&&(this._ubos=[]),this._ubos.push({name:e,size:i,type:t})},t}(BABYLON.StandardMaterial);e.StandardShaderMaterial=t;var n=function(e){function t(t,n,i,r,o,a,s){void 0===o&&(o=!0),void 0===a&&(a=!0),void 0===s&&(s=!1);var l=e.call(this,t,n,i,r,o,a,s)||this;return l._isEnabled=!1,l.vertexDefinitions=null,l.fragmentDefinitions=null,l.setIsEnabled(a),l}return r(t,e),t.prototype.getClassName=function(){return"StandardMaterialPlugin"},t.prototype.getIsEnabled=function(){return this._isEnabled},t.prototype.setIsEnabled=function(e){this._isEnabled=e,this._material.markAsDirty(BABYLON.Constants.MATERIAL_AllDirtyFlag),this.markAllDefinesAsDirty(),this._enable(this._isEnabled)},t.prototype.getCustomShaderMaterial=function(){return this._material},t}(BABYLON.MaterialPluginBase);e.StandardShaderMaterialPlugin=n,e.SceneManager.RegisterClass("TOOLKIT.StandardShaderMaterial",t),e.SceneManager.RegisterClass("TOOLKIT.StandardShaderMaterialPlugin",n)}(i||(i={})),function(e){var t=function(){function t(){}return t.ZeroPad=function(e,t){var n=t-e.toString().length+1;return Array(+(n>0&&n)).join("0")+e},t.ShiftArray=function(e,t){return t?e.unshift(e.pop()):e.push(e.shift()),e},t.GetLayerMask=function(e){return 1<<e},t.IsLayerMasked=function(e,t){return!!(e&1<<t)},t.GetHavokPlugin=function(){return globalThis.HKP},t.GetLoadingState=function(){return e.Utilities.LoadingState},t.GetRandomRange=function(e,t,n,i){void 0===n&&(n=null),void 0===i&&(i=null);var r=BABYLON.Scalar.RandomRange(e,t);if(null!=n){var o=null!=i?i:100;if(r===n)for(var a=0;a<o&&(r=BABYLON.Scalar.RandomRange(e,t))===n;a++);}return r},t.GetRandomFloat=function(t,n,i,r){return void 0===i&&(i=null),void 0===r&&(r=null),parseFloat(e.Utilities.GetRandomRange(t,n,i,r).toFixed(2))},t.GetRandomInteger=function(t,n,i,r){return void 0===i&&(i=null),void 0===r&&(r=null),parseInt(e.Utilities.GetRandomRange(t,n,i,r).toFixed(0))},t.Approximately=function(t,n){return Math.abs(n-t)<Math.max(e.System.Epsilon*Math.max(Math.abs(t),Math.abs(n)),8*e.System.SingleEpsilon)},t.GetVertexDataFromMesh=function(e){var t=e.computeWorldMatrix(!0),n=BABYLON.VertexData.ExtractFromMesh(e,!0,!0);return n.transform(t),n},t.CalculateDestinationPoint=function(t,n,i){var r=new BABYLON.Vector3(0,0,0);return e.Utilities.CalculateDestinationPointToRef(t,n,i,r),r},t.CalculateDestinationPointToRef=function(t,n,i,r){null==e.Utilities.TempDirectionBuffer&&(e.Utilities.TempDirectionBuffer=new BABYLON.Vector3(0,0,0)),e.Utilities.TempDirectionBuffer.set(0,0,0),n.scaleToRef(i,e.Utilities.TempDirectionBuffer),t.addToRef(e.Utilities.TempDirectionBuffer,r)},t.UpdateAbstractMeshMaterial=function(e,t,n){if(null!=e)if(!1==e instanceof BABYLON.InstancedMesh){var i=e.material;if(i instanceof BABYLON.MultiMaterial){var r=i.clone(i.name+".Clone");r.subMaterials[n]=t,e.material=r}else e.material=t}else console.warn("Instanced mesh not supported as a node material on mesh: "+e.name);else console.warn("Null source mesh for mesh: "+e.name)},t.HermiteVector3=function(t,n,i,r,o){var a=new BABYLON.Vector3(0,0,0);return e.Utilities.HermiteVector3ToRef(t,n,i,r,o,a),a},t.HermiteVector3ToRef=function(e,t,n,i,r,o){var a=r*r,s=r*a,l=2*s-3*a+1,u=-2*s+3*a,c=s-2*a+r,d=s-a,h=e._x*l+n._x*u+t._x*c+i._x*d,p=e._y*l+n._y*u+t._y*c+i._y*d,m=e._z*l+n._z*u+t._z*c+i._z*d;o.set(h,p,m)},t.ExpSmoothing=function(e,t){return t<=0?1:1-Math.exp(-e/t)},t.LerpLog=function(e,t,n){var i=Math.min(Math.max(n,0),1);return e+(t-e)*Math.sin(i*Math.PI*.5)},t.LerpExp=function(e,t,n){var i=Math.min(Math.max(n,0),1);return e+(t-e)*(1-Math.cos(i*Math.PI*.5))},t.LerpUnclamped=function(e,t,n){return e+(t-e)*n},t.LerpUnclampedColor3=function(t,n,i){var r=new BABYLON.Color3(0,0,0);return e.Utilities.LerpUnclampedColor3ToRef(t,n,i,r),r},t.LerpUnclampedColor3ToRef=function(e,t,n,i){i.set(e.r+(t.r-e.r)*n,e.g+(t.g-e.g)*n,e.b+(t.b-e.b)*n)},t.LerpUnclampedColor4=function(t,n,i){var r=new BABYLON.Color4(0,0,0,1);return e.Utilities.LerpUnclampedColor4ToRef(t,n,i,r),r},t.LerpUnclampedColor4ToRef=function(e,t,n,i){i.set(e.r+(t.r-e.r)*n,e.g+(t.g-e.g)*n,e.b+(t.b-e.b)*n,e.a+(t.a-e.a)*n)},t.LerpUnclampedVector2=function(t,n,i){var r=new BABYLON.Vector2(0,0);return e.Utilities.LerpUnclampedVector2ToRef(t,n,i,r),r},t.LerpUnclampedVector2ToRef=function(e,t,n,i){i.set(e.x+(t.x-e.x)*n,e.y+(t.y-e.y)*n)},t.LerpUnclampedVector3=function(t,n,i){var r=new BABYLON.Vector3(0,0,0);return e.Utilities.LerpUnclampedVector3ToRef(t,n,i,r),r},t.LerpUnclampedVector3ToRef=function(e,t,n,i){i.set(e.x+(t.x-e.x)*n,e.y+(t.y-e.y)*n,e.z+(t.z-e.z)*n)},t.LerpUnclampedVector4=function(t,n,i){var r=new BABYLON.Vector4(0,0,0,0);return e.Utilities.LerpUnclampedVector4ToRef(t,n,i,r),r},t.LerpUnclampedVector4ToRef=function(e,t,n,i){i.set(e.x+(t.x-e.x)*n,e.y+(t.y-e.y)*n,e.z+(t.z-e.z)*n,e.w+(t.w-e.w)*n)},t.IsEqualUsingDot=function(t){return t>1-e.System.Epsilon},t.QuaternionAngle=function(t,n){var i=Math.min(Math.abs(BABYLON.Quaternion.Dot(t,n)),1);return e.Utilities.IsEqualUsingDot(i)?0:2*Math.acos(i)*e.System.Rad2Deg},t.QuaternionLengthSquared=function(e){return e.x*e.x+e.y*e.y+e.z*e.z+e.w*e.w},t.QuaternionRotateTowards=function(t,n,i){var r=new BABYLON.Quaternion(0,0,0,1);return e.Utilities.QuaternionRotateTowardsToRef(t,n,i,r),r},t.QuaternionRotateTowardsToRef=function(t,n,i,r){var o=e.Utilities.QuaternionAngle(t,n);0==o?r.copyFrom(n):e.Utilities.QuaternionSlerpUnclampedToRef(t,n,Math.min(1,i/o),r)},t.QuaternionSlerpUnclamped=function(t,n,i){var r=new BABYLON.Quaternion(0,0,0,1);return e.Utilities.QuaternionSlerpUnclampedToRef(t,n,i,r),r},t.QuaternionSlerpUnclampedToRef=function(e,t,n,i){},t.MoveTowards=function(e,t,n){var i=t-e;return Math.abs(i)<=n?t:e+Math.sign(i)*n},t.MoveTowardsVector2=function(t,n,i){var r=new BABYLON.Vector2(0,0);return e.Utilities.MoveTowardsVector2ToRef(t,n,i,r),r},t.MoveTowardsVector2ToRef=function(e,t,n,i){var r=t.x-e.x,o=t.y-e.y,a=r*r+o*o;if(0==a||n>=0&&a<=n*n)i.set(t.x,t.y);else{var s=Math.sqrt(a);i.set(e.x+r/s*n,e.y+o/s*n)}},t.MoveTowardsVector3=function(t,n,i){var r=new BABYLON.Vector3(0,0,0);return e.Utilities.MoveTowardsVector3ToRef(t,n,i,r),r},t.MoveTowardsVector3ToRef=function(e,t,n,i){var r=t.x-e.x,o=t.y-e.y,a=t.z-e.z,s=r*r+o*o+a*a;if(0==s||n>=0&&s<=n*n)i.set(t.x,t.y,t.z);else{var l=Math.sqrt(s);i.set(e.x+r/l*n,e.y+o/l*n,e.z+a/l*n)}},t.MoveTowardsVector4=function(t,n,i){var r=new BABYLON.Vector4(0,0,0,0);return e.Utilities.MoveTowardsVector4ToRef(t,n,i,r),r},t.MoveTowardsVector4ToRef=function(e,t,n,i){var r=t.x-e.x,o=t.y-e.y,a=t.z-e.z,s=t.w-e.w,l=r*r+o*o+a*a+s*s;if(0==l||n>=0&&l<=n*n)i.set(t.x,t.y,t.z,t.w);else{var u=Math.sqrt(l);i.set(e.x+r/u*n,e.y+o/u*n,e.z+a/u*n,e.w+s/u*n)}},t.ClampMagnitudeVector2=function(t,n){var i=new BABYLON.Vector2(0,0);return e.Utilities.ClampMagnitudeVector2ToRef(t,n,i),i},t.ClampMagnitudeVector2ToRef=function(e,t,n){var i=e.lengthSquared();if(i>t*t){var r=Math.sqrt(i),o=e.x/r,a=e.y/r;n.set(o*t,a*t)}},t.ClampMagnitudeVector3=function(t,n){var i=new BABYLON.Vector3(0,0,0);return e.Utilities.ClampMagnitudeVector3ToRef(t,n,i),i},t.ClampMagnitudeVector3ToRef=function(e,t,n){var i=e.lengthSquared();if(i>t*t){var r=Math.sqrt(i),o=e.x/r,a=e.y/r,s=e.z/r;n.set(o*t,a*t,s*t)}},t.GetAngle=function(t,n){return e.Utilities.GetAngleRadians(t,n)*e.System.Rad2Deg},t.GetAngleRadians=function(e,t){return Math.acos(BABYLON.Vector3.Dot(e,t))},t.ClampAngle=function(e,t,n){var i=e;do{i<-360&&(i+=360),i>360&&(i-=360)}while(i<-360||i>360);return BABYLON.Scalar.Clamp(i,t,n)},t.ClampAngle180=function(e,t,n){return e>180&&(e-=360),(e=BABYLON.Scalar.Clamp(e,t,n))<0&&(e+=360),e},t.ClampAngle360=function(e,t,n){return(e<90||e>270)&&(e>180&&(e-=360),n>180&&(n-=360),t>180&&(t-=360)),(e=BABYLON.Scalar.Clamp(e,t,n))<0&&(e+=360),e},t.SmoothDamp=function(e,t,n,i,r,o){if(!o)return 0;var a=e-t,s=Math.max(1e-4,n),l=2/s,u=l*r,c=1/(1+u+.48*u*u+.235*u*u*u),d=t,h=i*s,p=e-(a=BABYLON.Scalar.Clamp(a,-h,h)),m=(o.x+l*a)*r;o.x=(o.x-l*m)*c;var f=p+(a+m)*c;return d-e>0==f>d&&(f=d,o.x=(f-d)/r),f},t.SmoothDampAngle=function(t,n,i,r,o,a){var s=t+BABYLON.Scalar.DeltaAngle(t,n);return e.Utilities.SmoothDamp(t,s,i,r,o,a)},t.SmoothDampVector2=function(t,n,i,r,o,a){var s=new BABYLON.Vector2(0,0);return e.Utilities.SmoothDampVector2ToRef(t,n,i,r,o,a,s),s},t.SmoothDampVector2ToRef=function(e,t,n,i,r,o,a){var s=2/(n=Math.max(1e-4,n)),l=s*r,u=1/(1+l+.48*l*l+.235*l*l*l),c=e.x-t.x,d=e.y-t.y,h=t.clone(),p=i*n,m=c*c+d*d;if(m>p*p){var f=Math.sqrt(m);c=c/f*p,d=d/f*p}t.x=e.x-c,t.y=e.y-d;var g=(o.x+s*c)*r,v=(o.y+s*d)*r;o.x=(o.x-s*g)*u,o.y=(o.y-s*v)*u;var y=t.x+(c+g)*u,_=t.y+(d+v)*u,S=h.x-e.x,A=h.y-e.y;S*(y-h.x)+A*(_-h.y)>0&&(y=h.x,_=h.y,o.x=(y-h.x)/r,o.y=(_-h.y)/r),a.set(y,_)},t.SmoothDampVector3=function(t,n,i,r,o,a){var s=new BABYLON.Vector3(0,0,0);return e.Utilities.SmoothDampVector3ToRef(t,n,i,r,o,a,s),s},t.SmoothDampVector3ToRef=function(e,t,n,i,r,o,a){var s=0,l=0,u=0,c=2/(n=Math.max(1e-4,n)),d=c*r,h=1/(1+d+.48*d*d+.235*d*d*d),p=e.x-t.x,m=e.y-t.y,f=e.z-t.z,g=t.clone(),v=i*n,y=p*p+m*m+f*f;if(y>v*v){var _=Math.sqrt(y);p=p/_*v,m=m/_*v,f=f/_*v}t.x=e.x-p,t.y=e.y-m,t.z=e.z-f;var S=(o.x+c*p)*r,A=(o.y+c*m)*r,b=(o.z+c*f)*r;o.x=(o.x-c*S)*h,o.y=(o.y-c*A)*h,o.z=(o.z-c*b)*h,s=t.x+(p+S)*h,l=t.y+(m+A)*h,u=t.z+(f+b)*h;var M=g.x-e.x,B=g.y-e.y,C=g.z-e.z;M*(s-g.x)+B*(l-g.y)+C*(u-g.z)>0&&(s=g.x,l=g.y,u=g.z,o.x=(s-g.x)/r,o.y=(l-g.y)/r,o.z=(u-g.z)/r),a.set(s,l,u)},t.ToMatrix=function(e,t,n){return BABYLON.Matrix.RotationYawPitchRoll(BABYLON.Tools.ToRadians(t),BABYLON.Tools.ToRadians(e),BABYLON.Tools.ToRadians(n))},t.ToMatrixToRef=function(e,t,n,i){BABYLON.Matrix.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(t),BABYLON.Tools.ToRadians(e),BABYLON.Tools.ToRadians(n),i)},t.FastMatrixLerp=function(e,t,n,i){BABYLON.Matrix.LerpToRef(e,t,n,i)},t.FastMatrixSlerp=function(e,t,n,i){BABYLON.Matrix.DecomposeLerpToRef(e,t,n,i)},t.ToEuler=function(e){var t=e.toEulerAngles();return t.x=BABYLON.Tools.ToDegrees(t.x),t.y=BABYLON.Tools.ToDegrees(t.y),t.z=BABYLON.Tools.ToDegrees(t.z),t},t.ToEulerToRef=function(e,t){e.toEulerAnglesToRef(t),t.x=BABYLON.Tools.ToDegrees(t.x),t.y=BABYLON.Tools.ToDegrees(t.y),t.z=BABYLON.Tools.ToDegrees(t.z)},t.FromEuler=function(e,t,n){return BABYLON.Quaternion.FromEulerAngles(BABYLON.Tools.ToRadians(e),BABYLON.Tools.ToRadians(t),BABYLON.Tools.ToRadians(n))},t.FromEulerToRef=function(e,t,n,i){BABYLON.Quaternion.FromEulerAnglesToRef(BABYLON.Tools.ToRadians(e),BABYLON.Tools.ToRadians(t),BABYLON.Tools.ToRadians(n),i)},t.QuaternionDiff=function(t,n){var i=new BABYLON.Quaternion(0,0,0,1);return e.Utilities.QuaternionDiffToRef(t,n,i),i},t.QuaternionDiffToRef=function(t,n,i){BABYLON.Quaternion.InverseToRef(n,e.Utilities.TempQuaternion),e.Utilities.TempQuaternion.multiplyToRef(t,i)},t.QuaternionSubtractToRef=function(e,t,n){n.set(e._x-t._x,e._y-t._y,e._z-t._z,e._w-t._w)},t.RotateVector=function(e,t){var n=2*(t.y*e.z-t.z*e.y),i=2*(t.z*e.x-t.x*e.z),r=2*(t.x*e.y-t.y*e.x);return new BABYLON.Vector3(e.x+t.w*n+(t.y*r-t.z*i),e.y+t.w*i+(t.z*n-t.x*r),e.z+t.w*r+(t.x*i-t.y*n))},t.RotateVectorToRef=function(e,t,n){var i=2*(t.y*e.z-t.z*e.y),r=2*(t.z*e.x-t.x*e.z),o=2*(t.x*e.y-t.y*e.x);n.x=e.x+t.w*i+(t.y*o-t.z*r),n.y=e.y+t.w*r+(t.z*i-t.x*o),n.z=e.z+t.w*o+(t.x*r-t.y*i)},t.LookRotation=function(t){var n=BABYLON.Quaternion.Zero();return e.Utilities.LookRotationToRef(t,n),n},t.LookRotationToRef=function(e,t){BABYLON.Quaternion.FromLookDirectionRHToRef(e,BABYLON.Vector3.Up(),t)},t.Vector3Rad2Deg=function(t){var n=BABYLON.Vector3.Zero();return e.Utilities.Vector3Rad2DegToRef(t,n),n},t.Vector3Rad2DegToRef=function(e,t){t.x=BABYLON.Tools.ToDegrees(e.x),t.y=BABYLON.Tools.ToDegrees(e.y),t.z=BABYLON.Tools.ToDegrees(e.z)},t.MultiplyQuaternionByVector=function(t,n){var i=new BABYLON.Vector3(0,0,0);return e.Utilities.MultiplyQuaternionByVectorToRef(t,n,i),i},t.MultiplyQuaternionByVectorToRef=function(e,t,n){var i=2*e.x,r=2*e.y,o=2*e.z,a=e.x*i,s=e.y*r,l=e.z*o,u=e.x*r,c=e.x*o,d=e.y*o,h=e.w*i,p=e.w*r,m=e.w*o;n.x=(1-(s+l))*t.x+(u-m)*t.y+(c+p)*t.z,n.y=(u+m)*t.x+(1-(a+l))*t.y+(d-h)*t.z,n.z=(c-p)*t.x+(d+h)*t.y+(1-(a+s))*t.z},t.ValidateTransformRotation=function(e){null!=e.rotationQuaternion&&(e.rotation=e.rotationQuaternion.toEulerAngles(),e.rotationQuaternion=null)},t.ValidateTransformQuaternion=function(e){null==e.rotationQuaternion&&null!=e.rotation&&(e.rotationQuaternion=BABYLON.Quaternion.FromEulerAngles(e.rotation.x,e.rotation.y,e.rotation.z),e.rotation.set(0,0,0))},t.GetKeyboardInputValue=function(t,n,i){var r=i;return!0===e.UserInputOptions.KeyboardSmoothing&&(r=BABYLON.Scalar.MoveTowards(n,i,e.UserInputOptions.KeyboardMoveSensibility*e.SceneManager.GetDeltaSeconds(t)),Math.abs(r)<e.UserInputOptions.KeyboardMoveDeadZone&&(r=0)),r},t.GenerateRandonNumber=function(e,t,n){void 0===n&&(n=2);var i=(Math.random()*(t-e)+e).toFixed(n);return parseFloat(i)},t.ProjectVector=function(t,n){var i=new BABYLON.Vector3(0,0,0);return e.Utilities.ProjectVectorToRef(t,n,i),i},t.ProjectVectorToRef=function(t,n,i){var r=BABYLON.Vector3.Dot(n,n);if(r<e.System.Epsilon)i.set(0,0,0);else{var o=BABYLON.Vector3.Dot(t,n);i.set(n.x*o/r,n.y*o/r,n.z*o/r)}},t.ProjectVectorOnPlane=function(t,n){var i=new BABYLON.Vector3(0,0,0);return e.Utilities.ProjectVectorOnPlaneToRef(t,n,i),i},t.ProjectVectorOnPlaneToRef=function(t,n,i){var r=BABYLON.Vector3.Dot(n,n);if(r<e.System.Epsilon)i.copyFrom(t);else{var o=BABYLON.Vector3.Dot(t,n);i.set(t.x-n.x*o/r,t.y-n.y*o/r,t.z-n.z*o/r)}},t.AreVectorsEqual=function(e,t,n){return Math.abs(e.x-t.x)<n&&Math.abs(e.y-t.y)<n&&Math.abs(e.z-t.z)<n},t.GetVerticalSlopeAngle=function(t,n){void 0===n&&(n=0);var i=Math.atan(Math.abs(t.y/Math.sqrt(t.x*t.x+t.z*t.z)))*e.System.Rad2Deg;return i=null!=i&&!1===Number.isNaN(i)?i:0,n>0&&i>=n&&(i=0),i},t.DownloadEnvironment=function(e,t,n){void 0===t&&(t=null),void 0===n&&(n=null),BABYLON.EnvironmentTextureTools.CreateEnvTextureAsync(e).then(function(n){var i=e.name||"Environment",r=new Blob([n],{type:"octet/stream"});BABYLON.Tools.Download(r,i+".env"),null!=t&&t()}).catch(function(e){console.error(e),null!=n&&n()})},t.HasOwnProperty=function(e,t){return null!=e&&null!=t&&""!==t&&t in e},t.FindMeshCollider=function(e,t){var n=null;if(t instanceof BABYLON.TransformNode&&!0==(null!=t.metadata&&null!=t.metadata.toolkit&&null!=t.metadata.toolkit.renderer&&null!=t.metadata.toolkit.renderer.hasmeshcollider&&!0===t.metadata.toolkit.renderer.hasmeshcollider)){var i=t.id+"-collider";n=e.getMeshById(i)}return n},t.ColliderInstances=function(){return null==e.SceneManager.GlobalOptions.colliderInstances||e.SceneManager.GlobalOptions.colliderInstances},t.ReparentColliders=function(){return null==e.SceneManager.GlobalOptions.reparentColliders||e.SceneManager.GlobalOptions.reparentColliders},t.UseTriangleNormals=function(){return null!=e.SceneManager.GlobalOptions.useTriangleNormals&&e.SceneManager.GlobalOptions.useTriangleNormals},t.UseConvexTriangles=function(){return null!=e.SceneManager.GlobalOptions.useConvexTriangles&&e.SceneManager.GlobalOptions.useConvexTriangles},t.DefaultRenderGroup=function(){return null!=e.SceneManager.GlobalOptions.defaultRenderGroup?e.SceneManager.GlobalOptions.defaultRenderGroup:0},t.ShowDebugColliders=function(){return!0===e.SceneManager.EnableDebugMode||null!=e.SceneManager.GlobalOptions.showDebugColliders&&e.SceneManager.GlobalOptions.showDebugColliders},t.ColliderVisibility=function(){return null!=e.SceneManager.GlobalOptions.colliderVisibility?e.SceneManager.GlobalOptions.colliderVisibility:0},t.ColliderRenderGroup=function(){return null!=e.SceneManager.GlobalOptions.colliderRenderGroup?e.SceneManager.GlobalOptions.colliderRenderGroup:0},t.CollisionWireframe=function(){return null!=e.SceneManager.GlobalOptions.collisionWireframe&&e.SceneManager.GlobalOptions.collisionWireframe},t.GetColliderMaterial=function(t){var n="Collider-Material",i=t.getMaterialByName(n);if(null==i){var r=new BABYLON.PBRMaterial(n,t);r.albedoColor=new BABYLON.Color3(0,.75,0),r.wireframe=e.Utilities.CollisionWireframe(),r.unlit=!0,i=r}return i},t.CalculateCombinedFriction=function(e,t){var n=e*t;return n<-10&&(n=-10),n>10&&(n=10),n},t.CalculateCombinedRestitution=function(e,t){return e*t},t.AddLoaderItemMarkedForDisposal=function(t){null==e.Utilities.LoaderItemsMarkedForDisposal&&(e.Utilities.LoaderItemsMarkedForDisposal=[]),e.Utilities.LoaderItemsMarkedForDisposal.push(t)},t.ResetLoaderItemsMarkedForDisposal=function(){e.Utilities.LoaderItemsMarkedForDisposal=[]},t.RemoveLoaderItemsMarkedForDisposal=function(){null!=e.Utilities.LoaderItemsMarkedForDisposal&&e.Utilities.LoaderItemsMarkedForDisposal.length>0&&e.Utilities.LoaderItemsMarkedForDisposal.forEach(function(e){try{e.dispose()}catch(e){console.warn(e)}}),e.Utilities.ResetLoaderItemsMarkedForDisposal()},t.GetDirectTargetAngle=function(t,n){return e.Utilities.TempVector3.set(0,0,0),e.Utilities.InverseTransformPointToRef(t,n,e.Utilities.TempVector3),Math.atan2(e.Utilities.TempVector3.x,e.Utilities.TempVector3.z)},t.GetSmoothTargetAngle=function(t,n){return e.Utilities.TempVector3.set(0,0,0),e.Utilities.InverseTransformPointToRef(t,n,e.Utilities.TempVector3),e.Utilities.TempVector3.x/e.Utilities.TempVector3.length()},t.CalculatCatmullRom=function(t,n,i,r,o){var a=new BABYLON.Vector3(0,0,0);return e.Utilities.CalculatCatmullRomToRef(t,n,i,r,o,a),a},t.CalculatCatmullRomToRef=function(e,t,n,i,r,o){},t.MakeProper=function(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},t.StartsWith=function(e,t){return 0===e.lastIndexOf(t,0)},t.EndsWith=function(e,t){return-1!==e.indexOf(t,e.length-t.length)},t.ReplaceAll=function(e,t,n){return e.replace(new RegExp(t,"g"),n)},t.IsNullOrEmpty=function(e){return null==e||""===e},t.SafeStringPush=function(e,t){-1===e.indexOf(t)&&e.push(t)},t.ParseColor3=function(e,t,n){return void 0===t&&(t=null),void 0===n&&(n=!1),null!=e&&null!=e.r&&null!=e.g&&null!=e.b?!0===n?new BABYLON.Color3(e.r,e.g,e.b).toLinearSpace():new BABYLON.Color3(e.r,e.g,e.b):t},t.ParseColor4=function(e,t,n){void 0===t&&(t=null),void 0===n&&(n=!1);var i=null;if(null!=e&&null!=e.r&&null!=e.g&&null!=e.b){var r=null!=e.a?e.a:1;i=!0===n?new BABYLON.Color4(e.r,e.g,e.b,r).toLinearSpace():new BABYLON.Color4(e.r,e.g,e.b,r)}else i=t;return i},t.ParseVector2=function(e,t){return void 0===t&&(t=null),null!=e&&null!=e.x&&null!=e.y?new BABYLON.Vector2(e.x,e.y):t},t.ParseVector3=function(e,t){return void 0===t&&(t=null),null!=e&&null!=e.x&&null!=e.y&&null!=e.z?new BABYLON.Vector3(e.x,e.y,e.z):t},t.ParseVector4=function(e,t){return void 0===t&&(t=null),null!=e&&null!=e.x&&null!=e.y&&null!=e.z&&null!=e.w?new BABYLON.Vector4(e.x,e.y,e.z,e.w):t},t.ParseSound=function(t,n,i,r,o){return a(this,void 0,void 0,function(){var a,l,u;return s(this,function(s){switch(s.label){case 0:return a=null,null==t||null==t.filename||""===t.filename?[3,2]:(l=e.SceneManager.GetRootUrl(n),u=t.filename,[4,e.AudioSource.CreateStaticSound(i,l+u,o)]);case 1:a=s.sent(),null!=r&&r(),s.label=2;case 2:return[2,a]}})})},t.ParseTexture=function(t,n,i,r,o,a,s,l,u,c){var d=null;if(null!=t&&null!=t.filename&&""!==t.filename){var h=e.SceneManager.GetRootUrl(n),p=t.filename;d=new BABYLON.Texture(h+p,n,i,r,o,a,s,l,u,c)}return d},t.ParseCubemap=function(t,n){var i=null;if(null!=t&&null!=t.info){var r=e.SceneManager.GetRootUrl(n),o=(t.info.rooturl,r+t.info.rooturl);null!=(i=BABYLON.CubeTexture.Parse(t.info,n,o))&&(i.gammaSpace=!1)}return i},t.ParseTextAsset=function(t,n){return void 0===n&&(n=null),null!=t&&null!=t.base64&&""!==t.base64?e.WindowManager.Atob(t.base64):n},t.ParseJsonAsset=function(t,n,i){void 0===n&&(n=null),void 0===i&&(i=null);var r=e.Utilities.ParseTextAsset(t,n);return null!=r&&""!==r?JSON.parse(r,i):null},t.ParseTransformByID=function(t,n,i){return void 0===i&&(i=null),null!=t&&null!=t.id?e.SceneManager.GetTransformNodeByID(n,t.id):i},t.ParseTransformByName=function(t,n,i){return void 0===i&&(i=null),null!=t&&null!=t.id?e.SceneManager.GetTransformNode(n,t.id):i},t.ParseChildTransform=function(t,n,i){return void 0===i&&(i=null),null!=n&&null!=n.name?e.SceneManager.FindChildTransformNode(t,n.name,e.SearchType.IndexOf,!1):i},t.SetAbsolutePosition=function(e,t){e.setAbsolutePosition(t)},t.GetAbsolutePosition=function(t,n,i){void 0===n&&(n=null),void 0===i&&(i=!0);var r=new BABYLON.Vector3(0,0,0);return e.Utilities.GetAbsolutePositionToRef(t,r,n,i),r},t.GetAbsolutePositionToRef=function(e,t,n,i){void 0===n&&(n=null),void 0===i&&(i=!0),!0===i&&e.computeWorldMatrix(!0),t.copyFrom(e.getAbsolutePosition()),null!=n&&t.addInPlace(n)},t.SetAbsoluteRotation=function(t,n){null==t.rotationQuaternion&&(t.rotationQuaternion=t.rotation.toQuaternion()),null!=t.parent&&t.parent instanceof BABYLON.TransformNode?(e.Utilities.TempQuaternion2.set(0,0,0,1),e.Utilities.GetAbsoluteRotationToRef(t.parent,e.Utilities.TempQuaternion2),BABYLON.Quaternion.InverseToRef(e.Utilities.TempQuaternion2,e.Utilities.TempQuaternion2),e.Utilities.TempQuaternion2.multiplyInPlace(n),t.rotationQuaternion.copyFrom(e.Utilities.TempQuaternion2)):t.rotationQuaternion.copyFrom(n)},t.GetAbsoluteRotation=function(t){var n=new BABYLON.Quaternion(0,0,0,1);return e.Utilities.GetAbsoluteRotationToRef(t,n),n},t.GetAbsoluteRotationToRef=function(e,t){null!=e.absoluteRotationQuaternion&&t.copyFrom(e.absoluteRotationQuaternion)},t.TransformPoint=function(e,t,n){return void 0===n&&(n=!0),!0===n&&e.computeWorldMatrix(),BABYLON.Vector3.TransformCoordinates(t,e.getWorldMatrix())},t.InverseTransformPoint=function(t,n,i){return void 0===i&&(i=!0),!0===i&&t.computeWorldMatrix(),e.Utilities.TempMatrix.reset(),t.getWorldMatrix().invertToRef(e.Utilities.TempMatrix),BABYLON.Vector3.TransformCoordinates(n,e.Utilities.TempMatrix)},t.TransformPointToRef=function(e,t,n,i){void 0===i&&(i=!0),!0===i&&e.computeWorldMatrix(),BABYLON.Vector3.TransformCoordinatesToRef(t,e.getWorldMatrix(),n)},t.InverseTransformPointToRef=function(t,n,i,r){void 0===r&&(r=!0),!0===r&&t.computeWorldMatrix(),e.Utilities.TempMatrix.reset(),t.getWorldMatrix().invertToRef(e.Utilities.TempMatrix),BABYLON.Vector3.TransformCoordinatesToRef(n,e.Utilities.TempMatrix,i)},t.TransformDirection=function(e,t,n){return void 0===n&&(n=!0),!0===n&&e.computeWorldMatrix(),BABYLON.Vector3.TransformNormal(t,e.getWorldMatrix())},t.InverseTransformDirection=function(t,n,i){return void 0===i&&(i=!0),!0===i&&t.computeWorldMatrix(),e.Utilities.TempMatrix.reset(),t.getWorldMatrix().invertToRef(e.Utilities.TempMatrix),BABYLON.Vector3.TransformNormal(n,e.Utilities.TempMatrix)},t.TransformDirectionToRef=function(e,t,n,i){void 0===i&&(i=!0),!0===i&&e.computeWorldMatrix(),BABYLON.Vector3.TransformNormalToRef(t,e.getWorldMatrix(),n)},t.InverseTransformDirectionToRef=function(t,n,i,r){void 0===r&&(r=!0),!0===r&&t.computeWorldMatrix(),e.Utilities.TempMatrix.reset(),t.getWorldMatrix().invertToRef(e.Utilities.TempMatrix),BABYLON.Vector3.TransformNormalToRef(n,e.Utilities.TempMatrix,i)},t.RecomputeCenterPivotPoint=function(e){var t=e.getBoundingInfo().boundingSphere.center;e.setPivotMatrix(BABYLON.Matrix.Translation(-t.x,-t.y,-t.z))},t.GetDirectionVector=function(e,t){return e.getDirection(t)},t.GetDirectionVectorToRef=function(e,t,n){e.getDirectionToRef(t,n)},t.GetForwardVector=function(e){return e.getDirection(BABYLON.Vector3.Forward())},t.GetForwardVectorToRef=function(e,t){e.getDirectionToRef(BABYLON.Vector3.Forward(),t)},t.GetRightVector=function(e){return e.getDirection(BABYLON.Vector3.Right())},t.GetRightVectorToRef=function(e,t){e.getDirectionToRef(BABYLON.Vector3.Right(),t)},t.GetUpVector=function(e){return e.getDirection(BABYLON.Vector3.Up())},t.GetUpVectorToRef=function(e,t){e.getDirectionToRef(BABYLON.Vector3.Up(),t)},t.BlendFloatValue=function(e,t,n){var i=BABYLON.Scalar.Clamp(n,0,1);return i>0?BABYLON.Scalar.Lerp(e,t,i):e},t.BlendVector2Value=function(e,t,n){var i=BABYLON.Scalar.Clamp(n,0,1);if(i>0){var r=BABYLON.Vector2.Lerp(e,t,i);e.copyFrom(r)}},t.BlendVector3Value=function(e,t,n){var i=BABYLON.Scalar.Clamp(n,0,1);i>0&&BABYLON.Vector3.LerpToRef(e,t,i,e)},t.BlendQuaternionValue=function(e,t,n){var i=BABYLON.Scalar.Clamp(n,0,1);i>0&&BABYLON.Quaternion.SlerpToRef(e,t,i,e)},t.SetAnimationTargetProperty=function(e,t){null!=e&&(e.targetProperty=t,e.targetPropertyPath=e.targetProperty.split("."))},t.SampleAnimationFloat=function(t,n,i,r){void 0===i&&(i=BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE),void 0===r&&(r=!1);var o=0;return null!=t&&t.dataType===BABYLON.Animation.ANIMATIONTYPE_FLOAT&&(null==t._state&&(t._state={key:0,repeatCount:0,loopMode:i,workValue:BABYLON.Matrix.Zero()}),o=e.Utilities.InterpolateAnimation(t,n,t._state,r)),o},t.SampleAnimationVector2=function(t,n,i,r){void 0===i&&(i=BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE),void 0===r&&(r=!1);var o=null;return null!=t&&t.dataType===BABYLON.Animation.ANIMATIONTYPE_VECTOR2&&(null==t._state&&(t._state={key:0,repeatCount:0,loopMode:i,workValue:BABYLON.Matrix.Zero()}),o=e.Utilities.InterpolateAnimation(t,n,t._state,r)),o},t.SampleAnimationVector3=function(t,n,i,r){void 0===i&&(i=BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE),void 0===r&&(r=!1);var o=null;return null!=t&&t.dataType===BABYLON.Animation.ANIMATIONTYPE_VECTOR3&&(null==t._state&&(t._state={key:0,repeatCount:0,loopMode:i,workValue:BABYLON.Matrix.Zero()}),o=e.Utilities.InterpolateAnimation(t,n,t._state,r)),o},t.SampleAnimationQuaternion=function(t,n,i,r){void 0===i&&(i=BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE),void 0===r&&(r=!1);var o=null;return null!=t&&t.dataType===BABYLON.Animation.ANIMATIONTYPE_QUATERNION&&(null==t._state&&(t._state={key:0,repeatCount:0,loopMode:i,workValue:BABYLON.Matrix.Zero()}),o=e.Utilities.InterpolateAnimation(t,n,t._state,r)),o},t.SampleAnimationMatrix=function(t,n,i,r){void 0===i&&(i=BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE),void 0===r&&(r=!1);var o=null;return null!=t&&t.dataType===BABYLON.Animation.ANIMATIONTYPE_MATRIX&&(null==t._state&&(t._state={key:0,repeatCount:0,loopMode:i,workValue:BABYLON.Matrix.Zero()}),o=e.Utilities.InterpolateAnimation(t,n,t._state,r)),o},t.GetLastKeyFrameIndex=function(e){var t=0;if(null!=e){var n=e.getKeys();if(null!=n&&n.length>0){var i=n[n.length-1];null!=i&&(t=i.frame)}}return t},t.InterpolateAnimation=function(t,n,i,r){void 0===r&&(r=!1);var o=!0===r?n*e.SceneManager.AnimationTargetFps:n;return t._interpolate(o,i)},t.UpdateLoopBlendPositionSettings=function(e,t,n){var i=e;null!=i.metadata&&null!=i.metadata.toolkit&&null!=i.metadata.toolkit.settings&&(i.metadata.toolkit.settings.loopblendpositiony=t,i.metadata.toolkit.settings.loopblendpositionxz=n)},t.TakeScreenSnapshot=function(e,t,n,i,r){if(e&&t){var o=e.activeCamera;if(o){var a=t.getRenderWidth(),s=t.getRenderHeight(),l=a,u=s;if(n)if(n.width&&n.height)l=Math.max(1,n.width),u=Math.max(1,n.height);else if(n.width){l=Math.max(1,n.width);var c=s/Math.max(1,a);u=Math.round(l*c)}else if(n.height)u=Math.max(1,n.height),c=a/Math.max(1,s),l=Math.round(u*c);else if(n.precision){var d=Math.max(.05,n.precision);l=Math.round(a*d),u=Math.round(s*d)}BABYLON.CreateScreenshotUsingRenderTarget(t,o,{width:l,height:u},void 0,void 0,void 0,!1,void 0,!1,!1,!0,void 0,void 0,function(e,t,n,o,a,s,l){try{var u=n,c=new Uint8ClampedArray(u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength));if(l)for(var d=4*e,h=Math.floor(t/2),p=new Uint8ClampedArray(d),m=0;m<h;m++){var f=m*d,g=(t-1-m)*d;p.set(c.subarray(f,f+d)),c.copyWithin(f,g,g+d),c.set(p,g)}var v=void 0;if("OffscreenCanvas"in window)v=new OffscreenCanvas(e,t);else{var y=document.createElement("canvas");y.width=e,y.height=t,v=y}var _=v.getContext("2d");if(!_)return void(r&&r(null));var S=_.createImageData(e,t);if(S.data.set(c),_.putImageData(S,0,0),!r)return;v instanceof OffscreenCanvas&&"function"==typeof v.transferToImageBitmap?r(v.transferToImageBitmap()):"function"==typeof createImageBitmap?createImageBitmap(v,i).then(function(e){return r(e)}).catch(function(){return r(null)}):r(null)}catch(e){r&&r(null)}})}else r&&r(null)}else r&&r(null)},t.DownloadImageBitmap=function(e,t,n,i){if(void 0===t&&(t="image.png"),void 0===n&&(n="image/png"),!e)return null;var r=e.width,o=e.height,a="OffscreenCanvas"in window?new OffscreenCanvas(r,o):Object.assign(document.createElement("canvas"),{width:r,height:o});a.getContext("2d").drawImage(e,0,0);var s=function(e){if(e){var n=URL.createObjectURL(e),i=document.createElement("a");i.href=n,i.download=t,i.click(),setTimeout(function(){return URL.revokeObjectURL(n)},2e3)}};return"convertToBlob"in a?a.convertToBlob({type:n,quality:i}).then(s):a.toBlob(s,n,i),a},t.MarkLinear=function(e){e&&(e.gammaSpace=!1)},t.MarkGamma=function(e){e&&(e.gammaSpace=!0)},t.WorldToScreenPoint=function(e,t,n){void 0===n&&(n=null);var i=null,r=null!=n?n.viewport:null!=e.activeCamera?e.activeCamera.viewport:null;return null!=r&&(i=BABYLON.Vector3.Project(t,BABYLON.Matrix.Identity(),e.getTransformMatrix(),r.toGlobal(e.getEngine().getRenderWidth(),e.getEngine().getRenderHeight()))),i},t.ScreenToWorldPoint=function(e,t){return BABYLON.Vector3.Unproject(t,e.getEngine().getRenderWidth(),e.getEngine().getRenderHeight(),BABYLON.Matrix.Identity(),e.getViewMatrix(),e.getProjectionMatrix())},t.LoadTextFile=function(e,t,n,i){return BABYLON.Tools.LoadFile(e,t,n,null,!1,i)},t.LoadTextFileAsync=function(e){return BABYLON.Tools.LoadFileAsync(e,!1)},t.GetHttpRequest=function(e,t,n,i,r,o,a){void 0===t&&(t=null),void 0===n&&(n=null),void 0===i&&(i=null),void 0===r&&(r=null),void 0===o&&(o=!1),void 0===a&&(a=null);var s=new XMLHttpRequest;return s.open("GET",e,!0),!0===o&&(s.responseType="arraybuffer"),null!=a&&s.overrideMimeType(a),null!=t&&t.forEach(function(e){null!=e&&null!=e.name&&""!==e.name&&s.setRequestHeader(e.name,e.value)}),s.onreadystatechange=function(){s.readyState===XMLHttpRequest.DONE&&null!=n&&n(s)},s.onprogress=function(e){null!=r&&r(e)},s.onerror=function(){null!=i&&i("Failed to get data from server.")},s.onabort=function(){null!=i&&i("Aborted get data from server.")},s.send(null),s},t.GetHttpRequestAsync=function(t,n,i,r,o){return void 0===n&&(n=null),void 0===i&&(i=null),void 0===r&&(r=!1),void 0===o&&(o=null),new Promise(function(a,s){e.Utilities.GetHttpRequest(t,n,function(e){a(e)},function(e){s(e)},i,r,o)})},t.PostHttpRequest=function(e,t,n,i,r,o,a,s,l){void 0===n&&(n=null),void 0===i&&(i="application/x-www-form-urlencoded"),void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=!1),void 0===l&&(l=null);var u=new XMLHttpRequest;return u.open("POST",e,!0),!0===s&&(u.responseType="arraybuffer"),null!=l&&u.overrideMimeType(l),null!=n&&n.forEach(function(e){null!=e&&null!=e.name&&""!==e.name&&u.setRequestHeader(e.name,e.value)}),u.setRequestHeader("Content-Type",i),u.onreadystatechange=function(){u.readyState===XMLHttpRequest.DONE&&null!=r&&r(u)},u.onprogress=function(e){null!=a&&a(e)},u.onerror=function(){null!=o&&o("Failed to post data to server.")},u.onabort=function(){null!=o&&o("Aborted post data to server.")},u.send(t),u},t.PostHttpRequestAsync=function(t,n,i,r,o,a,s){return void 0===i&&(i=null),void 0===r&&(r="application/x-www-form-urlencoded"),void 0===o&&(o=null),void 0===a&&(a=!1),void 0===s&&(s=null),new Promise(function(l,u){e.Utilities.PostHttpRequest(t,n,i,r,function(e){l(e)},function(e){u(e)},o,a,s)})},t.RemapValueToRange=function(e,t,n,i,r){return i+(e-t)*(r-i)/(n-t)},t.CloneSkeletonPrefab=function(e,t,n,i,r){void 0===r&&(r=null);var o=new BABYLON.Skeleton(n,i||n,e);o.needInitialSkinMatrix=t.needInitialSkinMatrix;for(var a=0;a<t.bones.length;a++){var s=t.bones[a],l=null,u=s.getParent();if(u){var c=t.bones.indexOf(u);l=o.bones[c]}var d=new BABYLON.Bone(s.name,o,l,s.getBaseMatrix().clone(),s.getRestPose().clone());d._index=s._index,d.metadata=s.metadata,s._linkedTransformNode&&d.linkTransformNode(s._linkedTransformNode),BABYLON.DeepCopier.DeepCopy(s.animations,d.animations)}var h=o,p=t;if(p._ranges)for(var m in h._ranges={},p._ranges){var f=p._ranges[m];f&&(h._ranges[m]=f.clone())}return p._isDirty=!0,o},t.GetSceneTransforms=function(e){var t=null;return null!=e.transformNodes&&e.transformNodes.length>0&&e.transformNodes.forEach(function(e){null!=e.metadata&&null!=e.metadata.toolkit&&null!=e.metadata.toolkit.prefab&&!1===e.metadata.toolkit.prefab&&(null==t&&(t=[]),t.push(e))}),null!=e.meshes&&e.meshes.length>0&&e.meshes.forEach(function(e){null!=e.metadata&&null!=e.metadata.toolkit&&null!=e.metadata.toolkit.prefab&&!1===e.metadata.toolkit.prefab&&(null==t&&(t=[]),t.push(e))}),t},t.PostParseSceneComponents=function(t,n,i,r){var o=new e.MetadataParser(t);return null!=n&&n.length>0&&(n.forEach(function(e){o.parseSceneComponents(e)}),o.postProcessSceneComponents(i,r)),o},t.GetDefaultReflectionTexture=function(e){if(!e._DefaultCube){var t=document.createElement("canvas");t.width=t.height=1;var n=t.getContext("2d");n.fillStyle="rgba(128,128,128,1)",n.fillRect(0,0,1,1);var i=t.toDataURL("image/png"),r=[i,i,i,i,i,i],o=BABYLON.CubeTexture.CreateFromImages(r,e,!0);o.name="DefaultReflection",o.gammaSpace=!1,o.coordinatesMode=BABYLON.Texture.CUBIC_MODE,o.level=.1,e._DefaultCube=o}return e._DefaultCube},t.GetNeutralReflectionTexture=function(e,t,n){void 0===t&&(t=128),void 0===n&&(n=.4);var i="_NeutralCube_".concat(t,"_").concat(n);if(!e[i]){var r=document.createElement("canvas");r.width=r.height=1;var o=r.getContext("2d");o.fillStyle="rgba(".concat(t,",").concat(t,",").concat(t,",1)"),o.fillRect(0,0,1,1);var a=r.toDataURL("image/png"),s=[a,a,a,a,a,a],l=BABYLON.CubeTexture.CreateFromImages(s,e,!0);l.name="NeutralReflection",l.gammaSpace=!1,l.coordinatesMode=BABYLON.Texture.CUBIC_MODE,l.level=n,e[i]=l}return e[i]},t.GetAssetContainerMesh=function(e,t){var n=null,i=t.toLowerCase();if(null==n&&null!=e.meshes&&e.meshes.length>0)for(var r=0;r<e.meshes.length;r++){var o=e.meshes[r];if(o instanceof BABYLON.Mesh&&o.name.toLowerCase()===i){n=o;break}}return n},t.GetAssetContainerNode=function(e,t){var n=null,i=t.toLowerCase();if(null==n&&null!=e.transformNodes&&e.transformNodes.length>0)for(var r=0;r<e.transformNodes.length;r++){var o=e.transformNodes[r];if(o.name.toLowerCase()===i){n=o;break}}return n},t.CloneAssetContainerItem=function(t,n,i,r,o,a){void 0===r&&(r=null),void 0===o&&(o=!1),void 0===a&&(a=!0);var s=null,l={},u={},c={},d=null,h=null,p=[],m=[],f=n.toLowerCase(),g=null,v=function(t,n){null==g&&(g=n),l[t.uniqueId]=n.uniqueId,u[n.uniqueId]=n,i&&(n.name=i(t.name)),null!=t.metadata&&null!=t.metadata.toolkit&&null!=t.metadata.toolkit.entity&&(n.metadata=e.Utilities.CloneEntityMetadata(t.metadata));var r=null!=n.metadata&&null!=n.metadata.toolkit&&null!=n.metadata.toolkit.animator?n.metadata.toolkit.animator:null;if(null!=r&&""!==r&&(null==d&&(d=[]),d.indexOf(r)<0&&d.push(r),n.metadata.toolkit.animator=e.Utilities.CreateGuid(),c[r]=n.metadata.toolkit.animator),t instanceof BABYLON.AbstractMesh&&null!=t.skeleton&&(null==h&&(h=[]),h.indexOf(t.skeleton)<0&&h.push(t.skeleton)),n instanceof BABYLON.Mesh){var o=n;if(o.morphTargetManager){var a=t.morphTargetManager;o.morphTargetManager=a.clone();for(var s=0;s<a.numTargets;s++){var p=a.getTarget(s),m=o.morphTargetManager.getTarget(s);l[p.uniqueId]=m.uniqueId,u[m.uniqueId]=m}}}};if(null==s&&null!=t.transformNodes&&t.transformNodes.length>0)for(var y=0;y<t.transformNodes.length;y++){var _=t.transformNodes[y];if(_.name.toLowerCase()===f){var S=e.Utilities.InstantiateHierarchy(_,r,function(e,t){v(e,t)});if(S){s=S;break}}}if(null==s&&null!=t.meshes&&t.meshes.length>0){var A=function(n){var a=t.meshes[n];if(a.name.toLowerCase()===f){var c=e.Utilities.InstantiateHierarchy(a,r,function(e,n){v(e,n);var r=n;if(!0===a.isWorldMatrixFrozen&&r.freezeWorldMatrix&&r.freezeWorldMatrix(),n.material&&r.material)if(!0===o){var s=e.material;if(-1===m.indexOf(s)){var c=s.clone(i?i(s.name):"Clone of "+s.name);if(!0===s.isFrozen&&c.freeze&&c.freeze(),m.push(s),l[s.uniqueId]=c.uniqueId,u[c.uniqueId]=c,"MultiMaterial"===s.getClassName())for(var d=0,h=s.subMaterials;d<h.length;d++){var p=h[d];p&&(c=p.clone(i?i(p.name):"Clone of "+p.name),!0===p.isFrozen&&c.freeze&&c.freeze(),m.push(p),l[p.uniqueId]=c.uniqueId,u[c.uniqueId]=c)}}r.material=u[l[s.uniqueId]]}else"MultiMaterial"===r.material.getClassName()?-1===t.scene.multiMaterials.indexOf(r.material)&&t.scene.addMultiMaterial(r.material):-1===t.scene.materials.indexOf(r.material)&&t.scene.addMaterial(r.material)});if(c)return s=c,"break"}};for(y=0;y<t.meshes.length&&"break"!==A(y);y++);}if(null!=h&&h.length>0&&h.forEach(function(n){for(var r=i?i(n.name):"Clone of "+n.name,o=e.Utilities.CloneSkeletonPrefab(t.scene,n,r,r,g),a=0,s=t.meshes;a<s.length;a++){var c=s[a];if(c.skeleton===n&&!c.isAnInstance){if(u[l[c.uniqueId]].skeleton=o,-1!==p.indexOf(o))continue;p.push(o);for(var d=0,h=o.bones;d<h.length;d++){var m=h[d];m._linkedTransformNode&&(m._linkedTransformNode=u[l[m._linkedTransformNode.uniqueId]])}}}}),!0===a){var b=null;t.animationGroups.forEach(function(e){var t=e,n=null!=t.metadata&&null!=t.metadata.toolkit&&null!=t.metadata.toolkit.source&&""!==t.metadata.toolkit.source?t.metadata.toolkit.source:null;if(null!=n&&""!==n&&null!=d&&d.indexOf(n)>=0){var i=e.clone(e.name,function(e){return u[l[e.uniqueId]]||e}),r=c[n]||n;null!=t.metadata&&(i.metadata={},i.metadata.toolkit={},i.metadata.toolkit.id=t.metadata.toolkit.id,i.metadata.toolkit.clip=t.metadata.toolkit.clip,i.metadata.toolkit.source=r,i.metadata.toolkit.legacy=t.metadata.toolkit.legacy,i.metadata.toolkit.length=t.metadata.toolkit.length,i.metadata.toolkit.looping=t.metadata.toolkit.looping,i.metadata.toolkit.settings=t.metadata.toolkit.settings,i.metadata.toolkit.behavior=t.metadata.toolkit.behavior,i.metadata.toolkit.wrapmode=t.metadata.toolkit.wrapmode,i.metadata.toolkit.framerate=t.metadata.toolkit.framerate,i.metadata.toolkit.humanmotion=t.metadata.toolkit.humanmotion,i.metadata.toolkit.averagespeed=t.metadata.toolkit.averagespeed,i.metadata.toolkit.averageduration=t.metadata.toolkit.averageduration,i.metadata.toolkit.averageangularspeed=t.metadata.toolkit.averageangularspeed),null==b&&(b=[]),b.push(i)}}),null!=s&&null!=b&&e.Utilities.AssignAnimationGroupsToInstance(s,b)}return s},t.AssignAnimationGroupsToInstance=function(t,n){e.Utilities.AssignAnimationGroupsToNode(t,n);var i=t.getChildren(null,!1);null!=i&&i.length>0&&i.forEach(function(t){e.Utilities.AssignAnimationGroupsToNode(t,n)})},t.AssignAnimationGroupsToNode=function(t,n){if(null!=t&&null!=t.metadata&&t.metadata.toolkit){var i=t.metadata.toolkit;if(null!=i.components&&i.components.length>0)for(var r=0;r<i.components.length;r++){var o=i.components[r].klass;if(null!=o&&""!==o){if(!0===e.SceneManager.AutoStripNamespacePrefix&&!1===e.SceneManager.UniversalModuleDefinition){var a=o.lastIndexOf(".");-1!==a&&(o=o.substring(a+1))}"TOOLKIT.AnimationState"===o&&(t.metadata.toolkit.sourceAnimationGroups=n)}}}},t.UnitySlopeAngleToCosine=function(e){return Math.cos(e*Math.PI/180)},t.InstantiateHierarchy=function(t,n,i){if(void 0===n&&(n=null),t instanceof BABYLON.Mesh){var r=null!=t.metadata&&null!=t.metadata.toolkit&&null!=t.metadata.toolkit.instance&&!0===t.metadata.toolkit.instance;return e.Utilities.InstantiateMeshHierarchy(t,n,r,i)}return e.Utilities.InstantiateNodeHierarchy(t,n,i)},t.InstantiateNodeHierarchy=function(t,n,i){void 0===n&&(n=null);var r=t.clone("Clone of "+(t.name||t.id),n,!0);r&&i&&i(t,r);for(var o=0,a=t.getChildTransformNodes(!0);o<a.length;o++){var s=a[o];e.Utilities.InstantiateHierarchy(s,r,i)}return r},t.InstantiateMeshHierarchy=function(t,n,i,r){void 0===n&&(n=null);var o=t.getTotalVertices()>0&&!0===i?t.createInstance("Instance of "+(t.name||t.id)):t.clone("Clone of "+(t.name||t.id),n||t.parent,!0);o&&(o.parent=n,o.position=t.position.clone(),o.scaling=t.scaling.clone(),t.rotationQuaternion?o.rotationQuaternion=t.rotationQuaternion.clone():o.rotation=t.rotation.clone(),r&&r(t,o));for(var a=0,s=t.getChildTransformNodes(!0);a<s.length;a++){var l=s[a];e.Utilities.InstantiateHierarchy(l,o,r)}return o},t.PrepareSkeletonForRendering=function(e,t){void 0===t&&(t=!1),null!=e&&e.prepare(t)},t.RetargetAnimationGroupSkeleton=function(e,t,n){void 0===n&&(n=null),null!=e&&null!=t&&e.targetedAnimations.forEach(function(e,i){if(null!=e.target&&null!=e.target.name){var r=t.bones.filter(function(t){return t.name.toLowerCase()===e.target.name.toLowerCase()})[0];null!=r?null!=r.getTransformNode()&&(e.target=r.getTransformNode()):"Armature"===e.target.name&&null!=n?e.target=n:console.warn("Failed to locate matching animation cloning target: "+e.target.name)}})},t.RetargetAnimationGroupBlendShapes=function(e,t){null!=e&&null!=t&&e.targetedAnimations.forEach(function(e,t){null!=e.target&&e.target.name})},t.LinkSkeletonMeshes=function(t,n){if(null!=t&&null!=t.bones&&t.bones.length>0&&null!=n&&null!=n.bones&&n.bones.length>0)for(var i=n.bones.length,r=0;r<i;r++){var o=n.bones[r];if(null!=o){var a=e.Utilities.FindBoneByName(t,o.name);null!=a?o._linkedTransformNode=a._linkedTransformNode:console.warn("Failed to locate bone on mater rig: "+o.name)}}},t.FindBoneByName=function(e,t){var n=null;if(null!=e&&null!=e.bones)for(var i=0;i<e.bones.length;i++){var r=e.bones[i];if(r.name.toLowerCase().replace("mixamo:","").replace("left_","left").replace("right_","right")===t.toLowerCase().replace("mixamo:","").replace("left_","left").replace("right_","right")){n=r;break}}return n},t.SwitchHandednessVector3=function(e){return new BABYLON.Vector3(e.x,e.y,-e.z)},t.SwitchHandednessVector4=function(e){return new BABYLON.Vector4(e.x,e.y,-e.z,-e.w)},t.SwitchHandednessQuaternion=function(e){return new BABYLON.Quaternion(e.x,e.y,-e.z,-e.w)},t.ComputeBlendingSpeed=function(e,t,n){void 0===n&&(n=!1);var i=1/(e*t);return!0===n&&(i*=.5),i},t.CalculateCameraDistance=function(e,t,n){return void 0===n&&(n=1),Math.round(e*n*t*1)},t.EvalSphericalPolynomialRGB=function(e,t){var n=t.x,i=t.y,r=t.z,o=e.x.x*n+e.y.x*i+e.z.x*r+e.xx.x*n*n+e.yy.x*i*i+e.zz.x*r*r+e.xy.x*n*i+e.yz.x*i*r+e.zx.x*r*n,a=e.x.y*n+e.y.y*i+e.z.y*r+e.xx.y*n*n+e.yy.y*i*i+e.zz.y*r*r+e.xy.y*n*i+e.yz.y*i*r+e.zx.y*r*n,s=e.x.z*n+e.y.z*i+e.z.z*r+e.xx.z*n*n+e.yy.z*i*i+e.zz.z*r*r+e.xy.z*n*i+e.yz.z*i*r+e.zx.z*r*n;return new BABYLON.Color3(o,a,s)},t.BestFitScale=function(e,t){for(var n=0,i=0,r=0;r<e.length;r++){var o=e[r],a=t[r];n+=a*o,i+=a*a}return i>1e-12?n/i:1},t.ComputeSHEval6Fit=function(e,t){if(!Array.isArray(t)||18!==t.length)throw new Error("unityEval6 must be an array of 18 floats (6 dirs * RGB)");for(var n=[new BABYLON.Vector3(1,0,0),new BABYLON.Vector3(-1,0,0),new BABYLON.Vector3(0,1,0),new BABYLON.Vector3(0,-1,0),new BABYLON.Vector3(0,0,1),new BABYLON.Vector3(0,0,-1)],i=[],r=0;r<n.length;r++){var o=this.EvalSphericalPolynomialRGB(e,n[r]);i.push(o.r,o.g,o.b)}for(var a=t.slice(0),s=this.BestFitScale(a,i),l=0,u=[0,0,0],c=a.length,d=0;d<c;d++){var h=a[d]-s*i[d];l+=h*h,u[d%3]+=h*h}var p=Math.sqrt(l/c),m=u.map(function(e){return Math.sqrt(e/(c/3))}),f=[];for(r=0;r<n.length;r++)f.push({dir:n[r],unity:new BABYLON.Color3(a[3*r+0],a[3*r+1],a[3*r+2]),bab:new BABYLON.Color3(i[3*r+0],i[3*r+1],i[3*r+2]),scaledBab:new BABYLON.Color3(s*i[3*r+0],s*i[3*r+1],s*i[3*r+2]),diff:new BABYLON.Color3(a[3*r+0]-s*i[3*r+0],a[3*r+1]-s*i[3*r+1],a[3*r+2]-s*i[3*r+2])});return{scale:s,rmse:p,perChannelRMSE:m,perDir:f}},t.InstantiateClass=function(t){try{var n=e.SceneManager.GetClass(t);if(n)return n;var i=t.split("."),r=void 0;if("undefined"!=typeof window)r=window;else if("undefined"!=typeof globalThis)r=globalThis;else{if(void 0===globalThis.global)throw new Error("No global object available");r=globalThis.global}for(var o=0;o<i.length;o++)if(!(r=r[i[o]]))throw new Error("Class not found: ".concat(t));return"function"==typeof r?r:null}catch(e){return console.error("Failed to resolve class: ".concat(t),e),null}},t.GetSimpleClassName=function(e){if(e&&e.constructor&&e.constructor.toString){var t=e.constructor.toString().match(/function\s*(\w+)/);if(t&&2==t.length)return t[1]}},t.DisposeEntity=function(t){if(null!=t){if(null!=t.metadata&&t.metadata.toolkit){var n=t.metadata.toolkit;null!=n.components&&n.components.length>0&&n.components.forEach(function(t){if(null!=t.instance){try{e.SceneManager.DestroyScriptComponent(t.instance)}catch(e){}t.instance=null}}),delete t.metadata.toolkit}if(null!=t.metadata&&t.metadata.mixer&&delete t.metadata.mixer,null!=t.metadata&&null!=t.metadata.clone&&delete t.metadata.clone,null!=t.physicsImpostor){var i=t.physicsImpostor;null!=i.onCollideEvent&&(i.onCollideEvent=null),null!=i.tmpCollisionObjects&&delete i.tmpCollisionObjects,null!=t.physicsImpostor.physicsBody&&(null!=t.physicsImpostor.physicsBody.entity&&delete t.physicsImpostor.physicsBody.entity,null!=t.physicsImpostor.physicsBody.triangleMapInfo&&delete t.physicsImpostor.physicsBody.triangleMapInfo),t.physicsImpostor.dispose(),t.physicsImpostor=null}null!=t.skeleton&&(null!=t.skeleton._sockets&&delete t.skeleton._sockets,null!=t.skeleton.bones&&t.skeleton.bones.length>0&&t.skeleton.bones.forEach(function(e){null!=e&&null!=e.metadata&&(e.metadata=null)})),null!=t.cameraRig&&(t.cameraRig.dispose&&t.cameraRig.dispose(),delete t.cameraRig),null!=t.lightRig&&(t.lightRig.dispose&&t.lightRig.dispose(),delete t.lightRig),null!=t.shadowBox&&(t.shadowBox.dispose&&t.shadowBox.dispose(),delete t.shadowBox),null!=t._debugCollider&&(t._debugCollider.dispose&&t._debugCollider.dispose(),delete t._debugCollider),null!=t._meshCollider&&(t._meshCollider=null),null!=t._colliderType&&delete t._colliderType,null!=t._skinnedMesh&&delete t._skinnedMesh}},t.SearchTransformNodes=function(t,n,i){void 0===i&&(i=e.SearchType.ExactMatch);var r=null,o=null!=i?i:e.SearchType.ExactMatch;if(null!=n&&n.length>0)for(var a=0;a<n.length;a++){var s=n[a];if(o===e.SearchType.ExactMatch){if(s.name===t){r=s;break}}else if(o===e.SearchType.StartsWith){if(e.Utilities.StartsWith(s.name,t)){r=s;break}}else if(o===e.SearchType.EndsWith){if(e.Utilities.EndsWith(s.name,t)){r=s;break}}else if(o===e.SearchType.IndexOf){if(s.name.indexOf(t)>=0){r=s;break}}else if(s.name===t){r=s;break}}return r},t.SearchTransformNodeForTags=function(e,t){var n=null;if(null!=t&&t.length>0)for(var i=0;i<t.length;i++){var r=t[i];if(r instanceof BABYLON.TransformNode&&BABYLON.Tags.MatchesQuery(r,e)){n=r;break}}return n},t.SearchAllTransformNodesForTags=function(e,t){var n=null;if(null!=t&&t.length>0)for(var i=0;i<t.length;i++){var r=t[i];r instanceof BABYLON.TransformNode&&BABYLON.Tags.MatchesQuery(r,e)&&(null==n&&(n=[]),n.push(r))}return n},t.SearchTransformNodeForScript=function(t,n){var i=null;if(null!=n&&n.length>0)for(var r=0;r<n.length;r++){var o=n[r];if(o instanceof BABYLON.TransformNode&&null!=e.SceneManager.FindScriptComponent(o,t)){i=o;break}}return i},t.SearchAllTransformNodesForScript=function(t,n){var i=null;if(null!=n&&n.length>0)for(var r=0;r<n.length;r++){var o=n[r];o instanceof BABYLON.TransformNode&&null!=e.SceneManager.FindScriptComponent(o,t)&&(null==i&&(i=[]),i.push(o))}return i},t.CreateGuid=function(t){void 0===t&&(t=null);var n=BABYLON.Tools.RandomId();return e.Utilities.IsNullOrEmpty(t)||(n+="-"+t),n},t.ValidateTransformGuid=function(e){if(null!=e&&null!=e.metadata&&null!=e.metadata.toolkit&&null!=e.metadata.toolkit.guid&&""!==e.metadata.toolkit.guid){var t=e.metadata.toolkit.guid;e.id!==t&&(e.id=t),delete e.metadata.toolkit.guid}},t.RegisterInstancedMeshBuffers=function(e){var t=null!=e.metadata&&null!=e.metadata.toolkit&&null!=e.metadata.toolkit.buffers?e.metadata.toolkit.buffers:null;null!=t&&(null!=t.floats&&t.floats.length>0&&t.floats.forEach(function(t){null!=t.kind&&""!==t.kind&&null!=t.value&&(e.registerInstancedBuffer(t.kind,1),e.instancedBuffers[t.kind]=t.value)}),null!=t.colors&&t.colors.length>0&&t.colors.forEach(function(t){null!=t.kind&&""!==t.kind&&null!=t.value&&(e.registerInstancedBuffer(t.kind,4),e.instancedBuffers[t.kind]=new BABYLON.Color4(t.value.r||0,t.value.g||0,t.value.b||0,t.value.a||1).toLinearSpace())}),null!=t.vector2&&t.vector2.length>0&&t.vector2.forEach(function(t){null!=t.kind&&""!==t.kind&&null!=t.value&&(e.registerInstancedBuffer(t.kind,2),e.instancedBuffers[t.kind]=new BABYLON.Vector2(t.value.x||0,t.value.y||0))}),null!=t.vector3&&t.vector3.length>0&&t.vector3.forEach(function(t){null!=t.kind&&""!==t.kind&&null!=t.value&&(e.registerInstancedBuffer(t.kind,3),e.instancedBuffers[t.kind]=new BABYLON.Vector3(t.value.x||0,t.value.y||0,t.value.z||0))}),null!=t.vector4&&t.vector4.length>0&&t.vector4.forEach(function(t){null!=t.kind&&""!==t.kind&&null!=t.value&&(e.registerInstancedBuffer(t.kind,4),e.instancedBuffers[t.kind]=new BABYLON.Vector4(t.value.x||0,t.value.y||0,t.value.z||0,t.value.w||0))}))},t.CloneValue=function(e,t){return e?e instanceof BABYLON.Mesh?null:e instanceof BABYLON.SubMesh?e.clone(t):e.clone?e.clone():e:null},t.CloneEntityMetadata=function(t){var n=null;if(null!=t){var i=null;if(null!=t.toolkit){var r=null!=t.toolkit.instance&&t.toolkit.instance,o=null==t.toolkit.visible||t.toolkit.visible,a=null!=t.toolkit.visibility?t.toolkit.visibility:1,s=null!=t.toolkit.billboard?t.toolkit.billboard:0,l=null!=t.toolkit.tags?t.toolkit.tags:"Untagged Layer0",u=null!=t.toolkit.skin&&t.toolkit.skin,c=null!=t.toolkit.bone?t.toolkit.bone:null,d=null!=t.toolkit.rootbone&&t.toolkit.rootbone,h=null!=t.toolkit.rootpos?t.toolkit.rootpos:null,p=null!=t.toolkit.rootrot?t.toolkit.rootrot:null,m=null!=t.toolkit.group?t.toolkit.group:"Untagged",f=null!=t.toolkit.layer?t.toolkit.layer:0,g=null!=t.toolkit.layername?t.toolkit.layername:"Default",v=null!=t.toolkit.navigation?t.toolkit.navigation:null,y=null!=t.toolkit.lightmapped&&t.toolkit.lightmapped,_=null!=t.toolkit.lightmapuvs?t.toolkit.lightmapuvs:null,S=null!=t.toolkit.animator?t.toolkit.animator:null,A=null,b=null,M=null,B=null;t.toolkit.physics&&(A={},e.Utilities.DeepCopyProperties(t.toolkit.physics,A)),t.toolkit.renderer&&(b={},e.Utilities.DeepCopyProperties(t.toolkit.renderer,b)),t.toolkit.collision&&(M={},e.Utilities.DeepCopyProperties(t.toolkit.collision,M)),t.toolkit.properties&&(B={},e.Utilities.DeepCopyProperties(t.toolkit.properties,B));var C=null;null!=t.toolkit.wheels&&t.toolkit.wheels.length>0&&(C=[],t.toolkit.wheels.forEach(function(t){if(null!=t){var n={};e.Utilities.DeepCopyProperties(t,n),C.push(n)}}));var T=null;null!=t.toolkit.components&&t.toolkit.components.length>0&&(T=[],t.toolkit.components.forEach(function(t){if(null!=t){var n=e.Utilities.FastJsonCopy(t);n.instance=null,T.push(n)}})),(i={}).parsed=!1,i.prefab=!1,i.buffers=null,i.lods=null,i.coverages=null,i.distances=null,i.handlers=null,i.instance=r,i.visible=o,i.visibility=a,i.billboard=s,i.tags=l,i.skin=u,i.bone=c,i.rootbone=d,i.rootpos=h,i.rootrot=p,i.group=m,i.layer=f,i.layername=g,i.navigation=v,i.lightmapped=y,i.lightmapuvs=_,i.animator=S,i.renderer=b,i.physics=A,i.wheels=C,i.collision=M,i.properties=B,i.components=T}null!=i&&(n={toolkit:i})}return n},t.FastJsonCopy=function(t){if(!t)return t;if(Array.isArray(t)){for(var n=[],i=t.length,r=0;r<i;r++)n.push(e.Utilities.FastJsonCopy(t[r]));return n}if("object"==typeof t){var o=Object.keys(t),a={};for(r=o.length-1;r>-1;r--){var s=o[r];a[s]=e.Utilities.FastJsonCopy(t[s])}return a}return t},t.DeepCopyProperties=function(t,n,i,r){for(var o in t)if(("_"!==o[0]||r&&-1!==r.indexOf(o))&&(!i||-1===i.indexOf(o))){var a=t[o],s=typeof a;if("function"!==s)if("object"===s)if(a instanceof Array){if(n[o]=[],a.length>0)if("object"==typeof a[0])for(var l=0;l<a.length;l++){var u=e.Utilities.CloneValue(a[l],n);-1===n[o].indexOf(u)&&n[o].push(u)}else n[o]=a.slice(0)}else n[o]=e.Utilities.CloneValue(a,n);else n[o]=a}},t.ValidateTransformMetadata=function(t){null==t.metadata&&(t.metadata={}),null==t.metadata.toolkit&&(t.metadata.toolkit={});var n=t.metadata.toolkit;e.Utilities.HasOwnProperty(n,"entity")||(t.metadata.toolkit.entity=!0),e.Utilities.HasOwnProperty(n,"parsed")||(t.metadata.toolkit.parsed=!1),e.Utilities.HasOwnProperty(n,"prefab")||(t.metadata.toolkit.prefab=!1),e.Utilities.HasOwnProperty(n,"instance")||(t.metadata.toolkit.instance=!1),e.Utilities.HasOwnProperty(n,"buffers")||(t.metadata.toolkit.buffers=null),e.Utilities.HasOwnProperty(n,"visible")||(t.metadata.toolkit.visible=!0),e.Utilities.HasOwnProperty(n,"visibility")||(t.metadata.toolkit.visibility=1),e.Utilities.HasOwnProperty(n,"billboard")||(t.metadata.toolkit.billboard=0),e.Utilities.HasOwnProperty(n,"tags")||(t.metadata.toolkit.tags="Untagged Layer0"),e.Utilities.HasOwnProperty(n,"skin")||(t.metadata.toolkit.skin=!1),e.Utilities.HasOwnProperty(n,"bone")||(t.metadata.toolkit.bone=null),e.Utilities.HasOwnProperty(n,"rootbone")||(t.metadata.toolkit.rootbone=!1),e.Utilities.HasOwnProperty(n,"rootpos")||(t.metadata.toolkit.rootpos=null),e.Utilities.HasOwnProperty(n,"rootrot")||(t.metadata.toolkit.rootrot=null),e.Utilities.HasOwnProperty(n,"group")||(t.metadata.toolkit.group="Untagged"),e.Utilities.HasOwnProperty(n,"layer")||(t.metadata.toolkit.layer=0),e.Utilities.HasOwnProperty(n,"layername")||(t.metadata.toolkit.layername="Default"),e.Utilities.HasOwnProperty(n,"navigation")||(t.metadata.toolkit.navigation=null),e.Utilities.HasOwnProperty(n,"lightmapped")||(t.metadata.toolkit.lightmapped=!1),e.Utilities.HasOwnProperty(n,"lightmapuvs")||(t.metadata.toolkit.lightmapuvs=!1),e.Utilities.HasOwnProperty(n,"animator")||(t.metadata.toolkit.animator=null),e.Utilities.HasOwnProperty(n,"lods")||(t.metadata.toolkit.lods=null),e.Utilities.HasOwnProperty(n,"coverages")||(t.metadata.toolkit.coverages=null),e.Utilities.HasOwnProperty(n,"distances")||(t.metadata.toolkit.distances=null),e.Utilities.HasOwnProperty(n,"handlers")||(t.metadata.toolkit.handlers=null),e.Utilities.HasOwnProperty(n,"physics")||(t.metadata.toolkit.physics=null),e.Utilities.HasOwnProperty(n,"wheels")||(t.metadata.toolkit.wheels=null),e.Utilities.HasOwnProperty(n,"renderer")||(t.metadata.toolkit.renderer=null),e.Utilities.HasOwnProperty(n,"collision")||(t.metadata.toolkit.collision=null),e.Utilities.HasOwnProperty(n,"properties")||(t.metadata.toolkit.properties=null),e.Utilities.HasOwnProperty(n,"components")||(t.metadata.toolkit.components=null)},t.UpVector=BABYLON.Vector3.Up(),t.AuxVector=BABYLON.Vector3.Zero(),t.ZeroVector=BABYLON.Vector3.Zero(),t.TempMatrix=BABYLON.Matrix.Zero(),t.TempMatrix2=BABYLON.Matrix.Zero(),t.TempVector2=BABYLON.Vector2.Zero(),t.TempVector3=BABYLON.Vector3.Zero(),t.TempQuaternion=BABYLON.Quaternion.Zero(),t.TempQuaternion2=BABYLON.Quaternion.Zero(),t.TempQuaternion3=BABYLON.Quaternion.Zero(),t.TempDirectionBuffer=BABYLON.Vector3.Zero(),t.LoadingState=-1,t.OnPreloaderProgress=null,t.OnPreloaderComplete=null,t.LoaderItemsMarkedForDisposal=[],t}();e.Utilities=t}(i||(i={})),function(e){var t=function(t){function n(n,i){var r=t.call(this,n,i)||this;return r.terrainInfo=null,r.shader=r.getShaderName(),r.plugin=new e.UniversalTerrainMaterialPlugin(r,r.shader),r}return r(n,t),n.prototype.awake=function(){},n.prototype.update=function(){},n.prototype.getShaderName=function(){return"UniversalTerrainMaterial"},n.prototype.getTerrainInfo=function(){return this.terrainInfo},n}(e.CustomShaderMaterial);e.UniversalTerrainMaterial=t;var n=function(t){function n(e,n){var i=t.call(this,e,n,100,{UNIVERSALTERRAINMATERIAL:!1},!0,!0,!1)||this;return i.colorName="surfaceAlbedo",i.splatmapSampler="splatmapSampler",i.detailsSampler="detailsSampler",i.normalsSampler="normalsSampler",i.GLSL_CustomFragment=null,i.GLSL_CustomVertex=null,i.GLSL_VertexMainEnd=null,i.GLSL_FragmentUpdateColor=null,i.WGSL_CustomFragment=null,i.WGSL_CustomVertex=null,i.WGSL_VertexMainEnd=null,i.WGSL_FragmentUpdateColor=null,i}return r(n,t),n.prototype.isCompatible=function(e){return e===BABYLON.ShaderLanguage.WGSL||e===BABYLON.ShaderLanguage.GLSL},n.prototype.getClassName=function(){return"UniversalTerrainMaterialPlugin"},n.prototype.getCustomCode=function(t,n){var i=this.getCustomShaderMaterial().getTerrainInfo();if("vertex"===t){if(n===BABYLON.ShaderLanguage.WGSL)return null==this.WGSL_CustomVertex&&(this.WGSL_CustomVertex=this.WGSL_FormatTerrainVertexDefintions(i)),null==this.WGSL_VertexMainEnd&&(this.WGSL_VertexMainEnd=this.WGSL_FormatTerrainVertexMainEnd(i)),{CUSTOM_VERTEX_DEFINITIONS:this.WGSL_CustomVertex,CUSTOM_VERTEX_MAIN_END:this.WGSL_VertexMainEnd};if(n===BABYLON.ShaderLanguage.GLSL)return null==this.GLSL_CustomVertex&&(this.GLSL_CustomVertex=this.GLSL_FormatTerrainVertexDefintions(i)),null==this.GLSL_VertexMainEnd&&(this.GLSL_VertexMainEnd=this.GLSL_FormatTerrainVertexMainEnd(i)),{CUSTOM_VERTEX_DEFINITIONS:this.GLSL_CustomVertex,CUSTOM_VERTEX_MAIN_END:this.GLSL_VertexMainEnd}}else if("fragment"===t){if(n===BABYLON.ShaderLanguage.WGSL)return null==this.WGSL_CustomFragment&&(this.WGSL_CustomFragment=this.WGSL_FormatTerrainFragmentDefintions(i,this.splatmapSampler,this.detailsSampler,this.normalsSampler)),null==this.WGSL_FragmentUpdateColor&&(this.WGSL_FragmentUpdateColor=this.WGSL_FormatTerrainFragmentUpdateColor(i,this.colorName,this.splatmapSampler,this.detailsSampler,this.normalsSampler,e.SceneManager.TerrainColorCorrection)),{CUSTOM_FRAGMENT_DEFINITIONS:this.WGSL_CustomFragment,CUSTOM_FRAGMENT_BEFORE_LIGHTS:this.WGSL_FragmentUpdateColor};if(n===BABYLON.ShaderLanguage.GLSL)return null==this.GLSL_CustomFragment&&(this.GLSL_CustomFragment=this.GLSL_FormatTerrainFragmentDefintions(i,this.splatmapSampler,this.detailsSampler,this.normalsSampler)),null==this.GLSL_FragmentUpdateColor&&(this.GLSL_FragmentUpdateColor=this.GLSL_FormatTerrainFragmentUpdateColor(i,this.colorName,this.splatmapSampler,this.detailsSampler,this.normalsSampler,e.SceneManager.TerrainColorCorrection)),{CUSTOM_FRAGMENT_DEFINITIONS:this.GLSL_CustomFragment,CUSTOM_FRAGMENT_BEFORE_LIGHTS:this.GLSL_FragmentUpdateColor}}return null},n.prototype.getUniforms=function(e){var t=e===BABYLON.ShaderLanguage.WGSL;return this.vertexDefinitions=this.getCustomShaderMaterial().getCustomVertexCode(t),this.fragmentDefinitions=!0===t?this.getCustomShaderMaterial().getCustomFragmentCode(t):null,this.getCustomShaderMaterial().getCustomUniforms(t)},n.prototype.getSamplers=function(e){var t=this.getCustomShaderMaterial().getCustomSamplers();null!=t&&t.length>0&&e.push.apply(e,t)},n.prototype.getAttributes=function(e,t,n){var i=this.getCustomShaderMaterial().getCustomAttributes();null!=i&&i.length>0&&e.push.apply(e,i)},n.prototype.prepareDefines=function(e,t,n){this.getIsEnabled()&&this.getCustomShaderMaterial().prepareCustomDefines(e)},n.prototype.bindForSubMesh=function(e,t,n,i){this.getIsEnabled()&&this.getCustomShaderMaterial().updateCustomBindings(e)},n.prototype.WGSL_FormatTerrainVertexDefintions=function(e){var t="";return null!=e&&null!=e.textureAtlas&&null!=e.splatmapAtlas&&e.splatmapCount>0&&(t="\r\n#ifndef TERRAIN_VERTEX_DEFINITIONS\r\n\r\n#define TERRAIN_VERTEX_DEFINITIONS\r\n\r\nvarying vSplatmapUV: vec2<f32>;\r\n\r\n#endif\r\n\r\n"),t},n.prototype.WGSL_FormatTerrainVertexMainEnd=function(e){var t="";return null!=e&&null!=e.textureAtlas&&null!=e.splatmapAtlas&&e.splatmapCount>0&&(t="\r\n#ifndef TERRAIN_VERTEX_MAIN_END\r\n\r\n#define TERRAIN_VERTEX_MAIN_END\r\n\r\n#ifdef UV1\r\nvertexOutputs.vSplatmapUV = uvUpdated;\r\n#endif\r\n\r\n#endif\r\n\r\n"),t},n.prototype.WGSL_FormatTerrainFragmentDefintions=function(e,t,n,i){var r="";return null!=e&&null!=e.textureAtlas&&null!=e.splatmapAtlas&&e.splatmapCount>0&&(r="\r\n#ifndef TERRAIN_FRAGMENT_DEFNITIONS\r\n\r\n#define TERRAIN_FRAGMENT_DEFNITIONS\r\n\r\nvarying vSplatmapUV: vec2<f32>;\r\n\r\nfn srgb_to_linear(c: vec3<f32>) -> vec3<f32>\r\n{\r\n return pow(c, vec3<f32>(2.2));\r\n}\r\n\r\nfn linear_to_srgb(c: vec3<f32>) -> vec3<f32>\r\n{\r\n return pow(c, vec3<f32>(1.0 / 2.2));\r\n}\r\n\r\nfn calculateMipmapLevel(uvs: vec2<f32>, size: vec2<f32>) -> f32\r\n{\r\n let dx: vec2<f32> = dpdx(uvs * size.x);\r\n let dy: vec2<f32> = dpdy(uvs * size.y);\r\n let d: f32 = max(dot(dx, dx), dot(dy, dy));\r\n return (0.4 * log2(d));\r\n}\r\n\r\nfn sampleTextureAtlas2D(atlas: texture_2d<f32>, sampler: sampler, gamma: f32, tile: vec2<f32>, rect: vec4<f32>, uvs: vec2<f32>, lod: f32) -> vec4<f32>\r\n{\r\n var level: f32 = lod;\r\n if (level < 0.0) {\r\n level = clamp(calculateMipmapLevel(uvs, vec2(tile.x, tile.x)), 0.0, tile.y);\r\n }\r\n let size: f32 = pow(2.0, tile.y - level);\r\n let sizex: f32 = size / rect.z;\r\n let sizey: f32 = size / rect.w;\r\n var uv: vec2<f32> = fract(uvs);\r\n uv.x = uv.x * ((sizex * rect.z - 1.0) / sizex) + 0.5 / sizex + rect.z * rect.x;\r\n uv.y = uv.y * ((sizey * rect.w - 1.0) / sizey) + 0.5 / sizey + rect.w * rect.y;\r\n var color: vec4<f32> = textureSampleLevel(atlas, sampler, uv, level);\r\n if (gamma != 1.0) {\r\n color.r = pow(color.r, gamma);\r\n color.g = pow(color.g, gamma);\r\n color.b = pow(color.b, gamma);\r\n }\r\n return color;\r\n}\r\n\r\nfn sampleSplatmapAtlas2D(atlas: texture_2d<f32>, sampler: sampler, tile: vec2<f32>, rect: vec4<f32>, uvs: vec2<f32>) -> vec4<f32>\r\n{\r\n let size: f32 = pow(2.0, tile.y);\r\n\t let sizex: f32 = size / rect.z;\r\n\t let sizey: f32 = size / rect.w;\r\n\t var uv: vec2<f32> = uvs;\r\n\t uv.x = uv.x * ((sizex * rect.z - 1.0) / sizex) + 0.5 / sizex + rect.z * rect.x;\r\n\t uv.y = uv.y * ((sizey * rect.w - 1.0) / sizey) + 0.5 / sizey + rect.w * rect.y;\r\n return textureSample(atlas, sampler, uv);\r\n}\r\n\r\nfn blendSplatmapAtlasColors(splatmap: vec4<f32>, color1: vec4<f32>, color2: vec4<f32>, color3: vec4<f32>, color4: vec4<f32>, mixbuffer: vec3<f32>) -> vec3<f32>\r\n{\r\n let buffer1: vec3<f32> = mix(mixbuffer, color1.rgb, splatmap.r);\r\n let buffer2: vec3<f32> = mix(buffer1, color2.rgb, splatmap.g);\r\n let buffer3: vec3<f32> = mix(buffer2, color3.rgb, splatmap.b);\r\n return mix(buffer3, color4.rgb, splatmap.a);\r\n}\r\n\r\nfn perturbNormalSamplerColor(cotangentFrame: mat3x3<f32>, samplerColor: vec3<f32>, scale: f32) -> vec3<f32>\r\n{\r\n var map: vec3<f32> = samplerColor.xyz;\r\n map = map * 2.00787402 - 1.00787402;\r\n #ifdef NORMALXYSCALE\r\n map = normalize(map * vec3<f32>(scale, scale, 1.0));\r\n #endif\r\n return normalize(cotangentFrame * map);\r\n}\r\n#endif\r\n\r\n"),r},n.prototype.WGSL_FormatTerrainFragmentUpdateColor=function(e,t,n,i,r,o){void 0===o&&(o=1);var a="";if(null!=e&&null!=e.textureAtlas&&null!=e.splatmapAtlas&&e.splatmapCount>0){if(a="\r\n#ifndef TERRAIN_FRAGMENT_UPDATE_COLOR\r\n\r\n#define TERRAIN_FRAGMENT_UPDATE_COLOR\r\n\r\nvar normalsColor: vec3<f32> = vec3<f32>(0.5, 0.5, 1.0);\r\nvar normalsBuffer: vec3<f32> = normalW.rgb;\r\nvar splatmapBuffer: vec3<f32> = "+t+".rgb;\r\nvar autoMipMapLevel: f32 = -1.0;\r\nvar normalCorrection: f32 = 1.0;\r\nvar detailCorrection: f32 = "+o.toFixed(4)+";\r\n\r\n#if defined(ALBEDO) && defined("+n.toUpperCase()+") && defined("+i.toUpperCase()+")\r\n\r\n// Reset Normal Values\r\n#if defined(BUMP) || defined(PARALLAX) || defined(ANISOTROPIC)\r\n uvOffset = vec2<f32>(0.0, 0.0);\r\n #ifdef NORMAL\r\n normalW = normalize(input.vNormalW);\r\n #else\r\n normalW = normalize(cross(dpdx(input.vPositionW), dpdy(input.vPositionW))) * scene.vEyePosition.w;\r\n #endif\r\n #ifdef CLEARCOAT\r\n clearCoatNormalW = normalW;\r\n #endif\r\n #if defined(BUMP) || defined(PARALLAX)\r\n #if defined(CLEARCOAT_BUMP) && defined(TANGENT) && defined(NORMAL)\r\n TBN = vTBN;\r\n #else\r\n TBN = cotangent_frame(normalW, input.vPositionW, fragmentInputs.vSplatmapUV, vec2<f32>(1.0, 1.0));\r\n #endif\r\n #elif defined(ANISOTROPIC)\r\n #if defined(CLEARCOAT_BUMP) && defined(TANGENT) && defined(NORMAL)\r\n TBN = vTBN;\r\n #else\r\n TBN = cotangent_frame(normalW, input.vPositionW, fragmentInputs.vSplatmapUV, vec2<f32>(1.0, 1.0));\r\n #endif\r\n #endif\r\n #ifdef PARALLAX\r\n invTBN = transposeMat3(TBN);\r\n #endif\r\n normalW = perturbNormalSamplerColor(TBN, normalsColor, 1.0);\r\n#endif\r\n\r\n// Global Atlas Values\r\nlet splatTileSize: f32 = "+e.splatmapAtlas[2].toFixed(4)+";\r\nlet splatTileBits: f32 = "+e.splatmapAtlas[3].toFixed(4)+";\r\nlet detailTileSize: f32 = "+e.textureAtlas[2].toFixed(4)+";\r\nlet detailTileBits: f32 = "+e.textureAtlas[3].toFixed(4)+";\r\n\r\n// Sample splatmap textures\r\n",e.splatmapCount>0){var s=0;a+="normalsBuffer = vec3<f32>(0.0,0.0,0.0);\r\n";for(var l=0;l<e.splatmapCount;l++){s=4*l;var u=e["splatmapRect"+l];if(a+="var splatmapRect"+l+": vec4<f32> = vec4<f32>("+u[0].toFixed(4)+", "+u[1].toFixed(4)+", "+u[2].toFixed(4)+", "+u[3].toFixed(4)+");\r\n",a+="var splatmapAlbedo"+l+": vec4<f32> = sampleSplatmapAtlas2D("+n+", "+n+"Sampler, vec2<f32>(splatTileSize, splatTileBits), splatmapRect"+l+", (fragmentInputs.vSplatmapUV + uvOffset));\r\n",a+="var textureAlbedo"+(s+0)+": vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 1.0);\r\n",a+="var textureAlbedo"+(s+1)+": vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 1.0);\r\n",a+="var textureAlbedo"+(s+2)+": vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 1.0);\r\n",a+="var textureAlbedo"+(s+3)+": vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 1.0);\r\n",e["textureRect"+(s+0)]){var c=e["textureRect"+(s+0)],d=e["textureInfo"+(s+0)];a+="var textureRect"+(s+0)+": vec4<f32> = vec4<f32>("+c[0].toFixed(4)+", "+c[1].toFixed(4)+", "+c[2].toFixed(4)+", "+c[3].toFixed(4)+");\r\n",a+="var textureScale"+(s+0)+": vec2<f32> = vec2<f32>("+d[0].toFixed(4)+", "+d[1].toFixed(4)+");\r\n",a+="var textureOffset"+(s+0)+": vec2<f32> = vec2<f32>("+d[2].toFixed(4)+", "+d[3].toFixed(4)+");\r\n",a+="var textureTileUV"+(s+0)+": vec2<f32> = ((fragmentInputs.vSplatmapUV + textureOffset"+(s+0)+") * textureScale"+(s+0)+");\r\n",a+="textureAlbedo"+(s+0)+" = sampleTextureAtlas2D("+i+", "+i+"Sampler, detailCorrection, vec2<f32>(detailTileSize, detailTileBits), textureRect"+(s+0)+", textureTileUV"+(s+0)+", autoMipMapLevel);\r\n"}e["textureRect"+(s+1)]&&(c=e["textureRect"+(s+1)],d=e["textureInfo"+(s+1)],a+="var textureRect"+(s+1)+": vec4<f32> = vec4<f32>("+c[0].toFixed(4)+", "+c[1].toFixed(4)+", "+c[2].toFixed(4)+", "+c[3].toFixed(4)+");\r\n",a+="var textureScale"+(s+1)+": vec2<f32> = vec2<f32>("+d[0].toFixed(4)+", "+d[1].toFixed(4)+");\r\n",a+="var textureOffset"+(s+1)+": vec2<f32> = vec2<f32>("+d[2].toFixed(4)+", "+d[3].toFixed(4)+");\r\n",a+="var textureTileUV"+(s+1)+": vec2<f32> = ((fragmentInputs.vSplatmapUV + textureOffset"+(s+1)+") * textureScale"+(s+1)+");\r\n",a+="textureAlbedo"+(s+1)+" = sampleTextureAtlas2D("+i+", "+i+"Sampler, detailCorrection, vec2<f32>(detailTileSize, detailTileBits), textureRect"+(s+1)+", textureTileUV"+(s+1)+", autoMipMapLevel);\r\n"),e["textureRect"+(s+2)]&&(c=e["textureRect"+(s+2)],d=e["textureInfo"+(s+2)],a+="var textureRect"+(s+2)+": vec4<f32> = vec4<f32>("+c[0].toFixed(4)+", "+c[1].toFixed(4)+", "+c[2].toFixed(4)+", "+c[3].toFixed(4)+");\r\n",a+="var textureScale"+(s+2)+": vec2<f32> = vec2<f32>("+d[0].toFixed(4)+", "+d[1].toFixed(4)+");\r\n",a+="var textureOffset"+(s+2)+": vec2<f32> = vec2<f32>("+d[2].toFixed(4)+", "+d[3].toFixed(4)+");\r\n",a+="var textureTileUV"+(s+2)+": vec2<f32> = ((fragmentInputs.vSplatmapUV + textureOffset"+(s+2)+") * textureScale"+(s+2)+");\r\n",a+="textureAlbedo"+(s+2)+" = sampleTextureAtlas2D("+i+", "+i+"Sampler, detailCorrection, vec2<f32>(detailTileSize, detailTileBits), textureRect"+(s+2)+", textureTileUV"+(s+2)+", autoMipMapLevel);\r\n"),e["textureRect"+(s+3)]&&(c=e["textureRect"+(s+3)],d=e["textureInfo"+(s+3)],a+="var textureRect"+(s+3)+": vec4<f32> = vec4<f32>("+c[0].toFixed(4)+", "+c[1].toFixed(4)+", "+c[2].toFixed(4)+", "+c[3].toFixed(4)+");\r\n",a+="var textureScale"+(s+3)+": vec2<f32> = vec2<f32>("+d[0].toFixed(4)+", "+d[1].toFixed(4)+");\r\n",a+="var textureOffset"+(s+3)+": vec2<f32> = vec2<f32>("+d[2].toFixed(4)+", "+d[3].toFixed(4)+");\r\n",a+="var textureTileUV"+(s+3)+": vec2<f32> = ((fragmentInputs.vSplatmapUV + textureOffset"+(s+3)+") * textureScale"+(s+3)+");\r\n",a+="textureAlbedo"+(s+3)+" = sampleTextureAtlas2D("+i+", "+i+"Sampler, detailCorrection, vec2<f32>(detailTileSize, detailTileBits), textureRect"+(s+3)+", textureTileUV"+(s+3)+", autoMipMapLevel);\r\n"),a+="splatmapBuffer = blendSplatmapAtlasColors(splatmapAlbedo"+l+", textureAlbedo"+(s+0)+", textureAlbedo"+(s+1)+", textureAlbedo"+(s+2)+", textureAlbedo"+(s+3)+", splatmapBuffer);\r\n",a+="#if defined(BUMP) || defined(PARALLAX) || defined(ANISOTROPIC)\r\n",a+=" #if defined("+r.toUpperCase()+")\r\n",a+=" var normalColor"+(s+0)+": vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 1.0);\r\n",a+=" var normalColor"+(s+1)+": vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 1.0);\r\n",a+=" var normalColor"+(s+2)+": vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 1.0);\r\n",a+=" var normalColor"+(s+3)+": vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 1.0);\r\n",e["textureRect"+(s+0)]&&(a+=" var normalScale"+(s+0)+": f32 = "+e["normalsScale"+(s+0)].toFixed(4)+";\r\n",a+=" normalColor"+(s+0)+" = sampleTextureAtlas2D("+r+", "+r+"Sampler, normalCorrection, vec2<f32>(detailTileSize, detailTileBits), textureRect"+(s+0)+", textureTileUV"+(s+0)+", autoMipMapLevel);\r\n",a+=" normalColor"+(s+0)+" = vec4<f32>(perturbNormalSamplerColor(TBN, normalColor"+(s+0)+".rgb, normalScale"+(s+0)+"), 1.0);\r\n"),e["textureRect"+(s+1)]&&(a+=" var normalScale"+(s+1)+": f32 = "+e["normalsScale"+(s+1)].toFixed(4)+";\r\n",a+=" normalColor"+(s+1)+" = sampleTextureAtlas2D("+r+", "+r+"Sampler, normalCorrection, vec2<f32>(detailTileSize, detailTileBits), textureRect"+(s+1)+", textureTileUV"+(s+1)+", autoMipMapLevel);\r\n",a+=" normalColor"+(s+1)+" = vec4<f32>(perturbNormalSamplerColor(TBN, normalColor"+(s+1)+".rgb, normalScale"+(s+1)+"), 1.0);\r\n"),e["textureRect"+(s+2)]&&(a+=" var normalScale"+(s+2)+": f32 = "+e["normalsScale"+(s+2)].toFixed(4)+";\r\n",a+=" normalColor"+(s+2)+" = sampleTextureAtlas2D("+r+", "+r+"Sampler, normalCorrection, vec2<f32>(detailTileSize, detailTileBits), textureRect"+(s+2)+", textureTileUV"+(s+2)+", autoMipMapLevel);\r\n",a+=" normalColor"+(s+2)+" = vec4<f32>(perturbNormalSamplerColor(TBN, normalColor"+(s+2)+".rgb, normalScale"+(s+2)+"), 1.0);\r\n"),e["textureRect"+(s+3)]&&(a+=" var normalScale"+(s+3)+": f32 = "+e["normalsScale"+(s+3)].toFixed(4)+";\r\n",a+=" normalColor"+(s+3)+" = sampleTextureAtlas2D("+r+", "+r+"Sampler, normalCorrection, vec2<f32>(detailTileSize, detailTileBits), textureRect"+(s+3)+", textureTileUV"+(s+3)+", autoMipMapLevel);\r\n",a+=" normalColor"+(s+3)+" = vec4<f32>(perturbNormalSamplerColor(TBN, normalColor"+(s+3)+".rgb, normalScale"+(s+3)+"), 1.0);\r\n"),a+=" normalsBuffer = blendSplatmapAtlasColors(splatmapAlbedo"+l+", normalColor"+(s+0)+", normalColor"+(s+1)+", normalColor"+(s+2)+", normalColor"+(s+3)+", normalsBuffer);\r\n",a+=" #endif\r\n",a+="#endif\r\n",a+="\r\n"}}a+="// Update Color Values\r\n"+t+" = splatmapBuffer.rgb;\r\n#if defined(BUMP) || defined(PARALLAX) || defined(ANISOTROPIC)\r\n #if defined("+r.toUpperCase()+")\r\n normalW = normalsBuffer.rgb;\r\n #endif\r\n #if defined(FORCENORMALFORWARD) && defined(NORMAL)\r\n var faceNormal: vec3<f32> = normalize(cross(dpdx(input.vPositionW), dpdy(input.vPositionW))) * scene.vEyePosition.w;\r\n #if defined(TWOSIDEDLIGHTING)\r\n faceNormal = select(-faceNormal, faceNormal, fragmentInputs.frontFacing)\r\n #endif\r\n normalW *= sign(dot(normalW, faceNormal));\r\n #endif\r\n #if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\r\n normalW = select(-normalW, normalW, fragmentInputs.frontFacing);\r\n #endif\r\n#endif\r\n\r\n#endif\r\n\r\n#endif\r\n\r\n"}return a},n.prototype.GLSL_FormatTerrainVertexDefintions=function(e){var t="";return null!=e&&null!=e.textureAtlas&&null!=e.splatmapAtlas&&e.splatmapCount>0&&(t="\r\n#ifndef TERRAIN_VERTEX_DEFINITIONS\r\n\r\n#define TERRAIN_VERTEX_DEFINITIONS\r\n\r\nvarying vec2 vSplatmapUV;\r\n\r\n#endif\r\n\r\n"),t},n.prototype.GLSL_FormatTerrainVertexMainEnd=function(e){var t="";return null!=e&&null!=e.textureAtlas&&null!=e.splatmapAtlas&&e.splatmapCount>0&&(t="\r\n#ifndef TERRAIN_VERTEX_MAIN_END\r\n\r\n#define TERRAIN_VERTEX_MAIN_END\r\n\r\n#ifdef UV1\r\nvSplatmapUV = uv;\r\n#endif\r\n\r\n#endif\r\n\r\n"),t},n.prototype.GLSL_FormatTerrainFragmentDefintions=function(e,t,n,i){var r="";return null!=e&&null!=e.textureAtlas&&null!=e.splatmapAtlas&&e.splatmapCount>0&&(r="\r\n#ifndef TERRAIN_FRAGMENT_DEFNITIONS\r\n\r\n#define TERRAIN_FRAGMENT_DEFNITIONS\r\n\r\nvarying vec2 vSplatmapUV;\r\n\r\nvec3 srgb_to_linear(const in vec3 c)\r\n{\r\n return pow(c, vec3(2.2));\r\n}\r\n\r\nvec3 linear_to_srgb(const in vec3 c)\r\n{\r\n return pow(c, vec3(1.0 / 2.2));\r\n}\r\n\r\nfloat calculateMipmapLevel(const in vec2 uvs, const in vec2 size)\r\n{\r\n vec2 dx = dFdx(uvs * size.x);\r\n vec2 dy = dFdy(uvs * size.y);\r\n float d = max(dot(dx, dx), dot(dy, dy));\r\n return 0.4 * log2(d);\r\n}\r\n\r\nvec4 sampleTextureAtlas2D(const in sampler2D atlas, const in float gamma, const in vec2 tile, const in vec4 rect, in vec2 uvs, in float lod)\r\n{\r\n if (lod < 0.0) lod = clamp(calculateMipmapLevel(uvs, vec2(tile.x, tile.x)), 0.0, tile.y); // Tile Info (tile.xy)\r\n float size = pow(2.0, tile.y - lod); // Tile Bits (tile.y)\r\n float sizex = size / rect.z; // Tile Width (rect.z)\r\n float sizey = size / rect.w; // Tile Height (rect.w)\r\n uvs = fract(uvs); // Perfrom Tiling (fract)\r\n uvs.x = uvs.x * ((sizex * rect.z - 1.0) / sizex) + 0.5 / sizex + rect.z * rect.x; // Tile Position X (rect.x)\r\n uvs.y = uvs.y * ((sizey * rect.w - 1.0) / sizey) + 0.5 / sizey + rect.w * rect.y; // Tile Position Y (rect.y)\r\n vec4 color = texture2DLodEXT(atlas, uvs, lod);\r\n if (gamma != 1.0) {\r\n color.r = pow(color.r, gamma);\r\n color.g = pow(color.g, gamma);\r\n color.b = pow(color.b, gamma);\r\n }\r\n return color;\r\n}\r\n\r\nvec4 sampleSplatmapAtlas2D(const in sampler2D atlas, const in vec2 tile, const in vec4 rect, in vec2 uvs)\r\n{\r\n float size = pow(2.0, tile.y); // Tile Bits (tile.y)\r\n\t float sizex = size / rect.z; // Tile Width (rect.z)\r\n\t float sizey = size / rect.w; // Tile Height (rect.w)\r\n\t uvs.x = uvs.x * ((sizex * rect.z - 1.0) / sizex) + 0.5 / sizex + rect.z * rect.x; // Tile Position X (rect.x)\r\n\t uvs.y = uvs.y * ((sizey * rect.w - 1.0) / sizey) + 0.5 / sizey + rect.w * rect.y; // Tile Position Y (rect.y)\r\n return texture2D(atlas, uvs);\r\n}\r\n\r\nvec3 blendSplatmapAtlasColors(const in vec4 splatmap, in vec4 color1, in vec4 color2, in vec4 color3, in vec4 color4, in vec3 mixbuffer)\r\n{\r\n vec3 buffer1 = mix(mixbuffer, color1.rgb, splatmap.r);\r\n vec3 buffer2 = mix(buffer1, color2.rgb, splatmap.g);\r\n vec3 buffer3 = mix(buffer2, color3.rgb, splatmap.b);\r\n return mix(buffer3, color4.rgb, splatmap.a);\r\n}\r\n\r\nvec3 perturbNormalSamplerColor(mat3 cotangentFrame, vec3 samplerColor, float scale)\r\n{\r\n vec3 map = samplerColor.xyz;\r\n map = map * 2.00787402 - 1.00787402;\r\n #ifdef NORMALXYSCALE\r\n map = normalize(map * vec3(scale, scale, 1.0));\r\n #endif\r\n return normalize(cotangentFrame * map);\r\n}\r\n\r\n\r\n#endif\r\n\r\n"),r},n.prototype.GLSL_FormatTerrainFragmentUpdateColor=function(e,t,n,i,r,o){void 0===o&&(o=1);var a="";if(null!=e&&null!=e.textureAtlas&&null!=e.splatmapAtlas&&e.splatmapCount>0){if(a="\r\n#ifndef TERRAIN_FRAGMENT_UPDATE_COLOR\r\n\r\n#define TERRAIN_FRAGMENT_UPDATE_COLOR\r\n\r\nvec3 normalsColor = vec3(0.5, 0.5, 1.0);\r\nvec3 normalsBuffer = normalW.rgb;\r\nvec3 splatmapBuffer = "+t+".rgb;\r\nfloat autoMipMapLevel = -1.0;\r\nfloat normalCorrection = 1.0;\r\nfloat detailCorrection = "+o.toFixed(4)+";\r\n\r\n#if defined(ALBEDO) && defined("+n.toUpperCase()+") && defined("+i.toUpperCase()+")\r\n\r\n// Reset Normal Values\r\n#if defined(BUMP) || defined(PARALLAX) || defined(ANISOTROPIC)\r\n uvOffset = vec2(0.0, 0.0);\r\n #ifdef NORMAL\r\n normalW = normalize(vNormalW);\r\n #else\r\n normalW = normalize(cross(dFdx(vPositionW), dFdy(vPositionW))) * vEyePosition.w;\r\n #endif\r\n #ifdef CLEARCOAT\r\n clearCoatNormalW = normalW;\r\n #endif\r\n #if defined(BUMP) || defined(PARALLAX)\r\n #if defined(TANGENT) && defined(NORMAL)\r\n TBN = vTBN;\r\n #else\r\n TBN = cotangent_frame(normalW, vPositionW, vSplatmapUV);\r\n #endif\r\n #elif defined(ANISOTROPIC)\r\n #if defined(TANGENT) && defined(NORMAL)\r\n TBN = vTBN;\r\n #else\r\n TBN = cotangent_frame(normalW, vPositionW, vSplatmapUV, vec2(1.0, 1.0));\r\n #endif\r\n #endif\r\n #ifdef PARALLAX\r\n invTBN = transposeMat3(TBN);\r\n #endif\r\n normalW = perturbNormalSamplerColor(TBN, normalsColor, 1.0);\r\n#endif\r\n\r\n// Global Atlas Values\r\nfloat splatTileSize = "+e.splatmapAtlas[2].toFixed(4)+";\r\nfloat splatTileBits = "+e.splatmapAtlas[3].toFixed(4)+";\r\nfloat detailTileSize = "+e.textureAtlas[2].toFixed(4)+";\r\nfloat detailTileBits = "+e.textureAtlas[3].toFixed(4)+";\r\n\r\n// Sample splatmap textures\r\n",e.splatmapCount>0){var s=0;a+="normalsBuffer = vec3(0.0,0.0,0.0);\r\n";for(var l=0;l<e.splatmapCount;l++){s=4*l;var u=e["splatmapRect"+l];if(a+="vec4 splatmapRect"+l+" = vec4("+u[0].toFixed(4)+", "+u[1].toFixed(4)+", "+u[2].toFixed(4)+", "+u[3].toFixed(4)+");\r\n",a+="vec4 splatmapAlbedo"+l+" = sampleSplatmapAtlas2D("+n+", vec2(splatTileSize, splatTileBits), splatmapRect"+l+", (vSplatmapUV + uvOffset));\r\n",a+="vec4 textureAlbedo"+(s+0)+" = vec4(0.0, 0.0, 0.0, 1.0);\r\n",a+="vec4 textureAlbedo"+(s+1)+" = vec4(0.0, 0.0, 0.0, 1.0);\r\n",a+="vec4 textureAlbedo"+(s+2)+" = vec4(0.0, 0.0, 0.0, 1.0);\r\n",a+="vec4 textureAlbedo"+(s+3)+" = vec4(0.0, 0.0, 0.0, 1.0);\r\n",e["textureRect"+(s+0)]){var c=e["textureRect"+(s+0)],d=e["textureInfo"+(s+0)];a+="vec4 textureRect"+(s+0)+" = vec4("+c[0].toFixed(4)+", "+c[1].toFixed(4)+", "+c[2].toFixed(4)+", "+c[3].toFixed(4)+");\r\n",a+="vec2 textureScale"+(s+0)+" = vec2("+d[0].toFixed(4)+", "+d[1].toFixed(4)+");\r\n",a+="vec2 textureOffset"+(s+0)+" = vec2("+d[2].toFixed(4)+", "+d[3].toFixed(4)+");\r\n",a+="vec2 textureTileUV"+(s+0)+" = ((vSplatmapUV + textureOffset"+(s+0)+") * textureScale"+(s+0)+");\r\n",a+="textureAlbedo"+(s+0)+" = sampleTextureAtlas2D("+i+", detailCorrection, vec2(detailTileSize, detailTileBits), textureRect"+(s+0)+", textureTileUV"+(s+0)+", autoMipMapLevel);\r\n"}e["textureRect"+(s+1)]&&(c=e["textureRect"+(s+1)],d=e["textureInfo"+(s+1)],a+="vec4 textureRect"+(s+1)+" = vec4("+c[0].toFixed(4)+", "+c[1].toFixed(4)+", "+c[2].toFixed(4)+", "+c[3].toFixed(4)+");\r\n",a+="vec2 textureScale"+(s+1)+" = vec2("+d[0].toFixed(4)+", "+d[1].toFixed(4)+");\r\n",a+="vec2 textureOffset"+(s+1)+" = vec2("+d[2].toFixed(4)+", "+d[3].toFixed(4)+");\r\n",a+="vec2 textureTileUV"+(s+1)+" = ((vSplatmapUV + textureOffset"+(s+1)+") * textureScale"+(s+1)+");\r\n",a+="textureAlbedo"+(s+1)+" = sampleTextureAtlas2D("+i+", detailCorrection, vec2(detailTileSize, detailTileBits), textureRect"+(s+1)+", textureTileUV"+(s+1)+", autoMipMapLevel);\r\n"),e["textureRect"+(s+2)]&&(c=e["textureRect"+(s+2)],d=e["textureInfo"+(s+2)],a+="vec4 textureRect"+(s+2)+" = vec4("+c[0].toFixed(4)+", "+c[1].toFixed(4)+", "+c[2].toFixed(4)+", "+c[3].toFixed(4)+");\r\n",a+="vec2 textureScale"+(s+2)+" = vec2("+d[0].toFixed(4)+", "+d[1].toFixed(4)+");\r\n",a+="vec2 textureOffset"+(s+2)+" = vec2("+d[2].toFixed(4)+", "+d[3].toFixed(4)+");\r\n",a+="vec2 textureTileUV"+(s+2)+" = ((vSplatmapUV + textureOffset"+(s+2)+") * textureScale"+(s+2)+");\r\n",a+="textureAlbedo"+(s+2)+" = sampleTextureAtlas2D("+i+", detailCorrection, vec2(detailTileSize, detailTileBits), textureRect"+(s+2)+", textureTileUV"+(s+2)+", autoMipMapLevel);\r\n"),e["textureRect"+(s+3)]&&(c=e["textureRect"+(s+3)],d=e["textureInfo"+(s+3)],a+="vec4 textureRect"+(s+3)+" = vec4("+c[0].toFixed(4)+", "+c[1].toFixed(4)+", "+c[2].toFixed(4)+", "+c[3].toFixed(4)+");\r\n",a+="vec2 textureScale"+(s+3)+" = vec2("+d[0].toFixed(4)+", "+d[1].toFixed(4)+");\r\n",a+="vec2 textureOffset"+(s+3)+" = vec2("+d[2].toFixed(4)+", "+d[3].toFixed(4)+");\r\n",a+="vec2 textureTileUV"+(s+3)+" = ((vSplatmapUV + textureOffset"+(s+3)+") * textureScale"+(s+3)+");\r\n",a+="textureAlbedo"+(s+3)+" = sampleTextureAtlas2D("+i+", detailCorrection, vec2(detailTileSize, detailTileBits), textureRect"+(s+3)+", textureTileUV"+(s+3)+", autoMipMapLevel);\r\n"),a+="splatmapBuffer = blendSplatmapAtlasColors(splatmapAlbedo"+l+", textureAlbedo"+(s+0)+", textureAlbedo"+(s+1)+", textureAlbedo"+(s+2)+", textureAlbedo"+(s+3)+", splatmapBuffer);\r\n",a+="#if defined(BUMP) || defined(PARALLAX) || defined(ANISOTROPIC)\r\n",a+=" #if defined("+r.toUpperCase()+")\r\n",a+=" vec4 normalColor"+(s+0)+" = vec4(0.0, 0.0, 0.0, 1.0);\r\n",a+=" vec4 normalColor"+(s+1)+" = vec4(0.0, 0.0, 0.0, 1.0);\r\n",a+=" vec4 normalColor"+(s+2)+" = vec4(0.0, 0.0, 0.0, 1.0);\r\n",a+=" vec4 normalColor"+(s+3)+" = vec4(0.0, 0.0, 0.0, 1.0);\r\n",e["textureRect"+(s+0)]&&(a+=" float normalScale"+(s+0)+" = "+e["normalsScale"+(s+0)].toFixed(4)+";\r\n",a+=" normalColor"+(s+0)+" = sampleTextureAtlas2D("+r+", normalCorrection, vec2(detailTileSize, detailTileBits), textureRect"+(s+0)+", textureTileUV"+(s+0)+", autoMipMapLevel);\r\n",a+=" normalColor"+(s+0)+".rgb = perturbNormalSamplerColor(TBN, normalColor"+(s+0)+".rgb, normalScale"+(s+0)+");\r\n"),e["textureRect"+(s+1)]&&(a+=" float normalScale"+(s+1)+" = "+e["normalsScale"+(s+1)].toFixed(4)+";\r\n",a+=" normalColor"+(s+1)+" = sampleTextureAtlas2D("+r+", normalCorrection, vec2(detailTileSize, detailTileBits), textureRect"+(s+1)+", textureTileUV"+(s+1)+", autoMipMapLevel);\r\n",a+=" normalColor"+(s+1)+".rgb = perturbNormalSamplerColor(TBN, normalColor"+(s+1)+".rgb, normalScale"+(s+1)+");\r\n"),e["textureRect"+(s+2)]&&(a+=" float normalScale"+(s+2)+" = "+e["normalsScale"+(s+2)].toFixed(4)+";\r\n",a+=" normalColor"+(s+2)+" = sampleTextureAtlas2D("+r+", normalCorrection, vec2(detailTileSize, detailTileBits), textureRect"+(s+2)+", textureTileUV"+(s+2)+", autoMipMapLevel);\r\n",a+=" normalColor"+(s+2)+".rgb = perturbNormalSamplerColor(TBN, normalColor"+(s+2)+".rgb, normalScale"+(s+2)+");\r\n"),e["textureRect"+(s+3)]&&(a+=" float normalScale"+(s+3)+" = "+e["normalsScale"+(s+3)].toFixed(4)+";\r\n",a+=" normalColor"+(s+3)+" = sampleTextureAtlas2D("+r+", normalCorrection, vec2(detailTileSize, detailTileBits), textureRect"+(s+3)+", textureTileUV"+(s+3)+", autoMipMapLevel);\r\n",a+=" normalColor"+(s+3)+".rgb = perturbNormalSamplerColor(TBN, normalColor"+(s+3)+".rgb, normalScale"+(s+3)+");\r\n"),a+=" normalsBuffer = blendSplatmapAtlasColors(splatmapAlbedo"+l+", normalColor"+(s+0)+", normalColor"+(s+1)+", normalColor"+(s+2)+", normalColor"+(s+3)+", normalsBuffer);\r\n",a+=" #endif\r\n",a+="#endif\r\n",a+="\r\n"}}a+="// Update Color Values\r\n"+t+" = splatmapBuffer.rgb;\r\n#if defined(BUMP) || defined(PARALLAX) || defined(ANISOTROPIC)\r\n #if defined("+r.toUpperCase()+")\r\n normalW = normalsBuffer.rgb;\r\n #endif\r\n #if defined(FORCENORMALFORWARD) && defined(NORMAL)\r\n vec3 faceNormal = normalize(cross(dFdx(vPositionW), dFdy(vPositionW))) * vEyePosition.w;\r\n #if defined(TWOSIDEDLIGHTING)\r\n faceNormal = gl_FrontFacing ? faceNormal : -faceNormal;\r\n #endif\r\n normalW *= sign(dot(normalW, faceNormal));\r\n #endif\r\n #if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\r\n normalW = gl_FrontFacing ? normalW : -normalW;\r\n #endif\r\n#endif\r\n\r\n#endif\r\n\r\n#endif\r\n\r\n"}return a},n}(e.CustomShaderMaterialPlugin);e.UniversalTerrainMaterialPlugin=n,e.SceneManager.RegisterClass("TOOLKIT.UniversalTerrainMaterial",t),e.SceneManager.RegisterClass("TOOLKIT.UniversalTerrainMaterialPlugin",n)}(i||(i={})),function(e){var t=function(t){function n(n,i){var r=t.call(this,n,i)||this;return r._windTimeAccum=0,r._lastUpdateFrame=-1,r.shader=r.getShaderName(),r.plugin=new e.GrassStandardMaterialPlugin(r,r.shader),r.addFloatUniform("g_maxDistance",0),r.addFloatUniform("g_fadeStart",0),r.addFloatUniform("g_alphaCutoff",.3),r.addFloatUniform("g_windTime",0),r.addFloatUniform("g_waveSpeed",.5),r.addFloatUniform("g_waveSize",.5),r.addFloatUniform("g_windAmount",.5),r.addVector4Uniform("g_windTint",new BABYLON.Vector4(.7,.6,.5,0)),r.addFloatUniform("g_shadowIntensity",.7),r.emissiveColor=new BABYLON.Color3(.7,.7,.7),r._windTimeAccum=0,r}return r(n,t),n.prototype.awake=function(){},n.prototype.update=function(){var t;try{var n=this.getScene(),i=n.getFrameId();if(this._lastUpdateFrame===i)return;this._lastUpdateFrame=i;var r=e.SceneManager.GetDeltaSeconds(n),o=Math.min(r,1/30);(null!==(t=this.getFloatValue("g_waveSpeed"))&&void 0!==t?t:0)>0&&(this._windTimeAccum=this._windTimeAccum+o,this.setFloatValue("g_windTime",this._windTimeAccum))}catch(e){}},n.prototype.getShaderName=function(){return"GrassStandardMaterial"},n.prototype.getMaxDistance=function(){return this.getFloatValue("g_maxDistance")},n.prototype.setMaxDistance=function(e){this.setFloatValue("g_maxDistance",e)},n.prototype.getFadeStart=function(){return this.getFloatValue("g_fadeStart")},n.prototype.setFadeStart=function(e){this.setFloatValue("g_fadeStart",e)},n.prototype.getWaveSpeed=function(){return this.getFloatValue("g_waveSpeed")},n.prototype.setWaveSpeed=function(e){this.setFloatValue("g_waveSpeed",e)},n.prototype.getWaveSize=function(){return this.getFloatValue("g_waveSize")},n.prototype.setWaveSize=function(e){this.setFloatValue("g_waveSize",e)},n.prototype.getWindAmount=function(){return this.getFloatValue("g_windAmount")},n.prototype.setWindAmount=function(e){this.setFloatValue("g_windAmount",e)},n.prototype.getWindTint=function(){return this.getVector4Value("g_windTint")},n.prototype.setWindTint=function(e){this.setVector4Value("g_windTint",e)},n.prototype.getShadowIntensity=function(){return this.getFloatValue("g_shadowIntensity")},n.prototype.setShadowIntensity=function(e){var t=Math.max(0,Math.min(1,e));this.setFloatValue("g_shadowIntensity",t),this.emissiveColor=new BABYLON.Color3(t,t,t)},n}(e.StandardShaderMaterial);e.GrassStandardMaterial=t;var n=function(e){function t(t,n){return e.call(this,t,n,110,{GRASSSTANDARDMATERIAL:!1})||this}return r(t,e),t.prototype.isCompatible=function(e){return e===BABYLON.ShaderLanguage.WGSL||e===BABYLON.ShaderLanguage.GLSL},t.prototype.getCustomCode=function(e,t){if("vertex"===e){if(t===BABYLON.ShaderLanguage.WGSL)return{CUSTOM_VERTEX_DEFINITIONS:this.getWGSLVaryingDefinitions(),CUSTOM_VERTEX_MAIN_END:this.getWGSLVertexMainEnd(),CUSTOM_VERTEX_UPDATE_WORLDPOS:this.getWGSLVertexWorldPos()};if(t===BABYLON.ShaderLanguage.GLSL)return{CUSTOM_VERTEX_DEFINITIONS:this.getGLSLVertexDefinitions(),CUSTOM_VERTEX_MAIN_END:this.getGLSLVertexMainEnd(),CUSTOM_VERTEX_UPDATE_WORLDPOS:this.getGLSLVertexWorldPos()}}return"fragment"===e?t===BABYLON.ShaderLanguage.WGSL?{CUSTOM_FRAGMENT_DEFINITIONS:this.getWGSLVaryingDefinitions(),CUSTOM_FRAGMENT_BEFORE_FOG:this.getWGSLFragmentCode()}:{CUSTOM_FRAGMENT_DEFINITIONS:this.getGLSLFragmentDefinitions(),CUSTOM_FRAGMENT_BEFORE_FOG:this.getGLSLFragmentCode()}:null},t.prototype.getWGSLVertexMainEnd=function(){return""},t.prototype.getWGSLVaryingDefinitions=function(){return"\n #ifndef TOOLKIT_GRASS_VARYINGS\n #define TOOLKIT_GRASS_VARYINGS\n varying vGrassFade: f32;\n #endif\n "},t.prototype.getWGSLVertexWorldPos=function(){return"\n // Get instance world position (center of grass blade)\n let centerW = (finalWorld * vec4f(0.0, 0.0, 0.0, 1.0)).xyz;\n let up = vec3f(0.0, 1.0, 0.0);\n \n // Extract instance basis vectors and scale\n let right = normalize(finalWorld[0].xyz);\n let forward = normalize(finalWorld[2].xyz);\n let sx = length(finalWorld[0].xyz);\n let sy = length(finalWorld[1].xyz);\n let sz = length(finalWorld[2].xyz);\n \n // Compute world position of this vertex BEFORE waving\n // This is critical - Unity uses the actual vertex world position for wave phase\n let localPos = positionUpdated;\n var worldVertexPos = centerW + right * (localPos.x * sx) + up * (localPos.y * sy) + forward * (localPos.z * sz);\n \n // ============================================================\n // UNITY TerrainWaveGrass EXACT IMPLEMENTATION\n // From TerrainEngine.cginc lines 80-125\n // ============================================================\n \n // Wave amount is based on vertex height (top vertices wave more)\n // In Unity: v.color.a for mesh grass, tangent.y for billboard\n // Here we use the local Y position as the wave factor\n let waveAmount = max(localPos.y, 0.0) * uniforms.g_windAmount;\n \n // Wave constants tuned for LARGE, GENTLE rolling waves like Unity\n // Key insight: Unity's grass shows broad bands spanning large terrain sections\n // NOT tight ripples - spatial frequency must be very LOW\n let waveSize = uniforms.g_waveSize;\n \n // Spatial frequencies reduced by 10x from Unity's original values\n // This creates wavelengths of ~50-100 units instead of ~5-10 units\n // Result: 1-2 visible wave crests across terrain instead of 10-20\n let waveXSize = vec4f(0.0012, 0.002, 0.006, 0.0024) * waveSize;\n let waveZSize = vec4f(0.0006, 0.002, 0.002, 0.005) * waveSize;\n \n // Temporal speed reduced for smooth, gentle motion\n // Original Unity values divided by 10 for slower wave travel\n let waveSpeed = vec4f(0.03, 0.05, 0.04, 0.12);\n \n // Movement amplitudes - these control how far grass sways\n // Increased 5x from previous values to get visible bending like Unity\n // Unity grass shows significant physical displacement (20-30 degree lean)\n let waveXmove = vec4f(0.12, 0.2, -0.6, 0.48);\n let waveZmove = vec4f(0.06, 0.2, -0.2, 1.0);\n \n // Compute wave phases from BLADE CENTER position - this creates spatial bands\n // Using centerW ensures all vertices of the same blade have identical phase\n // The height-based waveAmount controls per-vertex displacement amount\n // Unity: waves = vertex.x * _waveXSize + vertex.z * _waveZSize + time * waveSpeed\n var waves = vec4f(\n centerW.x * waveXSize.x + centerW.z * waveZSize.x,\n centerW.x * waveXSize.y + centerW.z * waveZSize.y,\n centerW.x * waveXSize.z + centerW.z * waveZSize.z,\n centerW.x * waveXSize.w + centerW.z * waveZSize.w\n );\n \n // Add time component - this makes waves travel\n let windTime = uniforms.g_windTime * uniforms.g_waveSpeed;\n waves = waves + vec4f(\n windTime * waveSpeed.x,\n windTime * waveSpeed.y,\n windTime * waveSpeed.z,\n windTime * waveSpeed.w\n );\n \n // Keep in 0-1 range for FastSinCos\n waves = fract(waves);\n \n // ============================================================\n // FastSinCos - Unity's Taylor series approximation\n // From TerrainEngine.cginc lines 56-78\n // ============================================================\n // Convert from 0-1 to -PI to PI range\n let wavesRad = waves * 6.408849 - 3.1415927;\n \n // Powers for Taylor series\n let r5 = wavesRad * wavesRad; // x^2\n let r6 = r5 * r5; // x^4\n let r7 = r6 * r5; // x^6\n let r8 = r6 * r5; // x^8 (same as r7 in Unity code)\n let r1 = r5 * wavesRad; // x^3\n let r2 = r1 * r5; // x^5\n let r3 = r2 * r5; // x^7\n \n // Taylor series coefficients\n let sin7 = vec4f(1.0, -0.16161616, 0.0083333, -0.00019841);\n let cos8 = vec4f(-0.5, 0.041666666, -0.0013888889, 0.000024801587);\n \n // Compute sine using Taylor series: x - x^3/3! + x^5/5! - x^7/7!\n var s = wavesRad + r1 * sin7.y + r2 * sin7.z + r3 * sin7.w;\n \n // Compute cosine (not used for displacement but kept for completeness)\n // var c = vec4f(1.0) + r5 * cos8.x + r6 * cos8.y + r7 * cos8.z + r8 * cos8.w;\n \n // ============================================================\n // Unity's characteristic wave shaping: s = s * s; s = s * s;\n // This creates sharper peaks and flatter troughs (gust appearance)\n // ============================================================\n s = s * s; // s^2\n s = s * s; // s^4\n \n // Lighting variation based on wave state (for color tinting)\n let lightingWeights = normalize(vec4f(1.0, 1.0, 0.4, 0.2));\n let lighting = dot(s, lightingWeights) * 0.7;\n \n // Scale by wave amount (height-based)\n s = s * waveAmount;\n \n // Compute final displacement using dot product with movement vectors\n // Unity: waveMove.x = dot(s, _waveXmove); waveMove.z = dot(s, _waveZmove);\n var waveMove = vec3f(0.0, 0.0, 0.0);\n waveMove.x = dot(s, waveXmove);\n waveMove.z = dot(s, waveZmove);\n \n // Apply displacement scaled by wind amount\n // Unity: vertex.xz -= waveMove.xz * _WaveAndDistance.z;\n // Note: Unity subtracts, we add in the opposite direction for same effect\n let displacement = waveMove * uniforms.g_windAmount;\n \n // Apply wave color tinting (Unity's waveColor calculation)\n // This creates visual bands of lighter/darker grass\n // let waveColor = mix(vec3f(0.5), uniforms.g_windTint.xyz, vec3f(lighting));\n \n // Final world position with waving applied\n let billboardWorld = worldVertexPos - vec3f(displacement.x, 0.0, displacement.z);\n\n // Distance-based culling (Unity-style fade)\n var detailAlpha: f32 = 1.0;\n if (uniforms.g_maxDistance > 0.0) {\n let dist = length(centerW - scene.vEyePosition.xyz);\n let maxD = uniforms.g_maxDistance;\n let fadeStart = uniforms.g_fadeStart;\n if (dist > maxD) { detailAlpha = 0.0; }\n else if (dist > fadeStart) { detailAlpha = 1.0 - ((dist - fadeStart) / max((maxD - fadeStart), 0.0001)); }\n }\n vertexOutputs.vGrassFade = detailAlpha;\n \n // UPDATE worldPos to the animated position BEFORE shadow calculations\n // This is critical for correct shadow receiving - shadows should be stationary\n // while grass moves through them, not move with the grass\n worldPos = vec4f(billboardWorld, 1.0);\n \n // Output\n #if defined(POSITION) || defined(BUMP)\n vertexOutputs.vPositionW = billboardWorld;\n #endif\n #ifdef NORMAL\n vertexOutputs.vNormalW = up;\n #endif\n \n vertexOutputs.position = scene.viewProjection * vec4f(billboardWorld, 1.0);\n "},t.prototype.getGLSLVertexDefinitions=function(){return"\n #ifndef TOOLKIT_GRASS_V_UNIFORMS\n #define TOOLKIT_GRASS_V_UNIFORMS\n uniform vec4 vEyePosition;\n uniform float g_windTime;\n uniform float g_maxDistance;\n uniform float g_fadeStart;\n uniform float g_alphaCutoff;\n uniform float g_waveSpeed;\n uniform float g_waveSize;\n uniform float g_windAmount;\n uniform vec4 g_windTint;\n uniform float g_shadowIntensity;\n #endif\n\n #ifndef TOOLKIT_GRASS_VARYINGS\n #define TOOLKIT_GRASS_VARYINGS\n varying float vGrassFade;\n #endif\n "},t.prototype.getGLSLVertexMainEnd=function(){return""},t.prototype.getGLSLVertexWorldPos=function(){return"\n // Get instance world position (center of grass blade)\n vec3 centerW = (finalWorld * vec4(0.0, 0.0, 0.0, 1.0)).xyz;\n vec3 up = vec3(0.0, 1.0, 0.0);\n \n // Extract instance basis vectors and scale\n vec3 right = normalize(finalWorld[0].xyz);\n vec3 forward = normalize(finalWorld[2].xyz);\n float sx = length(finalWorld[0].xyz);\n float sy = length(finalWorld[1].xyz);\n float sz = length(finalWorld[2].xyz);\n \n // Compute world position of this vertex BEFORE waving\n vec3 localPos = positionUpdated;\n vec3 worldVertexPos = centerW + right * (localPos.x * sx) + up * (localPos.y * sy) + forward * (localPos.z * sz);\n \n // ============================================================\n // UNITY TerrainWaveGrass EXACT IMPLEMENTATION\n // ============================================================\n \n // Wave amount based on vertex height\n float waveAmount = max(localPos.y, 0.0) * g_windAmount;\n \n // Wave constants tuned for LARGE, GENTLE rolling waves like Unity\n // Key insight: Unity's grass shows broad bands spanning large terrain sections\n // NOT tight ripples - spatial frequency must be very LOW\n float waveSize = g_waveSize;\n \n // Spatial frequencies reduced by 10x from Unity's original values\n // This creates wavelengths of ~50-100 units instead of ~5-10 units\n vec4 waveXSize = vec4(0.0012, 0.002, 0.006, 0.0024) * waveSize;\n vec4 waveZSize = vec4(0.0006, 0.002, 0.002, 0.005) * waveSize;\n \n // Temporal speed reduced for smooth, gentle motion\n vec4 waveSpeedVec = vec4(0.03, 0.05, 0.04, 0.12);\n \n // Movement amplitudes - increased 5x for visible bending like Unity\n vec4 waveXmove = vec4(0.12, 0.2, -0.6, 0.48);\n vec4 waveZmove = vec4(0.06, 0.2, -0.2, 1.0);\n \n // Compute wave phases from BLADE CENTER position\n // Using centerW ensures all vertices of the same blade have identical phase\n vec4 waves = vec4(\n centerW.x * waveXSize.x + centerW.z * waveZSize.x,\n centerW.x * waveXSize.y + centerW.z * waveZSize.y,\n centerW.x * waveXSize.z + centerW.z * waveZSize.z,\n centerW.x * waveXSize.w + centerW.z * waveZSize.w\n );\n \n // Add time component\n float windTime = g_windTime * g_waveSpeed;\n waves += vec4(\n windTime * waveSpeedVec.x,\n windTime * waveSpeedVec.y,\n windTime * waveSpeedVec.z,\n windTime * waveSpeedVec.w\n );\n \n // Keep in 0-1 range\n waves = fract(waves);\n \n // ============================================================\n // FastSinCos - Unity's Taylor series approximation\n // ============================================================\n vec4 wavesRad = waves * 6.408849 - 3.1415927;\n \n // Powers for Taylor series\n vec4 r5 = wavesRad * wavesRad;\n vec4 r6 = r5 * r5;\n vec4 r7 = r6 * r5;\n vec4 r1 = r5 * wavesRad;\n vec4 r2 = r1 * r5;\n vec4 r3 = r2 * r5;\n \n // Taylor series coefficients\n vec4 sin7 = vec4(1.0, -0.16161616, 0.0083333, -0.00019841);\n \n // Compute sine\n vec4 s = wavesRad + r1 * sin7.y + r2 * sin7.z + r3 * sin7.w;\n \n // ============================================================\n // Unity's wave shaping: s = s * s; s = s * s; (s^4)\n // ============================================================\n s = s * s;\n s = s * s;\n \n // Lighting for color tinting\n float lighting = dot(s, normalize(vec4(1.0, 1.0, 0.4, 0.2))) * 0.7;\n \n // Scale by wave amount\n s = s * waveAmount;\n \n // Compute displacement\n vec3 waveMove = vec3(0.0);\n waveMove.x = dot(s, waveXmove);\n waveMove.z = dot(s, waveZmove);\n \n // Apply displacement\n vec3 displacement = waveMove * g_windAmount;\n \n // Final world position\n vec3 billboardWorld = worldVertexPos - vec3(displacement.x, 0.0, displacement.z);\n \n // Distance-based culling\n float detailAlpha = 1.0;\n if (g_maxDistance > 0.0) {\n float dist = distance(vEyePosition.xyz, centerW);\n float maxD = g_maxDistance;\n float fadeStart = g_fadeStart;\n if (dist > maxD) { detailAlpha = 0.0; }\n else if (dist > fadeStart) { detailAlpha = 1.0 - ((dist - fadeStart) / max((maxD - fadeStart), 0.0001)); }\n }\n vGrassFade = detailAlpha;\n \n // UPDATE worldPos to the animated position BEFORE shadow calculations\n // This is critical for correct shadow receiving - shadows should be stationary\n // while grass moves through them, not move with the grass\n worldPos = vec4(billboardWorld, 1.0);\n \n #if defined(POSITION) || defined(BUMP)\n vPositionW = billboardWorld;\n #endif\n #ifdef NORMAL\n vNormalW = up;\n #endif\n \n gl_Position = viewProjection * vec4(billboardWorld, 1.0);\n "},t.prototype.getWGSLFragmentCode=function(){return"\n let detailAlpha = fragmentInputs.vGrassFade;\n let combinedAlpha = alpha * detailAlpha;\n if (combinedAlpha <= uniforms.g_alphaCutoff) { discard; }\n alpha = combinedAlpha;\n \n // Apply shadow intensity - adds ambient light to dark/shadowed areas\n // shadowIntensity controls how much ambient light to add: 0.0 = no ambient, 1.0 = full texture color\n // Simple approach: check if pixel is very dark (likely in shadow) and add ambient\n let shadowIntensity = uniforms.g_shadowIntensity;\n let brightness = max(color.r, max(color.g, color.b));\n // If brightness is below threshold, we're likely in shadow - add ambient light\n // The darker the pixel, the more ambient we add (inverse relationship)\n let shadowThreshold = 0.2;\n let shadowAmount = clamp((shadowThreshold - brightness) / shadowThreshold, 0.0, 1.0);\n // Add ambient light using the grass texture color\n color = vec4f(color.rgb + baseColor.rgb * shadowIntensity * shadowAmount, color.a);\n "},t.prototype.getGLSLFragmentCode=function(){return"\n float detailAlpha = vGrassFade;\n float combinedAlpha = alpha * detailAlpha;\n if (combinedAlpha <= g_alphaCutoff) discard;\n alpha = combinedAlpha;\n \n // Apply shadow intensity - adds ambient light to dark/shadowed areas\n // shadowIntensity controls how much ambient light to add: 0.0 = no ambient, 1.0 = full texture color\n // Simple approach: check if pixel is very dark (likely in shadow) and add ambient\n float shadowIntensity = g_shadowIntensity;\n float brightness = max(color.r, max(color.g, color.b));\n // If brightness is below threshold, we're likely in shadow - add ambient light\n // The darker the pixel, the more ambient we add (inverse relationship)\n float shadowThreshold = 0.2;\n float shadowAmount = clamp((shadowThreshold - brightness) / shadowThreshold, 0.0, 1.0);\n // Add ambient light using the grass texture color\n color.rgb += baseColor.rgb * shadowIntensity * shadowAmount;\n "},t.prototype.getGLSLFragmentDefinitions=function(){return"\n #ifndef TOOLKIT_GRASS_VARYINGS\n #define TOOLKIT_GRASS_VARYINGS\n varying float vGrassFade;\n #endif\n "},t.prototype.getUniforms=function(e){var t=e===BABYLON.ShaderLanguage.WGSL;return this.vertexDefinitions=this.getCustomShaderMaterial().getCustomVertexCode(t),this.fragmentDefinitions=!0===t?this.getCustomShaderMaterial().getCustomFragmentCode(t):null,this.getCustomShaderMaterial().getCustomUniforms(t)},t.prototype.getSamplers=function(e){var t=this.getCustomShaderMaterial().getCustomSamplers();null!=t&&t.length>0&&e.push.apply(e,t)},t.prototype.getAttributes=function(e,t,n){var i=this.getCustomShaderMaterial().getCustomAttributes();null!=i&&i.length>0&&e.push.apply(e,i)},t.prototype.prepareDefines=function(e,t,n){this.getIsEnabled()&&this.getCustomShaderMaterial().prepareCustomDefines(e)},t.prototype.bindForSubMesh=function(e,t,n,i){this.getIsEnabled()&&this.getCustomShaderMaterial().updateCustomBindings(e)},t}(e.StandardShaderMaterialPlugin);e.GrassStandardMaterialPlugin=n,e.SceneManager.RegisterClass("TOOLKIT.GrassStandardMaterial",t),e.SceneManager.RegisterClass("TOOLKIT.GrassStandardMaterialPlugin",n)}(i||(i={})),function(e){var t=function(t){function n(n,i){var r=t.call(this,n,i)||this;return r._windTimeAccum=0,r._lastUpdateFrame=-1,r.shader=r.getShaderName(),r.plugin=new e.GrassBillboardMaterialPlugin(r,r.shader),r.addFloatUniform("g_maxDistance",0),r.addFloatUniform("g_fadeStart",0),r.addFloatUniform("g_alphaCutoff",.3),r.addFloatUniform("g_windTime",0),r.addFloatUniform("g_waveSpeed",.5),r.addFloatUniform("g_waveSize",.5),r.addFloatUniform("g_windAmount",.5),r.addVector4Uniform("g_windTint",new BABYLON.Vector4(.7,.6,.5,0)),r.addFloatUniform("g_shadowIntensity",.7),r.addFloatUniform("g_sphericalBillboardEnabled",1),r.emissiveColor=new BABYLON.Color3(.7,.7,.7),r._windTimeAccum=0,r}return r(n,t),n.prototype.awake=function(){},n.prototype.update=function(){var t;try{var n=this.getScene(),i=n.getFrameId();if(this._lastUpdateFrame===i)return;this._lastUpdateFrame=i;var r=e.SceneManager.GetDeltaSeconds(n),o=Math.min(r,1/30);(null!==(t=this.getFloatValue("g_waveSpeed"))&&void 0!==t?t:0)>0&&(this._windTimeAccum=this._windTimeAccum+o,this.setFloatValue("g_windTime",this._windTimeAccum))}catch(e){}},n.prototype.getShaderName=function(){return"GrassBillboardMaterial"},n.prototype.getMaxDistance=function(){return this.getFloatValue("g_maxDistance")},n.prototype.setMaxDistance=function(e){this.setFloatValue("g_maxDistance",e)},n.prototype.getFadeStart=function(){return this.getFloatValue("g_fadeStart")},n.prototype.setFadeStart=function(e){this.setFloatValue("g_fadeStart",e)},n.prototype.getWaveSpeed=function(){return this.getFloatValue("g_waveSpeed")},n.prototype.setWaveSpeed=function(e){this.setFloatValue("g_waveSpeed",e)},n.prototype.getWaveSize=function(){return this.getFloatValue("g_waveSize")},n.prototype.setWaveSize=function(e){this.setFloatValue("g_waveSize",e)},n.prototype.getWindAmount=function(){return this.getFloatValue("g_windAmount")},n.prototype.setWindAmount=function(e){this.setFloatValue("g_windAmount",e)},n.prototype.getWindTint=function(){return this.getVector4Value("g_windTint")},n.prototype.setWindTint=function(e){this.setVector4Value("g_windTint",e)},n.prototype.getShadowIntensity=function(){return this.getFloatValue("g_shadowIntensity")},n.prototype.setShadowIntensity=function(e){var t=Math.max(0,Math.min(1,e));this.setFloatValue("g_shadowIntensity",t),this.emissiveColor=new BABYLON.Color3(t,t,t)},n.prototype.getSphericalBillboardEnabled=function(){var e;return(null!==(e=this.getFloatValue("g_sphericalBillboardEnabled"))&&void 0!==e?e:0)>.5},n.prototype.setSphericalBillboardEnabled=function(e){this.setFloatValue("g_sphericalBillboardEnabled",e?1:0)},n}(e.StandardShaderMaterial);e.GrassBillboardMaterial=t;var n=function(e){function t(t,n){return e.call(this,t,n,110,{GRASSBILLBOARDMATERIAL:!1})||this}return r(t,e),t.prototype.isCompatible=function(e){return e===BABYLON.ShaderLanguage.WGSL||e===BABYLON.ShaderLanguage.GLSL},t.prototype.getCustomCode=function(e,t){if("vertex"===e){if(t===BABYLON.ShaderLanguage.WGSL)return{CUSTOM_VERTEX_DEFINITIONS:this.getWGSLVaryingDefinitions(),CUSTOM_VERTEX_MAIN_END:this.getWGSLVertexMainEnd(),CUSTOM_VERTEX_UPDATE_WORLDPOS:this.getWGSLVertexWorldPos()};if(t===BABYLON.ShaderLanguage.GLSL)return{CUSTOM_VERTEX_DEFINITIONS:this.getGLSLVertexDefinitions(),CUSTOM_VERTEX_MAIN_END:this.getGLSLVertexMainEnd(),CUSTOM_VERTEX_UPDATE_WORLDPOS:this.getGLSLVertexWorldPos()}}return"fragment"===e?t===BABYLON.ShaderLanguage.WGSL?{CUSTOM_FRAGMENT_DEFINITIONS:this.getWGSLVaryingDefinitions(),CUSTOM_FRAGMENT_BEFORE_FOG:this.getWGSLFragmentCode()}:{CUSTOM_FRAGMENT_DEFINITIONS:this.getGLSLFragmentDefinitions(),CUSTOM_FRAGMENT_BEFORE_FOG:this.getGLSLFragmentCode()}:null},t.prototype.getWGSLVertexMainEnd=function(){return""},t.prototype.getWGSLVaryingDefinitions=function(){return"\n #ifndef TOOLKIT_GRASS_VARYINGS\n #define TOOLKIT_GRASS_VARYINGS\n varying vGrassFade: f32;\n #endif\n "},t.prototype.getWGSLVertexWorldPos=function(){return"\n // Get instance world position (center of grass blade)\n let centerW = (finalWorld * vec4f(0.0, 0.0, 0.0, 1.0)).xyz;\n let up = vec3f(0.0, 1.0, 0.0);\n \n // Extract instance scale (keep scale, but override rotation with Y-locked billboard basis)\n let sx = length(finalWorld[0].xyz);\n let sy = length(finalWorld[1].xyz);\n let sz = length(finalWorld[2].xyz);\n\n // Compute billboard basis (Y-locked or spherical)\n // Face the camera on XZ plane without tilting unless spherical is enabled\n let eyeW = scene.vEyePosition.xyz;\n var faceDir = centerW - eyeW;\n if (uniforms.g_sphericalBillboardEnabled < 0.5) {\n faceDir.y = 0.0;\n }\n let faceLen = length(faceDir);\n if (faceLen < 0.0001) {\n faceDir = vec3f(0.0, 0.0, 1.0);\n } else {\n faceDir = faceDir / faceLen;\n }\n\n // Safe up reference to avoid degeneracy when looking straight down\n var upRef = up;\n if (abs(faceDir.y) > 0.99) {\n upRef = vec3f(0.0, 0.0, 1.0);\n }\n\n let right = normalize(cross(upRef, faceDir));\n let forward = normalize(cross(faceDir, right));\n\n // Compute world position of this vertex BEFORE waving\n // This is critical - Unity uses the actual vertex world position for wave phase\n let localPos = positionUpdated;\n var worldVertexPos = centerW + right * (localPos.x * sx) + up * (localPos.y * sy) + forward * (localPos.z * sz);\n \n // ============================================================\n // UNITY TerrainWaveGrass EXACT IMPLEMENTATION\n // From TerrainEngine.cginc lines 80-125\n // ============================================================\n \n // Wave amount is based on vertex height (top vertices wave more)\n // In Unity: v.color.a for mesh grass, tangent.y for billboard\n // Here we use the local Y position as the wave factor\n let waveAmount = max(localPos.y, 0.0) * uniforms.g_windAmount;\n \n // Wave constants tuned for LARGE, GENTLE rolling waves like Unity\n // Key insight: Unity's grass shows broad bands spanning large terrain sections\n // NOT tight ripples - spatial frequency must be very LOW\n let waveSize = uniforms.g_waveSize;\n \n // Spatial frequencies reduced by 10x from Unity's original values\n // This creates wavelengths of ~50-100 units instead of ~5-10 units\n // Result: 1-2 visible wave crests across terrain instead of 10-20\n let waveXSize = vec4f(0.0012, 0.002, 0.006, 0.0024) * waveSize;\n let waveZSize = vec4f(0.0006, 0.002, 0.002, 0.005) * waveSize;\n \n // Temporal speed reduced for smooth, gentle motion\n // Original Unity values divided by 10 for slower wave travel\n let waveSpeed = vec4f(0.03, 0.05, 0.04, 0.12);\n \n // Movement amplitudes - these control how far grass sways\n // Increased 5x from previous values to get visible bending like Unity\n // Unity grass shows significant physical displacement (20-30 degree lean)\n let waveXmove = vec4f(0.12, 0.2, -0.6, 0.48);\n let waveZmove = vec4f(0.06, 0.2, -0.2, 1.0);\n \n // Compute wave phases from BLADE CENTER position - this creates spatial bands\n // Using centerW ensures all vertices of the same blade have identical phase\n // The height-based waveAmount controls per-vertex displacement amount\n // Unity: waves = vertex.x * _waveXSize + vertex.z * _waveZSize + time * waveSpeed\n var waves = vec4f(\n centerW.x * waveXSize.x + centerW.z * waveZSize.x,\n centerW.x * waveXSize.y + centerW.z * waveZSize.y,\n centerW.x * waveXSize.z + centerW.z * waveZSize.z,\n centerW.x * waveXSize.w + centerW.z * waveZSize.w\n );\n \n // Add time component - this makes waves travel\n let windTime = uniforms.g_windTime * uniforms.g_waveSpeed;\n waves = waves + vec4f(\n windTime * waveSpeed.x,\n windTime * waveSpeed.y,\n windTime * waveSpeed.z,\n windTime * waveSpeed.w\n );\n \n // Keep in 0-1 range for FastSinCos\n waves = fract(waves);\n \n // ============================================================\n // FastSinCos - Unity's Taylor series approximation\n // From TerrainEngine.cginc lines 56-78\n // ============================================================\n // Convert from 0-1 to -PI to PI range\n let wavesRad = waves * 6.408849 - 3.1415927;\n \n // Powers for Taylor series\n let r5 = wavesRad * wavesRad; // x^2\n let r6 = r5 * r5; // x^4\n let r7 = r6 * r5; // x^6\n let r8 = r6 * r5; // x^8 (same as r7 in Unity code)\n let r1 = r5 * wavesRad; // x^3\n let r2 = r1 * r5; // x^5\n let r3 = r2 * r5; // x^7\n \n // Taylor series coefficients\n let sin7 = vec4f(1.0, -0.16161616, 0.0083333, -0.00019841);\n let cos8 = vec4f(-0.5, 0.041666666, -0.0013888889, 0.000024801587);\n \n // Compute sine using Taylor series: x - x^3/3! + x^5/5! - x^7/7!\n var s = wavesRad + r1 * sin7.y + r2 * sin7.z + r3 * sin7.w;\n \n // Compute cosine (not used for displacement but kept for completeness)\n // var c = vec4f(1.0) + r5 * cos8.x + r6 * cos8.y + r7 * cos8.z + r8 * cos8.w;\n \n // ============================================================\n // Unity's characteristic wave shaping: s = s * s; s = s * s;\n // This creates sharper peaks and flatter troughs (gust appearance)\n // ============================================================\n s = s * s; // s^2\n s = s * s; // s^4\n \n // Lighting variation based on wave state (for color tinting)\n let lightingWeights = normalize(vec4f(1.0, 1.0, 0.4, 0.2));\n let lighting = dot(s, lightingWeights) * 0.7;\n \n // Scale by wave amount (height-based)\n s = s * waveAmount;\n \n // Compute final displacement using dot product with movement vectors\n // Unity: waveMove.x = dot(s, _waveXmove); waveMove.z = dot(s, _waveZmove);\n var waveMove = vec3f(0.0, 0.0, 0.0);\n waveMove.x = dot(s, waveXmove);\n waveMove.z = dot(s, waveZmove);\n \n // Apply displacement scaled by wind amount\n // Unity: vertex.xz -= waveMove.xz * _WaveAndDistance.z;\n // Note: Unity subtracts, we add in the opposite direction for same effect\n let displacement = waveMove * uniforms.g_windAmount;\n \n // Apply wave color tinting (Unity's waveColor calculation)\n // This creates visual bands of lighter/darker grass\n // let waveColor = mix(vec3f(0.5), uniforms.g_windTint.xyz, vec3f(lighting));\n \n // Final world position with waving applied\n let billboardWorld = worldVertexPos - vec3f(displacement.x, 0.0, displacement.z);\n\n // Distance-based culling (Unity-style fade)\n var detailAlpha: f32 = 1.0;\n if (uniforms.g_maxDistance > 0.0) {\n let dist = length(centerW - scene.vEyePosition.xyz);\n let maxD = uniforms.g_maxDistance;\n let fadeStart = uniforms.g_fadeStart;\n if (dist > maxD) { detailAlpha = 0.0; }\n else if (dist > fadeStart) { detailAlpha = 1.0 - ((dist - fadeStart) / max((maxD - fadeStart), 0.0001)); }\n }\n vertexOutputs.vGrassFade = detailAlpha;\n \n // UPDATE worldPos to the animated position BEFORE shadow calculations\n // This is critical for correct shadow receiving - shadows should be stationary\n // while grass moves through them, not move with the grass\n worldPos = vec4f(billboardWorld, 1.0);\n \n // Output\n #if defined(POSITION) || defined(BUMP)\n vertexOutputs.vPositionW = billboardWorld;\n #endif\n #ifdef NORMAL\n vertexOutputs.vNormalW = up;\n #endif\n \n vertexOutputs.position = scene.viewProjection * vec4f(billboardWorld, 1.0);\n "},t.prototype.getGLSLVertexDefinitions=function(){return"\n #ifndef TOOLKIT_GRASS_V_UNIFORMS\n #define TOOLKIT_GRASS_V_UNIFORMS\n uniform vec4 vEyePosition;\n uniform float g_windTime;\n uniform float g_maxDistance;\n uniform float g_fadeStart;\n uniform float g_alphaCutoff;\n uniform float g_waveSpeed;\n uniform float g_waveSize;\n uniform float g_windAmount;\n uniform vec4 g_windTint;\n uniform float g_shadowIntensity;\n uniform float g_sphericalBillboardEnabled;\n #endif\n\n #ifndef TOOLKIT_GRASS_VARYINGS\n #define TOOLKIT_GRASS_VARYINGS\n varying float vGrassFade;\n #endif\n "},t.prototype.getGLSLVertexMainEnd=function(){return""},t.prototype.getGLSLVertexWorldPos=function(){return"\n // Get instance world position (center of grass blade)\n vec3 centerW = (finalWorld * vec4(0.0, 0.0, 0.0, 1.0)).xyz;\n vec3 up = vec3(0.0, 1.0, 0.0);\n \n // Extract instance scale (keep scale, but override rotation with Y-locked billboard basis)\n float sx = length(finalWorld[0].xyz);\n float sy = length(finalWorld[1].xyz);\n float sz = length(finalWorld[2].xyz);\n\n // Compute billboard basis (Y-locked or spherical)\n // Face the camera on XZ plane without tilting unless spherical is enabled\n vec3 eyeW = vEyePosition.xyz;\n vec3 faceDir = centerW - eyeW;\n if (g_sphericalBillboardEnabled < 0.5) {\n faceDir.y = 0.0;\n }\n float faceLen = length(faceDir);\n if (faceLen < 0.0001) {\n faceDir = vec3(0.0, 0.0, 1.0);\n } else {\n faceDir = faceDir / faceLen;\n }\n\n // Safe up reference to avoid degeneracy when looking straight down\n vec3 upRef = up;\n if (abs(faceDir.y) > 0.99) {\n upRef = vec3(0.0, 0.0, 1.0);\n }\n\n vec3 right = normalize(cross(upRef, faceDir));\n vec3 forward = normalize(cross(faceDir, right));\n\n // Compute world position of this vertex BEFORE waving\n vec3 localPos = positionUpdated;\n vec3 worldVertexPos = centerW + right * (localPos.x * sx) + up * (localPos.y * sy) + forward * (localPos.z * sz);\n \n // ============================================================\n // UNITY TerrainWaveGrass EXACT IMPLEMENTATION\n // ============================================================\n \n // Wave amount based on vertex height\n float waveAmount = max(localPos.y, 0.0) * g_windAmount;\n \n // Wave constants tuned for LARGE, GENTLE rolling waves like Unity\n // Key insight: Unity's grass shows broad bands spanning large terrain sections\n // NOT tight ripples - spatial frequency must be very LOW\n float waveSize = g_waveSize;\n \n // Spatial frequencies reduced by 10x from Unity's original values\n // This creates wavelengths of ~50-100 units instead of ~5-10 units\n vec4 waveXSize = vec4(0.0012, 0.002, 0.006, 0.0024) * waveSize;\n vec4 waveZSize = vec4(0.0006, 0.002, 0.002, 0.005) * waveSize;\n \n // Temporal speed reduced for smooth, gentle motion\n vec4 waveSpeedVec = vec4(0.03, 0.05, 0.04, 0.12);\n \n // Movement amplitudes - increased 5x for visible bending like Unity\n vec4 waveXmove = vec4(0.12, 0.2, -0.6, 0.48);\n vec4 waveZmove = vec4(0.06, 0.2, -0.2, 1.0);\n \n // Compute wave phases from BLADE CENTER position\n // Using centerW ensures all vertices of the same blade have identical phase\n vec4 waves = vec4(\n centerW.x * waveXSize.x + centerW.z * waveZSize.x,\n centerW.x * waveXSize.y + centerW.z * waveZSize.y,\n centerW.x * waveXSize.z + centerW.z * waveZSize.z,\n centerW.x * waveXSize.w + centerW.z * waveZSize.w\n );\n \n // Add time component\n float windTime = g_windTime * g_waveSpeed;\n waves += vec4(\n windTime * waveSpeedVec.x,\n windTime * waveSpeedVec.y,\n windTime * waveSpeedVec.z,\n windTime * waveSpeedVec.w\n );\n \n // Keep in 0-1 range\n waves = fract(waves);\n \n // ============================================================\n // FastSinCos - Unity's Taylor series approximation\n // ============================================================\n vec4 wavesRad = waves * 6.408849 - 3.1415927;\n \n // Powers for Taylor series\n vec4 r5 = wavesRad * wavesRad;\n vec4 r6 = r5 * r5;\n vec4 r7 = r6 * r5;\n vec4 r1 = r5 * wavesRad;\n vec4 r2 = r1 * r5;\n vec4 r3 = r2 * r5;\n \n // Taylor series coefficients\n vec4 sin7 = vec4(1.0, -0.16161616, 0.0083333, -0.00019841);\n \n // Compute sine\n vec4 s = wavesRad + r1 * sin7.y + r2 * sin7.z + r3 * sin7.w;\n \n // ============================================================\n // Unity's wave shaping: s = s * s; s = s * s; (s^4)\n // ============================================================\n s = s * s;\n s = s * s;\n \n // Lighting for color tinting\n float lighting = dot(s, normalize(vec4(1.0, 1.0, 0.4, 0.2))) * 0.7;\n \n // Scale by wave amount\n s = s * waveAmount;\n \n // Compute displacement\n vec3 waveMove = vec3(0.0);\n waveMove.x = dot(s, waveXmove);\n waveMove.z = dot(s, waveZmove);\n \n // Apply displacement\n vec3 displacement = waveMove * g_windAmount;\n \n // Final world position\n vec3 billboardWorld = worldVertexPos - vec3(displacement.x, 0.0, displacement.z);\n \n // Distance-based culling\n float detailAlpha = 1.0;\n if (g_maxDistance > 0.0) {\n float dist = distance(vEyePosition.xyz, centerW);\n float maxD = g_maxDistance;\n float fadeStart = g_fadeStart;\n if (dist > maxD) { detailAlpha = 0.0; }\n else if (dist > fadeStart) { detailAlpha = 1.0 - ((dist - fadeStart) / max((maxD - fadeStart), 0.0001)); }\n }\n vGrassFade = detailAlpha;\n \n // UPDATE worldPos to the animated position BEFORE shadow calculations\n // This is critical for correct shadow receiving - shadows should be stationary\n // while grass moves through them, not move with the grass\n worldPos = vec4(billboardWorld, 1.0);\n \n #if defined(POSITION) || defined(BUMP)\n vPositionW = billboardWorld;\n #endif\n #ifdef NORMAL\n vNormalW = up;\n #endif\n \n gl_Position = viewProjection * vec4(billboardWorld, 1.0);\n "},t.prototype.getWGSLFragmentCode=function(){return"\n let detailAlpha = fragmentInputs.vGrassFade;\n let combinedAlpha = alpha * detailAlpha;\n if (combinedAlpha <= uniforms.g_alphaCutoff) { discard; }\n alpha = combinedAlpha;\n \n // Apply shadow intensity - adds ambient light to dark/shadowed areas\n // shadowIntensity controls how much ambient light to add: 0.0 = no ambient, 1.0 = full texture color\n // Simple approach: check if pixel is very dark (likely in shadow) and add ambient\n let shadowIntensity = uniforms.g_shadowIntensity;\n let brightness = max(color.r, max(color.g, color.b));\n // If brightness is below threshold, we're likely in shadow - add ambient light\n // The darker the pixel, the more ambient we add (inverse relationship)\n let shadowThreshold = 0.2;\n let shadowAmount = clamp((shadowThreshold - brightness) / shadowThreshold, 0.0, 1.0);\n // Add ambient light using the grass texture color\n color = vec4f(color.rgb + baseColor.rgb * shadowIntensity * shadowAmount, color.a);\n "},t.prototype.getGLSLFragmentCode=function(){return"\n float detailAlpha = vGrassFade;\n float combinedAlpha = alpha * detailAlpha;\n if (combinedAlpha <= g_alphaCutoff) discard;\n alpha = combinedAlpha;\n \n // Apply shadow intensity - adds ambient light to dark/shadowed areas\n // shadowIntensity controls how much ambient light to add: 0.0 = no ambient, 1.0 = full texture color\n // Simple approach: check if pixel is very dark (likely in shadow) and add ambient\n float shadowIntensity = g_shadowIntensity;\n float brightness = max(color.r, max(color.g, color.b));\n // If brightness is below threshold, we're likely in shadow - add ambient light\n // The darker the pixel, the more ambient we add (inverse relationship)\n float shadowThreshold = 0.2;\n float shadowAmount = clamp((shadowThreshold - brightness) / shadowThreshold, 0.0, 1.0);\n // Add ambient light using the grass texture color\n color.rgb += baseColor.rgb * shadowIntensity * shadowAmount;\n "},t.prototype.getGLSLFragmentDefinitions=function(){return"\n #ifndef TOOLKIT_GRASS_VARYINGS\n #define TOOLKIT_GRASS_VARYINGS\n varying float vGrassFade;\n #endif\n "},t.prototype.getUniforms=function(e){var t=e===BABYLON.ShaderLanguage.WGSL;return this.vertexDefinitions=this.getCustomShaderMaterial().getCustomVertexCode(t),this.fragmentDefinitions=!0===t?this.getCustomShaderMaterial().getCustomFragmentCode(t):null,this.getCustomShaderMaterial().getCustomUniforms(t)},t.prototype.getSamplers=function(e){var t=this.getCustomShaderMaterial().getCustomSamplers();null!=t&&t.length>0&&e.push.apply(e,t)},t.prototype.getAttributes=function(e,t,n){var i=this.getCustomShaderMaterial().getCustomAttributes();null!=i&&i.length>0&&e.push.apply(e,i)},t.prototype.prepareDefines=function(e,t,n){this.getIsEnabled()&&this.getCustomShaderMaterial().prepareCustomDefines(e)},t.prototype.bindForSubMesh=function(e,t,n,i){this.getIsEnabled()&&this.getCustomShaderMaterial().updateCustomBindings(e)},t}(e.StandardShaderMaterialPlugin);e.GrassBillboardMaterialPlugin=n,e.SceneManager.RegisterClass("TOOLKIT.GrassStandardMaterial",e.GrassStandardMaterial),e.SceneManager.RegisterClass("TOOLKIT.GrassStandardMaterialPlugin",e.GrassStandardMaterialPlugin)}(i||(i={})),function(e){var t=function(t){function n(n,i){var r=t.call(this,n,i)||this;return r._windTimeAccum=0,r.shader=r.getShaderName(),r.plugin=new e.TreeBranchMaterialPlugin(r,r.shader),r.addFloatUniform("g_windTime",0),r.addFloatUniform("g_windAmount",.5),r.addFloatUniform("g_windSpeed",1),r.addFloatUniform("g_windStrength",.5),r.addVector4Uniform("g_windDirection",new BABYLON.Vector4(1,0,0,0)),r.addFloatUniform("g_branchRootY",0),r.addFloatUniform("g_branchMaxAngle",.35),r.addFloatUniform("g_branchMaxHeight",2),r.addFloatUniform("g_useVertexColorMask",1),r.addFloatUniform("g_spatialFrequency",.15),r._windTimeAccum=0,r}return r(n,t),n.prototype.awake=function(){},n.prototype.update=function(){var t;try{var n=e.SceneManager.GetDeltaSeconds(this.getScene()),i=Math.min(n,1/30);(null!==(t=this.getFloatValue("g_windSpeed"))&&void 0!==t?t:0)>0&&(this._windTimeAccum+=i,this.setFloatValue("g_windTime",this._windTimeAccum))}catch(e){}},n.prototype.getShaderName=function(){return"TreeBranchMaterial"},n.prototype.setWindDirection=function(e,t,n){var i=new BABYLON.Vector3(e,t,n);i.lengthSquared()<1e-8?this.setVector4Value("g_windDirection",new BABYLON.Vector4(1,0,0,0)):(i.normalize(),this.setVector4Value("g_windDirection",new BABYLON.Vector4(i.x,i.y,i.z,0)))},n.prototype.getWindDirection=function(){return this.getVector4Value("g_windDirection")},n}(e.CustomShaderMaterial);e.TreeBranchMaterial=t;var n=function(e){function t(t,n){return e.call(this,t,n,110,{TREEBRANCHMATERIAL:!1})||this}return r(t,e),t.prototype.isCompatible=function(e){return e===BABYLON.ShaderLanguage.WGSL||e===BABYLON.ShaderLanguage.GLSL},t.prototype.getCustomCode=function(e,t){return"vertex"===e?t===BABYLON.ShaderLanguage.WGSL?{CUSTOM_VERTEX_MAIN_END:"\n // -------------------------\n // TreeBranch wind bending (local-space)\n // Authoring (recommended):\n // vertexColor.r = bend weight (0 trunk .. 1 tips)\n // vertexColor.g = phase offset noise (0..1)\n // Falls back to height-based weight if vertex color missing/disabled.\n // -------------------------\n\n fn safeNormalize(v: vec3f) -> vec3f {\n let lsq = dot(v, v);\n if (lsq < 1e-8) { return vec3f(1.0, 0.0, 0.0); }\n return v * inverseSqrt(lsq);\n }\n\n fn rotateRodrigues(p: vec3f, axis: vec3f, angle: f32) -> vec3f {\n let a = safeNormalize(axis);\n let c = cos(angle);\n let s = sin(angle);\n return p * c + cross(a, p) * s + a * dot(a, p) * (1.0 - c);\n }\n\n // Local position & normal (preferred: use normalUpdated if present in shader)\n var pL: vec3f = positionUpdated;\n\n // If COLOR attribute exists, Babylon usually provides vertexInputs.color.\n // If not available, these will be 1,1,1,1 (depending on pipeline) — we guard with g_useVertexColorMask.\n var bendMask: f32 = 1.0;\n var phaseNoise: f32 = 0.0;\n if (uniforms.g_useVertexColorMask > 0.5) {\n bendMask = clamp(vertexInputs.color.r, 0.0, 1.0);\n phaseNoise = vertexInputs.color.g; // 0..1\n }\n\n // Height-based fallback weight (normalized between rootY..maxHeight)\n let denom = max(uniforms.g_branchMaxHeight - uniforms.g_branchRootY, 1e-3);\n let h01 = clamp((pL.y - uniforms.g_branchRootY) / denom, 0.0, 1.0);\n\n // Final per-vertex weight:\n // - If using vertex colors: bendMask * smooth tip emphasis\n // - Else: height-based\n var w: f32 = h01;\n if (uniforms.g_useVertexColorMask > 0.5) {\n w = bendMask * (h01 * h01 * (3.0 - 2.0 * h01)); // smoothstep(h01)\n } else {\n w = h01 * h01; // a bit stiffer near base\n }\n\n // Wind direction in LOCAL space:\n // We transform windDirWorld by inverse world matrix rotation (approx using finalWorld columns).\n // finalWorld transforms local->world. For direction, inverse rotation is transpose of 3x3 if no shear.\n let windW = safeNormalize(uniforms.g_windDirection.xyz);\n let rightW = safeNormalize(finalWorld[0].xyz);\n let upW = safeNormalize(finalWorld[1].xyz);\n let fwdW = safeNormalize(finalWorld[2].xyz);\n\n // Convert world dir to local by dot with basis\n let windL = safeNormalize(vec3f(dot(windW, rightW), dot(windW, upW), dot(windW, fwdW)));\n\n // Bend axis: perpendicular to up and wind, in LOCAL space\n var axisL = safeNormalize(cross(vec3f(0.0, 1.0, 0.0), windL));\n if (dot(axisL, axisL) < 1e-6) { axisL = vec3f(1.0, 0.0, 0.0); }\n\n // Spatially varying phase so whole tree doesn't move as a rigid sheet\n // Use local xz for coherence; optionally mod by vertexColor.g\n let spatial = (pL.x + pL.z) * uniforms.g_spatialFrequency;\n let phase = uniforms.g_windTime * uniforms.g_windSpeed\n + spatial * uniforms.g_windStrength\n + phaseNoise * 6.28318;\n\n // Two-wave composite like Unity-ish wind\n let base = sin(phase);\n let gust = 0.5 * sin(phase * 1.7 + 1.2);\n let sway = (base + gust) * uniforms.g_windAmount;\n\n // Convert sway to angle (clamped)\n var angle = sway * w * uniforms.g_branchMaxAngle;\n angle = clamp(angle, -uniforms.g_branchMaxAngle, uniforms.g_branchMaxAngle);\n\n // Pivot in local space\n let pivotL = vec3f(0.0, uniforms.g_branchRootY, 0.0);\n let relL = pL - pivotL;\n let bentRelL = rotateRodrigues(relL, axisL, angle);\n let bentPL = pivotL + bentRelL;\n\n // Transform to world using finalWorld (keeps proper anchoring)\n let branchWorld = (finalWorld * vec4f(bentPL, 1.0)).xyz;\n\n // Rotate normal similarly (only if NORMAL is active)\n #ifdef NORMAL\n // Babylon WGSL PBR usually provides normalUpdated in local/object space\n var nL: vec3f = normalize(normalUpdated);\n let bentNL = rotateRodrigues(nL, axisL, angle);\n // Convert to world by world 3x3\n let nW = normalize(vec3f(\n dot(bentNL, vec3f(finalWorld[0].x, finalWorld[0].y, finalWorld[0].z)),\n dot(bentNL, vec3f(finalWorld[1].x, finalWorld[1].y, finalWorld[1].z)),\n dot(bentNL, vec3f(finalWorld[2].x, finalWorld[2].y, finalWorld[2].z))\n ));\n vertexOutputs.vNormalW = nW;\n #endif\n\n #if defined(POSITION) || defined(BUMP)\n vertexOutputs.vPositionW = branchWorld;\n #endif\n\n vertexOutputs.position = scene.viewProjection * vec4f(branchWorld, 1.0);\n "}:{CUSTOM_VERTEX_DEFINITIONS:"\n uniform float g_windTime;\n uniform float g_windAmount;\n uniform float g_windSpeed;\n uniform float g_windStrength;\n uniform vec4 g_windDirection;\n\n uniform float g_branchRootY;\n uniform float g_branchMaxAngle;\n uniform float g_branchMaxHeight;\n uniform float g_useVertexColorMask;\n uniform float g_spatialFrequency;\n\n vec3 safeNormalize(vec3 v) {\n float lsq = dot(v, v);\n if (lsq < 1e-8) return vec3(1.0, 0.0, 0.0);\n return v * inversesqrt(lsq);\n }\n\n vec3 rotateRodrigues(vec3 p, vec3 axis, float angle) {\n vec3 a = safeNormalize(axis);\n float c = cos(angle);\n float s = sin(angle);\n return p * c + cross(a, p) * s + a * dot(a, p) * (1.0 - c);\n }\n ",CUSTOM_VERTEX_MAIN_END:"\n // Local/object position\n vec3 pL = positionUpdated;\n\n // Vertex color mask (recommended authoring)\n float bendMask = 1.0;\n float phaseNoise = 0.0;\n #ifdef VERTEXCOLOR\n if (g_useVertexColorMask > 0.5) {\n bendMask = clamp(color.r, 0.0, 1.0);\n phaseNoise = color.g;\n }\n #endif\n\n float denom = max(g_branchMaxHeight - g_branchRootY, 1e-3);\n float h01 = clamp((pL.y - g_branchRootY) / denom, 0.0, 1.0);\n\n float w = h01;\n if (g_useVertexColorMask > 0.5) {\n // smoothstep(h01)\n w = bendMask * (h01 * h01 * (3.0 - 2.0 * h01));\n } else {\n w = h01 * h01;\n }\n\n // Convert wind world dir to local using world basis (transpose approx)\n vec3 windW = safeNormalize(g_windDirection.xyz);\n vec3 rightW = safeNormalize(finalWorld[0].xyz);\n vec3 upW = safeNormalize(finalWorld[1].xyz);\n vec3 fwdW = safeNormalize(finalWorld[2].xyz);\n vec3 windL = safeNormalize(vec3(dot(windW, rightW), dot(windW, upW), dot(windW, fwdW)));\n\n vec3 axisL = safeNormalize(cross(vec3(0.0, 1.0, 0.0), windL));\n if (dot(axisL, axisL) < 1e-6) axisL = vec3(1.0, 0.0, 0.0);\n\n float spatial = (pL.x + pL.z) * g_spatialFrequency;\n float phase = g_windTime * g_windSpeed\n + spatial * g_windStrength\n + phaseNoise * 6.2831853;\n\n float base = sin(phase);\n float gust = 0.5 * sin(phase * 1.7 + 1.2);\n float sway = (base + gust) * g_windAmount;\n\n float angle = clamp(sway * w * g_branchMaxAngle, -g_branchMaxAngle, g_branchMaxAngle);\n\n vec3 pivotL = vec3(0.0, g_branchRootY, 0.0);\n vec3 relL = pL - pivotL;\n vec3 bentPL = pivotL + rotateRodrigues(relL, axisL, angle);\n\n vec3 branchWorld = (finalWorld * vec4(bentPL, 1.0)).xyz;\n\n #if defined(POSITION) || defined(BUMP)\n vPositionW = branchWorld;\n #endif\n\n #ifdef NORMAL\n // normalUpdated is local/object normal\n vec3 nL = normalize(normalUpdated);\n vec3 bentNL = rotateRodrigues(nL, axisL, angle);\n\n // world normal from world basis (approx; assumes no non-uniform scale/shear)\n vec3 nW = normalize(bentNL.x * rightW + bentNL.y * upW + bentNL.z * fwdW);\n vNormalW = nW;\n #endif\n\n gl_Position = viewProjection * vec4(branchWorld, 1.0);\n "}:"fragment"===e?(BABYLON.ShaderLanguage.WGSL,{CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:"\n // no-op\n "}):null},t.prototype.getUniforms=function(e){var t=e===BABYLON.ShaderLanguage.WGSL;return this.vertexDefinitions=this.getCustomShaderMaterial().getCustomVertexCode(t),this.fragmentDefinitions=!0===t?this.getCustomShaderMaterial().getCustomFragmentCode(t):null,this.getCustomShaderMaterial().getCustomUniforms(t)},t.prototype.getSamplers=function(e){var t=this.getCustomShaderMaterial().getCustomSamplers();t&&t.length>0&&e.push.apply(e,t)},t.prototype.getAttributes=function(e,t,n){var i=this.getCustomShaderMaterial().getCustomAttributes();i&&i.length>0&&e.push.apply(e,i),-1===e.indexOf("color")&&e.push("color")},t.prototype.prepareDefines=function(e,t,n){this.getIsEnabled()&&this.getCustomShaderMaterial().prepareCustomDefines(e)},t.prototype.bindForSubMesh=function(e,t,n,i){this.getIsEnabled()&&this.getCustomShaderMaterial().updateCustomBindings(e)},t.ExtractWindZoneOverride=function(e,t,n){var i,r=[];e&&r.push(e),e&&e.properties&&r.push(e.properties);var o=null==t?void 0:t.metadata;o&&r.push(o),o&&o.toolkit&&r.push(o.toolkit),o&&o.properties&&r.push(o.properties);var a=null==n?void 0:n.metadata;a&&r.push(a),a&&a.toolkit&&r.push(a.toolkit);var s=null===(i=null==n?void 0:n.transform)||void 0===i?void 0:i.metadata;s&&r.push(s),s&&s.toolkit&&r.push(s.toolkit);for(var l=null,u=0,c=r;u<c.length;u++){var d=c[u];if(d&&Array.isArray(d.windzones)){l=d.windzones;break}}if(!l||0===l.length)return null;for(var h=null,p=-1e9,m=0,f=l;m<f.length;m++){var g=f[m];if(g){var v=((null!=g.type?g.type:null!=g.mode?g.mode:"").toString().toLowerCase().indexOf("direction")>=0?1e3:0)+(null!=g.windMain?g.windMain:0);v>p&&(p=v,h=g)}}return h},t}(e.CustomShaderMaterialPlugin);e.TreeBranchMaterialPlugin=n,e.SceneManager.RegisterClass("TOOLKIT.TreeBranchMaterial",t),e.SceneManager.RegisterClass("TOOLKIT.TreeBranchMaterialPlugin",n)}(i||(i={})),function(e){var t=function(t){function n(n,i){var r=t.call(this,n,i)||this;return r.controller=null,r.runtimeAlbedoSkins=null,r.runtimeNormalSkins=null,r.shader=r.getShaderName(),r.addAttribute("g_vatAnim0"),r.addAttribute("g_vatAnim1"),r.addFloatUniform("g_vatTexWidth",1),r.addFloatUniform("g_vatTexHeight",1),r.addFloatUniform("g_vatRowsPerFrame",1),r.addFloatUniform("g_vatVertexCount",1),r.addVector3Uniform("g_vatPosMin",BABYLON.Vector3.Zero()),r.addVector3Uniform("g_vatPosMax",BABYLON.Vector3.One()),r.addFloatUniform("g_vatPrevTexWidth",1),r.addFloatUniform("g_vatPrevTexHeight",1),r.addFloatUniform("g_vatPrevRowsPerFrame",1),r.addVector3Uniform("g_vatPrevPosMin",BABYLON.Vector3.Zero()),r.addVector3Uniform("g_vatPrevPosMax",BABYLON.Vector3.One()),r.addTextureUniform("vatPosition",null),r.addTextureUniform("vatNormal",null),r.addTextureUniform("vatPrevPosition",null),r.addTextureUniform("vatPrevNormal",null),r.markTextureAsRaw("vatPosition"),r.markTextureAsRaw("vatNormal"),r.markTextureAsRaw("vatPrevPosition"),r.markTextureAsRaw("vatPrevNormal"),r.plugin=new e.VertexAnimationMaterialPlugin(r,r.shader),r}return r(n,t),n.prototype.awake=function(){console.warn("VertexAnimationMaterial - Awake(): "+this.name)},n.prototype.update=function(){},n.prototype.getShaderName=function(){return"VertexAnimationMaterial"},n.prototype.getController=function(){return this.controller},n.prototype.cloneForInstance=function(t){var n=this.getScene(),i=new e.VertexAnimationMaterial(t,n);return i.albedoColor=this.albedoColor?this.albedoColor.clone():i.albedoColor,i.albedoTexture=this.albedoTexture,i.reflectivityColor=this.reflectivityColor?this.reflectivityColor.clone():i.reflectivityColor,i.reflectivityTexture=this.reflectivityTexture,i.metallicTexture=this.metallicTexture,i.metallic=this.metallic,i.roughness=this.roughness,i.metallicF0Factor=this.metallicF0Factor,i.bumpTexture=this.bumpTexture,i.emissiveColor=this.emissiveColor?this.emissiveColor.clone():i.emissiveColor,i.emissiveTexture=this.emissiveTexture,i.ambientColor=this.ambientColor?this.ambientColor.clone():i.ambientColor,i.ambientTexture=this.ambientTexture,i.opacityTexture=this.opacityTexture,i.useAlphaFromAlbedoTexture=this.useAlphaFromAlbedoTexture,i.twoSidedLighting=this.twoSidedLighting,i.backFaceCulling=this.backFaceCulling,i.sideOrientation=this.sideOrientation,i.alpha=this.alpha,i.alphaMode=this.alphaMode,i.transparencyMode=this.transparencyMode,i.runtimeAlbedoSkins=this.runtimeAlbedoSkins,i.runtimeNormalSkins=this.runtimeNormalSkins,i._notifyPluginOfRuntimeSkinChange(),i},n.prototype.setRuntimeSkinArrays=function(e,t,n){void 0===n&&(n=!0),this.runtimeAlbedoSkins=e||null,this.runtimeNormalSkins=t||null,n&&(this.albedoTexture=null,this.bumpTexture=null),this._notifyPluginOfRuntimeSkinChange()},n.prototype.clearRuntimeSkinArrays=function(){this.runtimeAlbedoSkins=null,this.runtimeNormalSkins=null,this._notifyPluginOfRuntimeSkinChange()},n.prototype.installSkinsFromUrlsAsync=function(e,t,n,i){return a(this,void 0,void 0,function(){var r,o,a,l,u,c,d,h,p,m,f,g,v,y,_,S;return s(this,function(s){switch(s.label){case 0:if(!e||0===e.length)throw new Error("VertexAnimationMaterial.installSkinsFromUrlsAsync: layers list is empty.");for(o=!1!==(r=i||{}).nullOutDefaults,a=r.rootUrl||"",l=!1!==r.generateMipMaps,u=null!=r.samplingMode?r.samplingMode:BABYLON.Texture.TRILINEAR_SAMPLINGMODE,c=this.getScene(),d=e.length,h=t*n*4,p=new Uint8Array(h*d),m=new Uint8Array(h*d),f=function(e){if(!e)return"";if(e.indexOf("://")>=0||0===e.indexOf("blob:")||0===e.indexOf("data:")||0===e.indexOf("/"))return e;if(a){var t="/"===a.charAt(a.length-1)?"":"/";return a+t+e}return e},g=function(e,i,r,o){return new Promise(function(a,s){var l=f(e),d=new BABYLON.Texture(l,c,!0,!0,u,function(){var e=d.getSize();if(e.width!==t||e.height!==n)return d.dispose(),void s(new Error("".concat(o," '").concat(l,"' is ").concat(e.width,"x").concat(e.height,", expected ").concat(t,"x").concat(n,".")));var u=d.readPixels(),c=function(e){if(!e)return d.dispose(),void s(new Error("".concat(o," '").concat(l,"': readPixels returned null.")));i.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r*h),d.dispose(),a()};u&&"function"==typeof u.then?u.then(c).catch(function(e){d.dispose(),s(e)}):c(u)},function(e){return s(new Error("".concat(o," '").concat(l,"' load failed: ").concat(e)))})})},v=[],y=0;y<d;y++)v.push(g(e[y].albedo,p,y,"Skin albedo")),v.push(g(e[y].normal,m,y,"Skin normal"));return[4,Promise.all(v)];case 1:return s.sent(),_=BABYLON.RawTexture2DArray.CreateRGBATexture(p,t,n,d,c,l,!1,u),(S=BABYLON.RawTexture2DArray.CreateRGBATexture(m,t,n,d,c,l,!1,u)).gammaSpace=!1,this.setRuntimeSkinArrays(_,S,o),[2]}})})},n.prototype._notifyPluginOfRuntimeSkinChange=function(){var e=this.plugin;e&&"function"==typeof e.onRuntimeSkinArraysChanged&&e.onRuntimeSkinArraysChanged(),this.markAsDirty(BABYLON.Constants.MATERIAL_AllDirtyFlag)},n}(e.CustomShaderMaterial);e.VertexAnimationMaterial=t;var n=function(){function t(e,t,n,i){var r=this;this._plugins=[],this._clips={},this._currentClip=null,this._previousClip=null,this._time=0,this._previousTime=0,this._speed=1,this._loop=!1,this._loopBlend=!1,this._manualLoopOverride=null,this._playing=!1,this._blendDuration=0,this._blendElapsed=0,this._blendWeight=1,this._mode="auto",this._normalMode="none",this._lazyLoad=!1,this._tickObserver=null,this._disposeObserver=null,this._lastFrameId=-1,this._textureCache={},this._textureCacheKeys={},this._instanceMeshes={},this.guid=e,this.scene=t,this.rootUrl=n||"",this._lazyLoad=!0===i,this._tickObserver=t.onBeforeRenderObservable.add(function(){return r._tick()}),this._disposeObserver=t.onDisposeObservable.addOnce(function(){return r.dispose()})}return t.Find=function(t){return t&&e.VertexAnimationController._registry[t]||null},t.GetOrCreate=function(t,n,i,r){if(void 0===i&&(i=""),void 0===r&&(r=!1),!t)throw new Error("VertexAnimationController: vertexcontroller is required.");var o=e.VertexAnimationController._registry[t];return o||(o=new e.VertexAnimationController(t,n,i,r),e.VertexAnimationController._registry[t]=o),o},t.CollectRendererTargets=function(e){var t=[],n={};if(!e)return t;for(var i=0,r=e;i<r.length;i++){var o=r[i];if(o){var a=o.vertexguid||o.vertexpath||o.vertextransform||o.name;a&&!n[a]&&(n[a]=!0,t.push(o))}}return t},t.SetSkinIndex=function(e,t){e&&(e.runtimeSkinIndex=Math.max(0,Math.floor(t||0)))},t.GetSkinIndex=function(e){if(!e)return 0;var t=e.runtimeSkinIndex;return"number"==typeof t&&isFinite(t)&&t>=0?Math.floor(t):0},t.DisposeAll=function(t){for(var n=0,i=Object.keys(e.VertexAnimationController._registry);n<i.length;n++){var r=i[n],o=e.VertexAnimationController._registry[r];t&&o.scene!==t||o.dispose()}},t.prototype.setInstanceMesh=function(e,t){e&&t&&(this._instanceMeshes[e]=t)},t.prototype.dispose=function(){this._tickObserver&&(this.scene.onBeforeRenderObservable.remove(this._tickObserver),this._tickObserver=null),this._disposeObserver&&(this.scene.onDisposeObservable.remove(this._disposeObserver),this._disposeObserver=null);for(var n=0,i=Object.keys(this._textureCacheKeys);n<i.length;n++){var r=i[n];e.VertexAnimationController._releaseVATTexture(this.scene,r)}this._textureCache={},this._textureCacheKeys={},this._clips={},this._plugins.length=0,this._currentClip=null,this._previousClip=null,delete t._registry[this.guid]},Object.defineProperty(t.prototype,"currentClip",{get:function(){return this._currentClip},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"previousClip",{get:function(){return this._previousClip},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"currentTime",{get:function(){return this._time},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"previousTime",{get:function(){return this._previousTime},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"blendWeight",{get:function(){return this._blendWeight},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isPlaying",{get:function(){return this._playing},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"normalMode",{get:function(){return this._normalMode},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"loopBlend",{get:function(){return this._loopBlend},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"mode",{get:function(){return this._mode},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"speed",{get:function(){return this._speed},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"loopOverride",{get:function(){return this._manualLoopOverride},enumerable:!1,configurable:!0}),t.prototype.getClip=function(e){return e&&this._clips[e]||null},t.prototype.setSpeed=function(e){this._speed=e},t.prototype.setLoop=function(e){this._manualLoopOverride=e,this._loop=e},t.prototype.setRuntimeSkinArrays=function(e,t,n){void 0===n&&(n=!0);for(var i=0;i<this._plugins.length;i++){var r=this._plugins[i].getCustomShaderMaterial();r&&r.setRuntimeSkinArrays(e,t,n)}},t.prototype.clearRuntimeSkinArrays=function(){for(var e=0;e<this._plugins.length;e++){var t=this._plugins[e].getCustomShaderMaterial();t&&t.clearRuntimeSkinArrays()}},t.prototype.installSkinsFromUrlsAsync=function(e,t,n,i){return a(this,void 0,void 0,function(){var r,a,l,u,c,d,h,p;return s(this,function(s){switch(s.label){case 0:if(0===this._plugins.length)throw new Error("VertexAnimationController.installSkinsFromUrlsAsync: no registered VAT materials.");return a=o(o({},r=i||{}),{rootUrl:r.rootUrl||this.rootUrl}),l=!1!==r.nullOutDefaults,[4,(u=this._plugins[0].getCustomShaderMaterial()).installSkinsFromUrlsAsync(e,t,n,a)];case 1:for(s.sent(),c=u.runtimeAlbedoSkins,d=u.runtimeNormalSkins,h=1;h<this._plugins.length;h++)(p=this._plugins[h].getCustomShaderMaterial())&&p.setRuntimeSkinArrays(c,d,l);return[2]}})})},t.prototype.setCurrentTime=function(e){if(this._currentClip){var t=this._currentClip.duration;this._time=e,t>0?this._loop?this._time=this._wrapTime(this._time,t):this._time=Math.max(0,Math.min(this._time,t)):this._time=Math.max(0,this._time)}},t.prototype.getCurrentTime=function(){return this._time},t.prototype.addPlugin=function(e){-1===this._plugins.indexOf(e)&&this._plugins.push(e)},t.prototype.removePlugin=function(e){var t=this._plugins.indexOf(e);-1!==t&&this._plugins.splice(t,1)},t.prototype.loadAnimations=function(e){var t;if(e&&0!==e.length){"none"===this._normalMode&&e[0]&&e[0].vertexpacking&&(this._normalMode=e[0].vertexpacking);for(var n=0,i=e;n<i.length;n++){var r=i[n];if(r&&r.name){var o=r.vertexguid||r.vertextransform;if(o){var a=this._clips[r.name];if(a||(a={name:r.name,renderers:{},firstRendererGuid:o,duration:0,loop:!1,loopBlend:!1},this._clips[r.name]=a),a.firstRendererGuid||(a.firstRendererGuid=o),!a.renderers[o]){a.renderers&&0===Object.keys(a.renderers).length&&(a.loop=!0===r.vertexlooptime,a.loopBlend=!0===r.vertexloopblend);var s=null,l=null;this._lazyLoad||(s=this._getOrAcquireTexture(r.vertex),l="separate"===r.vertexpacking&&r.vertexnormal?this._getOrAcquireTexture(r.vertexnormal):null),a.renderers[o]={guid:o,settings:r,positionTexture:s,normalTexture:l,posMinV3:BABYLON.Vector3.FromArray(r.vertexposmin),posMaxV3:BABYLON.Vector3.FromArray(r.vertexposmax),fromRow:r.vertexcombined&&null!==(t=r.vertexfromrow)&&void 0!==t?t:0};var u=r.vertexframes>0&&r.vertexfps>0?r.vertexframes/r.vertexfps:0;u>a.duration&&(a.duration=u)}}}}}},t.prototype.play=function(e,t){void 0===t&&(t=.1);var n=this._clips[e];return n?(this._mode="auto",this._ensureClipTexturesLoaded(n),t>0&&this._currentClip&&this._currentClip!==n?(this._ensureClipTexturesLoaded(this._currentClip),this._previousClip=this._currentClip,this._previousTime=this._time,this._blendDuration=t,this._blendElapsed=0,this._blendWeight=0):(this._previousClip=null,this._blendDuration=0,this._blendElapsed=0,this._blendWeight=1),this._currentClip=n,this._time=0,this._playing=!0,this._loop=null!==this._manualLoopOverride?this._manualLoopOverride:!!n.loop,this._loopBlend=!!n.loopBlend,!0):(console.error("VertexAnimationController '".concat(this.guid,"': No clip found with name '").concat(e,"'.")),!1)},t.prototype.pause=function(){this._playing=!1},t.prototype.resume=function(){this._currentClip&&(this._playing=!0)},t.prototype.stop=function(){this._mode="auto",this._playing=!1,this._time=0,this._previousClip=null,this._previousTime=0,this._blendDuration=0,this._blendElapsed=0,this._blendWeight=1},t.prototype.driveBlend=function(e,t,n,i,r){var o=e?this._clips[e]:null;if(!o)return!1;this._ensureClipTexturesLoaded(o);var a=n?this._clips[n]:null;return a&&this._ensureClipTexturesLoaded(a),this._mode="drive",this._playing=!0,this._currentClip=o,this._time=t,this._previousClip=a||null,this._previousTime=a?i:0,this._blendDuration=0,this._blendElapsed=0,this._blendWeight=r<0?0:r>1?1:r,this._loop=null!==this._manualLoopOverride?this._manualLoopOverride:!!o.loop,this._loopBlend=!!o.loopBlend,!0},t.prototype.getCurrentRendererClip=function(e){return this._getRendererClip(this._currentClip,e)},t.prototype.getPreviousRendererClip=function(e){return this._getRendererClip(this._previousClip,e)},t.prototype._tick=function(){var e=this.scene.getFrameId();if(this._lastFrameId!==e){if(this._lastFrameId=e,"auto"===this._mode&&this._playing&&this._currentClip){var t=this.scene.getEngine().getDeltaTime()/1e3,n=Math.min(t,1/30);this._time+=n*this._speed;var i=this._currentClip.duration;if(i>0&&(this._loop?this._time=this._wrapTime(this._time,i):this._time>=i?(this._time=i,this._playing=!1):this._time<0&&(this._time=0,this._playing=!1)),this._previousClip){this._previousTime+=n*this._speed;var r=this._previousClip.duration;r>0&&this._previousTime>r&&(this._previousTime=r),r>0&&this._previousTime<0&&(this._previousTime=0)}this._blendDuration>0&&(this._areBlendTargetsReady()?(this._blendElapsed+=n,this._blendWeight=Math.min(1,this._blendElapsed/this._blendDuration),this._blendWeight>=1&&(this._previousClip=null,this._blendDuration=0,this._blendElapsed=0)):(this._blendElapsed=0,this._blendWeight=0))}for(var o=0,a=Object.keys(this._instanceMeshes);o<a.length;o++){var s=a[o],l=this._instanceMeshes[s];if(l&&l.instancedBuffers){var u=l.instancedBuffers,c=this._getOrCreateVATBuffer(u,"g_vatAnim0"),d=this._getOrCreateVATBuffer(u,"g_vatAnim1"),h=this.getCurrentRendererClip(s);if(h&&this._currentClip&&this._isRendererPositionReady(h)){var p=h.settings;c.set(this._time*p.vertexfps,p.vertexframes,h.fromRow,this._blendWeight);var m=this._loopBlend?1:0,f=l.runtimeSkinIndex,g="number"==typeof f&&f>=0?f:0;d.w=2*g+m;var v=this.getPreviousRendererClip(s);if(v&&this._previousClip&&this._blendWeight<.999&&this._isRendererPositionReady(v)){var y=v.settings;d.x=this._previousTime*y.vertexfps,d.y=y.vertexframes,d.z=v.fromRow}else d.x=0,d.y=0,d.z=0}else c.set(0,0,0,1),d.set(0,0,0,0)}}for(var _=0;_<this._plugins.length;_++){var S=this._plugins[_],A=S.getCustomShaderMaterial();S.syncFromController(A,this)}}},t.prototype._getOrCreateVATBuffer=function(e,t){var n=e[t];return n&&"function"==typeof n.set||(n=new BABYLON.Vector4(0,0,0,0),e[t]=n),n},t.prototype._isRendererPositionReady=function(e){var t=e?e.positionTexture:null;return!(!t||"function"!=typeof t.isReady||!t.isReady())},t.prototype._areBlendTargetsReady=function(){if(!this._previousClip)return!0;for(var e=0,t=Object.keys(this._instanceMeshes);e<t.length;e++){var n=t[e],i=this.getCurrentRendererClip(n),r=this.getPreviousRendererClip(n);if(!this._isRendererPositionReady(i)||!this._isRendererPositionReady(r))return!1}return!0},t.prototype._wrapTime=function(e,t){if(t<=0)return 0;var n=e%t;return n<0&&(n+=t),n},t.prototype._ensureClipTexturesLoaded=function(e){if(e&&e.renderers)for(var t=0,n=Object.keys(e.renderers);t<n.length;t++){var i=n[t],r=e.renderers[i];r&&(!r.positionTexture&&r.settings.vertex&&(r.positionTexture=this._getOrAcquireTexture(r.settings.vertex)),!r.normalTexture&&"separate"===r.settings.vertexpacking&&r.settings.vertexnormal&&(r.normalTexture=this._getOrAcquireTexture(r.settings.vertexnormal)))}},t.prototype._getOrAcquireTexture=function(t){if(!t)return null;var n=this._resolveUrl(t),i=this._textureCache[n];return i||(i=e.VertexAnimationController._acquireVATTexture(this.scene,n),this._textureCache[n]=i,this._textureCacheKeys[n]=!0,i)},t._acquireVATTexture=function(t,n){var i=e.VertexAnimationController._makeVATTextureCacheKey(t,n),r=e.VertexAnimationController._globalTextureCache[i];if(r&&r.texture)return r.refs++,r.texture;var o=e.VertexAnimationController._createVATTexture(t,n);return e.VertexAnimationController._globalTextureCache[i]={texture:o,refs:1},o},t._releaseVATTexture=function(t,n){var i=e.VertexAnimationController._makeVATTextureCacheKey(t,n),r=e.VertexAnimationController._globalTextureCache[i];r&&(r.refs--,r.refs<=0&&(r.texture&&r.texture.dispose(),delete e.VertexAnimationController._globalTextureCache[i]))},t._makeVATTextureCacheKey=function(e,t){var n=e?e.getEngine():null;return[n&&null!=n.uid?n.uid:n&&null!=n._uid?n._uid:n&&n.getClassName?n.getClassName():"engine",e&&null!=e.uid?e.uid:e&&null!=e._uid?e._uid:e&&e.metadata&&e.metadata.guid?e.metadata.guid:"scene",t,"VAT","noMipmap=true","invertY=true","sampling=NEAREST_NEAREST","wrap=CLAMP","gammaSpace=false"].join("|")},t._createVATTexture=function(e,t){var n=new BABYLON.Texture(t,e,!0,!0,BABYLON.Texture.NEAREST_NEAREST);return n.wrapU=BABYLON.Texture.CLAMP_ADDRESSMODE,n.wrapV=BABYLON.Texture.CLAMP_ADDRESSMODE,n.anisotropicFilteringLevel=1,n.gammaSpace=!1,n},t.prototype._resolveUrl=function(e){if(!e)return"";if(e.indexOf("://")>=0||0===e.indexOf("blob:")||0===e.indexOf("data:")||0===e.indexOf("/"))return e;if(this.rootUrl){var t="/"===this.rootUrl.charAt(this.rootUrl.length-1)?"":"/";return this.rootUrl+t+e}return e},t.prototype._getRendererClip=function(e,t){if(!e||!e.renderers)return null;if(t&&e.renderers[t])return e.renderers[t];if(e.firstRendererGuid&&e.renderers[e.firstRendererGuid])return e.renderers[e.firstRendererGuid];var n=Object.keys(e.renderers);return n.length>0?e.renderers[n[0]]:null},t._registry={},t._globalTextureCache={},t}();e.VertexAnimationController=n;var i=function(t){function n(e,n){var i=t.call(this,e,n,100,{VERTEXANIMATIONMATERIAL:!1,VAT_NORMAL_SEPARATE:!1,RUNTIME_SKINS_ALBEDO:!1,RUNTIME_SKINS_NORMAL:!1,RUNTIME_SKINS_NORMAL_DERIVE_TBN:!1})||this;i.vertexAnimations=null,i.controller=null,i._rendererTargets=[],i._targetRendererGuid="",i._placeholderTexture=null,i._placeholderAlbedoArray=null,i._placeholderNormalArray=null,i._cc_posTex=null,i._cc_normTex=null,i._cc_prevPosTex=null,i._cc_prevNormTex=null,i._cc_texW=1,i._cc_texH=1,i._cc_rowsPF=1,i._cc_vCount=1,i._cc_posMin=null,i._cc_posMax=null,i._cc_prevTexW=1,i._cc_prevTexH=1,i._cc_prevRowsPF=1,i._cc_prevPosMin=null,i._cc_prevPosMax=null;var r=e.getScene();i._placeholderTexture=BABYLON.RawTexture.CreateRGBATexture(new Uint8Array([128,128,128,255]),1,1,r,!1,!1,BABYLON.Texture.NEAREST_SAMPLINGMODE),e.setTextureValue("vatPosition",i._placeholderTexture),e.setTextureValue("vatNormal",i._placeholderTexture),e.setTextureValue("vatPrevPosition",i._placeholderTexture),e.setTextureValue("vatPrevNormal",i._placeholderTexture);var o=new Uint8Array([128,128,128,255]),a=new Uint8Array([128,128,255,255]);return i._placeholderAlbedoArray=BABYLON.RawTexture2DArray.CreateRGBATexture(o,1,1,1,r,!1,!1,BABYLON.Texture.NEAREST_SAMPLINGMODE),i._placeholderNormalArray=BABYLON.RawTexture2DArray.CreateRGBATexture(a,1,1,1,r,!1,!1,BABYLON.Texture.NEAREST_SAMPLINGMODE),i}return r(n,t),n.prototype.dispose=function(){this._placeholderTexture&&(this._placeholderTexture.dispose(),this._placeholderTexture=null),this._placeholderAlbedoArray&&(this._placeholderAlbedoArray.dispose(),this._placeholderAlbedoArray=null),this._placeholderNormalArray&&(this._placeholderNormalArray.dispose(),this._placeholderNormalArray=null),t.prototype.dispose.call(this)},n.prototype.isCompatible=function(e){return e===BABYLON.ShaderLanguage.WGSL||e===BABYLON.ShaderLanguage.GLSL},n.prototype.getCustomCode=function(e,t){var n=t===BABYLON.ShaderLanguage.WGSL;return"vertex"===e?n?{CUSTOM_VERTEX_DEFINITIONS:this.getWGSLVertexDefinitions(),CUSTOM_VERTEX_UPDATE_POSITION:this.getWGSLVertexPositionCode(),CUSTOM_VERTEX_UPDATE_NORMAL:this.getWGSLVertexNormalCode(),CUSTOM_VERTEX_MAIN_END:this.getWGSLVertexMainEnd()}:{CUSTOM_VERTEX_DEFINITIONS:this.getGLSLVertexDefinitions(),CUSTOM_VERTEX_UPDATE_POSITION:this.getGLSLVertexPositionCode(),CUSTOM_VERTEX_UPDATE_NORMAL:this.getGLSLVertexNormalCode(),CUSTOM_VERTEX_MAIN_END:this.getGLSLVertexMainEnd()}:"fragment"===e?n?{CUSTOM_FRAGMENT_DEFINITIONS:this.getWGSLFragmentDefinitions(),CUSTOM_FRAGMENT_UPDATE_ALBEDO:this.getWGSLFragmentAlbedoCode(),CUSTOM_FRAGMENT_BEFORE_LIGHTS:this.getWGSLFragmentNormalCode()}:{CUSTOM_FRAGMENT_DEFINITIONS:this.getGLSLFragmentDefinitions(),CUSTOM_FRAGMENT_UPDATE_ALBEDO:this.getGLSLFragmentAlbedoCode(),CUSTOM_FRAGMENT_BEFORE_LIGHTS:this.getGLSLFragmentNormalCode()}:null},n.prototype.getUniforms=function(e){var t=e===BABYLON.ShaderLanguage.WGSL;return this.vertexDefinitions=this.getCustomShaderMaterial().getCustomVertexCode(t),this.fragmentDefinitions=!0===t?this.getCustomShaderMaterial().getCustomFragmentCode(t):null,this.getCustomShaderMaterial().getCustomUniforms(t)},n.prototype.getSamplers=function(e){var t=this.getCustomShaderMaterial().getCustomSamplers();null!=t&&t.length>0&&e.push.apply(e,t),this.getCustomShaderMaterial()&&(-1===e.indexOf("runtimeAlbedoSkins")&&e.push("runtimeAlbedoSkins"),-1===e.indexOf("runtimeNormalSkins")&&e.push("runtimeNormalSkins"))},n.prototype.getAttributes=function(e,t,n){var i=this.getCustomShaderMaterial().getCustomAttributes();null!=i&&i.length>0&&e.push.apply(e,i)},n.prototype.prepareDefines=function(e,t,n){if(this.getIsEnabled()){this._captureRendererTarget(n),this.getCustomShaderMaterial().prepareCustomDefines(e);var i=this.controller?this.controller.normalMode:"none";e.VAT_NORMAL_SEPARATE="separate"===i;var r=t?t.getEngine():null;e.UV3=!(r&&r.isWebGPU);var o=this.getCustomShaderMaterial(),a=!(!o||!o.runtimeAlbedoSkins),s=!(!o||!o.runtimeNormalSkins);e.RUNTIME_SKINS_ALBEDO=a,e.RUNTIME_SKINS_NORMAL=s,e.RUNTIME_SKINS_NORMAL_DERIVE_TBN=s&&!(o&&o.bumpTexture)}},n.prototype.onRuntimeSkinArraysChanged=function(){this.markAllDefinesAsDirty()},n.prototype.bindForSubMesh=function(e,t,n,i){if(this.getIsEnabled()){var r=i&&i.getRenderingMesh?i.getRenderingMesh():null;this._captureRendererTarget(r||(i?i.getMesh():null)),this._pushVATUniforms(e,!1),this._pushRuntimeSkinSamplers(e)}},n.prototype._pushRuntimeSkinSamplers=function(e){var t=this.getCustomShaderMaterial(),n=t&&t.runtimeAlbedoSkins&&t.runtimeAlbedoSkins.isReady&&t.runtimeAlbedoSkins.isReady()?t.runtimeAlbedoSkins:this._placeholderAlbedoArray,i=t&&t.runtimeNormalSkins&&t.runtimeNormalSkins.isReady&&t.runtimeNormalSkins.isReady()?t.runtimeNormalSkins:this._placeholderNormalArray;e.setTexture("runtimeAlbedoSkins",n),e.setTexture("runtimeNormalSkins",i)},n.prototype.setupAnimations=function(t,n,i,r){var o,a;if(void 0===i&&(i=""),void 0===r&&(r=!1),this.vertexAnimations=t,t&&0!==t.length){if(n){this._rendererTargets=e.VertexAnimationController.CollectRendererTargets(t),this._targetRendererGuid="";var s=this.getCustomShaderMaterial(),l=s.getScene(),u=e.VertexAnimationController.GetOrCreate(n,l,i,r);u.loadAnimations(t),u.addPlugin(this),this.controller=u,s.controller=u;var c=function(e){var t,n;if(e){if(!e._vatMaterials){e._vatMaterials=[];var i=null;e.onBeforeShadowMapRenderMeshObservable.add(function(e){i=e}),e.onBeforeShadowMapRenderObservable.add(function(t){if(i&&t)for(var n=i.material,r=e._vatMaterials,o=0;o<r.length;o++)if(r[o]===n){var a=r[o].getPlugin();a&&a.bindVATToEffect(t);break}i=null}),e.forceBackFacesOnly=!0,h?(e.normalBias=0,0===(null!==(n=e.bias)&&void 0!==n?n:0)&&(e.bias=.005)):0===(null!==(t=e.normalBias)&&void 0!==t?t:0)&&(e.normalBias=.02)}var r=e._vatMaterials;-1===r.indexOf(s)&&r.push(s)}},d=function(){for(var e,t,n=0,i=l.lights;n<i.length;n++){var r=i[n];c(null===(t=(e=r).getShadowGenerator)||void 0===t?void 0:t.call(e))}},h=!0===l.getEngine().isWebGPU||"WebGPUEngine"===(null===(a=(o=l.getEngine()).getClassName)||void 0===a?void 0:a.call(o));return s.shadowDepthWrapper||(s.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(s,l)),d(),l.onAfterRenderObservable.addOnce(function(){return d()}),s.markAsDirty(BABYLON.Constants.MATERIAL_AllDirtyFlag),this.markAllDefinesAsDirty(),u}BABYLON.Tools.Warn("VertexAnimationMaterialPlugin: vertexcontroller is empty — cannot share controller.")}},n.prototype._captureRendererTarget=function(e){if(""===this._targetRendererGuid){var t=this._resolveRendererTarget(e);t&&t.vertexguid&&(this._targetRendererGuid=t.vertexguid)}},n.prototype._resolveRendererTarget=function(e){if(!e||!this._rendererTargets||0===this._rendererTargets.length)return null;if(1===this._rendererTargets.length)return this._rendererTargets[0];for(var t=[],n=e;n;)t.push(n),n=n.parent;for(var i=0,r=t;i<r.length;i++){var o=r[i],a=this._readMetadataString(o,"guid");if(a&&(h=this._matchRendererByGuid(a)))return h}for(var s=0,l=t;s<l.length;s++){o=l[s];var u=this._buildNodePath(o);if(u&&(h=this._matchRendererByPath(u)))return h}for(var c=0,d=t;c<d.length;c++){var h,p=(o=d[c])&&o.name?o.name:"";if(p&&(h=this._matchRendererByName(p)))return h}return null},n.prototype._matchRendererByGuid=function(e){for(var t=0,n=this._rendererTargets;t<n.length;t++){var i=n[t];if(i&&i.vertexguid===e)return i}return null},n.prototype._matchRendererByPath=function(e){for(var t=0,n=this._rendererTargets;t<n.length;t++){var i=n[t];if(i&&i.vertexpath&&this._pathEndsWith(e,i.vertexpath))return i}return null},n.prototype._matchRendererByName=function(e){for(var t=0,n=this._rendererTargets;t<n.length;t++){var i=n[t];if(i){if(i.vertextransform===e)return i;if(i.vertexrenderer===e)return i;if(i.vertexmesh===e)return i}}return null},n.prototype._readMetadataString=function(e,t){if(!e||!e.metadata)return"";var n=e.metadata,i=n?n[t]:null;if("string"==typeof i&&""!==i)return i;var r=n?n.toolkit:null,o=r?r[t]:null;return"string"==typeof o&&""!==o?o:"guid"===t&&"string"==typeof e.id&&""!==e.id?e.id:""},n.prototype._buildNodePath=function(e){for(var t=[],n=e;n;)n.name&&t.unshift(n.name),n=n.parent;return t.join("/")},n.prototype._pathEndsWith=function(e,t){if(!e||!t)return!1;if(e===t)return!0;if(e.length<=t.length)return!1;var n=e.length-t.length;return e.substring(n)===t&&"/"===e.charAt(n-1)},n.prototype.syncFromController=function(e,t){void 0===t&&(t=null);var n=t||this.controller;if(n){var i=this._placeholderTexture,r=function(e){return null!=e&&"function"==typeof e.isReady&&e.isReady()},o=(n.normalMode,n.getCurrentRendererClip(this._targetRendererGuid));if(o){var a=r(o.positionTexture)?o.positionTexture:i,s=r(o.normalTexture)?o.normalTexture:i;e.setTextureValue("vatPosition",a),e.setTextureValue("vatNormal",s);var l=o.settings;this._cc_posTex=a,this._cc_normTex=s,this._cc_texW=l.vertexwidth,this._cc_texH=l.vertexheight,this._cc_rowsPF=l.vertexrowsperframe,this._cc_vCount=l.vertexcount,this._cc_posMin=o.posMinV3,this._cc_posMax=o.posMaxV3}else e.setTextureValue("vatPosition",i),e.setTextureValue("vatNormal",i),this._cc_posTex=i,this._cc_normTex=i,this._cc_posMin=null,this._cc_posMax=null;var u=n.getPreviousRendererClip(this._targetRendererGuid);if(u){var c=r(u.positionTexture)?u.positionTexture:i,d=r(u.normalTexture)?u.normalTexture:i;e.setTextureValue("vatPrevPosition",c),e.setTextureValue("vatPrevNormal",d),l=u.settings,this._cc_prevPosTex=c,this._cc_prevNormTex=d,this._cc_prevTexW=l.vertexwidth,this._cc_prevTexH=l.vertexheight,this._cc_prevRowsPF=l.vertexrowsperframe,this._cc_prevPosMin=u.posMinV3,this._cc_prevPosMax=u.posMaxV3}else e.setTextureValue("vatPrevPosition",i),e.setTextureValue("vatPrevNormal",i),this._cc_prevPosTex=i,this._cc_prevNormTex=i,this._cc_prevPosMin=null,this._cc_prevPosMax=null}},n.prototype.bindVATToEffect=function(e){this._pushVATUniforms(e,!0),this._pushRuntimeSkinSamplers(e)},n.prototype._pushVATUniforms=function(e,t){var i,r,o,a,s,l,u,c,d,h,p=this._placeholderTexture,m=n._zeroV3,f=n._oneV3,g=null==this._cc_prevPosTex||this._cc_prevPosTex===p||null==this._cc_prevPosMin||null==this._cc_prevPosMax,v=g?null!==(i=this._cc_posTex)&&void 0!==i?i:p:this._cc_prevPosTex,y=g?null!==(r=this._cc_normTex)&&void 0!==r?r:p:this._cc_prevNormTex,_=g?null!==(o=this._cc_posMin)&&void 0!==o?o:m:this._cc_prevPosMin,S=g?null!==(a=this._cc_posMax)&&void 0!==a?a:f:this._cc_prevPosMax,A=g?this._cc_texW:this._cc_prevTexW,b=g?this._cc_texH:this._cc_prevTexH,M=g?this._cc_rowsPF:this._cc_prevRowsPF;if(e.setTexture("vatPosition",null!==(s=this._cc_posTex)&&void 0!==s?s:p),e.setTexture("vatNormal",null!==(l=this._cc_normTex)&&void 0!==l?l:p),e.setTexture("vatPrevPosition",null!=v?v:p),e.setTexture("vatPrevNormal",null!=y?y:p),t){var B=e;B.setFloat("g_vatTexWidth",this._cc_texW),B.setFloat("g_vatTexHeight",this._cc_texH),B.setFloat("g_vatRowsPerFrame",this._cc_rowsPF),B.setFloat("g_vatVertexCount",this._cc_vCount),B.setVector3("g_vatPosMin",null!==(u=this._cc_posMin)&&void 0!==u?u:m),B.setVector3("g_vatPosMax",null!==(c=this._cc_posMax)&&void 0!==c?c:f),B.setFloat("g_vatPrevTexWidth",A),B.setFloat("g_vatPrevTexHeight",b),B.setFloat("g_vatPrevRowsPerFrame",M),B.setVector3("g_vatPrevPosMin",_),B.setVector3("g_vatPrevPosMax",S)}else{var C=e;C.updateFloat("g_vatTexWidth",this._cc_texW),C.updateFloat("g_vatTexHeight",this._cc_texH),C.updateFloat("g_vatRowsPerFrame",this._cc_rowsPF),C.updateFloat("g_vatVertexCount",this._cc_vCount),C.updateVector3("g_vatPosMin",null!==(d=this._cc_posMin)&&void 0!==d?d:m),C.updateVector3("g_vatPosMax",null!==(h=this._cc_posMax)&&void 0!==h?h:f),C.updateFloat("g_vatPrevTexWidth",A),C.updateFloat("g_vatPrevTexHeight",b),C.updateFloat("g_vatPrevRowsPerFrame",M),C.updateVector3("g_vatPrevPosMin",_),C.updateVector3("g_vatPrevPosMax",S)}},n.prototype.getGLSLVertexDefinitions=function(){return"\n #ifndef TOOLKIT_VAT_V_UNIFORMS\n #define TOOLKIT_VAT_V_UNIFORMS\n // Per-instance animation values come from InstancedMesh.instancedBuffers\n // (vertex attributes with divisor=1) — NOT uniforms. Every instance in a\n // hardware-instanced draw call gets its own independent values.\n attribute vec4 g_vatAnim0; // frame, frameCount, fromRow, blendWeight\n attribute vec4 g_vatAnim1; // prevFrame, prevFrameCount, prevFromRow, loopBlend\n uniform float g_vatTexWidth;\n uniform float g_vatTexHeight;\n uniform float g_vatRowsPerFrame;\n uniform float g_vatVertexCount;\n uniform vec3 g_vatPosMin;\n uniform vec3 g_vatPosMax;\n uniform float g_vatPrevTexWidth;\n uniform float g_vatPrevTexHeight;\n uniform float g_vatPrevRowsPerFrame;\n uniform vec3 g_vatPrevPosMin;\n uniform vec3 g_vatPrevPosMax;\n uniform sampler2D vatPosition;\n uniform sampler2D vatNormal;\n uniform sampler2D vatPrevPosition;\n uniform sampler2D vatPrevNormal;\n #endif\n // Runtime-skin varyings — pass packed skin index + UV0 to the fragment stage so\n // fragment can sample runtimeAlbedoSkins[layer]/runtimeNormalSkins[layer]. Always\n // emitted (cheap) so the shader compiles regardless of the runtime-skin defines.\n #ifndef TOOLKIT_VAT_RUNTIMESKIN_VARYINGS\n #define TOOLKIT_VAT_RUNTIMESKIN_VARYINGS\n varying float vRuntimeSkinIndex;\n varying vec2 vRuntimeSkinUV;\n #endif\n "},n.prototype.getGLSLVertexPositionCode=function(){return"\n #ifdef VERTEXANIMATIONMATERIAL\n float vatFrame = g_vatAnim0.x;\n float vatFrameCount = g_vatAnim0.y;\n float vatFromRow = g_vatAnim0.z;\n float vatBlendWeight = g_vatAnim0.w;\n float vatPrevFrame = g_vatAnim1.x;\n float vatPrevFrameCount = g_vatAnim1.y;\n float vatPrevFromRow = g_vatAnim1.z;\n float vatPackedSkinLoop = g_vatAnim1.w;\n float vatLoopBlend = mod(vatPackedSkinLoop, 2.0);\n if (vatFrameCount > 0.5) {\n // GLSL path uses the third UV channel:\n // Unity uv3 -> glTF TEXCOORD_2 -> Babylon shader uv3\n // uv3.x = texel-centre U inside one VAT frame\n // uv3.y = row index inside the frame tile (+0.5 for stable floor)\n float baseU = clamp(uv3.x, 0.0, 1.0);\n float rowInTile = max(0.0, floor(uv3.y));\n\n float rowsPF = g_vatRowsPerFrame;\n float frameA = clamp(floor(vatFrame), 0.0, vatFrameCount - 1.0);\n float fracA = fract(vatFrame);\n float frameB = frameA + 1.0;\n if (frameB >= vatFrameCount) {\n if (vatLoopBlend > 0.5) {\n frameB = 0.0;\n } else {\n frameB = frameA;\n fracA = 0.0;\n }\n }\n\n vec2 uvA = vec2(baseU, (vatFromRow + frameA * rowsPF + rowInTile + 0.5) / g_vatTexHeight);\n vec2 uvB = vec2(baseU, (vatFromRow + frameB * rowsPF + rowInTile + 0.5) / g_vatTexHeight);\n vec4 encA = textureLod(vatPosition, uvA, 0.0);\n vec4 encB = textureLod(vatPosition, uvB, 0.0);\n vec3 posA = mix(g_vatPosMin, g_vatPosMax, encA.xyz);\n vec3 posB = mix(g_vatPosMin, g_vatPosMax, encB.xyz);\n vec3 curPos = mix(posA, posB, fracA);\n\n // Crossfade with previous clip if a blend is active\n if (vatBlendWeight < 0.999 && vatPrevFrameCount > 0.5) {\n float rowsPFp = g_vatPrevRowsPerFrame;\n float rowInTileP = rowInTile;\n float frameAp = clamp(floor(vatPrevFrame), 0.0, vatPrevFrameCount - 1.0);\n float fracAp = fract(vatPrevFrame);\n float frameBp = frameAp + 1.0;\n if (frameBp >= vatPrevFrameCount) {\n if (vatLoopBlend > 0.5) {\n frameBp = 0.0;\n } else {\n frameBp = frameAp;\n fracAp = 0.0;\n }\n }\n float tileRowAp = frameAp * rowsPFp + rowInTileP;\n float tileRowBp = frameBp * rowsPFp + rowInTileP;\n vec2 uvAp = vec2(baseU, (vatPrevFromRow + tileRowAp + 0.5) / g_vatPrevTexHeight);\n vec2 uvBp = vec2(baseU, (vatPrevFromRow + tileRowBp + 0.5) / g_vatPrevTexHeight);\n vec4 encAp = textureLod(vatPrevPosition, uvAp, 0.0);\n vec4 encBp = textureLod(vatPrevPosition, uvBp, 0.0);\n vec3 prevPosA = mix(g_vatPrevPosMin, g_vatPrevPosMax, encAp.xyz);\n vec3 prevPosB = mix(g_vatPrevPosMin, g_vatPrevPosMax, encBp.xyz);\n vec3 prevPos = mix(prevPosA, prevPosB, fracAp);\n curPos = mix(prevPos, curPos, vatBlendWeight);\n }\n\n positionUpdated = curPos;\n }\n #endif\n "},n.prototype.getGLSLVertexNormalCode=function(){return"\n #ifdef VERTEXANIMATIONMATERIAL\n float vatNormFrame = g_vatAnim0.x;\n float vatNormFrameCount = g_vatAnim0.y;\n float vatNormFromRow = g_vatAnim0.z;\n \n float vatNormPackedSkinLoop = g_vatAnim1.w;\n float vatNormLoopBlend = mod(vatNormPackedSkinLoop, 2.0);\n\n if (vatNormFrameCount > 0.5) {\n // GLSL path uses the third UV channel:\n // Unity uv3 -> glTF TEXCOORD_2 -> Babylon shader uv3\n float baseU = clamp(uv3.x, 0.0, 1.0);\n float rowInTile = max(0.0, floor(uv3.y));\n float rowsPF = g_vatRowsPerFrame;\n float frameA = clamp(floor(vatNormFrame), 0.0, vatNormFrameCount - 1.0);\n float fractA = fract(vatNormFrame);\n float frameB = frameA + 1.0;\n if (frameB >= vatNormFrameCount) {\n if (vatNormLoopBlend > 0.5) {\n frameB = 0.0;\n } else {\n frameB = frameA;\n fractA = 0.0;\n }\n }\n\n vec2 uvA = vec2(baseU, (vatNormFromRow + frameA * rowsPF + rowInTile + 0.5) / g_vatTexHeight);\n vec2 uvB = vec2(baseU, (vatNormFromRow + frameB * rowsPF + rowInTile + 0.5) / g_vatTexHeight);\n vec4 nA = textureLod(vatNormal, uvA, 0.0);\n vec4 nB = textureLod(vatNormal, uvB, 0.0);\n vec3 normalA = normalize(nA.xyz * 2.0 - 1.0);\n vec3 normalB = normalize(nB.xyz * 2.0 - 1.0);\n vec3 normalResult = normalize(mix(normalA, normalB, fractA));\n\n normalUpdated = normalResult;\n }\n #endif\n "},n.prototype.getWGSLVertexDefinitions=function(){return"\n #ifdef VERTEXANIMATIONMATERIAL\n attribute g_vatAnim0 : vec4<f32>;\n attribute g_vatAnim1 : vec4<f32>;\n var vatPosition: texture_2d<f32>;\n var vatPositionSampler: sampler;\n var vatNormal: texture_2d<f32>;\n var vatNormalSampler: sampler;\n var vatPrevPosition: texture_2d<f32>;\n var vatPrevPositionSampler: sampler;\n var vatPrevNormal: texture_2d<f32>;\n var vatPrevNormalSampler: sampler;\n // Runtime-skin varyings — packed skin index and UV0, passed to fragment.\n varying vRuntimeSkinIndex: f32;\n varying vRuntimeSkinUV: vec2<f32>;\n #endif\n "},n.prototype.getWGSLVertexPositionCode=function(){return"\n #ifdef VERTEXANIMATIONMATERIAL\n let vatFrame = vertexInputs.g_vatAnim0.x;\n let vatFrameCount = vertexInputs.g_vatAnim0.y;\n let vatFromRow = vertexInputs.g_vatAnim0.z;\n let vatBlendWeight = vertexInputs.g_vatAnim0.w;\n let vatPrevFrame = vertexInputs.g_vatAnim1.x;\n let vatPrevFrameCount = vertexInputs.g_vatAnim1.y;\n let vatPrevFromRow = vertexInputs.g_vatAnim1.z;\n let packedSkinLoop = vertexInputs.g_vatAnim1.w;\n let vatLoopBlend = packedSkinLoop % 2.0;\n if (vatFrameCount > 0.5) {\n // WGSL path derives the VAT texel coordinate from the vertex index instead\n // of consuming a dedicated uv3 vertex-buffer slot.\n let vatTexWidth = max(uniforms.g_vatTexWidth, 1.0);\n let vatVertexIndex = f32(vertexInputs.vertexIndex);\n let rowInTile = max(0.0, floor(vatVertexIndex / vatTexWidth));\n let colInTile = vatVertexIndex - rowInTile * vatTexWidth;\n let baseU = (colInTile + 0.5) / vatTexWidth;\n\n let rowsPF = uniforms.g_vatRowsPerFrame;\n let frameA = clamp(floor(vatFrame), 0.0, vatFrameCount - 1.0);\n var fracA = fract(vatFrame);\n var frameB = frameA + 1.0;\n if (frameB >= vatFrameCount) {\n if (vatLoopBlend > 0.5) {\n frameB = 0.0;\n } else {\n frameB = frameA;\n fracA = 0.0;\n }\n }\n let tileRowA = frameA * rowsPF + rowInTile;\n let tileRowB = frameB * rowsPF + rowInTile;\n let uvA = vec2f(baseU, (vatFromRow + tileRowA + 0.5) / uniforms.g_vatTexHeight);\n let uvB = vec2f(baseU, (vatFromRow + tileRowB + 0.5) / uniforms.g_vatTexHeight);\n let encA = textureSampleLevel(vatPosition, vatPositionSampler, uvA, 0.0);\n let encB = textureSampleLevel(vatPosition, vatPositionSampler, uvB, 0.0);\n let posA = mix(uniforms.g_vatPosMin, uniforms.g_vatPosMax, encA.xyz);\n let posB = mix(uniforms.g_vatPosMin, uniforms.g_vatPosMax, encB.xyz);\n var curPos = mix(posA, posB, fracA);\n\n if (vatBlendWeight < 0.999 && vatPrevFrameCount > 0.5) {\n let rowsPFp = uniforms.g_vatPrevRowsPerFrame;\n let rowInTileP = rowInTile;\n let frameAp = clamp(floor(vatPrevFrame), 0.0, vatPrevFrameCount - 1.0);\n var fracAp = fract(vatPrevFrame);\n var frameBp = frameAp + 1.0;\n if (frameBp >= vatPrevFrameCount) {\n if (vatLoopBlend > 0.5) {\n frameBp = 0.0;\n } else {\n frameBp = frameAp;\n fracAp = 0.0;\n }\n }\n let tileRowAp = frameAp * rowsPFp + rowInTileP;\n let tileRowBp = frameBp * rowsPFp + rowInTileP;\n let uvAp = vec2f(baseU, (vatPrevFromRow + tileRowAp + 0.5) / uniforms.g_vatPrevTexHeight);\n let uvBp = vec2f(baseU, (vatPrevFromRow + tileRowBp + 0.5) / uniforms.g_vatPrevTexHeight);\n let encAp = textureSampleLevel(vatPrevPosition, vatPrevPositionSampler, uvAp, 0.0);\n let encBp = textureSampleLevel(vatPrevPosition, vatPrevPositionSampler, uvBp, 0.0);\n let prevPosA = mix(uniforms.g_vatPrevPosMin, uniforms.g_vatPrevPosMax, encAp.xyz);\n let prevPosB = mix(uniforms.g_vatPrevPosMin, uniforms.g_vatPrevPosMax, encBp.xyz);\n let prevPos = mix(prevPosA, prevPosB, fracAp);\n curPos = mix(prevPos, curPos, vatBlendWeight);\n }\n\n positionUpdated = curPos;\n }\n #endif\n "},n.prototype.getWGSLVertexNormalCode=function(){return"\n #ifdef VERTEXANIMATIONMATERIAL\n let vatNormFrame = vertexInputs.g_vatAnim0.x;\n let vatNormFrameCount = vertexInputs.g_vatAnim0.y;\n let vatNormFromRow = vertexInputs.g_vatAnim0.z;\n let vatNormPackedSkinLoop = vertexInputs.g_vatAnim1.w;\n let vatNormLoopBlend = vatNormPackedSkinLoop % 2.0;\n if (vatNormFrameCount > 0.5) {\n // WGSL path derives the VAT texel coordinate from the vertex index instead\n // of consuming a dedicated uv3 vertex-buffer slot.\n let vatTexWidth = max(uniforms.g_vatTexWidth, 1.0);\n let vatVertexIndex = f32(vertexInputs.vertexIndex);\n let rowInTile = max(0.0, floor(vatVertexIndex / vatTexWidth));\n let colInTile = vatVertexIndex - rowInTile * vatTexWidth;\n let baseU = (colInTile + 0.5) / vatTexWidth;\n let rowsPF = uniforms.g_vatRowsPerFrame;\n\n #ifdef VAT_NORMAL_SEPARATE\n let frameA = clamp(floor(vatNormFrame), 0.0, vatNormFrameCount - 1.0);\n var fracA = fract(vatNormFrame);\n var frameB = frameA + 1.0;\n if (frameB >= vatNormFrameCount) {\n if (vatNormLoopBlend > 0.5) {\n frameB = 0.0;\n } else {\n frameB = frameA;\n fracA = 0.0;\n }\n }\n let tileRowA = frameA * rowsPF + rowInTile;\n let tileRowB = frameB * rowsPF + rowInTile;\n let uvA = vec2f(baseU, (vatNormFromRow + tileRowA + 0.5) / uniforms.g_vatTexHeight);\n let uvB = vec2f(baseU, (vatNormFromRow + tileRowB + 0.5) / uniforms.g_vatTexHeight);\n let nA = textureSampleLevel(vatNormal, vatNormalSampler, uvA, 0.0);\n let nB = textureSampleLevel(vatNormal, vatNormalSampler, uvB, 0.0);\n let normalA = normalize(nA.xyz * 2.0 - vec3f(1.0));\n let normalB = normalize(nB.xyz * 2.0 - vec3f(1.0));\n normalUpdated = normalize(mix(normalA, normalB, fracA));\n #endif\n }\n #endif\n "},n.prototype.getGLSLVertexMainEnd=function(){return"\n #ifdef VERTEXANIMATIONMATERIAL\n {\n float _rsPackedSkinLoop = g_vatAnim1.w;\n vRuntimeSkinIndex = floor(_rsPackedSkinLoop * 0.5 + 0.0001);\n #ifdef UV1\n vRuntimeSkinUV = uv;\n #else\n vRuntimeSkinUV = vec2(0.0, 0.0);\n #endif\n }\n #endif\n "},n.prototype.getWGSLVertexMainEnd=function(){return"\n #ifdef VERTEXANIMATIONMATERIAL\n {\n let _rsPackedSkinLoop = vertexInputs.g_vatAnim1.w;\n vertexOutputs.vRuntimeSkinIndex = floor(_rsPackedSkinLoop * 0.5 + 0.0001);\n #ifdef UV1\n vertexOutputs.vRuntimeSkinUV = vertexInputs.uv;\n #else\n vertexOutputs.vRuntimeSkinUV = vec2f(0.0, 0.0);\n #endif\n }\n #endif\n "},n.prototype.getGLSLFragmentDefinitions=function(){return"\n #ifndef TOOLKIT_VAT_RUNTIMESKIN_F_UNIFORMS\n #define TOOLKIT_VAT_RUNTIMESKIN_F_UNIFORMS\n varying float vRuntimeSkinIndex;\n varying vec2 vRuntimeSkinUV;\n uniform highp sampler2DArray runtimeAlbedoSkins;\n uniform highp sampler2DArray runtimeNormalSkins;\n #endif\n "},n.prototype.getGLSLFragmentAlbedoCode=function(){return"\n #ifdef RUNTIME_SKINS_ALBEDO\n {\n float _rsLayer = max(0.0, floor(vRuntimeSkinIndex + 0.5));\n vec4 _rsAlbedo = texture(runtimeAlbedoSkins, vec3(vRuntimeSkinUV, _rsLayer));\n surfaceAlbedo = _rsAlbedo.rgb * vAlbedoColor.rgb;\n #ifdef ALPHATEST\n if (_rsAlbedo.a < alphaCutOff) discard;\n #endif\n }\n #endif\n "},n.prototype.getGLSLFragmentNormalCode=function(){return"\n #ifdef RUNTIME_SKINS_NORMAL\n {\n float _rsLayer = max(0.0, floor(vRuntimeSkinIndex + 0.5));\n vec3 _rsNormalSample = texture(runtimeNormalSkins, vec3(vRuntimeSkinUV, _rsLayer)).xyz;\n vec3 _rsNormalTS = _rsNormalSample * 2.0 - 1.0;\n vec3 _rsP = vPositionW;\n vec3 _rsN = normalize(vNormalW);\n vec3 _rsDp1 = dFdx(_rsP);\n vec3 _rsDp2 = dFdy(_rsP);\n vec2 _rsDuv1 = dFdx(vRuntimeSkinUV);\n vec2 _rsDuv2 = dFdy(vRuntimeSkinUV);\n vec3 _rsDp2perp = cross(_rsDp2, _rsN);\n vec3 _rsDp1perp = cross(_rsN, _rsDp1);\n vec3 _rsT = _rsDp2perp * _rsDuv1.x + _rsDp1perp * _rsDuv2.x;\n vec3 _rsB = _rsDp2perp * _rsDuv1.y + _rsDp1perp * _rsDuv2.y;\n float _rsInvMax = inversesqrt(max(dot(_rsT, _rsT), dot(_rsB, _rsB)));\n mat3 _rsTBN = mat3(_rsT * _rsInvMax, _rsB * _rsInvMax, _rsN);\n normalW = normalize(_rsTBN * _rsNormalTS);\n }\n #endif\n "},n.prototype.getWGSLFragmentDefinitions=function(){return"\n varying vRuntimeSkinIndex: f32;\n varying vRuntimeSkinUV: vec2<f32>;\n var runtimeAlbedoSkins: texture_2d_array<f32>;\n var runtimeAlbedoSkinsSampler: sampler;\n var runtimeNormalSkins: texture_2d_array<f32>;\n var runtimeNormalSkinsSampler: sampler;\n "},n.prototype.getWGSLFragmentAlbedoCode=function(){return"\n #ifdef RUNTIME_SKINS_ALBEDO\n {\n let _rsLayer = i32(max(0.0, floor(fragmentInputs.vRuntimeSkinIndex + 0.5)));\n let _rsAlbedo = textureSample(runtimeAlbedoSkins, runtimeAlbedoSkinsSampler, fragmentInputs.vRuntimeSkinUV, _rsLayer);\n surfaceAlbedo = _rsAlbedo.rgb * vAlbedoColor.rgb;\n #ifdef ALPHATEST\n if (_rsAlbedo.a < alphaCutOff) { discard; }\n #endif\n }\n #endif\n "},n.prototype.getWGSLFragmentNormalCode=function(){return"\n #ifdef RUNTIME_SKINS_NORMAL\n {\n let _rsLayer = i32(max(0.0, floor(fragmentInputs.vRuntimeSkinIndex + 0.5)));\n let _rsNormalSample = textureSample(runtimeNormalSkins, runtimeNormalSkinsSampler, fragmentInputs.vRuntimeSkinUV, _rsLayer).xyz;\n let _rsNormalTS = _rsNormalSample * 2.0 - vec3f(1.0);\n let _rsP = fragmentInputs.vPositionW;\n let _rsN = normalize(fragmentInputs.vNormalW);\n let _rsDp1 = dpdx(_rsP);\n let _rsDp2 = dpdy(_rsP);\n let _rsDuv1 = dpdx(fragmentInputs.vRuntimeSkinUV);\n let _rsDuv2 = dpdy(fragmentInputs.vRuntimeSkinUV);\n let _rsDp2perp = cross(_rsDp2, _rsN);\n let _rsDp1perp = cross(_rsN, _rsDp1);\n let _rsT = _rsDp2perp * _rsDuv1.x + _rsDp1perp * _rsDuv2.x;\n let _rsB = _rsDp2perp * _rsDuv1.y + _rsDp1perp * _rsDuv2.y;\n let _rsInvMax = inverseSqrt(max(dot(_rsT, _rsT), dot(_rsB, _rsB)));\n let _rsTcol = _rsT * _rsInvMax;\n let _rsBcol = _rsB * _rsInvMax;\n normalW = normalize(_rsTcol * _rsNormalTS.x + _rsBcol * _rsNormalTS.y + _rsN * _rsNormalTS.z);\n }\n #endif\n "},n._zeroV3=BABYLON.Vector3.Zero(),n._oneV3=BABYLON.Vector3.One(),n}(e.CustomShaderMaterialPlugin);e.VertexAnimationMaterialPlugin=i,e.SceneManager.RegisterClass("TOOLKIT.VertexAnimationController",n),e.SceneManager.RegisterClass("TOOLKIT.VertexAnimationMaterial",t),e.SceneManager.RegisterClass("TOOLKIT.VertexAnimationMaterialPlugin",i)}(i||(i={})),function(e){var t,n,i,r;(r=e.DragDirection||(e.DragDirection={}))[r.None=0]="None",r[r.Up=1]="Up",r[r.Down=2]="Down",r[r.Right=3]="Right",r[r.Left=4]="Left",(i=e.PinchZoomState||(e.PinchZoomState={}))[i.None=0]="None",i[i.ZoomIn=1]="ZoomIn",i[i.ZoomOut=2]="ZoomOut",(n=e.MouseButtonMode||(e.MouseButtonMode={}))[n.Pan=0]="Pan",n[n.Look=1]="Look",n[n.Move=2]="Move",(t=e.TouchMouseButton||(e.TouchMouseButton={}))[t.Any=-1]="Any",t[t.Left=0]="Left",t[t.Right=1]="Right";var o=function(){function t(){}return t.GetMouseButtonsDown=function(){return e.InputController.mouseButtonsDown},t.GetLeftButtonDown=function(){return e.InputController.leftButtonDown},t.GetMiddleButtonDown=function(){return e.InputController.middleButtonDown},t.GetRightButtonDown=function(){return e.InputController.rightButtonDown},t.GetMouseDownTarget=function(){return e.InputController.mouseDownTarget},t.GetMouseDragTarget=function(){return e.InputController.mouseDragTarget},t.GetPinchZoomState=function(){return e.InputController.pinchZoomState},t.EnableUserInput=function(t,n,i){void 0===i&&(i=null),e.InputController.ConfigureUserInput(t,n,i)},t.ConfigureUserInput=function(t,n,i){void 0===i&&(i=null);var r=null==i||null==i.contextMenu||i.contextMenu,o=null!=i&&null!=i.pointerLock&&i.pointerLock,a=null!=i&&null!=i.preventDefault&&i.preventDefault,s=null!=i&&null!=i.useCapture&&i.useCapture;if(e.InputController.resetUserInput(),!e.InputController.input){document.documentElement.tabIndex=1,document.documentElement.addEventListener("keyup",e.InputController.inputKeyUpHandler,s),document.documentElement.addEventListener("pointerup",e.InputController.inputPointerUpHandler,s),document.documentElement.addEventListener("pointerout",e.InputController.inputPointerUpHandler,s),document.documentElement.addEventListener("pointerleave",e.InputController.inputPointerUpHandler,s),document.documentElement.addEventListener("pointercancel",e.InputController.inputPointerUpHandler,s);var l=document.getElementById("renderingCanvas")||t.getRenderingCanvas();null!=l&&(l.oncontextmenu=!0===r?null:function(e){e.preventDefault(),e.stopPropagation()}),!0===e.UserInputOptions.UseCanvasElement?(l.tabIndex=2,l.addEventListener("focusout",e.InputController.resetKeyMapHandler,s),l.addEventListener("keydown",e.InputController.inputKeyDownHandler,s),l.addEventListener("pointerdown",e.InputController.inputPointerDownHandler,s),l.addEventListener("pointermove",e.InputController.inputPointerMoveHandler,s),l.addEventListener("onwheel"in document?"wheel":"mousewheel",e.InputController.inputPointerWheelHandler,s)):(document.documentElement.addEventListener("focusout",e.InputController.resetKeyMapHandler,s),document.documentElement.addEventListener("keydown",e.InputController.inputKeyDownHandler,s),document.documentElement.addEventListener("pointerdown",e.InputController.inputPointerDownHandler,s),document.documentElement.addEventListener("pointermove",e.InputController.inputPointerMoveHandler,s),document.documentElement.addEventListener("onwheel"in document?"wheel":"mousewheel",e.InputController.inputPointerWheelHandler,s)),e.InputController.preventDefault=a,null==e.InputController.GamepadManager&&(e.InputController.GamepadManager=new BABYLON.GamepadManager,e.InputController.GamepadManager.onGamepadConnectedObservable.add(e.InputController.inputManagerGamepadConnected),e.InputController.GamepadManager.onGamepadDisconnectedObservable.add(e.InputController.inputManagerGamepadDisconnected)),e.InputController.input=!0,document.documentElement.focus(),!0===o&&e.InputController.LockMousePointer(n,!0)}n.registerAfterRender(function(){e.InputController.updateUserInput(n)})},t.SetLeftJoystickBuffer=function(t,n,i){void 0===i&&(i=!0),e.InputController.j_horizontal=t,e.InputController.j_vertical=!0===i?-n:n},t.SetRightJoystickBuffer=function(t,n,i){void 0===i&&(i=!0),e.InputController.j_mousex=t,e.InputController.j_mousey=!0===i?-n:n},t.DisableUserInput=function(t,n){void 0===n&&(n=!1),e.InputController.LockMousePointer(t,!1),e.InputController.resetUserInput()},t.LockMousePointer=function(t,n){!0===n?e.InputController.LockMousePointerObserver=t.onPointerObservable.add(function(n,i){var r;n.type==BABYLON.PointerEventTypes.POINTERDOWN&&(document.pointerLockElement||null===(r=e.SceneManager.GetEngine(t))||void 0===r||r.enterPointerlock())}):e.InputController.IsPointerLockHandled()&&(t.onPointerObservable.remove(e.InputController.LockMousePointerObserver),e.InputController.LockMousePointerObserver=null)},t.IsPointerLocked=function(){return e.InputController.PointerLockedFlag},t.IsPointerLockHandled=function(){return null!=e.InputController.LockMousePointerObserver},t.GetUserInput=function(t,n){void 0===n&&(n=e.PlayerNumber.One);var i=0;if(e.InputController.input)switch(t){case e.UserInputAxis.Vertical:case e.UserInputAxis.Horizontal:i=n===e.PlayerNumber.Four?t===e.UserInputAxis.Horizontal?e.InputController.horizontal4:e.InputController.vertical4:n===e.PlayerNumber.Three?t===e.UserInputAxis.Horizontal?e.InputController.horizontal3:e.InputController.vertical3:n===e.PlayerNumber.Two?t===e.UserInputAxis.Horizontal?e.InputController.horizontal2:e.InputController.vertical2:t===e.UserInputAxis.Horizontal?e.InputController.horizontal:e.InputController.vertical;break;case e.UserInputAxis.MouseX:case e.UserInputAxis.MouseY:i=n===e.PlayerNumber.Four?t===e.UserInputAxis.MouseX?e.InputController.mousex4:e.InputController.mousey4:n===e.PlayerNumber.Three?t===e.UserInputAxis.MouseX?e.InputController.mousex3:e.InputController.mousey3:n===e.PlayerNumber.Two?t===e.UserInputAxis.MouseX?e.InputController.mousex2:e.InputController.mousey2:t===e.UserInputAxis.MouseX?e.InputController.mousex:e.InputController.mousey;break;case e.UserInputAxis.Wheel:n===e.PlayerNumber.One&&(i=e.InputController.wheel)}return i},t.OnKeyboardUp=function(t){e.InputController.input&&e.InputController.keyButtonUp.push(t)},t.OnKeyboardDown=function(t){e.InputController.input&&e.InputController.keyButtonDown.push(t)},t.OnKeyboardPress=function(t,n){e.InputController.input&&e.InputController.keyButtonPress.push({index:t,action:n})},t.GetKeyboardInput=function(t){var n=!1;if(e.InputController.input){var i="k:"+t.toString();if(null!=e.InputController.keymap[i]){var r=e.InputController.keymap[i];n=null!=r.result&&r.result}}return n},t.IsKeyboardButtonHeld=function(t){var n=!1;if(e.InputController.input){var i="k:"+t.toString();if(null!=e.InputController.keymap[i]){var r=e.InputController.keymap[i];null!=r.pressTime&&null!=r.releaseTime&&!0===(null!=r.result&&r.result)&&r.pressTime>0&&0===r.releaseTime&&(n=e.SceneManager.GetTimeMs()-r.pressTime>=e.InputController.TAP_THRESHOLD_MS)}}return n},t.WasKeyboardButtonTapped=function(t,n){void 0===n&&(n=!0);var i=!1;if(e.InputController.input){var r="k:"+t.toString();if(null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];null!=o.pressTime&&null!=o.releaseTime&&!1===(null!=o.result&&o.result)&&o.pressTime>0&&o.releaseTime>0&&(i=o.releaseTime-o.pressTime<e.InputController.TAP_THRESHOLD_MS)}!0===n&&e.InputController.ResetKeyboardButtonTapped(t)}return i},t.ResetKeyboardButtonTapped=function(t){if(e.InputController.input){var n="k:"+t.toString();null!=e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0})}},t.OnPointerUp=function(t){e.InputController.input&&e.InputController.mouseButtonUp.push(t)},t.OnPointerDown=function(t){e.InputController.input&&e.InputController.mouseButtonDown.push(t)},t.OnPointerPress=function(t,n){e.InputController.input&&e.InputController.mouseButtonPress.push({index:t,action:n})},t.GetPointerInput=function(t){var n=!1;if(e.InputController.input){var i="p:"+t.toString();if(null!=e.InputController.keymap[i]){var r=e.InputController.keymap[i];n=null!=r.result&&r.result}}return n},t.IsPointerButtonHeld=function(t){var n=!1;if(e.InputController.input){var i="p:"+t.toString();if(null!=e.InputController.keymap[i]){var r=e.InputController.keymap[i];null!=r.pressTime&&null!=r.releaseTime&&!0===(null!=r.result&&r.result)&&r.pressTime>0&&0===r.releaseTime&&(n=e.SceneManager.GetTimeMs()-r.pressTime>=e.InputController.TAP_THRESHOLD_MS)}}return n},t.WasPointerButtonTapped=function(t,n){void 0===n&&(n=!0);var i=!1;if(e.InputController.input){var r="p:"+t.toString();if(null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];null!=o.pressTime&&null!=o.releaseTime&&!1===(null!=o.result&&o.result)&&o.pressTime>0&&o.releaseTime>0&&(i=o.releaseTime-o.pressTime<e.InputController.TAP_THRESHOLD_MS)}!0===n&&e.InputController.ResetPointerButtonTapped(t)}return i},t.ResetPointerButtonTapped=function(t){if(e.InputController.input){var n="p:"+t.toString();null!=e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0})}},t.GetPointerDragDirection=function(t,n,i){return!0===i?0===t&&0===n||(Math.abs(t)>Math.abs(n)?t>0?e.InputController.dragDirection=e.DragDirection.Right:t<0&&(e.InputController.dragDirection=e.DragDirection.Left):n>0?e.InputController.dragDirection=e.DragDirection.Up:n<0&&(e.InputController.dragDirection=e.DragDirection.Down)):e.InputController.dragDirection=e.DragDirection.None,e.InputController.dragDirection},t.ResetPinchZoomTracking=function(){e.InputController.pinchZoomState=0,e.InputController.pinchZoomEvents=[],e.InputController.pinchZoomDistance=null},t.GetMousePosition=function(t,n){void 0===n&&(n=!1);var i=e.InputController.IsPointerLocked(),r=i?e.InputController.virtualClientX:e.InputController.lastClientX||0,o=i?e.InputController.virtualClientY:e.InputController.lastClientY||0,a=t.getEngine().getRenderingCanvas();if(a){var s=a.getBoundingClientRect(),l=r-s.left,u=o-s.top;if(!0===n){var c=s.height-u;e.InputController.LastMousePosition.set(l,c,0)}else e.InputController.LastMousePosition.set(l,u,0);return e.InputController.LastMousePosition}return!0===n?e.InputController.LastMousePosition.set(r,window.innerHeight-o,0):e.InputController.LastMousePosition.set(r,o,0),e.InputController.LastMousePosition},t.IsWheelScrolling=function(){return 0!==e.InputController.scroll},t.OnGamepadButtonUp=function(t,n){if(void 0===n&&(n=e.PlayerNumber.One),e.InputController.input)switch(n){case e.PlayerNumber.One:e.InputController.gamepad1ButtonUp.push(t);break;case e.PlayerNumber.Two:e.InputController.gamepad2ButtonUp.push(t);break;case e.PlayerNumber.Three:e.InputController.gamepad3ButtonUp.push(t);break;case e.PlayerNumber.Four:e.InputController.gamepad4ButtonUp.push(t)}},t.OnGamepadButtonDown=function(t,n){if(void 0===n&&(n=e.PlayerNumber.One),e.InputController.input)switch(n){case e.PlayerNumber.One:e.InputController.gamepad1ButtonDown.push(t);break;case e.PlayerNumber.Two:e.InputController.gamepad2ButtonDown.push(t);break;case e.PlayerNumber.Three:e.InputController.gamepad3ButtonDown.push(t);break;case e.PlayerNumber.Four:e.InputController.gamepad4ButtonDown.push(t)}},t.OnGamepadButtonPress=function(t,n,i){if(void 0===i&&(i=e.PlayerNumber.One),e.InputController.input)switch(i){case e.PlayerNumber.One:e.InputController.gamepad1ButtonPress.push({index:t,action:n});break;case e.PlayerNumber.Two:e.InputController.gamepad2ButtonPress.push({index:t,action:n});break;case e.PlayerNumber.Three:e.InputController.gamepad3ButtonPress.push({index:t,action:n});break;case e.PlayerNumber.Four:e.InputController.gamepad4ButtonPress.push({index:t,action:n})}},t.GetGamepadButtonInput=function(t,n){void 0===n&&(n=e.PlayerNumber.One);var i=!1;if(e.InputController.input){var r=null;switch(n){case e.PlayerNumber.One:r="b1:"+t.toString();break;case e.PlayerNumber.Two:r="b2:"+t.toString();break;case e.PlayerNumber.Three:r="b3:"+t.toString();break;case e.PlayerNumber.Four:r="b4:"+t.toString()}if(null!=r&&null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];i=null!=o.result&&o.result}}return i},t.IsGamepadButtonHeld=function(t,n){void 0===n&&(n=e.PlayerNumber.One);var i=!1;if(e.InputController.input){var r=null;switch(n){case e.PlayerNumber.One:r="b1:"+t.toString();break;case e.PlayerNumber.Two:r="b2:"+t.toString();break;case e.PlayerNumber.Three:r="b3:"+t.toString();break;case e.PlayerNumber.Four:r="b4:"+t.toString()}if(null!=r&&null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];null!=o.pressTime&&null!=o.releaseTime&&!0===(null!=o.result&&o.result)&&o.pressTime>0&&0===o.releaseTime&&(i=e.SceneManager.GetTimeMs()-o.pressTime>=e.InputController.TAP_THRESHOLD_MS)}}return i},t.IsGamepadButtonTapped=function(t,n){void 0===n&&(n=e.PlayerNumber.One);var i=!1;if(e.InputController.input){var r=null;switch(n){case e.PlayerNumber.One:r="b1:"+t.toString();break;case e.PlayerNumber.Two:r="b2:"+t.toString();break;case e.PlayerNumber.Three:r="b3:"+t.toString();break;case e.PlayerNumber.Four:r="b4:"+t.toString()}if(null!=r&&null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];null!=o.pressTime&&null!=o.releaseTime&&!1===(null!=o.result&&o.result)&&o.pressTime>0&&o.releaseTime>0&&(i=o.releaseTime-o.pressTime<e.InputController.TAP_THRESHOLD_MS)}}return i},t.ResetGamepadButtonTapped=function(t,n){if(void 0===n&&(n=e.PlayerNumber.One),e.InputController.input){var i=null;switch(n){case e.PlayerNumber.One:i="b1:"+t.toString();break;case e.PlayerNumber.Two:i="b2:"+t.toString();break;case e.PlayerNumber.Three:i="b3:"+t.toString();break;case e.PlayerNumber.Four:i="b4:"+t.toString()}null!=i&&null!=e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0})}},t.OnGamepadDirectionUp=function(t,n){if(void 0===n&&(n=e.PlayerNumber.One),e.InputController.input)switch(n){case e.PlayerNumber.One:e.InputController.gamepad1DpadUp.push(t);break;case e.PlayerNumber.Two:e.InputController.gamepad2DpadUp.push(t);break;case e.PlayerNumber.Three:e.InputController.gamepad3DpadUp.push(t);break;case e.PlayerNumber.Four:e.InputController.gamepad4DpadUp.push(t)}},t.OnGamepadDirectionDown=function(t,n){if(void 0===n&&(n=e.PlayerNumber.One),e.InputController.input)switch(n){case e.PlayerNumber.One:e.InputController.gamepad1DpadDown.push(t);break;case e.PlayerNumber.Two:e.InputController.gamepad2DpadDown.push(t);break;case e.PlayerNumber.Three:e.InputController.gamepad3DpadDown.push(t);break;case e.PlayerNumber.Four:e.InputController.gamepad4DpadDown.push(t)}},t.OnGamepadDirectionPress=function(t,n,i){if(void 0===i&&(i=e.PlayerNumber.One),e.InputController.input)switch(i){case e.PlayerNumber.One:e.InputController.gamepad1DpadPress.push({index:t,action:n});break;case e.PlayerNumber.Two:e.InputController.gamepad2DpadPress.push({index:t,action:n});break;case e.PlayerNumber.Three:e.InputController.gamepad3DpadPress.push({index:t,action:n});break;case e.PlayerNumber.Four:e.InputController.gamepad4DpadPress.push({index:t,action:n})}},t.GetGamepadDirectionInput=function(t,n){void 0===n&&(n=e.PlayerNumber.One);var i=!1;if(e.InputController.input){var r=null;switch(n){case e.PlayerNumber.One:r="d1:"+t.toString();break;case e.PlayerNumber.Two:r="d2:"+t.toString();break;case e.PlayerNumber.Three:r="d3:"+t.toString();break;case e.PlayerNumber.Four:r="d4:"+t.toString()}if(null!=r&&null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];i=null!=o.result&&o.result}}return i},t.IsGamepadDirectionHeld=function(t,n){void 0===n&&(n=e.PlayerNumber.One);var i=!1;if(e.InputController.input){var r=null;switch(n){case e.PlayerNumber.One:r="d1:"+t.toString();break;case e.PlayerNumber.Two:r="d2:"+t.toString();break;case e.PlayerNumber.Three:r="d3:"+t.toString();break;case e.PlayerNumber.Four:r="d4:"+t.toString()}if(null!=r&&null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];null!=o.pressTime&&null!=o.releaseTime&&!0===(null!=o.result&&o.result)&&o.pressTime>0&&0===o.releaseTime&&(i=e.SceneManager.GetTimeMs()-o.pressTime>=e.InputController.TAP_THRESHOLD_MS)}}return i},t.IsGamepadDirectionTapped=function(t,n){void 0===n&&(n=e.PlayerNumber.One);var i=!1;if(e.InputController.input){var r=null;switch(n){case e.PlayerNumber.One:r="d1:"+t.toString();break;case e.PlayerNumber.Two:r="d2:"+t.toString();break;case e.PlayerNumber.Three:r="d3:"+t.toString();break;case e.PlayerNumber.Four:r="d4:"+t.toString()}if(null!=r&&null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];null!=o.pressTime&&null!=o.releaseTime&&!1===(null!=o.result&&o.result)&&o.pressTime>0&&o.releaseTime>0&&(i=o.releaseTime-o.pressTime<e.InputController.TAP_THRESHOLD_MS)}}return i},t.ResetGamepadDirectionTapped=function(t,n){if(void 0===n&&(n=e.PlayerNumber.One),e.InputController.input){var i=null;switch(n){case e.PlayerNumber.One:i="d1:"+t.toString();break;case e.PlayerNumber.Two:i="d2:"+t.toString();break;case e.PlayerNumber.Three:i="d3:"+t.toString();break;case e.PlayerNumber.Four:i="d4:"+t.toString()}null!=i&&null!=e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0})}},t.OnGamepadTriggerLeft=function(t,n){if(void 0===n&&(n=e.PlayerNumber.One),e.InputController.input)switch(n){case e.PlayerNumber.One:e.InputController.gamepad1LeftTrigger.push(t);break;case e.PlayerNumber.Two:e.InputController.gamepad2LeftTrigger.push(t);break;case e.PlayerNumber.Three:e.InputController.gamepad3LeftTrigger.push(t);break;case e.PlayerNumber.Four:e.InputController.gamepad4LeftTrigger.push(t)}},t.OnGamepadTriggerRight=function(t,n){if(void 0===n&&(n=e.PlayerNumber.One),e.InputController.input)switch(n){case e.PlayerNumber.One:e.InputController.gamepad1RightTrigger.push(t);break;case e.PlayerNumber.Two:e.InputController.gamepad2RightTrigger.push(t);break;case e.PlayerNumber.Three:e.InputController.gamepad3RightTrigger.push(t);break;case e.PlayerNumber.Four:e.InputController.gamepad4RightTrigger.push(t)}},t.GetGamepadTriggerInput=function(t,n){void 0===n&&(n=e.PlayerNumber.One);var i=0;if(e.InputController.input){var r=null;switch(n){case e.PlayerNumber.One:r="t1:"+t.toString();break;case e.PlayerNumber.Two:r="t2:"+t.toString();break;case e.PlayerNumber.Three:r="t3:"+t.toString();break;case e.PlayerNumber.Four:r="t4:"+t.toString()}if(null!=r&&null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];i=null!=o.result?o.result:0}}return i},t.IsGamepadTriggerHeld=function(t,n){void 0===n&&(n=e.PlayerNumber.One);var i=!1;if(e.InputController.input){var r=null;switch(n){case e.PlayerNumber.One:r="t1:"+t.toString();break;case e.PlayerNumber.Two:r="t2:"+t.toString();break;case e.PlayerNumber.Three:r="t3:"+t.toString();break;case e.PlayerNumber.Four:r="t4:"+t.toString()}if(null!=r&&null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];null!=o.pressTime&&null!=o.releaseTime&&!0===(null!=o.result&&o.result)&&o.pressTime>0&&0===o.releaseTime&&(i=e.SceneManager.GetTimeMs()-o.pressTime>=e.InputController.TAP_THRESHOLD_MS)}}return i},t.IsGamepadTriggerTapped=function(t,n){void 0===n&&(n=e.PlayerNumber.One);var i=!1;if(e.InputController.input){var r=null;switch(n){case e.PlayerNumber.One:r="t1:"+t.toString();break;case e.PlayerNumber.Two:r="t2:"+t.toString();break;case e.PlayerNumber.Three:r="t3:"+t.toString();break;case e.PlayerNumber.Four:r="t4:"+t.toString()}if(null!=r&&null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];null!=o.pressTime&&null!=o.releaseTime&&!1===(null!=o.result&&o.result)&&o.pressTime>0&&o.releaseTime>0&&(i=o.releaseTime-o.pressTime<e.InputController.TAP_THRESHOLD_MS)}}return i},t.ResetGamepadTriggerTapped=function(t,n){if(void 0===n&&(n=e.PlayerNumber.One),e.InputController.input){var i=null;switch(n){case e.PlayerNumber.One:i="t1:"+t.toString();break;case e.PlayerNumber.Two:i="t2:"+t.toString();break;case e.PlayerNumber.Three:i="t3:"+t.toString();break;case e.PlayerNumber.Four:i="t4:"+t.toString()}null!=i&&null!=e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0})}},t.GetGamepadType=function(t){void 0===t&&(t=e.PlayerNumber.One);var n=e.GamepadType.None;if(e.InputController.input)switch(t){case e.PlayerNumber.One:n=e.InputController.gamepad1Type;break;case e.PlayerNumber.Two:n=e.InputController.gamepad2Type;break;case e.PlayerNumber.Three:n=e.InputController.gamepad3Type;break;case e.PlayerNumber.Four:n=e.InputController.gamepad4Type}return n},t.GetGamepad=function(t){void 0===t&&(t=e.PlayerNumber.One);var n=null;if(e.InputController.input)switch(t){case e.PlayerNumber.One:n=e.InputController.gamepad1;break;case e.PlayerNumber.Two:n=e.InputController.gamepad2;break;case e.PlayerNumber.Three:n=e.InputController.gamepad3;break;case e.PlayerNumber.Four:n=e.InputController.gamepad4}return n},t.InputKeyDownHandler=function(t,n){if(void 0===n&&(n=null),null==t||!1===e.SceneManager.EnableUserInput)return!1;n&&n.preventDefault();var i="k:"+t.toString(),r=!1;if(null==e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[i]){var o=e.InputController.keymap[i];!1===(r=null!=o.result&&o.result)&&(o.result=!0,o.pressTime=e.SceneManager.GetTimeMs(),o.releaseTime=0)}return null!=e.InputController.keyButtonDown&&e.InputController.keyButtonDown.length>0&&e.InputController.keyButtonDown.forEach(function(e){e(t)}),r||null!=e.InputController.keyButtonPress&&e.InputController.keyButtonPress.length>0&&e.InputController.keyButtonPress.forEach(function(e){e.index===t&&e.action()}),!0},t.InputKeyUpHandler=function(t,n){if(void 0===n&&(n=null),null==t||!1===e.SceneManager.EnableUserInput)return!1;var i="k:"+t.toString();if(null!=e.InputController.keymap[i]){var r=e.InputController.keymap[i];!0===(null!=r.result&&r.result)&&(r.result=!1,r.releaseTime=e.SceneManager.GetTimeMs())}return null!=e.InputController.keyButtonUp&&e.InputController.keyButtonUp.length>0&&e.InputController.keyButtonUp.forEach(function(e){e(t)}),!0},t.tickKeyboardInput=function(t){if(!1!==e.SceneManager.EnableUserInput){var n=e.InputController.GetKeyboardInput(e.UserInputKey.W)||e.InputController.GetKeyboardInput(e.UserInputKey.UpArrow),i=e.InputController.GetKeyboardInput(e.UserInputKey.A),r=e.InputController.GetKeyboardInput(e.UserInputKey.S)||e.InputController.GetKeyboardInput(e.UserInputKey.DownArrow),o=e.InputController.GetKeyboardInput(e.UserInputKey.D),a=e.InputController.GetKeyboardInput(e.UserInputKey.LeftArrow),s=e.InputController.GetKeyboardInput(e.UserInputKey.RightArrow);e.InputController.k_vertical=!0===n?e.Utilities.GetKeyboardInputValue(t,e.InputController.k_vertical,1):!0===r?e.Utilities.GetKeyboardInputValue(t,e.InputController.k_vertical,-1):0,!0===e.UserInputOptions.UseArrowKeyRotation?(e.InputController.k_horizontal=!0===o?e.Utilities.GetKeyboardInputValue(t,e.InputController.k_horizontal,1):!0===i?e.Utilities.GetKeyboardInputValue(t,e.InputController.k_horizontal,-1):0,e.InputController.a_mousex=!0===s?1*e.UserInputOptions.KeyboardArrowSensibility:!0===a?-1*e.UserInputOptions.KeyboardArrowSensibility:0):e.InputController.k_horizontal=!0===o||!0===s?e.Utilities.GetKeyboardInputValue(t,e.InputController.k_horizontal,1):!0===i||!0===a?e.Utilities.GetKeyboardInputValue(t,e.InputController.k_horizontal,-1):0}},t.updateUserInput=function(t){var n=e.InputController.GetMouseButtonsDown();e.InputController.leftButtonDown=!(1&~n),e.InputController.middleButtonDown=!(4&~n),e.InputController.rightButtonDown=!(2&~n),!1!==e.SceneManager.EnableUserInput&&(e.InputController.PointerLockedFlag=t.getEngine().isPointerLock,e.InputController.tickKeyboardInput(t),e.InputController.x_horizontal=0,e.InputController.x_vertical=0,e.InputController.x_mousex=0,e.InputController.x_mousey=0,0!==e.InputController.j_horizontal?e.InputController.x_horizontal=e.InputController.j_horizontal:0!==e.InputController.g_horizontal1?e.InputController.x_horizontal=e.InputController.g_horizontal1:0!==e.InputController.k_horizontal&&(e.InputController.x_horizontal=e.InputController.k_horizontal),0!==e.InputController.j_vertical?e.InputController.x_vertical=e.InputController.j_vertical:0!==e.InputController.g_vertical1?e.InputController.x_vertical=e.InputController.g_vertical1:0!==e.InputController.k_vertical&&(e.InputController.x_vertical=e.InputController.k_vertical),0!==e.InputController.j_mousex?e.InputController.x_mousex=e.InputController.j_mousex:0!==e.InputController.g_mousex1?e.InputController.x_mousex=e.InputController.g_mousex1:0!==e.InputController.a_mousex?e.InputController.x_mousex=e.InputController.a_mousex:0!==e.InputController.k_mousex&&(e.InputController.x_mousex=e.InputController.k_mousex),0!==e.InputController.j_mousey?e.InputController.x_mousey=e.InputController.j_mousey:0!==e.InputController.g_mousey1?e.InputController.x_mousey=e.InputController.g_mousey1:0!==e.InputController.k_mousey&&(e.InputController.x_mousey=e.InputController.k_mousey),e.InputController.horizontal=e.InputController.x_horizontal,e.InputController.vertical=e.InputController.x_vertical,e.InputController.mousex=e.InputController.x_mousex,e.InputController.mousey=e.InputController.x_mousey,e.InputController.scroll=e.InputController.x_scroll,e.InputController.wheel=e.InputController.x_wheel,e.InputController.horizontal2=e.InputController.g_horizontal2,e.InputController.vertical2=e.InputController.g_vertical2,e.InputController.mousex2=e.InputController.g_mousex2,e.InputController.mousey2=e.InputController.g_mousey2,e.InputController.horizontal3=e.InputController.g_horizontal3,e.InputController.vertical3=e.InputController.g_vertical3,e.InputController.mousex3=e.InputController.g_mousex3,e.InputController.mousey3=e.InputController.g_mousey3,e.InputController.horizontal4=e.InputController.g_horizontal4,e.InputController.vertical4=e.InputController.g_vertical4,e.InputController.mousex4=e.InputController.g_mousex4,e.InputController.mousey4=e.InputController.g_mousey4,e.InputController.k_mousex=0,e.InputController.k_mousey=0,e.InputController.x_mousey=0,e.InputController.x_scroll=0)},t.resetUserInput=function(){e.InputController.input=!1,e.InputController.keymap={},e.InputController.scroll=0,e.InputController.wheel=0,e.InputController.mousex=0,e.InputController.mousey=0,e.InputController.vertical=0,e.InputController.horizontal=0,e.InputController.mousex2=0,e.InputController.mousey2=0,e.InputController.vertical2=0,e.InputController.horizontal2=0,e.InputController.mousex3=0,e.InputController.mousey3=0,e.InputController.vertical3=0,e.InputController.horizontal3=0,e.InputController.mousex4=0,e.InputController.mousey4=0,e.InputController.vertical4=0,e.InputController.horizontal4=0,e.InputController.a_mousex=0,e.InputController.x_scroll=0,e.InputController.x_wheel=0,e.InputController.x_mousex=0,e.InputController.x_mousey=0,e.InputController.x_vertical=0,e.InputController.x_horizontal=0,e.InputController.k_mousex=0,e.InputController.k_mousey=0,e.InputController.k_vertical=0,e.InputController.k_horizontal=0,e.InputController.j_mousex=0,e.InputController.j_mousey=0,e.InputController.j_vertical=0,e.InputController.j_horizontal=0,e.InputController.g_mousex1=0,e.InputController.g_mousey1=0,e.InputController.g_vertical1=0,e.InputController.g_horizontal1=0,e.InputController.g_mousex2=0,e.InputController.g_mousey2=0,e.InputController.g_vertical2=0,e.InputController.g_horizontal2=0,e.InputController.g_mousex3=0,e.InputController.g_mousey3=0,e.InputController.g_vertical3=0,e.InputController.g_horizontal3=0,e.InputController.g_mousex4=0,e.InputController.g_mousey4=0,e.InputController.g_vertical4=0,e.InputController.g_horizontal4=0,e.InputController.dragDirection=0,e.InputController.pinchZoomState=0,e.InputController.pinchZoomEvents=[],e.InputController.pinchZoomDistance=null,e.InputController.preventDefault=!1,e.InputController.leftButtonDown=!1,e.InputController.middleButtonDown=!1,e.InputController.rightButtonDown=!1,e.InputController.mouseDownTarget=null,e.InputController.mouseDragTarget=null,e.InputController.mouseButtonsDown=0,e.InputController.mouseButtonUp=[],e.InputController.mouseButtonDown=[],e.InputController.mouseButtonPress=[],e.InputController.keyButtonUp=[],e.InputController.keyButtonDown=[],e.InputController.keyButtonPress=[],e.InputController.gamepad1ButtonUp=[],e.InputController.gamepad1ButtonDown=[],e.InputController.gamepad1ButtonPress=[],e.InputController.gamepad1DpadUp=[],e.InputController.gamepad1DpadDown=[],e.InputController.gamepad1DpadPress=[],e.InputController.gamepad1LeftTrigger=[],e.InputController.gamepad1RightTrigger=[],e.InputController.gamepad2ButtonUp=[],e.InputController.gamepad2ButtonDown=[],e.InputController.gamepad2ButtonPress=[],e.InputController.gamepad2DpadUp=[],e.InputController.gamepad2DpadDown=[],e.InputController.gamepad2DpadPress=[],e.InputController.gamepad2LeftTrigger=[],e.InputController.gamepad2RightTrigger=[],e.InputController.gamepad3ButtonUp=[],e.InputController.gamepad3ButtonDown=[],e.InputController.gamepad3ButtonPress=[],e.InputController.gamepad3DpadUp=[],e.InputController.gamepad3DpadDown=[],e.InputController.gamepad3DpadPress=[],e.InputController.gamepad3LeftTrigger=[],e.InputController.gamepad3RightTrigger=[],e.InputController.gamepad4ButtonUp=[],e.InputController.gamepad4ButtonDown=[],e.InputController.gamepad4ButtonPress=[],e.InputController.gamepad4DpadUp=[],e.InputController.gamepad4DpadDown=[],e.InputController.gamepad4DpadPress=[],e.InputController.gamepad4LeftTrigger=[],e.InputController.gamepad4RightTrigger=[],e.InputController.previousPosition=null,e.InputController.lastClientX=0,e.InputController.lastClientY=0,e.InputController.virtualClientX=0,e.InputController.virtualClientY=0},t.resetKeyMapHandler=function(t){e.InputController.keymap={}},t.getPinchZoomDistance=function(e,t){var n=t.clientX-e.clientX,i=t.clientY-e.clientY;return Math.sqrt(n*n+i*i)},t.cachePinchZoomPointer=function(t){!0===e.InputController.EnablePinchZoomTracking&&e.InputController.pinchZoomEvents.push(t)},t.removePinchZoomPointer=function(t){if(!0===e.InputController.EnablePinchZoomTracking){for(var n=0;n<e.InputController.pinchZoomEvents.length;n++)if(e.InputController.pinchZoomEvents[n].pointerId===t.pointerId){e.InputController.pinchZoomEvents.splice(n,1);break}e.InputController.pinchZoomEvents.length<2&&(e.InputController.pinchZoomDistance=null)}},t.processPinchZoomTracking=function(t){if(!0===e.InputController.EnablePinchZoomTracking){for(var n=0;n<e.InputController.pinchZoomEvents.length;n++)if(e.InputController.pinchZoomEvents[n].pointerId===t.pointerId){e.InputController.pinchZoomEvents[n]=t;break}if(e.InputController.pinchZoomState=e.PinchZoomState.None,2===e.InputController.pinchZoomEvents.length){var i=e.InputController.getPinchZoomDistance(e.InputController.pinchZoomEvents[0],e.InputController.pinchZoomEvents[1]);i!==e.InputController.pinchZoomDistance&&(i>e.InputController.pinchZoomDistance?e.InputController.pinchZoomState=e.PinchZoomState.ZoomIn:i<e.InputController.pinchZoomDistance&&(e.InputController.pinchZoomState=e.PinchZoomState.ZoomOut),e.InputController.pinchZoomDistance=i)}}},t.inputKeyDownHandler=function(t){return e.InputController.InputKeyDownHandler(t.keyCode,t)},t.inputKeyUpHandler=function(t){return e.InputController.InputKeyUpHandler(t.keyCode,t)},t.inputPointerWheelHandler=function(t){if(!1===e.SceneManager.EnableUserInput)return!1;var n=t.deltaY?-t.deltaY:t.wheelDelta/40;return e.InputController.x_scroll=1,e.InputController.x_wheel=Math.abs(n)>e.UserInputOptions.PointerWheelDeadZone?0+n:0,e.InputController.preventDefault&&t.preventDefault(),!0},t.inputPointerDownHandler=function(t){if(e.InputController.mouseDownTarget=t.target,e.InputController.mouseButtonsDown=t.buttons,e.InputController.lastClientX=t.clientX||0,e.InputController.lastClientY=t.clientY||0,e.InputController.virtualClientX=e.InputController.lastClientX,e.InputController.virtualClientY=e.InputController.lastClientY,e.InputController.cachePinchZoomPointer(t),!1===e.SceneManager.EnableUserInput)return!1;e.InputController.previousPosition={x:t.clientX,y:t.clientY};var n="p:"+t.button.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}return null!=e.InputController.mouseButtonDown&&e.InputController.mouseButtonDown.length>0&&e.InputController.mouseButtonDown.forEach(function(e){e(t.button)}),i||null!=e.InputController.mouseButtonPress&&e.InputController.mouseButtonPress.length>0&&e.InputController.mouseButtonPress.forEach(function(e){e.index===t.button&&e.action()}),e.InputController.preventDefault&&t.preventDefault(),!0},t.inputPointerUpHandler=function(t){if(e.InputController.mouseDownTarget=null,e.InputController.mouseDragTarget=null,e.InputController.mouseButtonsDown=t.buttons,e.InputController.lastClientX=t.clientX||0,e.InputController.lastClientY=t.clientY||0,e.InputController.virtualClientX=e.InputController.lastClientX,e.InputController.virtualClientY=e.InputController.lastClientY,e.InputController.removePinchZoomPointer(t),!1===e.SceneManager.EnableUserInput)return!1;e.InputController.previousPosition=null,e.InputController.k_mousex=0,e.InputController.k_mousey=0;var n="p:"+t.button.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}return null!=e.InputController.mouseButtonUp&&e.InputController.mouseButtonUp.length>0&&e.InputController.mouseButtonUp.forEach(function(e){e(t.button)}),e.InputController.preventDefault&&t.preventDefault(),!0},t.inputPointerMoveHandler=function(t){if(e.InputController.mouseDragTarget=t.target,e.InputController.mouseButtonsDown=t.buttons,e.InputController.lastClientX=t.clientX||0,e.InputController.lastClientY=t.clientY||0,e.InputController.IsPointerLocked()){var n=t.movementX||t.mozMovementX||t.webkitMovementX||t.msMovementX||0,i=t.movementY||t.mozMovementY||t.webkitMovementY||t.msMovementY||0;e.InputController.virtualClientX+=n,e.InputController.virtualClientY+=i}else e.InputController.virtualClientX=e.InputController.lastClientX,e.InputController.virtualClientY=e.InputController.lastClientY;if(e.InputController.processPinchZoomTracking(t),!1===e.SceneManager.EnableUserInput)return!1;if(!1===e.SceneManager.VirtualJoystickEnabled){var r=0,o=0;if(e.InputController.IsPointerLocked()?(r=t.movementX||t.mozMovementX||t.webkitMovementX||t.msMovementX||0,o=t.movementY||t.mozMovementY||t.webkitMovementY||t.msMovementY||0,e.InputController.previousPosition=null):null!=e.InputController.previousPosition&&(r=t.clientX-e.InputController.previousPosition.x,o=t.clientY-e.InputController.previousPosition.y,e.InputController.previousPosition={x:t.clientX,y:t.clientY}),!0===e.UserInputOptions.PointerMouseInverted&&(r*=-1,o*=-1),!0===e.InputController.rightHanded&&(r*=-1),!0===e.UserInputOptions.EnableBabylonRotation)e.InputController.k_mousex=r/e.UserInputOptions.BabylonAngularSensibility,e.InputController.k_mousey=o/e.UserInputOptions.BabylonAngularSensibility;else{var a=r*e.UserInputOptions.DefaultAngularSensibility*e.InputController.MOUSE_DAMPENER,s=o*e.UserInputOptions.DefaultAngularSensibility*e.InputController.MOUSE_DAMPENER;Math.abs(r)<=e.UserInputOptions.PointerMouseDeadZone&&(a=0),Math.abs(o)<=e.UserInputOptions.PointerMouseDeadZone&&(s=0),e.InputController.k_mousex+=a,e.InputController.k_mousey+=s,e.InputController.k_mousex=BABYLON.Scalar.Clamp(e.InputController.k_mousex,-1,1),e.InputController.k_mousey=BABYLON.Scalar.Clamp(e.InputController.k_mousey,-1,1)}}return e.InputController.preventDefault&&t.preventDefault(),!0},t.inputOneButtonDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad1){var n="b1:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad1ButtonDown&&e.InputController.gamepad1ButtonDown.length>0&&e.InputController.gamepad1ButtonDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad1ButtonPress&&e.InputController.gamepad1ButtonPress.length>0&&e.InputController.gamepad1ButtonPress.forEach(function(e){e.index===t&&e.action()})}},t.inputOneButtonUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad1){var n="b1:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad1ButtonUp&&e.InputController.gamepad1ButtonUp.length>0&&e.InputController.gamepad1ButtonUp.forEach(function(e){e(t)})}},t.inputOneXboxDPadDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad1){var n="d1:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad1DpadDown&&e.InputController.gamepad1DpadDown.length>0&&e.InputController.gamepad1DpadDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad1DpadPress&&e.InputController.gamepad1DpadPress.length>0&&e.InputController.gamepad1DpadPress.forEach(function(e){e.index===t&&e.action()})}},t.inputOneShockDPadDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad1){var n="d1:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad1DpadDown&&e.InputController.gamepad1DpadDown.length>0&&e.InputController.gamepad1DpadDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad1DpadPress&&e.InputController.gamepad1DpadPress.length>0&&e.InputController.gamepad1DpadPress.forEach(function(e){e.index===t&&e.action()})}},t.inputOneXboxDPadUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad1){var n="d1:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad1DpadUp&&e.InputController.gamepad1DpadUp.length>0&&e.InputController.gamepad1DpadUp.forEach(function(e){e(t)})}},t.inputOneShockDPadUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad1){var n="d1:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad1DpadUp&&e.InputController.gamepad1DpadUp.length>0&&e.InputController.gamepad1DpadUp.forEach(function(e){e(t)})}},t.inputOneXboxLeftTriggerHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad1){var n,i="t1:0";t>0?(null==e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[i]&&!1===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!0,n.pressTime=e.SceneManager.GetTimeMs(),n.releaseTime=0)):null!=e.InputController.keymap[i]&&!0===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!1,n.releaseTime=e.SceneManager.GetTimeMs()),null!=e.InputController.gamepad1LeftTrigger&&e.InputController.gamepad1LeftTrigger.length>0&&e.InputController.gamepad1LeftTrigger.forEach(function(e){e(t)})}},t.inputOneXboxRightTriggerHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad1){var n,i="t1:1";t>0?(null==e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[i]&&!1===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!0,n.pressTime=e.SceneManager.GetTimeMs(),n.releaseTime=0)):null!=e.InputController.keymap[i]&&!0===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!1,n.releaseTime=e.SceneManager.GetTimeMs()),null!=e.InputController.gamepad1RightTrigger&&e.InputController.gamepad1RightTrigger.length>0&&e.InputController.gamepad1RightTrigger.forEach(function(e){e(t)})}},t.inputOneLeftStickHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad1){var n=t,i=n.x*e.UserInputOptions.GamepadLStickSensibility,r=n.y*e.UserInputOptions.GamepadLStickSensibility;n.x=Math.abs(i)>e.UserInputOptions.GamepadDeadStickValue?i:0,n.y=Math.abs(r)>e.UserInputOptions.GamepadDeadStickValue?r:0,n.x=BABYLON.Scalar.Clamp(n.x,-1,1),n.y=BABYLON.Scalar.Clamp(n.y,-1,1),e.InputController.g_horizontal1=e.UserInputOptions.GamepadLStickXInverted?-n.x:n.x,e.InputController.g_vertical1=e.UserInputOptions.GamepadLStickYInverted?n.y:-n.y}},t.inputOneRightStickHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad1){var n=t,i=n.x*e.UserInputOptions.GamepadRStickSensibility,r=n.y*e.UserInputOptions.GamepadRStickSensibility;n.x=Math.abs(i)>e.UserInputOptions.GamepadDeadStickValue?i:0,n.y=Math.abs(r)>e.UserInputOptions.GamepadDeadStickValue?r:0,n.x=BABYLON.Scalar.Clamp(n.x,-1,1),n.y=BABYLON.Scalar.Clamp(n.y,-1,1),e.InputController.g_mousex1=e.UserInputOptions.GamepadRStickXInverted?-n.x:n.x,e.InputController.g_mousey1=e.UserInputOptions.GamepadRStickYInverted?-n.y:n.y}},t.inputTwoButtonDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad2){var n="b2:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad2ButtonDown&&e.InputController.gamepad2ButtonDown.length>0&&e.InputController.gamepad2ButtonDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad2ButtonPress&&e.InputController.gamepad2ButtonPress.length>0&&e.InputController.gamepad2ButtonPress.forEach(function(e){e.index===t&&e.action()})}},t.inputTwoButtonUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad2){var n="b2:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad2ButtonUp&&e.InputController.gamepad2ButtonUp.length>0&&e.InputController.gamepad2ButtonUp.forEach(function(e){e(t)})}},t.inputTwoXboxDPadDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad2){var n="d2:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad2DpadDown&&e.InputController.gamepad2DpadDown.length>0&&e.InputController.gamepad2DpadDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad2DpadPress&&e.InputController.gamepad2DpadPress.length>0&&e.InputController.gamepad2DpadPress.forEach(function(e){e.index===t&&e.action()})}},t.inputTwoShockDPadDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad2){var n="d2:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad2DpadDown&&e.InputController.gamepad2DpadDown.length>0&&e.InputController.gamepad2DpadDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad2DpadPress&&e.InputController.gamepad2DpadPress.length>0&&e.InputController.gamepad2DpadPress.forEach(function(e){e.index===t&&e.action()})}},t.inputTwoXboxDPadUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad2){var n="d2:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad2DpadUp&&e.InputController.gamepad2DpadUp.length>0&&e.InputController.gamepad2DpadUp.forEach(function(e){e(t)})}},t.inputTwoShockDPadUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad2){var n="d2:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad2DpadUp&&e.InputController.gamepad2DpadUp.length>0&&e.InputController.gamepad2DpadUp.forEach(function(e){e(t)})}},t.inputTwoXboxLeftTriggerHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad2){var n,i="t2:0";t>0?(null==e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[i]&&!1===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!0,n.pressTime=e.SceneManager.GetTimeMs(),n.releaseTime=0)):null!=e.InputController.keymap[i]&&!0===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!1,n.releaseTime=e.SceneManager.GetTimeMs()),null!=e.InputController.gamepad2LeftTrigger&&e.InputController.gamepad2LeftTrigger.length>0&&e.InputController.gamepad2LeftTrigger.forEach(function(e){e(t)})}},t.inputTwoXboxRightTriggerHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad2){var n,i="t2:1";t>0?(null==e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[i]&&!1===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!0,n.pressTime=e.SceneManager.GetTimeMs(),n.releaseTime=0)):null!=e.InputController.keymap[i]&&!0===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!1,n.releaseTime=e.SceneManager.GetTimeMs()),null!=e.InputController.gamepad2RightTrigger&&e.InputController.gamepad2RightTrigger.length>0&&e.InputController.gamepad2RightTrigger.forEach(function(e){e(t)})}},t.inputTwoLeftStickHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad2){var n=t,i=n.x*e.UserInputOptions.GamepadLStickSensibility,r=n.y*e.UserInputOptions.GamepadLStickSensibility;n.x=Math.abs(i)>e.UserInputOptions.GamepadDeadStickValue?i:0,n.y=Math.abs(r)>e.UserInputOptions.GamepadDeadStickValue?r:0,n.x=BABYLON.Scalar.Clamp(n.x,-1,1),n.y=BABYLON.Scalar.Clamp(n.y,-1,1),e.InputController.g_horizontal2=e.UserInputOptions.GamepadLStickXInverted?-n.x:n.x,e.InputController.g_vertical2=e.UserInputOptions.GamepadLStickYInverted?n.y:-n.y}},t.inputTwoRightStickHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad2){var n=t,i=n.x*e.UserInputOptions.GamepadRStickSensibility,r=n.y*e.UserInputOptions.GamepadRStickSensibility;n.x=Math.abs(i)>e.UserInputOptions.GamepadDeadStickValue?i:0,n.y=Math.abs(r)>e.UserInputOptions.GamepadDeadStickValue?r:0,n.x=BABYLON.Scalar.Clamp(n.x,-1,1),n.y=BABYLON.Scalar.Clamp(n.y,-1,1),e.InputController.g_mousex2=e.UserInputOptions.GamepadRStickXInverted?-n.x:n.x,e.InputController.g_mousey2=e.UserInputOptions.GamepadRStickYInverted?-n.y:n.y}},t.inputThreeButtonDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad3){var n="b3:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad3ButtonDown&&e.InputController.gamepad3ButtonDown.length>0&&e.InputController.gamepad3ButtonDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad3ButtonPress&&e.InputController.gamepad3ButtonPress.length>0&&e.InputController.gamepad3ButtonPress.forEach(function(e){e.index===t&&e.action()})}},t.inputThreeButtonUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad3){var n="b3:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad3ButtonUp&&e.InputController.gamepad3ButtonUp.length>0&&e.InputController.gamepad3ButtonUp.forEach(function(e){e(t)})}},t.inputThreeXboxDPadDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad3){var n="d3:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad3DpadDown&&e.InputController.gamepad3DpadDown.length>0&&e.InputController.gamepad3DpadDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad3DpadPress&&e.InputController.gamepad3DpadPress.length>0&&e.InputController.gamepad3DpadPress.forEach(function(e){e.index===t&&e.action()})}},t.inputThreeShockDPadDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad3){var n="d3:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad3DpadDown&&e.InputController.gamepad3DpadDown.length>0&&e.InputController.gamepad3DpadDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad3DpadPress&&e.InputController.gamepad3DpadPress.length>0&&e.InputController.gamepad3DpadPress.forEach(function(e){e.index===t&&e.action()})}},t.inputThreeXboxDPadUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad3){var n="d3:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad3DpadUp&&e.InputController.gamepad3DpadUp.length>0&&e.InputController.gamepad3DpadUp.forEach(function(e){e(t)})}},t.inputThreeShockDPadUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad3){var n="d3:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad3DpadUp&&e.InputController.gamepad3DpadUp.length>0&&e.InputController.gamepad3DpadUp.forEach(function(e){e(t)})}},t.inputThreeXboxLeftTriggerHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad3){var n,i="t3:0";t>0?(null==e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[i]&&!1===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!0,n.pressTime=e.SceneManager.GetTimeMs(),n.releaseTime=0)):null!=e.InputController.keymap[i]&&!0===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!1,n.releaseTime=e.SceneManager.GetTimeMs()),null!=e.InputController.gamepad3LeftTrigger&&e.InputController.gamepad3LeftTrigger.length>0&&e.InputController.gamepad3LeftTrigger.forEach(function(e){e(t)})}},t.inputThreeXboxRightTriggerHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad3){var n,i="t3:1";t>0?(null==e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[i]&&!1===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!0,n.pressTime=e.SceneManager.GetTimeMs(),n.releaseTime=0)):null!=e.InputController.keymap[i]&&!0===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!1,n.releaseTime=e.SceneManager.GetTimeMs()),null!=e.InputController.gamepad3RightTrigger&&e.InputController.gamepad3RightTrigger.length>0&&e.InputController.gamepad3RightTrigger.forEach(function(e){e(t)})}},t.inputThreeLeftStickHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad3){var n=t,i=n.x*e.UserInputOptions.GamepadLStickSensibility,r=n.y*e.UserInputOptions.GamepadLStickSensibility;n.x=Math.abs(i)>e.UserInputOptions.GamepadDeadStickValue?i:0,n.y=Math.abs(r)>e.UserInputOptions.GamepadDeadStickValue?r:0,n.x=BABYLON.Scalar.Clamp(n.x,-1,1),n.y=BABYLON.Scalar.Clamp(n.y,-1,1),e.InputController.g_horizontal3=e.UserInputOptions.GamepadLStickXInverted?-n.x:n.x,e.InputController.g_vertical3=e.UserInputOptions.GamepadLStickYInverted?n.y:-n.y}},t.inputThreeRightStickHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad3){var n=t,i=n.x*e.UserInputOptions.GamepadRStickSensibility,r=n.y*e.UserInputOptions.GamepadRStickSensibility;n.x=Math.abs(i)>e.UserInputOptions.GamepadDeadStickValue?i:0,n.y=Math.abs(r)>e.UserInputOptions.GamepadDeadStickValue?r:0,n.x=BABYLON.Scalar.Clamp(n.x,-1,1),n.y=BABYLON.Scalar.Clamp(n.y,-1,1),e.InputController.g_mousex3=e.UserInputOptions.GamepadRStickXInverted?-n.x:n.x,e.InputController.g_mousey3=e.UserInputOptions.GamepadRStickYInverted?-n.y:n.y}},t.inputFourButtonDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad4){var n="b4:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad4ButtonDown&&e.InputController.gamepad4ButtonDown.length>0&&e.InputController.gamepad4ButtonDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad4ButtonPress&&e.InputController.gamepad4ButtonPress.length>0&&e.InputController.gamepad4ButtonPress.forEach(function(e){e.index===t&&e.action()})}},t.inputFourButtonUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad4){var n="b4:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad4ButtonUp&&e.InputController.gamepad4ButtonUp.length>0&&e.InputController.gamepad4ButtonUp.forEach(function(e){e(t)})}},t.inputFourXboxDPadDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad4){var n="d4:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad4DpadDown&&e.InputController.gamepad4DpadDown.length>0&&e.InputController.gamepad4DpadDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad4DpadPress&&e.InputController.gamepad4DpadPress.length>0&&e.InputController.gamepad4DpadPress.forEach(function(e){e.index===t&&e.action()})}},t.inputFourShockDPadDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad4){var n="d4:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad4DpadDown&&e.InputController.gamepad4DpadDown.length>0&&e.InputController.gamepad4DpadDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad4DpadPress&&e.InputController.gamepad4DpadPress.length>0&&e.InputController.gamepad4DpadPress.forEach(function(e){e.index===t&&e.action()})}},t.inputFourXboxDPadUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad4){var n="d4:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad4DpadUp&&e.InputController.gamepad4DpadUp.length>0&&e.InputController.gamepad4DpadUp.forEach(function(e){e(t)})}},t.inputFourShockDPadUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad4){var n="d4:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad4DpadUp&&e.InputController.gamepad4DpadUp.length>0&&e.InputController.gamepad4DpadUp.forEach(function(e){e(t)})}},t.inputFourXboxLeftTriggerHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad4){var n,i="t4:0";t>0?(null==e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[i]&&!1===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!0,n.pressTime=e.SceneManager.GetTimeMs(),n.releaseTime=0)):null!=e.InputController.keymap[i]&&!0===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!1,n.releaseTime=e.SceneManager.GetTimeMs()),null!=e.InputController.gamepad4LeftTrigger&&e.InputController.gamepad4LeftTrigger.length>0&&e.InputController.gamepad4LeftTrigger.forEach(function(e){e(t)})}},t.inputFourXboxRightTriggerHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad4){var n,i="t4:1";t>0?(null==e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[i]&&!1===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!0,n.pressTime=e.SceneManager.GetTimeMs(),n.releaseTime=0)):null!=e.InputController.keymap[i]&&!0===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!1,n.releaseTime=e.SceneManager.GetTimeMs()),null!=e.InputController.gamepad4RightTrigger&&e.InputController.gamepad4RightTrigger.length>0&&e.InputController.gamepad4RightTrigger.forEach(function(e){e(t)})}},t.inputFourLeftStickHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad4){var n=t,i=n.x*e.UserInputOptions.GamepadLStickSensibility,r=n.y*e.UserInputOptions.GamepadLStickSensibility;n.x=Math.abs(i)>e.UserInputOptions.GamepadDeadStickValue?i:0,n.y=Math.abs(r)>e.UserInputOptions.GamepadDeadStickValue?r:0,n.x=BABYLON.Scalar.Clamp(n.x,-1,1),n.y=BABYLON.Scalar.Clamp(n.y,-1,1),e.InputController.g_horizontal4=e.UserInputOptions.GamepadLStickXInverted?-n.x:n.x,e.InputController.g_vertical4=e.UserInputOptions.GamepadLStickYInverted?n.y:-n.y}},t.inputFourRightStickHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad4){var n=t,i=n.x*e.UserInputOptions.GamepadRStickSensibility,r=n.y*e.UserInputOptions.GamepadRStickSensibility;n.x=Math.abs(i)>e.UserInputOptions.GamepadDeadStickValue?i:0,n.y=Math.abs(r)>e.UserInputOptions.GamepadDeadStickValue?r:0,n.x=BABYLON.Scalar.Clamp(n.x,-1,1),n.y=BABYLON.Scalar.Clamp(n.y,-1,1),e.InputController.g_mousex4=e.UserInputOptions.GamepadRStickXInverted?-n.x:n.x,e.InputController.g_mousey4=e.UserInputOptions.GamepadRStickYInverted?-n.y:n.y}},t.inputManagerGamepadConnected=function(t,n){if(null==e.InputController.gamepad1&&0===t.index)if(e.InputController.gamepad1=t,BABYLON.Tools.Log("Gamepad One Connected: "+e.InputController.gamepad1.id),e.InputController.gamepad1 instanceof BABYLON.Xbox360Pad){e.InputController.gamepad1Type=e.GamepadType.Xbox360;var i=e.InputController.gamepad1;i.onbuttonup(e.InputController.inputOneButtonUpHandler),i.onbuttondown(e.InputController.inputOneButtonDownHandler),i.onleftstickchanged(e.InputController.inputOneLeftStickHandler),i.onrightstickchanged(e.InputController.inputOneRightStickHandler),i.ondpadup(e.InputController.inputOneXboxDPadUpHandler),i.ondpaddown(e.InputController.inputOneXboxDPadDownHandler),i.onlefttriggerchanged(e.InputController.inputOneXboxLeftTriggerHandler),i.onrighttriggerchanged(e.InputController.inputOneXboxRightTriggerHandler)}else if(e.InputController.gamepad1 instanceof BABYLON.DualShockPad){e.InputController.gamepad1Type=e.GamepadType.DualShock;var r=e.InputController.gamepad1;r.onbuttonup(e.InputController.inputOneButtonUpHandler),r.onbuttondown(e.InputController.inputOneButtonDownHandler),r.onleftstickchanged(e.InputController.inputOneLeftStickHandler),r.onrightstickchanged(e.InputController.inputOneRightStickHandler),r.ondpadup(e.InputController.inputOneShockDPadUpHandler),r.ondpaddown(e.InputController.inputOneShockDPadDownHandler),r.onlefttriggerchanged(e.InputController.inputOneXboxLeftTriggerHandler),r.onrighttriggerchanged(e.InputController.inputOneXboxRightTriggerHandler)}else{e.InputController.gamepad1Type=e.GamepadType.Generic;var o=e.InputController.gamepad1;o.onbuttonup(e.InputController.inputOneButtonUpHandler),o.onbuttondown(e.InputController.inputOneButtonDownHandler),o.onleftstickchanged(e.InputController.inputOneLeftStickHandler),o.onrightstickchanged(e.InputController.inputOneRightStickHandler)}if(null==e.InputController.gamepad2&&1===t.index)if(e.InputController.gamepad2=t,BABYLON.Tools.Log("Gamepad Two Connected: "+e.InputController.gamepad2.id),e.InputController.gamepad2 instanceof BABYLON.Xbox360Pad){e.InputController.gamepad2Type=e.GamepadType.Xbox360;var a=e.InputController.gamepad2;a.onbuttonup(e.InputController.inputTwoButtonUpHandler),a.onbuttondown(e.InputController.inputTwoButtonDownHandler),a.onleftstickchanged(e.InputController.inputTwoLeftStickHandler),a.onrightstickchanged(e.InputController.inputTwoRightStickHandler),a.ondpadup(e.InputController.inputTwoXboxDPadUpHandler),a.ondpaddown(e.InputController.inputTwoXboxDPadDownHandler),a.onlefttriggerchanged(e.InputController.inputTwoXboxLeftTriggerHandler),a.onrighttriggerchanged(e.InputController.inputTwoXboxRightTriggerHandler)}else if(e.InputController.gamepad2 instanceof BABYLON.DualShockPad){e.InputController.gamepad2Type=e.GamepadType.DualShock;var s=e.InputController.gamepad2;s.onbuttonup(e.InputController.inputOneButtonUpHandler),s.onbuttondown(e.InputController.inputOneButtonDownHandler),s.onleftstickchanged(e.InputController.inputOneLeftStickHandler),s.onrightstickchanged(e.InputController.inputOneRightStickHandler),s.ondpadup(e.InputController.inputOneShockDPadUpHandler),s.ondpaddown(e.InputController.inputOneShockDPadDownHandler),s.onlefttriggerchanged(e.InputController.inputOneXboxLeftTriggerHandler),s.onrighttriggerchanged(e.InputController.inputOneXboxRightTriggerHandler)}else{e.InputController.gamepad2Type=e.GamepadType.Generic;var l=e.InputController.gamepad2;l.onbuttonup(e.InputController.inputTwoButtonUpHandler),l.onbuttondown(e.InputController.inputTwoButtonDownHandler),l.onleftstickchanged(e.InputController.inputTwoLeftStickHandler),l.onrightstickchanged(e.InputController.inputTwoRightStickHandler)}if(null==e.InputController.gamepad3&&2===t.index)if(e.InputController.gamepad3=t,BABYLON.Tools.Log("Gamepad Three Connected: "+e.InputController.gamepad3.id),e.InputController.gamepad3 instanceof BABYLON.Xbox360Pad){e.InputController.gamepad3Type=e.GamepadType.Xbox360;var u=e.InputController.gamepad3;u.onbuttonup(e.InputController.inputThreeButtonUpHandler),u.onbuttondown(e.InputController.inputThreeButtonDownHandler),u.onleftstickchanged(e.InputController.inputThreeLeftStickHandler),u.onrightstickchanged(e.InputController.inputThreeRightStickHandler),u.ondpadup(e.InputController.inputThreeXboxDPadUpHandler),u.ondpaddown(e.InputController.inputThreeXboxDPadDownHandler),u.onlefttriggerchanged(e.InputController.inputThreeXboxLeftTriggerHandler),u.onrighttriggerchanged(e.InputController.inputThreeXboxRightTriggerHandler)}else if(e.InputController.gamepad3 instanceof BABYLON.DualShockPad){var c=e.InputController.gamepad3;c.onbuttonup(e.InputController.inputOneButtonUpHandler),c.onbuttondown(e.InputController.inputOneButtonDownHandler),c.onleftstickchanged(e.InputController.inputOneLeftStickHandler),c.onrightstickchanged(e.InputController.inputOneRightStickHandler),c.ondpadup(e.InputController.inputOneShockDPadUpHandler),c.ondpaddown(e.InputController.inputOneShockDPadDownHandler),c.onlefttriggerchanged(e.InputController.inputOneXboxLeftTriggerHandler),c.onrighttriggerchanged(e.InputController.inputOneXboxRightTriggerHandler)}else{e.InputController.gamepad3Type=e.GamepadType.Generic;var d=e.InputController.gamepad3;d.onbuttonup(e.InputController.inputThreeButtonUpHandler),d.onbuttondown(e.InputController.inputThreeButtonDownHandler),d.onleftstickchanged(e.InputController.inputThreeLeftStickHandler),d.onrightstickchanged(e.InputController.inputThreeRightStickHandler)}if(null==e.InputController.gamepad4&&3===t.index)if(e.InputController.gamepad4=t,BABYLON.Tools.Log("Gamepad Four Connected: "+e.InputController.gamepad4.id),e.InputController.gamepad4 instanceof BABYLON.Xbox360Pad){e.InputController.gamepad4Type=e.GamepadType.Xbox360;var h=e.InputController.gamepad4;h.onbuttonup(e.InputController.inputFourButtonUpHandler),h.onbuttondown(e.InputController.inputFourButtonDownHandler),h.onleftstickchanged(e.InputController.inputFourLeftStickHandler),h.onrightstickchanged(e.InputController.inputFourRightStickHandler),h.ondpadup(e.InputController.inputFourXboxDPadUpHandler),h.ondpaddown(e.InputController.inputFourXboxDPadDownHandler),h.onlefttriggerchanged(e.InputController.inputFourXboxLeftTriggerHandler),h.onrighttriggerchanged(e.InputController.inputFourXboxRightTriggerHandler)}else if(e.InputController.gamepad4 instanceof BABYLON.DualShockPad){var p=e.InputController.gamepad4;p.onbuttonup(e.InputController.inputOneButtonUpHandler),p.onbuttondown(e.InputController.inputOneButtonDownHandler),p.onleftstickchanged(e.InputController.inputOneLeftStickHandler),p.onrightstickchanged(e.InputController.inputOneRightStickHandler),p.ondpadup(e.InputController.inputOneShockDPadUpHandler),p.ondpaddown(e.InputController.inputOneShockDPadDownHandler),p.onlefttriggerchanged(e.InputController.inputOneXboxLeftTriggerHandler),p.onrighttriggerchanged(e.InputController.inputOneXboxRightTriggerHandler)}else{e.InputController.gamepad4Type=e.GamepadType.Generic;var m=e.InputController.gamepad4;m.onbuttonup(e.InputController.inputFourButtonUpHandler),m.onbuttondown(e.InputController.inputFourButtonDownHandler),m.onleftstickchanged(e.InputController.inputFourLeftStickHandler),m.onrightstickchanged(e.InputController.inputFourRightStickHandler)}null!=e.InputController.GamepadConnected&&e.InputController.GamepadConnected(t,n)},t.inputManagerGamepadDisconnected=function(t,n){null!=e.InputController.GamepadDisconnected&&e.InputController.GamepadDisconnected(t,n)},t.MOUSE_DAMPENER=.5,t.TAP_THRESHOLD_MS=200,t.GamepadManager=null,t.GamepadConnected=null,t.GamepadDisconnected=null,t.AllowMobileControls=!0,t.MobileControlsActive=!1,t.EnablePinchZoomTracking=!1,t.LastMousePosition=new BABYLON.Vector3(0,0,0),t.PointerLockedFlag=!1,t.LockMousePointerObserver=null,t.input=!1,t.keymap={},t.scroll=0,t.wheel=0,t.mousex=0,t.mousey=0,t.vertical=0,t.horizontal=0,t.mousex2=0,t.mousey2=0,t.vertical2=0,t.horizontal2=0,t.mousex3=0,t.mousey3=0,t.vertical3=0,t.horizontal3=0,t.mousex4=0,t.mousey4=0,t.vertical4=0,t.horizontal4=0,t.a_mousex=0,t.x_scroll=0,t.x_wheel=0,t.x_mousex=0,t.x_mousey=0,t.x_vertical=0,t.x_horizontal=0,t.k_mousex=0,t.k_mousey=0,t.k_vertical=0,t.k_horizontal=0,t.j_mousex=0,t.j_mousey=0,t.j_vertical=0,t.j_horizontal=0,t.g_mousex1=0,t.g_mousey1=0,t.g_vertical1=0,t.g_horizontal1=0,t.g_mousex2=0,t.g_mousey2=0,t.g_vertical2=0,t.g_horizontal2=0,t.g_mousex3=0,t.g_mousey3=0,t.g_vertical3=0,t.g_horizontal3=0,t.g_mousex4=0,t.g_mousey4=0,t.g_vertical4=0,t.g_horizontal4=0,t.dragDirection=0,t.pinchZoomState=0,t.pinchZoomEvents=[],t.pinchZoomDistance=null,t.mouseDownTarget=null,t.mouseDragTarget=null,t.leftButtonDown=!1,t.middleButtonDown=!1,t.rightButtonDown=!1,t.mouseButtonsDown=0,t.mouseButtonPress=[],t.mouseButtonDown=[],t.mouseButtonUp=[],t.keyButtonPress=[],t.keyButtonDown=[],t.keyButtonUp=[],t.previousPosition=null,t.preventDefault=!1,t.lastClientX=0,t.lastClientY=0,t.virtualClientX=0,t.virtualClientY=0,t.rightHanded=!0,t.gamepad1=null,t.gamepad1Type=-1,t.gamepad1ButtonPress=[],t.gamepad1ButtonDown=[],t.gamepad1ButtonUp=[],t.gamepad1DpadPress=[],t.gamepad1DpadDown=[],t.gamepad1DpadUp=[],t.gamepad1LeftTrigger=[],t.gamepad1RightTrigger=[],t.gamepad2=null,t.gamepad2Type=-1,t.gamepad2ButtonPress=[],t.gamepad2ButtonDown=[],t.gamepad2ButtonUp=[],t.gamepad2DpadPress=[],t.gamepad2DpadDown=[],t.gamepad2DpadUp=[],t.gamepad2LeftTrigger=[],t.gamepad2RightTrigger=[],t.gamepad3=null,t.gamepad3Type=-1,t.gamepad3ButtonPress=[],t.gamepad3ButtonDown=[],t.gamepad3ButtonUp=[],t.gamepad3DpadPress=[],t.gamepad3DpadDown=[],t.gamepad3DpadUp=[],t.gamepad3LeftTrigger=[],t.gamepad3RightTrigger=[],t.gamepad4=null,t.gamepad4Type=-1,t.gamepad4ButtonPress=[],t.gamepad4ButtonDown=[],t.gamepad4ButtonUp=[],t.gamepad4DpadPress=[],t.gamepad4DpadDown=[],t.gamepad4DpadUp=[],t.gamepad4LeftTrigger=[],t.gamepad4RightTrigger=[],t}();e.InputController=o;var a=function(){function t(e,t,n,i,r,o){void 0===i&&(i=!0),void 0===r&&(r=-1),void 0===o&&(o=null);var a=this;this.isFixed=!0,this.touchId=null,this.pointerId=null,this.dragStart=null,this.mouseButton=-1,this.maxDistance=48,this.deadZone=2,this.xvalue=0,this.yvalue=0,this.stick=null,this.base=null,this.active=!1,this.enabled=!0,this.updateElements=!0,this.preventDefault=!0,this.stopPropagation=!0,this.baseElementOpacity="1",this.stickElementOpacity="1",this.onHandleDown=null,this.onHandleMove=null,this.onHandleUp=null,this.isFixed=i,this.deadZone=n,this.maxDistance=t,this.mouseButton=r,o&&(this.base=document.getElementById(o)),e&&(this.stick=document.getElementById(e)),this.base&&(this.base.oncontextmenu=function(e){return!1}),this.stick&&(this.stick.oncontextmenu=function(e){return!1}),this.isFixed?this.stick?this.stick.addEventListener("pointerdown",function(e){return a.handleDown(e)}):console.warn("Failed to locate fixed joystick element: "+e):(this.base&&(this.base.style.opacity="0"),this.stick&&(this.stick.style.opacity="0"),document.documentElement.addEventListener("pointerdown",function(e){return a.handleDown(e)})),document.documentElement.addEventListener("pointermove",function(e){return a.handleMove(e)},{passive:!1}),document.documentElement.addEventListener("pointerup",function(e){return a.handleUp(e)})}return t.prototype.dispose=function(){},t.prototype.isActive=function(){return this.active},t.prototype.getValueX=function(){return this.xvalue},t.prototype.getValueY=function(){return this.yvalue},t.prototype.getMouseButton=function(){return this.mouseButton},t.prototype.getBaseElement=function(){return this.base},t.prototype.getStickElement=function(){return this.stick},t.prototype.isFixedJoystick=function(){return this.isFixed},t.prototype.handleDown=function(t){if(this.enabled){var n=!(1&~t.buttons),i=!(2&~t.buttons);(this.mouseButton!==e.TouchMouseButton.Left||n)&&(this.mouseButton!==e.TouchMouseButton.Right||i)&&(this.active=!0,this.pointerId=t.pointerId,this.showBaseElement(t),this.stick&&(this.stick.style.transition="0s"),this.active&&this.preventDefault&&t.preventDefault(),t.changedTouches?(this.dragStart={x:t.changedTouches[0].clientX,y:t.changedTouches[0].clientY},this.touchId=t.changedTouches[0].identifier):this.dragStart={x:t.clientX,y:t.clientY},this.onHandleDown&&this.onHandleDown(t),this.stopPropagation&&t.stopPropagation())}},t.prototype.handleMove=function(e){if(this.enabled&&this.active&&e.pointerId===this.pointerId){if(e.changedTouches){for(var t=null,n=0;n<e.changedTouches.length;n++)this.touchId===e.changedTouches[n].identifier&&(t=n,e.clientX=e.changedTouches[n].clientX,e.clientY=e.changedTouches[n].clientY);if(null===t)return}var i=e.clientX-this.dragStart.x,r=e.clientY-this.dragStart.y,o=Math.atan2(r,i),a=Math.min(this.maxDistance,Math.hypot(i,r)),s=a*Math.cos(o),l=a*Math.sin(o);this.stick&&(this.stick.style.transform="translate3d(".concat(s,"px, ").concat(l,"px, 0px)"));var u=a<this.deadZone?0:this.maxDistance/(this.maxDistance-this.deadZone)*(a-this.deadZone),c=u*Math.cos(o),d=u*Math.sin(o),h=parseFloat((c/this.maxDistance).toFixed(4)),p=parseFloat((d/this.maxDistance).toFixed(4));this.xvalue=h,this.yvalue=p,this.onHandleMove&&this.onHandleMove(e),this.stopPropagation&&e.stopPropagation()}},t.prototype.handleUp=function(e){this.enabled&&this.active&&e.pointerId===this.pointerId&&(e.changedTouches&&this.touchId!==e.changedTouches[0].identifier||(this.stick&&(this.stick.style.transition=".2s",this.stick.style.transform="translate3d(0px, 0px, 0px)"),this.xvalue=0,this.yvalue=0,this.touchId=null,this.pointerId=null,this.active=!1,this.hideBaseElement(),this.onHandleUp&&this.onHandleUp(e),this.stopPropagation&&e.stopPropagation()))},t.prototype.showBaseElement=function(e){if(!this.isFixed&&this.updateElements){if(this.base&&this.base.style.opacity!==this.baseElementOpacity){var t=this.base.getBoundingClientRect();this.base.style.left=e.clientX-t.width/2+"px",this.base.style.top=e.clientY-t.height/2+"px",this.base.style.opacity=this.baseElementOpacity}this.stick&&this.stick.style.opacity!==this.stickElementOpacity&&(this.stick.style.opacity=this.stickElementOpacity)}else this.isFixed||this.updateElements||this.hideBaseElement()},t.prototype.hideBaseElement=function(){this.isFixed||(this.base&&"0"!==this.base.style.opacity&&(this.base.style.opacity="0",this.base.style.left="-1000px",this.base.style.top="-1000px"),this.stick&&"0"!==this.stick.style.opacity&&(this.stick.style.opacity="0"))},t}();e.TouchJoystickHandler=a}(i||(i={})),function(e){var t=function(){function t(){}return t.IsWindows=function(){return"undefined"!=typeof Windows&&void 0!==Windows.UI&&void 0!==Windows.System&&void 0!==Windows.Foundation},t.IsCordova=function(){return null!=window.cordova},t.IsWebAssembly=function(){return window.WebAssembly},t.IsOculusBrowser=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/OculusBrowser/i)&&(e=!0),e},t.IsSamsungBrowser=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/SamsungBrowser/i)&&(e=!0),e},t.IsWindowsPhone=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/Windows Phone/i)&&(e=!0),e},t.IsBlackBerry=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/BlackBerry/i)&&(e=!0),e},t.IsOperaMini=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/Opera Mini/i)&&(e=!0),e},t.IsAndroid=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/Android/i)&&(e=!0),e},t.IsWebOS=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/webOS/i)&&(e=!0),e},t.IsIOS=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/iPhone|iPad|iPod/i)&&(e=!0),e},t.IsIPHONE=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/iPhone/i)&&(e=!0),e},t.IsIPAD=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/iPad/i)&&(e=!0),e},t.IsIPOD=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/iPod/i)&&(e=!0),e},t.IsIE11=function(){return void 0!==navigator.maxTouchPoints},t.IsMobile=function(){var e,t,n,i;if("undefined"==typeof navigator||"undefined"==typeof window)return!1;var r=!0===(null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile),o=null!==(i=null===(n=null===(t=window.matchMedia)||void 0===t?void 0:t.call(window,"(pointer: coarse)"))||void 0===n?void 0:n.matches)&&void 0!==i&&i,a=Math.min(window.innerWidth,window.innerHeight)<=820,s=navigator.userAgent||"",l=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Windows Phone/i.test(s);return r||o&&a||l},t.IsHighEndMobile=function(){var e;if(!this.IsMobile())return!1;var t=window.__HEM_CACHE__;if("boolean"==typeof t)return t;var n=0,i=null!==(e=navigator.hardwareConcurrency)&&void 0!==e?e:0;i>=8?n+=3:i>=6?n+=2:i>=4&&(n+=1);var r=navigator.deviceMemory;"number"==typeof r&&(r>=8?n+=3:r>=6?n+=2:r>=4&&(n+=1));var o=window.devicePixelRatio||1;o>=3&&(n+=1);var a=null;try{var s=document.createElement("canvas");if(a=s.getContext("webgl2")||s.getContext("webgl")||s.getContext("experimental-webgl")||null){a.getParameter&&s.getContext("webgl2")&&(n+=2);var l=a.getParameter(a.MAX_TEXTURE_SIZE);l>=8192?n+=2:l>=4096&&(n+=1)}}catch(e){}try{screen.width*o*(screen.height*o)>=25e5&&(n+=1)}catch(e){}var u=n>=6;return window.__HEM_CACHE__=u,u},t.IsHighEndMobileAsync=function(){return a(this,void 0,void 0,function(){var e,t,n,i;return s(this,function(r){for(e=this.IsHighEndMobile(),t=performance.now(),n=0;n<75e4;n++);return(i=performance.now()-t)<18?e=!0:i>45&&(e=!1),[2,e]})})},t.IsDesktop=function(){return!e.WindowManager.IsMobile()},t.IsPlaystation=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/Playstation/i)&&(e=!0),e},t.IsXboxConsole=function(){var t=!1;return e.WindowManager.IsWindows()&&void 0!==Windows.System.Profile&&void 0!==Windows.System.Profile.AnalyticsInfo&&void 0!==Windows.System.Profile.AnalyticsInfo.versionInfo&&void 0!==Windows.System.Profile.AnalyticsInfo.versionInfo.deviceFamily&&Windows.System.Profile.AnalyticsInfo.versionInfo.deviceFamily.match(/Xbox/i)&&(t=!0),t},t.IsXboxLive=function(){return e.WindowManager.IsWindows()&&"undefined"!=typeof Microsoft&&void 0!==Microsoft.Xbox&&void 0!==Microsoft.Xbox.Services},t.IsFrameWindow=function(){return null!=window.parent&&window!==window.parent},t.IsPortraitWindow=function(){return"portrait"===e.WindowManager.GetOrientation()},t.IsLandscapeWindow=function(){return"landscape"===e.WindowManager.GetOrientation()},t.IsStandaloneWindow=function(){return!!window.navigator.standalone||!(!window.matchMedia||!window.matchMedia("(display-mode: standalone)").matches)},t.IsFullscreenWindow=function(){return!!window.navigator.standalone||!(!window.matchMedia||!window.matchMedia("(display-mode: fullscreen)").matches)},t.IsProgressiveWindow=function(){return e.WindowManager.IsStandaloneWindow()||e.WindowManager.IsFullscreenWindow()},t.GetDisplayMode=function(){if(window.navigator.standalone)return"standalone";if(window.matchMedia){if(window.matchMedia("(display-mode: fullscreen)").matches)return"fullscreen";if(window.matchMedia("(display-mode: standalone)").matches)return"standalone";if(window.matchMedia("(display-mode: minimal-ui)").matches)return"minimal-ui"}return"browser"},t.GetOrientation=function(){var e="portrait";if(window.screen&&window.screen.orientation){var t=window.screen.orientation.type;t.includes("portrait")?e="portrait":t.includes("landscape")&&(e="landscape")}else if(window.orientation){var n=window.orientation;0===n||180===n?e="portrait":90!==n&&-90!==n||(e="landscape")}return e},t.SetLocation=function(e,t){void 0===t&&(t=!1),!0===t?window.location.replace(e):window.location.assign(e)},t.AlertMessage=function(t,n){void 0===n&&(n="Babylon Toolkit");var i=null;return e.WindowManager.IsWindows()?i=new Windows.UI.Popups.MessageDialog(t,n).showAsync():window.alert(t),i},t.GetQueryStringParam=function(e,t){t||(t=window.location.href),e=e.replace(/[\[\]]/g,"\\$&");var n=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)").exec(t);return n?n[2]?decodeURIComponent(n[2].replace(/\+/g," ")):"":null},t.PostWindowMessage=function(e,t,n){void 0===t&&(t="*"),void 0===n&&(n=!1),!0===n?window.postMessage(e,t):window.top?window.top.postMessage(e,t):console.warn("No Valid Top Window")},t.ShowSceneLoader=function(){window.showSceneLoader&&window.showSceneLoader()},t.HideSceneLoader=function(){window.hideSceneLoader&&window.hideSceneLoader()},t.UpdateLoaderStatus=function(e,t,n){window.updateStatus&&window.updateStatus(e,t,n)},t.UpdateLoaderDetails=function(e,t){window.updateDetails&&window.updateDetails(e,t)},t.UpdateLoaderProgress=function(e,t){window.updateProgress&&window.updateProgress(e,t)},t.ShowPageErrorMessage=function(e,t,n){void 0===t&&(t="Error"),void 0===n&&(n=0),window.showErrorMessage&&window.showErrorMessage(e,t,n)},t.SetTimeout=function(e,t){return window.setTimeout(t,e)},t.ClearTimeout=function(e){window.clearTimeout(e)},t.SetInterval=function(e,t){return window.setInterval(t,e)},t.ClearInterval=function(e){window.clearInterval(e)},t.Atob=function(e){return window.atob(e)},t.Btoa=function(e){return window.btoa(e)},t.PopupDebug=function(e){e.debugLayer&&(e.debugLayer.hide(),e.debugLayer.show({enablePopup:!0,globalRoot:null}))},t.ToggleDebug=function(t,n,i){if(void 0===n&&(n=!1),void 0===i&&(i=null),t.debugLayer){var r=window;!0===e.WindowManager.debugLayerVisible?(e.WindowManager.debugLayerVisible=!1,r.METER&&r.METER.show&&r.METER.show(),t.debugLayer.hide()):(e.WindowManager.debugLayerVisible=!0,r.METER&&r.METER.hide&&r.METER.hide(),t.debugLayer.show({embedMode:n,globalRoot:i}))}},t.GetLocalStorageItem=function(e){return null!=window.localStorage?window.localStorage.getItem(e):null},t.SetLocalStorageItem=function(e,t){null!=window.localStorage&&window.localStorage.setItem(e,t)},t.GetSessionStorageItem=function(e){return null!=window.sessionStorage?window.sessionStorage.getItem(e):null},t.SetSessionStorageItem=function(e,t){null!=window.sessionStorage&&window.sessionStorage.setItem(e,t)},t.GetFilenameFromUrl=function(e){return e.substring(e.lastIndexOf("/")+1)},t.GetUrlParameter=function(e){var t=e.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]"),n=new RegExp("[\\?&]"+t+"=([^&#]*)").exec(window.location.search);return null!==n?decodeURIComponent(n[1].replace(/\+/g," ")):null},t.GetVirtualRealityEnabled=function(){var t=e.WindowManager.GetLocalStorageItem("virtualReality");return null!=t&&"true"===t},t.SetVirtualRealityEnabled=function(t){e.WindowManager.SetLocalStorageItem("virtualReality",t.toString().toLowerCase())},t.SetWindowsLaunchMode=function(t){void 0===t&&(t=1),e.WindowManager.IsWindows()&&void 0!==Windows.UI.ViewManagement&&void 0!==Windows.UI.ViewManagement.ApplicationView&&(Windows.UI.ViewManagement.ApplicationView.preferredLaunchWindowingMode=t)},t.GetHardwareScalingLevel=function(){return 1/window.devicePixelRatio},t.QuitWindowsApplication=function(){e.WindowManager.IsWindows()&&window.close()},t.PrintToScreen=function(t,n){if(void 0===n&&(n="white"),e.WindowManager.PrintElement=document.getElementById("print"),null==e.WindowManager.PrintElement){var i=document.createElement("div");i.id="print",i.style.position="absolute",i.style.left="6px",i.style.bottom="3px",i.style.fontSize="12px",i.style.zIndex="9001",i.style.color="#0c0",i.style.pointerEvents="none",document.body.appendChild(i),e.WindowManager.PrintElement=i}null!=e.WindowManager.PrintElement&&e.WindowManager.PrintElement.innerHTML!==t&&(e.WindowManager.PrintElement.style.color!==n&&(e.WindowManager.PrintElement.style.color=n),e.WindowManager.PrintElement.innerHTML=t)},t.debugLayerVisible=!1,t.PrintElement=null,t}();e.WindowManager=t}(i||(i={})),i.WindowManager.IsWindows()&&void 0!==Windows.UI.ViewManagement&&void 0!==Windows.UI.ViewManagement.ApplicationViewBoundsMode&&void 0!==Windows.UI.ViewManagement.ApplicationViewBoundsMode.useCoreWindow&&Windows.UI.ViewManagement.ApplicationView.getForCurrentView().setDesiredBoundsMode(Windows.UI.ViewManagement.ApplicationViewBoundsMode.useCoreWindow),i.WindowManager.IsXboxConsole()&&navigator.gamepadInputEmulation&&(navigator.gamepadInputEmulation="gamepad"),function(e){var t=function(t){function n(n,i,r,o){void 0===r&&(r={}),void 0===o&&(o="TOOLKIT.AnimationState");var a=t.call(this,n,i,r,o)||this;return a._looptime=!1,a._loopblend=!1,a._frametime=0,a._layercount=0,a._updatemode=0,a._hasrootmotion=!1,a._animationplaying=!1,a._initialtargetblending=!1,a._hastransformhierarchy=!1,a._leftfeetbottomheight=0,a._rightfeetbottomheight=0,a._runtimecontroller=null,a._executed=!1,a._awakened=!1,a._initialized=!1,a._checkers=new e.TransitionCheck,a._source="",a._machine=null,a._animationmode=0,a._animationrig=null,a._deltaPosition=new BABYLON.Vector3(0,0,0),a._deltaRotation=new BABYLON.Quaternion(0,0,0,0),a._angularVelocity=new BABYLON.Vector3(0,0,0),a._rootMotionSpeed=0,a._lastMotionSpeed=0,a._loopMotionSpeed=0,a._lastRotateSpeed=0,a._loopRotateSpeed=0,a._lastMotionRotation=new BABYLON.Quaternion(0,0,0,0),a._lastMotionPosition=new BABYLON.Vector3(0,0,0),a._positionWeight=!1,a._rootBoneWeight=!1,a._rotationWeight=!1,a._rootQuatWeight=!1,a._rootBoneTransform=null,a._positionHolder=new BABYLON.Vector3(0,0,0),a._rootBoneHolder=new BABYLON.Vector3(0,0,0),a._rotationHolder=new BABYLON.Quaternion(0,0,0,0),a._rootQuatHolder=new BABYLON.Quaternion(0,0,0,0),a._rootMotionMatrix=BABYLON.Matrix.Zero(),a._rootMotionScaling=new BABYLON.Vector3(0,0,0),a._rootMotionRotation=new BABYLON.Quaternion(0,0,0,0),a._rootMotionPosition=new BABYLON.Vector3(0,0,0),a._dirtyMotionMatrix=null,a._dirtyBlenderMatrix=null,a._targetPosition=new BABYLON.Vector3(0,0,0),a._targetRotation=new BABYLON.Quaternion(0,0,0,0),a._targetScaling=new BABYLON.Vector3(1,1,1),a._updateMatrix=BABYLON.Matrix.Zero(),a._blenderMatrix=BABYLON.Matrix.Zero(),a._blendWeights=new e.BlendingWeights,a._emptyScaling=new BABYLON.Vector3(1,1,1),a._emptyPosition=new BABYLON.Vector3(0,0,0),a._emptyRotation=new BABYLON.Quaternion(0,0,0,0),a._ikFrameEanbled=!1,a._data=new Map,a._anims=new Map,a._clips=null,a._numbers=new Map,a._booleans=new Map,a._triggers=new Map,a._parameters=new Map,a._smoothTargets=new Map,a.delayStart=0,a.speedRatio=1,a.delayUpdateUntilReady=!0,a.enableAnimations=!0,a.applyRootMotion=!1,a.onAnimationAwakeObservable=new BABYLON.Observable,a.onAnimationInitObservable=new BABYLON.Observable,a.onAnimationIKObservable=new BABYLON.Observable,a.onAnimationEndObservable=new BABYLON.Observable,a.onAnimationLoopObservable=new BABYLON.Observable,a.onAnimationEventObservable=new BABYLON.Observable,a.onAnimationUpdateObservable=new BABYLON.Observable,a.onAnimationTransitionObservable=new BABYLON.Observable,a.m_zeroVector=new BABYLON.Vector3(0,0,0),a.m_defaultGroup=null,a.m_animationTargets=null,a.m_rotationIdentity=new BABYLON.Quaternion(0,0,0,0),a.m_timelineScrubbing=!1,a.m_vertexAnimationMode=!1,a.m_vertexAnimationRenderers=null,a.m_vertexAnimationController=null,a.m_vertexAnimationDefaultClip=null,a.sourceAnimationGroups=null,a}return r(n,t),n.prototype.awakened=function(){return this._awakened},n.prototype.initialized=function(){return this._initialized},n.prototype.hasRootMotion=function(){return this._hasrootmotion},n.prototype.isFirstFrame=function(){return 0===this._frametime},n.prototype.isLastFrame=function(){return this._frametime>=.985},n.prototype.ikFrameEnabled=function(){return this._ikFrameEanbled},n.prototype.getAnimationTime=function(){return this._frametime},n.prototype.getFrameLoopTime=function(){return this._looptime},n.prototype.getFrameLoopBlend=function(){return this._loopblend},n.prototype.getAnimationPlaying=function(){return this._animationplaying},n.prototype.getRuntimeController=function(){return this._runtimecontroller},n.prototype.getRootBoneTransform=function(){return this._rootBoneTransform},n.prototype.getDeltaRootMotionAngle=function(){return this._angularVelocity.y},n.prototype.getDeltaRootMotionSpeed=function(){return this._rootMotionSpeed},n.prototype.getDeltaRootMotionPosition=function(){return this._deltaPosition},n.prototype.getDeltaRootMotionRotation=function(){return this._deltaRotation},n.prototype.getFixedRootMotionPosition=function(){return null!=this._dirtyMotionMatrix?this._rootMotionPosition:null},n.prototype.getFixedRootMotionRotation=function(){return null!=this._dirtyMotionMatrix?this._rootMotionRotation:null},n.prototype.getVertexAnimationController=function(){return this.m_vertexAnimationController},n.prototype.isVertexAnimationModeEnabled=function(){return this.m_vertexAnimationMode},n.prototype.getVertexAnimationMaterial=function(t,n){if(void 0===t&&(t=0),void 0===n&&(n=0),!this.m_vertexAnimationRenderers||0===this.m_vertexAnimationRenderers.length)return null;var i=Math.max(0,Math.min(t,this.m_vertexAnimationRenderers.length-1)),r=this.m_vertexAnimationRenderers[i];if(!r)return null;var o=r.material;if(o instanceof e.VertexAnimationMaterial)return o;if(o instanceof BABYLON.MultiMaterial){var a=o.subMaterials,s=Math.max(0,Math.min(n,a.length-1));return a[s]instanceof e.VertexAnimationMaterial?a[s]:null}return null},n.prototype.awake=function(){this.awakeStateMachine()},n.prototype.update=function(){this.updateSmoothParameters(this.getDeltaSeconds()),this.updateStateMachine()},n.prototype.destroy=function(){this.destroyStateMachine()},n.prototype.playDefault=function(t,n,i){void 0===t&&(t=.1),void 0===n&&(n=0),void 0===i&&(i=null);var r=!1;if(!0===this._initialized)if(!0===this.m_vertexAnimationMode)if(null!=this.m_vertexAnimationController)if(null!=this._machine&&null!=this._machine.layers&&this._machine.layers.length>0){var o=this._machine.layers[0];this.playCurrentAnimationState(o,o.entry,t),r=!0}else BABYLON.Tools.Warn("No animation state layers on "+this.transform.name);else BABYLON.Tools.Warn("Vertex animation controller not initialized for "+this.transform.name);else if(!0===this._initialized)if(null!=this._machine&&null!=this._machine.layers&&this._machine.layers.length>n){var a=null!=(o=this._machine.layers[n]).animationStateMachine&&o.animationStateMachine.rate||e.AnimationState.FPS,s=t>0?e.Utilities.ComputeBlendingSpeed(i||a,t):0;this.playCurrentAnimationState(o,o.entry,s),r=!0}else BABYLON.Tools.Warn("No animation state layers on "+this.transform.name);else BABYLON.Tools.Warn("Animation state machine not initialized for "+this.transform.name);else BABYLON.Tools.Warn("Animation state machine not initialized for "+this.transform.name);return r},n.prototype.playAnimation=function(t,n,i,r){void 0===n&&(n=.1),void 0===i&&(i=0),void 0===r&&(r=null);var o=!1;if(!0===this._initialized)if(!0===this.m_vertexAnimationMode)if(null!=this.m_vertexAnimationController)if(null!=this._machine&&null!=this._machine.layers&&this._machine.layers.length>0){var a=this._machine.layers[0];this.playCurrentAnimationState(a,t,n),o=!0}else BABYLON.Tools.Warn("No animation state layers on "+this.transform.name);else BABYLON.Tools.Warn("Vertex animation controller not initialized for "+this.transform.name);else if(null!=this._machine&&null!=this._machine.layers&&this._machine.layers.length>i){var s=null!=(a=this._machine.layers[i]).animationStateMachine&&a.animationStateMachine.rate||e.AnimationState.FPS,l=n>0?e.Utilities.ComputeBlendingSpeed(r||s,n):0;this.playCurrentAnimationState(a,t,l),o=!0}else BABYLON.Tools.Warn("No animation state layers on "+this.transform.name);else BABYLON.Tools.Warn("Animation state machine not initialized for "+this.transform.name);return o},n.prototype.stopAnimation=function(e){void 0===e&&(e=0);var t=!1;if(!0===this._initialized)if(!0===this.m_vertexAnimationMode)if(null!=this.m_vertexAnimationController)if(null!=this._machine&&null!=this._machine.layers&&this._machine.layers.length>0){var n=this._machine.layers[0];this.stopCurrentAnimationState(n),t=!0}else BABYLON.Tools.Warn("No animation state layers on "+this.transform.name);else BABYLON.Tools.Warn("Vertex animation controller not initialized for "+this.transform.name);else null!=this._machine&&null!=this._machine.layers&&this._machine.layers.length>e?(n=this._machine.layers[e],this.stopCurrentAnimationState(n),t=!0):BABYLON.Tools.Warn("No animation state layers on "+this.transform.name);else BABYLON.Tools.Warn("Animation state machine not initialized for "+this.transform.name);return t},n.prototype.killAnimations=function(){var e=this,t=!1;if(!0===this._initialized)if(!0===this.m_vertexAnimationMode)if(null!=this.m_vertexAnimationController)if(null!=this._machine&&null!=this._machine.layers&&this._machine.layers.length>0){var n=this._machine.layers[0];this.stopCurrentAnimationState(n),t=!0}else BABYLON.Tools.Warn("No animation state layers on "+this.transform.name);else BABYLON.Tools.Warn("Vertex animation controller not initialized for "+this.transform.name);else null!=this._machine&&null!=this._machine.layers?this._machine.layers.forEach(function(n){e.stopCurrentAnimationState(n),t=!0}):BABYLON.Tools.Warn("No animation state layers on "+this.transform.name);else BABYLON.Tools.Warn("Animation state machine not initialized for "+this.transform.name);return t},n.prototype.setTimelineScrubbing=function(e){this.m_timelineScrubbing=e,!0===this.m_vertexAnimationMode&&null!=this.m_vertexAnimationController&&!1===e&&this.m_vertexAnimationController.currentClip&&this.m_vertexAnimationController.resume()},n.prototype.getIsTimelineScrubbing=function(){return this.m_timelineScrubbing},n.prototype.setAnimationTime=function(t){if(!0===this.m_vertexAnimationMode&&null!=this.m_vertexAnimationController){if(this.m_vertexAnimationController.setCurrentTime(t),null!=this._machine&&null!=this._machine.layers&&this._machine.layers.length>0){var n=this._machine.layers[0],i=this.m_vertexAnimationController.currentClip,r=null!=i?i.duration:0,o=r>0?Math.max(0,Math.min(1,t/r)):0;n.animationNormal=o,n.animationTime=o*e.AnimationState.TIME}return!0}return!1},n.prototype.setAnimationSpeed=function(e){return!0===this.m_vertexAnimationMode&&null!=this.m_vertexAnimationController&&(this.m_vertexAnimationController.setSpeed(e),!0)},n.prototype.setAnimationLoop=function(e){return!0===this.m_vertexAnimationMode&&null!=this.m_vertexAnimationController&&(this.m_vertexAnimationController.setLoop(e),!0)},n.prototype.hasBool=function(e){return null!=this._booleans.get(e)},n.prototype.getBool=function(e){return this._booleans.get(e)||!1},n.prototype.setBool=function(e,t){this._booleans.set(e,t)},n.prototype.hasFloat=function(e){return null!=this._numbers.get(e)},n.prototype.getFloat=function(e){return this._numbers.get(e)||0},n.prototype.setFloat=function(e,t){this._numbers.set(e,t)},n.prototype.hasInteger=function(e){return null!=this._numbers.get(e)},n.prototype.getInteger=function(e){return this._numbers.get(e)||0},n.prototype.setInteger=function(e,t){this._numbers.set(e,t)},n.prototype.hasTrigger=function(e){return null!=this._triggers.get(e)},n.prototype.getTrigger=function(e){return this._triggers.get(e)||!1},n.prototype.setTrigger=function(e){this._triggers.set(e,!0)},n.prototype.resetTrigger=function(e){this._triggers.set(e,!1)},n.prototype.setSmoothFloat=function(e,t,n,i){if(void 0===n&&(n=.1),!(n>0))return this._smoothTargets&&this._smoothTargets.delete(e),void this.setFloat(e,t);var r=this._smoothTargets.get(e);null==r?(r={target:t,dampTime:n,velocity:new BABYLON.Vector2(0,0)},this._smoothTargets.set(e,r)):(r.target=t,r.dampTime=n)},n.prototype.setSmoothInteger=function(e,t,n,i){void 0===n&&(n=.1),this.setSmoothFloat(e,t,n,i)},n.prototype.updateSmoothParameters=function(t){var n=this;if(null!=this._smoothTargets&&0!==this._smoothTargets.size&&t>0){var i=1e-4,r=[];this._smoothTargets.forEach(function(o,a){var s=n.getFloat(a);if(Math.abs(s-o.target)<=i&&Math.abs(o.velocity.x)<=i)return n.setFloat(a,o.target),void r.push(a);var l=e.Utilities.SmoothDamp(s,o.target,o.dampTime,Number.POSITIVE_INFINITY,t,o.velocity);n.setFloat(a,l)});for(var o=0;o<r.length;o++)this._smoothTargets.delete(r[o])}},n.prototype.getMachineState=function(e){return this._data.get(e)},n.prototype.setMachineState=function(e,t){this._data.set(e,t)},n.prototype.getCurrentState=function(e){return null!=this._machine.layers&&this._machine.layers.length>e?this._machine.layers[e].animationStateMachine:null},n.prototype.getDefaultClips=function(){return this._clips},n.prototype.getDefaultSource=function(){return this._source},n.prototype.setLayerWeight=function(e,t){},n.prototype.fixAnimationGroup=function(e){var t=null;if(null!=this._clips&&this._clips.length>0)for(var n=0;n<this._clips.length;n++){var i=this._clips[n];if(null!=i.clip){var r=("."+i.clip).toLowerCase();if(e.name.toLowerCase().endsWith(r)){null==e.metadata&&(e.metadata={}),null==e.metadata.toolkit&&(e.metadata.toolkit=i),e.metadata.toolkit.source=this._source,t=i;break}}}return t},n.prototype.getAnimationGroup=function(e){return this._anims.get(e)},n.prototype.getAnimationGroups=function(){return this.sourceAnimationGroups},n.prototype.setAnimationGroups=function(e){!0!==this.m_vertexAnimationMode&&(null==this.transform.metadata&&(this.transform.metadata={}),null==this.transform.metadata.toolkit&&(this.transform.metadata.toolkit={}),this.transform.metadata.toolkit.sourceAnimationGroups=e,this.setupSourceAnimationGroups())},n.prototype.updateAnimationGroups=function(t){var n=this;!0!==this.m_vertexAnimationMode&&null!=t&&t.length>0&&(this._anims=new Map,this.m_animationTargets=[],this.m_defaultGroup=null,this.sourceAnimationGroups=null,t.forEach(function(t){var i=!1,r=t;if(null!=r&&null!=r.metadata&&null!=r.metadata.toolkit&&null!=r.metadata.toolkit.source&&""!==r.metadata.toolkit.source&&r.metadata.toolkit.source===n._source&&(i=!0),!0===i&&null!=r&&null!=r.metadata&&null!=r.metadata.toolkit&&null!=r.metadata.toolkit.clip&&""!==r.metadata.toolkit.clip){try{t.stop()}catch(e){}null==n.sourceAnimationGroups&&(n.sourceAnimationGroups=[]),n.sourceAnimationGroups.push(t),n._anims.set(r.metadata.toolkit.clip,t),null==n.m_defaultGroup&&(n.m_defaultGroup=t),null!=t.targetedAnimations&&t.targetedAnimations.length>0&&t.targetedAnimations.forEach(function(t){for(var i=-1,r=0;r<n.m_animationTargets.length;r++)if(n.m_animationTargets[r].target===t.target){i=r;break}if(i<0)if(n.m_animationTargets.push(t),null==t.target.metadata&&(t.target.metadata={}),t.target instanceof BABYLON.TransformNode){e.Utilities.ValidateTransformQuaternion(t.target);for(var o=[],a=0;a<n._layercount;a++){var s=new e.AnimationMixer;s.positionBuffer=null,s.rotationBuffer=null,s.scalingBuffer=null,s.originalMatrix=null,s.blendingFactor=0,s.blendingSpeed=0,s.rootPosition=null,s.rootRotation=null,o.push(s)}t.target.metadata.mixer=o}else if(t.target instanceof BABYLON.MorphTarget){var l=[];for(a=0;a<n._layercount;a++){var u=new e.AnimationMixer;u.influenceBuffer=null,l.push(u)}t.target.metadata.mixer=l}})}}))},n.prototype.setupSourceAnimationGroups=function(){var e=this;if(!0!==this.m_vertexAnimationMode){var t=null!=this.transform.metadata&&null!=this.transform.metadata.toolkit&&null!=this.transform.metadata.toolkit.sourceAnimationGroups?this.transform.metadata.toolkit.sourceAnimationGroups:null;null!=t&&(this.updateAnimationGroups(t),null!=this.sourceAnimationGroups&&null!=this._machine&&null!=this._machine.states&&this._machine.states.length>0&&this._machine.states.forEach(function(t){null!=t&&null!=t.name&&(null!=t.ccurves&&t.ccurves.length>0&&t.ccurves.forEach(function(e){if(null!=e.animation){var n=BABYLON.Animation.Parse(e.animation);null!=n&&(null==t.tcurves&&(t.tcurves=[]),t.tcurves.push(n))}}),e.setupTreeBranches(t.blendtree),e.setMachineState(t.name,t))}))}},n.prototype.awakeStateMachine=function(){var t=this;e.Utilities.ValidateTransformQuaternion(this.transform),this.m_animationTargets=[],this.m_defaultGroup=null,this.m_rotationIdentity=BABYLON.Quaternion.Identity(),this._source=null!=this.transform.metadata&&null!=this.transform.metadata.toolkit&&null!=this.transform.metadata.toolkit.animator&&""!==this.transform.metadata.toolkit.animator?this.transform.metadata.toolkit.animator:null,this._clips=this.getProperty("clips",this._clips),this._machine=this.getProperty("machine",this._machine),this._updatemode=this.getProperty("updatemode",this._updatemode),this._animationrig=this.getProperty("animationrig",this._animationrig),this._animationmode=this.getProperty("animationmode",this._animationmode),this._hasrootmotion=this.getProperty("hasrootmotion",this._hasrootmotion),this._runtimecontroller=this.getProperty("runtimecontroller",this._runtimecontroller),this._hastransformhierarchy=this.getProperty("hastransformhierarchy",this._hastransformhierarchy),this._leftfeetbottomheight=this.getProperty("leftfeetbottomheight",this._leftfeetbottomheight),this._rightfeetbottomheight=this.getProperty("rightfeetbottomheight",this._rightfeetbottomheight),this.applyRootMotion=this.getProperty("applyrootmotion",this.applyRootMotion),null!=this._machine&&(null!=this._machine.owner&&null!=this._machine.owner&&""!==this._machine.owner&&"*"!==this._machine.owner||(this._machine.owner=null!=this.transform.parent?this.transform.parent.name:this.transform.name),null!=this._machine.speed&&(this.speedRatio=this._machine.speed),null!=this._machine.parameters&&this._machine.parameters.length>0&&this._machine.parameters.forEach(function(n){var i=n.name,r=n.type,o=(n.curve,n.defaultFloat),a=n.defaultBool,s=n.defaultInt;t._parameters.set(i,r),r===e.AnimatorParameterType.Bool?t.setBool(i,a):r===e.AnimatorParameterType.Float?t.setFloat(i,o):r===e.AnimatorParameterType.Int?t.setInteger(i,s):r===e.AnimatorParameterType.Trigger&&t.resetTrigger(i)}),null!=this._machine.layers&&this._machine.layers.length>0&&(this._layercount=this._machine.layers.length,this._machine.layers.sort(function(e,t){return e.index<t.index?-1:e.index>t.index?1:0}),this._machine.layers.forEach(function(e){if(null==e.owner||null==e.owner||""===e.owner||e.owner,e.animationMaskMap=new Map,null!=e.avatarMask&&null!=e.avatarMask.transformPaths&&e.avatarMask.transformPaths.length>0)for(var t=0;t<e.avatarMask.transformPaths.length;t++)e.animationMaskMap.set(e.avatarMask.transformPaths[t],t)})));var n=this.getProperty("vertexcontroller",null),i=this.getProperty("lazyloadtextures",!1),r=this.getProperty("clips",null);if(null!=n&&null!=r){var o=[];if(r.forEach(function(e){var n,i;null==t.m_vertexAnimationDefaultClip&&null!=e.clip&&(t.m_vertexAnimationDefaultClip=e.clip);var r=null!==(i=null===(n=null==e?void 0:e.settings)||void 0===n?void 0:n.vertexrenderers)&&void 0!==i?i:null;null!=r&&r.forEach(function(e){return o.push(e)})}),o.length>0){this.m_vertexAnimationMode=!0,this.m_vertexAnimationRenderers=[];var a=e.SceneManager.GetRootUrl(this.scene),s={};o.forEach(function(r){if(r&&r.vertexguid&&!s[r.vertexguid]){s[r.vertexguid]=!0;var l=t.scene.getNodeById(r.vertexguid);if(null!=l){var u=l.material,c=!1;if(!(l instanceof BABYLON.InstancedMesh)){var d=function(t){if(t instanceof e.VertexAnimationMaterial){var i=t.getPlugin();i&&i.controller&&i.controller.guid!==n&&(c=!0)}};u instanceof BABYLON.MultiMaterial?u.subMaterials.forEach(d):d(u)}if(c)if(u instanceof BABYLON.MultiMaterial){var h=new BABYLON.MultiMaterial(u.name+"_"+n,t.scene);u.subMaterials.forEach(function(t){h.subMaterials.push(t instanceof e.VertexAnimationMaterial?t.cloneForInstance(t.name+"_"+n):t)}),l.material=h}else u instanceof e.VertexAnimationMaterial&&(l.material=u.cloneForInstance(u.name+"_"+n));var p=[];if(l.material instanceof BABYLON.MultiMaterial?l.material.subMaterials.forEach(function(t){t instanceof e.VertexAnimationMaterial&&p.push(t)}):l.material instanceof e.VertexAnimationMaterial&&p.push(l.material),p.length>0){t.m_vertexAnimationRenderers.push(l);var m=l instanceof BABYLON.InstancedMesh?l.sourceMesh:l;m&&!m.__vatPackedInstancedBuffersRegistered&&(m.__vatPackedInstancedBuffersRegistered=!0,m.registerInstancedBuffer("g_vatAnim0",4),m.registerInstancedBuffer("g_vatAnim1",4));var f=l.instancedBuffers;f&&(f.g_vatAnim0=new BABYLON.Vector4(0,0,0,1),f.g_vatAnim1=new BABYLON.Vector4(0,0,0,0)),p.forEach(function(s){var u=s.getPlugin();if(u instanceof e.VertexAnimationMaterialPlugin){var c=u.setupAnimations(o,n,a,i);null!=c&&(c.setInstanceMesh(r.vertexguid,l),null==t.m_vertexAnimationController&&(t.m_vertexAnimationController=c))}})}else console.error("### No VertexAnimationMaterial found on mesh GUID: "+r.vertexguid+" --\x3e For: "+t.transform.name,l)}else console.error("### Failed To Setup Vertex Animation Renderer For GUID: "+r.vertexguid+" --\x3e For: "+t.transform.name)}}),null!=this._machine&&null!=this._machine.states&&this._machine.states.length>0&&this._machine.states.forEach(function(e){null!=e&&null!=e.name&&(null!=e.ccurves&&e.ccurves.length>0&&e.ccurves.forEach(function(t){if(null!=t.animation){var n=BABYLON.Animation.Parse(t.animation);null!=n&&(null==e.tcurves&&(e.tcurves=[]),e.tcurves.push(n))}}),t.setMachineState(e.name,e))})}else this.m_vertexAnimationMode=!1,this.m_vertexAnimationRenderers=null}else this.m_vertexAnimationMode=!1,this.m_vertexAnimationRenderers=null;this._awakened=!0,this.onAnimationAwakeObservable&&this.onAnimationAwakeObservable.hasObservers()&&this.onAnimationAwakeObservable.notifyObservers(this.transform)},n.prototype.updateStateMachine=function(e){var t=this;if(void 0===e&&(e=null),!1===this.delayUpdateUntilReady||!0===this.delayUpdateUntilReady&&this.isReady())if(!0===this.m_vertexAnimationMode){if(!1===this._executed){if(this._executed=!0,null!=this._machine.layers&&this._machine.layers.length>0){var n=this._machine.layers[0];this.playCurrentAnimationState(n,n.entry,0)}this._initialized=!0,this.onAnimationInitObservable&&this.onAnimationInitObservable.hasObservers()&&this.onAnimationInitObservable.notifyObservers(this.transform)}if(!0===this.enableAnimations){var i=e||this.getDeltaSeconds();this.updateAnimationState(i),this.onAnimationUpdateObservable&&this.onAnimationUpdateObservable.hasObservers()&&this.onAnimationUpdateObservable.notifyObservers(this.transform)}}else null==this.sourceAnimationGroups&&this.setupSourceAnimationGroups(),null!=this.sourceAnimationGroups&&(!1===this._executed&&(this._executed=!0,null!=this._machine.layers&&this._machine.layers.length>0&&this._machine.layers.forEach(function(e){t.playCurrentAnimationState(e,e.entry,0)}),this._initialized=!0,this.onAnimationInitObservable&&this.onAnimationInitObservable.hasObservers()&&this.onAnimationInitObservable.notifyObservers(this.transform)),!0===this.enableAnimations)&&(i=e||this.getDeltaSeconds(),this.updateAnimationState(i),this.updateAnimationTargets(i),this.onAnimationUpdateObservable&&this.onAnimationUpdateObservable.hasObservers()&&this.onAnimationUpdateObservable.notifyObservers(this.transform))},n.prototype.destroyStateMachine=function(){this._data=null,this._clips=null,this._anims=null,this._numbers=null,this._booleans=null,this._triggers=null,this._parameters=null,this._smoothTargets=null,this._checkers=null,this._machine=null,this.sourceAnimationGroups=null,this.onAnimationAwakeObservable.clear(),this.onAnimationAwakeObservable=null,this.onAnimationInitObservable.clear(),this.onAnimationInitObservable=null,this.onAnimationIKObservable.clear(),this.onAnimationIKObservable=null,this.onAnimationEndObservable.clear(),this.onAnimationEndObservable=null,this.onAnimationLoopObservable.clear(),this.onAnimationLoopObservable=null,this.onAnimationEventObservable.clear(),this.onAnimationEventObservable=null,this.onAnimationUpdateObservable.clear(),this.onAnimationUpdateObservable=null,this.onAnimationTransitionObservable.clear(),this.onAnimationTransitionObservable=null},n.prototype.updateAnimationState=function(e){var t=this;if(null!=this._machine.layers&&this._machine.layers.length>0)if(!0===this.m_vertexAnimationMode){var n=this._machine.layers[0];this.checkStateMachine(n,e),this.updateVertexAnimationLayer(n,e)}else this._machine.layers.forEach(function(n){t.checkStateMachine(n,e)})},n.prototype.updateVertexAnimationLayer=function(t,n){if(null!=this.m_vertexAnimationController&&null!=t&&null!=t.animationStateMachine){var i=t.animationStateMachine,r=i.blendtree;if(null!=r&&null!=r.children&&0!==r.children.length){var o="number"==typeof i.speed?i.speed:1,a=Math.abs(o)*Math.abs(this.speedRatio||1),s=null,l=null,u=1,c=0,d=0,h=!1;if(r.blendType===e.BlendTreeType.Clip){var p=r.children[0];if(null==p||!p.motion)return;var m=this.m_vertexAnimationController.getClip(p.motion);if(null==m||m.duration<=0)return;s=p.motion,c=m.duration,h=!!m.loop}else{var f=[];if(this.parseTreeBranches(t,r,1,f),0===f.length)return;this.sortWeightedBlendingList(f);var g=f[0],v=f.length>1?f[1]:null,y=g.weight||0,_=y+(v&&v.weight||0);u=_>0?y/_:1;var S=this.m_vertexAnimationController.getClip(g.motion);if(null==S||S.duration<=0)return;if(s=g.motion,c=S.duration,h=!!S.loop,null!=v){var A=this.m_vertexAnimationController.getClip(v.motion);null!=A&&A.duration>0&&(l=v.motion,d=A.duration)}}if(!(null==s||c<=0)){var b=e.AnimationState.TIME/c,M=b;if(null!=l&&d>0){var B=e.AnimationState.TIME/d;M=BABYLON.Scalar.Lerp(B,b,u)}var C=this.m_vertexAnimationController.loopOverride,T=null!==C?C:h;if(t.animationTime+=n*M*a,T){for(;t.animationTime>=e.AnimationState.TIME;)t.animationTime-=e.AnimationState.TIME,this.onAnimationLoopObservable&&this.onAnimationLoopObservable.hasObservers()&&this.onAnimationLoopObservable.notifyObservers(t.index);t.animationTime<0&&(t.animationTime+=e.AnimationState.TIME)}else t.animationTime>e.AnimationState.TIME&&(t.animationTime=e.AnimationState.TIME),t.animationTime<0&&(t.animationTime=0);t.animationNormal=e.AnimationState.TIME>0?t.animationTime/e.AnimationState.TIME:0;var x=o<0!=(this.speedRatio||1)<0?1-t.animationNormal:t.animationNormal,I=x*c,O=null!=l&&d>0?x*d:0;if(!0===t.vatTransitionActive&&t.vatTransitionDuration>0){t.vatTransitionElapsed=(t.vatTransitionElapsed||0)+n;var L=t.vatTransitionElapsed/t.vatTransitionDuration;L>=1&&(L=1,t.vatTransitionActive=!1,t.vatTransitionElapsed=0,t.vatTransitionDuration=0,t.vatSourceClipName=null,t.vatSourceTimeSec=0),this.m_vertexAnimationController.driveBlend(s,I,L<1&&t.vatSourceClipName||null,L<1&&t.vatSourceTimeSec||0,L)}else this.m_vertexAnimationController.driveBlend(s,I,l,O,u)}}}},n.prototype.updateAnimationTargets=function(t){var n=this;!0!==this.m_vertexAnimationMode&&(this._looptime=!1,this._loopblend=!1,this._ikFrameEanbled=!1,this._animationplaying=!1,null!=this._machine.layers&&this._machine.layers.length>0&&this._machine.layers.forEach(function(i){if(0===i.index&&(n._frametime=i.animationTime),null!=i.animationStateMachine&&null!=i.animationStateMachine.blendtree){!0===i.animationStateMachine.iKOnFeet&&(n._ikFrameEanbled=!0),!0===i.iKPass&&n.onAnimationIKObservable&&n.onAnimationIKObservable.hasObservers()&&n.onAnimationIKObservable.notifyObservers(i.index);var r=i.animationStateMachine;if(r.type===e.MotionType.Clip&&-1!==r.played&&(r.played+=t),null!=r.blendtree.children&&r.blendtree.children.length>0){var o=r.blendtree.children[0];if(null!=o)if(r.blendtree.blendType==e.BlendTreeType.Clip){var a=o.track;if(null!=a){var s=a.metadata.toolkit.length,l=s>0?e.AnimationState.TIME/s:0;i.animationTime+=t*l*Math.abs(r.speed)*Math.abs(n.speedRatio),i.animationTime>e.AnimationState.TIME&&(i.animationTime=e.AnimationState.TIME);var u=i.animationTime>0?BABYLON.Scalar.Clamp(i.animationTime/e.AnimationState.TIME,0,1):0,c=r.speed<0!=n.speedRatio<0;i.animationNormal=c?1-u:u;var d=i.animationNormal>=.99?1:i.animationNormal,h=(parseFloat(d.toFixed(3)),s*i.animationNormal),p=0,m=0,f=0,g=!1,v=!1,y=0,_=!0,S=!0,A=!0,b=a;if(null!=b.metadata&&null!=b.metadata.toolkit&&(null!=b.metadata.toolkit.averagespeed&&(m=null!=b.metadata.toolkit.averagespeed.x?b.metadata.toolkit.averagespeed.x:0,f=null!=b.metadata.toolkit.averagespeed.z?b.metadata.toolkit.averagespeed.z:0),null!=b.metadata.toolkit.settings&&(p=null!=b.metadata.toolkit.settings.level?b.metadata.toolkit.settings.level:0,g=null!=b.metadata.toolkit.settings.looptime&&b.metadata.toolkit.settings.looptime,v=null!=b.metadata.toolkit.settings.loopblend&&b.metadata.toolkit.settings.loopblend,y=null!=b.metadata.toolkit.settings.orientationoffsety?b.metadata.toolkit.settings.orientationoffsety:0,_=null==b.metadata.toolkit.settings.loopblendorientation||b.metadata.toolkit.settings.loopblendorientation,S=null==b.metadata.toolkit.settings.loopblendpositiony||b.metadata.toolkit.settings.loopblendpositiony,A=null==b.metadata.toolkit.settings.loopblendpositionxz||b.metadata.toolkit.settings.loopblendpositionxz)),0===i.index&&(n._looptime=g,n._loopblend=v),y=BABYLON.Tools.ToRadians(y),m=Math.abs(m),f=Math.abs(f),p*=-1,i.animationTime>=e.AnimationState.TIME&&(i.animationFirstRun=!1,i.animationLoopFrame=!0,!0===g?(i.animationLoopCount++,n.onAnimationLoopObservable&&n.onAnimationLoopObservable.hasObservers()&&n.onAnimationLoopObservable.notifyObservers(i.index)):!1===i.animationEndFrame&&(i.animationEndFrame=!0,n.onAnimationEndObservable&&n.onAnimationEndObservable.hasObservers()&&n.onAnimationEndObservable.notifyObservers(i.index))),!0!==i.animationFirstRun&&!0!==g||(n._animationplaying=!0,a.targetedAnimations.forEach(function(t){if(t.target instanceof BABYLON.TransformNode){var r=t.target;if(0===i.index||null==i.avatarMask||n.filterTargetAvatarMask(i,r)){var o=null!=r.metadata&&null!=r.metadata.toolkit&&null!=r.metadata.toolkit.rootbone&&r.metadata.toolkit.rootbone;if(!0===o&&null==n._rootBoneTransform&&(n._rootBoneTransform=r),null!=r.metadata&&null!=r.metadata.mixer){var a=r.metadata.mixer[i.index];if(null!=a)if("position"===t.animation.targetProperty)n._targetPosition=e.Utilities.SampleAnimationVector3(t.animation,h,BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE,!0),!0===o&&null!=n._rootBoneTransform?(n._positionWeight=!0,n._positionHolder.set(0,0,0),n._rootBoneWeight=!1,n._rootBoneHolder.set(0,0,0),!0===n.applyRootMotion?!0===S&&!0===A?(n._positionWeight=!0,n._positionHolder.set(n._targetPosition.x,n._targetPosition.y+p,n._targetPosition.z)):!1===S&&!1===A?(n._rootBoneWeight=!0,n._rootBoneHolder.set(n._targetPosition.x,n._targetPosition.y+p,n._targetPosition.z)):!0===S&&!1===A?(n._positionWeight=!0,n._positionHolder.set(n.m_zeroVector.x,n._targetPosition.y+p,n.m_zeroVector.z),n._rootBoneWeight=!0,n._rootBoneHolder.set(n._targetPosition.x,n.m_zeroVector.y,n._targetPosition.z)):!0===A&&!1===S&&(n._positionWeight=!0,n._positionHolder.set(n._targetPosition.x,n.m_zeroVector.y,n._targetPosition.z),n._rootBoneWeight=!0,n._rootBoneHolder.set(n.m_zeroVector.x,n._targetPosition.y+p,n.m_zeroVector.z)):(n._positionWeight=!0,n._positionHolder.set(n._targetPosition.x,n._targetPosition.y,n._targetPosition.z)),!0===n._positionWeight&&(null==a.positionBuffer&&(a.positionBuffer=new BABYLON.Vector3(0,0,0)),e.Utilities.BlendVector3Value(a.positionBuffer,n._positionHolder,1)),!0===n._rootBoneWeight&&(null==a.rootPosition&&(a.rootPosition=new BABYLON.Vector3(0,0,0)),e.Utilities.BlendVector3Value(a.rootPosition,n._rootBoneHolder,1))):(null==a.positionBuffer&&(a.positionBuffer=new BABYLON.Vector3(0,0,0)),e.Utilities.BlendVector3Value(a.positionBuffer,n._targetPosition,1));else if("rotationQuaternion"===t.animation.targetProperty)if(n._targetRotation=e.Utilities.SampleAnimationQuaternion(t.animation,h,BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE,!0),!0===o&&null!=n._rootBoneTransform){n._rotationWeight=!1,n._rotationHolder.copyFrom(n.m_rotationIdentity),n._rootQuatWeight=!1,n._rootQuatHolder.copyFrom(n.m_rotationIdentity);var s=n._targetRotation.toEulerAngles(),l=s.y;!0===n.applyRootMotion?!0===_?(n._rotationWeight=!0,BABYLON.Quaternion.FromEulerAnglesToRef(s.x,l+y,s.z,n._rotationHolder)):(n._rotationWeight=!0,BABYLON.Quaternion.FromEulerAnglesToRef(s.x,n.m_zeroVector.y,s.z,n._rotationHolder),n._rootQuatWeight=!0,BABYLON.Quaternion.FromEulerAnglesToRef(n.m_zeroVector.x,l+y,n.m_zeroVector.z,n._rootQuatHolder)):(n._rotationWeight=!0,BABYLON.Quaternion.FromEulerAnglesToRef(s.x,l+y,s.z,n._rotationHolder)),!0===n._rotationWeight&&(null==a.rotationBuffer&&(a.rotationBuffer=new BABYLON.Quaternion(0,0,0,0)),e.Utilities.BlendQuaternionValue(a.rotationBuffer,n._rotationHolder,1)),!0===n._rootQuatWeight&&(null==a.rootRotation&&(a.rootRotation=new BABYLON.Quaternion(0,0,0,0)),e.Utilities.BlendQuaternionValue(a.rootRotation,n._rootQuatHolder,1))}else null==a.rotationBuffer&&(a.rotationBuffer=new BABYLON.Quaternion(0,0,0,0)),e.Utilities.BlendQuaternionValue(a.rotationBuffer,n._targetRotation,1);else"scaling"===t.animation.targetProperty&&(n._targetScaling=e.Utilities.SampleAnimationVector3(t.animation,h,BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE,!0),null==a.scalingBuffer&&(a.scalingBuffer=new BABYLON.Vector3(1,1,1)),e.Utilities.BlendVector3Value(a.scalingBuffer,n._targetScaling,1))}}}else if(t.target instanceof BABYLON.MorphTarget){var u=t.target;if(null!=u.metadata&&null!=u.metadata.mixer){var c=u.metadata.mixer[i.index];if("influence"===t.animation.targetProperty){var d=e.Utilities.SampleAnimationFloat(t.animation,h,BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE,!0);null==c.influenceBuffer&&(c.influenceBuffer=0),c.influenceBuffer=e.Utilities.BlendFloatValue(c.influenceBuffer,d,1)}}}})),1==n._animationplaying&&(null!=i.animationStateMachine.tcurves&&i.animationStateMachine.tcurves.length>0&&i.animationStateMachine.tcurves.forEach(function(t){if(null!=t.targetProperty&&""!==t.targetProperty){var r=e.Utilities.SampleAnimationFloat(t,i.animationNormal,BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE,!0);n.setFloat(t.targetProperty,r)}}),null!=i.animationStateMachine.events&&i.animationStateMachine.events.length>0)){for(var M=void 0!==i._prevAnimationNormal?i._prevAnimationNormal:i.animationNormal,B=i.animationNormal,C=r.speed<0!=n.speedRatio<0?-1:1,T=function(e,t,n,i){return 1===i?e<=t?e<n&&n<=t:e<n&&n<=1||0<=n&&n<=t:e>=t?t<=n&&n<e:0<=n&&n<e||t<=n&&n<=1},x=0,I=i.animationStateMachine.events;x<I.length;x++)if(T(M,B,(G=I[x]).time,C)){var O=G.function+"_"+G.time;null==i.animationLoopEvents&&(i.animationLoopEvents={}),i.animationLoopEvents[O]||(i.animationLoopEvents[O]=!0,n.onAnimationEventObservable&&n.onAnimationEventObservable.hasObservers()&&n.onAnimationEventObservable.notifyObservers(G))}i._prevAnimationNormal=B}!0===i.animationLoopFrame&&(i.animationTime=0,i.animationNormal=0,i.animationLoopFrame=!1,i.animationLoopEvents=null)}}else{n._animationplaying=!0,n._blendWeights.primary=null,n._blendWeights.secondary=null;var L=[],w=r.blendtree;n.parseTreeBranches(i,w,1,L),l=n.computeWeightedFrameRatio(L),i.animationTime+=t*l*Math.abs(r.speed)*Math.abs(n.speedRatio),i.animationTime>e.AnimationState.TIME&&(i.animationTime=e.AnimationState.TIME),u=i.animationTime>0?BABYLON.Scalar.Clamp(i.animationTime/e.AnimationState.TIME,0,1):0,c=r.speed<0!=n.speedRatio<0,i.animationNormal=c?1-u:u,d=i.animationNormal>=.99?1:i.animationNormal,parseFloat(d.toFixed(3));var N=i.animationNormal;i.animationTime>=e.AnimationState.TIME&&(i.animationFirstRun=!1,i.animationLoopFrame=!0,i.animationLoopCount++);var P=null!=L&&L.length>0&&null!=L[0].track?L[0].track:null;if(null!=P)for(var R=P.targetedAnimations.length,E=0;E<R;E++){var k=P.targetedAnimations[E];if(k.target instanceof BABYLON.TransformNode){var D=k.target;if(0===i.index||null==i.avatarMask||n.filterTargetAvatarMask(i,D)){var F=null!=D.metadata&&null!=D.metadata.toolkit&&null!=D.metadata.toolkit.rootbone&&D.metadata.toolkit.rootbone;if(!0===F&&null==n._rootBoneTransform&&(n._rootBoneTransform=D),null!=D.metadata&&null!=D.metadata.mixer){n._initialtargetblending=!0;var U=D.metadata.mixer[i.index];n.updateBlendableTargets(t,i,w,k,E,U,N,F,D)}}}}if(null!=i.animationStateMachine.tcurves&&i.animationStateMachine.tcurves.length>0&&i.animationStateMachine.tcurves.forEach(function(t){if(null!=t.targetProperty&&""!==t.targetProperty){var r=e.Utilities.SampleAnimationFloat(t,i.animationNormal,BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE,!0);n.setFloat(t.targetProperty,r)}}),null!=i.animationStateMachine.events&&i.animationStateMachine.events.length>0){B=N,M=void 0!==i._prevBlendingNormal?i._prevBlendingNormal:B,C=r.speed<0!=n.speedRatio<0?-1:1,T=function(e,t,n,i){return 1===i?e<=t?e<n&&n<=t:e<n&&n<=1||0<=n&&n<=t:e>=t?t<=n&&n<e:0<=n&&n<e||t<=n&&n<=1};for(var Y=0,V=i.animationStateMachine.events;Y<V.length;Y++){var G;T(M,B,(G=V[Y]).time,C)&&(O=G.function+"_"+G.time,null==i.animationLoopEvents&&(i.animationLoopEvents={}),i.animationLoopEvents[O]||(i.animationLoopEvents[O]=!0,n.onAnimationEventObservable&&n.onAnimationEventObservable.hasObservers()&&n.onAnimationEventObservable.notifyObservers(G)))}i._prevBlendingNormal=B}!0===i.animationLoopFrame&&(i.animationTime=0,i.animationNormal=0,i.animationLoopFrame=!1,i.animationLoopEvents=null)}}}}),this.finalizeAnimationTargets(t))},n.prototype.updateBlendableTargets=function(t,n,i,r,o,a,s,l,u){if(!0!==this.m_vertexAnimationMode&&null!=a&&null!=i.children&&i.children.length>0)for(var c=0;c<i.children.length;c++){var d=i.children[c];if(d.weight>0)if(d.type===e.MotionType.Clip){if(null!=d.track){var h=0,p=0,m=0,f=!1,g=0,v=!0,y=!0,_=!0,S=d.track;null!=S.metadata&&null!=S.metadata.toolkit&&(null!=S.metadata.toolkit.averagespeed&&(p=null!=S.metadata.toolkit.averagespeed.x?S.metadata.toolkit.averagespeed.x:0,m=null!=S.metadata.toolkit.averagespeed.z?S.metadata.toolkit.averagespeed.z:0),null!=S.metadata.toolkit.settings&&(h=null!=S.metadata.toolkit.settings.level?S.metadata.toolkit.settings.level:0,f=null!=S.metadata.toolkit.settings.loopblend&&S.metadata.toolkit.settings.loopblend,g=null!=S.metadata.toolkit.settings.orientationoffsety?S.metadata.toolkit.settings.orientationoffsety:0,v=null==S.metadata.toolkit.settings.loopblendorientation||S.metadata.toolkit.settings.loopblendorientation,y=null==S.metadata.toolkit.settings.loopblendpositiony||S.metadata.toolkit.settings.loopblendpositiony,_=null==S.metadata.toolkit.settings.loopblendpositionxz||S.metadata.toolkit.settings.loopblendpositionxz)),0===n.index&&(this._looptime=!0,this._loopblend=f),g=BABYLON.Tools.ToRadians(g),p=Math.abs(p),m=Math.abs(m),h*=-1;var A=d.track.targetedAnimations[o],b=!0===this._initialtargetblending?1:parseFloat(d.weight.toFixed(2));if(this._initialtargetblending=!1,A.target===r.target&&A.animation.targetProperty===r.animation.targetProperty){var M=s;d.timescale<0&&(M=1-M);var B=d.track.metadata.toolkit.length*M;if("position"===r.animation.targetProperty)this._targetPosition=e.Utilities.SampleAnimationVector3(A.animation,B,BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE,!0),!0===l&&null!=this._rootBoneTransform?(this._positionWeight=!0,this._positionHolder.set(0,0,0),this._rootBoneWeight=!1,this._rootBoneHolder.set(0,0,0),!0===this.applyRootMotion?!0===y&&!0===_?(this._positionWeight=!0,this._positionHolder.set(this._targetPosition.x,this._targetPosition.y+h,this._targetPosition.z)):!1===y&&!1===_?(this._rootBoneWeight=!0,this._rootBoneHolder.set(this._targetPosition.x,this._targetPosition.y+h,this._targetPosition.z)):!0===y&&!1===_?(this._positionWeight=!0,this._positionHolder.set(this.m_zeroVector.x,this._targetPosition.y+h,this.m_zeroVector.z),this._rootBoneWeight=!0,this._rootBoneHolder.set(this._targetPosition.x,this.m_zeroVector.y,this._targetPosition.z)):!0===_&&!1===y&&(this._positionWeight=!0,this._positionHolder.set(this._targetPosition.x,this.m_zeroVector.y,this._targetPosition.z),this._rootBoneWeight=!0,this._rootBoneHolder.set(this.m_zeroVector.x,this._targetPosition.y+h,this.m_zeroVector.z)):(this._positionWeight=!0,this._positionHolder.set(this._targetPosition.x,this._targetPosition.y,this._targetPosition.z)),!0===this._positionWeight&&(null==a.positionBuffer&&(a.positionBuffer=new BABYLON.Vector3(0,0,0)),e.Utilities.BlendVector3Value(a.positionBuffer,this._positionHolder,b)),!0===this._rootBoneWeight&&(null==a.rootPosition&&(a.rootPosition=new BABYLON.Vector3(0,0,0)),e.Utilities.BlendVector3Value(a.rootPosition,this._rootBoneHolder,b))):(null==a.positionBuffer&&(a.positionBuffer=new BABYLON.Vector3(0,0,0)),e.Utilities.BlendVector3Value(a.positionBuffer,this._targetPosition,b));else if("rotationQuaternion"===r.animation.targetProperty)if(this._targetRotation=e.Utilities.SampleAnimationQuaternion(A.animation,B,BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE,!0),!0===l&&null!=this._rootBoneTransform){this._rotationWeight=!1,this._rotationHolder.copyFrom(this.m_rotationIdentity),this._rootQuatWeight=!1,this._rootQuatHolder.copyFrom(this.m_rotationIdentity);var C=this._targetRotation.toEulerAngles(),T=C.y;!0===this.applyRootMotion?!0===v?(this._rotationWeight=!0,BABYLON.Quaternion.FromEulerAnglesToRef(C.x,T+g,C.z,this._rotationHolder)):(this._rotationWeight=!0,BABYLON.Quaternion.FromEulerAnglesToRef(C.x,this.m_zeroVector.y,C.z,this._rotationHolder),this._rootQuatWeight=!0,BABYLON.Quaternion.FromEulerAnglesToRef(this.m_zeroVector.x,T+g,this.m_zeroVector.z,this._rootQuatHolder)):(this._rotationWeight=!0,BABYLON.Quaternion.FromEulerAnglesToRef(C.x,T+g,C.z,this._rotationHolder)),!0===this._rotationWeight&&(null==a.rotationBuffer&&(a.rotationBuffer=new BABYLON.Quaternion(0,0,0,0)),e.Utilities.BlendQuaternionValue(a.rotationBuffer,this._rotationHolder,b)),!0===this._rootQuatWeight&&(null==a.rootRotation&&(a.rootRotation=new BABYLON.Quaternion(0,0,0,0)),e.Utilities.BlendQuaternionValue(a.rootRotation,this._rootQuatHolder,b))}else null==a.rotationBuffer&&(a.rotationBuffer=new BABYLON.Quaternion(0,0,0,0)),e.Utilities.BlendQuaternionValue(a.rotationBuffer,this._targetRotation,b);else"scaling"===r.animation.targetProperty&&(this._targetScaling=e.Utilities.SampleAnimationVector3(A.animation,B,BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE,!0),null==a.scalingBuffer&&(a.scalingBuffer=new BABYLON.Vector3(1,1,1)),e.Utilities.BlendVector3Value(a.scalingBuffer,this._targetScaling,b))}}}else d.type===e.MotionType.Tree&&this.updateBlendableTargets(t,n,d.subtree,r,o,a,s,l,u)}},n.prototype.finalizeAnimationTargets=function(t){var n=this;if(!0!==this.m_vertexAnimationMode&&(this._deltaPosition.set(0,0,0),this._deltaRotation.set(0,0,0,0),this._angularVelocity.set(0,0,0),this._rootMotionSpeed=0,this._rootMotionMatrix.reset(),this._dirtyMotionMatrix=null,this._rootMotionPosition.set(0,0,0),this._rootMotionRotation.set(0,0,0,0),null!=this.m_animationTargets&&this.m_animationTargets.length>0&&this.m_animationTargets.forEach(function(t){var i=t.target;null!=i.metadata&&null!=i.metadata.mixer&&null!=n._machine.layers&&n._machine.layers.length>0&&(n._blenderMatrix.reset(),n._dirtyBlenderMatrix=null,n._machine.layers.forEach(function(t){var r=i.metadata.mixer[t.index];if(null!=r)if(i instanceof BABYLON.TransformNode){if(null==r.positionBuffer&&null==r.rotationBuffer&&null==r.scalingBuffer||(BABYLON.Matrix.ComposeToRef(r.scalingBuffer||i.scaling,r.rotationBuffer||i.rotationQuaternion,r.positionBuffer||i.position,n._updateMatrix),r.blendingSpeed>0&&(r.blendingFactor<=1&&null==r.originalMatrix&&(r.originalMatrix=BABYLON.Matrix.Compose(i.scaling,i.rotationQuaternion,i.position)),r.blendingFactor<=1&&null!=r.originalMatrix&&(e.Utilities.FastMatrixSlerp(r.originalMatrix,n._updateMatrix,r.blendingFactor,n._updateMatrix),r.blendingFactor+=r.blendingSpeed)),e.Utilities.FastMatrixSlerp(n._blenderMatrix,n._updateMatrix,t.defaultWeight,n._blenderMatrix),n._dirtyBlenderMatrix=!0,r.positionBuffer=null,r.rotationBuffer=null,r.scalingBuffer=null),n._emptyPosition.set(0,0,0),n._emptyRotation.set(0,0,0,0),n._emptyScaling.set(1,1,1),null!=r.rootPosition||null!=r.rootRotation){var o=n._emptyPosition,a=r.rootRotation?r.rootRotation.clone():n._emptyRotation,s=r.rootPosition?r.rootPosition.clone():n._emptyPosition;BABYLON.Matrix.ComposeToRef(o,a,s,n._updateMatrix),e.Utilities.FastMatrixSlerp(n._rootMotionMatrix,n._updateMatrix,t.defaultWeight,n._rootMotionMatrix),n._dirtyMotionMatrix=!0,r.rootPosition=null,r.rootRotation=null}}else i instanceof BABYLON.MorphTarget&&null!=r.influenceBuffer&&(i.influence=BABYLON.Scalar.Lerp(i.influence,r.influenceBuffer,t.defaultWeight),r.influenceBuffer=null)}),null!=n._dirtyBlenderMatrix&&n._blenderMatrix.decompose(i.scaling,i.rotationQuaternion,i.position))}),!0===this.applyRootMotion&&null!=this._dirtyMotionMatrix)){if(this._rootMotionMatrix.decompose(this._rootMotionScaling,this._rootMotionRotation,this._rootMotionPosition),!0===this.isFirstFrame())this._deltaPosition.copyFrom(this._rootMotionPosition),this._deltaRotation.copyFrom(this._rootMotionRotation);else if(!0===this.isLastFrame()){if(this._rootMotionPosition.subtractToRef(this._lastMotionPosition,this._deltaPosition),e.Utilities.QuaternionDiffToRef(this._rootMotionRotation,this._lastMotionRotation,this._deltaRotation),!0===this._looptime&&!0===this._loopblend){var i=this._loopMotionSpeed+this._lastMotionSpeed;0!==i&&(i/=2),this._deltaPosition.normalize(),this._deltaPosition.scaleInPlace(i*t);var r=this._loopRotateSpeed+this._lastRotateSpeed;0!==r&&(r/=2),this._deltaRotation.toEulerAnglesToRef(this._angularVelocity),BABYLON.Quaternion.FromEulerAnglesToRef(this._angularVelocity.x,r,this._angularVelocity.z,this._deltaRotation)}}else this._rootMotionPosition.subtractToRef(this._lastMotionPosition,this._deltaPosition),e.Utilities.QuaternionDiffToRef(this._rootMotionRotation,this._lastMotionRotation,this._deltaRotation);var o=this._deltaPosition.length();this._rootMotionSpeed=o>0?o/t:o,this._deltaRotation.toEulerAnglesToRef(this._angularVelocity),this._lastMotionPosition.copyFrom(this._rootMotionPosition),this._lastMotionRotation.copyFrom(this._rootMotionRotation),this._lastMotionSpeed=this._rootMotionSpeed,this._lastRotateSpeed=this._angularVelocity.y,0===this._frametime&&(this._loopMotionSpeed=this._rootMotionSpeed,this._loopRotateSpeed=this._angularVelocity.y)}},n.prototype.checkStateMachine=function(e,t){var n=this;if(this._checkers.result=null,this._checkers.offest=0,this._checkers.blending=0,this._checkers.duration=0,this._checkers.triggered=[],null!=e.animationStateMachine&&(e.animationStateMachine.time+=t,this.checkStateTransitions(e,e.animationStateMachine.transitions),null==this._checkers.result&&null!=this._machine.transitions&&this.checkStateTransitions(e,this._machine.transitions)),null!=this._checkers.triggered&&this._checkers.triggered.length>0&&(this._checkers.triggered.forEach(function(e){n.resetTrigger(e)}),this._checkers.triggered=null),null!=this._checkers.result){this.onAnimationTransitionObservable&&this.onAnimationTransitionObservable.hasObservers()&&this.onAnimationTransitionObservable.notifyObservers(this.transform);var i=!0===this.m_vertexAnimationMode?this._checkers.duration:this._checkers.blending;this.playCurrentAnimationState(e,this._checkers.result,i,this._checkers.offest)}},n.prototype.checkStateTransitions=function(t,n){var i=this,r=t.animationStateMachine.rate,o=t.animationStateMachine.length;if(null!=n&&n.length>0){var a=0,s=-1;for(a=0;a<n.length;a++)if(!0===n[a].solo&&!1===n[a].mute){s=a;break}var l=function(){var l=n[a];if(l.layerIndex!==t.index)return"continue";if(!0===l.mute)return"continue";if(s>=0&&s!==a)return"continue";var c=!1,d=0,h=!0;if(l.exitTime>0&&(d=o*l.exitTime/u.speedRatio,h=!0!==l.hasExitTime||t.animationStateMachine.time>=d),!0===l.hasExitTime&&l.intSource==e.InterruptionSource.None&&!1===h)return"continue";if(null!=l.conditions&&l.conditions.length>0){var p=0,m=l.conditions.length;l.conditions.forEach(function(t){var n=i._parameters.get(t.parameter);if(null!=n)if(n==e.AnimatorParameterType.Float||n==e.AnimatorParameterType.Int){var r=parseFloat(i.getFloat(t.parameter).toFixed(2));(t.mode===e.ConditionMode.Greater&&r>t.threshold||t.mode===e.ConditionMode.Less&&r<t.threshold||t.mode===e.ConditionMode.Equals&&r===t.threshold||t.mode===e.ConditionMode.NotEqual&&r!==t.threshold)&&p++}else if(n==e.AnimatorParameterType.Bool){var o=i.getBool(t.parameter);(t.mode===e.ConditionMode.If&&!0===o||t.mode===e.ConditionMode.IfNot&&!1===o)&&p++}else if(n==e.AnimatorParameterType.Trigger&&!0===i.getTrigger(t.parameter)){p++;for(var a=-1,s=0;s<i._checkers.triggered.length;s++)if(i._checkers.triggered[s]===t.parameter){a=s;break}a<0&&i._checkers.triggered.push(t.parameter)}}),c=!0===l.hasExitTime?!0===h&&p===m:p===m}else c=!0===l.hasExitTime&&!0===h;if(!0===c){!0===l.hasExitTime&&!0===h&&u.onAnimationEndObservable&&u.onAnimationEndObservable.hasObservers()&&u.onAnimationEndObservable.notifyObservers(t.index);var f=r>0?r:e.AnimationState.FPS,g=!1===l.isExit?l.destination:e.AnimationState.EXIT,v=!0===l.fixedDuration?l.duration:BABYLON.Scalar.Denormalize(l.duration,0,o),y=e.Utilities.ComputeBlendingSpeed(f,v),_=l.offset;return u._checkers.result=g,u._checkers.offest=_,u._checkers.blending=y,u._checkers.duration=v,"break"}},u=this;for(a=0;a<n.length&&"break"!==l();a++);}},n.prototype.playCurrentAnimationState=function(t,n,i,r){if(void 0===r&&(r=0),null!=t&&null!=n&&""!==n&&n!==e.AnimationState.EXIT&&(null==t.animationStateMachine||t.animationStateMachine.name!==n)){null!=this.m_animationTargets&&this.m_animationTargets.length>0&&this.m_animationTargets.forEach(function(e){var n=e.target;if(null!=n.metadata&&null!=n.metadata.mixer){var r=n.metadata.mixer[t.index];null!=r&&(r.originalMatrix=null,r.blendingFactor=0,r.blendingSpeed=i)}});var o=this.getMachineState(n);if(null!=o&&o.layerIndex===t.index&&(o.time=0,o.played=0,o.interrupted=!1,t.animationTime=BABYLON.Scalar.Clamp(r),t.animationNormal=0,t.animationFirstRun=!0,t.animationEndFrame=!1,t.animationLoopFrame=!1,t.animationLoopCount=0,t.animationLoopEvents=null,t.animationStateMachine=o,this._deltaPosition.set(0,0,0),this._deltaRotation.set(0,0,0,0),this._angularVelocity.set(0,0,0),this._rootMotionSpeed=0,this._rootMotionMatrix.reset(),this._dirtyMotionMatrix=null,this._rootMotionPosition.set(0,0,0),this._rootMotionRotation.set(0,0,0,0),this._lastMotionPosition.set(0,0,0),this._lastMotionRotation.set(0,0,0,0),!0===this.m_vertexAnimationMode&&null!=this.m_vertexAnimationController)){var a=this.m_vertexAnimationController.currentClip;i>0&&null!=a?(t.vatTransitionActive=!0,t.vatTransitionElapsed=0,t.vatTransitionDuration=i,t.vatSourceClipName=a.name,t.vatSourceTimeSec=this.m_vertexAnimationController.currentTime):(t.vatTransitionActive=!1,t.vatTransitionElapsed=0,t.vatTransitionDuration=0,t.vatSourceClipName=null,t.vatSourceTimeSec=0)}}},n.prototype.stopCurrentAnimationState=function(e){null!=e&&(null!=this.m_animationTargets&&this.m_animationTargets.length>0&&this.m_animationTargets.forEach(function(t){var n=t.target;if(null!=n.metadata&&null!=n.metadata.mixer){var i=n.metadata.mixer[e.index];null!=i&&(i.originalMatrix=null,i.blendingFactor=0,i.blendingSpeed=0)}}),e.animationTime=0,e.animationNormal=0,e.animationFirstRun=!0,e.animationEndFrame=!1,e.animationLoopFrame=!1,e.animationLoopCount=0,e.animationLoopEvents=null,e.animationStateMachine=null,this._deltaPosition.set(0,0,0),this._deltaRotation.set(0,0,0,0),this._angularVelocity.set(0,0,0),this._rootMotionSpeed=0,this._rootMotionMatrix.reset(),this._dirtyMotionMatrix=null,this._rootMotionPosition.set(0,0,0),this._rootMotionRotation.set(0,0,0,0),this._lastMotionPosition.set(0,0,0),this._lastMotionRotation.set(0,0,0,0),!0===this.m_vertexAnimationMode&&null!=this.m_vertexAnimationController&&(this.m_vertexAnimationController.stop(),e.vatTransitionActive=!1,e.vatTransitionElapsed=0,e.vatTransitionDuration=0,e.vatSourceClipName=null,e.vatSourceTimeSec=0))},n.prototype.checkAvatarTransformPath=function(e,t){var n=!1;if(null!=e.animationMaskMap){var i=e.animationMaskMap.get(t);null!=i&&i>=0&&(n=!0)}return n},n.prototype.filterTargetAvatarMask=function(e,t){var n=!1;if(null!=t.metadata&&null!=t.metadata.toolkit&&null!=t.metadata.toolkit.bone&&""!==t.metadata.toolkit.bone){var i=t.metadata.toolkit.bone;n=this.checkAvatarTransformPath(e,i)}return n},n.prototype.sortWeightedBlendingList=function(e){null!=e&&e.length>0&&e.sort(function(e,t){return e.weight<t.weight?1:e.weight>t.weight?-1:0})},n.prototype.computeWeightedFrameRatio=function(e){var t=1;if(null!=e&&e.length>0)if(this.sortWeightedBlendingList(e),this._blendWeights.primary=e[0],this._blendWeights.primary.weight<1&&e.length>1&&(this._blendWeights.secondary=e[1]),null!=this._blendWeights.primary&&null!=this._blendWeights.secondary){var n=BABYLON.Scalar.Clamp(this._blendWeights.primary.weight);t=BABYLON.Scalar.Lerp(this._blendWeights.secondary.ratio,this._blendWeights.primary.ratio,n)}else null!=this._blendWeights.primary&&null==this._blendWeights.secondary&&(t=this._blendWeights.primary.ratio);return t},n.prototype.getFirstMotion=function(t){var n;if(!(null===(n=null==t?void 0:t.children)||void 0===n?void 0:n.length))return null;for(var i=0,r=t.children;i<r.length;i++){var o=r[i];if(o.type===e.MotionType.Clip)return o.motion;if(o.type===e.MotionType.Tree){var a=this.getFirstMotion(o.subtree);if(null!=a)return a}}return null},n.prototype.getLastMotion=function(t){var n;if(!(null===(n=null==t?void 0:t.children)||void 0===n?void 0:n.length))return null;for(var i=t.children.length-1;i>=0;i--){var r=t.children[i];if(r.type===e.MotionType.Clip)return r.motion;if(r.type===e.MotionType.Tree){var o=this.getLastMotion(r.subtree);if(null!=o)return o}}return null},n.prototype.setupTreeBranches=function(t){var n=this;null!=t&&null!=t.children&&t.children.length>0&&t.children.forEach(function(t){if(t.type===e.MotionType.Tree)n.setupTreeBranches(t.subtree);else if(t.type===e.MotionType.Clip&&null!=t.motion&&""!==t.motion&&(t.weight=0,t.ratio=0,t.track=n.getAnimationGroup(t.motion),null!=t.track)){var i=t.track.metadata.toolkit.length;t.ratio=e.AnimationState.TIME/i}})},n.prototype.parseTreeBranches=function(t,n,i,r){if(null!=n)switch(n.valueParameterX=null!=n.blendParameterX?parseFloat(this.getFloat(n.blendParameterX).toFixed(2)):0,n.valueParameterY=null!=n.blendParameterY?parseFloat(this.getFloat(n.blendParameterY).toFixed(2)):0,n.blendType){case e.BlendTreeType.Simple1D:this.parse1DSimpleTreeBranches(t,n,i,r);break;case e.BlendTreeType.SimpleDirectional2D:this.parse2DSimpleDirectionalTreeBranches(t,n,i,r);break;case e.BlendTreeType.FreeformDirectional2D:this.parse2DFreeformDirectionalTreeBranches(t,n,i,r);break;case e.BlendTreeType.FreeformCartesian2D:this.parse2DFreeformCartesianTreeBranches(t,n,i,r)}},n.prototype.parse1DSimpleTreeBranches=function(t,n,i,r){var o=this;if(null!=n&&null!=n.children&&n.children.length>0){var a=[];n.children.forEach(function(e){e.weight=0;var t={source:e,motion:e.motion,posX:e.threshold,posY:e.threshold,weight:e.weight};a.push(t)}),e.BlendTreeSystem.Calculate1DSimpleBlendTree(n.valueParameterX,a),a.forEach(function(e){null!=e.source&&(e.source.weight=e.weight)}),n.children.forEach(function(n){n.weight*=i,n.type===e.MotionType.Clip&&n.weight>0&&r.push(n),n.type===e.MotionType.Tree&&o.parseTreeBranches(t,n.subtree,n.weight,r)})}},n.prototype.parse2DSimpleDirectionalTreeBranches=function(t,n,i,r){var o=this;if(null!=n&&null!=n.children&&n.children.length>0){var a=[];n.children.forEach(function(e){e.weight=0;var t={source:e,motion:e.motion,posX:e.positionX,posY:e.positionY,weight:e.weight};a.push(t)}),e.BlendTreeSystem.Calculate2DFreeformDirectional(n.valueParameterX,n.valueParameterY,a),a.forEach(function(e){null!=e.source&&(e.source.weight=e.weight)}),n.children.forEach(function(n){n.weight*=i,n.type===e.MotionType.Clip&&n.weight>0&&r.push(n),n.type===e.MotionType.Tree&&o.parseTreeBranches(t,n.subtree,n.weight,r)})}},n.prototype.parse2DFreeformDirectionalTreeBranches=function(t,n,i,r){var o=this;if(null!=n&&null!=n.children&&n.children.length>0){var a=[];n.children.forEach(function(e){e.weight=0;var t={source:e,motion:e.motion,posX:e.positionX,posY:e.positionY,weight:e.weight};a.push(t)}),e.BlendTreeSystem.Calculate2DFreeformDirectional(n.valueParameterX,n.valueParameterY,a),a.forEach(function(e){null!=e.source&&(e.source.weight=e.weight)}),n.children.forEach(function(n){n.weight*=i,n.type===e.MotionType.Clip&&n.weight>0&&r.push(n),n.type===e.MotionType.Tree&&o.parseTreeBranches(t,n.subtree,n.weight,r)})}},n.prototype.parse2DFreeformCartesianTreeBranches=function(t,n,i,r){var o=this;if(null!=n&&null!=n.children&&n.children.length>0){var a=[];n.children.forEach(function(e){e.weight=0;var t={source:e,motion:e.motion,posX:e.positionX,posY:e.positionY,weight:e.weight};a.push(t)}),e.BlendTreeSystem.Calculate2DFreeformCartesian(n.valueParameterX,n.valueParameterY,a),a.forEach(function(e){null!=e.source&&(e.source.weight=e.weight)}),n.children.forEach(function(n){n.weight*=i,n.type===e.MotionType.Clip&&n.weight>0&&r.push(n),n.type===e.MotionType.Tree&&o.parseTreeBranches(t,n.subtree,n.weight,r)})}},n.FPS=30,n.EXIT="[EXIT]",n.TIME=1,n}(e.ScriptComponent);e.AnimationState=t;e.BlendTreeValue=function(e){this.source=e.source,this.motion=e.motion,this.posX=e.posX||0,this.posY=e.posY||0,this.weight=e.weight||0};var n=function(){function e(){}return e.ClampValue=function(e,t,n){return e<=t?t:e>=n?n:e},e.GetSignedAngle=function(e,t){return Math.atan2(e.x*t.y-e.y*t.x,e.x*t.x+e.y*t.y)},e.GetLinearInterpolation=function(e,t,n,i,r){return t+(i-t)/(n-e)*(r-e)},e.GetRightNeighbourIndex=function(e,t){t.sort(function(e,t){return e.posX-t.posX});for(var n=0;n<t.length;++n)if(t[n].posX>e)return n;return-1},e}();e.BlendTreeUtils=n;var i=function(){function t(){}return t.Calculate1DSimpleBlendTree=function(t,n){var i=n[0],r=n[n.length-1];if(t<=i.posX)i.weight=1;else if(t>=r.posX)r.weight=1;else{var o=e.BlendTreeUtils.GetRightNeighbourIndex(t,n),a=n[o-1],s=n[o],l=e.BlendTreeUtils.GetLinearInterpolation(a.posX,1,s.posX,0,t);a.weight=l,s.weight=1-a.weight}},t.Calculate2DFreeformDirectional=function(t,n,i){e.BlendTreeSystem.TempVector2_IP.set(t,n),e.BlendTreeSystem.TempVector2_POSI.set(0,0),e.BlendTreeSystem.TempVector2_POSJ.set(0,0),e.BlendTreeSystem.TempVector2_POSIP.set(0,0),e.BlendTreeSystem.TempVector2_POSIJ.set(0,0);for(var r=0,o=e.BlendTreeSystem.TempVector2_IP.length(),a=0;a<i.length;++a){var s=i[a];e.BlendTreeSystem.TempVector2_POSI.set(s.posX,s.posY);for(var l=e.BlendTreeSystem.TempVector2_POSI.length(),u=o-l,c=e.BlendTreeUtils.GetSignedAngle(e.BlendTreeSystem.TempVector2_POSI,e.BlendTreeSystem.TempVector2_IP),d=1,h=0;h<i.length;++h)if(h!==a){e.BlendTreeSystem.TempVector2_POSJ.set(i[h].posX,i[h].posY);var p=e.BlendTreeSystem.TempVector2_POSJ.length(),m=(l+p)/2,f=u/m,g=(p-l)/m,v=e.BlendTreeUtils.GetSignedAngle(e.BlendTreeSystem.TempVector2_POSI,e.BlendTreeSystem.TempVector2_POSJ);e.BlendTreeSystem.TempVector2_POSIP.set(f,2*c),e.BlendTreeSystem.TempVector2_POSIJ.set(g,2*v);var y=e.BlendTreeSystem.TempVector2_POSIJ.lengthSquared(),_=BABYLON.Vector2.Dot(e.BlendTreeSystem.TempVector2_POSIP,e.BlendTreeSystem.TempVector2_POSIJ)/y;_=1-_,_=e.BlendTreeUtils.ClampValue(_,0,1),d=Math.min(_,d)}s.weight=d,r+=d}for(var S=0,A=i;S<A.length;S++)(s=A[S]).weight/=r},t.Calculate2DFreeformCartesian=function(t,n,i){e.BlendTreeSystem.TempVector2_IP.set(t,n),e.BlendTreeSystem.TempVector2_POSI.set(0,0),e.BlendTreeSystem.TempVector2_POSJ.set(0,0),e.BlendTreeSystem.TempVector2_POSIP.set(0,0),e.BlendTreeSystem.TempVector2_POSIJ.set(0,0);for(var r=0,o=0;o<i.length;++o){var a=i[o];e.BlendTreeSystem.TempVector2_POSI.set(a.posX,a.posY),e.BlendTreeSystem.TempVector2_IP.subtractToRef(e.BlendTreeSystem.TempVector2_POSI,e.BlendTreeSystem.TempVector2_POSIP);for(var s=1,l=0;l<i.length;++l)if(l!==o){e.BlendTreeSystem.TempVector2_POSJ.set(i[l].posX,i[l].posY),e.BlendTreeSystem.TempVector2_POSJ.subtractToRef(e.BlendTreeSystem.TempVector2_POSI,e.BlendTreeSystem.TempVector2_POSIJ);var u=e.BlendTreeSystem.TempVector2_POSIJ.lengthSquared(),c=BABYLON.Vector2.Dot(e.BlendTreeSystem.TempVector2_POSIP,e.BlendTreeSystem.TempVector2_POSIJ)/u;c=1-c,c=e.BlendTreeUtils.ClampValue(c,0,1),s=Math.min(s,c)}a.weight=s,r+=s}for(var d=0,h=i;d<h.length;d++)(a=h[d]).weight/=r},t.TempVector2_IP=new BABYLON.Vector2(0,0),t.TempVector2_POSI=new BABYLON.Vector2(0,0),t.TempVector2_POSJ=new BABYLON.Vector2(0,0),t.TempVector2_POSIP=new BABYLON.Vector2(0,0),t.TempVector2_POSIJ=new BABYLON.Vector2(0,0),t}();e.BlendTreeSystem=i;e.MachineState=function(){};e.TransitionCheck=function(){};e.AnimationMixer=function(){};var o,a,s,l,u,c;e.BlendingWeights=function(){},(c=e.MotionType||(e.MotionType={}))[c.Clip=0]="Clip",c[c.Tree=1]="Tree",(u=e.ConditionMode||(e.ConditionMode={}))[u.If=1]="If",u[u.IfNot=2]="IfNot",u[u.Greater=3]="Greater",u[u.Less=4]="Less",u[u.Equals=6]="Equals",u[u.NotEqual=7]="NotEqual",(l=e.InterruptionSource||(e.InterruptionSource={}))[l.None=0]="None",l[l.Source=1]="Source",l[l.Destination=2]="Destination",l[l.SourceThenDestination=3]="SourceThenDestination",l[l.DestinationThenSource=4]="DestinationThenSource",(s=e.BlendTreeType||(e.BlendTreeType={}))[s.Simple1D=0]="Simple1D",s[s.SimpleDirectional2D=1]="SimpleDirectional2D",s[s.FreeformDirectional2D=2]="FreeformDirectional2D",s[s.FreeformCartesian2D=3]="FreeformCartesian2D",s[s.Direct=4]="Direct",s[s.Clip=5]="Clip",(a=e.BlendTreePosition||(e.BlendTreePosition={}))[a.Lower=0]="Lower",a[a.Upper=1]="Upper",(o=e.AnimatorParameterType||(e.AnimatorParameterType={}))[o.Float=1]="Float",o[o.Int=3]="Int",o[o.Bool=4]="Bool",o[o.Trigger=9]="Trigger",e.SceneManager.RegisterClass("TOOLKIT.AnimationState",t)}(i||(i={})),function(e){var t=function(t){function n(e,n,i,r){void 0===i&&(i={}),void 0===r&&(r="TOOLKIT.AudioSource");var o=t.call(this,e,n,i,r)||this;return o._audio=null,o._name=null,o._loop=!1,o._mute=!1,o._pitch=1,o._volume=1,o._preload=!1,o._playonawake=!0,o._spatialblend=0,o._preloaderUrl=null,o._lastmutedvolume=null,o._priority=128,o._panstereo=0,o._mindistance=1,o._maxdistance=200,o._reverbzonemix=1,o._bypasseffects=!1,o._bypassreverbzones=!1,o._bypasslistenereffects=!1,o._initializedReadyInstance=!1,o._isAudioPlaying=!1,o._isAudioPaused=!1,o._isAudioSpatial=!1,o.onReadyObservable=new BABYLON.Observable,o}return r(n,t),n.prototype.getSoundClip=function(){return this._audio},n.prototype.awake=function(){this.awakeAudioSource()},n.prototype.start=function(){this.startAudioSource()},n.prototype.after=function(){this.updateAudioSource()},n.prototype.destroy=function(){this.destroyAudioSource()},n.prototype.awakeAudioSource=function(){return a(this,void 0,void 0,function(){var t,n,i;return s(this,function(r){switch(r.label){case 0:return this._name=this.getProperty("name",this._name),this._loop=this.getProperty("loop",this._loop),this._mute=this.getProperty("mute",this._mute),this._pitch=this.getProperty("pitch",this._pitch),this._volume=this.getProperty("volume",this._volume),this._preload=this.getProperty("preload",this._preload),this._priority=this.getProperty("priority",this._priority),this._panstereo=this.getProperty("panstereo",this._panstereo),this._playonawake=this.getProperty("playonawake",this._playonawake),this._mindistance=this.getProperty("mindistance",this._mindistance),this._maxdistance=this.getProperty("maxdistance",this._maxdistance),this._spatialblend=this.getProperty("spatialblend",this._spatialblend),this._reverbzonemix=this.getProperty("reverbzonemix",this._reverbzonemix),this._bypasseffects=this.getProperty("bypasseffects",this._bypasseffects),this._bypassreverbzones=this.getProperty("bypassreverbzones",this._bypassreverbzones),this._bypasslistenereffects=this.getProperty("bypasslistenereffects",this._bypasslistenereffects),null!=this._name&&""!==this._name||(this._name="Unknown"),null==(t=this.getProperty("file"))||""===t?[3,4]:(n=e.SceneManager.GetRootUrl(this.scene),null==(i=n+t)||""===i?[3,4]:!0!==this._preload?[3,1]:(this._preloaderUrl=i,[3,4]));case 1:return this.isLegacy()?(this.setLegacyDataSource(i),[3,4]):[3,2];case 2:return[4,this.setAudioDataSource(i)];case 3:r.sent(),r.label=4;case 4:return[2]}})})},n.prototype.startAudioSource=function(){this._volume>=e.AudioSource.MAX_VOLUME&&(this._volume=e.AudioSource.DEFAULT_LEVEL)},n.prototype.updateAudioSource=function(){return a(this,void 0,void 0,function(){return s(this,function(e){return!0===this._isAudioSpatial&&(this._audio,BABYLON.StaticSound),[2]})})},n.prototype.destroyAudioSource=function(){this.onReadyObservable.clear(),this.onReadyObservable=null,null!=this._audio&&(this._audio.dispose(),this._audio=null)},n.prototype.isLegacy=function(){return!!BABYLON.Engine.audioEngine},n.prototype.isReady=function(){return null!=this._audio},n.prototype.isPlaying=function(){return this._isAudioPlaying},n.prototype.isPaused=function(){return this._isAudioPaused},n.prototype.play=function(t,n,i){return a(this,void 0,void 0,function(){return s(this,function(r){switch(r.label){case 0:return[4,e.AudioSource.UnlockAudioEngine()];case 1:return r.sent(),this.internalPlay(t,n,i),[2,!0]}})})},n.prototype.internalPlay=function(e,t,n){var i=this;null!=this._audio&&(!0===this._initializedReadyInstance?(this._audio instanceof BABYLON.StaticSound?this._audio.play({waitTime:e,startOffset:t,duration:n}):this._audio instanceof BABYLON.Sound&&this._audio.play(e,t,n),this._isAudioPlaying=!0,this._isAudioPaused=!1):this.onReadyObservable.addOnce(function(){i._audio instanceof BABYLON.StaticSound?i._audio.play({waitTime:e,startOffset:t,duration:n}):i._audio instanceof BABYLON.Sound&&i._audio.play(e,t,n),i._isAudioPlaying=!0,i._isAudioPaused=!1}))},n.prototype.pause=function(){var e=!1;return null!=this._audio&&(this._audio.pause(),this._isAudioPlaying=!1,this._isAudioPaused=!0,e=!0),e},n.prototype.stop=function(e){var t=!1;return null!=this._audio&&(this._audio instanceof BABYLON.StaticSound?this._audio.stop({waitTime:e}):this._audio instanceof BABYLON.Sound&&this._audio.stop(e),this._isAudioPlaying=!1,this._isAudioPaused=!1,t=!0),t},n.prototype.mute=function(t){var n=this,i=!1;return null!=this._audio&&(this._audio instanceof BABYLON.StaticSound?null!=t&&t>0?e.WindowManager.SetTimeout(t/1e3,function(){n._lastmutedvolume=n._audio.volume,n._audio.volume=0}):(this._lastmutedvolume=this._audio.volume,this._audio.volume=0):this._audio instanceof BABYLON.Sound&&(this._lastmutedvolume=this._audio.getVolume(),this._audio.setVolume(0,t)),i=!0),i},n.prototype.unmute=function(t){var n=this,i=!1;return null!=this._audio&&(this._audio instanceof BABYLON.StaticSound?null!=t&&t>0?e.WindowManager.SetTimeout(t/1e3,function(){null!=n._lastmutedvolume&&(n._audio.volume=n._lastmutedvolume,n._lastmutedvolume=null)}):null!=this._lastmutedvolume&&(this._audio.volume=this._lastmutedvolume,this._lastmutedvolume=null):this._audio instanceof BABYLON.Sound&&null!=this._lastmutedvolume&&(this._audio.setVolume(this._lastmutedvolume,t),this._lastmutedvolume=null),i=!0),i},n.prototype.getPitch=function(){return null==this._audio?0:this._audio instanceof BABYLON.StaticSound?this._audio.playbackRate:this._audio instanceof BABYLON.Sound?this._audio.getPlaybackRate():void 0},n.prototype.setPitch=function(e){null!=this._audio&&(this._audio instanceof BABYLON.StaticSound?this._audio.playbackRate=e:this._audio instanceof BABYLON.Sound&&this._audio.setPlaybackRate(e))},n.prototype.getVolume=function(){var e=0;return null!=this._audio?this._audio instanceof BABYLON.StaticSound?e=this._audio.volume:this._audio instanceof BABYLON.Sound&&(e=this._audio.getVolume()):e=this._volume,e},n.prototype.setVolume=function(t,n){var i=this;return this._volume=t,null!=this._audio&&(this._audio instanceof BABYLON.StaticSound?null!=n&&n>0?e.WindowManager.SetTimeout(n/1e3,function(){i._audio.volume=i._volume}):this._audio.volume=this._volume:this._audio instanceof BABYLON.Sound&&this._audio.setVolume(this._volume,n)),!0},n.prototype.setPosition=function(e){this._audio instanceof BABYLON.StaticSound?null!=this._audio.spatial&&(this._audio.spatial.position=e):this._audio instanceof BABYLON.Sound&&this._audio.setPosition(e)},n.prototype.getPlaybackSpeed=function(){return null==this._audio?0:this._audio instanceof BABYLON.StaticSound?this._audio.playbackRate:this._audio instanceof BABYLON.Sound?this._audio.getPlaybackRate():void 0},n.prototype.setPlaybackSpeed=function(e){null!=this._audio&&(this._audio instanceof BABYLON.StaticSound?this._audio.playbackRate=e:this._audio instanceof BABYLON.Sound&&this._audio.setPlaybackRate(e))},n.prototype.setRolloffMode=function(e){null!=this._audio&&(this._audio instanceof BABYLON.StaticSound&&("linear"===e||"inverse"===e||"exponential"===e)?null!=this._audio.spatial&&(this._audio.spatial.distanceModel=e):(this._audio,BABYLON.Sound))},n.prototype.setMinDistance=function(e){null!=this._audio&&(this._audio instanceof BABYLON.StaticSound?null!=this._audio.spatial&&(this._audio.spatial.minDistance=Math.max(1,e)):this._audio instanceof BABYLON.Sound&&(this._audio.refDistance=e))},n.prototype.setMaxDistance=function(e){null!=this._audio&&(this._audio instanceof BABYLON.StaticSound?null!=this._audio.spatial&&(this._audio.spatial.maxDistance=e):this._audio instanceof BABYLON.Sound&&(this._audio.maxDistance=e))},n.prototype.setSpatialBlend=function(e){null!=this._audio&&(this._audio instanceof BABYLON.StaticSound||(this._audio,BABYLON.Sound))},n.prototype.hasSpatialSound=function(){var e=!1;return null!=this._audio&&(this._audio instanceof BABYLON.StaticSound?e=null!=this._audio.spatial:this._audio instanceof BABYLON.Sound&&(e=this._audio.spatialSound)),e},n.prototype.getSpatialSound=function(){var e=null;return null!=this._audio&&this._audio instanceof BABYLON.StaticSound&&(e=this._audio.spatial),e},n.prototype.attachToSpatialNode=function(e){null!=this._audio&&(this._audio instanceof BABYLON.StaticSound?null!=this._audio.spatial&&this._audio.spatial.attach(e,!0,BABYLON.SpatialAudioAttachmentType.PositionAndRotation):this._audio instanceof BABYLON.Sound&&this._audio.attachToMesh(e),this._isAudioSpatial=!0)},n.prototype.getCurrentTrackTime=function(){var e=0;return null!=this._audio&&(e=this._audio.currentTime),e},n.prototype.setAudioDataSource=function(t){return a(this,void 0,void 0,function(){var n,i,r;return s(this,function(o){switch(o.label){case 0:return null!=this._audio&&(this._audio.dispose(),this._audio=null),n=this._spatialblend>=.1,this._initializedReadyInstance=!1,this._lastmutedvolume=this._volume,i={loop:this._loop,volume:!0===this._mute?0:this._volume,autoplay:!1,autoUpdate:!0,playbackRate:this._pitch,spatialEnabled:n,spatialAutoUpdate:!0,spatialPosition:new BABYLON.Vector3(0,0,0),spatialRotationQuaternion:new BABYLON.Quaternion(0,0,0,1),spatialPanningModel:"equalpower",spatialDistanceModel:"linear",spatialMinDistance:this._mindistance,spatialMaxDistance:this._maxdistance,spatialRolloffFactor:e.AudioSource.DEFAULT_ROLLOFF,spatialConeInnerAngle:360,spatialConeOuterAngle:360},r=this,[4,e.AudioSource.CreateStaticSound(this._name,t,i)];case 1:return r._audio=o.sent(),null!=this._audio&&(this._initializedReadyInstance=!0,!0===n&&null!=this._audio.spatial&&(this._audio.spatial.position=new BABYLON.Vector3(0,0,0),this._audio.spatial.rotationQuaternion=new BABYLON.Quaternion(0,0,0,1),this._audio.spatial.panningModel="equalpower",this._audio.spatial.distanceModel="linear",this._audio.spatial.minDistance=this._mindistance,this._audio.spatial.maxDistance=this._maxdistance,this._audio.spatial.rolloffFactor=e.AudioSource.DEFAULT_ROLLOFF,this._audio.spatial.coneInnerAngle=360,this._audio.spatial.coneOuterAngle=360,this._audio.spatial.attach(this.transform,!0,BABYLON.SpatialAudioAttachmentType.PositionAndRotation),this._isAudioSpatial=!0),this.onReadyObservable&&this.onReadyObservable.hasObservers()&&this.onReadyObservable.notifyObservers(this._audio),!0===this._playonawake&&this.play()),[2]}})})},n.prototype.setLegacyDataSource=function(t){var n=this;null!=this._audio&&(this._audio.dispose(),this._audio=null);var i=this._spatialblend>=.1,r=null!=this.transform.metadata&&null!=this.transform.metadata.vtt&&!0===this.transform.metadata.vtt;this._initializedReadyInstance=!1,this._audio=new BABYLON.Sound(this._name,t,this.scene,function(){n._lastmutedvolume=n._volume,n._audio.setVolume(!0===n._mute?0:n._volume),n._audio.setPlaybackRate(n._pitch),n._audio.setPosition(n.transform.absolutePosition.clone()),n._initializedReadyInstance=!0,!0===i&&n._audio instanceof BABYLON.Sound&&(n._isAudioSpatial=!0,n._audio.attachToMesh(n.transform)),n.onReadyObservable&&n.onReadyObservable.hasObservers()&&n.onReadyObservable.notifyObservers(n._audio),!0===n._playonawake&&n.play()},{loop:this._loop,autoplay:!1,refDistance:this._mindistance,maxDistance:this._maxdistance,rolloffFactor:e.AudioSource.DEFAULT_ROLLOFF,spatialSound:i,distanceModel:"linear",streaming:r})},n.prototype.addPreloaderTasks=function(e){var t=this;!0===this._preload&&(e.addBinaryFileTask(this.transform.name+".AudioTask",this._preloaderUrl).onSuccess=function(e){return a(t,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return this.isLegacy()?(this.setLegacyDataSource(e.data),[3,3]):[3,1];case 1:return[4,this.setAudioDataSource(e.data)];case 2:t.sent(),t.label=3;case 3:return[2]}})})})},n.IsLegacyEngine=function(){return!!BABYLON.Engine.audioEngine},n.GetAudioOptions=function(){return e.AudioSource.AUDIO_ENGINE_V2_OPTIONS},n.SetAudioOptions=function(t){e.AudioSource.AUDIO_ENGINE_V2_OPTIONS=t},n.GetAudioEngine=function(){return a(this,void 0,void 0,function(){var t;return s(this,function(n){switch(n.label){case 0:return null!=e.AudioSource.AUDIO_ENGINE_V2?[3,2]:(t=e.AudioSource,[4,BABYLON.CreateAudioEngineAsync(e.AudioSource.AUDIO_ENGINE_V2_OPTIONS||{listenerAutoUpdate:!0,listenerEnabled:!0,resumeOnInteraction:!0,resumeOnPause:!0})]);case 1:t.AUDIO_ENGINE_V2=n.sent(),n.label=2;case 2:return[2,e.AudioSource.AUDIO_ENGINE_V2]}})})},n.UnlockLegacyAudio=function(){null==BABYLON.Engine.audioEngine||BABYLON.Engine.audioEngine.unlocked||BABYLON.Engine.audioEngine.unlock()},n.UnlockAudioEngine=function(){return a(this,void 0,void 0,function(){var t;return s(this,function(n){switch(n.label){case 0:return[4,e.AudioSource.GetAudioEngine()];case 1:return null==(t=n.sent())?[3,3]:[4,t.unlockAsync()];case 2:n.sent(),n.label=3;case 3:return[2]}})})},n.AttachSpatialCamera=function(t){return a(this,void 0,void 0,function(){var n;return s(this,function(i){switch(i.label){case 0:return null==t?(console.warn("TOOLKIT.AudioSource.AttachSpatialCamera: No node provided to attach spatial audio listener to."),[2]):[4,e.AudioSource.GetAudioEngine()];case 1:return null!=(n=i.sent())&&null!=n.listener&&n.listener.attach(t,!0,BABYLON.SpatialAudioAttachmentType.PositionAndRotation),[2]}})})},n.DetachSpatialCamera=function(){return a(this,void 0,void 0,function(){var t;return s(this,function(n){switch(n.label){case 0:return[4,e.AudioSource.GetAudioEngine()];case 1:return null!=(t=n.sent())&&null!=t.listener&&t.listener.detach(),[2]}})})},n.CreateSoundBuffer=function(t,n){return a(this,void 0,void 0,function(){var i,r;return s(this,function(o){switch(o.label){case 0:return i=null,[4,e.AudioSource.GetAudioEngine()];case 1:return null==(r=o.sent())?[3,3]:[4,r.createSoundBufferAsync(t,n)];case 2:i=o.sent(),o.label=3;case 3:return[2,i]}})})},n.CreateStaticSound=function(t,n,i){return a(this,void 0,void 0,function(){var r,o;return s(this,function(a){switch(a.label){case 0:return r=null,[4,e.AudioSource.GetAudioEngine()];case 1:return null==(o=a.sent())?[3,3]:[4,o.createSoundAsync(t,n,i)];case 2:r=a.sent(),a.label=3;case 3:return[2,r]}})})},n.CreateStreamingSound=function(t,n,i){return a(this,void 0,void 0,function(){var r,o;return s(this,function(a){switch(a.label){case 0:return r=null,[4,e.AudioSource.GetAudioEngine()];case 1:return null==(o=a.sent())?[3,3]:[4,o.createStreamingSoundAsync(t,n,i)];case 2:r=a.sent(),a.label=3;case 3:return[2,r]}})})},n.MAX_VOLUME=1,n.DEFAULT_LEVEL=1,n.DEFAULT_ROLLOFF=1,n.AUDIO_ENGINE_V2=null,n.AUDIO_ENGINE_V2_OPTIONS={listenerAutoUpdate:!0,listenerEnabled:!0,resumeOnInteraction:!0,resumeOnPause:!0},n}(e.ScriptComponent);e.AudioSource=t,e.SceneManager.RegisterClass("TOOLKIT.AudioSource",t)}(i||(i={})),function(e){var t=function(){function e(){}return e.CreatePostProcess=function(e,t,n){var i=n||{},r=i.red||[1,0,0],o=i.green||[0,1,0],a=i.blue||[0,0,1],s=new BABYLON.PostProcess("channelMixer","\n precision highp float;\n varying vec2 vUV;\n uniform sampler2D textureSampler;\n uniform vec3 redMix;\n uniform vec3 greenMix;\n uniform vec3 blueMix;\n\n void main(void) {\n vec4 sceneColor = texture2D(textureSampler, vUV);\n vec3 rgb = sceneColor.rgb;\n float newR = dot(rgb, redMix);\n float newG = dot(rgb, greenMix);\n float newB = dot(rgb, blueMix);\n gl_FragColor = vec4(newR, newG, newB, sceneColor.a);\n }\n ",["redMix","greenMix","blueMix"],[],1,t,BABYLON.Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1);return s.onApply=function(e){e.setFloat3("redMix",r[0]||1,r[1]||0,r[2]||0),e.setFloat3("greenMix",o[0]||0,o[1]||1,o[2]||0),e.setFloat3("blueMix",a[0]||0,a[1]||0,a[2]||1)},s},e}();e.ChannelMixerPlugin=t}(i||(i={})),function(e){var t=function(t){function n(e,n,i,r){void 0===i&&(i={}),void 0===r&&(r="TOOLKIT.CharacterController");var o=t.call(this,e,n,i,r)||this;return o._avatarRadius=.28,o._avatarHeight=1.8,o._centerOffset=new BABYLON.Vector3(0,.94,0),o._slopeLimit=45,o._skinWidth=.025,o._stepHeight=.25,o._minMoveDistance=.001,o._verticalVelocity=0,o._currentSlopeAngle=0,o._collisionEvents=!0,o._targetRotation=new BABYLON.Quaternion(0,0,0,1),o._targetVelocity=new BABYLON.Vector3,o._currentVelocity=new BABYLON.Vector3(0,0,0),o._inputVelocity=new BABYLON.Vector3(0,0,0),o._stepUpVelocity=0,o._gravityFactor=3,o._minJumpTimer=0,o._isGrounded=!1,o._groundContacts=new Map,o._groundContactInfo=null,o._groundedEnterTimer=0,o._groundedExitTimer=0,o._raycastResult=new BABYLON.PhysicsRaycastResult,o._rayOrigin=new BABYLON.Vector3,o._rayTarget=new BABYLON.Vector3,o._previousGroundHeight=0,o._stepDetectionDistance=.5,o.m_moveDeltaX=0,o.m_moveDeltaY=0,o.m_moveDeltaZ=0,o.m_havokplugin=null,o.onUpdatePositionObservable=new BABYLON.Observable,o.onUpdateVelocityObservable=new BABYLON.Observable,o.enableUpdate=!0,o.enableGravity=!1,o.enableStepOffset=!1,o.useMultiRaycast=!1,o.multiRaycastCount=5,o.groundCheckDistance=.25,o.stepUpVelocityFactor=.5,o.defaultJumpingTimer=.5,o.onlyApplyGravityWhenNotGrounded=!1,o.downwardVelocityClamp=-2,o.contactHysteresisTime=.15,o.groundedEnterTime=.03,o.groundedExitTime=.1,o}return r(n,t),n.prototype.getAvatarRadius=function(){return this._avatarRadius},n.prototype.getAvatarHeight=function(){return this._avatarHeight},n.prototype.getCenterOffset=function(){return this._centerOffset},n.prototype.getSkinWidth=function(){return this._skinWidth},n.prototype.getStepHeight=function(){return this._stepHeight},n.prototype.getGravityFactor=function(){return this._gravityFactor},n.prototype.setGravityFactor=function(e){this._gravityFactor=e},n.prototype.getInputVelocity=function(){return this._inputVelocity},n.prototype.setInputVelocity=function(e){this._inputVelocity.copyFrom(e)},n.prototype.getStepUpVelocity=function(){return this._stepUpVelocity},n.prototype.getCurrentSlopeAngle=function(){return this._currentSlopeAngle},n.prototype.getVerticalVelocity=function(){return!0===this.isGrounded()?0:this._currentVelocity.y},n.prototype.getMinMoveDistance=function(){return this._minMoveDistance},n.prototype.setMinMoveDistance=function(e){this._minMoveDistance=e},n.prototype.getGroundContactInfo=function(){return this._groundContactInfo},n.prototype.getMinJumpTimer=function(){return this._minJumpTimer},n.prototype.getSlopeLimit=function(){return this._slopeLimit},n.prototype.setSlopeLimit=function(e){this._slopeLimit=e},n.prototype.isGrounded=function(){return this._isGrounded},n.prototype.canJump=function(){return!0===this.isGrounded()},n.prototype.awake=function(){var t=this;this._avatarRadius=this.getProperty("avatarRadius",this._avatarRadius),this._avatarHeight=this.getProperty("avatarHeight",this._avatarHeight),this._slopeLimit=this.getProperty("slopeLimit",this._slopeLimit),this._skinWidth=this.getProperty("skinWidth",this._skinWidth),this._stepHeight=this.getProperty("stepOffset",this._stepHeight),this._minMoveDistance=this.getProperty("minMoveDistance",this._minMoveDistance),this._collisionEvents=this.getProperty("collisionEvents",this._collisionEvents),this.contactHysteresisTime=this.getProperty("contactHysteresisTime",this.contactHysteresisTime),this.groundedEnterTime=this.getProperty("groundedEnterTime",this.groundedEnterTime),this.groundedExitTime=this.getProperty("groundedExitTime",this.groundedExitTime);var n=this.getProperty("centerOffset");null!=n&&(this._centerOffset=e.Utilities.ParseVector3(n)),this.enableStepOffset=this.getProperty("enableStepOffset",this.enableStepOffset),this.createPhysicsBodyAndShape(e.CharacterController.DEFAULT_CHARACTER_MASS,e.Utilities.GetLayerMask(31),-1),this.enableCollisionEvents();var i=function(e){t.registerGroundContact(e)};this.onCollisionEnterObservable.add(i),this.onCollisionStayObservable.add(i),this.onCollisionExitObservable.add(function(e){})},n.prototype.update=function(){if(!1!==this.enableUpdate){var e=this.getDeltaSeconds();this._minJumpTimer>0&&(this._minJumpTimer-=e,this._minJumpTimer<0&&(this._minJumpTimer=0))}},n.prototype.fixed=function(){if(!1!==this.enableUpdate&&null!=this.transform){if(null!=this.transform.physicsBody?this.transform.physicsBody.getLinearVelocityToRef(this._currentVelocity):this._currentVelocity.set(0,0,0),this.m_moveDeltaX=this._targetVelocity.x,this.m_moveDeltaY=this._targetVelocity.y,this.m_moveDeltaZ=this._targetVelocity.z,Math.abs(this.m_moveDeltaX)<this._minMoveDistance&&(this.m_moveDeltaX>0?this.m_moveDeltaX=this._minMoveDistance:this.m_moveDeltaX<0&&(this.m_moveDeltaX=-this._minMoveDistance)),Math.abs(this.m_moveDeltaZ)<this._minMoveDistance&&(this.m_moveDeltaZ>0?this.m_moveDeltaZ=this._minMoveDistance:this.m_moveDeltaZ<0&&(this.m_moveDeltaZ=-this._minMoveDistance)),this.updateGroundedState(),this.onUpdateVelocityObservable&&this.onUpdateVelocityObservable.hasObservers()&&this.onUpdateVelocityObservable.notifyObservers(this.transform),this._inputVelocity.set(this.m_moveDeltaX,this.m_moveDeltaY+this._verticalVelocity,this.m_moveDeltaZ),null!=this.transform.physicsBody)try{(!1===this.enableGravity||!0===this.onlyApplyGravityWhenNotGrounded&&!0===this._isGrounded)&&(this._inputVelocity.y=0),this.transform.physicsBody.setLinearVelocity(this._inputVelocity)}catch(e){console.warn("Failed to set linear velocity on physics body: ",e)}else console.warn("No physics body attached to character controller transform: "+this.transform.name);this.onUpdatePositionObservable&&this.onUpdatePositionObservable.hasObservers()&&this.onUpdatePositionObservable.notifyObservers(this.transform)}},n.prototype.set=function(e,t,n,i,r,o,a){void 0===i&&(i=null),void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),!1!==this.enableUpdate&&null!=this.transform&&(null!=this.transform.position&&null!=e&&null!=t&&null!=n&&this.transform.position.set(e,t,n),null!=this.transform.rotationQuaternion&&null!=i&&null!=r&&null!=o&&null!=a&&this.transform.rotationQuaternion.set(i,r,o,a))},n.prototype.move=function(e,t){void 0===t&&(t=!0),!1!==this.enableUpdate&&null!=e&&this._targetVelocity.copyFrom(e)},n.prototype.jump=function(e){var t;if(!1!==this.enableUpdate&&this.canJump()&&(this._isGrounded=!1,this._groundContactInfo=null,this._minJumpTimer=this.defaultJumpingTimer,this._verticalVelocity=e,null===(t=this.transform)||void 0===t?void 0:t.physicsBody)){var n=new BABYLON.Vector3;this.transform.physicsBody.getLinearVelocityToRef(n),n.y=e,this.transform.physicsBody.setLinearVelocity(n)}},n.prototype.turn=function(e){!1!==this.enableUpdate&&null!=this.transform&&this.transform.addRotation(0,e,0)},n.prototype.rotate=function(e,t,n,i){!1!==this.enableUpdate&&null!=this.transform&&null!=this.transform.rotationQuaternion&&(this._targetRotation.set(e,t,n,i),this.transform.rotationQuaternion.copyFrom(this._targetRotation))},n.prototype.setRigidBodyMass=function(e){if(null!=this.transform&&null!=this.transform.physicsBody){var t=this.transform.physicsBody.getMassProperties();t.mass=e>=1e-7?e:1e-7,this.transform.physicsBody.setMassProperties(t)}},n.prototype.setCollisionState=function(e){null!=this.transform&&null!=this.transform.physicsBody&&null!=this.transform.physicsBody.shape&&(this.transform.physicsBody.shape.isTrigger=!e)},n.prototype.setCollisionFilters=function(e,t){if(null!=this.transform&&null!=this.transform.physicsBody&&null!=this.transform.physicsBody.shape){var n=this.transform.physicsBody.shape,i=function(n){n&&(n.filterCollideMask=t,n.filterMembershipMask=e)};i(n),Array.isArray(n.children)&&n.children.forEach(function(e){return i(e)})}},n.prototype.registerGroundContact=function(e){e&&this.isContactAtFeet(e)&&this._groundContacts.set(e,0)},n.prototype.updateGroundContactAges=function(e){var t=this;if(0===this._groundContacts.size)return 0;var n=1e3*Math.max(0,this.contactHysteresisTime),i=0;return this._groundContacts.forEach(function(r,o){var a=r+e;a>n?t._groundContacts.delete(o):(t._groundContacts.set(o,a),i++)}),i},n.prototype.isContactAtFeet=function(e){return!(!e||!this.transform)},n.prototype.isValidGroundNormal=function(e){var t=new BABYLON.Vector3(0,1,0),n=BABYLON.Vector3.Dot(e,t);return this._currentSlopeAngle=Math.acos(n)*(180/Math.PI),n>=Math.cos(this._slopeLimit*Math.PI/180)},n.prototype.performSingleRayGroundCheck=function(t){return this._rayOrigin.copyFrom(this.transform.position),this._rayOrigin.y+=.1*this._centerOffset.y,this._rayTarget.copyFrom(this._rayOrigin),this._rayTarget.y-=this.groundCheckDistance,this._raycastResult.reset(),e.RigidbodyPhysics.RaycastToRef(this._rayOrigin,this._rayTarget,this._raycastResult),this._raycastResult.hasHit&&(t.hasGround=!0,t.groundNormal.copyFrom(this._raycastResult.hitNormalWorld),t.groundHeight=this._raycastResult.hitPointWorld.y,t.groundBody=this._raycastResult.body),t},n.prototype.performMultiRayGroundCheck=function(t){for(var n=[],i=this.transform.position.y+.1*this._centerOffset.y,r=0;r<this.multiRaycastCount;r++){var o=r/this.multiRaycastCount*Math.PI*2,a=.7*this._avatarRadius;if(this._rayOrigin.set(this.transform.position.x+Math.cos(o)*a,i,this.transform.position.z+Math.sin(o)*a),this._rayTarget.copyFrom(this._rayOrigin),this._rayTarget.y-=this.groundCheckDistance,this._raycastResult.reset(),e.RigidbodyPhysics.RaycastToRef(this._rayOrigin,this._rayTarget,this._raycastResult),this._raycastResult.hasHit){var s=this._rayOrigin.y-this._raycastResult.hitPointWorld.y;n.push({normal:this._raycastResult.hitNormalWorld.clone(),height:this._raycastResult.hitPointWorld.y,distance:s,body:this._raycastResult.body})}}if(n.length>0){var l=n[0];for(r=1;r<n.length;r++)n[r].distance<l.distance&&(l=n[r]);var u=new BABYLON.Vector3;n.forEach(function(e){return u.addInPlace(e.normal)}),u.scaleInPlace(1/n.length),u.normalize(),t.hasGround=!0,t.groundNormal.copyFrom(u),t.groundHeight=l.height,t.groundBody=l.body}return t},n.prototype.performGroundRaycast=function(){var e={hasGround:!1,groundNormal:new BABYLON.Vector3(0,1,0),groundHeight:0,groundBody:null};return this.useMultiRaycast?this.performMultiRayGroundCheck(e):this.performSingleRayGroundCheck(e)},n.prototype.detectAndHandleStepOffset=function(t){if(Math.sqrt(this.m_moveDeltaX*this.m_moveDeltaX+this.m_moveDeltaZ*this.m_moveDeltaZ)<.01)return 0;var n=new BABYLON.Vector3(this.m_moveDeltaX,0,this.m_moveDeltaZ).normalize(),i=t;if(this._rayOrigin.copyFrom(this.transform.position),this._rayOrigin.y=i+.05,this._rayTarget.copyFrom(this._rayOrigin),this._rayTarget.addInPlace(n.scale(this._stepDetectionDistance)),this._raycastResult.reset(),e.RigidbodyPhysics.RaycastToRef(this._rayOrigin,this._rayTarget,this._raycastResult),!this._raycastResult.hasHit)return 0;var r=BABYLON.Vector3.Distance(this._rayOrigin,this._raycastResult.hitPointWorld);if(this._rayOrigin.copyFrom(this.transform.position),this._rayOrigin.y=i+this._stepHeight+.05,this._rayOrigin.addInPlace(n.scale(r+.1)),this._rayTarget.copyFrom(this._rayOrigin),this._rayTarget.y=i-.05,this._raycastResult.reset(),e.RigidbodyPhysics.RaycastToRef(this._rayOrigin,this._rayTarget,this._raycastResult),!this._raycastResult.hasHit)return 0;var o=this._raycastResult.hitPointWorld.y-i;return o>.01&&o<=this._stepHeight?Math.sqrt(2*Math.abs(this.scene.gravity.y)*o*this._gravityFactor)*this.stepUpVelocityFactor:0},n.prototype.updateGroundedState=function(){if(this._minJumpTimer>0){this._isGrounded=!1,this._groundContactInfo=null;var t=this.getDeltaSeconds();return this._verticalVelocity-=Math.abs(this.scene.gravity.y)*this._gravityFactor*t,void(Math.abs(this._verticalVelocity)>e.CharacterController.TERMINAL_VELOCITY&&(this._verticalVelocity=-e.CharacterController.TERMINAL_VELOCITY))}var n=this.getDeltaSeconds(),i=1e3*n,r=Math.max(0,this.groundedEnterTime),o=Math.max(0,this.groundedExitTime),a=this.updateGroundContactAges(i)>0,s=null;if(this._currentSlopeAngle=0,a){var l=this.performGroundRaycast();l.hasGround&&this.isValidGroundNormal(l.groundNormal)?s=l:a=!1}if(a?(this._groundedExitTimer=0,this._groundedEnterTimer=Math.min(this._groundedEnterTimer+n,r),!this._isGrounded&&this._groundedEnterTimer>=r?this._isGrounded=!0:this._isGrounded&&(this._groundedEnterTimer=r)):(this._groundedEnterTimer=0,this._groundedExitTimer=Math.min(this._groundedExitTimer+n,o),this._isGrounded&&this._groundedExitTimer>=o&&(this._isGrounded=!1)),s&&this._isGrounded?(this._groundContactInfo=s,this._previousGroundHeight=s.groundHeight):s||(this._groundContactInfo=null),!0===this._isGrounded&&!0===this.enableStepOffset){var u=this._groundContactInfo?this._groundContactInfo.groundHeight:this.transform.position.y;this._stepUpVelocity=this.detectAndHandleStepOffset(u),this._stepUpVelocity>0&&(this._verticalVelocity=Math.max(this._verticalVelocity,this._stepUpVelocity))}else this._stepUpVelocity=0;!0===this._isGrounded&&this._verticalVelocity<0?this._verticalVelocity=Math.max(this._verticalVelocity,this.downwardVelocityClamp):(this._verticalVelocity-=Math.abs(this.scene.gravity.y)*this._gravityFactor*n,Math.abs(this._verticalVelocity)>e.CharacterController.TERMINAL_VELOCITY&&(this._verticalVelocity=-e.CharacterController.TERMINAL_VELOCITY))},n.prototype.createPhysicsBodyAndShape=function(t,n,i){var r=this.transform;e.Utilities.ReparentColliders()||r.setParent(null,!0,!0);var o=this._avatarRadius*parseFloat(r.scaling.x.toFixed(4)),a=this._avatarHeight*parseFloat(r.scaling.y.toFixed(4)),s=this.createPhysicsShapeCapsule(o,a);s.filterCollideMask=this.getProperty("filterCollideMask")||4294967295,s.filterMembershipMask=this.getProperty("filterMembershipMask")||n;var l=new BABYLON.Quaternion(0,0,0,1),u=this._centerOffset.x*parseFloat(r.scaling.x.toFixed(4)),c=this._centerOffset.y*parseFloat(r.scaling.y.toFixed(4)),d=this._centerOffset.z*parseFloat(r.scaling.z.toFixed(4)),h=new BABYLON.Vector3(u,c,d),p=new BABYLON.PhysicsShapeContainer(this.scene);p.filterCollideMask=s.filterCollideMask,p.filterMembershipMask=s.filterMembershipMask,p.material={friction:0,staticFriction:0,restitution:0,frictionCombine:0,restitutionCombine:0},p.addChild(s,h,l,new BABYLON.Vector3(1,1,1));var m=new BABYLON.PhysicsBody(r,BABYLON.PhysicsMotionType.DYNAMIC,!1,this.scene);if(m.shape=p,m.setMassProperties({mass:t,centerOfMass:new BABYLON.Vector3(0,0,0),inertia:new BABYLON.Vector3(0,0,0)}),m.setGravityFactor(0),m.setLinearDamping(0),m.setAngularDamping(0),m.disablePreStep=!1,!0===this._collisionEvents&&(m.setCollisionCallbackEnabled(!0),m.setCollisionEndedCallbackEnabled(!0)),e.Utilities.ShowDebugColliders()&&console.log("Setup character controller physics collider for: "+r.name,r),!e.Utilities.ShowDebugColliders()){var f=r;null!=f.material&&"CenterBox-Material"===f.material.name&&(f.isVisible=!1)}e.Utilities.ShowDebugColliders()&&(null==e.RigidbodyPhysics.DebugPhysicsViewer&&(e.RigidbodyPhysics.DebugPhysicsViewer=new BABYLON.Debug.PhysicsViewer),null!=e.RigidbodyPhysics.DebugPhysicsViewer&&e.RigidbodyPhysics.DebugPhysicsViewer.showBody(m))},n.prototype.createPhysicsShapeCapsule=function(e,t){var n=-.5*(t-.5),i=.5*(t-.5);return new BABYLON.PhysicsShapeCapsule(new BABYLON.Vector3(0,n,0),new BABYLON.Vector3(0,i,0),e,this.scene)},n.TERMINAL_VELOCITY=55,n.DEFAULT_CHARACTER_MASS=85,n}(e.ScriptComponent);e.CharacterController=t;var n=function(e){function t(t,n,i,r){void 0===i&&(i={}),void 0===r&&(r="TOOLKIT.SimpleCharacterController");var o=e.call(this,t,n,i,r)||this;return o._eulerAngles=new BABYLON.Vector3(0,0,0),o}return r(t,e),t.prototype.start=function(){},t.prototype.set=function(e,t,n,i,r,o,a,s){void 0===i&&(i=null),void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=!0),null!=this.transform&&(null!=this.transform.position&&null!=e&&null!=t&&null!=n&&this.transform.position.set(e,t,n),null!=this.transform.rotationQuaternion&&null!=i&&null!=r&&null!=o&&null!=a&&this.transform.rotationQuaternion.set(i,r,o,a))},t.prototype.move=function(e,t){void 0===t&&(t=!0),null!=e&&null!=this.transform&&this.transform instanceof BABYLON.AbstractMesh&&this.transform.moveWithCollisions(e)},t.prototype.jump=function(e){},t.prototype.turn=function(e){null!=this.transform&&this.transform.addRotation(0,e,0)},t.prototype.rotate=function(e,t,n,i){null!=this.transform&&null!=this.transform.rotationQuaternion&&this.transform.rotationQuaternion.set(e,t,n,i)},t}(e.ScriptComponent);e.SimpleCharacterController=n;var i=function(e){function t(t,n,i,r){void 0===i&&(i={}),void 0===r&&(r="TOOLKIT.RecastCharacterController");var o=e.call(this,t,n,i,r)||this;return o._eulerAngles=new BABYLON.Vector3(0,0,0),o._teleportVector=new BABYLON.Vector3(0,0,0),o._navigationAgent=null,o}return r(t,e),t.prototype.getNavigationAgent=function(){return this._navigationAgent},t.prototype.setNavigationAgent=function(e){this._navigationAgent=e},t.prototype.setDestinationPoint=function(e,t){void 0===t&&(t=!0),null!=this._navigationAgent&&this._navigationAgent.setDestination(e,t)},t.prototype.start=function(){this._navigationAgent=this.getComponent("TOOLKIT.NavigationAgent")},t.prototype.set=function(e,t,n,i,r,o,a,s){void 0===i&&(i=null),void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=!0),null!=this.transform&&null!=this._navigationAgent&&(null!=this.transform.position&&null!=e&&null!=t&&null!=n&&(this._teleportVector.set(e,t,n),this._navigationAgent.teleport(this._teleportVector,s)),null!=this.transform.rotationQuaternion&&null!=i&&null!=r&&null!=o&&null!=a&&this.transform.rotationQuaternion.set(i,r,o,a))},t.prototype.move=function(e,t){void 0===t&&(t=!0),null!=e&&null!=this._navigationAgent&&this._navigationAgent.move(e,t)},t.prototype.jump=function(e){console.warn("Jump is not supported by the navigation mesh character controller.")},t.prototype.turn=function(e){null!=this.transform&&this.transform.addRotation(0,e,0)},t.prototype.rotate=function(e,t,n,i){null!=this.transform&&null!=this.transform.rotationQuaternion&&null!=this._navigationAgent&&this.transform.rotationQuaternion.set(e,t,n,i)},t}(e.ScriptComponent);e.RecastCharacterController=i,e.SceneManager.RegisterClass("TOOLKIT.CharacterController",t),e.SceneManager.RegisterClass("TOOLKIT.SimpleCharacterController",n),e.SceneManager.RegisterClass("TOOLKIT.RecastCharacterController",i)}(i||(i={})),function(e){var t=function(){function e(){}return e.CreatePostProcess=function(e,t,n){var i=n||{},r=Array.isArray(i.color)?i.color:i.color?[i.color.r||1,i.color.g||1,i.color.b||1,null!=i.color.a?i.color.a:1]:[1,1,1,1],o=new BABYLON.PostProcess("colorFilter","\n precision highp float;\n varying vec2 vUV;\n uniform sampler2D textureSampler;\n uniform vec4 filterColor;\n\n void main(void) {\n vec4 sceneColor = texture2D(textureSampler, vUV);\n gl_FragColor = sceneColor * filterColor;\n }\n ",["filterColor"],[],1,t,BABYLON.Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1);return o.onApply=function(e){e.setFloat4("filterColor",r[0]||1,r[1]||1,r[2]||1,null!=r[3]?r[3]:1)},o},e}();e.ColorFilterPlugin=t}(i||(i={})),function(e){var t=function(){function e(){}return e.CreateColoredBloom=function(e,t,n){var i=n||{},r=null!=i.threshold?i.threshold:1,o=Array.isArray(i.color)?i.color:i.color?[i.color.r||1,i.color.g||1,i.color.b||1]:[1,1,1],a=null!=i.weight?i.weight:1,s=null!=i.kernel?i.kernel:4,l=null!=i.downsampleRatio?i.downsampleRatio:null!=i.ratio?i.ratio:.5,u=null!=i.passes?Math.max(1,Math.floor(i.passes)):1,c=null!=i.saturation?i.saturation:1,d=new BABYLON.PostProcess("coloredBloom_prefilter","\n precision highp float;\n varying vec2 vUV;\n uniform sampler2D textureSampler;\n uniform float threshold;\n uniform vec3 tint;\n\n void main(void) {\n vec4 color = texture2D(textureSampler, vUV);\n float lum = dot(color.rgb, vec3(0.2126, 0.7152, 0.0722));\n float mask = smoothstep(threshold * 0.95, threshold * 1.05, lum);\n vec3 bloom = color.rgb * mask * tint;\n gl_FragColor = vec4(bloom, 1.0);\n }\n ",["threshold","tint"],[],l,t,BABYLON.Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1);d.onApply=function(e){e.setFloat("threshold",r),e.setFloat3("tint",o[0]||1,o[1]||1,o[2]||1)};for(var h=[],p=0;p<u;p++){var m=new BABYLON.BlurPostProcess("coloredBloom_blurH_"+p,new BABYLON.Vector2(1,0),s,l,null,BABYLON.Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1),f=new BABYLON.BlurPostProcess("coloredBloom_blurV_"+p,new BABYLON.Vector2(0,1),s,l,null,BABYLON.Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1);h.push({h:m,v:f})}var g=new BABYLON.PostProcess("coloredBloom_composite","\n precision highp float;\n varying vec2 vUV;\n uniform sampler2D textureSampler;\n uniform sampler2D bloomSampler;\n uniform float weight;\n uniform float saturation;\n\n vec3 desaturate(in vec3 c) {\n float l = dot(c, vec3(0.2126, 0.7152, 0.0722));\n return vec3(l);\n }\n\n void main(void) {\n vec4 scene = texture2D(textureSampler, vUV);\n vec3 bloom = texture2D(bloomSampler, vUV).rgb;\n // apply saturation control to bloom\n bloom = mix(desaturate(bloom), bloom, saturation);\n gl_FragColor = vec4(scene.rgb + bloom * weight, scene.a);\n }\n ",["weight","saturation"],["bloomSampler"],1,t,BABYLON.Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1);return g.onApply=function(e){e.setFloat("weight",a),e.setFloat("saturation",c)},{prefilter:d,blurPasses:h,composite:g,passes:u,saturation:c,dispose:function(){try{this.prefilter.dispose()}catch(e){}try{this.blurPasses.forEach(function(e){try{e.h.dispose()}catch(e){}try{e.v.dispose()}catch(e){}})}catch(e){}try{this.composite.dispose()}catch(e){}}}},e}();e.ColoredBloomPlugin=t}(i||(i={})),function(e){e.btVehicleTuning=function(){this.suspensionStiffness=25,this.suspensionCompression=4.5,this.suspensionDamping=6.5,this.maxSuspensionTravelCm=10,this.frictionSlip=10,this.maxSuspensionForce=15e3};var t=function(){this.hitPointInWorld=new BABYLON.Vector3,this.hitNormalInWorld=new BABYLON.Vector3,this.distFraction=0,this.hitBody=null,this.filterCollideMask=0,this.filterMembershipMask=0};e.btVehicleRaycasterResult=t;var n=function(){function t(e){this._raycastResult=new BABYLON.PhysicsRaycastResult,this._query=e||void 0}return t.prototype.castRay=function(t,n,i){if(this._raycastResult.reset(),i.hitBody=null,i.filterCollideMask=0,i.filterMembershipMask=0,e.RigidbodyPhysics.RaycastToRef(t,n,this._raycastResult,this._query),this._raycastResult.hasHit){var r=this._raycastResult.body;if(r){i.hitPointInWorld.copyFrom(this._raycastResult.hitPointWorld),i.hitNormalInWorld.copyFrom(this._raycastResult.hitNormalWorld),i.hitNormalInWorld.normalize();var o=i.hitPointInWorld.x-t.x,a=i.hitPointInWorld.y-t.y,s=i.hitPointInWorld.z-t.z,l=Math.sqrt(o*o+a*a+s*s),u=n.x-t.x,c=n.y-t.y,d=n.z-t.z,h=Math.sqrt(u*u+c*c+d*d);i.distFraction=h>1e-8?l/h:0,i.hitBody=r;var p=this._raycastResult.shape||r.shape;return p&&(i.filterCollideMask=0|p.filterCollideMask,i.filterMembershipMask=0|p.filterMembershipMask),r}}return null},t}();e.btDefaultVehicleRaycaster=n;var i=function(){this.contactNormalWS=new BABYLON.Vector3(0,1,0),this.contactPointWS=new BABYLON.Vector3,this.suspensionLength=0,this.hardPointWS=new BABYLON.Vector3,this.wheelDirectionWS=new BABYLON.Vector3(0,-1,0),this.wheelAxleWS=new BABYLON.Vector3(1,0,0),this.isInContact=!1,this.groundObject=null};e.btWheelRaycastInfo=i;var r=function(){function e(e){this.raycastInfo=new i,this.worldTransformPosition=new BABYLON.Vector3,this.worldTransformRotation=new BABYLON.Quaternion,this.steering=0,this.rotation=0,this.deltaRotation=0,this.rollInfluence=.1,this.engineForce=0,this.brake=0,this.clippedInvContactDotSuspension=1,this.suspensionRelativeVelocity=0,this.suspensionForce=0,this.skidInfo=1,this.clientInfo=null,this.steeringAngle=0,this.rotationBoost=0,this.defaultFriction=0,this.invertWheelDirection=!1,this.maxVisualTravelRange=0,this.contactCollideMask=0,this.contactMembershipMask=0,this._prevContactNormalWS=new BABYLON.Vector3(0,1,0),this._prevSuspensionLength=-1,this._prevSuspensionForce=-1,this._hasPrevSuspState=!1,this._rayHistoryLengths=[],this._rayHistoryNormalsX=[],this._rayHistoryNormalsY=[],this._rayHistoryNormalsZ=[],this._rayHistoryIndex=0,this._rayHistoryCount=0,this._smoothedSuspensionLength=-1,this._smoothedContactNormal=new BABYLON.Vector3(0,1,0),this._smoothedContactNormalValid=!1,this._contactLossFrames=0,this.transform=null,this.spinner=null,this.chassisConnectionPointCS=e.chassisConnectionCS.clone(),this.wheelDirectionCS=e.wheelDirectionCS.clone(),this.wheelAxleCS=e.wheelAxleCS.clone(),this.suspensionRestLength=e.suspensionRestLength,this.maxSuspensionTravelCm=e.maxSuspensionTravelCm,this.wheelRadius=e.wheelRadius,this.suspensionStiffness=e.suspensionStiffness,this.dampingCompression=e.dampingCompression,this.dampingRelaxation=e.dampingRelaxation,this.frictionSlip=e.frictionSlip,this.maxSuspensionForce=e.maxSuspensionForce,this.isFrontWheel=e.isFrontWheel}return e.prototype.getSuspensionRestLength=function(){return this.suspensionRestLength},e}();e.btWheelInfo=r;var o=function(){function n(e,n,i){this._wheelInfo=[],this._indexRightAxis=0,this._indexUpAxis=1,this._indexForwardAxis=2,this._currentVehicleSpeedKmHour=0,this.enableMultiRaycast=!0,this.minimumWheelContacts=4,this.trackConnectionAccel=6,this.smoothFlyingImpulse=8,this.arcadeSteeringAssist=1,this.smoothedGradientSpeed=.5,this.maximumYawRateLow=60,this.maximumYawRateHigh=30,this.angularDamping=new BABYLON.Vector3(.5,1,.5),this.wheelSkidFadeInSpeed=18,this.wheelSkidFadeOutSpeed=6,this.minContactDotSuspension=.1,this.suspensionForceSmoothing=0,this.suspensionDampingOverdrive=1,this.raycastSmoothingEnabled=!0,this.raycastHistoryBufferSize=12,this.raycastLengthCompressionAlpha=.5,this.raycastLengthRelaxationAlpha=.2,this.raycastNormalSmoothingAlpha=.15,this.raycastOutlierRejectionEnabled=!0,this.raycastOutlierThresholdMeters=.03,this.raycastMaxLengthChangePerSecond=3.5,this.raycastContactLossGraceFrames=3,this.raycastDebugLogEnabled=!1,this.raycastDebugLogIntervalFrames=30,this.raycastDebugLogSpikeThresholdMeters=.04,this.raycastDebugLogWheelMask=65535,this._raycastDebugFrameCounter=0,this._raycastMedianScratch=[],this.sideToSideStabilityEnabled=!0,this.sideToSideStabilityStartKmh=80,this.sideToSideStabilityFullKmh=180,this.stabilizationDebug=!1,this.stabilizationDebugInterval=.25,this.downforceCoefficient=.8,this.constantDownforce=.1,this.stabilizationNormalSmoothing=.85,this.airborneGroundNormalHoldTime=.35,this.groundedAutoLevelEnabled=!0,this.groundedAutoLevelStrength=20,this.groundedAutoLevelDeadzoneDeg=3,this.groundedAutoLevelSettleDeg=1,this.groundedAutoLevelSettleScale=.55,this.groundedAutoLevelHysteresisDeg=.25,this.groundedAutoLevelStartKmh=20,this.groundedAutoLevelFullKmh=100,this.groundedAutoLevelMaxRate=9,this.groundedAutoLevelPartialContactBoost=1.6,this.groundedAutoLevelSlideScale=.35,this.groundedAutoLevelTrackNormalMinDot=.45,this.airborneTrackConnectionStartKmh=80,this.airborneTrackConnectionFullKmh=180,this.airborneTrackConnectionMaxAccel=12,this.airborneRiseDamping=6,this.airborneMaxRiseSpeed=0,this._groundedAutoLevelWasActive=!1,this._stabilizationGroundNormal=new BABYLON.Vector3(0,1,0),this._stabilizationHasGroundNormal=!1,this._stabilizationAirborneTime=0,this.isArcadeBurnoutModeActive=!1,this.isArcadeDonutModeActive=!1,this.isArcadeFootBrakeActive=!1,this.isArcadeHandBrakeActive=!1,this.isArcadeWheelSkidActive=!1,this.isArcadeYawAssistActive=!1,this.burnoutFrictionFloor=1,this.frictionRestoreSpeed=8,this.arcadeBurnoutWheelSpinGain=1,this.arcadeDonutWheelSpinGain=1,this.arcadeBurnoutDirectionChangeSpeedKmh=24.1401,this.arcadeBurnoutDirectionChangeGripScale=.2,this.arcadeWheelSpinBuildSpeed=12,this.arcadeWheelSpinRecoverySpeed=10,this.arcadeWheelSpinAirDamping=.985,this.arcadeWheelSpinMaxAngularVelocity=160,this.arcadeStationaryBurnoutWheelSpinGain=3.25,this.arcadeStationaryBurnoutMinAngularVelocity=65,this.arcadeHandbrakeYawCapMultiplier=1.85,this.arcadeBurnoutYawCapMultiplier=1.25,this.arcadeDonutYawCapMultiplier=1.15,this.arcadeSkidFadeInSpeed=18,this.arcadeSkidFadeOutSpeed=6,this.wheelAtRestSpeedThresholdKmh=1,this.arcadeHandbrakeAssistEnabled=!0,this.currentSteeringInput=0,this.arcadeDonutDirectYawEnabled=!0,this.arcadeDonutDirectYawDegPerSec=60,this.arcadeDonutDirectYawDurationMs=0,this.arcadeDonutDirectYawFadeMs=120,this._arcadeDonutHoldElapsedSec=0,this._arcadeDonutDirectionSign=0,this._forwardWS=[],this._axle=[],this._forwardImpulse=[],this._sideImpulse=[],this._arcadeSkidInfo=[],this._arcadePreviousWheelSpin=[],this.sideFrictionStiffness=1,this.arcadeSideSlipSaturationEnabled=!0,this.arcadeSideSlipPeakDeg=8,this.arcadeSideSlipFalloffDeg=45,this.arcadeSideSlipFalloffFactor=.4,this.arcadeSideSlipMinSpeedMps=1.5,this._chassisMass=0,this._chassisInvMass=0,this._chassisTransform=BABYLON.Matrix.Identity(),this._rayResults=new t,this._sv1=new BABYLON.Vector3,this._sv2=new BABYLON.Vector3,this._sv3=new BABYLON.Vector3,this._sv4=new BABYLON.Vector3,this._sv5=new BABYLON.Vector3,this._sv6=new BABYLON.Vector3,this._sv7=new BABYLON.Vector3,this._sv8=new BABYLON.Vector3,this._sv9=new BABYLON.Vector3,this._sv10=new BABYLON.Vector3,this._sq1=new BABYLON.Quaternion,this._sq2=new BABYLON.Quaternion,this._sm1=BABYLON.Matrix.Identity(),this._sm2=BABYLON.Matrix.Identity(),this._sm3=BABYLON.Matrix.Identity(),this._sm4=BABYLON.Matrix.Identity(),this._vapLinVel=new BABYLON.Vector3,this._vapAngVel=new BABYLON.Vector3,this._vapRelPos=new BABYLON.Vector3,this._vapCenter=new BABYLON.Vector3,this._vapCross=new BABYLON.Vector3,this._rsbVel1=new BABYLON.Vector3,this._crfVel1=new BABYLON.Vector3,this._basisCols=[new BABYLON.Vector3,new BABYLON.Vector3,new BABYLON.Vector3],this._stb1=new BABYLON.Vector3,this._stb2=new BABYLON.Vector3,this._stb3=new BABYLON.Vector3,this._stb4=new BABYLON.Vector3,this._stb5=new BABYLON.Vector3,this._chassisBody=n,this._vehicleRaycaster=i,this._currentVehicleSpeedKmHour=0,this.cacheMassProperties()}return n.prototype.addWheel=function(e,t,n,i,o,a,s){var l=new r({chassisConnectionCS:e,wheelDirectionCS:t,wheelAxleCS:n,suspensionRestLength:i,maxSuspensionTravelCm:a.maxSuspensionTravelCm,wheelRadius:o,suspensionStiffness:a.suspensionStiffness,dampingCompression:a.suspensionCompression,dampingRelaxation:a.suspensionDamping,frictionSlip:a.frictionSlip,maxSuspensionForce:a.maxSuspensionForce,isFrontWheel:s});return this._wheelInfo.push(l),this._forwardWS.push(new BABYLON.Vector3),this._axle.push(new BABYLON.Vector3),this._forwardImpulse.push(0),this._sideImpulse.push(0),this._arcadeSkidInfo.push(1),this._arcadePreviousWheelSpin.push(0),this.updateWheelTransformsWS(l,!1),this.updateWheelTransform(this._wheelInfo.length-1,!1),l},n.prototype.getNumWheels=function(){return this._wheelInfo.length},n.prototype.getWheelInfo=function(e){return this._wheelInfo[e]},n.prototype.setSteeringValue=function(e,t){this._wheelInfo[t].steering=e},n.prototype.getSteeringValue=function(e){return this._wheelInfo[e].steering},n.prototype.applyEngineForce=function(e,t){this._wheelInfo[t].engineForce=e},n.prototype.setBrake=function(e,t){this._wheelInfo[t].brake=e},n.prototype.getCurrentSpeedKmHour=function(){return this._currentVehicleSpeedKmHour},n.prototype.getRigidBody=function(){return this._chassisBody},n.prototype.getRightAxis=function(){return this._indexRightAxis},n.prototype.getUpAxis=function(){return this._indexUpAxis},n.prototype.getForwardAxis=function(){return this._indexForwardAxis},n.prototype.setCoordinateSystem=function(e,t,n){this._indexRightAxis=e,this._indexUpAxis=t,this._indexForwardAxis=n},n.prototype.getForwardVector=function(){var e=this._chassisTransform.m,t=this._indexForwardAxis;return new BABYLON.Vector3(e[4*t],e[4*t+1],e[4*t+2])},n.prototype.getForwardVectorToRef=function(e){var t=this._chassisTransform.m,n=this._indexForwardAxis;e.set(t[4*n],t[4*n+1],t[4*n+2])},n.prototype.cacheMassProperties=function(){var e=this._chassisBody.getMassProperties();this._chassisMass=e.mass,this._chassisInvMass=this._chassisMass>0?1/this._chassisMass:0},n.prototype.setIsArcadeBurnoutActive=function(e){this.isArcadeBurnoutModeActive=e},n.prototype.getIsArcadeBurnoutActive=function(){return this.isArcadeBurnoutModeActive},n.prototype.setIsArcadeDonutActive=function(e){!0!==e&&(this._arcadeDonutDirectionSign=0),this.isArcadeDonutModeActive=e},n.prototype.getIsArcadeDonutActive=function(){return this.isArcadeDonutModeActive},n.prototype.setIsArcadeFootBrakeActive=function(e){this.isArcadeFootBrakeActive=e},n.prototype.getIsArcadeFootBrakeActive=function(){return this.isArcadeFootBrakeActive},n.prototype.setIsArcadeHandBrakeActive=function(e){this.isArcadeHandBrakeActive=e},n.prototype.getIsArcadeHandBrakeActive=function(){return this.isArcadeHandBrakeActive},n.prototype.setIsArcadeWheelSkidActive=function(e){this.isArcadeWheelSkidActive=e},n.prototype.getIsArcadeWheelSkidActive=function(){return this.isArcadeWheelSkidActive},n.prototype.setWheelContactFilters=function(e,t,n){e.contactCollideMask=0|t,e.contactMembershipMask=0|n},n.prototype.resetSuspension=function(){for(var e=0;e<this._wheelInfo.length;e++){var t=this._wheelInfo[e];t.raycastInfo.suspensionLength=t.getSuspensionRestLength(),t.suspensionRelativeVelocity=0,t.raycastInfo.contactNormalWS.copyFrom(t.raycastInfo.wheelDirectionWS).scaleInPlace(-1),t.clippedInvContactDotSuspension=1,t._rayHistoryCount=0,t._rayHistoryIndex=0,t._smoothedSuspensionLength=-1,t._smoothedContactNormalValid=!1,t._prevSuspensionLength=-1,t._contactLossFrames=0,this.setWheelContactFilters(t,0,0)}this._stabilizationGroundNormal.set(0,1,0),this._stabilizationHasGroundNormal=!1,this._stabilizationAirborneTime=0,this._groundedAutoLevelWasActive=!1},n.prototype.getChassisWorldTransform=function(){var e=this._chassisBody.transformNode.getWorldMatrix();return this._chassisTransform.copyFrom(e),this._chassisTransform},n.prototype.updateWheelTransformsWS=function(e,t,n){void 0===n&&(n=1),e.raycastInfo.isInContact=!1;var i=this._chassisTransform;1!==n?(e.chassisConnectionPointCS.scaleToRef(n,this._sv1),BABYLON.Vector3.TransformCoordinatesToRef(this._sv1,i,e.raycastInfo.hardPointWS)):BABYLON.Vector3.TransformCoordinatesToRef(e.chassisConnectionPointCS,i,e.raycastInfo.hardPointWS),BABYLON.Vector3.TransformNormalToRef(e.wheelDirectionCS,i,e.raycastInfo.wheelDirectionWS),BABYLON.Vector3.TransformNormalToRef(e.wheelAxleCS,i,e.raycastInfo.wheelAxleWS)},n.prototype.updateWheelTransform=function(e,t){void 0===t&&(t=!0);var n=this._wheelInfo[e];this.updateWheelTransformsWS(n,t);var i=this._sv1;n.raycastInfo.wheelDirectionWS.negateToRef(i);var r=this._sv2;r.copyFrom(n.raycastInfo.wheelAxleWS);var o=this._sv3;BABYLON.Vector3.CrossToRef(i,r,o),o.normalize(),BABYLON.Quaternion.RotationAxisToRef(i,n.steering,this._sq1),BABYLON.Matrix.FromQuaternionToRef(this._sq1,this._sm2),BABYLON.Quaternion.RotationAxisToRef(r,-n.rotation,this._sq2),BABYLON.Matrix.FromQuaternionToRef(this._sq2,this._sm3),this._basisCols[this._indexRightAxis].copyFrom(r),this._basisCols[this._indexUpAxis].copyFrom(i),this._basisCols[this._indexForwardAxis].copyFrom(o);var a=this._basisCols[0],s=this._basisCols[1],l=this._basisCols[2];BABYLON.Matrix.FromValuesToRef(a.x,a.y,a.z,0,s.x,s.y,s.z,0,l.x,l.y,l.z,0,0,0,0,1,this._sm1),this._sm1.multiplyToRef(this._sm3,this._sm4),this._sm4.multiplyToRef(this._sm2,this._sm1),n.raycastInfo.wheelDirectionWS.scaleToRef(n.raycastInfo.suspensionLength,this._sv4),this._sv4.addInPlace(n.raycastInfo.hardPointWS),n.worldTransformPosition.copyFrom(this._sv4),this._sm1.setTranslationFromFloats(this._sv4.x,this._sv4.y,this._sv4.z),BABYLON.Quaternion.FromRotationMatrixToRef(this._sm1,n.worldTransformRotation)},n.prototype.rayCast=function(e,t){void 0===t&&(t=1),this.updateWheelTransformsWS(e,!1,t),this.setWheelContactFilters(e,0,0);var n=-1,i=e.getSuspensionRestLength()+e.wheelRadius;e.raycastInfo.wheelDirectionWS.scaleToRef(i,this._sv1);var r=e.raycastInfo.hardPointWS;r.addToRef(this._sv1,this._sv2),e.raycastInfo.contactPointWS.copyFrom(this._sv2);var o=this._sv2,a=this._vehicleRaycaster.castRay(r,o,this._rayResults);if(e.raycastInfo.groundObject=null,a&&this._rayResults.hitNormalInWorld.y<.5&&(a=null),a){var s=this._rayResults.distFraction;n=i*s;var l=s*i-e.wheelRadius,u=this._rayResults.hitNormalInWorld.x,c=this._rayResults.hitNormalInWorld.y,d=this._rayResults.hitNormalInWorld.z,h=l,p=u,m=c,f=d;this.raycastSmoothingEnabled&&(e._contactLossFrames=0,this.smoothRaycastHit(e,l,u,c,d),h=e._smoothedSuspensionLength,p=e._smoothedContactNormal.x,m=e._smoothedContactNormal.y,f=e._smoothedContactNormal.z),e.raycastInfo.contactNormalWS.set(p,m,f),e.raycastInfo.isInContact=!0,e.raycastInfo.groundObject=a,e.raycastInfo.suspensionLength=h,this.setWheelContactFilters(e,this._rayResults.filterCollideMask,this._rayResults.filterMembershipMask);var g=e.getSuspensionRestLength()-.01*e.maxSuspensionTravelCm,v=e.getSuspensionRestLength()+.01*e.maxSuspensionTravelCm;e.raycastInfo.suspensionLength<g&&(e.raycastInfo.suspensionLength=g),e.raycastInfo.suspensionLength>v&&(e.raycastInfo.suspensionLength=v),e.raycastInfo.contactPointWS.copyFrom(this._rayResults.hitPointInWorld);var y=BABYLON.Vector3.Dot(e.raycastInfo.contactNormalWS,e.raycastInfo.wheelDirectionWS);this.velocityAtWorldPoint(this._chassisBody,e.raycastInfo.contactPointWS,this._sv3);var _=BABYLON.Vector3.Dot(e.raycastInfo.contactNormalWS,this._sv3),S=this.minContactDotSuspension;if(y>=-S)e.suspensionRelativeVelocity=0,e.clippedInvContactDotSuspension=1/S;else{var A=-1/y;e.suspensionRelativeVelocity=_*A,e.clippedInvContactDotSuspension=A}}else e.raycastInfo.suspensionLength=e.getSuspensionRestLength(),e.suspensionRelativeVelocity=0,e.raycastInfo.contactNormalWS.copyFrom(e.raycastInfo.wheelDirectionWS).scaleInPlace(-1),e.clippedInvContactDotSuspension=1,this.setWheelContactFilters(e,0,0),this.raycastSmoothingEnabled&&(e._contactLossFrames++,e._contactLossFrames>this.raycastContactLossGraceFrames&&(e._rayHistoryCount=0,e._rayHistoryIndex=0,e._smoothedSuspensionLength=-1,e._smoothedContactNormalValid=!1,e._prevSuspensionLength=-1));return n},n.prototype.smoothRaycastHit=function(e,t,n,i,r){var o=0|this.raycastHistoryBufferSize;o<2&&(o=2),e._rayHistoryLengths.length!==o&&(e._rayHistoryLengths=new Array(o),e._rayHistoryNormalsX=new Array(o),e._rayHistoryNormalsY=new Array(o),e._rayHistoryNormalsZ=new Array(o),e._rayHistoryCount=0,e._rayHistoryIndex=0),e._rayHistoryLengths[e._rayHistoryIndex]=t,e._rayHistoryNormalsX[e._rayHistoryIndex]=n,e._rayHistoryNormalsY[e._rayHistoryIndex]=i,e._rayHistoryNormalsZ[e._rayHistoryIndex]=r,e._rayHistoryIndex=(e._rayHistoryIndex+1)%o,e._rayHistoryCount<o&&e._rayHistoryCount++;var a=t;if(this.raycastOutlierRejectionEnabled&&e._rayHistoryCount>=3){var s=e._rayHistoryCount;this._raycastMedianScratch.length!==s&&(this._raycastMedianScratch=new Array(s));for(var l=0;l<s;l++)this._raycastMedianScratch[l]=e._rayHistoryLengths[l];this._raycastMedianScratch.sort(function(e,t){return e-t});var u=s%2==1?this._raycastMedianScratch[s-1>>1]:.5*(this._raycastMedianScratch[(s>>1)-1]+this._raycastMedianScratch[s>>1]),c=this.raycastOutlierThresholdMeters;c>0&&(a>u+c?a=u+c:a<u-c&&(a=u-c))}if(e._smoothedSuspensionLength<0)e._smoothedSuspensionLength=a;else{var d=a<e._smoothedSuspensionLength?this.raycastLengthCompressionAlpha:this.raycastLengthRelaxationAlpha;d<0?d=0:d>1&&(d=1),e._smoothedSuspensionLength=e._smoothedSuspensionLength*(1-d)+a*d}if(this.raycastMaxLengthChangePerSecond>0&&e._prevSuspensionLength>=0){var h=this.raycastMaxLengthChangePerSecond*(1/60),p=e._smoothedSuspensionLength-e._prevSuspensionLength;p>h?e._smoothedSuspensionLength=e._prevSuspensionLength+h:p<-h&&(e._smoothedSuspensionLength=e._prevSuspensionLength-h)}if(e._prevSuspensionLength=e._smoothedSuspensionLength,e._smoothedContactNormalValid){var m=this.raycastNormalSmoothingAlpha;m<0?m=0:m>1&&(m=1);var f=1-m,g=e._smoothedContactNormal.x*f+n*m,v=e._smoothedContactNormal.y*f+i*m,y=e._smoothedContactNormal.z*f+r*m,_=Math.sqrt(g*g+v*v+y*y);if(_>1e-6){var S=1/_;e._smoothedContactNormal.set(g*S,v*S,y*S)}else e._smoothedContactNormal.set(n,i,r)}else e._smoothedContactNormal.set(n,i,r),e._smoothedContactNormalValid=!0},n.prototype.getGravityUpToRef=function(e){var t=null!=this._chassisBody.transformNode?this._chassisBody.transformNode.getScene():null;if(null!=t&&null!=t.gravity){var n=t.gravity;if(n.lengthSquared()>1e-8)return e.copyFrom(n).scaleInPlace(-1),void e.normalize()}e.set(0,1,0)},n.prototype.computeStabilizationUpVector=function(e,t,n){if(n.set(0,0,0),t>0){for(var i=0;i<this._wheelInfo.length;i++){var r=this._wheelInfo[i];r.raycastInfo.isInContact&&n.addInPlace(r.raycastInfo.contactNormalWS)}if(n.lengthSquared()>1e-8){if(n.scaleInPlace(1/t),n.normalize(),this._stabilizationHasGroundNormal&&this.stabilizationNormalSmoothing>0){var o=BABYLON.Scalar.Clamp(this.stabilizationNormalSmoothing,0,.999),a=1-o;n.x=n.x*a+this._stabilizationGroundNormal.x*o,n.y=n.y*a+this._stabilizationGroundNormal.y*o,n.z=n.z*a+this._stabilizationGroundNormal.z*o,n.normalize()}return this._stabilizationGroundNormal.copyFrom(n),this._stabilizationHasGroundNormal=!0,void(this._stabilizationAirborneTime=0)}}this._stabilizationAirborneTime+=e,this._stabilizationHasGroundNormal&&(this.airborneGroundNormalHoldTime<=0||this._stabilizationAirborneTime<=this.airborneGroundNormalHoldTime)?n.copyFrom(this._stabilizationGroundNormal):this.getGravityUpToRef(n)},n.prototype.applyFlyingStabilization=function(e,t){if(!(e<=0||this.smoothFlyingImpulse<=0)){var n=this._chassisTransform.m,i=this._indexRightAxis,r=this._indexUpAxis,o=this._indexForwardAxis;this._stb1.set(n[4*i],n[4*i+1],n[4*i+2]),this._stb2.set(n[4*r],n[4*r+1],n[4*r+2]),this._stb3.set(n[4*o],n[4*o+1],n[4*o+2]),this._chassisBody.getAngularVelocityToRef(this._stb4);var a=BABYLON.Vector3.Dot(this._stb4,this._stb1),s=BABYLON.Vector3.Dot(this._stb4,this._stb2),l=BABYLON.Vector3.Dot(this._stb4,this._stb3),u=(BABYLON.Scalar.Clamp(BABYLON.Vector3.Dot(this._stb2,t),-1,1),BABYLON.Scalar.Clamp(1-Math.exp(-this.smoothFlyingImpulse*e),0,.95));a*=1-u,l*=1-u,BABYLON.Vector3.CrossToRef(this._stb2,t,this._stb5);var c=this._stb5.lengthSquared();this._stb4.set(this._stb1.x*a+this._stb2.x*s+this._stb3.x*l,this._stb1.y*a+this._stb2.y*s+this._stb3.y*l,this._stb1.z*a+this._stb2.z*s+this._stb3.z*l),c>1e-8&&(this._stb5.scaleInPlace(this.smoothFlyingImpulse*e),this._stb4.addInPlace(this._stb5)),this._chassisBody.setAngularVelocity(this._stb4)}},n.prototype.applyGroundedAutoLevel=function(e,t,n,i){if(!this.groundedAutoLevelEnabled||e<=0)this._groundedAutoLevelWasActive=!1;else{var r=this._wheelInfo.length;if(r<=0||t<=0)this._groundedAutoLevelWasActive=!1;else{var o=this._chassisTransform.m,a=this._indexRightAxis,s=this._indexUpAxis,l=this._indexForwardAxis;this._stb1.set(o[4*a],o[4*a+1],o[4*a+2]),this._stb2.set(o[4*s],o[4*s+1],o[4*s+2]),this._stb3.set(o[4*l],o[4*l+1],o[4*l+2]),this.getGravityUpToRef(this._stb4);var u=BABYLON.Scalar.Clamp(BABYLON.Vector3.Dot(n,this._stb4),-1,1),c=1;if(u<1){var d=BABYLON.Scalar.Clamp(this.groundedAutoLevelTrackNormalMinDot,-1,.999);c=BABYLON.Scalar.Clamp((u-d)/(1-d),0,1)}this._stb5.set(this._stb4.x*(1-c)+n.x*c,this._stb4.y*(1-c)+n.y*c,this._stb4.z*(1-c)+n.z*c),this._stb5.lengthSquared()<=1e-8?this._stb5.copyFrom(this._stb4):this._stb5.normalize();var h=BABYLON.Scalar.Clamp(BABYLON.Vector3.Dot(this._stb2,this._stb5),-1,1),p=BABYLON.Scalar.Clamp(this.groundedAutoLevelDeadzoneDeg,0,89),m=BABYLON.Scalar.Clamp(Math.min(this.groundedAutoLevelSettleDeg,p),0,p),f=BABYLON.Scalar.Clamp(this.groundedAutoLevelHysteresisDeg,0,m),g=p*Math.PI/180,v=m*Math.PI/180,y=f*Math.PI/180,_=Math.min(v+y,g),S=Math.max(v-y,0),A=this._groundedAutoLevelWasActive?S:_,b=Math.acos(h);if(b<=A)this._groundedAutoLevelWasActive=!1;else if(BABYLON.Vector3.CrossToRef(this._stb2,this._stb5,this._stb4),this._stb4.lengthSquared()<=1e-8)this._groundedAutoLevelWasActive=!1;else{var M=Math.abs(this._currentVehicleSpeedKmHour),B=1,C=this.groundedAutoLevelFullKmh-this.groundedAutoLevelStartKmh;C>0?B=BABYLON.Scalar.Clamp((M-this.groundedAutoLevelStartKmh)/C,0,1):M<this.groundedAutoLevelStartKmh&&(B=0);var T=this.groundedAutoLevelStrength*(.45+.55*B);if(t<r&&(T*=this.groundedAutoLevelPartialContactBoost),i&&(T*=this.groundedAutoLevelSlideScale),T<=0)this._groundedAutoLevelWasActive=!1;else{var x=this.groundedAutoLevelMaxRate,I=0;if(b<=g){var O=Math.max(g-A,.05),L=BABYLON.Scalar.Clamp((b-A)/O,0,1);I=T*BABYLON.Scalar.Clamp(this.groundedAutoLevelSettleScale,0,1)*(.4+.6*L),x*=.35+.45*L}else{var w=Math.max(20*Math.PI/180-g,.05);I=T*(.35+.65*BABYLON.Scalar.Clamp((b-g)/w,0,1))}if(I<=1e-4)this._groundedAutoLevelWasActive=!1;else{this._chassisBody.getAngularVelocityToRef(this._sv9);var N=BABYLON.Vector3.Dot(this._sv9,this._stb1),P=BABYLON.Vector3.Dot(this._sv9,this._stb2),R=BABYLON.Vector3.Dot(this._sv9,this._stb3),E=BABYLON.Scalar.Clamp(BABYLON.Vector3.Dot(this._stb4,this._stb1)*I,-x,x),k=BABYLON.Scalar.Clamp(BABYLON.Vector3.Dot(this._stb4,this._stb3)*I,-x,x),D=BABYLON.Scalar.Clamp(1-Math.exp(-I*e),0,.85);N+=(E-N)*D,R+=(k-R)*D,this._sv9.set(this._stb1.x*N+this._stb2.x*P+this._stb3.x*R,this._stb1.y*N+this._stb2.y*P+this._stb3.y*R,this._stb1.z*N+this._stb2.z*P+this._stb3.z*R),this._chassisBody.setAngularVelocity(this._sv9),this._groundedAutoLevelWasActive=!0}}}}}},n.prototype.applyTrackConnectionAndDownforce=function(e,t,n){if(!(e<=0||this._chassisMass<=0)){var i=this._wheelInfo.length;if(!(i<=0)){var r=9.81,o=null!=this._chassisBody.transformNode?this._chassisBody.transformNode.getScene():null;if(null!=o&&null!=o.gravity){var a=o.gravity.length();a>1e-4&&(r=a)}this._chassisBody.getObjectCenterWorldToRef(this._sv7);var s=Math.abs(this._currentVehicleSpeedKmHour),l=s/3.6;if(this.trackConnectionAccel>0&&t<i){var u=(i-t)/i,c=this.trackConnectionAccel;if(0===t&&this.airborneTrackConnectionMaxAccel>c){var d=1,h=this.airborneTrackConnectionFullKmh-this.airborneTrackConnectionStartKmh;h>0?d=BABYLON.Scalar.Clamp((s-this.airborneTrackConnectionStartKmh)/h,0,1):s<this.airborneTrackConnectionStartKmh&&(d=0),c+=(this.airborneTrackConnectionMaxAccel-c)*d}var p=c*this._chassisMass*u;n.scaleToRef(-p*e,this._sv1),this._chassisBody.applyImpulse(this._sv1,this._sv7)}if(t<=0){if(this.airborneRiseDamping>0||this.airborneMaxRiseSpeed>0){this._chassisBody.getLinearVelocityToRef(this._sv8);var m=BABYLON.Vector3.Dot(this._sv8,n);if(m>0){var f=0;if(this.airborneRiseDamping>0&&(f+=m*BABYLON.Scalar.Clamp(1-Math.exp(-this.airborneRiseDamping*e),0,.95)),this.airborneMaxRiseSpeed>0){var g=m-f;g>this.airborneMaxRiseSpeed&&(f+=g-this.airborneMaxRiseSpeed)}if((f=BABYLON.Scalar.Clamp(f,0,m))>1e-4){var v=f*this._chassisMass;n.scaleToRef(-v,this._sv1),this._chassisBody.applyImpulse(this._sv1,this._sv7)}}}}else{if(this.constantDownforce>0){var y=this._chassisMass*r*this.constantDownforce;n.scaleToRef(-y*e,this._sv1),this._chassisBody.applyImpulse(this._sv1,this._sv7)}if(this.downforceCoefficient>0&&l>1){var _=this.downforceCoefficient*l*l;n.scaleToRef(-_*e,this._sv1),this._chassisBody.applyImpulse(this._sv1,this._sv7)}}}}},n.prototype.updateVehicle=function(t){var n=this._wheelInfo.length;t>1/30&&(t=1/30),this.getChassisWorldTransform();for(var i=0;i<n;i++)this.updateWheelTransform(i,!1);this._chassisBody.getLinearVelocityToRef(this._sv1),this._currentVehicleSpeedKmHour=3.6*Math.sqrt(this._sv1.x*this._sv1.x+this._sv1.y*this._sv1.y+this._sv1.z*this._sv1.z);var r=this._chassisTransform.m,o=this._indexForwardAxis;this._sv2.set(r[4*o],r[4*o+1],r[4*o+2]),BABYLON.Vector3.Dot(this._sv2,this._sv1)<0&&(this._currentVehicleSpeedKmHour*=-1),this.raycastDebugLogEnabled&&this._raycastDebugFrameCounter++;var a=0;for(i=0;i<n;i++){var s=this._wheelInfo[i];this.rayCast(s);var l=s.raycastInfo.isInContact;l||!0!==this.enableMultiRaycast||(this.rayCast(s,.95),l=s.raycastInfo.isInContact),l&&a++}this.computeStabilizationUpVector(t,a,this._sv10),0===a&&this.smoothFlyingImpulse>0&&this.applyFlyingStabilization(t,this._sv10);var u=Math.abs(this._currentVehicleSpeedKmHour),c=this.isArcadeHandBrakeActive||this.isArcadeWheelSkidActive||this.isArcadeBurnoutModeActive||this.isArcadeDonutModeActive;if(this.sideToSideStabilityEnabled&&a>0&&u>this.sideToSideStabilityStartKmh&&!c){var d=this.sideToSideStabilityFullKmh-this.sideToSideStabilityStartKmh;d>0&&Math.min((u-this.sideToSideStabilityStartKmh)/d,1)}e.RigidbodyPhysics.SetAngularFactor(this._chassisBody,this.angularDamping.x,1,this.angularDamping.z),this.applyGroundedAutoLevel(t,a,this._sv10,c),this.applyHandbrakeYawAssist(t,u,this._currentVehicleSpeedKmHour),this.applyEasyDonutYawAssist(t,u,this._currentVehicleSpeedKmHour),this.updateSuspension(t);var h=0,p=0;for(this._sv6.set(0,0,0),i=0;i<n;i++)if((s=this._wheelInfo[i]).raycastInfo.isInContact){var m=s.suspensionForce;m>s.maxSuspensionForce&&(m=s.maxSuspensionForce),h+=m,this._sv6.addInPlace(s.raycastInfo.contactNormalWS),p++}for(p>0&&(h/=p,this._sv6.scaleInPlace(1/p),this._sv6.normalize()),this._chassisBody.getObjectCenterWorldToRef(this._sv5),p>0&&(this._sv6.scaleToRef(h*t*p,this._sv1),this._chassisBody.applyImpulse(this._sv1,this._sv5)),i=0;i<n;i++)if((s=this._wheelInfo[i]).raycastInfo.isInContact){var f=s.suspensionForce;f>s.maxSuspensionForce&&(f=s.maxSuspensionForce);var g=f-h;0!==g&&(s.raycastInfo.contactNormalWS.scaleToRef(g*t,this._sv1),this._chassisBody.applyImpulse(this._sv1,s.raycastInfo.contactPointWS))}this.updateFriction(t),this.updateArcadeWheelRotationBoost(t),this.applyTrackConnectionAndDownforce(t,a,this._sv10);for(var v=!0===this.isArcadeBurnoutModeActive||!0===this.isArcadeDonutModeActive||!0===this.isArcadeHandBrakeActive||!0===this.isArcadeWheelSkidActive,y=!1,_=0;_<n;_++)if(Math.abs(this._wheelInfo[_].engineForce)>1e-4){y=!0;break}var S=this.wheelAtRestSpeedThresholdKmh>0&&Math.abs(this._currentVehicleSpeedKmHour)<this.wheelAtRestSpeedThresholdKmh&&(!v||!y);for(i=0;i<n;i++){s=this._wheelInfo[i];var A=0;if(this.velocityAtWorldPoint(this._chassisBody,s.raycastInfo.hardPointWS,this._sv1),s.raycastInfo.isInContact){this._sv2.set(r[4*o],r[4*o+1],r[4*o+2]);var b=BABYLON.Vector3.Dot(this._sv2,s.raycastInfo.contactNormalWS);s.raycastInfo.contactNormalWS.scaleToRef(b,this._sv3),this._sv2.subtractInPlace(this._sv3),A=BABYLON.Vector3.Dot(this._sv2,this._sv1)/s.wheelRadius}if(!0!==S){var M=this.getWheelAngularVelocity(i,A,t,s.raycastInfo.isInContact);s.deltaRotation=M*t,s.rotation+=s.deltaRotation,s.deltaRotation*=.99}else s.rotationBoost=0,s.deltaRotation=0}this.clampChassisYawRate(t)},n.prototype.updateSuspension=function(e){for(var t=this._chassisMass,n=0;n<this._wheelInfo.length;n++){var i=this._wheelInfo[n];if(i.raycastInfo.isInContact){var r,o=i.getSuspensionRestLength()-i.raycastInfo.suspensionLength;r=i.suspensionStiffness*o*i.clippedInvContactDotSuspension;var a,s=i.suspensionRelativeVelocity;if(a=s<0?i.dampingCompression:i.dampingRelaxation,1!==this.suspensionDampingOverdrive&&(a*=this.suspensionDampingOverdrive),r-=a*s,i.suspensionForce=r*t,i.suspensionForce<0&&(i.suspensionForce=0),this.suspensionForceSmoothing>0&&i._prevSuspensionForce>=0){var l=this.suspensionForceSmoothing;i.suspensionForce=i.suspensionForce*(1-l)+i._prevSuspensionForce*l}i._prevSuspensionForce=i.suspensionForce}else this.trackConnectionAccel>0?i.suspensionForce=-this.trackConnectionAccel*t:i.suspensionForce=0,i._prevSuspensionForce=-1}},n.prototype.getSteeringAuthorityInput=function(){var e=BABYLON.Scalar.Clamp(this.currentSteeringInput,-1,1);if(Math.abs(e)>.001)return e;var t=this.getSignedFrontSteeringAngleRad();return BABYLON.Scalar.Clamp(t/.6,-1,1)},n.prototype.getSteeringMagnitude=function(){return Math.abs(this.getSteeringAuthorityInput())},n.prototype.applyEasyDonutYawAssist=function(e,t,n){if(!0!==this.isArcadeDonutModeActive)return this._arcadeDonutHoldElapsedSec=0,void(this._arcadeDonutDirectionSign=0);if(!0===this.arcadeDonutDirectYawEnabled){var i=this.getSignedFrontSteeringAngleRad();if(Math.abs(i)<=.02||this.arcadeSteeringAssist<=0)this._arcadeDonutHoldElapsedSec+=e;else{var r=this.arcadeDonutDirectYawDurationMs>0?this.arcadeDonutDirectYawDurationMs/1e3:0,o=this.arcadeDonutDirectYawFadeMs>0?this.arcadeDonutDirectYawFadeMs/1e3:0,a=this._arcadeDonutHoldElapsedSec,s=o>0?BABYLON.Scalar.Clamp(a/o,0,1):1,l=1;if(r>0){var u=r-a;u<=0?l=0:o>0&&u<o&&(l=u/o)}var c=Math.min(s,l);if(c<=0)this._arcadeDonutHoldElapsedSec+=e;else{var d=this._chassisTransform.m,h=this._indexForwardAxis,p=this._indexUpAxis,m=this._sv6,f=this._sv5;m.set(d[4*h],d[4*h+1],d[4*h+2]),f.set(d[4*p],d[4*p+1],d[4*p+2]),this._chassisBody.getLinearVelocityToRef(this._sv8);var g=BABYLON.Vector3.Dot(this._sv8,m),v=i>=0?1:-1;0===this._arcadeDonutDirectionSign&&(this._arcadeDonutDirectionSign=Math.abs(g)>.25?g>=0?1:-1:v);var y=BABYLON.Tools.ToRadians(this.arcadeDonutDirectYawDegPerSec)*this._arcadeDonutDirectionSign*v*c*this.arcadeSteeringAssist;if(Math.abs(y)<=1e-5)this._arcadeDonutHoldElapsedSec+=e;else{this._chassisBody.getAngularVelocityToRef(this._sv9);var _=BABYLON.Vector3.Dot(this._sv9,f),S=_+(y-_)*BABYLON.Scalar.Clamp(1-Math.exp(-14*e),0,1),A=.55*Math.abs(y);(Math.sign(S)!==Math.sign(y)||Math.abs(S)<A)&&(S=Math.sign(y)*A),f.scaleToRef(_,this._sv1),this._sv9.subtractToRef(this._sv1,this._sv2),f.scaleToRef(S,this._sv3),this._sv2.addToRef(this._sv3,this._sv9),this._chassisBody.setAngularVelocity(this._sv9),this._arcadeDonutHoldElapsedSec+=e}}}}},n.prototype.applyHandbrakeYawAssist=function(e,t,n){if(this.isArcadeYawAssistActive=!1,this.arcadeHandbrakeAssistEnabled){var i=this.getSteeringMagnitude(),r=this.getSteeringAuthorityInput();if(this.isArcadeHandBrakeActive&&!(i<.02)){var o=Math.max(0,t/3.6),a=BABYLON.Scalar.Clamp((o-.5)/3,0,1);if(!(a<=0)){var s=this._chassisTransform.m,l=this._indexRightAxis,u=this._indexUpAxis,c=this._indexForwardAxis;this._stb1.set(s[4*l],s[4*l+1],s[4*l+2]),this._stb2.set(s[4*u],s[4*u+1],s[4*u+2]),this._stb3.set(s[4*c],s[4*c+1],s[4*c+2]),this._chassisBody.getAngularVelocityToRef(this._sv9);var d=BABYLON.Vector3.Dot(this._sv9,this._stb1),h=BABYLON.Vector3.Dot(this._sv9,this._stb2),p=BABYLON.Vector3.Dot(this._sv9,this._stb3),m=this.getSignedFrontSteeringAngleRad();this.getApproxWheelbaseMeters()>.5&&o>.2&&Math.abs(m);var f=r*this.arcadeSteeringAssist*(.25+1*i)*a,g=Math.abs(0)>Math.abs(f)?0:f;if(g*h>=0&&Math.abs(h)>=Math.abs(g))this.isArcadeYawAssistActive=!0;else{var v=(.15+.35*i)*a,y=BABYLON.Scalar.Clamp(g*(2+4*i)*e,-v,v);Math.abs(y)<1e-6||(h+=y,this._sv9.set(this._stb1.x*d+this._stb2.x*h+this._stb3.x*p,this._stb1.y*d+this._stb2.y*h+this._stb3.y*p,this._stb1.z*d+this._stb2.z*h+this._stb3.z*p),this._chassisBody.setAngularVelocity(this._sv9),this.isArcadeYawAssistActive=!0)}}}}},n.prototype.resolveWheelSpinDirection=function(e,t,n){if(Math.abs(t)>1e-4)return t<0?-1:1;if(Math.abs(n)>1e-4)return n<0?-1:1;var i=this._wheelInfo[e];if(null!=i){if(Math.abs(i.deltaRotation)>1e-4)return i.deltaRotation<0?-1:1;if(Math.abs(i.rotationBoost)>1e-4)return i.rotationBoost<0?-1:1}return 0},n.prototype.updateArcadeWheelRotationBoost=function(e){for(var t=this.isArcadeBurnoutModeActive||this.isArcadeDonutModeActive,n=this.isArcadeBurnoutModeActive&&this.isArcadeHandBrakeActive&&Math.abs(this._currentVehicleSpeedKmHour)<=this.wheelAtRestSpeedThresholdKmh+2,i=BABYLON.Scalar.Clamp(e*this.arcadeWheelSpinBuildSpeed,0,1),r=0;r<this._wheelInfo.length;r++){var o=this._wheelInfo[r];this._arcadePreviousWheelSpin[r]=o.rotationBoost;var a=o.rotationBoost,s=0,l=o.defaultFriction>0?o.defaultFriction:o.frictionSlip,u=l>0?BABYLON.Scalar.Clamp(o.frictionSlip/l,0,1):1,c=o.engineForce*e,d=0;if(Math.abs(c)>1e-4&&r<this._forwardImpulse.length){var h=this._forwardImpulse[r];(c>0&&h>0||c<0&&h<0)&&(d=Math.sign(c)*Math.min(Math.abs(h),Math.abs(c)))}var p=Math.max(0,Math.abs(c)-Math.abs(d)),m=Math.abs(c)>1e-4?BABYLON.Scalar.Clamp(p/Math.abs(c),0,1):0,f=Math.max(0,o.suspensionForce*e*o.frictionSlip),g=o.raycastInfo.groundObject&&f>1e-4?BABYLON.Scalar.Clamp(Math.abs(this._sideImpulse[r])/f,0,1):0,v=BABYLON.Scalar.Clamp(1-o.skidInfo,0,1),y=this.resolveWheelSpinDirection(r,c,d);if(t&&0!==y&&Math.abs(c)>1e-4){var _=m,S=1;if(this.isArcadeBurnoutModeActive&&(_=Math.max(_,.65*v),S=Math.max(S,this.arcadeBurnoutWheelSpinGain),n&&(_=Math.max(_,1),S=Math.max(S,this.arcadeStationaryBurnoutWheelSpinGain))),this.isArcadeDonutModeActive&&(_=Math.max(_,.9*g,.5*v),S=Math.max(S,this.arcadeDonutWheelSpinGain)),o.raycastInfo.groundObject||(_=Math.max(_,1)),_>0){var A=p*this._chassisInvMass;if(o.raycastInfo.groundObject||(A=Math.max(A,Math.abs(c)*this._chassisInvMass)),s=y*(A/Math.max(o.wheelRadius,1e-4)/Math.max(e,1e-4))*S*BABYLON.Scalar.Lerp(.2,1,_),n){var b=Math.max(0,this.arcadeStationaryBurnoutMinAngularVelocity);Math.abs(s)<b&&(s=y*b)}}}if(Math.abs(s)>0){if(a*s<0){var M=BABYLON.Scalar.Clamp(e*this.arcadeWheelSpinRecoverySpeed*2,0,1);a=BABYLON.Scalar.Lerp(a,0,M)}a=BABYLON.Scalar.Lerp(a,s,i)}if(o.raycastInfo.groundObject){var B=Math.max(m,.5*v);this.isArcadeDonutModeActive&&(B=Math.max(B,g));var C=this.arcadeWheelSpinRecoverySpeed*(.25+.75*u)*(1-Math.min(B,.92));t||(C=this.arcadeWheelSpinRecoverySpeed*(.75+1.5*u));var T=BABYLON.Scalar.Clamp(e*C,0,1);a=BABYLON.Scalar.Lerp(a,0,T)}else a*=Math.pow(this.arcadeWheelSpinAirDamping,60*e);a=BABYLON.Scalar.Clamp(a,-this.arcadeWheelSpinMaxAngularVelocity,this.arcadeWheelSpinMaxAngularVelocity),Math.abs(this._currentVehicleSpeedKmHour)<1&&(!t||Math.abs(c)<=1e-4)&&(a=0),Math.abs(a)<.001&&(a=0),o.rotationBoost=a}},n.prototype.getWheelAngularVelocity=function(e,t,n,i){var r=this._wheelInfo[e];return null==r||n<=0?0:i?t+r.rotationBoost:r.deltaRotation/n-(e<this._arcadePreviousWheelSpin.length?this._arcadePreviousWheelSpin[e]:0)+r.rotationBoost},n.prototype.getArcadeBurnoutDirectionChangeFactor=function(e,t){if(!this.isArcadeBurnoutModeActive||null==e||Math.abs(e.engineForce)<=1e-4)return 0;var n=Math.max(0,this.arcadeBurnoutDirectionChangeSpeedKmh);if(n>0&&Math.abs(this._currentVehicleSpeedKmHour)>n)return 0;var i=-t*(e.engineForce<0?-1:1);if(i<=.15)return 0;var r=BABYLON.Scalar.Clamp((i-.15)/2.5,0,1);if(n<=0)return r;var o=1-BABYLON.Scalar.Clamp(Math.abs(this._currentVehicleSpeedKmHour)/n,0,1);return r*BABYLON.Scalar.Lerp(.45,1,o)},n.prototype.updateArcadeSkidInfo=function(e,t,n){var i=e<this._arcadeSkidInfo.length?this._arcadeSkidInfo[e]:1,r=BABYLON.Scalar.Clamp(t,0,1),o=r<i?this.wheelSkidFadeInSpeed:this.wheelSkidFadeOutSpeed,a=BABYLON.Scalar.Clamp(n*o,0,1);return i=BABYLON.Scalar.Lerp(i,r,a),Math.abs(i-r)<.001&&(i=r),this._arcadeSkidInfo[e]=i,i},n.prototype.updateFriction=function(e){var t=this._wheelInfo.length;if(0!==t){for(var n=0,i=0;i<t;i++)(le=this._wheelInfo[i]).raycastInfo.groundObject&&n++,this._sideImpulse[i]=0,this._forwardImpulse[i]=0;for(i=0;i<t;i++)if((le=this._wheelInfo[i]).raycastInfo.groundObject){var r=this._sv5;le.raycastInfo.wheelDirectionWS.negateToRef(r),BABYLON.Quaternion.RotationAxisToRef(r,le.steering,this._sq1),BABYLON.Matrix.FromQuaternionToRef(this._sq1,this._sm2),BABYLON.Vector3.TransformNormalToRef(le.raycastInfo.wheelAxleWS,this._sm2,this._axle[i]);var o=le.raycastInfo.contactNormalWS,a=BABYLON.Vector3.Dot(this._axle[i],o);if(o.scaleToRef(a,this._sv6),this._axle[i].subtractInPlace(this._sv6),this._axle[i].normalize(),BABYLON.Vector3.CrossToRef(o,this._axle[i],this._forwardWS[i]),this._forwardWS[i].normalize(),this._sideImpulse[i]=this.resolveSingleBilateral(this._chassisBody,le.raycastInfo.contactPointWS,this._axle[i]),this._sideImpulse[i]*=this.sideFrictionStiffness,this.arcadeSideSlipSaturationEnabled&&0!==this._sideImpulse[i]){this.velocityAtWorldPoint(this._chassisBody,le.raycastInfo.contactPointWS,this._sv8);var s=BABYLON.Vector3.Dot(this._axle[i],this._sv8),l=BABYLON.Vector3.Dot(this._forwardWS[i],this._sv8),u=s*s+l*l,c=this.arcadeSideSlipMinSpeedMps;if(u>c*c){var d=Math.atan2(Math.abs(s),Math.max(Math.abs(l),.001)),h=BABYLON.Tools.ToRadians(Math.max(this.arcadeSideSlipPeakDeg,.1));if(d>h){var p=Math.sin(h)/Math.max(Math.sin(d),.001),m=Math.max(this.arcadeSideSlipFalloffDeg-this.arcadeSideSlipPeakDeg,.1),f=Math.min(Math.max((BABYLON.Tools.ToDegrees(d)-this.arcadeSideSlipPeakDeg)/m,0),1),g=BABYLON.Scalar.Lerp(1,this.arcadeSideSlipFalloffFactor,f);this._sideImpulse[i]*=p*g}}}}for(var v=!1,y=0;y<t;y++){var _=0,S=1,A=!1,b=!1,M=0,B=0,C=0;if((le=this._wheelInfo[y]).raycastInfo.groundObject)if(0!==le.engineForce)_=le.engineForce*e;else{var T=le.brake?le.brake:0;_=this.calcRollingFriction(this._chassisBody,le.raycastInfo.contactPointWS,this._forwardWS[y],T,n)}if(this._forwardImpulse[y]=0,this._wheelInfo[y].skidInfo=1,le.raycastInfo.groundObject){this._wheelInfo[y].skidInfo=1;var x=le.suspensionForce*e*le.frictionSlip,I=x*x;this._forwardImpulse[y]=_;var O=.5*this._forwardImpulse[y],L=1*this._sideImpulse[y],w=O*O+L*L,N=Math.sqrt(w);if(w>I){v=!0;var P=x/Math.sqrt(w);this._wheelInfo[y].skidInfo*=P}if(b=(A=(this.isArcadeHandBrakeActive||this.isArcadeWheelSkidActive)&&le.brake>0&&0===le.engineForce)||this.isArcadeWheelSkidActive||this.isArcadeBurnoutModeActive||this.isArcadeDonutModeActive){this.velocityAtWorldPoint(this._chassisBody,le.raycastInfo.contactPointWS,this._sv3);var R=BABYLON.Vector3.Dot(this._forwardWS[y],this._sv3);M=Math.abs(R),B=Math.abs(BABYLON.Vector3.Dot(this._axle[y],this._sv3)),C=this.getArcadeBurnoutDirectionChangeFactor(le,R)}if(this.isArcadeBurnoutModeActive&&x>0){var E=x;C>0&&(E*=BABYLON.Scalar.Lerp(1,this.arcadeBurnoutDirectionChangeGripScale,C));var k=Math.abs(this._forwardImpulse[y]);if(k>E){var D=E/k;this._forwardImpulse[y]*=D,this._wheelInfo[y].skidInfo=Math.min(this._wheelInfo[y].skidInfo,D),v=!0}if(C>0){var F=BABYLON.Scalar.Lerp(.18,.02,C);this._wheelInfo[y].skidInfo=Math.min(this._wheelInfo[y].skidInfo,F),v=!0}}if(b){var U=BABYLON.Scalar.Clamp((Math.abs(this._currentVehicleSpeedKmHour)-2)/20,0,1),Y=BABYLON.Scalar.Clamp((M-.5)/6,0,1),V=BABYLON.Scalar.Clamp((B-.2)/4,0,1),G=x>0?BABYLON.Scalar.Clamp((N/x-.55)/.45,0,1):0,z=x>0?BABYLON.Scalar.Clamp(Math.abs(this._forwardImpulse[y])/x,0,1):0;if(A){var W=Math.max(Y,U);W>0&&(S=Math.min(S,BABYLON.Scalar.Lerp(.32,.02,W)))}if(this.isArcadeWheelSkidActive){var H=Math.max(G,V,.85*Y);H>0&&(S=Math.min(S,BABYLON.Scalar.Lerp(.34,.05,H)))}if(this.isArcadeBurnoutModeActive&&0!==le.engineForce){var X=Math.max(z,Y,.7*U);if(C>0&&(X=Math.max(X,C)),X>0){var K=le.isFrontWheel?.38:.28,Q=le.isFrontWheel?.12:.04;S=Math.min(S,BABYLON.Scalar.Lerp(K,Q,X))}if(C>0){var j=le.isFrontWheel?.24:.1,Z=le.isFrontWheel?.08:.02;S=Math.min(S,BABYLON.Scalar.Lerp(j,Z,C))}}if(this.isArcadeDonutModeActive){var q=Math.max(V,z,.9*U,.75*Y);if(le.isFrontWheel||(q=Math.max(q,.55*U)),q>0){var J=le.isFrontWheel?.42:.24,$=le.isFrontWheel?.16:.03;S=Math.min(S,BABYLON.Scalar.Lerp(J,$,q))}}}}var ee=this.updateArcadeSkidInfo(y,S,e);le.raycastInfo.groundObject&&(this._wheelInfo[y].skidInfo=Math.min(this._wheelInfo[y].skidInfo,ee))}if(v)for(y=0;y<t;y++)0!==this._sideImpulse[y]&&this._wheelInfo[y].skidInfo<1&&(this.isArcadeBurnoutModeActive||(this._forwardImpulse[y]*=this._wheelInfo[y].skidInfo),this._sideImpulse[y]*=this._wheelInfo[y].skidInfo);var te=0,ne=0;for(y=0;y<t;y++)this._wheelInfo[y].raycastInfo.groundObject&&0!==this._sideImpulse[y]&&(te+=this._sideImpulse[y],ne++);ne>0&&(te/=ne);var ie=0,re=Math.abs(this._currentVehicleSpeedKmHour);if(!(this.isArcadeHandBrakeActive||this.isArcadeWheelSkidActive||this.isArcadeBurnoutModeActive||this.isArcadeDonutModeActive)&&this.sideToSideStabilityEnabled&&re>this.sideToSideStabilityStartKmh){var oe=this.sideToSideStabilityFullKmh-this.sideToSideStabilityStartKmh;oe>0&&(ie=.7*Math.min((re-this.sideToSideStabilityStartKmh)/oe,1))}this._chassisBody.getObjectCenterWorldToRef(this._sv7);var ae=this._indexUpAxis,se=this._chassisTransform.m;for(this._sv2.set(se[4*ae],se[4*ae+1],se[4*ae+2]),y=0;y<t;y++){var le=this._wheelInfo[y];if(0!==this._forwardImpulse[y]&&(this._forwardWS[y].scaleToRef(this._forwardImpulse[y],this._sv1),this._chassisBody.applyImpulse(this._sv1,this._sv7)),0!==this._sideImpulse[y]){le.raycastInfo.contactPointWS.subtractToRef(this._sv7,this._sv1);var ue=BABYLON.Vector3.Dot(this._sv2,this._sv1);this._sv2.scaleToRef(ue*(1-le.rollInfluence),this._sv3),this._sv1.subtractInPlace(this._sv3),this._sv7.addToRef(this._sv1,this._sv4);var ce=this._sideImpulse[y]-te,de=te+ce*ie,he=ce*(1-ie);this._axle[y].scaleToRef(de,this._sv5),this._chassisBody.applyImpulse(this._sv5,this._sv7),0!==he&&(this._axle[y].scaleToRef(he,this._sv5),this._chassisBody.applyImpulse(this._sv5,this._sv4))}}}},n.prototype.velocityAtWorldPoint=function(e,t,n){e.getObjectCenterWorldToRef(this._vapCenter),t.subtractToRef(this._vapCenter,this._vapRelPos),e.getAngularVelocityToRef(this._vapAngVel),BABYLON.Vector3.CrossToRef(this._vapAngVel,this._vapRelPos,this._vapCross),e.getLinearVelocityToRef(this._vapLinVel),this._vapLinVel.addToRef(this._vapCross,n)},n.prototype.resolveSingleBilateral=function(e,t,n){return n.lengthSquared()>1.1?0:(this.velocityAtWorldPoint(e,t,this._rsbVel1),-.2*BABYLON.Vector3.Dot(n,this._rsbVel1)*this._chassisMass)},n.prototype.calcRollingFriction=function(e,t,n,i,r){this.velocityAtWorldPoint(e,t,this._crfVel1);var o=-BABYLON.Vector3.Dot(n,this._crfVel1)*this._chassisMass;return r>0&&(o/=r),o>i&&(o=i),o<-i&&(o=-i),o},n.prototype.clampChassisYawRate=function(e){if(!(this.maximumYawRateLow<=0&&this.maximumYawRateHigh<=0)){var t=!0===this.isArcadeHandBrakeActive||!0===this.isArcadeBurnoutModeActive||!0===this.isArcadeDonutModeActive;if(!(!0===t&&!0===this.isArcadeHandBrakeActive&&this.arcadeHandbrakeYawCapMultiplier<=0||!0===t&&!0===this.isArcadeBurnoutModeActive&&this.arcadeBurnoutYawCapMultiplier<=0||!0===t&&!0===this.isArcadeDonutModeActive&&this.arcadeDonutYawCapMultiplier<=0)){var n=BABYLON.Scalar.Lerp(this.maximumYawRateLow,this.maximumYawRateHigh,this.smoothedGradientSpeed);if(!0===t&&(!0===this.isArcadeHandBrakeActive&&(n*=this.arcadeHandbrakeYawCapMultiplier),!0===this.isArcadeBurnoutModeActive&&(n*=this.arcadeBurnoutYawCapMultiplier),!0===this.isArcadeDonutModeActive&&(n*=this.arcadeDonutYawCapMultiplier)),!(n<=0)){var i=BABYLON.Tools.ToRadians(n),r=this._chassisBody.getAngularVelocity();if(null!=r){var o=Math.abs(r.y);if(o>i)r.y=Math.sign(r.y)*i*.95,this._chassisBody.setAngularVelocity(r);else if(o>.85*i){var a=(o-.85*i)/(.15*i);r.y*=1-.15*a,this._chassisBody.setAngularVelocity(r)}}}}}},n.prototype.getNaturalWheelSlip=function(e){var t=!1;return null!=this._wheelInfo[e]&&(t=!!this._wheelInfo[e].raycastInfo.groundObject&&this._wheelInfo[e].skidInfo<.999&&!this.isArcadeHandBrakeActive&&!this.isArcadeBurnoutModeActive&&!this.isArcadeDonutModeActive),t},n.prototype.getSignedFrontSteeringAngleRad=function(){for(var e=0,t=0,n=0;n<this._wheelInfo.length;n++)this._wheelInfo[n].isFrontWheel&&(e+=this._wheelInfo[n].steering,t++);return t>0?e/t:0},n.prototype.getApproxWheelbaseMeters=function(){for(var e=0,t=0,n=0,i=0,r=0;r<this._wheelInfo.length;r++){var o=this._wheelInfo[r].chassisConnectionPointCS.z;this._wheelInfo[r].isFrontWheel?(e+=o,n++):(t+=o,i++)}return 0===n||0===i?2.5:Math.abs(e/n-t/i)},n.prototype.dispose=function(){this._chassisBody=null,this._vehicleRaycaster=null,this._wheelInfo.length=0,this._forwardWS.length=0,this._axle.length=0,this._forwardImpulse.length=0,this._sideImpulse.length=0,this._arcadeSkidInfo.length=0,this._arcadePreviousWheelSpin.length=0},n.FILTER_GROUP_ALL_COLLIDERS=4294967295,n.FILTER_GROUP_VEHICLE_COLLIDERS=1048576,n.FILTER_GROUP_BRIDGE_COLLIDERS=2097152,n.FILTER_GROUP_ROAD_COLLIDERS=4194304,n.FILTER_GROUP_GRASS_COLLIDERS=8388608,n.FILTER_GROUP_CURB_COLLIDERS=16777216,n.FILTER_GROUP_FENCE_COLLIDERS=33554432,n.FILTER_GROUP_ALL_VEHICLE_COLLIDERS=66060288,n.VEHICLE_MESH_TAG="Vehicle",n.BRIDGE_MESH_TAG="Bridge",n.ROAD_MESH_TAG="Road",n.GRASS_MESH_TAG="Grass",n.CURB_MESH_TAG="Curb",n.FENCE_MESH_TAG="Fence",n}();e.btRaycastVehicle=o}(i||(i={})),function(e){var t=function(){function e(){}return e.CreatePostProcess=function(e,t,n){var i,r=(null==n?void 0:n.lutA)||null,o=(null==n?void 0:n.lutB)||null,a=null!==(i=null==n?void 0:n.mix)&&void 0!==i?i:0,s=new BABYLON.PostProcess("lutBlend","\n precision highp float;\n varying vec2 vUV;\n uniform sampler2D textureSampler;\n uniform sampler2D lutA;\n uniform sampler2D lutB;\n uniform float mixVal;\n uniform float lutTileCountA; // number of tiles per row for LUT A\n uniform float lutTileCountB; // number of tiles per row for LUT B\n\n vec3 sampleLUT(in sampler2D lut, in vec3 color, in float tileCount) {\n if (tileCount <= 0.5) return color;\n float tc = floor(tileCount + 0.5);\n float tileSize = 1.0 / tc;\n\n // For normalized RGB [0..1], compute position in LUT\n float r = color.r;\n float g = color.g;\n float b = color.b;\n\n // Determine slice and tile coords\n float slice = b * (tc - 1.0);\n float sliceIndex = floor(slice + 0.5);\n\n float tx = mod(sliceIndex, tc);\n float ty = floor(sliceIndex / tc);\n\n vec2 uv = vec2(tx * tileSize + r * tileSize, ty * tileSize + g * tileSize);\n vec3 sampled = texture2D(lut, uv).rgb;\n return sampled;\n }\n\n void main(void) {\n vec4 sceneColor = texture2D(textureSampler, vUV);\n vec3 a = sceneColor.rgb;\n if (lutTileCountA <= 0.5 || lutTileCountB <= 0.5) {\n // No LUT size provided fallback to passthrough\n gl_FragColor = sceneColor;\n return;\n }\n vec3 colA = sampleLUT(lutA, a, lutTileCountA);\n vec3 colB = sampleLUT(lutB, a, lutTileCountB);\n vec3 outc = mix(colA, colB, mixVal);\n gl_FragColor = vec4(outc, sceneColor.a);\n }\n ",["mixVal","lutTileCountA","lutTileCountB"],["lutA","lutB"],1,t,BABYLON.Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1);function l(e,t){if(!e||!t)return 0;if(e%t===0)return Math.round(e/t);if(t%e===0)return Math.round(t/e);if(e===t){var n=Math.round(Math.sqrt(e));return n*n===e?n:Math.round(Math.sqrt(e))}return Math.round(Math.pow(e*t,1/3))}var u=0,c=0;return s.onApply=function(t){if(t.setFloat("mixVal",a),r&&"string"==typeof r){var n=new BABYLON.Texture(r,e,!0,!1,BABYLON.Texture.TRILINEAR_SAMPLINGMODE,void 0,void 0,void 0,!1);n.onLoadObservable.addOnce(function(){u=l(n.getSize?n.getSize().width:n.width,n.getSize?n.getSize().height:n.height)}),t.setTexture("lutA",n)}else if(r instanceof BABYLON.Texture){var i=r;u=l(i.getSize?i.getSize().width:i.width,i.getSize?i.getSize().height:i.height),t.setTexture("lutA",i)}if(o&&"string"==typeof o){var s=new BABYLON.Texture(o,e,!0,!1,BABYLON.Texture.TRILINEAR_SAMPLINGMODE,void 0,void 0,void 0,!1);s.onLoadObservable.addOnce(function(){c=l(s.getSize?s.getSize().width:s.width,s.getSize?s.getSize().height:s.height)}),t.setTexture("lutB",s)}else if(o instanceof BABYLON.Texture){var d=o;c=l(d.getSize?d.getSize().width:d.width,d.getSize?d.getSize().height:d.height),t.setTexture("lutB",d)}t.setFloat("lutTileCountA",u),t.setFloat("lutTileCountB",c)},s._detectedTileCountA=function(){return u},s._detectedTileCountB=function(){return c},s},e.prototype.getWGSLShaderCode=function(){return"\n [[group(0), binding(0)]] var textureSampler: texture_2d<f32>;\n [[group(0), binding(1)]] var textureSamplerSampler: sampler;\n [[group(0), binding(2)]] var lutA: texture_2d<f32>;\n [[group(0), binding(3)]] var lutASampler: sampler;\n [[group(0), binding(4)]] var lutB: texture_2d<f32>;\n [[group(0), binding(5)]] var lutBSampler: sampler;\n\n [[block]] struct Uniforms {\n mixVal: f32;\n lutTileCountA: f32;\n lutTileCountB: f32;\n };\n [[group(0), binding(6)]] var<uniform> uniforms: Uniforms;\n\n fn sampleLUT(lut: texture_2d<f32>, lutSamp: sampler, color: vec3<f32>, tileCount: f32) -> vec3<f32> {\n if (tileCount <= 0.5) { return color; }\n let tc = floor(tileCount + 0.5);\n let tileSize = 1.0 / tc;\n\n let r = color.r;\n let g = color.g;\n let b = color.b;\n\n let slice = b * (tc - 1.0);\n let sliceIndex = floor(slice + 0.5);\n\n let tx = sliceIndex % tc;\n let ty = floor(sliceIndex / tc);\n\n let uv = vec2<f32>(tx * tileSize + r * tileSize, ty * tileSize + g * tileSize);\n let sampled = textureSample(lut, lutSamp, uv).rgb;\n return sampled;\n }\n\n fn mainImage(vUV: vec2<f32>) -> vec4<f32> {\n let sceneColor = textureSample(textureSampler, textureSamplerSampler, vUV);\n let a = sceneColor.rgb;\n if (uniforms.lutTileCountA <= 0.5 || uniforms.lutTileCountB <= 0.5) {\n return sceneColor;\n }\n let colA = sampleLUT(lutA, lutASampler, a, uniforms.lutTileCountA);\n let colB = sampleLUT(lutB, lutBSampler, a, uniforms.lutTileCountB);\n let outc = mix(colA, colB, uniforms.mixVal);\n return vec4<f32>(outc, sceneColor.a);\n }\n "},e}();e.LUTBlendPlugin=t}(i||(i={})),function(e){var t=function(){function e(e){var t,n,i,r,o,a;this._distortionIntensity=null!==(t=null==e?void 0:e.distortionIntensity)&&void 0!==t?t:0,this._distortionIntensityX=null!==(n=null==e?void 0:e.distortionIntensityX)&&void 0!==n?n:0,this._distortionIntensityY=null!==(i=null==e?void 0:e.distortionIntensityY)&&void 0!==i?i:0,this._distortionCenterX=null!==(r=null==e?void 0:e.distortionCenterX)&&void 0!==r?r:.5,this._distortionCenterY=null!==(o=null==e?void 0:e.distortionCenterY)&&void 0!==o?o:.5,this._distortionScale=null!==(a=null==e?void 0:e.distortionScale)&&void 0!==a?a:1,this._updateEnabledState()}return Object.defineProperty(e.prototype,"distortionIntensity",{get:function(){return this._distortionIntensity},set:function(e){this._distortionIntensity!==e&&(this._distortionIntensity=e,this._updateEnabledState())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"distortionIntensityX",{get:function(){return this._distortionIntensityX},set:function(e){this._distortionIntensityX!==e&&(this._distortionIntensityX=e,this._updateEnabledState())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"distortionIntensityY",{get:function(){return this._distortionIntensityY},set:function(e){this._distortionIntensityY!==e&&(this._distortionIntensityY=e,this._updateEnabledState())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"distortionCenterX",{get:function(){return this._distortionCenterX},set:function(e){this._distortionCenterX=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"distortionCenterY",{get:function(){return this._distortionCenterY},set:function(e){this._distortionCenterY=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"distortionScale",{get:function(){return this._distortionScale},set:function(e){this._distortionScale=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isEnabled",{get:function(){return this._isEnabled},enumerable:!1,configurable:!0}),e.prototype._updateEnabledState=function(){this._isEnabled=0!==this._distortionIntensity||0!==this._distortionIntensityX||0!==this._distortionIntensityY},e.prototype.getUniforms=function(){return{distortionIntensity:{type:"float",value:this._distortionIntensity},distortionIntensityX:{type:"float",value:this._distortionIntensityX},distortionIntensityY:{type:"float",value:this._distortionIntensityY},distortionCenter:{type:"vec2",value:[this._distortionCenterX,this._distortionCenterY]},distortionScale:{type:"float",value:this._distortionScale}}},e.prototype.getFragmentShaderCode=function(){return"\n uniform float distortionIntensity;\n uniform float distortionIntensityX;\n uniform float distortionIntensityY;\n uniform vec2 distortionCenter;\n uniform float distortionScale;\n\n void applyLensDistortion(inout vec4 color, vec2 uv) {\n // Calculate UV coordinates relative to center\n vec2 uvCentered = uv - distortionCenter;\n\n // Apply different distortion for X and Y if specified\n float intensityX = distortionIntensity + distortionIntensityX;\n float intensityY = distortionIntensity + distortionIntensityY;\n\n // Calculate distortion amount based on distance from center\n float r = length(uvCentered);\n float r2 = r * r;\n\n // Barrel distortion formula: r' = r * (1 + k1 * r^2 + k2 * r^4 + ...)\n // For simplicity, we use a quadratic approximation\n float distortion = 1.0 + intensityX * r2 + intensityY * r2 * r2;\n\n // Scale the distortion\n distortion *= distortionScale;\n\n // Apply distortion to UV coordinates\n vec2 distortedUV = distortionCenter + uvCentered * distortion;\n\n // Ensure UV coordinates stay within bounds\n distortedUV = clamp(distortedUV, vec2(0.0), vec2(1.0));\n\n // Sample the texture at the distorted position\n vec4 distortedColor = texture2D(diffuseSampler, distortedUV);\n\n // Mix with original color based on distortion strength\n float mixFactor = clamp(abs(distortionIntensity) + abs(distortionIntensityX) + abs(distortionIntensityY), 0.0, 1.0);\n color = mix(color, distortedColor, mixFactor);\n }\n "},e.prototype.getWGSLShaderCode=function(){return"\n [[group(0), binding(0)]] var diffuseSampler: texture_2d<f32>;\n [[group(0), binding(1)]] var diffuseSamplerSampler: sampler;\n\n struct Uniforms {\n distortionIntensity: f32;\n distortionIntensityX: f32;\n distortionIntensityY: f32;\n distortionCenter: vec2<f32>;\n distortionScale: f32;\n };\n\n [[group(0), binding(2)]] var<uniform> uniforms: Uniforms;\n\n fn applyLensDistortion(color: ptr<function, vec4<f32>>, uv: vec2<f32>) {\n // Calculate UV coordinates relative to center\n let uvCentered = uv - uniforms.distortionCenter;\n\n // Apply different distortion for X and Y if specified\n let intensityX = uniforms.distortionIntensity + uniforms.distortionIntensityX;\n let intensityY = uniforms.distortionIntensity + uniforms.distortionIntensityY;\n\n // Calculate distortion amount based on distance from center\n let r = length(uvCentered);\n let r2 = r * r;\n\n // Barrel distortion formula: r' = r * (1 + k1 * r^2 + k2 * r^4 + ...)\n let distortion = 1.0 + intensityX * r2 + intensityY * r2 * r2;\n\n // Scale the distortion\n let distortion_scaled = distortion * uniforms.distortionScale;\n\n // Apply distortion to UV coordinates\n let distortedUV = uniforms.distortionCenter + uvCentered * distortion_scaled;\n\n // Ensure UV coordinates stay within bounds\n let clampedUV = clamp(distortedUV, vec2<f32>(0.0), vec2<f32>(1.0));\n\n // Sample the texture at the distorted position\n let distortedColor = textureSample(diffuseSampler, diffuseSamplerSampler, clampedUV);\n\n // Mix with original color based on distortion strength\n let mixFactor = clamp(abs(uniforms.distortionIntensity) + abs(uniforms.distortionIntensityX) + abs(uniforms.distortionIntensityY), 0.0, 1.0);\n *color = mix(*color, distortedColor, mixFactor);\n }\n "},e.CreatePostProcess=function(e,t,n){var i,r,o,a,s,l,u={distortionIntensity:null!==(i=null==n?void 0:n.distortionIntensity)&&void 0!==i?i:0,distortionIntensityX:null!==(r=null==n?void 0:n.distortionIntensityX)&&void 0!==r?r:0,distortionIntensityY:null!==(o=null==n?void 0:n.distortionIntensityY)&&void 0!==o?o:0,distortionCenterX:null!==(a=null==n?void 0:n.distortionCenterX)&&void 0!==a?a:.5,distortionCenterY:null!==(s=null==n?void 0:n.distortionCenterY)&&void 0!==s?s:.5,distortionScale:null!==(l=null==n?void 0:n.distortionScale)&&void 0!==l?l:1},c=new BABYLON.PostProcess("lensDistortion","\n precision highp float;\n\n uniform float distortionIntensity;\n uniform float distortionIntensityX;\n uniform float distortionIntensityY;\n uniform vec2 distortionCenter;\n uniform float distortionScale;\n\n varying vec2 vUV;\n uniform sampler2D textureSampler;\n\n void main(void) {\n // Calculate UV coordinates relative to center\n vec2 uvCentered = vUV - distortionCenter;\n\n // Apply different distortion for X and Y if specified\n float intensityX = distortionIntensity + distortionIntensityX;\n float intensityY = distortionIntensity + distortionIntensityY;\n\n // Calculate distortion amount based on distance from center\n float r = length(uvCentered);\n float r2 = r * r;\n\n // Barrel distortion formula: r' = r * (1 + k1 * r^2 + k2 * r^4 + ...)\n float distortion = 1.0 + intensityX * r2 + intensityY * r2 * r2;\n\n // Scale the distortion\n distortion *= distortionScale;\n\n // Apply distortion to UV coordinates\n vec2 distortedUV = distortionCenter + uvCentered * distortion;\n\n // Ensure UV coordinates stay within bounds\n distortedUV = clamp(distortedUV, vec2(0.0), vec2(1.0));\n\n // Sample the texture at the distorted position\n vec4 distortedColor = texture2D(textureSampler, distortedUV);\n\n // Mix with original color based on distortion strength\n float mixFactor = clamp(abs(distortionIntensity) + abs(distortionIntensityX) + abs(distortionIntensityY), 0.0, 1.0);\n gl_FragColor = mix(texture2D(textureSampler, vUV), distortedColor, mixFactor);\n }\n ",["distortionIntensity","distortionIntensityX","distortionIntensityY","distortionCenter","distortionScale"],[],1,t,BABYLON.Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1);return c.onApply=function(e){e.setFloat("distortionIntensity",u.distortionIntensity),e.setFloat("distortionIntensityX",u.distortionIntensityX),e.setFloat("distortionIntensityY",u.distortionIntensityY),e.setVector2("distortionCenter",new BABYLON.Vector2(u.distortionCenterX,u.distortionCenterY)),e.setFloat("distortionScale",u.distortionScale)},c},e}();e.LensDistortionPlugin=t}(i||(i={})),function(e){var t,n=function(t){function n(e,n,i,r){void 0===i&&(i={}),void 0===r&&(r="TOOLKIT.NavigationAgent");var o=t.call(this,e,n,i,r)||this;return o.crowd=null,o.distanceToTarget=0,o.teleporting=!1,o.moveDirection=new BABYLON.Vector3(0,0,0),o.resetPosition=new BABYLON.Vector3(0,0,0),o.lastPosition=new BABYLON.Vector3(0,0,0),o.distancePosition=new BABYLON.Vector3(0,0,0),o.currentPosition=new BABYLON.Vector3(0,0,0),o.currentRotation=new BABYLON.Quaternion(0,0,0,1),o.currentVelocity=new BABYLON.Vector3(0,0,0),o.currentWaypoint=new BABYLON.Vector3(0,0,0),o.heightOffset=0,o.angularSpeed=0,o.updatePosition=!0,o.updateRotation=!0,o.distanceEpsilon=.1,o.velocityEpsilon=1.1,o.offMeshVelocity=1.5,o.stoppingDistance=0,o.onReadyObservable=new BABYLON.Observable,o.onPreUpdateObservable=new BABYLON.Observable,o.onPostUpdateObservable=new BABYLON.Observable,o.onNavCompleteObservable=new BABYLON.Observable,o.m_agentState=0,o.m_agentIndex=-1,o.m_agentReady=!1,o.m_agentGhost=null,o.m_agentParams=null,o.m_agentMovement=new BABYLON.Vector3(0,0,0),o.m_agentDirection=new BABYLON.Vector3(0,0,1),o.m_agentQuaternion=new BABYLON.Quaternion(0,0,0,1),o.m_agentDestination=null,o.m_debugDestinationSphere=null,o}return r(n,t),n.prototype.isReady=function(){return this.m_agentReady},n.prototype.isNavigating=function(){return null!=this.m_agentDestination},n.prototype.isTeleporting=function(){return this.teleporting},n.prototype.isOnOffMeshLink=function(){return this.m_agentState===e.CrowdAgentState.DT_CROWDAGENT_STATE_OFFMESH},n.prototype.getAgentType=function(){return this.type},n.prototype.getAgentState=function(){return this.m_agentState},n.prototype.getAgentIndex=function(){return this.m_agentIndex},n.prototype.getAgentOffset=function(){return this.baseOffset},n.prototype.getTargetDistance=function(){return this.distanceToTarget},n.prototype.getCurrentPosition=function(){return this.currentPosition},n.prototype.getCurrentRotation=function(){return this.currentRotation},n.prototype.getCurrentVelocity=function(){return this.currentVelocity},n.prototype.getAgentParameters=function(){return this.m_agentParams},n.prototype.setAgentParameters=function(e){this.m_agentParams=e,this.updateAgentParameters()},n.prototype.awake=function(){this.awakeNavigationAgent()},n.prototype.update=function(){this.updateNavigationAgent()},n.prototype.destroy=function(){this.destroyNavigationAgent()},n.prototype.awakeNavigationAgent=function(){this.type=this.getProperty("type",this.type),this.speed=this.getProperty("speed",this.speed),this.baseOffset=this.getProperty("offset",this.baseOffset),this.angularSpeed=this.getProperty("angularspeed",this.angularSpeed),this.acceleration=this.getProperty("acceleration",this.acceleration),this.stoppingDistance=this.getProperty("stoppingdistance",this.stoppingDistance),this.autoBraking=this.getProperty("autobraking",this.autoBraking),this.avoidRadius=this.getProperty("avoidradius",this.avoidRadius),this.avoidHeight=this.getProperty("avoidheight",this.avoidHeight),this.obstacleAvoidanceType=this.getProperty("avoidquality",this.obstacleAvoidanceType),this.avoidancePriority=this.getProperty("avoidpriority",this.avoidancePriority),this.autoTraverseOffMeshLink=this.getProperty("autotraverse",this.autoTraverseOffMeshLink),this.autoRepath=this.getProperty("autopepath",this.autoRepath),this.areaMask=this.getProperty("areamask",this.areaMask),e.Utilities.ValidateTransformQuaternion(this.transform),this.m_agentGhost=new BABYLON.TransformNode(this.transform.name+".Agent",this.scene),this.m_agentGhost.position=new BABYLON.Vector3(0,0,0),this.m_agentGhost.rotation=new BABYLON.Vector3(0,0,0),e.Utilities.ValidateTransformQuaternion(this.m_agentGhost),this.m_agentGhost.position.copyFrom(this.transform.position),this.lastPosition.copyFrom(this.transform.position),this.m_debugDestinationSphere=BABYLON.MeshBuilder.CreateSphere(this.transform.name+".DebugDestination",{diameter:.5},this.scene);var t=new BABYLON.StandardMaterial(this.transform.name+".DebugDestinationMat",this.scene);t.emissiveColor=new BABYLON.Color3(1,0,0),t.disableLighting=!0,this.m_debugDestinationSphere.material=t,this.m_debugDestinationSphere.isVisible=!1},n.prototype.updateNavigationAgent=function(){if(null==this.crowd)if(!0===e.NavigationAgent.GLOBAL_CROWD_INSTANCE)this.crowd=e.SceneManager.GetCrowdInterface(this.scene);else{var t=e.SceneManager.GetNavigationPlugin();null!=t&&e.SceneManager.HasNavigationData()?this.crowd=t.createCrowd(e.SceneManager.MAX_AGENT_COUNT,e.SceneManager.MAX_AGENT_RADIUS,this.scene):this.crowd=null}if(null!=this.crowd){if(this.m_agentIndex<0)return this.m_agentParams={radius:this.avoidRadius,height:this.avoidHeight,maxSpeed:this.speed,maxAcceleration:this.acceleration},e.Utilities.GetAbsolutePositionToRef(this.transform,this.resetPosition),this.m_agentIndex=this.crowd.addAgent(this.resetPosition,this.m_agentParams,this.m_agentGhost),void(this.m_agentIndex>=0&&(this.m_agentReady=!0,this.onReadyObservable&&this.onReadyObservable.hasObservers()&&this.onReadyObservable.notifyObservers(this.transform)));if(this.m_agentState=this.crowd.getAgentState(this.m_agentIndex),this.getAgentWaypointToRef(this.currentWaypoint),this.getAgentPositionToRef(this.currentPosition),this.distancePosition.copyFrom(this.currentPosition),this.isOnOffMeshLink()?(this.currentPosition.subtractToRef(this.lastPosition,this.currentVelocity),this.currentVelocity.scaleInPlace(this.speed*this.offMeshVelocity)):this.getAgentVelocityToRef(this.currentVelocity),this.onPreUpdateObservable&&this.onPreUpdateObservable.hasObservers()&&this.onPreUpdateObservable.notifyObservers(this.transform),this.currentPosition.y+=this.baseOffset+this.heightOffset,this.currentVelocity.length()>=this.velocityEpsilon){this.currentVelocity.normalize();var n=this.angularSpeed*e.NavigationAgent.ANGULAR_SPEED_RATIO*this.getDeltaSeconds();if(this.isOnOffMeshLink()){this.moveDirection.copyFrom(this.m_agentDirection),this.m_agentDirection.set(this.moveDirection.x+(this.currentVelocity.x-this.moveDirection.x),this.moveDirection.y+(this.currentVelocity.y-this.moveDirection.y),this.moveDirection.z+(this.currentVelocity.z-this.moveDirection.z)),this.m_agentDirection.normalize();var i=e.NavigationAgent.TARGET_ANGLE_FACTOR-Math.atan2(this.m_agentDirection.x,this.m_agentDirection.z);BABYLON.Quaternion.FromEulerAnglesToRef(0,i,0,this.currentRotation),this.isNavigating()&&!0===this.updateRotation&&BABYLON.Quaternion.SlerpToRef(this.transform.rotationQuaternion,this.currentRotation,n,this.transform.rotationQuaternion)}else this.m_agentQuaternion.copyFrom(this.transform.rotationQuaternion),this.isNavigating()&&!0===this.updateRotation&&this.transform.lookAt(this.currentWaypoint),this.transform.rotationQuaternion.toEulerAnglesToRef(this.m_agentDirection),BABYLON.Quaternion.FromEulerAnglesToRef(0,this.m_agentDirection.y,0,this.currentRotation),this.isNavigating()&&!0===this.updateRotation&&BABYLON.Quaternion.SlerpToRef(this.m_agentQuaternion,this.currentRotation,n,this.transform.rotationQuaternion)}this.isNavigating()&&!0===this.updatePosition&&this.transform.position.copyFrom(this.currentPosition),this.isNavigating()?(this.distanceToTarget=BABYLON.Vector3.Distance(this.distancePosition,this.m_agentDestination),this.distanceToTarget<=Math.max(this.distanceEpsilon,this.stoppingDistance)&&(this.cancelNavigation(),this.onNavCompleteObservable&&this.onNavCompleteObservable.hasObservers()&&this.onNavCompleteObservable.notifyObservers(this.transform))):this.distanceToTarget=0,this.lastPosition.copyFrom(this.currentPosition),this.onPostUpdateObservable&&this.onPostUpdateObservable.hasObservers()&&this.onPostUpdateObservable.notifyObservers(this.transform),null!=this.m_debugDestinationSphere&&(null!=this.m_agentDestination?this.m_debugDestinationSphere.position.copyFrom(this.m_agentDestination):this.m_debugDestinationSphere.position.set(0,0,0)),this.teleporting=!1}},n.prototype.updateAgentParameters=function(){null!=this.crowd&&this.m_agentIndex>=0&&this.crowd.updateAgentParameters(this.m_agentIndex,this.m_agentParams)},n.prototype.destroyNavigationAgent=function(){this.m_agentIndex=-1,this.m_agentReady=!1,this.m_agentMovement=null,this.m_agentDirection=null,this.m_agentDestination=null,this.moveDirection=null,this.resetPosition=null,this.lastPosition=null,this.currentPosition=null,this.currentRotation=null,this.currentVelocity=null,this.currentWaypoint=null,this.onReadyObservable.clear(),this.onReadyObservable=null,this.onPreUpdateObservable.clear(),this.onPreUpdateObservable=null,this.onPostUpdateObservable.clear(),this.onPostUpdateObservable=null,this.onNavCompleteObservable.clear(),this.onNavCompleteObservable=null,null!=this.m_agentGhost&&(this.m_agentGhost.dispose(),this.m_agentGhost=null),null!=this.m_debugDestinationSphere&&(this.m_debugDestinationSphere.dispose(),this.m_debugDestinationSphere=null)},n.prototype.move=function(t,n){void 0===n&&(n=!0);var i=e.SceneManager.GetNavigationPlugin();null!=i&&null!=this.crowd?(this.crowd.getAgentPosition(this.m_agentIndex).addToRef(t,this.m_agentMovement),this.m_agentDestination=!0===n?i.getClosestPoint(this.m_agentMovement):this.m_agentMovement.clone(),this.m_agentIndex>=0&&this.crowd.agentGoto(this.m_agentIndex,this.m_agentDestination)):BABYLON.Tools.Warn("No recast navigation mesh or crowd interface data available!")},n.prototype.teleport=function(t,n){void 0===n&&(n=!0);var i=e.SceneManager.GetNavigationPlugin();null!=i&&null!=this.crowd?(this.teleporting=!0,this.m_agentDestination=!0===n?i.getClosestPoint(t):t.clone(),this.m_agentIndex>=0&&this.crowd.agentTeleport(this.m_agentIndex,this.m_agentDestination)):BABYLON.Tools.Warn("No recast navigation mesh or crowd interface data available!")},n.prototype.setDestination=function(t,n){void 0===n&&(n=!0);var i=e.SceneManager.GetNavigationPlugin();null!=i&&null!=this.crowd?(this.m_agentDestination=!0===n?i.getClosestPoint(t):t.clone(),this.m_agentIndex>=0&&this.crowd.agentGoto(this.m_agentIndex,this.m_agentDestination)):BABYLON.Tools.Warn("No recast navigation mesh or crowd interface data available!")},n.prototype.setAcceleration=function(e){null!=this.m_agentParams&&(this.acceleration=e,this.m_agentParams.maxAcceleration=this.acceleration,this.updateAgentParameters())},n.prototype.setMovementSpeed=function(e){null!=this.m_agentParams&&(this.speed=e,this.m_agentParams.maxSpeed=this.speed,this.updateAgentParameters())},n.prototype.setSeparationWeight=function(e){null!=this.m_agentParams&&(this.m_agentParams.separationWeight=e,this.updateAgentParameters())},n.prototype.setOptimizationRange=function(e){null!=this.m_agentParams&&(this.m_agentParams.pathOptimizationRange=e,this.updateAgentParameters())},n.prototype.setCollisionQueryRange=function(e){null!=this.m_agentParams&&(this.m_agentParams.collisionQueryRange=e,this.updateAgentParameters())},n.prototype.setAgentRadius=function(e){null!=this.m_agentParams&&(this.m_agentParams.radius=e,this.updateAgentParameters())},n.prototype.setAgentHeight=function(e){null!=this.m_agentParams&&(this.m_agentParams.height=e,this.updateAgentParameters())},n.prototype.getAgentVelocity=function(){return null!=this.crowd&&this.m_agentIndex>=0?this.crowd.getAgentVelocity(this.m_agentIndex):null},n.prototype.getAgentVelocityToRef=function(e){null!=this.crowd&&this.m_agentIndex>=0&&this.crowd.getAgentVelocityToRef(this.m_agentIndex,e)},n.prototype.getAgentPosition=function(){return null!=this.crowd&&this.m_agentIndex>=0?this.crowd.getAgentPosition(this.m_agentIndex):null},n.prototype.getAgentPositionToRef=function(e){null!=this.crowd&&this.m_agentIndex>=0&&this.crowd.getAgentPositionToRef(this.m_agentIndex,e)},n.prototype.getAgentWaypoint=function(){return null!=this.crowd&&this.m_agentIndex>=0?this.crowd.getAgentNextTargetPath(this.m_agentIndex):null},n.prototype.getAgentWaypointToRef=function(e){null!=this.crowd&&this.m_agentIndex>=0&&this.crowd.getAgentNextTargetPathToRef(this.m_agentIndex,e)},n.prototype.cancelNavigation=function(){this.m_agentDestination=null;var e=this.getAgentPosition();null!=e&&null!=this.crowd&&this.m_agentIndex>=0&&this.crowd.agentTeleport(this.m_agentIndex,e)},n.prototype.getDebugDestinationMesh=function(){return this.m_debugDestinationSphere},n.prototype.showDebugDestination=function(e){null!=this.m_debugDestinationSphere&&(this.m_debugDestinationSphere.isVisible=e)},n.TARGET_ANGLE_FACTOR=.5*Math.PI,n.ANGULAR_SPEED_RATIO=.05,n.GLOBAL_CROWD_INSTANCE=!1,n}(e.ScriptComponent);e.NavigationAgent=n,(t=e.CrowdAgentState||(e.CrowdAgentState={}))[t.DT_CROWDAGENT_STATE_INVALID=0]="DT_CROWDAGENT_STATE_INVALID",t[t.DT_CROWDAGENT_STATE_WALKING=1]="DT_CROWDAGENT_STATE_WALKING",t[t.DT_CROWDAGENT_STATE_OFFMESH=2]="DT_CROWDAGENT_STATE_OFFMESH",e.SceneManager.RegisterClass("TOOLKIT.NavigationAgent",n)}(i||(i={})),function(e){var t=function(t){function n(n,i,r,o){void 0===r&&(r={}),void 0===o&&(o="TOOLKIT.PostProcessor");var a=t.call(this,n,i,r,o)||this;return a.highDynamicRange=!0,a.neutralToneMapping=!1,a.toneMappingMode=-1,a.defaultContrast=1,a.defaultExposure=1,a.defaultLookupTable=null,a.colorGradingSettings=null,a.bloomSettings=null,a.vignetteSettings=null,a.sharpenSettings=null,a.grainSettings=null,a.chromaticAberrationSettings=null,a.depthOfFieldSettings=null,a.motionBlurSettings=null,a.lensDistortionSettings=null,a.autoExposureSettings=null,a.colorFilterPP=null,a.coloredBloomPP=null,a.motionBlurPP=null,a.roundedVignettePP=null,a.lensDistortionPP=null,a.defaultRenderPipeline=null,a.screenSpaceAOPipeline=null,a.screenSpaceRPipeline=null,e.PostProcessor.GlobalInstance=a,a}return r(n,t),Object.defineProperty(n,"Instance",{get:function(){return n.GlobalInstance},enumerable:!1,configurable:!0}),n.prototype.GetDefaultRenderPipeline=function(){return this.defaultRenderPipeline},n.prototype.GetSSAORRenderPipeline=function(){return this.screenSpaceAOPipeline},n.prototype.GetSSRRenderPipeline=function(){return this.screenSpaceRPipeline},n.prototype.ready=function(){var e=this.getProperties();if(e.isglobal){if(null!=e.effects&&Array.isArray(e.effects))for(var t=0,n=e.effects;t<n.length;t++){var i=n[t];if(i&&i.effecttype){var r=i.effecttype.toLowerCase();switch(r){case"colorgrading":this.colorGradingSettings=this.parseColorGradingSettings(i.parameters);break;case"ambientocclusion":var o=this.parseAmbientOcclusionSettings(i.parameters);null!=o&&(this.screenSpaceAOPipeline=new BABYLON.SSAORenderingPipeline("SSAO",this.scene,1,this.scene.cameras),o.intensity&&!1!==o.intensity.overrideState&&(this.screenSpaceAOPipeline.totalStrength=Number(o.intensity.value)),o.radius&&!1!==o.radius.overrideState&&(this.screenSpaceAOPipeline.radius=Number(o.radius.value)),o.thicknessModifier&&!1!==o.thicknessModifier.overrideState&&(this.screenSpaceAOPipeline.fallOff=Number(o.thicknessModifier.value)));break;case"screenspacereflections":var a=this.parseScreenSpaceReflectionsSettings(i.parameters);if(null!=a){if(this.screenSpaceRPipeline=new BABYLON.SSRRenderingPipeline("SSR",this.scene,this.scene.cameras),a.preset&&!1!==a.preset.overrideState){var s=Number(a.preset.value);this.screenSpaceRPipeline.step=Math.max(.1,1/(s+1)),this.screenSpaceRPipeline.strength=Math.min(2,.5*s+.5)}a.maximumIterationCount&&!1!==a.maximumIterationCount.overrideState&&(this.screenSpaceRPipeline.maxSteps=Number(a.maximumIterationCount.value)),a.thickness&&!1!==a.thickness.overrideState&&(this.screenSpaceRPipeline.thickness=Number(a.thickness.value))}break;case"autoexposure":this.autoExposureSettings=this.parseAutoExposure(i.parameters);break;case"bloom":this.bloomSettings=this.parseBloomSettings(i.parameters);break;case"chromaticaberration":this.chromaticAberrationSettings=this.parseChromaticAberrationSettings(i.parameters);break;case"depthoffield":this.depthOfFieldSettings=this.parseDepthOfFieldSettings(i.parameters);break;case"grain":this.grainSettings=this.parseGrainSettings(i.parameters);break;case"lensdistortion":this.lensDistortionSettings=this.parseLensDistortionSettings(i.parameters);break;case"motionblur":this.motionBlurSettings=this.parseMotionBlurSettings(i.parameters);break;case"vignette":this.vignetteSettings=this.parseVignetteSettings(i.parameters);break;case"sharpen":this.sharpenSettings=this.parseSharpenSettings(i.parameters);break;default:console.warn("[PostProcessor] Unsupported effect type:",r)}}}}else console.warn("[PostProcessor] Non global volumes are not supported..");this.defaultRenderPipeline=new BABYLON.DefaultRenderingPipeline("DefaultPostProcessor",this.highDynamicRange,this.scene,this.scene.cameras,!0),this.defaultRenderPipeline.imageProcessingEnabled=!0,this.defaultRenderPipeline.samples=1,this.applyColorGradingSettings(),this.applyBloomSettings(),this.applyVignetteSettings(),this.applySharpenSettings(),this.applyGrainSettings(),this.applyChromaticAberrationSettings(),this.applyDepthOfFieldSettings(),this.applyMotionBlurSettings(),this.applyLensDistortionSettings(),this.applyAutoExposureSettings(),console.log("[PostProcessor] Initialized DefaultRenderingPipeline",this)},n.prototype.parseColorGradingSettings=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)},i={tonemapper:n("tonemapper"),postExposure:n("postexposure"),saturation:n("saturation"),contrast:n("contrast"),lut:n("lut")||n("externallut")||n("ldrlut"),lut2:n("lut2"),lutCrossFade:n("lutCrossFade")||n("lutBlend")||n("mix"),lift:n("lift"),gamma:n("gamma"),gain:n("gain"),tonecurvetoestrength:n("tonecurvetoestrength"),tonecurvetoelength:n("tonecurvetoelength"),tonecurveshoulderstrength:n("tonecurveshoulderstrength"),tonecurveshoulderlength:n("tonecurveshoulderlength"),tonecurveshoulderangle:n("tonecurveshoulderangle"),tonecurvegamma:n("tonecurvegamma"),temperature:n("temperature"),tint:n("tint"),colorfilter:n("colorfilter")};if(this.colorGradingSettings=i,i.tonemapper&&!1!==i.tonemapper.overrideState&&null!=i.tonemapper.value){var r=this.mapToneMapper(i.tonemapper);r&&r.enabled&&(this.toneMappingMode=1===r.type?BABYLON.ImageProcessingConfiguration.TONEMAPPING_ACES:2===r.type?BABYLON.ImageProcessingConfiguration.TONEMAPPING_KHR_PBR_NEUTRAL:BABYLON.ImageProcessingConfiguration.TONEMAPPING_STANDARD)}if(i.postExposure&&!1!==i.postExposure.overrideState&&null!=i.postExposure.value){var o=Math.pow(2,Number(i.postExposure.value));this.defaultExposure=1*o}return i.contrast&&!1!==i.contrast.overrideState&&null!=i.contrast.value&&(this.defaultContrast=.05*Number(i.contrast.value)),i},n.prototype.applyColorGradingSettings=function(){if(this.colorGradingSettings&&this.defaultRenderPipeline&&this.defaultRenderPipeline.imageProcessing){console.log("[PostProcessor] Applying Color Grading Settings:",this.colorGradingSettings),this.colorGradingSettings;var e=this.defaultRenderPipeline.imageProcessing;0!=this.defaultExposure&&(e.exposure=this.defaultExposure),0===e.exposure&&(e.exposure=1),0!=this.defaultContrast&&(e.contrast=this.defaultContrast),0===e.contrast&&(e.contrast=1),this.toneMappingMode>=0&&(e.toneMappingType=this.toneMappingMode,e.toneMappingEnabled=!0)}},n.prototype.mapToneMapper=function(t){var n=e.PostProcessor.extractParam(t);if(!n||null==n.value)return{enabled:!1,type:null};if(!1===n.overrideState)return{enabled:!1,type:null};var i=n.value,r=null;"object"==typeof i?i.name?r=(""+i.name).toUpperCase():null!=i.value&&"string"==typeof i.value&&(r=(""+i.value).toUpperCase()):r=(""+i).toUpperCase();var o=BABYLON.ImageProcessingConfiguration.TONEMAPPING_ACES,a=BABYLON.ImageProcessingConfiguration.TONEMAPPING_KHR_PBR_NEUTRAL,s=BABYLON.ImageProcessingConfiguration.TONEMAPPING_STANDARD;return r&&r.indexOf("ACES")>=0?{enabled:!0,type:o}:r&&r.indexOf("NEUTRAL")>=0?{enabled:!0,type:a}:r&&(r.indexOf("NONE")>=0||r.indexOf("DISABLED")>=0)||isNaN(Number(i))?{enabled:!1,type:s}:{enabled:!0,type:Number(i)}},n.prototype.parseBloomSettings=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)};return{intensity:n("intensity"),threshold:n("threshold"),softKnee:n("softKnee")||n("softknee"),clamp:n("clamp"),diffusion:n("diffusion"),anamorphicRatio:n("anamorphicRatio")||n("anamorphicratio"),color:n("color"),fastMode:n("fastMode")||n("fastmode")}},n.prototype.applyBloomSettings=function(){var t;if(this.bloomSettings&&this.defaultRenderPipeline){console.log("[PostProcessor] Applying Bloom Settings:",this.bloomSettings);var n=this.bloomSettings,i=this.defaultRenderPipeline;if(n.intensity&&!1!==n.intensity.overrideState&&null!=n.intensity.value&&(i.bloomWeight=Number(n.intensity.value)),n.threshold&&!1!==n.threshold.overrideState&&null!=n.threshold.value&&(i.bloomThreshold=Number(n.threshold.value)),n.diffusion&&!1!==n.diffusion.overrideState&&null!=n.diffusion.value){var r=Number(n.diffusion.value);i.bloomKernel=Math.max(1,Math.floor(10*r)),i.bloomScale=r}n.color&&!1!==n.color.overrideState&&Array.isArray(n.color.value)&&(i.bloomWeight=0,this.coloredBloomPP=e.ColoredBloomPlugin.CreateColoredBloom(this.scene,this.scene.activeCamera,{threshold:i.bloomThreshold,color:n.color.value,weight:Number((null===(t=n.intensity)||void 0===t?void 0:t.value)||1),kernel:i.bloomKernel,saturation:1}),this.coloredBloomPP.name="ColoredBloomPostProcess")}},n.prototype.parseSharpenSettings=function(t){return t?{intensity:function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)}("intensity")}:null},n.prototype.applySharpenSettings=function(){if(this.sharpenSettings&&this.defaultRenderPipeline&&this.defaultRenderPipeline.sharpen){console.log("[PostProcessor] Applying Sharpen Settings:",this.sharpenSettings);var e=this.sharpenSettings,t=this.defaultRenderPipeline.sharpen;e.intensity&&!1!==e.intensity.overrideState&&null!=e.intensity.value&&(t.edgeAmount=Number(e.intensity.value))}},n.prototype.parseGrainSettings=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)};return{intensity:n("intensity"),size:n("size"),lumContrib:n("lumContrib")||n("lumcontrib"),colored:n("colored")}},n.prototype.applyGrainSettings=function(){if(this.grainSettings&&this.defaultRenderPipeline&&this.defaultRenderPipeline.grain){console.log("[PostProcessor] Applying Grain Settings:",this.grainSettings);var e=this.grainSettings,t=this.defaultRenderPipeline.grain;e.intensity&&!1!==e.intensity.overrideState&&null!=e.intensity.value&&(t.intensity=Number(e.intensity.value))}},n.prototype.parseVignetteSettings=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)};return{color:n("color"),center:n("center"),intensity:n("intensity"),smoothness:n("smoothness"),rounded:n("rounded"),mode:n("mode")||n("blendMode")}},n.prototype.applyVignetteSettings=function(){if(this.vignetteSettings&&this.defaultRenderPipeline&&this.defaultRenderPipeline.imageProcessing){console.log("[PostProcessor] Applying Vignette Settings:",this.vignetteSettings);var t=this.vignetteSettings,n=this.defaultRenderPipeline.imageProcessing;t.color&&!1!==t.color.overrideState&&Array.isArray(t.color.value)&&(n.vignetteColor=new BABYLON.Color4(t.color.value[0]||0,t.color.value[1]||0,t.color.value[2]||0,null!=t.color.value[3]?t.color.value[3]:1)),t.center&&!1!==t.center.overrideState&&Array.isArray(t.center.value)&&(n.vignetteCenterX=(t.center.value[0]||.5)-.5,n.vignetteCenterY=(t.center.value[1]||.5)-.5),t.intensity&&!1!==t.intensity.overrideState&&null!=t.intensity.value&&(n.vignetteWeight=10*Number(t.intensity.value)),t.smoothness&&!1!==t.smoothness.overrideState&&null!=t.smoothness.value&&(n.vignetteBlendMode=Number(t.smoothness.value)),t.rounded&&!1!==t.rounded.overrideState&&!0===t.rounded.value&&(n.vignetteWeight=0,this.roundedVignettePP=e.RoundedVignettePlugin.CreatePostProcess(this.scene,this.scene.activeCamera,{color:n.vignetteColor?[n.vignetteColor.r,n.vignetteColor.g,n.vignetteColor.b,n.vignetteColor.a]:[0,0,0,1],center:[(n.vignetteCenterX||.5)-.5,(n.vignetteCenterY||.5)-.5],intensity:n.vignetteWeight,smoothness:n.vignetteBlendMode,rounded:!0,blendMode:t.mode&&t.mode.value?t.mode.value:"multiply"}),this.roundedVignettePP.name="RoundedVignettePostProcess"),n.vignetteEnabled=!0}},n.prototype.parseDepthOfFieldSettings=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)};return{focusDistance:n("focusDistance")||n("focusdistance"),aperture:n("aperture"),focalLength:n("focalLength")||n("focallength"),kernelSize:n("kernelSize")||n("kernelsize")}},n.prototype.applyDepthOfFieldSettings=function(){if(this.depthOfFieldSettings&&this.defaultRenderPipeline&&this.defaultRenderPipeline.depthOfField){console.log("[PostProcessor] Applying Depth Of Field Settings:",this.depthOfFieldSettings);var e=this.depthOfFieldSettings,t=this.defaultRenderPipeline.depthOfField;if(e.focusDistance&&!1!==e.focusDistance.overrideState&&null!=e.focusDistance.value&&(t.focusDistance=Number(e.focusDistance.value)),e.aperture&&!1!==e.aperture.overrideState&&null!=e.aperture.value&&(t.fStop=Number(e.aperture.value)),e.focalLength&&!1!==e.focalLength.overrideState&&null!=e.focalLength.value&&(t.focalLength=Number(e.focalLength.value)),e.kernelSize&&!1!==e.kernelSize.overrideState&&null!=e.kernelSize.value){var n=Number(e.kernelSize.value);t.fStop=Math.max(.1,2-n)}t._enable([this.scene.activeCamera])}},n.prototype.parseMotionBlurSettings=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)};return{shutterAngle:n("shutterAngle")||n("shutterangle"),sampleCount:n("sampleCount")||n("samplecount")}},n.prototype.applyMotionBlurSettings=function(){if(this.motionBlurSettings){console.log("[PostProcessor] Applying Motion Blur Settings:",this.motionBlurSettings);var e=this.motionBlurSettings;this.motionBlurPP=new BABYLON.MotionBlurPostProcess("motionBlur",this.scene,1,this.scene.activeCamera),this.motionBlurPP.name="MotionBlurPostProcess",e.sampleCount&&!1!==e.sampleCount.overrideState&&null!=e.sampleCount.value&&(this.motionBlurPP.samples=Number(e.sampleCount.value))}},n.prototype.parseAutoExposure=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)};return{filtering:n("filtering"),minimum:n("minimum"),maximum:n("maximum"),speedUp:n("speedUp")||n("speedup"),speedDown:n("speedDown")||n("speeddown")}},n.prototype.applyAutoExposureSettings=function(){if(this.autoExposureSettings&&this.defaultRenderPipeline&&this.defaultRenderPipeline.imageProcessing){console.log("[PostProcessor] Applying Auto Exposure Settings:",this.autoExposureSettings);var e=this.autoExposureSettings;this.defaultRenderPipeline.imageProcessing,e.minimum&&!1!==e.minimum.overrideState&&e.minimum.value,e.maximum&&!1!==e.maximum.overrideState&&e.maximum.value,console.warn("[PostProcessor] Auto-exposure is partially supported; full adaptive exposure requires custom implementation.")}},n.prototype.parseLensDistortionSettings=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)};return{intensity:n("intensity"),intensityX:n("intensityX")||n("intensityx"),intensityY:n("intensityY")||n("intensityy"),centerX:n("centerX")||n("centerx"),centerY:n("centerY")||n("centery"),scale:n("scale")}},n.prototype.applyLensDistortionSettings=function(){var t,n,i,r,o,a;if(this.lensDistortionSettings){console.log("[PostProcessor] Applying Lens Distortion Settings:",this.lensDistortionSettings);var s=this.lensDistortionSettings;this.lensDistortionPP=e.LensDistortionPlugin.CreatePostProcess(this.scene,this.scene.activeCamera,{distortionIntensity:(null===(t=s.intensity)||void 0===t?void 0:t.value)||0,distortionIntensityX:(null===(n=s.intensityX)||void 0===n?void 0:n.value)||0,distortionIntensityY:(null===(i=s.intensityY)||void 0===i?void 0:i.value)||0,distortionCenterX:(null===(r=s.centerX)||void 0===r?void 0:r.value)||.5,distortionCenterY:(null===(o=s.centerY)||void 0===o?void 0:o.value)||.5,distortionScale:(null===(a=s.scale)||void 0===a?void 0:a.value)||1}),this.lensDistortionPP.name="LensDistortionPostProcess"}},n.prototype.parseChromaticAberrationSettings=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)};return{intensity:n("intensity"),fastMode:n("fastMode")||n("fastmode")}},n.prototype.applyChromaticAberrationSettings=function(){if(this.chromaticAberrationSettings&&this.defaultRenderPipeline&&this.defaultRenderPipeline.chromaticAberration){console.log("[PostProcessor] Applying Chromatic Aberration Settings:",this.chromaticAberrationSettings);var e=this.chromaticAberrationSettings,t=this.defaultRenderPipeline.chromaticAberration;e.intensity&&!1!==e.intensity.overrideState&&null!=e.intensity.value&&(t.aberrationAmount=Number(e.intensity.value))}},n.prototype.parseAmbientOcclusionSettings=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)};return{intensity:n("intensity"),radius:n("radius"),sampleCount:n("sampleCount")||n("samplecount"),downsampling:n("downsampling"),thicknessModifier:n("thicknessModifier")||n("thicknessmodifier")}},n.prototype.parseScreenSpaceReflectionsSettings=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)};return{preset:n("preset"),maximumIterationCount:n("maximumIterationCount")||n("maximumiterationcount"),thickness:n("thickness"),resolution:n("resolution"),bounce:n("bounce")}},n.unwrapParam=function(e){if(null==e)return e;try{if("object"==typeof e&&"value"in e)return e.value}catch(e){}return e},n.extractParam=function(e){if(null==e)return{value:null,overrideState:null};try{if("object"==typeof e&&"value"in e){var t=null!=e.overrideState?!!e.overrideState:null;return{value:e.value,overrideState:t}}}catch(e){}return{value:e,overrideState:null}},n.GlobalInstance=null,n}(e.ScriptComponent);e.PostProcessor=t,e.SceneManager.RegisterClass("TOOLKIT.PostProcessor",t)}(i||(i={})),function(e){var t=function(){function t(t,n,i){this._centerMass=new BABYLON.Vector3(0,0,0),this._chassisMesh=null,this._tempVectorPos=new BABYLON.Vector3(0,0,0),this.lockedWheelIndexes=null,this.m_scene=null,this.m_vehicle=null,this.m_vehicleTuning=null,this.m_vehicleRaycaster=null,this.m_vehicleColliders=null,this.m_tempPosition=null,this.m_wheelDirectionCS0=null,this.m_wheelAxleCS=null,this._chassisMesh=n,this._centerMass=i,this.m_scene=t,this.m_vehicleTuning=new e.btVehicleTuning,this.m_vehicleRaycaster=new e.btDefaultVehicleRaycaster({shouldHitTriggers:!1,ignoreBody:this._chassisMesh.physicsBody}),this.m_vehicleColliders=null!=this._chassisMesh.metadata&&null!=this._chassisMesh.metadata.toolkit&&null!=this._chassisMesh.metadata.toolkit.wheels?this._chassisMesh.metadata.toolkit.wheels:null,this.m_vehicle=new e.btRaycastVehicle(this.m_vehicleTuning,this._chassisMesh.physicsBody,this.m_vehicleRaycaster),this.m_vehicle.setCoordinateSystem(0,1,2),this.m_wheelDirectionCS0=new BABYLON.Vector3(0,-1,0),this.m_wheelAxleCS=new BABYLON.Vector3(-1,0,0),this.m_tempPosition=null,this.setupWheelInformation()}return t.prototype.getCenterMassOffset=function(){return this._centerMass},t.prototype.getInternalVehicle=function(){return this.m_vehicle},t.prototype.getUpAxis=function(){return null!=this.m_vehicle?this.m_vehicle.getUpAxis():null},t.prototype.getRightAxis=function(){return null!=this.m_vehicle?this.m_vehicle.getRightAxis():null},t.prototype.getForwardAxis=function(){return null!=this.m_vehicle?this.m_vehicle.getForwardAxis():null},t.prototype.getForwardVector=function(){return null!=this.m_vehicle?this.m_vehicle.getForwardVector():null},t.prototype.getNumWheels=function(){return null!=this.m_vehicle?this.m_vehicle.getNumWheels():null},t.prototype.getWheelInfo=function(e){return null!=this.m_vehicle?this.m_vehicle.getWheelInfo(e):null},t.prototype.resetSuspension=function(){null!=this.m_vehicle&&this.m_vehicle.resetSuspension()},t.prototype.setEngineForce=function(e,t){null!=this.m_vehicle&&this.m_vehicle.applyEngineForce(e,t)},t.prototype.setBrakingForce=function(e,t){null!=this.m_vehicle&&this.m_vehicle.setBrake(e,t)},t.prototype.updateWheelTransform=function(e,t){null!=this.m_vehicle&&this.m_vehicle.updateWheelTransform(e,t)},t.prototype.getWheelTransformPosition=function(e){return null!=this.m_vehicle?this.m_vehicle.getWheelInfo(e).worldTransformPosition:null},t.prototype.getWheelTransformRotation=function(e){return null!=this.m_vehicle?this.m_vehicle.getWheelInfo(e).worldTransformRotation:null},t.prototype.getRawCurrentSpeedKph=function(){return null!=this.m_vehicle?this.m_vehicle.getCurrentSpeedKmHour():null},t.prototype.getRawCurrentSpeedMph=function(){return null!=this.m_vehicle?this.m_vehicle.getCurrentSpeedKmHour()*e.System.Kph2Mph:null},t.prototype.getAbsCurrentSpeedKph=function(){return null!=this.m_vehicle?Math.abs(this.m_vehicle.getCurrentSpeedKmHour()):null},t.prototype.getAbsCurrentSpeedMph=function(){return null!=this.m_vehicle?Math.abs(this.m_vehicle.getCurrentSpeedKmHour())*e.System.Kph2Mph:null},t.prototype.getVehicleTuningSystem=function(){return this.m_vehicleTuning},t.prototype.getChassisWorldTransform=function(){return null!=this.m_vehicle?this.m_vehicle.getChassisWorldTransform():null},t.prototype.dispose=function(){this.deleteWheelInformation(),null!=this.m_vehicle&&(this.m_vehicle=null),null!=this.m_vehicleTuning&&(this.m_vehicleTuning=null),null!=this.m_vehicleRaycaster&&(this.m_vehicleRaycaster=null),null!=this.m_wheelDirectionCS0&&(this.m_wheelDirectionCS0=null),null!=this.m_wheelAxleCS&&(this.m_wheelAxleCS=null),null!=this.m_tempPosition&&(this.m_tempPosition=null),this.m_vehicleColliders=null},t.GetInstance=function(t,n){var i=n;return null==i.m_raycastVehicle&&(n.hasWheelColliders()?i.m_raycastVehicle=new e.RaycastVehicle(t,i.transform,i._centerOfMass):BABYLON.Tools.Warn("No wheel collider metadata found for: "+i.transform.name)),i.m_raycastVehicle},t.prototype.tickVehicleController=function(e){null!=this.m_vehicle&&this.m_vehicle.updateVehicle(e)},t.prototype.getEnableMultiRaycast=function(){var e=!1;return null!=this.m_vehicle&&(e=this.m_vehicle.enableMultiRaycast),e},t.prototype.setEnableMultiRaycast=function(e){null!=this.m_vehicle&&(this.m_vehicle.enableMultiRaycast=e)},t.prototype.getSmoothedGradientSpeed=function(){var e=-1;return null!=this.m_vehicle&&(e=this.m_vehicle.smoothedGradientSpeed),e},t.prototype.setSmoothedGradientSpeed=function(e){null!=this.m_vehicle&&(this.m_vehicle.smoothedGradientSpeed=e)},t.prototype.getMaximumYawRateLow=function(){var e=-1;return null!=this.m_vehicle&&(e=this.m_vehicle.maximumYawRateLow),e},t.prototype.setMaximumYawRateLow=function(e){null!=this.m_vehicle&&(this.m_vehicle.maximumYawRateLow=e)},t.prototype.getMaximumYawRateHigh=function(){var e=-1;return null!=this.m_vehicle&&(e=this.m_vehicle.maximumYawRateHigh),e},t.prototype.setMaximumYawRateHigh=function(e){null!=this.m_vehicle&&(this.m_vehicle.maximumYawRateHigh=e)},t.prototype.getAngularDampingControl=function(){var e=new BABYLON.Vector3;return null!=this.m_vehicle&&(e=this.m_vehicle.angularDamping),e},t.prototype.setAngularDampingControl=function(e){null!=this.m_vehicle&&(this.m_vehicle.angularDamping=e)},t.prototype.getSmoothFlyingImpulse=function(){var e=-1;return null!=this.m_vehicle&&this.m_vehicle.smoothFlyingImpulse&&(e=this.m_vehicle.smoothFlyingImpulse),e},t.prototype.setSmoothFlyingImpulse=function(e){null!=this.m_vehicle&&(this.m_vehicle.smoothFlyingImpulse=e)},t.prototype.setGroundedAutoLevelEnabled=function(e){null!=this.m_vehicle&&(this.m_vehicle.groundedAutoLevelEnabled=e)},t.prototype.setGroundedAutoLevelStrength=function(e){null!=this.m_vehicle&&(this.m_vehicle.groundedAutoLevelStrength=e)},t.prototype.setGroundedAutoLevelDeadzone=function(e){null!=this.m_vehicle&&(this.m_vehicle.groundedAutoLevelDeadzoneDeg=e)},t.prototype.setGroundedAutoLevelSettleDeg=function(e){null!=this.m_vehicle&&(this.m_vehicle.groundedAutoLevelSettleDeg=e)},t.prototype.setGroundedAutoLevelSettleScale=function(e){null!=this.m_vehicle&&(this.m_vehicle.groundedAutoLevelSettleScale=e)},t.prototype.setGroundedAutoLevelHysteresis=function(e){null!=this.m_vehicle&&(this.m_vehicle.groundedAutoLevelHysteresisDeg=e)},t.prototype.setGroundedAutoLevelSpeedRange=function(e,t){null!=this.m_vehicle&&(this.m_vehicle.groundedAutoLevelStartKmh=e,this.m_vehicle.groundedAutoLevelFullKmh=t)},t.prototype.setGroundedAutoLevelMaxRate=function(e){null!=this.m_vehicle&&(this.m_vehicle.groundedAutoLevelMaxRate=e)},t.prototype.getTrackConnectionAccel=function(){var e=-1;return null!=this.m_vehicle&&this.m_vehicle.trackConnectionAccel&&(e=this.m_vehicle.trackConnectionAccel),e},t.prototype.setTrackConnectionAccel=function(e){null!=this.m_vehicle&&(this.m_vehicle.trackConnectionAccel=e)},t.prototype.setAirborneTrackConnectionMaxAccel=function(e){null!=this.m_vehicle&&(this.m_vehicle.airborneTrackConnectionMaxAccel=e)},t.prototype.setAirborneTrackConnectionSpeedRange=function(e,t){null!=this.m_vehicle&&(this.m_vehicle.airborneTrackConnectionStartKmh=e,this.m_vehicle.airborneTrackConnectionFullKmh=t)},t.prototype.setAirborneRiseDamping=function(e){null!=this.m_vehicle&&(this.m_vehicle.airborneRiseDamping=e)},t.prototype.setAirborneMaxRiseSpeed=function(e){null!=this.m_vehicle&&(this.m_vehicle.airborneMaxRiseSpeed=e)},t.prototype.getMinimumWheelContacts=function(){var e=-1;return null!=this.m_vehicle&&this.m_vehicle.minimumWheelContacts&&(e=this.m_vehicle.minimumWheelContacts),e},t.prototype.setMinimumWheelContacts=function(e){null!=this.m_vehicle&&(this.m_vehicle.minimumWheelContacts=e)},t.prototype.getDownforceCoefficient=function(){return null!=this.m_vehicle?this.m_vehicle.downforceCoefficient:0},t.prototype.setDownforceCoefficient=function(e){null!=this.m_vehicle&&(this.m_vehicle.downforceCoefficient=e)},t.prototype.getConstantDownforce=function(){return null!=this.m_vehicle?this.m_vehicle.constantDownforce:0},t.prototype.setConstantDownforce=function(e){null!=this.m_vehicle&&(this.m_vehicle.constantDownforce=e)},t.prototype.getWheelIndexByID=function(e){var t=-1;if(null!=this.m_vehicleColliders&&this.m_vehicleColliders.length>0)for(var n=0;n<this.m_vehicleColliders.length;n++){var i=this.m_vehicleColliders[n];if(e.toLowerCase()===i.id.toLowerCase()){t=n;break}}return t},t.prototype.getWheelIndexByName=function(e){var t=-1;if(null!=this.m_vehicleColliders&&this.m_vehicleColliders.length>0)for(var n=0;n<this.m_vehicleColliders.length;n++){var i=this.m_vehicleColliders[n];if(e.toLowerCase()===i.name.toLowerCase()){t=n;break}}return t},t.prototype.getWheelColliderInfo=function(e){var t=-1;return null!=this.m_vehicleColliders&&this.m_vehicleColliders.length>0&&this.m_vehicleColliders.length>e&&(t=this.m_vehicleColliders[e]),t},t.prototype.setWheelTransformMesh=function(e,t){if(null!=t){var n=this.getWheelInfo(e);null!=n&&(n.transform=t)}},t.prototype.ensureNodeRotationQuaternion=function(e){return null==e.rotationQuaternion&&(e.rotationQuaternion=BABYLON.Quaternion.FromEulerAngles(e.rotation.x,e.rotation.y,e.rotation.z)),e.rotationQuaternion},t.prototype.normalizeWheelRotation=function(e){var t=2*Math.PI;return isFinite(e)?((e%=t)>Math.PI&&(e-=t),e<-Math.PI&&(e+=t),e):0},t.prototype.syncWheelSpinnerRotation=function(e){var t=e.spinner;if(null!=t){var n=this.ensureNodeRotationQuaternion(t);null!=e.spinnerBaseRotation&&e.spinnerBaseNode===t||(e.spinnerBaseRotation=n.clone(),e.spinnerBaseNode=t);var i=this.normalizeWheelRotation(e.rotation||0);!0===e.invertWheelDirection&&(i=-i),n.copyFrom(e.spinnerBaseRotation),t.rotate(BABYLON.Axis.X,i,BABYLON.Space.LOCAL)}},t.prototype.rebaseWheelSpinnerRotation=function(e){var t=e.spinner;if(null!=t){var n=this.ensureNodeRotationQuaternion(t),i=this.normalizeWheelRotation(e.rotation||0);!0===e.invertWheelDirection&&(i=-i);var r=n.clone();n.copyFrom(r),t.rotate(BABYLON.Axis.X,-i,BABYLON.Space.LOCAL),e.spinnerBaseRotation=n.clone(),e.spinnerBaseNode=t,n.copyFrom(r)}},t.prototype.getWheelSkidFadeInSpeed=function(){return this.m_vehicle,3},t.prototype.setWheelSkidFadeInSpeed=function(e){this.m_vehicle},t.prototype.getWheelSkidFadeOutSpeed=function(){return this.m_vehicle,3.5},t.prototype.setWheelSkidFadeOutSpeed=function(e){this.m_vehicle},t.prototype.isArcadeYawAssistActive=function(){var e=!1;return null!=this.m_vehicle&&(e=this.m_vehicle.isArcadeYawAssistActive),e},t.prototype.getArcadeSteeringAssist=function(){return null!=this.m_vehicle?this.m_vehicle.arcadeSteeringAssist:1},t.prototype.setArcadeSteeringAssist=function(e){null!=this.m_vehicle&&(this.m_vehicle.arcadeSteeringAssist=e)},t.prototype.getArcadeDonutDirectYawEnabled=function(){return null!=this.m_vehicle&&this.m_vehicle.arcadeDonutDirectYawEnabled},t.prototype.setArcadeDonutDirectYawEnabled=function(e){null!=this.m_vehicle&&(this.m_vehicle.arcadeDonutDirectYawEnabled=e)},t.prototype.getArcadeDonutDirectYawDegPerSec=function(){return null!=this.m_vehicle?this.m_vehicle.arcadeDonutDirectYawDegPerSec:1},t.prototype.setArcadeDonutDirectYawDegPerSec=function(e){null!=this.m_vehicle&&(this.m_vehicle.arcadeDonutDirectYawDegPerSec=e)},t.prototype.getArcadeHandbrakeYawCapMultiplier=function(){return null!=this.m_vehicle?this.m_vehicle.arcadeHandbrakeYawCapMultiplier:1},t.prototype.setArcadeHandbrakeYawCapMultiplier=function(e){null!=this.m_vehicle&&(this.m_vehicle.arcadeHandbrakeYawCapMultiplier=e)},t.prototype.getArcadeBurnoutYawCapMultiplier=function(){return null!=this.m_vehicle?this.m_vehicle.arcadeBurnoutYawCapMultiplier:1},t.prototype.setArcadeBurnoutYawCapMultiplier=function(e){null!=this.m_vehicle&&(this.m_vehicle.arcadeBurnoutYawCapMultiplier=e)},t.prototype.getArcadeDonutYawCapMultiplier=function(){return null!=this.m_vehicle?this.m_vehicle.arcadeDonutYawCapMultiplier:1},t.prototype.setArcadeDonutYawCapMultiplier=function(e){null!=this.m_vehicle&&(this.m_vehicle.arcadeDonutYawCapMultiplier=e)},t.prototype.getArcadeBurnoutActive=function(){var e=!1;return null!=this.m_vehicle&&(e=this.m_vehicle.getIsArcadeBurnoutActive()),e},t.prototype.setArcadeBurnoutActive=function(e){null!=this.m_vehicle&&this.m_vehicle.setIsArcadeBurnoutActive(e)},t.prototype.getArcadeDonutActive=function(){var e=!1;return null!=this.m_vehicle&&(e=this.m_vehicle.getIsArcadeDonutActive()),e},t.prototype.setArcadeDonutActive=function(e){null!=this.m_vehicle&&this.m_vehicle.setIsArcadeDonutActive(e)},t.prototype.getArcadeFootBrakeActive=function(){var e=!1;return null!=this.m_vehicle&&(e=this.m_vehicle.getIsArcadeFootBrakeActive()),e},t.prototype.setArcadeFootBrakeActive=function(e){null!=this.m_vehicle&&this.m_vehicle.setIsArcadeFootBrakeActive(e)},t.prototype.getArcadeHandBrakeActive=function(){var e=!1;return null!=this.m_vehicle&&(e=this.m_vehicle.getIsArcadeHandBrakeActive()),e},t.prototype.setArcadeHandBrakeActive=function(e){null!=this.m_vehicle&&this.m_vehicle.setIsArcadeHandBrakeActive(e)},t.prototype.setArcadeBurnoutDirectionChangeSpeed=function(t){null!=this.m_vehicle&&(this.m_vehicle.arcadeBurnoutDirectionChangeSpeedKmh=t*e.System.Mph2Kph)},t.prototype.getApproxWheelbaseMeters=function(){var e=2.5;return null!=this.m_vehicle&&(e=this.m_vehicle.getApproxWheelbaseMeters()),e},t.prototype.getSignedFrontSteeringAngleRad=function(){var e=0;return null!=this.m_vehicle&&(e=this.m_vehicle.getSignedFrontSteeringAngleRad()),e},t.prototype.getVisualSteeringAngle=function(e){var t=0,n=this.getWheelInfo(e);return null!=n&&null!=n.steeringAngle&&(t=n.steeringAngle),t},t.prototype.setVisualSteeringAngle=function(e,t){var n=this.getWheelInfo(t);null!=n&&(n.steeringAngle=e)},t.prototype.getPhysicsSteeringAngle=function(e){return null!=this.m_vehicle?Math.abs(this.m_vehicle.getSteeringValue(e)):0},t.prototype.setPhysicsSteeringAngle=function(e,t){null!=this.m_vehicle&&this.m_vehicle.setSteeringValue(e,t)},t.prototype.setupWheelInformation=function(){if(null!=this._chassisMesh&&this._chassisMesh.physicsBody,null!=this.m_vehicle&&null!=this.m_vehicleColliders&&this.m_vehicleColliders.length>0){var t=-1;for(t=0;t<this.m_vehicleColliders.length;t++){var n=null!=(m=this.m_vehicleColliders[t]).name?m.name:"Unknown",i=null!=m.radius?m.radius:.35,r=null!=m.position&&m.position.length>=3?m.position[0]:1,o=null!=m.position&&m.position.length>=3?m.position[2]:-1,a=null!=m.wheelconnectionpoint?m.wheelconnectionpoint:.5,s=null!=m.suspensionrestlength?m.suspensionrestlength:.3,l=null!=m.frontwheel||n.toLowerCase().indexOf("front")>=0,u=o,c=r,d=-this._centerMass.x,h=-this._centerMass.z;null==e.RaycastVehicle.TempVector&&(e.RaycastVehicle.TempVector=new BABYLON.Vector3(0,0,0)),e.RaycastVehicle.TempVector.set(c+d,a,u+h),this.m_vehicle.addWheel(e.RaycastVehicle.TempVector,this.m_wheelDirectionCS0,this.m_wheelAxleCS,s,i,this.m_vehicleTuning,l)}if(this.m_vehicle.getNumWheels()===this.m_vehicleColliders.length){var p=[];for(t=0;t<this.m_vehicleColliders.length;t++){var m,f=null!=(m=this.m_vehicleColliders[t]).totalsuspensionforces?m.totalsuspensionforces:0,g=null!=m.suspensiontravelcm?m.suspensiontravelcm:50,v=null!=m.rollinfluence?m.rollinfluence:.1,y=null!=m.frictionslip?m.frictionslip:10,_=null!=m.suspensionstiffness?m.suspensionstiffness:50,S=null!=m.dampingcompression?m.dampingcompression:2.5,A=null!=m.dampingrelaxation?m.dampingrelaxation:4.5,b=null!=m.invertWheelDirection&&m.invertWheelDirection,M=null!=m.maxVisualTravelRange?m.maxVisualTravelRange:0,B=this.m_vehicle.getWheelInfo(t);null!=B&&(B.steeringAngle=0,B.rotationBoost=0,B.defaultFriction=y,B.invertWheelDirection=b,B.maxVisualTravelRange=M,B.frictionSlip=y,B.rollInfluence=v,B.maxSuspensionTravelCm=g,B.suspensionStiffness=_,B.dampingCompression=S,B.dampingRelaxation=A,f>0?B.maxSuspensionForce=f:p.push(t))}this.applyAutoSuspensionForce(p)}else BABYLON.Tools.Warn("Failed to create proper number of wheels for: "+this._chassisMesh.name);this.m_vehicle.cacheMassProperties()}},t.prototype.applyAutoSuspensionForce=function(t){if(null!=this.m_vehicle&&null!=t&&0!==t.length){var n=null!=this._chassisMesh?this._chassisMesh.physicsBody:null;if(null!=n){var i=n.getMassProperties(),r=null!=i&&null!=i.mass?i.mass:0;if(r>0){var o=9.81;if(null!=this.m_scene&&null!=this.m_scene.gravity){var a=this.m_scene.gravity.length();a>1e-4&&(o=a)}var s=e.RaycastVehicle.AutoSuspensionForceReserve,l=this.m_vehicle.getNumWheels();if(!(l<=0)){for(var u=0,c=0,d=0,h=0,p=0;p<l;p++)if(null!=(M=this.m_vehicle.getWheelInfo(p))){var m=this.getWheelForwardPosition(M.chassisConnectionPointCS);M.isFrontWheel?(u+=m,d++):(c+=m,h++)}var f=0,g=0;if(d>0&&h>0){var v=u/d,y=c/h,_=Math.abs(v-y);if((v>=0&&y<=0||v<=0&&y>=0)&&_>1e-4){var S=Math.abs(v),A=r*o;f=A*(Math.abs(y)/_)/d,g=A*(S/_)/h}}if(!(f>0&&g>0)){var b=r*o/l;f=b,g=b}for(p=0;p<t.length;p++){var M,B=t[p];if(null!=(M=this.m_vehicle.getWheelInfo(B))){var C=M.isFrontWheel?f:g;M.maxSuspensionForce=C*s}}}}}}},t.prototype.getWheelForwardPosition=function(e){if(null==e||null==this.m_vehicle)return 0;switch(this.m_vehicle.getForwardAxis()){case 0:return e.x;case 1:return e.y;default:return e.z}},t.prototype.getNaturalWheelSlip=function(e){var t=!1;return null!=this.m_vehicle&&(t=this.m_vehicle.getNaturalWheelSlip(e)),t},t.prototype.getWheelAtRestSpeedThresholdKmh=function(){return null!=this.m_vehicle?this.m_vehicle.wheelAtRestSpeedThresholdKmh:1},t.prototype.setWheelAtRestSpeedThresholdKmh=function(e){null!=this.m_vehicle&&(this.m_vehicle.wheelAtRestSpeedThresholdKmh=e)},t.prototype.updateWheelInformation=function(){var t=this.getNumWheels();if(t>0)for(var n=0;n<t;n++){var i=this.getWheelInfo(n);if(null!=i){var r=this.lockedWheelInformation(n);if(this.updateWheelTransform(n,!1),this.m_tempPosition=this.getWheelTransformPosition(n),null!=i.transform){var o=i.transform;if(null!=o.parent){this._tempVectorPos.copyFrom(this.m_tempPosition),e.Utilities.InverseTransformPointToRef(o.parent,this._tempVectorPos,this._tempVectorPos),o.position.y=this._tempVectorPos.y,this.ensureNodeRotationQuaternion(o);var a=null!=i.steeringAngle?i.steeringAngle:0;BABYLON.Quaternion.FromEulerAnglesToRef(0,a,0,o.rotationQuaternion),null!=i.spinner&&(!0===r?i.spinnerLocked=!0:(!0===i.spinnerLocked&&(this.rebaseWheelSpinnerRotation(i),i.spinnerLocked=!1),this.syncWheelSpinnerRotation(i)))}}}}},t.prototype.lockedWheelInformation=function(e){var t=!1;if(null!=this.lockedWheelIndexes&&this.lockedWheelIndexes.length>0)for(var n=0;n<this.lockedWheelIndexes.length;n++)if(this.lockedWheelIndexes[n]===e){t=!0;break}return t},t.prototype.deleteWheelInformation=function(){var e=this.getNumWheels();if(e>0)for(var t=0;t<e;t++){var n=this.getWheelInfo(t);null!=n&&(null!=n.transform&&delete n.transform,null!=n.spinner&&delete n.spinner,null!=n.steeringAngle&&delete n.steeringAngle,null!=n.rotationBoost&&delete n.rotationBoost,null!=n.invertWheelDirection&&delete n.invertWheelDirection,null!=n.defaultFriction&&delete n.defaultFriction,null!=n.spinnerBaseRotation&&delete n.spinnerBaseRotation,null!=n.spinnerBaseNode&&delete n.spinnerBaseNode,null!=n.spinnerLocked&&delete n.spinnerLocked)}},t.TempVector=null,t.AutoSuspensionForceReserve=3.5,t}();e.RaycastVehicle=t}(i||(i={})),function(e){var t=function(t){function n(e,n,i,r){void 0===i&&(i={}),void 0===r&&(r="TOOLKIT.RigidbodyPhysics");var o=t.call(this,e,n,i,r)||this;return o._isKinematic=!1,o._centerOfMass=new BABYLON.Vector3(0,0,0),o.m_raycastVehicle=null,o}return r(n,t),n.prototype.awake=function(){this.awakeRigidbodyState()},n.prototype.update=function(){this.updateRigidbodyState()},n.prototype.fixed=function(){this.fixedRigidbodyState()},n.prototype.destroy=function(){this.destroyRigidbodyState()},n.prototype.awakeRigidbodyState=function(){this._isKinematic=this.getProperty("isKinematic",this._isKinematic),null!=this.transform.metadata&&null!=this.transform.metadata.toolkit&&null!=this.transform.metadata.toolkit.physics&&(this._centerOfMass=null!=this.transform.metadata.toolkit.physics.center?e.Utilities.ParseVector3(this.transform.metadata.toolkit.physics.center,this._centerOfMass):this._centerOfMass),this.hasWheelColliders()&&(this._isKinematic=!1,this.transform.physicsBody.disablePreStep=!1,this.m_raycastVehicle=new e.RaycastVehicle(this.scene,this.transform,this._centerOfMass),e.Utilities.ShowDebugColliders()&&console.log("Raycase Vehicle Created For: "+this.transform.name))},n.prototype.updateRigidbodyState=function(){null!=this.m_raycastVehicle&&this.m_raycastVehicle.updateWheelInformation()},n.prototype.fixedRigidbodyState=function(){null!=this.m_raycastVehicle&&this.m_raycastVehicle.tickVehicleController(e.RigidbodyPhysics.PHYSICS_STEP_TIME)},n.prototype.destroyRigidbodyState=function(){null!=this.m_raycastVehicle&&(this.m_raycastVehicle.dispose(),this.m_raycastVehicle=null)},n.prototype.isKinematic=function(){return this._isKinematic},n.prototype.hasWheelColliders=function(){return null!=this.transform.metadata&&null!=this.transform.metadata.toolkit&&null!=this.transform.metadata.toolkit.wheels},n.prototype.getRaycastVehicle=function(){return this.m_raycastVehicle},n.GetHavokInstance=function(){return globalThis.HK},n.Raycast=function(t,n,i,r){return null==e.RigidbodyPhysics.RaycastResult&&(e.RigidbodyPhysics.RaycastResult=new BABYLON.PhysicsRaycastResult),null==e.RigidbodyPhysics.RaycastDestination&&(e.RigidbodyPhysics.RaycastDestination=new BABYLON.Vector3(0,0,0)),e.RigidbodyPhysics.RaycastResult.reset(),e.RigidbodyPhysics.RaycastDestination.set(0,0,0),e.Utilities.CalculateDestinationPointToRef(t,n,i,e.RigidbodyPhysics.RaycastDestination),e.RigidbodyPhysics.RaycastToRef(t,e.RigidbodyPhysics.RaycastDestination,e.RigidbodyPhysics.RaycastResult,r),e.RigidbodyPhysics.RaycastResult},n.Shapecast=function(t){return null==e.RigidbodyPhysics.LocalShapeResult&&(e.RigidbodyPhysics.LocalShapeResult=new BABYLON.ShapeCastResult),null==e.RigidbodyPhysics.WorldShapeResult&&(e.RigidbodyPhysics.WorldShapeResult=new BABYLON.ShapeCastResult),e.RigidbodyPhysics.LocalShapeResult.reset(),e.RigidbodyPhysics.WorldShapeResult.reset(),e.RigidbodyPhysics.ShapecastToRef(t,e.RigidbodyPhysics.LocalShapeResult,e.RigidbodyPhysics.WorldShapeResult),{local:e.RigidbodyPhysics.LocalShapeResult,world:e.RigidbodyPhysics.WorldShapeResult}},n.RaycastToRef=function(t,n,i,r){var o=e.Utilities.GetHavokPlugin();if(o){null==e.RigidbodyPhysics.RaycastResult&&(e.RigidbodyPhysics.RaycastResult=new BABYLON.PhysicsRaycastResult),null==e.RigidbodyPhysics.RaycastDestination&&(e.RigidbodyPhysics.RaycastDestination=new BABYLON.Vector3(0,0,0)),e.RigidbodyPhysics.RaycastResult.reset(),e.RigidbodyPhysics.RaycastDestination.set(0,0,0);var a=null!=i?i:e.RigidbodyPhysics.RaycastResult;o.raycast(t,n,a,r)}else BABYLON.Tools.Warn("Havok.js physics library not loaded")},n.ShapecastToRef=function(t,n,i){var r=e.Utilities.GetHavokPlugin();if(r){null==e.RigidbodyPhysics.LocalShapeResult&&(e.RigidbodyPhysics.LocalShapeResult=new BABYLON.ShapeCastResult),null==e.RigidbodyPhysics.WorldShapeResult&&(e.RigidbodyPhysics.WorldShapeResult=new BABYLON.ShapeCastResult),e.RigidbodyPhysics.LocalShapeResult.reset(),e.RigidbodyPhysics.WorldShapeResult.reset();var o=null!=n?n:e.RigidbodyPhysics.LocalShapeResult,a=null!=i?i:e.RigidbodyPhysics.WorldShapeResult;r.shapeCast(t,o,a)}else BABYLON.Tools.Warn("Havok.js physics library not loaded")},n.SetMaxVelocities=function(t,n){var i=e.Utilities.GetHavokPlugin();if(i){var r=i._hknp.HEAP8.buffer,o=new Int32Array(r,Number(i.world),100),a=new Int32Array(r,o[8],500),s=new Int32Array(r,a[428],100),l=new Float32Array(r,s[8],300);l[32]=t,l[33]=n,l[60]=t,l[61]=n,l[88]=t,l[89]=n,l[144]=t,l[145]=n,l[172]=t,l[173]=n,l[200]=t,l[201]=n,l[228]=t}else BABYLON.Tools.Warn("Havok.js physics library not loaded")},n.ConfigurePhysicsEngine=function(t){return a(this,arguments,void 0,function(t,n,i,r,o,a,l){var u,c,d,h,p,m,f;return void 0===n&&(n=!0),void 0===i&&(i=0),void 0===r&&(r=0),void 0===o&&(o=!0),void 0===a&&(a=1e-4),void 0===l&&(l=null),s(this,function(r){switch(r.label){case 0:if(!BABYLON.HavokPlugin)return[3,7];r.label=1;case 1:return r.trys.push([1,5,6,7]),t.isPhysicsEnabled()?[3,4]:null!=(u=e.RigidbodyPhysics.GetHavokInstance())?[3,3]:(c=globalThis,[4,BABYLON.HavokPhysics()]);case 2:c.HK=r.sent(),u=globalThis.HK,r.label=3;case 3:return d=new BABYLON.Vector3(0,-9.81,0),h=null!=l?l:d,globalThis.HKP=new BABYLON.HavokPlugin(!n,u),t.enablePhysics(h,globalThis.HKP),[3,4];case 4:return[3,7];case 5:return p=r.sent(),console.warn(p),[3,7];case 6:e.RigidbodyPhysics.PhysicsShapeCache={},e.RigidbodyPhysics.NewPhysicsShapeCount=0,e.RigidbodyPhysics.CachedPhysicsShapeCount=0;try{null===(f=t.getPhysicsEngine())||void 0===f||f.setSubTimeStep(i),BABYLON.Tools.Log("Havok.js initialized with sub time step of "+i),m=e.RigidbodyPhysics.GetPhysicsHeapSize(),BABYLON.Tools.Log("Havok.js initialized with a heap size of "+m+" MB")}catch(e){console.warn(e)}try{null!=e.RigidbodyPhysics.OnSetupPhysicsPlugin&&e.RigidbodyPhysics.OnSetupPhysicsPlugin(t)}catch(e){console.warn(e)}return[7];case 7:return[2]}})})},n.SetupPhysicsComponent=function(t,n){var i=null!=n.metadata&&null!=n.metadata.toolkit?n.metadata.toolkit:null,r=null!=i.layermask?i.layermask:-1;if(null!=i&&(null!=i.physics||null!=i.collision)){var o=null!=i.physics,a=null!=i.physics&&null!=i.physics.filter?i.physics.filter:-1,s=null!=i.physics&&null!=i.physics.vehicle&&i.physics.vehicle,l=null!=i.physics&&null!=i.physics.root&&i.physics.root,u=null!=i.collision&&null!=i.collision.compoundcolliders,c=null!=i.physics&&null!=i.physics.mass?i.physics.mass:0,d=null!=i.physics&&null!=i.physics.center?i.physics.center:{x:0,y:0,z:0},h=null==i.physics||null==i.physics.kinematic||i.physics.kinematic,p=null==i.physics||null==i.physics.truestatic||i.physics.truestatic,m=BABYLON.PhysicsMotionType.DYNAMIC;if(m=!0===p?BABYLON.PhysicsMotionType.STATIC:!0===h?BABYLON.PhysicsMotionType.ANIMATED:BABYLON.PhysicsMotionType.DYNAMIC,!0===o){if(s){var f=null,g=n.getChildren(null,!1);null!=g&&g.length>0&&g.forEach(function(t){if(null!=t.metadata&&null!=t.metadata.toolkit&&null!=t.metadata.toolkit.collision){var i=t.metadata.toolkit.collision,r=null!=i.wheelinformation?i.wheelinformation:null;null!=r&&(e.Utilities.ShowDebugColliders()&&console.log("Setup raycast wheel collider: "+t.name+" --\x3e on to: "+n.name,n),null==f&&(f=[]),f.push(r))}}),null!=f&&f.length>0&&(null==n.metadata&&(n.metadata={}),null==n.metadata.toolkit&&(n.metadata.toolkit={}),n.metadata.toolkit.wheels=f)}if(u){var v=i.collision.compoundcolliders;if(null!=v&&v.length>0){var y=0,_=0,S=0,A=!1,b=[];if(v.forEach(function(i){if(null!=i){var o=null!=i.type?i.type:"BoxCollider",s=null!=i.restitutioncombine?e.RigidbodyPhysics.GetPhysicsMaterialCombine(i.restitutioncombine):0,l=null!=i.frictioncombine?e.RigidbodyPhysics.GetPhysicsMaterialCombine(i.frictioncombine):0,u=null!=i.dynamicfriction?i.dynamicfriction:.6,c=null!=i.staticfriction?i.staticfriction:.6,d=null!=i.restitution?i.restitution:0,h=null!=i.trigger&&i.trigger;u>y&&(y=u),c>_&&(_=c),d>S&&(S=d),1==h&&(A=!0);var p=e.RigidbodyPhysics.BoxImpostor;p="MeshCollider"===o?e.RigidbodyPhysics.ConvexHullImpostor:"CapsuleCollider"===o?e.RigidbodyPhysics.CapsuleImpostor:"SphereCollider"===o?e.RigidbodyPhysics.SphereImpostor:e.RigidbodyPhysics.BoxImpostor;var m=i,f=null!=m.center?m.center:{x:0,y:0,z:0},g=null!=m.persist&&m.persist,v=new e.PhyscisContainerData;e.Utilities.ShowDebugColliders()&&console.log("Setup simple compound child collider type ("+o+") --\x3e on to: "+n.name,n),e.RigidbodyPhysics.CreateCompoundPhysicsShapeAndBody(t,n,n,m,p,c,u,d,l,s,b,v,f,!1,h,g,r,a)}}),b.length>0){e.Utilities.ReparentColliders()||n.setParent(null,!0,!0);var M=new BABYLON.Vector3(d.x,d.y,d.z),B=new BABYLON.PhysicsShapeContainer(t);b.forEach(function(e){B.addChild(e.shape,e.translation,e.rotation,e.scale)}),B.material=b[0].shape.material;var C=new BABYLON.PhysicsBody(n,m,!1,t);C.shape=B,e.RigidbodyPhysics.ConfigRigidbodyPhysics(t,n,!1,A,i.physics,c,M),e.Utilities.ShowDebugColliders()||null!=(E=n).material&&"CenterBox-Material"===E.material.name&&(E.isVisible=!1),e.Utilities.ShowDebugColliders()&&(null==e.RigidbodyPhysics.DebugPhysicsViewer&&(e.RigidbodyPhysics.DebugPhysicsViewer=new BABYLON.Debug.PhysicsViewer),null!=e.RigidbodyPhysics.DebugPhysicsViewer&&e.RigidbodyPhysics.DebugPhysicsViewer.showBody(C))}}}else if(l){var T=0,x=0,I=0,O=!1,L=[],w=null!=i.physics&&null!=i.physics.center?e.Utilities.ParseVector3(i.physics.center,BABYLON.Vector3.Zero()):BABYLON.Vector3.Zero(),N=n.getChildren(null,!0);null!=N&&N.length>0&&N.forEach(function(e){e.position.subtractInPlace(w)});var P=n.getChildren(null,!1);if(null!=P&&P.length>0&&P.forEach(function(i){if(null!=i.metadata&&null!=i.metadata.toolkit&&null!=i.metadata.toolkit.collision){var o=i.metadata.toolkit.collision,s=null!=o.restitutioncombine?e.RigidbodyPhysics.GetPhysicsMaterialCombine(o.restitutioncombine):0,u=null!=o.frictioncombine?e.RigidbodyPhysics.GetPhysicsMaterialCombine(o.frictioncombine):0,c=null!=o.dynamicfriction?o.dynamicfriction:.6,d=null!=o.staticfriction?o.staticfriction:.6,h=null!=o.restitution?o.restitution:0,p=null!=o.trigger&&o.trigger,m=null!=o.type?o.type:"BoxCollider";c>T&&(T=c),d>x&&(x=d),h>I&&(I=h),1==p&&(O=!0);var f=e.RigidbodyPhysics.BoxImpostor;f="MeshCollider"===m?e.RigidbodyPhysics.ConvexHullImpostor:"CapsuleCollider"===m?e.RigidbodyPhysics.CapsuleImpostor:"SphereCollider"===m?e.RigidbodyPhysics.SphereImpostor:e.RigidbodyPhysics.BoxImpostor;var g=o,v=null!=g.center?g.center:{x:0,y:0,z:0},y=null!=g.persist&&g.persist,_=new e.PhyscisContainerData;e.Utilities.ShowDebugColliders()&&console.log("Setup complex compound child collider type ("+m+") --\x3e on to: "+n.name,n),e.RigidbodyPhysics.CreateCompoundPhysicsShapeAndBody(t,n,i,g,f,d,c,h,u,s,L,_,v,l,p,y,r,a)}}),L.length>0){e.Utilities.ReparentColliders()||n.setParent(null,!0,!0),M=new BABYLON.Vector3(d.x,d.y,d.z);var R=new BABYLON.PhysicsShapeContainer(t);R.material=L[0].shape.material,L.forEach(function(e){R.addChild(e.shape,e.translation,e.rotation,e.scale)});var E,k=new BABYLON.PhysicsBody(n,m,!1,t);k.shape=R,e.RigidbodyPhysics.ConfigRigidbodyPhysics(t,n,!1,O,i.physics,c,M),e.Utilities.ShowDebugColliders()||null!=(E=n).material&&"CenterBox-Material"===E.material.name&&(E.isVisible=!1),e.Utilities.ShowDebugColliders()&&(null==e.RigidbodyPhysics.DebugPhysicsViewer&&(e.RigidbodyPhysics.DebugPhysicsViewer=new BABYLON.Debug.PhysicsViewer),null!=e.RigidbodyPhysics.DebugPhysicsViewer&&e.RigidbodyPhysics.DebugPhysicsViewer.showBody(k))}}else if(null!=i.collision){var D=null!=i.collision.type?i.collision.type:"BoxCollider",F=null!=i.collision.convexmesh&&i.collision.convexmesh,U=null!=i.collision.restitutioncombine?e.RigidbodyPhysics.GetPhysicsMaterialCombine(i.collision.restitutioncombine):0,Y=null!=i.collision.frictioncombine?e.RigidbodyPhysics.GetPhysicsMaterialCombine(i.collision.frictioncombine):0,V=null!=i.collision.dynamicfriction?i.collision.dynamicfriction:.6,G=null!=i.collision.staticfriction?i.collision.staticfriction:.6,z=null!=i.collision.restitution?i.collision.restitution:0,W=null!=i.collision.terraindata?i.collision.terraindata:null,H=null!=i.collision.trigger&&i.collision.trigger,X=null!=i.collision.persist&&i.collision.persist,K=e.RigidbodyPhysics.BoxImpostor;K="MeshCollider"===D?!0===F?e.RigidbodyPhysics.ConvexHullImpostor:e.RigidbodyPhysics.MeshImpostor:"TerrainCollider"===D?e.RigidbodyPhysics.HeightmapImpostor:"CapsuleCollider"===D?e.RigidbodyPhysics.CapsuleImpostor:"SphereCollider"===D?e.RigidbodyPhysics.SphereImpostor:e.RigidbodyPhysics.BoxImpostor,e.RigidbodyPhysics.CreateStandardPhysicsShapeAndBody(t,n,i,K,H,p,m,c,G,V,z,Y,U,W,d,X,r,a)}}null!=n&&null!=n.physicsBody&&!0===h&&(n.physicsBody.disablePreStep=!1)}},n.GetPhysicsMaterialCombine=function(e){switch(e){case 0:default:return BABYLON.PhysicsMaterialCombineMode.ARITHMETIC_MEAN;case 1:return BABYLON.PhysicsMaterialCombineMode.MULTIPLY;case 2:return BABYLON.PhysicsMaterialCombineMode.MINIMUM;case 3:return BABYLON.PhysicsMaterialCombineMode.MAXIMUM}},n.GetCachedPhysicsMeshShape=function(t,n,i,r,o,a,s,l,u,c){if(null==i||""===i)return console.warn("Invalid mesh key specfifed for child collider: "+n.name),null;i+="_SF"+r+"_DF"+o+"_R"+a+"_T0_L"+u+"_X"+c;var d=e.RigidbodyPhysics.PhysicsShapeCache[i];return null==d?((d=new BABYLON.PhysicsShapeMesh(n,t)).material={friction:o,staticFriction:r,restitution:a,frictionCombine:s,restitutionCombine:l},d.isTrigger=!1,d.filterMembershipMask=u,e.RigidbodyPhysics.NewPhysicsShapeCount++,e.RigidbodyPhysics.PhysicsShapeCache[i]=d):e.RigidbodyPhysics.CachedPhysicsShapeCount++,d},n.GetCachedPhysicsConvexHullShape=function(t,n,i,r,o,a,s,l,u,c){if(null==i||""===i)return console.warn("Invalid mesh key specfifed for child collider: "+n.name),null;i+="_SF"+r+"_DF"+o+"_R"+a+"_T0_L"+u+"_X"+c;var d=e.RigidbodyPhysics.PhysicsShapeCache[i];return null==d?((d=new BABYLON.PhysicsShapeConvexHull(n,t)).material={friction:o,staticFriction:r,restitution:a,frictionCombine:s,restitutionCombine:l},d.isTrigger=!1,d.filterMembershipMask=u,e.RigidbodyPhysics.NewPhysicsShapeCount++,e.RigidbodyPhysics.PhysicsShapeCache[i]=d):e.RigidbodyPhysics.CachedPhysicsShapeCount++,d},n.GetCachedPhysicsBoxShape=function(t,n,i,r,o,a,s,l,u){var c="SHAPE_BOX_SF"+i+"_DF"+r+"_R"+o+"_T"+(1==n?"1":"0")+"_L"+l+"_X"+u,d=e.RigidbodyPhysics.PhysicsShapeCache[c];return null==d?((d=new BABYLON.PhysicsShapeBox(new BABYLON.Vector3(0,0,0),new BABYLON.Quaternion(0,0,0,1),new BABYLON.Vector3(1,1,1),t)).material={friction:r,staticFriction:i,restitution:o,frictionCombine:a,restitutionCombine:s},d.isTrigger=n,d.filterMembershipMask=l,e.RigidbodyPhysics.NewPhysicsShapeCount++,e.RigidbodyPhysics.PhysicsShapeCache[c]=d):e.RigidbodyPhysics.CachedPhysicsShapeCount++,d},n.GetCachedPhysicsSphereShape=function(t,n,i,r,o,a,s,l,u){var c="SHAPE_SPHERE_SF"+i+"_DF"+r+"_R"+o+"_T"+(1==n?"1":"0")+"_L"+l+"_X"+u,d=e.RigidbodyPhysics.PhysicsShapeCache[c];return null==d?((d=new BABYLON.PhysicsShapeSphere(new BABYLON.Vector3(0,0,0),1,t)).material={friction:r,staticFriction:i,restitution:o,frictionCombine:a,restitutionCombine:s},d.isTrigger=n,d.filterMembershipMask=l,e.RigidbodyPhysics.NewPhysicsShapeCount++,e.RigidbodyPhysics.PhysicsShapeCache[c]=d):e.RigidbodyPhysics.CachedPhysicsShapeCount++,d},n.GetCachedPhysicsCapsuleShape=function(t,n,i,r,o,a,s,l,u){var c="SHAPE_CAPSULE_SF"+i+"_DF"+r+"_R"+o+"_T"+(1==n?"1":"0")+"_L"+l+"_X"+u,d=e.RigidbodyPhysics.PhysicsShapeCache[c];return null==d?((d=new BABYLON.PhysicsShapeCapsule(new BABYLON.Vector3(0,-1,0),new BABYLON.Vector3(0,1,0),1,t)).material={friction:r,staticFriction:i,restitution:o,frictionCombine:a,restitutionCombine:s},d.isTrigger=n,d.filterMembershipMask=l,e.RigidbodyPhysics.NewPhysicsShapeCount++,e.RigidbodyPhysics.PhysicsShapeCache[c]=d):e.RigidbodyPhysics.CachedPhysicsShapeCount++,d},n.GetCachedPhysicsCylinderShape=function(t,n,i,r,o,a,s,l,u){var c="SHAPE_CYLINDER_SF"+i+"_DF"+r+"_R"+o+"_T"+(1==n?"1":"0")+"_L"+l+"_X"+u,d=e.RigidbodyPhysics.PhysicsShapeCache[c];return null==d?((d=new BABYLON.PhysicsShapeCylinder(new BABYLON.Vector3(0,-.5,0),new BABYLON.Vector3(0,.5,0),1,t)).material={friction:r,staticFriction:i,restitution:o,frictionCombine:a,restitutionCombine:s},d.isTrigger=n,d.filterMembershipMask=l,e.RigidbodyPhysics.NewPhysicsShapeCount++,e.RigidbodyPhysics.PhysicsShapeCache[c]=d):e.RigidbodyPhysics.CachedPhysicsShapeCount++,d},n.CreateStandardPhysicsShapeAndBody=function(t,n,i,r,o,a,s,l,u,c,d,h,p,m,f,g,v,y){var _=i.collision,S=null!=_.meshkey?_.meshkey:null,A=null!=_.center?_.center:{x:0,y:0,z:0};if(r==e.RigidbodyPhysics.HeightmapImpostor)if(null!=m){e.Utilities.ReparentColliders()||n.setParent(null,!0,!0);var b=n,M=m.index,B=m.segments,C=m.resolution,T=m.width,x=(m.height,m.length);if(1===(null!=m.collider?m.collider:0)){var I=1,O=1,L=0,w=0;if(1===B)L=.5*(T+(I=T/(C-1))),w=.5*(x-(O=x/(C-1)));else if(2===B){var N=T/B,P=x/B;I=T/(C-1),O=x/(C-1),0===M?(L=.5*(N+I)+0,w=.5*(P-O)+0):1===M?(L=.5*(1*N+I)+0,w=.5*(P-O)+P):2===M?(L=.5*(1*N+I)+N,w=.5*(P-O)+0):3===M&&(L=.5*(1*N+I)+N,w=.5*(P-O)+P)}var R=e.RigidbodyPhysics.CreateHeightFieldTerrainShapeFromMesh(b,I,O),E=new BABYLON.PhysicsShape({type:BABYLON.PhysicsShapeType.HEIGHTFIELD,pluginData:R},t);E.filterMembershipMask=v,E.material={friction:c,staticFriction:u,restitution:d,frictionCombine:h,restitutionCombine:p};var k="TERRAIN_MESH_ID"+b.uniqueId+"_SF"+u+"_DF"+c+"_R"+d+"_T0_L"+v+"_X"+y;e.RigidbodyPhysics.NewPhysicsShapeCount++,e.RigidbodyPhysics.PhysicsShapeCache[k]=E;var D=new BABYLON.Vector3(L,0,w),F=new BABYLON.Quaternion(0,0,0,1),U=new BABYLON.Vector3(1,1,1),Y=new BABYLON.PhysicsShapeContainer(t);Y.material=E.material,e.Utilities.FromEulerToRef(0,90,0,F),E.isTrigger=!1,Y.addChild(E,D,F,U);var V=new BABYLON.PhysicsBody(n,BABYLON.PhysicsMotionType.STATIC,!1,t);V.shape=Y,e.Utilities.ShowDebugColliders()&&console.log("Setup standard terrain heightmap physics collider for: "+n.name,n),e.RigidbodyPhysics.ConfigRigidbodyPhysics(t,n,!1,o,i.physics,0,new BABYLON.Vector3(f.x,f.y,f.z)),e.Utilities.ShowDebugColliders()||null!=(be=n).material&&"CenterBox-Material"===be.material.name&&(be.isVisible=!1),e.Utilities.ShowDebugColliders()&&(null==e.RigidbodyPhysics.DebugPhysicsViewer&&(e.RigidbodyPhysics.DebugPhysicsViewer=new BABYLON.Debug.PhysicsViewer),null!=e.RigidbodyPhysics.DebugPhysicsViewer&&e.RigidbodyPhysics.DebugPhysicsViewer.showBody(V))}else(W=new BABYLON.PhysicsShapeMesh(b,t)).filterMembershipMask=v,W.material={friction:c,staticFriction:u,restitution:d,frictionCombine:h,restitutionCombine:p},(z=new BABYLON.PhysicsBody(n,BABYLON.PhysicsMotionType.STATIC,!1,t)).shape=W,e.Utilities.ShowDebugColliders()&&console.log("Setup terrain mesh physics collider for: "+n.name,n),e.RigidbodyPhysics.ConfigRigidbodyPhysics(t,n,!1,o,i.physics,0,new BABYLON.Vector3(f.x,f.y,f.z)),e.Utilities.ShowDebugColliders()||null!=(be=n).material&&"CenterBox-Material"===be.material.name&&(be.isVisible=!1),e.Utilities.ShowDebugColliders()&&(null==e.RigidbodyPhysics.DebugPhysicsViewer&&(e.RigidbodyPhysics.DebugPhysicsViewer=new BABYLON.Debug.PhysicsViewer),null!=e.RigidbodyPhysics.DebugPhysicsViewer&&e.RigidbodyPhysics.DebugPhysicsViewer.showBody(z))}else BABYLON.Tools.Warn("No terrain collision data found for: "+n.name+". No terrain collision impostor will be created.");else if(r==e.RigidbodyPhysics.MeshImpostor){var G=e.SceneManager.FindChildTransformNode(n,n.name+".Collider",e.SearchType.ExactMatch,!0);if(null!=G){e.Utilities.ReparentColliders()||n.setParent(null,!0,!0);var z=new BABYLON.PhysicsBody(n,BABYLON.PhysicsMotionType.STATIC,!1,t),W=e.RigidbodyPhysics.GetCachedPhysicsMeshShape(t,G,S,u,c,d,h,p,v,y),H=new BABYLON.PhysicsShapeContainer(t);H.material=W.material,e.RigidbodyPhysics.AddChildShapeFromParent(H,n,W,G),z.shape=H,!1===g&&e.Utilities.AddLoaderItemMarkedForDisposal(G),e.Utilities.ShowDebugColliders()&&console.log("Setup standard mesh physics collider for: "+n.name,n),e.RigidbodyPhysics.ConfigRigidbodyPhysics(t,n,!1,o,i.physics,0,new BABYLON.Vector3(f.x,f.y,f.z)),e.Utilities.ShowDebugColliders()||null!=(be=n).material&&"CenterBox-Material"===be.material.name&&(be.isVisible=!1),e.Utilities.ShowDebugColliders()&&(null==e.RigidbodyPhysics.DebugPhysicsViewer&&(e.RigidbodyPhysics.DebugPhysicsViewer=new BABYLON.Debug.PhysicsViewer),null!=e.RigidbodyPhysics.DebugPhysicsViewer&&e.RigidbodyPhysics.DebugPhysicsViewer.showBody(z))}else BABYLON.Tools.Warn("No mesh collider found for: "+n.name+".")}else if(r==e.RigidbodyPhysics.ConvexHullImpostor){var X=e.SceneManager.FindChildTransformNode(n,n.name+".Collider",e.SearchType.ExactMatch,!0);if(null!=X){!1===g&&e.Utilities.AddLoaderItemMarkedForDisposal(X),e.Utilities.ReparentColliders()||n.setParent(null,!0,!0);var K=e.RigidbodyPhysics.GetCachedPhysicsConvexHullShape(t,X,S,u,c,d,h,p,v,y),Q=new BABYLON.PhysicsShapeContainer(t);Q.material=K.material,e.RigidbodyPhysics.AddChildShapeFromParent(Q,n,K,X);var j=new BABYLON.PhysicsBody(n,s,!1,t);j.shape=Q,e.Utilities.ShowDebugColliders()&&console.log("Setup standard convex hull physics collider for: "+n.name,n),e.RigidbodyPhysics.ConfigRigidbodyPhysics(t,n,!0,!1,i.physics,l,new BABYLON.Vector3(f.x,f.y,f.z)),e.Utilities.ShowDebugColliders()||null!=(be=n).material&&"CenterBox-Material"===be.material.name&&(be.isVisible=!1),e.Utilities.ShowDebugColliders()&&(null==e.RigidbodyPhysics.DebugPhysicsViewer&&(e.RigidbodyPhysics.DebugPhysicsViewer=new BABYLON.Debug.PhysicsViewer),null!=e.RigidbodyPhysics.DebugPhysicsViewer&&e.RigidbodyPhysics.DebugPhysicsViewer.showBody(j))}else BABYLON.Tools.Warn("No convex hull child mesh collider found for: "+n.name+".")}else if(r==e.RigidbodyPhysics.BoxImpostor){e.Utilities.ReparentColliders()||n.setParent(null,!0,!0);var Z=null!=_.boxsize?_.boxsize:{x:1,y:1,z:1},q=Z.x*parseFloat(n.scaling.x.toFixed(4)),J=Z.y*parseFloat(n.scaling.y.toFixed(4)),$=Z.z*parseFloat(n.scaling.z.toFixed(4)),ee=A.x*parseFloat(n.scaling.x.toFixed(4)),te=A.y*parseFloat(n.scaling.y.toFixed(4)),ne=A.z*parseFloat(n.scaling.z.toFixed(4)),ie=new BABYLON.Vector3(ee,te,ne),re=e.RigidbodyPhysics.GetCachedPhysicsBoxShape(t,o,u,c,d,h,p,v,y),oe=new BABYLON.PhysicsShapeContainer(t);oe.material=re.material,oe.addChild(re,ie,new BABYLON.Quaternion(0,0,0,1),new BABYLON.Vector3(q,J,$));var ae=new BABYLON.PhysicsBody(n,s,!1,t);ae.shape=oe,e.Utilities.ShowDebugColliders()&&console.log("Setup standard box physics collider for: "+n.name,n),e.RigidbodyPhysics.ConfigRigidbodyPhysics(t,n,!1,!1,i.physics,l,ie.add(new BABYLON.Vector3(f.x,f.y,f.z))),e.Utilities.ShowDebugColliders()||null!=(be=n).material&&"CenterBox-Material"===be.material.name&&(be.isVisible=!1),e.Utilities.ShowDebugColliders()&&(null==e.RigidbodyPhysics.DebugPhysicsViewer&&(e.RigidbodyPhysics.DebugPhysicsViewer=new BABYLON.Debug.PhysicsViewer),null!=e.RigidbodyPhysics.DebugPhysicsViewer&&e.RigidbodyPhysics.DebugPhysicsViewer.showBody(ae))}else if(r==e.RigidbodyPhysics.SphereImpostor){e.Utilities.ReparentColliders()||n.setParent(null,!0,!0);var se=null!=_.sphereradius?_.sphereradius:.5,le=parseFloat(n.scaling.x.toFixed(4)),ue=parseFloat(n.scaling.y.toFixed(4)),ce=parseFloat(n.scaling.z.toFixed(4)),de=Math.max(le,ue,ce)*se,he=(ee=A.x*parseFloat(n.scaling.x.toFixed(4)),te=A.y*parseFloat(n.scaling.y.toFixed(4)),ne=A.z*parseFloat(n.scaling.z.toFixed(4)),ie=new BABYLON.Vector3(ee,te,ne),e.RigidbodyPhysics.GetCachedPhysicsSphereShape(t,o,u,c,d,h,p,v,y)),pe=new BABYLON.PhysicsShapeContainer(t);pe.material=he.material,pe.addChild(he,ie,new BABYLON.Quaternion(0,0,0,1),new BABYLON.Vector3(de,de,de));var me=new BABYLON.PhysicsBody(n,s,!1,t);me.shape=pe,e.Utilities.ShowDebugColliders()&&console.log("Setup standard sphere physics collider for: "+n.name,n),e.RigidbodyPhysics.ConfigRigidbodyPhysics(t,n,!1,!1,i.physics,l,ie.add(new BABYLON.Vector3(f.x,f.y,f.z))),e.Utilities.ShowDebugColliders()||null!=(be=n).material&&"CenterBox-Material"===be.material.name&&(be.isVisible=!1),e.Utilities.ShowDebugColliders()&&(null==e.RigidbodyPhysics.DebugPhysicsViewer&&(e.RigidbodyPhysics.DebugPhysicsViewer=new BABYLON.Debug.PhysicsViewer),null!=e.RigidbodyPhysics.DebugPhysicsViewer&&e.RigidbodyPhysics.DebugPhysicsViewer.showBody(me))}else if(r==e.RigidbodyPhysics.CapsuleImpostor){e.Utilities.ReparentColliders()||n.setParent(null,!0,!0);var fe=null!=_.cylinder&&_.cylinder,ge=null!=_.capsulesize?_.capsulesize:{x:.5,y:2,z:1},ve=ge.x*parseFloat(n.scaling.x.toFixed(4)),ye=ge.y*parseFloat(n.scaling.y.toFixed(4)),_e=parseFloat(n.scaling.z.toFixed(4));_e=!0===fe?e.RigidbodyPhysics.GetCachedPhysicsCylinderShape(t,o,u,c,d,h,p,v,y):e.RigidbodyPhysics.GetCachedPhysicsCapsuleShape(t,o,u,c,d,h,p,v,y);var Se=new BABYLON.Quaternion(0,0,0,1);0!==ge.z&&2!==ge.z||(0===ge.z?e.Utilities.FromEulerToRef(0,0,90,Se):2===ge.z&&e.Utilities.FromEulerToRef(90,0,0,Se)),ee=A.x*parseFloat(n.scaling.x.toFixed(4)),te=A.y*parseFloat(n.scaling.y.toFixed(4)),ne=A.z*parseFloat(n.scaling.z.toFixed(4)),ie=new BABYLON.Vector3(ee,te,ne);var Ae=new BABYLON.PhysicsShapeContainer(t);Ae.material=_e.material,Ae.addChild(_e,ie,Se,new BABYLON.Vector3(ve,ye,ve));var be,Me=new BABYLON.PhysicsBody(n,s,!1,t);Me.shape=Ae,e.Utilities.ShowDebugColliders()&&console.log("Setup standard "+(!0===fe?"cylinder":"capsule")+" physics collider for: "+n.name,n),e.RigidbodyPhysics.ConfigRigidbodyPhysics(t,n,!1,!1,i.physics,l,ie.add(new BABYLON.Vector3(f.x,f.y,f.z))),e.Utilities.ShowDebugColliders()||null!=(be=n).material&&"CenterBox-Material"===be.material.name&&(be.isVisible=!1),e.Utilities.ShowDebugColliders()&&(null==e.RigidbodyPhysics.DebugPhysicsViewer&&(e.RigidbodyPhysics.DebugPhysicsViewer=new BABYLON.Debug.PhysicsViewer),null!=e.RigidbodyPhysics.DebugPhysicsViewer&&e.RigidbodyPhysics.DebugPhysicsViewer.showBody(Me))}},n.CreateCompoundPhysicsShapeAndBody=function(t,n,i,r,o,a,s,l,u,c,d,h,p,m,f,g,v,y){var _=0,S=0,A=0,b=new BABYLON.Vector3(0,0,0),M=new BABYLON.Quaternion(0,0,0,1),B=new BABYLON.Vector3(1,1,1);if(!1===g&&!0===m&&e.Utilities.AddLoaderItemMarkedForDisposal(i),o==e.RigidbodyPhysics.ConvexHullImpostor){var C=e.SceneManager.FindChildTransformNode(i,i.name+".Collider",e.SearchType.ExactMatch,!0);if(null!=C){var T=1,x=1,I=1;if(C instanceof BABYLON.InstancedMesh){!0===m&&(T*=parseFloat(n.scaling.x.toFixed(4)),x*=parseFloat(n.scaling.y.toFixed(4)),I*=parseFloat(n.scaling.z.toFixed(4))),B.set(T,x,I);var O=C.sourceMesh;if(null!=O){var L=null!=C.metadata&&null!=C.metadata.toolkit&&null!=C.metadata.toolkit.collision&&null!=C.metadata.toolkit.collision.sourcescale?C.metadata.toolkit.collision.sourcescale:null,w=null!=O.metadata&&null!=O.metadata.toolkit&&null!=O.metadata.toolkit.collision&&null!=O.metadata.toolkit.collision.sourcescale?O.metadata.toolkit.collision.sourcescale:null;if(null!=w&&null!=L){var N=new BABYLON.Vector3(1,1,1),P=new BABYLON.Vector3(L.x,L.y,L.z),R=new BABYLON.Vector3(w.x,w.y,w.z);P.divideToRef(R,N),B.multiplyInPlace(N)}}}else B.set(T,x,I);var E=null!=r.meshkey?r.meshkey:null,k=e.RigidbodyPhysics.GetCachedPhysicsConvexHullShape(t,C,E,a,s,l,u,c,v,y);if(!0===m){var D=i.position.x*parseFloat(n.scaling.x.toFixed(4)),F=i.position.y*parseFloat(n.scaling.y.toFixed(4)),U=i.position.z*parseFloat(n.scaling.z.toFixed(4));b.set(D,F,U),M.multiplyInPlace(i.rotationQuaternion)}else _=p.x*parseFloat(i.scaling.x.toFixed(4)),S=p.y*parseFloat(i.scaling.y.toFixed(4)),A=p.z*parseFloat(i.scaling.z.toFixed(4)),b.set(_,S,A);h.shape=k,h.translation=b,h.rotation=M,h.scale=B,d.push(h)}}else if(o==e.RigidbodyPhysics.CapsuleImpostor){var Y=null!=r.cylinder&&r.cylinder,V=null!=r.capsulesize?r.capsulesize:{x:.5,y:2,z:1},G=V.x*parseFloat(i.scaling.x.toFixed(4)),z=V.y*parseFloat(i.scaling.y.toFixed(4));parseFloat(i.scaling.z.toFixed(4)),!0===m&&(G*=parseFloat(n.scaling.x.toFixed(4)),z*=parseFloat(n.scaling.y.toFixed(4)),parseFloat(n.scaling.z.toFixed(4))),B.set(G,z,G);var W;W=!0===Y?e.RigidbodyPhysics.GetCachedPhysicsCylinderShape(t,f,a,s,l,u,c,v,y):e.RigidbodyPhysics.GetCachedPhysicsCapsuleShape(t,f,a,s,l,u,c,v,y),0!==V.z&&2!==V.z||(0===V.z?e.Utilities.FromEulerToRef(0,0,90,M):2===V.z&&e.Utilities.FromEulerToRef(90,0,0,M)),!0===m?(0===p.x&&0===p.y&&0===p.z||console.warn("WARNING: Center offset not supported for complex compound item: "+i.name),D=i.position.x*parseFloat(n.scaling.x.toFixed(4)),F=i.position.y*parseFloat(n.scaling.y.toFixed(4)),U=i.position.z*parseFloat(n.scaling.z.toFixed(4)),b.set(D,F,U),M.multiplyInPlace(i.rotationQuaternion)):(_=p.x*parseFloat(i.scaling.x.toFixed(4)),S=p.y*parseFloat(i.scaling.y.toFixed(4)),A=p.z*parseFloat(i.scaling.z.toFixed(4)),b.set(_,S,A)),h.shape=W,h.translation=b,h.rotation=M,h.scale=B,d.push(h)}else if(o==e.RigidbodyPhysics.SphereImpostor){var H=null!=r.sphereradius?r.sphereradius:.5,X=parseFloat(i.scaling.x.toFixed(4)),K=parseFloat(i.scaling.y.toFixed(4)),Q=parseFloat(i.scaling.z.toFixed(4)),j=Math.max(X,K,Q)*H;if(!0===m){var Z=parseFloat(n.scaling.x.toFixed(4)),q=parseFloat(n.scaling.y.toFixed(4)),J=parseFloat(n.scaling.z.toFixed(4));j*=Math.max(Z,q,J)}B.set(j,j,j);var $=e.RigidbodyPhysics.GetCachedPhysicsSphereShape(t,f,a,s,l,u,c,v,y);!0===m?(0===p.x&&0===p.y&&0===p.z||console.warn("WARNING: Center offset not supported for complex compound item: "+i.name),D=i.position.x*parseFloat(n.scaling.x.toFixed(4)),F=i.position.y*parseFloat(n.scaling.y.toFixed(4)),U=i.position.z*parseFloat(n.scaling.z.toFixed(4)),b.set(D,F,U),M.multiplyInPlace(i.rotationQuaternion)):(_=p.x*parseFloat(i.scaling.x.toFixed(4)),S=p.y*parseFloat(i.scaling.y.toFixed(4)),A=p.z*parseFloat(i.scaling.z.toFixed(4)),b.set(_,S,A)),h.shape=$,h.translation=b,h.rotation=M,h.scale=B,d.push(h)}else if(o==e.RigidbodyPhysics.BoxImpostor){var ee=null!=r.boxsize?r.boxsize:{x:1,y:1,z:1},te=ee.x*parseFloat(i.scaling.x.toFixed(4)),ne=ee.y*parseFloat(i.scaling.y.toFixed(4)),ie=ee.z*parseFloat(i.scaling.z.toFixed(4));!0===m&&(te*=parseFloat(n.scaling.x.toFixed(4)),ne*=parseFloat(n.scaling.y.toFixed(4)),ie*=parseFloat(n.scaling.z.toFixed(4))),B.set(te,ne,ie);var re=e.RigidbodyPhysics.GetCachedPhysicsBoxShape(t,f,a,s,l,u,c,v,y);!0===m?(0===p.x&&0===p.y&&0===p.z||console.warn("WARNING: Center offset not supported for complex compound item: "+i.name),D=i.position.x*parseFloat(n.scaling.x.toFixed(4)),F=i.position.y*parseFloat(n.scaling.y.toFixed(4)),U=i.position.z*parseFloat(n.scaling.z.toFixed(4)),b.set(D,F,U),M.multiplyInPlace(i.rotationQuaternion)):(_=p.x*parseFloat(i.scaling.x.toFixed(4)),S=p.y*parseFloat(i.scaling.y.toFixed(4)),A=p.z*parseFloat(i.scaling.z.toFixed(4)),b.set(_,S,A)),h.shape=re,h.translation=b,h.rotation=M,h.scale=B,d.push(h)}},n.CreateHeightFieldTerrainShapeFromMesh=function(t,n,i){var r=e.RigidbodyPhysics.GetHavokInstance();if(!r)return BABYLON.Tools.Warn("Havok.js physics library not loaded"),null;var o=t.getVerticesData(BABYLON.VertexBuffer.PositionKind),a=o.length/3,s=r._malloc(4*a),l=Math.sqrt(a),u=l;if(l%1!=0)return console.error("Terrain mesh does not seem to be a regular square grid: "+t.name),null;for(var c=0,d=u-1;d>=0;d--)for(var h=0;h<l;h++){var p=d*l+h;r.HEAPF32[s+c>>2]=o[3*p+1],c+=4}var m=r.HP_Shape_CreateHeightField(l,u,[n,1,i],s)[1];return r._free(s),m},n.GetPhysicsHeapSize=function(){var t=e.RigidbodyPhysics.GetHavokInstance();if(!t)return BABYLON.Tools.Warn("Havok.js physics library not loaded"),0;var n=0;return t.HEAP8&&t.HEAP8.length&&(n=t.HEAP8.length/1048576),n},n.ConfigRigidbodyPhysics=function(e,t,n,i,r,o,a){if(null!=t&&null!=t.physicsBody){!1===(null==r||null==r.gravity||r.gravity)&&t.physicsBody.setGravityFactor(0);var s=null!=r&&null!=r.ldrag?r.ldrag:0,l=null!=r&&null!=r.adrag?r.adrag:.05;t.physicsBody.setLinearDamping(s),t.physicsBody.setAngularDamping(l);var u=null!=r&&null!=r.freeze?r.freeze:null,c=1,d=1,h=1;null!=u&&(null!=u.positionx&&u.positionx,null!=u.positiony&&u.positiony,null!=u.positionz&&u.positionz,c=null!=u.rotationx&&!0===u.rotationx?0:1,d=null!=u.rotationy&&!0===u.rotationy?0:1,h=null!=u.rotationz&&!0===u.rotationz?0:1),t.physicsBody.setMassProperties({mass:o,centerOfMass:a,inertia:new BABYLON.Vector3(c,d,h)})}},n.CreatePhysicsMetadata=function(e,t,n,i){void 0===t&&(t=0),void 0===n&&(n=.05),void 0===i&&(i=null);var r=null!=i?i:new BABYLON.Vector3(0,0,0);return{type:"rigidbody",mass:e,ldrag:t,adrag:n,center:{x:r.x,y:r.y,z:r.z}}},n.CreateCollisionMetadata=function(e,t,n,i,r,o){return void 0===t&&(t=!1),void 0===n&&(n=!1),void 0===i&&(i=0),void 0===r&&(r=.6),void 0===o&&(o=.6),{type:e,trigger:t,convexmesh:n,restitution:i,dynamicfriction:r,staticfriction:o,wheelinformation:null}},n.CreatePhysicsProperties=function(e,t,n,i,r){return void 0===t&&(t=0),void 0===n&&(n=.05),void 0===i&&(i=!0),void 0===r&&(r=!1),{mass:e,drag:t,angularDrag:n,useGravity:i,isKinematic:r}},n.AddChildShapeFromParent=function(t,n,i,r){var o,a=r.computeWorldMatrix(!0),s=n.computeWorldMatrix(!0),l=BABYLON.TmpVectors.Matrix[0];a.multiplyToRef(BABYLON.Matrix.Invert(s),l);var u=BABYLON.TmpVectors.Vector3[0],c=BABYLON.TmpVectors.Quaternion[0],d=BABYLON.TmpVectors.Vector3[1];l.decompose(d,c,u);var h=new BABYLON.Vector3(d.x,d.y,d.z);if(r instanceof BABYLON.InstancedMesh){var p=r.sourceMesh;if(null!=p){var m=null!=r.metadata&&null!=r.metadata.toolkit&&null!=r.metadata.toolkit.collision&&null!=r.metadata.toolkit.collision.sourcescale?r.metadata.toolkit.collision.sourcescale:null,f=null!=p.metadata&&null!=p.metadata.toolkit&&null!=p.metadata.toolkit.collision&&null!=p.metadata.toolkit.collision.sourcescale?p.metadata.toolkit.collision.sourcescale:null;if(null!=f&&null!=m){var g=new BABYLON.Vector3(1,1,1),v=new BABYLON.Vector3(m.x,m.y,m.z),y=new BABYLON.Vector3(f.x,f.y,f.z);v.divideToRef(y,g),h.multiplyInPlace(g)}}}null===(o=e.Utilities.GetHavokPlugin())||void 0===o||o.addChild(t,i,u,c,h)},n.PHYSICS_STEP_TIME=.016,n.RaycastResult=null,n.LocalShapeResult=null,n.WorldShapeResult=null,n.RaycastDestination=null,n.PhysicsShapeCache={},n.NewPhysicsShapeCount=0,n.CachedPhysicsShapeCount=0,n.DebugPhysicsViewer=null,n.OnSetupPhysicsPlugin=null,n.NoImpostor=0,n.SphereImpostor=1,n.BoxImpostor=2,n.PlaneImpostor=3,n.MeshImpostor=4,n.CapsuleImpostor=6,n.CylinderImpostor=7,n.ParticleImpostor=8,n.HeightmapImpostor=9,n.ConvexHullImpostor=10,n.CustomImpostor=100,n.RopeImpostor=101,n.ClothImpostor=102,n.SoftbodyImpostor=103,n._factorAngVel=new BABYLON.Vector3,n._factorLinVel=new BABYLON.Vector3,n._factorLocalVel=new BABYLON.Vector3,n._dampingAngVel=new BABYLON.Vector3,n._dampingLinVel=new BABYLON.Vector3,n._dampingLocalVel=new BABYLON.Vector3,n._tempMatrix=new BABYLON.Matrix,n.SetDamping=function(e,t,n){e.setLinearDamping(Math.max(0,Math.min(1,t))),e.setAngularDamping(Math.max(0,Math.min(1,n)))},n.GetDamping=function(e){return{linearDamping:e.getLinearDamping(),angularDamping:e.getAngularDamping()}},n.ApplyDamping=function(t,n,i,r){var o=Math.pow(1-Math.max(0,Math.min(1,n)),r),a=Math.pow(1-Math.max(0,Math.min(1,i)),r);t.getLinearVelocityToRef(e.RigidbodyPhysics._dampingLinVel),e.RigidbodyPhysics._dampingLinVel.scaleInPlace(o),t.setLinearVelocity(e.RigidbodyPhysics._dampingLinVel),t.getAngularVelocityToRef(e.RigidbodyPhysics._dampingAngVel),e.RigidbodyPhysics._dampingAngVel.scaleInPlace(a),t.setAngularVelocity(e.RigidbodyPhysics._dampingAngVel)},n.ApplyPerAxisAngularDamping=function(t,n,i,r,o){t.getAngularVelocityToRef(e.RigidbodyPhysics._dampingAngVel);var a=t.transformNode.getWorldMatrix();a.invertToRef(e.RigidbodyPhysics._tempMatrix),BABYLON.Vector3.TransformNormalToRef(e.RigidbodyPhysics._dampingAngVel,e.RigidbodyPhysics._tempMatrix,e.RigidbodyPhysics._dampingLocalVel),e.RigidbodyPhysics._dampingLocalVel.x*=Math.pow(1-Math.max(0,Math.min(1,n)),o),e.RigidbodyPhysics._dampingLocalVel.y*=Math.pow(1-Math.max(0,Math.min(1,i)),o),e.RigidbodyPhysics._dampingLocalVel.z*=Math.pow(1-Math.max(0,Math.min(1,r)),o),BABYLON.Vector3.TransformNormalToRef(e.RigidbodyPhysics._dampingLocalVel,a,e.RigidbodyPhysics._dampingAngVel),t.setAngularVelocity(e.RigidbodyPhysics._dampingAngVel)},n.SetAngularFactor=function(t,n,i,r){var o=Math.max(0,Math.min(1,n)),a=Math.max(0,Math.min(1,i)),s=Math.max(0,Math.min(1,r));t.getAngularVelocityToRef(e.RigidbodyPhysics._factorAngVel);var l=t.transformNode.getWorldMatrix();l.invertToRef(e.RigidbodyPhysics._tempMatrix),BABYLON.Vector3.TransformNormalToRef(e.RigidbodyPhysics._factorAngVel,e.RigidbodyPhysics._tempMatrix,e.RigidbodyPhysics._factorLocalVel),e.RigidbodyPhysics._factorLocalVel.x*=o,e.RigidbodyPhysics._factorLocalVel.y*=a,e.RigidbodyPhysics._factorLocalVel.z*=s,BABYLON.Vector3.TransformNormalToRef(e.RigidbodyPhysics._factorLocalVel,l,e.RigidbodyPhysics._factorAngVel),t.setAngularVelocity(e.RigidbodyPhysics._factorAngVel)},n.SetLinearFactor=function(t,n,i,r){var o=Math.max(0,Math.min(1,n)),a=Math.max(0,Math.min(1,i)),s=Math.max(0,Math.min(1,r));t.getLinearVelocityToRef(e.RigidbodyPhysics._factorLinVel),e.RigidbodyPhysics._factorLinVel.x*=o,e.RigidbodyPhysics._factorLinVel.y*=a,e.RigidbodyPhysics._factorLinVel.z*=s,t.setLinearVelocity(e.RigidbodyPhysics._factorLinVel)},n.SetFactors=function(t,n,i){e.RigidbodyPhysics.SetLinearFactor(t,n.x,n.y,n.z),e.RigidbodyPhysics.SetAngularFactor(t,i.x,i.y,i.z)},n}(e.ScriptComponent);e.RigidbodyPhysics=t;e.PhyscisContainerData=function(){},e.SceneManager.RegisterClass("TOOLKIT.RigidbodyPhysics",t)}(i||(i={})),function(e){var t=function(){function e(){}return e.CreatePostProcess=function(e,t,n){var i=n||{},r=Array.isArray(i.color)?i.color:i.color?[i.color.r||0,i.color.g||0,i.color.b||0,i.color.a||1]:[0,0,0,1],o=i.center&&Array.isArray(i.center)?i.center:[.5,.5],a=null!=i.intensity?i.intensity:1,s=null!=i.smoothness?i.smoothness:.5,l=!!i.rounded,u=new BABYLON.PostProcess("roundedVignette","\n precision highp float;\n varying vec2 vUV;\n uniform sampler2D textureSampler;\n uniform vec4 vignetteColor;\n uniform vec2 center;\n uniform float intensity;\n uniform float smoothness;\n uniform float rounded; // 0 or 1\n uniform int blendMode; // 0 = multiply, 1 = overlay\n\n vec3 overlayBlend(vec3 base, vec3 blend) {\n vec3 res;\n for (int i = 0; i < 3; i++) {\n float b = base[i];\n float f = blend[i];\n float outv = (b < 0.5) ? (2.0 * b * f) : (1.0 - 2.0 * (1.0 - b) * (1.0 - f));\n res[i] = outv;\n }\n return res;\n }\n\n void main(void) {\n vec4 scene = texture2D(textureSampler, vUV);\n vec2 p = vUV - center;\n float d;\n if (rounded > 0.5) {\n d = length(p);\n } else {\n // ellipse based on aspect ratio (approx using normalized coords)\n d = sqrt((p.x*p.x) + (p.y*p.y));\n }\n float vig = 1.0 - smoothstep(0.0, 1.0, (d - (1.0 - intensity)) / smoothness);\n float weight = (1.0 - vig);\n vec3 vcol = vignetteColor.rgb;\n vec3 outc;\n if (blendMode == 1) {\n outc = mix(scene.rgb, overlayBlend(scene.rgb, vcol), weight);\n } else {\n // multiply\n outc = mix(scene.rgb, scene.rgb * vcol, weight);\n }\n gl_FragColor = vec4(outc, scene.a);\n }\n ",["vignetteColor","center","intensity","smoothness","rounded","blendMode"],[],1,t,BABYLON.Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1);return u.onApply=function(e){e.setFloat4("vignetteColor",r[0]||0,r[1]||0,r[2]||0,null!=r[3]?r[3]:1),e.setVector2("center",new BABYLON.Vector2(o[0]||.5,o[1]||.5)),e.setFloat("intensity",a),e.setFloat("smoothness",s),e.setFloat("rounded",l?1:0),e.setInt("blendMode","overlay"===i.blendMode||1===i.blendMode?1:0)},u._blendMode="overlay"===i.blendMode||1===i.blendMode?"overlay":"multiply",u},e}();e.RoundedVignettePlugin=t}(i||(i={})),function(e){var t=function(t){function n(e,n,i,r){void 0===i&&(i={}),void 0===r&&(r="TOOLKIT.ShurikenParticles");var o=t.call(this,e,n,i,r)||this;return o.m_particleSystem=null,o.m_emitterMesh=null,o.m_systemProperties=null,o.m_isInitialized=!1,o.m_playOnAwake=!0,o.m_autoStart=!0,o.m_systemTime=0,o.m_isLooping=!0,o.m_duration=5,o.m_emissionTimer=0,o.m_burstTimers=[],o.m_prewarm=!1,o.m_startDelay=null,o.m_simulationSpeed=1,o.m_scalingMode=0,o.m_emitterVelocityMode=0,o.m_customSimulationSpace=0,o.m_emitterVelocity=new BABYLON.Vector3(0,0,0),o.m_gravitySource=0,o.m_useUnscaledTime=!1,o.m_reportedDeltaTime=0,o.m_isSystemRunning=!1,o.m_cullingMode=0,o.m_isVisible=!0,o.m_pausedTime=0,o.m_lastVisibilityCheck=0,o.m_animationCurves=new Map,o.m_gradients=new Map,o}return r(n,t),n.prototype.getParticleSystem=function(){return this.m_particleSystem},n.prototype.getEmitterMesh=function(){return this.m_emitterMesh},n.prototype.internalPlay=function(){var e=this;if(this.m_particleSystem){if(this.m_prewarm&&this.m_isLooping&&this.m_duration>0)if(this.m_systemTime=this.m_duration,this.m_emissionTimer=this.m_duration,this.m_particleSystem instanceof BABYLON.ParticleSystem){var t=this.m_particleSystem.emitRate,n=Math.min(Math.ceil(t*this.m_duration),this.m_particleSystem.getCapacity());this.m_particleSystem.emitRate=60*n,this.m_particleSystem.start(),setTimeout(function(){e.m_particleSystem instanceof BABYLON.ParticleSystem&&(e.m_particleSystem.emitRate=t)},16)}else this.m_particleSystem.start();else this.m_systemTime=0,this.m_emissionTimer=0,this.m_particleSystem.start();this.m_isSystemRunning=!0,this.resetBurstTimers()}},n.prototype.play=function(){var t=this,n=this.calculateStartDelay();n>0?(this.m_systemTime=0,this.m_emissionTimer=0,this.m_isSystemRunning=!1,e.WindowManager.SetTimeout(1e3*n,function(){t.internalPlay()})):(this.m_systemTime=0,this.m_emissionTimer=0,this.internalPlay())},n.prototype.stop=function(){this.m_particleSystem&&(this.m_particleSystem.stop(),this.m_isSystemRunning=!1)},n.prototype.pause=function(){var e,t;this.m_particleSystem&&(this.m_particleSystem instanceof BABYLON.ParticleSystem?this.m_particleSystem.stop():null===(t=(e=this.m_particleSystem).pause)||void 0===t||t.call(e),this.m_isSystemRunning=!1)},n.prototype.reset=function(){this.m_particleSystem&&(this.m_particleSystem.reset(),this.m_systemTime=0,this.m_emissionTimer=0,this.resetBurstTimers(),this.m_isSystemRunning=!1)},n.prototype.isPlaying=function(){return this.m_isSystemRunning&&this.m_isInitialized},n.prototype.getParticleCount=function(){return this.m_particleSystem?this.m_particleSystem.getActiveCount():0},n.prototype.getCustomSimulationSpace=function(){return this.m_customSimulationSpace},n.prototype.getEmitterVelocity=function(){return this.m_emitterVelocity.clone()},n.prototype.getGravitySource=function(){return this.m_gravitySource},n.prototype.getUseUnscaledTime=function(){return this.m_useUnscaledTime},n.prototype.getCustomDeltaTime=function(){return this.m_reportedDeltaTime},n.prototype.getReportedDeltaTime=function(){return this.m_reportedDeltaTime},n.prototype.getEffectiveDeltaTime=function(){return(this.m_useUnscaledTime?this.scene.getEngine().getDeltaTime()/1e3:this.getDeltaTime())*this.m_simulationSpeed},n.prototype.calculateStartDelay=function(){var e,t,n=0;if(null!=this.m_startDelay){var i=this.convertMinMaxCurve(this.m_startDelay);switch(null!==(e=this.m_startDelay.mode)&&void 0!==e?e:0){case 0:case 1:default:n=i.value;break;case 2:case 3:n=Math.random()*(i.max-i.min)+i.min}void 0!==(null===(t=this.m_systemProperties.main)||void 0===t?void 0:t.startDelayMultiplier)&&(n*=this.m_systemProperties.main.startDelayMultiplier)}return parseFloat(Math.max(0,n).toFixed(2))},n.prototype.awake=function(){this.initializeParticleSystem()},n.prototype.start=function(){this.m_isInitialized&&this.m_autoStart&&this.m_playOnAwake&&this.play()},n.prototype.ready=function(){},n.prototype.update=function(){if(this.m_particleSystem&&this.m_systemProperties&&this.m_isSystemRunning){if(!this.shouldSimulateThisFrame()){if(1===this.m_cullingMode){var e=this.m_useUnscaledTime?this.scene.getEngine().getDeltaTime()/1e3:this.getDeltaTime();this.m_pausedTime+=e}return}var t=(this.m_useUnscaledTime?this.scene.getEngine().getDeltaTime()/1e3:this.getDeltaTime())*this.m_simulationSpeed;this.updateSystem(t),this.updateEmission(t),this.updateAnimationProperties(),this.updateBursts(t),this.updateEmitterVelocityInheritance(t),this.updateCustomSimulationSpace(t),this.updateRingBufferMode(t),!this.m_isLooping&&this.m_duration>0&&this.m_systemTime>=this.m_duration&&this.handleStopAction()}},n.prototype.shouldSimulateThisFrame=function(){switch(this.m_cullingMode){case 0:case 1:case 2:default:return this.m_isVisible;case 3:return!0}},n.prototype.late=function(){},n.prototype.step=function(){},n.prototype.fixed=function(){},n.prototype.after=function(){},n.prototype.destroy=function(){this.disposeParticleSystem()},n.mergeWithDefaults=function(e){return e?n.deepMerge(JSON.parse(JSON.stringify(n.DEFAULT_PARTICLE_PROPERTIES)),e):JSON.parse(JSON.stringify(n.DEFAULT_PARTICLE_PROPERTIES))},n.deepMerge=function(e,t){if(!t||"object"!=typeof t)return e;if(!e||"object"!=typeof e)return t;for(var i in t)t.hasOwnProperty(i)&&(t[i]&&"object"==typeof t[i]&&!Array.isArray(t[i])?e[i]=n.deepMerge(e[i]||{},t[i]):e[i]=t[i]);return e},n.getPropertyWithDefault=function(e,t){for(var i=e.split("."),r=t,o=n.DEFAULT_PARTICLE_PROPERTIES,a=0,s=i;a<s.length;a++){var l=s[a];r=null==r?void 0:r[l],o=null==o?void 0:o[l]}return void 0!==r?r:o},n.getMinimalSerializationData=function(e){if(!e)return{};var t=n.DEFAULT_PARTICLE_PROPERTIES;return n.extractDifferences(e,t)},n.extractDifferences=function(e,t){if(!e||"object"!=typeof e)return e;if(!t||"object"!=typeof t)return e;var i={};for(var r in e)if(e.hasOwnProperty(r)){var o=e[r],a=t[r];if(void 0!==o)if(Array.isArray(o))Array.isArray(a)&&o.length===a.length&&n.arraysEqual(o,a)||(i[r]=o);else if(o&&"object"==typeof o){var s=n.extractDifferences(o,a);Object.keys(s).length>0&&(i[r]=s)}else o!==a&&(i[r]=o)}return i},n.arraysEqual=function(e,t){if(e.length!==t.length)return!1;for(var i=0;i<e.length;i++){var r=e[i],o=t[i];if(Array.isArray(r)&&Array.isArray(o)){if(!n.arraysEqual(r,o))return!1}else if(r&&"object"==typeof r&&o&&"object"==typeof o){var a=n.extractDifferences(r,o);if(Object.keys(a).length>0)return!1}else if(r!==o)return!1}return!0},n.getDefaultProperties=function(){return JSON.parse(JSON.stringify(n.DEFAULT_PARTICLE_PROPERTIES))},n.prototype.initializeParticleSystem=function(){try{var e=this._properties;if(this.m_systemProperties=n.mergeWithDefaults(e),!this.m_systemProperties)return void BABYLON.Tools.Warn("ShurikenParticles: Failed to create merged particle system properties");if(!this.m_systemProperties.main)return void BABYLON.Tools.Warn("### ShurikenParticles: No main module found in merged properties");this.createEmitterMesh(),this.shouldUseGPUParticles()?this.createGPUParticleSystem():this.createCPUParticleSystem(),this.configureMainModule(),this.configureEmissionModule(),this.configureShapeModule(),this.configureRendererModule(),this.configureVelocityOverLifetimeModule(),this.configureLimitVelocityOverLifetimeModule(),this.configureColorOverLifetimeModule(),this.configureSizeOverLifetimeModule(),this.configureRotationOverLifetimeModule(),this.configureTextureSheetAnimationModule(),this.configureNoiseModule(),this.configureCollisionModule(),this.configureTrailsModule(),this.configureSubEmittersModule(),this.ensureBasicConfiguration(),this.m_isInitialized=!0}catch(e){BABYLON.Tools.Error("ShurikenParticles: Failed to initialize particle system: "+e)}},n.prototype.shouldUseGPUParticles=function(){var e,t,n,i,r,o,a=null!==(t=null===(e=this.m_systemProperties.main)||void 0===e?void 0:e.maxParticles)&&void 0!==t?t:1e3,s=(null===(n=this.m_systemProperties.noise)||void 0===n?void 0:n.enabled)||(null===(i=this.m_systemProperties.collision)||void 0===i?void 0:i.enabled)||(null===(r=this.m_systemProperties.trails)||void 0===r?void 0:r.enabled)||(null===(o=this.m_systemProperties.subEmitters)||void 0===o?void 0:o.enabled);return a>5e3&&!s},n.prototype.createEmitterMesh=function(){this.m_emitterMesh=BABYLON.MeshBuilder.CreateBox(this.transform.name+"_ParticleProxy",{size:.1},this.scene);var e=null!=n.EMITTER_POSITION_OFFSET?n.EMITTER_POSITION_OFFSET:new BABYLON.Vector3(0,0,0),t=null!=n.EMITTER_ROTATION_OFFSET?n.EMITTER_ROTATION_OFFSET:new BABYLON.Vector3(0,0,0);this.m_emitterMesh.parent=this.transform,this.m_emitterMesh.position.copyFrom(e),this.m_systemProperties.shape,t.set(90,0,0),this.m_emitterMesh.rotationQuaternion=BABYLON.Quaternion.FromEulerAngles(BABYLON.Tools.ToRadians(t.x),BABYLON.Tools.ToRadians(t.y),BABYLON.Tools.ToRadians(t.z)),this.m_emitterMesh.isVisible=!1,this.m_emitterMesh.isPickable=!1},n.prototype.createDefaultParticleTexture=function(){if(null!=e.ShurikenParticles.DefaultParticleTexture)return e.ShurikenParticles.DefaultParticleTexture;var t=64,n=document.createElement("canvas");n.width=t,n.height=t;var i=n.getContext("2d");i.clearRect(0,0,t,t);var r=i.createRadialGradient(32,32,0,32,32,32);r.addColorStop(0,"rgba(255, 255, 255, 1.0)"),r.addColorStop(.15,"rgba(255, 255, 255, 0.95)"),r.addColorStop(.3,"rgba(255, 255, 255, 0.7)"),r.addColorStop(.6,"rgba(255, 255, 255, 0.2)"),r.addColorStop(.85,"rgba(255, 255, 255, 0.05)"),r.addColorStop(1,"rgba(255, 255, 255, 0.0)"),i.fillStyle=r,i.fillRect(0,0,t,t);var o=n.toDataURL("image/png"),a=new BABYLON.Texture(o,this.scene);return a.name=this.transform.name+"_DefaultParticleTexture",a.hasAlpha=!0,a.wrapU=BABYLON.Texture.CLAMP_ADDRESSMODE,a.wrapV=BABYLON.Texture.CLAMP_ADDRESSMODE,e.ShurikenParticles.DefaultParticleTexture=a,e.ShurikenParticles.DefaultParticleTexture},n.prototype.createCPUParticleSystem=function(){var e,t,n=null!==(t=null===(e=this.m_systemProperties.main)||void 0===e?void 0:e.maxParticles)&&void 0!==t?t:1e3;this.m_particleSystem=new BABYLON.ParticleSystem(this.transform.name+"_ParticleSystem",n,this.scene),this.m_particleSystem.emitter=this.m_emitterMesh,this.m_particleSystem.particleTexture||(this.m_particleSystem.particleTexture=this.createDefaultParticleTexture()),this.m_particleSystem.blendMode=BABYLON.ParticleSystem.BLENDMODE_STANDARD,this.m_particleSystem.particleTexture&&(this.m_particleSystem.particleTexture.wrapU=BABYLON.Texture.CLAMP_ADDRESSMODE,this.m_particleSystem.particleTexture.wrapV=BABYLON.Texture.CLAMP_ADDRESSMODE),this.m_particleSystem.color1=new BABYLON.Color4(1,1,1,1),this.m_particleSystem.color2=new BABYLON.Color4(1,1,1,1),this.m_particleSystem.colorDead=new BABYLON.Color4(1,1,1,0),this.m_particleSystem.minSize=1,this.m_particleSystem.maxSize=1,this.m_particleSystem.minInitialRotation=0,this.m_particleSystem.maxInitialRotation=0,this.m_particleSystem.minAngularSpeed=0,this.m_particleSystem.maxAngularSpeed=0},n.prototype.createGPUParticleSystem=function(){var e,t,n=null!==(t=null===(e=this.m_systemProperties.main)||void 0===e?void 0:e.maxParticles)&&void 0!==t?t:1e3;this.m_particleSystem=new BABYLON.GPUParticleSystem(this.transform.name+"_GPUParticleSystem",{capacity:n},this.scene),this.m_particleSystem.emitter=this.m_emitterMesh,this.m_particleSystem.particleTexture||(this.m_particleSystem.particleTexture=this.createDefaultParticleTexture()),this.m_particleSystem.blendMode=BABYLON.GPUParticleSystem.BLENDMODE_STANDARD,this.m_particleSystem.particleTexture&&(this.m_particleSystem.particleTexture.wrapU=BABYLON.Texture.CLAMP_ADDRESSMODE,this.m_particleSystem.particleTexture.wrapV=BABYLON.Texture.CLAMP_ADDRESSMODE),this.m_particleSystem.color1=new BABYLON.Color4(1,1,1,1),this.m_particleSystem.color2=new BABYLON.Color4(1,1,1,1),this.m_particleSystem.colorDead=new BABYLON.Color4(1,1,1,0),this.m_particleSystem.minSize=.25,this.m_particleSystem.maxSize=.25,this.m_particleSystem.minInitialRotation=0,this.m_particleSystem.maxInitialRotation=0,this.m_particleSystem.minAngularSpeed=0,this.m_particleSystem.maxAngularSpeed=0},n.prototype.configureMainModule=function(){var e,t,i,r,o,a,s,l,u,c,d,h,p,m,f,g,v,y,_,S,A,b;if(this.m_systemProperties.main&&this.m_particleSystem){var M=this.m_systemProperties.main;if(void 0!==M.loop&&(this.m_isLooping=M.loop),void 0!==M.duration&&(this.m_duration=M.duration),this.m_isLooping&&(this.m_duration=0),M.prewarm&&M.loop?this.m_prewarm=!0:this.m_prewarm=!1,M.startDelay?this.m_startDelay=M.startDelay:this.m_startDelay=null,void 0!==M.playOnAwake&&(this.m_playOnAwake=M.playOnAwake,this.m_autoStart=M.playOnAwake),M.maxParticles,void 0!==M.scalingMode){var B=M.scalingMode;this.m_scalingMode=B}if(void 0!==M.emitterVelocityMode){var C=M.emitterVelocityMode;this.m_emitterVelocityMode=C}if(void 0!==M.emitterVelocity){var T=M.emitterVelocity;this.m_emitterVelocity.set(T.x||0,T.y||0,T.z||0),this.m_emitterVelocity.length()}if(void 0!==M.customSimulationSpace){var x=M.customSimulationSpace;this.m_customSimulationSpace=x}if(void 0!==M.stopAction&&M.stopAction,void 0!==M.ringBufferMode)M.ringBufferMode>0&&M.ringBufferLoopRange&&M.ringBufferLoopRange;var I=this.convertMinMaxGradient(M.startColor),O=null!==(t=null===(e=M.startColor)||void 0===e?void 0:e.mode)&&void 0!==t?t:0,L=(null===(i=M.startColor)||void 0===i?void 0:i.color)||{r:1,g:1,b:1,a:1};0===O?(this.m_particleSystem.color1=new BABYLON.Color4(L.r,L.g,L.b,L.a),this.m_particleSystem.color2=new BABYLON.Color4(L.r,L.g,L.b,L.a),this.m_particleSystem.colorDead=new BABYLON.Color4(L.r,L.g,L.b,n.UNITY_TO_BABYLON_DEATH_FADE_ALPHA)):(this.m_particleSystem.color1=I.colorMin,this.m_particleSystem.color2=I.colorMax,this.m_particleSystem.colorDead=new BABYLON.Color4(I.colorMin.r,I.colorMin.g,I.colorMin.b,n.UNITY_TO_BABYLON_DEATH_FADE_ALPHA));var w=this.convertMinMaxCurve(M.startLifetime);0===(null!==(o=null===(r=M.startLifetime)||void 0===r?void 0:r.mode)&&void 0!==o?o:0)?(this.m_particleSystem.minLifeTime=w.value*n.UNITY_TO_BABYLON_LIFETIME_RATIO,this.m_particleSystem.maxLifeTime=w.value*n.UNITY_TO_BABYLON_LIFETIME_RATIO):(this.m_particleSystem.minLifeTime=w.min*n.UNITY_TO_BABYLON_LIFETIME_RATIO,this.m_particleSystem.maxLifeTime=w.max*n.UNITY_TO_BABYLON_LIFETIME_RATIO);var N=this.convertMinMaxCurve(M.startSpeed),P=null!==(s=null===(a=M.startSpeed)||void 0===a?void 0:a.mode)&&void 0!==s?s:0;if(0===N.min&&0===N.max?(this.m_particleSystem.minEmitPower=0,this.m_particleSystem.maxEmitPower=0):0===P?(this.m_particleSystem.minEmitPower=N.value*n.UNITY_TO_BABYLON_EMIT_POWER_RATIO,this.m_particleSystem.maxEmitPower=N.value*n.UNITY_TO_BABYLON_EMIT_POWER_RATIO):(this.m_particleSystem.minEmitPower=N.min*n.UNITY_TO_BABYLON_EMIT_POWER_RATIO,this.m_particleSystem.maxEmitPower=N.max*n.UNITY_TO_BABYLON_EMIT_POWER_RATIO),M.startSize3D){var R=this.convertMinMaxCurve(M.startSizeX),E=this.convertMinMaxCurve(M.startSizeY),k=this.convertMinMaxCurve(M.startSizeZ),D=null!==(u=null===(l=M.startSizeX)||void 0===l?void 0:l.mode)&&void 0!==u?u:0,F=null!==(d=null===(c=M.startSizeY)||void 0===c?void 0:c.mode)&&void 0!==d?d:0,U=null!==(p=null===(h=M.startSizeZ)||void 0===h?void 0:h.mode)&&void 0!==p?p:0,Y=void 0,V=void 0;0===D&&0===F&&0===U?V=Y=Math.max(R.value,E.value,k.value):(Y=Math.max(R.min,E.min,k.min),V=Math.max(R.max,E.max,k.max)),this.m_particleSystem.minSize=Y*n.UNITY_TO_BABYLON_SIZE_RATIO,this.m_particleSystem.maxSize=V*n.UNITY_TO_BABYLON_SIZE_RATIO}else{var G=this.convertMinMaxCurve(M.startSize);0===(null!==(f=null===(m=M.startSize)||void 0===m?void 0:m.mode)&&void 0!==f?f:0)?(this.m_particleSystem.minSize=G.value*n.UNITY_TO_BABYLON_SIZE_RATIO,this.m_particleSystem.maxSize=G.value*n.UNITY_TO_BABYLON_SIZE_RATIO):(this.m_particleSystem.minSize=G.min*n.UNITY_TO_BABYLON_SIZE_RATIO,this.m_particleSystem.maxSize=G.max*n.UNITY_TO_BABYLON_SIZE_RATIO)}if(M.startRotation3D){this.convertMinMaxCurve(M.startRotationX),this.convertMinMaxCurve(M.startRotationY);var z=this.convertMinMaxCurve(M.startRotationZ),W=(null===(g=M.startRotationX)||void 0===g?void 0:g.mode,void(null===(v=M.startRotationY)||void 0===v?void 0:v.mode)),H=void 0;0===(null!==(_=null===(y=M.startRotationZ)||void 0===y?void 0:y.mode)&&void 0!==_?_:0)?(W=z.value,H=z.value):(W=z.min,H=z.max),this.m_particleSystem instanceof BABYLON.ParticleSystem&&(this.m_particleSystem.minInitialRotation=W,this.m_particleSystem.maxInitialRotation=H)}else{var X=this.convertMinMaxCurve(M.startRotation);0===(null!==(A=null===(S=M.startRotation)||void 0===S?void 0:S.mode)&&void 0!==A?A:0)?this.m_particleSystem instanceof BABYLON.ParticleSystem&&(this.m_particleSystem.minInitialRotation=X.value,this.m_particleSystem.maxInitialRotation=X.value):this.m_particleSystem instanceof BABYLON.ParticleSystem&&(this.m_particleSystem.minInitialRotation=X.min,this.m_particleSystem.maxInitialRotation=X.max)}if(M.flipRotation&&M.flipRotation>0){if(this.m_particleSystem instanceof BABYLON.ParticleSystem){var K=this.m_particleSystem.minAngularSpeed||0,Q=this.m_particleSystem.maxAngularSpeed||0,j=Math.max(Math.abs(K),Math.abs(Q));this.m_particleSystem.minAngularSpeed=-j*M.flipRotation,this.m_particleSystem.maxAngularSpeed=j*M.flipRotation}}else this.m_particleSystem instanceof BABYLON.ParticleSystem&&(this.m_particleSystem.minAngularSpeed=0,this.m_particleSystem.maxAngularSpeed=0);if(void 0!==M.cullingMode){var Z=M.cullingMode;this.m_cullingMode=Z,3!==Z?this.setupCullingVisibilityCheck():this.m_isVisible=!0}var q,J=this.convertMinMaxCurve(M.gravityModifier);if(null===(b=M.gravityModifier)||void 0===b?void 0:b.mode,q=J.value*n.UNITY_TO_BABYLON_GRAVITY_RATIO,this.m_particleSystem.gravity=new BABYLON.Vector3(0,-9.81*q,0),void 0!==M.gravitySource){var $=M.gravitySource;this.m_gravitySource=$}if(void 0!==M.gravitySource&&1===this.m_gravitySource){var ee=this.m_particleSystem.gravity;this.m_particleSystem.gravity=new BABYLON.Vector3(0,ee.y,0)}this.m_particleSystem.worldOffset=BABYLON.Vector3.Zero(),1===M.simulationSpace?this.m_particleSystem.emitter=this.m_emitterMesh.getAbsolutePosition().clone():this.m_particleSystem.emitter=this.m_emitterMesh;var te=M.simulationSpeed||1;if(this.m_simulationSpeed=1!==te?te:1,void 0!==M.useUnscaledTime){var ne=M.useUnscaledTime;this.m_useUnscaledTime=ne}void 0!==M.deltaTime?this.m_reportedDeltaTime=M.deltaTime:this.m_reportedDeltaTime=0}},n.prototype.configureEmissionModule=function(){var e,t;if(this.m_systemProperties.emission&&this.m_particleSystem){var i=this.m_systemProperties.emission;if(i.enabled){if(i.rateOverTime){var r=this.convertMinMaxCurve(i.rateOverTime),o=(null===(e=i.rateOverTime)||void 0===e?void 0:e.mode,r.value*n.UNITY_TO_BABYLON_EMIT_RATE_RATIO);this.m_particleSystem.emitRate=o}else this.m_particleSystem.emitRate=0;if(i.rateOverDistance){var a=this.convertMinMaxCurve(i.rateOverDistance);null===(t=i.rateOverDistance)||void 0===t?void 0:t.mode,a.value,void 0!==i.rateOverDistanceMultiplier&&i.rateOverDistanceMultiplier}if(i.bursts&&i.bursts.length>0){var s=i.bursts.filter(function(e){return e&&"number"==typeof e.time&&void 0!==e.count});s.length>0&&(this.setupBursts(s),void 0!==i.burstCount&&(i.burstCount,s.length))}else i.burstCount&&i.burstCount}else this.m_particleSystem.emitRate=0;i.enabled&&this.m_particleSystem.emitRate>0&&this.m_particleSystem.emitRate<.1&&(this.m_particleSystem.emitRate=.1)}},n.prototype.configureShapeModule=function(){var e;if(this.m_systemProperties.shape&&this.m_particleSystem){var t=this.m_systemProperties.shape;if(t.enabled)this.configureEmissionShape(t);else if(this.m_particleSystem instanceof BABYLON.ParticleSystem){var i=this.m_systemProperties.shape,r=null!==(e=null==i?void 0:i.radius)&&void 0!==e?e:n.DEFAULT_PARTICLE_PROPERTIES.shape.radius;this.createSphereShapeEmitter(r,0,0)}}},n.prototype.configureRendererModule=function(){var e,t;if(this.m_systemProperties.renderer&&this.m_particleSystem){var n=this.m_systemProperties.renderer;if(void 0!==n.renderMode)switch(n.renderMode){case 0:break;case 1:void 0!==n.lengthScale&&n.lengthScale>0&&this.implementStretchRendering(n.lengthScale,n.velocityScale,n.freeformStretching);break;case 2:this.implementConstrainedBillboarding("horizontal");break;case 3:this.implementConstrainedBillboarding("vertical");break;case 4:this.implementMeshRendering(n);break;case 5:this.m_particleSystem instanceof BABYLON.ParticleSystem&&(this.m_particleSystem.renderingGroupId=-1)}if(void 0!==n.minParticleSize||void 0!==n.maxParticleSize){var i=null!==(e=n.minParticleSize)&&void 0!==e?e:0,r=null!==(t=n.maxParticleSize)&&void 0!==t?t:.5;this.m_particleSystem.minSize<i&&(this.m_particleSystem.minSize=i),this.m_particleSystem.maxSize>r&&(this.m_particleSystem.maxSize=r)}void 0!==n.sortMode&&this.implementParticleSorting(n.sortMode,n.sortingFudge),void 0!==n.alignment&&this.implementParticleAlignment(n.alignment),!n.flip||0===n.flip.x&&0===n.flip.y||this.implementParticleFlipping(n.flip),!n.pivot||0===n.pivot.x&&0===n.pivot.y&&0===n.pivot.z||this.implementParticlePivot(n.pivot),void 0!==n.allowRoll&&this.implementParticleRoll(n.allowRoll),void 0!==n.velocityScale&&n.velocityScale>0&&this.implementVelocityScaling(n.velocityScale,n.cameraVelocityScale),void 0!==n.normalDirection&&this.implementNormalDirection(n.normalDirection),void 0!==n.freeformStretching&&this.implementFreeformStretching(n.freeformStretching),void 0!==n.maskInteraction&&n.maskInteraction>0&&this.implementMaskInteraction(n.maskInteraction),void 0!==n.rotateWithStretchDirection&&this.implementStretchRotation(n.rotateWithStretchDirection),void 0!==n.shadowBias&&0!==n.shadowBias&&this.implementShadowBias(n.shadowBias),void 0!==n.meshCount&&n.meshCount>1&&n.meshes&&this.implementMultiMeshRendering(n.meshes,n.meshDistribution),void 0!==n.activeVertexStreamsCount&&n.activeVertexStreamsCount>0&&this.implementCustomVertexStreams(n.activeVertexStreamsCount),n.trailMaterial&&this.implementTrailMaterial(n.trailMaterial),n.materials&&n.materials.length>0&&this.implementMaterialConfiguration(n.materials),void 0===n.shadowCastingMode&&void 0===n.receiveShadows||this.implementShadowConfiguration(n.shadowCastingMode,n.receiveShadows),void 0===n.lightProbeUsage&&void 0===n.reflectionProbeUsage||this.implementProbeConfiguration(n.lightProbeUsage,n.reflectionProbeUsage),void 0===n.enableGPUInstancing&&void 0===n.supportsMeshInstancing||this.implementGPUInstancing(n.enableGPUInstancing,n.supportsMeshInstancing),void 0===n.sortingLayerID&&void 0===n.sortingOrder||this.implementSortingLayer(n.sortingLayerID,n.sortingOrder)}},n.prototype.implementStretchRendering=function(e,t,n){this.m_particleSystem instanceof BABYLON.ParticleSystem&&(this.m_particleSystem.stretchSettings={lengthScale:e,velocityScale:null!=t?t:1,freeform:null!=n&&n})},n.prototype.implementConstrainedBillboarding=function(e){this.m_particleSystem instanceof BABYLON.ParticleSystem&&(this.m_particleSystem.billboardConstraint=e)},n.prototype.implementMeshRendering=function(e){e.mesh&&(this.m_particleSystem,BABYLON.GPUParticleSystem)},n.prototype.implementParticleSorting=function(e,t){switch(e){case 1:this.m_particleSystem instanceof BABYLON.ParticleSystem&&(this.m_particleSystem.blendMode=BABYLON.ParticleSystem.BLENDMODE_ONEONE);break;case 2:case 3:this.m_particleSystem.customSortMode=e,void 0!==t&&(this.m_particleSystem.sortingFudge=t)}},n.prototype.implementParticleAlignment=function(e){switch(e){case 1:this.m_particleSystem.worldAlignment=!0;break;case 2:this.m_particleSystem.localAlignment=!0;break;case 3:case 4:this.m_particleSystem.velocityAlignment=!0}},n.prototype.implementParticleFlipping=function(e){this.m_particleSystem.flipSettings={x:e.x,y:e.y}},n.prototype.implementParticlePivot=function(e){this.m_particleSystem.pivotOffset=new BABYLON.Vector3(e.x,e.y,e.z)},n.prototype.implementParticleRoll=function(e){this.m_particleSystem.allowRoll=e},n.prototype.implementVelocityScaling=function(e,t){this.m_particleSystem.velocityScaling={scale:e,cameraScale:null!=t?t:1}},n.prototype.implementNormalDirection=function(e){this.m_particleSystem.normalDirection=e},n.prototype.implementFreeformStretching=function(e){this.m_particleSystem.freeformStretching=e},n.prototype.implementMaskInteraction=function(e){switch(e){case 1:this.m_particleSystem.maskMode="inside";break;case 2:this.m_particleSystem.maskMode="outside"}},n.prototype.implementStretchRotation=function(e){this.m_particleSystem.rotateWithStretch=e},n.prototype.implementShadowBias=function(e){this.m_particleSystem.shadowBias=e},n.prototype.implementMultiMeshRendering=function(e,t){this.m_particleSystem.multiMeshSettings={meshes:e,distribution:t}},n.prototype.implementCustomVertexStreams=function(e){this.m_particleSystem.customVertexStreams=e},n.prototype.implementTrailMaterial=function(e){this.m_particleSystem.trailMaterial=e},n.prototype.implementMaterialConfiguration=function(e){if(e.length>0){var t=e[0];t&&t.name,e.length>1&&(this.m_particleSystem.additionalMaterials=e.slice(1))}},n.prototype.implementShadowConfiguration=function(e,t){void 0!==e&&(this.m_particleSystem.shadowCastingMode=e),void 0!==t&&(this.m_particleSystem.receiveShadows=t)},n.prototype.implementProbeConfiguration=function(e,t){void 0!==e&&(this.m_particleSystem.lightProbeUsage=e),void 0!==t&&(this.m_particleSystem.reflectionProbeUsage=t)},n.prototype.implementGPUInstancing=function(e,t){void 0!==e&&(this.m_particleSystem.gpuInstancesEnabled=e),void 0!==t&&(this.m_particleSystem.meshInstancingSupported=t)},n.prototype.implementSortingLayer=function(e,t){void 0!==e&&(this.m_particleSystem.sortingLayerID=e),void 0!==t&&(this.m_particleSystem instanceof BABYLON.ParticleSystem&&(this.m_particleSystem.renderingGroupId=Math.max(0,Math.min(3,t))),this.m_particleSystem.sortingOrder=t)},n.prototype.configureVelocityOverLifetimeModule=function(){var e,t,n,i,r,o,a,s,l,u,c;if(this.m_systemProperties.velocityOverLifetime&&this.m_particleSystem){var d=this.m_systemProperties.velocityOverLifetime;d.enabled&&(this.convertMinMaxCurve(d.x),this.convertMinMaxCurve(d.y),this.convertMinMaxCurve(d.z),null===(e=d.x)||void 0===e?void 0:e.mode,null===(t=d.y)||void 0===t?void 0:t.mode,null===(n=d.z)||void 0===n?void 0:n.mode,(d.orbitalX||d.orbitalY||d.orbitalZ)&&(this.convertMinMaxCurve(d.orbitalX),this.convertMinMaxCurve(d.orbitalY),this.convertMinMaxCurve(d.orbitalZ),null===(i=d.orbitalX)||void 0===i?void 0:i.mode,null===(r=d.orbitalY)||void 0===r?void 0:r.mode,null===(o=d.orbitalZ)||void 0===o?void 0:o.mode),(d.orbitalOffsetX||d.orbitalOffsetY||d.orbitalOffsetZ)&&(this.convertMinMaxCurve(d.orbitalOffsetX),this.convertMinMaxCurve(d.orbitalOffsetY),this.convertMinMaxCurve(d.orbitalOffsetZ),null===(a=d.orbitalOffsetX)||void 0===a?void 0:a.mode,null===(s=d.orbitalOffsetY)||void 0===s?void 0:s.mode,null===(l=d.orbitalOffsetZ)||void 0===l?void 0:l.mode),d.radial&&(this.convertMinMaxCurve(d.radial),null===(u=d.radial)||void 0===u?void 0:u.mode),d.speedModifier&&(this.convertMinMaxCurve(d.speedModifier),null===(c=d.speedModifier)||void 0===c?void 0:c.mode),this.setupVelocityOverLifetime(d))}},n.prototype.configureLimitVelocityOverLifetimeModule=function(){if(this.m_systemProperties.limitVelocityOverLifetime&&this.m_particleSystem){var e=this.m_systemProperties.limitVelocityOverLifetime;e.enabled&&this.setupLimitVelocity(e)}},n.prototype.configureColorOverLifetimeModule=function(){if(this.m_systemProperties.colorOverLifetime&&this.m_particleSystem){var e=this.m_systemProperties.colorOverLifetime;if(e.enabled&&e.color&&this.m_particleSystem instanceof BABYLON.ParticleSystem){var t=this.convertMinMaxGradient(e.color);if(this.m_particleSystem.addColorGradient(0,t.colorMin),this.m_particleSystem.addColorGradient(1,t.colorMax),e.color.gradient&&e.color.gradient.colorKeys){this.m_particleSystem.removeColorGradient(0),this.m_particleSystem.removeColorGradient(1);for(var n=0,i=e.color.gradient.colorKeys;n<i.length;n++){var r=i[n],o=this.convertColor(r.color);this.m_particleSystem.addColorGradient(r.time,o)}if(e.color.gradient.alphaKeys)for(var a=0,s=e.color.gradient.alphaKeys;a<s.length;a++)s[a]}}else e.enabled}},n.prototype.configureSizeOverLifetimeModule=function(){var e,t,n,i,r;if(this.m_systemProperties.sizeOverLifetime&&this.m_particleSystem){var o=this.m_systemProperties.sizeOverLifetime;if(o.enabled&&this.m_particleSystem instanceof BABYLON.ParticleSystem)if(o.separateAxes){var a=this.convertMinMaxCurve(o.x),s=this.convertMinMaxCurve(o.y),l=this.convertMinMaxCurve(o.z),u=(null===(e=o.x)||void 0===e?void 0:e.mode,null===(t=o.y)||void 0===t?void 0:t.mode,null===(n=o.z)||void 0===n?void 0:n.mode,Math.max(a.min,s.min,l.min)),c=Math.max(a.max,s.max,l.max);this.m_particleSystem.addSizeGradient(0,u),this.m_particleSystem.addSizeGradient(1,c)}else{var d=this.convertMinMaxCurve(o.size);u=void 0,c=void 0,0===(null!==(r=null===(i=o.size)||void 0===i?void 0:i.mode)&&void 0!==r?r:0)?(u=d.value,c=d.value):(u=d.min,c=d.max),this.m_particleSystem.addSizeGradient(0,u),this.m_particleSystem.addSizeGradient(1,c)}else o.enabled}},n.prototype.configureRotationOverLifetimeModule=function(){var e,t,n,i,r,o;if(this.m_systemProperties.rotationOverLifetime&&this.m_particleSystem){var a=this.m_systemProperties.rotationOverLifetime;if(a.enabled&&this.m_particleSystem instanceof BABYLON.ParticleSystem)if(a.separateAxes){this.convertMinMaxCurve(a.x),this.convertMinMaxCurve(a.y);var s=this.convertMinMaxCurve(a.z),l=(null===(e=a.x)||void 0===e?void 0:e.mode,void(null===(t=a.y)||void 0===t?void 0:t.mode)),u=void 0;0===(null!==(i=null===(n=a.z)||void 0===n?void 0:n.mode)&&void 0!==i?i:0)?(l=s.value,u=s.value):(l=s.min,u=s.max),this.m_particleSystem.addAngularSpeedGradient(0,l),this.m_particleSystem.addAngularSpeedGradient(1,u)}else{var c=this.convertMinMaxCurve(a.z);l=void 0,u=void 0,0===(null!==(o=null===(r=a.z)||void 0===r?void 0:r.mode)&&void 0!==o?o:0)?(l=c.value,u=c.value):(l=c.min,u=c.max),this.m_particleSystem.addAngularSpeedGradient(0,l),this.m_particleSystem.addAngularSpeedGradient(1,u)}}},n.prototype.configureTextureSheetAnimationModule=function(){if(this.m_systemProperties.textureSheetAnimation&&this.m_particleSystem){var e=this.m_systemProperties.textureSheetAnimation;e.enabled&&this.m_particleSystem instanceof BABYLON.ParticleSystem?(this.m_particleSystem.spriteCellChangeSpeed=e.fps||1,this.m_particleSystem.spriteCellWidth=1/(e.numTilesX||1),this.m_particleSystem.spriteCellHeight=1/(e.numTilesY||1),this.m_particleSystem.spriteRandomStartCell=e.useRandomRow||!1,e.frameOverTime&&this.convertMinMaxCurve(e.frameOverTime),e.startFrame&&this.convertMinMaxCurve(e.startFrame),e.speedRange):e.enabled}},n.prototype.ensureBasicConfiguration=function(){var e;if(this.m_particleSystem&&(this.m_particleSystem.emitRate<0&&(this.m_particleSystem.emitRate=0),this.m_particleSystem.minLifeTime<=0&&(this.m_particleSystem.minLifeTime=5*n.UNITY_TO_BABYLON_LIFETIME_RATIO,this.m_particleSystem.maxLifeTime=5*n.UNITY_TO_BABYLON_LIFETIME_RATIO),this.m_particleSystem.minSize<=0&&(this.m_particleSystem.minSize=1*n.UNITY_TO_BABYLON_SIZE_RATIO,this.m_particleSystem.maxSize=1*n.UNITY_TO_BABYLON_SIZE_RATIO),this.m_particleSystem instanceof BABYLON.ParticleSystem&&(!this.m_particleSystem.direction1||!this.m_particleSystem.direction2||this.m_particleSystem.direction1.equals(new BABYLON.Vector3(-1,1,-1))&&this.m_particleSystem.direction2.equals(new BABYLON.Vector3(1,1,1))))){var t=this.m_systemProperties.shape,i=null!==(e=null==t?void 0:t.radius)&&void 0!==e?e:n.DEFAULT_PARTICLE_PROPERTIES.shape.radius;this.createSphereShapeEmitter(i,0,0)}},n.prototype.convertMinMaxCurve=function(e){var t,n,i,r,o,a,s,l;if(!e)return console.warn("### ShurikenParticles: ERROR - No curve data provided from Unity export"),{min:0,max:0,value:0};var u=null!==(t=e.mode)&&void 0!==t?t:0;(u<0||u>3)&&console.warn("### ShurikenParticles: WARNING - Invalid Unity curve mode:",u,"using mode 0 (Constant)");var c=e.multiplier||1;switch(u){case 0:var d=null!==(n=e.constant)&&void 0!==n?n:0;return{min:d,max:d,value:d};case 1:if(e.curve&&e.curve.keys&&e.curve.keys.length>0){var h=this.evaluateCurveAtTime(e.curve,0)*c,p=this.evaluateCurveAtTime(e.curve,.5)*c,m=this.evaluateCurveAtTime(e.curve,1)*c;return{min:Math.min(h,p,m),max:Math.max(h,p,m),value:(h+p+m)/3}}var f=(null!==(i=e.constant)&&void 0!==i?i:1)*c;return{min:f,max:f,value:f};case 2:var g=null!==(r=e.constantMin)&&void 0!==r?r:0,v=null!==(o=e.constantMax)&&void 0!==o?o:0;return{min:g,max:v,value:(g+v)/2};case 3:if(e.curveMin&&e.curveMax&&e.curveMin.keys&&e.curveMax.keys){var y=this.evaluateCurveAtTime(e.curveMin,0)*c,_=this.evaluateCurveAtTime(e.curveMin,.5)*c,S=this.evaluateCurveAtTime(e.curveMin,1)*c,A=this.evaluateCurveAtTime(e.curveMax,0)*c,b=this.evaluateCurveAtTime(e.curveMax,.5)*c,M=this.evaluateCurveAtTime(e.curveMax,1)*c,B=Math.min(y,_,S,A,b,M),C=Math.max(y,_,S,A,b,M);return{min:B,max:C,value:(B+C)/2}}var T=(null!==(a=e.constantMin)&&void 0!==a?a:0)*c,x=(null!==(s=e.constantMax)&&void 0!==s?s:0)*c;return{min:T,max:x,value:(T+x)/2};default:var I=null!==(l=e.constant)&&void 0!==l?l:0;return{min:I,max:I,value:I}}},n.prototype.convertMinMaxGradient=function(e){if(!e){var t=new BABYLON.Color4(1,1,1,1);return{colorMin:t,colorMax:t}}var n,i;switch(e.mode){case 0:var r=this.convertColor(e.color);n=r,i=r;break;case 2:n=this.convertColor(e.colorMin),i=this.convertColor(e.colorMax);break;case 1:if(e.gradient&&e.gradient.colorKeys&&e.gradient.colorKeys.length>0){var o=e.gradient.colorKeys[0],a=e.gradient.colorKeys[e.gradient.colorKeys.length-1];n=this.convertColor(o.color),i=this.convertColor(a.color)}else if(e.color)n=l=this.convertColor(e.color),i=l;else{var s=new BABYLON.Color4(1,1,1,1);n=s,i=s}break;case 3:e.gradientMin&&e.gradientMax&&e.gradientMin.colorKeys&&e.gradientMin.colorKeys.length>0&&e.gradientMax.colorKeys&&e.gradientMax.colorKeys.length>0?(n=this.convertColor(e.gradientMin.colorKeys[0].color),i=this.convertColor(e.gradientMax.colorKeys[0].color)):(n=this.convertColor(e.colorMin),i=this.convertColor(e.colorMax));break;case 4:e.gradient&&e.gradient.colorKeys&&e.gradient.colorKeys.length>0?(o=e.gradient.colorKeys[0],a=e.gradient.colorKeys[e.gradient.colorKeys.length-1],n=this.convertColor(o.color),i=this.convertColor(a.color)):(n=this.convertColor(e.colorMin),i=this.convertColor(e.colorMax));break;default:var l;e.color?(n=l=this.convertColor(e.color),i=l):(n=this.convertColor(e.colorMin),i=this.convertColor(e.colorMax))}return{colorMin:n,colorMax:i}},n.prototype.convertColor=function(e){if(!e)return new BABYLON.Color4(1,1,1,1);var t="number"==typeof e.r&&!isNaN(e.r)&&isFinite(e.r)?e.r:1,n="number"==typeof e.g&&!isNaN(e.g)&&isFinite(e.g)?e.g:1,i="number"==typeof e.b&&!isNaN(e.b)&&isFinite(e.b)?e.b:1,r="number"==typeof e.a&&!isNaN(e.a)&&isFinite(e.a)?e.a:1;return 1!==t||1!==n||1!==i||1!==r||1===e.r&&1===e.g&&1===e.b&&1===e.a?new BABYLON.Color4(t,n,i,r):new BABYLON.Color4(1,1,1,1)},n.prototype.colorsEqual=function(e,t){if(!e&&!t)return!0;if(!e||!t)return!1;var n=1e-4;return Math.abs(e.r-t.r)<n&&Math.abs(e.g-t.g)<n&&Math.abs(e.b-t.b)<n&&Math.abs(e.a-t.a)<n},n.prototype.applyUnityGradientToBabylon=function(e,t){if(!e||!e.colorKeys||0===e.colorKeys.length)return!1;t.removeColorGradient(0),t.removeColorGradient(1);for(var n=0,i=e.colorKeys;n<i.length;n++){var r=i[n],o=this.convertColor(r.color);t.addColorGradient(r.time,o)}return e.alphaKeys&&e.alphaKeys.length>0&&console.warn("### ShurikenParticles: Alpha keys detected but not fully supported yet"),!0},n.prototype.convertVector3=function(e){return e?new BABYLON.Vector3(e.x,e.y,e.z):BABYLON.Vector3.Zero()},n.prototype.evaluateCurveAtTime=function(e,t){if(!e||!e.keys||0===e.keys.length)return 1;var n=e.keys;if(t<=n[0].time)return n[0].value;if(t>=n[n.length-1].time)return n[n.length-1].value;for(var i=0;i<n.length-1;i++){var r=n[i],o=n[i+1];if(t>=r.time&&t<=o.time){var a=(t-r.time)/(o.time-r.time);return r.value+a*(o.value-r.value)}}return n[0].value},n.prototype.setupBursts=function(e){if(this.m_burstTimers=[],e&&e.length>0)for(var t=0;t<e.length;t++){var n=e[t];this.m_burstTimers.push(-n.time)}},n.prototype.resetBurstTimers=function(){var e;if((null===(e=this.m_systemProperties.emission)||void 0===e?void 0:e.bursts)&&this.m_burstTimers)for(var t=0;t<this.m_systemProperties.emission.bursts.length;t++){var n=this.m_systemProperties.emission.bursts[t];this.m_burstTimers[t]=-n.time}},n.prototype.updateSystem=function(e){this.m_systemTime+=e},n.prototype.updateEmission=function(e){this.m_emissionTimer+=e},n.prototype.updateAnimationProperties=function(){},n.prototype.updateBursts=function(e){var t,n,i;if(null===(t=this.m_systemProperties.emission)||void 0===t?void 0:t.bursts)for(var r=0;r<this.m_systemProperties.emission.bursts.length;r++){var o=this.m_systemProperties.emission.bursts[r];if(this.m_systemTime>=o.time&&this.m_burstTimers[r]<0){var a=void 0!==o.probability?o.probability:1;if(Math.random()>a){this.m_burstTimers[r]=this.m_systemTime;continue}var s=this.convertMinMaxCurve(o.count),l=void 0;switch(null!==(i=null===(n=o.count)||void 0===n?void 0:n.mode)&&void 0!==i?i:0){case 0:case 1:default:l=s.value;break;case 2:case 3:l=Math.random()*(s.max-s.min)+s.min}(l=Math.max(0,Math.round(l)))>0&&this.triggerBurst(l),this.m_burstTimers[r]=this.m_systemTime;var u=void 0!==o.cycleCount?o.cycleCount:1;(-1===u||u>1)&&void 0!==o.repeatInterval&&o.repeatInterval}}},n.prototype.triggerBurst=function(e){var t=this;if(this.m_particleSystem instanceof BABYLON.ParticleSystem){var n=this.m_particleSystem.emitRate;this.m_particleSystem.emitRate=60*e,setTimeout(function(){t.m_particleSystem&&(t.m_particleSystem.emitRate=n)},16)}},n.prototype.configureEmissionShape=function(e){var t,n,i;if(e.radiusSpeed&&(this.convertMinMaxCurve(e.radiusSpeed),null===(t=e.radiusSpeed)||void 0===t?void 0:t.mode),e.meshSpawnSpeed&&(this.convertMinMaxCurve(e.meshSpawnSpeed),null===(n=e.meshSpawnSpeed)||void 0===n?void 0:n.mode),e.arcSpeed&&(this.convertMinMaxCurve(e.arcSpeed),null===(i=e.arcSpeed)||void 0===i?void 0:i.mode),e.rotation&&this.m_emitterMesh){var r=this.convertVector3(e.rotation),o=BABYLON.Quaternion.FromEulerAngles(BABYLON.Tools.ToRadians(r.x),BABYLON.Tools.ToRadians(r.y),BABYLON.Tools.ToRadians(r.z)),a=this.m_emitterMesh.rotationQuaternion||BABYLON.Quaternion.Identity();this.m_emitterMesh.rotationQuaternion=a.multiply(o)}switch(e.shapeType){case 4:case 7:case 8:case 9:var s=e.radius||1,l=e.angle||25,u=(e.length,e.arc,e.radiusSpread,e.scale||{x:1,y:1,z:1}),c=(e.radiusMode,s*((u.x+u.z)/2)),d=Math.max(.1,l*Math.PI/180),h=Math.max(.5,c);this.createConeShapeEmitter(h,d);break;case 0:case 1:var p=e.radius||1,m=e.scale||{x:1,y:1,z:1},f=e.radiusSpread||0,g=e.radiusMode||0,v=(e.donutRadius,p);2===g&&f>0&&(v=p*(1+.5*f));var y=v*((m.x+m.y+m.z)/3);e.shapeType,this.m_particleSystem.createSphereEmitter(y);break;case 2:case 3:var _=e.radius||1,S=e.scale||{x:1,y:1,z:1},A=e.radiusSpread||0,b=e.radiusMode||0,M=(e.donutRadius,e.arc,_);2===b&&A>0&&(M=_*(1+.5*A));var B=M*((S.x+S.y+S.z)/3);e.shapeType,this.m_particleSystem.createHemisphericEmitter(B);break;case 10:case 11:var C=e.radius||1,T=e.scale||{x:1,y:1,z:1},x=(e.arc,e.donutRadius,e.radiusSpread||0),I=e.radiusMode||0,O=(e.length,C);2===I&&x>0&&(O=C*(1+.5*x));var L=O*((T.x+T.z)/2);T.y,this.m_particleSystem.createDirectedSphereEmitter(L,new BABYLON.Vector3(0,1,0),new BABYLON.Vector3(0,1,0));break;case 5:case 15:case 16:var w=e.scale||{x:1,y:1,z:1},N=e.boxThickness||{x:0,y:0,z:0};15!==e.shapeType&&16!==e.shapeType||(w={x:Math.max(.1,w.x-N.x),y:Math.max(.1,w.y-N.y),z:Math.max(.1,w.z-N.z)}),this.m_particleSystem.createBoxEmitter(new BABYLON.Vector3(-w.x/2,-w.y/2,-w.z/2),new BABYLON.Vector3(w.x/2,w.y/2,w.z/2),new BABYLON.Vector3(0,1,0),new BABYLON.Vector3(0,1,0));break;case 17:var P=e.radius||1,R=e.donutRadius||.2,E=e.scale||{x:1,y:1,z:1},k=(e.arc,e.radiusSpread||0),D=P;2===(e.radiusMode||0)&&k>0&&(D=P*(1+.5*k));var F=(E.x+E.z)/2,U=(D*F+R*F)/2;this.m_particleSystem.createDirectedSphereEmitter(U,new BABYLON.Vector3(0,1,0),new BABYLON.Vector3(0,1,0));break;case 18:var Y=e.scale||{x:1,y:1,z:1},V=e.length||1,G=(e.arc,Y.x),z=Y.z,W=V*Y.y;this.m_particleSystem.createBoxEmitter(new BABYLON.Vector3(-G/2,-W/2,-z/2),new BABYLON.Vector3(G/2,W/2,z/2),new BABYLON.Vector3(0,1,0),new BABYLON.Vector3(0,1,0));break;case 12:var H=e.length||1,X=e.scale||{x:1,y:1,z:1},K=e.radius||.1,Q=H*X.x,j=K*Math.max(X.y,X.z);this.m_particleSystem.createBoxEmitter(new BABYLON.Vector3(-Q/2,-j/2,-j/2),new BABYLON.Vector3(Q/2,j/2,j/2),new BABYLON.Vector3(0,1,0),new BABYLON.Vector3(0,1,0));break;default:if(6===e.shapeType||13===e.shapeType||14===e.shapeType){var Z=e.radius||1,q=e.scale||{x:1,y:1,z:1},J=Z*((q.x+q.y+q.z)/3);this.m_particleSystem.createSphereEmitter(J)}else if(19===e.shapeType||20===e.shapeType){var $=e.scale||{x:1,y:1,z:1};this.m_particleSystem.createBoxEmitter(new BABYLON.Vector3(-$.x/2,-$.y/2,-.1),new BABYLON.Vector3($.x/2,$.y/2,.1),new BABYLON.Vector3(0,0,1),new BABYLON.Vector3(0,0,1))}else{var ee=e.radius||1,te=(e.angle||25)*Math.PI/180,ne=e.length||1,ie=e.scale||{x:1,y:1,z:1},re=te,oe=(ee+(ee+ne*Math.tan(re)))/2,ae=3*ee;(oe*=(ie.x+ie.z)/2)>ae&&(oe=ae);var se=Math.min(re,Math.PI/4);this.createConeShapeEmitter(oe,se)}}if(e.position&&(0!==e.position.x||0!==e.position.y||0!==e.position.z)){var le=this.convertVector3(e.position);this.m_emitterMesh&&(this.m_emitterMesh.position.clone(),this.m_emitterMesh.position.addInPlace(le))}!e.rotation||0===e.rotation.x&&0===e.rotation.y&&0===e.rotation.z||this.m_emitterMesh,e.randomDirectionAmount,e.randomPositionAmount,e.sphericalDirectionAmount,e.alignToDirection,e.arc,void 0!==e.normalOffset&&e.normalOffset},n.prototype.setupVelocityOverLifetime=function(e){},n.prototype.setupLimitVelocity=function(e){},n.prototype.createColorGradient=function(e){return this.convertMinMaxGradient(e)},n.prototype.setupSpriteAnimation=function(e){this.m_particleSystem instanceof BABYLON.ParticleSystem&&(this.m_particleSystem.spriteCellChangeSpeed=e.fps||1,this.m_particleSystem.spriteCellWidth=1/e.numTilesX,this.m_particleSystem.spriteCellHeight=1/e.numTilesY,this.m_particleSystem.spriteRandomStartCell=e.useRandomRow)},n.prototype.createBoxShapeEmitter=function(e,t){if(this.m_particleSystem instanceof BABYLON.ParticleSystem){var n=e||{x:1,y:1,z:1};this.m_particleSystem.createBoxEmitter(new BABYLON.Vector3(-n.x/2,-n.y/2,-n.z/2),new BABYLON.Vector3(n.x/2,n.y/2,n.z/2),new BABYLON.Vector3(0,1,0),new BABYLON.Vector3(0,1,0))}},n.prototype.createSphereShapeEmitter=function(e,t,n){if(this.m_particleSystem instanceof BABYLON.ParticleSystem){var i=e||1;this.m_particleSystem.createSphereEmitter(i)}},n.prototype.createConeShapeEmitter=function(e,t){if(this.m_particleSystem instanceof BABYLON.ParticleSystem){var i=e||1,r=t||Math.PI/7.2,o=this.m_particleSystem.createConeEmitter(i*n.UNITY_TO_BABYLON_CONE_SCALE_RATIO,r*n.UNITY_TO_BABYLON_CONE_SCALE_RATIO);o.radiusRange=1,o.heightRange=1,o.directionRandomizer=1,o.emitFromSpawnPointOnly=!1}},n.prototype.configureNoiseModule=function(){},n.prototype.configureCollisionModule=function(){},n.prototype.configureTrailsModule=function(){},n.prototype.configureSubEmittersModule=function(){},n.prototype.updateEmitterVelocityInheritance=function(e){var t;this.m_emitterVelocity.length()>0&&void 0!==(null===(t=this.m_systemProperties.main)||void 0===t?void 0:t.emitterVelocityMode)&&this.m_systemProperties.main.emitterVelocityMode},n.prototype.updateCustomSimulationSpace=function(e){this.m_customSimulationSpace},n.prototype.updateRingBufferMode=function(e){var t=this.m_systemProperties.main;(null==t?void 0:t.ringBufferMode)&&t.ringBufferMode>0&&t.ringBufferLoopRange&&(t.ringBufferLoopRange,2===t.ringBufferMode||t.ringBufferMode)},n.prototype.handleStopAction=function(){var e=this,t=this.m_systemProperties.main;void 0!==(null==t?void 0:t.stopAction)?1===t.stopAction?setTimeout(function(){e.transform&&e.transform.dispose&&e.transform.dispose()},0):this.stop():this.stop()},n.prototype.setupCullingVisibilityCheck=function(){var e=this,t=function(){if(e.m_isInitialized&&e.m_emitterMesh){var t=Date.now();if(!(t-e.m_lastVisibilityCheck<100)){e.m_lastVisibilityCheck=t;var n=e.m_isVisible;e.m_isVisible=e.isEmitterVisible(),n!==e.m_isVisible&&e.handleVisibilityChange(n,e.m_isVisible)}}};this.scene.registerBeforeRender(t);var n=this.disposeParticleSystem.bind(this);this.disposeParticleSystem=function(){e.scene.unregisterBeforeRender(t),n()}},n.prototype.isEmitterVisible=function(){if(!this.m_emitterMesh||!this.scene.activeCamera)return!0;var e=this.m_emitterMesh.getBoundingInfo();if(!e)return!0;var t=this.scene.activeCamera;if(t.isInFrustum&&e.boundingBox)return t.isInFrustum(e.boundingBox);var n=this.m_emitterMesh.getAbsolutePosition(),i=t.position;return BABYLON.Vector3.Distance(n,i)<=1e3},n.prototype.handleVisibilityChange=function(e,t){var n=this.m_cullingMode;!e&&t?1===n&&this.m_pausedTime>0&&(this.m_pausedTime=0):e&&!t&&(this.m_pausedTime=0)},n.prototype.disposeParticleSystem=function(){this.m_particleSystem&&(this.m_particleSystem.dispose(),this.m_particleSystem=null),this.m_emitterMesh&&this.m_emitterMesh.parent===this.transform&&(this.m_emitterMesh.dispose(),this.m_emitterMesh=null),this.m_animationCurves.clear(),this.m_gradients.clear(),this.m_isInitialized=!1},n.DefaultParticleTexture=null,n.DEFAULT_PARTICLE_PROPERTIES={isPlaying:!0,isPaused:!1,isStopped:!1,isEmitting:!0,particleCount:50,time:0,randomSeed:0,useAutoRandomSeed:!0,name:"",instanceId:0,enabled:!0,transformPosition:{x:0,y:0,z:0},transformRotation:{x:0,y:0,z:0},transformScale:{x:1,y:1,z:1},main:{duration:5,loop:!0,prewarm:!0,startDelay:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},startDelayMultiplier:0,startLifetime:{mode:0,constant:5,constantMin:0,constantMax:5,multiplier:1},startLifetimeMultiplier:5,startSpeed:{mode:0,constant:5,constantMin:0,constantMax:5,multiplier:1},startSpeedMultiplier:5,startSize3D:!1,startSize:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},startSizeMultiplier:1,startSizeX:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},startSizeXMultiplier:1,startSizeY:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},startSizeYMultiplier:1,startSizeZ:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},startSizeZMultiplier:1,startRotation3D:!1,startRotation:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},startRotationMultiplier:0,startRotationX:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},startRotationXMultiplier:0,startRotationY:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},startRotationYMultiplier:0,startRotationZ:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},startRotationZMultiplier:0,flipRotation:0,startColor:{mode:0,color:{r:1,g:1,b:1,a:1},colorMin:{r:0,g:0,b:0,a:0},colorMax:{r:1,g:1,b:1,a:1}},gravityModifier:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},gravityModifierMultiplier:0,simulationSpace:0,simulationSpeed:1,deltaTime:0,scalingMode:1,playOnAwake:!0,emitterVelocityMode:1,maxParticles:1e3,stopAction:0,cullingMode:0,ringBufferMode:0,ringBufferLoopRange:{x:0,y:1},customSimulationSpace:0,emitterVelocity:{x:0,y:0,z:0},gravitySource:0,useUnscaledTime:!1},emission:{enabled:!0,rateOverTime:{mode:0,constant:10,constantMin:0,constantMax:10,multiplier:1},rateOverTimeMultiplier:10,rateOverDistance:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},rateOverDistanceMultiplier:0,burstCount:0,bursts:[]},shape:{enabled:!0,shapeType:0,angle:25,radius:.025,radiusMode:0,radiusSpread:0,radiusSpeed:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},radiusSpeedMultiplier:1,donutRadius:.2,position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0},scale:{x:1,y:1,z:1},alignToDirection:!1,randomDirectionAmount:0,sphericalDirectionAmount:0,randomPositionAmount:0,biasOnTriangles:!1,useMeshMaterialIndex:!1,meshMaterialIndex:0,useMeshColors:!0,normalOffset:0,meshSpawnMode:0,meshSpawnSpread:0,meshSpawnSpeed:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},meshSpawnSpeedMultiplier:1,arc:360,arcMode:0,arcSpread:0,arcSpeed:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},arcSpeedMultiplier:1,length:5,boxThickness:{x:0,y:0,z:0}},renderer:{enabled:!0,materials:[],renderMode:0,cameraVelocityScale:0,velocityScale:0,lengthScale:2,normalDirection:1,sortMode:0,sortingFudge:0,minParticleSize:0,maxParticleSize:.5,alignment:0,flip:{x:0,y:0},allowRoll:!0,pivot:{x:0,y:0,z:0},shadowCastingMode:1,receiveShadows:!0,motionVectorGenerationMode:1,lightProbeUsage:1,reflectionProbeUsage:1,enableGPUInstancing:!0,mesh:null,sortingLayerID:0,sortingOrder:0,freeformStretching:!1,maskInteraction:0,meshCount:0,meshDistribution:0,rotateWithStretchDirection:!1,shadowBias:0,supportsMeshInstancing:!0,activeVertexStreamsCount:0,activeTrailVertexStreamsCount:0,meshes:[],trailMaterial:null},velocityOverLifetime:{enabled:!1,space:0,x:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},y:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},z:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},xMultiplier:0,yMultiplier:0,zMultiplier:0,orbitalX:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},orbitalY:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},orbitalZ:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},orbitalXMultiplier:0,orbitalYMultiplier:0,orbitalZMultiplier:0,orbitalOffsetX:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},orbitalOffsetY:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},orbitalOffsetZ:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},orbitalOffsetXMultiplier:0,orbitalOffsetYMultiplier:0,orbitalOffsetZMultiplier:0,radial:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},radialMultiplier:0,speedModifier:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},speedModifierMultiplier:1},limitVelocityOverLifetime:{enabled:!1,limitX:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},limitY:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},limitZ:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},limitXMultiplier:1,limitYMultiplier:1,limitZMultiplier:1,limit:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},limitMultiplier:1,dampen:0,separateAxes:!1,space:0,drag:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},dragMultiplier:0,multiplyDragByParticleSize:!0,multiplyDragByParticleVelocity:!0},colorOverLifetime:{enabled:!1,color:{mode:1,color:{r:0,g:0,b:0,a:0},colorMin:{r:0,g:0,b:0,a:0},colorMax:{r:0,g:0,b:0,a:0}}},sizeOverLifetime:{enabled:!1,size:{mode:1,constant:0,constantMin:0,constantMax:0,multiplier:1},sizeMultiplier:1,x:{mode:1,constant:0,constantMin:0,constantMax:0,multiplier:1},xMultiplier:1,y:{mode:1,constant:0,constantMin:0,constantMax:0,multiplier:1},yMultiplier:1,z:{mode:1,constant:0,constantMin:0,constantMax:0,multiplier:1},zMultiplier:1,separateAxes:!1},rotationOverLifetime:{enabled:!1,x:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},xMultiplier:0,y:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},yMultiplier:0,z:{mode:0,constant:.7853982,constantMin:0,constantMax:.7853982,multiplier:1},zMultiplier:.7853982,separateAxes:!1},textureSheetAnimation:{enabled:!1,mode:0,timeMode:0,fps:30,numTilesX:1,numTilesY:1,animation:0,useRandomRow:!0,frameOverTime:{mode:1,constant:0,constantMin:0,constantMax:0,multiplier:.9999},frameOverTimeMultiplier:.9999,startFrame:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},startFrameMultiplier:0,cycleCount:1,rowIndex:0,rowMode:1,uvChannelMask:-1,flipU:0,flipV:0,speedRange:{x:0,y:1}}},n.UNITY_TO_BABYLON_SIZE_RATIO=1,n.UNITY_TO_BABYLON_GRAVITY_RATIO=1,n.UNITY_TO_BABYLON_EMIT_RATE_RATIO=2,n.UNITY_TO_BABYLON_EMIT_POWER_RATIO=2,n.UNITY_TO_BABYLON_CONE_SCALE_RATIO=2,n.UNITY_TO_BABYLON_LIFETIME_RATIO=.65,n.UNITY_TO_BABYLON_DEATH_FADE_ALPHA=.2,n.EMITTER_POSITION_OFFSET=new BABYLON.Vector3(0,0,0),n.EMITTER_ROTATION_OFFSET=new BABYLON.Vector3(90,0,0),n}(e.ScriptComponent);e.ShurikenParticles=t,e.SceneManager.RegisterClass("TOOLKIT.ShurikenParticles",t)}(i||(i={})),function(e){var t=function(){function e(){this.blendWithPhysicsNormal=0,this.maxLookupDistance=8,this.searchRadius=1,this.useProjectionTest=!0,this._v0x=null,this._v0y=null,this._v0z=null,this._v1x=null,this._v1y=null,this._v1z=null,this._v2x=null,this._v2y=null,this._v2z=null,this._n0x=null,this._n0y=null,this._n0z=null,this._n1x=null,this._n1y=null,this._n1z=null,this._n2x=null,this._n2y=null,this._n2z=null,this._fnx=null,this._fny=null,this._fnz=null,this._cx=null,this._cy=null,this._cz=null,this._triangleCount=0,this._cellTriangles=null,this._htKeys=null,this._htStarts=null,this._htCounts=null,this._cellSize=2,this._hashOriginX=0,this._hashOriginZ=0,this._sourceMesh=null,this._worldMatrix=BABYLON.Matrix.Identity(),this._invWorldMatrix=BABYLON.Matrix.Identity(),this._matrixDirty=!0,this._scratchV0=new BABYLON.Vector3,this._scratchLocal=new BABYLON.Vector3,this._candidatesBuf=[],this._uniqueBuf=[],this._seenSet=new Set,this._barycentricScratch=[0,0,0]}return Object.defineProperty(e.prototype,"triangleCount",{get:function(){return this._triangleCount},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"cellSize",{get:function(){return this._cellSize},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sourceMesh",{get:function(){return this._sourceMesh},enumerable:!1,configurable:!0}),e.prototype.buildFromMesh=function(e,t){void 0===t&&(t=2),this._sourceMesh=e,this._cellSize=Math.max(.01,t),this._htKeys=null,this._htStarts=null,this._htCounts=null,this._cellTriangles=null,this._triangleCount=0,this._matrixDirty=!0;var n=e.geometry;if(!n)return console.warn("[MeshNormalProxy] Mesh '"+e.name+"' has no geometry. Ensure the mesh is fully loaded before calling buildFromMesh."),!1;var i=n.getVerticesData(BABYLON.VertexBuffer.PositionKind),r=n.getVerticesData(BABYLON.VertexBuffer.NormalKind),o=n.getIndices();if(!i||0===i.length)return console.warn("[MeshNormalProxy] Mesh '"+e.name+"' has no position data."),!1;if(!r||0===r.length)return console.warn("[MeshNormalProxy] Mesh '"+e.name+"' has no normal data. Ensure normals are baked into the mesh."),!1;if(!o||0===o.length)return console.warn("[MeshNormalProxy] Mesh '"+e.name+"' has no index data."),!1;var a=Math.floor(o.length/3);if(0===a)return console.warn("[MeshNormalProxy] Mesh '"+e.name+"' has zero triangles."),!1;this._v0x=new Float32Array(a),this._v0y=new Float32Array(a),this._v0z=new Float32Array(a),this._v1x=new Float32Array(a),this._v1y=new Float32Array(a),this._v1z=new Float32Array(a),this._v2x=new Float32Array(a),this._v2y=new Float32Array(a),this._v2z=new Float32Array(a),this._n0x=new Float32Array(a),this._n0y=new Float32Array(a),this._n0z=new Float32Array(a),this._n1x=new Float32Array(a),this._n1y=new Float32Array(a),this._n1z=new Float32Array(a),this._n2x=new Float32Array(a),this._n2y=new Float32Array(a),this._n2z=new Float32Array(a),this._fnx=new Float32Array(a),this._fny=new Float32Array(a),this._fnz=new Float32Array(a),this._cx=new Float32Array(a),this._cy=new Float32Array(a),this._cz=new Float32Array(a);for(var s=1/0,l=1/0,u=-1/0,c=-1/0,d=0;d<a;d++){var h=o[3*d+0],p=o[3*d+1],m=o[3*d+2],f=i[3*h],g=i[3*h+1],v=i[3*h+2],y=i[3*p],_=i[3*p+1],S=i[3*p+2],A=i[3*m],b=i[3*m+1],M=i[3*m+2];this._v0x[d]=f,this._v0y[d]=g,this._v0z[d]=v,this._v1x[d]=y,this._v1y[d]=_,this._v1z[d]=S,this._v2x[d]=A,this._v2y[d]=b,this._v2z[d]=M,this._n0x[d]=r[3*h],this._n0y[d]=r[3*h+1],this._n0z[d]=r[3*h+2],this._n1x[d]=r[3*p],this._n1y[d]=r[3*p+1],this._n1z[d]=r[3*p+2],this._n2x[d]=r[3*m],this._n2y[d]=r[3*m+1],this._n2z[d]=r[3*m+2];var B=y-f,C=_-g,T=S-v,x=A-f,I=b-g,O=M-v,L=C*O-T*I,w=T*x-B*O,N=B*I-C*x,P=Math.sqrt(L*L+w*w+N*N);P>1e-10&&(L/=P,w/=P,N/=P),this._fnx[d]=L,this._fny[d]=w,this._fnz[d]=N;var R=(f+y+A)/3,E=(g+_+b)/3,k=(v+S+M)/3;this._cx[d]=R,this._cy[d]=E,this._cz[d]=k,(F=Math.min(f,y,A))<s&&(s=F),(U=Math.max(f,y,A))>u&&(u=U),(Y=Math.min(v,S,M))<l&&(l=Y),(V=Math.max(v,S,M))>c&&(c=V)}this._triangleCount=a,this._hashOriginX=s-this._cellSize,this._hashOriginZ=l-this._cellSize;var D=new Map;for(d=0;d<a;d++)for(var F=Math.min(this._v0x[d],this._v1x[d],this._v2x[d]),U=Math.max(this._v0x[d],this._v1x[d],this._v2x[d]),Y=Math.min(this._v0z[d],this._v1z[d],this._v2z[d]),V=Math.max(this._v0z[d],this._v1z[d],this._v2z[d]),G=Math.floor((F-this._hashOriginX)/this._cellSize),z=Math.floor((U-this._hashOriginX)/this._cellSize),W=Math.floor((Y-this._hashOriginZ)/this._cellSize),H=Math.floor((V-this._hashOriginZ)/this._cellSize),X=G;X<=z;X++)for(var K=W;K<=H;K++){var Q=this._makeHashKey(X,K),j=D.get(Q);D.set(Q,void 0!==j?j+1:1)}var Z=D.size,q=new Uint32Array(Z),J=0;D.forEach(function(e,t){q[J++]=t}),q.sort(),this._htKeys=new Uint32Array(Z),this._htStarts=new Int32Array(Z),this._htCounts=new Int32Array(Z);for(var $=0,ee=0;ee<Z;ee++){var te=q[ee];this._htKeys[ee]=te,this._htStarts[ee]=$,this._htCounts[ee]=D.get(te),$+=this._htCounts[ee]}this._cellTriangles=new Int32Array($);var ne=new Map;for(ee=0;ee<Z;ee++)ne.set(this._htKeys[ee],this._htStarts[ee]);for(d=0;d<a;d++)for(F=Math.min(this._v0x[d],this._v1x[d],this._v2x[d]),U=Math.max(this._v0x[d],this._v1x[d],this._v2x[d]),Y=Math.min(this._v0z[d],this._v1z[d],this._v2z[d]),V=Math.max(this._v0z[d],this._v1z[d],this._v2z[d]),G=Math.floor((F-this._hashOriginX)/this._cellSize),z=Math.floor((U-this._hashOriginX)/this._cellSize),W=Math.floor((Y-this._hashOriginZ)/this._cellSize),H=Math.floor((V-this._hashOriginZ)/this._cellSize),X=G;X<=z;X++)for(K=W;K<=H;K++){Q=this._makeHashKey(X,K);var ie=ne.get(Q);this._cellTriangles[ie]=d,ne.set(Q,ie+1)}return!0},e.prototype.invalidateTransform=function(){this._matrixDirty=!0},e.prototype.getNormalAtPointToRef=function(e,t,n){if(void 0===n&&(n=null),0===this._triangleCount||!this._sourceMesh)return!1;this._matrixDirty&&(this._worldMatrix.copyFrom(this._sourceMesh.getWorldMatrix()),this._worldMatrix.invertToRef(this._invWorldMatrix),this._matrixDirty=!1),BABYLON.Vector3.TransformCoordinatesToRef(e,this._invWorldMatrix,this._scratchLocal);var i=this._scratchLocal.x,r=this._scratchLocal.y,o=this._scratchLocal.z,a=Math.floor((i-this._hashOriginX)/this._cellSize),s=Math.floor((o-this._hashOriginZ)/this._cellSize),l=this._candidatesBuf;l.length=0;for(var u=this.searchRadius,c=-u;c<=u;c++)for(var d=-u;d<=u;d++)if((f=this._bsearchCell(this._makeHashKey(a+c,s+d)))>=0)for(var h=(g=this._htStarts[f])+this._htCounts[f],p=g;p<h;p++)l.push(this._cellTriangles[p]);if(0===l.length){var m=u+1;for(c=-m;c<=m;c++)for(d=-m;d<=m;d++){var f,g;if((f=this._bsearchCell(this._makeHashKey(a+c,s+d)))>=0)for(h=(g=this._htStarts[f])+this._htCounts[f],p=g;p<h;p++)l.push(this._cellTriangles[p])}}if(0===l.length)return!1;var v=this._seenSet;v.clear();var y=this._uniqueBuf;for(y.length=0,p=0;p<l.length;p++)v.has(l[p])||(v.add(l[p]),y.push(l[p]));for(var _=-1,S=1/0,A=-1,b=1/0,M=this.maxLookupDistance*this.maxLookupDistance,B=0;B<y.length;B++){var C=y[B],T=i-this._cx[C],x=o-this._cz[C],I=T*T+x*x;if(!(I>M))if(this.useProjectionTest){var O,L=this._fnx[C],w=this._fny[C],N=this._fnz[C],P=(c=i-this._v0x[C])*L+(r-this._v0y[C])*w+(d=o-this._v0z[C])*N,R=Math.abs(P),E=i-P*L,k=r-P*w,D=o-P*N,F=(G=this._computeBarycentricInline(E,k,D,C))[0],U=G[1],Y=G[2];F>=-.01&&U>=-.01&&Y>=-.01?(O=R+.001*I)<b&&(b=O,A=C):(O=R+.1*I)<S&&(S=O,_=C)}else I<S&&(S=I,_=C)}var V=A>=0?A:_;if(V<0)return!1;L=this._fnx[V],w=this._fny[V],N=this._fnz[V],E=i-(P=(c=i-this._v0x[V])*L+(r-this._v0y[V])*w+(d=o-this._v0z[V])*N)*L,k=r-P*w,D=o-P*N;var G=this._computeBarycentricInline(E,k,D,V),z=Math.max(0,G[0]),W=Math.max(0,G[1]),H=Math.max(0,G[2]),X=z+W+H;X<1e-8?z=W=H=1/3:(z/=X,W/=X,H/=X);var K=z*this._n0x[V]+W*this._n1x[V]+H*this._n2x[V],Q=z*this._n0y[V]+W*this._n1y[V]+H*this._n2y[V],j=z*this._n0z[V]+W*this._n1z[V]+H*this._n2z[V];if(this._scratchV0.set(K,Q,j),BABYLON.Vector3.TransformNormalToRef(this._scratchV0,this._worldMatrix,t),t.normalize(),this.blendWithPhysicsNormal>0&&n){var Z=this.blendWithPhysicsNormal;t.x=t.x*(1-Z)+n.x*Z,t.y=t.y*(1-Z)+n.y*Z,t.z=t.z*(1-Z)+n.z*Z,t.normalize()}return!0},e.prototype.dispose=function(){this._v0x=null,this._v0y=null,this._v0z=null,this._v1x=null,this._v1y=null,this._v1z=null,this._v2x=null,this._v2y=null,this._v2z=null,this._n0x=null,this._n0y=null,this._n0z=null,this._n1x=null,this._n1y=null,this._n1z=null,this._n2x=null,this._n2y=null,this._n2z=null,this._fnx=null,this._fny=null,this._fnz=null,this._cx=null,this._cy=null,this._cz=null,this._cellTriangles=null,this._htKeys=null,this._htStarts=null,this._htCounts=null,this._triangleCount=0,this._sourceMesh=null},e.prototype._makeHashKey=function(e,t){return e+32768+65536*(t+32768)>>>0},e.prototype._bsearchCell=function(e){for(var t=0,n=this._htKeys.length-1;t<=n;){var i=t+n>>>1,r=this._htKeys[i];if(r===e)return i;r<e?t=i+1:n=i-1}return-1},e.prototype._computeBarycentricInline=function(e,t,n,i){var r=this._v0x[i],o=this._v0y[i],a=this._v0z[i],s=this._v1x[i]-r,l=this._v1y[i]-o,u=this._v1z[i]-a,c=this._v2x[i]-r,d=this._v2y[i]-o,h=this._v2z[i]-a,p=e-r,m=t-o,f=n-a,g=s*s+l*l+u*u,v=s*c+l*d+u*h,y=c*c+d*d+h*h,_=p*s+m*l+f*u,S=p*c+m*d+f*h,A=g*y-v*v;if(Math.abs(A)<1e-12)return this._barycentricScratch[0]=1/3,this._barycentricScratch[1]=1/3,this._barycentricScratch[2]=1/3,this._barycentricScratch;var b=(y*_-v*S)/A,M=(g*S-v*_)/A,B=1-b-M;return this._barycentricScratch[0]=B,this._barycentricScratch[1]=b,this._barycentricScratch[2]=M,this._barycentricScratch},e}();e.MeshNormalProxy=t;var n=function(){function e(){this._registry=new Map}return Object.defineProperty(e,"instance",{get:function(){return e._instance||(e._instance=new e),e._instance},enumerable:!1,configurable:!0}),e.prototype.register=function(e,t){e?t&&0!==t.triangleCount?this._registry.set(e,t):console.warn("[SmoothMeshNormalSystem] register: proxy is null or empty — did you call buildFromMesh()?"):console.warn("[SmoothMeshNormalSystem] register: body is null.")},e.prototype.unregister=function(e,t){void 0===t&&(t=!1);var n=this._registry.get(e);n&&(t&&n.dispose(),this._registry.delete(e))},e.prototype.lookup=function(e){return this._registry.get(e)||null},e.prototype.has=function(e){return this._registry.has(e)},Object.defineProperty(e.prototype,"count",{get:function(){return this._registry.size},enumerable:!1,configurable:!0}),e.prototype.disposeAll=function(){this._registry.forEach(function(e){e.dispose()}),this._registry.clear()},e.buildAndRegister=function(n,i,r,o){if(void 0===r&&(r=2),void 0===o&&(o=0),!n)return console.warn("[SmoothMeshNormalSystem] buildAndRegister: mesh is null."),null;if(!n.geometry)return console.warn("[SmoothMeshNormalSystem] buildAndRegister: mesh '"+n.name+"' has no geometry. Ensure the mesh has been properly initialized."),null;if(!i)return console.warn("[SmoothMeshNormalSystem] buildAndRegister: mesh '"+n.name+"' has no physicsBody. Ensure RigidbodyPhysics has run first."),null;var a=new t;return a.blendWithPhysicsNormal=Math.max(0,Math.min(1,o)),a.buildFromMesh(n,r)?(e.instance.register(i,a),a):(a.dispose(),null)},e._instance=null,e}();e.SmoothMeshNormalSystem=n}(i||(i={})),function(e){var t;!function(e){e[e.None=0]="None",e[e.ToGamma=1]="ToGamma",e[e.ToLinear=2]="ToLinear"}(t=e.ColorCorrectionMode||(e.ColorCorrectionMode={}));var n=function(n){function i(e,t,i,r){void 0===i&&(i={}),void 0===r&&(r="TOOLKIT.TerrainBuilder");var o=n.call(this,e,t,i,r)||this;return o.detailLayerContainers=[],o.detailMeshSources=new Map,o}return r(i,n),i.prototype.awake=function(){var t=this.getProperties();t&&e.TerrainBuilder.BuildDetailPrototypes(t,this.transform,this.scene,this)},i.prototype.destroy=function(){this.disposeDetailLayers()},i.prototype.disposeDetailLayers=function(){for(var e=0,t=this.detailLayerContainers;e<t.length;e++)t[e].dispose();this.detailLayerContainers=[],this.detailMeshSources.forEach(function(e,t){try{e.dispose()}catch(e){}}),this.detailMeshSources.clear()},i.BuildDetailPrototypes=function(t,n,i,r){if(t&&t.detaillayers&&0!==t.detaillayers.length)for(var o=t.terrainsize?new BABYLON.Vector3(t.terrainsize[0],t.terrainsize[1],t.terrainsize[2]):new BABYLON.Vector3(500,100,500),a=n.position||BABYLON.Vector3.Zero(),s=t.detailobjectdensity||1,l=null!=t.detailbillboardingmode?t.detailbillboardingmode:0,u=null!=t.detailgrassshadowlevel?t.detailgrassshadowlevel:.7,c=null==t.detailgrassreceiveshadows||t.detailgrassreceiveshadows,d=null!=t.wavinggrassamount?t.wavinggrassamount:.5,h=null!=t.wavinggrassspeed?t.wavinggrassspeed:.5,p=null!=t.wavinggrasssize?t.wavinggrasssize:.5,m=t.wavinggrasstint?new BABYLON.Color4(t.wavinggrasstint[0],t.wavinggrasstint[1],t.wavinggrasstint[2],t.wavinggrasstint[3]||1):new BABYLON.Color4(.7,.8,.5,1),f=0;f<t.detaillayers.length;f++){var g=t.detaillayers[f];if(g.detailscattermode=t.detailscattermode,g.isvalid)try{if(g.useprototypemesh)e.TerrainBuilder.BuildMeshDetailLayer(g,o,a,n,i,s,r);else{var v=null!=s?s:1;e.TerrainBuilder.BuildGrassDetailLayer(g,o,a,n,i,v,d,h,p,m,l,u,c,r)}}catch(e){}}},i.BuildMeshDetailLayer=function(t,n,i,r,o,a,s){var l=t.prototypemeshnodeid?o.getNodeById(t.prototypemeshnodeid):null;if(l&&l instanceof BABYLON.Mesh){var u=new BABYLON.TransformNode("DetailLayer_".concat(t.layerindex,"_").concat(t.prototypemeshname),o);u.parent=r,s&&s.detailLayerContainers.push(u);var c=t.detailinstancepatches&&t.detailinstancepatches.length>0?e.TerrainBuilder.GenerateMeshInstancesFromUnityPatches(t,n,i):null;if(null!=c&&0!==c.length){var d=e.TerrainBuilder.CreateDetailThinInstancesFromDensityMap(l,c,u,o,t);d&&s&&s.detailMeshSources.set("layer_".concat(t.layerindex),d)}}},i.BuildGrassDetailLayer=function(t,n,i,r,o,a,s,l,u,c,d,h,p,m){var f=new BABYLON.TransformNode("DetailLayer_".concat(t.layerindex,"_Grass"),o);f.parent=r,m&&m.detailLayerContainers.push(f);var g=e.TerrainBuilder.CreateGrassPrototype(t,f,o,s,l,u,c,d,h);if(g){var v=e.TerrainBuilder.CreateGrassThinInstancesFromDensityMap(g,t,n,i,a,p,f,o);v&&m&&m.detailMeshSources.set("layer_".concat(t.layerindex),v)}else console.warn("Failed to create grass prototype mesh for layer ".concat(t.layerindex))},i.GenerateMeshInstancesFromUnityPatches=function(t,n,i){var r=[],o=t.detailinstancepatches;if(!o||0===o.length)return r;for(var a=0;a<o.length;a++){var s=o[a],l=s&&s.transforms?s.transforms:null;if(l&&!(l.length<6))for(var u=0;u+5<l.length;u+=6){var c=l[u+0],d=l[u+1],h=l[u+2],p=l[u+3],m=l[u+4],f=l[u+5],g=i.x+c-.5*n.x,v=i.z+h-.5*n.z,y=i.y+d,_=new BABYLON.Vector3(g,y,v),S=e.TerrainBuilder.NormalizeRotation(p),A=new BABYLON.Vector3(m,f,m),b=new BABYLON.Color4(1,1,1,1);r.push({position:_,rotation:S,scale:A,color:b})}}return r},i.CreateGrassThinInstancesFromDensityMap=function(t,n,i,r,o,a,s,l){var u;if(!n.densitymap||!n.densitywidth||!n.densityheight)return null;for(var c=n.densitywidth,d=n.densityheight,h=!1===n.usedensityscaling?1:null!=o?o:1,p=null!=n.targetcoverage?n.targetcoverage:null!=n.density?n.density:1,m=Math.max(0,Math.min(1,p)),f="CoverageMode"===(n.detailscattermode||n.detailScatterMode),g=null!=n.positionjitter?n.positionjitter:null!=n.positionsjitter?n.positionsjitter:null,v=null!=g?g:1,y=null!=n.noisespread?n.noisespread:1,_=i.x/c,S=i.z/d,A=n.minwidth||1,b=n.maxwidth||2,M=n.minheight||1,B=n.maxheight||2,C=Math.max(1e-4,.5*(A+b)),T=Math.max(1e-4,.5*(M+B)),x=_*S,I=C*T,O=!n.useprototypemesh&&(n.healthycolor||n.drycolor),L=n.healthycolor?n.healthycolor[0]:.3,w=n.healthycolor?n.healthycolor[1]:.8,N=n.healthycolor?n.healthycolor[2]:.2,P=n.healthycolor&&n.healthycolor[3]||1,R=n.drycolor?n.drycolor[0]:.8,E=n.drycolor?n.drycolor[1]:.7,k=n.drycolor?n.drycolor[2]:.3,D=n.drycolor&&n.drycolor[3]||1,F=null!=n.noiseseed?n.noiseseed:(null!=n.layerindex?n.layerindex:0)+1,U=function(t,n,i,r){var o=Math.floor(1e3*(y||1));return e.TerrainBuilder.HashToUnitFloat(t+o,n-o,i,F,r)},Y=function(e,t,n){if(n<=0)return 0;var i=0;if((i=f?Math.max(0,Math.min(1,n/255))*m*h*(x/I):n*h*m)<=0)return 0;var r=Math.floor(i),o=i-r;return o<=0?r:r+(U(e,t,0,907)<o?1:0)},V=0,G=0;G<d;G++)for(var z=0;z<c;z++){var W=G*c+z;(re=n.densitymap[W]||0)<=0||(V+=Y(z,G,re))}if(V<=0)return null;var H=new Float32Array(3*V),X=new Float32Array(V),K=new Float32Array(V),Q=new Float32Array(V),j=O?new Float32Array(4*V):null,Z=Number.POSITIVE_INFINITY,q=Number.POSITIVE_INFINITY,J=Number.NEGATIVE_INFINITY,$=Number.NEGATIVE_INFINITY,ee=n&&n.cellcornerheights?n.cellcornerheights:null,te=n&&n.cellheights?n.cellheights:null,ne=null!=n.groundOffset?n.groundOffset:.02,ie=0;for(G=0;G<d;G++)for(z=0;z<c;z++){var re;if(W=G*c+z,!((re=n.densitymap[W]||0)<=0)){var oe=Y(z,G,re);if(!(oe<=0))for(var ae=0;ae<oe;ae++){var se=U(z,G,ae,11),le=U(z,G,ae,43),ue=Math.min(Math.max(v,0),1),ce=G*S+(.5+(le-.5)*ue)*S,de=z*_+(.5+(se-.5)*ue)*_,he=r.x+ce-.5*i.z,pe=r.z+de-.5*i.x,me=r.y;if(ee&&ee.length===(c+1)*(d+1)){var fe=(he-(r.x-.5*i.x))/i.x,ge=(pe-(r.z-.5*i.z))/i.z,ve=Math.max(0,Math.min(1,fe))*c,ye=Math.max(0,Math.min(1,ge))*d,_e=ve-(Bt=Math.floor(ve)),Se=ye-(Te=Math.floor(ye)),Ae=Math.max(0,Math.min(c,Bt)),be=Math.max(0,Math.min(c,Bt+1)),Me=Math.max(0,Math.min(d,Te)),Be=Math.max(0,Math.min(d,Te+1)),Ce=c+1;me=(we=(xe=ee[Me*Ce+Ae])+((Ie=ee[Me*Ce+be])-xe)*_e)+((Oe=ee[Be*Ce+Ae])+((Le=ee[Be*Ce+be])-Oe)*_e-we)*Se,me+=ne}else if(te&&te.length===c*d){var Te,xe,Ie,Oe,Le,we;fe=(he-(r.x-.5*i.x))/i.x,ge=(pe-(r.z-.5*i.z))/i.z,ve=Math.max(0,Math.min(1,fe))*c-.5,ye=Math.max(0,Math.min(1,ge))*d-.5,_e=ve-(Bt=Math.floor(ve)),Se=ye-(Te=Math.floor(ye)),Ae=Math.max(0,Math.min(c-1,Bt)),be=Math.max(0,Math.min(c-1,Bt+1)),Me=Math.max(0,Math.min(d-1,Te)),Be=Math.max(0,Math.min(d-1,Te+1)),me=(we=(xe=te[Me*c+Ae])+((Ie=te[Me*c+be])-xe)*_e)+((Oe=te[Be*c+Ae])+((Le=te[Be*c+be])-Oe)*_e-we)*Se,me+=ne;try{var Ne=Math.max(xe,Ie,Oe,Le);Ne-me>.05&&(me=.6*me+.4*Ne)}catch(e){}}else me=r.y;H[0+(Mt=3*ie)]=he,H[Mt+1]=me,H[Mt+2]=pe,he<Z&&(Z=he),pe<q&&(q=pe),he>J&&(J=he),pe>$&&($=pe);var Pe=A+U(z,G,ae,71)*(b-A),Re=(M+U(z,G,ae,17)*(B-M))*e.TerrainBuilder.grassHeightScale;X[ie]=Pe,K[ie]=Re;var Ee=2*Math.PI,ke=0;if("GrassBillboard"!==(n&&n.rendermode?n.rendermode:"GrassBillboard")&&(ke=U(z,G,ae,131)*Ee,e.TerrainBuilder.grassRandomFlip&&U(z,G,ae,997)<.5&&(ke+=Math.PI)),Q[ie]=ke,j){var De=.5;if(n.colorvariationmap&&n.colorvariationmap.length===c*d){var Fe=G*c+z;if(De=n.colorvariationmap[Fe],0===ie&&0===n.layerindex){for(var Ue=1,Ye=0,Ve=0,Ge=0;Ge<n.colorvariationmap.length;Ge++){var ze=n.colorvariationmap[Ge];ze<Ue&&(Ue=ze),ze>Ye&&(Ye=ze),Ve+=ze}Ve/=n.colorvariationmap.length,console.log("[TerrainBuilder] Color variation map stats: min=".concat(Ue.toFixed(3),", max=").concat(Ye.toFixed(3),", avg=").concat(Ve.toFixed(3)))}}else De=U(z,G,ae,101),0===ie&&0===n.layerindex&&console.warn("[TerrainBuilder] No color variation map found for layer ".concat(n.layerindex,". Using per-instance random. Export colorvariationmap from Unity for exact matching."));var We=L+(R-L)*(De=1-(De=Math.min(1,Math.max(0,De)))),He=w+(E-w)*De,Xe=N+(k-N)*De,Ke=P+(D-P)*De;j[0+(Lt=4*ie)]=We,j[Lt+1]=He,j[Lt+2]=Xe,j[Lt+3]=Ke}ie++}}}var Qe=Math.min(ie,V);if(Qe<=0)return null;var je=null!==(u=e.TerrainBuilder.detailChunkMode)&&void 0!==u?u:0,Ze=Math.max(1,e.TerrainBuilder.detailChunkTargetInstances||8e3),qe=Math.max(1e-4,e.TerrainBuilder.detailChunkWorldSize||32),Je=Math.max(1,e.TerrainBuilder.detailChunkMaxChunksPerAxis||64),$e=Math.max(1,e.TerrainBuilder.detailChunkMaxTotalChunks||256),et=Math.max(1e-4,J-Z),tt=Math.max(1e-4,$-q),nt=1,it=1;if(0===je){if(nt=Math.ceil(et/qe),it=Math.ceil(tt/qe),nt=Math.max(1,Math.min(Je,nt)),it=Math.max(1,Math.min(Je,it)),(lt=nt*it)>$e){var rt=Math.sqrt(lt/$e);nt=Math.max(1,Math.min(Je,Math.ceil(nt/rt))),it=Math.max(1,Math.min(Je,Math.ceil(it/rt)))}}else{var ot=Math.max(1,Math.ceil(Qe/Ze)),at=Math.ceil(Math.sqrt(ot)),st=Math.max(1,Math.floor(Math.sqrt($e)));at=Math.max(1,Math.min(Je,Math.min(st,at)));var lt,ut=et/tt;nt=at,it=at,ut>1.5?(nt=Math.min(Je,Math.ceil(at*Math.sqrt(ut))),it=Math.max(1,Math.ceil(at/Math.sqrt(ut)))):ut<1/1.5&&(it=Math.min(Je,Math.ceil(at*Math.sqrt(1/ut))),nt=Math.max(1,Math.ceil(at/Math.sqrt(1/ut)))),(lt=nt*it)>$e&&(rt=Math.sqrt(lt/$e),nt=Math.max(1,Math.min(Je,Math.ceil(nt/rt))),it=Math.max(1,Math.min(Je,Math.ceil(it/rt))),lt=nt*it)}var ct=et/nt,dt=tt/it,ht=new BABYLON.TransformNode("".concat(t.name,"_Chunks_L").concat(n.layerindex),l);ht.parent=s;try{t.setEnabled(!1),t.isVisible=!1}catch(e){}var pt=new Map;for(ae=0;ae<Qe;ae++){var mt=H[0+(Mt=3*ae)],ft=H[Mt+2];(Bt=Math.floor((mt-Z)/ct))<0&&(Bt=0),(Ct=Math.floor((ft-q)/dt))<0&&(Ct=0),Bt>=nt&&(Bt=nt-1),Ct>=it&&(Ct=it-1);var gt=Bt+Ct*nt;pt.set(gt,(pt.get(gt)||0)+1)}var vt=new Map;pt.forEach(function(e,t){var n=new Float32Array(16*e),i=j?new Float32Array(4*e):null;vt.set(t,{count:e,write:0,matrices:n,colors:i})});var yt=new BABYLON.Matrix,_t=new BABYLON.Vector3(1,1,1),St=new BABYLON.Vector3(0,0,0),At=new BABYLON.Quaternion,bt=BABYLON.Axis.Y;for(ae=0;ae<Qe;ae++){mt=H[0+(Mt=3*ae)];var Mt,Bt,Ct,Tt=H[Mt+1];ft=H[Mt+2],(Bt=Math.floor((mt-Z)/ct))<0&&(Bt=0),(Ct=Math.floor((ft-q)/dt))<0&&(Ct=0),Bt>=nt&&(Bt=nt-1),Ct>=it&&(Ct=it-1),gt=Bt+Ct*nt;var xt=vt.get(gt);if(xt){var It=xt.write++;St.x=mt,St.y=Tt,St.z=ft;var Ot=X[ae];if(_t.x=Ot,_t.y=K[ae],_t.z=Ot,BABYLON.Quaternion.RotationAxisToRef(bt,Q[ae],At),BABYLON.Matrix.ComposeToRef(_t,At,St,yt),yt.copyToArray(xt.matrices,16*It),xt.colors&&j){var Lt=4*ae,wt=(We=Math.min(1,j[Lt+0]),He=Math.min(1,j[Lt+1]),Xe=Math.min(1,j[Lt+2]),Ke=j[Lt+3],4*It);xt.colors[wt+0]=e.TerrainBuilder.DoColorCorrection(We,e.TerrainBuilder.grassColorCorrectionMode),xt.colors[wt+1]=e.TerrainBuilder.DoColorCorrection(He,e.TerrainBuilder.grassColorCorrectionMode),xt.colors[wt+2]=e.TerrainBuilder.DoColorCorrection(Xe,e.TerrainBuilder.grassColorCorrectionMode),xt.colors[wt+3]=Ke}}}var Nt=null,Pt=0;return vt.forEach(function(i,r){if(i&&!(i.count<=0)){var o=function(i,r){var o,s,u,c,d,h;if(!i||i.count<=0)return null;var p=r%nt,m=Math.floor(r/nt),f="".concat(t.name,"_L").concat(n.layerindex,"_C").concat(p,"_").concat(m,"_").concat(Pt),g=t.clone(f,ht);if(!g)return null;try{g.makeGeometryUnique()}catch(e){}g.setEnabled(!0),g.isVisible=!0,g.applyFog=e.TerrainBuilder.grassReceiveFog,g.receiveShadows=a,g.thinInstanceEnablePicking=!1;try{null===(s=(o=g).thinInstanceSetBuffer)||void 0===s||s.call(o,"matrix",null,16,!0)}catch(e){}try{null===(c=(u=g).thinInstanceSetBuffer)||void 0===c||c.call(u,"color",null,4,!0)}catch(e){}g.thinInstanceSetBuffer("matrix",i.matrices,16,!0),i.colors&&(g.thinInstanceSetBuffer("color",i.colors,4,!0),g.useVertexColors=!0,g.hasVertexAlpha=!0);try{null===(h=(d=g).thinInstanceRefreshBoundingInfo)||void 0===h||h.call(d,!0)}catch(e){}try{var v=g.material;if(v&&"function"==typeof v.setFloatValue){var y=null!=n.maxdistance?n.maxdistance:0;v.setFloatValue("g_maxDistance",y);var _=y>0?Math.max(0,.75*y):0;v.setFloatValue("g_fadeStart",_)}}catch(e){}try{l&&l.lights&&l.lights.forEach(function(t){try{var n=t.getShadowGenerator?t.getShadowGenerator():null;if(n){var i=n.getShadowMap?n.getShadowMap():null;if(i)if(e.TerrainBuilder.grassCastShadows)i.renderList||(i.renderList=[]),-1===i.renderList.indexOf(g)&&i.renderList.push(g);else if(i.renderList){var r=i.renderList.indexOf(g);-1!==r&&i.renderList.splice(r,1)}}}catch(e){}})}catch(e){}return g.metadata=g.metadata||{},g.metadata.toolkit=g.metadata.toolkit||{},g.metadata.toolkit.castRealtimeShadow=e.TerrainBuilder.grassCastShadows,g.metadata.toolkit.terrainDetailLayer=n.layerindex,g.metadata.toolkit.terrainDetailChunked=!0,g}(i,r);o&&(Pt++,Nt||(Nt=o))}}),Nt||(ht.dispose(),null)},i.CreateDetailThinInstancesFromDensityMap=function(t,n,i,r,o){var a,s;if(!n||0===n.length)return null;var l=t;try{var u=t.clone("".concat(t.name,"_DetailSourceNorm_L").concat(o.layerindex),i,!1,!1);if(u){try{u.makeGeometryUnique()}catch(e){}try{u.bakeCurrentTransformIntoVertices()}catch(e){}u.position.set(0,0,0),u.rotationQuaternion=BABYLON.Quaternion.Identity(),u.scaling.set(1,1,1),u.setEnabled(!1),u.isVisible=!1,l=u}}catch(e){l=t}for(var c=!!o.useprototypemesh,d=c?null!==(a=e.TerrainBuilder.meshDetailChunkMode)&&void 0!==a?a:1:null!==(s=e.TerrainBuilder.detailChunkMode)&&void 0!==s?s:0,h=Math.max(1,(c?e.TerrainBuilder.meshDetailChunkTargetInstances:e.TerrainBuilder.detailChunkTargetInstances)||8e3),p=Math.max(1e-4,(c?e.TerrainBuilder.meshDetailChunkWorldSize:e.TerrainBuilder.detailChunkWorldSize)||32),m=Math.max(1,e.TerrainBuilder.detailChunkMaxChunksPerAxis||64),f=Math.max(1,e.TerrainBuilder.detailChunkMaxTotalChunks||256),g=Number.POSITIVE_INFINITY,v=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,_=Number.NEGATIVE_INFINITY,S=0;S<n.length;S++){var A=n[S].position;A.x<g&&(g=A.x),A.z<v&&(v=A.z),A.x>y&&(y=A.x),A.z>_&&(_=A.z)}var b=Math.max(1e-4,y-g),M=Math.max(1e-4,_-v),B=1,C=1;if(0===d){if(B=Math.ceil(b/p),C=Math.ceil(M/p),B=Math.max(1,Math.min(m,B)),C=Math.max(1,Math.min(m,C)),(L=B*C)>f){var T=Math.sqrt(L/f);B=Math.max(1,Math.min(m,Math.ceil(B/T))),C=Math.max(1,Math.min(m,Math.ceil(C/T)))}}else{var x=Math.max(1,Math.ceil(n.length/h)),I=Math.ceil(Math.sqrt(x)),O=Math.max(1,Math.floor(Math.sqrt(f)));I=Math.max(1,Math.min(m,Math.min(O,I)));var L,w=b/M;B=I,C=I,w>1.5?(B=Math.min(m,Math.ceil(I*Math.sqrt(w))),C=Math.max(1,Math.ceil(I/Math.sqrt(w)))):w<1/1.5&&(C=Math.min(m,Math.ceil(I*Math.sqrt(1/w))),B=Math.max(1,Math.ceil(I/Math.sqrt(1/w)))),(L=B*C)>f&&(T=Math.sqrt(L/f),B=Math.max(1,Math.min(m,Math.ceil(B/T))),C=Math.max(1,Math.min(m,Math.ceil(C/T))),L=B*C)}var N=b/B,P=M/C,R=new BABYLON.TransformNode("".concat(t.name,"_Chunks_L").concat(o.layerindex),r);R.parent=i;var E=new Map;for(S=0;S<n.length;S++){var k=n[S],D=Math.floor((k.position.x-g)/N),F=Math.floor((k.position.z-v)/P);D<0&&(D=0),F<0&&(F=0),D>=B&&(D=B-1),F>=C&&(F=C-1);var U=D+F*B,Y=E.get(U);Y?Y.push(k):E.set(U,[k])}try{t.setEnabled(!1),t.isVisible=!1}catch(e){}var V=!o.useprototypemesh&&(o.healthycolor||o.drycolor),G=null,z=0;return E.forEach(function(n,i){if(n&&0!==n.length){var a=i%B,s=Math.floor(i/B),u=function(t,n){var i,a,s,u,c,d;if(!t||0===t.length)return null;var h=l.clone(n,R);if(!h)return null;try{h.makeGeometryUnique()}catch(e){}h.setEnabled(!0),h.isVisible=!0,h.receiveShadows=!1,h.applyFog=!0,h.thinInstanceEnablePicking=!1;for(var p=new Float32Array(16*t.length),m=V?new Float32Array(4*t.length):null,f=new BABYLON.Matrix,g=new BABYLON.Quaternion,v=0;v<t.length;v++){var y=t[v],_=16*v,S=y.scale;if(BABYLON.Quaternion.RotationAxisToRef(BABYLON.Axis.Y,y.rotation,g),BABYLON.Matrix.ComposeToRef(S,g,y.position,f),f.copyToArray(p,_),m){var A=4*v,b=Math.min(1,y.color.r),M=Math.min(1,y.color.g),B=Math.min(1,y.color.b);m[A]=e.TerrainBuilder.DoColorCorrection(b,e.TerrainBuilder.grassColorCorrectionMode),m[A+1]=e.TerrainBuilder.DoColorCorrection(M,e.TerrainBuilder.grassColorCorrectionMode),m[A+2]=e.TerrainBuilder.DoColorCorrection(B,e.TerrainBuilder.grassColorCorrectionMode),m[A+3]=y.color.a}}try{null===(a=(i=h).thinInstanceSetBuffer)||void 0===a||a.call(i,"matrix",null,16,!0)}catch(e){}try{null===(u=(s=h).thinInstanceSetBuffer)||void 0===u||u.call(s,"color",null,4,!0)}catch(e){}h.thinInstanceSetBuffer("matrix",p,16,!0),m&&(h.thinInstanceSetBuffer("color",m,4,!0),h.useVertexColors=!0,h.hasVertexAlpha=!0);try{null===(d=(c=h).thinInstanceRefreshBoundingInfo)||void 0===d||d.call(c,!0)}catch(e){}try{var C=h.material;if(C&&"function"==typeof C.setFloatValue){var T=null!=o.maxdistance?o.maxdistance:0;C.setFloatValue("g_maxDistance",T);var x=T>0?Math.max(0,.75*T):0;C.setFloatValue("g_fadeStart",x)}}catch(e){}try{r&&r.lights&&r.lights.forEach(function(t){try{var n=t.getShadowGenerator?t.getShadowGenerator():null;if(n){var i=n.getShadowMap?n.getShadowMap():null;if(i)if(e.TerrainBuilder.grassCastShadows)i.renderList||(i.renderList=[]),-1===i.renderList.indexOf(h)&&i.renderList.push(h);else if(i.renderList){var r=i.renderList.indexOf(h);-1!==r&&i.renderList.splice(r,1)}}}catch(e){}})}catch(e){}return h.metadata=h.metadata||{},h.metadata.toolkit=h.metadata.toolkit||{},h.metadata.toolkit.castRealtimeShadow=e.TerrainBuilder.grassCastShadows,h.metadata.toolkit.terrainDetailLayer=o.layerindex,h.metadata.toolkit.terrainDetailChunked=!0,h}(n,"".concat(t.name,"_L").concat(o.layerindex,"_C").concat(a,"_").concat(s,"_").concat(z));u&&(z++,G||(G=u))}}),G||(R.dispose(),null)},i.CreateGrassPrototype=function(t,n,i,r,o,a,s,l,u){var c=t.rendermode||"GrassBillboard",d=(null!=t.prototypetexture&&null!=t.prototypetexture.filename&&t.prototypetexture.filename,((t.minwidth||1)+(t.maxwidth||2))/2),h=((t.minheight||1)+(t.maxheight||2))/2*e.TerrainBuilder.grassHeightScale,p=null;if("GrassBillboard"===c?p=e.TerrainBuilder.CreateSingleQuadBillboard("GrassBillboard_".concat(t.layerindex),d,h,i):"Grass"===c?p=e.TerrainBuilder.CreateCrossQuadGrass("GrassCross_".concat(t.layerindex),d,h,i):"VertexLit"===c&&((p=BABYLON.MeshBuilder.CreatePlane("GrassPlane_".concat(t.layerindex),{width:d,height:h},i)).rotation.x=Math.PI/2),!p)return null;p.parent=n,p.isVisible=!1,p.applyFog=!0,"VertexLit"!==c&&e.TerrainBuilder.ApplyUpNormals(p);var m="GrassBillboard"===c?new e.GrassBillboardMaterial("GrassBillboardMaterial_".concat(t.layerindex),i):new e.GrassStandardMaterial("GrassStandardMaterial_".concat(t.layerindex),i);if(null!=t.prototypetexture&&null!=t.prototypetexture.filename&&""!==t.prototypetexture.filename){var f="scenes/".concat(t.prototypetexture.filename),g=new BABYLON.Texture(f,i);g.hasAlpha=!0,g.gammaSpace=!0,g.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE),g.anisotropicFilteringLevel=4,g.wrapU=BABYLON.Texture.CLAMP_ADDRESSMODE,g.wrapV=BABYLON.Texture.CLAMP_ADDRESSMODE,(m instanceof e.GrassStandardMaterial||m instanceof e.GrassBillboardMaterial)&&(m.diffuseTexture=g,m.useAlphaFromDiffuseTexture=!0),m.alphaCutOff=.3;try{m.setFloatValue("g_alphaCutoff",null!=m.alphaCutOff?m.alphaCutOff:.3)}catch(e){}}else m.alphaCutOff=.3,m.emissiveColor=new BABYLON.Color3(0,0,0),t&&t.healthycolor&&(m instanceof e.GrassStandardMaterial||m instanceof e.GrassBillboardMaterial)&&(m.diffuseColor=new BABYLON.Color3(e.TerrainBuilder.DoColorCorrection(t.healthycolor[0],e.TerrainBuilder.grassColorCorrectionMode),e.TerrainBuilder.DoColorCorrection(t.healthycolor[1],e.TerrainBuilder.grassColorCorrectionMode),e.TerrainBuilder.DoColorCorrection(t.healthycolor[2],e.TerrainBuilder.grassColorCorrectionMode)));if(m instanceof e.GrassStandardMaterial){if(m.diffuseTexture){m.diffuseColor=new BABYLON.Color3(1,1,1);try{m.setFloatValue("g_alphaCutoff",null!=m.alphaCutOff?m.alphaCutOff:.3)}catch(e){}}}else if(m instanceof e.GrassBillboardMaterial&&m.diffuseTexture){m.diffuseColor=new BABYLON.Color3(1,1,1);try{m.setFloatValue("g_alphaCutoff",null!=m.alphaCutOff?m.alphaCutOff:.3)}catch(e){}}return m.roughness=1,m.twoSidedLighting=!0,m.backFaceCulling=!1,m.emissiveColor=new BABYLON.Color3(0,0,0),m.transparencyMode=BABYLON.Material.MATERIAL_ALPHATEST,m.separateCullingPass=!0,p.material=m,m.setFloatValue("g_maxDistance",0),m.setFloatValue("g_fadeStart",0),m.setFloatValue("g_windAmount",null!=r?r:.5),m.setFloatValue("g_waveSpeed",null!=o?o:.5),m.setFloatValue("g_waveSize",null!=a?a:.5),m.setVector4Value("g_windTint",new BABYLON.Vector4(s.r,s.g,s.b,s.a)),m.setShadowIntensity(u),m instanceof e.GrassBillboardMaterial&&m.setSphericalBillboardEnabled(0===l),p},i.CreateSingleQuadBillboard=function(e,t,n,i){var r=[],o=[],a=[],s=[],l=t/2;r.push(-l,0,0,l,0,0,l,n,0,-l,n,0),o.push(0,1,2,0,2,3),s.push(0,0,1,0,1,1,0,1);for(var u=0;u<4;u++)a.push(0,1,0);var c=new BABYLON.Mesh(e,i),d=new BABYLON.VertexData;return d.positions=r,d.indices=o,d.normals=a,d.uvs=s,d.applyToMesh(c),c},i.CreateCrossQuadGrass=function(e,t,n,i){var r=[],o=[],a=[],s=[],l=t/2;r.push(-l,0,0,l,0,0,l,n,0,-l,n,0),r.push(0,0,-l,0,0,l,0,n,l,0,n,-l),o.push(0,1,2,0,2,3,4,5,6,4,6,7),s.push(0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1);for(var u=0;u<8;u++)a.push(0,1,0);var c=new BABYLON.Mesh(e,i),d=new BABYLON.VertexData;return d.positions=r,d.indices=o,d.normals=a,d.uvs=s,d.applyToMesh(c),c},i.ApplyUpNormals=function(e){var t=e.getVerticesData(BABYLON.VertexBuffer.PositionKind);if(t){for(var n=new Array(t.length),i=0;i<t.length;i+=3)n[i]=0,n[i+1]=1,n[i+2]=0;e.setVerticesData(BABYLON.VertexBuffer.NormalKind,n,!1)}},i.HashToUnitFloat=function(e,t,n,i,r){var o=374761393*e+668265263*t+1442695041*n+374761393*i+374761393*r;return o=1274126177*(o^o>>13),((o^=o>>16)>>>0)/4294967296},i.NormalizeRotation=function(e){var t=2*Math.PI,n=e%t;return n<0&&(n+=t),n},i.DoColorCorrection=function(n,i){switch(i){case t.ToGamma:return e.TerrainBuilder.LinearToGamma(n);case t.ToLinear:return e.TerrainBuilder.GammaToLinear(n);case t.None:default:return n}},i.GammaToLinear=function(e){var t=Math.max(0,Math.min(1,e));return Math.pow(t,2.2)},i.LinearToGamma=function(e){var t=Math.max(0,Math.min(1,e));return Math.pow(t,1/2.2)},i.grassHeightScale=.85,i.grassRandomFlip=!1,i.grassCastShadows=!1,i.grassReceiveFog=!0,i.grassColorCorrectionMode=1,i.detailChunkMode=0,i.detailChunkTargetInstances=8e3,i.detailChunkWorldSize=32,i.detailChunkMaxChunksPerAxis=64,i.detailChunkMaxTotalChunks=256,i.meshDetailChunkMode=1,i.meshDetailChunkTargetInstances=2e4,i.meshDetailChunkWorldSize=64,i}(e.ScriptComponent);e.TerrainBuilder=n,e.SceneManager.RegisterClass("TOOLKIT.TerrainBuilder",n)}(i||(i={})),function(e){var t=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return r(t,e),t}(BABYLON.GUI.Slider);e.UnitySlider=t;var n=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._direction="LeftToRight",t}return r(t,e),Object.defineProperty(t.prototype,"direction",{get:function(){return this._direction},set:function(e){this._direction=e,this._markAsDirty()},enumerable:!1,configurable:!0}),t.prototype._getThumbPosition=function(){var e=(this.value-this.minimum)/(this.maximum-this.minimum),t=this.isVertical?this._currentMeasure.height-this._effectiveThumbThickness:this._currentMeasure.width-this._effectiveThumbThickness,n=e*t;return"RightToLeft"!==this._direction||this.isVertical?"TopToBottom"===this._direction&&this.isVertical&&(n=t-n):n=t-n,n},t.prototype.serialize=function(t){e.prototype.serialize.call(this,t),t.direction=this._direction},t.prototype._parseFromContent=function(t,n){e.prototype._parseFromContent.call(this,t,n),t.direction&&(this._direction=t.direction)},t}(BABYLON.GUI.ScrollBar);e.UnityScrollBar=n;var i=function(e){function t(t){var n=e.call(this,t||"dropdownMenu")||this;n._button=null,n._popup=null,n._options=[],n._selectedIndex=0,n.width="150px",n.height="30px",n.thickness=1,n.cornerRadius=3,n.color="#333333",n.background="transparent",console.warn("DropdownMenu is a custom control and may not be fully supported in all environments."),n._button=BABYLON.GUI.Button.CreateSimpleButton((n.name||"")+"_btn",""),n._button.width="100%",n._button.height="100%",n._button.horizontalAlignment=BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT,n._button.verticalAlignment=BABYLON.GUI.Control.VERTICAL_ALIGNMENT_CENTER,n._button.cornerRadius=3,n._button.thickness=0,n._button.color="#000000",n._button.background="#ffffff00";var i=new BABYLON.GUI.TextBlock((n.name||"")+"_label","");i.textHorizontalAlignment=BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT,i.paddingLeft="8px",i.resizeToFit=!1,i.text="",i.color="#000000",i.fontSize="14px",i.textWrapping=!0,n._button.addControl(i);var r=new BABYLON.GUI.TextBlock((n.name||"")+"_arrow","▼");r.width="24px",r.textHorizontalAlignment=BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER,r.horizontalAlignment=BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT,r.paddingRight="6px",r.color="#222222",n._button.addControl(r),n._popup=new BABYLON.GUI.Container((n.name||"")+"_popup"),n._popup.width="150px",n._popup.isVisible=!1,n._popup.background="#ffffff",n._popup.thickness=1,n._popup.cornerRadius=3,n._popup.zIndex=1e3,n._popup.verticalAlignment=BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;var o=new BABYLON.GUI.StackPanel((n.name||"")+"_stack");return o.isVertical=!0,n._popup.addControl(o),n._button.onPointerUpObservable.add(function(){n._popup&&(n._popup.isVisible=!n._popup.isVisible)}),n.addControl(n._button),n.addControl(n._popup),n}return r(t,e),Object.defineProperty(t.prototype,"selectedIndex",{get:function(){return this._selectedIndex},set:function(e){this._selectedIndex=e,this._updateSelectedText()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"options",{set:function(e){this._options=e||[],this._rebuildOptions()},enumerable:!1,configurable:!0}),t.prototype._updateSelectedText=function(){if(this._button){var e=this._button.getChildByName((this.name||"")+"_label");if(e){var t=this._options[this._selectedIndex];e.text=t?t.text:""}}},t.prototype._rebuildOptions=function(){var e=this;if(this._popup){this._popup.dispose(),this._popup=new BABYLON.GUI.Container((this.name||"")+"_popup"),this._popup.width="150px",this._popup.isVisible=!1,this._popup.background="#ffffff",this._popup.thickness=1,this._popup.cornerRadius=3,this._popup.zIndex=1e3,this._popup.verticalAlignment=BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;var t=new BABYLON.GUI.StackPanel((this.name||"")+"_stack");t.isVertical=!0,this._popup.addControl(t);for(var n=function(n){var r=i._options[n],o=BABYLON.GUI.Button.CreateSimpleButton((i.name||"")+"_opt_"+n,r.text||"");o.width="100%",o.height="28px",o.thickness=0,o.cornerRadius=0,o.color="#000000",o.horizontalAlignment=BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT,o.onPointerUpObservable.add(function(){e.selectedIndex=n,e._popup&&(e._popup.isVisible=!1),e.onSelectionChanged&&e.onSelectionChanged(n)}),t.addControl(o)},i=this,r=0;r<this._options.length;r++)n(r);this.addControl(this._popup),this._updateSelectedText()}},t.prototype.serialize=function(){var e={};try{var t=BABYLON.GUI.Container.prototype.serialize;"function"==typeof t&&(e=t.call(this)||{})}catch(t){e={}}return(e=e||{}).className="UnityDropdownMenu",e.options=this._options.map(function(e){return{text:e.text,imageSource:e.imageSource}}),e.selectedIndex=this._selectedIndex,e},t.Parse=function(e,n,i){var r=new t(e.name||"dropdownMenu");try{Array.isArray(e.options)&&(r.options=e.options.map(function(e){return{text:e.text||"",imageSource:e.imageSource}})),"number"==typeof e.selectedIndex&&(r.selectedIndex=e.selectedIndex)}catch(e){console.warn(e)}return r},t}(BABYLON.GUI.Container);e.UnityDropdownMenu=i,e.SceneManager.RegisterClass("BABYLON.GUI.UnitySlider",t),e.SceneManager.RegisterClass("BABYLON.GUI.UnityScrollBar",n),e.SceneManager.RegisterClass("BABYLON.GUI.UnityDropdownMenu",i)}(i||(i={})),function(e){var t=function(t){function n(e,n,i,r){return void 0===i&&(i={}),void 0===r&&(r="TOOLKIT.UserInterface"),t.call(this,e,n,i,r)||this}return r(n,t),n.prototype.start=function(){return a(this,void 0,void 0,function(){var t,n,i,r,o;return s(this,function(a){switch(a.label){case 0:return null==(t=this.getProperty("gui"))?[3,2]:(n=e.SceneManager.GetRootUrl(this.scene)||"",i=!1,r=!0,o=this.extractRequiredFonts(t),[4,this.loadRequiredFonts(o,n)]);case 1:if(a.sent(),this.parseNodeObject(t.root||t.controls,n),e.UserInterface.LoadForegroundInterfaceData(this.scene,t,BABYLON.Texture.BILINEAR_SAMPLINGMODE,r,null,i),e.UserInterface.OnInterfaceLoaded&&e.UserInterface.OnInterfaceLoaded.hasObservers())try{e.UserInterface.OnInterfaceLoaded.notifyObservers(this.transform.name)}catch(e){console.warn(e instanceof Error?e.message:String(e))}a.label=2;case 2:return[2]}})})},n.prototype.parseNodeObject=function(e,t){var i=this;if(null!=e&&(this.processNodeSources(e,t),null!=e.children&&Array.isArray(e.children)&&e.children.forEach(function(e){i.parseNodeObject(e,t)}),n.OnParseNodeObject&&n.OnParseNodeObject.hasObservers()))try{n.OnParseNodeObject.notifyObservers(e)}catch(e){console.warn(e instanceof Error?e.message:String(e))}},n.prototype.processNodeSources=function(e,t){if(null!=e&&"object"==typeof e){if(e.source&&"string"==typeof e.source&&e.source.startsWith("assets/")){var n=t&&!t.endsWith("/")?t+"/":t;e.source,e.source=n+e.source}for(var i in e)e.hasOwnProperty(i)&&"object"==typeof e[i]&&null!==e[i]&&"children"!==i&&this.processNodeSources(e[i],t)}},n.prototype.extractRequiredFonts=function(e){var t=new Set,n=function(e){e.fontFamily&&"Arial"!==e.fontFamily&&"sans-serif"!==e.fontFamily&&t.add(e.fontFamily),e.children&&Array.isArray(e.children)&&e.children.forEach(n)};return e.root&&n(e.root),Array.from(t)},n.prototype.loadRequiredFonts=function(e,t){return a(this,void 0,void 0,function(){var n,i,r=this;return s(this,function(o){switch(o.label){case 0:return e&&0!==e.length?[4,this.loadFontManifest(t)]:[2];case 1:return n=o.sent(),i=e.map(function(e){return r.loadSingleFont(e,n,t)}),[4,Promise.allSettled(i)];case 2:return o.sent().forEach(function(t,n){"fulfilled"===t.status||console.warn("✗ Font failed: ".concat(e[n]),t.reason)}),[4,document.fonts.ready];case 3:return o.sent(),[2]}})})},n.prototype.loadFontManifest=function(e){return a(this,void 0,void 0,function(){var t;return s(this,function(n){switch(n.label){case 0:return n.trys.push([0,4,,5]),[4,fetch(e+"font-manifest.json")];case 1:return(t=n.sent()).ok?[4,t.json()]:[3,3];case 2:return[2,n.sent()];case 3:return[3,5];case 4:return n.sent(),console.warn("No Font Manifest Found, Using Web Fonts Fallback"),[3,5];case 5:return[2,[]]}})})},n.prototype.loadSingleFont=function(e,t,n){return a(this,void 0,void 0,function(){var i;return s(this,function(r){switch(r.label){case 0:return(i=t.find(function(t){return t.family===e}))?[4,this.loadUnityFont(i,n)]:[3,2];case 1:case 3:return r.sent(),[2];case 2:return this.isGoogleFont(e)?[4,this.loadGoogleFont(e)]:[3,4];case 4:return this.isSystemFontAvailable(e)||console.warn("Font Not Available: ".concat(e)),[2]}})})},n.prototype.loadUnityFont=function(e,t){return a(this,void 0,void 0,function(){var n,i,r;return s(this,function(o){switch(o.label){case 0:n=t+e.path,o.label=1;case 1:return o.trys.push([1,3,,4]),[4,(i=new FontFace(e.family,"url('".concat(n,"') format('truetype')"),{style:e.style||"normal",weight:e.weight||"normal",display:"swap"})).load()];case 2:return o.sent(),document.fonts.add(i),[3,4];case 3:return r=o.sent(),console.warn("Failed To Load Unity Font: ".concat(e.family),r),[3,4];case 4:return[2]}})})},n.prototype.loadGoogleFont=function(e){return a(this,void 0,void 0,function(){return s(this,function(t){return[2,new Promise(function(t,n){var i=document.createElement("link");i.rel="stylesheet",i.href="https://fonts.googleapis.com/css2?family=".concat(encodeURIComponent(e),":wght@400;700&display=swap"),i.onload=function(){t()},i.onerror=function(){return n(new Error("Failed To Load Google Font: ".concat(e)))},document.head.appendChild(i)})]})})},n.prototype.isGoogleFont=function(e){return["Roboto","Open Sans","Lato","Montserrat","Source Sans Pro","Oswald","Raleway","Poppins","Merriweather","Nunito","Ubuntu","Playfair Display","Work Sans","Fira Sans","Noto Sans","PT Sans","Crimson Text","Inter"].includes(e)},n.prototype.isSystemFontAvailable=function(e){var t=document.createElement("canvas").getContext("2d"),n="mmmmmmmmmmlli";t.font="72px monospace";var i=t.measureText(n).width;return t.font='72px "'.concat(e,'", monospace'),t.measureText(n).width!==i},n.CreateInternalUserInterface=function(e,t,n,i){return 1==t?(e._foregroundTexture=BABYLON.GUI.AdvancedDynamicTexture.CreateFullscreenUI("Default-Screen-UI",!0,e,n,i),e._foregroundTexture):(e._backgroundTexture=BABYLON.GUI.AdvancedDynamicTexture.CreateFullscreenUI("Background-Screen-UI",!1,e,n,i),e._backgroundTexture)},n.LoadForegroundInterfaceData=function(t,n,i,r,o,a){if(null==t._foregroundTexture&&(t._foregroundTexture=e.UserInterface.CreateInternalUserInterface(t,!0,i,a)),null!=n){var s=t._foregroundTexture&&null!=t._foregroundTexture._textureInitialized&&!0===t._foregroundTexture._textureInitialized;e.UserInterface.ParseUserInterfaceObject(t,t._foregroundTexture,n,r,o,s),t._foregroundTexture._textureInitialized=!0}t.getEngine().resize(!0)},n.LoadBackgroundInterfaceData=function(t,n,i,r,o,a){if(null==t._backgroundTexture&&(t._backgroundTexture=e.UserInterface.CreateInternalUserInterface(t,!1,i,a)),null!=n){var s=t._backgroundTexture&&null!=t._backgroundTexture._textureInitialized&&!0===t._backgroundTexture._textureInitialized;e.UserInterface.ParseUserInterfaceObject(t,t._backgroundTexture,n,r,o,s),t._backgroundTexture._textureInitialized=!0}t.getEngine().resize(!0)},n.ParseUserInterfaceObject=function(t,n,i,r,o,a){if(i&&n){e.UserInterface.FixUserInterfacePrototypes();var s=t.getEngine().getHardwareScalingLevel()||1,l=Number.isFinite(+i.canvasScalerMode)?+i.canvasScalerMode:1,u=Number.isFinite(+i.renderScaleFactor)&&+i.renderScaleFactor>0?+i.renderScaleFactor:1,c=Number.isFinite(+i.fallbackScreenDpi)&&+i.fallbackScreenDpi>0?+i.fallbackScreenDpi:72,d=Number.isFinite(+i.defaultSpriteDpi)&&+i.defaultSpriteDpi>0?+i.defaultSpriteDpi:72,h=Number.isFinite(+i.referencePixelsPerUnit)&&+i.referencePixelsPerUnit>0?+i.referencePixelsPerUnit:100,p=Number.isFinite(+i.pixelScaleFactor)&&+i.pixelScaleFactor>0?+i.pixelScaleFactor:1,m=e.UserInterface.PHYSICAL_SIZE_POINT_FACTOR,f=Number(i.width),g=Number(i.height),v=Number.isFinite(f)&&f>0&&Number.isFinite(g)&&g>0,y=v?f:1920,_=v?g:1080,S=function(e){e.width="100%",e.height="100%",e.left="0px",e.top="0px",e.horizontalAlignment=BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT,e.verticalAlignment=BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP},A=function(e){return JSON.parse(JSON.stringify(e))},b=function(e){if("number"==typeof e)return Number.isFinite(e);if("string"==typeof e){var t=e.trim().toLowerCase();return!t.endsWith("%")&&(t.endsWith("px")?Number.isFinite(parseFloat(t)):/^-?\d+(\.\d+)?$/.test(t))}return!1},M=function(e,t){if(e&&"object"==typeof e){var n=new Set(["left","top","width","height","minWidth","minHeight","maxWidth","maxHeight","marginLeft","marginRight","marginTop","marginBottom","paddingLeft","paddingRight","paddingTop","paddingBottom","fontSize","thickness","cornerRadius","shadowOffsetX","shadowOffsetY","shadowBlur","linkOffsetX","linkOffsetY"]),i=new Set(["cornerRadiusX","cornerRadiusY","cornerRadiusZ","cornerRadiusW"]),r=function(e){if(null==e)return e;if("number"==typeof e)return Math.round(e*t);if("string"==typeof e){var n=e.trim();if(n.endsWith("%"))return e;if(n.toLowerCase().endsWith("px")){var i=parseFloat(n);return Number.isFinite(i)?"".concat(Math.round(i*t),"px"):e}return/^-?\d+(\.\d+)?$/.test(n)?(i=parseFloat(n),Number.isFinite(i)?"".concat(Math.round(i*t),"px"):e):e}if("object"==typeof e){for(var o=0,a=["left","top","right","bottom","x","y","w","h","value"];o<a.length;o++){var s=a[o];s in e&&b(e[s])&&(e[s]=r(e[s]))}return e}return e};for(var o in e)(n.has(o)||i.has(o))&&(e[o]=r(e[o]));if(e.style&&"object"==typeof e.style)for(var o in e.style)(n.has(o)||i.has(o))&&(e.style[o]=r(e.style[o]));var a=e.children;if(Array.isArray(a))for(var s=0,l=a;s<l.length;s++){var u=l[s];M(u,t)}}};if(!0!==a){if(1===l){var B=Number(i.idealWidth),C=Number(i.idealHeight),T=Number.isFinite(B)&&B>0?B:NaN,x=Number.isFinite(C)&&C>0?C:NaN;!Number.isFinite(T)&&Number.isFinite(x)&&v?T=Math.round(x*y/_):!Number.isFinite(x)&&Number.isFinite(T)&&v&&(x=Math.round(T*_/y)),n.renderScale=1/s*u,Number.isFinite(T)&&Number.isFinite(x)?(n.idealWidth=T,n.idealHeight=x,n.useSmallestIdeal=!!i.useSmallestIdeal,n.renderAtIdealSize=!0):v?(n.idealWidth=y,n.idealHeight=_,n.useSmallestIdeal=!0,n.renderAtIdealSize=!0):n.renderAtIdealSize=!1;var I=BABYLON.GUI.Control.Parse(i.root,n,o);return S(I),n._rootContainer=I,e.UserInterface.ProcessTextSpacingProperties(I,i.root),e.UserInterface.ProcessHdrColors(I,i.root),e.UserInterface.ApplyHdrVisualEnhancements(I),e.UserInterface.ProcessPreserveAspectRatio(I,i.root),e.UserInterface.ProcessControlEvents(t,I,i.root),n.__canvasScalerMode=l,n.__cpsScale=1,n.__defaultSpriteDpi=d,n.__fallbackScreenDpi=c,n.__referencePixelsPerUnit=h,r&&!n.renderAtIdealSize&&n.scaleTo(y,_),void n.markAsDirty()}n.renderScale=1,n.renderAtIdealSize=!1,n.idealWidth=void 0,n.idealHeight=void 0,n.useSmallestIdeal=void 0;var O=0===l?p:m,L=A(i.root);Number.isFinite(O)&&1!==O&&M(L,O);var w=BABYLON.GUI.Control.Parse(L,n,o);S(w),n._rootContainer=w,e.UserInterface.ProcessTextSpacingProperties(w,i.root),e.UserInterface.ProcessHdrColors(w,i.root),e.UserInterface.ApplyHdrVisualEnhancements(w),e.UserInterface.ProcessPreserveAspectRatio(w,i.root),e.UserInterface.ProcessControlEvents(t,w,i.root),n.__canvasScalerMode=l,n.__cpsScale=0===l?p:1,n.__defaultSpriteDpi=d,n.__fallbackScreenDpi=c,n.__referencePixelsPerUnit=h,n.markAsDirty()}else{for(var N=null!=i.root&&null!=i.root.children&&i.root.children.length>0?i.root.children[0]:i.root,P=0===l?p:2===l?m:1,R=0,E=Array.isArray(null==N?void 0:N.children)&&(null==N?void 0:N.typeName)?N.children:[N];R<E.length;R++){var k=E[R],D=k;1===P||0!==l&&2!==l||(D=A(k),M(D,P));var F=BABYLON.GUI.Control.Parse(D,n,o);F&&(n.addControl(F),e.UserInterface.ProcessTextSpacingProperties(F,k),e.UserInterface.ProcessHdrColors(F,k),e.UserInterface.ApplyHdrVisualEnhancements(F),e.UserInterface.ProcessPreserveAspectRatio(F,k),e.UserInterface.ProcessControlEvents(t,F,k))}n.markAsDirty()}}},n.FixUserInterfacePrototypes=function(){var t=globalThis||window,n=t&&t.BABYLON,i=n&&n.GUI,r=i&&i.Image,o=i&&i.Control;o&&(o.__prototypeFunctionsPatched||(o.__prototypeFunctionsPatched=!0,o.prototype.getScene=function(){var e;return null===(e=this._host)||void 0===e?void 0:e.getScene()},r.prototype._renderNinePatch=function(t,n,i,r,o){var a,s,l,u,c,d,h,p,m,f,g,v,y,_=null!==(s=null===(a=this.host)||void 0===a?void 0:a.__canvasScalerMode)&&void 0!==s?s:1,S=null!==(u=null===(l=this.host)||void 0===l?void 0:l.__cpsScale)&&void 0!==u?u:1,A=null!==(d=null===(c=this.host)||void 0===c?void 0:c.__referencePixelsPerUnit)&&void 0!==d?d:100,b=null!==(p=null===(h=this.host)||void 0===h?void 0:h.__defaultSpriteDpi)&&void 0!==p?p:96,M=(null===(m=this.host)||void 0===m?void 0:m.__fallbackScreenDpi,null!==(g=null===(f=this.metadata)||void 0===f?void 0:f.spritePixelsPerUnit)&&void 0!==g?g:A),B=this.host.idealWidth?this._currentMeasure.width/this.host.idealWidth:this.host.idealHeight?this._currentMeasure.height/this.host.idealHeight:1;0===_?(B*=S,B*=A/M):1===_?(B=null!==(y=null===(v=this.host)||void 0===v?void 0:v.idealRatio)&&void 0!==y?y:1,B*=A/M):2===_&&(B*=e.UserInterface.PHYSICAL_SIZE_SLICE_FACTOR,B*=A/M,B*=1/(b/96*1));var C=this._sliceLeft,T=this._sliceTop,x=r-this._sliceRight,I=o-this._sliceBottom,O=this._sliceRight-this._sliceLeft,L=this._sliceBottom-this._sliceTop,w=Math.round(C*B),N=Math.round(T*B),P=Math.round(I*B),R=Math.round(x*B),E=Math.max(0,Math.round(this._currentMeasure.width)-R-w+2),k=Math.max(0,Math.round(this._currentMeasure.height)-P-N+2),D=Math.round(this._currentMeasure.left)+w-1,F=Math.round(this._currentMeasure.top)+N-1,U=Math.round(this._currentMeasure.left+this._currentMeasure.width)-R,Y=Math.round(this._currentMeasure.top+this._currentMeasure.height)-P;this._drawImage(t,n,i,C,T,this._currentMeasure.left,this._currentMeasure.top,w,N),this._drawImage(t,n+this._sliceLeft,i,O,T,D+1,this._currentMeasure.top,E-2,N),this._drawImage(t,n+this._sliceRight,i,x,T,U,this._currentMeasure.top,R,N),this._drawImage(t,n,i+this._sliceTop,C,L,this._currentMeasure.left,F+1,w,k-2),this._drawImage(t,n+this._sliceLeft,i+this._sliceTop,O,L,D+1,F+1,E-2,k-2),this._drawImage(t,n+this._sliceRight,i+this._sliceTop,x,L,U,F+1,R,k-2),this._drawImage(t,n,i+this._sliceBottom,C,I,this._currentMeasure.left,Y,w,P),this._drawImage(t,n+this._sliceLeft,i+this._sliceBottom,O,I,D+1,Y,E-2,P),this._drawImage(t,n+this._sliceRight,i+this._sliceBottom,x,I,U,Y,R,P)}))},n.ProcessControlEvents=function(e,t,n){var i=this,r=function(t,n){n&&t&&(i.processUnityUIEvents(e,t,n),i.processUIToolkitEvents(e,t,n),t instanceof BABYLON.GUI.Container&&t.children.forEach(function(e,t){var i=n&&n.children?n.children[t]:null;r(e,i)}))};r(t,n)},n.processUnityUIEvents=function(e,t,n){n.onClick&&this.isUnityUIEvent(n.onClick)&&this.wireUnityUIButtonEvents(e,t,n.onClick),n.onValueChanged&&this.isUnityUIEvent(n.onValueChanged)&&"Toggle"===n.className&&this.wireUnityUIToggleEvents(e,t,n.onValueChanged),n.onValueChanged&&this.isUnityUIEvent(n.onValueChanged)&&"Slider"===n.className&&this.wireUnityUISliderEvents(e,t,n.onValueChanged),n.onValueChanged&&this.isUnityUIEvent(n.onValueChanged)&&"Dropdown"===n.className&&this.wireUnityUIDropdownEvents(e,t,n.onValueChanged),n.onValueChanged&&this.isUnityUIEvent(n.onValueChanged)&&"ScrollRect"===n.className&&this.wireUnityUIScrollRectEvents(e,t,n.onValueChanged),"InputField"===n.className&&this.wireUnityUIInputFieldEvents(e,t,n)},n.processUIToolkitEvents=function(e,t,n){n.isUIToolkit&&(n.events&&"Button"===n.className&&this.wireUIToolkitButtonEvents(e,t,n),n.events&&"Toggle"===n.className&&this.wireUIToolkitToggleEvents(e,t,n),!n.events||"Slider"!==n.className&&"SliderInt"!==n.className||this.wireUIToolkitSliderEvents(e,t,n),n.events&&"DropdownField"===n.className&&this.wireUIToolkitDropdownEvents(e,t,n))},n.isUnityUIEvent=function(e){return e&&e.events&&Array.isArray(e.events)&&e.events.some(function(e){return e.targetName||e.targetType||e.methodName})},n.wireUnityUIButtonEvents=function(e,t,n){var i=this;n.events&&Array.isArray(n.events)&&n.events.forEach(function(n){var r=i.findTargetObject(e,n.targetName,n.targetPath,n.targetInstanceId,n.targetType);null!=r&&(r.args=i.extractParameters(n.mode,n.parameters),t.onPointerClickObservable.add(function(){i.executeUnityUIEvent(r,n)}))})},n.wireUnityUIToggleEvents=function(e,t,n){n.events&&Array.isArray(n.events)},n.wireUnityUISliderEvents=function(e,t,n){n.events&&Array.isArray(n.events)},n.wireUnityUIDropdownEvents=function(e,t,n){n.events&&Array.isArray(n.events)},n.wireUnityUIScrollRectEvents=function(e,t,n){n.events&&Array.isArray(n.events)},n.wireUnityUIInputFieldEvents=function(e,t,n){BABYLON.GUI.InputText},n.wireUIToolkitButtonEvents=function(e,t,n){n.events&&Array.isArray(n.events)},n.wireUIToolkitToggleEvents=function(e,t,n){n.events&&Array.isArray(n.events)},n.wireUIToolkitSliderEvents=function(e,t,n){n.events&&Array.isArray(n.events)},n.wireUIToolkitDropdownEvents=function(e,t,n){n.events&&Array.isArray(n.events)},n.executeUnityUIEvent=function(e,t){for(var n,i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];try{e.instance&&e.instance[t.methodName]&&"function"==typeof e.instance[t.methodName]?null!=e.args?(n=e.instance)[t.methodName].apply(n,e.args):e.instance[t.methodName]():console.warn("⚠️ UI Event: Target not found or method missing: ".concat(t.targetPath||t.targetName,".").concat(t.methodName))}catch(e){console.error("❌ Error Executing UI event: ".concat(t.methodName),e)}},n.executeUIToolkitEvent=function(e,t){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i]},n.findTargetObject=function(e,t,n,i,r){var o=null;if(null!=e&&null!=t){var a=e.getNodeByName(t);if(null!=a&&null!=a.metadata&&null!=a.metadata.toolkit&&null!=a.metadata.toolkit.components&&a.metadata.toolkit.components.length>0)for(var s=a.metadata.toolkit.components.length,l=0;l<s;l++){var u=a.metadata.toolkit.components[l],c=u.klass,d=c.lastIndexOf(".");if(-1!==d&&(c=c.substring(d+1)),c===r&&u.instanceID===i){o=u;break}}}return o},n.extractParameters=function(e,t){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];var r=[];return n&&n.length>0&&r.push.apply(r,n),t?(6===e&&null!=t.boolArgument&&r.push(t.boolArgument),5===e&&null!=t.stringArgument&&r.push(t.stringArgument),4===e&&null!=t.floatArgument&&r.push(t.floatArgument),3===e&&null!=t.intArgument&&r.push(t.intArgument),2===e&&t.objectArgument,r):r},n.resolveObjectReference=function(e){return BABYLON.EngineStore.LastCreatedScene,null},n.executeUIToolkitCallback=function(e,t){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];var r=window.uiToolkitCallbackRegistry;if(r&&r[e]&&r[e][t]){var o=r[e][t];"function"==typeof o&&o.apply(void 0,n)}else console.warn("⚠️ UI Toolkit callback not registered: ".concat(e,".").concat(t))},n.ProcessHdrColors=function(e,t){var n=this,i=function(e,t){if(e instanceof BABYLON.GUI.TextBlock&&t&&"TextBlock"===t.className){var r=e;if(t.colorIsHDR&&t.colorHdrMultiplier&&t.colorHdrMultiplier>1){var o=n.emulateUnityHDR(t.color,t.colorHdrMultiplier,t.hdrToneMapping);r.color=o.color,r._hdrMultiplier=t.colorHdrMultiplier,r._originalColor=t.color,n.applyHdrEffects(r,o,t.hdrToneMapping)}if(t.outlineColorIsHDR&&t.outlineColorHdrMultiplier&&t.outlineColorHdrMultiplier>1){var a=n.emulateUnityHDR(t.outlineColor,t.outlineColorHdrMultiplier,t.hdrToneMapping);r._hdrOutlineColor=a.color,r._hdrOutlineMultiplier=t.outlineColorHdrMultiplier}if(t.outlineBlur&&t.outlineBlur>0&&(r.outlineBlur=t.outlineBlur),t.faceSoftness&&t.faceSoftness>0&&(r.faceSoftness=t.faceSoftness),t.faceDilate&&0!==t.faceDilate&&(r.faceDilate=t.faceDilate),t.shadowColorIsHDR&&t.shadowColorHdrMultiplier&&t.shadowColorHdrMultiplier>1){var s=n.emulateUnityHDR(t.shadowColor,t.shadowColorHdrMultiplier,t.hdrToneMapping);r._hdrShadowColor=s.color,r._hdrShadowMultiplier=t.shadowColorHdrMultiplier}if(t.glowEnabled&&t.glowColor){var l=t.glowColorIsHDR&&t.glowColorHdrMultiplier>1?n.emulateUnityHDR(t.glowColor,t.glowColorHdrMultiplier,t.hdrToneMapping):{color:t.glowColor,cssFilter:""};r._glowEnabled=!0,r._glowColor=l.color,r._glowOffset=t.glowOffset||0,r._glowInner=t.glowInner||0,r._glowOuter=t.glowOuter||0,r._glowPower=t.glowPower||1,r._hdrGlowMultiplier=t.glowColorHdrMultiplier||1,n.applyGlowEffects(r,l,t)}if(t.lightingEnabled){var u=t.lightColorIsHDR&&t.lightColorHdrMultiplier>1?n.emulateUnityHDR(t.lightColor,t.lightColorHdrMultiplier,t.hdrToneMapping):{color:t.lightColor||"#ffffff",cssFilter:""},c=t.specularColorIsHDR&&t.specularColorHdrMultiplier>1?n.emulateUnityHDR(t.specularColor,t.specularColorHdrMultiplier,t.hdrToneMapping):{color:t.specularColor||"#ffffff",cssFilter:""},d=t.envMapColorIsHDR&&t.envMapColorHdrMultiplier>1?n.emulateUnityHDR(t.envMapColor,t.envMapColorHdrMultiplier,t.hdrToneMapping):{color:t.envMapColor||"#88aadd",cssFilter:""};r._lightingEnabled=!0,r._lightColor=u.color,r._bevelAmount=t.bevelAmount||0,r._bevelOffset=t.bevelOffset||0,r._bevelWidth=t.bevelWidth||0,r._bevelRoundness=t.bevelRoundness||0,r._bevelClamp=t.bevelClamp||1,r._lightAngle=t.lightAngle||0,r._specularPower=t.specularPower||1,r._reflectance=t.reflectance||.5,r._hdrLightMultiplier=t.lightColorHdrMultiplier||1,r._specularColor=c.color,r._shininess=t.shininess||1,r._envMapSampling=t.envMapSampling||0,r._envMapColor=d.color,r._bumpIntensity=t.bumpIntensity||0,r._hdrSpecularMultiplier=t.specularColorHdrMultiplier||1,r._hdrEnvMapMultiplier=t.envMapColorHdrMultiplier||1,n.applyAdvancedLightingEffects(r,u,c,d,t)}}e instanceof BABYLON.GUI.Container&&e.children.forEach(function(e,n){var r=t&&t.children?t.children[n]:null;i(e,r)})};i(e,t)},n.emulateUnityHDR=function(e,t,n){var i=this.parseRgbaColor(e);if(!i)return{color:e,cssFilter:""};var r=(null==n?void 0:n.exposure)||1,o=(null==n?void 0:n.gamma)||2.2,a=(null==n?void 0:n.saturation)||.9,s=(null==n?void 0:n.brightness)||1.1;return this.applyUnityHDRToneMapping(i,t,{exposure:r,gamma:o,saturation:a,brightness:s})},n.applyUnityHDRToneMapping=function(e,t,n){var i=Math.min(t*n.exposure,3),r=e.r/255,o=e.g/255,a=e.b/255,s=.299*(r=1-Math.exp(-r*i))+.587*(o=1-Math.exp(-o*i))+.114*(a=1-Math.exp(-a*i)),l=Math.min(.2*(t-1),.5);r=r*(1-l)+s*l,o=o*(1-l)+s*l,a=a*(1-l)+s*l;var u=1/n.gamma;r=Math.pow(r,u),o=Math.pow(o,u),a=Math.pow(a,u);var c=1+.3*(t-1);r=Math.min(r*c,1),o=Math.min(o*c,1),a=Math.min(a*c,1);var d=Math.round(255*r),h=Math.round(255*o),p=Math.round(255*a),m="rgba(".concat(d,",").concat(h,",").concat(p,",").concat(e.a,")"),f=Math.min(1+.15*(t-1),1.5),g=Math.max(n.saturation,.7);return{color:m,cssFilter:"brightness(".concat(f,") saturate(").concat(g,")")}},n.applyHdrEffects=function(e,t,n){e.color=t.color,e._hdrEnabled=!0,e._hdrCssFilter=t.cssFilter,e._hdrToneMapping=n},n.applyGlowEffects=function(e,t,n){e._glowEnabled=!0,e._glowColor=t.color,e._glowOffset=n.glowOffset||0,e._glowInner=n.glowInner||0,e._glowOuter=n.glowOuter||0,e._glowPower=n.glowPower||1;var i=n.glowInner||0,r=n.glowOuter||0,o=n.glowOffset||0,a=n.glowPower||1,s=Math.max(i,r),l=Math.max(2,8*s*a),u=[];if(i>0){var c=.3*l;u.push("0 0 ".concat(c,"px ").concat(t.color))}if(r>0){var d=l;if(u.push("".concat(o,"px ").concat(o,"px ").concat(d,"px ").concat(t.color)),r>.5){var h=1.5*l;u.push("0 0 ".concat(h,"px ").concat(t.color))}}u.length>0&&(e._glowCssFilter="drop-shadow(".concat(u.join(") drop-shadow("),")"))},n.applyLightingEffects=function(e,t,n){e._lightingEnabled=!0,e._lightColor=t.color,e._bevelAmount=n.bevelAmount||0,e._bevelOffset=n.bevelOffset||0,e._bevelWidth=n.bevelWidth||0,e._bevelRoundness=n.bevelRoundness||0,e._bevelClamp=n.bevelClamp||1,e._lightAngle=n.lightAngle||0,e._specularPower=n.specularPower||1,e._reflectance=n.reflectance||.5;var i=n.bevelAmount||0,r=n.bevelWidth||0,o=(n.lightAngle||0)*Math.PI/180;if(i>0&&r>0){var a=Math.cos(o)*r,s=Math.sin(o)*r,l=-a,u=-s,c=this.parseRgbaColor(t.color),d=c?"rgba(".concat(Math.min(255,c.r+50),", ").concat(Math.min(255,c.g+50),", ").concat(Math.min(255,c.b+50),", ").concat(.6*c.a,")"):"rgba(255, 255, 255, 0.6)",h=c?"rgba(".concat(Math.max(0,c.r-100),", ").concat(Math.max(0,c.g-100),", ").concat(Math.max(0,c.b-100),", ").concat(.4*c.a,")"):"rgba(0, 0, 0, 0.4)",p=[];if(p.push("".concat(a,"px ").concat(s,"px 0px ").concat(d)),p.push("".concat(l,"px ").concat(u,"px 0px ").concat(h)),i>.5){var m=c?"rgba(".concat(c.r,", ").concat(c.g,", ").concat(c.b,", ").concat(.3*c.a,")"):"rgba(255, 255, 255, 0.3)";p.push("".concat(.5*a,"px ").concat(.5*s,"px 1px ").concat(m))}e._lightingCssFilter="drop-shadow(".concat(p.join(") drop-shadow("),")")}},n.applyAdvancedLightingEffects=function(e,t,n,i,r){e._lightingEnabled=!0,e._lightColor=t.color,e._specularColor=n.color,e._envMapColor=i.color;var o=r.bevelAmount||0,a=r.bevelWidth||0,s=(r.lightAngle||0)*Math.PI/180,l=r.shininess||1,u=r.envMapSampling||0,c=r.bumpIntensity||0,d=r.specularPower||1,h=[];if(o>0&&a>0){var p=Math.cos(s)*a,m=Math.sin(s)*a,f=-p,g=-m,v=this.parseRgbaColor(t.color),y=v?"rgba(".concat(Math.min(255,v.r+50),", ").concat(Math.min(255,v.g+50),", ").concat(Math.min(255,v.b+50),", ").concat(.6*v.a,")"):"rgba(255, 255, 255, 0.6)",_=v?"rgba(".concat(Math.max(0,v.r-100),", ").concat(Math.max(0,v.g-100),", ").concat(Math.max(0,v.b-100),", ").concat(.4*v.a,")"):"rgba(0, 0, 0, 0.4)";h.push("".concat(p,"px ").concat(m,"px 0px ").concat(y)),h.push("".concat(f,"px ").concat(g,"px 0px ").concat(_))}if(l>1&&"#ffffff"!==n.color){var S=this.parseRgbaColor(n.color);if(S){var A=Math.min(1,l/10),b="rgba(".concat(S.r,", ").concat(S.g,", ").concat(S.b,", ").concat(.8*A,")"),M=Math.cos(s+Math.PI)*(.3*a),B=Math.sin(s+Math.PI)*(.3*a);if(h.push("".concat(M,"px ").concat(B,"px ").concat(Math.max(1,l),"px ").concat(b)),d>2){var C="rgba(".concat(S.r,", ").concat(S.g,", ").concat(S.b,", ").concat(.4*A,")");h.push("".concat(1.5*M,"px ").concat(1.5*B,"px ").concat(2*l,"px ").concat(C))}}}if(u>0&&"#88aadd"!==i.color){var T=this.parseRgbaColor(i.color);if(T){var x=Math.min(.6,u),I="rgba(".concat(T.r,", ").concat(T.g,", ").concat(T.b,", ").concat(x,")"),O=Math.max(2,5*u);h.push("0 0 ".concat(O,"px ").concat(I));var L=2*Math.cos(s+Math.PI/2),w=2*Math.sin(s+Math.PI/2);h.push("".concat(L,"px ").concat(w,"px ").concat(.7*O,"px ").concat(I))}}if(c>0){var N="rgba(0, 0, 0, ".concat(Math.min(.3,.5*c),")"),P="rgba(255, 255, 255, ".concat(Math.min(.2,.3*c),")"),R=.5*Math.cos(s),E=.5*Math.sin(s);h.push("".concat(R,"px ").concat(E,"px 0px ").concat(P)),h.push("".concat(-R,"px ").concat(-E,"px 0px ").concat(N))}h.length>0&&(e._lightingCssFilter="drop-shadow(".concat(h.join(") drop-shadow("),")"))},n.parseRgbaColor=function(e){var t=e.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/);return t?{r:parseInt(t[1]),g:parseInt(t[2]),b:parseInt(t[3]),a:t[4]?parseFloat(t[4]):1}:null},n.ApplyHdrVisualEnhancements=function(e){var t=function(e){if(e instanceof BABYLON.GUI.TextBlock){var n=e;if(n._hdrEnabled){n._hdrCssFilter;var i=n._hdrMultiplier;i&&i>2&&(n._needsGlowEffect=!0)}}e instanceof BABYLON.GUI.Container&&e.children.forEach(function(e){t(e)})};t(e)},n.ProcessPreserveAspectRatio=function(e,t){},n.applyPreserveAspectRatio=function(e,t){},n.ProcessTextSpacingProperties=function(t,n){var i=this,r=function(t,n){if(t instanceof BABYLON.GUI.TextBlock&&n&&"TextBlock"===n.className){var o=t,a=o.fontSize||"18px",s=parseFloat(a.toString().replace(/px$/,""));if(n.characterSpacing&&0!==n.characterSpacing){var l=parseFloat(n.characterSpacing);if(!isNaN(l)&&0!==l){var u=l*(s*e.UserInterface.CHARACTER_WORD_SPACE_FACTOR);o._characterSpacing=u,i.applyCharacterSpacing(o,u)}}if(n.wordSpacing&&0!==n.wordSpacing&&(l=parseFloat(n.wordSpacing),isNaN(l)||0===l||(u=l*(s*e.UserInterface.CHARACTER_WORD_SPACE_FACTOR),o._wordSpacing=u,i.applyWordSpacing(o,u))),n.paragraphSpacing&&0!==n.paragraphSpacing&&(l=parseFloat(n.paragraphSpacing),!isNaN(l)&&0!==l))if(u=l*s,o._paragraphSpacing=u,o.lineSpacing){var c=parseFloat(o.lineSpacing.toString().replace(/px$/,""));o.lineSpacing=c+u+"px"}else o.lineSpacing=u+"px"}t instanceof BABYLON.GUI.Container&&t.children.forEach(function(e,t){var i=n&&n.children?n.children[t]:null;r(e,i)})};r(t,n)},n.applyCharacterSpacing=function(e,t){var n=e.text;if(n&&t>0){var i=e._drawText;if(i&&(e._drawText=function(e,n,r,o){if(t>0){o.save();var a=this.shadowOffsetX||0,s=this.shadowOffsetY||0,l=this.shadowBlur||0,u=this._hdrShadowColor||this.shadowColor||"transparent",c=this.outlineWidth||0,d=this.outlineBlur||0,h=this._hdrOutlineColor||this.outlineColor||"transparent",p=this.faceSoftness||0,m=this.faceDilate||0;if(0!==m){var f=Math.max(0,1+2*m);f>0&&(o.lineWidth=f,o.strokeStyle=o.fillStyle)}var g=this._hdrCssFilter,v=this._glowCssFilter,y=this._lightingCssFilter,_="";if(p>0){var S=Math.min(3,2*p);_="blur(".concat(S,"px)")}var A=[];g&&A.push(g),v&&A.push(v),y&&A.push(y),_&&A.push(_),A.length>0&&void 0!==o.filter&&(o.filter=A.join(" ")),(0!==a||0!==s||l>0)&&(o.shadowOffsetX=a,o.shadowOffsetY=s,o.shadowBlur=l,o.shadowColor=u),c>0&&(o.strokeStyle=h,o.lineWidth=c);for(var b=e.split(""),M=this._currentMeasure.left,B=0,C=0;C<b.length;C++)B+=o.measureText(b[C]).width,C<b.length-1&&(B+=t);for(this.textHorizontalAlignment===BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER?M+=(this._currentMeasure.width-B)/2:this.textHorizontalAlignment===BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT&&(M+=this._currentMeasure.width-B),C=0;C<b.length;C++)c>0&&(d>0?(o.save(),o.shadowColor=h,o.shadowBlur=d,o.shadowOffsetX=0,o.shadowOffsetY=0,o.strokeStyle=h,o.lineWidth=c,o.strokeText(b[C],M,r),o.restore()):o.strokeText(b[C],M,r)),0!==m&&(o.save(),o.strokeStyle=o.fillStyle,o.lineWidth=Math.abs(2*m),o.strokeText(b[C],M,r),o.restore()),o.fillText(b[C],M,r),M+=o.measureText(b[C]).width+t;o.restore()}else i.call(this,e,n,r,o)}),!i){var r=n.split("").join(" ");e.text=r}}},n.applyWordSpacing=function(e,t){var n=e._drawText;if(n)e._drawText=function(e,i,r,o){if(t>0){o.save();var a=this.shadowOffsetX||0,s=this.shadowOffsetY||0,l=this.shadowBlur||0,u=this._hdrShadowColor||this.shadowColor||"transparent",c=this.outlineWidth||0,d=this.outlineBlur||0,h=this._hdrOutlineColor||this.outlineColor||"transparent",p=this.faceSoftness||0,m=this.faceDilate||0,f=this._hdrCssFilter,g=this._glowCssFilter,v=this._lightingCssFilter,y="";if(p>0){var _=Math.min(3,2*p);y="blur(".concat(_,"px)")}var S=[];f&&S.push(f),g&&S.push(g),v&&S.push(v),y&&S.push(y),S.length>0&&void 0!==o.filter&&(o.filter=S.join(" ")),(0!==a||0!==s||l>0)&&(o.shadowOffsetX=a,o.shadowOffsetY=s,o.shadowBlur=l,o.shadowColor=u),c>0&&(o.strokeStyle=h,o.lineWidth=c);for(var A=e.split(" "),b=this._currentMeasure.left,M=0,B=0;B<A.length;B++)M+=o.measureText(A[B]).width,B<A.length-1&&(M+=o.measureText(" ").width+t);for(this.textHorizontalAlignment===BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER?b+=(this._currentMeasure.width-M)/2:this.textHorizontalAlignment===BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT&&(b+=this._currentMeasure.width-M),B=0;B<A.length;B++)c>0&&(d>0?(o.save(),o.shadowColor=h,o.shadowBlur=d,o.shadowOffsetX=0,o.shadowOffsetY=0,o.strokeStyle=h,o.lineWidth=c,o.strokeText(A[B],b,r),o.restore()):o.strokeText(A[B],b,r)),0!==m&&(o.save(),o.strokeStyle=o.fillStyle,o.lineWidth=Math.abs(2*m),o.strokeText(A[B],b,r),o.restore()),o.fillText(A[B],b,r),b+=o.measureText(A[B]).width,B<A.length-1&&(b+=o.measureText(" ").width+t);o.restore()}else n.call(this,e,i,r,o)};else{var i=e.text.split(" ").join(" ");e.text=i}},n.IsForegroundReady=function(e){return null!=e._foregroundTexture},n.SetForegroundTexture=function(e,t){e._foregroundTexture=t},n.GetForegroundTexture=function(t,n){return void 0===n&&(n=null),null==t._foregroundTexture&&null!=n&&(t._foregroundTexture=e.UserInterface.CreateInternalUserInterface(t,!0,null==n?void 0:n.samplerMode,null==n?void 0:n.adaptiveHardwareScaling)),t._foregroundTexture},n.IsBackgroundReady=function(e){return null!=e._backgroundTexture},n.SetBackgroundTexture=function(e,t){e._backgroundTexture=t},n.GetBackgroundTexture=function(t,n){return void 0===n&&(n=null),null==t._backgroundTexture&&null!=n&&(t._backgroundTexture=e.UserInterface.CreateInternalUserInterface(t,!1,null==n?void 0:n.samplerMode,null==n?void 0:n.adaptiveHardwareScaling)),t._backgroundTexture},n.GetCanvasElement=function(e,t){var n=t||BABYLON.EngineStore.LastCreatedScene;return null!=n._foregroundTexture?n._foregroundTexture.getControlByName(e):null},n.ShowCanvasElement=function(t){return a(this,arguments,void 0,function(t,n,i){var r;return void 0===n&&(n=0),void 0===i&&(i=1),s(this,function(o){switch(o.label){case 0:return null==t?[3,3]:n>0?(r=t.alpha,t.isVisible=!0,[4,e.SceneManager.TweenFromToAsync(t,{alpha:r},{alpha:1},{duration:n,speed:i})]):[3,2];case 1:return o.sent(),t.isEnabled=!0,[3,3];case 2:t.isEnabled=!0,t.isVisible=!0,t.alpha=1,o.label=3;case 3:return[2]}})})},n.HideCanvasElement=function(t){return a(this,arguments,void 0,function(t,n,i){var r;return void 0===n&&(n=0),void 0===i&&(i=1),s(this,function(o){switch(o.label){case 0:return null==t?[3,3]:n>0?(t.isEnabled=!1,r=t.alpha,t.isEnabled=!1,[4,e.SceneManager.TweenFromToAsync(t,{alpha:r},{alpha:0},{duration:n,speed:i})]):[3,2];case 1:return o.sent(),t.isVisible=!1,[3,3];case 2:t.isEnabled=!1,t.isVisible=!1,t.alpha=0,o.label=3;case 3:return[2]}})})},n.AttachClickHandler=function(e,t){return null==e||null==t?null:e.onPointerClickObservable.add(t)},n.PHYSICAL_SIZE_SLICE_FACTOR=1.5,n.PHYSICAL_SIZE_POINT_FACTOR=1.915,n.CHARACTER_WORD_SPACE_FACTOR=.01,n.OnParseNodeObject=new BABYLON.Observable,n.OnInterfaceLoaded=new BABYLON.Observable,n}(e.ScriptComponent);e.UserInterface=t,e.SceneManager.RegisterClass("TOOLKIT.UserInterface",t)}(i||(i={})),function(e){var t=function(t){function n(e,n,i,r){void 0===i&&(i={}),void 0===r&&(r="TOOLKIT.WebVideoPlayer");var o=t.call(this,e,n,i,r)||this;return o.videoLoop=!1,o.videoMuted=!1,o.videoAlpha=!1,o.videoFaded=!1,o.videoPoster=null,o.videoInvert=!0,o.videoSample=3,o.videoVolume=1,o.videoMipmaps=!1,o.videoPlayback=1,o.videoPlayOnAwake=!0,o.videoPreloaderUrl=null,o.videoBlobUrl=null,o.videoPreload=!1,o._initializedReadyInstance=!1,o.onReadyObservable=new BABYLON.Observable,o.m_abstractMesh=null,o.m_videoTexture=null,o.m_videoMaterial=null,o.m_diffuseIntensity=1,o}return r(n,t),n.prototype.getVideoMaterial=function(){return this.m_videoMaterial},n.prototype.getVideoTexture=function(){return this.m_videoTexture},n.prototype.getVideoElement=function(){return null!=this.m_videoTexture?this.m_videoTexture.video:null},n.prototype.getVideoScreen=function(){return this.m_abstractMesh},n.prototype.getVideoBlobUrl=function(){return this.videoBlobUrl},n.prototype.awake=function(){this.awakeWebVideoPlayer()},n.prototype.destroy=function(){this.destroyWebVideoPlayer()},n.prototype.awakeWebVideoPlayer=function(){this.videoLoop=this.getProperty("looping",!1),this.videoMuted=this.getProperty("muted",!1),this.videoInvert=this.getProperty("inverty",!0),this.videoSample=this.getProperty("sampling",3),this.videoVolume=this.getProperty("volume",1),this.videoMipmaps=this.getProperty("mipmaps",!1),this.videoAlpha=this.getProperty("texturealpha",!1),this.videoFaded=this.getProperty("diffusealpha",!1),this.videoPlayback=this.getProperty("playbackspeed",1),this.videoPlayOnAwake=this.getProperty("playonawake",!0),this.videoPreload=this.getProperty("preload",this.videoPreload),this.m_diffuseIntensity=this.getProperty("intensity",1),this.m_abstractMesh=this.getAbstractMesh(),!0===this.getProperty("poster")&&null!=this.m_abstractMesh&&null!=this.m_abstractMesh.material&&(this.m_abstractMesh.material instanceof BABYLON.PBRMaterial?null!=this.m_abstractMesh.material.albedoTexture&&null!=this.m_abstractMesh.material.albedoTexture.url&&""!==this.m_abstractMesh.material.albedoTexture.url&&(this.videoPoster=this.m_abstractMesh.material.albedoTexture.url.replace("data:","")):this.m_abstractMesh.material instanceof BABYLON.StandardMaterial&&null!=this.m_abstractMesh.material.diffuseTexture&&null!=this.m_abstractMesh.material.diffuseTexture.url&&""!==this.m_abstractMesh.material.diffuseTexture.url&&(this.videoPoster=this.m_abstractMesh.material.diffuseTexture.url.replace("data:","")));var t=this.getProperty("url",null),n=this.getProperty("source",null),i=t;null!=n&&null!=n.filename&&""!==n.filename&&(i=e.SceneManager.GetRootUrl(this.scene)+n.filename),null!=i&&""!==i&&(!0===this.videoPreload?this.videoPreloaderUrl=i:this.setDataSource(i))},n.prototype.destroyWebVideoPlayer=function(){this.m_abstractMesh=null,null!=this.m_videoTexture&&(this.m_videoTexture.dispose(),this.m_videoTexture=null),null!=this.m_videoMaterial&&(this.m_videoMaterial.dispose(),this.m_videoMaterial=null),this.revokeVideoBlobUrl()},n.prototype.isReady=function(){return null!=this.getVideoElement()},n.prototype.isPlaying=function(){var e=!1,t=this.getVideoElement();return null!=t&&(e=!1===t.paused),e},n.prototype.isPaused=function(){var e=!1,t=this.getVideoElement();return null!=t&&(e=!0===t.paused),e},n.prototype.play=function(){return a(this,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return[4,e.AudioSource.UnlockAudioEngine()];case 1:return t.sent(),this.internalPlay(),[2,!0]}})})},n.prototype.internalPlay=function(){var e=this;!0===this._initializedReadyInstance?this.checkedPlay():this.onReadyObservable.addOnce(function(){e.checkedPlay()})},n.prototype.checkedPlay=function(){var e=this,t=this.getVideoElement();null!=t&&t.play().then(function(){!0===t.paused&&e.checkedRePlay()})},n.prototype.checkedRePlay=function(){var e=this.getVideoElement();null!=e&&e.play().then(function(){})},n.prototype.pause=function(){var e=!1,t=this.getVideoElement();return null!=t&&(t.pause(),e=!0),e},n.prototype.mute=function(){var e=!1,t=this.getVideoElement();return null!=t&&(t.muted=!0,e=!0),e},n.prototype.unmute=function(){var e=!1,t=this.getVideoElement();return null!=t&&(t.muted=!1,e=!0),e},n.prototype.getVolume=function(){var e=0,t=this.getVideoElement();return null!=t&&(e=t.volume),e},n.prototype.setVolume=function(e){var t=!1,n=this.getVideoElement();return null!=n&&(n.volume=e,t=!0),t},n.prototype.setDataSource=function(e){var t=this;null!=this.m_abstractMesh&&(null==this.m_videoMaterial&&(this.m_videoMaterial=new BABYLON.StandardMaterial(this.transform.name+".VideoMat",this.scene),this.m_videoMaterial.roughness=1,this.m_videoMaterial.diffuseColor=new BABYLON.Color3(1,1,1),this.m_videoMaterial.emissiveColor=new BABYLON.Color3(1,1,1),this.m_videoMaterial.useAlphaFromDiffuseTexture=this.videoFaded,this.m_abstractMesh.material=this.m_videoMaterial),null!=this.m_videoMaterial?(this.m_videoMaterial.diffuseTexture=null,null!=this.m_videoTexture&&(this.m_videoTexture.dispose(),this.m_videoTexture=null),this._initializedReadyInstance=!1,this.m_videoTexture=new BABYLON.VideoTexture(this.transform.name+".VideoTex",e,this.scene,this.videoMipmaps,this.videoInvert,this.videoSample,{autoUpdateTexture:!0,poster:this.videoPoster}),null!=this.m_videoTexture&&(this.m_videoTexture.hasAlpha=this.videoAlpha,null!=this.m_videoTexture.video&&(this.m_videoTexture.video.loop=this.videoLoop,this.m_videoTexture.video.muted=this.videoMuted,this.m_videoTexture.video.volume=this.videoVolume,this.m_videoTexture.video.playbackRate=this.videoPlayback,this.m_videoTexture.video.addEventListener("loadeddata",function(){t._initializedReadyInstance=!0,t.onReadyObservable&&t.onReadyObservable.hasObservers()&&t.onReadyObservable.notifyObservers(t.m_videoTexture),!0===t.videoPlayOnAwake&&t.play()}),this.m_videoTexture.video.load())),null!=this.m_videoTexture&&(this.m_videoTexture.level=this.m_diffuseIntensity,this.m_videoMaterial.diffuseTexture=this.m_videoTexture)):BABYLON.Tools.Warn("No video mesh or material available for: "+this.transform.name))},n.prototype.revokeVideoBlobUrl=function(){null!=this.videoBlobUrl&&(URL.revokeObjectURL(this.videoBlobUrl),this.videoBlobUrl=null)},n.prototype.addPreloaderTasks=function(e){var t=this;if(!0===this.videoPreload){var n=e.addBinaryFileTask(this.transform.name+".VideoTask",this.videoPreloaderUrl);n.onSuccess=function(e){t.revokeVideoBlobUrl(),t.videoBlobUrl=URL.createObjectURL(new Blob([e.data])),t.setDataSource(t.videoBlobUrl)},n.onError=function(e,t,n){console.error(t,n)}}},n}(e.ScriptComponent);e.WebVideoPlayer=t,e.SceneManager.RegisterClass("TOOLKIT.WebVideoPlayer",t)}(i||(i={})),"undefined"!=typeof window?(window.TOOLKIT=i,window.SM=i.SceneManager,window.WM=i.WindowManager,window.UI=i.UserInterface,window.IC=i.InputController):(globalThis.TOOLKIT=i,globalThis.SM=i.SceneManager,globalThis.WM=i.WindowManager,globalThis.UI=i.UserInterface,globalThis.IC=i.InputController);const u=i;return t.default})());
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.TOOLKIT=t():e.TOOLKIT=t()}(this,()=>(()=>{"use strict";var e={d:(t,n)=>{for(var i in n)e.o(n,i)&&!e.o(t,i)&&Object.defineProperty(t,i,{enumerable:!0,get:n[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)},t={};e.d(t,{default:()=>u});var n,i,r=(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),o=function(){return o=Object.assign||function(e){for(var t,n=1,i=arguments.length;n<i;n++)for(var r in t=arguments[n])Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e},o.apply(this,arguments)},a=function(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{l(i.next(e))}catch(e){o(e)}}function s(e){try{l(i.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}l((i=i.apply(e,t||[])).next())})},s=function(e,t){var n,i,r,o={label:0,sent:function(){if(1&r[0])throw r[1];return r[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(l){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(n=1,i&&(r=2&s[0]?i.return:s[0]?i.throw||((r=i.return)&&r.call(i),0):i.next)&&!(r=r.call(i,s[1])).done)return r;switch(i=0,r&&(s=[2&s[0],r.value]),s[0]){case 0:case 1:r=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,i=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!((r=(r=o.trys).length>0&&r[r.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!r||s[1]>r[0]&&s[1]<r[3])){o.label=s[1];break}if(6===s[0]&&o.label<r[1]){o.label=r[1],r=s;break}if(r&&o.label<r[2]){o.label=r[2],o.ops.push(s);break}r[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],i=0}finally{n=r=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,l])}}},l=function(e,t,n){if(n||2===arguments.length)for(var i,r=0,o=t.length;r<o;r++)!i&&r in t||(i||(i=Array.prototype.slice.call(t,0,r)),i[r]=t[r]);return e.concat(i||Array.prototype.slice.call(t))};!function(e){var t=function(){function t(){}return Object.defineProperty(t,"Version",{get:function(){return"9.9.1 - R1"},enumerable:!1,configurable:!0}),Object.defineProperty(t,"Copyright",{get:function(){return"All rights reserved (c) 2024 Mackey Kinard"},enumerable:!1,configurable:!0}),t.GetEngine=function(e){var t=null,n=e.getEngine();return null!=n&&(n instanceof BABYLON.Engine||n instanceof BABYLON.WebGPUEngine)&&(t=n),t},t.GetClass=function(e){return BABYLON.GetClass(e)},t.RegisterClass=function(e,t){BABYLON.RegisterClass(e,t)},t.GetAuxiliaryData=function(e){var t;return null===(t=null==e?void 0:e.metadata)||void 0===t?void 0:t.auxiliary},t.SetAuxiliaryData=function(e,t){e.metadata=o(o({},e.metadata),{auxiliary:t})},Object.defineProperty(t,"EventBus",{get:function(){return null==e.SceneManager._EventBus&&(e.SceneManager._EventBus=new e.GlobalMessageBus),e.SceneManager._EventBus},enumerable:!1,configurable:!0}),Object.defineProperty(t,"PlaygroundCdn",{get:function(){return"https://cdn.jsdelivr.net/gh/BabylonJS/BabylonToolkit@master/Runtime/"},enumerable:!1,configurable:!0}),Object.defineProperty(t,"PlaygroundRepo",{get:function(){return"https://www.babylontoolkit.com/playground/"},enumerable:!1,configurable:!0}),t.InitializePlayground=function(t){return a(this,arguments,void 0,function(t,n,i,r){return void 0===n&&(n=null),void 0===i&&(i=null),void 0===r&&(r=null),s(this,function(o){return[2,e.SceneManager.InitializeRuntime(t,n,i,r)]})})},t.InitializeRuntime=function(t){return a(this,arguments,void 0,function(t,n,i,r){var o,a,l,u,c,d,h,p,m;return void 0===n&&(n=null),void 0===i&&(i=null),void 0===r&&(r=null),s(this,function(s){switch(s.label){case 0:BABYLON.Tools.Log("Babylon.js Toolkit v"+e.SceneManager.Version),e.AudioSource.IsLegacyEngine()&&BABYLON.Tools.Log("Legacy audio engine detected"),o=null!=n&&null!=n.hardwareScalingLevel?n.hardwareScalingLevel:e.WindowManager.GetHardwareScalingLevel(),null==n||null==n.initSceneFileLoaders||n.initSceneFileLoaders,null==n||null==n.loadAsyncRuntimeLibs||n.loadAsyncRuntimeLibs,a=null!=n&&null!=n.enableUserInput&&n.enableUserInput,l=e.SceneManager.PlaygroundCdn+"default.playground.js",u=null!=n&&null!=n.loadProjectScriptBundle&&n.loadProjectScriptBundle,c=null!=n&&null!=n.projectScriptBundleUrl?n.projectScriptBundleUrl:l,d=null!=n&&null!=n.showDefaultLoadingScreen&&n.showDefaultLoadingScreen,h=null==n||null==n.hideLoadingUIWithEngine||n.hideLoadingUIWithEngine,p=null!=n&&null!=n.defaultLoadingUIMarginTop?n.defaultLoadingUIMarginTop:"150px",!0===d&&e.SceneManager.ShowLoadingScreen(t,h,p),null!=o&&o>0&&t.setHardwareScalingLevel(o),!0===a&&e.InputController.EnableUserInput(t,i,r),e.SceneManager.UniversalModuleDefinition=!0;try{e.SceneManager.InitializeSceneLoaderPlugin()}catch(e){console.warn("Babylon Toolkit: Failed to initialize loader plugin:",e)}try{BABYLON&&BABYLON.GLTF2&&BABYLON.GLTF2.registerGLTFExtension?(e.SceneManager.CVTOOLS_NAME_REGISTERED||(BABYLON.GLTF2.registerGLTFExtension(e.SceneManager.CVTOOLS_NAME,!0,function(t){return new e.CVTOOLS_unity_metadata(t)}),e.SceneManager.CVTOOLS_NAME_REGISTERED=!0),e.SceneManager.CVTOOLS_MESH_REGISTERED||(BABYLON.GLTF2.registerGLTFExtension(e.SceneManager.CVTOOLS_MESH,!0,function(t){return new e.CVTOOLS_babylon_mesh(t)}),e.SceneManager.CVTOOLS_MESH_REGISTERED=!0),e.SceneManager.CVTOOLS_HAND_REGISTERED||(BABYLON.GLTF2.registerGLTFExtension(e.SceneManager.CVTOOLS_HAND,!0,function(t){return new e.CVTOOLS_left_handed(t)}),e.SceneManager.CVTOOLS_HAND_REGISTERED=!0)):console.warn("Babylon Toolkit: UMD GLTF Parser not registered because BABYLON.GLTF2 or RegisterGLTFExtension is not available.")}catch(e){console.warn("Babylon Toolkit: Failed to initialize GLTF extensions:",e)}return!0!==u||null==c||""===c?[3,2]:(m=c.substring(c.lastIndexOf("/")+1).toLowerCase(),[4,BABYLON.Tools.LoadScriptAsync(c,m)]);case 1:s.sent(),s.label=2;case 2:return[2]}})})},t.InitializeSceneLoaderPlugin=function(){BABYLON.SceneLoader.OnPluginActivatedObservable.add(function(t){null!=t&&"gltf"===t.name&&t instanceof BABYLON.GLTFFileLoader&&(t.extensions,t.animationStartMode=e.SceneManager.AnimationStartMode,t.targetFps=e.SceneManager.AnimationTargetFps,t.onSkinLoadedObservable&&t.onSkinLoadedObservable.add(function(e){if(null!=e){try{null!=e.skinnedNode&&(e.skinnedNode.id+=".Skin")}catch(e){console.warn(e)}try{null!=e.skinnedNode&&(e.skinnedNode.name+=".Skin")}catch(e){console.warn(e)}try{if(null!=e.node&&null!=e.skinnedNode){var t=BABYLON.Tags.GetTags(e.node);null!=t&&BABYLON.Tags.AddTagsTo(e.skinnedNode,t),e.node._skinnedMesh=e.skinnedNode}else console.warn("Babylon Toolkit: Skinned node not found in scene loader plugin: ",e)}catch(e){console.warn(e)}}}))})},t.LoadRuntimeAssets=function(t,n,i){return a(this,arguments,void 0,function(t,n,i,r,o){return void 0===r&&(r=60),void 0===o&&(o=!1),s(this,function(a){switch(a.label){case 0:return e.SceneManager.SetOnSceneReadyHandler(n,i,r,o),null==t?[3,2]:[4,t.loadAsync()];case 1:a.sent(),a.label=2;case 2:return[2]}})})},t.ShowLoadingScreen=function(t,n,i){if(void 0===n&&(n=!0),void 0===i&&(i="150px"),null!=t.loadingScreen){e.SceneManager._HideLoadingScreen=t.loadingScreen.hideLoadingUI.bind(t.loadingScreen),!1===n&&(t.loadingScreen.hideLoadingUI=function(){});var r=t.loadingScreen;r._loadingDivBackgroundColor="#2A2342",t.displayLoadingUI(),null!=r._loadingTextDiv&&null!=r._loadingTextDiv.style&&(r._loadingTextDiv.style.marginTop=i)}},t.HideLoadingScreen=function(t,n){if(void 0===n&&(n=!0),null!=t.loadingScreen){if(!1===n){var i=t.loadingScreen;i._loadingDivToRenderingCanvasMap&&i._loadingDivToRenderingCanvasMap.forEach(function(e,t){t&&t.style&&(t.style.transition="none",t.style.opacity="0")})}null!=e.SceneManager._HideLoadingScreen?e.SceneManager._HideLoadingScreen():t.hideLoadingUI()}else e.SceneManager.ForceHideLoadingScreen()},t.ForceHideLoadingScreen=function(){try{e.SceneManager.DoForceHideLoadingScreen()}catch(e){console.warn(e)}finally{try{e.SceneManager.DoForceHideLoadingScreen()}catch(e){console.warn(e)}finally{try{e.SceneManager.DoForceHideLoadingScreen()}catch(e){console.warn(e)}}}},t.DoForceHideLoadingScreen=function(){var e=document.getElementById("babylonjsLoadingDiv"),t=document.getElementById("babylonjsLoadingText"),n=document.getElementById("babylonjsLoadingDivStyle");try{null!=t&&(t.remove(),t=null)}catch(e){console.warn(e)}try{null!=e&&(e.remove(),e=null)}catch(e){console.warn(e)}try{null!=n&&n.remove()}catch(e){console.warn(e)}},t.FocusRenderCanvas=function(e){e.getEngine().getRenderingCanvas().focus()},t.ShowSplashScreen=function(){try{var e=document.getElementById("xbabylonjsSplashScreen");e&&(e.style.display="block")}catch(e){console.warn(e)}},t.HideSplashScreen=function(t,n){void 0===t&&(t=null),void 0===n&&(n=0),e.WindowManager.SetTimeout(n,function(){if(null!=t&&!t.isDisposed){try{e.SceneManager.HideLoadingScreen(t.getEngine())}catch(e){console.warn(e)}try{e.SceneManager.FocusRenderCanvas(t)}catch(e){console.warn(e)}}try{var n=document.getElementById("xbabylonjsSplashScreen");if(n){n.style.opacity="0";var i=function(){n.style.display="none",n.removeEventListener("transitionend",i)};n.addEventListener("transitionend",i)}}catch(e){console.warn(e)}})},t.UpdateSplashScreenStatus=function(e){try{var t=document.getElementById("xbabylonjsSplashScreen");if(t){t.style.display="block";var n=t.querySelector("#xbabylonjsStatusTextDiv");n&&(n.textContent=e)}}catch(e){console.warn(e)}},t.SetOnSceneReadyHandler=function(t,n,i,r){void 0===i&&(i=60),void 0===r&&(r=!1),e.SceneManager.SceneLoaderPropertyBag={},e.SceneManager.SceneLoaderHandledFlag=!1,e.SceneManager.SceneLoaderFileNames=t,e.SceneManager.SceneLoaderFileNames.forEach(function(t){e.SceneManager.SceneLoaderPropertyBag[t.toLowerCase()]=!1}),e.SceneManager.OnSceneReadyObservable.clear(),e.SceneManager.OnSceneReadyObservable.add(function(t){if(!0===r&&console.log("OnSceneReady(): "+t),e.SceneManager.SceneLoaderPropertyBag[t.toLowerCase()]=!0,!0===Object.values(e.SceneManager.SceneLoaderPropertyBag).every(function(e){return!0===e}))try{n&&n()}catch(e){console.warn(e)}finally{e.SceneManager.SceneLoaderHandledFlag=!0}}),e.WindowManager.SetTimeout(1e3*i,function(){if(!1===e.SceneManager.SceneLoaderHandledFlag)try{n&&n()}catch(e){console.warn(e)}finally{e.SceneManager.SceneLoaderHandledFlag=!0,e.SceneManager.ForceHideLoadingScreen()}})},t.EnableSceneParsing=function(t){e.SceneManager.SceneParsingEnabled=t},t.IsSceneParsingEnabled=function(){return e.SceneManager.SceneParsingEnabled},t.HasSceneBeenPreLoaded=function(e){var t=e;return null!=t._preloaded&&!0===t._preloaded},t.GetDefaultSkybox=function(e){return e.getMeshById("Default Skybox")},t.GetIntensityFactor=function(){return null!=e.SceneManager.GlobalOptions.intensityFactor?e.SceneManager.GlobalOptions.intensityFactor:2},t.GetRenderQuality=function(){var t=e.RenderQuality.High,n=e.SceneManager.GlobalOptions.renderQuality;return null!=n&&(t=n),t},t.SetRenderQuality=function(t){e.SceneManager.GlobalOptions.renderQuality=t},t.GetEngineVersionString=function(t){var n="Unknown",i=t||BABYLON.EngineStore.LastCreatedScene;if(null!=i){var r=e.SceneManager.GetEngine(i);if(null!=r){var o=r.getInfo();null!=o&&(n=o.version+" - "+o.renderer)}}return n},t.GetImageBasedLighting=function(e){return e.globalSphericalPolynomial},t.SetWindowState=function(t,n){e.SceneManager.WindowState[t]=n},t.GetWindowState=function(t){var n=e.SceneManager.WindowState[t];return null!=n?n:null},t.IsDebugMode=function(){return!0},t.ConsoleLog=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];e.SceneManager.IsDebugMode()&&console.log.apply(console,t)},t.ConsoleInfo=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];e.SceneManager.IsDebugMode()&&console.info.apply(console,t)},t.ConsoleWarn=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];e.SceneManager.IsDebugMode()&&console.warn.apply(console,t)},t.ConsoleError=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];console.error.apply(console,e)},t.LogMessage=function(t){e.SceneManager.IsDebugMode()&&BABYLON.Tools.Log(t)},t.LogWarning=function(t){e.SceneManager.IsDebugMode()&&BABYLON.Tools.Warn(t)},t.LogError=function(e){BABYLON.Tools.Error(e)},t.GetTime=function(){return.001*e.SceneManager.GetTimeMilliseconds()},t.GetTimeMs=function(){return e.SceneManager.GetTimeMilliseconds()},t.GetGameTime=function(){return.001*(e.SceneManager.GetTimeMilliseconds()-e.SceneManager.GameTimeMilliseconds)},t.GetGameTimeMs=function(){return e.SceneManager.GetTimeMilliseconds()-e.SceneManager.GameTimeMilliseconds},t.GetDeltaTime=function(t,n){return void 0===n&&(n=!1),e.SceneManager.GetDeltaSeconds(t,n)},t.GetDeltaSeconds=function(e,t){void 0===t&&(t=!1);var n=e||BABYLON.EngineStore.LastCreatedScene,i=.001*Math.max(BABYLON.Scene.MinDeltaTime,Math.min(n.getEngine().getDeltaTime(),BABYLON.Scene.MaxDeltaTime));return!0===t&&(i*=n.getAnimationRatio()),i},t.GetDeltaMilliseconds=function(e,t){void 0===t&&(t=!1);var n=e||BABYLON.EngineStore.LastCreatedScene,i=Math.max(BABYLON.Scene.MinDeltaTime,Math.min(n.getEngine().getDeltaTime(),BABYLON.Scene.MaxDeltaTime));return!0===t&&(i*=n.getAnimationRatio()),i},t.GetTimeMilliseconds=function(){var e=0;return"undefined"!=typeof window&&window.performance?e=window.performance.now():"undefined"!=typeof window&&window.Date?e=window.Date.now():null!=Date&&(e=Date.now()),e},t.GetAnimationRatio=function(e){return(e||BABYLON.EngineStore.LastCreatedScene).getAnimationRatio()},t.SetScenePlaying=function(t,n){void 0===n&&(n=null),e.SceneManager.ScenePlaying=t;var i=n||BABYLON.EngineStore.LastCreatedScene;if(null!=i){var r=i.getPhysicsEngine();null!=r&&(!0===t?r.setTimeStep(e.SceneManager.PhysicsTimeStep):(e.SceneManager.PhysicsTimeStep=r.getTimeStep(),r.setTimeStep(0)))}!0===t&&(e.SceneManager.GameTimeMilliseconds=e.SceneManager.GetTimeMilliseconds())},t.RunOnce=function(e,t,n){e.executeOnceBeforeRender(t,n)},t.DisposeScene=function(e,t){void 0===t&&(t=new BABYLON.Color4(0,0,0,1));var n=e.getEngine();e.dispose(),n.clear(t,!0,!0,!0)},t.SafeDestroy=function(t,n,i){void 0===n&&(n=5),void 0===i&&(i=!1),n>0?(!0===i&&t.setEnabled(!1),e.WindowManager.SetTimeout(n,function(){t.dispose(!1,!1)})):t.dispose(!1,!1)},t.GetRootUrl=function(e){return null!=e._rootUrl&&""!==e._rootUrl?e._rootUrl:"/"},t.SetRootUrl=function(e,t){e._rootUrl=t},t.GetSceneFile=function(e){return null!=e._fileName&&""!==e._fileName?e._fileName:null},t.SetSceneFile=function(e,t){e._fileName=t},t.AddShadowCaster=function(e,t,n){void 0===n&&(n=!1);var i=null==e?void 0:e.getShadowGenerator();if(null!=i){var r=i.getShadowMap();if(null!=r&&(null==r.renderList&&(r.renderList=[]),t instanceof BABYLON.AbstractMesh&&r.renderList.indexOf(t)<0&&r.renderList.push(t),!0===n)){var o=t.getChildMeshes(!1);null!=o&&o.forEach(function(e){r.renderList.indexOf(e)<0&&r.renderList.push(e)})}}},t.AddShadowCastersToLight=function(e,t,n){void 0===n&&(n=!1);var i=e.getShadowGenerator();if(null!=i){var r=i.getShadowMap();if(null!=r)for(var o=0;o<t.length;o++){var a=t[o];if(a instanceof BABYLON.AbstractMesh&&(null!=e.includedOnlyMeshes&&e.includedOnlyMeshes.length>0&&e.includedOnlyMeshes.indexOf(a)<0&&e.includedOnlyMeshes.push(a),null==r.renderList&&(r.renderList=[]),r.renderList.indexOf(a)<0&&r.renderList.push(a)),!0===n){var s=a.getChildMeshes();null!=s&&s.length>0&&s.forEach(function(t){null!=e.includedOnlyMeshes&&e.includedOnlyMeshes.length>0&&e.includedOnlyMeshes.indexOf(t)<0&&e.includedOnlyMeshes.push(t),null==r.renderList&&(r.renderList=[]),r.renderList.indexOf(t)<0&&r.renderList.push(t)})}}}},t.RefreshShadowCascades=function(e){var t=null==e?void 0:e.getShadowGenerator();if(null!=t&&t instanceof BABYLON.CascadedShadowGenerator){try{t.shadowMaxZ++}catch(e){}try{t.shadowMaxZ--}catch(e){}}},t.RefreshAllShadowCascades=function(t){null!=t.lights&&t.lights.length>0&&t.lights.forEach(function(t){t instanceof BABYLON.ShadowLight&&e.SceneManager.RefreshShadowCascades(t)})},t.IsPhysicsViewerEnabled=function(){return e.SceneManager.PhysicsViewersEnabled},t.TogglePhysicsViewer=function(t){if(e.SceneManager.PhysicsViewersEnabled=!e.SceneManager.PhysicsViewersEnabled,e.SceneManager.PhysicsViewersEnabled){var n=new BABYLON.Debug.PhysicsViewer(t);null==t.reservedDataStore&&(t.reservedDataStore={}),t.reservedDataStore.physicsViewer=n;for(var i=0,r=t.meshes;i<r.length;i++){var o=r[i];o.physicsImpostor?(l=n.showImpostor(o.physicsImpostor,o))&&(l.reservedDataStore={hidden:!0},l.material&&(l.material.reservedDataStore={hidden:!0})):o.physicsBody&&(l=n.showBody(o.physicsBody))&&(l.reservedDataStore={hidden:!0},l.material&&(l.material.reservedDataStore={hidden:!0}))}for(var a=0,s=t.transformNodes;a<s.length;a++){var l,u=s[a];u.physicsBody&&(l=n.showBody(u.physicsBody))&&(l.reservedDataStore={hidden:!0},l.material&&(l.material.reservedDataStore={hidden:!0}))}}else t.reservedDataStore&&t.reservedDataStore.physicsViewer&&(t.reservedDataStore.physicsViewer.dispose(),t.reservedDataStore.physicsViewer=null)},t.GetImportMeshes=function(e,t){return null==e||null==t||""===t?null:null!=e.importMeshes?e.importMeshes.get(t.toLowerCase()):null},t.GetImportMeshesMap=function(e){return null==e?null:null!=e.importMeshes?e.importMeshes:null},t.ClearImportMeshes=function(e){if(null==e)return null;e.importMeshes,e.importMeshes=new Map},t.RegisterImportMeshes=function(e,t,n){null!=e&&null!=t&&""!==t&&null!=n&&(null==e.importMeshes&&(e.importMeshes=new Map),e.importMeshes.set(t.toLowerCase(),n))},t.LoadImportMeshes=function(t,n,i,r,o,a,s,l,u){var c=null,d=n+i,h=e.SceneManager.GetImportMeshes(r,d);return null!=h?o&&o(h):c=BABYLON.SceneLoader.ImportMesh(t,n,i,r,function(t){e.SceneManager.RegisterImportMeshes(r,d,t),o&&o(t)},a,s,l,u),c},t.LoadImportMeshesAsync=function(t,n,i,r,o,l,u){return a(this,void 0,void 0,function(){var a,c,d,h;return s(this,function(s){switch(s.label){case 0:return a=n+i,null==(c=e.SceneManager.GetImportMeshes(r,a))?[3,1]:[2,c];case 1:return d=null,[4,BABYLON.SceneLoader.ImportMeshAsync(t,n,i,r,o,l,u)];case 2:return null!=(h=s.sent())&&null!=h.meshes&&(d=h.meshes),e.SceneManager.RegisterImportMeshes(r,a,d),[2,d]}})})},t.GetAssetContainer=function(e,t){return null==e||null==t||""===t?null:null!=e.assetContainers?e.assetContainers.get(t.toLowerCase()):null},t.GetAssetContainerMap=function(e){return null==e?null:null!=e.assetContainers?e.assetContainers:null},t.ClearAssetContainers=function(e){if(null==e)return null;e.assetContainers,e.assetContainers=new Map},t.RegisterAssetContainer=function(e,t,n){null!=e&&null!=t&&""!==t&&null!=n&&(null==e.assetContainers&&(e.assetContainers=new Map),e.assetContainers.set(t.toLowerCase(),n))},t.LoadAssetContainer=function(t,n,i,r,o,a,s,l){var u=t+n,c=e.SceneManager.GetAssetContainer(i,u);null!=c?r&&r(c):BABYLON.SceneLoader.LoadAssetContainer(t,n,i,function(t){e.SceneManager.RegisterAssetContainer(i,u,t),r&&r(t)},o,a,s,l)},t.LoadAssetContainerAsync=function(t,n,i,r,o,l){return a(this,void 0,void 0,function(){var a,u,c;return s(this,function(s){switch(s.label){case 0:return a=t+n,null==(u=e.SceneManager.GetAssetContainer(i,a))?[3,1]:[2,u];case 1:return[4,BABYLON.SceneLoader.LoadAssetContainerAsync(t,n,i,r,o,l)];case 2:return c=s.sent(),e.SceneManager.RegisterAssetContainer(i,a,c),[2,c]}})})},t.GetMesh=function(e,t){return null==e?null:e.getNodeByName(t)},t.GetMeshByID=function(e,t){return null==e?null:e.getNodeById(t)},t.GetAbstractMesh=function(e,t){return null==e?null:e.getNodeByName(t)},t.GetAbstractMeshByID=function(e,t){return null==e?null:e.getNodeById(t)},t.GetTransformNode=function(e,t){return null==e?null:e.getNodeByName(t)},t.GetTransformNodeByID=function(e,t){return null==e?null:e.getNodeById(t)},t.GetTransformDetailMesh=function(e){var t=null,n=e.name+".Detail",i=e.getChildren(function(e){return e.name===n&&e instanceof BABYLON.AbstractMesh},!0);return null!=i&&i.length>0&&(t=i[0]),t},t.GetSkinnedMesh=function(e){return null!=e._skinnedMesh?e._skinnedMesh:null},t.GetPrimitiveMeshes=function(e){return e.getChildMeshes(!0,function(e){return e.name.indexOf("_primitive")>=0})},t.GetTransformLayer=function(e){return null!=e.metadata&&null!=e.metadata.toolkit&&null!=e.metadata.toolkit.layer?e.metadata.toolkit.layer:0},t.GetTransformLayerMask=function(e){return null!=e.metadata&&null!=e.metadata.toolkit&&null!=e.metadata.toolkit.layermask?e.metadata.toolkit.layermask:1},t.GetTransformLayerName=function(e){return null!=e.metadata&&null!=e.metadata.toolkit&&null!=e.metadata.toolkit.layername&&""!==e.metadata.toolkit.layername?e.metadata.toolkit.layername:"Default"},t.GetTransformTag=function(e){return null!=e.metadata&&null!=e.metadata.toolkit&&null!=e.metadata.toolkit.group&&""!==e.metadata.toolkit.group?e.metadata.toolkit.group:"Untagged"},t.HasTransformTags=function(e,t){return BABYLON.Tags.MatchesQuery(e,t)},t.HasSoundManager=function(){return null!=PROJECT&&null!=PROJECT.SceneSoundSystem},t.IsSoundEffectPlaying=function(e){return null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.SFX&&PROJECT.SceneSoundSystem.SFX.isPlaying(e)},t.IsMusicTrackPlaying=function(e){return null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.MUSIC&&PROJECT.SceneSoundSystem.MUSIC.isPlaying(e)},t.PlayOneShot=function(e,t,n,i){return a(this,void 0,void 0,function(){return s(this,function(r){return null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.SFX?[2,PROJECT.SceneSoundSystem.SFX.playTrack(e,t,n,i)]:[2,!1]})})},t.PlayMusicTrack=function(e,t,n,i){return a(this,void 0,void 0,function(){return s(this,function(r){return null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.MUSIC?[2,PROJECT.SceneSoundSystem.MUSIC.playTrack(e,t,n,i)]:[2,!1]})})},t.PauseMusicTrack=function(e){return null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.MUSIC&&PROJECT.SceneSoundSystem.MUSIC.pauseTrack(e)},t.MuteMusicTrack=function(e,t){return null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.MUSIC&&PROJECT.SceneSoundSystem.MUSIC.muteTrack(e,t,offset,length)},t.UnmuteMusicTrack=function(e,t){return null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.MUSIC&&PROJECT.SceneSoundSystem.MUSIC.unmuteTrack(e,t)},t.StopMusicTrack=function(e,t){return null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.MUSIC&&PROJECT.SceneSoundSystem.MUSIC.stopTrack(e,t)},t.StopAllMusicTracks=function(){null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.MUSIC&&PROJECT.SceneSoundSystem.MUSIC.stopAllTracks()},t.PauseAllMusicTracks=function(){null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.MUSIC&&PROJECT.SceneSoundSystem.MUSIC.pauseAllTracks()},t.MuteAllMusicTracks=function(e){null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.MUSIC&&PROJECT.SceneSoundSystem.MUSIC.muteAllTracks(e)},t.UnmuteAllMusicTracks=function(e){null!=PROJECT&&null!=PROJECT.SceneSoundSystem&&null!=PROJECT.SceneSoundSystem.MUSIC&&PROJECT.SceneSoundSystem.MUSIC.unmuteAllTracks(e)},t.TextureFloatSupported=function(e){var t=!1,n=!1,i=e.getEngine().getCaps();return i.textureHalfFloatRender&&i.textureHalfFloatLinearFiltering?t=!0:i.textureFloatRender&&i.textureFloatLinearFiltering&&(n=!0),t||n},t.RegisterClickAction=function(e,t,n){var i=null;return null!=t&&(t.isPickable=!0,null==t.actionManager&&(t.actionManager=new BABYLON.ActionManager(e)),i=t.actionManager.registerAction(new BABYLON.ExecuteCodeAction({trigger:BABYLON.ActionManager.OnPickTrigger},n))),i},t.UnregisterClickAction=function(e,t){var n=!1;return null!=e&&null!=t&&(n=e.actionManager.unregisterAction(t)),n},t.GetMaterialWithName=function(e,t){var n=null;if(null!=e.materials&&e.materials.length>0){e.materials.length;for(var i=0;i<e.materials.length;i++){var r=e.materials[i];if(r.name.startsWith(t)){n=r;break}}}return n},t.GetAllMaterialsWithName=function(e,t){var n=null;if(null!=e.materials&&e.materials.length>0){e.materials.length;for(var i=0;i<e.materials.length;i++){var r=e.materials[i];r.name.startsWith(t)&&(null==n&&(n=[]),n.push(r))}}return n},t.InstantiatePrefabFromScene=function(t,n,i,r,o,a,s,l){void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),void 0===l&&(l=!0);var u=null;if(null!=t&&null!=n&&""!==n){var c=t.getNodeByName(n);if(null!=c)if(null!=(u=c.clone(i,r,!1))){null!=o&&(u.position=o.clone()),null!=a&&(u.rotationQuaternion=a.clone()),null!=s&&(u.scaling=s.clone());var d=null,h=u.getChildren(null,!1);null!=h&&(d=h),null==d?d=[u]:d.unshift(u),d.forEach(function(e){if(e.setEnabled(!0),e instanceof BABYLON.AbstractMesh&&null!=e.metadata&&null!=e.metadata.shadowCastingMode&&0!==e.metadata.shadowCastingMode&&t.lights.forEach(function(t){var n=t.getShadowGenerator();if(null!=n&&!1==(null!=t.includedOnlyMeshes&&t.includedOnlyMeshes.length>0)){var i=n.getShadowMap();null==i.renderList&&(i.renderList=[]),i.renderList.indexOf(e)<0&&i.renderList.push(e)}}),e instanceof BABYLON.Mesh)if(null!=e.source){if(null==e.skeleton&&null!=e.source.skeleton){var n=e.source.skeleton.name+".Skeleton",i=n+"."+e.source.skeleton.id;if(e.skeleton=e.source.skeleton.clone(n,i),null!=e.skeleton&&null!=e.skeleton.bones&&null!=e.source.skeleton.bones&&e.skeleton.bones.length===e.source.skeleton.bones.length)for(var r=e.skeleton.bones.length,o=0;o<r;o++)null==e.skeleton.bones[o].metadata&&null!=e.source.skeleton.bones[o].metadata&&(e.skeleton.bones[o].metadata=e.source.skeleton.bones[o].metadata)}}else BABYLON.Tools.Warn("Babylon.js encountered a null clone source for: "+e.name)});var p=[];if(d.forEach(function(e){p.push(e)}),null!=p&&p.length>0){var m=[];e.Utilities.PostParseSceneComponents(t,p,null,m),t.onAfterRenderObservable.addOnce(function(){if(null!=m&&m.length>0)for(var e=0;e<m.length;e++){var t=m[e];null!=t&&t.delayComponentInstance&&t.delayComponentInstance(t)}})}}else BABYLON.Tools.Warn("Failed to create prefab of: "+n);else BABYLON.Tools.Warn("Failed to lookup prefab map: "+n)}else BABYLON.Tools.Warn("Unable to locate prefab master: "+n);return u},t.InstantiatePrefabFromContainer=function(t,n,i,r,o,a,s,l,u){void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null),void 0===l&&(l=!0),void 0===u&&(u=!1);var c=e.Utilities.CloneAssetContainerItem(t,n,function(e){return e},r,u,l);if(null!=c){null!=i&&""!==i&&(c.name=i),null!=o&&(c.position=o.clone()),null!=a&&(c.rotationQuaternion=a.clone()),null!=s&&(c.scaling=s.clone());var d=[];d.push(c);var h=c.getChildren(null,!1);null!=h&&h.length>0&&h.forEach(function(e){d.push(e)}),d.forEach(function(t){t.id=e.Utilities.CreateGuid(),t.setEnabled(!0)});var p=[];e.Utilities.PostParseSceneComponents(t.scene,d,null,p),t.scene.onAfterRenderObservable.addOnce(function(){if(null!=p&&p.length>0)for(var e=0;e<p.length;e++){var t=p[e];null!=t&&t.delayComponentInstance&&t.delayComponentInstance(t)}})}return c},t.InstantiateModelsFromContainer=function(t,n,i,r,o,a){void 0===n&&(n=null),void 0===i&&(i=!1),void 0===r&&(r=!1),void 0===o&&(o=!1),void 0===a&&(a=null);var s=null,u=t.instantiateModelsToScene(n,r,{doNotInstantiate:!i,predicate:a});if(null!=u&&null!=u.rootNodes&&u.rootNodes.length>0){var c=u.rootNodes[0],d=c.getChildren(null,!1);!0===o&&e.SceneManager.RebuildBoundingBoxInfo(d),s=l([c],d,!0)}return s},t.CreateInstancedModelsFromContainer=function(t,n,i,r,o,a,s,l,u){void 0===n&&(n=null),void 0===i&&(i=null),void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=!0),void 0===l&&(l=!1),void 0===u&&(u=!1);var c=null,d=null,h=null,p=t.instantiateModelsToScene(function(e){return e},l,{doNotInstantiate:!1});if(null!=p&&(null!=p.rootNodes&&p.rootNodes.length>0&&(d=p.rootNodes[0].getChildren(null,!1),!0===u&&e.SceneManager.RebuildBoundingBoxInfo(d)),null!=p.animationGroups&&(h=p.animationGroups)),null!=d){if(c=d[0],null!=i&&(c.parent=i),null!=n&&""!==n&&(c.name=n),null!=r&&(c.position=r.clone()),null!=o&&(c.rotationQuaternion=o.clone()),null!=a&&(c.scaling=a.clone()),d.forEach(function(t){t.id=e.Utilities.CreateGuid(),t.setEnabled(!0)}),!0===s){var m=null;h.forEach(function(e){var t=e,n=null!=t.metadata&&null!=t.metadata.toolkit&&null!=t.metadata.toolkit.source&&""!==t.metadata.toolkit.source?t.metadata.toolkit.source:null;if(null!=n&&""!==n){var i=e.clone(e.name),r=n;null!=t.metadata&&(i.metadata={},i.metadata.toolkit={},i.metadata.toolkit.id=t.metadata.toolkit.id,i.metadata.toolkit.clip=t.metadata.toolkit.clip,i.metadata.toolkit.source=r,i.metadata.toolkit.legacy=t.metadata.toolkit.legacy,i.metadata.toolkit.length=t.metadata.toolkit.length,i.metadata.toolkit.looping=t.metadata.toolkit.looping,i.metadata.toolkit.settings=t.metadata.toolkit.settings,i.metadata.toolkit.behavior=t.metadata.toolkit.behavior,i.metadata.toolkit.wrapmode=t.metadata.toolkit.wrapmode,i.metadata.toolkit.framerate=t.metadata.toolkit.framerate,i.metadata.toolkit.humanmotion=t.metadata.toolkit.humanmotion,i.metadata.toolkit.averagespeed=t.metadata.toolkit.averagespeed,i.metadata.toolkit.averageduration=t.metadata.toolkit.averageduration,i.metadata.toolkit.averageangularspeed=t.metadata.toolkit.averageangularspeed),null==m&&(m=[]),m.push(i)}}),null!=c&&null!=m&&e.Utilities.AssignAnimationGroupsToInstance(c,m)}var f=[];e.Utilities.PostParseSceneComponents(t.scene,d,null,f),t.scene.onAfterRenderObservable.addOnce(function(){if(null!=f&&f.length>0)for(var e=0;e<f.length;e++){var t=f[e];null!=t&&t.delayComponentInstance&&t.delayComponentInstance(t)}})}return p},t.CloneTransformNode=function(t,n,i,r,o,a,s){void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null);var l=e.Utilities.GetAssetContainerNode(t,n).clone(i,r,!0);return null!=l&&(null!=o&&(l.position=o.clone()),null!=a&&(l.rotationQuaternion=a.clone()),null!=s&&(l.scaling=s.clone()),l.setEnabled(!0)),l},t.CloneAbstractMesh=function(t,n,i,r,o,a,s){void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null);var l=e.Utilities.GetAssetContainerMesh(t,n).clone(i,r,!0);return null!=l&&(null!=o&&(l.position=o.clone()),null!=a&&(l.rotationQuaternion=a.clone()),null!=s&&(l.scaling=s.clone()),l.setEnabled(!0)),l},t.CreateInstancedMesh=function(t,n,i,r,o,a,s){void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=null);var l=e.Utilities.GetAssetContainerMesh(t,n).createInstance(i);return null!=l&&(null!=r&&(l.parent=r),null!=o&&(l.position=o.clone()),null!=a&&(l.rotationQuaternion=a.clone()),null!=s&&(l.scaling=s.clone()),l.setEnabled(!0)),l},t.RebuildBoundingBoxInfo=function(e){null!=e&&e.length>0&&e.forEach(function(e){var t,n;if(e instanceof BABYLON.InstancedMesh){var i=null===(t=e.sourceMesh.getBoundingInfo())||void 0===t?void 0:t.boundingBox;null!=i&&null!=i.minimum&&null!=i.maximum&&e.setBoundingInfo(new BABYLON.BoundingInfo(i.minimum,i.maximum))}else if(e instanceof BABYLON.AbstractMesh){var r=null===(n=e.getBoundingInfo())||void 0===n?void 0:n.boundingBox;null!=r&&null!=r.minimum&&null!=r.maximum&&e.setBoundingInfo(new BABYLON.BoundingInfo(r.minimum,r.maximum))}})},t.AttachScriptComponent=function(e,t,n){void 0===n&&(n=!0),null!=e&&e.registerComponentInstance&&e.registerComponentInstance(e,t,n)},t.DestroyScriptComponent=function(e){null!=e&&e.destroyComponentInstance&&e.destroyComponentInstance(e)},t.DestroyGameObject=function(t){if(null!=t){var n=e.SceneManager.FindScriptComponents(t,!0);if(null!=n&&n.length>0)for(var i=0;i<n.length;i++){var r=n[i];e.SceneManager.DestroyScriptComponent(r)}e.SceneManager.SafeDestroy(t)}},t.GetComponent=function(t,n,i){return void 0===i&&(i=!1),e.SceneManager.FindScriptComponent(t,n,i)},t.GetComponents=function(t,n){return void 0===n&&(n=!1),e.SceneManager.FindScriptComponents(t,n)},t.FindGameObject=function(e,t){if(!t||""===t.trim())return null;var n=t.split("/").filter(function(e){return""!==e.trim()});if(0===n.length)return null;for(var i=null,r=e.rootNodes,o=function(e){var t=n[e];if(0===e)i=r.find(function(e){return e.name===t})||null;else{if(!i)return"break";var o=i.getChildren(null,!1);i=o.find(function(e){return e.name===t})||null}if(!i)return"break"},a=0;a<n.length&&"break"!==o(a);a++);if(i&&i instanceof BABYLON.TransformNode)return i;for(var s=0,l=r;s<l.length;s++){var u=l[s];if(u.name&&u.getChildren){var c,d="".concat(u.name,"/").concat(t);if(d!==t&&(c=this.FindGameObjectExactPath(e,d)))return c}}return 1===n.length&&(c=this.FindGameObjectRecursive(e,n[0]))?c:null},t.FindGameObjectExactPath=function(e,t){for(var n=t.split("/").filter(function(e){return""!==e.trim()}),i=null,r=e.rootNodes,o=function(e){var t=n[e];if(0===e)i=r.find(function(e){return e.name===t})||null;else{if(!i)return{value:null};var o=i.getChildren(null,!1);i=o.find(function(e){return e.name===t})||null}if(!i)return{value:null}},a=0;a<n.length;a++){var s=o(a);if("object"==typeof s)return s.value}return i instanceof BABYLON.TransformNode?i:null},t.FindGameObjectRecursive=function(e,t){for(var n=function(e){if(e.name===t&&e instanceof BABYLON.TransformNode)return e;if(e.getChildren)for(var i=0,r=e.getChildren(null,!1);i<r.length;i++){var o=r[i],a=n(o);if(a)return a}return null},i=0,r=e.rootNodes;i<r.length;i++){var o=r[i],a=n(o);if(a)return a}return null},t.DebugSceneHierarchy=function(e,t){void 0===t&&(t=3),console.log("=== SCENE HIERARCHY DEBUG ===");var n=function(e,i,r){if(void 0===r&&(r=""),!(i>t)){var o=" ".repeat(i),a=e instanceof BABYLON.TransformNode?"TransformNode":e instanceof BABYLON.AbstractMesh?"Mesh":e instanceof BABYLON.Camera?"Camera":e instanceof BABYLON.Light?"Light":e.constructor.name;if(console.log("".concat(o).concat(r).concat(e.name," (").concat(a,")")),e instanceof BABYLON.TransformNode||e instanceof BABYLON.AbstractMesh){var s=e.getChildren(null,!1);s.forEach(function(e,t){var r=t===s.length-1;n(e,i+1,r?"└─ ":"├─ ")})}}};console.log("Root nodes:"),e.rootNodes.forEach(function(t,i){var r=i===e.rootNodes.length-1;n(t,0,r?"└─ ":"├─ ")}),console.log("=== END HIERARCHY DEBUG ===")},t.LegacySearchForGameObject=function(e,t){for(var n=t.split("/"),i=null,r=e.rootNodes,o=function(e){var t=n[e];if(0===e)i=r.find(function(e){return e.name===t})||null;else{if(!(i&&i instanceof BABYLON.TransformNode))return{value:null};i=i.getChildren(function(e){return e.name===t},!1)[0]||null}if(!i)return{value:null}},a=0;a<n.length;a++){var s=o(a);if("object"==typeof s)return s.value}return i},t.FindGameObjectWithTag=function(t,n){for(var i=function(t){if(e.SceneManager.GetTransformTag(t)===n)return t;if(t instanceof BABYLON.TransformNode)for(var r=0,o=t.getChildren();r<o.length;r++){var a=o[r];if(a instanceof BABYLON.TransformNode){var s=i(a);if(s)return s}}return null},r=0,o=t.rootNodes;r<o.length;r++){var a=o[r];if(a instanceof BABYLON.TransformNode){var s=i(a);if(s)return s}}return null},t.FindGameObjectsWithTag=function(t,n){for(var i=[],r=function(t){if(e.SceneManager.GetTransformTag(t)===n&&i.push(t),t instanceof BABYLON.TransformNode)for(var o=0,a=t.getChildren();o<a.length;o++){var s=a[o];s instanceof BABYLON.TransformNode&&r(s)}},o=0,a=t.rootNodes;o<a.length;o++){var s=a[o];s instanceof BABYLON.TransformNode&&r(s)}return i},t.FindScriptComponents=function(t,n){if(void 0===n&&(n=!1),null==t)return null;var i=null;if(null!=t.metadata&&t.metadata.toolkit){var r=t.metadata.toolkit;if(null!=r.components&&r.components.length>0)for(var o=0;o<r.components.length;o++){var a=r.components[o];null==i&&(i=[]),i.push(a.instance)}}if(!0===n){var s=t.getChildren(null,!1);if(null!=s)for(var l=0;l<s.length;l++){var u=s[l],c=e.SceneManager.FindScriptComponents(u,!1);null!=c&&(null==i&&(i=[]),i.push.apply(i,c))}}return null!=i?i:null},t.FindScriptComponent=function(t,n,i){if(void 0===i&&(i=!1),null==t)return null;var r=null;if(null!=t.metadata&&t.metadata.toolkit){var o=t.metadata.toolkit;if(null!=o.components&&o.components.length>0)for(var a=0;a<o.components.length;a++){var s=o.components[a];if(null!=s.instance&&s.klass===n){r=s.instance;break}}}if(null==r&&!0===i){var l=t.getChildren(null,!1);if(null!=l)for(var u=0;u<l.length;u++){var c=l[u];if(null!=(r=e.SceneManager.FindScriptComponent(c,n,!1)))break}}return null!=r?r:null},t.FindAllScriptComponents=function(t,n,i){if(void 0===i&&(i=!1),null==t)return null;var r=null;if(null!=t.metadata&&t.metadata.toolkit){var o=t.metadata.toolkit;if(null!=o.components&&o.components.length>0)for(var a=0;a<o.components.length;a++){var s=o.components[a];null!=s.instance&&s.klass===n&&(null==r&&(r=[]),r.push(s.instance))}}if(!0===i){var l=t.getChildren(null,!1);if(null!=l)for(var u=0;u<l.length;u++){var c=l[u],d=e.SceneManager.FindAllScriptComponents(c,n,!1);null!=d&&(null==r&&(r=[]),r.push.apply(r,d))}}return null!=r?r:null},t.FindSceneMetadata=function(e){return null==e?null:null!=e.metadata&&e.metadata.toolkit?e.metadata.toolkit:null},t.FindSceneCameraRig=function(e){return null==e?null:null!=e.cameraRig?e.cameraRig:null},t.FindSceneLightRig=function(e){return null==e?null:null!=e.lightRig?e.lightRig:null},t.FindTransformWithScript=function(t,n){var i=t.getNodes();return e.Utilities.SearchTransformNodeForScript(n,i)},t.FindAllTransformsWithScript=function(t,n){var i=t.getNodes();return e.Utilities.SearchAllTransformNodesForScript(n,i)},t.FindChildTransformNode=function(t,n,i,r,o){if(void 0===i&&(i=e.SearchType.ExactMatch),void 0===r&&(r=!0),void 0===o&&(o=null),null==t)return null;var a=null!=i?i:e.SearchType.ExactMatch,s=t.getChildren(o,r);return e.Utilities.SearchTransformNodes(n,s,a)},t.FindChildTransformWithTags=function(t,n,i,r){if(void 0===i&&(i=!0),void 0===r&&(r=null),null==t)return null;var o=t.getChildren(r,i);return e.Utilities.SearchTransformNodeForTags(n,o)},t.FindAllChildTransformsWithTags=function(t,n,i,r){if(void 0===i&&(i=!0),void 0===r&&(r=null),null==t)return null;var o=t.getChildren(r,i);return e.Utilities.SearchAllTransformNodesForTags(n,o)},t.FindChildTransformWithScript=function(t,n,i,r){if(void 0===i&&(i=!0),void 0===r&&(r=null),null==t)return null;var o=t.getChildren(r,i);return e.Utilities.SearchTransformNodeForScript(n,o)},t.FindAllChildTransformsWithScript=function(t,n,i,r){if(void 0===i&&(i=!0),void 0===r&&(r=null),null==t)return null;var o=t.getChildren(r,i);return e.Utilities.SearchAllTransformNodesForScript(n,o)},t.FindComponentInParent=function(t,n,i){var r=null!=n.parent?[n,n.parent]:[n],o=e.Utilities.SearchTransformNodeForScript(i,r);return e.SceneManager.FindScriptComponent(o,i)},t.FindComponentsInParent=function(t,n,i){var r=null,o=n.getChildren(null,!1),a=null!=o?l([n],o,!0):[n],s=e.Utilities.SearchAllTransformNodesForScript(i,a);return null!=s&&s.length>0&&s.forEach(function(t){var n=e.SceneManager.FindScriptComponent(t,i);null!=n&&(null==r&&(r=[]),r.push(n))}),null!=r?r:null},t.FindComponentInChildren=function(t,n,i){var r=n.getChildren(null,!1),o=null!=r?l([n],r,!0):[n],a=e.Utilities.SearchTransformNodeForScript(i,o);return e.SceneManager.FindScriptComponent(a,i)},t.FindComponentsInChildren=function(t,n,i){var r=null,o=n.getChildren(null,!1),a=null!=o?l([n],o,!0):[n],s=e.Utilities.SearchAllTransformNodesForScript(i,a);return null!=s&&s.length>0&&s.forEach(function(t){var n=e.SceneManager.FindScriptComponent(t,i);null!=n&&(null==r&&(r=[]),r.push(n))}),null!=r?r:null},t.SearchForScriptComponentByName=function(t,n){var i=t.getNodes(),r=e.Utilities.SearchTransformNodeForScript(n,i);return e.SceneManager.FindScriptComponent(r,n)},t.SearchForAllScriptComponentsByName=function(t,n){var i=null,r=t.getNodes(),o=e.Utilities.SearchAllTransformNodesForScript(n,r);return null!=o&&o.length>0&&o.forEach(function(t){var r=e.SceneManager.FindScriptComponent(t,n);null!=r&&(null==i&&(i=[]),i.push(r))}),null!=i?i:null},t.MoveWithCollisions=function(e,t){if(null==e)return null;null!=t&&e.moveWithCollisions(t)},t.MoveWithTranslation=function(e,t){if(null==e)return null;null!=t&&e.position.addInPlace(t)},t.TurnWithRotation=function(e,t,n){if(void 0===n&&(n=BABYLON.Space.LOCAL),null==e)return null;0!=t&&e.rotate(BABYLON.Axis.Y,t,n)},t.HasNavigationData=function(){return null!=e.SceneManager.NavMeshPlugin&&null!=e.SceneManager.NavMeshPlugin.navMesh},t.GetNavigationData=function(){return null!=e.SceneManager.NavMeshPlugin&&null!=e.SceneManager.NavMeshPlugin.navMesh?e.SceneManager.NavMeshPlugin.navMesh:null},t.GetNavigationMesh=function(){return null!=e.SceneManager.NavMeshSurface?e.SceneManager.NavMeshSurface:null},t.GetNavigationDebug=function(){return null!=e.SceneManager.NavMeshDebugger?e.SceneManager.NavMeshDebugger:null},t.GetNavigationPlugin=function(){return null!=e.SceneManager.NavMeshPlugin?e.SceneManager.NavMeshPlugin:null},t.GetCrowdInterface=function(t){if(null!=e.SceneManager.NavMeshPlugin&&null!=e.SceneManager.NavMeshPlugin.navMesh){var n=e.SceneManager.GetNavigationPlugin();return null!=n&&null==e.SceneManager.CrowdInterface&&(e.SceneManager.CrowdInterface=n.createCrowd(e.SceneManager.MAX_AGENT_COUNT,e.SceneManager.MAX_AGENT_RADIUS,t)),e.SceneManager.CrowdInterface}return null},t.LoadNavigationMeshDataAsync=function(t,n){return a(this,arguments,void 0,function(t,n,i,r){var o,l,u=this;return void 0===i&&(i=null),void 0===r&&(r=!1),s(this,function(c){switch(c.label){case 0:return e.SceneManager.DestroyNavigationMeshData(),o=new BABYLON.AssetsManager(t),(l=o.addBinaryFileTask("System.NavigationMeshTask",n)).onSuccess=function(o){return a(u,void 0,void 0,function(){var a;return s(this,function(s){switch(s.label){case 0:return null==o.data?[3,2]:(a=new Uint8Array(o.data),[4,e.SceneManager.BuildNavigationMeshDataAsync(t,a,i,r)]);case 1:return s.sent(),[3,3];case 2:console.error("Failed to load navigation mesh task: "+n),s.label=3;case 3:return[2]}})})},l.onError=function(e,t,n){console.error(t,n)},[4,o.loadAsync()];case 1:return c.sent(),[2]}})})},t.BuildNavigationMeshDataAsync=function(t,n){return a(this,arguments,void 0,function(t,n,i,r){var o;return void 0===i&&(i=null),void 0===r&&(r=!1),s(this,function(a){switch(a.label){case 0:return null==n?[2]:(e.SceneManager.DestroyNavigationMeshData(),e.SceneManager.NavMeshSurface=i,null!=e.SceneManager.NavMeshPlugin?[3,2]:(o=e.SceneManager,[4,ADDONS.CreateNavigationPluginAsync()]));case 1:o.NavMeshPlugin=a.sent(),a.label=2;case 2:return null!=e.SceneManager.NavMeshPlugin&&(e.SceneManager.NavMeshPlugin.buildFromNavmeshData(n),!0===r&&(e.SceneManager.NavMeshDebugger=e.SceneManager.NavMeshPlugin.createDebugNavMesh(t),null!=e.SceneManager.NavMeshDebugger&&(e.SceneManager.NavMeshDebugger.checkCollisions=!1,e.SceneManager.NavMeshDebugger.isPickable=!1,e.SceneManager.NavMeshDebugger.isVisible=!0,e.SceneManager.NavMeshDebugger.visibility=1,null==e.SceneManager.NavMeshMaterial&&(e.SceneManager.NavMeshMaterial=new BABYLON.StandardMaterial("Navmesh-Debug-Material",t),e.SceneManager.NavMeshMaterial.transparencyMode=BABYLON.Material.MATERIAL_ALPHABLEND,e.SceneManager.NavMeshMaterial.backFaceCulling=!1,e.SceneManager.NavMeshMaterial.diffuseColor=new BABYLON.Color3(0,.75,1),e.SceneManager.NavMeshMaterial.alpha=.5),e.SceneManager.NavMeshDebugger.material=e.SceneManager.NavMeshMaterial)),e.SceneManager.OnNavMeshReadyObservable.hasObservers()&&e.SceneManager.OnNavMeshReadyObservable.notifyObservers(e.SceneManager.GetNavigationMesh())),[2]}})})},t.BuildNavigationMeshTileCacheAsync=function(t,n){return a(this,arguments,void 0,function(t,n,i,r,o){var a;return void 0===i&&(i=null),void 0===r&&(r=null),void 0===o&&(o=!1),s(this,function(s){switch(s.label){case 0:return null==n?[2]:(e.SceneManager.DestroyNavigationMeshData(),e.SceneManager.NavMeshSurface=r,null!=e.SceneManager.NavMeshPlugin?[3,2]:(a=e.SceneManager,[4,ADDONS.CreateNavigationPluginAsync()]));case 1:a.NavMeshPlugin=s.sent(),s.label=2;case 2:return null!=e.SceneManager.NavMeshPlugin&&(null==i&&(i=function(e,t,n){for(var i=0;i<e.polyCount();i++)t.set(i,0),n.set(i,1)}),e.SceneManager.NavMeshPlugin.buildFromTileCacheData(n,i),!0===o&&(e.SceneManager.NavMeshDebugger=e.SceneManager.NavMeshPlugin.createDebugNavMesh(t),null!=e.SceneManager.NavMeshDebugger&&(e.SceneManager.NavMeshDebugger.checkCollisions=!1,e.SceneManager.NavMeshDebugger.isPickable=!1,e.SceneManager.NavMeshDebugger.isVisible=!0,e.SceneManager.NavMeshDebugger.visibility=1,null==e.SceneManager.NavMeshMaterial&&(e.SceneManager.NavMeshMaterial=new BABYLON.StandardMaterial("Navmesh-Debug-Material",t),e.SceneManager.NavMeshMaterial.transparencyMode=BABYLON.Material.MATERIAL_ALPHABLEND,e.SceneManager.NavMeshMaterial.backFaceCulling=!1,e.SceneManager.NavMeshMaterial.diffuseColor=new BABYLON.Color3(0,.75,1),e.SceneManager.NavMeshMaterial.alpha=.5),e.SceneManager.NavMeshDebugger.material=e.SceneManager.NavMeshMaterial)),e.SceneManager.OnNavMeshReadyObservable.hasObservers()&&e.SceneManager.OnNavMeshReadyObservable.notifyObservers(e.SceneManager.GetNavigationMesh())),[2]}})})},t.CreateNavigationMeshSceneDataAsync=function(t,n,i){return a(this,arguments,void 0,function(t,n,i,r,o){var a,l;return void 0===r&&(r=null),void 0===o&&(o=!1),s(this,function(s){switch(s.label){case 0:return null==n||null==i||0===i.length?[2]:(e.SceneManager.DestroyNavigationMeshData(),e.SceneManager.NavMeshSurface=r,null!=e.SceneManager.NavMeshPlugin?[3,2]:(a=e.SceneManager,[4,ADDONS.CreateNavigationPluginAsync()]));case 1:a.NavMeshPlugin=s.sent(),s.label=2;case 2:return null==e.SceneManager.NavMeshPlugin?[3,4]:(l={cs:n.cs||.2,ch:n.ch||.2,walkableSlopeAngle:n.walkableslopeangle||45,walkableHeight:n.walkableheight||2,walkableClimb:n.walkableclimb||1,walkableRadius:n.walkableradius||.5,maxEdgeLen:n.maxedgelen||12,maxSimplificationError:n.maxsimplificationerror||1.3,minRegionArea:n.minregionarea||2,mergeRegionArea:n.mergeregionarea||20,maxVertsPerPoly:n.maxvertsperpoly||6,detailSampleDist:n.detailsampledist||6,detailSampleMaxError:n.detailsamplemaxerror||1,tileSize:n.tilesize||32,borderSize:0,offMeshConnections:null,keepIntermediates:!1,maxObstacles:0,expectedLayersPerTile:32,tileCacheMeshProcess:null,doNotReverseIndices:!1},[4,e.SceneManager.NavMeshPlugin.createNavMeshAsync(i,l)]);case 3:s.sent(),!0===o&&(e.SceneManager.NavMeshDebugger=e.SceneManager.NavMeshPlugin.createDebugNavMesh(t),null!=e.SceneManager.NavMeshDebugger&&(e.SceneManager.NavMeshDebugger.checkCollisions=!1,e.SceneManager.NavMeshDebugger.isPickable=!1,e.SceneManager.NavMeshDebugger.isVisible=!0,e.SceneManager.NavMeshDebugger.visibility=1,null==e.SceneManager.NavMeshMaterial&&(e.SceneManager.NavMeshMaterial=new BABYLON.StandardMaterial("Navmesh-Debug-Material",t),e.SceneManager.NavMeshMaterial.transparencyMode=BABYLON.Material.MATERIAL_ALPHABLEND,e.SceneManager.NavMeshMaterial.backFaceCulling=!1,e.SceneManager.NavMeshMaterial.diffuseColor=new BABYLON.Color3(0,.75,1),e.SceneManager.NavMeshMaterial.alpha=.5),e.SceneManager.NavMeshDebugger.material=e.SceneManager.NavMeshMaterial)),e.SceneManager.OnNavMeshReadyObservable.hasObservers()&&e.SceneManager.OnNavMeshReadyObservable.notifyObservers(e.SceneManager.GetNavigationMesh()),s.label=4;case 4:return[2]}})})},t.DestroyNavigationMeshData=function(){if(e.SceneManager.NavMeshSurface=null,null!=e.SceneManager.NavMeshDebugger){try{e.SceneManager.NavMeshDebugger.dispose()}catch(e){console.warn("Failed to dispose previous NavMesh debugger: ",e)}e.SceneManager.NavMeshDebugger=null}if(null!=e.SceneManager.NavMeshPlugin&&null!=e.SceneManager.NavMeshPlugin.navMesh){try{e.SceneManager.NavMeshPlugin.navMesh.destroy()}catch(e){console.warn("Failed to destroy previous navMesh data object: ",e)}e.SceneManager.NavMeshPlugin.navMesh=null}if(null!=e.SceneManager.NavMeshPlugin&&null!=e.SceneManager.NavMeshPlugin.navMeshQuery){try{e.SceneManager.NavMeshPlugin.navMeshQuery.destroy()}catch(e){console.warn("Failed to destroy previous navMesh query object: ",e)}if(e.SceneManager.NavMeshPlugin._navMeshQuery)try{e.SceneManager.NavMeshPlugin._navMeshQuery=null}catch(e){console.warn("Failed to set previous navMesh query object to null: ",e)}}},t.ToggleFullscreenMode=function(e,t){void 0===t&&(t=!0),e.getEngine().switchFullscreen(t)},t.EnterFullscreenMode=function(t,n){void 0===n&&(n=!0),e.SceneManager.GotoFullscreenBrowser(t,n)},t.ExitFullscreenMode=function(t){e.SceneManager.ExitFromFullscreenBrowser(t)},t.GotoFullscreenBrowser=function(t,n){void 0===n&&(n=!0);var i=document.documentElement;i.requestFullscreen?i.requestFullscreen().then(function(){!0===n&&e.SceneManager.RequestBrowserPointerLock(i)}).catch(function(e){console.error("Error attempting to enable full-screen mode: ".concat(e.message," (").concat(e.name,")"))}):i.mozRequestFullScreen?(i.mozRequestFullScreen(),!0===n&&e.SceneManager.RequestBrowserPointerLock(i)):i.webkitRequestFullscreen?(i.webkitRequestFullscreen(),!0===n&&e.SceneManager.RequestBrowserPointerLock(i)):i.msRequestFullscreen?(i.msRequestFullscreen(),!0===n&&e.SceneManager.RequestBrowserPointerLock(i)):t.getEngine().enterFullscreen(n)},t.RequestBrowserPointerLock=function(e){e.requestPointerLock?e.requestPointerLock():e.mozRequestPointerLock?e.mozRequestPointerLock():e.webkitRequestPointerLock&&e.webkitRequestPointerLock()},t.ExitFromFullscreenBrowser=function(e){var t=document;t.exitFullscreen?t.exitFullscreen():t.mozCancelFullScreen?t.mozCancelFullScreen():t.webkitExitFullscreen?t.webkitExitFullscreen():t.msExitFullscreen?t.msExitFullscreen():e.getEngine().exitFullscreen()},t.CreateEasingFunction=function(e){if(!e)return null;if("string"==typeof e){var t=void 0;switch(e.toLowerCase()){case"linear":case"sineout":default:return(t=new BABYLON.SineEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEOUT),t;case"sinein":return(t=new BABYLON.SineEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN),t;case"sineinout":return(t=new BABYLON.SineEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT),t;case"quadin":return(t=new BABYLON.QuadraticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN),t;case"quadout":return(t=new BABYLON.QuadraticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEOUT),t;case"quadinout":return(t=new BABYLON.QuadraticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT),t;case"cubicin":return(t=new BABYLON.CubicEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN),t;case"cubicout":return(t=new BABYLON.CubicEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEOUT),t;case"cubicinout":return(t=new BABYLON.CubicEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT),t;case"quartin":return(t=new BABYLON.QuarticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN),t;case"quartout":return(t=new BABYLON.QuarticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEOUT),t;case"quartinout":return(t=new BABYLON.QuarticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT),t;case"quintin":return(t=new BABYLON.QuinticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN),t;case"quintout":return(t=new BABYLON.QuinticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEOUT),t;case"quintinout":return(t=new BABYLON.QuinticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT),t;case"expoin":return(t=new BABYLON.ExponentialEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN),t;case"expoout":return(t=new BABYLON.ExponentialEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEOUT),t;case"expoinout":return(t=new BABYLON.ExponentialEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT),t;case"circlein":return(t=new BABYLON.CircleEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN),t;case"circleout":return(t=new BABYLON.CircleEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEOUT),t;case"circleinout":return(t=new BABYLON.CircleEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT),t;case"backin":return(t=new BABYLON.BackEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN),t;case"backout":return(t=new BABYLON.BackEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEOUT),t;case"backinout":return(t=new BABYLON.BackEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT),t;case"elasticin":return(t=new BABYLON.ElasticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN),t;case"elasticout":return(t=new BABYLON.ElasticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEOUT),t;case"elasticinout":return(t=new BABYLON.ElasticEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT),t;case"bouncein":return(t=new BABYLON.BounceEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEIN),t;case"bounceout":return(t=new BABYLON.BounceEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEOUT),t;case"bounceinout":return(t=new BABYLON.BounceEase).setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT),t}}return e},t.GetPropertyValue=function(e,t){for(var n=e,i=0,r=t.split(".");i<r.length;i++){var o=r[i];if(!n||"object"!=typeof n||!(o in n))return;n=n[o]}return n},t.SetPropertyValue=function(e,t,n){for(var i=t.split("."),r=e,o=0;o<i.length-1;o++){var a=i[o];a in r&&"object"==typeof r[a]||(r[a]={}),r=r[a]}r[i[i.length-1]]=n},t.IsGUIControl=function(e){if(!e)return!1;if(e.getClassName&&"function"==typeof e.getClassName){var t=e.getClassName();if(t&&t.includes("GUI"))return!0}return!!(e._host&&e._currentMeasure&&e._markAsDirty)||!!(e.constructor&&e.constructor.name&&e.constructor.name.includes("Control"))},t.IsGUIPositionProperty=function(e){return["left","top","width","height","paddingLeft","paddingTop","paddingRight","paddingBottom"].includes(e)},t.ExtractGUINumericValue=function(e,t){if(!e||!t)return 0;var n=t+"InPixels";if(void 0!==e[n]){var i=e[n];if("number"==typeof i&&!isNaN(i))return i}var r=e[t];return"string"==typeof r?r.endsWith("px")||r.endsWith("%")?parseFloat(r):parseFloat(r)||0:"number"==typeof r?r:0},t.CreateGUIAnimationProxy=function(t,n){var i={_control:t,_property:n,animations:[]};return Object.defineProperty(i,n,{get:function(){return e.SceneManager.ExtractGUINumericValue(i._control,i._property)},set:function(e){var t=i._property+"InPixels";void 0!==i._control[t]?i._control[t]=e:i._control[i._property]=e+"px"},enumerable:!0,configurable:!0}),i},t.GetAnimationType=function(e){if("number"==typeof e)return BABYLON.Animation.ANIMATIONTYPE_FLOAT;if(e&&"object"==typeof e){if(void 0!==e.x&&void 0!==e.y)return void 0!==e.z?BABYLON.Animation.ANIMATIONTYPE_VECTOR3:BABYLON.Animation.ANIMATIONTYPE_VECTOR2;if(void 0!==e.r&&void 0!==e.g&&void 0!==e.b)return BABYLON.Animation.ANIMATIONTYPE_COLOR3;if(void 0!==e.w&&void 0!==e.x&&void 0!==e.y&&void 0!==e.z)return BABYLON.Animation.ANIMATIONTYPE_QUATERNION}return BABYLON.Animation.ANIMATIONTYPE_FLOAT},t.CreateTweenAnimations=function(t,n,i,r,o){var a=[],s=[],l=60*(r.duration||1),u=e.SceneManager.IsGUIControl(t);for(var c in r.yoyo&&r.loop||r.yoyo&&r.yoyoCount&&r.yoyoCount>0&&r.yoyoCount,i){var d=i[c],h=n?n[c]:e.SceneManager.GetPropertyValue(t,c),p=t,m=c;if(u&&e.SceneManager.IsGUIPositionProperty(c)){p=e.SceneManager.CreateGUIAnimationProxy(t,c),m=c,h=n?"string"==typeof n[c]?parseFloat(n[c]):n[c]:e.SceneManager.ExtractGUINumericValue(t,c);var f="string"==typeof d?parseFloat(d):d,g=BABYLON.Animation.ANIMATIONTYPE_FLOAT,v=new BABYLON.Animation("tween_".concat(c),m,60,g,r.loop?BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT),y=e.SceneManager.CreateEasingFunction(r.ease);y&&v.setEasingFunction(y);var _=[],S=0;if(_.push({frame:S,value:h}),S+=l,_.push({frame:S,value:f}),r.yoyo&&r.loop)S+=l,_.push({frame:S,value:h});else if(r.yoyo&&r.yoyoCount&&r.yoyoCount>0){S+=l,_.push({frame:S,value:h});for(var A=1;A<r.yoyoCount;A++)S+=l,_.push({frame:S,value:f}),S+=l,_.push({frame:S,value:h})}v.setKeys(_),a.push(v),s.push(p)}else if(void 0!==h&&void 0!==d){var b=e.SceneManager.GetAnimationType(d),M=new BABYLON.Animation("tween_".concat(c),c,60,b,r.loop?BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT),B=e.SceneManager.CreateEasingFunction(r.ease);B&&M.setEasingFunction(B);var C=[],T=0;if(C.push({frame:T,value:h}),T+=l,C.push({frame:T,value:d}),r.yoyo&&r.loop)T+=l,C.push({frame:T,value:h});else if(r.yoyo&&r.yoyoCount&&r.yoyoCount>0)for(T+=l,C.push({frame:T,value:h}),A=1;A<r.yoyoCount;A++)T+=l,C.push({frame:T,value:d}),T+=l,C.push({frame:T,value:h});M.setKeys(C),a.push(M),s.push(p)}}return{animations:a,targets:s}},t.TweenTo=function(t,n,i,r){var o;void 0===i&&(i={}),r=r||BABYLON.EngineStore.LastCreatedScene;var a,s=e.SceneManager.CreateTweenAnimations(t,null,n,i,r),l=s.animations,u=s.targets,c=e.SceneManager.IsGUIControl(t);if(c)for(var d=0;d<l.length;d++){var h=l[d];(A=u[d])!==t?(A.animations=A.animations||[],A.animations.push(h)):(t.animations=t.animations||[],t.animations.push(h))}else t.animations=t.animations||[],(o=t.animations).push.apply(o,l);var p,m=new Promise(function(e){a=e}),f=function(){i.onComplete&&i.onComplete(),a()},g=1e3*(i.delay||0),v=i.speed||1,y=60*(i.duration||1);i.yoyo&&i.loop?y*=2:i.yoyo&&i.yoyoCount&&i.yoyoCount>0&&(y*=1+i.yoyoCount);var _=[];if(c&&u.some(function(e){return e!==t})){var S=[];if(g>0)setTimeout(function(){i.onStart&&i.onStart();for(var e=0;e<u.length;e++){var t=u[e],n=r.beginAnimation(t,0,y,i.loop||!1,v,e===u.length-1?f:void 0);n&&(S.push(n),_.push(n))}p=S[0]},g);else{for(i.onStart&&i.onStart(),d=0;d<u.length;d++){var A=u[d],b=r.beginAnimation(A,0,y,i.loop||!1,v,d===u.length-1?f:void 0);b&&(S.push(b),_.push(b))}p=S[0]}}else g>0?setTimeout(function(){i.onStart&&i.onStart(),(p=r.beginAnimation(t,0,y,i.loop||!1,v,f))&&_.push(p)},g):(i.onStart&&i.onStart(),(p=r.beginAnimation(t,0,y,i.loop||!1,v,f))&&_.push(p));return{animations:_,finished:m}},t.TweenToAsync=function(t,n){return a(this,arguments,void 0,function(t,n,i,r){return void 0===i&&(i={}),s(this,function(o){return[2,e.SceneManager.TweenTo(t,n,i,r).finished]})})},t.TweenFromTo=function(t,n,i,r,o){for(var a in void 0===r&&(r={}),n)e.SceneManager.SetPropertyValue(t,a,n[a]);return e.SceneManager.TweenTo(t,i,r,o)},t.TweenFromToAsync=function(t,n,i){return a(this,arguments,void 0,function(t,n,i,r,o){return void 0===r&&(r={}),s(this,function(a){return[2,e.SceneManager.TweenFromTo(t,n,i,r,o).finished]})})},t.TweenGroupAsync=function(e){return a(this,arguments,void 0,function(e,t,n){var i,r,o,a,l,u,c,d,h;return void 0===t&&(t={}),s(this,function(s){switch(s.label){case 0:if(n=n||BABYLON.EngineStore.LastCreatedScene,i=t.mode||"all",r=t.stagger||0,"sequence"!==i)return[3,7];o=0,a=e,s.label=1;case 1:return o<a.length?(l=a[o],(u=l())&&u.finished?[4,u.finished]:[3,3]):[3,6];case 2:return s.sent(),[3,5];case 3:return u&&u.then?[4,u]:[3,5];case 4:s.sent(),s.label=5;case 5:return o++,[3,1];case 6:return[3,9];case 7:for(c=[],d=function(t){var n=e[t];if(r>0&&t>0)c.push(new Promise(function(e){setTimeout(function(){var t=n();t&&t.finished?t.finished.then(e):t&&t.then?t.then(e):e()},t*r)}));else{var i=n();i&&i.finished?c.push(i.finished):i&&i.then&&c.push(i)}},h=0;h<e.length;h++)d(h);return[4,Promise.all(c)];case 8:s.sent(),s.label=9;case 9:return t.onComplete&&t.onComplete(),[2]}})})},t.GlobalOptions={},t.WindowState={},t.ServerEndPoint="http://127.0.0.1:2567",t.EnableDebugMode=!1,t.EnableUserInput=!0,t.RenderLoopReady=!0,t.PauseRenderLoop=!1,t.ScenePlaying=!0,t.PhysicsTimeStep=1/60,t.LostRenderContext=!1,t.AutoUpdateProgress=!0,t.PhysicsCapsuleShape=0,t.SupportSRGBBuffers=!1,t.AnimationStartMode=0,t.AnimationTargetFps=60,t.DefaultConvexHullMargin=.001,t.DefaultHeightFieldMargin=.001,t.AmbientLightIntensity=1,t.PointLightIntensity=1,t.SpotLightIntensity=1,t.DirectionalLightIntensity=1,t.FogExpDensityScale=1,t.FogExp2DensityScale=1,t.FogLinearDensityScale=1,t.TerrainColorCorrection=2.2,t.AllowCameraMovement=!0,t.AllowCameraRotation=!0,t.VirtualJoystickEnabled=!1,t.GameTimeMilliseconds=0,t.ParseScriptComponents=!0,t.AutoLoadScriptBundles=!0,t.AutoStripNamespacePrefix=!0,t.UniversalModuleDefinition=!0,t.WaitForSeconds=function(t){return new Promise(function(n){return e.WindowManager.SetTimeout(1e3*t,n)})},t.OnPreRenderLoopObservable=new BABYLON.Observable,t.OnPostRenderLoopObservable=new BABYLON.Observable,t.OnSceneReadyObservable=new BABYLON.Observable,t.OnEngineResizeObservable=new BABYLON.Observable,t.OnLoadCompleteObservable=new BABYLON.Observable,t.OnRebuildContextObservable=new BABYLON.Observable,t.OnAssetManagerProgress=null,t.AllLayerMask=4294967295,t.DefaultLayerMask=268435455,t.HiddenLayerMask=268435456,t._HideLoadingScreen=null,t.CVTOOLS_NAME="CVTOOLS_unity_metadata",t.CVTOOLS_MESH="CVTOOLS_babylon_mesh",t.CVTOOLS_HAND="CVTOOLS_left_handed",t.CVTOOLS_NAME_REGISTERED=!1,t.CVTOOLS_MESH_REGISTERED=!1,t.CVTOOLS_HAND_REGISTERED=!1,t._EventBus=null,t.SceneLoaderFileNames=[],t.SceneLoaderPropertyBag={},t.SceneLoaderHandledFlag=!1,t.SceneParsingEnabled=!0,t.PhysicsViewersEnabled=!1,t.MAX_AGENT_COUNT=200,t.MAX_AGENT_RADIUS=2,t.OnNavMeshReadyObservable=new BABYLON.Observable,t.NavMeshPlugin=null,t.NavMeshSurface=null,t.NavMeshDebugger=null,t.NavMeshMaterial=null,t.CrowdInterface=null,t}();e.SceneManager=t}(i||(i={})),i.SceneManager.GameTimeMilliseconds=i.SceneManager.GetTimeMilliseconds(),function(e){var t=function(){function t(t,n,i,r){if(void 0===i&&(i={}),void 0===r&&(r=null),this._update=null,this._late=null,this._step=null,this._fixed=null,this._after=null,this._ready=null,this._lateUpdate=!1,this._properties=null,this._awoken=!1,this._started=!1,this._scene=null,this._delyed=!1,this._transform=null,this._scriptReady=!1,this._registeredClassname=null,this._registerComponentAlias=!0,this._lateUpdateObserver=null,this.resetScriptComponent=null,this._bodyCollisionObserver=null,this._bodyCollisionEndedObserver=null,this._worldTriggerEventObserver=null,this.onCollisionEnterObservable=new BABYLON.Observable,this.onCollisionStayObservable=new BABYLON.Observable,this.onCollisionExitObservable=new BABYLON.Observable,this.onTriggerEnterObservable=new BABYLON.Observable,this.onTriggerExitObservable=new BABYLON.Observable,null==t)throw new Error("Null transform object specified.");if(null==n)throw new Error("Null host scene object specified.");this._scene=n,this._transform=t,this._properties=i||{},null!=this._properties._scriptComponentAlias&&""!==this._properties._scriptComponentAlias?this._registeredClassname=this._properties._scriptComponentAlias:this._registeredClassname=r||this.constructor.name||"Unknown",null!=this._properties._registerComponentAlias?this._registerComponentAlias=this._properties._registerComponentAlias:this._registerComponentAlias=!0;var o=this;o._update=function(){e.ScriptComponent.UpdateInstance(o)},o._late=function(){e.ScriptComponent.LateInstance(o)},o._step=function(){e.ScriptComponent.StepInstance(o)},o._fixed=function(){e.ScriptComponent.FixedInstance(o)},o._after=function(){e.ScriptComponent.AfterInstance(o)},o._ready=function(){e.ScriptComponent.ReadyInstance(o)},o.resetScriptComponent=function(){e.ScriptComponent.ResetInstance(o)},o.registerComponentInstance&&o.destroyComponentInstance||BABYLON.Tools.Warn("Invalid component registration handlers for: "+this._transform.name),!0===this._registerComponentAlias&&null!=o.registerComponentInstance&&o.registerComponentInstance(o,this._registeredClassname,!0)}return t.prototype.isReady=function(){return this._scriptReady},Object.defineProperty(t.prototype,"scene",{get:function(){return this._scene},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"transform",{get:function(){return this._transform},enumerable:!1,configurable:!0}),t.prototype.dispose=function(){},t.prototype.getClassName=function(){return this._registeredClassname},t.prototype.getProperties=function(){return this._properties},t.prototype.getProperty=function(e,t){void 0===t&&(t=null);var n=null;return null!=this._properties&&null==(n=this._properties[e])&&(n=this._properties["auto__"+e]),null==n&&(n=t),null!=n?n:null},t.prototype.setProperty=function(e,t){null==this._properties&&(this._properties={}),this._properties[e]=t},t.prototype.getTime=function(){return e.SceneManager.GetTime()},t.prototype.getTimeMs=function(){return e.SceneManager.GetTimeMs()},t.prototype.getGameTime=function(){return e.SceneManager.GetGameTime()},t.prototype.getGameTimeMs=function(){return e.SceneManager.GetGameTimeMs()},t.prototype.getDeltaTime=function(){return e.SceneManager.GetDeltaTime(this.scene)},t.prototype.getDeltaSeconds=function(){return e.SceneManager.GetDeltaSeconds(this.scene)},t.prototype.getDeltaMilliseconds=function(){return e.SceneManager.GetDeltaMilliseconds(this.scene)},t.prototype.getAnimationRatio=function(){return e.SceneManager.GetAnimationRatio(this.scene)},t.prototype.hasSkinnedMesh=function(){return null!=this.getSkinnedMesh()},t.prototype.getSkinnedMesh=function(){return e.SceneManager.GetSkinnedMesh(this.transform)},t.prototype.getTransformMesh=function(){return this._transform instanceof BABYLON.Mesh?this._transform:null},t.prototype.getAbstractMesh=function(){return this._transform instanceof BABYLON.AbstractMesh?this._transform:null},t.prototype.getInstancedMesh=function(){return this._transform instanceof BABYLON.InstancedMesh?this._transform:null},t.prototype.getPrimitiveMeshes=function(){return e.SceneManager.GetPrimitiveMeshes(this.transform)},t.prototype.getMetadata=function(){return e.SceneManager.FindSceneMetadata(this._transform)},t.prototype.getComponent=function(t,n){void 0===n&&(n=!1);var i=e.SceneManager.FindScriptComponent(this._transform,t,n);return null!=i?i:null},t.prototype.getComponents=function(t,n){void 0===n&&(n=!1);var i=e.SceneManager.FindAllScriptComponents(this._transform,t,n);return null!=i?i:null},t.prototype.getLightRig=function(){return e.SceneManager.FindSceneLightRig(this._transform)},t.prototype.getCameraRig=function(){return e.SceneManager.FindSceneCameraRig(this._transform)},t.prototype.getTransformTag=function(){return e.SceneManager.GetTransformTag(this.transform)},t.prototype.hasTransformTags=function(t){return e.SceneManager.HasTransformTags(this._transform,t)},t.prototype.getChildNode=function(t,n,i,r){return void 0===n&&(n=e.SearchType.ExactMatch),void 0===i&&(i=!0),void 0===r&&(r=null),e.SceneManager.FindChildTransformNode(this._transform,t,n,i,r)},t.prototype.getChildWithTags=function(t,n,i){return void 0===n&&(n=!0),void 0===i&&(i=null),e.SceneManager.FindChildTransformWithTags(this._transform,t,n,i)},t.prototype.getChildrenWithTags=function(t,n,i){return void 0===n&&(n=!0),void 0===i&&(i=null),e.SceneManager.FindAllChildTransformsWithTags(this._transform,t,n,i)},t.prototype.getChildWithScript=function(t,n,i){return void 0===n&&(n=!0),void 0===i&&(i=null),e.SceneManager.FindChildTransformWithScript(this._transform,t,n,i)},t.prototype.getChildrenWithScript=function(t,n,i){return void 0===n&&(n=!0),void 0===i&&(i=null),e.SceneManager.FindAllChildTransformsWithScript(this._transform,t,n,i)},t.prototype.enableCollisionEvents=function(){var t=this,n=e.Utilities.GetHavokPlugin();if(null!=n&&null!=this.transform.physicsBody){if(this.transform.physicsBody.setCollisionCallbackEnabled(!0),this.transform.physicsBody.setCollisionEndedCallbackEnabled(!0),null==this._bodyCollisionObserver){var i=this.transform.physicsBody.getCollisionObservable();null!=i&&(this._bodyCollisionObserver=i.add(function(e){null!=e.collidedAgainst&&null!=e.collidedAgainst.transformNode&&("COLLISION_STARTED"===e.type?t.onCollisionEnterObservable.notifyObservers(e.collidedAgainst.transformNode):"COLLISION_CONTINUED"===e.type&&t.onCollisionStayObservable.notifyObservers(e.collidedAgainst.transformNode))}))}if(null==this._bodyCollisionEndedObserver){var r=this.transform.physicsBody.getCollisionEndedObservable();null!=r&&(this._bodyCollisionEndedObserver=r.add(function(e){null!=e.collidedAgainst&&null!=e.collidedAgainst.transformNode&&"COLLISION_FINISHED"===e.type&&t.onCollisionExitObservable.notifyObservers(e.collidedAgainst.transformNode)}))}null==this._worldTriggerEventObserver&&(this._worldTriggerEventObserver=n.onTriggerCollisionObservable.add(function(e){if(e.collider===t.transform.physicsBody||e.collidedAgainst===t.transform.physicsBody){var n=e.collider===t.transform.physicsBody?e.collidedAgainst:e.collider;"TRIGGER_ENTERED"===e.type?t.onTriggerEnterObservable.notifyObservers(n.transformNode):"TRIGGER_EXITED"===e.type&&t.onTriggerExitObservable.notifyObservers(n.transformNode)}}))}},t.prototype.disableCollisionEvents=function(){null!=e.Utilities.GetHavokPlugin()&&null!=this.transform.physicsBody&&(this.transform.physicsBody.setCollisionCallbackEnabled(!1),this.transform.physicsBody.setCollisionEndedCallbackEnabled(!1))},t.prototype.setTransformPosition=function(e){this.transform.physicsBody&&0!=this.transform.physicsBody.disablePreStep&&(this.transform.physicsBody.disablePreStep=!1),null!=this.transform.position&&this.transform.position.copyFrom(e)},t.prototype.setTransformRotation=function(e){this.transform.physicsBody&&0!=this.transform.physicsBody.disablePreStep&&(this.transform.physicsBody.disablePreStep=!1),null!=this.transform.rotationQuaternion&&this.transform.rotationQuaternion.copyFrom(e)},t.prototype.registerOnClickAction=function(t){var n=null;return this.transform instanceof BABYLON.AbstractMesh&&(n=e.SceneManager.RegisterClickAction(this.scene,this.transform,t)),n},t.prototype.unregisterOnClickAction=function(t){var n=!1;return this.transform instanceof BABYLON.AbstractMesh&&(n=e.SceneManager.UnregisterClickAction(this.transform,t)),n},t.prototype.registerComponentInstance=function(t,n,i){if(void 0===i&&(i=!0),null!=n&&""!==n&&"Unknown"!==n){if(!0===i){e.Utilities.ValidateTransformMetadata(this._transform);var r={alias:"script",order:0,klass:n,properties:null,instance:t};null==this._transform.metadata.toolkit.components&&(this._transform.metadata.toolkit.components=[]),this._transform.metadata.toolkit.components.push(r)}e.ScriptComponent.RegisterInstance(t),!0===i&&t.scene.onAfterRenderObservable.addOnce(function(){t.delayComponentInstance(t)})}else console.warn("Failed to register unknown component instance: ",t)},t.prototype.delayComponentInstance=function(t){e.WindowManager.SetTimeout(100,function(){t._delyed=!0})},t.prototype.destroyComponentInstance=function(t){e.ScriptComponent.DestroyInstance(t)},t.prototype.setupStepComponentInstance=function(e){e.scene.onBeforePhysicsObservable&&e.scene.onBeforePhysicsObservable.add(e._step)},t.prototype.removeStepComponentInstance=function(e){e.scene.onBeforePhysicsObservable&&e.scene.onBeforePhysicsObservable.removeCallback(e._step)},t.prototype.setupFixedComponentInstance=function(e){e.scene.onAfterPhysicsObservable&&e.scene.onAfterPhysicsObservable.add(e._fixed)},t.prototype.removeFixedComponentInstance=function(e){e.scene.onAfterPhysicsObservable&&e.scene.onAfterPhysicsObservable.removeCallback(e._fixed)},t.RegisterInstance=function(e){null!=e&&(null!=e._update&&e.scene.registerBeforeRender(e._update),e.late&&null!=e._late&&null!=e.scene.onBeforeRenderTargetsRenderObservable&&(e._lateUpdateObserver=e.scene.onBeforeRenderTargetsRenderObservable.add(e._late)),e.after&&null!=e._after&&e.scene.registerAfterRender(e._after),e.step&&null!=e._step&&e.setupStepComponentInstance(e),e.fixed&&null!=e._fixed&&e.setupFixedComponentInstance(e))},t.UpdateInstance=function(t){!0===e.SceneManager.ScenePlaying&&null!=t&&null!=t.transform&&t.transform.isEnabled(!1)&&(!1===t._awoken?(t._awoken=!0,e.ScriptComponent.ParseAutoProperties(t),t.awake&&t.awake()):!1===t._started?(t._started=!0,t.start&&t.start()):!0===t._awoken&&!0===t._started&&(!0===t._delyed&&(t._delyed=!1,e.ScriptComponent.ReadyInstance(t)),t.update&&t.update(),t._lateUpdate=!0))},t.LateInstance=function(t){!0===e.SceneManager.ScenePlaying&&null!=t&&null!=t.transform&&t.transform.isEnabled(!1)&&!0===t._lateUpdate&&(t._lateUpdate=!1,!0===t._started&&t.late&&t.late())},t.AfterInstance=function(t){!0===e.SceneManager.ScenePlaying&&null!=t&&null!=t.transform&&t.transform.isEnabled(!1)&&!0===t._started&&t.after&&t.after()},t.StepInstance=function(t){!0===e.SceneManager.ScenePlaying&&null!=t&&null!=t.transform&&!0===t._started&&t.step&&t.step()},t.FixedInstance=function(t){!0===e.SceneManager.ScenePlaying&&null!=t&&null!=t.transform&&!0===t._started&&t.fixed&&t.fixed()},t.ReadyInstance=function(e){null!=e&&null!=e.transform&&!1===e._scriptReady&&(e._scriptReady=!0,e.ready&&e.ready())},t.ResetInstance=function(e){null!=e&&null!=e.transform&&!0===e._started&&e.reset&&e.reset()},t.DestroyInstance=function(t){if(null!=t){t.scene.unregisterBeforeRender(t._update),null!=t._lateUpdateObserver&&null!=t.scene.onBeforeRenderTargetsRenderObservable&&t.scene.onBeforeRenderTargetsRenderObservable.remove(t._lateUpdateObserver),t.after&&null!=t._after&&t.scene.unregisterAfterRender(t._after),t.step&&null!=t._step&&t.removeStepComponentInstance(t),t.fixed&&null!=t._fixed&&t.removeFixedComponentInstance(t);var n=e.Utilities.GetHavokPlugin();if(null!=n){if(null!=t._bodyCollisionObserver)try{t._bodyCollisionObserver.remove()}catch(e){}if(null!=t._bodyCollisionEndedObserver)try{t._bodyCollisionEndedObserver.remove()}catch(e){}if(null!=t._worldTriggerEventObserver)try{n.onTriggerCollisionObservable.remove(t._worldTriggerEventObserver)}catch(e){}}try{t.onCollisionEnterObservable.clear()}catch(e){}try{t.onCollisionStayObservable.clear()}catch(e){}try{t.onCollisionExitObservable.clear()}catch(e){}try{t.onTriggerEnterObservable.clear()}catch(e){}try{t.onTriggerExitObservable.clear()}catch(e){}try{t.destroy&&t.destroy()}catch(e){}t._scriptReady=!1,t._transform=null,t._properties=null,t._started=!1,t._delyed=!1,t._update=null,t._late=null,t._step=null,t._fixed=null,t._after=null,t._ready=null,t._scene=null}},t.ParseAutoProperties=function(t){var n=Object.keys(t._properties);if(null!=n&&n.length>0)for(var i=function(i){var r=n[i];if(e.Utilities.StartsWith(r,"auto__")){var o=r.replace("auto__","");if(e.Utilities.HasOwnProperty(t,o)){var a=t.getProperty(r);if(null!=a){var s=typeof a;if(null!=s&&""!==s)if("object"===s)if(Array.isArray(a)){var l=[];a.forEach(function(n){null!=n&&("object"==typeof n?l.push(e.ScriptComponent.UnpackObjectProperty(n,t.scene)):l.push(n))}),t[o]=l}else{var u=t[o],c=e.ScriptComponent.UnpackObjectProperty(a,t.scene);u instanceof BABYLON.Color3&&c instanceof BABYLON.Color4?t[o]=new BABYLON.Color3(c.r,c.g,c.b):t[o]=c}else t[o]=a;else t[o]=a}else t[o]=a}else BABYLON.Tools.Warn(t.getClassName()||"Unregistered Class: Auto property '"+o+"' not found for transform '"+t.transform.name+"'")}},r=0;r<n.length;r++)i(r)},t.UnpackObjectProperty=function(t,n){var i=null;if(null!=t)if(void 0!==t.x&&void 0!==t.y)i=void 0!==t.z?void 0!==t.w?new BABYLON.Vector4(t.x,t.y,t.z,t.w):new BABYLON.Vector3(t.x,t.y,t.z):new BABYLON.Vector2(t.x,t.y);else if(void 0!==t.r&&void 0!==t.g&&void 0!==t.b){var r=1;void 0!==t.a&&(r=t.a),i=new BABYLON.Color4(t.r,t.g,t.b,r)}else if(void 0!==t.type)switch(t.type){case"UnityEngine.AnimationCurve":var o=t;i=BABYLON.Animation.Parse(o.animation);break;case"UnityEngine.Transform":var a=t;i=e.Utilities.ParseTransformByID(a,n);break;case"UnityEngine.Material":var s=t;i=n.getMaterialByName(s.name);break;case"UnityEngine.Texture2D":var l=t;i=e.Utilities.ParseTexture(l,n);break;case"UnityEngine.Cubemap":var u=t;i=e.Utilities.ParseCubemap(u,n);break;case"UnityEngine.AudioClip":case"UnityEngine.Video.VideoClip":case"UnityEngine.Font":default:i=t;break;case"UnityEngine.TextAsset":var c=t;i=null!=c.base64?!0===c.json?JSON.parse(e.WindowManager.Atob(c.base64)):e.WindowManager.Atob(c.base64):c;break;case"UnityEditor.DefaultAsset":var d=t;i=null!=d.base64?!0===d.json?JSON.parse(e.WindowManager.Atob(d.base64)):e.WindowManager.Atob(d.base64):d}else i=t;return i},t}();e.ScriptComponent=t;var n=function(t){function n(e,n,i,r){void 0===i&&(i={}),void 0===r&&(r=null);var o=t.call(this,e,n,i,r)||this;return o.autoHideSplashScreen=!0,o.postCreateSceneDelayMs=1e3,o.hideSplashScreenDelayMs=3e3,o.createSceneHandled=!1,o}return r(n,t),n.prototype.preCreateScene=function(t){return a(this,void 0,void 0,function(){var n=this;return s(this,function(i){return this.createSceneHandled||(this.createSceneHandled=!0,e.WindowManager.SetTimeout(this.postCreateSceneDelayMs,function(){return a(n,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return[4,this.postCreateScene(t)];case 1:return e.sent(),[2]}})})})),[2]})})},n.prototype.postCreateScene=function(t){return a(this,void 0,void 0,function(){var n;return s(this,function(i){switch(i.label){case 0:return i.trys.push([0,3,4,5]),this.createScene?[4,this.createScene(t)]:[3,2];case 1:i.sent(),i.label=2;case 2:return[3,5];case 3:return n=i.sent(),console.error("Failed to initialize game mode",n),[3,5];case 4:return this.autoHideSplashScreen&&e.SceneManager.HideSplashScreen(this.scene,this.hideSplashScreenDelayMs),[7];case 5:return[2]}})})},n}(e.ScriptComponent);e.GameModeController=n}(i||(i={})),function(e){var t,n,i,o,a,s,l,u,c,d,h,p,m,f,g,v,y;(y=e.System||(e.System={}))[y.Deg2Rad=2*Math.PI/360]="Deg2Rad",y[y.Rad2Deg=1/e.System.Deg2Rad]="Rad2Deg",y[y.Epsilon=1e-6]="Epsilon",y[y.SingleEpsilon=1401298e-51]="SingleEpsilon",y[y.EpsilonNormalSqrt=1e-15]="EpsilonNormalSqrt",y[y.Kph2Mph=.621371]="Kph2Mph",y[y.Mph2Kph=1.60934]="Mph2Kph",y[y.Mps2Kph=3.6]="Mps2Kph",y[y.Mps2Mph=2.23694]="Mps2Mph",y[y.Meter2Inch=39.3701]="Meter2Inch",y[y.Inch2Meter=.0254]="Inch2Meter",y[y.Gravity=9.81]="Gravity",y[y.Gravity3G=29.400000000000002]="Gravity3G",y[y.SkidFactor=.25]="SkidFactor",y[y.MaxInteger=2147483647]="MaxInteger",y[y.WalkingVelocity=4.4]="WalkingVelocity",y[y.TerminalVelocity=55]="TerminalVelocity",y[y.SmoothDeltaFactor=.2]="SmoothDeltaFactor",y[y.ToLinearSpace=2.2]="ToLinearSpace",y[y.ToGammaSpace=.45454545454545453]="ToGammaSpace",(v=e.Handedness||(e.Handedness={}))[v.Default=-1]="Default",v[v.Right=0]="Right",v[v.Left=1]="Left",(g=e.SearchType||(e.SearchType={}))[g.ExactMatch=0]="ExactMatch",g[g.StartsWith=1]="StartsWith",g[g.EndsWith=2]="EndsWith",g[g.IndexOf=3]="IndexOf",(f=e.PlayerNumber||(e.PlayerNumber={}))[f.Auto=0]="Auto",f[f.One=1]="One",f[f.Two=2]="Two",f[f.Three=3]="Three",f[f.Four=4]="Four",(m=e.PlayerControl||(e.PlayerControl={}))[m.FirstPerson=0]="FirstPerson",m[m.ThirdPerson=1]="ThirdPerson",(p=e.RenderQuality||(e.RenderQuality={}))[p.High=0]="High",p[p.Medium=1]="Medium",p[p.Low=2]="Low",(h=e.GamepadType||(e.GamepadType={}))[h.None=-1]="None",h[h.Generic=0]="Generic",h[h.Xbox360=1]="Xbox360",h[h.DualShock=2]="DualShock",h[h.PoseController=3]="PoseController",(d=e.Xbox360Trigger||(e.Xbox360Trigger={}))[d.Left=0]="Left",d[d.Right=1]="Right",(c=e.MovementType||(e.MovementType={}))[c.DirectVelocity=0]="DirectVelocity",c[c.AppliedForces=1]="AppliedForces",(u=e.CollisionContact||(e.CollisionContact={}))[u.Top=0]="Top",u[u.Left=1]="Left",u[u.Right=2]="Right",u[u.Bottom=3]="Bottom",(l=e.IntersectionPrecision||(e.IntersectionPrecision={}))[l.AABB=0]="AABB",l[l.OBB=1]="OBB",(s=e.CollisionFilters||(e.CollisionFilters={}))[s.DefaultFilter=1]="DefaultFilter",s[s.StaticFilter=2]="StaticFilter",s[s.KinematicFilter=4]="KinematicFilter",s[s.DebrisFilter=8]="DebrisFilter",s[s.SensorTrigger=16]="SensorTrigger",s[s.CharacterFilter=32]="CharacterFilter",s[s.AllFilter=-1]="AllFilter",(a=e.CollisionState||(e.CollisionState={}))[a.ACTIVE_TAG=1]="ACTIVE_TAG",a[a.ISLAND_SLEEPING=2]="ISLAND_SLEEPING",a[a.WANTS_DEACTIVATION=3]="WANTS_DEACTIVATION",a[a.DISABLE_DEACTIVATION=4]="DISABLE_DEACTIVATION",a[a.DISABLE_SIMULATION=5]="DISABLE_SIMULATION",(o=e.CollisionFlags||(e.CollisionFlags={}))[o.CF_STATIC_OBJECT=1]="CF_STATIC_OBJECT",o[o.CF_KINEMATIC_OBJECT=2]="CF_KINEMATIC_OBJECT",o[o.CF_NO_CONTACT_RESPONSE=4]="CF_NO_CONTACT_RESPONSE",o[o.CF_CUSTOM_MATERIAL_CALLBACK=8]="CF_CUSTOM_MATERIAL_CALLBACK",o[o.CF_CHARACTER_OBJECT=16]="CF_CHARACTER_OBJECT",o[o.CF_DISABLE_VISUALIZE_OBJECT=32]="CF_DISABLE_VISUALIZE_OBJECT",o[o.CF_DISABLE_SPU_COLLISION_PROCESSING=64]="CF_DISABLE_SPU_COLLISION_PROCESSING",o[o.CF_HAS_CONTACT_STIFFNESS_DAMPING=128]="CF_HAS_CONTACT_STIFFNESS_DAMPING",o[o.CF_HAS_CUSTOM_DEBUG_RENDERING_COLOR=256]="CF_HAS_CUSTOM_DEBUG_RENDERING_COLOR",o[o.CF_HAS_FRICTION_ANCHOR=512]="CF_HAS_FRICTION_ANCHOR",o[o.CF_HAS_COLLISION_SOUND_TRIGGER=1024]="CF_HAS_COLLISION_SOUND_TRIGGER",(i=e.UserInputPointer||(e.UserInputPointer={}))[i.Left=0]="Left",i[i.Middle=1]="Middle",i[i.Right=2]="Right",(n=e.UserInputAxis||(e.UserInputAxis={}))[n.Horizontal=0]="Horizontal",n[n.Vertical=1]="Vertical",n[n.ClientX=2]="ClientX",n[n.ClientY=3]="ClientY",n[n.MouseX=4]="MouseX",n[n.MouseY=5]="MouseY",n[n.Wheel=6]="Wheel",(t=e.UserInputKey||(e.UserInputKey={}))[t.BackSpace=8]="BackSpace",t[t.Tab=9]="Tab",t[t.Enter=13]="Enter",t[t.Shift=16]="Shift",t[t.Ctrl=17]="Ctrl",t[t.Alt=18]="Alt",t[t.Pause=19]="Pause",t[t.Break=19]="Break",t[t.CapsLock=20]="CapsLock",t[t.Escape=27]="Escape",t[t.SpaceBar=32]="SpaceBar",t[t.PageUp=33]="PageUp",t[t.PageDown=34]="PageDown",t[t.End=35]="End",t[t.Home=36]="Home",t[t.LeftArrow=37]="LeftArrow",t[t.UpArrow=38]="UpArrow",t[t.RightArrow=39]="RightArrow",t[t.DownArrow=40]="DownArrow",t[t.Insert=45]="Insert",t[t.Delete=46]="Delete",t[t.Num0=48]="Num0",t[t.Num1=49]="Num1",t[t.Num2=50]="Num2",t[t.Num3=51]="Num3",t[t.Num4=52]="Num4",t[t.Num5=53]="Num5",t[t.Num6=54]="Num6",t[t.Num7=55]="Num7",t[t.Num8=56]="Num8",t[t.Num9=57]="Num9",t[t.A=65]="A",t[t.B=66]="B",t[t.C=67]="C",t[t.D=68]="D",t[t.E=69]="E",t[t.F=70]="F",t[t.G=71]="G",t[t.H=72]="H",t[t.I=73]="I",t[t.J=74]="J",t[t.K=75]="K",t[t.L=76]="L",t[t.M=77]="M",t[t.N=78]="N",t[t.O=79]="O",t[t.P=80]="P",t[t.Q=81]="Q",t[t.R=82]="R",t[t.S=83]="S",t[t.T=84]="T",t[t.U=85]="U",t[t.V=86]="V",t[t.W=87]="W",t[t.X=88]="X",t[t.Y=89]="Y",t[t.Z=90]="Z",t[t.LeftWindowKey=91]="LeftWindowKey",t[t.RightWindowKey=92]="RightWindowKey",t[t.SelectKey=93]="SelectKey",t[t.Numpad0=96]="Numpad0",t[t.Numpad1=97]="Numpad1",t[t.Numpad2=98]="Numpad2",t[t.Numpad3=99]="Numpad3",t[t.Numpad4=100]="Numpad4",t[t.Numpad5=101]="Numpad5",t[t.Numpad6=102]="Numpad6",t[t.Numpad7=103]="Numpad7",t[t.Numpad8=104]="Numpad8",t[t.Numpad9=105]="Numpad9",t[t.Multiply=106]="Multiply",t[t.Add=107]="Add",t[t.Subtract=109]="Subtract",t[t.DecimalPoint=110]="DecimalPoint",t[t.Divide=111]="Divide",t[t.F1=112]="F1",t[t.F2=113]="F2",t[t.F3=114]="F3",t[t.F4=115]="F4",t[t.F5=116]="F5",t[t.F6=117]="F6",t[t.F7=118]="F7",t[t.F8=119]="F8",t[t.F9=120]="F9",t[t.F10=121]="F10",t[t.F11=122]="F11",t[t.F12=123]="F12",t[t.NumLock=144]="NumLock",t[t.ScrollLock=145]="ScrollLock",t[t.SemiColon=186]="SemiColon",t[t.EqualSign=187]="EqualSign",t[t.Comma=188]="Comma",t[t.Dash=189]="Dash",t[t.Period=190]="Period",t[t.ForwardSlash=191]="ForwardSlash",t[t.GraveAccent=192]="GraveAccent",t[t.OpenBracket=219]="OpenBracket",t[t.BackSlash=220]="BackSlash",t[t.CloseBraket=221]="CloseBraket",t[t.SingleQuote=222]="SingleQuote";var _=function(){function e(){}return e.KeyboardSmoothing=!1,e.KeyboardMoveSensibility=3,e.KeyboardArrowSensibility=1,e.KeyboardMoveDeadZone=.001,e.GamepadDeadStickValue=.15,e.GamepadLStickXInverted=!1,e.GamepadLStickYInverted=!1,e.GamepadRStickXInverted=!1,e.GamepadRStickYInverted=!0,e.GamepadLStickSensibility=1,e.GamepadRStickSensibility=1,e.SupportedInputDevices=null,e.BabylonAngularSensibility=2e3,e.DefaultAngularSensibility=.5,e.PointerWheelDeadZone=.1,e.PointerMouseDeadZone=.1,e.PointerMouseInverted=!0,e.UseCanvasElement=!0,e.UseArrowKeyRotation=!1,e.EnableBabylonRotation=!1,e}();e.UserInputOptions=_;e.RequestHeader=function(){};e.TriggerVolume=function(){this.mesh=null,this.state=0};e.RoomErrorMessage=function(){};var S=function(){function e(e,t,n,i,r){void 0===n&&(n=!0),void 0===i&&(i=null),void 0===r&&(r=null),this.loadingDivId=e,this.loadingUIText=t,this.hideLoadingUIWithEngine=n,this.customInnerHtml=i,this.customInnerCss=r,this.loadingUIBackgroundColor="#000000",null!=this.loadingDivId&&""!==this.loadingDivId||(this.loadingDivId="customLoadingScreen"),null!=this.loadingUIText&&""!==this.loadingUIText||(this.loadingUIText="Please Wait")}return e.prototype.displayLoadingUI=function(){if(this.hasLoadingDiv())this.showLoadingDiv(!0);else{var e=document.createElement("style");e.type="text/css",e.innerHTML=this.customInnerCss||"",document.getElementsByTagName("head")[0].appendChild(e);var t=this.loadingUIText,n=document.createElement("div");n.id=this.loadingDivId,n.innerHTML=this.customInnerHtml||t,document.body.appendChild(n)}},e.prototype.hideLoadingUI=function(){!0===this.hideLoadingUIWithEngine&&this.showLoadingDiv(!1)},e.prototype.showLoadingDiv=function(e){var t=this.getLoadingDiv();null!=t&&(t.style.display=e?"initial":"none")},e.prototype.getLoadingDiv=function(){return document.getElementById(this.loadingDivId)},e.prototype.hasLoadingDiv=function(){return null!=document.getElementById(this.loadingDivId)},e}();e.CustomLoadingScreen=S;var A=function(){function e(){this.ListenerDictionary={}}return e.prototype.OnMessage=function(e,t){var n;null==this.ListenerDictionary[e]?(n=[],this.ListenerDictionary[e]=n):n=this.ListenerDictionary[e],n.findIndex(function(e){return t==e})<0&&n.push(t)},e.prototype.PostMessage=function(e,t){void 0===t&&(t=null);var n=this.ListenerDictionary[e];null!=n&&n.forEach(function(e){try{e&&e(t)}catch(e){console.warn(e)}})},e.prototype.RemoveHandler=function(e,t){var n=this.ListenerDictionary[e];if(null!=n){var i=n.findIndex(function(e){return t==e});i>=0&&n.splice(i,1)}},e.prototype.ResetHandlers=function(){this.ListenerDictionary={}},e.prototype.Dispose=function(){this.ResetHandlers()},e}();e.LocalMessageBus=A;var b=function(){function e(){this.ListenerDictionary={},window&&window.top?(this.HandleWindowMessage=this.HandleWindowMessage.bind(this),window.top.addEventListener("message",this.HandleWindowMessage)):console.warn("GlobalMessageBus: No Top Window Available")}return e.prototype.OnMessage=function(e,t){var n;null==this.ListenerDictionary[e]?(n=[],this.ListenerDictionary[e]=n):n=this.ListenerDictionary[e],n.findIndex(function(e){return t==e})<0&&n.push(t)},e.prototype.PostMessage=function(e,t,n,i){void 0===t&&(t=null),void 0===n&&(n="*"),window&&window.top?window.top.postMessage({source:"eventbus",message:e,data:t},n,i):console.warn("GlobalMessageBus: No Top Window Available")},e.prototype.RemoveHandler=function(e,t){var n=this.ListenerDictionary[e];if(null!=n){var i=n.findIndex(function(e){return t==e});i>=0&&n.splice(i,1)}},e.prototype.ResetHandlers=function(){this.ListenerDictionary={}},e.prototype.Dispose=function(){this.ResetHandlers(),window&&window.top&&window.top.removeEventListener("message",this.HandleWindowMessage)},e.prototype.HandleWindowMessage=function(e){null!=e&&null!=e.data&&null!=e.data.message&&null!=e.data.source&&"eventbus"==e.data.source&&this.OnDispatchMessage(e.data.message,null!=e.data.data?e.data.data:null)},e.prototype.OnDispatchMessage=function(e,t){void 0===t&&(t=null);var n=this.ListenerDictionary[e];null!=n&&n.forEach(function(e){try{e&&e(t)}catch(e){console.warn(e)}})},e}();e.GlobalMessageBus=b;var M=function(){function t(e,t,n,i,r,o){void 0===n&&(n=1),void 0===i&&(i=!0),void 0===r&&(r=!1),void 0===o&&(o=!0),this.prefabName=null,this.allowGrowth=!0,this.assetContainer=null,this.cloneAnimations=!0,this.makeNewMaterials=!1,this.availableInstances=null,this.prefabName=t,this.allowGrowth=i,this.assetContainer=e,this.cloneAnimations=o,this.makeNewMaterials=r,this.availableInstances=[],this.populatePool(n)}return t.prototype.getAvailableCount=function(){return this.availableInstances.length},t.prototype.populatePool=function(e){if(e>0)for(var t=0;t<e;t++){var n=this.createNewInstance();null!=n&&this.freeInstance(n)}},t.prototype.getInstance=function(e,t){void 0===e&&(e=null),void 0===t&&(t=null);var n=this.availableInstances.length>0?this.availableInstances.pop():this.appendNewInstance();return null!=n&&(null!=e?n.position.copyFrom(e):n.position.set(0,0,0),null!=t?null!=n.rotationQuaternion?n.rotationQuaternion.copyFrom(t):n.rotationQuaternion=t.clone():null!=n.rotationQuaternion?n.rotationQuaternion.set(0,0,0,1):n.rotationQuaternion=new BABYLON.Quaternion(0,0,0,1),n.name=this.prefabName+".Instance",n.setEnabled(!0)),n},t.prototype.freeInstance=function(e){null!=e&&(e.setEnabled(!1),e.position.set(0,0,0),null!=e.rotationQuaternion?e.rotationQuaternion.set(0,0,0,1):e.rotationQuaternion=new BABYLON.Quaternion(0,0,0,1),null!=e.metadata&&null!=e.metadata.toolkit&&null!=e.metadata.toolkit.components&&e.metadata.toolkit.components.forEach(function(e){if(null!=e)try{e.resetScriptComponent()}catch(e){}}),e.name=this.prefabName+".Unassigned",this.availableInstances.push(e))},t.prototype.appendNewInstance=function(){var e=null;return!0===this.allowGrowth&&(e=this.createNewInstance()),e},t.prototype.createNewInstance=function(t,n,i,r){void 0===t&&(t=null),void 0===n&&(n=null),void 0===i&&(i=null),void 0===r&&(r=null);var o=null;return null!=this.assetContainer&&null!=this.prefabName&&""!==this.prefabName&&(this.assetContainer instanceof BABYLON.AssetContainer?o=e.SceneManager.InstantiatePrefabFromContainer(this.assetContainer,this.prefabName,this.prefabName+".Instance",t,n,i,r,this.cloneAnimations,this.makeNewMaterials):this.assetContainer instanceof BABYLON.Scene&&(o=e.SceneManager.InstantiatePrefabFromScene(this.assetContainer,this.prefabName,this.prefabName+".Instance",t,n,i,r,this.cloneAnimations))),o},t}();e.PrefabObjectPool=M;var B=function(){function e(){this._hit=!1,this._dest=new BABYLON.Vector3(0,0,0),this._origin=new BABYLON.Vector3(0,0,0),this._hitPoint=new BABYLON.Vector3(0,0,0),this._hitNormal=new BABYLON.Vector3(0,0,0),this._hitDistance=0,this._collisionObject=null,this.reset(BABYLON.Vector3.Zero(),BABYLON.Vector3.Zero())}return Object.defineProperty(e.prototype,"hasHit",{get:function(){return this._hit},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hitPoint",{get:function(){return this._hitPoint},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hitNormal",{get:function(){return this._hitNormal},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hitDistance",{get:function(){return this._hitDistance},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"collisionObject",{get:function(){return this._collisionObject},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"rayDestination",{get:function(){return this._dest},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"rayOrigin",{get:function(){return this._origin},enumerable:!1,configurable:!0}),e.prototype.reset=function(e,t){this._hit=!1,this._hitPoint.set(0,0,0),this._hitNormal.set(0,0,0),this._hitDistance=0,this._collisionObject=null,this._origin.copyFrom(e),this._dest.copyFrom(t)},e.prototype.update=function(e,t,n,i,r,o,a,s){void 0===s&&(s=null),this._hit=e,this._hitPoint.set(t,n,i),this._hitNormal.set(r,o,a),this._hitDistance=BABYLON.Vector3.Distance(this._origin,this.hitPoint),this._collisionObject=s},e}();e.RaycastHitResult=B;var C=function(){function t(e,t,n,i){void 0===n&&(n=0),void 0===i&&(i=.5),this._numPoints=-1,this._pointMesh=null,this._pointSize=.5,this._pointType=0,this._linesName="MeshLines",this._linesMesh=null,this._babylonScene=null,this._pointMesh=null,this._linesMesh=null,this._linesName=e,this._babylonScene=t,this._pointType=n,this._pointSize=i}return Object.defineProperty(t.prototype,"pointMesh",{get:function(){return this._pointMesh},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"linesMesh",{get:function(){return this._linesMesh},enumerable:!1,configurable:!0}),t.prototype.dispose=function(e){void 0===e&&(e=!0),this._babylonScene=null,this._linesName=null,null!=this._pointMesh&&(this._pointMesh.dispose(e),this._pointMesh=null),null!=this._linesMesh&&(this._linesMesh.dispose(e),this._linesMesh=null)},t.prototype.hidePoint=function(e){void 0===e&&(e=!0),null!=this._pointMesh&&(this._pointMesh.isVisible=!e)},t.prototype.drawPoint=function(t){null==this._pointMesh&&(1===this._pointType?(this._pointMesh=BABYLON.MeshBuilder.CreateBox(this._linesName+".EndPoint",{size:2*this._pointSize},this._babylonScene),this._pointMesh.renderingGroupId=e.Utilities.DefaultRenderGroup(),this._pointMesh.visibility=.25):(this._pointMesh=BABYLON.MeshBuilder.CreateSphere(this._linesName+".EndPoint",{segments:24,diameter:2*this._pointSize},this._babylonScene),this._pointMesh.renderingGroupId=e.Utilities.DefaultRenderGroup(),this._pointMesh.visibility=.25)),null!=this._pointMesh&&(this._pointMesh.isVisible=!0,this._pointMesh.position.copyFrom(t))},t.prototype.drawLine=function(t,n){void 0===n&&(n=null),null==this._linesMesh?(this._numPoints=t.length,this._linesMesh=BABYLON.MeshBuilder.CreateLines(this._linesName,{points:t,updatable:!0},this._babylonScene),this._linesMesh.renderingGroupId=e.Utilities.DefaultRenderGroup(),null!=n&&(this._linesMesh.color=n),this._linesMesh.refreshBoundingInfo(!1)):t.length===this._numPoints?(this._linesMesh=BABYLON.MeshBuilder.CreateLines(this._linesName,{points:t,instance:this._linesMesh},this._babylonScene),this._linesMesh.renderingGroupId=e.Utilities.DefaultRenderGroup(),null!=n&&(this._linesMesh.color=n),this._linesMesh.refreshBoundingInfo(!1)):BABYLON.Tools.Warn("Dynamic line mesh point count mismatch for "+this._linesName)},t}();e.LinesMeshRenderer=C;var T=function(t){function n(){return null!==t&&t.apply(this,arguments)||this}return r(n,t),n.prototype.addContainerTask=function(e,t,n,i){var r=this,o=new BABYLON.ContainerAssetTask(e,t,n,i),a=o;return a._lengthComputable=0,a._loaded=0,a._total=0,a.runTask=function(e,t,n){BABYLON.SceneLoader.LoadAssetContainer(o.rootUrl,o.sceneFilename,e,function(e){o.loadedContainer=e,o.loadedMeshes=e.meshes,o.loadedParticleSystems=e.particleSystems,o.loadedSkeletons=e.skeletons,o.loadedAnimationGroups=e.animationGroups,t()},function(e){a._lengthComputable=e.lengthComputable,a._loaded=e.loaded,a._total=e.total,r.handlePreloadingProgress()},function(e,t,i){n(t,i)})},this._tasks.push(o),o},n.prototype.addMeshTask=function(e,t,n,i){var r=this,o=new BABYLON.MeshAssetTask(e,t,n,i),a=o;return a._lengthComputable=0,a._loaded=0,a._total=0,a.runTask=function(e,t,n){BABYLON.SceneLoader.ImportMesh(o.meshesNames,o.rootUrl,o.sceneFilename,e,function(e,n,i,r){o.loadedMeshes=e,o.loadedParticleSystems=n,o.loadedSkeletons=i,o.loadedAnimationGroups=r,t()},function(e){a._lengthComputable=e.lengthComputable,a._loaded=e.loaded,a._total=e.total,r.handlePreloadingProgress()},function(e,t,i){n(t,i)})},this._tasks.push(o),o},n.prototype.addTextFileTask=function(e,t){var n=this,i=new BABYLON.TextFileAssetTask(e,t),r=i;return r._lengthComputable=0,r._loaded=0,r._total=0,r.runTask=function(e,t,o){e._loadFile(i.url,function(e){i.text=e,t()},function(e){r._lengthComputable=e.lengthComputable,r._loaded=e.loaded,r._total=e.total,n.handlePreloadingProgress()},!1,!1,function(e,t){e&&o(e.status+" "+e.statusText,t)})},this._tasks.push(i),i},n.prototype.addBinaryFileTask=function(e,t){var n=this,i=new BABYLON.BinaryFileAssetTask(e,t),r=i;return r._lengthComputable=0,r._loaded=0,r._total=0,r.runTask=function(e,t,o){e._loadFile(i.url,function(e){i.data=e,t()},function(e){r._lengthComputable=e.lengthComputable,r._loaded=e.loaded,r._total=e.total,n.handlePreloadingProgress()},!0,!0,function(e,t){e&&o(e.status+" "+e.statusText,t)})},this._tasks.push(i),i},n.prototype.addImageTask=function(e,t){var n=this,i=new BABYLON.ImageAssetTask(e,t),r=i;return r._lengthComputable=0,r._loaded=0,r._total=0,r.runTask=function(e,t,o){var a=new HTMLImageElement;BABYLON.Tools.SetCorsBehavior(i.url,a),a.onload=function(){i.image=a,t()},a.onerror=function(e){o("Error loading image",e)},a.onprogress=function(e){r._lengthComputable=e.lengthComputable,r._loaded=e.loaded,r._total=e.total,n.handlePreloadingProgress()},a.src=i.url},this._tasks.push(i),i},n.prototype.handlePreloadingProgress=function(){var t=!0,n=0,i=0;if(null!=this._tasks&&this._tasks.length>0)for(var r=0;r<this._tasks.length;r++){var o=this._tasks[r];null!=o._lengthComputable&&null!=o._loaded&&null!=o._total&&(t=t&&o._lengthComputable,n+=o._loaded,i+=o._total)}if(null!=e.SceneManager.OnAssetManagerProgress){var a={lengthComputable:t,loaded:n,total:t?i:0};e.SceneManager.OnAssetManagerProgress(a)}},n}(BABYLON.AssetsManager);e.PreloadAssetsManager=T;var x=function(){function e(){}return e.HasNetworkEntity=function(e){return null!=e&&null!=e.networkEntity},e.GetNetworkEntityId=function(e){return null==e?null:null!=e.networkEntity?e.networkEntity.id:null},e.GetNetworkEntityType=function(e){return null==e?0:null!=e.networkEntityType?e.networkEntityType:0},e.GetNetworkEntitySessionId=function(e){return null==e?null:null!=e.networkEntity?e.networkEntity.ownerId:null},e.QueryNetworkAttribute=function(e,t){var n=null;return null!=e&&null!=e.networkEntity&&null!=e.networkEntity.attributes&&(n=e.networkEntity.attributes.get(t)),n},e.QueryBufferedAttribute=function(e,t){var n=0;return null!=e&&null!=e.networkEntityAttributeBuffer&&(n=e.networkEntityAttributeBuffer[t.toFixed(0)]),n},e.PostBufferedAttribute=function(e,t,n){null==e.networkEntityBatch&&(e.networkEntityBatch={}),e.networkEntityBatch[t.toFixed(0)]=n},e}();e.EntityController=x}(i||(i={})),BABYLON.Bone.prototype.linkTransformNode=function(e){e._linkedBone=this,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++},function(e){var t;(t=e.MaterialAlphaMode||(e.MaterialAlphaMode={})).OPAQUE="OPAQUE",t.MASK="MASK",t.BLEND="BLEND";e.CubeTextureLoader=function(){};var n=function(){function t(t){this.name=e.SceneManager.CVTOOLS_NAME,this.enabled=!1,this._webgpu=!1,this._babylonScene=null,this._metadataParser=null,this._loaderScene=null,this._assetsManager=null,this._materialMap=null,this._lightmapMap=null,this._reflectionMap=null,this._reflectionCache=null,this._assetContainer=!1,this._activeMeshes=!1,this._parseScene=!1,this._leftHanded=!1,this._disposeRoot=!1,this._sceneParsed=!1,this._preWarmTime=1,this._hideLoader=!1,this._rootUrl=null,this._fileName="Unknown",this._licenseName="Unknown",this._licenseType="standard",this._pendingReflectionTextures=null,this._loader=t,this._pendingReflectionTextures=new Map,this.enabled=this._loader.isExtensionUsed(e.SceneManager.CVTOOLS_NAME)||this._loader.isExtensionUsed(e.SceneManager.CVTOOLS_HAND)||this._loader.isExtensionUsed(e.SceneManager.CVTOOLS_MESH),this._parseScene=this._leftHanded=this._disposeRoot=this._sceneParsed=!1,this._rootUrl=null,this._masterList=null,this._detailList=null,this._parserList=null,this._shaderList=null,this._readyList=null,this._preloadList=null,this._materialMap=null,this._lightmapMap=null,this._preWarmTime=1,this._hideLoader=!1,this._loaderScene=null,this._assetsManager=null,this._reflectionMap=null,this._reflectionCache=null,this._animationGroups=null,this._metadataParser=null,this._babylonScene=null,this.order=100}return t.prototype.dispose=function(){delete this._loader},t.prototype.onLoading=function(){var t=this;e.Utilities.LoadingState=0,this._assetContainer=null!=this._loader._assetContainer,this._metadataParser=null,this._babylonScene=this._loader.babylonScene,this._loaderScene=null,this._assetsManager=null,this._rootUrl=this._loader.rootUrl?this._loader.rootUrl:"/",this._fileName=this._loader._fileName?this._loader._fileName:"Unknown",this._fileName.indexOf("?")>=0&&(this._fileName=this._fileName.split("?")[0]),e.SceneManager.SetRootUrl(this._babylonScene,this._rootUrl),e.SceneManager.SetSceneFile(this._babylonScene,this._fileName),this._loader.parent.onCompleteObservable.addOnce(function(){t.onComplete()}),this._loader.parent.onValidatedObservable.addOnce(function(){t.onValidate()}),this._parseScene=this._loader.isExtensionUsed(e.SceneManager.CVTOOLS_NAME)&&!0===e.SceneManager.IsSceneParsingEnabled(),this._leftHanded=this._loader.isExtensionUsed(e.SceneManager.CVTOOLS_HAND),this._disposeRoot=this._sceneParsed=!1,this._animationGroups=[],this._masterList=[],this._detailList=[],this._parserList=[],this._shaderList=[],this._readyList=[],this._preloadList=[],this._materialMap=new Map,this._lightmapMap=new Map,this._preWarmTime=1,this._hideLoader=!1,this._reflectionMap={},this._reflectionCache={},e.Utilities.ResetLoaderItemsMarkedForDisposal(),this._webgpu=this._babylonScene.getEngine()instanceof BABYLON.WebGPUEngine,this._babylonScene.getEngine().getCaps().supportSRGBBuffers=e.SceneManager.SupportSRGBBuffers,!0===this._leftHanded&&null!=this._loader.rootBabylonMesh&&(this._loader.rootBabylonMesh.rotationQuaternion=BABYLON.Quaternion.Identity(),this._loader.rootBabylonMesh.scaling=BABYLON.Vector3.One()),!0===this._parseScene&&(e.SceneManager.RenderLoopReady=!1,null!=this._loader.rootBabylonMesh&&(this._loader.rootBabylonMesh.name="Root."+this._fileName.replace(".gltf","").replace(".glb","")),this.setupLoader())},t.prototype.onReady=function(){!0===this._parseScene&&!0===this._disposeRoot&&null!=this._loader.rootBabylonMesh&&this._loader.rootBabylonMesh.dispose(!0)},t.prototype.onComplete=function(){this._parseScene,this.finishComplete()},t.prototype.getScriptBundleTag=function(){var e=null,t=this._loaderScene,n=null!=t&&null!=t.extras&&null!=t.extras.metadata?t.extras.metadata:null;if(null!=n){null!=this._rootUrl&&this._rootUrl;var i=null!=n.script?n.script:null,r=null!=n.project?n.project:null;null!=i&&""!==i&&null!=r&&""!==r&&(e=r.toLocaleLowerCase())}return e},t.prototype.getScriptBundleUrl=function(){var e=null,t=this._loaderScene,n=null!=t&&null!=t.extras&&null!=t.extras.metadata?t.extras.metadata:null;if(null!=n){var i=null!=this._rootUrl?this._rootUrl:"/",r=null!=n.script?n.script:null,o=null!=n.project?n.project:null;null!=r&&""!==r&&null!=o&&""!==o&&(e=i+o)}return e},t.prototype.finishComplete=function(){var t=this;!0===this._parseScene&&(this.startParsing(),e.SceneManager.RenderLoopReady=!0,this._babylonScene.onAfterRenderObservable.addOnce(function(){e.Utilities.LoadingState=3,t._processPreloadTimeout()}))},t.prototype.onValidate=function(){this._parseScene},t.prototype.onCleanup=function(){this._fileName=null,this._rootUrl=null,this._parseScene=this._leftHanded=this._disposeRoot=this._sceneParsed=!1,this._masterList=null,this._detailList=null,this._parserList=null,this._shaderList=null,this._preWarmTime=1,this._readyList=null,this._preloadList=null,this._hideLoader=!1,this._animationGroups=null,null!=this._materialMap&&(this._materialMap.clear(),this._materialMap=null),null!=this._lightmapMap&&(this._lightmapMap.clear(),this._lightmapMap=null),this._loaderScene=null,this._assetsManager=null,this._reflectionMap=null,this._reflectionCache=null,this._metadataParser=null,this._babylonScene=null,null!=this._pendingReflectionTextures&&(this._pendingReflectionTextures.clear(),this._pendingReflectionTextures=null)},t.prototype.setupLoader=function(){var t=this,n=this._fileName;!0===this._parseScene&&(this._assetsManager=new e.PreloadAssetsManager(this._babylonScene),this._assetsManager.onProgress=function(t,n,i){if(!0===e.SceneManager.AutoUpdateProgress){var r="LOADING "+(n-t)+" OF "+n+(1===n?" ASSET":" ASSETS");e.WindowManager.UpdateLoaderDetails(r,e.Utilities.LoadingState)}else null!=e.Utilities.OnPreloaderProgress&&e.Utilities.OnPreloaderProgress(t,n,i)},this._assetsManager.onFinish=function(i){e.WindowManager.SetTimeout(100,function(){e.Utilities.LoadingState=4,!0===e.SceneManager.AutoUpdateProgress&&e.WindowManager.UpdateLoaderStatus("PLEASE WAIT","PREPARING SCENE VIEW",e.Utilities.LoadingState);var r=t._preWarmTime>0?1e3*t._preWarmTime:100;e.WindowManager.SetTimeout(r,function(){if(null!=e.Utilities.OnPreloaderComplete&&e.Utilities.OnPreloaderComplete(i),t._processShaderMaterials(t._babylonScene,t._shaderList),e.Utilities.RemoveLoaderItemsMarkedForDisposal(),null!=t._readyList&&t._readyList.length>0)for(var r=0;r<t._readyList.length;r++){var o=t._readyList[r];null!=o&&o._ready&&o._ready()}t._babylonScene.onAfterRenderObservable.addOnce(function(){var i=null!=n&&""!==n?n:"Unknown";null!=e.SceneManager.OnSceneReadyObservable&&e.SceneManager.OnSceneReadyObservable.notifyObservers(i),1==t._hideLoader&&e.WindowManager.HideSceneLoader(),t.onCleanup()})})})})},t.prototype.startParsing=function(){!0===this._parseScene&&(e.Utilities.LoadingState=2,this._processLevelOfDetail(this._babylonScene,this._detailList),this._processActiveMeshes(this._babylonScene,this._activeMeshes),this._processUnityMeshes(this._masterList),null!=this._loaderScene&&(this.preProcessSceneProperties(this._loaderScene,this._babylonScene),this.postProcessSceneProperties(this._rootUrl,this._loaderScene,this._babylonScene)),!1===this._assetContainer&&null!=this._parserList&&this._parserList.length>0&&(this._metadataParser=e.Utilities.PostParseSceneComponents(this._babylonScene,this._parserList,this._preloadList,this._readyList)),null!=this._loaderScene&&this.lateProcessSceneProperties(this._rootUrl,this._loaderScene,this._babylonScene))},t.prototype._processActiveMeshes=function(e,t){!0===t&&e.freeActiveMeshes()},t.prototype._processUnityMeshes=function(t){null!=t&&t.length>0&&t.forEach(function(t){e.Utilities.RegisterInstancedMeshBuffers(t)})},t.prototype._processPreloadTimeout=function(){if(null!=this._assetsManager){if(null!=this._preloadList&&this._preloadList.length>0)for(var e=0;e<this._preloadList.length;e++){var t=this._preloadList[e];null!=t&&t.addPreloaderTasks&&t.addPreloaderTasks(this._assetsManager)}this._babylonScene._preloaded=!0,this._assetsManager.load()}},t.prototype.loadSceneAsync=function(t,n){var i;return!0===this._parseScene&&(this._loaderScene=n,e.Utilities.LoadingState=1),this._parseScene&&(null===(i=n.extras)||void 0===i?void 0:i.metadata)?this._loadSceneInternalAsync(t,n):null},t.prototype._loadSceneInternalAsync=function(e,t){return a(this,void 0,void 0,function(){var n,i,r;return s(this,function(o){switch(o.label){case 0:return o.trys.push([0,3,,4]),n=t.extras.metadata,(null===(r=null==n?void 0:n.skybox)||void 0===r?void 0:r.environment)&&this.updateSkyboxEnvironment(n.skybox,this._babylonScene),[4,this._loader.loadSceneAsync(e,t)];case 1:return o.sent(),[4,this._loadSceneExAsync(e,t)];case 2:return o.sent(),[3,4];case 3:return i=o.sent(),console.error("CVTOOLS: Error in loadSceneAsync:",i),[3,4];case 4:return[2]}})})},t.prototype._loadSceneExAsync=function(t,n){return a(this,void 0,void 0,function(){var t,n,i,r,o,a,l,u,c,d=this;return s(this,function(s){if(t=this._loader,n=new Array,t._gltf.nodes)for(i=0,r=t._gltf.nodes;i<r.length;i++)(o=r[i])._babylonTransformNode&&this._animationGroups&&e.Utilities.AssignAnimationGroupsToNode(o._babylonTransformNode,this._animationGroups);if(null!=this._reflectionMap&&null!=this._reflectionCache)for(c in a=0,l=function(t){if(a++,u._reflectionMap.hasOwnProperty(t)){var n=t;if(null!=u._assetsManager){var i=u._assetsManager.addBinaryFileTask("Material.ReflectionTextureTask"+a.toFixed(0),n);i.onSuccess=function(t){if(null!=t.data){new Blob([t.data]);var i=d._reflectionMap[n];null!=i&&i.forEach(function(i){if(null!=i&&null!=i.mapkey){var r=d._reflectionCache[i.mapkey];if(null!=r)null!=i.material&&e.Utilities.HasOwnProperty(i.material,"reflectionTexture")&&(i.material.reflectionTexture=r);else{var o=d._babylonScene,a=t.data instanceof ArrayBuffer?new Uint8Array(t.data):t.data,s=".env"===(i.extension||"").toLowerCase()||i.mapkey&&i.mapkey.toLowerCase().endsWith(".env")?".env":".dds",l=new BABYLON.CubeTexture(n,o,{buffer:a,prefiltered:!0,forcedExtension:s,createPolynomials:!0,onLoad:function(){},onError:function(e,t){return console.error(e,t)}});l.name=i.name,l.level=i.reflectionProbePower*e.CVTOOLS_unity_metadata.IBL_PROBE_FACTOR,l.gammaSpace=!1,null!=i.boundingBoxSize&&(l.boundingBoxSize=i.boundingBoxSize),null!=i.boundingBoxPosition&&(l.boundingBoxPosition=i.boundingBoxPosition),d._reflectionCache[i.mapkey]=l,null!=i.material&&e.Utilities.HasOwnProperty(i.material,"reflectionTexture")&&(i.material.reflectionTexture=l)}}})}else console.error("Failed to load reflection texture task: "+n)},i.onError=function(e,t,n){console.error(t,n)}}}},u=this,this._reflectionMap)l(c);return t.logClose(),[2,Promise.all(n).then(function(){})]})})},t.prototype.loadNodeAsync=function(t,n,i){var r,o=this;if(!this._parseScene||!(null===(r=n.extras)||void 0===r?void 0:r.metadata))return null;try{return this._loader.loadNodeAsync(t,n,function(t){try{var r=t,a=n.extras.metadata;null==r.metadata&&(r.metadata={}),r.metadata.toolkit=a,e.Utilities.ValidateTransformGuid(r),e.Utilities.ValidateTransformMetadata(r),e.Utilities.ValidateTransformQuaternion(r),r.layerMask=null!=r.metadata.toolkit.layermask?r.metadata.toolkit.layermask:e.SceneManager.DefaultLayerMask,r.isVisible=null==r.metadata.toolkit.visible||r.metadata.toolkit.visible,r.visibility=null!=r.metadata.toolkit.visibility?r.metadata.toolkit.visibility:1,r.billboardMode=null!=r.metadata.toolkit.billboard?r.metadata.toolkit.billboard:0,!0===o._assetContainer&&(r.metadata.toolkit.prefab=!0),!0===r.metadata.toolkit.prefab?r.setEnabled(!1):(o._parserList.push(r),null!=n.extras.metadata.lods&&null!=n.extras.metadata.distances&&null!=o._detailList&&o._detailList.push(r)),o._masterList.push(r),i(r)}catch(e){console.error("CVTOOLS: Error in node assignment callback:",e),i(t)}})}catch(e){return console.error("CVTOOLS: Error in loadNodeAsync:",e),null}},t.prototype.loadMaterialPropertiesAsync=function(e,t,n){var i=this;return this.enabled?this._loader.loadMaterialPropertiesAsync(e,t,n).then(function(){var r,o=[];try{i._parseCommonConstantProperties(o,e,t,n)}catch(e){BABYLON.Tools.Warn("[CVTOOLS] _parseCommonConstantProperties threw for ".concat(null!==(r=null==t?void 0:t.name)&&void 0!==r?r:"material",": ").concat(e))}if(0!==o.length)return Promise.all(o.map(function(e){return e.catch(function(e){var n;BABYLON.Tools.Warn("[CVTOOLS] Extra material async failed for ".concat(null!==(n=null==t?void 0:t.name)&&void 0!==n?n:"material",": ").concat(e))})})).then(function(){})}):null},t.prototype._getCachedMaterialByIndex=function(e){var t=null;return e>=0&&null!=this._materialMap&&(t=this._materialMap.get(e)||null),t},t.prototype._getCachedLightmapByIndex=function(e){var t=null;return e>=0&&null!=this._lightmapMap&&(t=this._lightmapMap.get(e)||null),t},t.prototype.createMaterial=function(t,n,i){if(!0===this._parseScene&&n.index){var r=n.index;if(r>=0){var o=this._getCachedMaterialByIndex(r);if(null!=o)return o}}if(!0===this._parseScene){var a=null,s=n.name||"No Name";if(null!=n.extras&&null!=n.extras.metadata&&null!=n.extras.metadata.customMaterial){var l=n.extras.metadata,u=l.customMaterial,c=(l.customShader,e.Utilities.InstantiateClass(u));if(null!=c){var d=new c(s,this._loader.babylonScene);null!=d?!0==d instanceof BABYLON.Material?(a=d).fillMode=i:BABYLON.Tools.Warn("Non material instantiated class: "+u):BABYLON.Tools.Warn("Failed to instantiate material class: "+u)}else BABYLON.Tools.Warn("Failed to locate material class: "+u)}return null==a&&((a=new e.UniversalShaderMaterial(s,this._loader.babylonScene)).fillMode=i),null!=a&&this._parseUniformAndSamplerProperties(t,n,a),a}return null},t.prototype.loadAnimationAsync=function(e,t){if(!0===this._parseScene){this._loader;var n=t;this._babylonScene._blockEntityCollection=!!this._assetContainer;var i=new BABYLON.AnimationGroup(t.name||"animation".concat(n.index),this._babylonScene);i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n._babylonAnimationGroup=i,this._animationGroups.push(i);var r=new Array;BABYLON.GLTF2.ArrayItem.Assign(n.channels),BABYLON.GLTF2.ArrayItem.Assign(n.samplers);for(var o=0,a=t.channels;o<a.length;o++){var s=a[o],l=s;r.push(this._loader._loadAnimationChannelAsync("".concat(e,"/channels/").concat(l.index),e,t,s,function(e,t){e.animations=e.animations||[],e.animations.push(t),i.addTargetedAnimation(t,e)}))}return Promise.all(r).then(function(){if(null!=t.extras&&null!=t.extras.metadata){var e={};e.toolkit=t.extras.metadata,i.metadata=e,null!=e.label&&""!==e.label&&(i.name=e.label)}return i.normalize(0),i})}return null},t.prototype._loadMeshPrimitiveAsync=function(e,t,n,i,r,o){var a=this;if(!0===this._parseScene){var s=this._loader;s.logOpen("".concat(e));var l,u=0===s._disableInstancedMesh&&s._parent.createInstances&&null==n.skin&&!i.primitives[0].targets,c=void 0;if(u&&r._instanceData)s._babylonScene._blockEntityCollection=!!s._assetContainer,(l=r._instanceData.babylonSourceMesh.createInstance(t))._parentContainer=s._assetContainer,s._babylonScene._blockEntityCollection=!1,c=r._instanceData.promise;else{var d=new Array;s._babylonScene._blockEntityCollection=!!s._assetContainer;var h=new BABYLON.Mesh(t,s._babylonScene);h._parentContainer=s._assetContainer,s._babylonScene._blockEntityCollection=!1,!0===this._leftHanded?h.sideOrientation=BABYLON.Material.CounterClockWiseSideOrientation:h.sideOrientation=s._babylonScene.useRightHandedSystem?BABYLON.Material.ClockWiseSideOrientation:BABYLON.Material.CounterClockWiseSideOrientation,s._createMorphTargets(e,n,i,r,h),d.push(s._loadVertexDataAsync(e,r,h).then(function(t){return s._loadMorphTargetsAsync(e,r,h,t).then(function(){s._disposed||(s._babylonScene._blockEntityCollection=!!s._assetContainer,t.applyToMesh(h),a._setupBabylonMesh(h,n,i,r),t._parentContainer=s._assetContainer,s._babylonScene._blockEntityCollection=!1)})}));var p=BABYLON.GLTF2.GLTFLoader._GetDrawMode(e,r.mode);if(null!=r.extras&&null!=r.extras.metadata&&null!=r.extras.metadata.multimaterial&&null!=r.extras.metadata.submeshes)this._setupBabylonMultiMaterials(e,d,p,h,i,r);else if(null==r.material){var m=s._defaultBabylonMaterialData[p];m||(m=s._createDefaultMaterial("__GLTFLoader._default",p),s._parent.onMaterialLoadedObservable.notifyObservers(m),s._defaultBabylonMaterialData[p]=m),h.material=m}else if(!s.parent.skipMaterials){var f=BABYLON.GLTF2.ArrayItem.Get("".concat(e,"/material"),s._gltf.materials,r.material);d.push(s._loadMaterialAsync("/materials/".concat(f.index),f,h,p,function(e){h.material=e}))}c=Promise.all(d),u&&(r._instanceData={babylonSourceMesh:h,promise:c}),l=h}return BABYLON.GLTF2.GLTFLoader.AddPointerMetadata(l,e),s._parent.onMeshLoadedObservable.notifyObservers(l),o(l),s.logClose(),c.then(function(){return l})}return null},t.prototype._setupBabylonMesh=function(e,t,n,i){if(!0===this._parseScene){if(this._loader,null!=i.extras&&null!=i.extras.metadata&&null!=i.extras.metadata.multimaterial&&null!=i.extras.metadata.submeshes){var r=i.extras.metadata.submeshes;e.subMeshes=[];for(var o=0;o<r.length;o++){var a=r[o];BABYLON.SubMesh.AddToMesh(a.materialIndex,a.verticesStart,a.verticesCount,a.indexStart,a.indexCount,e)}}e.computeWorldMatrix(!0)}},t.prototype._setupBabylonMultiMaterials=function(e,t,n,i,r,o){if(!0===this._parseScene){var a=this._loader,s=o.extras.metadata.multimaterial,l=s.materials,u=[],c=s.id||"MM_"+r.name,d=s.name||"MM_"+r.name,h=new BABYLON.MultiMaterial("["+d+"]",a._babylonScene);h.id=c,l.forEach(function(t){if(null!=t){var n=parseInt(t);if(n>=0){var r=BABYLON.GLTF2.ArrayItem.Get("".concat(e,"/material"),a._gltf.materials,n);u.push(r)}else console.warn("Invalid Submesh Material Index Encountered For: "+i.name)}else console.warn("Null Submesh Material Encountered For: "+i.name)}),t.push(this._parseMultiMaterialAsync("/materials/".concat(d),u,i,n,function(e){h.subMaterials=e,i.material=h}))}},t.prototype._processLevelOfDetail=function(e,t){null!=t&&t.length>0&&t.forEach(function(e){})},t.prototype._processShaderMaterials=function(e,t){null!=t&&t.length>0&&t.forEach(function(e){e.freeze()})},t.prototype.preProcessSceneProperties=function(t,n){var i,r,o;if(!0!==this._assetContainer&&!1===this._sceneParsed&&null!=t.extras&&null!=t.extras.metadata&&null!=t.extras.metadata.properties&&!0===t.extras.metadata.properties){this._sceneParsed=!0,null!=this._rootUrl&&this._rootUrl;var a=t.extras.metadata;if(null==n.metadata&&(n.metadata={}),null==n.metadata.toolkit&&(n.metadata.toolkit={}),n.metadata.toolkit=a,this._disposeRoot=null!=a.disposeroot&&!0===a.disposeroot,this._hideLoader=null!=a.hideloader&&!0===a.hideloader,this._preWarmTime=null!=a.prewarmup?a.prewarmup:0,this._licenseType=null!=a.license?a.license:"standard",this._licenseName=null!=a.licensee?a.licensee:"Unknown",e.SceneManager.EnableUserInput=!0,null!=this._licenseName&&""!==this._licenseName&&"Unknown"!==this._licenseName&&"DefaultCompany"!==this._licenseName&&"Default Company"!==this._licenseName&&BABYLON.Tools.Log(e.Utilities.MakeProper(this._fileName)+" licensed to "+this._licenseName),e.SceneManager.GlobalOptions.ktxtextures=null!=a.ktxtextures&&a.ktxtextures,e.SceneManager.GlobalOptions.ktxlightmaps=null!=a.ktxlightmaps&&a.ktxlightmaps,e.SceneManager.GlobalOptions.intensityFactor=null!=a.intensity?a.intensity:1,e.SceneManager.GlobalOptions.debugModeEnabled=null!=a.debugging&&a.debugging,e.SceneManager.GlobalOptions.showDebugColliders=null!=a.showdebugcolliders&&a.showdebugcolliders,e.SceneManager.GlobalOptions.colliderVisibility=null!=a.collidervisibility?a.collidervisibility:0,e.SceneManager.GlobalOptions.colliderRenderGroup=null!=a.colliderrendergroup?a.colliderrendergroup:0,e.SceneManager.GlobalOptions.defaultRenderGroup=null!=a.defaultrendergroup?a.defaultrendergroup:0,e.SceneManager.GlobalOptions.collisionWireframe=null!=a.collisionwireframe&&a.collisionwireframe,e.SceneManager.GlobalOptions.useTriangleNormals=null!=a.trianglenormals&&a.trianglenormals,e.SceneManager.GlobalOptions.useConvexTriangles=null==a.convextriangles||a.convextriangles,e.SceneManager.GlobalOptions.colliderInstances=null==a.colliderinstances||a.colliderinstances,e.SceneManager.GlobalOptions.reparentColliders=null==a.reparentcolliders||a.reparentcolliders,e.SceneManager.GlobalOptions.enablelegacyaudio=null!=a.enablelegacyaudio&&a.enablelegacyaudio,e.SceneManager.GlobalOptions.globalillumination=null!=a.globalillumination&&a.globalillumination,null!=a.clearcolor&&(n.clearColor=e.Utilities.ParseColor4(a.clearcolor)),null!=a.autoclear&&!0===a.autoclear&&(n.autoClear=!0,n.autoClearDepthAndStencil=!0),null!=a.rendergroups&&(BABYLON.RenderingManager.MAX_RENDERINGGROUPS=a.rendergroups),null!=a.imageprocessing){var s=a.imageprocessing,l=null!=s.contrast?s.contrast:1,u=null!=s.exposure?s.exposure:1;null!=n.imageProcessingConfiguration&&(n.imageProcessingConfiguration.contrast=l,n.imageProcessingConfiguration.exposure=u)}var c=null!=a.ambientlightmap?a.ambientlightmap:0;if(null!=a.ambientcoloring&&(n.ambientColor=e.Utilities.ParseColor3(a.ambientcoloring)),null!=a.ambientlighting&&1===a.ambientlighting){var d=n;if(null==d._AmbientLight)switch(d._AmbientLight=new BABYLON.HemisphericLight("Ambient Lighting",new BABYLON.Vector3(0,1,0),n),d._AmbientLight.falloffType=BABYLON.Light.FALLOFF_STANDARD,c){case 2:d._AmbientLight.lightmapMode=BABYLON.Light.LIGHTMAP_SHADOWSONLY;break;case 1:d._AmbientLight.lightmapMode=BABYLON.Light.LIGHTMAP_SPECULAR;break;default:d._AmbientLight.lightmapMode=BABYLON.Light.LIGHTMAP_DEFAULT}null!=d._AmbientLight&&("skybox"===a.ambientskymode||!1===a.ambientoverride?(d._AmbientLight.name="Ambient Blacklight",d._AmbientLight.diffuse=BABYLON.Color3.Black(),d._AmbientLight.specular=BABYLON.Color3.Black(),d._AmbientLight.groundColor=BABYLON.Color3.Black(),null!=a.ambientlightintensity&&(d._AmbientLight.intensity=a.ambientlightintensity),d._AmbientLight.intensity*=e.SceneManager.AmbientLightIntensity,d._AmbientLight.intensityMode=BABYLON.Light.INTENSITYMODE_ILLUMINANCE):(null!=a.ambientskycolor&&(d._AmbientLight.diffuse=e.Utilities.ParseColor3(a.ambientskycolor,BABYLON.Color3.Gray())),null!=a.ambientspecularcolor&&(d._AmbientLight.specular=e.Utilities.ParseColor3(a.ambientspecularcolor,BABYLON.Color3.Black())),null!=a.ambientgroundcolor&&(d._AmbientLight.groundColor=e.Utilities.ParseColor3(a.ambientgroundcolor,BABYLON.Color3.Gray())),null!=a.ambientlightintensity&&(d._AmbientLight.intensity=a.ambientlightintensity),d._AmbientLight.intensity*=e.SceneManager.AmbientLightIntensity,d._AmbientLight.intensityMode=BABYLON.Light.INTENSITYMODE_ILLUMINANCE))}if(null!=a.fogmode){var h=a.fogmode,p=1,m=BABYLON.Scene.FOGMODE_NONE;switch(h){case 1:m=BABYLON.Scene.FOGMODE_EXP,p=null!==(i=e.SceneManager.FogExpDensityScale)&&void 0!==i?i:1;break;case 2:m=BABYLON.Scene.FOGMODE_EXP2,p=null!==(r=e.SceneManager.FogExp2DensityScale)&&void 0!==r?r:1;break;case 3:m=BABYLON.Scene.FOGMODE_LINEAR,p=null!==(o=e.SceneManager.FogLinearDensityScale)&&void 0!==o?o:1;break;default:m=BABYLON.Scene.FOGMODE_NONE}m!==BABYLON.Scene.FOGMODE_NONE?(n.fogMode=m,n.fogEnabled=!0,null==a.fogdensity||m!==BABYLON.Scene.FOGMODE_EXP&&m!==BABYLON.Scene.FOGMODE_EXP2||(n.fogDensity=Math.max(0,a.fogdensity*p)),m===BABYLON.Scene.FOGMODE_LINEAR&&(null!=a.fogstart&&(n.fogStart=a.fogstart||0),null!=a.fogend&&(n.fogEnd=2*(a.fogend||300))),null!=a.fogcolor&&(n.fogColor=e.Utilities.ParseColor3(a.fogcolor))):n.fogEnabled=!1}var f=new BABYLON.Vector3(0,-9.81,0),g=null!=a.defaultgravity?e.Utilities.ParseVector3(a.defaultgravity,f):f;if(n.gravity=g.clone(),n.collisionsEnabled=!0,null!=a.enablephysics&&!0===a.enablephysics){var v=null==a.ccdenabled||a.ccdenabled,y=null!=a.ccdpenetration?a.ccdpenetration:1e-4,_=null!=a.subtimestep?a.subtimestep:0,S=null!=a.maxworldsweep?a.maxworldsweep:0,A=null==a.deltaworldstep||a.deltaworldstep;e.RigidbodyPhysics.ConfigurePhysicsEngine(n,!A,_,S,v,y,g)}if(null!=a.userinput){var b=a.userinput;e.UserInputOptions.KeyboardSmoothing=b.keyboardSmoothing,e.UserInputOptions.KeyboardMoveSensibility=b.keyboardSensitivity,e.UserInputOptions.KeyboardArrowSensibility=1,e.UserInputOptions.KeyboardMoveDeadZone=b.keyboardDeadZone,e.UserInputOptions.GamepadDeadStickValue=b.padDeadStick,e.UserInputOptions.GamepadLStickXInverted=b.padLStickXInvert,e.UserInputOptions.GamepadLStickYInverted=b.padLStickYInvert,e.UserInputOptions.GamepadRStickXInverted=b.padRStickXInvert,e.UserInputOptions.GamepadRStickYInverted=b.padRStickYInvert,e.UserInputOptions.GamepadLStickSensibility=b.padLStickLevel,e.UserInputOptions.GamepadRStickSensibility=b.padRStickLevel,e.UserInputOptions.SupportedInputDevices=b.supportedDevices,e.UserInputOptions.BabylonAngularSensibility=2e3,e.UserInputOptions.DefaultAngularSensibility=b.mouseSensitivity,e.UserInputOptions.PointerWheelDeadZone=b.wheelDeadZone,e.UserInputOptions.PointerMouseDeadZone=b.mouseDeadZone,e.UserInputOptions.PointerMouseInverted=b.mouseMoveInvert,e.UserInputOptions.UseCanvasElement=b.useCanvasElement,e.UserInputOptions.UseArrowKeyRotation=b.arrowKeyRotation,e.UserInputOptions.EnableBabylonRotation=!1}if(null!=a.enableinput&&!0===a.enableinput){var M={contextMenu:null==a.contextmenu||a.contextmenu,pointerLock:null!=a.pointerlock&&a.pointerlock,preventDefault:null!=a.preventdefault&&a.preventdefault,useCapture:null!=a.usecapture&&a.usecapture};e.InputController.ConfigureUserInput(n.getEngine(),n,M)}null!=a.freezeactivemeshes&&!0===a.freezeactivemeshes&&(this._activeMeshes=!0),null!=a.performancepriority&&(n.performancePriority=a.performancepriority)}},t.prototype.postProcessSceneProperties=function(t,n,i){return a(this,void 0,void 0,function(){var r,o,a,l,u,c,d,h,p,m,f,g,v,y,_,S,A,b,M;return s(this,function(s){if(!0===this._assetContainer)return[2];if(null!=n.extras&&null!=n.extras.metadata&&null!=n.extras.metadata.properties&&!0===n.extras.metadata.properties&&null!=(r=n.extras.metadata).skybox){null!=(o=r.skybox).skyurl&&o.skyurl,a=null!=o.skyres?o.skyres:512,l=null!=o.skyfog&&o.skyfog,u=null!=o.skytags?o.skytags:"Untagged",c=null!=o.skysize?o.skysize:1e3,d=null!=o.rotation?o.rotation:0,h=null!=o.basename&&""!==o.basename?t+o.basename:null,p=null!=o.skyfaces?o.skyfaces:null,m=null==o.sixsided||o.sixsided,f=null!=o.rendergroup?o.rendergroup:0,g=null!=o.extensions&&o.extensions.length>0?o.extensions:null,null==o.polynomial||o.polynomial;try{null!=p&&""!==p&&null!=h&&""!==h&&(v=null,"png"===p||"webp"===p?!0===m?(v=new BABYLON.CubeTexture(h,i,g),h.indexOf("_rgbd")>=0?(v.isRGBD=!0,v.gammaSpace=!0):(v.isRGBD=!1,v.gammaSpace=!0)):(y=h+"."+p,(v=new BABYLON.Texture(y,i,!0,!1)).isRGBD=h.indexOf("_rgbd")>=0,v.gammaSpace=!0):"hdr"===p?(_=h+"."+p,(v=new BABYLON.HDRCubeTexture(_,i,a,!0,!1,!0,!1)).isRGBD=!1,v.gammaSpace=!0):"exr"===p?(S=h+"."+p,(v=new BABYLON.EXRCubeTexture(S,i,a,!0,!1,!0,!1)).isRGBD=!1,v.gammaSpace=!0):((v=new BABYLON.CubeTexture(h,i,g)).isRGBD=!1,v.gammaSpace=!0),v.name=o.basename,v.coordinatesMode=BABYLON.Texture.SKYBOX_MODE,v.rotationY=BABYLON.Tools.ToRadians(d),A="Default Skybox",(b=BABYLON.MeshBuilder.CreateBox(A,{size:c},i)).renderingGroupId=e.Utilities.DefaultRenderGroup(),b.id=A,b.infiniteDistance=!0,b.applyFog=l,b.renderingGroupId=f,null!=u&&""!==u&&BABYLON.Tags.AddTagsTo(b,u),!0===i.useRightHandedSystem&&(b.scaling.x*=-1),(M=new BABYLON.StandardMaterial("Skybox-Material",i)).backFaceCulling=!1,M.disableLighting=!0,M.diffuseColor=new BABYLON.Color3(0,0,0),M.emissiveColor=new BABYLON.Color3(0,0,0),M.specularColor=new BABYLON.Color3(0,0,0),M.ambientColor=new BABYLON.Color3(0,0,0),M.reflectionTexture=v,b.material=M)}catch(e){console.warn(e)}}return[2]})})},t.prototype.updateSkyboxEnvironment=function(t,n){if(null!=t.environment){var i=t.environment,r=null!=i.info&&""!==i.info?i.info:null,o=null!=i.ibl?i.ibl:1,a=null!=i.level?i.level:1,s=null!=i.refl?i.refl:null,l=null!=i.scale?i.scale:1,u=null!=i.mode?i.mode:0;o=Math.max(0,o);var c=null!=s?s:o*a,d=BABYLON.Scalar.Clamp(o,0,10),h=BABYLON.Scalar.Clamp(c,0,1e3),p=Array.isArray(i.sh)&&27===i.sh.length,m="skybox"===i.sky&&!0===p;if(m&&this.generateSphericalHarmonics(n,i.sh,d),null!=r&&""!==r)try{var f=(null!=this._rootUrl?this._rootUrl:"/")+r.rooturl+r.name;if(null!=this._assetsManager){var g=this._assetsManager.addBinaryFileTask("Global.EnvironmentTextureTask",f);g.onSuccess=function(t){if(null!=t.data){var i=t.data instanceof ArrayBuffer?new Uint8Array(t.data):t.data,o=f.toLowerCase().endsWith(".env")?".env":".dds",a=new BABYLON.CubeTexture(f,n,{buffer:i,prefiltered:!0,forcedExtension:o,createPolynomials:1===u,onLoad:function(){},onError:function(e,t){return console.error(e,t)}});if(n.environmentTexture=a,n.environmentTexture.name="assets/"+r.name,n.environmentTexture.level=m?h*l:h,m)if(a.isReady()){var s=e.SceneManager.GetImageBasedLighting(n);null!=s&&(0===u&&(n.environmentTexture.sphericalPolynomial=s),n.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag))}else a.onLoadObservable.addOnce(function(){var t=e.SceneManager.GetImageBasedLighting(n);null!=t&&(0===u&&(n.environmentTexture.sphericalPolynomial=t),n.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag))})}else console.error("❌ Failed to load environment texture task: "+f)},g.onError=function(e,t,n){console.error("❌ Environment texture error:",t,n)}}}catch(e){console.warn("⚠️ Error setting up environment texture:",e)}}},t.prototype.generateSphericalHarmonics=function(e,t,n){try{var i=t.slice(0,9),r=t.slice(9,18),o=t.slice(18,27),a=new BABYLON.SphericalHarmonics;a.l00=new BABYLON.Vector3(i[0],r[0],o[0]),a.l1_1=new BABYLON.Vector3(i[1],r[1],o[1]),a.l10=new BABYLON.Vector3(i[2],r[2],o[2]),a.l11=new BABYLON.Vector3(i[3],r[3],o[3]),a.l2_2=new BABYLON.Vector3(i[4],r[4],o[4]),a.l2_1=new BABYLON.Vector3(i[5],r[5],o[5]),a.l20=new BABYLON.Vector3(i[6],r[6],o[6]),a.l21=new BABYLON.Vector3(i[7],r[7],o[7]),a.l22=new BABYLON.Vector3(i[8],r[8],o[8]),a.preScaled=!0,1!==n&&a.scaleInPlace(n);var s=BABYLON.SphericalPolynomial.FromHarmonics(a);e.globalSphericalPolynomial=s}catch(e){console.error("Failed to apply Unity SH to scene environment:",e)}},t.prototype.lateProcessSceneProperties=function(t,n,i){return a(this,void 0,void 0,function(){var t,r,o,a;return s(this,function(s){switch(s.label){case 0:return!0===this._assetContainer?[2]:null==n.extras||null==n.extras.metadata||null==n.extras.metadata.properties||!0!==n.extras.metadata.properties||null==(t=n.extras.metadata).navigation||null==t.navigation.prebaked||""===t.navigation.prebaked?[3,2]:(r=null!=t.navigation.prebaked&&""!==t.navigation.prebaked?t.navigation.prebaked:null,o=null!=t.navigation.showdebug&&!0===t.navigation.showdebug,a=null,null!=t.navigation.heightmesh&&""!==t.navigation.heightmesh&&null!=(a=i.getMeshByName(t.navigation.heightmesh))&&(a.material.transparencyMode=BABYLON.Material.MATERIAL_ALPHABLEND,a.checkCollisions=!1,a.visibility=o?.3:0,a.isVisible=!0,a.isPickable=!0),[4,e.SceneManager.LoadNavigationMeshDataAsync(i,r,a,o)]);case 1:s.sent(),s.label=2;case 2:return[2]}})})},t.prototype._preloadRawMaterialsAsync=function(e,t,n){var i=this._loader,r=new Array,o=BABYLON.Material.TriangleFillMode;return n.forEach(function(n){var a=BABYLON.GLTF2.ArrayItem.Get("".concat(e,"/material"),t,n);if(null!=a){var s=i.createMaterial(e,a,o);BABYLON.GLTF2.GLTFLoader.AddPointerMetadata(s,e),i._parent.onMaterialLoadedObservable.notifyObservers(s),r.push(i.loadMaterialPropertiesAsync(e,a,s))}}),Promise.all(r).then(function(){})},t.prototype._parseMultiMaterialAsync=function(e,t,n,i,r){var o=this;void 0===r&&(r=function(){});var a=this._loader,s=t;s._data=s._data||{};var l=s._data[i];if(!l){a.logOpen("".concat(e," ").concat(n.name||""));var u=[],c=new Array;t.forEach(function(t){var n=null;if(t.index){var r=t.index;r>=0&&(n=o._getCachedMaterialByIndex(r))}null==n&&(n=a.createMaterial(e,t,i),BABYLON.GLTF2.GLTFLoader.AddPointerMetadata(n,e),a._parent.onMaterialLoadedObservable.notifyObservers(n),c.push(a.loadMaterialPropertiesAsync(e,t,n))),u.push(n)}),l={babylonMaterials:u,babylonMeshes:[],promises:c},s._data[i]=l,a.logClose()}return l.babylonMeshes.push(n),n.onDisposeObservable.addOnce(function(){var e=l.babylonMeshes.indexOf(n);-1!==e&&l.babylonMeshes.splice(e,1)}),r(l.babylonMaterials),Promise.all(l.promises).then(function(){return l.babylonMaterials})},t.prototype._parseCommonConstantProperties=function(n,i,r,o){var a=this,s=null!=r.extras&&null!=r.extras.metadata?r.extras.metadata:null;if(null!=s){var l=o;e.Utilities.HasOwnProperty(l,"alphaMode")&&(l.alphaMode=null!=s&&s.alphaMode?s.alphaMode:BABYLON.Engine.ALPHA_COMBINE),e.Utilities.HasOwnProperty(l,"ambientColor")&&(l.ambientColor=null!=s&&s.ambientColorFactor?BABYLON.Color3.FromArray(s.ambientColorFactor):BABYLON.Color3.Black()),e.Utilities.HasOwnProperty(l,"backFaceCulling")&&(l.backFaceCulling=null==s||null==s.backFaceCulling||s.backFaceCulling);var u=!1,c=!1;if(o instanceof BABYLON.PBRMaterial){switch(u=!(!r.extensions||!r.extensions.KHR_materials_pbrSpecularGlossiness),!r.extensions||r.extensions.KHR_materials_specular,!0!==(c=u)&&(o.useMetallnessFromMetallicTextureBlue=!0,o.useRoughnessFromMetallicTextureGreen=!0,o.useRoughnessFromMetallicTextureAlpha=!1,o.useAmbientOcclusionFromMetallicTextureRed=!1),!0===c&&(o.useMicroSurfaceFromReflectivityMapAlpha=!0),o.directIntensity=null!=s.directIntensity?s.directIntensity:1,o.specularIntensity=null!=s.specularIntensity?s.specularIntensity:1,o.emissiveIntensity=null!=s.emissiveIntensity?s.emissiveIntensity:1,o.environmentIntensity=null!=s.environmentIntensity?s.environmentIntensity:1,o.indexOfRefraction=null!=s.indexOfRefraction?s.indexOfRefraction:1.5,e.Utilities.MarkGamma(o.albedoTexture),e.Utilities.MarkGamma(o.emissiveTexture),!0!==c&&e.Utilities.MarkLinear(o.metallicTexture),e.Utilities.MarkLinear(o.ambientTexture),e.Utilities.MarkLinear(o.opacityTexture),e.Utilities.MarkLinear(o.bumpTexture),!0===c&&e.Utilities.MarkGamma(o.reflectivityTexture),r.alphaMode||e.MaterialAlphaMode.OPAQUE){case e.MaterialAlphaMode.OPAQUE:o.alpha=1,o.transparencyMode=BABYLON.ShaderMaterial.MATERIAL_OPAQUE;break;case e.MaterialAlphaMode.MASK:o.transparencyMode=BABYLON.ShaderMaterial.MATERIAL_ALPHATEST;break;case e.MaterialAlphaMode.BLEND:o.transparencyMode=BABYLON.ShaderMaterial.MATERIAL_ALPHABLEND;break;default:o.alpha=1,o.transparencyMode=BABYLON.ShaderMaterial.MATERIAL_OPAQUE}var d=null!=s.clearCoatIntensity?s.clearCoatIntensity:0;d>0&&(o.clearCoat.isEnabled=!0,o.clearCoat.intensity=d),null!=s.useAlphaFromAlbedoTexture&&(o.useAlphaFromAlbedoTexture=s.useAlphaFromAlbedoTexture),null!=s.parallaxBias&&s.parallaxBias>0&&(o.useParallax=!0,o.parallaxScaleBias=s.parallaxBias)}if(e.Utilities.HasOwnProperty(l,"unlit")&&(l.unlit=null!=s.unlitMaterial&&s.unlitMaterial),e.Utilities.HasOwnProperty(l,"wireframe")&&(l.wireframe=null!=s.useWireframe&&s.useWireframe),e.Utilities.HasOwnProperty(l,"disableLighting")&&(l.disableLighting=null!=s.disableLighting&&s.disableLighting),e.Utilities.HasOwnProperty(l,"maxSimultaneousLights")&&(l.maxSimultaneousLights=null!=s.maxSimultaneousLights?s.maxSimultaneousLights:4),e.Utilities.HasOwnProperty(l,"needDepthPrePass")&&(l.needDepthPrePass=null!=s.depthPrepass&&s.depthPrepass),e.Utilities.HasOwnProperty(l,"lightmapTexture")&&s.lightmapTexture){s.lightmapTexture.nonColorData=!0;var h=!0;e.Utilities.HasOwnProperty(l,"useLightmapAsShadowmap")&&(h=null==s.useLightmapAsShadowmap||s.useLightmapAsShadowmap);var p=null,m=null!=s.lightmapTexture.index?s.lightmapTexture.index:-1;m>=0&&(p=this._getCachedLightmapByIndex(m)),null!=p?(l.lightmapTexture=p,l.useLightmapAsShadowmap=h,e.Utilities.HasOwnProperty(l,"ambientColor")&&(l.ambientColor=BABYLON.Color3.White())):n.push(this._loader.loadTextureInfoAsync(i+"/lightmapTexture",s.lightmapTexture,function(t){t.name="assets/LightmapTexture-".concat(m),t.level=s.lightmapLevel?s.lightmapLevel:1;var n=t;n.onLoadObservable.addOnce(function(){n.isReady()?(n.isRGBD=!0,n.gammaSpace=!1):BABYLON.Tools.Warn("[LM] Failed to register RGBD lightmap (not ready): "+n.name)}),l.lightmapTexture=t,l.useLightmapAsShadowmap=h,m>=0&&null!=a._lightmapMap&&(a._lightmapMap.has(m)||a._lightmapMap.set(m,n)),e.Utilities.HasOwnProperty(l,"ambientColor")&&(l.ambientColor=BABYLON.Color3.White())}))}o instanceof BABYLON.PBRMaterial&&s.detailMapTexture&&(s.detailMapTexture.nonColorData=!0,n.push(this._loader.loadTextureInfoAsync(i+"/detailMapTexture",s.detailMapTexture,function(e){e.name="".concat(o.name," (Detail Map)"),e.level=1;var t=e;t.gammaSpace=!1,o.detailMap.texture=t,o.detailMap.bumpLevel=null!=s.detailBumpLevel?s.detailBumpLevel:1,o.detailMap.diffuseBlendLevel=null!=s.detailBlendLevel?s.detailBlendLevel:.75,o.detailMap.roughnessBlendLevel=null!=s.detailRoughLevel?s.detailRoughLevel:.5,null!=BABYLON.Material.MATERIAL_NORMALBLENDMETHOD_RNM&&(o.detailMap.normalBlendMethod=BABYLON.Material.MATERIAL_NORMALBLENDMETHOD_RNM),o.detailMap.isEnabled=!0})));var f=e.SceneManager.GetRenderQuality(),g=f===e.RenderQuality.High||f===e.RenderQuality.Medium;if(!0===g&&e.Utilities.HasOwnProperty(l,"reflectionColor")&&(l.reflectionColor=null!=s&&s.reflectionColorFactor?BABYLON.Color3.FromArray(s.reflectionColorFactor):BABYLON.Color3.White()),!0===g&&e.Utilities.HasOwnProperty(l,"reflectionTexture")&&s.reflectionCubemapInfo){var v=(this._loader._rootUrl+s.reflectionCubemapInfo.rooturl+s.reflectionCubemapInfo.name).toLowerCase(),y=v.lastIndexOf("."),_=y>-1?v.substring(y).toLowerCase():"",S=null!=s.reflectionCubemapInfo.size?s.reflectionCubemapInfo.size:128,A=null!=s.reflectionProbePower?s.reflectionProbePower:1,b=new e.CubeTextureLoader;b.name="assets/"+s.reflectionCubemapInfo.name,b.size=S,b.mapkey=v,b.material=l,b.extension=_,b.prefiltered=!0,b.reflectionProbePower=A,s.reflectionCubemapInfo.boundingBoxSize&&(b.boundingBoxSize=BABYLON.Vector3.FromArray(s.reflectionCubemapInfo.boundingBoxSize),b.name+=" ("+b.boundingBoxSize.x.toString()+" "+b.boundingBoxSize.y.toString()+" "+b.boundingBoxSize.z.toString()+")",b.mapkey+="_"+b.boundingBoxSize.x.toString()+"_"+b.boundingBoxSize.y.toString()+"_"+b.boundingBoxSize.z.toString()),s.reflectionCubemapInfo.boundingBoxPosition&&(b.boundingBoxPosition=BABYLON.Vector3.FromArray(s.reflectionCubemapInfo.boundingBoxPosition),b.name+=" ("+b.boundingBoxPosition.x.toString()+" "+b.boundingBoxPosition.y.toString()+" "+b.boundingBoxPosition.z.toString()+")",b.mapkey+="_"+b.boundingBoxPosition.x.toString()+"_"+b.boundingBoxPosition.y.toString()+"_"+b.boundingBoxPosition.z.toString());var M=this._reflectionMap[v];null==M?(M=[b],this._reflectionMap[v]=M):M.push(b)}if(e.Utilities.HasOwnProperty(l,"terrainInfo")&&(l.terrainInfo=null!=s.terrainInfo?s.terrainInfo:null),e.Utilities.HasOwnProperty(o,"universalMaterial")){var B=o;if(s.customTextures){var C=function(e){var t=s.customTextures[e];null!=t&&(B.checkSampler(e),n.push(T._loader.loadTextureInfoAsync(i+"/"+e,t,function(t){t.name="".concat(o.name,"detailsSampler"===e||"normalsSampler"===e?" (Atlas)":" (Custom)"),B.setTextureValue(e,t)})))},T=this;for(var x in s.customTextures)C(x)}if(s.customVectors)for(var I in s.customVectors)null!=(P=s.customVectors[I])&&B.addVector4Uniform(I,BABYLON.Vector4.FromArray(P),!0);if(s.customColors)for(var O in s.customColors)null!=(R=s.customColors[O])&&B.addVector4Uniform(O,BABYLON.Vector4.FromArray(R),!0);if(s.customFloats)for(var L in s.customFloats)null!=(E=s.customFloats[L])&&B.addFloatUniform(L,E,!0)}else{if(s.customTextures){var w=function(t){var r=s.customTextures[t];null!=r&&e.Utilities.HasOwnProperty(l,t)&&n.push(N._loader.loadTextureInfoAsync(i+"/"+t,r,function(e){e.name="".concat(o.name,"detailsSampler"===t||"normalsSampler"===t?" (Atlas)":" (Custom)"),l[t]=e}))},N=this;for(var x in s.customTextures)w(x)}if(s.customVectors)for(var I in s.customVectors){var P;null!=(P=s.customVectors[I])&&e.Utilities.HasOwnProperty(l,I)&&(l[I]=BABYLON.Vector4.FromArray(P))}if(s.customColors)for(var O in s.customColors){var R;null!=(R=s.customColors[O])&&e.Utilities.HasOwnProperty(l,O)&&(l[O]instanceof BABYLON.Vector4?l[O]=BABYLON.Vector4.FromArray(R):l[O]instanceof BABYLON.Color4?l[O]=BABYLON.Color4.FromArray(R):l[O]=BABYLON.Color3.FromArray(R))}if(s.customFloats)for(var L in s.customFloats){var E;null!=(E=s.customFloats[L])&&e.Utilities.HasOwnProperty(l,L)&&(l[L]instanceof Boolean?l[L]=E>0:l[L]=E)}}if(o instanceof e.CustomShaderMaterial){var k=null==s.enableGlossyReflections||s.enableGlossyReflections,D=null!=s.specularIntensityScale?s.specularIntensityScale:1,F=null!=s.lightmapTexture?t.IBL_TINY_VALUE:1,U=!0===k?t.IBL_SPEC_FACTOR*D:t.IBL_TINY_VALUE;o.splitLighting(F,U),o.initMaterial()}else o instanceof e.StandardShaderMaterial&&o.initMaterial();null!=s.freezeMaterial&&!0===s.freezeMaterial&&null!=this._shaderList&&this._shaderList.push(o)}},t.prototype._parseUniformAndSamplerProperties=function(t,n,i){var r=null!=n.extras&&null!=n.extras.metadata?n.extras.metadata:null;if(null!=r&&e.Utilities.HasOwnProperty(i,"universalMaterial")){var o=i;if(r.customTextures)for(var a in r.customTextures)null!=r.customTextures[a]&&o.checkSampler(a);if(r.customVectors)for(var s in r.customVectors){var l=r.customVectors[s];null!=l&&o.checkUniform(s,"vec4",BABYLON.Vector4.FromArray(l))}if(r.customColors)for(var u in r.customColors){var c=r.customColors[u];null!=c&&o.checkUniform(u,"vec4",BABYLON.Vector4.FromArray(c))}if(r.customFloats)for(var d in r.customFloats){var h=r.customFloats[d];null!=h&&o.checkUniform(d,"float",h)}}},t.IBL_TINY_VALUE=.001,t.IBL_SPEC_FACTOR=1,t.IBL_PROBE_FACTOR=1,t.ScriptBundleCache={},t}();e.CVTOOLS_unity_metadata=n;var i=function(){function t(t){this.name=e.SceneManager.CVTOOLS_MESH,this.enabled=!1,this._loader=t,this.enabled=this._loader.isExtensionUsed(e.SceneManager.CVTOOLS_MESH),this.order=101}return t.prototype.dispose=function(){delete this._loader},t}();e.CVTOOLS_babylon_mesh=i;var r=function(){function t(t){this.name=e.SceneManager.CVTOOLS_HAND,this.enabled=!1,this._loader=t,this.enabled=this._loader.isExtensionUsed(e.SceneManager.CVTOOLS_HAND),this.order=102}return t.prototype.dispose=function(){delete this._loader},t}();e.CVTOOLS_left_handed=r}(i||(i={})),function(e){var t=function(t){function n(n,i){var r=t.call(this,n,i)||this;return r.universalMaterial=!0,r._defines={},r._uniforms=[],r._samplers=[],r._attributes=[],r._textures={},r._vectors4={},r._vectors3={},r._vectors2={},r._floats={},r._bools={},r._ubos=null,r._wgslSamplers=null,r._noMatrixTextures=null,r.shader=null,r.plugin=null,r._unityLightingPlugin=null,r.shader="CustomShaderMaterial",r.addFloatUniform("tkIblDiffuseScale",1),r.addFloatUniform("tkIblSpecularScale",1),r._unityLightingPlugin=new e.UnityStyleLightingPlugin(r,r.shader),r}return r(n,t),n.prototype.getPlugin=function(){return this.plugin},n.prototype.getClassName=function(){return"PBRMaterial"},n.prototype.initMaterial=function(){this.awake&&this.awake()},n.prototype.addAttribute=function(e){-1===this._attributes.indexOf(e)&&this._attributes.push(e)},n.prototype.checkUniform=function(e,t,n){void 0===n&&(n=null),-1===this._uniforms.indexOf(e)&&(this._uniforms.push(e),this._defines[e.toUpperCase()]=!0,this.buildUniformProperty(e,t,n))},n.prototype.checkSampler=function(e,t){void 0===t&&(t=null),-1===this._samplers.indexOf(e)&&(this._samplers.push(e),this._defines[e.toUpperCase()]=!0,this.buildUniformProperty(e,"sampler2D",t),this.checkUniform(e+"Infos","vec2",BABYLON.Vector2.Zero()),this.checkUniform(e+"Matrix","mat4",BABYLON.Matrix.Identity()))},n.prototype.splitLighting=function(e,t){var n,i;this.setFloatValue("tkIblDiffuseScale",e),this.setFloatValue("tkIblSpecularScale",t),this.markAsDirty(BABYLON.Constants.MATERIAL_AllDirtyFlag),null===(n=this.plugin)||void 0===n||n.markAllDefinesAsDirty(),null===(i=this._unityLightingPlugin)||void 0===i||i.markAllDefinesAsDirty()},n.prototype.addTextureUniform=function(e,t){return this.checkSampler(e,t),this._textures[e]=t,this},n.prototype.setTextureValue=function(e,t){return this._textures[e]=t,this},n.prototype.markTextureAsRaw=function(e){this._noMatrixTextures||(this._noMatrixTextures=new Set),this._noMatrixTextures.add(e)},n.prototype.getTextureValue=function(e){return this._textures[e]},n.prototype.addVector4Uniform=function(e,t){return this.checkUniform(e,"vec4",t),this._vectors4[e]=t,this},n.prototype.setVector4Value=function(e,t){return this._vectors4[e]=t,this},n.prototype.getVector4Value=function(e){return this._vectors4[e]},n.prototype.addVector3Uniform=function(e,t){return this.checkUniform(e,"vec3",t),this._vectors3[e]=t,this},n.prototype.setVector3Value=function(e,t){return this._vectors3[e]=t,this},n.prototype.getVector3Value=function(e){return this._vectors3[e]},n.prototype.addVector2Uniform=function(e,t){return this.checkUniform(e,"vec2",t),this._vectors2[e]=t,this},n.prototype.setVector2Value=function(e,t){return this._vectors2[e]=t,this},n.prototype.getVector2Value=function(e){return this._vectors2[e]},n.prototype.addFloatUniform=function(e,t){return this.checkUniform(e,"float",t),this._floats[e]=t,this},n.prototype.setFloatValue=function(e,t){return this._floats[e]=t,this},n.prototype.getFloatValue=function(e){return this._floats[e]},n.prototype.addBoolUniform=function(e,t){return this.checkUniform(e,"bool",t),this._bools[e]=t,this},n.prototype.setBoolValue=function(e,t){return this._bools[e]=t,this},n.prototype.getBoolValue=function(e){return this._bools[e]},n.prototype.getAnimatables=function(){var e=t.prototype.getAnimatables.call(this);for(var n in this._textures){var i=this._textures[n];i&&i.animations&&i.animations.length>0&&e.push(i)}return e},n.prototype.getActiveTextures=function(){var e=t.prototype.getActiveTextures.call(this);for(var n in this._textures){var i=this._textures[n];i&&e.push(i)}return e},n.prototype.hasTexture=function(e){if(t.prototype.hasTexture.call(this,e))return!0;for(var n in this._textures)if(this._textures[n]===e)return!0;return!1},n.prototype.getCustomUniforms=function(e){var t={};return null!=this._ubos&&this._ubos.length>0&&(t.ubo=this._ubos.filter(function(e){return"sampler2D"!==e.type})),!1===e&&(t.fragment=this.getCustomFragmentCode(!1)),t},n.prototype.getCustomSamplers=function(){return this._samplers},n.prototype.getCustomAttributes=function(){return this._attributes},n.prototype.getCustomVertexCode=function(e){return null},n.prototype.getCustomFragmentCode=function(e){var t=this,n=null;return null!=this._ubos&&this._ubos.length>0&&(n="#ifdef "+this.shader.toUpperCase()+"\n",this._ubos.forEach(function(i){if(!0===e)"sampler2D"===i.type&&(null==t._wgslSamplers&&(t._wgslSamplers=new Set),t._wgslSamplers.has(i.name)||(n+="\tvar "+i.name+": texture_2d<f32>;\n",n+="\tvar "+i.name+"Sampler: sampler;\n",t._wgslSamplers.add(i.name)));else{var r=i.name.toUpperCase()+"_DEFINED";"float"===i.type||"bool"===i.type||"int"===i.type?(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform float "+i.name+";\n",n+="\t#endif\n"):"vec2"===i.type?(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform vec2 "+i.name+";\n",n+="\t#endif\n"):"vec3"===i.type?(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform vec3 "+i.name+";\n",n+="\t#endif\n"):"vec4"===i.type?(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform vec4 "+i.name+";\n",n+="\t#endif\n"):"mat4"===i.type?(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform mat4 "+i.name+";\n",n+="\t#endif\n"):"sampler2D"===i.type&&(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform sampler2D "+i.name+";\n",n+="\t#endif\n")}}),n+="#endif\n"),n},n.prototype.prepareCustomDefines=function(e){if(this._wgslSamplers&&this._wgslSamplers.clear(),e[this.shader.toUpperCase()]=!0,null!=this._defines){var t=Object.keys(this._defines);if(null!=t&&t.length>0)for(var n=0,i=t;n<i.length;n++){var r=i[n];e[r]=this._defines[r]}}e.isDirty&&e.rebuild()},n.prototype.updateCustomBindings=function(e){var t,n=this.getScene();this.update&&this.update();var i=null!=e&&"function"==typeof e.getUniformNames,r=i?e.getUniformNames():[],o=function(e){return i&&-1!==r.indexOf(e)};if(n.texturesEnabled)for(t in this._textures){var a=this._textures[t];null!=a&&a.isReady&&a.isReady()&&(null==a.isChecked&&(a.isChecked=!0,("detailsSampler"===t||"normalsSampler"===t||t.indexOf("(Atlas)")>=0)&&a.updateSamplingMode(8)),e.setTexture&&e.setTexture(t,a),this._noMatrixTextures&&this._noMatrixTextures.has(t)||(o(t+"Infos")&&e.updateFloat2?e.updateFloat2(t+"Infos",a.coordinatesIndex,a.level):e.setFloat2?e.setFloat2(t+"Infos",a.coordinatesIndex,a.level):e.setFloat&&e.setFloat(t+"Infos",a.coordinatesIndex),o(t+"Matrix")&&e.updateMatrix?e.updateMatrix(t+"Matrix",a.getTextureMatrix()):e.setMatrix&&e.setMatrix(t+"Matrix",a.getTextureMatrix())))}for(t in this._vectors4){var s=this._vectors4[t];o(t)&&e.updateVector4?e.updateVector4(t,s):e.setVector4?e.setVector4(t,s):e.setFloat4&&e.setFloat4(t,s.x,s.y,s.z,s.w)}for(t in this._vectors3)s=this._vectors3[t],o(t)&&e.updateVector3?e.updateVector3(t,s):e.setVector3?e.setVector3(t,s):e.setFloat3&&e.setFloat3(t,s.x,s.y,s.z);for(t in this._vectors2)s=this._vectors2[t],o(t)&&e.updateFloat2?e.updateFloat2(t,s.x,s.y):e.setFloat2?e.setFloat2(t,s.x,s.y):e.setFloat&&e.setFloat(t,s.x);for(t in this._floats){var l=this._floats[t];o(t)&&e.updateFloat?e.updateFloat(t,l):e.setFloat&&e.setFloat(t,l)}for(t in this._bools)l=this._bools[t]?1:0,o(t)&&e.updateFloat?e.updateFloat(t,l):e.setFloat&&e.setFloat(t,l)},n.prototype.legacyUpdateCustomBindings=function(e){var t,n=this.getScene();if(this.update&&this.update(),n.texturesEnabled)for(t in this._textures){var i=this._textures[t];null!=i&&i.isReady&&i.isReady()&&(null==i.isChecked&&(i.isChecked=!0,("detailsSampler"===t||"normalsSampler"===t||t.indexOf("(Atlas)")>=0)&&i.updateSamplingMode(8)),e.setTexture(t,i),e.updateFloat2(t+"Infos",i.coordinatesIndex,i.level),e.updateMatrix(t+"Matrix",i.getTextureMatrix()))}for(t in this._vectors4)e.updateVector4(t,this._vectors4[t]);for(t in this._vectors3)e.updateVector3(t,this._vectors3[t]);for(t in this._vectors2)e.updateFloat2(t,this._vectors2[t].x,this._vectors2[t].y);for(t in this._floats)e.updateFloat(t,this._floats[t]);for(t in this._bools)e.updateFloat(t,this._bools[t]?1:0);e.update()},n.prototype.buildUniformProperty=function(e,t,n){var i=1;switch(t){case"float":case"bool":case"int":i=1;break;case"vec2":i=2;break;case"vec3":i=3;break;case"vec4":i=4;break;case"mat4":i=16}null==this._ubos&&(this._ubos=[]),this._ubos.push({name:e,size:i,type:t})},n}(BABYLON.PBRMaterial);e.CustomShaderMaterial=t;var n=function(e){function t(t,n,i,r,o,a,s){void 0===o&&(o=!0),void 0===a&&(a=!0),void 0===s&&(s=!1);var l=e.call(this,t,n,i,r,o,a,s)||this;return l._isEnabled=!1,l.vertexDefinitions=null,l.fragmentDefinitions=null,l.setIsEnabled(a),l}return r(t,e),t.prototype.getClassName=function(){return"MaterialPluginBase"},t.prototype.getIsEnabled=function(){return this._isEnabled},t.prototype.setIsEnabled=function(e){this._isEnabled=e,this._material.markAsDirty(BABYLON.Constants.MATERIAL_AllDirtyFlag),this.markAllDefinesAsDirty(),this._enable(this._isEnabled)},t.prototype.getCustomShaderMaterial=function(){return this._material},t}(BABYLON.MaterialPluginBase);e.CustomShaderMaterialPlugin=n;var i=function(e){function t(t,n){return e.call(this,t,n,10,{UNITYSTYLELIGHTINGPLUGIN:!1},!0,!0,!1)||this}return r(t,e),t.prototype.isCompatible=function(e){return e===BABYLON.ShaderLanguage.WGSL||e===BABYLON.ShaderLanguage.GLSL},t.prototype.getClassName=function(){return"UnityStyleLightingPlugin"},t.prototype.getCustomCode=function(e,t){var n=t===BABYLON.ShaderLanguage.WGSL;if("fragment"===e){var i=n?"\n // Unity-Style IBL split scaling (WGSL)\n #if defined(REFLECTION) && defined(UNITYSTYLELIGHTINGPLUGIN) && !defined(UNLIT)\n finalIrradiance = finalIrradiance * uniforms.tkIblDiffuseScale;\n finalRadiance = finalRadiance * uniforms.tkIblSpecularScale;\n finalRadianceScaled = finalRadianceScaled * uniforms.tkIblSpecularScale;\n #endif\n ":"\n // Unity-Style IBL split scaling (GLSL)\n #if defined(REFLECTION) && defined(UNITYSTYLELIGHTINGPLUGIN) && !defined(UNLIT)\n finalIrradiance = finalIrradiance * tkIblDiffuseScale;\n finalRadiance = finalRadiance * tkIblSpecularScale;\n finalRadianceScaled = finalRadianceScaled * tkIblSpecularScale;\n #endif\n ";return{CUSTOM_FRAGMENT_DEFINITIONS:this.fragmentDefinitions,CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:i}}return null},t.prototype.getUniforms=function(e){var t=e===BABYLON.ShaderLanguage.WGSL;return this.vertexDefinitions=this.getCustomShaderMaterial().getCustomVertexCode(t),this.fragmentDefinitions=!0===t?this.getCustomShaderMaterial().getCustomFragmentCode(t):null,this.getCustomShaderMaterial().getCustomUniforms(t)},t.prototype.prepareDefines=function(e,t,n){this.getIsEnabled()&&(e.UNITYSTYLELIGHTINGPLUGIN=!0,this.getCustomShaderMaterial().prepareCustomDefines(e))},t.prototype.bindForSubMesh=function(e,t,n,i){this.getIsEnabled()&&this.getCustomShaderMaterial().updateCustomBindings(e)},t}(e.CustomShaderMaterialPlugin);e.UnityStyleLightingPlugin=i;var o=function(e){function t(t,n){var i=e.call(this,t,n)||this;return i.shader=i.getShaderName(),i}return r(t,e),t.prototype.getShaderName=function(){return"UniversalShaderMaterial"},t}(e.CustomShaderMaterial);e.UniversalShaderMaterial=o,e.SceneManager.RegisterClass("TOOLKIT.CustomShaderMaterial",t),e.SceneManager.RegisterClass("TOOLKIT.UniversalShaderMaterial",o),e.SceneManager.RegisterClass("TOOLKIT.UnityStyleLightingPlugin",i),e.SceneManager.RegisterClass("TOOLKIT.CustomShaderMaterialPlugin",n)}(i||(i={})),function(e){var t=function(){function t(e){this._babylonScene=e,this._physicList=[],this._shadowList=[],this._scriptList=[],this._freezeList=[]}return t.prototype.parseSceneComponents=function(t){e.MetadataParser.DoParseSceneComponents(this._babylonScene,t,this._physicList,this._shadowList,this._scriptList,this._freezeList)},t.prototype.postProcessSceneComponents=function(t,n){e.MetadataParser.DoProcessPendingPhysics(this._babylonScene,this._physicList),e.MetadataParser.DoProcessPendingShadows(this._babylonScene,this._shadowList),e.MetadataParser.DoProcessPendingScripts(this._babylonScene,this._scriptList,t,n),e.MetadataParser.DoProcessPendingFreezes(this._freezeList),this._babylonScene=null,this._physicList=null,this._shadowList=null,this._scriptList=null,this._freezeList=null},t.DoParseSceneComponents=function(t,n,i,r,o,a){if(null!=n&&null!=n.metadata&&null!=n.metadata.toolkit&&null!=n.metadata.toolkit.parsed&&!1===n.metadata.toolkit.parsed){n.onDisposeObservable.addOnce(function(){e.Utilities.DisposeEntity(n)}),n.metadata.toolkit.parsed=!0,n.metadata.toolkit.prefab=!1;var s=n.metadata.toolkit,l=null==n.metadata.toolkit.visible||n.metadata.toolkit.visible,u=null!=n.metadata.toolkit.visibility?n.metadata.toolkit.visibility:1,c=null!=n.metadata.toolkit.billboard?n.metadata.toolkit.billboard:0,d=n instanceof BABYLON.AbstractMesh,h=(null!=n.metadata.toolkit.lightmapped&&n.metadata.toolkit.lightmapped,s.tags);if(null!=h&&""!==h&&(BABYLON.Tags.AddTagsTo(n,h),h.indexOf("NavigationMesh")>=0&&(n.isVisible=!1,n.isPickable=!1,n.useVertexColors=!1)),null!=s.physics&&null!=i&&i.push(n),null!=s.renderer)if(!0===d)n.isPickable=!0,n.useVertexColors=!1,n.isVisible=l,n.visibility=u,n.billboardMode=c,n.cullingStrategy=BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD,null!=s.renderer.cullingstrategy&&s.renderer.cullingstrategy!==BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD&&(n.cullingStrategy=s.renderer.cullingstrategy),null!=s.renderer.castshadows&&!0===s.renderer.castshadows&&null!=r&&r.push(n),null!=s.renderer.receiveshadows&&!0===s.renderer.receiveshadows&&(n.receiveShadows=!0),null!=s.renderer.checkcollisions&&!0===s.renderer.checkcollisions&&(n.checkCollisions=!0),null!=s.renderer.istriggervolume&&!0===s.renderer.istriggervolume&&(n.collisionResponse=!1),null!=s.renderer.usevertexcolors&&(n.useVertexColors=s.renderer.usevertexcolors),null!=s.renderer.setmeshpickable&&(n.isPickable=s.renderer.setmeshpickable),null!=s.renderer.showboundingbox&&(n.showBoundingBox=s.renderer.showboundingbox),null!=s.renderer.defaultellipsoid&&(n.ellipsoid=e.Utilities.ParseVector3(s.renderer.defaultellipsoid)),null!=s.renderer.ellipsoidoffset&&(n.ellipsoidOffset=e.Utilities.ParseVector3(s.renderer.ellipsoidoffset)),null!=s.renderer.rendergroupid&&(n.renderingGroupId=s.renderer.rendergroupid),null!=s.renderer.freezeworldmatrix&&!0===s.renderer.freezeworldmatrix&&null!=a&&a.push(n),null!=s.renderer.snapshotrendering&&s.renderer.snapshotrendering>0&&(e.Utilities.PrepareSkeletonForRendering(n.skeleton),n.alwaysSelectAsActiveMesh=!0);else{var p=e.SceneManager.GetSkinnedMesh(n);if(null!=p)p.isPickable=!0,p.useVertexColors=!1,p.isVisible=l,p.visibility=u,p.billboardMode=c,p.cullingStrategy=BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD,p.alwaysSelectAsActiveMesh=!0,null!=s.renderer.cullingstrategy&&s.renderer.cullingstrategy!==BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD&&(p.cullingStrategy=s.renderer.cullingstrategy),null!=s.renderer.castshadows&&!0===s.renderer.castshadows&&null!=r&&r.push(p),null!=s.renderer.receiveshadows&&!0===s.renderer.receiveshadows&&(p.receiveShadows=!0),null!=s.renderer.checkcollisions&&!0===s.renderer.checkcollisions&&(p.checkCollisions=!0),null!=s.renderer.istriggervolume&&!0===s.renderer.istriggervolume&&(p.collisionResponse=!1),null!=s.renderer.usevertexcolors&&(p.useVertexColors=s.renderer.usevertexcolors),null!=s.renderer.setmeshpickable&&(p.isPickable=s.renderer.setmeshpickable),null!=s.renderer.showboundingbox&&(p.showBoundingBox=s.renderer.showboundingbox),null!=s.renderer.defaultellipsoid&&(p.ellipsoid=e.Utilities.ParseVector3(s.renderer.defaultellipsoid)),null!=s.renderer.ellipsoidoffset&&(p.ellipsoidOffset=e.Utilities.ParseVector3(s.renderer.ellipsoidoffset)),null!=s.renderer.rendergroupid&&(p.renderingGroupId=s.renderer.rendergroupid),null!=s.renderer.freezeworldmatrix&&!0===s.renderer.freezeworldmatrix&&null!=a&&a.push(p),null!=s.renderer.snapshotrendering&&s.renderer.snapshotrendering>0&&e.Utilities.PrepareSkeletonForRendering(p.skeleton);else{var m=e.SceneManager.GetPrimitiveMeshes(n);null!=m&&m.length>0&&m.forEach(function(t){var n=e.SceneManager.GetSkinnedMesh(t);null!=n?(n.isPickable=!0,n.useVertexColors=!1,n.isVisible=l,n.visibility=u,n.billboardMode=c,n.cullingStrategy=BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD,n.alwaysSelectAsActiveMesh=!0,null!=s.renderer.cullingstrategy&&s.renderer.cullingstrategy!==BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD&&(n.cullingStrategy=s.renderer.cullingstrategy),null!=s.renderer.castshadows&&!0===s.renderer.castshadows&&null!=r&&r.push(n),null!=s.renderer.receiveshadows&&!0===s.renderer.receiveshadows&&(n.receiveShadows=!0),null!=s.renderer.checkcollisions&&!0===s.renderer.checkcollisions&&(n.checkCollisions=!0),null!=s.renderer.istriggervolume&&!0===s.renderer.istriggervolume&&(n.collisionResponse=!1),null!=s.renderer.usevertexcolors&&(n.useVertexColors=s.renderer.usevertexcolors),null!=s.renderer.setmeshpickable&&(n.isPickable=s.renderer.setmeshpickable),null!=s.renderer.showboundingbox&&(n.showBoundingBox=s.renderer.showboundingbox),null!=s.renderer.defaultellipsoid&&(n.ellipsoid=e.Utilities.ParseVector3(s.renderer.defaultellipsoid)),null!=s.renderer.ellipsoidoffset&&(n.ellipsoidOffset=e.Utilities.ParseVector3(s.renderer.ellipsoidoffset)),null!=s.renderer.rendergroupid&&(n.renderingGroupId=s.renderer.rendergroupid),null!=s.renderer.freezeworldmatrix&&!0===s.renderer.freezeworldmatrix&&null!=a&&a.push(n),null!=s.renderer.snapshotrendering&&s.renderer.snapshotrendering>0&&e.Utilities.PrepareSkeletonForRendering(n.skeleton)):(t.isPickable=!0,t.useVertexColors=!1,t.isVisible=l,t.visibility=u,t.billboardMode=c,t.cullingStrategy=BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD,null!=s.renderer.cullingstrategy&&s.renderer.cullingstrategy!==BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD&&(t.cullingStrategy=s.renderer.cullingstrategy),null!=s.renderer.castshadows&&!0===s.renderer.castshadows&&null!=r&&r.push(t),null!=s.renderer.receiveshadows&&!0===s.renderer.receiveshadows&&(t.receiveShadows=!0),null!=s.renderer.checkcollisions&&!0===s.renderer.checkcollisions&&(t.checkCollisions=!0),null!=s.renderer.istriggervolume&&!0===s.renderer.istriggervolume&&(t.collisionResponse=!1),null!=s.renderer.usevertexcolors&&(t.useVertexColors=s.renderer.usevertexcolors),null!=s.renderer.setmeshpickable&&(t.isPickable=s.renderer.setmeshpickable),null!=s.renderer.showboundingbox&&(t.showBoundingBox=s.renderer.showboundingbox),null!=s.renderer.defaultellipsoid&&(t.ellipsoid=e.Utilities.ParseVector3(s.renderer.defaultellipsoid)),null!=s.renderer.ellipsoidoffset&&(t.ellipsoidOffset=e.Utilities.ParseVector3(s.renderer.ellipsoidoffset)),null!=s.renderer.rendergroupid&&(t.renderingGroupId=s.renderer.rendergroupid),null!=s.renderer.freezeworldmatrix&&!0===s.renderer.freezeworldmatrix&&null!=a&&a.push(t),null!=s.renderer.snapshotrendering&&s.renderer.snapshotrendering>0&&(e.Utilities.PrepareSkeletonForRendering(t.skeleton),t.alwaysSelectAsActiveMesh=!0))})}}if(null!=s.components){var f=s.components;null!=f&&f.length>0&&f.forEach(function(i){if(null!=i)switch(i.alias){case"camera":e.MetadataParser.SetupCameraComponent(t,n,i);break;case"light":e.MetadataParser.SetupLightComponent(t,n,i);break;case"script":null!=o&&o.push({mesh:n,comp:i})}})}}},t.DoProcessPendingScripts=function(t,n,i,r){null!=n&&n.length>0&&(n.sort(function(e,t){return e.comp.order<t.comp.order?-1:e.comp.order>t.comp.order?1:0}),n.forEach(function(n){if(null!=n.comp.klass&&""!==n.comp.klass){if(!0===e.SceneManager.AutoStripNamespacePrefix&&!1===e.SceneManager.UniversalModuleDefinition){var o=n.comp.klass.lastIndexOf(".");-1!==o&&(n.comp.klass=n.comp.klass.substring(o+1))}if("TOOLKIT.ScriptComponent"!==n.comp.klass){var a=n.comp.klass;null==n.comp.properties&&(n.comp.properties={}),n.comp.properties._scriptComponentAlias=a,n.comp.properties._registerComponentAlias=!1;var s=e.Utilities.InstantiateClass(a);if(null!=s){var l=new s(n.mesh,t,n.comp.properties);null!=l?(n.comp.instance=l,null!=r&&r.push(n.comp.instance),n.comp.instance.addPreloaderTasks&&null!=i&&i.push(n.comp.instance),e.SceneManager.AttachScriptComponent(n.comp.instance,a,!1)):BABYLON.Tools.Warn("Failed to instantiate script class: "+a)}else BABYLON.Tools.Warn("Failed to locate script class: "+a)}}}))},t.DoProcessPendingShadows=function(e,t){null!=t&&t.length>0&&null!=e.lights&&e.lights.length>0&&e.lights.forEach(function(e){var n=e.getShadowGenerator();null!=n&&null!=e.metadata&&null!=e.metadata.toolkit&&!0===e.metadata.toolkit.autorender&&t.forEach(function(t){!0==(!(null!=e.includedOnlyMeshes&&e.includedOnlyMeshes.length>0)||e.includedOnlyMeshes.indexOf(t)>=0)&&n.addShadowCaster(t,!1)})})},t.DoProcessPendingPhysics=function(t,n){if(null!=n&&n.length>0){var i=t.isPhysicsEnabled(),r=!0===i?t.getPhysicsEngine():null;!0==(!0===i&&null!=r)?n.forEach(function(n){e.RigidbodyPhysics.SetupPhysicsComponent(t,n)}):BABYLON.Tools.Warn("Physics engine not loaded. Physics impostors will not be created.")}},t.DoProcessPendingFreezes=function(e){null!=e&&e.length>0&&e.forEach(function(e){e.freezeWorldMatrix()})},t.SetupCameraComponent=function(t,n,i){n.checkCollisions=!1;var r=0,o=n.name+".Rig",a=null!=i.culling?i.culling:-1,s=null!=i.camerabase?i.camerabase:0,l=(null!=i.clearflags&&i.clearflags,null!=i.renderlist?i.renderlist:null),u=null!=i.maincamera&&i.maincamera,c=4===s?new BABYLON.FreeCamera(o,BABYLON.Vector3.Zero(),t):new BABYLON.UniversalCamera(o,BABYLON.Vector3.Zero(),t);switch(c.layerMask=~e.SceneManager.HiddenLayerMask,c.checkCollisions=!1,c.rotationQuaternion=BABYLON.Quaternion.FromEulerAngles(0,0,0),c.parent=n,!0===u&&(t.activeCamera=c),null!=i.type?i.type:0){case 0:c.mode=BABYLON.Camera.PERSPECTIVE_CAMERA,null!=i.perspectiveyfov&&(c.fov=i.perspectiveyfov),null!=i.perspectiveznear&&(c.minZ=i.perspectiveznear),null!=i.perspectivezfar&&(c.maxZ=i.perspectivezfar);break;case 1:c.mode=BABYLON.Camera.ORTHOGRAPHIC_CAMERA,null!=i.orthoxmag&&(c.orthoLeft=-i.orthoxmag,c.orthoRight=i.orthoxmag),null!=i.orthoymag&&(c.orthoBottom=-i.orthoymag,c.orthoTop=i.orthoymag),null!=i.orthoznear&&(c.minZ=i.orthoznear),null!=i.orthozfar&&(c.maxZ=i.orthozfar)}if(-1===a);else if(0===a);else{var d=l;if(null!=d&&d.length>0){var h=function(){var n=d[r],i=e.SceneManager.GetMeshByID(t,n);if(null!=i){var o=i.name+".Detail",a=i.getChildren(function(e){return e.name===o},!0);null!=a&&a.length}};for(r=0;r<d.length;r++)h()}}n.cameraRig=c},t.SetupLightComponent=function(t,n,i){n.checkCollisions=!1;var r,o=n.name+".Rig",a=0,s=BABYLON.Light.INTENSITYMODE_AUTOMATIC,l=1,u=null!=i.culling?i.culling:-1,c=(null!=i.clearflags&&i.clearflags,null!=i.renderlist?i.renderlist:null),d=null!=i.type?i.type:0,h=e.SceneManager.GetRenderQuality(),p=null!=i.exponentdecayspeed?i.exponentdecayspeed:1,m=!1;switch(d){case 0:var f=BABYLON.Vector3.Forward(),g=null!=i.orthoscale?i.orthoscale:.1,v=null!=i.ortholeft?i.ortholeft:Number.MAX_VALUE,y=null!=i.orthoright?i.orthoright:Number.MAX_VALUE,_=null!=i.orthotop?i.orthotop:Number.MAX_VALUE,S=null!=i.orthobottom?i.orthobottom:Number.MAX_VALUE,A=null!=i.calczbounds&&i.calczbounds,b=null!=i.updateextends&&i.updateextends,M=null!=i.shadowfrustumsize?i.shadowfrustumsize:0,B=new BABYLON.DirectionalLight(o,f,t);B.shadowFrustumSize=M,B.shadowOrthoScale=g,B.autoCalcShadowZBounds=A,B.autoUpdateExtends=b,B.orthoLeft=v,B.orthoRight=y,B.orthoTop=_,B.orthoBottom=S,(r=B).falloffType=BABYLON.Light.FALLOFF_STANDARD,m=h===e.RenderQuality.High||h===e.RenderQuality.Medium,s=BABYLON.Light.INTENSITYMODE_ILLUMINANCE,l=e.SceneManager.DirectionalLightIntensity;break;case 1:var C=r=new BABYLON.PointLight(o,BABYLON.Vector3.Zero(),t);(r=C).falloffType=BABYLON.Light.FALLOFF_STANDARD,m=h===e.RenderQuality.High||h===e.RenderQuality.Medium,s=BABYLON.Light.INTENSITYMODE_LUMINOUSPOWER,l=e.SceneManager.PointLightIntensity;break;case 2:f=BABYLON.Vector3.Forward();var T=null!=i.spotangle?i.spotangle:Math.PI/4,x=new BABYLON.SpotLight(o,BABYLON.Vector3.Zero(),f,0,p,t);x.angle=.966*BABYLON.Tools.ToRadians(T),x.innerAngle=.8*x.angle,(r=x).falloffType=BABYLON.Light.FALLOFF_GLTF,m=h===e.RenderQuality.High||h===e.RenderQuality.Medium,s=BABYLON.Light.INTENSITYMODE_LUMINOUSPOWER,l=e.SceneManager.SpotLightIntensity}if(null!=r){var I=null!=i.range?i.range:Number.MAX_VALUE,O=null!=i.color?e.Utilities.ParseColor3(i.color,BABYLON.Color3.White()):BABYLON.Color3.White(),L=null!=i.specular?e.Utilities.ParseColor3(i.specular,BABYLON.Color3.White()):BABYLON.Color3.White(),w=null!=i.lightmapmode?i.lightmapmode:0;switch(null!=i.lightmaptype&&i.lightmaptype,r.parent=n,r.range=I,r.diffuse=O,r.specular=L,r.intensity=(null!=i.intensity?i.intensity:1)*l,w){case 2:r.lightmapMode=BABYLON.Light.LIGHTMAP_SHADOWSONLY;break;case 1:r.lightmapMode=BABYLON.Light.LIGHTMAP_SPECULAR;break;default:r.lightmapMode=BABYLON.Light.LIGHTMAP_DEFAULT}r.intensityMode=s,r.shadowEnabled=!1;var N=null==i.autorender||i.autorender,P=null!=i.softshadows&&i.softshadows,R=null!=i.numcascades?i.numcascades:0,E=null!=i.cascadelambda?i.cascadelambda:1,k=null!=i.setdepthclamp&&i.setdepthclamp,D=null!=i.blendpertecntage?i.blendpertecntage:1e-8,F=null!=i.boundsrefreshrate?i.boundsrefreshrate:1,U=null!=i.lightcontactratio?i.lightcontactratio:.1,Y=null!=i.stabilizecascades&&i.stabilizecascades,V=null!=i.penumbradarkness?i.penumbradarkness:1,G=null!=i.softshadowsfilter?i.softshadowsfilter:99,z=null!=i.freezeshadows&&i.freezeshadows,W=null!=i.calcdepths&&i.calcdepths,H=null!=i.depthscaling?i.depthscaling:50,X=null!=i.blurscaling?i.blurscaling:2,K=null==i.kernelblur||i.kernelblur,Q=null!=i.blurkernelsize?i.blurkernelsize:1,j=null!=i.blurboxoffset?i.blurboxoffset:1,Z=null!=i.shadowmapsize?i.shadowmapsize:1024,q=null!=i.generateshadows&&i.generateshadows,J=null!=i.shadowbiasfactor?i.shadowbiasfactor:.01,$=null!=i.normalbiasfactor?i.normalbiasfactor:.01,ee=null!=i.shadowmapbias?i.shadowmapbias:.05,te=null!=i.normalmapbias?i.normalmapbias:.4,ne=null!=i.shadowstrength?i.shadowstrength:1,ie=null!=i.shadowdistance?i.shadowdistance:150,re=null!=i.shadownearplane?i.shadownearplane:.2,oe=null!=i.shadowfilterquality?i.shadowfilterquality:"Medium",ae=null!=i.transparencyshadow&&i.transparencyshadow,se=null!=i.softtransparency&&i.softtransparency,le=null==i.forcebackfacesonly||i.forcebackfacesonly,ue=null!=i.frustumedgefalloff?i.frustumedgefalloff:0,ce=null!=i.usefullfloatfirst&&i.usefullfloatfirst;if(!0===m&&!0===q){var de=r,he=e.SceneManager.GetEngine(t),pe=he instanceof BABYLON.Engine?he.webGLVersion:0,me=he instanceof BABYLON.WebGPUEngine?1:0,fe=0===d&&R>=2&&(pe>=2||me>=1),ge=!0===fe?new BABYLON.CascadedShadowGenerator(Z,r,ce):new BABYLON.ShadowGenerator(Z,de,ce);if(ge.bias=ee*J,ge.normalBias=te*$,ge.depthScale=H,ge.useKernelBlur=K,ge.blurKernel=Q,ge.blurScale=X,ge.blurBoxOffset=j,ge.frustumEdgeFalloff=ue,ge.forceBackFacesOnly=le,ge.transparencyShadow=ae,ge.enableSoftTransparentShadow=se,ge.contactHardeningLightSizeUVRatio=U,!0===P)if(pe<=1&&me<=0)ge.usePoissonSampling=!0;else if(!0===fe)ge.usePercentageCloserFiltering=!0;else switch(G){case 0:default:ge.usePoissonSampling=!0;break;case 1:ge.useExponentialShadowMap=!0;break;case 2:ge.useBlurExponentialShadowMap=!0;break;case 3:ge.useCloseExponentialShadowMap=!0;break;case 4:ge.useBlurCloseExponentialShadowMap=!0;break;case 5:ge.useContactHardeningShadow=!0;break;case 99:ge.usePercentageCloserFiltering=!0}switch(oe){case"High":ge.filteringQuality=BABYLON.ShadowGenerator.QUALITY_HIGH;break;case"Medium":ge.filteringQuality=BABYLON.ShadowGenerator.QUALITY_MEDIUM;break;case"Low":ge.filteringQuality=BABYLON.ShadowGenerator.QUALITY_LOW}if(!0===fe){var ve=ge;ve.lambda=E,ve.depthClamp=k,ve.shadowMaxZ=ie,ve.numCascades=R,ve.penumbraDarkness=V,ve.autoCalcDepthBounds=W,ve.stabilizeCascades=Y,ve.cascadeBlendPercentage=D,ve.autoCalcDepthBoundsRefreshRate=F,ve.freezeShadowCastersBoundingInfo=z,ve.setDarkness(1-BABYLON.Scalar.Clamp(ne)),de.shadowEnabled=!0,ve.splitFrustum()}else ge.setDarkness(1-BABYLON.Scalar.Clamp(ne)),de.shadowEnabled=!0,de.shadowMinZ=re,de.shadowMaxZ=ie;null==r.metadata&&(r.metadata={}),null==r.metadata.toolkit&&(r.metadata.toolkit={}),r.metadata.toolkit.autorender=N}var ye=n.name+".Holder";if(-1===u)r.includedOnlyMeshes=[];else if(0===u)r.includedOnlyMeshes=[new BABYLON.Mesh(ye,t)];else{r.includedOnlyMeshes=[new BABYLON.Mesh(ye,t)];var _e=c;if(null!=_e&&_e.length>0){var Se=function(){var n=_e[a],i=e.SceneManager.GetMeshByID(t,n);if(null!=i){var o=i.name+".Detail",s=i.getChildren(function(e){return e.name===o},!0);null!=s&&s.length>0?r.includedOnlyMeshes.push(s[0]):r.includedOnlyMeshes.push(i)}};for(a=0;a<_e.length;a++)Se()}}n.lightRig=r}},t}();e.MetadataParser=t}(i||(i={})),function(e){var t=function(){function e(e){for(var t=new Array(256),n=0;n<256;n++)t[n]=n;var i=(0|e)>>>0,r=function(){return(i=16807*i%2147483647)/2147483647};for(n=255;n>0;n--){var o=Math.floor(r()*(n+1)),a=t[n];t[n]=t[o],t[o]=a}for(this.perm=new Array(512),n=0;n<512;n++)this.perm[n]=t[255&n]}return e.prototype.fade=function(e){return e*e*e*(e*(6*e-15)+10)},e.prototype.lerp=function(e,t,n){return e+n*(t-e)},e.prototype.grad=function(e,t,n){var i=7&e,r=i<4?t:n,o=i<4?n:t;return(1&i?-r:r)+(2&i?-o:o)},e.prototype.noise=function(e,t){var n=255&Math.floor(e),i=255&Math.floor(t),r=e-Math.floor(e),o=t-Math.floor(t),a=this.fade(r),s=this.fade(o),l=this.perm[n]+i,u=this.perm[n+1]+i;return this.lerp(this.lerp(this.grad(this.perm[l],r,o),this.grad(this.perm[u],r-1,o),a),this.lerp(this.grad(this.perm[l+1],r,o-1),this.grad(this.perm[u+1],r-1,o-1),a),s)},e}();e.Perlin2D=t;var n=function(){function e(){}return e.fastFloor=function(e){return 0|Math.floor(e)},e.createNoise2D=function(t){void 0===t&&(t=Math.random);var n=e.buildPermutationTable(t),i=new Float64Array(n).map(function(t){return e.grad2[t%12*2]}),r=new Float64Array(n).map(function(t){return e.grad2[t%12*2+1]});return function(t,o){var a,s,l=0,u=0,c=0,d=(t+o)*e.F2,h=e.fastFloor(t+d),p=e.fastFloor(o+d),m=(h+p)*e.G2,f=t-(h-m),g=o-(p-m);f>g?(a=1,s=0):(a=0,s=1);var v=f-a+e.G2,y=g-s+e.G2,_=f-1+2*e.G2,S=g-1+2*e.G2,A=255&h,b=255&p,M=.5-f*f-g*g;if(M>=0){var B=A+n[b];l=(M*=M)*M*(i[B]*f+r[B]*g)}var C=.5-v*v-y*y;if(C>=0){var T=A+a+n[b+s];u=(C*=C)*C*(i[T]*v+r[T]*y)}var x=.5-_*_-S*S;if(x>=0){var I=A+1+n[b+1];c=(x*=x)*x*(i[I]*_+r[I]*S)}return 70*(l+u+c)}},e.createNoise3D=function(t){void 0===t&&(t=Math.random);var n=e.buildPermutationTable(t),i=new Float64Array(n).map(function(t){return e.grad3[t%12*3]}),r=new Float64Array(n).map(function(t){return e.grad3[t%12*3+1]}),o=new Float64Array(n).map(function(t){return e.grad3[t%12*3+2]});return function(t,a,s){var l,u,c,d,h,p,m,f,g,v,y=(t+a+s)*e.F3,_=e.fastFloor(t+y),S=e.fastFloor(a+y),A=e.fastFloor(s+y),b=(_+S+A)*e.G3,M=t-(_-b),B=a-(S-b),C=s-(A-b);M>=B?B>=C?(h=1,p=0,m=0,f=1,g=1,v=0):M>=C?(h=1,p=0,m=0,f=1,g=0,v=1):(h=0,p=0,m=1,f=1,g=0,v=1):B<C?(h=0,p=0,m=1,f=0,g=1,v=1):M<C?(h=0,p=1,m=0,f=0,g=1,v=1):(h=0,p=1,m=0,f=1,g=1,v=0);var T=M-h+e.G3,x=B-p+e.G3,I=C-m+e.G3,O=M-f+2*e.G3,L=B-g+2*e.G3,w=C-v+2*e.G3,N=M-1+3*e.G3,P=B-1+3*e.G3,R=C-1+3*e.G3,E=255&_,k=255&S,D=255&A,F=.6-M*M-B*B-C*C;if(F<0)l=0;else{var U=E+n[k+n[D]];l=(F*=F)*F*(i[U]*M+r[U]*B+o[U]*C)}var Y=.6-T*T-x*x-I*I;if(Y<0)u=0;else{var V=E+h+n[k+p+n[D+m]];u=(Y*=Y)*Y*(i[V]*T+r[V]*x+o[V]*I)}var G=.6-O*O-L*L-w*w;if(G<0)c=0;else{var z=E+f+n[k+g+n[D+v]];c=(G*=G)*G*(i[z]*O+r[z]*L+o[z]*w)}var W=.6-N*N-P*P-R*R;if(W<0)d=0;else{var H=E+1+n[k+1+n[D+1]];d=(W*=W)*W*(i[H]*N+r[H]*P+o[H]*R)}return 32*(l+u+c+d)}},e.createNoise4D=function(t){void 0===t&&(t=Math.random);var n=e.buildPermutationTable(t),i=new Float64Array(n).map(function(t){return e.grad4[t%32*4]}),r=new Float64Array(n).map(function(t){return e.grad4[t%32*4+1]}),o=new Float64Array(n).map(function(t){return e.grad4[t%32*4+2]}),a=new Float64Array(n).map(function(t){return e.grad4[t%32*4+3]});return function(t,s,l,u){var c,d,h,p,m,f=(t+s+l+u)*e.F4,g=e.fastFloor(t+f),v=e.fastFloor(s+f),y=e.fastFloor(l+f),_=e.fastFloor(u+f),S=(g+v+y+_)*e.G4,A=t-(g-S),b=s-(v-S),M=l-(y-S),B=u-(_-S),C=0,T=0,x=0,I=0;A>b?C++:T++,A>M?C++:x++,A>B?C++:I++,b>M?T++:x++,b>B?T++:I++,M>B?x++:I++;var O=C>=3?1:0,L=T>=3?1:0,w=x>=3?1:0,N=I>=3?1:0,P=C>=2?1:0,R=T>=2?1:0,E=x>=2?1:0,k=I>=2?1:0,D=C>=1?1:0,F=T>=1?1:0,U=x>=1?1:0,Y=I>=1?1:0,V=A-O+e.G4,G=b-L+e.G4,z=M-w+e.G4,W=B-N+e.G4,H=A-P+2*e.G4,X=b-R+2*e.G4,K=M-E+2*e.G4,Q=B-k+2*e.G4,j=A-D+3*e.G4,Z=b-F+3*e.G4,q=M-U+3*e.G4,J=B-Y+3*e.G4,$=A-1+4*e.G4,ee=b-1+4*e.G4,te=M-1+4*e.G4,ne=B-1+4*e.G4,ie=255&g,re=255&v,oe=255&y,ae=255&_,se=.6-A*A-b*b-M*M-B*B;if(se<0)c=0;else{var le=ie+n[re+n[oe+n[ae]]];c=(se*=se)*se*(i[le]*A+r[le]*b+o[le]*M+a[le]*B)}var ue=.6-V*V-G*G-z*z-W*W;if(ue<0)d=0;else{var ce=ie+O+n[re+L+n[oe+w+n[ae+N]]];d=(ue*=ue)*ue*(i[ce]*V+r[ce]*G+o[ce]*z+a[ce]*W)}var de=.6-H*H-X*X-K*K-Q*Q;if(de<0)h=0;else{var he=ie+P+n[re+R+n[oe+E+n[ae+k]]];h=(de*=de)*de*(i[he]*H+r[he]*X+o[he]*K+a[he]*Q)}var pe=.6-j*j-Z*Z-q*q-J*J;if(pe<0)p=0;else{var me=ie+D+n[re+F+n[oe+U+n[ae+Y]]];p=(pe*=pe)*pe*(i[me]*j+r[me]*Z+o[me]*q+a[me]*J)}var fe=.6-$*$-ee*ee-te*te-ne*ne;if(fe<0)m=0;else{var ge=ie+1+n[re+1+n[oe+1+n[ae+1]]];m=(fe*=fe)*fe*(i[ge]*$+r[ge]*ee+o[ge]*te+a[ge]*ne)}return 27*(c+d+h+p+m)}},e.buildPermutationTable=function(e){for(var t=new Uint8Array(512),n=0;n<256;n++)t[n]=n;for(n=0;n<255;n++){var i=n+~~(e()*(256-n)),r=t[n];t[n]=t[i],t[i]=r}for(n=256;n<512;n++)t[n]=t[n-256];return t},e.F2=.5*(Math.sqrt(3)-1),e.G2=(3-Math.sqrt(3))/6,e.F3=1/3,e.G3=1/6,e.F4=(Math.sqrt(5)-1)/4,e.G4=(5-Math.sqrt(5))/20,e.grad2=new Float64Array([1,1,-1,1,1,-1,-1,-1,1,0,-1,0,1,0,-1,0,0,1,0,-1,0,1,0,-1]),e.grad3=new Float64Array([1,1,0,-1,1,0,1,-1,0,-1,-1,0,1,0,1,-1,0,1,1,0,-1,-1,0,-1,0,1,1,0,-1,1,0,1,-1,0,-1,-1]),e.grad4=new Float64Array([0,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,1,0,1,1,1,0,1,-1,1,0,-1,1,1,0,-1,-1,-1,0,1,1,-1,0,1,-1,-1,0,-1,1,-1,0,-1,-1,1,1,0,1,1,1,0,-1,1,-1,0,1,1,-1,0,-1,-1,1,0,1,-1,1,0,-1,-1,-1,0,1,-1,-1,0,-1,1,1,1,0,1,1,-1,0,1,-1,1,0,1,-1,-1,0,-1,1,1,0,-1,1,-1,0,-1,-1,1,0,-1,-1,-1,0]),e}();e.SimplexNoise=n}(i||(i={})),function(e){var t=function(e){function t(t,n){var i=e.call(this,t,n)||this;return i.universalMaterial=!0,i._defines={},i._uniforms=[],i._samplers=[],i._attributes=[],i._textures={},i._vectors4={},i._vectors3={},i._vectors2={},i._floats={},i._bools={},i._ubos=null,i._wgslSamplers=null,i.shader=null,i.plugin=null,i.shader="StandardShaderMaterial",i.specularColor=new BABYLON.Color3(0,0,0),i}return r(t,e),t.prototype.getClassName=function(){return"StandardMaterial"},t.prototype.initMaterial=function(){this.awake&&this.awake()},t.prototype.addAttribute=function(e){-1===this._attributes.indexOf(e)&&this._attributes.push(e)},t.prototype.checkUniform=function(e,t,n){void 0===n&&(n=null),-1===this._uniforms.indexOf(e)&&(this._uniforms.push(e),this._defines[e.toUpperCase()]=!0,this.buildUniformProperty(e,t,n))},t.prototype.checkSampler=function(e,t){void 0===t&&(t=null),-1===this._samplers.indexOf(e)&&(this._samplers.push(e),this._defines[e.toUpperCase()]=!0,this.buildUniformProperty(e,"sampler2D",t),this.checkUniform(e+"Infos","vec2",BABYLON.Vector2.Zero()),this.checkUniform(e+"Matrix","mat4",BABYLON.Matrix.Identity()))},t.prototype.addTextureUniform=function(e,t){return this.checkSampler(e,t),this._textures[e]=t,this},t.prototype.setTextureValue=function(e,t){return this._textures[e]=t,this},t.prototype.getTextureValue=function(e){return this._textures[e]},t.prototype.addVector4Uniform=function(e,t){return this.checkUniform(e,"vec4",t),this._vectors4[e]=t,this},t.prototype.setVector4Value=function(e,t){return this._vectors4[e]=t,this},t.prototype.getVector4Value=function(e){return this._vectors4[e]},t.prototype.addVector3Uniform=function(e,t){return this.checkUniform(e,"vec3",t),this._vectors3[e]=t,this},t.prototype.setVector3Value=function(e,t){return this._vectors3[e]=t,this},t.prototype.getVector3Value=function(e){return this._vectors3[e]},t.prototype.addVector2Uniform=function(e,t){return this.checkUniform(e,"vec2",t),this._vectors2[e]=t,this},t.prototype.setVector2Value=function(e,t){return this._vectors2[e]=t,this},t.prototype.getVector2Value=function(e){return this._vectors2[e]},t.prototype.addFloatUniform=function(e,t){return this.checkUniform(e,"float",t),this._floats[e]=t,this},t.prototype.setFloatValue=function(e,t){return this._floats[e]=t,this},t.prototype.getFloatValue=function(e){return this._floats[e]},t.prototype.addBoolUniform=function(e,t){return this.checkUniform(e,"bool",t),this._bools[e]=t,this},t.prototype.setBoolValue=function(e,t){return this._bools[e]=t,this},t.prototype.getBoolValue=function(e){return this._bools[e]},t.prototype.getAnimatables=function(){var t=e.prototype.getAnimatables.call(this);for(var n in this._textures){var i=this._textures[n];i&&i.animations&&i.animations.length>0&&t.push(i)}return t},t.prototype.getActiveTextures=function(){var t=e.prototype.getActiveTextures.call(this);for(var n in this._textures){var i=this._textures[n];i&&t.push(i)}return t},t.prototype.hasTexture=function(t){if(e.prototype.hasTexture.call(this,t))return!0;for(var n in this._textures)if(this._textures[n]===t)return!0;return!1},t.prototype.getCustomUniforms=function(e){var t={};return null!=this._ubos&&this._ubos.length>0&&(t.ubo=this._ubos.filter(function(e){return"sampler2D"!==e.type})),!1===e&&(t.fragment=this.getCustomFragmentCode(!1)),t},t.prototype.getCustomSamplers=function(){return this._samplers},t.prototype.getCustomAttributes=function(){return this._attributes},t.prototype.getCustomVertexCode=function(e){return null},t.prototype.getCustomFragmentCode=function(e){var t=this,n=null;return null!=this._ubos&&this._ubos.length>0&&(n="#ifdef "+this.shader.toUpperCase()+"\n",this._ubos.forEach(function(i){if(!0===e)"sampler2D"===i.type&&(null==t._wgslSamplers&&(t._wgslSamplers=new Set),t._wgslSamplers.has(i.name)||(n+="\tvar "+i.name+": texture_2d<f32>;\n",n+="\tvar "+i.name+"Sampler: sampler;\n",t._wgslSamplers.add(i.name)));else{var r=i.name.toUpperCase()+"_DEFINED";"float"===i.type||"bool"===i.type||"int"===i.type?(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform float "+i.name+";\n",n+="\t#endif\n"):"vec2"===i.type?(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform vec2 "+i.name+";\n",n+="\t#endif\n"):"vec3"===i.type?(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform vec3 "+i.name+";\n",n+="\t#endif\n"):"vec4"===i.type?(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform vec4 "+i.name+";\n",n+="\t#endif\n"):"mat4"===i.type?(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform mat4 "+i.name+";\n",n+="\t#endif\n"):"sampler2D"===i.type&&(n+="\t#ifndef "+r+"\n",n+="\t#define "+r+"\n",n+="\tuniform sampler2D "+i.name+";\n",n+="\t#endif\n")}}),n+="#endif\n"),n},t.prototype.prepareCustomDefines=function(e){if(this._wgslSamplers&&this._wgslSamplers.clear(),e[this.shader.toUpperCase()]=!0,null!=this._defines){var t=Object.keys(this._defines);if(null!=t&&t.length>0)for(var n=0,i=t;n<i.length;n++){var r=i[n];e[r]=this._defines[r]}}e.isDirty&&e.rebuild()},t.prototype.updateCustomBindings=function(e){var t,n=this.getScene();this.update&&this.update();var i=null!=e&&"function"==typeof e.getUniformNames,r=i?e.getUniformNames():[],o=function(e){return i&&-1!==r.indexOf(e)};if(n.texturesEnabled)for(t in this._textures){var a=this._textures[t];null!=a&&a.isReady&&a.isReady()&&(null==a.isChecked&&(a.isChecked=!0,("detailsSampler"===t||"normalsSampler"===t||t.indexOf("(Atlas)")>=0)&&a.updateSamplingMode(8)),e.setTexture&&e.setTexture(t,a),o(t+"Infos")&&e.updateFloat2?e.updateFloat2(t+"Infos",a.coordinatesIndex,a.level):e.setFloat2?e.setFloat2(t+"Infos",a.coordinatesIndex,a.level):e.setFloat&&e.setFloat(t+"Infos",a.coordinatesIndex),o(t+"Matrix")&&e.updateMatrix?e.updateMatrix(t+"Matrix",a.getTextureMatrix()):e.setMatrix&&e.setMatrix(t+"Matrix",a.getTextureMatrix()))}for(t in this._vectors4){var s=this._vectors4[t];o(t)&&e.updateVector4?e.updateVector4(t,s):e.setVector4?e.setVector4(t,s):e.setFloat4&&e.setFloat4(t,s.x,s.y,s.z,s.w)}for(t in this._vectors3)s=this._vectors3[t],o(t)&&e.updateVector3?e.updateVector3(t,s):e.setVector3?e.setVector3(t,s):e.setFloat3&&e.setFloat3(t,s.x,s.y,s.z);for(t in this._vectors2)s=this._vectors2[t],o(t)&&e.updateFloat2?e.updateFloat2(t,s.x,s.y):e.setFloat2?e.setFloat2(t,s.x,s.y):e.setFloat&&e.setFloat(t,s.x);for(t in this._floats){var l=this._floats[t];o(t)&&e.updateFloat?e.updateFloat(t,l):e.setFloat&&e.setFloat(t,l)}for(t in this._bools)l=this._bools[t]?1:0,o(t)&&e.updateFloat?e.updateFloat(t,l):e.setFloat&&e.setFloat(t,l);i&&e.update&&e.update()},t.prototype.legacyUpdateCustomBindings=function(e){var t,n=this.getScene();if(this.update&&this.update(),n.texturesEnabled)for(t in this._textures){var i=this._textures[t];null!=i&&i.isReady&&i.isReady()&&(null==i.isChecked&&(i.isChecked=!0,("detailsSampler"===t||"normalsSampler"===t||t.indexOf("(Atlas)")>=0)&&i.updateSamplingMode(8)),e.setTexture(t,i),e.updateFloat2(t+"Infos",i.coordinatesIndex,i.level),e.updateMatrix(t+"Matrix",i.getTextureMatrix()))}for(t in this._vectors4)e.updateVector4(t,this._vectors4[t]);for(t in this._vectors3)e.updateVector3(t,this._vectors3[t]);for(t in this._vectors2)e.updateFloat2(t,this._vectors2[t].x,this._vectors2[t].y);for(t in this._floats)e.updateFloat(t,this._floats[t]);for(t in this._bools)e.updateFloat(t,this._bools[t]?1:0);e.update()},t.prototype.buildUniformProperty=function(e,t,n){var i=1;switch(t){case"float":case"bool":case"int":i=1;break;case"vec2":i=2;break;case"vec3":i=3;break;case"vec4":i=4;break;case"mat4":i=16}null==this._ubos&&(this._ubos=[]),this._ubos.push({name:e,size:i,type:t})},t}(BABYLON.StandardMaterial);e.StandardShaderMaterial=t;var n=function(e){function t(t,n,i,r,o,a,s){void 0===o&&(o=!0),void 0===a&&(a=!0),void 0===s&&(s=!1);var l=e.call(this,t,n,i,r,o,a,s)||this;return l._isEnabled=!1,l.vertexDefinitions=null,l.fragmentDefinitions=null,l.setIsEnabled(a),l}return r(t,e),t.prototype.getClassName=function(){return"StandardMaterialPlugin"},t.prototype.getIsEnabled=function(){return this._isEnabled},t.prototype.setIsEnabled=function(e){this._isEnabled=e,this._material.markAsDirty(BABYLON.Constants.MATERIAL_AllDirtyFlag),this.markAllDefinesAsDirty(),this._enable(this._isEnabled)},t.prototype.getCustomShaderMaterial=function(){return this._material},t}(BABYLON.MaterialPluginBase);e.StandardShaderMaterialPlugin=n,e.SceneManager.RegisterClass("TOOLKIT.StandardShaderMaterial",t),e.SceneManager.RegisterClass("TOOLKIT.StandardShaderMaterialPlugin",n)}(i||(i={})),function(e){var t=function(){function t(){}return t.ZeroPad=function(e,t){var n=t-e.toString().length+1;return Array(+(n>0&&n)).join("0")+e},t.ShiftArray=function(e,t){return t?e.unshift(e.pop()):e.push(e.shift()),e},t.GetLayerMask=function(e){return 1<<e},t.IsLayerMasked=function(e,t){return!!(e&1<<t)},t.GetHavokPlugin=function(){return globalThis.HKP},t.GetLoadingState=function(){return e.Utilities.LoadingState},t.GetRandomRange=function(e,t,n,i){void 0===n&&(n=null),void 0===i&&(i=null);var r=BABYLON.Scalar.RandomRange(e,t);if(null!=n){var o=null!=i?i:100;if(r===n)for(var a=0;a<o&&(r=BABYLON.Scalar.RandomRange(e,t))===n;a++);}return r},t.GetRandomFloat=function(t,n,i,r){return void 0===i&&(i=null),void 0===r&&(r=null),parseFloat(e.Utilities.GetRandomRange(t,n,i,r).toFixed(2))},t.GetRandomInteger=function(t,n,i,r){return void 0===i&&(i=null),void 0===r&&(r=null),parseInt(e.Utilities.GetRandomRange(t,n,i,r).toFixed(0))},t.Approximately=function(t,n){return Math.abs(n-t)<Math.max(e.System.Epsilon*Math.max(Math.abs(t),Math.abs(n)),8*e.System.SingleEpsilon)},t.GetVertexDataFromMesh=function(e){var t=e.computeWorldMatrix(!0),n=BABYLON.VertexData.ExtractFromMesh(e,!0,!0);return n.transform(t),n},t.CalculateDestinationPoint=function(t,n,i){var r=new BABYLON.Vector3(0,0,0);return e.Utilities.CalculateDestinationPointToRef(t,n,i,r),r},t.CalculateDestinationPointToRef=function(t,n,i,r){null==e.Utilities.TempDirectionBuffer&&(e.Utilities.TempDirectionBuffer=new BABYLON.Vector3(0,0,0)),e.Utilities.TempDirectionBuffer.set(0,0,0),n.scaleToRef(i,e.Utilities.TempDirectionBuffer),t.addToRef(e.Utilities.TempDirectionBuffer,r)},t.UpdateAbstractMeshMaterial=function(e,t,n){if(null!=e)if(!1==e instanceof BABYLON.InstancedMesh){var i=e.material;if(i instanceof BABYLON.MultiMaterial){var r=i.clone(i.name+".Clone");r.subMaterials[n]=t,e.material=r}else e.material=t}else console.warn("Instanced mesh not supported as a node material on mesh: "+e.name);else console.warn("Null source mesh for mesh: "+e.name)},t.HermiteVector3=function(t,n,i,r,o){var a=new BABYLON.Vector3(0,0,0);return e.Utilities.HermiteVector3ToRef(t,n,i,r,o,a),a},t.HermiteVector3ToRef=function(e,t,n,i,r,o){var a=r*r,s=r*a,l=2*s-3*a+1,u=-2*s+3*a,c=s-2*a+r,d=s-a,h=e._x*l+n._x*u+t._x*c+i._x*d,p=e._y*l+n._y*u+t._y*c+i._y*d,m=e._z*l+n._z*u+t._z*c+i._z*d;o.set(h,p,m)},t.ExpSmoothing=function(e,t){return t<=0?1:1-Math.exp(-e/t)},t.LerpLog=function(e,t,n){var i=Math.min(Math.max(n,0),1);return e+(t-e)*Math.sin(i*Math.PI*.5)},t.LerpExp=function(e,t,n){var i=Math.min(Math.max(n,0),1);return e+(t-e)*(1-Math.cos(i*Math.PI*.5))},t.LerpUnclamped=function(e,t,n){return e+(t-e)*n},t.LerpUnclampedColor3=function(t,n,i){var r=new BABYLON.Color3(0,0,0);return e.Utilities.LerpUnclampedColor3ToRef(t,n,i,r),r},t.LerpUnclampedColor3ToRef=function(e,t,n,i){i.set(e.r+(t.r-e.r)*n,e.g+(t.g-e.g)*n,e.b+(t.b-e.b)*n)},t.LerpUnclampedColor4=function(t,n,i){var r=new BABYLON.Color4(0,0,0,1);return e.Utilities.LerpUnclampedColor4ToRef(t,n,i,r),r},t.LerpUnclampedColor4ToRef=function(e,t,n,i){i.set(e.r+(t.r-e.r)*n,e.g+(t.g-e.g)*n,e.b+(t.b-e.b)*n,e.a+(t.a-e.a)*n)},t.LerpUnclampedVector2=function(t,n,i){var r=new BABYLON.Vector2(0,0);return e.Utilities.LerpUnclampedVector2ToRef(t,n,i,r),r},t.LerpUnclampedVector2ToRef=function(e,t,n,i){i.set(e.x+(t.x-e.x)*n,e.y+(t.y-e.y)*n)},t.LerpUnclampedVector3=function(t,n,i){var r=new BABYLON.Vector3(0,0,0);return e.Utilities.LerpUnclampedVector3ToRef(t,n,i,r),r},t.LerpUnclampedVector3ToRef=function(e,t,n,i){i.set(e.x+(t.x-e.x)*n,e.y+(t.y-e.y)*n,e.z+(t.z-e.z)*n)},t.LerpUnclampedVector4=function(t,n,i){var r=new BABYLON.Vector4(0,0,0,0);return e.Utilities.LerpUnclampedVector4ToRef(t,n,i,r),r},t.LerpUnclampedVector4ToRef=function(e,t,n,i){i.set(e.x+(t.x-e.x)*n,e.y+(t.y-e.y)*n,e.z+(t.z-e.z)*n,e.w+(t.w-e.w)*n)},t.IsEqualUsingDot=function(t){return t>1-e.System.Epsilon},t.QuaternionAngle=function(t,n){var i=Math.min(Math.abs(BABYLON.Quaternion.Dot(t,n)),1);return e.Utilities.IsEqualUsingDot(i)?0:2*Math.acos(i)*e.System.Rad2Deg},t.QuaternionLengthSquared=function(e){return e.x*e.x+e.y*e.y+e.z*e.z+e.w*e.w},t.QuaternionRotateTowards=function(t,n,i){var r=new BABYLON.Quaternion(0,0,0,1);return e.Utilities.QuaternionRotateTowardsToRef(t,n,i,r),r},t.QuaternionRotateTowardsToRef=function(t,n,i,r){var o=e.Utilities.QuaternionAngle(t,n);0==o?r.copyFrom(n):e.Utilities.QuaternionSlerpUnclampedToRef(t,n,Math.min(1,i/o),r)},t.QuaternionSlerpUnclamped=function(t,n,i){var r=new BABYLON.Quaternion(0,0,0,1);return e.Utilities.QuaternionSlerpUnclampedToRef(t,n,i,r),r},t.QuaternionSlerpUnclampedToRef=function(e,t,n,i){},t.MoveTowards=function(e,t,n){var i=t-e;return Math.abs(i)<=n?t:e+Math.sign(i)*n},t.MoveTowardsVector2=function(t,n,i){var r=new BABYLON.Vector2(0,0);return e.Utilities.MoveTowardsVector2ToRef(t,n,i,r),r},t.MoveTowardsVector2ToRef=function(e,t,n,i){var r=t.x-e.x,o=t.y-e.y,a=r*r+o*o;if(0==a||n>=0&&a<=n*n)i.set(t.x,t.y);else{var s=Math.sqrt(a);i.set(e.x+r/s*n,e.y+o/s*n)}},t.MoveTowardsVector3=function(t,n,i){var r=new BABYLON.Vector3(0,0,0);return e.Utilities.MoveTowardsVector3ToRef(t,n,i,r),r},t.MoveTowardsVector3ToRef=function(e,t,n,i){var r=t.x-e.x,o=t.y-e.y,a=t.z-e.z,s=r*r+o*o+a*a;if(0==s||n>=0&&s<=n*n)i.set(t.x,t.y,t.z);else{var l=Math.sqrt(s);i.set(e.x+r/l*n,e.y+o/l*n,e.z+a/l*n)}},t.MoveTowardsVector4=function(t,n,i){var r=new BABYLON.Vector4(0,0,0,0);return e.Utilities.MoveTowardsVector4ToRef(t,n,i,r),r},t.MoveTowardsVector4ToRef=function(e,t,n,i){var r=t.x-e.x,o=t.y-e.y,a=t.z-e.z,s=t.w-e.w,l=r*r+o*o+a*a+s*s;if(0==l||n>=0&&l<=n*n)i.set(t.x,t.y,t.z,t.w);else{var u=Math.sqrt(l);i.set(e.x+r/u*n,e.y+o/u*n,e.z+a/u*n,e.w+s/u*n)}},t.ClampMagnitudeVector2=function(t,n){var i=new BABYLON.Vector2(0,0);return e.Utilities.ClampMagnitudeVector2ToRef(t,n,i),i},t.ClampMagnitudeVector2ToRef=function(e,t,n){var i=e.lengthSquared();if(i>t*t){var r=Math.sqrt(i),o=e.x/r,a=e.y/r;n.set(o*t,a*t)}},t.ClampMagnitudeVector3=function(t,n){var i=new BABYLON.Vector3(0,0,0);return e.Utilities.ClampMagnitudeVector3ToRef(t,n,i),i},t.ClampMagnitudeVector3ToRef=function(e,t,n){var i=e.lengthSquared();if(i>t*t){var r=Math.sqrt(i),o=e.x/r,a=e.y/r,s=e.z/r;n.set(o*t,a*t,s*t)}},t.GetAngle=function(t,n){return e.Utilities.GetAngleRadians(t,n)*e.System.Rad2Deg},t.GetAngleRadians=function(e,t){return Math.acos(BABYLON.Vector3.Dot(e,t))},t.ClampAngle=function(e,t,n){var i=e;do{i<-360&&(i+=360),i>360&&(i-=360)}while(i<-360||i>360);return BABYLON.Scalar.Clamp(i,t,n)},t.ClampAngle180=function(e,t,n){return e>180&&(e-=360),(e=BABYLON.Scalar.Clamp(e,t,n))<0&&(e+=360),e},t.ClampAngle360=function(e,t,n){return(e<90||e>270)&&(e>180&&(e-=360),n>180&&(n-=360),t>180&&(t-=360)),(e=BABYLON.Scalar.Clamp(e,t,n))<0&&(e+=360),e},t.SmoothDamp=function(e,t,n,i,r,o){if(!o)return 0;var a=e-t,s=Math.max(1e-4,n),l=2/s,u=l*r,c=1/(1+u+.48*u*u+.235*u*u*u),d=t,h=i*s,p=e-(a=BABYLON.Scalar.Clamp(a,-h,h)),m=(o.x+l*a)*r;o.x=(o.x-l*m)*c;var f=p+(a+m)*c;return d-e>0==f>d&&(f=d,o.x=(f-d)/r),f},t.SmoothDampAngle=function(t,n,i,r,o,a){var s=t+BABYLON.Scalar.DeltaAngle(t,n);return e.Utilities.SmoothDamp(t,s,i,r,o,a)},t.SmoothDampVector2=function(t,n,i,r,o,a){var s=new BABYLON.Vector2(0,0);return e.Utilities.SmoothDampVector2ToRef(t,n,i,r,o,a,s),s},t.SmoothDampVector2ToRef=function(e,t,n,i,r,o,a){var s=2/(n=Math.max(1e-4,n)),l=s*r,u=1/(1+l+.48*l*l+.235*l*l*l),c=e.x-t.x,d=e.y-t.y,h=t.clone(),p=i*n,m=c*c+d*d;if(m>p*p){var f=Math.sqrt(m);c=c/f*p,d=d/f*p}t.x=e.x-c,t.y=e.y-d;var g=(o.x+s*c)*r,v=(o.y+s*d)*r;o.x=(o.x-s*g)*u,o.y=(o.y-s*v)*u;var y=t.x+(c+g)*u,_=t.y+(d+v)*u,S=h.x-e.x,A=h.y-e.y;S*(y-h.x)+A*(_-h.y)>0&&(y=h.x,_=h.y,o.x=(y-h.x)/r,o.y=(_-h.y)/r),a.set(y,_)},t.SmoothDampVector3=function(t,n,i,r,o,a){var s=new BABYLON.Vector3(0,0,0);return e.Utilities.SmoothDampVector3ToRef(t,n,i,r,o,a,s),s},t.SmoothDampVector3ToRef=function(e,t,n,i,r,o,a){var s=0,l=0,u=0,c=2/(n=Math.max(1e-4,n)),d=c*r,h=1/(1+d+.48*d*d+.235*d*d*d),p=e.x-t.x,m=e.y-t.y,f=e.z-t.z,g=t.clone(),v=i*n,y=p*p+m*m+f*f;if(y>v*v){var _=Math.sqrt(y);p=p/_*v,m=m/_*v,f=f/_*v}t.x=e.x-p,t.y=e.y-m,t.z=e.z-f;var S=(o.x+c*p)*r,A=(o.y+c*m)*r,b=(o.z+c*f)*r;o.x=(o.x-c*S)*h,o.y=(o.y-c*A)*h,o.z=(o.z-c*b)*h,s=t.x+(p+S)*h,l=t.y+(m+A)*h,u=t.z+(f+b)*h;var M=g.x-e.x,B=g.y-e.y,C=g.z-e.z;M*(s-g.x)+B*(l-g.y)+C*(u-g.z)>0&&(s=g.x,l=g.y,u=g.z,o.x=(s-g.x)/r,o.y=(l-g.y)/r,o.z=(u-g.z)/r),a.set(s,l,u)},t.ToMatrix=function(e,t,n){return BABYLON.Matrix.RotationYawPitchRoll(BABYLON.Tools.ToRadians(t),BABYLON.Tools.ToRadians(e),BABYLON.Tools.ToRadians(n))},t.ToMatrixToRef=function(e,t,n,i){BABYLON.Matrix.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(t),BABYLON.Tools.ToRadians(e),BABYLON.Tools.ToRadians(n),i)},t.FastMatrixLerp=function(e,t,n,i){BABYLON.Matrix.LerpToRef(e,t,n,i)},t.FastMatrixSlerp=function(e,t,n,i){BABYLON.Matrix.DecomposeLerpToRef(e,t,n,i)},t.ToEuler=function(e){var t=e.toEulerAngles();return t.x=BABYLON.Tools.ToDegrees(t.x),t.y=BABYLON.Tools.ToDegrees(t.y),t.z=BABYLON.Tools.ToDegrees(t.z),t},t.ToEulerToRef=function(e,t){e.toEulerAnglesToRef(t),t.x=BABYLON.Tools.ToDegrees(t.x),t.y=BABYLON.Tools.ToDegrees(t.y),t.z=BABYLON.Tools.ToDegrees(t.z)},t.FromEuler=function(e,t,n){return BABYLON.Quaternion.FromEulerAngles(BABYLON.Tools.ToRadians(e),BABYLON.Tools.ToRadians(t),BABYLON.Tools.ToRadians(n))},t.FromEulerToRef=function(e,t,n,i){BABYLON.Quaternion.FromEulerAnglesToRef(BABYLON.Tools.ToRadians(e),BABYLON.Tools.ToRadians(t),BABYLON.Tools.ToRadians(n),i)},t.QuaternionDiff=function(t,n){var i=new BABYLON.Quaternion(0,0,0,1);return e.Utilities.QuaternionDiffToRef(t,n,i),i},t.QuaternionDiffToRef=function(t,n,i){BABYLON.Quaternion.InverseToRef(n,e.Utilities.TempQuaternion),e.Utilities.TempQuaternion.multiplyToRef(t,i)},t.QuaternionSubtractToRef=function(e,t,n){n.set(e._x-t._x,e._y-t._y,e._z-t._z,e._w-t._w)},t.RotateVector=function(e,t){var n=2*(t.y*e.z-t.z*e.y),i=2*(t.z*e.x-t.x*e.z),r=2*(t.x*e.y-t.y*e.x);return new BABYLON.Vector3(e.x+t.w*n+(t.y*r-t.z*i),e.y+t.w*i+(t.z*n-t.x*r),e.z+t.w*r+(t.x*i-t.y*n))},t.RotateVectorToRef=function(e,t,n){var i=2*(t.y*e.z-t.z*e.y),r=2*(t.z*e.x-t.x*e.z),o=2*(t.x*e.y-t.y*e.x);n.x=e.x+t.w*i+(t.y*o-t.z*r),n.y=e.y+t.w*r+(t.z*i-t.x*o),n.z=e.z+t.w*o+(t.x*r-t.y*i)},t.LookRotation=function(t){var n=BABYLON.Quaternion.Zero();return e.Utilities.LookRotationToRef(t,n),n},t.LookRotationToRef=function(e,t){BABYLON.Quaternion.FromLookDirectionRHToRef(e,BABYLON.Vector3.Up(),t)},t.Vector3Rad2Deg=function(t){var n=BABYLON.Vector3.Zero();return e.Utilities.Vector3Rad2DegToRef(t,n),n},t.Vector3Rad2DegToRef=function(e,t){t.x=BABYLON.Tools.ToDegrees(e.x),t.y=BABYLON.Tools.ToDegrees(e.y),t.z=BABYLON.Tools.ToDegrees(e.z)},t.MultiplyQuaternionByVector=function(t,n){var i=new BABYLON.Vector3(0,0,0);return e.Utilities.MultiplyQuaternionByVectorToRef(t,n,i),i},t.MultiplyQuaternionByVectorToRef=function(e,t,n){var i=2*e.x,r=2*e.y,o=2*e.z,a=e.x*i,s=e.y*r,l=e.z*o,u=e.x*r,c=e.x*o,d=e.y*o,h=e.w*i,p=e.w*r,m=e.w*o;n.x=(1-(s+l))*t.x+(u-m)*t.y+(c+p)*t.z,n.y=(u+m)*t.x+(1-(a+l))*t.y+(d-h)*t.z,n.z=(c-p)*t.x+(d+h)*t.y+(1-(a+s))*t.z},t.ValidateTransformRotation=function(e){null!=e.rotationQuaternion&&(e.rotation=e.rotationQuaternion.toEulerAngles(),e.rotationQuaternion=null)},t.ValidateTransformQuaternion=function(e){null==e.rotationQuaternion&&null!=e.rotation&&(e.rotationQuaternion=BABYLON.Quaternion.FromEulerAngles(e.rotation.x,e.rotation.y,e.rotation.z),e.rotation.set(0,0,0))},t.GetKeyboardInputValue=function(t,n,i){var r=i;return!0===e.UserInputOptions.KeyboardSmoothing&&(r=BABYLON.Scalar.MoveTowards(n,i,e.UserInputOptions.KeyboardMoveSensibility*e.SceneManager.GetDeltaSeconds(t)),Math.abs(r)<e.UserInputOptions.KeyboardMoveDeadZone&&(r=0)),r},t.GenerateRandonNumber=function(e,t,n){void 0===n&&(n=2);var i=(Math.random()*(t-e)+e).toFixed(n);return parseFloat(i)},t.ProjectVector=function(t,n){var i=new BABYLON.Vector3(0,0,0);return e.Utilities.ProjectVectorToRef(t,n,i),i},t.ProjectVectorToRef=function(t,n,i){var r=BABYLON.Vector3.Dot(n,n);if(r<e.System.Epsilon)i.set(0,0,0);else{var o=BABYLON.Vector3.Dot(t,n);i.set(n.x*o/r,n.y*o/r,n.z*o/r)}},t.ProjectVectorOnPlane=function(t,n){var i=new BABYLON.Vector3(0,0,0);return e.Utilities.ProjectVectorOnPlaneToRef(t,n,i),i},t.ProjectVectorOnPlaneToRef=function(t,n,i){var r=BABYLON.Vector3.Dot(n,n);if(r<e.System.Epsilon)i.copyFrom(t);else{var o=BABYLON.Vector3.Dot(t,n);i.set(t.x-n.x*o/r,t.y-n.y*o/r,t.z-n.z*o/r)}},t.AreVectorsEqual=function(e,t,n){return Math.abs(e.x-t.x)<n&&Math.abs(e.y-t.y)<n&&Math.abs(e.z-t.z)<n},t.GetVerticalSlopeAngle=function(t,n){void 0===n&&(n=0);var i=Math.atan(Math.abs(t.y/Math.sqrt(t.x*t.x+t.z*t.z)))*e.System.Rad2Deg;return i=null!=i&&!1===Number.isNaN(i)?i:0,n>0&&i>=n&&(i=0),i},t.DownloadEnvironment=function(e,t,n){void 0===t&&(t=null),void 0===n&&(n=null),BABYLON.EnvironmentTextureTools.CreateEnvTextureAsync(e).then(function(n){var i=e.name||"Environment",r=new Blob([n],{type:"octet/stream"});BABYLON.Tools.Download(r,i+".env"),null!=t&&t()}).catch(function(e){console.error(e),null!=n&&n()})},t.HasOwnProperty=function(e,t){return null!=e&&null!=t&&""!==t&&t in e},t.FindMeshCollider=function(e,t){var n=null;if(t instanceof BABYLON.TransformNode&&!0==(null!=t.metadata&&null!=t.metadata.toolkit&&null!=t.metadata.toolkit.renderer&&null!=t.metadata.toolkit.renderer.hasmeshcollider&&!0===t.metadata.toolkit.renderer.hasmeshcollider)){var i=t.id+"-collider";n=e.getMeshById(i)}return n},t.ColliderInstances=function(){return null==e.SceneManager.GlobalOptions.colliderInstances||e.SceneManager.GlobalOptions.colliderInstances},t.ReparentColliders=function(){return null==e.SceneManager.GlobalOptions.reparentColliders||e.SceneManager.GlobalOptions.reparentColliders},t.UseTriangleNormals=function(){return null!=e.SceneManager.GlobalOptions.useTriangleNormals&&e.SceneManager.GlobalOptions.useTriangleNormals},t.UseConvexTriangles=function(){return null!=e.SceneManager.GlobalOptions.useConvexTriangles&&e.SceneManager.GlobalOptions.useConvexTriangles},t.DefaultRenderGroup=function(){return null!=e.SceneManager.GlobalOptions.defaultRenderGroup?e.SceneManager.GlobalOptions.defaultRenderGroup:0},t.ShowDebugColliders=function(){return!0===e.SceneManager.EnableDebugMode||null!=e.SceneManager.GlobalOptions.showDebugColliders&&e.SceneManager.GlobalOptions.showDebugColliders},t.ColliderVisibility=function(){return null!=e.SceneManager.GlobalOptions.colliderVisibility?e.SceneManager.GlobalOptions.colliderVisibility:0},t.ColliderRenderGroup=function(){return null!=e.SceneManager.GlobalOptions.colliderRenderGroup?e.SceneManager.GlobalOptions.colliderRenderGroup:0},t.CollisionWireframe=function(){return null!=e.SceneManager.GlobalOptions.collisionWireframe&&e.SceneManager.GlobalOptions.collisionWireframe},t.GetColliderMaterial=function(t){var n="Collider-Material",i=t.getMaterialByName(n);if(null==i){var r=new BABYLON.PBRMaterial(n,t);r.albedoColor=new BABYLON.Color3(0,.75,0),r.wireframe=e.Utilities.CollisionWireframe(),r.unlit=!0,i=r}return i},t.CalculateCombinedFriction=function(e,t){var n=e*t;return n<-10&&(n=-10),n>10&&(n=10),n},t.CalculateCombinedRestitution=function(e,t){return e*t},t.AddLoaderItemMarkedForDisposal=function(t){null==e.Utilities.LoaderItemsMarkedForDisposal&&(e.Utilities.LoaderItemsMarkedForDisposal=[]),e.Utilities.LoaderItemsMarkedForDisposal.push(t)},t.ResetLoaderItemsMarkedForDisposal=function(){e.Utilities.LoaderItemsMarkedForDisposal=[]},t.RemoveLoaderItemsMarkedForDisposal=function(){null!=e.Utilities.LoaderItemsMarkedForDisposal&&e.Utilities.LoaderItemsMarkedForDisposal.length>0&&e.Utilities.LoaderItemsMarkedForDisposal.forEach(function(e){try{e.dispose()}catch(e){console.warn(e)}}),e.Utilities.ResetLoaderItemsMarkedForDisposal()},t.GetDirectTargetAngle=function(t,n){return e.Utilities.TempVector3.set(0,0,0),e.Utilities.InverseTransformPointToRef(t,n,e.Utilities.TempVector3),Math.atan2(e.Utilities.TempVector3.x,e.Utilities.TempVector3.z)},t.GetSmoothTargetAngle=function(t,n){return e.Utilities.TempVector3.set(0,0,0),e.Utilities.InverseTransformPointToRef(t,n,e.Utilities.TempVector3),e.Utilities.TempVector3.x/e.Utilities.TempVector3.length()},t.CalculatCatmullRom=function(t,n,i,r,o){var a=new BABYLON.Vector3(0,0,0);return e.Utilities.CalculatCatmullRomToRef(t,n,i,r,o,a),a},t.CalculatCatmullRomToRef=function(e,t,n,i,r,o){},t.MakeProper=function(e){return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},t.StartsWith=function(e,t){return 0===e.lastIndexOf(t,0)},t.EndsWith=function(e,t){return-1!==e.indexOf(t,e.length-t.length)},t.ReplaceAll=function(e,t,n){return e.replace(new RegExp(t,"g"),n)},t.IsNullOrEmpty=function(e){return null==e||""===e},t.SafeStringPush=function(e,t){-1===e.indexOf(t)&&e.push(t)},t.ParseColor3=function(e,t,n){return void 0===t&&(t=null),void 0===n&&(n=!1),null!=e&&null!=e.r&&null!=e.g&&null!=e.b?!0===n?new BABYLON.Color3(e.r,e.g,e.b).toLinearSpace():new BABYLON.Color3(e.r,e.g,e.b):t},t.ParseColor4=function(e,t,n){void 0===t&&(t=null),void 0===n&&(n=!1);var i=null;if(null!=e&&null!=e.r&&null!=e.g&&null!=e.b){var r=null!=e.a?e.a:1;i=!0===n?new BABYLON.Color4(e.r,e.g,e.b,r).toLinearSpace():new BABYLON.Color4(e.r,e.g,e.b,r)}else i=t;return i},t.ParseVector2=function(e,t){return void 0===t&&(t=null),null!=e&&null!=e.x&&null!=e.y?new BABYLON.Vector2(e.x,e.y):t},t.ParseVector3=function(e,t){return void 0===t&&(t=null),null!=e&&null!=e.x&&null!=e.y&&null!=e.z?new BABYLON.Vector3(e.x,e.y,e.z):t},t.ParseVector4=function(e,t){return void 0===t&&(t=null),null!=e&&null!=e.x&&null!=e.y&&null!=e.z&&null!=e.w?new BABYLON.Vector4(e.x,e.y,e.z,e.w):t},t.ParseSound=function(t,n,i,r,o){return a(this,void 0,void 0,function(){var a,l,u;return s(this,function(s){switch(s.label){case 0:return a=null,null==t||null==t.filename||""===t.filename?[3,2]:(l=e.SceneManager.GetRootUrl(n),u=t.filename,[4,e.AudioSource.CreateStaticSound(i,l+u,o)]);case 1:a=s.sent(),null!=r&&r(),s.label=2;case 2:return[2,a]}})})},t.ParseTexture=function(t,n,i,r,o,a,s,l,u,c){var d=null;if(null!=t&&null!=t.filename&&""!==t.filename){var h=e.SceneManager.GetRootUrl(n),p=t.filename;d=new BABYLON.Texture(h+p,n,i,r,o,a,s,l,u,c)}return d},t.ParseCubemap=function(t,n){var i=null;if(null!=t&&null!=t.info){var r=e.SceneManager.GetRootUrl(n),o=(t.info.rooturl,r+t.info.rooturl);null!=(i=BABYLON.CubeTexture.Parse(t.info,n,o))&&(i.gammaSpace=!1)}return i},t.ParseTextAsset=function(t,n){return void 0===n&&(n=null),null!=t&&null!=t.base64&&""!==t.base64?e.WindowManager.Atob(t.base64):n},t.ParseJsonAsset=function(t,n,i){void 0===n&&(n=null),void 0===i&&(i=null);var r=e.Utilities.ParseTextAsset(t,n);return null!=r&&""!==r?JSON.parse(r,i):null},t.ParseTransformByID=function(t,n,i){return void 0===i&&(i=null),null!=t&&null!=t.id?e.SceneManager.GetTransformNodeByID(n,t.id):i},t.ParseTransformByName=function(t,n,i){return void 0===i&&(i=null),null!=t&&null!=t.id?e.SceneManager.GetTransformNode(n,t.id):i},t.ParseChildTransform=function(t,n,i){return void 0===i&&(i=null),null!=n&&null!=n.name?e.SceneManager.FindChildTransformNode(t,n.name,e.SearchType.IndexOf,!1):i},t.SetAbsolutePosition=function(e,t){e.setAbsolutePosition(t)},t.GetAbsolutePosition=function(t,n,i){void 0===n&&(n=null),void 0===i&&(i=!0);var r=new BABYLON.Vector3(0,0,0);return e.Utilities.GetAbsolutePositionToRef(t,r,n,i),r},t.GetAbsolutePositionToRef=function(e,t,n,i){void 0===n&&(n=null),void 0===i&&(i=!0),!0===i&&e.computeWorldMatrix(!0),t.copyFrom(e.getAbsolutePosition()),null!=n&&t.addInPlace(n)},t.SetAbsoluteRotation=function(t,n){null==t.rotationQuaternion&&(t.rotationQuaternion=t.rotation.toQuaternion()),null!=t.parent&&t.parent instanceof BABYLON.TransformNode?(e.Utilities.TempQuaternion2.set(0,0,0,1),e.Utilities.GetAbsoluteRotationToRef(t.parent,e.Utilities.TempQuaternion2),BABYLON.Quaternion.InverseToRef(e.Utilities.TempQuaternion2,e.Utilities.TempQuaternion2),e.Utilities.TempQuaternion2.multiplyInPlace(n),t.rotationQuaternion.copyFrom(e.Utilities.TempQuaternion2)):t.rotationQuaternion.copyFrom(n)},t.GetAbsoluteRotation=function(t){var n=new BABYLON.Quaternion(0,0,0,1);return e.Utilities.GetAbsoluteRotationToRef(t,n),n},t.GetAbsoluteRotationToRef=function(e,t){null!=e.absoluteRotationQuaternion&&t.copyFrom(e.absoluteRotationQuaternion)},t.TransformPoint=function(e,t,n){return void 0===n&&(n=!0),!0===n&&e.computeWorldMatrix(),BABYLON.Vector3.TransformCoordinates(t,e.getWorldMatrix())},t.InverseTransformPoint=function(t,n,i){return void 0===i&&(i=!0),!0===i&&t.computeWorldMatrix(),e.Utilities.TempMatrix.reset(),t.getWorldMatrix().invertToRef(e.Utilities.TempMatrix),BABYLON.Vector3.TransformCoordinates(n,e.Utilities.TempMatrix)},t.TransformPointToRef=function(e,t,n,i){void 0===i&&(i=!0),!0===i&&e.computeWorldMatrix(),BABYLON.Vector3.TransformCoordinatesToRef(t,e.getWorldMatrix(),n)},t.InverseTransformPointToRef=function(t,n,i,r){void 0===r&&(r=!0),!0===r&&t.computeWorldMatrix(),e.Utilities.TempMatrix.reset(),t.getWorldMatrix().invertToRef(e.Utilities.TempMatrix),BABYLON.Vector3.TransformCoordinatesToRef(n,e.Utilities.TempMatrix,i)},t.TransformDirection=function(e,t,n){return void 0===n&&(n=!0),!0===n&&e.computeWorldMatrix(),BABYLON.Vector3.TransformNormal(t,e.getWorldMatrix())},t.InverseTransformDirection=function(t,n,i){return void 0===i&&(i=!0),!0===i&&t.computeWorldMatrix(),e.Utilities.TempMatrix.reset(),t.getWorldMatrix().invertToRef(e.Utilities.TempMatrix),BABYLON.Vector3.TransformNormal(n,e.Utilities.TempMatrix)},t.TransformDirectionToRef=function(e,t,n,i){void 0===i&&(i=!0),!0===i&&e.computeWorldMatrix(),BABYLON.Vector3.TransformNormalToRef(t,e.getWorldMatrix(),n)},t.InverseTransformDirectionToRef=function(t,n,i,r){void 0===r&&(r=!0),!0===r&&t.computeWorldMatrix(),e.Utilities.TempMatrix.reset(),t.getWorldMatrix().invertToRef(e.Utilities.TempMatrix),BABYLON.Vector3.TransformNormalToRef(n,e.Utilities.TempMatrix,i)},t.RecomputeCenterPivotPoint=function(e){var t=e.getBoundingInfo().boundingSphere.center;e.setPivotMatrix(BABYLON.Matrix.Translation(-t.x,-t.y,-t.z))},t.GetDirectionVector=function(e,t){return e.getDirection(t)},t.GetDirectionVectorToRef=function(e,t,n){e.getDirectionToRef(t,n)},t.GetForwardVector=function(e){return e.getDirection(BABYLON.Vector3.Forward())},t.GetForwardVectorToRef=function(e,t){e.getDirectionToRef(BABYLON.Vector3.Forward(),t)},t.GetRightVector=function(e){return e.getDirection(BABYLON.Vector3.Right())},t.GetRightVectorToRef=function(e,t){e.getDirectionToRef(BABYLON.Vector3.Right(),t)},t.GetUpVector=function(e){return e.getDirection(BABYLON.Vector3.Up())},t.GetUpVectorToRef=function(e,t){e.getDirectionToRef(BABYLON.Vector3.Up(),t)},t.BlendFloatValue=function(e,t,n){var i=BABYLON.Scalar.Clamp(n,0,1);return i>0?BABYLON.Scalar.Lerp(e,t,i):e},t.BlendVector2Value=function(e,t,n){var i=BABYLON.Scalar.Clamp(n,0,1);if(i>0){var r=BABYLON.Vector2.Lerp(e,t,i);e.copyFrom(r)}},t.BlendVector3Value=function(e,t,n){var i=BABYLON.Scalar.Clamp(n,0,1);i>0&&BABYLON.Vector3.LerpToRef(e,t,i,e)},t.BlendQuaternionValue=function(e,t,n){var i=BABYLON.Scalar.Clamp(n,0,1);i>0&&BABYLON.Quaternion.SlerpToRef(e,t,i,e)},t.SetAnimationTargetProperty=function(e,t){null!=e&&(e.targetProperty=t,e.targetPropertyPath=e.targetProperty.split("."))},t.SampleAnimationFloat=function(t,n,i,r){void 0===i&&(i=BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE),void 0===r&&(r=!1);var o=0;return null!=t&&t.dataType===BABYLON.Animation.ANIMATIONTYPE_FLOAT&&(null==t._state&&(t._state={key:0,repeatCount:0,loopMode:i,workValue:BABYLON.Matrix.Zero()}),o=e.Utilities.InterpolateAnimation(t,n,t._state,r)),o},t.SampleAnimationVector2=function(t,n,i,r){void 0===i&&(i=BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE),void 0===r&&(r=!1);var o=null;return null!=t&&t.dataType===BABYLON.Animation.ANIMATIONTYPE_VECTOR2&&(null==t._state&&(t._state={key:0,repeatCount:0,loopMode:i,workValue:BABYLON.Matrix.Zero()}),o=e.Utilities.InterpolateAnimation(t,n,t._state,r)),o},t.SampleAnimationVector3=function(t,n,i,r){void 0===i&&(i=BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE),void 0===r&&(r=!1);var o=null;return null!=t&&t.dataType===BABYLON.Animation.ANIMATIONTYPE_VECTOR3&&(null==t._state&&(t._state={key:0,repeatCount:0,loopMode:i,workValue:BABYLON.Matrix.Zero()}),o=e.Utilities.InterpolateAnimation(t,n,t._state,r)),o},t.SampleAnimationQuaternion=function(t,n,i,r){void 0===i&&(i=BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE),void 0===r&&(r=!1);var o=null;return null!=t&&t.dataType===BABYLON.Animation.ANIMATIONTYPE_QUATERNION&&(null==t._state&&(t._state={key:0,repeatCount:0,loopMode:i,workValue:BABYLON.Matrix.Zero()}),o=e.Utilities.InterpolateAnimation(t,n,t._state,r)),o},t.SampleAnimationMatrix=function(t,n,i,r){void 0===i&&(i=BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE),void 0===r&&(r=!1);var o=null;return null!=t&&t.dataType===BABYLON.Animation.ANIMATIONTYPE_MATRIX&&(null==t._state&&(t._state={key:0,repeatCount:0,loopMode:i,workValue:BABYLON.Matrix.Zero()}),o=e.Utilities.InterpolateAnimation(t,n,t._state,r)),o},t.GetLastKeyFrameIndex=function(e){var t=0;if(null!=e){var n=e.getKeys();if(null!=n&&n.length>0){var i=n[n.length-1];null!=i&&(t=i.frame)}}return t},t.InterpolateAnimation=function(t,n,i,r){void 0===r&&(r=!1);var o=!0===r?n*e.SceneManager.AnimationTargetFps:n;return t._interpolate(o,i)},t.UpdateLoopBlendPositionSettings=function(e,t,n){var i=e;null!=i.metadata&&null!=i.metadata.toolkit&&null!=i.metadata.toolkit.settings&&(i.metadata.toolkit.settings.loopblendpositiony=t,i.metadata.toolkit.settings.loopblendpositionxz=n)},t.TakeScreenSnapshot=function(e,t,n,i,r){if(e&&t){var o=e.activeCamera;if(o){var a=t.getRenderWidth(),s=t.getRenderHeight(),l=a,u=s;if(n)if(n.width&&n.height)l=Math.max(1,n.width),u=Math.max(1,n.height);else if(n.width){l=Math.max(1,n.width);var c=s/Math.max(1,a);u=Math.round(l*c)}else if(n.height)u=Math.max(1,n.height),c=a/Math.max(1,s),l=Math.round(u*c);else if(n.precision){var d=Math.max(.05,n.precision);l=Math.round(a*d),u=Math.round(s*d)}BABYLON.CreateScreenshotUsingRenderTarget(t,o,{width:l,height:u},void 0,void 0,void 0,!1,void 0,!1,!1,!0,void 0,void 0,function(e,t,n,o,a,s,l){try{var u=n,c=new Uint8ClampedArray(u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength));if(l)for(var d=4*e,h=Math.floor(t/2),p=new Uint8ClampedArray(d),m=0;m<h;m++){var f=m*d,g=(t-1-m)*d;p.set(c.subarray(f,f+d)),c.copyWithin(f,g,g+d),c.set(p,g)}var v=void 0;if("OffscreenCanvas"in window)v=new OffscreenCanvas(e,t);else{var y=document.createElement("canvas");y.width=e,y.height=t,v=y}var _=v.getContext("2d");if(!_)return void(r&&r(null));var S=_.createImageData(e,t);if(S.data.set(c),_.putImageData(S,0,0),!r)return;v instanceof OffscreenCanvas&&"function"==typeof v.transferToImageBitmap?r(v.transferToImageBitmap()):"function"==typeof createImageBitmap?createImageBitmap(v,i).then(function(e){return r(e)}).catch(function(){return r(null)}):r(null)}catch(e){r&&r(null)}})}else r&&r(null)}else r&&r(null)},t.DownloadImageBitmap=function(e,t,n,i){if(void 0===t&&(t="image.png"),void 0===n&&(n="image/png"),!e)return null;var r=e.width,o=e.height,a="OffscreenCanvas"in window?new OffscreenCanvas(r,o):Object.assign(document.createElement("canvas"),{width:r,height:o});a.getContext("2d").drawImage(e,0,0);var s=function(e){if(e){var n=URL.createObjectURL(e),i=document.createElement("a");i.href=n,i.download=t,i.click(),setTimeout(function(){return URL.revokeObjectURL(n)},2e3)}};return"convertToBlob"in a?a.convertToBlob({type:n,quality:i}).then(s):a.toBlob(s,n,i),a},t.MarkLinear=function(e){e&&(e.gammaSpace=!1)},t.MarkGamma=function(e){e&&(e.gammaSpace=!0)},t.WorldToScreenPoint=function(e,t,n){void 0===n&&(n=null);var i=null,r=null!=n?n.viewport:null!=e.activeCamera?e.activeCamera.viewport:null;return null!=r&&(i=BABYLON.Vector3.Project(t,BABYLON.Matrix.Identity(),e.getTransformMatrix(),r.toGlobal(e.getEngine().getRenderWidth(),e.getEngine().getRenderHeight()))),i},t.ScreenToWorldPoint=function(e,t){return BABYLON.Vector3.Unproject(t,e.getEngine().getRenderWidth(),e.getEngine().getRenderHeight(),BABYLON.Matrix.Identity(),e.getViewMatrix(),e.getProjectionMatrix())},t.LoadTextFile=function(e,t,n,i){return BABYLON.Tools.LoadFile(e,t,n,null,!1,i)},t.LoadTextFileAsync=function(e){return BABYLON.Tools.LoadFileAsync(e,!1)},t.GetHttpRequest=function(e,t,n,i,r,o,a){void 0===t&&(t=null),void 0===n&&(n=null),void 0===i&&(i=null),void 0===r&&(r=null),void 0===o&&(o=!1),void 0===a&&(a=null);var s=new XMLHttpRequest;return s.open("GET",e,!0),!0===o&&(s.responseType="arraybuffer"),null!=a&&s.overrideMimeType(a),null!=t&&t.forEach(function(e){null!=e&&null!=e.name&&""!==e.name&&s.setRequestHeader(e.name,e.value)}),s.onreadystatechange=function(){s.readyState===XMLHttpRequest.DONE&&null!=n&&n(s)},s.onprogress=function(e){null!=r&&r(e)},s.onerror=function(){null!=i&&i("Failed to get data from server.")},s.onabort=function(){null!=i&&i("Aborted get data from server.")},s.send(null),s},t.GetHttpRequestAsync=function(t,n,i,r,o){return void 0===n&&(n=null),void 0===i&&(i=null),void 0===r&&(r=!1),void 0===o&&(o=null),new Promise(function(a,s){e.Utilities.GetHttpRequest(t,n,function(e){a(e)},function(e){s(e)},i,r,o)})},t.PostHttpRequest=function(e,t,n,i,r,o,a,s,l){void 0===n&&(n=null),void 0===i&&(i="application/x-www-form-urlencoded"),void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=!1),void 0===l&&(l=null);var u=new XMLHttpRequest;return u.open("POST",e,!0),!0===s&&(u.responseType="arraybuffer"),null!=l&&u.overrideMimeType(l),null!=n&&n.forEach(function(e){null!=e&&null!=e.name&&""!==e.name&&u.setRequestHeader(e.name,e.value)}),u.setRequestHeader("Content-Type",i),u.onreadystatechange=function(){u.readyState===XMLHttpRequest.DONE&&null!=r&&r(u)},u.onprogress=function(e){null!=a&&a(e)},u.onerror=function(){null!=o&&o("Failed to post data to server.")},u.onabort=function(){null!=o&&o("Aborted post data to server.")},u.send(t),u},t.PostHttpRequestAsync=function(t,n,i,r,o,a,s){return void 0===i&&(i=null),void 0===r&&(r="application/x-www-form-urlencoded"),void 0===o&&(o=null),void 0===a&&(a=!1),void 0===s&&(s=null),new Promise(function(l,u){e.Utilities.PostHttpRequest(t,n,i,r,function(e){l(e)},function(e){u(e)},o,a,s)})},t.RemapValueToRange=function(e,t,n,i,r){return i+(e-t)*(r-i)/(n-t)},t.CloneSkeletonPrefab=function(e,t,n,i,r){void 0===r&&(r=null);var o=new BABYLON.Skeleton(n,i||n,e);o.needInitialSkinMatrix=t.needInitialSkinMatrix;for(var a=0;a<t.bones.length;a++){var s=t.bones[a],l=null,u=s.getParent();if(u){var c=t.bones.indexOf(u);l=o.bones[c]}var d=new BABYLON.Bone(s.name,o,l,s.getBaseMatrix().clone(),s.getRestPose().clone());d._index=s._index,d.metadata=s.metadata,s._linkedTransformNode&&d.linkTransformNode(s._linkedTransformNode),BABYLON.DeepCopier.DeepCopy(s.animations,d.animations)}var h=o,p=t;if(p._ranges)for(var m in h._ranges={},p._ranges){var f=p._ranges[m];f&&(h._ranges[m]=f.clone())}return p._isDirty=!0,o},t.GetSceneTransforms=function(e){var t=null;return null!=e.transformNodes&&e.transformNodes.length>0&&e.transformNodes.forEach(function(e){null!=e.metadata&&null!=e.metadata.toolkit&&null!=e.metadata.toolkit.prefab&&!1===e.metadata.toolkit.prefab&&(null==t&&(t=[]),t.push(e))}),null!=e.meshes&&e.meshes.length>0&&e.meshes.forEach(function(e){null!=e.metadata&&null!=e.metadata.toolkit&&null!=e.metadata.toolkit.prefab&&!1===e.metadata.toolkit.prefab&&(null==t&&(t=[]),t.push(e))}),t},t.PostParseSceneComponents=function(t,n,i,r){var o=new e.MetadataParser(t);return null!=n&&n.length>0&&(n.forEach(function(e){o.parseSceneComponents(e)}),o.postProcessSceneComponents(i,r)),o},t.GetDefaultReflectionTexture=function(e){if(!e._DefaultCube){var t=document.createElement("canvas");t.width=t.height=1;var n=t.getContext("2d");n.fillStyle="rgba(128,128,128,1)",n.fillRect(0,0,1,1);var i=t.toDataURL("image/png"),r=[i,i,i,i,i,i],o=BABYLON.CubeTexture.CreateFromImages(r,e,!0);o.name="DefaultReflection",o.gammaSpace=!1,o.coordinatesMode=BABYLON.Texture.CUBIC_MODE,o.level=.1,e._DefaultCube=o}return e._DefaultCube},t.GetNeutralReflectionTexture=function(e,t,n){void 0===t&&(t=128),void 0===n&&(n=.4);var i="_NeutralCube_".concat(t,"_").concat(n);if(!e[i]){var r=document.createElement("canvas");r.width=r.height=1;var o=r.getContext("2d");o.fillStyle="rgba(".concat(t,",").concat(t,",").concat(t,",1)"),o.fillRect(0,0,1,1);var a=r.toDataURL("image/png"),s=[a,a,a,a,a,a],l=BABYLON.CubeTexture.CreateFromImages(s,e,!0);l.name="NeutralReflection",l.gammaSpace=!1,l.coordinatesMode=BABYLON.Texture.CUBIC_MODE,l.level=n,e[i]=l}return e[i]},t.GetAssetContainerMesh=function(e,t){var n=null,i=t.toLowerCase();if(null==n&&null!=e.meshes&&e.meshes.length>0)for(var r=0;r<e.meshes.length;r++){var o=e.meshes[r];if(o instanceof BABYLON.Mesh&&o.name.toLowerCase()===i){n=o;break}}return n},t.GetAssetContainerNode=function(e,t){var n=null,i=t.toLowerCase();if(null==n&&null!=e.transformNodes&&e.transformNodes.length>0)for(var r=0;r<e.transformNodes.length;r++){var o=e.transformNodes[r];if(o.name.toLowerCase()===i){n=o;break}}return n},t.CloneAssetContainerItem=function(t,n,i,r,o,a){void 0===r&&(r=null),void 0===o&&(o=!1),void 0===a&&(a=!0);var s=null,l={},u={},c={},d=null,h=null,p=[],m=[],f=n.toLowerCase(),g=null,v=function(t,n){null==g&&(g=n),l[t.uniqueId]=n.uniqueId,u[n.uniqueId]=n,i&&(n.name=i(t.name)),null!=t.metadata&&null!=t.metadata.toolkit&&null!=t.metadata.toolkit.entity&&(n.metadata=e.Utilities.CloneEntityMetadata(t.metadata));var r=null!=n.metadata&&null!=n.metadata.toolkit&&null!=n.metadata.toolkit.animator?n.metadata.toolkit.animator:null;if(null!=r&&""!==r&&(null==d&&(d=[]),d.indexOf(r)<0&&d.push(r),n.metadata.toolkit.animator=e.Utilities.CreateGuid(),c[r]=n.metadata.toolkit.animator),t instanceof BABYLON.AbstractMesh&&null!=t.skeleton&&(null==h&&(h=[]),h.indexOf(t.skeleton)<0&&h.push(t.skeleton)),n instanceof BABYLON.Mesh){var o=n;if(o.morphTargetManager){var a=t.morphTargetManager;o.morphTargetManager=a.clone();for(var s=0;s<a.numTargets;s++){var p=a.getTarget(s),m=o.morphTargetManager.getTarget(s);l[p.uniqueId]=m.uniqueId,u[m.uniqueId]=m}}}};if(null==s&&null!=t.transformNodes&&t.transformNodes.length>0)for(var y=0;y<t.transformNodes.length;y++){var _=t.transformNodes[y];if(_.name.toLowerCase()===f){var S=e.Utilities.InstantiateHierarchy(_,r,function(e,t){v(e,t)});if(S){s=S;break}}}if(null==s&&null!=t.meshes&&t.meshes.length>0){var A=function(n){var a=t.meshes[n];if(a.name.toLowerCase()===f){var c=e.Utilities.InstantiateHierarchy(a,r,function(e,n){v(e,n);var r=n;if(!0===a.isWorldMatrixFrozen&&r.freezeWorldMatrix&&r.freezeWorldMatrix(),n.material&&r.material)if(!0===o){var s=e.material;if(-1===m.indexOf(s)){var c=s.clone(i?i(s.name):"Clone of "+s.name);if(!0===s.isFrozen&&c.freeze&&c.freeze(),m.push(s),l[s.uniqueId]=c.uniqueId,u[c.uniqueId]=c,"MultiMaterial"===s.getClassName())for(var d=0,h=s.subMaterials;d<h.length;d++){var p=h[d];p&&(c=p.clone(i?i(p.name):"Clone of "+p.name),!0===p.isFrozen&&c.freeze&&c.freeze(),m.push(p),l[p.uniqueId]=c.uniqueId,u[c.uniqueId]=c)}}r.material=u[l[s.uniqueId]]}else"MultiMaterial"===r.material.getClassName()?-1===t.scene.multiMaterials.indexOf(r.material)&&t.scene.addMultiMaterial(r.material):-1===t.scene.materials.indexOf(r.material)&&t.scene.addMaterial(r.material)});if(c)return s=c,"break"}};for(y=0;y<t.meshes.length&&"break"!==A(y);y++);}if(null!=h&&h.length>0&&h.forEach(function(n){for(var r=i?i(n.name):"Clone of "+n.name,o=e.Utilities.CloneSkeletonPrefab(t.scene,n,r,r,g),a=0,s=t.meshes;a<s.length;a++){var c=s[a];if(c.skeleton===n&&!c.isAnInstance){if(u[l[c.uniqueId]].skeleton=o,-1!==p.indexOf(o))continue;p.push(o);for(var d=0,h=o.bones;d<h.length;d++){var m=h[d];m._linkedTransformNode&&(m._linkedTransformNode=u[l[m._linkedTransformNode.uniqueId]])}}}}),!0===a){var b=null;t.animationGroups.forEach(function(e){var t=e,n=null!=t.metadata&&null!=t.metadata.toolkit&&null!=t.metadata.toolkit.source&&""!==t.metadata.toolkit.source?t.metadata.toolkit.source:null;if(null!=n&&""!==n&&null!=d&&d.indexOf(n)>=0){var i=e.clone(e.name,function(e){return u[l[e.uniqueId]]||e}),r=c[n]||n;null!=t.metadata&&(i.metadata={},i.metadata.toolkit={},i.metadata.toolkit.id=t.metadata.toolkit.id,i.metadata.toolkit.clip=t.metadata.toolkit.clip,i.metadata.toolkit.source=r,i.metadata.toolkit.legacy=t.metadata.toolkit.legacy,i.metadata.toolkit.length=t.metadata.toolkit.length,i.metadata.toolkit.looping=t.metadata.toolkit.looping,i.metadata.toolkit.settings=t.metadata.toolkit.settings,i.metadata.toolkit.behavior=t.metadata.toolkit.behavior,i.metadata.toolkit.wrapmode=t.metadata.toolkit.wrapmode,i.metadata.toolkit.framerate=t.metadata.toolkit.framerate,i.metadata.toolkit.humanmotion=t.metadata.toolkit.humanmotion,i.metadata.toolkit.averagespeed=t.metadata.toolkit.averagespeed,i.metadata.toolkit.averageduration=t.metadata.toolkit.averageduration,i.metadata.toolkit.averageangularspeed=t.metadata.toolkit.averageangularspeed),null==b&&(b=[]),b.push(i)}}),null!=s&&null!=b&&e.Utilities.AssignAnimationGroupsToInstance(s,b)}return s},t.AssignAnimationGroupsToInstance=function(t,n){e.Utilities.AssignAnimationGroupsToNode(t,n);var i=t.getChildren(null,!1);null!=i&&i.length>0&&i.forEach(function(t){e.Utilities.AssignAnimationGroupsToNode(t,n)})},t.AssignAnimationGroupsToNode=function(t,n){if(null!=t&&null!=t.metadata&&t.metadata.toolkit){var i=t.metadata.toolkit;if(null!=i.components&&i.components.length>0)for(var r=0;r<i.components.length;r++){var o=i.components[r].klass;if(null!=o&&""!==o){if(!0===e.SceneManager.AutoStripNamespacePrefix&&!1===e.SceneManager.UniversalModuleDefinition){var a=o.lastIndexOf(".");-1!==a&&(o=o.substring(a+1))}"TOOLKIT.AnimationState"===o&&(t.metadata.toolkit.sourceAnimationGroups=n)}}}},t.UnitySlopeAngleToCosine=function(e){return Math.cos(e*Math.PI/180)},t.InstantiateHierarchy=function(t,n,i){if(void 0===n&&(n=null),t instanceof BABYLON.Mesh){var r=null!=t.metadata&&null!=t.metadata.toolkit&&null!=t.metadata.toolkit.instance&&!0===t.metadata.toolkit.instance;return e.Utilities.InstantiateMeshHierarchy(t,n,r,i)}return e.Utilities.InstantiateNodeHierarchy(t,n,i)},t.InstantiateNodeHierarchy=function(t,n,i){void 0===n&&(n=null);var r=t.clone("Clone of "+(t.name||t.id),n,!0);r&&i&&i(t,r);for(var o=0,a=t.getChildTransformNodes(!0);o<a.length;o++){var s=a[o];e.Utilities.InstantiateHierarchy(s,r,i)}return r},t.InstantiateMeshHierarchy=function(t,n,i,r){void 0===n&&(n=null);var o=t.getTotalVertices()>0&&!0===i?t.createInstance("Instance of "+(t.name||t.id)):t.clone("Clone of "+(t.name||t.id),n||t.parent,!0);o&&(o.parent=n,o.position=t.position.clone(),o.scaling=t.scaling.clone(),t.rotationQuaternion?o.rotationQuaternion=t.rotationQuaternion.clone():o.rotation=t.rotation.clone(),r&&r(t,o));for(var a=0,s=t.getChildTransformNodes(!0);a<s.length;a++){var l=s[a];e.Utilities.InstantiateHierarchy(l,o,r)}return o},t.PrepareSkeletonForRendering=function(e,t){void 0===t&&(t=!1),null!=e&&e.prepare(t)},t.RetargetAnimationGroupSkeleton=function(e,t,n){void 0===n&&(n=null),null!=e&&null!=t&&e.targetedAnimations.forEach(function(e,i){if(null!=e.target&&null!=e.target.name){var r=t.bones.filter(function(t){return t.name.toLowerCase()===e.target.name.toLowerCase()})[0];null!=r?null!=r.getTransformNode()&&(e.target=r.getTransformNode()):"Armature"===e.target.name&&null!=n?e.target=n:console.warn("Failed to locate matching animation cloning target: "+e.target.name)}})},t.RetargetAnimationGroupBlendShapes=function(e,t){null!=e&&null!=t&&e.targetedAnimations.forEach(function(e,t){null!=e.target&&e.target.name})},t.LinkSkeletonMeshes=function(t,n){if(null!=t&&null!=t.bones&&t.bones.length>0&&null!=n&&null!=n.bones&&n.bones.length>0)for(var i=n.bones.length,r=0;r<i;r++){var o=n.bones[r];if(null!=o){var a=e.Utilities.FindBoneByName(t,o.name);null!=a?o._linkedTransformNode=a._linkedTransformNode:console.warn("Failed to locate bone on mater rig: "+o.name)}}},t.FindBoneByName=function(e,t){var n=null;if(null!=e&&null!=e.bones)for(var i=0;i<e.bones.length;i++){var r=e.bones[i];if(r.name.toLowerCase().replace("mixamo:","").replace("left_","left").replace("right_","right")===t.toLowerCase().replace("mixamo:","").replace("left_","left").replace("right_","right")){n=r;break}}return n},t.SwitchHandednessVector3=function(e){return new BABYLON.Vector3(e.x,e.y,-e.z)},t.SwitchHandednessVector4=function(e){return new BABYLON.Vector4(e.x,e.y,-e.z,-e.w)},t.SwitchHandednessQuaternion=function(e){return new BABYLON.Quaternion(e.x,e.y,-e.z,-e.w)},t.ComputeBlendingSpeed=function(e,t,n){void 0===n&&(n=!1);var i=1/(e*t);return!0===n&&(i*=.5),i},t.CalculateCameraDistance=function(e,t,n){return void 0===n&&(n=1),Math.round(e*n*t*1)},t.EvalSphericalPolynomialRGB=function(e,t){var n=t.x,i=t.y,r=t.z,o=e.x.x*n+e.y.x*i+e.z.x*r+e.xx.x*n*n+e.yy.x*i*i+e.zz.x*r*r+e.xy.x*n*i+e.yz.x*i*r+e.zx.x*r*n,a=e.x.y*n+e.y.y*i+e.z.y*r+e.xx.y*n*n+e.yy.y*i*i+e.zz.y*r*r+e.xy.y*n*i+e.yz.y*i*r+e.zx.y*r*n,s=e.x.z*n+e.y.z*i+e.z.z*r+e.xx.z*n*n+e.yy.z*i*i+e.zz.z*r*r+e.xy.z*n*i+e.yz.z*i*r+e.zx.z*r*n;return new BABYLON.Color3(o,a,s)},t.BestFitScale=function(e,t){for(var n=0,i=0,r=0;r<e.length;r++){var o=e[r],a=t[r];n+=a*o,i+=a*a}return i>1e-12?n/i:1},t.ComputeSHEval6Fit=function(e,t){if(!Array.isArray(t)||18!==t.length)throw new Error("unityEval6 must be an array of 18 floats (6 dirs * RGB)");for(var n=[new BABYLON.Vector3(1,0,0),new BABYLON.Vector3(-1,0,0),new BABYLON.Vector3(0,1,0),new BABYLON.Vector3(0,-1,0),new BABYLON.Vector3(0,0,1),new BABYLON.Vector3(0,0,-1)],i=[],r=0;r<n.length;r++){var o=this.EvalSphericalPolynomialRGB(e,n[r]);i.push(o.r,o.g,o.b)}for(var a=t.slice(0),s=this.BestFitScale(a,i),l=0,u=[0,0,0],c=a.length,d=0;d<c;d++){var h=a[d]-s*i[d];l+=h*h,u[d%3]+=h*h}var p=Math.sqrt(l/c),m=u.map(function(e){return Math.sqrt(e/(c/3))}),f=[];for(r=0;r<n.length;r++)f.push({dir:n[r],unity:new BABYLON.Color3(a[3*r+0],a[3*r+1],a[3*r+2]),bab:new BABYLON.Color3(i[3*r+0],i[3*r+1],i[3*r+2]),scaledBab:new BABYLON.Color3(s*i[3*r+0],s*i[3*r+1],s*i[3*r+2]),diff:new BABYLON.Color3(a[3*r+0]-s*i[3*r+0],a[3*r+1]-s*i[3*r+1],a[3*r+2]-s*i[3*r+2])});return{scale:s,rmse:p,perChannelRMSE:m,perDir:f}},t.InstantiateClass=function(t){try{var n=e.SceneManager.GetClass(t);if(n)return n;var i=t.split("."),r=void 0;if("undefined"!=typeof window)r=window;else if("undefined"!=typeof globalThis)r=globalThis;else{if(void 0===globalThis.global)throw new Error("No global object available");r=globalThis.global}for(var o=0;o<i.length;o++)if(!(r=r[i[o]]))throw new Error("Class not found: ".concat(t));return"function"==typeof r?r:null}catch(e){return console.error("Failed to resolve class: ".concat(t),e),null}},t.GetSimpleClassName=function(e){if(e&&e.constructor&&e.constructor.toString){var t=e.constructor.toString().match(/function\s*(\w+)/);if(t&&2==t.length)return t[1]}},t.DisposeEntity=function(t){if(null!=t){if(null!=t.metadata&&t.metadata.toolkit){var n=t.metadata.toolkit;null!=n.components&&n.components.length>0&&n.components.forEach(function(t){if(null!=t.instance){try{e.SceneManager.DestroyScriptComponent(t.instance)}catch(e){}t.instance=null}}),delete t.metadata.toolkit}if(null!=t.metadata&&t.metadata.mixer&&delete t.metadata.mixer,null!=t.metadata&&null!=t.metadata.clone&&delete t.metadata.clone,null!=t.physicsImpostor){var i=t.physicsImpostor;null!=i.onCollideEvent&&(i.onCollideEvent=null),null!=i.tmpCollisionObjects&&delete i.tmpCollisionObjects,null!=t.physicsImpostor.physicsBody&&(null!=t.physicsImpostor.physicsBody.entity&&delete t.physicsImpostor.physicsBody.entity,null!=t.physicsImpostor.physicsBody.triangleMapInfo&&delete t.physicsImpostor.physicsBody.triangleMapInfo),t.physicsImpostor.dispose(),t.physicsImpostor=null}null!=t.skeleton&&(null!=t.skeleton._sockets&&delete t.skeleton._sockets,null!=t.skeleton.bones&&t.skeleton.bones.length>0&&t.skeleton.bones.forEach(function(e){null!=e&&null!=e.metadata&&(e.metadata=null)})),null!=t.cameraRig&&(t.cameraRig.dispose&&t.cameraRig.dispose(),delete t.cameraRig),null!=t.lightRig&&(t.lightRig.dispose&&t.lightRig.dispose(),delete t.lightRig),null!=t.shadowBox&&(t.shadowBox.dispose&&t.shadowBox.dispose(),delete t.shadowBox),null!=t._debugCollider&&(t._debugCollider.dispose&&t._debugCollider.dispose(),delete t._debugCollider),null!=t._meshCollider&&(t._meshCollider=null),null!=t._colliderType&&delete t._colliderType,null!=t._skinnedMesh&&delete t._skinnedMesh}},t.SearchTransformNodes=function(t,n,i){void 0===i&&(i=e.SearchType.ExactMatch);var r=null,o=null!=i?i:e.SearchType.ExactMatch;if(null!=n&&n.length>0)for(var a=0;a<n.length;a++){var s=n[a];if(o===e.SearchType.ExactMatch){if(s.name===t){r=s;break}}else if(o===e.SearchType.StartsWith){if(e.Utilities.StartsWith(s.name,t)){r=s;break}}else if(o===e.SearchType.EndsWith){if(e.Utilities.EndsWith(s.name,t)){r=s;break}}else if(o===e.SearchType.IndexOf){if(s.name.indexOf(t)>=0){r=s;break}}else if(s.name===t){r=s;break}}return r},t.SearchTransformNodeForTags=function(e,t){var n=null;if(null!=t&&t.length>0)for(var i=0;i<t.length;i++){var r=t[i];if(r instanceof BABYLON.TransformNode&&BABYLON.Tags.MatchesQuery(r,e)){n=r;break}}return n},t.SearchAllTransformNodesForTags=function(e,t){var n=null;if(null!=t&&t.length>0)for(var i=0;i<t.length;i++){var r=t[i];r instanceof BABYLON.TransformNode&&BABYLON.Tags.MatchesQuery(r,e)&&(null==n&&(n=[]),n.push(r))}return n},t.SearchTransformNodeForScript=function(t,n){var i=null;if(null!=n&&n.length>0)for(var r=0;r<n.length;r++){var o=n[r];if(o instanceof BABYLON.TransformNode&&null!=e.SceneManager.FindScriptComponent(o,t)){i=o;break}}return i},t.SearchAllTransformNodesForScript=function(t,n){var i=null;if(null!=n&&n.length>0)for(var r=0;r<n.length;r++){var o=n[r];o instanceof BABYLON.TransformNode&&null!=e.SceneManager.FindScriptComponent(o,t)&&(null==i&&(i=[]),i.push(o))}return i},t.CreateGuid=function(t){void 0===t&&(t=null);var n=BABYLON.Tools.RandomId();return e.Utilities.IsNullOrEmpty(t)||(n+="-"+t),n},t.ValidateTransformGuid=function(e){if(null!=e&&null!=e.metadata&&null!=e.metadata.toolkit&&null!=e.metadata.toolkit.guid&&""!==e.metadata.toolkit.guid){var t=e.metadata.toolkit.guid;e.id!==t&&(e.id=t),delete e.metadata.toolkit.guid}},t.RegisterInstancedMeshBuffers=function(e){var t=null!=e.metadata&&null!=e.metadata.toolkit&&null!=e.metadata.toolkit.buffers?e.metadata.toolkit.buffers:null;null!=t&&(null!=t.floats&&t.floats.length>0&&t.floats.forEach(function(t){null!=t.kind&&""!==t.kind&&null!=t.value&&(e.registerInstancedBuffer(t.kind,1),e.instancedBuffers[t.kind]=t.value)}),null!=t.colors&&t.colors.length>0&&t.colors.forEach(function(t){null!=t.kind&&""!==t.kind&&null!=t.value&&(e.registerInstancedBuffer(t.kind,4),e.instancedBuffers[t.kind]=new BABYLON.Color4(t.value.r||0,t.value.g||0,t.value.b||0,t.value.a||1).toLinearSpace())}),null!=t.vector2&&t.vector2.length>0&&t.vector2.forEach(function(t){null!=t.kind&&""!==t.kind&&null!=t.value&&(e.registerInstancedBuffer(t.kind,2),e.instancedBuffers[t.kind]=new BABYLON.Vector2(t.value.x||0,t.value.y||0))}),null!=t.vector3&&t.vector3.length>0&&t.vector3.forEach(function(t){null!=t.kind&&""!==t.kind&&null!=t.value&&(e.registerInstancedBuffer(t.kind,3),e.instancedBuffers[t.kind]=new BABYLON.Vector3(t.value.x||0,t.value.y||0,t.value.z||0))}),null!=t.vector4&&t.vector4.length>0&&t.vector4.forEach(function(t){null!=t.kind&&""!==t.kind&&null!=t.value&&(e.registerInstancedBuffer(t.kind,4),e.instancedBuffers[t.kind]=new BABYLON.Vector4(t.value.x||0,t.value.y||0,t.value.z||0,t.value.w||0))}))},t.CloneValue=function(e,t){return e?e instanceof BABYLON.Mesh?null:e instanceof BABYLON.SubMesh?e.clone(t):e.clone?e.clone():e:null},t.CloneEntityMetadata=function(t){var n=null;if(null!=t){var i=null;if(null!=t.toolkit){var r=null!=t.toolkit.instance&&t.toolkit.instance,o=null==t.toolkit.visible||t.toolkit.visible,a=null!=t.toolkit.visibility?t.toolkit.visibility:1,s=null!=t.toolkit.billboard?t.toolkit.billboard:0,l=null!=t.toolkit.tags?t.toolkit.tags:"Untagged Layer0",u=null!=t.toolkit.skin&&t.toolkit.skin,c=null!=t.toolkit.bone?t.toolkit.bone:null,d=null!=t.toolkit.rootbone&&t.toolkit.rootbone,h=null!=t.toolkit.rootpos?t.toolkit.rootpos:null,p=null!=t.toolkit.rootrot?t.toolkit.rootrot:null,m=null!=t.toolkit.group?t.toolkit.group:"Untagged",f=null!=t.toolkit.layer?t.toolkit.layer:0,g=null!=t.toolkit.layername?t.toolkit.layername:"Default",v=null!=t.toolkit.navigation?t.toolkit.navigation:null,y=null!=t.toolkit.lightmapped&&t.toolkit.lightmapped,_=null!=t.toolkit.lightmapuvs?t.toolkit.lightmapuvs:null,S=null!=t.toolkit.animator?t.toolkit.animator:null,A=null,b=null,M=null,B=null;t.toolkit.physics&&(A={},e.Utilities.DeepCopyProperties(t.toolkit.physics,A)),t.toolkit.renderer&&(b={},e.Utilities.DeepCopyProperties(t.toolkit.renderer,b)),t.toolkit.collision&&(M={},e.Utilities.DeepCopyProperties(t.toolkit.collision,M)),t.toolkit.properties&&(B={},e.Utilities.DeepCopyProperties(t.toolkit.properties,B));var C=null;null!=t.toolkit.wheels&&t.toolkit.wheels.length>0&&(C=[],t.toolkit.wheels.forEach(function(t){if(null!=t){var n={};e.Utilities.DeepCopyProperties(t,n),C.push(n)}}));var T=null;null!=t.toolkit.components&&t.toolkit.components.length>0&&(T=[],t.toolkit.components.forEach(function(t){if(null!=t){var n=e.Utilities.FastJsonCopy(t);n.instance=null,T.push(n)}})),(i={}).parsed=!1,i.prefab=!1,i.buffers=null,i.lods=null,i.coverages=null,i.distances=null,i.handlers=null,i.instance=r,i.visible=o,i.visibility=a,i.billboard=s,i.tags=l,i.skin=u,i.bone=c,i.rootbone=d,i.rootpos=h,i.rootrot=p,i.group=m,i.layer=f,i.layername=g,i.navigation=v,i.lightmapped=y,i.lightmapuvs=_,i.animator=S,i.renderer=b,i.physics=A,i.wheels=C,i.collision=M,i.properties=B,i.components=T}null!=i&&(n={toolkit:i})}return n},t.FastJsonCopy=function(t){if(!t)return t;if(Array.isArray(t)){for(var n=[],i=t.length,r=0;r<i;r++)n.push(e.Utilities.FastJsonCopy(t[r]));return n}if("object"==typeof t){var o=Object.keys(t),a={};for(r=o.length-1;r>-1;r--){var s=o[r];a[s]=e.Utilities.FastJsonCopy(t[s])}return a}return t},t.DeepCopyProperties=function(t,n,i,r){for(var o in t)if(("_"!==o[0]||r&&-1!==r.indexOf(o))&&(!i||-1===i.indexOf(o))){var a=t[o],s=typeof a;if("function"!==s)if("object"===s)if(a instanceof Array){if(n[o]=[],a.length>0)if("object"==typeof a[0])for(var l=0;l<a.length;l++){var u=e.Utilities.CloneValue(a[l],n);-1===n[o].indexOf(u)&&n[o].push(u)}else n[o]=a.slice(0)}else n[o]=e.Utilities.CloneValue(a,n);else n[o]=a}},t.ValidateTransformMetadata=function(t){null==t.metadata&&(t.metadata={}),null==t.metadata.toolkit&&(t.metadata.toolkit={});var n=t.metadata.toolkit;e.Utilities.HasOwnProperty(n,"entity")||(t.metadata.toolkit.entity=!0),e.Utilities.HasOwnProperty(n,"parsed")||(t.metadata.toolkit.parsed=!1),e.Utilities.HasOwnProperty(n,"prefab")||(t.metadata.toolkit.prefab=!1),e.Utilities.HasOwnProperty(n,"instance")||(t.metadata.toolkit.instance=!1),e.Utilities.HasOwnProperty(n,"buffers")||(t.metadata.toolkit.buffers=null),e.Utilities.HasOwnProperty(n,"visible")||(t.metadata.toolkit.visible=!0),e.Utilities.HasOwnProperty(n,"visibility")||(t.metadata.toolkit.visibility=1),e.Utilities.HasOwnProperty(n,"billboard")||(t.metadata.toolkit.billboard=0),e.Utilities.HasOwnProperty(n,"tags")||(t.metadata.toolkit.tags="Untagged Layer0"),e.Utilities.HasOwnProperty(n,"skin")||(t.metadata.toolkit.skin=!1),e.Utilities.HasOwnProperty(n,"bone")||(t.metadata.toolkit.bone=null),e.Utilities.HasOwnProperty(n,"rootbone")||(t.metadata.toolkit.rootbone=!1),e.Utilities.HasOwnProperty(n,"rootpos")||(t.metadata.toolkit.rootpos=null),e.Utilities.HasOwnProperty(n,"rootrot")||(t.metadata.toolkit.rootrot=null),e.Utilities.HasOwnProperty(n,"group")||(t.metadata.toolkit.group="Untagged"),e.Utilities.HasOwnProperty(n,"layer")||(t.metadata.toolkit.layer=0),e.Utilities.HasOwnProperty(n,"layername")||(t.metadata.toolkit.layername="Default"),e.Utilities.HasOwnProperty(n,"navigation")||(t.metadata.toolkit.navigation=null),e.Utilities.HasOwnProperty(n,"lightmapped")||(t.metadata.toolkit.lightmapped=!1),e.Utilities.HasOwnProperty(n,"lightmapuvs")||(t.metadata.toolkit.lightmapuvs=!1),e.Utilities.HasOwnProperty(n,"animator")||(t.metadata.toolkit.animator=null),e.Utilities.HasOwnProperty(n,"lods")||(t.metadata.toolkit.lods=null),e.Utilities.HasOwnProperty(n,"coverages")||(t.metadata.toolkit.coverages=null),e.Utilities.HasOwnProperty(n,"distances")||(t.metadata.toolkit.distances=null),e.Utilities.HasOwnProperty(n,"handlers")||(t.metadata.toolkit.handlers=null),e.Utilities.HasOwnProperty(n,"physics")||(t.metadata.toolkit.physics=null),e.Utilities.HasOwnProperty(n,"wheels")||(t.metadata.toolkit.wheels=null),e.Utilities.HasOwnProperty(n,"renderer")||(t.metadata.toolkit.renderer=null),e.Utilities.HasOwnProperty(n,"collision")||(t.metadata.toolkit.collision=null),e.Utilities.HasOwnProperty(n,"properties")||(t.metadata.toolkit.properties=null),e.Utilities.HasOwnProperty(n,"components")||(t.metadata.toolkit.components=null)},t.UpVector=BABYLON.Vector3.Up(),t.AuxVector=BABYLON.Vector3.Zero(),t.ZeroVector=BABYLON.Vector3.Zero(),t.TempMatrix=BABYLON.Matrix.Zero(),t.TempMatrix2=BABYLON.Matrix.Zero(),t.TempVector2=BABYLON.Vector2.Zero(),t.TempVector3=BABYLON.Vector3.Zero(),t.TempQuaternion=BABYLON.Quaternion.Zero(),t.TempQuaternion2=BABYLON.Quaternion.Zero(),t.TempQuaternion3=BABYLON.Quaternion.Zero(),t.TempDirectionBuffer=BABYLON.Vector3.Zero(),t.LoadingState=-1,t.OnPreloaderProgress=null,t.OnPreloaderComplete=null,t.LoaderItemsMarkedForDisposal=[],t}();e.Utilities=t}(i||(i={})),function(e){var t=function(t){function n(n,i){var r=t.call(this,n,i)||this;return r.terrainInfo=null,r.shader=r.getShaderName(),r.plugin=new e.UniversalTerrainMaterialPlugin(r,r.shader),r}return r(n,t),n.prototype.awake=function(){},n.prototype.update=function(){},n.prototype.getShaderName=function(){return"UniversalTerrainMaterial"},n.prototype.getTerrainInfo=function(){return this.terrainInfo},n}(e.CustomShaderMaterial);e.UniversalTerrainMaterial=t;var n=function(t){function n(e,n){var i=t.call(this,e,n,100,{UNIVERSALTERRAINMATERIAL:!1},!0,!0,!1)||this;return i.colorName="surfaceAlbedo",i.splatmapSampler="splatmapSampler",i.detailsSampler="detailsSampler",i.normalsSampler="normalsSampler",i.GLSL_CustomFragment=null,i.GLSL_CustomVertex=null,i.GLSL_VertexMainEnd=null,i.GLSL_FragmentUpdateColor=null,i.WGSL_CustomFragment=null,i.WGSL_CustomVertex=null,i.WGSL_VertexMainEnd=null,i.WGSL_FragmentUpdateColor=null,i}return r(n,t),n.prototype.isCompatible=function(e){return e===BABYLON.ShaderLanguage.WGSL||e===BABYLON.ShaderLanguage.GLSL},n.prototype.getClassName=function(){return"UniversalTerrainMaterialPlugin"},n.prototype.getCustomCode=function(t,n){var i=this.getCustomShaderMaterial().getTerrainInfo();if("vertex"===t){if(n===BABYLON.ShaderLanguage.WGSL)return null==this.WGSL_CustomVertex&&(this.WGSL_CustomVertex=this.WGSL_FormatTerrainVertexDefintions(i)),null==this.WGSL_VertexMainEnd&&(this.WGSL_VertexMainEnd=this.WGSL_FormatTerrainVertexMainEnd(i)),{CUSTOM_VERTEX_DEFINITIONS:this.WGSL_CustomVertex,CUSTOM_VERTEX_MAIN_END:this.WGSL_VertexMainEnd};if(n===BABYLON.ShaderLanguage.GLSL)return null==this.GLSL_CustomVertex&&(this.GLSL_CustomVertex=this.GLSL_FormatTerrainVertexDefintions(i)),null==this.GLSL_VertexMainEnd&&(this.GLSL_VertexMainEnd=this.GLSL_FormatTerrainVertexMainEnd(i)),{CUSTOM_VERTEX_DEFINITIONS:this.GLSL_CustomVertex,CUSTOM_VERTEX_MAIN_END:this.GLSL_VertexMainEnd}}else if("fragment"===t){if(n===BABYLON.ShaderLanguage.WGSL)return null==this.WGSL_CustomFragment&&(this.WGSL_CustomFragment=this.WGSL_FormatTerrainFragmentDefintions(i,this.splatmapSampler,this.detailsSampler,this.normalsSampler)),null==this.WGSL_FragmentUpdateColor&&(this.WGSL_FragmentUpdateColor=this.WGSL_FormatTerrainFragmentUpdateColor(i,this.colorName,this.splatmapSampler,this.detailsSampler,this.normalsSampler,e.SceneManager.TerrainColorCorrection)),{CUSTOM_FRAGMENT_DEFINITIONS:this.WGSL_CustomFragment,CUSTOM_FRAGMENT_BEFORE_LIGHTS:this.WGSL_FragmentUpdateColor};if(n===BABYLON.ShaderLanguage.GLSL)return null==this.GLSL_CustomFragment&&(this.GLSL_CustomFragment=this.GLSL_FormatTerrainFragmentDefintions(i,this.splatmapSampler,this.detailsSampler,this.normalsSampler)),null==this.GLSL_FragmentUpdateColor&&(this.GLSL_FragmentUpdateColor=this.GLSL_FormatTerrainFragmentUpdateColor(i,this.colorName,this.splatmapSampler,this.detailsSampler,this.normalsSampler,e.SceneManager.TerrainColorCorrection)),{CUSTOM_FRAGMENT_DEFINITIONS:this.GLSL_CustomFragment,CUSTOM_FRAGMENT_BEFORE_LIGHTS:this.GLSL_FragmentUpdateColor}}return null},n.prototype.getUniforms=function(e){var t=e===BABYLON.ShaderLanguage.WGSL;return this.vertexDefinitions=this.getCustomShaderMaterial().getCustomVertexCode(t),this.fragmentDefinitions=!0===t?this.getCustomShaderMaterial().getCustomFragmentCode(t):null,this.getCustomShaderMaterial().getCustomUniforms(t)},n.prototype.getSamplers=function(e){var t=this.getCustomShaderMaterial().getCustomSamplers();null!=t&&t.length>0&&e.push.apply(e,t)},n.prototype.getAttributes=function(e,t,n){var i=this.getCustomShaderMaterial().getCustomAttributes();null!=i&&i.length>0&&e.push.apply(e,i)},n.prototype.prepareDefines=function(e,t,n){this.getIsEnabled()&&this.getCustomShaderMaterial().prepareCustomDefines(e)},n.prototype.bindForSubMesh=function(e,t,n,i){this.getIsEnabled()&&this.getCustomShaderMaterial().updateCustomBindings(e)},n.prototype.WGSL_FormatTerrainVertexDefintions=function(e){var t="";return null!=e&&null!=e.textureAtlas&&null!=e.splatmapAtlas&&e.splatmapCount>0&&(t="\r\n#ifndef TERRAIN_VERTEX_DEFINITIONS\r\n\r\n#define TERRAIN_VERTEX_DEFINITIONS\r\n\r\nvarying vSplatmapUV: vec2<f32>;\r\n\r\n#endif\r\n\r\n"),t},n.prototype.WGSL_FormatTerrainVertexMainEnd=function(e){var t="";return null!=e&&null!=e.textureAtlas&&null!=e.splatmapAtlas&&e.splatmapCount>0&&(t="\r\n#ifndef TERRAIN_VERTEX_MAIN_END\r\n\r\n#define TERRAIN_VERTEX_MAIN_END\r\n\r\n#ifdef UV1\r\nvertexOutputs.vSplatmapUV = uvUpdated;\r\n#endif\r\n\r\n#endif\r\n\r\n"),t},n.prototype.WGSL_FormatTerrainFragmentDefintions=function(e,t,n,i){var r="";return null!=e&&null!=e.textureAtlas&&null!=e.splatmapAtlas&&e.splatmapCount>0&&(r="\r\n#ifndef TERRAIN_FRAGMENT_DEFNITIONS\r\n\r\n#define TERRAIN_FRAGMENT_DEFNITIONS\r\n\r\nvarying vSplatmapUV: vec2<f32>;\r\n\r\nfn srgb_to_linear(c: vec3<f32>) -> vec3<f32>\r\n{\r\n return pow(c, vec3<f32>(2.2));\r\n}\r\n\r\nfn linear_to_srgb(c: vec3<f32>) -> vec3<f32>\r\n{\r\n return pow(c, vec3<f32>(1.0 / 2.2));\r\n}\r\n\r\nfn calculateMipmapLevel(uvs: vec2<f32>, size: vec2<f32>) -> f32\r\n{\r\n let dx: vec2<f32> = dpdx(uvs * size.x);\r\n let dy: vec2<f32> = dpdy(uvs * size.y);\r\n let d: f32 = max(dot(dx, dx), dot(dy, dy));\r\n return (0.4 * log2(d));\r\n}\r\n\r\nfn sampleTextureAtlas2D(atlas: texture_2d<f32>, sampler: sampler, gamma: f32, tile: vec2<f32>, rect: vec4<f32>, uvs: vec2<f32>, lod: f32) -> vec4<f32>\r\n{\r\n var level: f32 = lod;\r\n if (level < 0.0) {\r\n level = clamp(calculateMipmapLevel(uvs, vec2(tile.x, tile.x)), 0.0, tile.y);\r\n }\r\n let size: f32 = pow(2.0, tile.y - level);\r\n let sizex: f32 = size / rect.z;\r\n let sizey: f32 = size / rect.w;\r\n var uv: vec2<f32> = fract(uvs);\r\n uv.x = uv.x * ((sizex * rect.z - 1.0) / sizex) + 0.5 / sizex + rect.z * rect.x;\r\n uv.y = uv.y * ((sizey * rect.w - 1.0) / sizey) + 0.5 / sizey + rect.w * rect.y;\r\n var color: vec4<f32> = textureSampleLevel(atlas, sampler, uv, level);\r\n if (gamma != 1.0) {\r\n color.r = pow(color.r, gamma);\r\n color.g = pow(color.g, gamma);\r\n color.b = pow(color.b, gamma);\r\n }\r\n return color;\r\n}\r\n\r\nfn sampleSplatmapAtlas2D(atlas: texture_2d<f32>, sampler: sampler, tile: vec2<f32>, rect: vec4<f32>, uvs: vec2<f32>) -> vec4<f32>\r\n{\r\n let size: f32 = pow(2.0, tile.y);\r\n\t let sizex: f32 = size / rect.z;\r\n\t let sizey: f32 = size / rect.w;\r\n\t var uv: vec2<f32> = uvs;\r\n\t uv.x = uv.x * ((sizex * rect.z - 1.0) / sizex) + 0.5 / sizex + rect.z * rect.x;\r\n\t uv.y = uv.y * ((sizey * rect.w - 1.0) / sizey) + 0.5 / sizey + rect.w * rect.y;\r\n return textureSample(atlas, sampler, uv);\r\n}\r\n\r\nfn blendSplatmapAtlasColors(splatmap: vec4<f32>, color1: vec4<f32>, color2: vec4<f32>, color3: vec4<f32>, color4: vec4<f32>, mixbuffer: vec3<f32>) -> vec3<f32>\r\n{\r\n let buffer1: vec3<f32> = mix(mixbuffer, color1.rgb, splatmap.r);\r\n let buffer2: vec3<f32> = mix(buffer1, color2.rgb, splatmap.g);\r\n let buffer3: vec3<f32> = mix(buffer2, color3.rgb, splatmap.b);\r\n return mix(buffer3, color4.rgb, splatmap.a);\r\n}\r\n\r\nfn perturbNormalSamplerColor(cotangentFrame: mat3x3<f32>, samplerColor: vec3<f32>, scale: f32) -> vec3<f32>\r\n{\r\n var map: vec3<f32> = samplerColor.xyz;\r\n map = map * 2.00787402 - 1.00787402;\r\n #ifdef NORMALXYSCALE\r\n map = normalize(map * vec3<f32>(scale, scale, 1.0));\r\n #endif\r\n return normalize(cotangentFrame * map);\r\n}\r\n#endif\r\n\r\n"),r},n.prototype.WGSL_FormatTerrainFragmentUpdateColor=function(e,t,n,i,r,o){void 0===o&&(o=1);var a="";if(null!=e&&null!=e.textureAtlas&&null!=e.splatmapAtlas&&e.splatmapCount>0){if(a="\r\n#ifndef TERRAIN_FRAGMENT_UPDATE_COLOR\r\n\r\n#define TERRAIN_FRAGMENT_UPDATE_COLOR\r\n\r\nvar normalsColor: vec3<f32> = vec3<f32>(0.5, 0.5, 1.0);\r\nvar normalsBuffer: vec3<f32> = normalW.rgb;\r\nvar splatmapBuffer: vec3<f32> = "+t+".rgb;\r\nvar autoMipMapLevel: f32 = -1.0;\r\nvar normalCorrection: f32 = 1.0;\r\nvar detailCorrection: f32 = "+o.toFixed(4)+";\r\n\r\n#if defined(ALBEDO) && defined("+n.toUpperCase()+") && defined("+i.toUpperCase()+")\r\n\r\n// Reset Normal Values\r\n#if defined(BUMP) || defined(PARALLAX) || defined(ANISOTROPIC)\r\n uvOffset = vec2<f32>(0.0, 0.0);\r\n #ifdef NORMAL\r\n normalW = normalize(input.vNormalW);\r\n #else\r\n normalW = normalize(cross(dpdx(input.vPositionW), dpdy(input.vPositionW))) * scene.vEyePosition.w;\r\n #endif\r\n #ifdef CLEARCOAT\r\n clearCoatNormalW = normalW;\r\n #endif\r\n #if defined(BUMP) || defined(PARALLAX)\r\n #if defined(CLEARCOAT_BUMP) && defined(TANGENT) && defined(NORMAL)\r\n TBN = vTBN;\r\n #else\r\n TBN = cotangent_frame(normalW, input.vPositionW, fragmentInputs.vSplatmapUV, vec2<f32>(1.0, 1.0));\r\n #endif\r\n #elif defined(ANISOTROPIC)\r\n #if defined(CLEARCOAT_BUMP) && defined(TANGENT) && defined(NORMAL)\r\n TBN = vTBN;\r\n #else\r\n TBN = cotangent_frame(normalW, input.vPositionW, fragmentInputs.vSplatmapUV, vec2<f32>(1.0, 1.0));\r\n #endif\r\n #endif\r\n #ifdef PARALLAX\r\n invTBN = transposeMat3(TBN);\r\n #endif\r\n normalW = perturbNormalSamplerColor(TBN, normalsColor, 1.0);\r\n#endif\r\n\r\n// Global Atlas Values\r\nlet splatTileSize: f32 = "+e.splatmapAtlas[2].toFixed(4)+";\r\nlet splatTileBits: f32 = "+e.splatmapAtlas[3].toFixed(4)+";\r\nlet detailTileSize: f32 = "+e.textureAtlas[2].toFixed(4)+";\r\nlet detailTileBits: f32 = "+e.textureAtlas[3].toFixed(4)+";\r\n\r\n// Sample splatmap textures\r\n",e.splatmapCount>0){var s=0;a+="normalsBuffer = vec3<f32>(0.0,0.0,0.0);\r\n";for(var l=0;l<e.splatmapCount;l++){s=4*l;var u=e["splatmapRect"+l];if(a+="var splatmapRect"+l+": vec4<f32> = vec4<f32>("+u[0].toFixed(4)+", "+u[1].toFixed(4)+", "+u[2].toFixed(4)+", "+u[3].toFixed(4)+");\r\n",a+="var splatmapAlbedo"+l+": vec4<f32> = sampleSplatmapAtlas2D("+n+", "+n+"Sampler, vec2<f32>(splatTileSize, splatTileBits), splatmapRect"+l+", (fragmentInputs.vSplatmapUV + uvOffset));\r\n",a+="var textureAlbedo"+(s+0)+": vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 1.0);\r\n",a+="var textureAlbedo"+(s+1)+": vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 1.0);\r\n",a+="var textureAlbedo"+(s+2)+": vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 1.0);\r\n",a+="var textureAlbedo"+(s+3)+": vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 1.0);\r\n",e["textureRect"+(s+0)]){var c=e["textureRect"+(s+0)],d=e["textureInfo"+(s+0)];a+="var textureRect"+(s+0)+": vec4<f32> = vec4<f32>("+c[0].toFixed(4)+", "+c[1].toFixed(4)+", "+c[2].toFixed(4)+", "+c[3].toFixed(4)+");\r\n",a+="var textureScale"+(s+0)+": vec2<f32> = vec2<f32>("+d[0].toFixed(4)+", "+d[1].toFixed(4)+");\r\n",a+="var textureOffset"+(s+0)+": vec2<f32> = vec2<f32>("+d[2].toFixed(4)+", "+d[3].toFixed(4)+");\r\n",a+="var textureTileUV"+(s+0)+": vec2<f32> = ((fragmentInputs.vSplatmapUV + textureOffset"+(s+0)+") * textureScale"+(s+0)+");\r\n",a+="textureAlbedo"+(s+0)+" = sampleTextureAtlas2D("+i+", "+i+"Sampler, detailCorrection, vec2<f32>(detailTileSize, detailTileBits), textureRect"+(s+0)+", textureTileUV"+(s+0)+", autoMipMapLevel);\r\n"}e["textureRect"+(s+1)]&&(c=e["textureRect"+(s+1)],d=e["textureInfo"+(s+1)],a+="var textureRect"+(s+1)+": vec4<f32> = vec4<f32>("+c[0].toFixed(4)+", "+c[1].toFixed(4)+", "+c[2].toFixed(4)+", "+c[3].toFixed(4)+");\r\n",a+="var textureScale"+(s+1)+": vec2<f32> = vec2<f32>("+d[0].toFixed(4)+", "+d[1].toFixed(4)+");\r\n",a+="var textureOffset"+(s+1)+": vec2<f32> = vec2<f32>("+d[2].toFixed(4)+", "+d[3].toFixed(4)+");\r\n",a+="var textureTileUV"+(s+1)+": vec2<f32> = ((fragmentInputs.vSplatmapUV + textureOffset"+(s+1)+") * textureScale"+(s+1)+");\r\n",a+="textureAlbedo"+(s+1)+" = sampleTextureAtlas2D("+i+", "+i+"Sampler, detailCorrection, vec2<f32>(detailTileSize, detailTileBits), textureRect"+(s+1)+", textureTileUV"+(s+1)+", autoMipMapLevel);\r\n"),e["textureRect"+(s+2)]&&(c=e["textureRect"+(s+2)],d=e["textureInfo"+(s+2)],a+="var textureRect"+(s+2)+": vec4<f32> = vec4<f32>("+c[0].toFixed(4)+", "+c[1].toFixed(4)+", "+c[2].toFixed(4)+", "+c[3].toFixed(4)+");\r\n",a+="var textureScale"+(s+2)+": vec2<f32> = vec2<f32>("+d[0].toFixed(4)+", "+d[1].toFixed(4)+");\r\n",a+="var textureOffset"+(s+2)+": vec2<f32> = vec2<f32>("+d[2].toFixed(4)+", "+d[3].toFixed(4)+");\r\n",a+="var textureTileUV"+(s+2)+": vec2<f32> = ((fragmentInputs.vSplatmapUV + textureOffset"+(s+2)+") * textureScale"+(s+2)+");\r\n",a+="textureAlbedo"+(s+2)+" = sampleTextureAtlas2D("+i+", "+i+"Sampler, detailCorrection, vec2<f32>(detailTileSize, detailTileBits), textureRect"+(s+2)+", textureTileUV"+(s+2)+", autoMipMapLevel);\r\n"),e["textureRect"+(s+3)]&&(c=e["textureRect"+(s+3)],d=e["textureInfo"+(s+3)],a+="var textureRect"+(s+3)+": vec4<f32> = vec4<f32>("+c[0].toFixed(4)+", "+c[1].toFixed(4)+", "+c[2].toFixed(4)+", "+c[3].toFixed(4)+");\r\n",a+="var textureScale"+(s+3)+": vec2<f32> = vec2<f32>("+d[0].toFixed(4)+", "+d[1].toFixed(4)+");\r\n",a+="var textureOffset"+(s+3)+": vec2<f32> = vec2<f32>("+d[2].toFixed(4)+", "+d[3].toFixed(4)+");\r\n",a+="var textureTileUV"+(s+3)+": vec2<f32> = ((fragmentInputs.vSplatmapUV + textureOffset"+(s+3)+") * textureScale"+(s+3)+");\r\n",a+="textureAlbedo"+(s+3)+" = sampleTextureAtlas2D("+i+", "+i+"Sampler, detailCorrection, vec2<f32>(detailTileSize, detailTileBits), textureRect"+(s+3)+", textureTileUV"+(s+3)+", autoMipMapLevel);\r\n"),a+="splatmapBuffer = blendSplatmapAtlasColors(splatmapAlbedo"+l+", textureAlbedo"+(s+0)+", textureAlbedo"+(s+1)+", textureAlbedo"+(s+2)+", textureAlbedo"+(s+3)+", splatmapBuffer);\r\n",a+="#if defined(BUMP) || defined(PARALLAX) || defined(ANISOTROPIC)\r\n",a+=" #if defined("+r.toUpperCase()+")\r\n",a+=" var normalColor"+(s+0)+": vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 1.0);\r\n",a+=" var normalColor"+(s+1)+": vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 1.0);\r\n",a+=" var normalColor"+(s+2)+": vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 1.0);\r\n",a+=" var normalColor"+(s+3)+": vec4<f32> = vec4<f32>(0.0, 0.0, 0.0, 1.0);\r\n",e["textureRect"+(s+0)]&&(a+=" var normalScale"+(s+0)+": f32 = "+e["normalsScale"+(s+0)].toFixed(4)+";\r\n",a+=" normalColor"+(s+0)+" = sampleTextureAtlas2D("+r+", "+r+"Sampler, normalCorrection, vec2<f32>(detailTileSize, detailTileBits), textureRect"+(s+0)+", textureTileUV"+(s+0)+", autoMipMapLevel);\r\n",a+=" normalColor"+(s+0)+" = vec4<f32>(perturbNormalSamplerColor(TBN, normalColor"+(s+0)+".rgb, normalScale"+(s+0)+"), 1.0);\r\n"),e["textureRect"+(s+1)]&&(a+=" var normalScale"+(s+1)+": f32 = "+e["normalsScale"+(s+1)].toFixed(4)+";\r\n",a+=" normalColor"+(s+1)+" = sampleTextureAtlas2D("+r+", "+r+"Sampler, normalCorrection, vec2<f32>(detailTileSize, detailTileBits), textureRect"+(s+1)+", textureTileUV"+(s+1)+", autoMipMapLevel);\r\n",a+=" normalColor"+(s+1)+" = vec4<f32>(perturbNormalSamplerColor(TBN, normalColor"+(s+1)+".rgb, normalScale"+(s+1)+"), 1.0);\r\n"),e["textureRect"+(s+2)]&&(a+=" var normalScale"+(s+2)+": f32 = "+e["normalsScale"+(s+2)].toFixed(4)+";\r\n",a+=" normalColor"+(s+2)+" = sampleTextureAtlas2D("+r+", "+r+"Sampler, normalCorrection, vec2<f32>(detailTileSize, detailTileBits), textureRect"+(s+2)+", textureTileUV"+(s+2)+", autoMipMapLevel);\r\n",a+=" normalColor"+(s+2)+" = vec4<f32>(perturbNormalSamplerColor(TBN, normalColor"+(s+2)+".rgb, normalScale"+(s+2)+"), 1.0);\r\n"),e["textureRect"+(s+3)]&&(a+=" var normalScale"+(s+3)+": f32 = "+e["normalsScale"+(s+3)].toFixed(4)+";\r\n",a+=" normalColor"+(s+3)+" = sampleTextureAtlas2D("+r+", "+r+"Sampler, normalCorrection, vec2<f32>(detailTileSize, detailTileBits), textureRect"+(s+3)+", textureTileUV"+(s+3)+", autoMipMapLevel);\r\n",a+=" normalColor"+(s+3)+" = vec4<f32>(perturbNormalSamplerColor(TBN, normalColor"+(s+3)+".rgb, normalScale"+(s+3)+"), 1.0);\r\n"),a+=" normalsBuffer = blendSplatmapAtlasColors(splatmapAlbedo"+l+", normalColor"+(s+0)+", normalColor"+(s+1)+", normalColor"+(s+2)+", normalColor"+(s+3)+", normalsBuffer);\r\n",a+=" #endif\r\n",a+="#endif\r\n",a+="\r\n"}}a+="// Update Color Values\r\n"+t+" = splatmapBuffer.rgb;\r\n#if defined(BUMP) || defined(PARALLAX) || defined(ANISOTROPIC)\r\n #if defined("+r.toUpperCase()+")\r\n normalW = normalsBuffer.rgb;\r\n #endif\r\n #if defined(FORCENORMALFORWARD) && defined(NORMAL)\r\n var faceNormal: vec3<f32> = normalize(cross(dpdx(input.vPositionW), dpdy(input.vPositionW))) * scene.vEyePosition.w;\r\n #if defined(TWOSIDEDLIGHTING)\r\n faceNormal = select(-faceNormal, faceNormal, fragmentInputs.frontFacing)\r\n #endif\r\n normalW *= sign(dot(normalW, faceNormal));\r\n #endif\r\n #if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\r\n normalW = select(-normalW, normalW, fragmentInputs.frontFacing);\r\n #endif\r\n#endif\r\n\r\n#endif\r\n\r\n#endif\r\n\r\n"}return a},n.prototype.GLSL_FormatTerrainVertexDefintions=function(e){var t="";return null!=e&&null!=e.textureAtlas&&null!=e.splatmapAtlas&&e.splatmapCount>0&&(t="\r\n#ifndef TERRAIN_VERTEX_DEFINITIONS\r\n\r\n#define TERRAIN_VERTEX_DEFINITIONS\r\n\r\nvarying vec2 vSplatmapUV;\r\n\r\n#endif\r\n\r\n"),t},n.prototype.GLSL_FormatTerrainVertexMainEnd=function(e){var t="";return null!=e&&null!=e.textureAtlas&&null!=e.splatmapAtlas&&e.splatmapCount>0&&(t="\r\n#ifndef TERRAIN_VERTEX_MAIN_END\r\n\r\n#define TERRAIN_VERTEX_MAIN_END\r\n\r\n#ifdef UV1\r\nvSplatmapUV = uv;\r\n#endif\r\n\r\n#endif\r\n\r\n"),t},n.prototype.GLSL_FormatTerrainFragmentDefintions=function(e,t,n,i){var r="";return null!=e&&null!=e.textureAtlas&&null!=e.splatmapAtlas&&e.splatmapCount>0&&(r="\r\n#ifndef TERRAIN_FRAGMENT_DEFNITIONS\r\n\r\n#define TERRAIN_FRAGMENT_DEFNITIONS\r\n\r\nvarying vec2 vSplatmapUV;\r\n\r\nvec3 srgb_to_linear(const in vec3 c)\r\n{\r\n return pow(c, vec3(2.2));\r\n}\r\n\r\nvec3 linear_to_srgb(const in vec3 c)\r\n{\r\n return pow(c, vec3(1.0 / 2.2));\r\n}\r\n\r\nfloat calculateMipmapLevel(const in vec2 uvs, const in vec2 size)\r\n{\r\n vec2 dx = dFdx(uvs * size.x);\r\n vec2 dy = dFdy(uvs * size.y);\r\n float d = max(dot(dx, dx), dot(dy, dy));\r\n return 0.4 * log2(d);\r\n}\r\n\r\nvec4 sampleTextureAtlas2D(const in sampler2D atlas, const in float gamma, const in vec2 tile, const in vec4 rect, in vec2 uvs, in float lod)\r\n{\r\n if (lod < 0.0) lod = clamp(calculateMipmapLevel(uvs, vec2(tile.x, tile.x)), 0.0, tile.y); // Tile Info (tile.xy)\r\n float size = pow(2.0, tile.y - lod); // Tile Bits (tile.y)\r\n float sizex = size / rect.z; // Tile Width (rect.z)\r\n float sizey = size / rect.w; // Tile Height (rect.w)\r\n uvs = fract(uvs); // Perfrom Tiling (fract)\r\n uvs.x = uvs.x * ((sizex * rect.z - 1.0) / sizex) + 0.5 / sizex + rect.z * rect.x; // Tile Position X (rect.x)\r\n uvs.y = uvs.y * ((sizey * rect.w - 1.0) / sizey) + 0.5 / sizey + rect.w * rect.y; // Tile Position Y (rect.y)\r\n vec4 color = texture2DLodEXT(atlas, uvs, lod);\r\n if (gamma != 1.0) {\r\n color.r = pow(color.r, gamma);\r\n color.g = pow(color.g, gamma);\r\n color.b = pow(color.b, gamma);\r\n }\r\n return color;\r\n}\r\n\r\nvec4 sampleSplatmapAtlas2D(const in sampler2D atlas, const in vec2 tile, const in vec4 rect, in vec2 uvs)\r\n{\r\n float size = pow(2.0, tile.y); // Tile Bits (tile.y)\r\n\t float sizex = size / rect.z; // Tile Width (rect.z)\r\n\t float sizey = size / rect.w; // Tile Height (rect.w)\r\n\t uvs.x = uvs.x * ((sizex * rect.z - 1.0) / sizex) + 0.5 / sizex + rect.z * rect.x; // Tile Position X (rect.x)\r\n\t uvs.y = uvs.y * ((sizey * rect.w - 1.0) / sizey) + 0.5 / sizey + rect.w * rect.y; // Tile Position Y (rect.y)\r\n return texture2D(atlas, uvs);\r\n}\r\n\r\nvec3 blendSplatmapAtlasColors(const in vec4 splatmap, in vec4 color1, in vec4 color2, in vec4 color3, in vec4 color4, in vec3 mixbuffer)\r\n{\r\n vec3 buffer1 = mix(mixbuffer, color1.rgb, splatmap.r);\r\n vec3 buffer2 = mix(buffer1, color2.rgb, splatmap.g);\r\n vec3 buffer3 = mix(buffer2, color3.rgb, splatmap.b);\r\n return mix(buffer3, color4.rgb, splatmap.a);\r\n}\r\n\r\nvec3 perturbNormalSamplerColor(mat3 cotangentFrame, vec3 samplerColor, float scale)\r\n{\r\n vec3 map = samplerColor.xyz;\r\n map = map * 2.00787402 - 1.00787402;\r\n #ifdef NORMALXYSCALE\r\n map = normalize(map * vec3(scale, scale, 1.0));\r\n #endif\r\n return normalize(cotangentFrame * map);\r\n}\r\n\r\n\r\n#endif\r\n\r\n"),r},n.prototype.GLSL_FormatTerrainFragmentUpdateColor=function(e,t,n,i,r,o){void 0===o&&(o=1);var a="";if(null!=e&&null!=e.textureAtlas&&null!=e.splatmapAtlas&&e.splatmapCount>0){if(a="\r\n#ifndef TERRAIN_FRAGMENT_UPDATE_COLOR\r\n\r\n#define TERRAIN_FRAGMENT_UPDATE_COLOR\r\n\r\nvec3 normalsColor = vec3(0.5, 0.5, 1.0);\r\nvec3 normalsBuffer = normalW.rgb;\r\nvec3 splatmapBuffer = "+t+".rgb;\r\nfloat autoMipMapLevel = -1.0;\r\nfloat normalCorrection = 1.0;\r\nfloat detailCorrection = "+o.toFixed(4)+";\r\n\r\n#if defined(ALBEDO) && defined("+n.toUpperCase()+") && defined("+i.toUpperCase()+")\r\n\r\n// Reset Normal Values\r\n#if defined(BUMP) || defined(PARALLAX) || defined(ANISOTROPIC)\r\n uvOffset = vec2(0.0, 0.0);\r\n #ifdef NORMAL\r\n normalW = normalize(vNormalW);\r\n #else\r\n normalW = normalize(cross(dFdx(vPositionW), dFdy(vPositionW))) * vEyePosition.w;\r\n #endif\r\n #ifdef CLEARCOAT\r\n clearCoatNormalW = normalW;\r\n #endif\r\n #if defined(BUMP) || defined(PARALLAX)\r\n #if defined(TANGENT) && defined(NORMAL)\r\n TBN = vTBN;\r\n #else\r\n TBN = cotangent_frame(normalW, vPositionW, vSplatmapUV);\r\n #endif\r\n #elif defined(ANISOTROPIC)\r\n #if defined(TANGENT) && defined(NORMAL)\r\n TBN = vTBN;\r\n #else\r\n TBN = cotangent_frame(normalW, vPositionW, vSplatmapUV, vec2(1.0, 1.0));\r\n #endif\r\n #endif\r\n #ifdef PARALLAX\r\n invTBN = transposeMat3(TBN);\r\n #endif\r\n normalW = perturbNormalSamplerColor(TBN, normalsColor, 1.0);\r\n#endif\r\n\r\n// Global Atlas Values\r\nfloat splatTileSize = "+e.splatmapAtlas[2].toFixed(4)+";\r\nfloat splatTileBits = "+e.splatmapAtlas[3].toFixed(4)+";\r\nfloat detailTileSize = "+e.textureAtlas[2].toFixed(4)+";\r\nfloat detailTileBits = "+e.textureAtlas[3].toFixed(4)+";\r\n\r\n// Sample splatmap textures\r\n",e.splatmapCount>0){var s=0;a+="normalsBuffer = vec3(0.0,0.0,0.0);\r\n";for(var l=0;l<e.splatmapCount;l++){s=4*l;var u=e["splatmapRect"+l];if(a+="vec4 splatmapRect"+l+" = vec4("+u[0].toFixed(4)+", "+u[1].toFixed(4)+", "+u[2].toFixed(4)+", "+u[3].toFixed(4)+");\r\n",a+="vec4 splatmapAlbedo"+l+" = sampleSplatmapAtlas2D("+n+", vec2(splatTileSize, splatTileBits), splatmapRect"+l+", (vSplatmapUV + uvOffset));\r\n",a+="vec4 textureAlbedo"+(s+0)+" = vec4(0.0, 0.0, 0.0, 1.0);\r\n",a+="vec4 textureAlbedo"+(s+1)+" = vec4(0.0, 0.0, 0.0, 1.0);\r\n",a+="vec4 textureAlbedo"+(s+2)+" = vec4(0.0, 0.0, 0.0, 1.0);\r\n",a+="vec4 textureAlbedo"+(s+3)+" = vec4(0.0, 0.0, 0.0, 1.0);\r\n",e["textureRect"+(s+0)]){var c=e["textureRect"+(s+0)],d=e["textureInfo"+(s+0)];a+="vec4 textureRect"+(s+0)+" = vec4("+c[0].toFixed(4)+", "+c[1].toFixed(4)+", "+c[2].toFixed(4)+", "+c[3].toFixed(4)+");\r\n",a+="vec2 textureScale"+(s+0)+" = vec2("+d[0].toFixed(4)+", "+d[1].toFixed(4)+");\r\n",a+="vec2 textureOffset"+(s+0)+" = vec2("+d[2].toFixed(4)+", "+d[3].toFixed(4)+");\r\n",a+="vec2 textureTileUV"+(s+0)+" = ((vSplatmapUV + textureOffset"+(s+0)+") * textureScale"+(s+0)+");\r\n",a+="textureAlbedo"+(s+0)+" = sampleTextureAtlas2D("+i+", detailCorrection, vec2(detailTileSize, detailTileBits), textureRect"+(s+0)+", textureTileUV"+(s+0)+", autoMipMapLevel);\r\n"}e["textureRect"+(s+1)]&&(c=e["textureRect"+(s+1)],d=e["textureInfo"+(s+1)],a+="vec4 textureRect"+(s+1)+" = vec4("+c[0].toFixed(4)+", "+c[1].toFixed(4)+", "+c[2].toFixed(4)+", "+c[3].toFixed(4)+");\r\n",a+="vec2 textureScale"+(s+1)+" = vec2("+d[0].toFixed(4)+", "+d[1].toFixed(4)+");\r\n",a+="vec2 textureOffset"+(s+1)+" = vec2("+d[2].toFixed(4)+", "+d[3].toFixed(4)+");\r\n",a+="vec2 textureTileUV"+(s+1)+" = ((vSplatmapUV + textureOffset"+(s+1)+") * textureScale"+(s+1)+");\r\n",a+="textureAlbedo"+(s+1)+" = sampleTextureAtlas2D("+i+", detailCorrection, vec2(detailTileSize, detailTileBits), textureRect"+(s+1)+", textureTileUV"+(s+1)+", autoMipMapLevel);\r\n"),e["textureRect"+(s+2)]&&(c=e["textureRect"+(s+2)],d=e["textureInfo"+(s+2)],a+="vec4 textureRect"+(s+2)+" = vec4("+c[0].toFixed(4)+", "+c[1].toFixed(4)+", "+c[2].toFixed(4)+", "+c[3].toFixed(4)+");\r\n",a+="vec2 textureScale"+(s+2)+" = vec2("+d[0].toFixed(4)+", "+d[1].toFixed(4)+");\r\n",a+="vec2 textureOffset"+(s+2)+" = vec2("+d[2].toFixed(4)+", "+d[3].toFixed(4)+");\r\n",a+="vec2 textureTileUV"+(s+2)+" = ((vSplatmapUV + textureOffset"+(s+2)+") * textureScale"+(s+2)+");\r\n",a+="textureAlbedo"+(s+2)+" = sampleTextureAtlas2D("+i+", detailCorrection, vec2(detailTileSize, detailTileBits), textureRect"+(s+2)+", textureTileUV"+(s+2)+", autoMipMapLevel);\r\n"),e["textureRect"+(s+3)]&&(c=e["textureRect"+(s+3)],d=e["textureInfo"+(s+3)],a+="vec4 textureRect"+(s+3)+" = vec4("+c[0].toFixed(4)+", "+c[1].toFixed(4)+", "+c[2].toFixed(4)+", "+c[3].toFixed(4)+");\r\n",a+="vec2 textureScale"+(s+3)+" = vec2("+d[0].toFixed(4)+", "+d[1].toFixed(4)+");\r\n",a+="vec2 textureOffset"+(s+3)+" = vec2("+d[2].toFixed(4)+", "+d[3].toFixed(4)+");\r\n",a+="vec2 textureTileUV"+(s+3)+" = ((vSplatmapUV + textureOffset"+(s+3)+") * textureScale"+(s+3)+");\r\n",a+="textureAlbedo"+(s+3)+" = sampleTextureAtlas2D("+i+", detailCorrection, vec2(detailTileSize, detailTileBits), textureRect"+(s+3)+", textureTileUV"+(s+3)+", autoMipMapLevel);\r\n"),a+="splatmapBuffer = blendSplatmapAtlasColors(splatmapAlbedo"+l+", textureAlbedo"+(s+0)+", textureAlbedo"+(s+1)+", textureAlbedo"+(s+2)+", textureAlbedo"+(s+3)+", splatmapBuffer);\r\n",a+="#if defined(BUMP) || defined(PARALLAX) || defined(ANISOTROPIC)\r\n",a+=" #if defined("+r.toUpperCase()+")\r\n",a+=" vec4 normalColor"+(s+0)+" = vec4(0.0, 0.0, 0.0, 1.0);\r\n",a+=" vec4 normalColor"+(s+1)+" = vec4(0.0, 0.0, 0.0, 1.0);\r\n",a+=" vec4 normalColor"+(s+2)+" = vec4(0.0, 0.0, 0.0, 1.0);\r\n",a+=" vec4 normalColor"+(s+3)+" = vec4(0.0, 0.0, 0.0, 1.0);\r\n",e["textureRect"+(s+0)]&&(a+=" float normalScale"+(s+0)+" = "+e["normalsScale"+(s+0)].toFixed(4)+";\r\n",a+=" normalColor"+(s+0)+" = sampleTextureAtlas2D("+r+", normalCorrection, vec2(detailTileSize, detailTileBits), textureRect"+(s+0)+", textureTileUV"+(s+0)+", autoMipMapLevel);\r\n",a+=" normalColor"+(s+0)+".rgb = perturbNormalSamplerColor(TBN, normalColor"+(s+0)+".rgb, normalScale"+(s+0)+");\r\n"),e["textureRect"+(s+1)]&&(a+=" float normalScale"+(s+1)+" = "+e["normalsScale"+(s+1)].toFixed(4)+";\r\n",a+=" normalColor"+(s+1)+" = sampleTextureAtlas2D("+r+", normalCorrection, vec2(detailTileSize, detailTileBits), textureRect"+(s+1)+", textureTileUV"+(s+1)+", autoMipMapLevel);\r\n",a+=" normalColor"+(s+1)+".rgb = perturbNormalSamplerColor(TBN, normalColor"+(s+1)+".rgb, normalScale"+(s+1)+");\r\n"),e["textureRect"+(s+2)]&&(a+=" float normalScale"+(s+2)+" = "+e["normalsScale"+(s+2)].toFixed(4)+";\r\n",a+=" normalColor"+(s+2)+" = sampleTextureAtlas2D("+r+", normalCorrection, vec2(detailTileSize, detailTileBits), textureRect"+(s+2)+", textureTileUV"+(s+2)+", autoMipMapLevel);\r\n",a+=" normalColor"+(s+2)+".rgb = perturbNormalSamplerColor(TBN, normalColor"+(s+2)+".rgb, normalScale"+(s+2)+");\r\n"),e["textureRect"+(s+3)]&&(a+=" float normalScale"+(s+3)+" = "+e["normalsScale"+(s+3)].toFixed(4)+";\r\n",a+=" normalColor"+(s+3)+" = sampleTextureAtlas2D("+r+", normalCorrection, vec2(detailTileSize, detailTileBits), textureRect"+(s+3)+", textureTileUV"+(s+3)+", autoMipMapLevel);\r\n",a+=" normalColor"+(s+3)+".rgb = perturbNormalSamplerColor(TBN, normalColor"+(s+3)+".rgb, normalScale"+(s+3)+");\r\n"),a+=" normalsBuffer = blendSplatmapAtlasColors(splatmapAlbedo"+l+", normalColor"+(s+0)+", normalColor"+(s+1)+", normalColor"+(s+2)+", normalColor"+(s+3)+", normalsBuffer);\r\n",a+=" #endif\r\n",a+="#endif\r\n",a+="\r\n"}}a+="// Update Color Values\r\n"+t+" = splatmapBuffer.rgb;\r\n#if defined(BUMP) || defined(PARALLAX) || defined(ANISOTROPIC)\r\n #if defined("+r.toUpperCase()+")\r\n normalW = normalsBuffer.rgb;\r\n #endif\r\n #if defined(FORCENORMALFORWARD) && defined(NORMAL)\r\n vec3 faceNormal = normalize(cross(dFdx(vPositionW), dFdy(vPositionW))) * vEyePosition.w;\r\n #if defined(TWOSIDEDLIGHTING)\r\n faceNormal = gl_FrontFacing ? faceNormal : -faceNormal;\r\n #endif\r\n normalW *= sign(dot(normalW, faceNormal));\r\n #endif\r\n #if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\r\n normalW = gl_FrontFacing ? normalW : -normalW;\r\n #endif\r\n#endif\r\n\r\n#endif\r\n\r\n#endif\r\n\r\n"}return a},n}(e.CustomShaderMaterialPlugin);e.UniversalTerrainMaterialPlugin=n,e.SceneManager.RegisterClass("TOOLKIT.UniversalTerrainMaterial",t),e.SceneManager.RegisterClass("TOOLKIT.UniversalTerrainMaterialPlugin",n)}(i||(i={})),function(e){var t=function(t){function n(n,i){var r=t.call(this,n,i)||this;return r._windTimeAccum=0,r._lastUpdateFrame=-1,r.shader=r.getShaderName(),r.plugin=new e.GrassStandardMaterialPlugin(r,r.shader),r.addFloatUniform("g_maxDistance",0),r.addFloatUniform("g_fadeStart",0),r.addFloatUniform("g_alphaCutoff",.3),r.addFloatUniform("g_windTime",0),r.addFloatUniform("g_waveSpeed",.5),r.addFloatUniform("g_waveSize",.5),r.addFloatUniform("g_windAmount",.5),r.addVector4Uniform("g_windTint",new BABYLON.Vector4(.7,.6,.5,0)),r.addFloatUniform("g_shadowIntensity",.7),r.emissiveColor=new BABYLON.Color3(.7,.7,.7),r._windTimeAccum=0,r}return r(n,t),n.prototype.awake=function(){},n.prototype.update=function(){var t;try{var n=this.getScene(),i=n.getFrameId();if(this._lastUpdateFrame===i)return;this._lastUpdateFrame=i;var r=e.SceneManager.GetDeltaSeconds(n),o=Math.min(r,1/30);(null!==(t=this.getFloatValue("g_waveSpeed"))&&void 0!==t?t:0)>0&&(this._windTimeAccum=this._windTimeAccum+o,this.setFloatValue("g_windTime",this._windTimeAccum))}catch(e){}},n.prototype.getShaderName=function(){return"GrassStandardMaterial"},n.prototype.getMaxDistance=function(){return this.getFloatValue("g_maxDistance")},n.prototype.setMaxDistance=function(e){this.setFloatValue("g_maxDistance",e)},n.prototype.getFadeStart=function(){return this.getFloatValue("g_fadeStart")},n.prototype.setFadeStart=function(e){this.setFloatValue("g_fadeStart",e)},n.prototype.getWaveSpeed=function(){return this.getFloatValue("g_waveSpeed")},n.prototype.setWaveSpeed=function(e){this.setFloatValue("g_waveSpeed",e)},n.prototype.getWaveSize=function(){return this.getFloatValue("g_waveSize")},n.prototype.setWaveSize=function(e){this.setFloatValue("g_waveSize",e)},n.prototype.getWindAmount=function(){return this.getFloatValue("g_windAmount")},n.prototype.setWindAmount=function(e){this.setFloatValue("g_windAmount",e)},n.prototype.getWindTint=function(){return this.getVector4Value("g_windTint")},n.prototype.setWindTint=function(e){this.setVector4Value("g_windTint",e)},n.prototype.getShadowIntensity=function(){return this.getFloatValue("g_shadowIntensity")},n.prototype.setShadowIntensity=function(e){var t=Math.max(0,Math.min(1,e));this.setFloatValue("g_shadowIntensity",t),this.emissiveColor=new BABYLON.Color3(t,t,t)},n}(e.StandardShaderMaterial);e.GrassStandardMaterial=t;var n=function(e){function t(t,n){return e.call(this,t,n,110,{GRASSSTANDARDMATERIAL:!1})||this}return r(t,e),t.prototype.isCompatible=function(e){return e===BABYLON.ShaderLanguage.WGSL||e===BABYLON.ShaderLanguage.GLSL},t.prototype.getCustomCode=function(e,t){if("vertex"===e){if(t===BABYLON.ShaderLanguage.WGSL)return{CUSTOM_VERTEX_DEFINITIONS:this.getWGSLVaryingDefinitions(),CUSTOM_VERTEX_MAIN_END:this.getWGSLVertexMainEnd(),CUSTOM_VERTEX_UPDATE_WORLDPOS:this.getWGSLVertexWorldPos()};if(t===BABYLON.ShaderLanguage.GLSL)return{CUSTOM_VERTEX_DEFINITIONS:this.getGLSLVertexDefinitions(),CUSTOM_VERTEX_MAIN_END:this.getGLSLVertexMainEnd(),CUSTOM_VERTEX_UPDATE_WORLDPOS:this.getGLSLVertexWorldPos()}}return"fragment"===e?t===BABYLON.ShaderLanguage.WGSL?{CUSTOM_FRAGMENT_DEFINITIONS:this.getWGSLVaryingDefinitions(),CUSTOM_FRAGMENT_BEFORE_FOG:this.getWGSLFragmentCode()}:{CUSTOM_FRAGMENT_DEFINITIONS:this.getGLSLFragmentDefinitions(),CUSTOM_FRAGMENT_BEFORE_FOG:this.getGLSLFragmentCode()}:null},t.prototype.getWGSLVertexMainEnd=function(){return""},t.prototype.getWGSLVaryingDefinitions=function(){return"\n #ifndef TOOLKIT_GRASS_VARYINGS\n #define TOOLKIT_GRASS_VARYINGS\n varying vGrassFade: f32;\n #endif\n "},t.prototype.getWGSLVertexWorldPos=function(){return"\n // Get instance world position (center of grass blade)\n let centerW = (finalWorld * vec4f(0.0, 0.0, 0.0, 1.0)).xyz;\n let up = vec3f(0.0, 1.0, 0.0);\n \n // Extract instance basis vectors and scale\n let right = normalize(finalWorld[0].xyz);\n let forward = normalize(finalWorld[2].xyz);\n let sx = length(finalWorld[0].xyz);\n let sy = length(finalWorld[1].xyz);\n let sz = length(finalWorld[2].xyz);\n \n // Compute world position of this vertex BEFORE waving\n // This is critical - Unity uses the actual vertex world position for wave phase\n let localPos = positionUpdated;\n var worldVertexPos = centerW + right * (localPos.x * sx) + up * (localPos.y * sy) + forward * (localPos.z * sz);\n \n // ============================================================\n // UNITY TerrainWaveGrass EXACT IMPLEMENTATION\n // From TerrainEngine.cginc lines 80-125\n // ============================================================\n \n // Wave amount is based on vertex height (top vertices wave more)\n // In Unity: v.color.a for mesh grass, tangent.y for billboard\n // Here we use the local Y position as the wave factor\n let waveAmount = max(localPos.y, 0.0) * uniforms.g_windAmount;\n \n // Wave constants tuned for LARGE, GENTLE rolling waves like Unity\n // Key insight: Unity's grass shows broad bands spanning large terrain sections\n // NOT tight ripples - spatial frequency must be very LOW\n let waveSize = uniforms.g_waveSize;\n \n // Spatial frequencies reduced by 10x from Unity's original values\n // This creates wavelengths of ~50-100 units instead of ~5-10 units\n // Result: 1-2 visible wave crests across terrain instead of 10-20\n let waveXSize = vec4f(0.0012, 0.002, 0.006, 0.0024) * waveSize;\n let waveZSize = vec4f(0.0006, 0.002, 0.002, 0.005) * waveSize;\n \n // Temporal speed reduced for smooth, gentle motion\n // Original Unity values divided by 10 for slower wave travel\n let waveSpeed = vec4f(0.03, 0.05, 0.04, 0.12);\n \n // Movement amplitudes - these control how far grass sways\n // Increased 5x from previous values to get visible bending like Unity\n // Unity grass shows significant physical displacement (20-30 degree lean)\n let waveXmove = vec4f(0.12, 0.2, -0.6, 0.48);\n let waveZmove = vec4f(0.06, 0.2, -0.2, 1.0);\n \n // Compute wave phases from BLADE CENTER position - this creates spatial bands\n // Using centerW ensures all vertices of the same blade have identical phase\n // The height-based waveAmount controls per-vertex displacement amount\n // Unity: waves = vertex.x * _waveXSize + vertex.z * _waveZSize + time * waveSpeed\n var waves = vec4f(\n centerW.x * waveXSize.x + centerW.z * waveZSize.x,\n centerW.x * waveXSize.y + centerW.z * waveZSize.y,\n centerW.x * waveXSize.z + centerW.z * waveZSize.z,\n centerW.x * waveXSize.w + centerW.z * waveZSize.w\n );\n \n // Add time component - this makes waves travel\n let windTime = uniforms.g_windTime * uniforms.g_waveSpeed;\n waves = waves + vec4f(\n windTime * waveSpeed.x,\n windTime * waveSpeed.y,\n windTime * waveSpeed.z,\n windTime * waveSpeed.w\n );\n \n // Keep in 0-1 range for FastSinCos\n waves = fract(waves);\n \n // ============================================================\n // FastSinCos - Unity's Taylor series approximation\n // From TerrainEngine.cginc lines 56-78\n // ============================================================\n // Convert from 0-1 to -PI to PI range\n let wavesRad = waves * 6.408849 - 3.1415927;\n \n // Powers for Taylor series\n let r5 = wavesRad * wavesRad; // x^2\n let r6 = r5 * r5; // x^4\n let r7 = r6 * r5; // x^6\n let r8 = r6 * r5; // x^8 (same as r7 in Unity code)\n let r1 = r5 * wavesRad; // x^3\n let r2 = r1 * r5; // x^5\n let r3 = r2 * r5; // x^7\n \n // Taylor series coefficients\n let sin7 = vec4f(1.0, -0.16161616, 0.0083333, -0.00019841);\n let cos8 = vec4f(-0.5, 0.041666666, -0.0013888889, 0.000024801587);\n \n // Compute sine using Taylor series: x - x^3/3! + x^5/5! - x^7/7!\n var s = wavesRad + r1 * sin7.y + r2 * sin7.z + r3 * sin7.w;\n \n // Compute cosine (not used for displacement but kept for completeness)\n // var c = vec4f(1.0) + r5 * cos8.x + r6 * cos8.y + r7 * cos8.z + r8 * cos8.w;\n \n // ============================================================\n // Unity's characteristic wave shaping: s = s * s; s = s * s;\n // This creates sharper peaks and flatter troughs (gust appearance)\n // ============================================================\n s = s * s; // s^2\n s = s * s; // s^4\n \n // Lighting variation based on wave state (for color tinting)\n let lightingWeights = normalize(vec4f(1.0, 1.0, 0.4, 0.2));\n let lighting = dot(s, lightingWeights) * 0.7;\n \n // Scale by wave amount (height-based)\n s = s * waveAmount;\n \n // Compute final displacement using dot product with movement vectors\n // Unity: waveMove.x = dot(s, _waveXmove); waveMove.z = dot(s, _waveZmove);\n var waveMove = vec3f(0.0, 0.0, 0.0);\n waveMove.x = dot(s, waveXmove);\n waveMove.z = dot(s, waveZmove);\n \n // Apply displacement scaled by wind amount\n // Unity: vertex.xz -= waveMove.xz * _WaveAndDistance.z;\n // Note: Unity subtracts, we add in the opposite direction for same effect\n let displacement = waveMove * uniforms.g_windAmount;\n \n // Apply wave color tinting (Unity's waveColor calculation)\n // This creates visual bands of lighter/darker grass\n // let waveColor = mix(vec3f(0.5), uniforms.g_windTint.xyz, vec3f(lighting));\n \n // Final world position with waving applied\n let billboardWorld = worldVertexPos - vec3f(displacement.x, 0.0, displacement.z);\n\n // Distance-based culling (Unity-style fade)\n var detailAlpha: f32 = 1.0;\n if (uniforms.g_maxDistance > 0.0) {\n let dist = length(centerW - scene.vEyePosition.xyz);\n let maxD = uniforms.g_maxDistance;\n let fadeStart = uniforms.g_fadeStart;\n if (dist > maxD) { detailAlpha = 0.0; }\n else if (dist > fadeStart) { detailAlpha = 1.0 - ((dist - fadeStart) / max((maxD - fadeStart), 0.0001)); }\n }\n vertexOutputs.vGrassFade = detailAlpha;\n \n // UPDATE worldPos to the animated position BEFORE shadow calculations\n // This is critical for correct shadow receiving - shadows should be stationary\n // while grass moves through them, not move with the grass\n worldPos = vec4f(billboardWorld, 1.0);\n \n // Output\n #if defined(POSITION) || defined(BUMP)\n vertexOutputs.vPositionW = billboardWorld;\n #endif\n #ifdef NORMAL\n vertexOutputs.vNormalW = up;\n #endif\n \n vertexOutputs.position = scene.viewProjection * vec4f(billboardWorld, 1.0);\n "},t.prototype.getGLSLVertexDefinitions=function(){return"\n #ifndef TOOLKIT_GRASS_V_UNIFORMS\n #define TOOLKIT_GRASS_V_UNIFORMS\n uniform vec4 vEyePosition;\n uniform float g_windTime;\n uniform float g_maxDistance;\n uniform float g_fadeStart;\n uniform float g_alphaCutoff;\n uniform float g_waveSpeed;\n uniform float g_waveSize;\n uniform float g_windAmount;\n uniform vec4 g_windTint;\n uniform float g_shadowIntensity;\n #endif\n\n #ifndef TOOLKIT_GRASS_VARYINGS\n #define TOOLKIT_GRASS_VARYINGS\n varying float vGrassFade;\n #endif\n "},t.prototype.getGLSLVertexMainEnd=function(){return""},t.prototype.getGLSLVertexWorldPos=function(){return"\n // Get instance world position (center of grass blade)\n vec3 centerW = (finalWorld * vec4(0.0, 0.0, 0.0, 1.0)).xyz;\n vec3 up = vec3(0.0, 1.0, 0.0);\n \n // Extract instance basis vectors and scale\n vec3 right = normalize(finalWorld[0].xyz);\n vec3 forward = normalize(finalWorld[2].xyz);\n float sx = length(finalWorld[0].xyz);\n float sy = length(finalWorld[1].xyz);\n float sz = length(finalWorld[2].xyz);\n \n // Compute world position of this vertex BEFORE waving\n vec3 localPos = positionUpdated;\n vec3 worldVertexPos = centerW + right * (localPos.x * sx) + up * (localPos.y * sy) + forward * (localPos.z * sz);\n \n // ============================================================\n // UNITY TerrainWaveGrass EXACT IMPLEMENTATION\n // ============================================================\n \n // Wave amount based on vertex height\n float waveAmount = max(localPos.y, 0.0) * g_windAmount;\n \n // Wave constants tuned for LARGE, GENTLE rolling waves like Unity\n // Key insight: Unity's grass shows broad bands spanning large terrain sections\n // NOT tight ripples - spatial frequency must be very LOW\n float waveSize = g_waveSize;\n \n // Spatial frequencies reduced by 10x from Unity's original values\n // This creates wavelengths of ~50-100 units instead of ~5-10 units\n vec4 waveXSize = vec4(0.0012, 0.002, 0.006, 0.0024) * waveSize;\n vec4 waveZSize = vec4(0.0006, 0.002, 0.002, 0.005) * waveSize;\n \n // Temporal speed reduced for smooth, gentle motion\n vec4 waveSpeedVec = vec4(0.03, 0.05, 0.04, 0.12);\n \n // Movement amplitudes - increased 5x for visible bending like Unity\n vec4 waveXmove = vec4(0.12, 0.2, -0.6, 0.48);\n vec4 waveZmove = vec4(0.06, 0.2, -0.2, 1.0);\n \n // Compute wave phases from BLADE CENTER position\n // Using centerW ensures all vertices of the same blade have identical phase\n vec4 waves = vec4(\n centerW.x * waveXSize.x + centerW.z * waveZSize.x,\n centerW.x * waveXSize.y + centerW.z * waveZSize.y,\n centerW.x * waveXSize.z + centerW.z * waveZSize.z,\n centerW.x * waveXSize.w + centerW.z * waveZSize.w\n );\n \n // Add time component\n float windTime = g_windTime * g_waveSpeed;\n waves += vec4(\n windTime * waveSpeedVec.x,\n windTime * waveSpeedVec.y,\n windTime * waveSpeedVec.z,\n windTime * waveSpeedVec.w\n );\n \n // Keep in 0-1 range\n waves = fract(waves);\n \n // ============================================================\n // FastSinCos - Unity's Taylor series approximation\n // ============================================================\n vec4 wavesRad = waves * 6.408849 - 3.1415927;\n \n // Powers for Taylor series\n vec4 r5 = wavesRad * wavesRad;\n vec4 r6 = r5 * r5;\n vec4 r7 = r6 * r5;\n vec4 r1 = r5 * wavesRad;\n vec4 r2 = r1 * r5;\n vec4 r3 = r2 * r5;\n \n // Taylor series coefficients\n vec4 sin7 = vec4(1.0, -0.16161616, 0.0083333, -0.00019841);\n \n // Compute sine\n vec4 s = wavesRad + r1 * sin7.y + r2 * sin7.z + r3 * sin7.w;\n \n // ============================================================\n // Unity's wave shaping: s = s * s; s = s * s; (s^4)\n // ============================================================\n s = s * s;\n s = s * s;\n \n // Lighting for color tinting\n float lighting = dot(s, normalize(vec4(1.0, 1.0, 0.4, 0.2))) * 0.7;\n \n // Scale by wave amount\n s = s * waveAmount;\n \n // Compute displacement\n vec3 waveMove = vec3(0.0);\n waveMove.x = dot(s, waveXmove);\n waveMove.z = dot(s, waveZmove);\n \n // Apply displacement\n vec3 displacement = waveMove * g_windAmount;\n \n // Final world position\n vec3 billboardWorld = worldVertexPos - vec3(displacement.x, 0.0, displacement.z);\n \n // Distance-based culling\n float detailAlpha = 1.0;\n if (g_maxDistance > 0.0) {\n float dist = distance(vEyePosition.xyz, centerW);\n float maxD = g_maxDistance;\n float fadeStart = g_fadeStart;\n if (dist > maxD) { detailAlpha = 0.0; }\n else if (dist > fadeStart) { detailAlpha = 1.0 - ((dist - fadeStart) / max((maxD - fadeStart), 0.0001)); }\n }\n vGrassFade = detailAlpha;\n \n // UPDATE worldPos to the animated position BEFORE shadow calculations\n // This is critical for correct shadow receiving - shadows should be stationary\n // while grass moves through them, not move with the grass\n worldPos = vec4(billboardWorld, 1.0);\n \n #if defined(POSITION) || defined(BUMP)\n vPositionW = billboardWorld;\n #endif\n #ifdef NORMAL\n vNormalW = up;\n #endif\n \n gl_Position = viewProjection * vec4(billboardWorld, 1.0);\n "},t.prototype.getWGSLFragmentCode=function(){return"\n let detailAlpha = fragmentInputs.vGrassFade;\n let combinedAlpha = alpha * detailAlpha;\n if (combinedAlpha <= uniforms.g_alphaCutoff) { discard; }\n alpha = combinedAlpha;\n \n // Apply shadow intensity - adds ambient light to dark/shadowed areas\n // shadowIntensity controls how much ambient light to add: 0.0 = no ambient, 1.0 = full texture color\n // Simple approach: check if pixel is very dark (likely in shadow) and add ambient\n let shadowIntensity = uniforms.g_shadowIntensity;\n let brightness = max(color.r, max(color.g, color.b));\n // If brightness is below threshold, we're likely in shadow - add ambient light\n // The darker the pixel, the more ambient we add (inverse relationship)\n let shadowThreshold = 0.2;\n let shadowAmount = clamp((shadowThreshold - brightness) / shadowThreshold, 0.0, 1.0);\n // Add ambient light using the grass texture color\n color = vec4f(color.rgb + baseColor.rgb * shadowIntensity * shadowAmount, color.a);\n "},t.prototype.getGLSLFragmentCode=function(){return"\n float detailAlpha = vGrassFade;\n float combinedAlpha = alpha * detailAlpha;\n if (combinedAlpha <= g_alphaCutoff) discard;\n alpha = combinedAlpha;\n \n // Apply shadow intensity - adds ambient light to dark/shadowed areas\n // shadowIntensity controls how much ambient light to add: 0.0 = no ambient, 1.0 = full texture color\n // Simple approach: check if pixel is very dark (likely in shadow) and add ambient\n float shadowIntensity = g_shadowIntensity;\n float brightness = max(color.r, max(color.g, color.b));\n // If brightness is below threshold, we're likely in shadow - add ambient light\n // The darker the pixel, the more ambient we add (inverse relationship)\n float shadowThreshold = 0.2;\n float shadowAmount = clamp((shadowThreshold - brightness) / shadowThreshold, 0.0, 1.0);\n // Add ambient light using the grass texture color\n color.rgb += baseColor.rgb * shadowIntensity * shadowAmount;\n "},t.prototype.getGLSLFragmentDefinitions=function(){return"\n #ifndef TOOLKIT_GRASS_VARYINGS\n #define TOOLKIT_GRASS_VARYINGS\n varying float vGrassFade;\n #endif\n "},t.prototype.getUniforms=function(e){var t=e===BABYLON.ShaderLanguage.WGSL;return this.vertexDefinitions=this.getCustomShaderMaterial().getCustomVertexCode(t),this.fragmentDefinitions=!0===t?this.getCustomShaderMaterial().getCustomFragmentCode(t):null,this.getCustomShaderMaterial().getCustomUniforms(t)},t.prototype.getSamplers=function(e){var t=this.getCustomShaderMaterial().getCustomSamplers();null!=t&&t.length>0&&e.push.apply(e,t)},t.prototype.getAttributes=function(e,t,n){var i=this.getCustomShaderMaterial().getCustomAttributes();null!=i&&i.length>0&&e.push.apply(e,i)},t.prototype.prepareDefines=function(e,t,n){this.getIsEnabled()&&this.getCustomShaderMaterial().prepareCustomDefines(e)},t.prototype.bindForSubMesh=function(e,t,n,i){this.getIsEnabled()&&this.getCustomShaderMaterial().updateCustomBindings(e)},t}(e.StandardShaderMaterialPlugin);e.GrassStandardMaterialPlugin=n,e.SceneManager.RegisterClass("TOOLKIT.GrassStandardMaterial",t),e.SceneManager.RegisterClass("TOOLKIT.GrassStandardMaterialPlugin",n)}(i||(i={})),function(e){var t=function(t){function n(n,i){var r=t.call(this,n,i)||this;return r._windTimeAccum=0,r._lastUpdateFrame=-1,r.shader=r.getShaderName(),r.plugin=new e.GrassBillboardMaterialPlugin(r,r.shader),r.addFloatUniform("g_maxDistance",0),r.addFloatUniform("g_fadeStart",0),r.addFloatUniform("g_alphaCutoff",.3),r.addFloatUniform("g_windTime",0),r.addFloatUniform("g_waveSpeed",.5),r.addFloatUniform("g_waveSize",.5),r.addFloatUniform("g_windAmount",.5),r.addVector4Uniform("g_windTint",new BABYLON.Vector4(.7,.6,.5,0)),r.addFloatUniform("g_shadowIntensity",.7),r.addFloatUniform("g_sphericalBillboardEnabled",1),r.emissiveColor=new BABYLON.Color3(.7,.7,.7),r._windTimeAccum=0,r}return r(n,t),n.prototype.awake=function(){},n.prototype.update=function(){var t;try{var n=this.getScene(),i=n.getFrameId();if(this._lastUpdateFrame===i)return;this._lastUpdateFrame=i;var r=e.SceneManager.GetDeltaSeconds(n),o=Math.min(r,1/30);(null!==(t=this.getFloatValue("g_waveSpeed"))&&void 0!==t?t:0)>0&&(this._windTimeAccum=this._windTimeAccum+o,this.setFloatValue("g_windTime",this._windTimeAccum))}catch(e){}},n.prototype.getShaderName=function(){return"GrassBillboardMaterial"},n.prototype.getMaxDistance=function(){return this.getFloatValue("g_maxDistance")},n.prototype.setMaxDistance=function(e){this.setFloatValue("g_maxDistance",e)},n.prototype.getFadeStart=function(){return this.getFloatValue("g_fadeStart")},n.prototype.setFadeStart=function(e){this.setFloatValue("g_fadeStart",e)},n.prototype.getWaveSpeed=function(){return this.getFloatValue("g_waveSpeed")},n.prototype.setWaveSpeed=function(e){this.setFloatValue("g_waveSpeed",e)},n.prototype.getWaveSize=function(){return this.getFloatValue("g_waveSize")},n.prototype.setWaveSize=function(e){this.setFloatValue("g_waveSize",e)},n.prototype.getWindAmount=function(){return this.getFloatValue("g_windAmount")},n.prototype.setWindAmount=function(e){this.setFloatValue("g_windAmount",e)},n.prototype.getWindTint=function(){return this.getVector4Value("g_windTint")},n.prototype.setWindTint=function(e){this.setVector4Value("g_windTint",e)},n.prototype.getShadowIntensity=function(){return this.getFloatValue("g_shadowIntensity")},n.prototype.setShadowIntensity=function(e){var t=Math.max(0,Math.min(1,e));this.setFloatValue("g_shadowIntensity",t),this.emissiveColor=new BABYLON.Color3(t,t,t)},n.prototype.getSphericalBillboardEnabled=function(){var e;return(null!==(e=this.getFloatValue("g_sphericalBillboardEnabled"))&&void 0!==e?e:0)>.5},n.prototype.setSphericalBillboardEnabled=function(e){this.setFloatValue("g_sphericalBillboardEnabled",e?1:0)},n}(e.StandardShaderMaterial);e.GrassBillboardMaterial=t;var n=function(e){function t(t,n){return e.call(this,t,n,110,{GRASSBILLBOARDMATERIAL:!1})||this}return r(t,e),t.prototype.isCompatible=function(e){return e===BABYLON.ShaderLanguage.WGSL||e===BABYLON.ShaderLanguage.GLSL},t.prototype.getCustomCode=function(e,t){if("vertex"===e){if(t===BABYLON.ShaderLanguage.WGSL)return{CUSTOM_VERTEX_DEFINITIONS:this.getWGSLVaryingDefinitions(),CUSTOM_VERTEX_MAIN_END:this.getWGSLVertexMainEnd(),CUSTOM_VERTEX_UPDATE_WORLDPOS:this.getWGSLVertexWorldPos()};if(t===BABYLON.ShaderLanguage.GLSL)return{CUSTOM_VERTEX_DEFINITIONS:this.getGLSLVertexDefinitions(),CUSTOM_VERTEX_MAIN_END:this.getGLSLVertexMainEnd(),CUSTOM_VERTEX_UPDATE_WORLDPOS:this.getGLSLVertexWorldPos()}}return"fragment"===e?t===BABYLON.ShaderLanguage.WGSL?{CUSTOM_FRAGMENT_DEFINITIONS:this.getWGSLVaryingDefinitions(),CUSTOM_FRAGMENT_BEFORE_FOG:this.getWGSLFragmentCode()}:{CUSTOM_FRAGMENT_DEFINITIONS:this.getGLSLFragmentDefinitions(),CUSTOM_FRAGMENT_BEFORE_FOG:this.getGLSLFragmentCode()}:null},t.prototype.getWGSLVertexMainEnd=function(){return""},t.prototype.getWGSLVaryingDefinitions=function(){return"\n #ifndef TOOLKIT_GRASS_VARYINGS\n #define TOOLKIT_GRASS_VARYINGS\n varying vGrassFade: f32;\n #endif\n "},t.prototype.getWGSLVertexWorldPos=function(){return"\n // Get instance world position (center of grass blade)\n let centerW = (finalWorld * vec4f(0.0, 0.0, 0.0, 1.0)).xyz;\n let up = vec3f(0.0, 1.0, 0.0);\n \n // Extract instance scale (keep scale, but override rotation with Y-locked billboard basis)\n let sx = length(finalWorld[0].xyz);\n let sy = length(finalWorld[1].xyz);\n let sz = length(finalWorld[2].xyz);\n\n // Compute billboard basis (Y-locked or spherical)\n // Face the camera on XZ plane without tilting unless spherical is enabled\n let eyeW = scene.vEyePosition.xyz;\n var faceDir = centerW - eyeW;\n if (uniforms.g_sphericalBillboardEnabled < 0.5) {\n faceDir.y = 0.0;\n }\n let faceLen = length(faceDir);\n if (faceLen < 0.0001) {\n faceDir = vec3f(0.0, 0.0, 1.0);\n } else {\n faceDir = faceDir / faceLen;\n }\n\n // Safe up reference to avoid degeneracy when looking straight down\n var upRef = up;\n if (abs(faceDir.y) > 0.99) {\n upRef = vec3f(0.0, 0.0, 1.0);\n }\n\n let right = normalize(cross(upRef, faceDir));\n let forward = normalize(cross(faceDir, right));\n\n // Compute world position of this vertex BEFORE waving\n // This is critical - Unity uses the actual vertex world position for wave phase\n let localPos = positionUpdated;\n var worldVertexPos = centerW + right * (localPos.x * sx) + up * (localPos.y * sy) + forward * (localPos.z * sz);\n \n // ============================================================\n // UNITY TerrainWaveGrass EXACT IMPLEMENTATION\n // From TerrainEngine.cginc lines 80-125\n // ============================================================\n \n // Wave amount is based on vertex height (top vertices wave more)\n // In Unity: v.color.a for mesh grass, tangent.y for billboard\n // Here we use the local Y position as the wave factor\n let waveAmount = max(localPos.y, 0.0) * uniforms.g_windAmount;\n \n // Wave constants tuned for LARGE, GENTLE rolling waves like Unity\n // Key insight: Unity's grass shows broad bands spanning large terrain sections\n // NOT tight ripples - spatial frequency must be very LOW\n let waveSize = uniforms.g_waveSize;\n \n // Spatial frequencies reduced by 10x from Unity's original values\n // This creates wavelengths of ~50-100 units instead of ~5-10 units\n // Result: 1-2 visible wave crests across terrain instead of 10-20\n let waveXSize = vec4f(0.0012, 0.002, 0.006, 0.0024) * waveSize;\n let waveZSize = vec4f(0.0006, 0.002, 0.002, 0.005) * waveSize;\n \n // Temporal speed reduced for smooth, gentle motion\n // Original Unity values divided by 10 for slower wave travel\n let waveSpeed = vec4f(0.03, 0.05, 0.04, 0.12);\n \n // Movement amplitudes - these control how far grass sways\n // Increased 5x from previous values to get visible bending like Unity\n // Unity grass shows significant physical displacement (20-30 degree lean)\n let waveXmove = vec4f(0.12, 0.2, -0.6, 0.48);\n let waveZmove = vec4f(0.06, 0.2, -0.2, 1.0);\n \n // Compute wave phases from BLADE CENTER position - this creates spatial bands\n // Using centerW ensures all vertices of the same blade have identical phase\n // The height-based waveAmount controls per-vertex displacement amount\n // Unity: waves = vertex.x * _waveXSize + vertex.z * _waveZSize + time * waveSpeed\n var waves = vec4f(\n centerW.x * waveXSize.x + centerW.z * waveZSize.x,\n centerW.x * waveXSize.y + centerW.z * waveZSize.y,\n centerW.x * waveXSize.z + centerW.z * waveZSize.z,\n centerW.x * waveXSize.w + centerW.z * waveZSize.w\n );\n \n // Add time component - this makes waves travel\n let windTime = uniforms.g_windTime * uniforms.g_waveSpeed;\n waves = waves + vec4f(\n windTime * waveSpeed.x,\n windTime * waveSpeed.y,\n windTime * waveSpeed.z,\n windTime * waveSpeed.w\n );\n \n // Keep in 0-1 range for FastSinCos\n waves = fract(waves);\n \n // ============================================================\n // FastSinCos - Unity's Taylor series approximation\n // From TerrainEngine.cginc lines 56-78\n // ============================================================\n // Convert from 0-1 to -PI to PI range\n let wavesRad = waves * 6.408849 - 3.1415927;\n \n // Powers for Taylor series\n let r5 = wavesRad * wavesRad; // x^2\n let r6 = r5 * r5; // x^4\n let r7 = r6 * r5; // x^6\n let r8 = r6 * r5; // x^8 (same as r7 in Unity code)\n let r1 = r5 * wavesRad; // x^3\n let r2 = r1 * r5; // x^5\n let r3 = r2 * r5; // x^7\n \n // Taylor series coefficients\n let sin7 = vec4f(1.0, -0.16161616, 0.0083333, -0.00019841);\n let cos8 = vec4f(-0.5, 0.041666666, -0.0013888889, 0.000024801587);\n \n // Compute sine using Taylor series: x - x^3/3! + x^5/5! - x^7/7!\n var s = wavesRad + r1 * sin7.y + r2 * sin7.z + r3 * sin7.w;\n \n // Compute cosine (not used for displacement but kept for completeness)\n // var c = vec4f(1.0) + r5 * cos8.x + r6 * cos8.y + r7 * cos8.z + r8 * cos8.w;\n \n // ============================================================\n // Unity's characteristic wave shaping: s = s * s; s = s * s;\n // This creates sharper peaks and flatter troughs (gust appearance)\n // ============================================================\n s = s * s; // s^2\n s = s * s; // s^4\n \n // Lighting variation based on wave state (for color tinting)\n let lightingWeights = normalize(vec4f(1.0, 1.0, 0.4, 0.2));\n let lighting = dot(s, lightingWeights) * 0.7;\n \n // Scale by wave amount (height-based)\n s = s * waveAmount;\n \n // Compute final displacement using dot product with movement vectors\n // Unity: waveMove.x = dot(s, _waveXmove); waveMove.z = dot(s, _waveZmove);\n var waveMove = vec3f(0.0, 0.0, 0.0);\n waveMove.x = dot(s, waveXmove);\n waveMove.z = dot(s, waveZmove);\n \n // Apply displacement scaled by wind amount\n // Unity: vertex.xz -= waveMove.xz * _WaveAndDistance.z;\n // Note: Unity subtracts, we add in the opposite direction for same effect\n let displacement = waveMove * uniforms.g_windAmount;\n \n // Apply wave color tinting (Unity's waveColor calculation)\n // This creates visual bands of lighter/darker grass\n // let waveColor = mix(vec3f(0.5), uniforms.g_windTint.xyz, vec3f(lighting));\n \n // Final world position with waving applied\n let billboardWorld = worldVertexPos - vec3f(displacement.x, 0.0, displacement.z);\n\n // Distance-based culling (Unity-style fade)\n var detailAlpha: f32 = 1.0;\n if (uniforms.g_maxDistance > 0.0) {\n let dist = length(centerW - scene.vEyePosition.xyz);\n let maxD = uniforms.g_maxDistance;\n let fadeStart = uniforms.g_fadeStart;\n if (dist > maxD) { detailAlpha = 0.0; }\n else if (dist > fadeStart) { detailAlpha = 1.0 - ((dist - fadeStart) / max((maxD - fadeStart), 0.0001)); }\n }\n vertexOutputs.vGrassFade = detailAlpha;\n \n // UPDATE worldPos to the animated position BEFORE shadow calculations\n // This is critical for correct shadow receiving - shadows should be stationary\n // while grass moves through them, not move with the grass\n worldPos = vec4f(billboardWorld, 1.0);\n \n // Output\n #if defined(POSITION) || defined(BUMP)\n vertexOutputs.vPositionW = billboardWorld;\n #endif\n #ifdef NORMAL\n vertexOutputs.vNormalW = up;\n #endif\n \n vertexOutputs.position = scene.viewProjection * vec4f(billboardWorld, 1.0);\n "},t.prototype.getGLSLVertexDefinitions=function(){return"\n #ifndef TOOLKIT_GRASS_V_UNIFORMS\n #define TOOLKIT_GRASS_V_UNIFORMS\n uniform vec4 vEyePosition;\n uniform float g_windTime;\n uniform float g_maxDistance;\n uniform float g_fadeStart;\n uniform float g_alphaCutoff;\n uniform float g_waveSpeed;\n uniform float g_waveSize;\n uniform float g_windAmount;\n uniform vec4 g_windTint;\n uniform float g_shadowIntensity;\n uniform float g_sphericalBillboardEnabled;\n #endif\n\n #ifndef TOOLKIT_GRASS_VARYINGS\n #define TOOLKIT_GRASS_VARYINGS\n varying float vGrassFade;\n #endif\n "},t.prototype.getGLSLVertexMainEnd=function(){return""},t.prototype.getGLSLVertexWorldPos=function(){return"\n // Get instance world position (center of grass blade)\n vec3 centerW = (finalWorld * vec4(0.0, 0.0, 0.0, 1.0)).xyz;\n vec3 up = vec3(0.0, 1.0, 0.0);\n \n // Extract instance scale (keep scale, but override rotation with Y-locked billboard basis)\n float sx = length(finalWorld[0].xyz);\n float sy = length(finalWorld[1].xyz);\n float sz = length(finalWorld[2].xyz);\n\n // Compute billboard basis (Y-locked or spherical)\n // Face the camera on XZ plane without tilting unless spherical is enabled\n vec3 eyeW = vEyePosition.xyz;\n vec3 faceDir = centerW - eyeW;\n if (g_sphericalBillboardEnabled < 0.5) {\n faceDir.y = 0.0;\n }\n float faceLen = length(faceDir);\n if (faceLen < 0.0001) {\n faceDir = vec3(0.0, 0.0, 1.0);\n } else {\n faceDir = faceDir / faceLen;\n }\n\n // Safe up reference to avoid degeneracy when looking straight down\n vec3 upRef = up;\n if (abs(faceDir.y) > 0.99) {\n upRef = vec3(0.0, 0.0, 1.0);\n }\n\n vec3 right = normalize(cross(upRef, faceDir));\n vec3 forward = normalize(cross(faceDir, right));\n\n // Compute world position of this vertex BEFORE waving\n vec3 localPos = positionUpdated;\n vec3 worldVertexPos = centerW + right * (localPos.x * sx) + up * (localPos.y * sy) + forward * (localPos.z * sz);\n \n // ============================================================\n // UNITY TerrainWaveGrass EXACT IMPLEMENTATION\n // ============================================================\n \n // Wave amount based on vertex height\n float waveAmount = max(localPos.y, 0.0) * g_windAmount;\n \n // Wave constants tuned for LARGE, GENTLE rolling waves like Unity\n // Key insight: Unity's grass shows broad bands spanning large terrain sections\n // NOT tight ripples - spatial frequency must be very LOW\n float waveSize = g_waveSize;\n \n // Spatial frequencies reduced by 10x from Unity's original values\n // This creates wavelengths of ~50-100 units instead of ~5-10 units\n vec4 waveXSize = vec4(0.0012, 0.002, 0.006, 0.0024) * waveSize;\n vec4 waveZSize = vec4(0.0006, 0.002, 0.002, 0.005) * waveSize;\n \n // Temporal speed reduced for smooth, gentle motion\n vec4 waveSpeedVec = vec4(0.03, 0.05, 0.04, 0.12);\n \n // Movement amplitudes - increased 5x for visible bending like Unity\n vec4 waveXmove = vec4(0.12, 0.2, -0.6, 0.48);\n vec4 waveZmove = vec4(0.06, 0.2, -0.2, 1.0);\n \n // Compute wave phases from BLADE CENTER position\n // Using centerW ensures all vertices of the same blade have identical phase\n vec4 waves = vec4(\n centerW.x * waveXSize.x + centerW.z * waveZSize.x,\n centerW.x * waveXSize.y + centerW.z * waveZSize.y,\n centerW.x * waveXSize.z + centerW.z * waveZSize.z,\n centerW.x * waveXSize.w + centerW.z * waveZSize.w\n );\n \n // Add time component\n float windTime = g_windTime * g_waveSpeed;\n waves += vec4(\n windTime * waveSpeedVec.x,\n windTime * waveSpeedVec.y,\n windTime * waveSpeedVec.z,\n windTime * waveSpeedVec.w\n );\n \n // Keep in 0-1 range\n waves = fract(waves);\n \n // ============================================================\n // FastSinCos - Unity's Taylor series approximation\n // ============================================================\n vec4 wavesRad = waves * 6.408849 - 3.1415927;\n \n // Powers for Taylor series\n vec4 r5 = wavesRad * wavesRad;\n vec4 r6 = r5 * r5;\n vec4 r7 = r6 * r5;\n vec4 r1 = r5 * wavesRad;\n vec4 r2 = r1 * r5;\n vec4 r3 = r2 * r5;\n \n // Taylor series coefficients\n vec4 sin7 = vec4(1.0, -0.16161616, 0.0083333, -0.00019841);\n \n // Compute sine\n vec4 s = wavesRad + r1 * sin7.y + r2 * sin7.z + r3 * sin7.w;\n \n // ============================================================\n // Unity's wave shaping: s = s * s; s = s * s; (s^4)\n // ============================================================\n s = s * s;\n s = s * s;\n \n // Lighting for color tinting\n float lighting = dot(s, normalize(vec4(1.0, 1.0, 0.4, 0.2))) * 0.7;\n \n // Scale by wave amount\n s = s * waveAmount;\n \n // Compute displacement\n vec3 waveMove = vec3(0.0);\n waveMove.x = dot(s, waveXmove);\n waveMove.z = dot(s, waveZmove);\n \n // Apply displacement\n vec3 displacement = waveMove * g_windAmount;\n \n // Final world position\n vec3 billboardWorld = worldVertexPos - vec3(displacement.x, 0.0, displacement.z);\n \n // Distance-based culling\n float detailAlpha = 1.0;\n if (g_maxDistance > 0.0) {\n float dist = distance(vEyePosition.xyz, centerW);\n float maxD = g_maxDistance;\n float fadeStart = g_fadeStart;\n if (dist > maxD) { detailAlpha = 0.0; }\n else if (dist > fadeStart) { detailAlpha = 1.0 - ((dist - fadeStart) / max((maxD - fadeStart), 0.0001)); }\n }\n vGrassFade = detailAlpha;\n \n // UPDATE worldPos to the animated position BEFORE shadow calculations\n // This is critical for correct shadow receiving - shadows should be stationary\n // while grass moves through them, not move with the grass\n worldPos = vec4(billboardWorld, 1.0);\n \n #if defined(POSITION) || defined(BUMP)\n vPositionW = billboardWorld;\n #endif\n #ifdef NORMAL\n vNormalW = up;\n #endif\n \n gl_Position = viewProjection * vec4(billboardWorld, 1.0);\n "},t.prototype.getWGSLFragmentCode=function(){return"\n let detailAlpha = fragmentInputs.vGrassFade;\n let combinedAlpha = alpha * detailAlpha;\n if (combinedAlpha <= uniforms.g_alphaCutoff) { discard; }\n alpha = combinedAlpha;\n \n // Apply shadow intensity - adds ambient light to dark/shadowed areas\n // shadowIntensity controls how much ambient light to add: 0.0 = no ambient, 1.0 = full texture color\n // Simple approach: check if pixel is very dark (likely in shadow) and add ambient\n let shadowIntensity = uniforms.g_shadowIntensity;\n let brightness = max(color.r, max(color.g, color.b));\n // If brightness is below threshold, we're likely in shadow - add ambient light\n // The darker the pixel, the more ambient we add (inverse relationship)\n let shadowThreshold = 0.2;\n let shadowAmount = clamp((shadowThreshold - brightness) / shadowThreshold, 0.0, 1.0);\n // Add ambient light using the grass texture color\n color = vec4f(color.rgb + baseColor.rgb * shadowIntensity * shadowAmount, color.a);\n "},t.prototype.getGLSLFragmentCode=function(){return"\n float detailAlpha = vGrassFade;\n float combinedAlpha = alpha * detailAlpha;\n if (combinedAlpha <= g_alphaCutoff) discard;\n alpha = combinedAlpha;\n \n // Apply shadow intensity - adds ambient light to dark/shadowed areas\n // shadowIntensity controls how much ambient light to add: 0.0 = no ambient, 1.0 = full texture color\n // Simple approach: check if pixel is very dark (likely in shadow) and add ambient\n float shadowIntensity = g_shadowIntensity;\n float brightness = max(color.r, max(color.g, color.b));\n // If brightness is below threshold, we're likely in shadow - add ambient light\n // The darker the pixel, the more ambient we add (inverse relationship)\n float shadowThreshold = 0.2;\n float shadowAmount = clamp((shadowThreshold - brightness) / shadowThreshold, 0.0, 1.0);\n // Add ambient light using the grass texture color\n color.rgb += baseColor.rgb * shadowIntensity * shadowAmount;\n "},t.prototype.getGLSLFragmentDefinitions=function(){return"\n #ifndef TOOLKIT_GRASS_VARYINGS\n #define TOOLKIT_GRASS_VARYINGS\n varying float vGrassFade;\n #endif\n "},t.prototype.getUniforms=function(e){var t=e===BABYLON.ShaderLanguage.WGSL;return this.vertexDefinitions=this.getCustomShaderMaterial().getCustomVertexCode(t),this.fragmentDefinitions=!0===t?this.getCustomShaderMaterial().getCustomFragmentCode(t):null,this.getCustomShaderMaterial().getCustomUniforms(t)},t.prototype.getSamplers=function(e){var t=this.getCustomShaderMaterial().getCustomSamplers();null!=t&&t.length>0&&e.push.apply(e,t)},t.prototype.getAttributes=function(e,t,n){var i=this.getCustomShaderMaterial().getCustomAttributes();null!=i&&i.length>0&&e.push.apply(e,i)},t.prototype.prepareDefines=function(e,t,n){this.getIsEnabled()&&this.getCustomShaderMaterial().prepareCustomDefines(e)},t.prototype.bindForSubMesh=function(e,t,n,i){this.getIsEnabled()&&this.getCustomShaderMaterial().updateCustomBindings(e)},t}(e.StandardShaderMaterialPlugin);e.GrassBillboardMaterialPlugin=n,e.SceneManager.RegisterClass("TOOLKIT.GrassStandardMaterial",e.GrassStandardMaterial),e.SceneManager.RegisterClass("TOOLKIT.GrassStandardMaterialPlugin",e.GrassStandardMaterialPlugin)}(i||(i={})),function(e){var t=function(t){function n(n,i){var r=t.call(this,n,i)||this;return r._windTimeAccum=0,r.shader=r.getShaderName(),r.plugin=new e.TreeBranchMaterialPlugin(r,r.shader),r.addFloatUniform("g_windTime",0),r.addFloatUniform("g_windAmount",.5),r.addFloatUniform("g_windSpeed",1),r.addFloatUniform("g_windStrength",.5),r.addVector4Uniform("g_windDirection",new BABYLON.Vector4(1,0,0,0)),r.addFloatUniform("g_branchRootY",0),r.addFloatUniform("g_branchMaxAngle",.35),r.addFloatUniform("g_branchMaxHeight",2),r.addFloatUniform("g_useVertexColorMask",1),r.addFloatUniform("g_spatialFrequency",.15),r._windTimeAccum=0,r}return r(n,t),n.prototype.awake=function(){},n.prototype.update=function(){var t;try{var n=e.SceneManager.GetDeltaSeconds(this.getScene()),i=Math.min(n,1/30);(null!==(t=this.getFloatValue("g_windSpeed"))&&void 0!==t?t:0)>0&&(this._windTimeAccum+=i,this.setFloatValue("g_windTime",this._windTimeAccum))}catch(e){}},n.prototype.getShaderName=function(){return"TreeBranchMaterial"},n.prototype.setWindDirection=function(e,t,n){var i=new BABYLON.Vector3(e,t,n);i.lengthSquared()<1e-8?this.setVector4Value("g_windDirection",new BABYLON.Vector4(1,0,0,0)):(i.normalize(),this.setVector4Value("g_windDirection",new BABYLON.Vector4(i.x,i.y,i.z,0)))},n.prototype.getWindDirection=function(){return this.getVector4Value("g_windDirection")},n}(e.CustomShaderMaterial);e.TreeBranchMaterial=t;var n=function(e){function t(t,n){return e.call(this,t,n,110,{TREEBRANCHMATERIAL:!1})||this}return r(t,e),t.prototype.isCompatible=function(e){return e===BABYLON.ShaderLanguage.WGSL||e===BABYLON.ShaderLanguage.GLSL},t.prototype.getCustomCode=function(e,t){return"vertex"===e?t===BABYLON.ShaderLanguage.WGSL?{CUSTOM_VERTEX_MAIN_END:"\n // -------------------------\n // TreeBranch wind bending (local-space)\n // Authoring (recommended):\n // vertexColor.r = bend weight (0 trunk .. 1 tips)\n // vertexColor.g = phase offset noise (0..1)\n // Falls back to height-based weight if vertex color missing/disabled.\n // -------------------------\n\n fn safeNormalize(v: vec3f) -> vec3f {\n let lsq = dot(v, v);\n if (lsq < 1e-8) { return vec3f(1.0, 0.0, 0.0); }\n return v * inverseSqrt(lsq);\n }\n\n fn rotateRodrigues(p: vec3f, axis: vec3f, angle: f32) -> vec3f {\n let a = safeNormalize(axis);\n let c = cos(angle);\n let s = sin(angle);\n return p * c + cross(a, p) * s + a * dot(a, p) * (1.0 - c);\n }\n\n // Local position & normal (preferred: use normalUpdated if present in shader)\n var pL: vec3f = positionUpdated;\n\n // If COLOR attribute exists, Babylon usually provides vertexInputs.color.\n // If not available, these will be 1,1,1,1 (depending on pipeline) — we guard with g_useVertexColorMask.\n var bendMask: f32 = 1.0;\n var phaseNoise: f32 = 0.0;\n if (uniforms.g_useVertexColorMask > 0.5) {\n bendMask = clamp(vertexInputs.color.r, 0.0, 1.0);\n phaseNoise = vertexInputs.color.g; // 0..1\n }\n\n // Height-based fallback weight (normalized between rootY..maxHeight)\n let denom = max(uniforms.g_branchMaxHeight - uniforms.g_branchRootY, 1e-3);\n let h01 = clamp((pL.y - uniforms.g_branchRootY) / denom, 0.0, 1.0);\n\n // Final per-vertex weight:\n // - If using vertex colors: bendMask * smooth tip emphasis\n // - Else: height-based\n var w: f32 = h01;\n if (uniforms.g_useVertexColorMask > 0.5) {\n w = bendMask * (h01 * h01 * (3.0 - 2.0 * h01)); // smoothstep(h01)\n } else {\n w = h01 * h01; // a bit stiffer near base\n }\n\n // Wind direction in LOCAL space:\n // We transform windDirWorld by inverse world matrix rotation (approx using finalWorld columns).\n // finalWorld transforms local->world. For direction, inverse rotation is transpose of 3x3 if no shear.\n let windW = safeNormalize(uniforms.g_windDirection.xyz);\n let rightW = safeNormalize(finalWorld[0].xyz);\n let upW = safeNormalize(finalWorld[1].xyz);\n let fwdW = safeNormalize(finalWorld[2].xyz);\n\n // Convert world dir to local by dot with basis\n let windL = safeNormalize(vec3f(dot(windW, rightW), dot(windW, upW), dot(windW, fwdW)));\n\n // Bend axis: perpendicular to up and wind, in LOCAL space\n var axisL = safeNormalize(cross(vec3f(0.0, 1.0, 0.0), windL));\n if (dot(axisL, axisL) < 1e-6) { axisL = vec3f(1.0, 0.0, 0.0); }\n\n // Spatially varying phase so whole tree doesn't move as a rigid sheet\n // Use local xz for coherence; optionally mod by vertexColor.g\n let spatial = (pL.x + pL.z) * uniforms.g_spatialFrequency;\n let phase = uniforms.g_windTime * uniforms.g_windSpeed\n + spatial * uniforms.g_windStrength\n + phaseNoise * 6.28318;\n\n // Two-wave composite like Unity-ish wind\n let base = sin(phase);\n let gust = 0.5 * sin(phase * 1.7 + 1.2);\n let sway = (base + gust) * uniforms.g_windAmount;\n\n // Convert sway to angle (clamped)\n var angle = sway * w * uniforms.g_branchMaxAngle;\n angle = clamp(angle, -uniforms.g_branchMaxAngle, uniforms.g_branchMaxAngle);\n\n // Pivot in local space\n let pivotL = vec3f(0.0, uniforms.g_branchRootY, 0.0);\n let relL = pL - pivotL;\n let bentRelL = rotateRodrigues(relL, axisL, angle);\n let bentPL = pivotL + bentRelL;\n\n // Transform to world using finalWorld (keeps proper anchoring)\n let branchWorld = (finalWorld * vec4f(bentPL, 1.0)).xyz;\n\n // Rotate normal similarly (only if NORMAL is active)\n #ifdef NORMAL\n // Babylon WGSL PBR usually provides normalUpdated in local/object space\n var nL: vec3f = normalize(normalUpdated);\n let bentNL = rotateRodrigues(nL, axisL, angle);\n // Convert to world by world 3x3\n let nW = normalize(vec3f(\n dot(bentNL, vec3f(finalWorld[0].x, finalWorld[0].y, finalWorld[0].z)),\n dot(bentNL, vec3f(finalWorld[1].x, finalWorld[1].y, finalWorld[1].z)),\n dot(bentNL, vec3f(finalWorld[2].x, finalWorld[2].y, finalWorld[2].z))\n ));\n vertexOutputs.vNormalW = nW;\n #endif\n\n #if defined(POSITION) || defined(BUMP)\n vertexOutputs.vPositionW = branchWorld;\n #endif\n\n vertexOutputs.position = scene.viewProjection * vec4f(branchWorld, 1.0);\n "}:{CUSTOM_VERTEX_DEFINITIONS:"\n uniform float g_windTime;\n uniform float g_windAmount;\n uniform float g_windSpeed;\n uniform float g_windStrength;\n uniform vec4 g_windDirection;\n\n uniform float g_branchRootY;\n uniform float g_branchMaxAngle;\n uniform float g_branchMaxHeight;\n uniform float g_useVertexColorMask;\n uniform float g_spatialFrequency;\n\n vec3 safeNormalize(vec3 v) {\n float lsq = dot(v, v);\n if (lsq < 1e-8) return vec3(1.0, 0.0, 0.0);\n return v * inversesqrt(lsq);\n }\n\n vec3 rotateRodrigues(vec3 p, vec3 axis, float angle) {\n vec3 a = safeNormalize(axis);\n float c = cos(angle);\n float s = sin(angle);\n return p * c + cross(a, p) * s + a * dot(a, p) * (1.0 - c);\n }\n ",CUSTOM_VERTEX_MAIN_END:"\n // Local/object position\n vec3 pL = positionUpdated;\n\n // Vertex color mask (recommended authoring)\n float bendMask = 1.0;\n float phaseNoise = 0.0;\n #ifdef VERTEXCOLOR\n if (g_useVertexColorMask > 0.5) {\n bendMask = clamp(color.r, 0.0, 1.0);\n phaseNoise = color.g;\n }\n #endif\n\n float denom = max(g_branchMaxHeight - g_branchRootY, 1e-3);\n float h01 = clamp((pL.y - g_branchRootY) / denom, 0.0, 1.0);\n\n float w = h01;\n if (g_useVertexColorMask > 0.5) {\n // smoothstep(h01)\n w = bendMask * (h01 * h01 * (3.0 - 2.0 * h01));\n } else {\n w = h01 * h01;\n }\n\n // Convert wind world dir to local using world basis (transpose approx)\n vec3 windW = safeNormalize(g_windDirection.xyz);\n vec3 rightW = safeNormalize(finalWorld[0].xyz);\n vec3 upW = safeNormalize(finalWorld[1].xyz);\n vec3 fwdW = safeNormalize(finalWorld[2].xyz);\n vec3 windL = safeNormalize(vec3(dot(windW, rightW), dot(windW, upW), dot(windW, fwdW)));\n\n vec3 axisL = safeNormalize(cross(vec3(0.0, 1.0, 0.0), windL));\n if (dot(axisL, axisL) < 1e-6) axisL = vec3(1.0, 0.0, 0.0);\n\n float spatial = (pL.x + pL.z) * g_spatialFrequency;\n float phase = g_windTime * g_windSpeed\n + spatial * g_windStrength\n + phaseNoise * 6.2831853;\n\n float base = sin(phase);\n float gust = 0.5 * sin(phase * 1.7 + 1.2);\n float sway = (base + gust) * g_windAmount;\n\n float angle = clamp(sway * w * g_branchMaxAngle, -g_branchMaxAngle, g_branchMaxAngle);\n\n vec3 pivotL = vec3(0.0, g_branchRootY, 0.0);\n vec3 relL = pL - pivotL;\n vec3 bentPL = pivotL + rotateRodrigues(relL, axisL, angle);\n\n vec3 branchWorld = (finalWorld * vec4(bentPL, 1.0)).xyz;\n\n #if defined(POSITION) || defined(BUMP)\n vPositionW = branchWorld;\n #endif\n\n #ifdef NORMAL\n // normalUpdated is local/object normal\n vec3 nL = normalize(normalUpdated);\n vec3 bentNL = rotateRodrigues(nL, axisL, angle);\n\n // world normal from world basis (approx; assumes no non-uniform scale/shear)\n vec3 nW = normalize(bentNL.x * rightW + bentNL.y * upW + bentNL.z * fwdW);\n vNormalW = nW;\n #endif\n\n gl_Position = viewProjection * vec4(branchWorld, 1.0);\n "}:"fragment"===e?(BABYLON.ShaderLanguage.WGSL,{CUSTOM_FRAGMENT_BEFORE_FINALCOLORCOMPOSITION:"\n // no-op\n "}):null},t.prototype.getUniforms=function(e){var t=e===BABYLON.ShaderLanguage.WGSL;return this.vertexDefinitions=this.getCustomShaderMaterial().getCustomVertexCode(t),this.fragmentDefinitions=!0===t?this.getCustomShaderMaterial().getCustomFragmentCode(t):null,this.getCustomShaderMaterial().getCustomUniforms(t)},t.prototype.getSamplers=function(e){var t=this.getCustomShaderMaterial().getCustomSamplers();t&&t.length>0&&e.push.apply(e,t)},t.prototype.getAttributes=function(e,t,n){var i=this.getCustomShaderMaterial().getCustomAttributes();i&&i.length>0&&e.push.apply(e,i),-1===e.indexOf("color")&&e.push("color")},t.prototype.prepareDefines=function(e,t,n){this.getIsEnabled()&&this.getCustomShaderMaterial().prepareCustomDefines(e)},t.prototype.bindForSubMesh=function(e,t,n,i){this.getIsEnabled()&&this.getCustomShaderMaterial().updateCustomBindings(e)},t.ExtractWindZoneOverride=function(e,t,n){var i,r=[];e&&r.push(e),e&&e.properties&&r.push(e.properties);var o=null==t?void 0:t.metadata;o&&r.push(o),o&&o.toolkit&&r.push(o.toolkit),o&&o.properties&&r.push(o.properties);var a=null==n?void 0:n.metadata;a&&r.push(a),a&&a.toolkit&&r.push(a.toolkit);var s=null===(i=null==n?void 0:n.transform)||void 0===i?void 0:i.metadata;s&&r.push(s),s&&s.toolkit&&r.push(s.toolkit);for(var l=null,u=0,c=r;u<c.length;u++){var d=c[u];if(d&&Array.isArray(d.windzones)){l=d.windzones;break}}if(!l||0===l.length)return null;for(var h=null,p=-1e9,m=0,f=l;m<f.length;m++){var g=f[m];if(g){var v=((null!=g.type?g.type:null!=g.mode?g.mode:"").toString().toLowerCase().indexOf("direction")>=0?1e3:0)+(null!=g.windMain?g.windMain:0);v>p&&(p=v,h=g)}}return h},t}(e.CustomShaderMaterialPlugin);e.TreeBranchMaterialPlugin=n,e.SceneManager.RegisterClass("TOOLKIT.TreeBranchMaterial",t),e.SceneManager.RegisterClass("TOOLKIT.TreeBranchMaterialPlugin",n)}(i||(i={})),function(e){var t=function(t){function n(n,i){var r=t.call(this,n,i)||this;return r.controller=null,r.runtimeAlbedoSkins=null,r.runtimeNormalSkins=null,r.shader=r.getShaderName(),r.addAttribute("g_vatAnim0"),r.addAttribute("g_vatAnim1"),r.addFloatUniform("g_vatTexWidth",1),r.addFloatUniform("g_vatTexHeight",1),r.addFloatUniform("g_vatRowsPerFrame",1),r.addFloatUniform("g_vatVertexCount",1),r.addVector3Uniform("g_vatPosMin",BABYLON.Vector3.Zero()),r.addVector3Uniform("g_vatPosMax",BABYLON.Vector3.One()),r.addFloatUniform("g_vatPrevTexWidth",1),r.addFloatUniform("g_vatPrevTexHeight",1),r.addFloatUniform("g_vatPrevRowsPerFrame",1),r.addVector3Uniform("g_vatPrevPosMin",BABYLON.Vector3.Zero()),r.addVector3Uniform("g_vatPrevPosMax",BABYLON.Vector3.One()),r.addTextureUniform("vatPosition",null),r.addTextureUniform("vatNormal",null),r.addTextureUniform("vatPrevPosition",null),r.addTextureUniform("vatPrevNormal",null),r.markTextureAsRaw("vatPosition"),r.markTextureAsRaw("vatNormal"),r.markTextureAsRaw("vatPrevPosition"),r.markTextureAsRaw("vatPrevNormal"),r.plugin=new e.VertexAnimationMaterialPlugin(r,r.shader),r}return r(n,t),n.prototype.awake=function(){console.warn("VertexAnimationMaterial - Awake(): "+this.name)},n.prototype.update=function(){},n.prototype.getShaderName=function(){return"VertexAnimationMaterial"},n.prototype.getController=function(){return this.controller},n.prototype.cloneForInstance=function(t){var n=this.getScene(),i=new e.VertexAnimationMaterial(t,n);return i.albedoColor=this.albedoColor?this.albedoColor.clone():i.albedoColor,i.albedoTexture=this.albedoTexture,i.reflectivityColor=this.reflectivityColor?this.reflectivityColor.clone():i.reflectivityColor,i.reflectivityTexture=this.reflectivityTexture,i.metallicTexture=this.metallicTexture,i.metallic=this.metallic,i.roughness=this.roughness,i.metallicF0Factor=this.metallicF0Factor,i.bumpTexture=this.bumpTexture,i.emissiveColor=this.emissiveColor?this.emissiveColor.clone():i.emissiveColor,i.emissiveTexture=this.emissiveTexture,i.ambientColor=this.ambientColor?this.ambientColor.clone():i.ambientColor,i.ambientTexture=this.ambientTexture,i.opacityTexture=this.opacityTexture,i.useAlphaFromAlbedoTexture=this.useAlphaFromAlbedoTexture,i.twoSidedLighting=this.twoSidedLighting,i.backFaceCulling=this.backFaceCulling,i.sideOrientation=this.sideOrientation,i.alpha=this.alpha,i.alphaMode=this.alphaMode,i.transparencyMode=this.transparencyMode,i.runtimeAlbedoSkins=this.runtimeAlbedoSkins,i.runtimeNormalSkins=this.runtimeNormalSkins,i._notifyPluginOfRuntimeSkinChange(),i},n.prototype.setRuntimeSkinArrays=function(e,t,n){void 0===n&&(n=!0),this.runtimeAlbedoSkins=e||null,this.runtimeNormalSkins=t||null,n&&(this.albedoTexture=null,this.bumpTexture=null),this._notifyPluginOfRuntimeSkinChange()},n.prototype.clearRuntimeSkinArrays=function(){this.runtimeAlbedoSkins=null,this.runtimeNormalSkins=null,this._notifyPluginOfRuntimeSkinChange()},n.prototype.installSkinsFromUrlsAsync=function(e,t,n,i){return a(this,void 0,void 0,function(){var r,o,a,l,u,c,d,h,p,m,f,g,v,y,_,S;return s(this,function(s){switch(s.label){case 0:if(!e||0===e.length)throw new Error("VertexAnimationMaterial.installSkinsFromUrlsAsync: layers list is empty.");for(o=!1!==(r=i||{}).nullOutDefaults,a=r.rootUrl||"",l=!1!==r.generateMipMaps,u=null!=r.samplingMode?r.samplingMode:BABYLON.Texture.TRILINEAR_SAMPLINGMODE,c=this.getScene(),d=e.length,h=t*n*4,p=new Uint8Array(h*d),m=new Uint8Array(h*d),f=function(e){if(!e)return"";if(e.indexOf("://")>=0||0===e.indexOf("blob:")||0===e.indexOf("data:")||0===e.indexOf("/"))return e;if(a){var t="/"===a.charAt(a.length-1)?"":"/";return a+t+e}return e},g=function(e,i,r,o){return new Promise(function(a,s){var l=f(e),d=new BABYLON.Texture(l,c,!0,!0,u,function(){var e=d.getSize();if(e.width!==t||e.height!==n)return d.dispose(),void s(new Error("".concat(o," '").concat(l,"' is ").concat(e.width,"x").concat(e.height,", expected ").concat(t,"x").concat(n,".")));var u=d.readPixels(),c=function(e){if(!e)return d.dispose(),void s(new Error("".concat(o," '").concat(l,"': readPixels returned null.")));i.set(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r*h),d.dispose(),a()};u&&"function"==typeof u.then?u.then(c).catch(function(e){d.dispose(),s(e)}):c(u)},function(e){return s(new Error("".concat(o," '").concat(l,"' load failed: ").concat(e)))})})},v=[],y=0;y<d;y++)v.push(g(e[y].albedo,p,y,"Skin albedo")),v.push(g(e[y].normal,m,y,"Skin normal"));return[4,Promise.all(v)];case 1:return s.sent(),_=BABYLON.RawTexture2DArray.CreateRGBATexture(p,t,n,d,c,l,!1,u),(S=BABYLON.RawTexture2DArray.CreateRGBATexture(m,t,n,d,c,l,!1,u)).gammaSpace=!1,this.setRuntimeSkinArrays(_,S,o),[2]}})})},n.prototype._notifyPluginOfRuntimeSkinChange=function(){var e=this.plugin;e&&"function"==typeof e.onRuntimeSkinArraysChanged&&e.onRuntimeSkinArraysChanged(),this.markAsDirty(BABYLON.Constants.MATERIAL_AllDirtyFlag)},n}(e.CustomShaderMaterial);e.VertexAnimationMaterial=t;var n=function(){function t(e,t,n,i){var r=this;this._plugins=[],this._clips={},this._currentClip=null,this._previousClip=null,this._time=0,this._previousTime=0,this._speed=1,this._loop=!1,this._loopBlend=!1,this._manualLoopOverride=null,this._playing=!1,this._blendDuration=0,this._blendElapsed=0,this._blendWeight=1,this._mode="auto",this._normalMode="none",this._lazyLoad=!1,this._tickObserver=null,this._disposeObserver=null,this._lastFrameId=-1,this._textureCache={},this._textureCacheKeys={},this._instanceMeshes={},this.guid=e,this.scene=t,this.rootUrl=n||"",this._lazyLoad=!0===i,this._tickObserver=t.onBeforeRenderObservable.add(function(){return r._tick()}),this._disposeObserver=t.onDisposeObservable.addOnce(function(){return r.dispose()})}return t.Find=function(t){return t&&e.VertexAnimationController._registry[t]||null},t.GetOrCreate=function(t,n,i,r){if(void 0===i&&(i=""),void 0===r&&(r=!1),!t)throw new Error("VertexAnimationController: vertexcontroller is required.");var o=e.VertexAnimationController._registry[t];return o||(o=new e.VertexAnimationController(t,n,i,r),e.VertexAnimationController._registry[t]=o),o},t.CollectRendererTargets=function(e){var t=[],n={};if(!e)return t;for(var i=0,r=e;i<r.length;i++){var o=r[i];if(o){var a=o.vertexguid||o.vertexpath||o.vertextransform||o.name;a&&!n[a]&&(n[a]=!0,t.push(o))}}return t},t.SetSkinIndex=function(e,t){e&&(e.runtimeSkinIndex=Math.max(0,Math.floor(t||0)))},t.GetSkinIndex=function(e){if(!e)return 0;var t=e.runtimeSkinIndex;return"number"==typeof t&&isFinite(t)&&t>=0?Math.floor(t):0},t.DisposeAll=function(t){for(var n=0,i=Object.keys(e.VertexAnimationController._registry);n<i.length;n++){var r=i[n],o=e.VertexAnimationController._registry[r];t&&o.scene!==t||o.dispose()}},t.prototype.setInstanceMesh=function(e,t){e&&t&&(this._instanceMeshes[e]=t)},t.prototype.dispose=function(){this._tickObserver&&(this.scene.onBeforeRenderObservable.remove(this._tickObserver),this._tickObserver=null),this._disposeObserver&&(this.scene.onDisposeObservable.remove(this._disposeObserver),this._disposeObserver=null);for(var n=0,i=Object.keys(this._textureCacheKeys);n<i.length;n++){var r=i[n];e.VertexAnimationController._releaseVATTexture(this.scene,r)}this._textureCache={},this._textureCacheKeys={},this._clips={},this._plugins.length=0,this._currentClip=null,this._previousClip=null,delete t._registry[this.guid]},Object.defineProperty(t.prototype,"currentClip",{get:function(){return this._currentClip},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"previousClip",{get:function(){return this._previousClip},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"currentTime",{get:function(){return this._time},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"previousTime",{get:function(){return this._previousTime},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"blendWeight",{get:function(){return this._blendWeight},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"isPlaying",{get:function(){return this._playing},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"normalMode",{get:function(){return this._normalMode},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"loopBlend",{get:function(){return this._loopBlend},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"mode",{get:function(){return this._mode},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"speed",{get:function(){return this._speed},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"loopOverride",{get:function(){return this._manualLoopOverride},enumerable:!1,configurable:!0}),t.prototype.getClip=function(e){return e&&this._clips[e]||null},t.prototype.setSpeed=function(e){this._speed=e},t.prototype.setLoop=function(e){this._manualLoopOverride=e,this._loop=e},t.prototype.setRuntimeSkinArrays=function(e,t,n){void 0===n&&(n=!0);for(var i=0;i<this._plugins.length;i++){var r=this._plugins[i].getCustomShaderMaterial();r&&r.setRuntimeSkinArrays(e,t,n)}},t.prototype.clearRuntimeSkinArrays=function(){for(var e=0;e<this._plugins.length;e++){var t=this._plugins[e].getCustomShaderMaterial();t&&t.clearRuntimeSkinArrays()}},t.prototype.installSkinsFromUrlsAsync=function(e,t,n,i){return a(this,void 0,void 0,function(){var r,a,l,u,c,d,h,p;return s(this,function(s){switch(s.label){case 0:if(0===this._plugins.length)throw new Error("VertexAnimationController.installSkinsFromUrlsAsync: no registered VAT materials.");return a=o(o({},r=i||{}),{rootUrl:r.rootUrl||this.rootUrl}),l=!1!==r.nullOutDefaults,[4,(u=this._plugins[0].getCustomShaderMaterial()).installSkinsFromUrlsAsync(e,t,n,a)];case 1:for(s.sent(),c=u.runtimeAlbedoSkins,d=u.runtimeNormalSkins,h=1;h<this._plugins.length;h++)(p=this._plugins[h].getCustomShaderMaterial())&&p.setRuntimeSkinArrays(c,d,l);return[2]}})})},t.prototype.setCurrentTime=function(e){if(this._currentClip){var t=this._currentClip.duration;this._time=e,t>0?this._loop?this._time=this._wrapTime(this._time,t):this._time=Math.max(0,Math.min(this._time,t)):this._time=Math.max(0,this._time)}},t.prototype.getCurrentTime=function(){return this._time},t.prototype.addPlugin=function(e){-1===this._plugins.indexOf(e)&&this._plugins.push(e)},t.prototype.removePlugin=function(e){var t=this._plugins.indexOf(e);-1!==t&&this._plugins.splice(t,1)},t.prototype.loadAnimations=function(e){var t;if(e&&0!==e.length){"none"===this._normalMode&&e[0]&&e[0].vertexpacking&&(this._normalMode=e[0].vertexpacking);for(var n=0,i=e;n<i.length;n++){var r=i[n];if(r&&r.name){var o=r.vertexguid||r.vertextransform;if(o){var a=this._clips[r.name];if(a||(a={name:r.name,renderers:{},firstRendererGuid:o,duration:0,loop:!1,loopBlend:!1},this._clips[r.name]=a),a.firstRendererGuid||(a.firstRendererGuid=o),!a.renderers[o]){a.renderers&&0===Object.keys(a.renderers).length&&(a.loop=!0===r.vertexlooptime,a.loopBlend=!0===r.vertexloopblend);var s=null,l=null;this._lazyLoad||(s=this._getOrAcquireTexture(r.vertex),l="separate"===r.vertexpacking&&r.vertexnormal?this._getOrAcquireTexture(r.vertexnormal):null),a.renderers[o]={guid:o,settings:r,positionTexture:s,normalTexture:l,posMinV3:BABYLON.Vector3.FromArray(r.vertexposmin),posMaxV3:BABYLON.Vector3.FromArray(r.vertexposmax),fromRow:r.vertexcombined&&null!==(t=r.vertexfromrow)&&void 0!==t?t:0};var u=r.vertexframes>0&&r.vertexfps>0?r.vertexframes/r.vertexfps:0;u>a.duration&&(a.duration=u)}}}}}},t.prototype.play=function(e,t){void 0===t&&(t=.1);var n=this._clips[e];return n?(this._mode="auto",this._ensureClipTexturesLoaded(n),t>0&&this._currentClip&&this._currentClip!==n?(this._ensureClipTexturesLoaded(this._currentClip),this._previousClip=this._currentClip,this._previousTime=this._time,this._blendDuration=t,this._blendElapsed=0,this._blendWeight=0):(this._previousClip=null,this._blendDuration=0,this._blendElapsed=0,this._blendWeight=1),this._currentClip=n,this._time=0,this._playing=!0,this._loop=null!==this._manualLoopOverride?this._manualLoopOverride:!!n.loop,this._loopBlend=!!n.loopBlend,!0):(console.error("VertexAnimationController '".concat(this.guid,"': No clip found with name '").concat(e,"'.")),!1)},t.prototype.pause=function(){this._playing=!1},t.prototype.resume=function(){this._currentClip&&(this._playing=!0)},t.prototype.stop=function(){this._mode="auto",this._playing=!1,this._time=0,this._previousClip=null,this._previousTime=0,this._blendDuration=0,this._blendElapsed=0,this._blendWeight=1},t.prototype.driveBlend=function(e,t,n,i,r){var o=e?this._clips[e]:null;if(!o)return!1;this._ensureClipTexturesLoaded(o);var a=n?this._clips[n]:null;return a&&this._ensureClipTexturesLoaded(a),this._mode="drive",this._playing=!0,this._currentClip=o,this._time=t,this._previousClip=a||null,this._previousTime=a?i:0,this._blendDuration=0,this._blendElapsed=0,this._blendWeight=r<0?0:r>1?1:r,this._loop=null!==this._manualLoopOverride?this._manualLoopOverride:!!o.loop,this._loopBlend=!!o.loopBlend,!0},t.prototype.getCurrentRendererClip=function(e){return this._getRendererClip(this._currentClip,e)},t.prototype.getPreviousRendererClip=function(e){return this._getRendererClip(this._previousClip,e)},t.prototype._tick=function(){var e=this.scene.getFrameId();if(this._lastFrameId!==e){if(this._lastFrameId=e,"auto"===this._mode&&this._playing&&this._currentClip){var t=this.scene.getEngine().getDeltaTime()/1e3,n=Math.min(t,1/30);this._time+=n*this._speed;var i=this._currentClip.duration;if(i>0&&(this._loop?this._time=this._wrapTime(this._time,i):this._time>=i?(this._time=i,this._playing=!1):this._time<0&&(this._time=0,this._playing=!1)),this._previousClip){this._previousTime+=n*this._speed;var r=this._previousClip.duration;r>0&&this._previousTime>r&&(this._previousTime=r),r>0&&this._previousTime<0&&(this._previousTime=0)}this._blendDuration>0&&(this._areBlendTargetsReady()?(this._blendElapsed+=n,this._blendWeight=Math.min(1,this._blendElapsed/this._blendDuration),this._blendWeight>=1&&(this._previousClip=null,this._blendDuration=0,this._blendElapsed=0)):(this._blendElapsed=0,this._blendWeight=0))}for(var o=0,a=Object.keys(this._instanceMeshes);o<a.length;o++){var s=a[o],l=this._instanceMeshes[s];if(l&&l.instancedBuffers){var u=l.instancedBuffers,c=this._getOrCreateVATBuffer(u,"g_vatAnim0"),d=this._getOrCreateVATBuffer(u,"g_vatAnim1"),h=this.getCurrentRendererClip(s);if(h&&this._currentClip&&this._isRendererPositionReady(h)){var p=h.settings;c.set(this._time*p.vertexfps,p.vertexframes,h.fromRow,this._blendWeight);var m=this._loopBlend?1:0,f=l.runtimeSkinIndex,g="number"==typeof f&&f>=0?f:0;d.w=2*g+m;var v=this.getPreviousRendererClip(s);if(v&&this._previousClip&&this._blendWeight<.999&&this._isRendererPositionReady(v)){var y=v.settings;d.x=this._previousTime*y.vertexfps,d.y=y.vertexframes,d.z=v.fromRow}else d.x=0,d.y=0,d.z=0}else c.set(0,0,0,1),d.set(0,0,0,0)}}for(var _=0;_<this._plugins.length;_++){var S=this._plugins[_],A=S.getCustomShaderMaterial();S.syncFromController(A,this)}}},t.prototype._getOrCreateVATBuffer=function(e,t){var n=e[t];return n&&"function"==typeof n.set||(n=new BABYLON.Vector4(0,0,0,0),e[t]=n),n},t.prototype._isRendererPositionReady=function(e){var t=e?e.positionTexture:null;return!(!t||"function"!=typeof t.isReady||!t.isReady())},t.prototype._areBlendTargetsReady=function(){if(!this._previousClip)return!0;for(var e=0,t=Object.keys(this._instanceMeshes);e<t.length;e++){var n=t[e],i=this.getCurrentRendererClip(n),r=this.getPreviousRendererClip(n);if(!this._isRendererPositionReady(i)||!this._isRendererPositionReady(r))return!1}return!0},t.prototype._wrapTime=function(e,t){if(t<=0)return 0;var n=e%t;return n<0&&(n+=t),n},t.prototype._ensureClipTexturesLoaded=function(e){if(e&&e.renderers)for(var t=0,n=Object.keys(e.renderers);t<n.length;t++){var i=n[t],r=e.renderers[i];r&&(!r.positionTexture&&r.settings.vertex&&(r.positionTexture=this._getOrAcquireTexture(r.settings.vertex)),!r.normalTexture&&"separate"===r.settings.vertexpacking&&r.settings.vertexnormal&&(r.normalTexture=this._getOrAcquireTexture(r.settings.vertexnormal)))}},t.prototype._getOrAcquireTexture=function(t){if(!t)return null;var n=this._resolveUrl(t),i=this._textureCache[n];return i||(i=e.VertexAnimationController._acquireVATTexture(this.scene,n),this._textureCache[n]=i,this._textureCacheKeys[n]=!0,i)},t._acquireVATTexture=function(t,n){var i=e.VertexAnimationController._makeVATTextureCacheKey(t,n),r=e.VertexAnimationController._globalTextureCache[i];if(r&&r.texture)return r.refs++,r.texture;var o=e.VertexAnimationController._createVATTexture(t,n);return e.VertexAnimationController._globalTextureCache[i]={texture:o,refs:1},o},t._releaseVATTexture=function(t,n){var i=e.VertexAnimationController._makeVATTextureCacheKey(t,n),r=e.VertexAnimationController._globalTextureCache[i];r&&(r.refs--,r.refs<=0&&(r.texture&&r.texture.dispose(),delete e.VertexAnimationController._globalTextureCache[i]))},t._makeVATTextureCacheKey=function(e,t){var n=e?e.getEngine():null;return[n&&null!=n.uid?n.uid:n&&null!=n._uid?n._uid:n&&n.getClassName?n.getClassName():"engine",e&&null!=e.uid?e.uid:e&&null!=e._uid?e._uid:e&&e.metadata&&e.metadata.guid?e.metadata.guid:"scene",t,"VAT","noMipmap=true","invertY=true","sampling=NEAREST_NEAREST","wrap=CLAMP","gammaSpace=false"].join("|")},t._createVATTexture=function(e,t){var n=new BABYLON.Texture(t,e,!0,!0,BABYLON.Texture.NEAREST_NEAREST);return n.wrapU=BABYLON.Texture.CLAMP_ADDRESSMODE,n.wrapV=BABYLON.Texture.CLAMP_ADDRESSMODE,n.anisotropicFilteringLevel=1,n.gammaSpace=!1,n},t.prototype._resolveUrl=function(e){if(!e)return"";if(e.indexOf("://")>=0||0===e.indexOf("blob:")||0===e.indexOf("data:")||0===e.indexOf("/"))return e;if(this.rootUrl){var t="/"===this.rootUrl.charAt(this.rootUrl.length-1)?"":"/";return this.rootUrl+t+e}return e},t.prototype._getRendererClip=function(e,t){if(!e||!e.renderers)return null;if(t&&e.renderers[t])return e.renderers[t];if(e.firstRendererGuid&&e.renderers[e.firstRendererGuid])return e.renderers[e.firstRendererGuid];var n=Object.keys(e.renderers);return n.length>0?e.renderers[n[0]]:null},t._registry={},t._globalTextureCache={},t}();e.VertexAnimationController=n;var i=function(t){function n(e,n){var i=t.call(this,e,n,100,{VERTEXANIMATIONMATERIAL:!1,VAT_NORMAL_SEPARATE:!1,RUNTIME_SKINS_ALBEDO:!1,RUNTIME_SKINS_NORMAL:!1,RUNTIME_SKINS_NORMAL_DERIVE_TBN:!1})||this;i.vertexAnimations=null,i.controller=null,i._rendererTargets=[],i._targetRendererGuid="",i._placeholderTexture=null,i._placeholderAlbedoArray=null,i._placeholderNormalArray=null,i._cc_posTex=null,i._cc_normTex=null,i._cc_prevPosTex=null,i._cc_prevNormTex=null,i._cc_texW=1,i._cc_texH=1,i._cc_rowsPF=1,i._cc_vCount=1,i._cc_posMin=null,i._cc_posMax=null,i._cc_prevTexW=1,i._cc_prevTexH=1,i._cc_prevRowsPF=1,i._cc_prevPosMin=null,i._cc_prevPosMax=null;var r=e.getScene();i._placeholderTexture=BABYLON.RawTexture.CreateRGBATexture(new Uint8Array([128,128,128,255]),1,1,r,!1,!1,BABYLON.Texture.NEAREST_SAMPLINGMODE),e.setTextureValue("vatPosition",i._placeholderTexture),e.setTextureValue("vatNormal",i._placeholderTexture),e.setTextureValue("vatPrevPosition",i._placeholderTexture),e.setTextureValue("vatPrevNormal",i._placeholderTexture);var o=new Uint8Array([128,128,128,255]),a=new Uint8Array([128,128,255,255]);return i._placeholderAlbedoArray=BABYLON.RawTexture2DArray.CreateRGBATexture(o,1,1,1,r,!1,!1,BABYLON.Texture.NEAREST_SAMPLINGMODE),i._placeholderNormalArray=BABYLON.RawTexture2DArray.CreateRGBATexture(a,1,1,1,r,!1,!1,BABYLON.Texture.NEAREST_SAMPLINGMODE),i}return r(n,t),n.prototype.dispose=function(){this._placeholderTexture&&(this._placeholderTexture.dispose(),this._placeholderTexture=null),this._placeholderAlbedoArray&&(this._placeholderAlbedoArray.dispose(),this._placeholderAlbedoArray=null),this._placeholderNormalArray&&(this._placeholderNormalArray.dispose(),this._placeholderNormalArray=null),t.prototype.dispose.call(this)},n.prototype.isCompatible=function(e){return e===BABYLON.ShaderLanguage.WGSL||e===BABYLON.ShaderLanguage.GLSL},n.prototype.getCustomCode=function(e,t){var n=t===BABYLON.ShaderLanguage.WGSL;return"vertex"===e?n?{CUSTOM_VERTEX_DEFINITIONS:this.getWGSLVertexDefinitions(),CUSTOM_VERTEX_UPDATE_POSITION:this.getWGSLVertexPositionCode(),CUSTOM_VERTEX_UPDATE_NORMAL:this.getWGSLVertexNormalCode(),CUSTOM_VERTEX_MAIN_END:this.getWGSLVertexMainEnd()}:{CUSTOM_VERTEX_DEFINITIONS:this.getGLSLVertexDefinitions(),CUSTOM_VERTEX_UPDATE_POSITION:this.getGLSLVertexPositionCode(),CUSTOM_VERTEX_UPDATE_NORMAL:this.getGLSLVertexNormalCode(),CUSTOM_VERTEX_MAIN_END:this.getGLSLVertexMainEnd()}:"fragment"===e?n?{CUSTOM_FRAGMENT_DEFINITIONS:this.getWGSLFragmentDefinitions(),CUSTOM_FRAGMENT_UPDATE_ALBEDO:this.getWGSLFragmentAlbedoCode(),CUSTOM_FRAGMENT_BEFORE_LIGHTS:this.getWGSLFragmentNormalCode()}:{CUSTOM_FRAGMENT_DEFINITIONS:this.getGLSLFragmentDefinitions(),CUSTOM_FRAGMENT_UPDATE_ALBEDO:this.getGLSLFragmentAlbedoCode(),CUSTOM_FRAGMENT_BEFORE_LIGHTS:this.getGLSLFragmentNormalCode()}:null},n.prototype.getUniforms=function(e){var t=e===BABYLON.ShaderLanguage.WGSL;return this.vertexDefinitions=this.getCustomShaderMaterial().getCustomVertexCode(t),this.fragmentDefinitions=!0===t?this.getCustomShaderMaterial().getCustomFragmentCode(t):null,this.getCustomShaderMaterial().getCustomUniforms(t)},n.prototype.getSamplers=function(e){var t=this.getCustomShaderMaterial().getCustomSamplers();null!=t&&t.length>0&&e.push.apply(e,t),this.getCustomShaderMaterial()&&(-1===e.indexOf("runtimeAlbedoSkins")&&e.push("runtimeAlbedoSkins"),-1===e.indexOf("runtimeNormalSkins")&&e.push("runtimeNormalSkins"))},n.prototype.getAttributes=function(e,t,n){var i=this.getCustomShaderMaterial().getCustomAttributes();null!=i&&i.length>0&&e.push.apply(e,i)},n.prototype.prepareDefines=function(e,t,n){if(this.getIsEnabled()){this._captureRendererTarget(n),this.getCustomShaderMaterial().prepareCustomDefines(e);var i=this.controller?this.controller.normalMode:"none";e.VAT_NORMAL_SEPARATE="separate"===i;var r=t?t.getEngine():null;e.UV3=!(r&&r.isWebGPU);var o=this.getCustomShaderMaterial(),a=!(!o||!o.runtimeAlbedoSkins),s=!(!o||!o.runtimeNormalSkins);e.RUNTIME_SKINS_ALBEDO=a,e.RUNTIME_SKINS_NORMAL=s,e.RUNTIME_SKINS_NORMAL_DERIVE_TBN=s&&!(o&&o.bumpTexture)}},n.prototype.onRuntimeSkinArraysChanged=function(){this.markAllDefinesAsDirty()},n.prototype.bindForSubMesh=function(e,t,n,i){if(this.getIsEnabled()){var r=i&&i.getRenderingMesh?i.getRenderingMesh():null;this._captureRendererTarget(r||(i?i.getMesh():null)),this._pushVATUniforms(e,!1),this._pushRuntimeSkinSamplers(e)}},n.prototype._pushRuntimeSkinSamplers=function(e){var t=this.getCustomShaderMaterial(),n=t&&t.runtimeAlbedoSkins&&t.runtimeAlbedoSkins.isReady&&t.runtimeAlbedoSkins.isReady()?t.runtimeAlbedoSkins:this._placeholderAlbedoArray,i=t&&t.runtimeNormalSkins&&t.runtimeNormalSkins.isReady&&t.runtimeNormalSkins.isReady()?t.runtimeNormalSkins:this._placeholderNormalArray;e.setTexture("runtimeAlbedoSkins",n),e.setTexture("runtimeNormalSkins",i)},n.prototype.setupAnimations=function(t,n,i,r){var o,a;if(void 0===i&&(i=""),void 0===r&&(r=!1),this.vertexAnimations=t,t&&0!==t.length){if(n){this._rendererTargets=e.VertexAnimationController.CollectRendererTargets(t),this._targetRendererGuid="";var s=this.getCustomShaderMaterial(),l=s.getScene(),u=e.VertexAnimationController.GetOrCreate(n,l,i,r);u.loadAnimations(t),u.addPlugin(this),this.controller=u,s.controller=u;var c=function(e){var t,n;if(e){if(!e._vatMaterials){e._vatMaterials=[];var i=null;e.onBeforeShadowMapRenderMeshObservable.add(function(e){i=e}),e.onBeforeShadowMapRenderObservable.add(function(t){if(i&&t)for(var n=i.material,r=e._vatMaterials,o=0;o<r.length;o++)if(r[o]===n){var a=r[o].getPlugin();a&&a.bindVATToEffect(t);break}i=null}),e.forceBackFacesOnly=!0,h?(e.normalBias=0,0===(null!==(n=e.bias)&&void 0!==n?n:0)&&(e.bias=.005)):0===(null!==(t=e.normalBias)&&void 0!==t?t:0)&&(e.normalBias=.02)}var r=e._vatMaterials;-1===r.indexOf(s)&&r.push(s)}},d=function(){for(var e,t,n=0,i=l.lights;n<i.length;n++){var r=i[n];c(null===(t=(e=r).getShadowGenerator)||void 0===t?void 0:t.call(e))}},h=!0===l.getEngine().isWebGPU||"WebGPUEngine"===(null===(a=(o=l.getEngine()).getClassName)||void 0===a?void 0:a.call(o));return s.shadowDepthWrapper||(s.shadowDepthWrapper=new BABYLON.ShadowDepthWrapper(s,l)),d(),l.onAfterRenderObservable.addOnce(function(){return d()}),s.markAsDirty(BABYLON.Constants.MATERIAL_AllDirtyFlag),this.markAllDefinesAsDirty(),u}BABYLON.Tools.Warn("VertexAnimationMaterialPlugin: vertexcontroller is empty — cannot share controller.")}},n.prototype._captureRendererTarget=function(e){if(""===this._targetRendererGuid){var t=this._resolveRendererTarget(e);t&&t.vertexguid&&(this._targetRendererGuid=t.vertexguid)}},n.prototype._resolveRendererTarget=function(e){if(!e||!this._rendererTargets||0===this._rendererTargets.length)return null;if(1===this._rendererTargets.length)return this._rendererTargets[0];for(var t=[],n=e;n;)t.push(n),n=n.parent;for(var i=0,r=t;i<r.length;i++){var o=r[i],a=this._readMetadataString(o,"guid");if(a&&(h=this._matchRendererByGuid(a)))return h}for(var s=0,l=t;s<l.length;s++){o=l[s];var u=this._buildNodePath(o);if(u&&(h=this._matchRendererByPath(u)))return h}for(var c=0,d=t;c<d.length;c++){var h,p=(o=d[c])&&o.name?o.name:"";if(p&&(h=this._matchRendererByName(p)))return h}return null},n.prototype._matchRendererByGuid=function(e){for(var t=0,n=this._rendererTargets;t<n.length;t++){var i=n[t];if(i&&i.vertexguid===e)return i}return null},n.prototype._matchRendererByPath=function(e){for(var t=0,n=this._rendererTargets;t<n.length;t++){var i=n[t];if(i&&i.vertexpath&&this._pathEndsWith(e,i.vertexpath))return i}return null},n.prototype._matchRendererByName=function(e){for(var t=0,n=this._rendererTargets;t<n.length;t++){var i=n[t];if(i){if(i.vertextransform===e)return i;if(i.vertexrenderer===e)return i;if(i.vertexmesh===e)return i}}return null},n.prototype._readMetadataString=function(e,t){if(!e||!e.metadata)return"";var n=e.metadata,i=n?n[t]:null;if("string"==typeof i&&""!==i)return i;var r=n?n.toolkit:null,o=r?r[t]:null;return"string"==typeof o&&""!==o?o:"guid"===t&&"string"==typeof e.id&&""!==e.id?e.id:""},n.prototype._buildNodePath=function(e){for(var t=[],n=e;n;)n.name&&t.unshift(n.name),n=n.parent;return t.join("/")},n.prototype._pathEndsWith=function(e,t){if(!e||!t)return!1;if(e===t)return!0;if(e.length<=t.length)return!1;var n=e.length-t.length;return e.substring(n)===t&&"/"===e.charAt(n-1)},n.prototype.syncFromController=function(e,t){void 0===t&&(t=null);var n=t||this.controller;if(n){var i=this._placeholderTexture,r=function(e){return null!=e&&"function"==typeof e.isReady&&e.isReady()},o=(n.normalMode,n.getCurrentRendererClip(this._targetRendererGuid));if(o){var a=r(o.positionTexture)?o.positionTexture:i,s=r(o.normalTexture)?o.normalTexture:i;e.setTextureValue("vatPosition",a),e.setTextureValue("vatNormal",s);var l=o.settings;this._cc_posTex=a,this._cc_normTex=s,this._cc_texW=l.vertexwidth,this._cc_texH=l.vertexheight,this._cc_rowsPF=l.vertexrowsperframe,this._cc_vCount=l.vertexcount,this._cc_posMin=o.posMinV3,this._cc_posMax=o.posMaxV3}else e.setTextureValue("vatPosition",i),e.setTextureValue("vatNormal",i),this._cc_posTex=i,this._cc_normTex=i,this._cc_posMin=null,this._cc_posMax=null;var u=n.getPreviousRendererClip(this._targetRendererGuid);if(u){var c=r(u.positionTexture)?u.positionTexture:i,d=r(u.normalTexture)?u.normalTexture:i;e.setTextureValue("vatPrevPosition",c),e.setTextureValue("vatPrevNormal",d),l=u.settings,this._cc_prevPosTex=c,this._cc_prevNormTex=d,this._cc_prevTexW=l.vertexwidth,this._cc_prevTexH=l.vertexheight,this._cc_prevRowsPF=l.vertexrowsperframe,this._cc_prevPosMin=u.posMinV3,this._cc_prevPosMax=u.posMaxV3}else e.setTextureValue("vatPrevPosition",i),e.setTextureValue("vatPrevNormal",i),this._cc_prevPosTex=i,this._cc_prevNormTex=i,this._cc_prevPosMin=null,this._cc_prevPosMax=null}},n.prototype.bindVATToEffect=function(e){this._pushVATUniforms(e,!0),this._pushRuntimeSkinSamplers(e)},n.prototype._pushVATUniforms=function(e,t){var i,r,o,a,s,l,u,c,d,h,p=this._placeholderTexture,m=n._zeroV3,f=n._oneV3,g=null==this._cc_prevPosTex||this._cc_prevPosTex===p||null==this._cc_prevPosMin||null==this._cc_prevPosMax,v=g?null!==(i=this._cc_posTex)&&void 0!==i?i:p:this._cc_prevPosTex,y=g?null!==(r=this._cc_normTex)&&void 0!==r?r:p:this._cc_prevNormTex,_=g?null!==(o=this._cc_posMin)&&void 0!==o?o:m:this._cc_prevPosMin,S=g?null!==(a=this._cc_posMax)&&void 0!==a?a:f:this._cc_prevPosMax,A=g?this._cc_texW:this._cc_prevTexW,b=g?this._cc_texH:this._cc_prevTexH,M=g?this._cc_rowsPF:this._cc_prevRowsPF;if(e.setTexture("vatPosition",null!==(s=this._cc_posTex)&&void 0!==s?s:p),e.setTexture("vatNormal",null!==(l=this._cc_normTex)&&void 0!==l?l:p),e.setTexture("vatPrevPosition",null!=v?v:p),e.setTexture("vatPrevNormal",null!=y?y:p),t){var B=e;B.setFloat("g_vatTexWidth",this._cc_texW),B.setFloat("g_vatTexHeight",this._cc_texH),B.setFloat("g_vatRowsPerFrame",this._cc_rowsPF),B.setFloat("g_vatVertexCount",this._cc_vCount),B.setVector3("g_vatPosMin",null!==(u=this._cc_posMin)&&void 0!==u?u:m),B.setVector3("g_vatPosMax",null!==(c=this._cc_posMax)&&void 0!==c?c:f),B.setFloat("g_vatPrevTexWidth",A),B.setFloat("g_vatPrevTexHeight",b),B.setFloat("g_vatPrevRowsPerFrame",M),B.setVector3("g_vatPrevPosMin",_),B.setVector3("g_vatPrevPosMax",S)}else{var C=e;C.updateFloat("g_vatTexWidth",this._cc_texW),C.updateFloat("g_vatTexHeight",this._cc_texH),C.updateFloat("g_vatRowsPerFrame",this._cc_rowsPF),C.updateFloat("g_vatVertexCount",this._cc_vCount),C.updateVector3("g_vatPosMin",null!==(d=this._cc_posMin)&&void 0!==d?d:m),C.updateVector3("g_vatPosMax",null!==(h=this._cc_posMax)&&void 0!==h?h:f),C.updateFloat("g_vatPrevTexWidth",A),C.updateFloat("g_vatPrevTexHeight",b),C.updateFloat("g_vatPrevRowsPerFrame",M),C.updateVector3("g_vatPrevPosMin",_),C.updateVector3("g_vatPrevPosMax",S)}},n.prototype.getGLSLVertexDefinitions=function(){return"\n #ifndef TOOLKIT_VAT_V_UNIFORMS\n #define TOOLKIT_VAT_V_UNIFORMS\n // Per-instance animation values come from InstancedMesh.instancedBuffers\n // (vertex attributes with divisor=1) — NOT uniforms. Every instance in a\n // hardware-instanced draw call gets its own independent values.\n attribute vec4 g_vatAnim0; // frame, frameCount, fromRow, blendWeight\n attribute vec4 g_vatAnim1; // prevFrame, prevFrameCount, prevFromRow, loopBlend\n uniform float g_vatTexWidth;\n uniform float g_vatTexHeight;\n uniform float g_vatRowsPerFrame;\n uniform float g_vatVertexCount;\n uniform vec3 g_vatPosMin;\n uniform vec3 g_vatPosMax;\n uniform float g_vatPrevTexWidth;\n uniform float g_vatPrevTexHeight;\n uniform float g_vatPrevRowsPerFrame;\n uniform vec3 g_vatPrevPosMin;\n uniform vec3 g_vatPrevPosMax;\n uniform sampler2D vatPosition;\n uniform sampler2D vatNormal;\n uniform sampler2D vatPrevPosition;\n uniform sampler2D vatPrevNormal;\n #endif\n // Runtime-skin varyings — pass packed skin index + UV0 to the fragment stage so\n // fragment can sample runtimeAlbedoSkins[layer]/runtimeNormalSkins[layer]. Always\n // emitted (cheap) so the shader compiles regardless of the runtime-skin defines.\n #ifndef TOOLKIT_VAT_RUNTIMESKIN_VARYINGS\n #define TOOLKIT_VAT_RUNTIMESKIN_VARYINGS\n varying float vRuntimeSkinIndex;\n varying vec2 vRuntimeSkinUV;\n #endif\n "},n.prototype.getGLSLVertexPositionCode=function(){return"\n #ifdef VERTEXANIMATIONMATERIAL\n float vatFrame = g_vatAnim0.x;\n float vatFrameCount = g_vatAnim0.y;\n float vatFromRow = g_vatAnim0.z;\n float vatBlendWeight = g_vatAnim0.w;\n float vatPrevFrame = g_vatAnim1.x;\n float vatPrevFrameCount = g_vatAnim1.y;\n float vatPrevFromRow = g_vatAnim1.z;\n float vatPackedSkinLoop = g_vatAnim1.w;\n float vatLoopBlend = mod(vatPackedSkinLoop, 2.0);\n if (vatFrameCount > 0.5) {\n // GLSL path uses the third UV channel:\n // Unity uv3 -> glTF TEXCOORD_2 -> Babylon shader uv3\n // uv3.x = texel-centre U inside one VAT frame\n // uv3.y = row index inside the frame tile (+0.5 for stable floor)\n float baseU = clamp(uv3.x, 0.0, 1.0);\n float rowInTile = max(0.0, floor(uv3.y));\n\n float rowsPF = g_vatRowsPerFrame;\n float frameA = clamp(floor(vatFrame), 0.0, vatFrameCount - 1.0);\n float fracA = fract(vatFrame);\n float frameB = frameA + 1.0;\n if (frameB >= vatFrameCount) {\n if (vatLoopBlend > 0.5) {\n frameB = 0.0;\n } else {\n frameB = frameA;\n fracA = 0.0;\n }\n }\n\n vec2 uvA = vec2(baseU, (vatFromRow + frameA * rowsPF + rowInTile + 0.5) / g_vatTexHeight);\n vec2 uvB = vec2(baseU, (vatFromRow + frameB * rowsPF + rowInTile + 0.5) / g_vatTexHeight);\n vec4 encA = textureLod(vatPosition, uvA, 0.0);\n vec4 encB = textureLod(vatPosition, uvB, 0.0);\n vec3 posA = mix(g_vatPosMin, g_vatPosMax, encA.xyz);\n vec3 posB = mix(g_vatPosMin, g_vatPosMax, encB.xyz);\n vec3 curPos = mix(posA, posB, fracA);\n\n // Crossfade with previous clip if a blend is active\n if (vatBlendWeight < 0.999 && vatPrevFrameCount > 0.5) {\n float rowsPFp = g_vatPrevRowsPerFrame;\n float rowInTileP = rowInTile;\n float frameAp = clamp(floor(vatPrevFrame), 0.0, vatPrevFrameCount - 1.0);\n float fracAp = fract(vatPrevFrame);\n float frameBp = frameAp + 1.0;\n if (frameBp >= vatPrevFrameCount) {\n if (vatLoopBlend > 0.5) {\n frameBp = 0.0;\n } else {\n frameBp = frameAp;\n fracAp = 0.0;\n }\n }\n float tileRowAp = frameAp * rowsPFp + rowInTileP;\n float tileRowBp = frameBp * rowsPFp + rowInTileP;\n vec2 uvAp = vec2(baseU, (vatPrevFromRow + tileRowAp + 0.5) / g_vatPrevTexHeight);\n vec2 uvBp = vec2(baseU, (vatPrevFromRow + tileRowBp + 0.5) / g_vatPrevTexHeight);\n vec4 encAp = textureLod(vatPrevPosition, uvAp, 0.0);\n vec4 encBp = textureLod(vatPrevPosition, uvBp, 0.0);\n vec3 prevPosA = mix(g_vatPrevPosMin, g_vatPrevPosMax, encAp.xyz);\n vec3 prevPosB = mix(g_vatPrevPosMin, g_vatPrevPosMax, encBp.xyz);\n vec3 prevPos = mix(prevPosA, prevPosB, fracAp);\n curPos = mix(prevPos, curPos, vatBlendWeight);\n }\n\n positionUpdated = curPos;\n }\n #endif\n "},n.prototype.getGLSLVertexNormalCode=function(){return"\n #ifdef VERTEXANIMATIONMATERIAL\n float vatNormFrame = g_vatAnim0.x;\n float vatNormFrameCount = g_vatAnim0.y;\n float vatNormFromRow = g_vatAnim0.z;\n \n float vatNormPackedSkinLoop = g_vatAnim1.w;\n float vatNormLoopBlend = mod(vatNormPackedSkinLoop, 2.0);\n\n if (vatNormFrameCount > 0.5) {\n // GLSL path uses the third UV channel:\n // Unity uv3 -> glTF TEXCOORD_2 -> Babylon shader uv3\n float baseU = clamp(uv3.x, 0.0, 1.0);\n float rowInTile = max(0.0, floor(uv3.y));\n float rowsPF = g_vatRowsPerFrame;\n float frameA = clamp(floor(vatNormFrame), 0.0, vatNormFrameCount - 1.0);\n float fractA = fract(vatNormFrame);\n float frameB = frameA + 1.0;\n if (frameB >= vatNormFrameCount) {\n if (vatNormLoopBlend > 0.5) {\n frameB = 0.0;\n } else {\n frameB = frameA;\n fractA = 0.0;\n }\n }\n\n vec2 uvA = vec2(baseU, (vatNormFromRow + frameA * rowsPF + rowInTile + 0.5) / g_vatTexHeight);\n vec2 uvB = vec2(baseU, (vatNormFromRow + frameB * rowsPF + rowInTile + 0.5) / g_vatTexHeight);\n vec4 nA = textureLod(vatNormal, uvA, 0.0);\n vec4 nB = textureLod(vatNormal, uvB, 0.0);\n vec3 normalA = normalize(nA.xyz * 2.0 - 1.0);\n vec3 normalB = normalize(nB.xyz * 2.0 - 1.0);\n vec3 normalResult = normalize(mix(normalA, normalB, fractA));\n\n normalUpdated = normalResult;\n }\n #endif\n "},n.prototype.getWGSLVertexDefinitions=function(){return"\n #ifdef VERTEXANIMATIONMATERIAL\n attribute g_vatAnim0 : vec4<f32>;\n attribute g_vatAnim1 : vec4<f32>;\n var vatPosition: texture_2d<f32>;\n var vatPositionSampler: sampler;\n var vatNormal: texture_2d<f32>;\n var vatNormalSampler: sampler;\n var vatPrevPosition: texture_2d<f32>;\n var vatPrevPositionSampler: sampler;\n var vatPrevNormal: texture_2d<f32>;\n var vatPrevNormalSampler: sampler;\n // Runtime-skin varyings — packed skin index and UV0, passed to fragment.\n varying vRuntimeSkinIndex: f32;\n varying vRuntimeSkinUV: vec2<f32>;\n #endif\n "},n.prototype.getWGSLVertexPositionCode=function(){return"\n #ifdef VERTEXANIMATIONMATERIAL\n let vatFrame = vertexInputs.g_vatAnim0.x;\n let vatFrameCount = vertexInputs.g_vatAnim0.y;\n let vatFromRow = vertexInputs.g_vatAnim0.z;\n let vatBlendWeight = vertexInputs.g_vatAnim0.w;\n let vatPrevFrame = vertexInputs.g_vatAnim1.x;\n let vatPrevFrameCount = vertexInputs.g_vatAnim1.y;\n let vatPrevFromRow = vertexInputs.g_vatAnim1.z;\n let packedSkinLoop = vertexInputs.g_vatAnim1.w;\n let vatLoopBlend = packedSkinLoop % 2.0;\n if (vatFrameCount > 0.5) {\n // WGSL path derives the VAT texel coordinate from the vertex index instead\n // of consuming a dedicated uv3 vertex-buffer slot.\n let vatTexWidth = max(uniforms.g_vatTexWidth, 1.0);\n let vatVertexIndex = f32(vertexInputs.vertexIndex);\n let rowInTile = max(0.0, floor(vatVertexIndex / vatTexWidth));\n let colInTile = vatVertexIndex - rowInTile * vatTexWidth;\n let baseU = (colInTile + 0.5) / vatTexWidth;\n\n let rowsPF = uniforms.g_vatRowsPerFrame;\n let frameA = clamp(floor(vatFrame), 0.0, vatFrameCount - 1.0);\n var fracA = fract(vatFrame);\n var frameB = frameA + 1.0;\n if (frameB >= vatFrameCount) {\n if (vatLoopBlend > 0.5) {\n frameB = 0.0;\n } else {\n frameB = frameA;\n fracA = 0.0;\n }\n }\n let tileRowA = frameA * rowsPF + rowInTile;\n let tileRowB = frameB * rowsPF + rowInTile;\n let uvA = vec2f(baseU, (vatFromRow + tileRowA + 0.5) / uniforms.g_vatTexHeight);\n let uvB = vec2f(baseU, (vatFromRow + tileRowB + 0.5) / uniforms.g_vatTexHeight);\n let encA = textureSampleLevel(vatPosition, vatPositionSampler, uvA, 0.0);\n let encB = textureSampleLevel(vatPosition, vatPositionSampler, uvB, 0.0);\n let posA = mix(uniforms.g_vatPosMin, uniforms.g_vatPosMax, encA.xyz);\n let posB = mix(uniforms.g_vatPosMin, uniforms.g_vatPosMax, encB.xyz);\n var curPos = mix(posA, posB, fracA);\n\n if (vatBlendWeight < 0.999 && vatPrevFrameCount > 0.5) {\n let rowsPFp = uniforms.g_vatPrevRowsPerFrame;\n let rowInTileP = rowInTile;\n let frameAp = clamp(floor(vatPrevFrame), 0.0, vatPrevFrameCount - 1.0);\n var fracAp = fract(vatPrevFrame);\n var frameBp = frameAp + 1.0;\n if (frameBp >= vatPrevFrameCount) {\n if (vatLoopBlend > 0.5) {\n frameBp = 0.0;\n } else {\n frameBp = frameAp;\n fracAp = 0.0;\n }\n }\n let tileRowAp = frameAp * rowsPFp + rowInTileP;\n let tileRowBp = frameBp * rowsPFp + rowInTileP;\n let uvAp = vec2f(baseU, (vatPrevFromRow + tileRowAp + 0.5) / uniforms.g_vatPrevTexHeight);\n let uvBp = vec2f(baseU, (vatPrevFromRow + tileRowBp + 0.5) / uniforms.g_vatPrevTexHeight);\n let encAp = textureSampleLevel(vatPrevPosition, vatPrevPositionSampler, uvAp, 0.0);\n let encBp = textureSampleLevel(vatPrevPosition, vatPrevPositionSampler, uvBp, 0.0);\n let prevPosA = mix(uniforms.g_vatPrevPosMin, uniforms.g_vatPrevPosMax, encAp.xyz);\n let prevPosB = mix(uniforms.g_vatPrevPosMin, uniforms.g_vatPrevPosMax, encBp.xyz);\n let prevPos = mix(prevPosA, prevPosB, fracAp);\n curPos = mix(prevPos, curPos, vatBlendWeight);\n }\n\n positionUpdated = curPos;\n }\n #endif\n "},n.prototype.getWGSLVertexNormalCode=function(){return"\n #ifdef VERTEXANIMATIONMATERIAL\n let vatNormFrame = vertexInputs.g_vatAnim0.x;\n let vatNormFrameCount = vertexInputs.g_vatAnim0.y;\n let vatNormFromRow = vertexInputs.g_vatAnim0.z;\n let vatNormPackedSkinLoop = vertexInputs.g_vatAnim1.w;\n let vatNormLoopBlend = vatNormPackedSkinLoop % 2.0;\n if (vatNormFrameCount > 0.5) {\n // WGSL path derives the VAT texel coordinate from the vertex index instead\n // of consuming a dedicated uv3 vertex-buffer slot.\n let vatTexWidth = max(uniforms.g_vatTexWidth, 1.0);\n let vatVertexIndex = f32(vertexInputs.vertexIndex);\n let rowInTile = max(0.0, floor(vatVertexIndex / vatTexWidth));\n let colInTile = vatVertexIndex - rowInTile * vatTexWidth;\n let baseU = (colInTile + 0.5) / vatTexWidth;\n let rowsPF = uniforms.g_vatRowsPerFrame;\n\n #ifdef VAT_NORMAL_SEPARATE\n let frameA = clamp(floor(vatNormFrame), 0.0, vatNormFrameCount - 1.0);\n var fracA = fract(vatNormFrame);\n var frameB = frameA + 1.0;\n if (frameB >= vatNormFrameCount) {\n if (vatNormLoopBlend > 0.5) {\n frameB = 0.0;\n } else {\n frameB = frameA;\n fracA = 0.0;\n }\n }\n let tileRowA = frameA * rowsPF + rowInTile;\n let tileRowB = frameB * rowsPF + rowInTile;\n let uvA = vec2f(baseU, (vatNormFromRow + tileRowA + 0.5) / uniforms.g_vatTexHeight);\n let uvB = vec2f(baseU, (vatNormFromRow + tileRowB + 0.5) / uniforms.g_vatTexHeight);\n let nA = textureSampleLevel(vatNormal, vatNormalSampler, uvA, 0.0);\n let nB = textureSampleLevel(vatNormal, vatNormalSampler, uvB, 0.0);\n let normalA = normalize(nA.xyz * 2.0 - vec3f(1.0));\n let normalB = normalize(nB.xyz * 2.0 - vec3f(1.0));\n normalUpdated = normalize(mix(normalA, normalB, fracA));\n #endif\n }\n #endif\n "},n.prototype.getGLSLVertexMainEnd=function(){return"\n #ifdef VERTEXANIMATIONMATERIAL\n {\n float _rsPackedSkinLoop = g_vatAnim1.w;\n vRuntimeSkinIndex = floor(_rsPackedSkinLoop * 0.5 + 0.0001);\n #ifdef UV1\n vRuntimeSkinUV = uv;\n #else\n vRuntimeSkinUV = vec2(0.0, 0.0);\n #endif\n }\n #endif\n "},n.prototype.getWGSLVertexMainEnd=function(){return"\n #ifdef VERTEXANIMATIONMATERIAL\n {\n let _rsPackedSkinLoop = vertexInputs.g_vatAnim1.w;\n vertexOutputs.vRuntimeSkinIndex = floor(_rsPackedSkinLoop * 0.5 + 0.0001);\n #ifdef UV1\n vertexOutputs.vRuntimeSkinUV = vertexInputs.uv;\n #else\n vertexOutputs.vRuntimeSkinUV = vec2f(0.0, 0.0);\n #endif\n }\n #endif\n "},n.prototype.getGLSLFragmentDefinitions=function(){return"\n #ifndef TOOLKIT_VAT_RUNTIMESKIN_F_UNIFORMS\n #define TOOLKIT_VAT_RUNTIMESKIN_F_UNIFORMS\n varying float vRuntimeSkinIndex;\n varying vec2 vRuntimeSkinUV;\n uniform highp sampler2DArray runtimeAlbedoSkins;\n uniform highp sampler2DArray runtimeNormalSkins;\n #endif\n "},n.prototype.getGLSLFragmentAlbedoCode=function(){return"\n #ifdef RUNTIME_SKINS_ALBEDO\n {\n float _rsLayer = max(0.0, floor(vRuntimeSkinIndex + 0.5));\n vec4 _rsAlbedo = texture(runtimeAlbedoSkins, vec3(vRuntimeSkinUV, _rsLayer));\n surfaceAlbedo = _rsAlbedo.rgb * vAlbedoColor.rgb;\n #ifdef ALPHATEST\n if (_rsAlbedo.a < alphaCutOff) discard;\n #endif\n }\n #endif\n "},n.prototype.getGLSLFragmentNormalCode=function(){return"\n #ifdef RUNTIME_SKINS_NORMAL\n {\n float _rsLayer = max(0.0, floor(vRuntimeSkinIndex + 0.5));\n vec3 _rsNormalSample = texture(runtimeNormalSkins, vec3(vRuntimeSkinUV, _rsLayer)).xyz;\n vec3 _rsNormalTS = _rsNormalSample * 2.0 - 1.0;\n vec3 _rsP = vPositionW;\n vec3 _rsN = normalize(vNormalW);\n vec3 _rsDp1 = dFdx(_rsP);\n vec3 _rsDp2 = dFdy(_rsP);\n vec2 _rsDuv1 = dFdx(vRuntimeSkinUV);\n vec2 _rsDuv2 = dFdy(vRuntimeSkinUV);\n vec3 _rsDp2perp = cross(_rsDp2, _rsN);\n vec3 _rsDp1perp = cross(_rsN, _rsDp1);\n vec3 _rsT = _rsDp2perp * _rsDuv1.x + _rsDp1perp * _rsDuv2.x;\n vec3 _rsB = _rsDp2perp * _rsDuv1.y + _rsDp1perp * _rsDuv2.y;\n float _rsInvMax = inversesqrt(max(dot(_rsT, _rsT), dot(_rsB, _rsB)));\n mat3 _rsTBN = mat3(_rsT * _rsInvMax, _rsB * _rsInvMax, _rsN);\n normalW = normalize(_rsTBN * _rsNormalTS);\n }\n #endif\n "},n.prototype.getWGSLFragmentDefinitions=function(){return"\n varying vRuntimeSkinIndex: f32;\n varying vRuntimeSkinUV: vec2<f32>;\n var runtimeAlbedoSkins: texture_2d_array<f32>;\n var runtimeAlbedoSkinsSampler: sampler;\n var runtimeNormalSkins: texture_2d_array<f32>;\n var runtimeNormalSkinsSampler: sampler;\n "},n.prototype.getWGSLFragmentAlbedoCode=function(){return"\n #ifdef RUNTIME_SKINS_ALBEDO\n {\n let _rsLayer = i32(max(0.0, floor(fragmentInputs.vRuntimeSkinIndex + 0.5)));\n let _rsAlbedo = textureSample(runtimeAlbedoSkins, runtimeAlbedoSkinsSampler, fragmentInputs.vRuntimeSkinUV, _rsLayer);\n surfaceAlbedo = _rsAlbedo.rgb * vAlbedoColor.rgb;\n #ifdef ALPHATEST\n if (_rsAlbedo.a < alphaCutOff) { discard; }\n #endif\n }\n #endif\n "},n.prototype.getWGSLFragmentNormalCode=function(){return"\n #ifdef RUNTIME_SKINS_NORMAL\n {\n let _rsLayer = i32(max(0.0, floor(fragmentInputs.vRuntimeSkinIndex + 0.5)));\n let _rsNormalSample = textureSample(runtimeNormalSkins, runtimeNormalSkinsSampler, fragmentInputs.vRuntimeSkinUV, _rsLayer).xyz;\n let _rsNormalTS = _rsNormalSample * 2.0 - vec3f(1.0);\n let _rsP = fragmentInputs.vPositionW;\n let _rsN = normalize(fragmentInputs.vNormalW);\n let _rsDp1 = dpdx(_rsP);\n let _rsDp2 = dpdy(_rsP);\n let _rsDuv1 = dpdx(fragmentInputs.vRuntimeSkinUV);\n let _rsDuv2 = dpdy(fragmentInputs.vRuntimeSkinUV);\n let _rsDp2perp = cross(_rsDp2, _rsN);\n let _rsDp1perp = cross(_rsN, _rsDp1);\n let _rsT = _rsDp2perp * _rsDuv1.x + _rsDp1perp * _rsDuv2.x;\n let _rsB = _rsDp2perp * _rsDuv1.y + _rsDp1perp * _rsDuv2.y;\n let _rsInvMax = inverseSqrt(max(dot(_rsT, _rsT), dot(_rsB, _rsB)));\n let _rsTcol = _rsT * _rsInvMax;\n let _rsBcol = _rsB * _rsInvMax;\n normalW = normalize(_rsTcol * _rsNormalTS.x + _rsBcol * _rsNormalTS.y + _rsN * _rsNormalTS.z);\n }\n #endif\n "},n._zeroV3=BABYLON.Vector3.Zero(),n._oneV3=BABYLON.Vector3.One(),n}(e.CustomShaderMaterialPlugin);e.VertexAnimationMaterialPlugin=i,e.SceneManager.RegisterClass("TOOLKIT.VertexAnimationController",n),e.SceneManager.RegisterClass("TOOLKIT.VertexAnimationMaterial",t),e.SceneManager.RegisterClass("TOOLKIT.VertexAnimationMaterialPlugin",i)}(i||(i={})),function(e){var t,n,i,r;(r=e.DragDirection||(e.DragDirection={}))[r.None=0]="None",r[r.Up=1]="Up",r[r.Down=2]="Down",r[r.Right=3]="Right",r[r.Left=4]="Left",(i=e.PinchZoomState||(e.PinchZoomState={}))[i.None=0]="None",i[i.ZoomIn=1]="ZoomIn",i[i.ZoomOut=2]="ZoomOut",(n=e.MouseButtonMode||(e.MouseButtonMode={}))[n.Pan=0]="Pan",n[n.Look=1]="Look",n[n.Move=2]="Move",(t=e.TouchMouseButton||(e.TouchMouseButton={}))[t.Any=-1]="Any",t[t.Left=0]="Left",t[t.Right=1]="Right";var o=function(){function t(){}return t.GetMouseButtonsDown=function(){return e.InputController.mouseButtonsDown},t.GetLeftButtonDown=function(){return e.InputController.leftButtonDown},t.GetMiddleButtonDown=function(){return e.InputController.middleButtonDown},t.GetRightButtonDown=function(){return e.InputController.rightButtonDown},t.GetMouseDownTarget=function(){return e.InputController.mouseDownTarget},t.GetMouseDragTarget=function(){return e.InputController.mouseDragTarget},t.GetPinchZoomState=function(){return e.InputController.pinchZoomState},t.EnableUserInput=function(t,n,i){void 0===i&&(i=null),e.InputController.ConfigureUserInput(t,n,i)},t.ConfigureUserInput=function(t,n,i){void 0===i&&(i=null);var r=null==i||null==i.contextMenu||i.contextMenu,o=null!=i&&null!=i.pointerLock&&i.pointerLock,a=null!=i&&null!=i.preventDefault&&i.preventDefault,s=null!=i&&null!=i.useCapture&&i.useCapture;if(e.InputController.resetUserInput(),!e.InputController.input){document.documentElement.tabIndex=1,document.documentElement.addEventListener("keyup",e.InputController.inputKeyUpHandler,s),document.documentElement.addEventListener("pointerup",e.InputController.inputPointerUpHandler,s),document.documentElement.addEventListener("pointerout",e.InputController.inputPointerUpHandler,s),document.documentElement.addEventListener("pointerleave",e.InputController.inputPointerUpHandler,s),document.documentElement.addEventListener("pointercancel",e.InputController.inputPointerUpHandler,s);var l=document.getElementById("renderingCanvas")||t.getRenderingCanvas();null!=l&&(l.oncontextmenu=!0===r?null:function(e){e.preventDefault(),e.stopPropagation()}),!0===e.UserInputOptions.UseCanvasElement?(l.tabIndex=2,l.addEventListener("focusout",e.InputController.resetKeyMapHandler,s),l.addEventListener("keydown",e.InputController.inputKeyDownHandler,s),l.addEventListener("pointerdown",e.InputController.inputPointerDownHandler,s),l.addEventListener("pointermove",e.InputController.inputPointerMoveHandler,s),l.addEventListener("onwheel"in document?"wheel":"mousewheel",e.InputController.inputPointerWheelHandler,s)):(document.documentElement.addEventListener("focusout",e.InputController.resetKeyMapHandler,s),document.documentElement.addEventListener("keydown",e.InputController.inputKeyDownHandler,s),document.documentElement.addEventListener("pointerdown",e.InputController.inputPointerDownHandler,s),document.documentElement.addEventListener("pointermove",e.InputController.inputPointerMoveHandler,s),document.documentElement.addEventListener("onwheel"in document?"wheel":"mousewheel",e.InputController.inputPointerWheelHandler,s)),e.InputController.preventDefault=a,null==e.InputController.GamepadManager&&(e.InputController.GamepadManager=new BABYLON.GamepadManager,e.InputController.GamepadManager.onGamepadConnectedObservable.add(e.InputController.inputManagerGamepadConnected),e.InputController.GamepadManager.onGamepadDisconnectedObservable.add(e.InputController.inputManagerGamepadDisconnected)),e.InputController.input=!0,document.documentElement.focus(),!0===o&&e.InputController.LockMousePointer(n,!0)}n.registerAfterRender(function(){e.InputController.updateUserInput(n)})},t.SetLeftJoystickBuffer=function(t,n,i){void 0===i&&(i=!0),e.InputController.j_horizontal=t,e.InputController.j_vertical=!0===i?-n:n},t.SetRightJoystickBuffer=function(t,n,i){void 0===i&&(i=!0),e.InputController.j_mousex=t,e.InputController.j_mousey=!0===i?-n:n},t.DisableUserInput=function(t,n){void 0===n&&(n=!1),e.InputController.LockMousePointer(t,!1),e.InputController.resetUserInput()},t.LockMousePointer=function(t,n){!0===n?e.InputController.LockMousePointerObserver=t.onPointerObservable.add(function(n,i){var r;n.type==BABYLON.PointerEventTypes.POINTERDOWN&&(document.pointerLockElement||null===(r=e.SceneManager.GetEngine(t))||void 0===r||r.enterPointerlock())}):e.InputController.IsPointerLockHandled()&&(t.onPointerObservable.remove(e.InputController.LockMousePointerObserver),e.InputController.LockMousePointerObserver=null)},t.IsPointerLocked=function(){return e.InputController.PointerLockedFlag},t.IsPointerLockHandled=function(){return null!=e.InputController.LockMousePointerObserver},t.GetUserInput=function(t,n){void 0===n&&(n=e.PlayerNumber.One);var i=0;if(e.InputController.input)switch(t){case e.UserInputAxis.Vertical:case e.UserInputAxis.Horizontal:i=n===e.PlayerNumber.Four?t===e.UserInputAxis.Horizontal?e.InputController.horizontal4:e.InputController.vertical4:n===e.PlayerNumber.Three?t===e.UserInputAxis.Horizontal?e.InputController.horizontal3:e.InputController.vertical3:n===e.PlayerNumber.Two?t===e.UserInputAxis.Horizontal?e.InputController.horizontal2:e.InputController.vertical2:t===e.UserInputAxis.Horizontal?e.InputController.horizontal:e.InputController.vertical;break;case e.UserInputAxis.MouseX:case e.UserInputAxis.MouseY:i=n===e.PlayerNumber.Four?t===e.UserInputAxis.MouseX?e.InputController.mousex4:e.InputController.mousey4:n===e.PlayerNumber.Three?t===e.UserInputAxis.MouseX?e.InputController.mousex3:e.InputController.mousey3:n===e.PlayerNumber.Two?t===e.UserInputAxis.MouseX?e.InputController.mousex2:e.InputController.mousey2:t===e.UserInputAxis.MouseX?e.InputController.mousex:e.InputController.mousey;break;case e.UserInputAxis.Wheel:n===e.PlayerNumber.One&&(i=e.InputController.wheel)}return i},t.OnKeyboardUp=function(t){e.InputController.input&&e.InputController.keyButtonUp.push(t)},t.OnKeyboardDown=function(t){e.InputController.input&&e.InputController.keyButtonDown.push(t)},t.OnKeyboardPress=function(t,n){e.InputController.input&&e.InputController.keyButtonPress.push({index:t,action:n})},t.GetKeyboardInput=function(t){var n=!1;if(e.InputController.input){var i="k:"+t.toString();if(null!=e.InputController.keymap[i]){var r=e.InputController.keymap[i];n=null!=r.result&&r.result}}return n},t.IsKeyboardButtonHeld=function(t){var n=!1;if(e.InputController.input){var i="k:"+t.toString();if(null!=e.InputController.keymap[i]){var r=e.InputController.keymap[i];null!=r.pressTime&&null!=r.releaseTime&&!0===(null!=r.result&&r.result)&&r.pressTime>0&&0===r.releaseTime&&(n=e.SceneManager.GetTimeMs()-r.pressTime>=e.InputController.TAP_THRESHOLD_MS)}}return n},t.WasKeyboardButtonTapped=function(t,n){void 0===n&&(n=!0);var i=!1;if(e.InputController.input){var r="k:"+t.toString();if(null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];null!=o.pressTime&&null!=o.releaseTime&&!1===(null!=o.result&&o.result)&&o.pressTime>0&&o.releaseTime>0&&(i=o.releaseTime-o.pressTime<e.InputController.TAP_THRESHOLD_MS)}!0===n&&e.InputController.ResetKeyboardButtonTapped(t)}return i},t.ResetKeyboardButtonTapped=function(t){if(e.InputController.input){var n="k:"+t.toString();null!=e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0})}},t.OnPointerUp=function(t){e.InputController.input&&e.InputController.mouseButtonUp.push(t)},t.OnPointerDown=function(t){e.InputController.input&&e.InputController.mouseButtonDown.push(t)},t.OnPointerPress=function(t,n){e.InputController.input&&e.InputController.mouseButtonPress.push({index:t,action:n})},t.GetPointerInput=function(t){var n=!1;if(e.InputController.input){var i="p:"+t.toString();if(null!=e.InputController.keymap[i]){var r=e.InputController.keymap[i];n=null!=r.result&&r.result}}return n},t.IsPointerButtonHeld=function(t){var n=!1;if(e.InputController.input){var i="p:"+t.toString();if(null!=e.InputController.keymap[i]){var r=e.InputController.keymap[i];null!=r.pressTime&&null!=r.releaseTime&&!0===(null!=r.result&&r.result)&&r.pressTime>0&&0===r.releaseTime&&(n=e.SceneManager.GetTimeMs()-r.pressTime>=e.InputController.TAP_THRESHOLD_MS)}}return n},t.WasPointerButtonTapped=function(t,n){void 0===n&&(n=!0);var i=!1;if(e.InputController.input){var r="p:"+t.toString();if(null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];null!=o.pressTime&&null!=o.releaseTime&&!1===(null!=o.result&&o.result)&&o.pressTime>0&&o.releaseTime>0&&(i=o.releaseTime-o.pressTime<e.InputController.TAP_THRESHOLD_MS)}!0===n&&e.InputController.ResetPointerButtonTapped(t)}return i},t.ResetPointerButtonTapped=function(t){if(e.InputController.input){var n="p:"+t.toString();null!=e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0})}},t.GetPointerDragDirection=function(t,n,i){return!0===i?0===t&&0===n||(Math.abs(t)>Math.abs(n)?t>0?e.InputController.dragDirection=e.DragDirection.Right:t<0&&(e.InputController.dragDirection=e.DragDirection.Left):n>0?e.InputController.dragDirection=e.DragDirection.Up:n<0&&(e.InputController.dragDirection=e.DragDirection.Down)):e.InputController.dragDirection=e.DragDirection.None,e.InputController.dragDirection},t.ResetPinchZoomTracking=function(){e.InputController.pinchZoomState=0,e.InputController.pinchZoomEvents=[],e.InputController.pinchZoomDistance=null},t.GetMousePosition=function(t,n){void 0===n&&(n=!1);var i=e.InputController.IsPointerLocked(),r=i?e.InputController.virtualClientX:e.InputController.lastClientX||0,o=i?e.InputController.virtualClientY:e.InputController.lastClientY||0,a=t.getEngine().getRenderingCanvas();if(a){var s=a.getBoundingClientRect(),l=r-s.left,u=o-s.top;if(!0===n){var c=s.height-u;e.InputController.LastMousePosition.set(l,c,0)}else e.InputController.LastMousePosition.set(l,u,0);return e.InputController.LastMousePosition}return!0===n?e.InputController.LastMousePosition.set(r,window.innerHeight-o,0):e.InputController.LastMousePosition.set(r,o,0),e.InputController.LastMousePosition},t.IsWheelScrolling=function(){return 0!==e.InputController.scroll},t.OnGamepadButtonUp=function(t,n){if(void 0===n&&(n=e.PlayerNumber.One),e.InputController.input)switch(n){case e.PlayerNumber.One:e.InputController.gamepad1ButtonUp.push(t);break;case e.PlayerNumber.Two:e.InputController.gamepad2ButtonUp.push(t);break;case e.PlayerNumber.Three:e.InputController.gamepad3ButtonUp.push(t);break;case e.PlayerNumber.Four:e.InputController.gamepad4ButtonUp.push(t)}},t.OnGamepadButtonDown=function(t,n){if(void 0===n&&(n=e.PlayerNumber.One),e.InputController.input)switch(n){case e.PlayerNumber.One:e.InputController.gamepad1ButtonDown.push(t);break;case e.PlayerNumber.Two:e.InputController.gamepad2ButtonDown.push(t);break;case e.PlayerNumber.Three:e.InputController.gamepad3ButtonDown.push(t);break;case e.PlayerNumber.Four:e.InputController.gamepad4ButtonDown.push(t)}},t.OnGamepadButtonPress=function(t,n,i){if(void 0===i&&(i=e.PlayerNumber.One),e.InputController.input)switch(i){case e.PlayerNumber.One:e.InputController.gamepad1ButtonPress.push({index:t,action:n});break;case e.PlayerNumber.Two:e.InputController.gamepad2ButtonPress.push({index:t,action:n});break;case e.PlayerNumber.Three:e.InputController.gamepad3ButtonPress.push({index:t,action:n});break;case e.PlayerNumber.Four:e.InputController.gamepad4ButtonPress.push({index:t,action:n})}},t.GetGamepadButtonInput=function(t,n){void 0===n&&(n=e.PlayerNumber.One);var i=!1;if(e.InputController.input){var r=null;switch(n){case e.PlayerNumber.One:r="b1:"+t.toString();break;case e.PlayerNumber.Two:r="b2:"+t.toString();break;case e.PlayerNumber.Three:r="b3:"+t.toString();break;case e.PlayerNumber.Four:r="b4:"+t.toString()}if(null!=r&&null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];i=null!=o.result&&o.result}}return i},t.IsGamepadButtonHeld=function(t,n){void 0===n&&(n=e.PlayerNumber.One);var i=!1;if(e.InputController.input){var r=null;switch(n){case e.PlayerNumber.One:r="b1:"+t.toString();break;case e.PlayerNumber.Two:r="b2:"+t.toString();break;case e.PlayerNumber.Three:r="b3:"+t.toString();break;case e.PlayerNumber.Four:r="b4:"+t.toString()}if(null!=r&&null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];null!=o.pressTime&&null!=o.releaseTime&&!0===(null!=o.result&&o.result)&&o.pressTime>0&&0===o.releaseTime&&(i=e.SceneManager.GetTimeMs()-o.pressTime>=e.InputController.TAP_THRESHOLD_MS)}}return i},t.IsGamepadButtonTapped=function(t,n){void 0===n&&(n=e.PlayerNumber.One);var i=!1;if(e.InputController.input){var r=null;switch(n){case e.PlayerNumber.One:r="b1:"+t.toString();break;case e.PlayerNumber.Two:r="b2:"+t.toString();break;case e.PlayerNumber.Three:r="b3:"+t.toString();break;case e.PlayerNumber.Four:r="b4:"+t.toString()}if(null!=r&&null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];null!=o.pressTime&&null!=o.releaseTime&&!1===(null!=o.result&&o.result)&&o.pressTime>0&&o.releaseTime>0&&(i=o.releaseTime-o.pressTime<e.InputController.TAP_THRESHOLD_MS)}}return i},t.ResetGamepadButtonTapped=function(t,n){if(void 0===n&&(n=e.PlayerNumber.One),e.InputController.input){var i=null;switch(n){case e.PlayerNumber.One:i="b1:"+t.toString();break;case e.PlayerNumber.Two:i="b2:"+t.toString();break;case e.PlayerNumber.Three:i="b3:"+t.toString();break;case e.PlayerNumber.Four:i="b4:"+t.toString()}null!=i&&null!=e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0})}},t.OnGamepadDirectionUp=function(t,n){if(void 0===n&&(n=e.PlayerNumber.One),e.InputController.input)switch(n){case e.PlayerNumber.One:e.InputController.gamepad1DpadUp.push(t);break;case e.PlayerNumber.Two:e.InputController.gamepad2DpadUp.push(t);break;case e.PlayerNumber.Three:e.InputController.gamepad3DpadUp.push(t);break;case e.PlayerNumber.Four:e.InputController.gamepad4DpadUp.push(t)}},t.OnGamepadDirectionDown=function(t,n){if(void 0===n&&(n=e.PlayerNumber.One),e.InputController.input)switch(n){case e.PlayerNumber.One:e.InputController.gamepad1DpadDown.push(t);break;case e.PlayerNumber.Two:e.InputController.gamepad2DpadDown.push(t);break;case e.PlayerNumber.Three:e.InputController.gamepad3DpadDown.push(t);break;case e.PlayerNumber.Four:e.InputController.gamepad4DpadDown.push(t)}},t.OnGamepadDirectionPress=function(t,n,i){if(void 0===i&&(i=e.PlayerNumber.One),e.InputController.input)switch(i){case e.PlayerNumber.One:e.InputController.gamepad1DpadPress.push({index:t,action:n});break;case e.PlayerNumber.Two:e.InputController.gamepad2DpadPress.push({index:t,action:n});break;case e.PlayerNumber.Three:e.InputController.gamepad3DpadPress.push({index:t,action:n});break;case e.PlayerNumber.Four:e.InputController.gamepad4DpadPress.push({index:t,action:n})}},t.GetGamepadDirectionInput=function(t,n){void 0===n&&(n=e.PlayerNumber.One);var i=!1;if(e.InputController.input){var r=null;switch(n){case e.PlayerNumber.One:r="d1:"+t.toString();break;case e.PlayerNumber.Two:r="d2:"+t.toString();break;case e.PlayerNumber.Three:r="d3:"+t.toString();break;case e.PlayerNumber.Four:r="d4:"+t.toString()}if(null!=r&&null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];i=null!=o.result&&o.result}}return i},t.IsGamepadDirectionHeld=function(t,n){void 0===n&&(n=e.PlayerNumber.One);var i=!1;if(e.InputController.input){var r=null;switch(n){case e.PlayerNumber.One:r="d1:"+t.toString();break;case e.PlayerNumber.Two:r="d2:"+t.toString();break;case e.PlayerNumber.Three:r="d3:"+t.toString();break;case e.PlayerNumber.Four:r="d4:"+t.toString()}if(null!=r&&null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];null!=o.pressTime&&null!=o.releaseTime&&!0===(null!=o.result&&o.result)&&o.pressTime>0&&0===o.releaseTime&&(i=e.SceneManager.GetTimeMs()-o.pressTime>=e.InputController.TAP_THRESHOLD_MS)}}return i},t.IsGamepadDirectionTapped=function(t,n){void 0===n&&(n=e.PlayerNumber.One);var i=!1;if(e.InputController.input){var r=null;switch(n){case e.PlayerNumber.One:r="d1:"+t.toString();break;case e.PlayerNumber.Two:r="d2:"+t.toString();break;case e.PlayerNumber.Three:r="d3:"+t.toString();break;case e.PlayerNumber.Four:r="d4:"+t.toString()}if(null!=r&&null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];null!=o.pressTime&&null!=o.releaseTime&&!1===(null!=o.result&&o.result)&&o.pressTime>0&&o.releaseTime>0&&(i=o.releaseTime-o.pressTime<e.InputController.TAP_THRESHOLD_MS)}}return i},t.ResetGamepadDirectionTapped=function(t,n){if(void 0===n&&(n=e.PlayerNumber.One),e.InputController.input){var i=null;switch(n){case e.PlayerNumber.One:i="d1:"+t.toString();break;case e.PlayerNumber.Two:i="d2:"+t.toString();break;case e.PlayerNumber.Three:i="d3:"+t.toString();break;case e.PlayerNumber.Four:i="d4:"+t.toString()}null!=i&&null!=e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0})}},t.OnGamepadTriggerLeft=function(t,n){if(void 0===n&&(n=e.PlayerNumber.One),e.InputController.input)switch(n){case e.PlayerNumber.One:e.InputController.gamepad1LeftTrigger.push(t);break;case e.PlayerNumber.Two:e.InputController.gamepad2LeftTrigger.push(t);break;case e.PlayerNumber.Three:e.InputController.gamepad3LeftTrigger.push(t);break;case e.PlayerNumber.Four:e.InputController.gamepad4LeftTrigger.push(t)}},t.OnGamepadTriggerRight=function(t,n){if(void 0===n&&(n=e.PlayerNumber.One),e.InputController.input)switch(n){case e.PlayerNumber.One:e.InputController.gamepad1RightTrigger.push(t);break;case e.PlayerNumber.Two:e.InputController.gamepad2RightTrigger.push(t);break;case e.PlayerNumber.Three:e.InputController.gamepad3RightTrigger.push(t);break;case e.PlayerNumber.Four:e.InputController.gamepad4RightTrigger.push(t)}},t.GetGamepadTriggerInput=function(t,n){void 0===n&&(n=e.PlayerNumber.One);var i=0;if(e.InputController.input){var r=null;switch(n){case e.PlayerNumber.One:r="t1:"+t.toString();break;case e.PlayerNumber.Two:r="t2:"+t.toString();break;case e.PlayerNumber.Three:r="t3:"+t.toString();break;case e.PlayerNumber.Four:r="t4:"+t.toString()}if(null!=r&&null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];i=null!=o.result?o.result:0}}return i},t.IsGamepadTriggerHeld=function(t,n){void 0===n&&(n=e.PlayerNumber.One);var i=!1;if(e.InputController.input){var r=null;switch(n){case e.PlayerNumber.One:r="t1:"+t.toString();break;case e.PlayerNumber.Two:r="t2:"+t.toString();break;case e.PlayerNumber.Three:r="t3:"+t.toString();break;case e.PlayerNumber.Four:r="t4:"+t.toString()}if(null!=r&&null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];null!=o.pressTime&&null!=o.releaseTime&&!0===(null!=o.result&&o.result)&&o.pressTime>0&&0===o.releaseTime&&(i=e.SceneManager.GetTimeMs()-o.pressTime>=e.InputController.TAP_THRESHOLD_MS)}}return i},t.IsGamepadTriggerTapped=function(t,n){void 0===n&&(n=e.PlayerNumber.One);var i=!1;if(e.InputController.input){var r=null;switch(n){case e.PlayerNumber.One:r="t1:"+t.toString();break;case e.PlayerNumber.Two:r="t2:"+t.toString();break;case e.PlayerNumber.Three:r="t3:"+t.toString();break;case e.PlayerNumber.Four:r="t4:"+t.toString()}if(null!=r&&null!=e.InputController.keymap[r]){var o=e.InputController.keymap[r];null!=o.pressTime&&null!=o.releaseTime&&!1===(null!=o.result&&o.result)&&o.pressTime>0&&o.releaseTime>0&&(i=o.releaseTime-o.pressTime<e.InputController.TAP_THRESHOLD_MS)}}return i},t.ResetGamepadTriggerTapped=function(t,n){if(void 0===n&&(n=e.PlayerNumber.One),e.InputController.input){var i=null;switch(n){case e.PlayerNumber.One:i="t1:"+t.toString();break;case e.PlayerNumber.Two:i="t2:"+t.toString();break;case e.PlayerNumber.Three:i="t3:"+t.toString();break;case e.PlayerNumber.Four:i="t4:"+t.toString()}null!=i&&null!=e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0})}},t.GetGamepadType=function(t){void 0===t&&(t=e.PlayerNumber.One);var n=e.GamepadType.None;if(e.InputController.input)switch(t){case e.PlayerNumber.One:n=e.InputController.gamepad1Type;break;case e.PlayerNumber.Two:n=e.InputController.gamepad2Type;break;case e.PlayerNumber.Three:n=e.InputController.gamepad3Type;break;case e.PlayerNumber.Four:n=e.InputController.gamepad4Type}return n},t.GetGamepad=function(t){void 0===t&&(t=e.PlayerNumber.One);var n=null;if(e.InputController.input)switch(t){case e.PlayerNumber.One:n=e.InputController.gamepad1;break;case e.PlayerNumber.Two:n=e.InputController.gamepad2;break;case e.PlayerNumber.Three:n=e.InputController.gamepad3;break;case e.PlayerNumber.Four:n=e.InputController.gamepad4}return n},t.InputKeyDownHandler=function(t,n){if(void 0===n&&(n=null),null==t||!1===e.SceneManager.EnableUserInput)return!1;n&&n.preventDefault();var i="k:"+t.toString(),r=!1;if(null==e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[i]){var o=e.InputController.keymap[i];!1===(r=null!=o.result&&o.result)&&(o.result=!0,o.pressTime=e.SceneManager.GetTimeMs(),o.releaseTime=0)}return null!=e.InputController.keyButtonDown&&e.InputController.keyButtonDown.length>0&&e.InputController.keyButtonDown.forEach(function(e){e(t)}),r||null!=e.InputController.keyButtonPress&&e.InputController.keyButtonPress.length>0&&e.InputController.keyButtonPress.forEach(function(e){e.index===t&&e.action()}),!0},t.InputKeyUpHandler=function(t,n){if(void 0===n&&(n=null),null==t||!1===e.SceneManager.EnableUserInput)return!1;var i="k:"+t.toString();if(null!=e.InputController.keymap[i]){var r=e.InputController.keymap[i];!0===(null!=r.result&&r.result)&&(r.result=!1,r.releaseTime=e.SceneManager.GetTimeMs())}return null!=e.InputController.keyButtonUp&&e.InputController.keyButtonUp.length>0&&e.InputController.keyButtonUp.forEach(function(e){e(t)}),!0},t.tickKeyboardInput=function(t){if(!1!==e.SceneManager.EnableUserInput){var n=e.InputController.GetKeyboardInput(e.UserInputKey.W)||e.InputController.GetKeyboardInput(e.UserInputKey.UpArrow),i=e.InputController.GetKeyboardInput(e.UserInputKey.A),r=e.InputController.GetKeyboardInput(e.UserInputKey.S)||e.InputController.GetKeyboardInput(e.UserInputKey.DownArrow),o=e.InputController.GetKeyboardInput(e.UserInputKey.D),a=e.InputController.GetKeyboardInput(e.UserInputKey.LeftArrow),s=e.InputController.GetKeyboardInput(e.UserInputKey.RightArrow);e.InputController.k_vertical=!0===n?e.Utilities.GetKeyboardInputValue(t,e.InputController.k_vertical,1):!0===r?e.Utilities.GetKeyboardInputValue(t,e.InputController.k_vertical,-1):0,!0===e.UserInputOptions.UseArrowKeyRotation?(e.InputController.k_horizontal=!0===o?e.Utilities.GetKeyboardInputValue(t,e.InputController.k_horizontal,1):!0===i?e.Utilities.GetKeyboardInputValue(t,e.InputController.k_horizontal,-1):0,e.InputController.a_mousex=!0===s?1*e.UserInputOptions.KeyboardArrowSensibility:!0===a?-1*e.UserInputOptions.KeyboardArrowSensibility:0):e.InputController.k_horizontal=!0===o||!0===s?e.Utilities.GetKeyboardInputValue(t,e.InputController.k_horizontal,1):!0===i||!0===a?e.Utilities.GetKeyboardInputValue(t,e.InputController.k_horizontal,-1):0}},t.updateUserInput=function(t){var n=e.InputController.GetMouseButtonsDown();e.InputController.leftButtonDown=!(1&~n),e.InputController.middleButtonDown=!(4&~n),e.InputController.rightButtonDown=!(2&~n),!1!==e.SceneManager.EnableUserInput&&(e.InputController.PointerLockedFlag=t.getEngine().isPointerLock,e.InputController.tickKeyboardInput(t),e.InputController.x_horizontal=0,e.InputController.x_vertical=0,e.InputController.x_mousex=0,e.InputController.x_mousey=0,0!==e.InputController.j_horizontal?e.InputController.x_horizontal=e.InputController.j_horizontal:0!==e.InputController.g_horizontal1?e.InputController.x_horizontal=e.InputController.g_horizontal1:0!==e.InputController.k_horizontal&&(e.InputController.x_horizontal=e.InputController.k_horizontal),0!==e.InputController.j_vertical?e.InputController.x_vertical=e.InputController.j_vertical:0!==e.InputController.g_vertical1?e.InputController.x_vertical=e.InputController.g_vertical1:0!==e.InputController.k_vertical&&(e.InputController.x_vertical=e.InputController.k_vertical),0!==e.InputController.j_mousex?e.InputController.x_mousex=e.InputController.j_mousex:0!==e.InputController.g_mousex1?e.InputController.x_mousex=e.InputController.g_mousex1:0!==e.InputController.a_mousex?e.InputController.x_mousex=e.InputController.a_mousex:0!==e.InputController.k_mousex&&(e.InputController.x_mousex=e.InputController.k_mousex),0!==e.InputController.j_mousey?e.InputController.x_mousey=e.InputController.j_mousey:0!==e.InputController.g_mousey1?e.InputController.x_mousey=e.InputController.g_mousey1:0!==e.InputController.k_mousey&&(e.InputController.x_mousey=e.InputController.k_mousey),e.InputController.horizontal=e.InputController.x_horizontal,e.InputController.vertical=e.InputController.x_vertical,e.InputController.mousex=e.InputController.x_mousex,e.InputController.mousey=e.InputController.x_mousey,e.InputController.scroll=e.InputController.x_scroll,e.InputController.wheel=e.InputController.x_wheel,e.InputController.horizontal2=e.InputController.g_horizontal2,e.InputController.vertical2=e.InputController.g_vertical2,e.InputController.mousex2=e.InputController.g_mousex2,e.InputController.mousey2=e.InputController.g_mousey2,e.InputController.horizontal3=e.InputController.g_horizontal3,e.InputController.vertical3=e.InputController.g_vertical3,e.InputController.mousex3=e.InputController.g_mousex3,e.InputController.mousey3=e.InputController.g_mousey3,e.InputController.horizontal4=e.InputController.g_horizontal4,e.InputController.vertical4=e.InputController.g_vertical4,e.InputController.mousex4=e.InputController.g_mousex4,e.InputController.mousey4=e.InputController.g_mousey4,e.InputController.k_mousex=0,e.InputController.k_mousey=0,e.InputController.x_mousey=0,e.InputController.x_scroll=0)},t.resetUserInput=function(){e.InputController.input=!1,e.InputController.keymap={},e.InputController.scroll=0,e.InputController.wheel=0,e.InputController.mousex=0,e.InputController.mousey=0,e.InputController.vertical=0,e.InputController.horizontal=0,e.InputController.mousex2=0,e.InputController.mousey2=0,e.InputController.vertical2=0,e.InputController.horizontal2=0,e.InputController.mousex3=0,e.InputController.mousey3=0,e.InputController.vertical3=0,e.InputController.horizontal3=0,e.InputController.mousex4=0,e.InputController.mousey4=0,e.InputController.vertical4=0,e.InputController.horizontal4=0,e.InputController.a_mousex=0,e.InputController.x_scroll=0,e.InputController.x_wheel=0,e.InputController.x_mousex=0,e.InputController.x_mousey=0,e.InputController.x_vertical=0,e.InputController.x_horizontal=0,e.InputController.k_mousex=0,e.InputController.k_mousey=0,e.InputController.k_vertical=0,e.InputController.k_horizontal=0,e.InputController.j_mousex=0,e.InputController.j_mousey=0,e.InputController.j_vertical=0,e.InputController.j_horizontal=0,e.InputController.g_mousex1=0,e.InputController.g_mousey1=0,e.InputController.g_vertical1=0,e.InputController.g_horizontal1=0,e.InputController.g_mousex2=0,e.InputController.g_mousey2=0,e.InputController.g_vertical2=0,e.InputController.g_horizontal2=0,e.InputController.g_mousex3=0,e.InputController.g_mousey3=0,e.InputController.g_vertical3=0,e.InputController.g_horizontal3=0,e.InputController.g_mousex4=0,e.InputController.g_mousey4=0,e.InputController.g_vertical4=0,e.InputController.g_horizontal4=0,e.InputController.dragDirection=0,e.InputController.pinchZoomState=0,e.InputController.pinchZoomEvents=[],e.InputController.pinchZoomDistance=null,e.InputController.preventDefault=!1,e.InputController.leftButtonDown=!1,e.InputController.middleButtonDown=!1,e.InputController.rightButtonDown=!1,e.InputController.mouseDownTarget=null,e.InputController.mouseDragTarget=null,e.InputController.mouseButtonsDown=0,e.InputController.mouseButtonUp=[],e.InputController.mouseButtonDown=[],e.InputController.mouseButtonPress=[],e.InputController.keyButtonUp=[],e.InputController.keyButtonDown=[],e.InputController.keyButtonPress=[],e.InputController.gamepad1ButtonUp=[],e.InputController.gamepad1ButtonDown=[],e.InputController.gamepad1ButtonPress=[],e.InputController.gamepad1DpadUp=[],e.InputController.gamepad1DpadDown=[],e.InputController.gamepad1DpadPress=[],e.InputController.gamepad1LeftTrigger=[],e.InputController.gamepad1RightTrigger=[],e.InputController.gamepad2ButtonUp=[],e.InputController.gamepad2ButtonDown=[],e.InputController.gamepad2ButtonPress=[],e.InputController.gamepad2DpadUp=[],e.InputController.gamepad2DpadDown=[],e.InputController.gamepad2DpadPress=[],e.InputController.gamepad2LeftTrigger=[],e.InputController.gamepad2RightTrigger=[],e.InputController.gamepad3ButtonUp=[],e.InputController.gamepad3ButtonDown=[],e.InputController.gamepad3ButtonPress=[],e.InputController.gamepad3DpadUp=[],e.InputController.gamepad3DpadDown=[],e.InputController.gamepad3DpadPress=[],e.InputController.gamepad3LeftTrigger=[],e.InputController.gamepad3RightTrigger=[],e.InputController.gamepad4ButtonUp=[],e.InputController.gamepad4ButtonDown=[],e.InputController.gamepad4ButtonPress=[],e.InputController.gamepad4DpadUp=[],e.InputController.gamepad4DpadDown=[],e.InputController.gamepad4DpadPress=[],e.InputController.gamepad4LeftTrigger=[],e.InputController.gamepad4RightTrigger=[],e.InputController.previousPosition=null,e.InputController.lastClientX=0,e.InputController.lastClientY=0,e.InputController.virtualClientX=0,e.InputController.virtualClientY=0},t.resetKeyMapHandler=function(t){e.InputController.keymap={}},t.getPinchZoomDistance=function(e,t){var n=t.clientX-e.clientX,i=t.clientY-e.clientY;return Math.sqrt(n*n+i*i)},t.cachePinchZoomPointer=function(t){!0===e.InputController.EnablePinchZoomTracking&&e.InputController.pinchZoomEvents.push(t)},t.removePinchZoomPointer=function(t){if(!0===e.InputController.EnablePinchZoomTracking){for(var n=0;n<e.InputController.pinchZoomEvents.length;n++)if(e.InputController.pinchZoomEvents[n].pointerId===t.pointerId){e.InputController.pinchZoomEvents.splice(n,1);break}e.InputController.pinchZoomEvents.length<2&&(e.InputController.pinchZoomDistance=null)}},t.processPinchZoomTracking=function(t){if(!0===e.InputController.EnablePinchZoomTracking){for(var n=0;n<e.InputController.pinchZoomEvents.length;n++)if(e.InputController.pinchZoomEvents[n].pointerId===t.pointerId){e.InputController.pinchZoomEvents[n]=t;break}if(e.InputController.pinchZoomState=e.PinchZoomState.None,2===e.InputController.pinchZoomEvents.length){var i=e.InputController.getPinchZoomDistance(e.InputController.pinchZoomEvents[0],e.InputController.pinchZoomEvents[1]);i!==e.InputController.pinchZoomDistance&&(i>e.InputController.pinchZoomDistance?e.InputController.pinchZoomState=e.PinchZoomState.ZoomIn:i<e.InputController.pinchZoomDistance&&(e.InputController.pinchZoomState=e.PinchZoomState.ZoomOut),e.InputController.pinchZoomDistance=i)}}},t.inputKeyDownHandler=function(t){return e.InputController.InputKeyDownHandler(t.keyCode,t)},t.inputKeyUpHandler=function(t){return e.InputController.InputKeyUpHandler(t.keyCode,t)},t.inputPointerWheelHandler=function(t){if(!1===e.SceneManager.EnableUserInput)return!1;var n=t.deltaY?-t.deltaY:t.wheelDelta/40;return e.InputController.x_scroll=1,e.InputController.x_wheel=Math.abs(n)>e.UserInputOptions.PointerWheelDeadZone?0+n:0,e.InputController.preventDefault&&t.preventDefault(),!0},t.inputPointerDownHandler=function(t){if(e.InputController.mouseDownTarget=t.target,e.InputController.mouseButtonsDown=t.buttons,e.InputController.lastClientX=t.clientX||0,e.InputController.lastClientY=t.clientY||0,e.InputController.virtualClientX=e.InputController.lastClientX,e.InputController.virtualClientY=e.InputController.lastClientY,e.InputController.cachePinchZoomPointer(t),!1===e.SceneManager.EnableUserInput)return!1;e.InputController.previousPosition={x:t.clientX,y:t.clientY};var n="p:"+t.button.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}return null!=e.InputController.mouseButtonDown&&e.InputController.mouseButtonDown.length>0&&e.InputController.mouseButtonDown.forEach(function(e){e(t.button)}),i||null!=e.InputController.mouseButtonPress&&e.InputController.mouseButtonPress.length>0&&e.InputController.mouseButtonPress.forEach(function(e){e.index===t.button&&e.action()}),e.InputController.preventDefault&&t.preventDefault(),!0},t.inputPointerUpHandler=function(t){if(e.InputController.mouseDownTarget=null,e.InputController.mouseDragTarget=null,e.InputController.mouseButtonsDown=t.buttons,e.InputController.lastClientX=t.clientX||0,e.InputController.lastClientY=t.clientY||0,e.InputController.virtualClientX=e.InputController.lastClientX,e.InputController.virtualClientY=e.InputController.lastClientY,e.InputController.removePinchZoomPointer(t),!1===e.SceneManager.EnableUserInput)return!1;e.InputController.previousPosition=null,e.InputController.k_mousex=0,e.InputController.k_mousey=0;var n="p:"+t.button.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}return null!=e.InputController.mouseButtonUp&&e.InputController.mouseButtonUp.length>0&&e.InputController.mouseButtonUp.forEach(function(e){e(t.button)}),e.InputController.preventDefault&&t.preventDefault(),!0},t.inputPointerMoveHandler=function(t){if(e.InputController.mouseDragTarget=t.target,e.InputController.mouseButtonsDown=t.buttons,e.InputController.lastClientX=t.clientX||0,e.InputController.lastClientY=t.clientY||0,e.InputController.IsPointerLocked()){var n=t.movementX||t.mozMovementX||t.webkitMovementX||t.msMovementX||0,i=t.movementY||t.mozMovementY||t.webkitMovementY||t.msMovementY||0;e.InputController.virtualClientX+=n,e.InputController.virtualClientY+=i}else e.InputController.virtualClientX=e.InputController.lastClientX,e.InputController.virtualClientY=e.InputController.lastClientY;if(e.InputController.processPinchZoomTracking(t),!1===e.SceneManager.EnableUserInput)return!1;if(!1===e.SceneManager.VirtualJoystickEnabled){var r=0,o=0;if(e.InputController.IsPointerLocked()?(r=t.movementX||t.mozMovementX||t.webkitMovementX||t.msMovementX||0,o=t.movementY||t.mozMovementY||t.webkitMovementY||t.msMovementY||0,e.InputController.previousPosition=null):null!=e.InputController.previousPosition&&(r=t.clientX-e.InputController.previousPosition.x,o=t.clientY-e.InputController.previousPosition.y,e.InputController.previousPosition={x:t.clientX,y:t.clientY}),!0===e.UserInputOptions.PointerMouseInverted&&(r*=-1,o*=-1),!0===e.InputController.rightHanded&&(r*=-1),!0===e.UserInputOptions.EnableBabylonRotation)e.InputController.k_mousex=r/e.UserInputOptions.BabylonAngularSensibility,e.InputController.k_mousey=o/e.UserInputOptions.BabylonAngularSensibility;else{var a=r*e.UserInputOptions.DefaultAngularSensibility*e.InputController.MOUSE_DAMPENER,s=o*e.UserInputOptions.DefaultAngularSensibility*e.InputController.MOUSE_DAMPENER;Math.abs(r)<=e.UserInputOptions.PointerMouseDeadZone&&(a=0),Math.abs(o)<=e.UserInputOptions.PointerMouseDeadZone&&(s=0),e.InputController.k_mousex+=a,e.InputController.k_mousey+=s,e.InputController.k_mousex=BABYLON.Scalar.Clamp(e.InputController.k_mousex,-1,1),e.InputController.k_mousey=BABYLON.Scalar.Clamp(e.InputController.k_mousey,-1,1)}}return e.InputController.preventDefault&&t.preventDefault(),!0},t.inputOneButtonDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad1){var n="b1:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad1ButtonDown&&e.InputController.gamepad1ButtonDown.length>0&&e.InputController.gamepad1ButtonDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad1ButtonPress&&e.InputController.gamepad1ButtonPress.length>0&&e.InputController.gamepad1ButtonPress.forEach(function(e){e.index===t&&e.action()})}},t.inputOneButtonUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad1){var n="b1:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad1ButtonUp&&e.InputController.gamepad1ButtonUp.length>0&&e.InputController.gamepad1ButtonUp.forEach(function(e){e(t)})}},t.inputOneXboxDPadDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad1){var n="d1:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad1DpadDown&&e.InputController.gamepad1DpadDown.length>0&&e.InputController.gamepad1DpadDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad1DpadPress&&e.InputController.gamepad1DpadPress.length>0&&e.InputController.gamepad1DpadPress.forEach(function(e){e.index===t&&e.action()})}},t.inputOneShockDPadDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad1){var n="d1:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad1DpadDown&&e.InputController.gamepad1DpadDown.length>0&&e.InputController.gamepad1DpadDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad1DpadPress&&e.InputController.gamepad1DpadPress.length>0&&e.InputController.gamepad1DpadPress.forEach(function(e){e.index===t&&e.action()})}},t.inputOneXboxDPadUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad1){var n="d1:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad1DpadUp&&e.InputController.gamepad1DpadUp.length>0&&e.InputController.gamepad1DpadUp.forEach(function(e){e(t)})}},t.inputOneShockDPadUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad1){var n="d1:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad1DpadUp&&e.InputController.gamepad1DpadUp.length>0&&e.InputController.gamepad1DpadUp.forEach(function(e){e(t)})}},t.inputOneXboxLeftTriggerHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad1){var n,i="t1:0";t>0?(null==e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[i]&&!1===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!0,n.pressTime=e.SceneManager.GetTimeMs(),n.releaseTime=0)):null!=e.InputController.keymap[i]&&!0===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!1,n.releaseTime=e.SceneManager.GetTimeMs()),null!=e.InputController.gamepad1LeftTrigger&&e.InputController.gamepad1LeftTrigger.length>0&&e.InputController.gamepad1LeftTrigger.forEach(function(e){e(t)})}},t.inputOneXboxRightTriggerHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad1){var n,i="t1:1";t>0?(null==e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[i]&&!1===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!0,n.pressTime=e.SceneManager.GetTimeMs(),n.releaseTime=0)):null!=e.InputController.keymap[i]&&!0===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!1,n.releaseTime=e.SceneManager.GetTimeMs()),null!=e.InputController.gamepad1RightTrigger&&e.InputController.gamepad1RightTrigger.length>0&&e.InputController.gamepad1RightTrigger.forEach(function(e){e(t)})}},t.inputOneLeftStickHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad1){var n=t,i=n.x*e.UserInputOptions.GamepadLStickSensibility,r=n.y*e.UserInputOptions.GamepadLStickSensibility;n.x=Math.abs(i)>e.UserInputOptions.GamepadDeadStickValue?i:0,n.y=Math.abs(r)>e.UserInputOptions.GamepadDeadStickValue?r:0,n.x=BABYLON.Scalar.Clamp(n.x,-1,1),n.y=BABYLON.Scalar.Clamp(n.y,-1,1),e.InputController.g_horizontal1=e.UserInputOptions.GamepadLStickXInverted?-n.x:n.x,e.InputController.g_vertical1=e.UserInputOptions.GamepadLStickYInverted?n.y:-n.y}},t.inputOneRightStickHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad1){var n=t,i=n.x*e.UserInputOptions.GamepadRStickSensibility,r=n.y*e.UserInputOptions.GamepadRStickSensibility;n.x=Math.abs(i)>e.UserInputOptions.GamepadDeadStickValue?i:0,n.y=Math.abs(r)>e.UserInputOptions.GamepadDeadStickValue?r:0,n.x=BABYLON.Scalar.Clamp(n.x,-1,1),n.y=BABYLON.Scalar.Clamp(n.y,-1,1),e.InputController.g_mousex1=e.UserInputOptions.GamepadRStickXInverted?-n.x:n.x,e.InputController.g_mousey1=e.UserInputOptions.GamepadRStickYInverted?-n.y:n.y}},t.inputTwoButtonDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad2){var n="b2:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad2ButtonDown&&e.InputController.gamepad2ButtonDown.length>0&&e.InputController.gamepad2ButtonDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad2ButtonPress&&e.InputController.gamepad2ButtonPress.length>0&&e.InputController.gamepad2ButtonPress.forEach(function(e){e.index===t&&e.action()})}},t.inputTwoButtonUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad2){var n="b2:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad2ButtonUp&&e.InputController.gamepad2ButtonUp.length>0&&e.InputController.gamepad2ButtonUp.forEach(function(e){e(t)})}},t.inputTwoXboxDPadDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad2){var n="d2:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad2DpadDown&&e.InputController.gamepad2DpadDown.length>0&&e.InputController.gamepad2DpadDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad2DpadPress&&e.InputController.gamepad2DpadPress.length>0&&e.InputController.gamepad2DpadPress.forEach(function(e){e.index===t&&e.action()})}},t.inputTwoShockDPadDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad2){var n="d2:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad2DpadDown&&e.InputController.gamepad2DpadDown.length>0&&e.InputController.gamepad2DpadDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad2DpadPress&&e.InputController.gamepad2DpadPress.length>0&&e.InputController.gamepad2DpadPress.forEach(function(e){e.index===t&&e.action()})}},t.inputTwoXboxDPadUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad2){var n="d2:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad2DpadUp&&e.InputController.gamepad2DpadUp.length>0&&e.InputController.gamepad2DpadUp.forEach(function(e){e(t)})}},t.inputTwoShockDPadUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad2){var n="d2:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad2DpadUp&&e.InputController.gamepad2DpadUp.length>0&&e.InputController.gamepad2DpadUp.forEach(function(e){e(t)})}},t.inputTwoXboxLeftTriggerHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad2){var n,i="t2:0";t>0?(null==e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[i]&&!1===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!0,n.pressTime=e.SceneManager.GetTimeMs(),n.releaseTime=0)):null!=e.InputController.keymap[i]&&!0===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!1,n.releaseTime=e.SceneManager.GetTimeMs()),null!=e.InputController.gamepad2LeftTrigger&&e.InputController.gamepad2LeftTrigger.length>0&&e.InputController.gamepad2LeftTrigger.forEach(function(e){e(t)})}},t.inputTwoXboxRightTriggerHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad2){var n,i="t2:1";t>0?(null==e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[i]&&!1===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!0,n.pressTime=e.SceneManager.GetTimeMs(),n.releaseTime=0)):null!=e.InputController.keymap[i]&&!0===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!1,n.releaseTime=e.SceneManager.GetTimeMs()),null!=e.InputController.gamepad2RightTrigger&&e.InputController.gamepad2RightTrigger.length>0&&e.InputController.gamepad2RightTrigger.forEach(function(e){e(t)})}},t.inputTwoLeftStickHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad2){var n=t,i=n.x*e.UserInputOptions.GamepadLStickSensibility,r=n.y*e.UserInputOptions.GamepadLStickSensibility;n.x=Math.abs(i)>e.UserInputOptions.GamepadDeadStickValue?i:0,n.y=Math.abs(r)>e.UserInputOptions.GamepadDeadStickValue?r:0,n.x=BABYLON.Scalar.Clamp(n.x,-1,1),n.y=BABYLON.Scalar.Clamp(n.y,-1,1),e.InputController.g_horizontal2=e.UserInputOptions.GamepadLStickXInverted?-n.x:n.x,e.InputController.g_vertical2=e.UserInputOptions.GamepadLStickYInverted?n.y:-n.y}},t.inputTwoRightStickHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad2){var n=t,i=n.x*e.UserInputOptions.GamepadRStickSensibility,r=n.y*e.UserInputOptions.GamepadRStickSensibility;n.x=Math.abs(i)>e.UserInputOptions.GamepadDeadStickValue?i:0,n.y=Math.abs(r)>e.UserInputOptions.GamepadDeadStickValue?r:0,n.x=BABYLON.Scalar.Clamp(n.x,-1,1),n.y=BABYLON.Scalar.Clamp(n.y,-1,1),e.InputController.g_mousex2=e.UserInputOptions.GamepadRStickXInverted?-n.x:n.x,e.InputController.g_mousey2=e.UserInputOptions.GamepadRStickYInverted?-n.y:n.y}},t.inputThreeButtonDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad3){var n="b3:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad3ButtonDown&&e.InputController.gamepad3ButtonDown.length>0&&e.InputController.gamepad3ButtonDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad3ButtonPress&&e.InputController.gamepad3ButtonPress.length>0&&e.InputController.gamepad3ButtonPress.forEach(function(e){e.index===t&&e.action()})}},t.inputThreeButtonUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad3){var n="b3:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad3ButtonUp&&e.InputController.gamepad3ButtonUp.length>0&&e.InputController.gamepad3ButtonUp.forEach(function(e){e(t)})}},t.inputThreeXboxDPadDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad3){var n="d3:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad3DpadDown&&e.InputController.gamepad3DpadDown.length>0&&e.InputController.gamepad3DpadDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad3DpadPress&&e.InputController.gamepad3DpadPress.length>0&&e.InputController.gamepad3DpadPress.forEach(function(e){e.index===t&&e.action()})}},t.inputThreeShockDPadDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad3){var n="d3:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad3DpadDown&&e.InputController.gamepad3DpadDown.length>0&&e.InputController.gamepad3DpadDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad3DpadPress&&e.InputController.gamepad3DpadPress.length>0&&e.InputController.gamepad3DpadPress.forEach(function(e){e.index===t&&e.action()})}},t.inputThreeXboxDPadUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad3){var n="d3:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad3DpadUp&&e.InputController.gamepad3DpadUp.length>0&&e.InputController.gamepad3DpadUp.forEach(function(e){e(t)})}},t.inputThreeShockDPadUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad3){var n="d3:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad3DpadUp&&e.InputController.gamepad3DpadUp.length>0&&e.InputController.gamepad3DpadUp.forEach(function(e){e(t)})}},t.inputThreeXboxLeftTriggerHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad3){var n,i="t3:0";t>0?(null==e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[i]&&!1===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!0,n.pressTime=e.SceneManager.GetTimeMs(),n.releaseTime=0)):null!=e.InputController.keymap[i]&&!0===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!1,n.releaseTime=e.SceneManager.GetTimeMs()),null!=e.InputController.gamepad3LeftTrigger&&e.InputController.gamepad3LeftTrigger.length>0&&e.InputController.gamepad3LeftTrigger.forEach(function(e){e(t)})}},t.inputThreeXboxRightTriggerHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad3){var n,i="t3:1";t>0?(null==e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[i]&&!1===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!0,n.pressTime=e.SceneManager.GetTimeMs(),n.releaseTime=0)):null!=e.InputController.keymap[i]&&!0===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!1,n.releaseTime=e.SceneManager.GetTimeMs()),null!=e.InputController.gamepad3RightTrigger&&e.InputController.gamepad3RightTrigger.length>0&&e.InputController.gamepad3RightTrigger.forEach(function(e){e(t)})}},t.inputThreeLeftStickHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad3){var n=t,i=n.x*e.UserInputOptions.GamepadLStickSensibility,r=n.y*e.UserInputOptions.GamepadLStickSensibility;n.x=Math.abs(i)>e.UserInputOptions.GamepadDeadStickValue?i:0,n.y=Math.abs(r)>e.UserInputOptions.GamepadDeadStickValue?r:0,n.x=BABYLON.Scalar.Clamp(n.x,-1,1),n.y=BABYLON.Scalar.Clamp(n.y,-1,1),e.InputController.g_horizontal3=e.UserInputOptions.GamepadLStickXInverted?-n.x:n.x,e.InputController.g_vertical3=e.UserInputOptions.GamepadLStickYInverted?n.y:-n.y}},t.inputThreeRightStickHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad3){var n=t,i=n.x*e.UserInputOptions.GamepadRStickSensibility,r=n.y*e.UserInputOptions.GamepadRStickSensibility;n.x=Math.abs(i)>e.UserInputOptions.GamepadDeadStickValue?i:0,n.y=Math.abs(r)>e.UserInputOptions.GamepadDeadStickValue?r:0,n.x=BABYLON.Scalar.Clamp(n.x,-1,1),n.y=BABYLON.Scalar.Clamp(n.y,-1,1),e.InputController.g_mousex3=e.UserInputOptions.GamepadRStickXInverted?-n.x:n.x,e.InputController.g_mousey3=e.UserInputOptions.GamepadRStickYInverted?-n.y:n.y}},t.inputFourButtonDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad4){var n="b4:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad4ButtonDown&&e.InputController.gamepad4ButtonDown.length>0&&e.InputController.gamepad4ButtonDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad4ButtonPress&&e.InputController.gamepad4ButtonPress.length>0&&e.InputController.gamepad4ButtonPress.forEach(function(e){e.index===t&&e.action()})}},t.inputFourButtonUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad4){var n="b4:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad4ButtonUp&&e.InputController.gamepad4ButtonUp.length>0&&e.InputController.gamepad4ButtonUp.forEach(function(e){e(t)})}},t.inputFourXboxDPadDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad4){var n="d4:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad4DpadDown&&e.InputController.gamepad4DpadDown.length>0&&e.InputController.gamepad4DpadDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad4DpadPress&&e.InputController.gamepad4DpadPress.length>0&&e.InputController.gamepad4DpadPress.forEach(function(e){e.index===t&&e.action()})}},t.inputFourShockDPadDownHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad4){var n="d4:"+t.toString(),i=!1;if(null==e.InputController.keymap[n]&&(e.InputController.keymap[n]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[n]){var r=e.InputController.keymap[n];!1===(i=null!=r.result&&r.result)&&(r.result=!0,r.pressTime=e.SceneManager.GetTimeMs(),r.releaseTime=0)}null!=e.InputController.gamepad4DpadDown&&e.InputController.gamepad4DpadDown.length>0&&e.InputController.gamepad4DpadDown.forEach(function(e){e(t)}),i||null!=e.InputController.gamepad4DpadPress&&e.InputController.gamepad4DpadPress.length>0&&e.InputController.gamepad4DpadPress.forEach(function(e){e.index===t&&e.action()})}},t.inputFourXboxDPadUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad4){var n="d4:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad4DpadUp&&e.InputController.gamepad4DpadUp.length>0&&e.InputController.gamepad4DpadUp.forEach(function(e){e(t)})}},t.inputFourShockDPadUpHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad4){var n="d4:"+t.toString();if(null!=e.InputController.keymap[n]){var i=e.InputController.keymap[n];!0===(null!=i.result&&i.result)&&(i.result=!1,i.releaseTime=e.SceneManager.GetTimeMs())}null!=e.InputController.gamepad4DpadUp&&e.InputController.gamepad4DpadUp.length>0&&e.InputController.gamepad4DpadUp.forEach(function(e){e(t)})}},t.inputFourXboxLeftTriggerHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad4){var n,i="t4:0";t>0?(null==e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[i]&&!1===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!0,n.pressTime=e.SceneManager.GetTimeMs(),n.releaseTime=0)):null!=e.InputController.keymap[i]&&!0===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!1,n.releaseTime=e.SceneManager.GetTimeMs()),null!=e.InputController.gamepad4LeftTrigger&&e.InputController.gamepad4LeftTrigger.length>0&&e.InputController.gamepad4LeftTrigger.forEach(function(e){e(t)})}},t.inputFourXboxRightTriggerHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad4){var n,i="t4:1";t>0?(null==e.InputController.keymap[i]&&(e.InputController.keymap[i]={result:!1,pressTime:0,releaseTime:0}),null!=e.InputController.keymap[i]&&!1===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!0,n.pressTime=e.SceneManager.GetTimeMs(),n.releaseTime=0)):null!=e.InputController.keymap[i]&&!0===(null!=(n=e.InputController.keymap[i]).result&&n.result)&&(n.result=!1,n.releaseTime=e.SceneManager.GetTimeMs()),null!=e.InputController.gamepad4RightTrigger&&e.InputController.gamepad4RightTrigger.length>0&&e.InputController.gamepad4RightTrigger.forEach(function(e){e(t)})}},t.inputFourLeftStickHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad4){var n=t,i=n.x*e.UserInputOptions.GamepadLStickSensibility,r=n.y*e.UserInputOptions.GamepadLStickSensibility;n.x=Math.abs(i)>e.UserInputOptions.GamepadDeadStickValue?i:0,n.y=Math.abs(r)>e.UserInputOptions.GamepadDeadStickValue?r:0,n.x=BABYLON.Scalar.Clamp(n.x,-1,1),n.y=BABYLON.Scalar.Clamp(n.y,-1,1),e.InputController.g_horizontal4=e.UserInputOptions.GamepadLStickXInverted?-n.x:n.x,e.InputController.g_vertical4=e.UserInputOptions.GamepadLStickYInverted?n.y:-n.y}},t.inputFourRightStickHandler=function(t){if(!1!==e.SceneManager.EnableUserInput&&null!=e.InputController.gamepad4){var n=t,i=n.x*e.UserInputOptions.GamepadRStickSensibility,r=n.y*e.UserInputOptions.GamepadRStickSensibility;n.x=Math.abs(i)>e.UserInputOptions.GamepadDeadStickValue?i:0,n.y=Math.abs(r)>e.UserInputOptions.GamepadDeadStickValue?r:0,n.x=BABYLON.Scalar.Clamp(n.x,-1,1),n.y=BABYLON.Scalar.Clamp(n.y,-1,1),e.InputController.g_mousex4=e.UserInputOptions.GamepadRStickXInverted?-n.x:n.x,e.InputController.g_mousey4=e.UserInputOptions.GamepadRStickYInverted?-n.y:n.y}},t.inputManagerGamepadConnected=function(t,n){if(null==e.InputController.gamepad1&&0===t.index)if(e.InputController.gamepad1=t,BABYLON.Tools.Log("Gamepad One Connected: "+e.InputController.gamepad1.id),e.InputController.gamepad1 instanceof BABYLON.Xbox360Pad){e.InputController.gamepad1Type=e.GamepadType.Xbox360;var i=e.InputController.gamepad1;i.onbuttonup(e.InputController.inputOneButtonUpHandler),i.onbuttondown(e.InputController.inputOneButtonDownHandler),i.onleftstickchanged(e.InputController.inputOneLeftStickHandler),i.onrightstickchanged(e.InputController.inputOneRightStickHandler),i.ondpadup(e.InputController.inputOneXboxDPadUpHandler),i.ondpaddown(e.InputController.inputOneXboxDPadDownHandler),i.onlefttriggerchanged(e.InputController.inputOneXboxLeftTriggerHandler),i.onrighttriggerchanged(e.InputController.inputOneXboxRightTriggerHandler)}else if(e.InputController.gamepad1 instanceof BABYLON.DualShockPad){e.InputController.gamepad1Type=e.GamepadType.DualShock;var r=e.InputController.gamepad1;r.onbuttonup(e.InputController.inputOneButtonUpHandler),r.onbuttondown(e.InputController.inputOneButtonDownHandler),r.onleftstickchanged(e.InputController.inputOneLeftStickHandler),r.onrightstickchanged(e.InputController.inputOneRightStickHandler),r.ondpadup(e.InputController.inputOneShockDPadUpHandler),r.ondpaddown(e.InputController.inputOneShockDPadDownHandler),r.onlefttriggerchanged(e.InputController.inputOneXboxLeftTriggerHandler),r.onrighttriggerchanged(e.InputController.inputOneXboxRightTriggerHandler)}else{e.InputController.gamepad1Type=e.GamepadType.Generic;var o=e.InputController.gamepad1;o.onbuttonup(e.InputController.inputOneButtonUpHandler),o.onbuttondown(e.InputController.inputOneButtonDownHandler),o.onleftstickchanged(e.InputController.inputOneLeftStickHandler),o.onrightstickchanged(e.InputController.inputOneRightStickHandler)}if(null==e.InputController.gamepad2&&1===t.index)if(e.InputController.gamepad2=t,BABYLON.Tools.Log("Gamepad Two Connected: "+e.InputController.gamepad2.id),e.InputController.gamepad2 instanceof BABYLON.Xbox360Pad){e.InputController.gamepad2Type=e.GamepadType.Xbox360;var a=e.InputController.gamepad2;a.onbuttonup(e.InputController.inputTwoButtonUpHandler),a.onbuttondown(e.InputController.inputTwoButtonDownHandler),a.onleftstickchanged(e.InputController.inputTwoLeftStickHandler),a.onrightstickchanged(e.InputController.inputTwoRightStickHandler),a.ondpadup(e.InputController.inputTwoXboxDPadUpHandler),a.ondpaddown(e.InputController.inputTwoXboxDPadDownHandler),a.onlefttriggerchanged(e.InputController.inputTwoXboxLeftTriggerHandler),a.onrighttriggerchanged(e.InputController.inputTwoXboxRightTriggerHandler)}else if(e.InputController.gamepad2 instanceof BABYLON.DualShockPad){e.InputController.gamepad2Type=e.GamepadType.DualShock;var s=e.InputController.gamepad2;s.onbuttonup(e.InputController.inputOneButtonUpHandler),s.onbuttondown(e.InputController.inputOneButtonDownHandler),s.onleftstickchanged(e.InputController.inputOneLeftStickHandler),s.onrightstickchanged(e.InputController.inputOneRightStickHandler),s.ondpadup(e.InputController.inputOneShockDPadUpHandler),s.ondpaddown(e.InputController.inputOneShockDPadDownHandler),s.onlefttriggerchanged(e.InputController.inputOneXboxLeftTriggerHandler),s.onrighttriggerchanged(e.InputController.inputOneXboxRightTriggerHandler)}else{e.InputController.gamepad2Type=e.GamepadType.Generic;var l=e.InputController.gamepad2;l.onbuttonup(e.InputController.inputTwoButtonUpHandler),l.onbuttondown(e.InputController.inputTwoButtonDownHandler),l.onleftstickchanged(e.InputController.inputTwoLeftStickHandler),l.onrightstickchanged(e.InputController.inputTwoRightStickHandler)}if(null==e.InputController.gamepad3&&2===t.index)if(e.InputController.gamepad3=t,BABYLON.Tools.Log("Gamepad Three Connected: "+e.InputController.gamepad3.id),e.InputController.gamepad3 instanceof BABYLON.Xbox360Pad){e.InputController.gamepad3Type=e.GamepadType.Xbox360;var u=e.InputController.gamepad3;u.onbuttonup(e.InputController.inputThreeButtonUpHandler),u.onbuttondown(e.InputController.inputThreeButtonDownHandler),u.onleftstickchanged(e.InputController.inputThreeLeftStickHandler),u.onrightstickchanged(e.InputController.inputThreeRightStickHandler),u.ondpadup(e.InputController.inputThreeXboxDPadUpHandler),u.ondpaddown(e.InputController.inputThreeXboxDPadDownHandler),u.onlefttriggerchanged(e.InputController.inputThreeXboxLeftTriggerHandler),u.onrighttriggerchanged(e.InputController.inputThreeXboxRightTriggerHandler)}else if(e.InputController.gamepad3 instanceof BABYLON.DualShockPad){var c=e.InputController.gamepad3;c.onbuttonup(e.InputController.inputOneButtonUpHandler),c.onbuttondown(e.InputController.inputOneButtonDownHandler),c.onleftstickchanged(e.InputController.inputOneLeftStickHandler),c.onrightstickchanged(e.InputController.inputOneRightStickHandler),c.ondpadup(e.InputController.inputOneShockDPadUpHandler),c.ondpaddown(e.InputController.inputOneShockDPadDownHandler),c.onlefttriggerchanged(e.InputController.inputOneXboxLeftTriggerHandler),c.onrighttriggerchanged(e.InputController.inputOneXboxRightTriggerHandler)}else{e.InputController.gamepad3Type=e.GamepadType.Generic;var d=e.InputController.gamepad3;d.onbuttonup(e.InputController.inputThreeButtonUpHandler),d.onbuttondown(e.InputController.inputThreeButtonDownHandler),d.onleftstickchanged(e.InputController.inputThreeLeftStickHandler),d.onrightstickchanged(e.InputController.inputThreeRightStickHandler)}if(null==e.InputController.gamepad4&&3===t.index)if(e.InputController.gamepad4=t,BABYLON.Tools.Log("Gamepad Four Connected: "+e.InputController.gamepad4.id),e.InputController.gamepad4 instanceof BABYLON.Xbox360Pad){e.InputController.gamepad4Type=e.GamepadType.Xbox360;var h=e.InputController.gamepad4;h.onbuttonup(e.InputController.inputFourButtonUpHandler),h.onbuttondown(e.InputController.inputFourButtonDownHandler),h.onleftstickchanged(e.InputController.inputFourLeftStickHandler),h.onrightstickchanged(e.InputController.inputFourRightStickHandler),h.ondpadup(e.InputController.inputFourXboxDPadUpHandler),h.ondpaddown(e.InputController.inputFourXboxDPadDownHandler),h.onlefttriggerchanged(e.InputController.inputFourXboxLeftTriggerHandler),h.onrighttriggerchanged(e.InputController.inputFourXboxRightTriggerHandler)}else if(e.InputController.gamepad4 instanceof BABYLON.DualShockPad){var p=e.InputController.gamepad4;p.onbuttonup(e.InputController.inputOneButtonUpHandler),p.onbuttondown(e.InputController.inputOneButtonDownHandler),p.onleftstickchanged(e.InputController.inputOneLeftStickHandler),p.onrightstickchanged(e.InputController.inputOneRightStickHandler),p.ondpadup(e.InputController.inputOneShockDPadUpHandler),p.ondpaddown(e.InputController.inputOneShockDPadDownHandler),p.onlefttriggerchanged(e.InputController.inputOneXboxLeftTriggerHandler),p.onrighttriggerchanged(e.InputController.inputOneXboxRightTriggerHandler)}else{e.InputController.gamepad4Type=e.GamepadType.Generic;var m=e.InputController.gamepad4;m.onbuttonup(e.InputController.inputFourButtonUpHandler),m.onbuttondown(e.InputController.inputFourButtonDownHandler),m.onleftstickchanged(e.InputController.inputFourLeftStickHandler),m.onrightstickchanged(e.InputController.inputFourRightStickHandler)}null!=e.InputController.GamepadConnected&&e.InputController.GamepadConnected(t,n)},t.inputManagerGamepadDisconnected=function(t,n){null!=e.InputController.GamepadDisconnected&&e.InputController.GamepadDisconnected(t,n)},t.MOUSE_DAMPENER=.5,t.TAP_THRESHOLD_MS=200,t.GamepadManager=null,t.GamepadConnected=null,t.GamepadDisconnected=null,t.AllowMobileControls=!0,t.MobileControlsActive=!1,t.EnablePinchZoomTracking=!1,t.LastMousePosition=new BABYLON.Vector3(0,0,0),t.PointerLockedFlag=!1,t.LockMousePointerObserver=null,t.input=!1,t.keymap={},t.scroll=0,t.wheel=0,t.mousex=0,t.mousey=0,t.vertical=0,t.horizontal=0,t.mousex2=0,t.mousey2=0,t.vertical2=0,t.horizontal2=0,t.mousex3=0,t.mousey3=0,t.vertical3=0,t.horizontal3=0,t.mousex4=0,t.mousey4=0,t.vertical4=0,t.horizontal4=0,t.a_mousex=0,t.x_scroll=0,t.x_wheel=0,t.x_mousex=0,t.x_mousey=0,t.x_vertical=0,t.x_horizontal=0,t.k_mousex=0,t.k_mousey=0,t.k_vertical=0,t.k_horizontal=0,t.j_mousex=0,t.j_mousey=0,t.j_vertical=0,t.j_horizontal=0,t.g_mousex1=0,t.g_mousey1=0,t.g_vertical1=0,t.g_horizontal1=0,t.g_mousex2=0,t.g_mousey2=0,t.g_vertical2=0,t.g_horizontal2=0,t.g_mousex3=0,t.g_mousey3=0,t.g_vertical3=0,t.g_horizontal3=0,t.g_mousex4=0,t.g_mousey4=0,t.g_vertical4=0,t.g_horizontal4=0,t.dragDirection=0,t.pinchZoomState=0,t.pinchZoomEvents=[],t.pinchZoomDistance=null,t.mouseDownTarget=null,t.mouseDragTarget=null,t.leftButtonDown=!1,t.middleButtonDown=!1,t.rightButtonDown=!1,t.mouseButtonsDown=0,t.mouseButtonPress=[],t.mouseButtonDown=[],t.mouseButtonUp=[],t.keyButtonPress=[],t.keyButtonDown=[],t.keyButtonUp=[],t.previousPosition=null,t.preventDefault=!1,t.lastClientX=0,t.lastClientY=0,t.virtualClientX=0,t.virtualClientY=0,t.rightHanded=!0,t.gamepad1=null,t.gamepad1Type=-1,t.gamepad1ButtonPress=[],t.gamepad1ButtonDown=[],t.gamepad1ButtonUp=[],t.gamepad1DpadPress=[],t.gamepad1DpadDown=[],t.gamepad1DpadUp=[],t.gamepad1LeftTrigger=[],t.gamepad1RightTrigger=[],t.gamepad2=null,t.gamepad2Type=-1,t.gamepad2ButtonPress=[],t.gamepad2ButtonDown=[],t.gamepad2ButtonUp=[],t.gamepad2DpadPress=[],t.gamepad2DpadDown=[],t.gamepad2DpadUp=[],t.gamepad2LeftTrigger=[],t.gamepad2RightTrigger=[],t.gamepad3=null,t.gamepad3Type=-1,t.gamepad3ButtonPress=[],t.gamepad3ButtonDown=[],t.gamepad3ButtonUp=[],t.gamepad3DpadPress=[],t.gamepad3DpadDown=[],t.gamepad3DpadUp=[],t.gamepad3LeftTrigger=[],t.gamepad3RightTrigger=[],t.gamepad4=null,t.gamepad4Type=-1,t.gamepad4ButtonPress=[],t.gamepad4ButtonDown=[],t.gamepad4ButtonUp=[],t.gamepad4DpadPress=[],t.gamepad4DpadDown=[],t.gamepad4DpadUp=[],t.gamepad4LeftTrigger=[],t.gamepad4RightTrigger=[],t}();e.InputController=o;var a=function(){function t(e,t,n,i,r,o){void 0===i&&(i=!0),void 0===r&&(r=-1),void 0===o&&(o=null);var a=this;this.isFixed=!0,this.touchId=null,this.pointerId=null,this.dragStart=null,this.mouseButton=-1,this.maxDistance=48,this.deadZone=2,this.xvalue=0,this.yvalue=0,this.stick=null,this.base=null,this.active=!1,this.enabled=!0,this.updateElements=!0,this.preventDefault=!0,this.stopPropagation=!0,this.baseElementOpacity="1",this.stickElementOpacity="1",this.onHandleDown=null,this.onHandleMove=null,this.onHandleUp=null,this.isFixed=i,this.deadZone=n,this.maxDistance=t,this.mouseButton=r,o&&(this.base=document.getElementById(o)),e&&(this.stick=document.getElementById(e)),this.base&&(this.base.oncontextmenu=function(e){return!1}),this.stick&&(this.stick.oncontextmenu=function(e){return!1}),this.isFixed?this.stick?this.stick.addEventListener("pointerdown",function(e){return a.handleDown(e)}):console.warn("Failed to locate fixed joystick element: "+e):(this.base&&(this.base.style.opacity="0"),this.stick&&(this.stick.style.opacity="0"),document.documentElement.addEventListener("pointerdown",function(e){return a.handleDown(e)})),document.documentElement.addEventListener("pointermove",function(e){return a.handleMove(e)},{passive:!1}),document.documentElement.addEventListener("pointerup",function(e){return a.handleUp(e)})}return t.prototype.dispose=function(){},t.prototype.isActive=function(){return this.active},t.prototype.getValueX=function(){return this.xvalue},t.prototype.getValueY=function(){return this.yvalue},t.prototype.getMouseButton=function(){return this.mouseButton},t.prototype.getBaseElement=function(){return this.base},t.prototype.getStickElement=function(){return this.stick},t.prototype.isFixedJoystick=function(){return this.isFixed},t.prototype.handleDown=function(t){if(this.enabled){var n=!(1&~t.buttons),i=!(2&~t.buttons);(this.mouseButton!==e.TouchMouseButton.Left||n)&&(this.mouseButton!==e.TouchMouseButton.Right||i)&&(this.active=!0,this.pointerId=t.pointerId,this.showBaseElement(t),this.stick&&(this.stick.style.transition="0s"),this.active&&this.preventDefault&&t.preventDefault(),t.changedTouches?(this.dragStart={x:t.changedTouches[0].clientX,y:t.changedTouches[0].clientY},this.touchId=t.changedTouches[0].identifier):this.dragStart={x:t.clientX,y:t.clientY},this.onHandleDown&&this.onHandleDown(t),this.stopPropagation&&t.stopPropagation())}},t.prototype.handleMove=function(e){if(this.enabled&&this.active&&e.pointerId===this.pointerId){if(e.changedTouches){for(var t=null,n=0;n<e.changedTouches.length;n++)this.touchId===e.changedTouches[n].identifier&&(t=n,e.clientX=e.changedTouches[n].clientX,e.clientY=e.changedTouches[n].clientY);if(null===t)return}var i=e.clientX-this.dragStart.x,r=e.clientY-this.dragStart.y,o=Math.atan2(r,i),a=Math.min(this.maxDistance,Math.hypot(i,r)),s=a*Math.cos(o),l=a*Math.sin(o);this.stick&&(this.stick.style.transform="translate3d(".concat(s,"px, ").concat(l,"px, 0px)"));var u=a<this.deadZone?0:this.maxDistance/(this.maxDistance-this.deadZone)*(a-this.deadZone),c=u*Math.cos(o),d=u*Math.sin(o),h=parseFloat((c/this.maxDistance).toFixed(4)),p=parseFloat((d/this.maxDistance).toFixed(4));this.xvalue=h,this.yvalue=p,this.onHandleMove&&this.onHandleMove(e),this.stopPropagation&&e.stopPropagation()}},t.prototype.handleUp=function(e){this.enabled&&this.active&&e.pointerId===this.pointerId&&(e.changedTouches&&this.touchId!==e.changedTouches[0].identifier||(this.stick&&(this.stick.style.transition=".2s",this.stick.style.transform="translate3d(0px, 0px, 0px)"),this.xvalue=0,this.yvalue=0,this.touchId=null,this.pointerId=null,this.active=!1,this.hideBaseElement(),this.onHandleUp&&this.onHandleUp(e),this.stopPropagation&&e.stopPropagation()))},t.prototype.showBaseElement=function(e){if(!this.isFixed&&this.updateElements){if(this.base&&this.base.style.opacity!==this.baseElementOpacity){var t=this.base.getBoundingClientRect();this.base.style.left=e.clientX-t.width/2+"px",this.base.style.top=e.clientY-t.height/2+"px",this.base.style.opacity=this.baseElementOpacity}this.stick&&this.stick.style.opacity!==this.stickElementOpacity&&(this.stick.style.opacity=this.stickElementOpacity)}else this.isFixed||this.updateElements||this.hideBaseElement()},t.prototype.hideBaseElement=function(){this.isFixed||(this.base&&"0"!==this.base.style.opacity&&(this.base.style.opacity="0",this.base.style.left="-1000px",this.base.style.top="-1000px"),this.stick&&"0"!==this.stick.style.opacity&&(this.stick.style.opacity="0"))},t}();e.TouchJoystickHandler=a}(i||(i={})),function(e){var t=function(){function t(){}return t.IsWindows=function(){return"undefined"!=typeof Windows&&void 0!==Windows.UI&&void 0!==Windows.System&&void 0!==Windows.Foundation},t.IsCordova=function(){return null!=window.cordova},t.IsWebAssembly=function(){return window.WebAssembly},t.IsOculusBrowser=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/OculusBrowser/i)&&(e=!0),e},t.IsSamsungBrowser=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/SamsungBrowser/i)&&(e=!0),e},t.IsWindowsPhone=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/Windows Phone/i)&&(e=!0),e},t.IsBlackBerry=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/BlackBerry/i)&&(e=!0),e},t.IsOperaMini=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/Opera Mini/i)&&(e=!0),e},t.IsAndroid=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/Android/i)&&(e=!0),e},t.IsWebOS=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/webOS/i)&&(e=!0),e},t.IsIOS=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/iPhone|iPad|iPod/i)&&(e=!0),e},t.IsIPHONE=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/iPhone/i)&&(e=!0),e},t.IsIPAD=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/iPad/i)&&(e=!0),e},t.IsIPOD=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/iPod/i)&&(e=!0),e},t.IsIE11=function(){return void 0!==navigator.maxTouchPoints},t.IsMobile=function(){var e,t,n,i;if("undefined"==typeof navigator||"undefined"==typeof window)return!1;var r=!0===(null===(e=navigator.userAgentData)||void 0===e?void 0:e.mobile),o=null!==(i=null===(n=null===(t=window.matchMedia)||void 0===t?void 0:t.call(window,"(pointer: coarse)"))||void 0===n?void 0:n.matches)&&void 0!==i&&i,a=Math.min(window.innerWidth,window.innerHeight)<=820,s=navigator.userAgent||"",l=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Windows Phone/i.test(s);return r||o&&a||l},t.IsHighEndMobile=function(){var e;if(!this.IsMobile())return!1;var t=window.__HEM_CACHE__;if("boolean"==typeof t)return t;var n=0,i=null!==(e=navigator.hardwareConcurrency)&&void 0!==e?e:0;i>=8?n+=3:i>=6?n+=2:i>=4&&(n+=1);var r=navigator.deviceMemory;"number"==typeof r&&(r>=8?n+=3:r>=6?n+=2:r>=4&&(n+=1));var o=window.devicePixelRatio||1;o>=3&&(n+=1);var a=null;try{var s=document.createElement("canvas");if(a=s.getContext("webgl2")||s.getContext("webgl")||s.getContext("experimental-webgl")||null){a.getParameter&&s.getContext("webgl2")&&(n+=2);var l=a.getParameter(a.MAX_TEXTURE_SIZE);l>=8192?n+=2:l>=4096&&(n+=1)}}catch(e){}try{screen.width*o*(screen.height*o)>=25e5&&(n+=1)}catch(e){}var u=n>=6;return window.__HEM_CACHE__=u,u},t.IsHighEndMobileAsync=function(){return a(this,void 0,void 0,function(){var e,t,n,i;return s(this,function(r){for(e=this.IsHighEndMobile(),t=performance.now(),n=0;n<75e4;n++);return(i=performance.now()-t)<18?e=!0:i>45&&(e=!1),[2,e]})})},t.IsDesktop=function(){return!e.WindowManager.IsMobile()},t.IsPlaystation=function(){var e=!1;return null!=navigator&&null!=navigator.userAgent&&navigator.userAgent.match(/Playstation/i)&&(e=!0),e},t.IsXboxConsole=function(){var t=!1;return e.WindowManager.IsWindows()&&void 0!==Windows.System.Profile&&void 0!==Windows.System.Profile.AnalyticsInfo&&void 0!==Windows.System.Profile.AnalyticsInfo.versionInfo&&void 0!==Windows.System.Profile.AnalyticsInfo.versionInfo.deviceFamily&&Windows.System.Profile.AnalyticsInfo.versionInfo.deviceFamily.match(/Xbox/i)&&(t=!0),t},t.IsXboxLive=function(){return e.WindowManager.IsWindows()&&"undefined"!=typeof Microsoft&&void 0!==Microsoft.Xbox&&void 0!==Microsoft.Xbox.Services},t.IsFrameWindow=function(){return null!=window.parent&&window!==window.parent},t.IsPortraitWindow=function(){return"portrait"===e.WindowManager.GetOrientation()},t.IsLandscapeWindow=function(){return"landscape"===e.WindowManager.GetOrientation()},t.IsStandaloneWindow=function(){return!!window.navigator.standalone||!(!window.matchMedia||!window.matchMedia("(display-mode: standalone)").matches)},t.IsFullscreenWindow=function(){return!!window.navigator.standalone||!(!window.matchMedia||!window.matchMedia("(display-mode: fullscreen)").matches)},t.IsProgressiveWindow=function(){return e.WindowManager.IsStandaloneWindow()||e.WindowManager.IsFullscreenWindow()},t.GetDisplayMode=function(){if(window.navigator.standalone)return"standalone";if(window.matchMedia){if(window.matchMedia("(display-mode: fullscreen)").matches)return"fullscreen";if(window.matchMedia("(display-mode: standalone)").matches)return"standalone";if(window.matchMedia("(display-mode: minimal-ui)").matches)return"minimal-ui"}return"browser"},t.GetOrientation=function(){var e="portrait";if(window.screen&&window.screen.orientation){var t=window.screen.orientation.type;t.includes("portrait")?e="portrait":t.includes("landscape")&&(e="landscape")}else if(window.orientation){var n=window.orientation;0===n||180===n?e="portrait":90!==n&&-90!==n||(e="landscape")}return e},t.SetLocation=function(e,t){void 0===t&&(t=!1),!0===t?window.location.replace(e):window.location.assign(e)},t.AlertMessage=function(t,n){void 0===n&&(n="Babylon Toolkit");var i=null;return e.WindowManager.IsWindows()?i=new Windows.UI.Popups.MessageDialog(t,n).showAsync():window.alert(t),i},t.GetQueryStringParam=function(e,t){t||(t=window.location.href),e=e.replace(/[\[\]]/g,"\\$&");var n=new RegExp("[?&]"+e+"(=([^&#]*)|&|#|$)").exec(t);return n?n[2]?decodeURIComponent(n[2].replace(/\+/g," ")):"":null},t.PostWindowMessage=function(e,t,n){void 0===t&&(t="*"),void 0===n&&(n=!1),!0===n?window.postMessage(e,t):window.top?window.top.postMessage(e,t):console.warn("No Valid Top Window")},t.ShowSceneLoader=function(){window.showSceneLoader&&window.showSceneLoader()},t.HideSceneLoader=function(){window.hideSceneLoader&&window.hideSceneLoader()},t.UpdateLoaderStatus=function(e,t,n){window.updateStatus&&window.updateStatus(e,t,n)},t.UpdateLoaderDetails=function(e,t){window.updateDetails&&window.updateDetails(e,t)},t.UpdateLoaderProgress=function(e,t){window.updateProgress&&window.updateProgress(e,t)},t.ShowPageErrorMessage=function(e,t,n){void 0===t&&(t="Error"),void 0===n&&(n=0),window.showErrorMessage&&window.showErrorMessage(e,t,n)},t.SetTimeout=function(e,t){return window.setTimeout(t,e)},t.ClearTimeout=function(e){window.clearTimeout(e)},t.SetInterval=function(e,t){return window.setInterval(t,e)},t.ClearInterval=function(e){window.clearInterval(e)},t.Atob=function(e){return window.atob(e)},t.Btoa=function(e){return window.btoa(e)},t.PopupDebug=function(e){e.debugLayer&&(e.debugLayer.hide(),e.debugLayer.show({enablePopup:!0,globalRoot:null}))},t.ToggleDebug=function(t,n,i){if(void 0===n&&(n=!1),void 0===i&&(i=null),t.debugLayer){var r=window;!0===e.WindowManager.debugLayerVisible?(e.WindowManager.debugLayerVisible=!1,r.METER&&r.METER.show&&r.METER.show(),t.debugLayer.hide()):(e.WindowManager.debugLayerVisible=!0,r.METER&&r.METER.hide&&r.METER.hide(),t.debugLayer.show({embedMode:n,globalRoot:i}))}},t.GetLocalStorageItem=function(e){return null!=window.localStorage?window.localStorage.getItem(e):null},t.SetLocalStorageItem=function(e,t){null!=window.localStorage&&window.localStorage.setItem(e,t)},t.GetSessionStorageItem=function(e){return null!=window.sessionStorage?window.sessionStorage.getItem(e):null},t.SetSessionStorageItem=function(e,t){null!=window.sessionStorage&&window.sessionStorage.setItem(e,t)},t.GetFilenameFromUrl=function(e){return e.substring(e.lastIndexOf("/")+1)},t.GetUrlParameter=function(e){var t=e.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]"),n=new RegExp("[\\?&]"+t+"=([^&#]*)").exec(window.location.search);return null!==n?decodeURIComponent(n[1].replace(/\+/g," ")):null},t.GetVirtualRealityEnabled=function(){var t=e.WindowManager.GetLocalStorageItem("virtualReality");return null!=t&&"true"===t},t.SetVirtualRealityEnabled=function(t){e.WindowManager.SetLocalStorageItem("virtualReality",t.toString().toLowerCase())},t.SetWindowsLaunchMode=function(t){void 0===t&&(t=1),e.WindowManager.IsWindows()&&void 0!==Windows.UI.ViewManagement&&void 0!==Windows.UI.ViewManagement.ApplicationView&&(Windows.UI.ViewManagement.ApplicationView.preferredLaunchWindowingMode=t)},t.GetHardwareScalingLevel=function(){return 1/window.devicePixelRatio},t.QuitWindowsApplication=function(){e.WindowManager.IsWindows()&&window.close()},t.PrintToScreen=function(t,n){if(void 0===n&&(n="white"),e.WindowManager.PrintElement=document.getElementById("print"),null==e.WindowManager.PrintElement){var i=document.createElement("div");i.id="print",i.style.position="absolute",i.style.left="6px",i.style.bottom="3px",i.style.fontSize="12px",i.style.zIndex="9001",i.style.color="#0c0",i.style.pointerEvents="none",document.body.appendChild(i),e.WindowManager.PrintElement=i}null!=e.WindowManager.PrintElement&&e.WindowManager.PrintElement.innerHTML!==t&&(e.WindowManager.PrintElement.style.color!==n&&(e.WindowManager.PrintElement.style.color=n),e.WindowManager.PrintElement.innerHTML=t)},t.debugLayerVisible=!1,t.PrintElement=null,t}();e.WindowManager=t}(i||(i={})),i.WindowManager.IsWindows()&&void 0!==Windows.UI.ViewManagement&&void 0!==Windows.UI.ViewManagement.ApplicationViewBoundsMode&&void 0!==Windows.UI.ViewManagement.ApplicationViewBoundsMode.useCoreWindow&&Windows.UI.ViewManagement.ApplicationView.getForCurrentView().setDesiredBoundsMode(Windows.UI.ViewManagement.ApplicationViewBoundsMode.useCoreWindow),i.WindowManager.IsXboxConsole()&&navigator.gamepadInputEmulation&&(navigator.gamepadInputEmulation="gamepad"),function(e){var t=function(t){function n(n,i,r,o){void 0===r&&(r={}),void 0===o&&(o="TOOLKIT.AnimationState");var a=t.call(this,n,i,r,o)||this;return a._looptime=!1,a._loopblend=!1,a._frametime=0,a._layercount=0,a._updatemode=0,a._hasrootmotion=!1,a._animationplaying=!1,a._initialtargetblending=!1,a._hastransformhierarchy=!1,a._leftfeetbottomheight=0,a._rightfeetbottomheight=0,a._runtimecontroller=null,a._executed=!1,a._awakened=!1,a._initialized=!1,a._checkers=new e.TransitionCheck,a._source="",a._machine=null,a._animationmode=0,a._animationrig=null,a._deltaPosition=new BABYLON.Vector3(0,0,0),a._deltaRotation=new BABYLON.Quaternion(0,0,0,0),a._angularVelocity=new BABYLON.Vector3(0,0,0),a._rootMotionSpeed=0,a._lastMotionSpeed=0,a._loopMotionSpeed=0,a._lastRotateSpeed=0,a._loopRotateSpeed=0,a._lastMotionRotation=new BABYLON.Quaternion(0,0,0,0),a._lastMotionPosition=new BABYLON.Vector3(0,0,0),a._positionWeight=!1,a._rootBoneWeight=!1,a._rotationWeight=!1,a._rootQuatWeight=!1,a._rootBoneTransform=null,a._positionHolder=new BABYLON.Vector3(0,0,0),a._rootBoneHolder=new BABYLON.Vector3(0,0,0),a._rotationHolder=new BABYLON.Quaternion(0,0,0,0),a._rootQuatHolder=new BABYLON.Quaternion(0,0,0,0),a._rootMotionMatrix=BABYLON.Matrix.Zero(),a._rootMotionScaling=new BABYLON.Vector3(0,0,0),a._rootMotionRotation=new BABYLON.Quaternion(0,0,0,0),a._rootMotionPosition=new BABYLON.Vector3(0,0,0),a._dirtyMotionMatrix=null,a._dirtyBlenderMatrix=null,a._targetPosition=new BABYLON.Vector3(0,0,0),a._targetRotation=new BABYLON.Quaternion(0,0,0,0),a._targetScaling=new BABYLON.Vector3(1,1,1),a._updateMatrix=BABYLON.Matrix.Zero(),a._blenderMatrix=BABYLON.Matrix.Zero(),a._blendWeights=new e.BlendingWeights,a._emptyScaling=new BABYLON.Vector3(1,1,1),a._emptyPosition=new BABYLON.Vector3(0,0,0),a._emptyRotation=new BABYLON.Quaternion(0,0,0,0),a._ikFrameEanbled=!1,a._data=new Map,a._anims=new Map,a._clips=null,a._numbers=new Map,a._booleans=new Map,a._triggers=new Map,a._parameters=new Map,a._smoothTargets=new Map,a.delayStart=0,a.speedRatio=1,a.delayUpdateUntilReady=!0,a.enableAnimations=!0,a.applyRootMotion=!1,a.onAnimationAwakeObservable=new BABYLON.Observable,a.onAnimationInitObservable=new BABYLON.Observable,a.onAnimationIKObservable=new BABYLON.Observable,a.onAnimationEndObservable=new BABYLON.Observable,a.onAnimationLoopObservable=new BABYLON.Observable,a.onAnimationEventObservable=new BABYLON.Observable,a.onAnimationUpdateObservable=new BABYLON.Observable,a.onAnimationTransitionObservable=new BABYLON.Observable,a.m_zeroVector=new BABYLON.Vector3(0,0,0),a.m_defaultGroup=null,a.m_animationTargets=null,a.m_rotationIdentity=new BABYLON.Quaternion(0,0,0,0),a.m_timelineScrubbing=!1,a.m_vertexAnimationMode=!1,a.m_vertexAnimationRenderers=null,a.m_vertexAnimationController=null,a.m_vertexAnimationDefaultClip=null,a.sourceAnimationGroups=null,a}return r(n,t),n.prototype.awakened=function(){return this._awakened},n.prototype.initialized=function(){return this._initialized},n.prototype.hasRootMotion=function(){return this._hasrootmotion},n.prototype.isFirstFrame=function(){return 0===this._frametime},n.prototype.isLastFrame=function(){return this._frametime>=.985},n.prototype.ikFrameEnabled=function(){return this._ikFrameEanbled},n.prototype.getAnimationTime=function(){return this._frametime},n.prototype.getFrameLoopTime=function(){return this._looptime},n.prototype.getFrameLoopBlend=function(){return this._loopblend},n.prototype.getAnimationPlaying=function(){return this._animationplaying},n.prototype.getRuntimeController=function(){return this._runtimecontroller},n.prototype.getRootBoneTransform=function(){return this._rootBoneTransform},n.prototype.getDeltaRootMotionAngle=function(){return this._angularVelocity.y},n.prototype.getDeltaRootMotionSpeed=function(){return this._rootMotionSpeed},n.prototype.getDeltaRootMotionPosition=function(){return this._deltaPosition},n.prototype.getDeltaRootMotionRotation=function(){return this._deltaRotation},n.prototype.getFixedRootMotionPosition=function(){return null!=this._dirtyMotionMatrix?this._rootMotionPosition:null},n.prototype.getFixedRootMotionRotation=function(){return null!=this._dirtyMotionMatrix?this._rootMotionRotation:null},n.prototype.getVertexAnimationController=function(){return this.m_vertexAnimationController},n.prototype.isVertexAnimationModeEnabled=function(){return this.m_vertexAnimationMode},n.prototype.getVertexAnimationMaterial=function(t,n){if(void 0===t&&(t=0),void 0===n&&(n=0),!this.m_vertexAnimationRenderers||0===this.m_vertexAnimationRenderers.length)return null;var i=Math.max(0,Math.min(t,this.m_vertexAnimationRenderers.length-1)),r=this.m_vertexAnimationRenderers[i];if(!r)return null;var o=r.material;if(o instanceof e.VertexAnimationMaterial)return o;if(o instanceof BABYLON.MultiMaterial){var a=o.subMaterials,s=Math.max(0,Math.min(n,a.length-1));return a[s]instanceof e.VertexAnimationMaterial?a[s]:null}return null},n.prototype.awake=function(){this.awakeStateMachine()},n.prototype.update=function(){this.updateSmoothParameters(this.getDeltaSeconds()),this.updateStateMachine()},n.prototype.destroy=function(){this.destroyStateMachine()},n.prototype.playDefault=function(t,n,i){void 0===t&&(t=.1),void 0===n&&(n=0),void 0===i&&(i=null);var r=!1;if(!0===this._initialized)if(!0===this.m_vertexAnimationMode)if(null!=this.m_vertexAnimationController)if(null!=this._machine&&null!=this._machine.layers&&this._machine.layers.length>0){var o=this._machine.layers[0];this.playCurrentAnimationState(o,o.entry,t),r=!0}else BABYLON.Tools.Warn("No animation state layers on "+this.transform.name);else BABYLON.Tools.Warn("Vertex animation controller not initialized for "+this.transform.name);else if(!0===this._initialized)if(null!=this._machine&&null!=this._machine.layers&&this._machine.layers.length>n){var a=null!=(o=this._machine.layers[n]).animationStateMachine&&o.animationStateMachine.rate||e.AnimationState.FPS,s=t>0?e.Utilities.ComputeBlendingSpeed(i||a,t):0;this.playCurrentAnimationState(o,o.entry,s),r=!0}else BABYLON.Tools.Warn("No animation state layers on "+this.transform.name);else BABYLON.Tools.Warn("Animation state machine not initialized for "+this.transform.name);else BABYLON.Tools.Warn("Animation state machine not initialized for "+this.transform.name);return r},n.prototype.playAnimation=function(t,n,i,r){void 0===n&&(n=.1),void 0===i&&(i=0),void 0===r&&(r=null);var o=!1;if(!0===this._initialized)if(!0===this.m_vertexAnimationMode)if(null!=this.m_vertexAnimationController)if(null!=this._machine&&null!=this._machine.layers&&this._machine.layers.length>0){var a=this._machine.layers[0];this.playCurrentAnimationState(a,t,n),o=!0}else BABYLON.Tools.Warn("No animation state layers on "+this.transform.name);else BABYLON.Tools.Warn("Vertex animation controller not initialized for "+this.transform.name);else if(null!=this._machine&&null!=this._machine.layers&&this._machine.layers.length>i){var s=null!=(a=this._machine.layers[i]).animationStateMachine&&a.animationStateMachine.rate||e.AnimationState.FPS,l=n>0?e.Utilities.ComputeBlendingSpeed(r||s,n):0;this.playCurrentAnimationState(a,t,l),o=!0}else BABYLON.Tools.Warn("No animation state layers on "+this.transform.name);else BABYLON.Tools.Warn("Animation state machine not initialized for "+this.transform.name);return o},n.prototype.stopAnimation=function(e){void 0===e&&(e=0);var t=!1;if(!0===this._initialized)if(!0===this.m_vertexAnimationMode)if(null!=this.m_vertexAnimationController)if(null!=this._machine&&null!=this._machine.layers&&this._machine.layers.length>0){var n=this._machine.layers[0];this.stopCurrentAnimationState(n),t=!0}else BABYLON.Tools.Warn("No animation state layers on "+this.transform.name);else BABYLON.Tools.Warn("Vertex animation controller not initialized for "+this.transform.name);else null!=this._machine&&null!=this._machine.layers&&this._machine.layers.length>e?(n=this._machine.layers[e],this.stopCurrentAnimationState(n),t=!0):BABYLON.Tools.Warn("No animation state layers on "+this.transform.name);else BABYLON.Tools.Warn("Animation state machine not initialized for "+this.transform.name);return t},n.prototype.killAnimations=function(){var e=this,t=!1;if(!0===this._initialized)if(!0===this.m_vertexAnimationMode)if(null!=this.m_vertexAnimationController)if(null!=this._machine&&null!=this._machine.layers&&this._machine.layers.length>0){var n=this._machine.layers[0];this.stopCurrentAnimationState(n),t=!0}else BABYLON.Tools.Warn("No animation state layers on "+this.transform.name);else BABYLON.Tools.Warn("Vertex animation controller not initialized for "+this.transform.name);else null!=this._machine&&null!=this._machine.layers?this._machine.layers.forEach(function(n){e.stopCurrentAnimationState(n),t=!0}):BABYLON.Tools.Warn("No animation state layers on "+this.transform.name);else BABYLON.Tools.Warn("Animation state machine not initialized for "+this.transform.name);return t},n.prototype.setTimelineScrubbing=function(e){this.m_timelineScrubbing=e,!0===this.m_vertexAnimationMode&&null!=this.m_vertexAnimationController&&!1===e&&this.m_vertexAnimationController.currentClip&&this.m_vertexAnimationController.resume()},n.prototype.getIsTimelineScrubbing=function(){return this.m_timelineScrubbing},n.prototype.setAnimationTime=function(t){if(!0===this.m_vertexAnimationMode&&null!=this.m_vertexAnimationController){if(this.m_vertexAnimationController.setCurrentTime(t),null!=this._machine&&null!=this._machine.layers&&this._machine.layers.length>0){var n=this._machine.layers[0],i=this.m_vertexAnimationController.currentClip,r=null!=i?i.duration:0,o=r>0?Math.max(0,Math.min(1,t/r)):0;n.animationNormal=o,n.animationTime=o*e.AnimationState.TIME}return!0}return!1},n.prototype.setAnimationSpeed=function(e){return!0===this.m_vertexAnimationMode&&null!=this.m_vertexAnimationController&&(this.m_vertexAnimationController.setSpeed(e),!0)},n.prototype.setAnimationLoop=function(e){return!0===this.m_vertexAnimationMode&&null!=this.m_vertexAnimationController&&(this.m_vertexAnimationController.setLoop(e),!0)},n.prototype.hasBool=function(e){return null!=this._booleans.get(e)},n.prototype.getBool=function(e){return this._booleans.get(e)||!1},n.prototype.setBool=function(e,t){this._booleans.set(e,t)},n.prototype.hasFloat=function(e){return null!=this._numbers.get(e)},n.prototype.getFloat=function(e){return this._numbers.get(e)||0},n.prototype.setFloat=function(e,t){this._numbers.set(e,t)},n.prototype.hasInteger=function(e){return null!=this._numbers.get(e)},n.prototype.getInteger=function(e){return this._numbers.get(e)||0},n.prototype.setInteger=function(e,t){this._numbers.set(e,t)},n.prototype.hasTrigger=function(e){return null!=this._triggers.get(e)},n.prototype.getTrigger=function(e){return this._triggers.get(e)||!1},n.prototype.setTrigger=function(e){this._triggers.set(e,!0)},n.prototype.resetTrigger=function(e){this._triggers.set(e,!1)},n.prototype.setSmoothFloat=function(e,t,n,i){if(void 0===n&&(n=.1),!(n>0))return this._smoothTargets&&this._smoothTargets.delete(e),void this.setFloat(e,t);var r=this._smoothTargets.get(e);null==r?(r={target:t,dampTime:n,velocity:new BABYLON.Vector2(0,0)},this._smoothTargets.set(e,r)):(r.target=t,r.dampTime=n)},n.prototype.setSmoothInteger=function(e,t,n,i){void 0===n&&(n=.1),this.setSmoothFloat(e,t,n,i)},n.prototype.updateSmoothParameters=function(t){var n=this;if(null!=this._smoothTargets&&0!==this._smoothTargets.size&&t>0){var i=1e-4,r=[];this._smoothTargets.forEach(function(o,a){var s=n.getFloat(a);if(Math.abs(s-o.target)<=i&&Math.abs(o.velocity.x)<=i)return n.setFloat(a,o.target),void r.push(a);var l=e.Utilities.SmoothDamp(s,o.target,o.dampTime,Number.POSITIVE_INFINITY,t,o.velocity);n.setFloat(a,l)});for(var o=0;o<r.length;o++)this._smoothTargets.delete(r[o])}},n.prototype.getMachineState=function(e){return this._data.get(e)},n.prototype.setMachineState=function(e,t){this._data.set(e,t)},n.prototype.getCurrentState=function(e){return null!=this._machine.layers&&this._machine.layers.length>e?this._machine.layers[e].animationStateMachine:null},n.prototype.getDefaultClips=function(){return this._clips},n.prototype.getDefaultSource=function(){return this._source},n.prototype.setLayerWeight=function(e,t){},n.prototype.fixAnimationGroup=function(e){var t=null;if(null!=this._clips&&this._clips.length>0)for(var n=0;n<this._clips.length;n++){var i=this._clips[n];if(null!=i.clip){var r=("."+i.clip).toLowerCase();if(e.name.toLowerCase().endsWith(r)){null==e.metadata&&(e.metadata={}),null==e.metadata.toolkit&&(e.metadata.toolkit=i),e.metadata.toolkit.source=this._source,t=i;break}}}return t},n.prototype.getAnimationGroup=function(e){return this._anims.get(e)},n.prototype.getAnimationGroups=function(){return this.sourceAnimationGroups},n.prototype.setAnimationGroups=function(e){!0!==this.m_vertexAnimationMode&&(null==this.transform.metadata&&(this.transform.metadata={}),null==this.transform.metadata.toolkit&&(this.transform.metadata.toolkit={}),this.transform.metadata.toolkit.sourceAnimationGroups=e,this.setupSourceAnimationGroups())},n.prototype.updateAnimationGroups=function(t){var n=this;!0!==this.m_vertexAnimationMode&&null!=t&&t.length>0&&(this._anims=new Map,this.m_animationTargets=[],this.m_defaultGroup=null,this.sourceAnimationGroups=null,t.forEach(function(t){var i=!1,r=t;if(null!=r&&null!=r.metadata&&null!=r.metadata.toolkit&&null!=r.metadata.toolkit.source&&""!==r.metadata.toolkit.source&&r.metadata.toolkit.source===n._source&&(i=!0),!0===i&&null!=r&&null!=r.metadata&&null!=r.metadata.toolkit&&null!=r.metadata.toolkit.clip&&""!==r.metadata.toolkit.clip){try{t.stop()}catch(e){}null==n.sourceAnimationGroups&&(n.sourceAnimationGroups=[]),n.sourceAnimationGroups.push(t),n._anims.set(r.metadata.toolkit.clip,t),null==n.m_defaultGroup&&(n.m_defaultGroup=t),null!=t.targetedAnimations&&t.targetedAnimations.length>0&&t.targetedAnimations.forEach(function(t){for(var i=-1,r=0;r<n.m_animationTargets.length;r++)if(n.m_animationTargets[r].target===t.target){i=r;break}if(i<0)if(n.m_animationTargets.push(t),null==t.target.metadata&&(t.target.metadata={}),t.target instanceof BABYLON.TransformNode){e.Utilities.ValidateTransformQuaternion(t.target);for(var o=[],a=0;a<n._layercount;a++){var s=new e.AnimationMixer;s.positionBuffer=null,s.rotationBuffer=null,s.scalingBuffer=null,s.originalMatrix=null,s.blendingFactor=0,s.blendingSpeed=0,s.rootPosition=null,s.rootRotation=null,o.push(s)}t.target.metadata.mixer=o}else if(t.target instanceof BABYLON.MorphTarget){var l=[];for(a=0;a<n._layercount;a++){var u=new e.AnimationMixer;u.influenceBuffer=null,l.push(u)}t.target.metadata.mixer=l}})}}))},n.prototype.setupSourceAnimationGroups=function(){var e=this;if(!0!==this.m_vertexAnimationMode){var t=null!=this.transform.metadata&&null!=this.transform.metadata.toolkit&&null!=this.transform.metadata.toolkit.sourceAnimationGroups?this.transform.metadata.toolkit.sourceAnimationGroups:null;null!=t&&(this.updateAnimationGroups(t),null!=this.sourceAnimationGroups&&null!=this._machine&&null!=this._machine.states&&this._machine.states.length>0&&this._machine.states.forEach(function(t){null!=t&&null!=t.name&&(null!=t.ccurves&&t.ccurves.length>0&&t.ccurves.forEach(function(e){if(null!=e.animation){var n=BABYLON.Animation.Parse(e.animation);null!=n&&(null==t.tcurves&&(t.tcurves=[]),t.tcurves.push(n))}}),e.setupTreeBranches(t.blendtree),e.setMachineState(t.name,t))}))}},n.prototype.awakeStateMachine=function(){var t=this;e.Utilities.ValidateTransformQuaternion(this.transform),this.m_animationTargets=[],this.m_defaultGroup=null,this.m_rotationIdentity=BABYLON.Quaternion.Identity(),this._source=null!=this.transform.metadata&&null!=this.transform.metadata.toolkit&&null!=this.transform.metadata.toolkit.animator&&""!==this.transform.metadata.toolkit.animator?this.transform.metadata.toolkit.animator:null,this._clips=this.getProperty("clips",this._clips),this._machine=this.getProperty("machine",this._machine),this._updatemode=this.getProperty("updatemode",this._updatemode),this._animationrig=this.getProperty("animationrig",this._animationrig),this._animationmode=this.getProperty("animationmode",this._animationmode),this._hasrootmotion=this.getProperty("hasrootmotion",this._hasrootmotion),this._runtimecontroller=this.getProperty("runtimecontroller",this._runtimecontroller),this._hastransformhierarchy=this.getProperty("hastransformhierarchy",this._hastransformhierarchy),this._leftfeetbottomheight=this.getProperty("leftfeetbottomheight",this._leftfeetbottomheight),this._rightfeetbottomheight=this.getProperty("rightfeetbottomheight",this._rightfeetbottomheight),this.applyRootMotion=this.getProperty("applyrootmotion",this.applyRootMotion),null!=this._machine&&(null!=this._machine.owner&&null!=this._machine.owner&&""!==this._machine.owner&&"*"!==this._machine.owner||(this._machine.owner=null!=this.transform.parent?this.transform.parent.name:this.transform.name),null!=this._machine.speed&&(this.speedRatio=this._machine.speed),null!=this._machine.parameters&&this._machine.parameters.length>0&&this._machine.parameters.forEach(function(n){var i=n.name,r=n.type,o=(n.curve,n.defaultFloat),a=n.defaultBool,s=n.defaultInt;t._parameters.set(i,r),r===e.AnimatorParameterType.Bool?t.setBool(i,a):r===e.AnimatorParameterType.Float?t.setFloat(i,o):r===e.AnimatorParameterType.Int?t.setInteger(i,s):r===e.AnimatorParameterType.Trigger&&t.resetTrigger(i)}),null!=this._machine.layers&&this._machine.layers.length>0&&(this._layercount=this._machine.layers.length,this._machine.layers.sort(function(e,t){return e.index<t.index?-1:e.index>t.index?1:0}),this._machine.layers.forEach(function(e){if(null==e.owner||null==e.owner||""===e.owner||e.owner,e.animationMaskMap=new Map,null!=e.avatarMask&&null!=e.avatarMask.transformPaths&&e.avatarMask.transformPaths.length>0)for(var t=0;t<e.avatarMask.transformPaths.length;t++)e.animationMaskMap.set(e.avatarMask.transformPaths[t],t)})));var n=this.getProperty("vertexcontroller",null),i=this.getProperty("lazyloadtextures",!1),r=this.getProperty("clips",null);if(null!=n&&null!=r){var o=[];if(r.forEach(function(e){var n,i;null==t.m_vertexAnimationDefaultClip&&null!=e.clip&&(t.m_vertexAnimationDefaultClip=e.clip);var r=null!==(i=null===(n=null==e?void 0:e.settings)||void 0===n?void 0:n.vertexrenderers)&&void 0!==i?i:null;null!=r&&r.forEach(function(e){return o.push(e)})}),o.length>0){this.m_vertexAnimationMode=!0,this.m_vertexAnimationRenderers=[];var a=e.SceneManager.GetRootUrl(this.scene),s={};o.forEach(function(r){if(r&&r.vertexguid&&!s[r.vertexguid]){s[r.vertexguid]=!0;var l=t.scene.getNodeById(r.vertexguid);if(null!=l){var u=l.material,c=!1;if(!(l instanceof BABYLON.InstancedMesh)){var d=function(t){if(t instanceof e.VertexAnimationMaterial){var i=t.getPlugin();i&&i.controller&&i.controller.guid!==n&&(c=!0)}};u instanceof BABYLON.MultiMaterial?u.subMaterials.forEach(d):d(u)}if(c)if(u instanceof BABYLON.MultiMaterial){var h=new BABYLON.MultiMaterial(u.name+"_"+n,t.scene);u.subMaterials.forEach(function(t){h.subMaterials.push(t instanceof e.VertexAnimationMaterial?t.cloneForInstance(t.name+"_"+n):t)}),l.material=h}else u instanceof e.VertexAnimationMaterial&&(l.material=u.cloneForInstance(u.name+"_"+n));var p=[];if(l.material instanceof BABYLON.MultiMaterial?l.material.subMaterials.forEach(function(t){t instanceof e.VertexAnimationMaterial&&p.push(t)}):l.material instanceof e.VertexAnimationMaterial&&p.push(l.material),p.length>0){t.m_vertexAnimationRenderers.push(l);var m=l instanceof BABYLON.InstancedMesh?l.sourceMesh:l;m&&!m.__vatPackedInstancedBuffersRegistered&&(m.__vatPackedInstancedBuffersRegistered=!0,m.registerInstancedBuffer("g_vatAnim0",4),m.registerInstancedBuffer("g_vatAnim1",4));var f=l.instancedBuffers;f&&(f.g_vatAnim0=new BABYLON.Vector4(0,0,0,1),f.g_vatAnim1=new BABYLON.Vector4(0,0,0,0)),p.forEach(function(s){var u=s.getPlugin();if(u instanceof e.VertexAnimationMaterialPlugin){var c=u.setupAnimations(o,n,a,i);null!=c&&(c.setInstanceMesh(r.vertexguid,l),null==t.m_vertexAnimationController&&(t.m_vertexAnimationController=c))}})}else console.error("### No VertexAnimationMaterial found on mesh GUID: "+r.vertexguid+" --\x3e For: "+t.transform.name,l)}else console.error("### Failed To Setup Vertex Animation Renderer For GUID: "+r.vertexguid+" --\x3e For: "+t.transform.name)}}),null!=this._machine&&null!=this._machine.states&&this._machine.states.length>0&&this._machine.states.forEach(function(e){null!=e&&null!=e.name&&(null!=e.ccurves&&e.ccurves.length>0&&e.ccurves.forEach(function(t){if(null!=t.animation){var n=BABYLON.Animation.Parse(t.animation);null!=n&&(null==e.tcurves&&(e.tcurves=[]),e.tcurves.push(n))}}),t.setMachineState(e.name,e))})}else this.m_vertexAnimationMode=!1,this.m_vertexAnimationRenderers=null}else this.m_vertexAnimationMode=!1,this.m_vertexAnimationRenderers=null;this._awakened=!0,this.onAnimationAwakeObservable&&this.onAnimationAwakeObservable.hasObservers()&&this.onAnimationAwakeObservable.notifyObservers(this.transform)},n.prototype.updateStateMachine=function(e){var t=this;if(void 0===e&&(e=null),!1===this.delayUpdateUntilReady||!0===this.delayUpdateUntilReady&&this.isReady())if(!0===this.m_vertexAnimationMode){if(!1===this._executed){if(this._executed=!0,null!=this._machine.layers&&this._machine.layers.length>0){var n=this._machine.layers[0];this.playCurrentAnimationState(n,n.entry,0)}this._initialized=!0,this.onAnimationInitObservable&&this.onAnimationInitObservable.hasObservers()&&this.onAnimationInitObservable.notifyObservers(this.transform)}if(!0===this.enableAnimations){var i=e||this.getDeltaSeconds();this.updateAnimationState(i),this.onAnimationUpdateObservable&&this.onAnimationUpdateObservable.hasObservers()&&this.onAnimationUpdateObservable.notifyObservers(this.transform)}}else null==this.sourceAnimationGroups&&this.setupSourceAnimationGroups(),null!=this.sourceAnimationGroups&&(!1===this._executed&&(this._executed=!0,null!=this._machine.layers&&this._machine.layers.length>0&&this._machine.layers.forEach(function(e){t.playCurrentAnimationState(e,e.entry,0)}),this._initialized=!0,this.onAnimationInitObservable&&this.onAnimationInitObservable.hasObservers()&&this.onAnimationInitObservable.notifyObservers(this.transform)),!0===this.enableAnimations)&&(i=e||this.getDeltaSeconds(),this.updateAnimationState(i),this.updateAnimationTargets(i),this.onAnimationUpdateObservable&&this.onAnimationUpdateObservable.hasObservers()&&this.onAnimationUpdateObservable.notifyObservers(this.transform))},n.prototype.destroyStateMachine=function(){this._data=null,this._clips=null,this._anims=null,this._numbers=null,this._booleans=null,this._triggers=null,this._parameters=null,this._smoothTargets=null,this._checkers=null,this._machine=null,this.sourceAnimationGroups=null,this.onAnimationAwakeObservable.clear(),this.onAnimationAwakeObservable=null,this.onAnimationInitObservable.clear(),this.onAnimationInitObservable=null,this.onAnimationIKObservable.clear(),this.onAnimationIKObservable=null,this.onAnimationEndObservable.clear(),this.onAnimationEndObservable=null,this.onAnimationLoopObservable.clear(),this.onAnimationLoopObservable=null,this.onAnimationEventObservable.clear(),this.onAnimationEventObservable=null,this.onAnimationUpdateObservable.clear(),this.onAnimationUpdateObservable=null,this.onAnimationTransitionObservable.clear(),this.onAnimationTransitionObservable=null},n.prototype.updateAnimationState=function(e){var t=this;if(null!=this._machine.layers&&this._machine.layers.length>0)if(!0===this.m_vertexAnimationMode){var n=this._machine.layers[0];this.checkStateMachine(n,e),this.updateVertexAnimationLayer(n,e)}else this._machine.layers.forEach(function(n){t.checkStateMachine(n,e)})},n.prototype.updateVertexAnimationLayer=function(t,n){if(null!=this.m_vertexAnimationController&&null!=t&&null!=t.animationStateMachine){var i=t.animationStateMachine,r=i.blendtree;if(null!=r&&null!=r.children&&0!==r.children.length){var o="number"==typeof i.speed?i.speed:1,a=Math.abs(o)*Math.abs(this.speedRatio||1),s=null,l=null,u=1,c=0,d=0,h=!1;if(r.blendType===e.BlendTreeType.Clip){var p=r.children[0];if(null==p||!p.motion)return;var m=this.m_vertexAnimationController.getClip(p.motion);if(null==m||m.duration<=0)return;s=p.motion,c=m.duration,h=!!m.loop}else{var f=[];if(this.parseTreeBranches(t,r,1,f),0===f.length)return;this.sortWeightedBlendingList(f);var g=f[0],v=f.length>1?f[1]:null,y=g.weight||0,_=y+(v&&v.weight||0);u=_>0?y/_:1;var S=this.m_vertexAnimationController.getClip(g.motion);if(null==S||S.duration<=0)return;if(s=g.motion,c=S.duration,h=!!S.loop,null!=v){var A=this.m_vertexAnimationController.getClip(v.motion);null!=A&&A.duration>0&&(l=v.motion,d=A.duration)}}if(!(null==s||c<=0)){var b=e.AnimationState.TIME/c,M=b;if(null!=l&&d>0){var B=e.AnimationState.TIME/d;M=BABYLON.Scalar.Lerp(B,b,u)}var C=this.m_vertexAnimationController.loopOverride,T=null!==C?C:h;if(t.animationTime+=n*M*a,T){for(;t.animationTime>=e.AnimationState.TIME;)t.animationTime-=e.AnimationState.TIME,this.onAnimationLoopObservable&&this.onAnimationLoopObservable.hasObservers()&&this.onAnimationLoopObservable.notifyObservers(t.index);t.animationTime<0&&(t.animationTime+=e.AnimationState.TIME)}else t.animationTime>e.AnimationState.TIME&&(t.animationTime=e.AnimationState.TIME),t.animationTime<0&&(t.animationTime=0);t.animationNormal=e.AnimationState.TIME>0?t.animationTime/e.AnimationState.TIME:0;var x=o<0!=(this.speedRatio||1)<0?1-t.animationNormal:t.animationNormal,I=x*c,O=null!=l&&d>0?x*d:0;if(!0===t.vatTransitionActive&&t.vatTransitionDuration>0){t.vatTransitionElapsed=(t.vatTransitionElapsed||0)+n;var L=t.vatTransitionElapsed/t.vatTransitionDuration;L>=1&&(L=1,t.vatTransitionActive=!1,t.vatTransitionElapsed=0,t.vatTransitionDuration=0,t.vatSourceClipName=null,t.vatSourceTimeSec=0),this.m_vertexAnimationController.driveBlend(s,I,L<1&&t.vatSourceClipName||null,L<1&&t.vatSourceTimeSec||0,L)}else this.m_vertexAnimationController.driveBlend(s,I,l,O,u)}}}},n.prototype.updateAnimationTargets=function(t){var n=this;!0!==this.m_vertexAnimationMode&&(this._looptime=!1,this._loopblend=!1,this._ikFrameEanbled=!1,this._animationplaying=!1,null!=this._machine.layers&&this._machine.layers.length>0&&this._machine.layers.forEach(function(i){if(0===i.index&&(n._frametime=i.animationTime),null!=i.animationStateMachine&&null!=i.animationStateMachine.blendtree){!0===i.animationStateMachine.iKOnFeet&&(n._ikFrameEanbled=!0),!0===i.iKPass&&n.onAnimationIKObservable&&n.onAnimationIKObservable.hasObservers()&&n.onAnimationIKObservable.notifyObservers(i.index);var r=i.animationStateMachine;if(r.type===e.MotionType.Clip&&-1!==r.played&&(r.played+=t),null!=r.blendtree.children&&r.blendtree.children.length>0){var o=r.blendtree.children[0];if(null!=o)if(r.blendtree.blendType==e.BlendTreeType.Clip){var a=o.track;if(null!=a){var s=a.metadata.toolkit.length,l=s>0?e.AnimationState.TIME/s:0;i.animationTime+=t*l*Math.abs(r.speed)*Math.abs(n.speedRatio),i.animationTime>e.AnimationState.TIME&&(i.animationTime=e.AnimationState.TIME);var u=i.animationTime>0?BABYLON.Scalar.Clamp(i.animationTime/e.AnimationState.TIME,0,1):0,c=r.speed<0!=n.speedRatio<0;i.animationNormal=c?1-u:u;var d=i.animationNormal>=.99?1:i.animationNormal,h=(parseFloat(d.toFixed(3)),s*i.animationNormal),p=0,m=0,f=0,g=!1,v=!1,y=0,_=!0,S=!0,A=!0,b=a;if(null!=b.metadata&&null!=b.metadata.toolkit&&(null!=b.metadata.toolkit.averagespeed&&(m=null!=b.metadata.toolkit.averagespeed.x?b.metadata.toolkit.averagespeed.x:0,f=null!=b.metadata.toolkit.averagespeed.z?b.metadata.toolkit.averagespeed.z:0),null!=b.metadata.toolkit.settings&&(p=null!=b.metadata.toolkit.settings.level?b.metadata.toolkit.settings.level:0,g=null!=b.metadata.toolkit.settings.looptime&&b.metadata.toolkit.settings.looptime,v=null!=b.metadata.toolkit.settings.loopblend&&b.metadata.toolkit.settings.loopblend,y=null!=b.metadata.toolkit.settings.orientationoffsety?b.metadata.toolkit.settings.orientationoffsety:0,_=null==b.metadata.toolkit.settings.loopblendorientation||b.metadata.toolkit.settings.loopblendorientation,S=null==b.metadata.toolkit.settings.loopblendpositiony||b.metadata.toolkit.settings.loopblendpositiony,A=null==b.metadata.toolkit.settings.loopblendpositionxz||b.metadata.toolkit.settings.loopblendpositionxz)),0===i.index&&(n._looptime=g,n._loopblend=v),y=BABYLON.Tools.ToRadians(y),m=Math.abs(m),f=Math.abs(f),p*=-1,i.animationTime>=e.AnimationState.TIME&&(i.animationFirstRun=!1,i.animationLoopFrame=!0,!0===g?(i.animationLoopCount++,n.onAnimationLoopObservable&&n.onAnimationLoopObservable.hasObservers()&&n.onAnimationLoopObservable.notifyObservers(i.index)):!1===i.animationEndFrame&&(i.animationEndFrame=!0,n.onAnimationEndObservable&&n.onAnimationEndObservable.hasObservers()&&n.onAnimationEndObservable.notifyObservers(i.index))),!0!==i.animationFirstRun&&!0!==g||(n._animationplaying=!0,a.targetedAnimations.forEach(function(t){if(t.target instanceof BABYLON.TransformNode){var r=t.target;if(0===i.index||null==i.avatarMask||n.filterTargetAvatarMask(i,r)){var o=null!=r.metadata&&null!=r.metadata.toolkit&&null!=r.metadata.toolkit.rootbone&&r.metadata.toolkit.rootbone;if(!0===o&&null==n._rootBoneTransform&&(n._rootBoneTransform=r),null!=r.metadata&&null!=r.metadata.mixer){var a=r.metadata.mixer[i.index];if(null!=a)if("position"===t.animation.targetProperty)n._targetPosition=e.Utilities.SampleAnimationVector3(t.animation,h,BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE,!0),!0===o&&null!=n._rootBoneTransform?(n._positionWeight=!0,n._positionHolder.set(0,0,0),n._rootBoneWeight=!1,n._rootBoneHolder.set(0,0,0),!0===n.applyRootMotion?!0===S&&!0===A?(n._positionWeight=!0,n._positionHolder.set(n._targetPosition.x,n._targetPosition.y+p,n._targetPosition.z)):!1===S&&!1===A?(n._rootBoneWeight=!0,n._rootBoneHolder.set(n._targetPosition.x,n._targetPosition.y+p,n._targetPosition.z)):!0===S&&!1===A?(n._positionWeight=!0,n._positionHolder.set(n.m_zeroVector.x,n._targetPosition.y+p,n.m_zeroVector.z),n._rootBoneWeight=!0,n._rootBoneHolder.set(n._targetPosition.x,n.m_zeroVector.y,n._targetPosition.z)):!0===A&&!1===S&&(n._positionWeight=!0,n._positionHolder.set(n._targetPosition.x,n.m_zeroVector.y,n._targetPosition.z),n._rootBoneWeight=!0,n._rootBoneHolder.set(n.m_zeroVector.x,n._targetPosition.y+p,n.m_zeroVector.z)):(n._positionWeight=!0,n._positionHolder.set(n._targetPosition.x,n._targetPosition.y,n._targetPosition.z)),!0===n._positionWeight&&(null==a.positionBuffer&&(a.positionBuffer=new BABYLON.Vector3(0,0,0)),e.Utilities.BlendVector3Value(a.positionBuffer,n._positionHolder,1)),!0===n._rootBoneWeight&&(null==a.rootPosition&&(a.rootPosition=new BABYLON.Vector3(0,0,0)),e.Utilities.BlendVector3Value(a.rootPosition,n._rootBoneHolder,1))):(null==a.positionBuffer&&(a.positionBuffer=new BABYLON.Vector3(0,0,0)),e.Utilities.BlendVector3Value(a.positionBuffer,n._targetPosition,1));else if("rotationQuaternion"===t.animation.targetProperty)if(n._targetRotation=e.Utilities.SampleAnimationQuaternion(t.animation,h,BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE,!0),!0===o&&null!=n._rootBoneTransform){n._rotationWeight=!1,n._rotationHolder.copyFrom(n.m_rotationIdentity),n._rootQuatWeight=!1,n._rootQuatHolder.copyFrom(n.m_rotationIdentity);var s=n._targetRotation.toEulerAngles(),l=s.y;!0===n.applyRootMotion?!0===_?(n._rotationWeight=!0,BABYLON.Quaternion.FromEulerAnglesToRef(s.x,l+y,s.z,n._rotationHolder)):(n._rotationWeight=!0,BABYLON.Quaternion.FromEulerAnglesToRef(s.x,n.m_zeroVector.y,s.z,n._rotationHolder),n._rootQuatWeight=!0,BABYLON.Quaternion.FromEulerAnglesToRef(n.m_zeroVector.x,l+y,n.m_zeroVector.z,n._rootQuatHolder)):(n._rotationWeight=!0,BABYLON.Quaternion.FromEulerAnglesToRef(s.x,l+y,s.z,n._rotationHolder)),!0===n._rotationWeight&&(null==a.rotationBuffer&&(a.rotationBuffer=new BABYLON.Quaternion(0,0,0,0)),e.Utilities.BlendQuaternionValue(a.rotationBuffer,n._rotationHolder,1)),!0===n._rootQuatWeight&&(null==a.rootRotation&&(a.rootRotation=new BABYLON.Quaternion(0,0,0,0)),e.Utilities.BlendQuaternionValue(a.rootRotation,n._rootQuatHolder,1))}else null==a.rotationBuffer&&(a.rotationBuffer=new BABYLON.Quaternion(0,0,0,0)),e.Utilities.BlendQuaternionValue(a.rotationBuffer,n._targetRotation,1);else"scaling"===t.animation.targetProperty&&(n._targetScaling=e.Utilities.SampleAnimationVector3(t.animation,h,BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE,!0),null==a.scalingBuffer&&(a.scalingBuffer=new BABYLON.Vector3(1,1,1)),e.Utilities.BlendVector3Value(a.scalingBuffer,n._targetScaling,1))}}}else if(t.target instanceof BABYLON.MorphTarget){var u=t.target;if(null!=u.metadata&&null!=u.metadata.mixer){var c=u.metadata.mixer[i.index];if("influence"===t.animation.targetProperty){var d=e.Utilities.SampleAnimationFloat(t.animation,h,BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE,!0);null==c.influenceBuffer&&(c.influenceBuffer=0),c.influenceBuffer=e.Utilities.BlendFloatValue(c.influenceBuffer,d,1)}}}})),1==n._animationplaying&&(null!=i.animationStateMachine.tcurves&&i.animationStateMachine.tcurves.length>0&&i.animationStateMachine.tcurves.forEach(function(t){if(null!=t.targetProperty&&""!==t.targetProperty){var r=e.Utilities.SampleAnimationFloat(t,i.animationNormal,BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE,!0);n.setFloat(t.targetProperty,r)}}),null!=i.animationStateMachine.events&&i.animationStateMachine.events.length>0)){for(var M=void 0!==i._prevAnimationNormal?i._prevAnimationNormal:i.animationNormal,B=i.animationNormal,C=r.speed<0!=n.speedRatio<0?-1:1,T=function(e,t,n,i){return 1===i?e<=t?e<n&&n<=t:e<n&&n<=1||0<=n&&n<=t:e>=t?t<=n&&n<e:0<=n&&n<e||t<=n&&n<=1},x=0,I=i.animationStateMachine.events;x<I.length;x++)if(T(M,B,(G=I[x]).time,C)){var O=G.function+"_"+G.time;null==i.animationLoopEvents&&(i.animationLoopEvents={}),i.animationLoopEvents[O]||(i.animationLoopEvents[O]=!0,n.onAnimationEventObservable&&n.onAnimationEventObservable.hasObservers()&&n.onAnimationEventObservable.notifyObservers(G))}i._prevAnimationNormal=B}!0===i.animationLoopFrame&&(i.animationTime=0,i.animationNormal=0,i.animationLoopFrame=!1,i.animationLoopEvents=null)}}else{n._animationplaying=!0,n._blendWeights.primary=null,n._blendWeights.secondary=null;var L=[],w=r.blendtree;n.parseTreeBranches(i,w,1,L),l=n.computeWeightedFrameRatio(L),i.animationTime+=t*l*Math.abs(r.speed)*Math.abs(n.speedRatio),i.animationTime>e.AnimationState.TIME&&(i.animationTime=e.AnimationState.TIME),u=i.animationTime>0?BABYLON.Scalar.Clamp(i.animationTime/e.AnimationState.TIME,0,1):0,c=r.speed<0!=n.speedRatio<0,i.animationNormal=c?1-u:u,d=i.animationNormal>=.99?1:i.animationNormal,parseFloat(d.toFixed(3));var N=i.animationNormal;i.animationTime>=e.AnimationState.TIME&&(i.animationFirstRun=!1,i.animationLoopFrame=!0,i.animationLoopCount++);var P=null!=L&&L.length>0&&null!=L[0].track?L[0].track:null;if(null!=P)for(var R=P.targetedAnimations.length,E=0;E<R;E++){var k=P.targetedAnimations[E];if(k.target instanceof BABYLON.TransformNode){var D=k.target;if(0===i.index||null==i.avatarMask||n.filterTargetAvatarMask(i,D)){var F=null!=D.metadata&&null!=D.metadata.toolkit&&null!=D.metadata.toolkit.rootbone&&D.metadata.toolkit.rootbone;if(!0===F&&null==n._rootBoneTransform&&(n._rootBoneTransform=D),null!=D.metadata&&null!=D.metadata.mixer){n._initialtargetblending=!0;var U=D.metadata.mixer[i.index];n.updateBlendableTargets(t,i,w,k,E,U,N,F,D)}}}}if(null!=i.animationStateMachine.tcurves&&i.animationStateMachine.tcurves.length>0&&i.animationStateMachine.tcurves.forEach(function(t){if(null!=t.targetProperty&&""!==t.targetProperty){var r=e.Utilities.SampleAnimationFloat(t,i.animationNormal,BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE,!0);n.setFloat(t.targetProperty,r)}}),null!=i.animationStateMachine.events&&i.animationStateMachine.events.length>0){B=N,M=void 0!==i._prevBlendingNormal?i._prevBlendingNormal:B,C=r.speed<0!=n.speedRatio<0?-1:1,T=function(e,t,n,i){return 1===i?e<=t?e<n&&n<=t:e<n&&n<=1||0<=n&&n<=t:e>=t?t<=n&&n<e:0<=n&&n<e||t<=n&&n<=1};for(var Y=0,V=i.animationStateMachine.events;Y<V.length;Y++){var G;T(M,B,(G=V[Y]).time,C)&&(O=G.function+"_"+G.time,null==i.animationLoopEvents&&(i.animationLoopEvents={}),i.animationLoopEvents[O]||(i.animationLoopEvents[O]=!0,n.onAnimationEventObservable&&n.onAnimationEventObservable.hasObservers()&&n.onAnimationEventObservable.notifyObservers(G)))}i._prevBlendingNormal=B}!0===i.animationLoopFrame&&(i.animationTime=0,i.animationNormal=0,i.animationLoopFrame=!1,i.animationLoopEvents=null)}}}}),this.finalizeAnimationTargets(t))},n.prototype.updateBlendableTargets=function(t,n,i,r,o,a,s,l,u){if(!0!==this.m_vertexAnimationMode&&null!=a&&null!=i.children&&i.children.length>0)for(var c=0;c<i.children.length;c++){var d=i.children[c];if(d.weight>0)if(d.type===e.MotionType.Clip){if(null!=d.track){var h=0,p=0,m=0,f=!1,g=0,v=!0,y=!0,_=!0,S=d.track;null!=S.metadata&&null!=S.metadata.toolkit&&(null!=S.metadata.toolkit.averagespeed&&(p=null!=S.metadata.toolkit.averagespeed.x?S.metadata.toolkit.averagespeed.x:0,m=null!=S.metadata.toolkit.averagespeed.z?S.metadata.toolkit.averagespeed.z:0),null!=S.metadata.toolkit.settings&&(h=null!=S.metadata.toolkit.settings.level?S.metadata.toolkit.settings.level:0,f=null!=S.metadata.toolkit.settings.loopblend&&S.metadata.toolkit.settings.loopblend,g=null!=S.metadata.toolkit.settings.orientationoffsety?S.metadata.toolkit.settings.orientationoffsety:0,v=null==S.metadata.toolkit.settings.loopblendorientation||S.metadata.toolkit.settings.loopblendorientation,y=null==S.metadata.toolkit.settings.loopblendpositiony||S.metadata.toolkit.settings.loopblendpositiony,_=null==S.metadata.toolkit.settings.loopblendpositionxz||S.metadata.toolkit.settings.loopblendpositionxz)),0===n.index&&(this._looptime=!0,this._loopblend=f),g=BABYLON.Tools.ToRadians(g),p=Math.abs(p),m=Math.abs(m),h*=-1;var A=d.track.targetedAnimations[o],b=!0===this._initialtargetblending?1:parseFloat(d.weight.toFixed(2));if(this._initialtargetblending=!1,A.target===r.target&&A.animation.targetProperty===r.animation.targetProperty){var M=s;d.timescale<0&&(M=1-M);var B=d.track.metadata.toolkit.length*M;if("position"===r.animation.targetProperty)this._targetPosition=e.Utilities.SampleAnimationVector3(A.animation,B,BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE,!0),!0===l&&null!=this._rootBoneTransform?(this._positionWeight=!0,this._positionHolder.set(0,0,0),this._rootBoneWeight=!1,this._rootBoneHolder.set(0,0,0),!0===this.applyRootMotion?!0===y&&!0===_?(this._positionWeight=!0,this._positionHolder.set(this._targetPosition.x,this._targetPosition.y+h,this._targetPosition.z)):!1===y&&!1===_?(this._rootBoneWeight=!0,this._rootBoneHolder.set(this._targetPosition.x,this._targetPosition.y+h,this._targetPosition.z)):!0===y&&!1===_?(this._positionWeight=!0,this._positionHolder.set(this.m_zeroVector.x,this._targetPosition.y+h,this.m_zeroVector.z),this._rootBoneWeight=!0,this._rootBoneHolder.set(this._targetPosition.x,this.m_zeroVector.y,this._targetPosition.z)):!0===_&&!1===y&&(this._positionWeight=!0,this._positionHolder.set(this._targetPosition.x,this.m_zeroVector.y,this._targetPosition.z),this._rootBoneWeight=!0,this._rootBoneHolder.set(this.m_zeroVector.x,this._targetPosition.y+h,this.m_zeroVector.z)):(this._positionWeight=!0,this._positionHolder.set(this._targetPosition.x,this._targetPosition.y,this._targetPosition.z)),!0===this._positionWeight&&(null==a.positionBuffer&&(a.positionBuffer=new BABYLON.Vector3(0,0,0)),e.Utilities.BlendVector3Value(a.positionBuffer,this._positionHolder,b)),!0===this._rootBoneWeight&&(null==a.rootPosition&&(a.rootPosition=new BABYLON.Vector3(0,0,0)),e.Utilities.BlendVector3Value(a.rootPosition,this._rootBoneHolder,b))):(null==a.positionBuffer&&(a.positionBuffer=new BABYLON.Vector3(0,0,0)),e.Utilities.BlendVector3Value(a.positionBuffer,this._targetPosition,b));else if("rotationQuaternion"===r.animation.targetProperty)if(this._targetRotation=e.Utilities.SampleAnimationQuaternion(A.animation,B,BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE,!0),!0===l&&null!=this._rootBoneTransform){this._rotationWeight=!1,this._rotationHolder.copyFrom(this.m_rotationIdentity),this._rootQuatWeight=!1,this._rootQuatHolder.copyFrom(this.m_rotationIdentity);var C=this._targetRotation.toEulerAngles(),T=C.y;!0===this.applyRootMotion?!0===v?(this._rotationWeight=!0,BABYLON.Quaternion.FromEulerAnglesToRef(C.x,T+g,C.z,this._rotationHolder)):(this._rotationWeight=!0,BABYLON.Quaternion.FromEulerAnglesToRef(C.x,this.m_zeroVector.y,C.z,this._rotationHolder),this._rootQuatWeight=!0,BABYLON.Quaternion.FromEulerAnglesToRef(this.m_zeroVector.x,T+g,this.m_zeroVector.z,this._rootQuatHolder)):(this._rotationWeight=!0,BABYLON.Quaternion.FromEulerAnglesToRef(C.x,T+g,C.z,this._rotationHolder)),!0===this._rotationWeight&&(null==a.rotationBuffer&&(a.rotationBuffer=new BABYLON.Quaternion(0,0,0,0)),e.Utilities.BlendQuaternionValue(a.rotationBuffer,this._rotationHolder,b)),!0===this._rootQuatWeight&&(null==a.rootRotation&&(a.rootRotation=new BABYLON.Quaternion(0,0,0,0)),e.Utilities.BlendQuaternionValue(a.rootRotation,this._rootQuatHolder,b))}else null==a.rotationBuffer&&(a.rotationBuffer=new BABYLON.Quaternion(0,0,0,0)),e.Utilities.BlendQuaternionValue(a.rotationBuffer,this._targetRotation,b);else"scaling"===r.animation.targetProperty&&(this._targetScaling=e.Utilities.SampleAnimationVector3(A.animation,B,BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE,!0),null==a.scalingBuffer&&(a.scalingBuffer=new BABYLON.Vector3(1,1,1)),e.Utilities.BlendVector3Value(a.scalingBuffer,this._targetScaling,b))}}}else d.type===e.MotionType.Tree&&this.updateBlendableTargets(t,n,d.subtree,r,o,a,s,l,u)}},n.prototype.finalizeAnimationTargets=function(t){var n=this;if(!0!==this.m_vertexAnimationMode&&(this._deltaPosition.set(0,0,0),this._deltaRotation.set(0,0,0,0),this._angularVelocity.set(0,0,0),this._rootMotionSpeed=0,this._rootMotionMatrix.reset(),this._dirtyMotionMatrix=null,this._rootMotionPosition.set(0,0,0),this._rootMotionRotation.set(0,0,0,0),null!=this.m_animationTargets&&this.m_animationTargets.length>0&&this.m_animationTargets.forEach(function(t){var i=t.target;null!=i.metadata&&null!=i.metadata.mixer&&null!=n._machine.layers&&n._machine.layers.length>0&&(n._blenderMatrix.reset(),n._dirtyBlenderMatrix=null,n._machine.layers.forEach(function(t){var r=i.metadata.mixer[t.index];if(null!=r)if(i instanceof BABYLON.TransformNode){if(null==r.positionBuffer&&null==r.rotationBuffer&&null==r.scalingBuffer||(BABYLON.Matrix.ComposeToRef(r.scalingBuffer||i.scaling,r.rotationBuffer||i.rotationQuaternion,r.positionBuffer||i.position,n._updateMatrix),r.blendingSpeed>0&&(r.blendingFactor<=1&&null==r.originalMatrix&&(r.originalMatrix=BABYLON.Matrix.Compose(i.scaling,i.rotationQuaternion,i.position)),r.blendingFactor<=1&&null!=r.originalMatrix&&(e.Utilities.FastMatrixSlerp(r.originalMatrix,n._updateMatrix,r.blendingFactor,n._updateMatrix),r.blendingFactor+=r.blendingSpeed)),e.Utilities.FastMatrixSlerp(n._blenderMatrix,n._updateMatrix,t.defaultWeight,n._blenderMatrix),n._dirtyBlenderMatrix=!0,r.positionBuffer=null,r.rotationBuffer=null,r.scalingBuffer=null),n._emptyPosition.set(0,0,0),n._emptyRotation.set(0,0,0,0),n._emptyScaling.set(1,1,1),null!=r.rootPosition||null!=r.rootRotation){var o=n._emptyPosition,a=r.rootRotation?r.rootRotation.clone():n._emptyRotation,s=r.rootPosition?r.rootPosition.clone():n._emptyPosition;BABYLON.Matrix.ComposeToRef(o,a,s,n._updateMatrix),e.Utilities.FastMatrixSlerp(n._rootMotionMatrix,n._updateMatrix,t.defaultWeight,n._rootMotionMatrix),n._dirtyMotionMatrix=!0,r.rootPosition=null,r.rootRotation=null}}else i instanceof BABYLON.MorphTarget&&null!=r.influenceBuffer&&(i.influence=BABYLON.Scalar.Lerp(i.influence,r.influenceBuffer,t.defaultWeight),r.influenceBuffer=null)}),null!=n._dirtyBlenderMatrix&&n._blenderMatrix.decompose(i.scaling,i.rotationQuaternion,i.position))}),!0===this.applyRootMotion&&null!=this._dirtyMotionMatrix)){if(this._rootMotionMatrix.decompose(this._rootMotionScaling,this._rootMotionRotation,this._rootMotionPosition),!0===this.isFirstFrame())this._deltaPosition.copyFrom(this._rootMotionPosition),this._deltaRotation.copyFrom(this._rootMotionRotation);else if(!0===this.isLastFrame()){if(this._rootMotionPosition.subtractToRef(this._lastMotionPosition,this._deltaPosition),e.Utilities.QuaternionDiffToRef(this._rootMotionRotation,this._lastMotionRotation,this._deltaRotation),!0===this._looptime&&!0===this._loopblend){var i=this._loopMotionSpeed+this._lastMotionSpeed;0!==i&&(i/=2),this._deltaPosition.normalize(),this._deltaPosition.scaleInPlace(i*t);var r=this._loopRotateSpeed+this._lastRotateSpeed;0!==r&&(r/=2),this._deltaRotation.toEulerAnglesToRef(this._angularVelocity),BABYLON.Quaternion.FromEulerAnglesToRef(this._angularVelocity.x,r,this._angularVelocity.z,this._deltaRotation)}}else this._rootMotionPosition.subtractToRef(this._lastMotionPosition,this._deltaPosition),e.Utilities.QuaternionDiffToRef(this._rootMotionRotation,this._lastMotionRotation,this._deltaRotation);var o=this._deltaPosition.length();this._rootMotionSpeed=o>0?o/t:o,this._deltaRotation.toEulerAnglesToRef(this._angularVelocity),this._lastMotionPosition.copyFrom(this._rootMotionPosition),this._lastMotionRotation.copyFrom(this._rootMotionRotation),this._lastMotionSpeed=this._rootMotionSpeed,this._lastRotateSpeed=this._angularVelocity.y,0===this._frametime&&(this._loopMotionSpeed=this._rootMotionSpeed,this._loopRotateSpeed=this._angularVelocity.y)}},n.prototype.checkStateMachine=function(e,t){var n=this;if(this._checkers.result=null,this._checkers.offest=0,this._checkers.blending=0,this._checkers.duration=0,this._checkers.triggered=[],null!=e.animationStateMachine&&(e.animationStateMachine.time+=t,this.checkStateTransitions(e,e.animationStateMachine.transitions),null==this._checkers.result&&null!=this._machine.transitions&&this.checkStateTransitions(e,this._machine.transitions)),null!=this._checkers.triggered&&this._checkers.triggered.length>0&&(this._checkers.triggered.forEach(function(e){n.resetTrigger(e)}),this._checkers.triggered=null),null!=this._checkers.result){this.onAnimationTransitionObservable&&this.onAnimationTransitionObservable.hasObservers()&&this.onAnimationTransitionObservable.notifyObservers(this.transform);var i=!0===this.m_vertexAnimationMode?this._checkers.duration:this._checkers.blending;this.playCurrentAnimationState(e,this._checkers.result,i,this._checkers.offest)}},n.prototype.checkStateTransitions=function(t,n){var i=this,r=t.animationStateMachine.rate,o=t.animationStateMachine.length;if(null!=n&&n.length>0){var a=0,s=-1;for(a=0;a<n.length;a++)if(!0===n[a].solo&&!1===n[a].mute){s=a;break}var l=function(){var l=n[a];if(l.layerIndex!==t.index)return"continue";if(!0===l.mute)return"continue";if(s>=0&&s!==a)return"continue";var c=!1,d=0,h=!0;if(l.exitTime>0&&(d=o*l.exitTime/u.speedRatio,h=!0!==l.hasExitTime||t.animationStateMachine.time>=d),!0===l.hasExitTime&&l.intSource==e.InterruptionSource.None&&!1===h)return"continue";if(null!=l.conditions&&l.conditions.length>0){var p=0,m=l.conditions.length;l.conditions.forEach(function(t){var n=i._parameters.get(t.parameter);if(null!=n)if(n==e.AnimatorParameterType.Float||n==e.AnimatorParameterType.Int){var r=parseFloat(i.getFloat(t.parameter).toFixed(2));(t.mode===e.ConditionMode.Greater&&r>t.threshold||t.mode===e.ConditionMode.Less&&r<t.threshold||t.mode===e.ConditionMode.Equals&&r===t.threshold||t.mode===e.ConditionMode.NotEqual&&r!==t.threshold)&&p++}else if(n==e.AnimatorParameterType.Bool){var o=i.getBool(t.parameter);(t.mode===e.ConditionMode.If&&!0===o||t.mode===e.ConditionMode.IfNot&&!1===o)&&p++}else if(n==e.AnimatorParameterType.Trigger&&!0===i.getTrigger(t.parameter)){p++;for(var a=-1,s=0;s<i._checkers.triggered.length;s++)if(i._checkers.triggered[s]===t.parameter){a=s;break}a<0&&i._checkers.triggered.push(t.parameter)}}),c=!0===l.hasExitTime?!0===h&&p===m:p===m}else c=!0===l.hasExitTime&&!0===h;if(!0===c){!0===l.hasExitTime&&!0===h&&u.onAnimationEndObservable&&u.onAnimationEndObservable.hasObservers()&&u.onAnimationEndObservable.notifyObservers(t.index);var f=r>0?r:e.AnimationState.FPS,g=!1===l.isExit?l.destination:e.AnimationState.EXIT,v=!0===l.fixedDuration?l.duration:BABYLON.Scalar.Denormalize(l.duration,0,o),y=e.Utilities.ComputeBlendingSpeed(f,v),_=l.offset;return u._checkers.result=g,u._checkers.offest=_,u._checkers.blending=y,u._checkers.duration=v,"break"}},u=this;for(a=0;a<n.length&&"break"!==l();a++);}},n.prototype.playCurrentAnimationState=function(t,n,i,r){if(void 0===r&&(r=0),null!=t&&null!=n&&""!==n&&n!==e.AnimationState.EXIT&&(null==t.animationStateMachine||t.animationStateMachine.name!==n)){null!=this.m_animationTargets&&this.m_animationTargets.length>0&&this.m_animationTargets.forEach(function(e){var n=e.target;if(null!=n.metadata&&null!=n.metadata.mixer){var r=n.metadata.mixer[t.index];null!=r&&(r.originalMatrix=null,r.blendingFactor=0,r.blendingSpeed=i)}});var o=this.getMachineState(n);if(null!=o&&o.layerIndex===t.index&&(o.time=0,o.played=0,o.interrupted=!1,t.animationTime=BABYLON.Scalar.Clamp(r),t.animationNormal=0,t.animationFirstRun=!0,t.animationEndFrame=!1,t.animationLoopFrame=!1,t.animationLoopCount=0,t.animationLoopEvents=null,t.animationStateMachine=o,this._deltaPosition.set(0,0,0),this._deltaRotation.set(0,0,0,0),this._angularVelocity.set(0,0,0),this._rootMotionSpeed=0,this._rootMotionMatrix.reset(),this._dirtyMotionMatrix=null,this._rootMotionPosition.set(0,0,0),this._rootMotionRotation.set(0,0,0,0),this._lastMotionPosition.set(0,0,0),this._lastMotionRotation.set(0,0,0,0),!0===this.m_vertexAnimationMode&&null!=this.m_vertexAnimationController)){var a=this.m_vertexAnimationController.currentClip;i>0&&null!=a?(t.vatTransitionActive=!0,t.vatTransitionElapsed=0,t.vatTransitionDuration=i,t.vatSourceClipName=a.name,t.vatSourceTimeSec=this.m_vertexAnimationController.currentTime):(t.vatTransitionActive=!1,t.vatTransitionElapsed=0,t.vatTransitionDuration=0,t.vatSourceClipName=null,t.vatSourceTimeSec=0)}}},n.prototype.stopCurrentAnimationState=function(e){null!=e&&(null!=this.m_animationTargets&&this.m_animationTargets.length>0&&this.m_animationTargets.forEach(function(t){var n=t.target;if(null!=n.metadata&&null!=n.metadata.mixer){var i=n.metadata.mixer[e.index];null!=i&&(i.originalMatrix=null,i.blendingFactor=0,i.blendingSpeed=0)}}),e.animationTime=0,e.animationNormal=0,e.animationFirstRun=!0,e.animationEndFrame=!1,e.animationLoopFrame=!1,e.animationLoopCount=0,e.animationLoopEvents=null,e.animationStateMachine=null,this._deltaPosition.set(0,0,0),this._deltaRotation.set(0,0,0,0),this._angularVelocity.set(0,0,0),this._rootMotionSpeed=0,this._rootMotionMatrix.reset(),this._dirtyMotionMatrix=null,this._rootMotionPosition.set(0,0,0),this._rootMotionRotation.set(0,0,0,0),this._lastMotionPosition.set(0,0,0),this._lastMotionRotation.set(0,0,0,0),!0===this.m_vertexAnimationMode&&null!=this.m_vertexAnimationController&&(this.m_vertexAnimationController.stop(),e.vatTransitionActive=!1,e.vatTransitionElapsed=0,e.vatTransitionDuration=0,e.vatSourceClipName=null,e.vatSourceTimeSec=0))},n.prototype.checkAvatarTransformPath=function(e,t){var n=!1;if(null!=e.animationMaskMap){var i=e.animationMaskMap.get(t);null!=i&&i>=0&&(n=!0)}return n},n.prototype.filterTargetAvatarMask=function(e,t){var n=!1;if(null!=t.metadata&&null!=t.metadata.toolkit&&null!=t.metadata.toolkit.bone&&""!==t.metadata.toolkit.bone){var i=t.metadata.toolkit.bone;n=this.checkAvatarTransformPath(e,i)}return n},n.prototype.sortWeightedBlendingList=function(e){null!=e&&e.length>0&&e.sort(function(e,t){return e.weight<t.weight?1:e.weight>t.weight?-1:0})},n.prototype.computeWeightedFrameRatio=function(e){var t=1;if(null!=e&&e.length>0)if(this.sortWeightedBlendingList(e),this._blendWeights.primary=e[0],this._blendWeights.primary.weight<1&&e.length>1&&(this._blendWeights.secondary=e[1]),null!=this._blendWeights.primary&&null!=this._blendWeights.secondary){var n=BABYLON.Scalar.Clamp(this._blendWeights.primary.weight);t=BABYLON.Scalar.Lerp(this._blendWeights.secondary.ratio,this._blendWeights.primary.ratio,n)}else null!=this._blendWeights.primary&&null==this._blendWeights.secondary&&(t=this._blendWeights.primary.ratio);return t},n.prototype.getFirstMotion=function(t){var n;if(!(null===(n=null==t?void 0:t.children)||void 0===n?void 0:n.length))return null;for(var i=0,r=t.children;i<r.length;i++){var o=r[i];if(o.type===e.MotionType.Clip)return o.motion;if(o.type===e.MotionType.Tree){var a=this.getFirstMotion(o.subtree);if(null!=a)return a}}return null},n.prototype.getLastMotion=function(t){var n;if(!(null===(n=null==t?void 0:t.children)||void 0===n?void 0:n.length))return null;for(var i=t.children.length-1;i>=0;i--){var r=t.children[i];if(r.type===e.MotionType.Clip)return r.motion;if(r.type===e.MotionType.Tree){var o=this.getLastMotion(r.subtree);if(null!=o)return o}}return null},n.prototype.setupTreeBranches=function(t){var n=this;null!=t&&null!=t.children&&t.children.length>0&&t.children.forEach(function(t){if(t.type===e.MotionType.Tree)n.setupTreeBranches(t.subtree);else if(t.type===e.MotionType.Clip&&null!=t.motion&&""!==t.motion&&(t.weight=0,t.ratio=0,t.track=n.getAnimationGroup(t.motion),null!=t.track)){var i=t.track.metadata.toolkit.length;t.ratio=e.AnimationState.TIME/i}})},n.prototype.parseTreeBranches=function(t,n,i,r){if(null!=n)switch(n.valueParameterX=null!=n.blendParameterX?parseFloat(this.getFloat(n.blendParameterX).toFixed(2)):0,n.valueParameterY=null!=n.blendParameterY?parseFloat(this.getFloat(n.blendParameterY).toFixed(2)):0,n.blendType){case e.BlendTreeType.Simple1D:this.parse1DSimpleTreeBranches(t,n,i,r);break;case e.BlendTreeType.SimpleDirectional2D:this.parse2DSimpleDirectionalTreeBranches(t,n,i,r);break;case e.BlendTreeType.FreeformDirectional2D:this.parse2DFreeformDirectionalTreeBranches(t,n,i,r);break;case e.BlendTreeType.FreeformCartesian2D:this.parse2DFreeformCartesianTreeBranches(t,n,i,r)}},n.prototype.parse1DSimpleTreeBranches=function(t,n,i,r){var o=this;if(null!=n&&null!=n.children&&n.children.length>0){var a=[];n.children.forEach(function(e){e.weight=0;var t={source:e,motion:e.motion,posX:e.threshold,posY:e.threshold,weight:e.weight};a.push(t)}),e.BlendTreeSystem.Calculate1DSimpleBlendTree(n.valueParameterX,a),a.forEach(function(e){null!=e.source&&(e.source.weight=e.weight)}),n.children.forEach(function(n){n.weight*=i,n.type===e.MotionType.Clip&&n.weight>0&&r.push(n),n.type===e.MotionType.Tree&&o.parseTreeBranches(t,n.subtree,n.weight,r)})}},n.prototype.parse2DSimpleDirectionalTreeBranches=function(t,n,i,r){var o=this;if(null!=n&&null!=n.children&&n.children.length>0){var a=[];n.children.forEach(function(e){e.weight=0;var t={source:e,motion:e.motion,posX:e.positionX,posY:e.positionY,weight:e.weight};a.push(t)}),e.BlendTreeSystem.Calculate2DFreeformDirectional(n.valueParameterX,n.valueParameterY,a),a.forEach(function(e){null!=e.source&&(e.source.weight=e.weight)}),n.children.forEach(function(n){n.weight*=i,n.type===e.MotionType.Clip&&n.weight>0&&r.push(n),n.type===e.MotionType.Tree&&o.parseTreeBranches(t,n.subtree,n.weight,r)})}},n.prototype.parse2DFreeformDirectionalTreeBranches=function(t,n,i,r){var o=this;if(null!=n&&null!=n.children&&n.children.length>0){var a=[];n.children.forEach(function(e){e.weight=0;var t={source:e,motion:e.motion,posX:e.positionX,posY:e.positionY,weight:e.weight};a.push(t)}),e.BlendTreeSystem.Calculate2DFreeformDirectional(n.valueParameterX,n.valueParameterY,a),a.forEach(function(e){null!=e.source&&(e.source.weight=e.weight)}),n.children.forEach(function(n){n.weight*=i,n.type===e.MotionType.Clip&&n.weight>0&&r.push(n),n.type===e.MotionType.Tree&&o.parseTreeBranches(t,n.subtree,n.weight,r)})}},n.prototype.parse2DFreeformCartesianTreeBranches=function(t,n,i,r){var o=this;if(null!=n&&null!=n.children&&n.children.length>0){var a=[];n.children.forEach(function(e){e.weight=0;var t={source:e,motion:e.motion,posX:e.positionX,posY:e.positionY,weight:e.weight};a.push(t)}),e.BlendTreeSystem.Calculate2DFreeformCartesian(n.valueParameterX,n.valueParameterY,a),a.forEach(function(e){null!=e.source&&(e.source.weight=e.weight)}),n.children.forEach(function(n){n.weight*=i,n.type===e.MotionType.Clip&&n.weight>0&&r.push(n),n.type===e.MotionType.Tree&&o.parseTreeBranches(t,n.subtree,n.weight,r)})}},n.FPS=30,n.EXIT="[EXIT]",n.TIME=1,n}(e.ScriptComponent);e.AnimationState=t;e.BlendTreeValue=function(e){this.source=e.source,this.motion=e.motion,this.posX=e.posX||0,this.posY=e.posY||0,this.weight=e.weight||0};var n=function(){function e(){}return e.ClampValue=function(e,t,n){return e<=t?t:e>=n?n:e},e.GetSignedAngle=function(e,t){return Math.atan2(e.x*t.y-e.y*t.x,e.x*t.x+e.y*t.y)},e.GetLinearInterpolation=function(e,t,n,i,r){return t+(i-t)/(n-e)*(r-e)},e.GetRightNeighbourIndex=function(e,t){t.sort(function(e,t){return e.posX-t.posX});for(var n=0;n<t.length;++n)if(t[n].posX>e)return n;return-1},e}();e.BlendTreeUtils=n;var i=function(){function t(){}return t.Calculate1DSimpleBlendTree=function(t,n){var i=n[0],r=n[n.length-1];if(t<=i.posX)i.weight=1;else if(t>=r.posX)r.weight=1;else{var o=e.BlendTreeUtils.GetRightNeighbourIndex(t,n),a=n[o-1],s=n[o],l=e.BlendTreeUtils.GetLinearInterpolation(a.posX,1,s.posX,0,t);a.weight=l,s.weight=1-a.weight}},t.Calculate2DFreeformDirectional=function(t,n,i){e.BlendTreeSystem.TempVector2_IP.set(t,n),e.BlendTreeSystem.TempVector2_POSI.set(0,0),e.BlendTreeSystem.TempVector2_POSJ.set(0,0),e.BlendTreeSystem.TempVector2_POSIP.set(0,0),e.BlendTreeSystem.TempVector2_POSIJ.set(0,0);for(var r=0,o=e.BlendTreeSystem.TempVector2_IP.length(),a=0;a<i.length;++a){var s=i[a];e.BlendTreeSystem.TempVector2_POSI.set(s.posX,s.posY);for(var l=e.BlendTreeSystem.TempVector2_POSI.length(),u=o-l,c=e.BlendTreeUtils.GetSignedAngle(e.BlendTreeSystem.TempVector2_POSI,e.BlendTreeSystem.TempVector2_IP),d=1,h=0;h<i.length;++h)if(h!==a){e.BlendTreeSystem.TempVector2_POSJ.set(i[h].posX,i[h].posY);var p=e.BlendTreeSystem.TempVector2_POSJ.length(),m=(l+p)/2,f=u/m,g=(p-l)/m,v=e.BlendTreeUtils.GetSignedAngle(e.BlendTreeSystem.TempVector2_POSI,e.BlendTreeSystem.TempVector2_POSJ);e.BlendTreeSystem.TempVector2_POSIP.set(f,2*c),e.BlendTreeSystem.TempVector2_POSIJ.set(g,2*v);var y=e.BlendTreeSystem.TempVector2_POSIJ.lengthSquared(),_=BABYLON.Vector2.Dot(e.BlendTreeSystem.TempVector2_POSIP,e.BlendTreeSystem.TempVector2_POSIJ)/y;_=1-_,_=e.BlendTreeUtils.ClampValue(_,0,1),d=Math.min(_,d)}s.weight=d,r+=d}for(var S=0,A=i;S<A.length;S++)(s=A[S]).weight/=r},t.Calculate2DFreeformCartesian=function(t,n,i){e.BlendTreeSystem.TempVector2_IP.set(t,n),e.BlendTreeSystem.TempVector2_POSI.set(0,0),e.BlendTreeSystem.TempVector2_POSJ.set(0,0),e.BlendTreeSystem.TempVector2_POSIP.set(0,0),e.BlendTreeSystem.TempVector2_POSIJ.set(0,0);for(var r=0,o=0;o<i.length;++o){var a=i[o];e.BlendTreeSystem.TempVector2_POSI.set(a.posX,a.posY),e.BlendTreeSystem.TempVector2_IP.subtractToRef(e.BlendTreeSystem.TempVector2_POSI,e.BlendTreeSystem.TempVector2_POSIP);for(var s=1,l=0;l<i.length;++l)if(l!==o){e.BlendTreeSystem.TempVector2_POSJ.set(i[l].posX,i[l].posY),e.BlendTreeSystem.TempVector2_POSJ.subtractToRef(e.BlendTreeSystem.TempVector2_POSI,e.BlendTreeSystem.TempVector2_POSIJ);var u=e.BlendTreeSystem.TempVector2_POSIJ.lengthSquared(),c=BABYLON.Vector2.Dot(e.BlendTreeSystem.TempVector2_POSIP,e.BlendTreeSystem.TempVector2_POSIJ)/u;c=1-c,c=e.BlendTreeUtils.ClampValue(c,0,1),s=Math.min(s,c)}a.weight=s,r+=s}for(var d=0,h=i;d<h.length;d++)(a=h[d]).weight/=r},t.TempVector2_IP=new BABYLON.Vector2(0,0),t.TempVector2_POSI=new BABYLON.Vector2(0,0),t.TempVector2_POSJ=new BABYLON.Vector2(0,0),t.TempVector2_POSIP=new BABYLON.Vector2(0,0),t.TempVector2_POSIJ=new BABYLON.Vector2(0,0),t}();e.BlendTreeSystem=i;e.MachineState=function(){};e.TransitionCheck=function(){};e.AnimationMixer=function(){};var o,a,s,l,u,c;e.BlendingWeights=function(){},(c=e.MotionType||(e.MotionType={}))[c.Clip=0]="Clip",c[c.Tree=1]="Tree",(u=e.ConditionMode||(e.ConditionMode={}))[u.If=1]="If",u[u.IfNot=2]="IfNot",u[u.Greater=3]="Greater",u[u.Less=4]="Less",u[u.Equals=6]="Equals",u[u.NotEqual=7]="NotEqual",(l=e.InterruptionSource||(e.InterruptionSource={}))[l.None=0]="None",l[l.Source=1]="Source",l[l.Destination=2]="Destination",l[l.SourceThenDestination=3]="SourceThenDestination",l[l.DestinationThenSource=4]="DestinationThenSource",(s=e.BlendTreeType||(e.BlendTreeType={}))[s.Simple1D=0]="Simple1D",s[s.SimpleDirectional2D=1]="SimpleDirectional2D",s[s.FreeformDirectional2D=2]="FreeformDirectional2D",s[s.FreeformCartesian2D=3]="FreeformCartesian2D",s[s.Direct=4]="Direct",s[s.Clip=5]="Clip",(a=e.BlendTreePosition||(e.BlendTreePosition={}))[a.Lower=0]="Lower",a[a.Upper=1]="Upper",(o=e.AnimatorParameterType||(e.AnimatorParameterType={}))[o.Float=1]="Float",o[o.Int=3]="Int",o[o.Bool=4]="Bool",o[o.Trigger=9]="Trigger",e.SceneManager.RegisterClass("TOOLKIT.AnimationState",t)}(i||(i={})),function(e){var t=function(t){function n(e,n,i,r){void 0===i&&(i={}),void 0===r&&(r="TOOLKIT.AudioSource");var o=t.call(this,e,n,i,r)||this;return o._audio=null,o._name=null,o._loop=!1,o._mute=!1,o._pitch=1,o._volume=1,o._preload=!1,o._playonawake=!0,o._spatialblend=0,o._preloaderUrl=null,o._lastmutedvolume=null,o._priority=128,o._panstereo=0,o._mindistance=1,o._maxdistance=200,o._reverbzonemix=1,o._bypasseffects=!1,o._bypassreverbzones=!1,o._bypasslistenereffects=!1,o._initializedReadyInstance=!1,o._isAudioPlaying=!1,o._isAudioPaused=!1,o._isAudioSpatial=!1,o.onReadyObservable=new BABYLON.Observable,o}return r(n,t),n.prototype.getSoundClip=function(){return this._audio},n.prototype.awake=function(){this.awakeAudioSource()},n.prototype.start=function(){this.startAudioSource()},n.prototype.after=function(){this.updateAudioSource()},n.prototype.destroy=function(){this.destroyAudioSource()},n.prototype.awakeAudioSource=function(){return a(this,void 0,void 0,function(){var t,n,i;return s(this,function(r){switch(r.label){case 0:return this._name=this.getProperty("name",this._name),this._loop=this.getProperty("loop",this._loop),this._mute=this.getProperty("mute",this._mute),this._pitch=this.getProperty("pitch",this._pitch),this._volume=this.getProperty("volume",this._volume),this._preload=this.getProperty("preload",this._preload),this._priority=this.getProperty("priority",this._priority),this._panstereo=this.getProperty("panstereo",this._panstereo),this._playonawake=this.getProperty("playonawake",this._playonawake),this._mindistance=this.getProperty("mindistance",this._mindistance),this._maxdistance=this.getProperty("maxdistance",this._maxdistance),this._spatialblend=this.getProperty("spatialblend",this._spatialblend),this._reverbzonemix=this.getProperty("reverbzonemix",this._reverbzonemix),this._bypasseffects=this.getProperty("bypasseffects",this._bypasseffects),this._bypassreverbzones=this.getProperty("bypassreverbzones",this._bypassreverbzones),this._bypasslistenereffects=this.getProperty("bypasslistenereffects",this._bypasslistenereffects),null!=this._name&&""!==this._name||(this._name="Unknown"),null==(t=this.getProperty("file"))||""===t?[3,4]:(n=e.SceneManager.GetRootUrl(this.scene),null==(i=n+t)||""===i?[3,4]:!0!==this._preload?[3,1]:(this._preloaderUrl=i,[3,4]));case 1:return this.isLegacy()?(this.setLegacyDataSource(i),[3,4]):[3,2];case 2:return[4,this.setAudioDataSource(i)];case 3:r.sent(),r.label=4;case 4:return[2]}})})},n.prototype.startAudioSource=function(){this._volume>=e.AudioSource.MAX_VOLUME&&(this._volume=e.AudioSource.DEFAULT_LEVEL)},n.prototype.updateAudioSource=function(){return a(this,void 0,void 0,function(){return s(this,function(e){return!0===this._isAudioSpatial&&(this._audio,BABYLON.StaticSound),[2]})})},n.prototype.destroyAudioSource=function(){this.onReadyObservable.clear(),this.onReadyObservable=null,null!=this._audio&&(this._audio.dispose(),this._audio=null)},n.prototype.isLegacy=function(){return!!BABYLON.Engine.audioEngine},n.prototype.isReady=function(){return null!=this._audio},n.prototype.isPlaying=function(){return this._isAudioPlaying},n.prototype.isPaused=function(){return this._isAudioPaused},n.prototype.play=function(t,n,i){return a(this,void 0,void 0,function(){return s(this,function(r){switch(r.label){case 0:return[4,e.AudioSource.UnlockAudioEngine()];case 1:return r.sent(),this.internalPlay(t,n,i),[2,!0]}})})},n.prototype.internalPlay=function(e,t,n){var i=this;null!=this._audio&&(!0===this._initializedReadyInstance?(this._audio instanceof BABYLON.StaticSound?this._audio.play({waitTime:e,startOffset:t,duration:n}):this._audio instanceof BABYLON.Sound&&this._audio.play(e,t,n),this._isAudioPlaying=!0,this._isAudioPaused=!1):this.onReadyObservable.addOnce(function(){i._audio instanceof BABYLON.StaticSound?i._audio.play({waitTime:e,startOffset:t,duration:n}):i._audio instanceof BABYLON.Sound&&i._audio.play(e,t,n),i._isAudioPlaying=!0,i._isAudioPaused=!1}))},n.prototype.pause=function(){var e=!1;return null!=this._audio&&(this._audio.pause(),this._isAudioPlaying=!1,this._isAudioPaused=!0,e=!0),e},n.prototype.stop=function(e){var t=!1;return null!=this._audio&&(this._audio instanceof BABYLON.StaticSound?this._audio.stop({waitTime:e}):this._audio instanceof BABYLON.Sound&&this._audio.stop(e),this._isAudioPlaying=!1,this._isAudioPaused=!1,t=!0),t},n.prototype.mute=function(t){var n=this,i=!1;return null!=this._audio&&(this._audio instanceof BABYLON.StaticSound?null!=t&&t>0?e.WindowManager.SetTimeout(t/1e3,function(){n._lastmutedvolume=n._audio.volume,n._audio.volume=0}):(this._lastmutedvolume=this._audio.volume,this._audio.volume=0):this._audio instanceof BABYLON.Sound&&(this._lastmutedvolume=this._audio.getVolume(),this._audio.setVolume(0,t)),i=!0),i},n.prototype.unmute=function(t){var n=this,i=!1;return null!=this._audio&&(this._audio instanceof BABYLON.StaticSound?null!=t&&t>0?e.WindowManager.SetTimeout(t/1e3,function(){null!=n._lastmutedvolume&&(n._audio.volume=n._lastmutedvolume,n._lastmutedvolume=null)}):null!=this._lastmutedvolume&&(this._audio.volume=this._lastmutedvolume,this._lastmutedvolume=null):this._audio instanceof BABYLON.Sound&&null!=this._lastmutedvolume&&(this._audio.setVolume(this._lastmutedvolume,t),this._lastmutedvolume=null),i=!0),i},n.prototype.getPitch=function(){return null==this._audio?0:this._audio instanceof BABYLON.StaticSound?this._audio.playbackRate:this._audio instanceof BABYLON.Sound?this._audio.getPlaybackRate():void 0},n.prototype.setPitch=function(e){null!=this._audio&&(this._audio instanceof BABYLON.StaticSound?this._audio.playbackRate=e:this._audio instanceof BABYLON.Sound&&this._audio.setPlaybackRate(e))},n.prototype.getVolume=function(){var e=0;return null!=this._audio?this._audio instanceof BABYLON.StaticSound?e=this._audio.volume:this._audio instanceof BABYLON.Sound&&(e=this._audio.getVolume()):e=this._volume,e},n.prototype.setVolume=function(t,n){var i=this;return this._volume=t,null!=this._audio&&(this._audio instanceof BABYLON.StaticSound?null!=n&&n>0?e.WindowManager.SetTimeout(n/1e3,function(){i._audio.volume=i._volume}):this._audio.volume=this._volume:this._audio instanceof BABYLON.Sound&&this._audio.setVolume(this._volume,n)),!0},n.prototype.setPosition=function(e){this._audio instanceof BABYLON.StaticSound?null!=this._audio.spatial&&(this._audio.spatial.position=e):this._audio instanceof BABYLON.Sound&&this._audio.setPosition(e)},n.prototype.getPlaybackSpeed=function(){return null==this._audio?0:this._audio instanceof BABYLON.StaticSound?this._audio.playbackRate:this._audio instanceof BABYLON.Sound?this._audio.getPlaybackRate():void 0},n.prototype.setPlaybackSpeed=function(e){null!=this._audio&&(this._audio instanceof BABYLON.StaticSound?this._audio.playbackRate=e:this._audio instanceof BABYLON.Sound&&this._audio.setPlaybackRate(e))},n.prototype.setRolloffMode=function(e){null!=this._audio&&(this._audio instanceof BABYLON.StaticSound&&("linear"===e||"inverse"===e||"exponential"===e)?null!=this._audio.spatial&&(this._audio.spatial.distanceModel=e):(this._audio,BABYLON.Sound))},n.prototype.setMinDistance=function(e){null!=this._audio&&(this._audio instanceof BABYLON.StaticSound?null!=this._audio.spatial&&(this._audio.spatial.minDistance=Math.max(1,e)):this._audio instanceof BABYLON.Sound&&(this._audio.refDistance=e))},n.prototype.setMaxDistance=function(e){null!=this._audio&&(this._audio instanceof BABYLON.StaticSound?null!=this._audio.spatial&&(this._audio.spatial.maxDistance=e):this._audio instanceof BABYLON.Sound&&(this._audio.maxDistance=e))},n.prototype.setSpatialBlend=function(e){null!=this._audio&&(this._audio instanceof BABYLON.StaticSound||(this._audio,BABYLON.Sound))},n.prototype.hasSpatialSound=function(){var e=!1;return null!=this._audio&&(this._audio instanceof BABYLON.StaticSound?e=null!=this._audio.spatial:this._audio instanceof BABYLON.Sound&&(e=this._audio.spatialSound)),e},n.prototype.getSpatialSound=function(){var e=null;return null!=this._audio&&this._audio instanceof BABYLON.StaticSound&&(e=this._audio.spatial),e},n.prototype.attachToSpatialNode=function(e){null!=this._audio&&(this._audio instanceof BABYLON.StaticSound?null!=this._audio.spatial&&this._audio.spatial.attach(e,!0,BABYLON.SpatialAudioAttachmentType.PositionAndRotation):this._audio instanceof BABYLON.Sound&&this._audio.attachToMesh(e),this._isAudioSpatial=!0)},n.prototype.getCurrentTrackTime=function(){var e=0;return null!=this._audio&&(e=this._audio.currentTime),e},n.prototype.setAudioDataSource=function(t){return a(this,void 0,void 0,function(){var n,i,r;return s(this,function(o){switch(o.label){case 0:return null!=this._audio&&(this._audio.dispose(),this._audio=null),n=this._spatialblend>=.1,this._initializedReadyInstance=!1,this._lastmutedvolume=this._volume,i={loop:this._loop,volume:!0===this._mute?0:this._volume,autoplay:!1,autoUpdate:!0,playbackRate:this._pitch,spatialEnabled:n,spatialAutoUpdate:!0,spatialPosition:new BABYLON.Vector3(0,0,0),spatialRotationQuaternion:new BABYLON.Quaternion(0,0,0,1),spatialPanningModel:"equalpower",spatialDistanceModel:"linear",spatialMinDistance:this._mindistance,spatialMaxDistance:this._maxdistance,spatialRolloffFactor:e.AudioSource.DEFAULT_ROLLOFF,spatialConeInnerAngle:360,spatialConeOuterAngle:360},r=this,[4,e.AudioSource.CreateStaticSound(this._name,t,i)];case 1:return r._audio=o.sent(),null!=this._audio&&(this._initializedReadyInstance=!0,!0===n&&null!=this._audio.spatial&&(this._audio.spatial.position=new BABYLON.Vector3(0,0,0),this._audio.spatial.rotationQuaternion=new BABYLON.Quaternion(0,0,0,1),this._audio.spatial.panningModel="equalpower",this._audio.spatial.distanceModel="linear",this._audio.spatial.minDistance=this._mindistance,this._audio.spatial.maxDistance=this._maxdistance,this._audio.spatial.rolloffFactor=e.AudioSource.DEFAULT_ROLLOFF,this._audio.spatial.coneInnerAngle=360,this._audio.spatial.coneOuterAngle=360,this._audio.spatial.attach(this.transform,!0,BABYLON.SpatialAudioAttachmentType.PositionAndRotation),this._isAudioSpatial=!0),this.onReadyObservable&&this.onReadyObservable.hasObservers()&&this.onReadyObservable.notifyObservers(this._audio),!0===this._playonawake&&this.play()),[2]}})})},n.prototype.setLegacyDataSource=function(t){var n=this;null!=this._audio&&(this._audio.dispose(),this._audio=null);var i=this._spatialblend>=.1,r=null!=this.transform.metadata&&null!=this.transform.metadata.vtt&&!0===this.transform.metadata.vtt;this._initializedReadyInstance=!1,this._audio=new BABYLON.Sound(this._name,t,this.scene,function(){n._lastmutedvolume=n._volume,n._audio.setVolume(!0===n._mute?0:n._volume),n._audio.setPlaybackRate(n._pitch),n._audio.setPosition(n.transform.absolutePosition.clone()),n._initializedReadyInstance=!0,!0===i&&n._audio instanceof BABYLON.Sound&&(n._isAudioSpatial=!0,n._audio.attachToMesh(n.transform)),n.onReadyObservable&&n.onReadyObservable.hasObservers()&&n.onReadyObservable.notifyObservers(n._audio),!0===n._playonawake&&n.play()},{loop:this._loop,autoplay:!1,refDistance:this._mindistance,maxDistance:this._maxdistance,rolloffFactor:e.AudioSource.DEFAULT_ROLLOFF,spatialSound:i,distanceModel:"linear",streaming:r})},n.prototype.addPreloaderTasks=function(e){var t=this;!0===this._preload&&(e.addBinaryFileTask(this.transform.name+".AudioTask",this._preloaderUrl).onSuccess=function(e){return a(t,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return this.isLegacy()?(this.setLegacyDataSource(e.data),[3,3]):[3,1];case 1:return[4,this.setAudioDataSource(e.data)];case 2:t.sent(),t.label=3;case 3:return[2]}})})})},n.IsLegacyEngine=function(){return!!BABYLON.Engine.audioEngine},n.GetAudioOptions=function(){return e.AudioSource.AUDIO_ENGINE_V2_OPTIONS},n.SetAudioOptions=function(t){e.AudioSource.AUDIO_ENGINE_V2_OPTIONS=t},n.GetAudioEngine=function(){return a(this,void 0,void 0,function(){var t;return s(this,function(n){switch(n.label){case 0:return null!=e.AudioSource.AUDIO_ENGINE_V2?[3,2]:(t=e.AudioSource,[4,BABYLON.CreateAudioEngineAsync(e.AudioSource.AUDIO_ENGINE_V2_OPTIONS||{listenerAutoUpdate:!0,listenerEnabled:!0,resumeOnInteraction:!0,resumeOnPause:!0})]);case 1:t.AUDIO_ENGINE_V2=n.sent(),n.label=2;case 2:return[2,e.AudioSource.AUDIO_ENGINE_V2]}})})},n.UnlockLegacyAudio=function(){null==BABYLON.Engine.audioEngine||BABYLON.Engine.audioEngine.unlocked||BABYLON.Engine.audioEngine.unlock()},n.UnlockAudioEngine=function(){return a(this,void 0,void 0,function(){var t;return s(this,function(n){switch(n.label){case 0:return[4,e.AudioSource.GetAudioEngine()];case 1:return null==(t=n.sent())?[3,3]:[4,t.unlockAsync()];case 2:n.sent(),n.label=3;case 3:return[2]}})})},n.AttachSpatialCamera=function(t){return a(this,void 0,void 0,function(){var n;return s(this,function(i){switch(i.label){case 0:return null==t?(console.warn("TOOLKIT.AudioSource.AttachSpatialCamera: No node provided to attach spatial audio listener to."),[2]):[4,e.AudioSource.GetAudioEngine()];case 1:return null!=(n=i.sent())&&null!=n.listener&&n.listener.attach(t,!0,BABYLON.SpatialAudioAttachmentType.PositionAndRotation),[2]}})})},n.DetachSpatialCamera=function(){return a(this,void 0,void 0,function(){var t;return s(this,function(n){switch(n.label){case 0:return[4,e.AudioSource.GetAudioEngine()];case 1:return null!=(t=n.sent())&&null!=t.listener&&t.listener.detach(),[2]}})})},n.CreateSoundBuffer=function(t,n){return a(this,void 0,void 0,function(){var i,r;return s(this,function(o){switch(o.label){case 0:return i=null,[4,e.AudioSource.GetAudioEngine()];case 1:return null==(r=o.sent())?[3,3]:[4,r.createSoundBufferAsync(t,n)];case 2:i=o.sent(),o.label=3;case 3:return[2,i]}})})},n.CreateStaticSound=function(t,n,i){return a(this,void 0,void 0,function(){var r,o;return s(this,function(a){switch(a.label){case 0:return r=null,[4,e.AudioSource.GetAudioEngine()];case 1:return null==(o=a.sent())?[3,3]:[4,o.createSoundAsync(t,n,i)];case 2:r=a.sent(),a.label=3;case 3:return[2,r]}})})},n.CreateStreamingSound=function(t,n,i){return a(this,void 0,void 0,function(){var r,o;return s(this,function(a){switch(a.label){case 0:return r=null,[4,e.AudioSource.GetAudioEngine()];case 1:return null==(o=a.sent())?[3,3]:[4,o.createStreamingSoundAsync(t,n,i)];case 2:r=a.sent(),a.label=3;case 3:return[2,r]}})})},n.MAX_VOLUME=1,n.DEFAULT_LEVEL=1,n.DEFAULT_ROLLOFF=1,n.AUDIO_ENGINE_V2=null,n.AUDIO_ENGINE_V2_OPTIONS={listenerAutoUpdate:!0,listenerEnabled:!0,resumeOnInteraction:!0,resumeOnPause:!0},n}(e.ScriptComponent);e.AudioSource=t,e.SceneManager.RegisterClass("TOOLKIT.AudioSource",t)}(i||(i={})),function(e){var t=function(){function e(){}return e.CreatePostProcess=function(e,t,n){var i=n||{},r=i.red||[1,0,0],o=i.green||[0,1,0],a=i.blue||[0,0,1],s=new BABYLON.PostProcess("channelMixer","\n precision highp float;\n varying vec2 vUV;\n uniform sampler2D textureSampler;\n uniform vec3 redMix;\n uniform vec3 greenMix;\n uniform vec3 blueMix;\n\n void main(void) {\n vec4 sceneColor = texture2D(textureSampler, vUV);\n vec3 rgb = sceneColor.rgb;\n float newR = dot(rgb, redMix);\n float newG = dot(rgb, greenMix);\n float newB = dot(rgb, blueMix);\n gl_FragColor = vec4(newR, newG, newB, sceneColor.a);\n }\n ",["redMix","greenMix","blueMix"],[],1,t,BABYLON.Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1);return s.onApply=function(e){e.setFloat3("redMix",r[0]||1,r[1]||0,r[2]||0),e.setFloat3("greenMix",o[0]||0,o[1]||1,o[2]||0),e.setFloat3("blueMix",a[0]||0,a[1]||0,a[2]||1)},s},e}();e.ChannelMixerPlugin=t}(i||(i={})),function(e){var t=function(t){function n(e,n,i,r){void 0===i&&(i={}),void 0===r&&(r="TOOLKIT.CharacterController");var o=t.call(this,e,n,i,r)||this;return o._avatarRadius=.28,o._avatarHeight=1.8,o._centerOffset=new BABYLON.Vector3(0,.94,0),o._slopeLimit=45,o._skinWidth=.025,o._stepHeight=.25,o._minMoveDistance=.001,o._verticalVelocity=0,o._currentSlopeAngle=0,o._collisionEvents=!0,o._targetRotation=new BABYLON.Quaternion(0,0,0,1),o._targetVelocity=new BABYLON.Vector3,o._currentVelocity=new BABYLON.Vector3(0,0,0),o._inputVelocity=new BABYLON.Vector3(0,0,0),o._stepUpVelocity=0,o._gravityFactor=3,o._minJumpTimer=0,o._isGrounded=!1,o._groundContacts=new Map,o._groundContactInfo=null,o._groundedEnterTimer=0,o._groundedExitTimer=0,o._raycastResult=new BABYLON.PhysicsRaycastResult,o._rayOrigin=new BABYLON.Vector3,o._rayTarget=new BABYLON.Vector3,o._previousGroundHeight=0,o._stepDetectionDistance=.5,o.m_moveDeltaX=0,o.m_moveDeltaY=0,o.m_moveDeltaZ=0,o.m_havokplugin=null,o.onUpdatePositionObservable=new BABYLON.Observable,o.onUpdateVelocityObservable=new BABYLON.Observable,o.enableUpdate=!0,o.enableGravity=!1,o.enableStepOffset=!1,o.useMultiRaycast=!1,o.multiRaycastCount=5,o.groundCheckDistance=.25,o.stepUpVelocityFactor=.5,o.defaultJumpingTimer=.5,o.onlyApplyGravityWhenNotGrounded=!1,o.downwardVelocityClamp=-2,o.contactHysteresisTime=.15,o.groundedEnterTime=.03,o.groundedExitTime=.1,o}return r(n,t),n.prototype.getAvatarRadius=function(){return this._avatarRadius},n.prototype.getAvatarHeight=function(){return this._avatarHeight},n.prototype.getCenterOffset=function(){return this._centerOffset},n.prototype.getSkinWidth=function(){return this._skinWidth},n.prototype.getStepHeight=function(){return this._stepHeight},n.prototype.getGravityFactor=function(){return this._gravityFactor},n.prototype.setGravityFactor=function(e){this._gravityFactor=e},n.prototype.getInputVelocity=function(){return this._inputVelocity},n.prototype.setInputVelocity=function(e){this._inputVelocity.copyFrom(e)},n.prototype.getStepUpVelocity=function(){return this._stepUpVelocity},n.prototype.getCurrentSlopeAngle=function(){return this._currentSlopeAngle},n.prototype.getVerticalVelocity=function(){return!0===this.isGrounded()?0:this._currentVelocity.y},n.prototype.getMinMoveDistance=function(){return this._minMoveDistance},n.prototype.setMinMoveDistance=function(e){this._minMoveDistance=e},n.prototype.getGroundContactInfo=function(){return this._groundContactInfo},n.prototype.getMinJumpTimer=function(){return this._minJumpTimer},n.prototype.getSlopeLimit=function(){return this._slopeLimit},n.prototype.setSlopeLimit=function(e){this._slopeLimit=e},n.prototype.isGrounded=function(){return this._isGrounded},n.prototype.canJump=function(){return!0===this.isGrounded()},n.prototype.awake=function(){var t=this;this._avatarRadius=this.getProperty("avatarRadius",this._avatarRadius),this._avatarHeight=this.getProperty("avatarHeight",this._avatarHeight),this._slopeLimit=this.getProperty("slopeLimit",this._slopeLimit),this._skinWidth=this.getProperty("skinWidth",this._skinWidth),this._stepHeight=this.getProperty("stepOffset",this._stepHeight),this._minMoveDistance=this.getProperty("minMoveDistance",this._minMoveDistance),this._collisionEvents=this.getProperty("collisionEvents",this._collisionEvents),this.contactHysteresisTime=this.getProperty("contactHysteresisTime",this.contactHysteresisTime),this.groundedEnterTime=this.getProperty("groundedEnterTime",this.groundedEnterTime),this.groundedExitTime=this.getProperty("groundedExitTime",this.groundedExitTime);var n=this.getProperty("centerOffset");null!=n&&(this._centerOffset=e.Utilities.ParseVector3(n)),this.enableStepOffset=this.getProperty("enableStepOffset",this.enableStepOffset),this.createPhysicsBodyAndShape(e.CharacterController.DEFAULT_CHARACTER_MASS,e.Utilities.GetLayerMask(31),-1),this.enableCollisionEvents();var i=function(e){t.registerGroundContact(e)};this.onCollisionEnterObservable.add(i),this.onCollisionStayObservable.add(i),this.onCollisionExitObservable.add(function(e){})},n.prototype.update=function(){if(!1!==this.enableUpdate){var e=this.getDeltaSeconds();this._minJumpTimer>0&&(this._minJumpTimer-=e,this._minJumpTimer<0&&(this._minJumpTimer=0))}},n.prototype.fixed=function(){if(!1!==this.enableUpdate&&null!=this.transform){if(null!=this.transform.physicsBody?this.transform.physicsBody.getLinearVelocityToRef(this._currentVelocity):this._currentVelocity.set(0,0,0),this.m_moveDeltaX=this._targetVelocity.x,this.m_moveDeltaY=this._targetVelocity.y,this.m_moveDeltaZ=this._targetVelocity.z,Math.abs(this.m_moveDeltaX)<this._minMoveDistance&&(this.m_moveDeltaX>0?this.m_moveDeltaX=this._minMoveDistance:this.m_moveDeltaX<0&&(this.m_moveDeltaX=-this._minMoveDistance)),Math.abs(this.m_moveDeltaZ)<this._minMoveDistance&&(this.m_moveDeltaZ>0?this.m_moveDeltaZ=this._minMoveDistance:this.m_moveDeltaZ<0&&(this.m_moveDeltaZ=-this._minMoveDistance)),this.updateGroundedState(),this.onUpdateVelocityObservable&&this.onUpdateVelocityObservable.hasObservers()&&this.onUpdateVelocityObservable.notifyObservers(this.transform),this._inputVelocity.set(this.m_moveDeltaX,this.m_moveDeltaY+this._verticalVelocity,this.m_moveDeltaZ),null!=this.transform.physicsBody)try{(!1===this.enableGravity||!0===this.onlyApplyGravityWhenNotGrounded&&!0===this._isGrounded)&&(this._inputVelocity.y=0),this.transform.physicsBody.setLinearVelocity(this._inputVelocity)}catch(e){console.warn("Failed to set linear velocity on physics body: ",e)}else console.warn("No physics body attached to character controller transform: "+this.transform.name);this.onUpdatePositionObservable&&this.onUpdatePositionObservable.hasObservers()&&this.onUpdatePositionObservable.notifyObservers(this.transform)}},n.prototype.set=function(e,t,n,i,r,o,a){void 0===i&&(i=null),void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),!1!==this.enableUpdate&&null!=this.transform&&(null!=this.transform.position&&null!=e&&null!=t&&null!=n&&this.transform.position.set(e,t,n),null!=this.transform.rotationQuaternion&&null!=i&&null!=r&&null!=o&&null!=a&&this.transform.rotationQuaternion.set(i,r,o,a))},n.prototype.move=function(e,t){void 0===t&&(t=!0),!1!==this.enableUpdate&&null!=e&&this._targetVelocity.copyFrom(e)},n.prototype.jump=function(e){var t;if(!1!==this.enableUpdate&&this.canJump()&&(this._isGrounded=!1,this._groundContactInfo=null,this._minJumpTimer=this.defaultJumpingTimer,this._verticalVelocity=e,null===(t=this.transform)||void 0===t?void 0:t.physicsBody)){var n=new BABYLON.Vector3;this.transform.physicsBody.getLinearVelocityToRef(n),n.y=e,this.transform.physicsBody.setLinearVelocity(n)}},n.prototype.turn=function(e){!1!==this.enableUpdate&&null!=this.transform&&this.transform.addRotation(0,e,0)},n.prototype.rotate=function(e,t,n,i){!1!==this.enableUpdate&&null!=this.transform&&null!=this.transform.rotationQuaternion&&(this._targetRotation.set(e,t,n,i),this.transform.rotationQuaternion.copyFrom(this._targetRotation))},n.prototype.setRigidBodyMass=function(e){if(null!=this.transform&&null!=this.transform.physicsBody){var t=this.transform.physicsBody.getMassProperties();t.mass=e>=1e-7?e:1e-7,this.transform.physicsBody.setMassProperties(t)}},n.prototype.setCollisionState=function(e){null!=this.transform&&null!=this.transform.physicsBody&&null!=this.transform.physicsBody.shape&&(this.transform.physicsBody.shape.isTrigger=!e)},n.prototype.setCollisionFilters=function(e,t){if(null!=this.transform&&null!=this.transform.physicsBody&&null!=this.transform.physicsBody.shape){var n=this.transform.physicsBody.shape,i=function(n){n&&(n.filterCollideMask=t,n.filterMembershipMask=e)};i(n),Array.isArray(n.children)&&n.children.forEach(function(e){return i(e)})}},n.prototype.registerGroundContact=function(e){e&&this.isContactAtFeet(e)&&this._groundContacts.set(e,0)},n.prototype.updateGroundContactAges=function(e){var t=this;if(0===this._groundContacts.size)return 0;var n=1e3*Math.max(0,this.contactHysteresisTime),i=0;return this._groundContacts.forEach(function(r,o){var a=r+e;a>n?t._groundContacts.delete(o):(t._groundContacts.set(o,a),i++)}),i},n.prototype.isContactAtFeet=function(e){return!(!e||!this.transform)},n.prototype.isValidGroundNormal=function(e){var t=new BABYLON.Vector3(0,1,0),n=BABYLON.Vector3.Dot(e,t);return this._currentSlopeAngle=Math.acos(n)*(180/Math.PI),n>=Math.cos(this._slopeLimit*Math.PI/180)},n.prototype.performSingleRayGroundCheck=function(t){return this._rayOrigin.copyFrom(this.transform.position),this._rayOrigin.y+=.1*this._centerOffset.y,this._rayTarget.copyFrom(this._rayOrigin),this._rayTarget.y-=this.groundCheckDistance,this._raycastResult.reset(),e.RigidbodyPhysics.RaycastToRef(this._rayOrigin,this._rayTarget,this._raycastResult),this._raycastResult.hasHit&&(t.hasGround=!0,t.groundNormal.copyFrom(this._raycastResult.hitNormalWorld),t.groundHeight=this._raycastResult.hitPointWorld.y,t.groundBody=this._raycastResult.body),t},n.prototype.performMultiRayGroundCheck=function(t){for(var n=[],i=this.transform.position.y+.1*this._centerOffset.y,r=0;r<this.multiRaycastCount;r++){var o=r/this.multiRaycastCount*Math.PI*2,a=.7*this._avatarRadius;if(this._rayOrigin.set(this.transform.position.x+Math.cos(o)*a,i,this.transform.position.z+Math.sin(o)*a),this._rayTarget.copyFrom(this._rayOrigin),this._rayTarget.y-=this.groundCheckDistance,this._raycastResult.reset(),e.RigidbodyPhysics.RaycastToRef(this._rayOrigin,this._rayTarget,this._raycastResult),this._raycastResult.hasHit){var s=this._rayOrigin.y-this._raycastResult.hitPointWorld.y;n.push({normal:this._raycastResult.hitNormalWorld.clone(),height:this._raycastResult.hitPointWorld.y,distance:s,body:this._raycastResult.body})}}if(n.length>0){var l=n[0];for(r=1;r<n.length;r++)n[r].distance<l.distance&&(l=n[r]);var u=new BABYLON.Vector3;n.forEach(function(e){return u.addInPlace(e.normal)}),u.scaleInPlace(1/n.length),u.normalize(),t.hasGround=!0,t.groundNormal.copyFrom(u),t.groundHeight=l.height,t.groundBody=l.body}return t},n.prototype.performGroundRaycast=function(){var e={hasGround:!1,groundNormal:new BABYLON.Vector3(0,1,0),groundHeight:0,groundBody:null};return this.useMultiRaycast?this.performMultiRayGroundCheck(e):this.performSingleRayGroundCheck(e)},n.prototype.detectAndHandleStepOffset=function(t){if(Math.sqrt(this.m_moveDeltaX*this.m_moveDeltaX+this.m_moveDeltaZ*this.m_moveDeltaZ)<.01)return 0;var n=new BABYLON.Vector3(this.m_moveDeltaX,0,this.m_moveDeltaZ).normalize(),i=t;if(this._rayOrigin.copyFrom(this.transform.position),this._rayOrigin.y=i+.05,this._rayTarget.copyFrom(this._rayOrigin),this._rayTarget.addInPlace(n.scale(this._stepDetectionDistance)),this._raycastResult.reset(),e.RigidbodyPhysics.RaycastToRef(this._rayOrigin,this._rayTarget,this._raycastResult),!this._raycastResult.hasHit)return 0;var r=BABYLON.Vector3.Distance(this._rayOrigin,this._raycastResult.hitPointWorld);if(this._rayOrigin.copyFrom(this.transform.position),this._rayOrigin.y=i+this._stepHeight+.05,this._rayOrigin.addInPlace(n.scale(r+.1)),this._rayTarget.copyFrom(this._rayOrigin),this._rayTarget.y=i-.05,this._raycastResult.reset(),e.RigidbodyPhysics.RaycastToRef(this._rayOrigin,this._rayTarget,this._raycastResult),!this._raycastResult.hasHit)return 0;var o=this._raycastResult.hitPointWorld.y-i;return o>.01&&o<=this._stepHeight?Math.sqrt(2*Math.abs(this.scene.gravity.y)*o*this._gravityFactor)*this.stepUpVelocityFactor:0},n.prototype.updateGroundedState=function(){if(this._minJumpTimer>0){this._isGrounded=!1,this._groundContactInfo=null;var t=this.getDeltaSeconds();return this._verticalVelocity-=Math.abs(this.scene.gravity.y)*this._gravityFactor*t,void(Math.abs(this._verticalVelocity)>e.CharacterController.TERMINAL_VELOCITY&&(this._verticalVelocity=-e.CharacterController.TERMINAL_VELOCITY))}var n=this.getDeltaSeconds(),i=1e3*n,r=Math.max(0,this.groundedEnterTime),o=Math.max(0,this.groundedExitTime),a=this.updateGroundContactAges(i)>0,s=null;if(this._currentSlopeAngle=0,a){var l=this.performGroundRaycast();l.hasGround&&this.isValidGroundNormal(l.groundNormal)?s=l:a=!1}if(a?(this._groundedExitTimer=0,this._groundedEnterTimer=Math.min(this._groundedEnterTimer+n,r),!this._isGrounded&&this._groundedEnterTimer>=r?this._isGrounded=!0:this._isGrounded&&(this._groundedEnterTimer=r)):(this._groundedEnterTimer=0,this._groundedExitTimer=Math.min(this._groundedExitTimer+n,o),this._isGrounded&&this._groundedExitTimer>=o&&(this._isGrounded=!1)),s&&this._isGrounded?(this._groundContactInfo=s,this._previousGroundHeight=s.groundHeight):s||(this._groundContactInfo=null),!0===this._isGrounded&&!0===this.enableStepOffset){var u=this._groundContactInfo?this._groundContactInfo.groundHeight:this.transform.position.y;this._stepUpVelocity=this.detectAndHandleStepOffset(u),this._stepUpVelocity>0&&(this._verticalVelocity=Math.max(this._verticalVelocity,this._stepUpVelocity))}else this._stepUpVelocity=0;!0===this._isGrounded&&this._verticalVelocity<0?this._verticalVelocity=Math.max(this._verticalVelocity,this.downwardVelocityClamp):(this._verticalVelocity-=Math.abs(this.scene.gravity.y)*this._gravityFactor*n,Math.abs(this._verticalVelocity)>e.CharacterController.TERMINAL_VELOCITY&&(this._verticalVelocity=-e.CharacterController.TERMINAL_VELOCITY))},n.prototype.createPhysicsBodyAndShape=function(t,n,i){var r=this.transform;e.Utilities.ReparentColliders()||r.setParent(null,!0,!0);var o=this._avatarRadius*parseFloat(r.scaling.x.toFixed(4)),a=this._avatarHeight*parseFloat(r.scaling.y.toFixed(4)),s=this.createPhysicsShapeCapsule(o,a);s.filterCollideMask=this.getProperty("filterCollideMask")||4294967295,s.filterMembershipMask=this.getProperty("filterMembershipMask")||n;var l=new BABYLON.Quaternion(0,0,0,1),u=this._centerOffset.x*parseFloat(r.scaling.x.toFixed(4)),c=this._centerOffset.y*parseFloat(r.scaling.y.toFixed(4)),d=this._centerOffset.z*parseFloat(r.scaling.z.toFixed(4)),h=new BABYLON.Vector3(u,c,d),p=new BABYLON.PhysicsShapeContainer(this.scene);p.filterCollideMask=s.filterCollideMask,p.filterMembershipMask=s.filterMembershipMask,p.material={friction:0,staticFriction:0,restitution:0,frictionCombine:0,restitutionCombine:0},p.addChild(s,h,l,new BABYLON.Vector3(1,1,1));var m=new BABYLON.PhysicsBody(r,BABYLON.PhysicsMotionType.DYNAMIC,!1,this.scene);if(m.shape=p,m.setMassProperties({mass:t,centerOfMass:new BABYLON.Vector3(0,0,0),inertia:new BABYLON.Vector3(0,0,0)}),m.setGravityFactor(0),m.setLinearDamping(0),m.setAngularDamping(0),m.disablePreStep=!1,!0===this._collisionEvents&&(m.setCollisionCallbackEnabled(!0),m.setCollisionEndedCallbackEnabled(!0)),e.Utilities.ShowDebugColliders()&&console.log("Setup character controller physics collider for: "+r.name,r),!e.Utilities.ShowDebugColliders()){var f=r;null!=f.material&&"CenterBox-Material"===f.material.name&&(f.isVisible=!1)}e.Utilities.ShowDebugColliders()&&(null==e.RigidbodyPhysics.DebugPhysicsViewer&&(e.RigidbodyPhysics.DebugPhysicsViewer=new BABYLON.Debug.PhysicsViewer),null!=e.RigidbodyPhysics.DebugPhysicsViewer&&e.RigidbodyPhysics.DebugPhysicsViewer.showBody(m))},n.prototype.createPhysicsShapeCapsule=function(e,t){var n=-.5*(t-.5),i=.5*(t-.5);return new BABYLON.PhysicsShapeCapsule(new BABYLON.Vector3(0,n,0),new BABYLON.Vector3(0,i,0),e,this.scene)},n.TERMINAL_VELOCITY=55,n.DEFAULT_CHARACTER_MASS=85,n}(e.ScriptComponent);e.CharacterController=t;var n=function(e){function t(t,n,i,r){void 0===i&&(i={}),void 0===r&&(r="TOOLKIT.SimpleCharacterController");var o=e.call(this,t,n,i,r)||this;return o._eulerAngles=new BABYLON.Vector3(0,0,0),o}return r(t,e),t.prototype.start=function(){},t.prototype.set=function(e,t,n,i,r,o,a,s){void 0===i&&(i=null),void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=!0),null!=this.transform&&(null!=this.transform.position&&null!=e&&null!=t&&null!=n&&this.transform.position.set(e,t,n),null!=this.transform.rotationQuaternion&&null!=i&&null!=r&&null!=o&&null!=a&&this.transform.rotationQuaternion.set(i,r,o,a))},t.prototype.move=function(e,t){void 0===t&&(t=!0),null!=e&&null!=this.transform&&this.transform instanceof BABYLON.AbstractMesh&&this.transform.moveWithCollisions(e)},t.prototype.jump=function(e){},t.prototype.turn=function(e){null!=this.transform&&this.transform.addRotation(0,e,0)},t.prototype.rotate=function(e,t,n,i){null!=this.transform&&null!=this.transform.rotationQuaternion&&this.transform.rotationQuaternion.set(e,t,n,i)},t}(e.ScriptComponent);e.SimpleCharacterController=n;var i=function(e){function t(t,n,i,r){void 0===i&&(i={}),void 0===r&&(r="TOOLKIT.RecastCharacterController");var o=e.call(this,t,n,i,r)||this;return o._eulerAngles=new BABYLON.Vector3(0,0,0),o._teleportVector=new BABYLON.Vector3(0,0,0),o._navigationAgent=null,o}return r(t,e),t.prototype.getNavigationAgent=function(){return this._navigationAgent},t.prototype.setNavigationAgent=function(e){this._navigationAgent=e},t.prototype.setDestinationPoint=function(e,t){void 0===t&&(t=!0),null!=this._navigationAgent&&this._navigationAgent.setDestination(e,t)},t.prototype.start=function(){this._navigationAgent=this.getComponent("TOOLKIT.NavigationAgent")},t.prototype.set=function(e,t,n,i,r,o,a,s){void 0===i&&(i=null),void 0===r&&(r=null),void 0===o&&(o=null),void 0===a&&(a=null),void 0===s&&(s=!0),null!=this.transform&&null!=this._navigationAgent&&(null!=this.transform.position&&null!=e&&null!=t&&null!=n&&(this._teleportVector.set(e,t,n),this._navigationAgent.teleport(this._teleportVector,s)),null!=this.transform.rotationQuaternion&&null!=i&&null!=r&&null!=o&&null!=a&&this.transform.rotationQuaternion.set(i,r,o,a))},t.prototype.move=function(e,t){void 0===t&&(t=!0),null!=e&&null!=this._navigationAgent&&this._navigationAgent.move(e,t)},t.prototype.jump=function(e){console.warn("Jump is not supported by the navigation mesh character controller.")},t.prototype.turn=function(e){null!=this.transform&&this.transform.addRotation(0,e,0)},t.prototype.rotate=function(e,t,n,i){null!=this.transform&&null!=this.transform.rotationQuaternion&&null!=this._navigationAgent&&this.transform.rotationQuaternion.set(e,t,n,i)},t}(e.ScriptComponent);e.RecastCharacterController=i,e.SceneManager.RegisterClass("TOOLKIT.CharacterController",t),e.SceneManager.RegisterClass("TOOLKIT.SimpleCharacterController",n),e.SceneManager.RegisterClass("TOOLKIT.RecastCharacterController",i)}(i||(i={})),function(e){var t=function(){function e(){}return e.CreatePostProcess=function(e,t,n){var i=n||{},r=Array.isArray(i.color)?i.color:i.color?[i.color.r||1,i.color.g||1,i.color.b||1,null!=i.color.a?i.color.a:1]:[1,1,1,1],o=new BABYLON.PostProcess("colorFilter","\n precision highp float;\n varying vec2 vUV;\n uniform sampler2D textureSampler;\n uniform vec4 filterColor;\n\n void main(void) {\n vec4 sceneColor = texture2D(textureSampler, vUV);\n gl_FragColor = sceneColor * filterColor;\n }\n ",["filterColor"],[],1,t,BABYLON.Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1);return o.onApply=function(e){e.setFloat4("filterColor",r[0]||1,r[1]||1,r[2]||1,null!=r[3]?r[3]:1)},o},e}();e.ColorFilterPlugin=t}(i||(i={})),function(e){var t=function(){function e(){}return e.CreateColoredBloom=function(e,t,n){var i=n||{},r=null!=i.threshold?i.threshold:1,o=Array.isArray(i.color)?i.color:i.color?[i.color.r||1,i.color.g||1,i.color.b||1]:[1,1,1],a=null!=i.weight?i.weight:1,s=null!=i.kernel?i.kernel:4,l=null!=i.downsampleRatio?i.downsampleRatio:null!=i.ratio?i.ratio:.5,u=null!=i.passes?Math.max(1,Math.floor(i.passes)):1,c=null!=i.saturation?i.saturation:1,d=new BABYLON.PostProcess("coloredBloom_prefilter","\n precision highp float;\n varying vec2 vUV;\n uniform sampler2D textureSampler;\n uniform float threshold;\n uniform vec3 tint;\n\n void main(void) {\n vec4 color = texture2D(textureSampler, vUV);\n float lum = dot(color.rgb, vec3(0.2126, 0.7152, 0.0722));\n float mask = smoothstep(threshold * 0.95, threshold * 1.05, lum);\n vec3 bloom = color.rgb * mask * tint;\n gl_FragColor = vec4(bloom, 1.0);\n }\n ",["threshold","tint"],[],l,t,BABYLON.Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1);d.onApply=function(e){e.setFloat("threshold",r),e.setFloat3("tint",o[0]||1,o[1]||1,o[2]||1)};for(var h=[],p=0;p<u;p++){var m=new BABYLON.BlurPostProcess("coloredBloom_blurH_"+p,new BABYLON.Vector2(1,0),s,l,null,BABYLON.Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1),f=new BABYLON.BlurPostProcess("coloredBloom_blurV_"+p,new BABYLON.Vector2(0,1),s,l,null,BABYLON.Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1);h.push({h:m,v:f})}var g=new BABYLON.PostProcess("coloredBloom_composite","\n precision highp float;\n varying vec2 vUV;\n uniform sampler2D textureSampler;\n uniform sampler2D bloomSampler;\n uniform float weight;\n uniform float saturation;\n\n vec3 desaturate(in vec3 c) {\n float l = dot(c, vec3(0.2126, 0.7152, 0.0722));\n return vec3(l);\n }\n\n void main(void) {\n vec4 scene = texture2D(textureSampler, vUV);\n vec3 bloom = texture2D(bloomSampler, vUV).rgb;\n // apply saturation control to bloom\n bloom = mix(desaturate(bloom), bloom, saturation);\n gl_FragColor = vec4(scene.rgb + bloom * weight, scene.a);\n }\n ",["weight","saturation"],["bloomSampler"],1,t,BABYLON.Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1);return g.onApply=function(e){e.setFloat("weight",a),e.setFloat("saturation",c)},{prefilter:d,blurPasses:h,composite:g,passes:u,saturation:c,dispose:function(){try{this.prefilter.dispose()}catch(e){}try{this.blurPasses.forEach(function(e){try{e.h.dispose()}catch(e){}try{e.v.dispose()}catch(e){}})}catch(e){}try{this.composite.dispose()}catch(e){}}}},e}();e.ColoredBloomPlugin=t}(i||(i={})),function(e){e.btVehicleTuning=function(){this.suspensionStiffness=25,this.suspensionCompression=4.5,this.suspensionDamping=6.5,this.maxSuspensionTravelCm=10,this.frictionSlip=10,this.maxSuspensionForce=15e3};var t=function(){this.hitPointInWorld=new BABYLON.Vector3,this.hitNormalInWorld=new BABYLON.Vector3,this.distFraction=0,this.hitBody=null,this.filterCollideMask=0,this.filterMembershipMask=0};e.btVehicleRaycasterResult=t;var n=function(){function t(e){this._raycastResult=new BABYLON.PhysicsRaycastResult,this._query=e||void 0}return t.prototype.castRay=function(t,n,i){if(this._raycastResult.reset(),i.hitBody=null,i.filterCollideMask=0,i.filterMembershipMask=0,e.RigidbodyPhysics.RaycastToRef(t,n,this._raycastResult,this._query),this._raycastResult.hasHit){var r=this._raycastResult.body;if(r){i.hitPointInWorld.copyFrom(this._raycastResult.hitPointWorld),i.hitNormalInWorld.copyFrom(this._raycastResult.hitNormalWorld),i.hitNormalInWorld.normalize();var o=i.hitPointInWorld.x-t.x,a=i.hitPointInWorld.y-t.y,s=i.hitPointInWorld.z-t.z,l=Math.sqrt(o*o+a*a+s*s),u=n.x-t.x,c=n.y-t.y,d=n.z-t.z,h=Math.sqrt(u*u+c*c+d*d);i.distFraction=h>1e-8?l/h:0,i.hitBody=r;var p=this._raycastResult.shape||r.shape;return p&&(i.filterCollideMask=0|p.filterCollideMask,i.filterMembershipMask=0|p.filterMembershipMask),r}}return null},t}();e.btDefaultVehicleRaycaster=n;var i=function(){this.contactNormalWS=new BABYLON.Vector3(0,1,0),this.contactPointWS=new BABYLON.Vector3,this.suspensionLength=0,this.hardPointWS=new BABYLON.Vector3,this.wheelDirectionWS=new BABYLON.Vector3(0,-1,0),this.wheelAxleWS=new BABYLON.Vector3(1,0,0),this.isInContact=!1,this.groundObject=null};e.btWheelRaycastInfo=i;var r=function(){function e(e){this.raycastInfo=new i,this.worldTransformPosition=new BABYLON.Vector3,this.worldTransformRotation=new BABYLON.Quaternion,this.steering=0,this.rotation=0,this.deltaRotation=0,this.rollInfluence=.1,this.engineForce=0,this.brake=0,this.clippedInvContactDotSuspension=1,this.suspensionRelativeVelocity=0,this.suspensionForce=0,this.skidInfo=1,this.clientInfo=null,this.steeringAngle=0,this.rotationBoost=0,this.defaultFriction=0,this.invertWheelDirection=!1,this.maxVisualTravelRange=0,this.contactCollideMask=0,this.contactMembershipMask=0,this._prevContactNormalWS=new BABYLON.Vector3(0,1,0),this._prevSuspensionLength=-1,this._prevSuspensionForce=-1,this._hasPrevSuspState=!1,this._rayHistoryLengths=[],this._rayHistoryNormalsX=[],this._rayHistoryNormalsY=[],this._rayHistoryNormalsZ=[],this._rayHistoryIndex=0,this._rayHistoryCount=0,this._smoothedSuspensionLength=-1,this._smoothedContactNormal=new BABYLON.Vector3(0,1,0),this._smoothedContactNormalValid=!1,this._contactLossFrames=0,this.transform=null,this.spinner=null,this.chassisConnectionPointCS=e.chassisConnectionCS.clone(),this.wheelDirectionCS=e.wheelDirectionCS.clone(),this.wheelAxleCS=e.wheelAxleCS.clone(),this.suspensionRestLength=e.suspensionRestLength,this.maxSuspensionTravelCm=e.maxSuspensionTravelCm,this.wheelRadius=e.wheelRadius,this.suspensionStiffness=e.suspensionStiffness,this.dampingCompression=e.dampingCompression,this.dampingRelaxation=e.dampingRelaxation,this.frictionSlip=e.frictionSlip,this.maxSuspensionForce=e.maxSuspensionForce,this.isFrontWheel=e.isFrontWheel}return e.prototype.getSuspensionRestLength=function(){return this.suspensionRestLength},e}();e.btWheelInfo=r;var o=function(){function n(e,n,i){this._wheelInfo=[],this._indexRightAxis=0,this._indexUpAxis=1,this._indexForwardAxis=2,this._currentVehicleSpeedKmHour=0,this.enableMultiRaycast=!0,this.minimumWheelContacts=4,this.trackConnectionAccel=6,this.smoothFlyingImpulse=8,this.arcadeSteeringAssist=1,this.smoothedGradientSpeed=.5,this.maximumYawRateLow=60,this.maximumYawRateHigh=30,this.angularDamping=new BABYLON.Vector3(.5,1,.5),this.wheelSkidFadeInSpeed=18,this.wheelSkidFadeOutSpeed=6,this.minContactDotSuspension=.1,this.suspensionForceSmoothing=0,this.suspensionDampingOverdrive=1,this.raycastSmoothingEnabled=!0,this.raycastHistoryBufferSize=12,this.raycastLengthCompressionAlpha=.5,this.raycastLengthRelaxationAlpha=.2,this.raycastNormalSmoothingAlpha=.15,this.raycastOutlierRejectionEnabled=!0,this.raycastOutlierThresholdMeters=.03,this.raycastMaxLengthChangePerSecond=3.5,this.raycastContactLossGraceFrames=3,this.raycastDebugLogEnabled=!1,this.raycastDebugLogIntervalFrames=30,this.raycastDebugLogSpikeThresholdMeters=.04,this.raycastDebugLogWheelMask=65535,this._raycastDebugFrameCounter=0,this._raycastMedianScratch=[],this.sideToSideStabilityEnabled=!0,this.sideToSideStabilityStartKmh=80,this.sideToSideStabilityFullKmh=180,this.stabilizationDebug=!1,this.stabilizationDebugInterval=.25,this.downforceCoefficient=.8,this.constantDownforce=.1,this.stabilizationNormalSmoothing=.85,this.airborneGroundNormalHoldTime=.35,this.groundedAutoLevelEnabled=!0,this.groundedAutoLevelStrength=20,this.groundedAutoLevelDeadzoneDeg=3,this.groundedAutoLevelSettleDeg=1,this.groundedAutoLevelSettleScale=.55,this.groundedAutoLevelHysteresisDeg=.25,this.groundedAutoLevelStartKmh=20,this.groundedAutoLevelFullKmh=100,this.groundedAutoLevelMaxRate=9,this.groundedAutoLevelPartialContactBoost=1.6,this.groundedAutoLevelSlideScale=.35,this.groundedAutoLevelTrackNormalMinDot=.45,this.airborneTrackConnectionStartKmh=80,this.airborneTrackConnectionFullKmh=180,this.airborneTrackConnectionMaxAccel=12,this.airborneRiseDamping=6,this.airborneMaxRiseSpeed=0,this._groundedAutoLevelWasActive=!1,this._stabilizationGroundNormal=new BABYLON.Vector3(0,1,0),this._stabilizationHasGroundNormal=!1,this._stabilizationAirborneTime=0,this.isArcadeBurnoutModeActive=!1,this.isArcadeDonutModeActive=!1,this.isArcadeFootBrakeActive=!1,this.isArcadeHandBrakeActive=!1,this.isArcadeWheelSkidActive=!1,this.isArcadeYawAssistActive=!1,this.burnoutFrictionFloor=1,this.frictionRestoreSpeed=8,this.arcadeBurnoutWheelSpinGain=1,this.arcadeDonutWheelSpinGain=1,this.arcadeBurnoutDirectionChangeSpeedKmh=24.1401,this.arcadeBurnoutDirectionChangeGripScale=.2,this.arcadeWheelSpinBuildSpeed=12,this.arcadeWheelSpinRecoverySpeed=10,this.arcadeWheelSpinAirDamping=.985,this.arcadeWheelSpinMaxAngularVelocity=160,this.arcadeStationaryBurnoutWheelSpinGain=3.25,this.arcadeStationaryBurnoutMinAngularVelocity=65,this.arcadeHandbrakeYawCapMultiplier=1.85,this.arcadeBurnoutYawCapMultiplier=1.25,this.arcadeDonutYawCapMultiplier=1.15,this.arcadeSkidFadeInSpeed=18,this.arcadeSkidFadeOutSpeed=6,this.wheelAtRestSpeedThresholdKmh=1,this.arcadeHandbrakeAssistEnabled=!0,this.currentSteeringInput=0,this.arcadeDonutDirectYawEnabled=!0,this.arcadeDonutDirectYawDegPerSec=60,this.arcadeDonutDirectYawDurationMs=0,this.arcadeDonutDirectYawFadeMs=120,this._arcadeDonutHoldElapsedSec=0,this._arcadeDonutDirectionSign=0,this._forwardWS=[],this._axle=[],this._forwardImpulse=[],this._sideImpulse=[],this._arcadeSkidInfo=[],this._arcadePreviousWheelSpin=[],this.sideFrictionStiffness=1,this.arcadeSideSlipSaturationEnabled=!0,this.arcadeSideSlipPeakDeg=8,this.arcadeSideSlipFalloffDeg=45,this.arcadeSideSlipFalloffFactor=.4,this.arcadeSideSlipMinSpeedMps=1.5,this._chassisMass=0,this._chassisInvMass=0,this._chassisTransform=BABYLON.Matrix.Identity(),this._rayResults=new t,this._sv1=new BABYLON.Vector3,this._sv2=new BABYLON.Vector3,this._sv3=new BABYLON.Vector3,this._sv4=new BABYLON.Vector3,this._sv5=new BABYLON.Vector3,this._sv6=new BABYLON.Vector3,this._sv7=new BABYLON.Vector3,this._sv8=new BABYLON.Vector3,this._sv9=new BABYLON.Vector3,this._sv10=new BABYLON.Vector3,this._sq1=new BABYLON.Quaternion,this._sq2=new BABYLON.Quaternion,this._sm1=BABYLON.Matrix.Identity(),this._sm2=BABYLON.Matrix.Identity(),this._sm3=BABYLON.Matrix.Identity(),this._sm4=BABYLON.Matrix.Identity(),this._vapLinVel=new BABYLON.Vector3,this._vapAngVel=new BABYLON.Vector3,this._vapRelPos=new BABYLON.Vector3,this._vapCenter=new BABYLON.Vector3,this._vapCross=new BABYLON.Vector3,this._rsbVel1=new BABYLON.Vector3,this._crfVel1=new BABYLON.Vector3,this._basisCols=[new BABYLON.Vector3,new BABYLON.Vector3,new BABYLON.Vector3],this._stb1=new BABYLON.Vector3,this._stb2=new BABYLON.Vector3,this._stb3=new BABYLON.Vector3,this._stb4=new BABYLON.Vector3,this._stb5=new BABYLON.Vector3,this._chassisBody=n,this._vehicleRaycaster=i,this._currentVehicleSpeedKmHour=0,this.cacheMassProperties()}return n.prototype.addWheel=function(e,t,n,i,o,a,s){var l=new r({chassisConnectionCS:e,wheelDirectionCS:t,wheelAxleCS:n,suspensionRestLength:i,maxSuspensionTravelCm:a.maxSuspensionTravelCm,wheelRadius:o,suspensionStiffness:a.suspensionStiffness,dampingCompression:a.suspensionCompression,dampingRelaxation:a.suspensionDamping,frictionSlip:a.frictionSlip,maxSuspensionForce:a.maxSuspensionForce,isFrontWheel:s});return this._wheelInfo.push(l),this._forwardWS.push(new BABYLON.Vector3),this._axle.push(new BABYLON.Vector3),this._forwardImpulse.push(0),this._sideImpulse.push(0),this._arcadeSkidInfo.push(1),this._arcadePreviousWheelSpin.push(0),this.updateWheelTransformsWS(l,!1),this.updateWheelTransform(this._wheelInfo.length-1,!1),l},n.prototype.getNumWheels=function(){return this._wheelInfo.length},n.prototype.getWheelInfo=function(e){return this._wheelInfo[e]},n.prototype.setSteeringValue=function(e,t){this._wheelInfo[t].steering=e},n.prototype.getSteeringValue=function(e){return this._wheelInfo[e].steering},n.prototype.applyEngineForce=function(e,t){this._wheelInfo[t].engineForce=e},n.prototype.setBrake=function(e,t){this._wheelInfo[t].brake=e},n.prototype.getCurrentSpeedKmHour=function(){return this._currentVehicleSpeedKmHour},n.prototype.getRigidBody=function(){return this._chassisBody},n.prototype.getRightAxis=function(){return this._indexRightAxis},n.prototype.getUpAxis=function(){return this._indexUpAxis},n.prototype.getForwardAxis=function(){return this._indexForwardAxis},n.prototype.setCoordinateSystem=function(e,t,n){this._indexRightAxis=e,this._indexUpAxis=t,this._indexForwardAxis=n},n.prototype.getForwardVector=function(){var e=this._chassisTransform.m,t=this._indexForwardAxis;return new BABYLON.Vector3(e[4*t],e[4*t+1],e[4*t+2])},n.prototype.getForwardVectorToRef=function(e){var t=this._chassisTransform.m,n=this._indexForwardAxis;e.set(t[4*n],t[4*n+1],t[4*n+2])},n.prototype.cacheMassProperties=function(){var e=this._chassisBody.getMassProperties();this._chassisMass=e.mass,this._chassisInvMass=this._chassisMass>0?1/this._chassisMass:0},n.prototype.setIsArcadeBurnoutActive=function(e){this.isArcadeBurnoutModeActive=e},n.prototype.getIsArcadeBurnoutActive=function(){return this.isArcadeBurnoutModeActive},n.prototype.setIsArcadeDonutActive=function(e){!0!==e&&(this._arcadeDonutDirectionSign=0),this.isArcadeDonutModeActive=e},n.prototype.getIsArcadeDonutActive=function(){return this.isArcadeDonutModeActive},n.prototype.setIsArcadeFootBrakeActive=function(e){this.isArcadeFootBrakeActive=e},n.prototype.getIsArcadeFootBrakeActive=function(){return this.isArcadeFootBrakeActive},n.prototype.setIsArcadeHandBrakeActive=function(e){this.isArcadeHandBrakeActive=e},n.prototype.getIsArcadeHandBrakeActive=function(){return this.isArcadeHandBrakeActive},n.prototype.setIsArcadeWheelSkidActive=function(e){this.isArcadeWheelSkidActive=e},n.prototype.getIsArcadeWheelSkidActive=function(){return this.isArcadeWheelSkidActive},n.prototype.setWheelContactFilters=function(e,t,n){e.contactCollideMask=0|t,e.contactMembershipMask=0|n},n.prototype.resetSuspension=function(){for(var e=0;e<this._wheelInfo.length;e++){var t=this._wheelInfo[e];t.raycastInfo.suspensionLength=t.getSuspensionRestLength(),t.suspensionRelativeVelocity=0,t.raycastInfo.contactNormalWS.copyFrom(t.raycastInfo.wheelDirectionWS).scaleInPlace(-1),t.clippedInvContactDotSuspension=1,t._rayHistoryCount=0,t._rayHistoryIndex=0,t._smoothedSuspensionLength=-1,t._smoothedContactNormalValid=!1,t._prevSuspensionLength=-1,t._contactLossFrames=0,this.setWheelContactFilters(t,0,0)}this._stabilizationGroundNormal.set(0,1,0),this._stabilizationHasGroundNormal=!1,this._stabilizationAirborneTime=0,this._groundedAutoLevelWasActive=!1},n.prototype.getChassisWorldTransform=function(){var e=this._chassisBody.transformNode.getWorldMatrix();return this._chassisTransform.copyFrom(e),this._chassisTransform},n.prototype.updateWheelTransformsWS=function(e,t,n){void 0===n&&(n=1),e.raycastInfo.isInContact=!1;var i=this._chassisTransform;1!==n?(e.chassisConnectionPointCS.scaleToRef(n,this._sv1),BABYLON.Vector3.TransformCoordinatesToRef(this._sv1,i,e.raycastInfo.hardPointWS)):BABYLON.Vector3.TransformCoordinatesToRef(e.chassisConnectionPointCS,i,e.raycastInfo.hardPointWS),BABYLON.Vector3.TransformNormalToRef(e.wheelDirectionCS,i,e.raycastInfo.wheelDirectionWS),BABYLON.Vector3.TransformNormalToRef(e.wheelAxleCS,i,e.raycastInfo.wheelAxleWS)},n.prototype.updateWheelTransform=function(e,t){void 0===t&&(t=!0);var n=this._wheelInfo[e];this.updateWheelTransformsWS(n,t);var i=this._sv1;n.raycastInfo.wheelDirectionWS.negateToRef(i);var r=this._sv2;r.copyFrom(n.raycastInfo.wheelAxleWS);var o=this._sv3;BABYLON.Vector3.CrossToRef(i,r,o),o.normalize(),BABYLON.Quaternion.RotationAxisToRef(i,n.steering,this._sq1),BABYLON.Matrix.FromQuaternionToRef(this._sq1,this._sm2),BABYLON.Quaternion.RotationAxisToRef(r,-n.rotation,this._sq2),BABYLON.Matrix.FromQuaternionToRef(this._sq2,this._sm3),this._basisCols[this._indexRightAxis].copyFrom(r),this._basisCols[this._indexUpAxis].copyFrom(i),this._basisCols[this._indexForwardAxis].copyFrom(o);var a=this._basisCols[0],s=this._basisCols[1],l=this._basisCols[2];BABYLON.Matrix.FromValuesToRef(a.x,a.y,a.z,0,s.x,s.y,s.z,0,l.x,l.y,l.z,0,0,0,0,1,this._sm1),this._sm1.multiplyToRef(this._sm3,this._sm4),this._sm4.multiplyToRef(this._sm2,this._sm1),n.raycastInfo.wheelDirectionWS.scaleToRef(n.raycastInfo.suspensionLength,this._sv4),this._sv4.addInPlace(n.raycastInfo.hardPointWS),n.worldTransformPosition.copyFrom(this._sv4),this._sm1.setTranslationFromFloats(this._sv4.x,this._sv4.y,this._sv4.z),BABYLON.Quaternion.FromRotationMatrixToRef(this._sm1,n.worldTransformRotation)},n.prototype.rayCast=function(e,t){void 0===t&&(t=1),this.updateWheelTransformsWS(e,!1,t),this.setWheelContactFilters(e,0,0);var n=-1,i=e.getSuspensionRestLength()+e.wheelRadius;e.raycastInfo.wheelDirectionWS.scaleToRef(i,this._sv1);var r=e.raycastInfo.hardPointWS;r.addToRef(this._sv1,this._sv2),e.raycastInfo.contactPointWS.copyFrom(this._sv2);var o=this._sv2,a=this._vehicleRaycaster.castRay(r,o,this._rayResults);if(e.raycastInfo.groundObject=null,a&&this._rayResults.hitNormalInWorld.y<.5&&(a=null),a){var s=this._rayResults.distFraction;n=i*s;var l=s*i-e.wheelRadius,u=this._rayResults.hitNormalInWorld.x,c=this._rayResults.hitNormalInWorld.y,d=this._rayResults.hitNormalInWorld.z,h=l,p=u,m=c,f=d;this.raycastSmoothingEnabled&&(e._contactLossFrames=0,this.smoothRaycastHit(e,l,u,c,d),h=e._smoothedSuspensionLength,p=e._smoothedContactNormal.x,m=e._smoothedContactNormal.y,f=e._smoothedContactNormal.z),e.raycastInfo.contactNormalWS.set(p,m,f),e.raycastInfo.isInContact=!0,e.raycastInfo.groundObject=a,e.raycastInfo.suspensionLength=h,this.setWheelContactFilters(e,this._rayResults.filterCollideMask,this._rayResults.filterMembershipMask);var g=e.getSuspensionRestLength()-.01*e.maxSuspensionTravelCm,v=e.getSuspensionRestLength()+.01*e.maxSuspensionTravelCm;e.raycastInfo.suspensionLength<g&&(e.raycastInfo.suspensionLength=g),e.raycastInfo.suspensionLength>v&&(e.raycastInfo.suspensionLength=v),e.raycastInfo.contactPointWS.copyFrom(this._rayResults.hitPointInWorld);var y=BABYLON.Vector3.Dot(e.raycastInfo.contactNormalWS,e.raycastInfo.wheelDirectionWS);this.velocityAtWorldPoint(this._chassisBody,e.raycastInfo.contactPointWS,this._sv3);var _=BABYLON.Vector3.Dot(e.raycastInfo.contactNormalWS,this._sv3),S=this.minContactDotSuspension;if(y>=-S)e.suspensionRelativeVelocity=0,e.clippedInvContactDotSuspension=1/S;else{var A=-1/y;e.suspensionRelativeVelocity=_*A,e.clippedInvContactDotSuspension=A}}else e.raycastInfo.suspensionLength=e.getSuspensionRestLength(),e.suspensionRelativeVelocity=0,e.raycastInfo.contactNormalWS.copyFrom(e.raycastInfo.wheelDirectionWS).scaleInPlace(-1),e.clippedInvContactDotSuspension=1,this.setWheelContactFilters(e,0,0),this.raycastSmoothingEnabled&&(e._contactLossFrames++,e._contactLossFrames>this.raycastContactLossGraceFrames&&(e._rayHistoryCount=0,e._rayHistoryIndex=0,e._smoothedSuspensionLength=-1,e._smoothedContactNormalValid=!1,e._prevSuspensionLength=-1));return n},n.prototype.smoothRaycastHit=function(e,t,n,i,r){var o=0|this.raycastHistoryBufferSize;o<2&&(o=2),e._rayHistoryLengths.length!==o&&(e._rayHistoryLengths=new Array(o),e._rayHistoryNormalsX=new Array(o),e._rayHistoryNormalsY=new Array(o),e._rayHistoryNormalsZ=new Array(o),e._rayHistoryCount=0,e._rayHistoryIndex=0),e._rayHistoryLengths[e._rayHistoryIndex]=t,e._rayHistoryNormalsX[e._rayHistoryIndex]=n,e._rayHistoryNormalsY[e._rayHistoryIndex]=i,e._rayHistoryNormalsZ[e._rayHistoryIndex]=r,e._rayHistoryIndex=(e._rayHistoryIndex+1)%o,e._rayHistoryCount<o&&e._rayHistoryCount++;var a=t;if(this.raycastOutlierRejectionEnabled&&e._rayHistoryCount>=3){var s=e._rayHistoryCount;this._raycastMedianScratch.length!==s&&(this._raycastMedianScratch=new Array(s));for(var l=0;l<s;l++)this._raycastMedianScratch[l]=e._rayHistoryLengths[l];this._raycastMedianScratch.sort(function(e,t){return e-t});var u=s%2==1?this._raycastMedianScratch[s-1>>1]:.5*(this._raycastMedianScratch[(s>>1)-1]+this._raycastMedianScratch[s>>1]),c=this.raycastOutlierThresholdMeters;c>0&&(a>u+c?a=u+c:a<u-c&&(a=u-c))}if(e._smoothedSuspensionLength<0)e._smoothedSuspensionLength=a;else{var d=a<e._smoothedSuspensionLength?this.raycastLengthCompressionAlpha:this.raycastLengthRelaxationAlpha;d<0?d=0:d>1&&(d=1),e._smoothedSuspensionLength=e._smoothedSuspensionLength*(1-d)+a*d}if(this.raycastMaxLengthChangePerSecond>0&&e._prevSuspensionLength>=0){var h=this.raycastMaxLengthChangePerSecond*(1/60),p=e._smoothedSuspensionLength-e._prevSuspensionLength;p>h?e._smoothedSuspensionLength=e._prevSuspensionLength+h:p<-h&&(e._smoothedSuspensionLength=e._prevSuspensionLength-h)}if(e._prevSuspensionLength=e._smoothedSuspensionLength,e._smoothedContactNormalValid){var m=this.raycastNormalSmoothingAlpha;m<0?m=0:m>1&&(m=1);var f=1-m,g=e._smoothedContactNormal.x*f+n*m,v=e._smoothedContactNormal.y*f+i*m,y=e._smoothedContactNormal.z*f+r*m,_=Math.sqrt(g*g+v*v+y*y);if(_>1e-6){var S=1/_;e._smoothedContactNormal.set(g*S,v*S,y*S)}else e._smoothedContactNormal.set(n,i,r)}else e._smoothedContactNormal.set(n,i,r),e._smoothedContactNormalValid=!0},n.prototype.getGravityUpToRef=function(e){var t=null!=this._chassisBody.transformNode?this._chassisBody.transformNode.getScene():null;if(null!=t&&null!=t.gravity){var n=t.gravity;if(n.lengthSquared()>1e-8)return e.copyFrom(n).scaleInPlace(-1),void e.normalize()}e.set(0,1,0)},n.prototype.computeStabilizationUpVector=function(e,t,n){if(n.set(0,0,0),t>0){for(var i=0;i<this._wheelInfo.length;i++){var r=this._wheelInfo[i];r.raycastInfo.isInContact&&n.addInPlace(r.raycastInfo.contactNormalWS)}if(n.lengthSquared()>1e-8){if(n.scaleInPlace(1/t),n.normalize(),this._stabilizationHasGroundNormal&&this.stabilizationNormalSmoothing>0){var o=BABYLON.Scalar.Clamp(this.stabilizationNormalSmoothing,0,.999),a=1-o;n.x=n.x*a+this._stabilizationGroundNormal.x*o,n.y=n.y*a+this._stabilizationGroundNormal.y*o,n.z=n.z*a+this._stabilizationGroundNormal.z*o,n.normalize()}return this._stabilizationGroundNormal.copyFrom(n),this._stabilizationHasGroundNormal=!0,void(this._stabilizationAirborneTime=0)}}this._stabilizationAirborneTime+=e,this._stabilizationHasGroundNormal&&(this.airborneGroundNormalHoldTime<=0||this._stabilizationAirborneTime<=this.airborneGroundNormalHoldTime)?n.copyFrom(this._stabilizationGroundNormal):this.getGravityUpToRef(n)},n.prototype.applyFlyingStabilization=function(e,t){if(!(e<=0||this.smoothFlyingImpulse<=0)){var n=this._chassisTransform.m,i=this._indexRightAxis,r=this._indexUpAxis,o=this._indexForwardAxis;this._stb1.set(n[4*i],n[4*i+1],n[4*i+2]),this._stb2.set(n[4*r],n[4*r+1],n[4*r+2]),this._stb3.set(n[4*o],n[4*o+1],n[4*o+2]),this._chassisBody.getAngularVelocityToRef(this._stb4);var a=BABYLON.Vector3.Dot(this._stb4,this._stb1),s=BABYLON.Vector3.Dot(this._stb4,this._stb2),l=BABYLON.Vector3.Dot(this._stb4,this._stb3),u=(BABYLON.Scalar.Clamp(BABYLON.Vector3.Dot(this._stb2,t),-1,1),BABYLON.Scalar.Clamp(1-Math.exp(-this.smoothFlyingImpulse*e),0,.95));a*=1-u,l*=1-u,BABYLON.Vector3.CrossToRef(this._stb2,t,this._stb5);var c=this._stb5.lengthSquared();this._stb4.set(this._stb1.x*a+this._stb2.x*s+this._stb3.x*l,this._stb1.y*a+this._stb2.y*s+this._stb3.y*l,this._stb1.z*a+this._stb2.z*s+this._stb3.z*l),c>1e-8&&(this._stb5.scaleInPlace(this.smoothFlyingImpulse*e),this._stb4.addInPlace(this._stb5)),this._chassisBody.setAngularVelocity(this._stb4)}},n.prototype.applyGroundedAutoLevel=function(e,t,n,i){if(!this.groundedAutoLevelEnabled||e<=0)this._groundedAutoLevelWasActive=!1;else{var r=this._wheelInfo.length;if(r<=0||t<=0)this._groundedAutoLevelWasActive=!1;else{var o=this._chassisTransform.m,a=this._indexRightAxis,s=this._indexUpAxis,l=this._indexForwardAxis;this._stb1.set(o[4*a],o[4*a+1],o[4*a+2]),this._stb2.set(o[4*s],o[4*s+1],o[4*s+2]),this._stb3.set(o[4*l],o[4*l+1],o[4*l+2]),this.getGravityUpToRef(this._stb4);var u=BABYLON.Scalar.Clamp(BABYLON.Vector3.Dot(n,this._stb4),-1,1),c=1;if(u<1){var d=BABYLON.Scalar.Clamp(this.groundedAutoLevelTrackNormalMinDot,-1,.999);c=BABYLON.Scalar.Clamp((u-d)/(1-d),0,1)}this._stb5.set(this._stb4.x*(1-c)+n.x*c,this._stb4.y*(1-c)+n.y*c,this._stb4.z*(1-c)+n.z*c),this._stb5.lengthSquared()<=1e-8?this._stb5.copyFrom(this._stb4):this._stb5.normalize();var h=BABYLON.Scalar.Clamp(BABYLON.Vector3.Dot(this._stb2,this._stb5),-1,1),p=BABYLON.Scalar.Clamp(this.groundedAutoLevelDeadzoneDeg,0,89),m=BABYLON.Scalar.Clamp(Math.min(this.groundedAutoLevelSettleDeg,p),0,p),f=BABYLON.Scalar.Clamp(this.groundedAutoLevelHysteresisDeg,0,m),g=p*Math.PI/180,v=m*Math.PI/180,y=f*Math.PI/180,_=Math.min(v+y,g),S=Math.max(v-y,0),A=this._groundedAutoLevelWasActive?S:_,b=Math.acos(h);if(b<=A)this._groundedAutoLevelWasActive=!1;else if(BABYLON.Vector3.CrossToRef(this._stb2,this._stb5,this._stb4),this._stb4.lengthSquared()<=1e-8)this._groundedAutoLevelWasActive=!1;else{var M=Math.abs(this._currentVehicleSpeedKmHour),B=1,C=this.groundedAutoLevelFullKmh-this.groundedAutoLevelStartKmh;C>0?B=BABYLON.Scalar.Clamp((M-this.groundedAutoLevelStartKmh)/C,0,1):M<this.groundedAutoLevelStartKmh&&(B=0);var T=this.groundedAutoLevelStrength*(.45+.55*B);if(t<r&&(T*=this.groundedAutoLevelPartialContactBoost),i&&(T*=this.groundedAutoLevelSlideScale),T<=0)this._groundedAutoLevelWasActive=!1;else{var x=this.groundedAutoLevelMaxRate,I=0;if(b<=g){var O=Math.max(g-A,.05),L=BABYLON.Scalar.Clamp((b-A)/O,0,1);I=T*BABYLON.Scalar.Clamp(this.groundedAutoLevelSettleScale,0,1)*(.4+.6*L),x*=.35+.45*L}else{var w=Math.max(20*Math.PI/180-g,.05);I=T*(.35+.65*BABYLON.Scalar.Clamp((b-g)/w,0,1))}if(I<=1e-4)this._groundedAutoLevelWasActive=!1;else{this._chassisBody.getAngularVelocityToRef(this._sv9);var N=BABYLON.Vector3.Dot(this._sv9,this._stb1),P=BABYLON.Vector3.Dot(this._sv9,this._stb2),R=BABYLON.Vector3.Dot(this._sv9,this._stb3),E=BABYLON.Scalar.Clamp(BABYLON.Vector3.Dot(this._stb4,this._stb1)*I,-x,x),k=BABYLON.Scalar.Clamp(BABYLON.Vector3.Dot(this._stb4,this._stb3)*I,-x,x),D=BABYLON.Scalar.Clamp(1-Math.exp(-I*e),0,.85);N+=(E-N)*D,R+=(k-R)*D,this._sv9.set(this._stb1.x*N+this._stb2.x*P+this._stb3.x*R,this._stb1.y*N+this._stb2.y*P+this._stb3.y*R,this._stb1.z*N+this._stb2.z*P+this._stb3.z*R),this._chassisBody.setAngularVelocity(this._sv9),this._groundedAutoLevelWasActive=!0}}}}}},n.prototype.applyTrackConnectionAndDownforce=function(e,t,n){if(!(e<=0||this._chassisMass<=0)){var i=this._wheelInfo.length;if(!(i<=0)){var r=9.81,o=null!=this._chassisBody.transformNode?this._chassisBody.transformNode.getScene():null;if(null!=o&&null!=o.gravity){var a=o.gravity.length();a>1e-4&&(r=a)}this._chassisBody.getObjectCenterWorldToRef(this._sv7);var s=Math.abs(this._currentVehicleSpeedKmHour),l=s/3.6;if(this.trackConnectionAccel>0&&t<i){var u=(i-t)/i,c=this.trackConnectionAccel;if(0===t&&this.airborneTrackConnectionMaxAccel>c){var d=1,h=this.airborneTrackConnectionFullKmh-this.airborneTrackConnectionStartKmh;h>0?d=BABYLON.Scalar.Clamp((s-this.airborneTrackConnectionStartKmh)/h,0,1):s<this.airborneTrackConnectionStartKmh&&(d=0),c+=(this.airborneTrackConnectionMaxAccel-c)*d}var p=c*this._chassisMass*u;n.scaleToRef(-p*e,this._sv1),this._chassisBody.applyImpulse(this._sv1,this._sv7)}if(t<=0){if(this.airborneRiseDamping>0||this.airborneMaxRiseSpeed>0){this._chassisBody.getLinearVelocityToRef(this._sv8);var m=BABYLON.Vector3.Dot(this._sv8,n);if(m>0){var f=0;if(this.airborneRiseDamping>0&&(f+=m*BABYLON.Scalar.Clamp(1-Math.exp(-this.airborneRiseDamping*e),0,.95)),this.airborneMaxRiseSpeed>0){var g=m-f;g>this.airborneMaxRiseSpeed&&(f+=g-this.airborneMaxRiseSpeed)}if((f=BABYLON.Scalar.Clamp(f,0,m))>1e-4){var v=f*this._chassisMass;n.scaleToRef(-v,this._sv1),this._chassisBody.applyImpulse(this._sv1,this._sv7)}}}}else{if(this.constantDownforce>0){var y=this._chassisMass*r*this.constantDownforce;n.scaleToRef(-y*e,this._sv1),this._chassisBody.applyImpulse(this._sv1,this._sv7)}if(this.downforceCoefficient>0&&l>1){var _=this.downforceCoefficient*l*l;n.scaleToRef(-_*e,this._sv1),this._chassisBody.applyImpulse(this._sv1,this._sv7)}}}}},n.prototype.updateVehicle=function(t){var n=this._wheelInfo.length;t>1/30&&(t=1/30),this.getChassisWorldTransform();for(var i=0;i<n;i++)this.updateWheelTransform(i,!1);this._chassisBody.getLinearVelocityToRef(this._sv1),this._currentVehicleSpeedKmHour=3.6*Math.sqrt(this._sv1.x*this._sv1.x+this._sv1.y*this._sv1.y+this._sv1.z*this._sv1.z);var r=this._chassisTransform.m,o=this._indexForwardAxis;this._sv2.set(r[4*o],r[4*o+1],r[4*o+2]),BABYLON.Vector3.Dot(this._sv2,this._sv1)<0&&(this._currentVehicleSpeedKmHour*=-1),this.raycastDebugLogEnabled&&this._raycastDebugFrameCounter++;var a=0;for(i=0;i<n;i++){var s=this._wheelInfo[i];this.rayCast(s);var l=s.raycastInfo.isInContact;l||!0!==this.enableMultiRaycast||(this.rayCast(s,.95),l=s.raycastInfo.isInContact),l&&a++}this.computeStabilizationUpVector(t,a,this._sv10),0===a&&this.smoothFlyingImpulse>0&&this.applyFlyingStabilization(t,this._sv10);var u=Math.abs(this._currentVehicleSpeedKmHour),c=this.isArcadeHandBrakeActive||this.isArcadeWheelSkidActive||this.isArcadeBurnoutModeActive||this.isArcadeDonutModeActive;if(this.sideToSideStabilityEnabled&&a>0&&u>this.sideToSideStabilityStartKmh&&!c){var d=this.sideToSideStabilityFullKmh-this.sideToSideStabilityStartKmh;d>0&&Math.min((u-this.sideToSideStabilityStartKmh)/d,1)}e.RigidbodyPhysics.SetAngularFactor(this._chassisBody,this.angularDamping.x,1,this.angularDamping.z),this.applyGroundedAutoLevel(t,a,this._sv10,c),this.applyHandbrakeYawAssist(t,u,this._currentVehicleSpeedKmHour),this.applyEasyDonutYawAssist(t,u,this._currentVehicleSpeedKmHour),this.updateSuspension(t);var h=0,p=0;for(this._sv6.set(0,0,0),i=0;i<n;i++)if((s=this._wheelInfo[i]).raycastInfo.isInContact){var m=s.suspensionForce;m>s.maxSuspensionForce&&(m=s.maxSuspensionForce),h+=m,this._sv6.addInPlace(s.raycastInfo.contactNormalWS),p++}for(p>0&&(h/=p,this._sv6.scaleInPlace(1/p),this._sv6.normalize()),this._chassisBody.getObjectCenterWorldToRef(this._sv5),p>0&&(this._sv6.scaleToRef(h*t*p,this._sv1),this._chassisBody.applyImpulse(this._sv1,this._sv5)),i=0;i<n;i++)if((s=this._wheelInfo[i]).raycastInfo.isInContact){var f=s.suspensionForce;f>s.maxSuspensionForce&&(f=s.maxSuspensionForce);var g=f-h;0!==g&&(s.raycastInfo.contactNormalWS.scaleToRef(g*t,this._sv1),this._chassisBody.applyImpulse(this._sv1,s.raycastInfo.contactPointWS))}this.updateFriction(t),this.updateArcadeWheelRotationBoost(t),this.applyTrackConnectionAndDownforce(t,a,this._sv10);for(var v=!0===this.isArcadeBurnoutModeActive||!0===this.isArcadeDonutModeActive||!0===this.isArcadeHandBrakeActive||!0===this.isArcadeWheelSkidActive,y=!1,_=0;_<n;_++)if(Math.abs(this._wheelInfo[_].engineForce)>1e-4){y=!0;break}var S=this.wheelAtRestSpeedThresholdKmh>0&&Math.abs(this._currentVehicleSpeedKmHour)<this.wheelAtRestSpeedThresholdKmh&&(!v||!y);for(i=0;i<n;i++){s=this._wheelInfo[i];var A=0;if(this.velocityAtWorldPoint(this._chassisBody,s.raycastInfo.hardPointWS,this._sv1),s.raycastInfo.isInContact){this._sv2.set(r[4*o],r[4*o+1],r[4*o+2]);var b=BABYLON.Vector3.Dot(this._sv2,s.raycastInfo.contactNormalWS);s.raycastInfo.contactNormalWS.scaleToRef(b,this._sv3),this._sv2.subtractInPlace(this._sv3),A=BABYLON.Vector3.Dot(this._sv2,this._sv1)/s.wheelRadius}if(!0!==S){var M=this.getWheelAngularVelocity(i,A,t,s.raycastInfo.isInContact);s.deltaRotation=M*t,s.rotation+=s.deltaRotation,s.deltaRotation*=.99}else s.rotationBoost=0,s.deltaRotation=0}this.clampChassisYawRate(t)},n.prototype.updateSuspension=function(e){for(var t=this._chassisMass,n=0;n<this._wheelInfo.length;n++){var i=this._wheelInfo[n];if(i.raycastInfo.isInContact){var r,o=i.getSuspensionRestLength()-i.raycastInfo.suspensionLength;r=i.suspensionStiffness*o*i.clippedInvContactDotSuspension;var a,s=i.suspensionRelativeVelocity;if(a=s<0?i.dampingCompression:i.dampingRelaxation,1!==this.suspensionDampingOverdrive&&(a*=this.suspensionDampingOverdrive),r-=a*s,i.suspensionForce=r*t,i.suspensionForce<0&&(i.suspensionForce=0),this.suspensionForceSmoothing>0&&i._prevSuspensionForce>=0){var l=this.suspensionForceSmoothing;i.suspensionForce=i.suspensionForce*(1-l)+i._prevSuspensionForce*l}i._prevSuspensionForce=i.suspensionForce}else this.trackConnectionAccel>0?i.suspensionForce=-this.trackConnectionAccel*t:i.suspensionForce=0,i._prevSuspensionForce=-1}},n.prototype.getSteeringAuthorityInput=function(){var e=BABYLON.Scalar.Clamp(this.currentSteeringInput,-1,1);if(Math.abs(e)>.001)return e;var t=this.getSignedFrontSteeringAngleRad();return BABYLON.Scalar.Clamp(t/.6,-1,1)},n.prototype.getSteeringMagnitude=function(){return Math.abs(this.getSteeringAuthorityInput())},n.prototype.applyEasyDonutYawAssist=function(e,t,n){if(!0!==this.isArcadeDonutModeActive)return this._arcadeDonutHoldElapsedSec=0,void(this._arcadeDonutDirectionSign=0);if(!0===this.arcadeDonutDirectYawEnabled){var i=this.getSignedFrontSteeringAngleRad();if(Math.abs(i)<=.02||this.arcadeSteeringAssist<=0)this._arcadeDonutHoldElapsedSec+=e;else{var r=this.arcadeDonutDirectYawDurationMs>0?this.arcadeDonutDirectYawDurationMs/1e3:0,o=this.arcadeDonutDirectYawFadeMs>0?this.arcadeDonutDirectYawFadeMs/1e3:0,a=this._arcadeDonutHoldElapsedSec,s=o>0?BABYLON.Scalar.Clamp(a/o,0,1):1,l=1;if(r>0){var u=r-a;u<=0?l=0:o>0&&u<o&&(l=u/o)}var c=Math.min(s,l);if(c<=0)this._arcadeDonutHoldElapsedSec+=e;else{var d=this._chassisTransform.m,h=this._indexForwardAxis,p=this._indexUpAxis,m=this._sv6,f=this._sv5;m.set(d[4*h],d[4*h+1],d[4*h+2]),f.set(d[4*p],d[4*p+1],d[4*p+2]),this._chassisBody.getLinearVelocityToRef(this._sv8);var g=BABYLON.Vector3.Dot(this._sv8,m),v=i>=0?1:-1;0===this._arcadeDonutDirectionSign&&(this._arcadeDonutDirectionSign=Math.abs(g)>.25?g>=0?1:-1:v);var y=BABYLON.Tools.ToRadians(this.arcadeDonutDirectYawDegPerSec)*this._arcadeDonutDirectionSign*v*c*this.arcadeSteeringAssist;if(Math.abs(y)<=1e-5)this._arcadeDonutHoldElapsedSec+=e;else{this._chassisBody.getAngularVelocityToRef(this._sv9);var _=BABYLON.Vector3.Dot(this._sv9,f),S=_+(y-_)*BABYLON.Scalar.Clamp(1-Math.exp(-14*e),0,1),A=.55*Math.abs(y);(Math.sign(S)!==Math.sign(y)||Math.abs(S)<A)&&(S=Math.sign(y)*A),f.scaleToRef(_,this._sv1),this._sv9.subtractToRef(this._sv1,this._sv2),f.scaleToRef(S,this._sv3),this._sv2.addToRef(this._sv3,this._sv9),this._chassisBody.setAngularVelocity(this._sv9),this._arcadeDonutHoldElapsedSec+=e}}}}},n.prototype.applyHandbrakeYawAssist=function(e,t,n){if(this.isArcadeYawAssistActive=!1,this.arcadeHandbrakeAssistEnabled){var i=this.getSteeringMagnitude(),r=this.getSteeringAuthorityInput();if(this.isArcadeHandBrakeActive&&!(i<.02)){var o=Math.max(0,t/3.6),a=BABYLON.Scalar.Clamp((o-.5)/3,0,1);if(!(a<=0)){var s=this._chassisTransform.m,l=this._indexRightAxis,u=this._indexUpAxis,c=this._indexForwardAxis;this._stb1.set(s[4*l],s[4*l+1],s[4*l+2]),this._stb2.set(s[4*u],s[4*u+1],s[4*u+2]),this._stb3.set(s[4*c],s[4*c+1],s[4*c+2]),this._chassisBody.getAngularVelocityToRef(this._sv9);var d=BABYLON.Vector3.Dot(this._sv9,this._stb1),h=BABYLON.Vector3.Dot(this._sv9,this._stb2),p=BABYLON.Vector3.Dot(this._sv9,this._stb3),m=this.getSignedFrontSteeringAngleRad();this.getApproxWheelbaseMeters()>.5&&o>.2&&Math.abs(m);var f=r*this.arcadeSteeringAssist*(.25+1*i)*a,g=Math.abs(0)>Math.abs(f)?0:f;if(g*h>=0&&Math.abs(h)>=Math.abs(g))this.isArcadeYawAssistActive=!0;else{var v=(.15+.35*i)*a,y=BABYLON.Scalar.Clamp(g*(2+4*i)*e,-v,v);Math.abs(y)<1e-6||(h+=y,this._sv9.set(this._stb1.x*d+this._stb2.x*h+this._stb3.x*p,this._stb1.y*d+this._stb2.y*h+this._stb3.y*p,this._stb1.z*d+this._stb2.z*h+this._stb3.z*p),this._chassisBody.setAngularVelocity(this._sv9),this.isArcadeYawAssistActive=!0)}}}}},n.prototype.resolveWheelSpinDirection=function(e,t,n){if(Math.abs(t)>1e-4)return t<0?-1:1;if(Math.abs(n)>1e-4)return n<0?-1:1;var i=this._wheelInfo[e];if(null!=i){if(Math.abs(i.deltaRotation)>1e-4)return i.deltaRotation<0?-1:1;if(Math.abs(i.rotationBoost)>1e-4)return i.rotationBoost<0?-1:1}return 0},n.prototype.updateArcadeWheelRotationBoost=function(e){for(var t=this.isArcadeBurnoutModeActive||this.isArcadeDonutModeActive,n=this.isArcadeBurnoutModeActive&&this.isArcadeHandBrakeActive&&Math.abs(this._currentVehicleSpeedKmHour)<=this.wheelAtRestSpeedThresholdKmh+2,i=BABYLON.Scalar.Clamp(e*this.arcadeWheelSpinBuildSpeed,0,1),r=0;r<this._wheelInfo.length;r++){var o=this._wheelInfo[r];this._arcadePreviousWheelSpin[r]=o.rotationBoost;var a=o.rotationBoost,s=0,l=o.defaultFriction>0?o.defaultFriction:o.frictionSlip,u=l>0?BABYLON.Scalar.Clamp(o.frictionSlip/l,0,1):1,c=o.engineForce*e,d=0;if(Math.abs(c)>1e-4&&r<this._forwardImpulse.length){var h=this._forwardImpulse[r];(c>0&&h>0||c<0&&h<0)&&(d=Math.sign(c)*Math.min(Math.abs(h),Math.abs(c)))}var p=Math.max(0,Math.abs(c)-Math.abs(d)),m=Math.abs(c)>1e-4?BABYLON.Scalar.Clamp(p/Math.abs(c),0,1):0,f=Math.max(0,o.suspensionForce*e*o.frictionSlip),g=o.raycastInfo.groundObject&&f>1e-4?BABYLON.Scalar.Clamp(Math.abs(this._sideImpulse[r])/f,0,1):0,v=BABYLON.Scalar.Clamp(1-o.skidInfo,0,1),y=this.resolveWheelSpinDirection(r,c,d);if(t&&0!==y&&Math.abs(c)>1e-4){var _=m,S=1;if(this.isArcadeBurnoutModeActive&&(_=Math.max(_,.65*v),S=Math.max(S,this.arcadeBurnoutWheelSpinGain),n&&(_=Math.max(_,1),S=Math.max(S,this.arcadeStationaryBurnoutWheelSpinGain))),this.isArcadeDonutModeActive&&(_=Math.max(_,.9*g,.5*v),S=Math.max(S,this.arcadeDonutWheelSpinGain)),o.raycastInfo.groundObject||(_=Math.max(_,1)),_>0){var A=p*this._chassisInvMass;if(o.raycastInfo.groundObject||(A=Math.max(A,Math.abs(c)*this._chassisInvMass)),s=y*(A/Math.max(o.wheelRadius,1e-4)/Math.max(e,1e-4))*S*BABYLON.Scalar.Lerp(.2,1,_),n){var b=Math.max(0,this.arcadeStationaryBurnoutMinAngularVelocity);Math.abs(s)<b&&(s=y*b)}}}if(Math.abs(s)>0){if(a*s<0){var M=BABYLON.Scalar.Clamp(e*this.arcadeWheelSpinRecoverySpeed*2,0,1);a=BABYLON.Scalar.Lerp(a,0,M)}a=BABYLON.Scalar.Lerp(a,s,i)}if(o.raycastInfo.groundObject){var B=Math.max(m,.5*v);this.isArcadeDonutModeActive&&(B=Math.max(B,g));var C=this.arcadeWheelSpinRecoverySpeed*(.25+.75*u)*(1-Math.min(B,.92));t||(C=this.arcadeWheelSpinRecoverySpeed*(.75+1.5*u));var T=BABYLON.Scalar.Clamp(e*C,0,1);a=BABYLON.Scalar.Lerp(a,0,T)}else a*=Math.pow(this.arcadeWheelSpinAirDamping,60*e);a=BABYLON.Scalar.Clamp(a,-this.arcadeWheelSpinMaxAngularVelocity,this.arcadeWheelSpinMaxAngularVelocity),Math.abs(this._currentVehicleSpeedKmHour)<1&&(!t||Math.abs(c)<=1e-4)&&(a=0),Math.abs(a)<.001&&(a=0),o.rotationBoost=a}},n.prototype.getWheelAngularVelocity=function(e,t,n,i){var r=this._wheelInfo[e];return null==r||n<=0?0:i?t+r.rotationBoost:r.deltaRotation/n-(e<this._arcadePreviousWheelSpin.length?this._arcadePreviousWheelSpin[e]:0)+r.rotationBoost},n.prototype.getArcadeBurnoutDirectionChangeFactor=function(e,t){if(!this.isArcadeBurnoutModeActive||null==e||Math.abs(e.engineForce)<=1e-4)return 0;var n=Math.max(0,this.arcadeBurnoutDirectionChangeSpeedKmh);if(n>0&&Math.abs(this._currentVehicleSpeedKmHour)>n)return 0;var i=-t*(e.engineForce<0?-1:1);if(i<=.15)return 0;var r=BABYLON.Scalar.Clamp((i-.15)/2.5,0,1);if(n<=0)return r;var o=1-BABYLON.Scalar.Clamp(Math.abs(this._currentVehicleSpeedKmHour)/n,0,1);return r*BABYLON.Scalar.Lerp(.45,1,o)},n.prototype.updateArcadeSkidInfo=function(e,t,n){var i=e<this._arcadeSkidInfo.length?this._arcadeSkidInfo[e]:1,r=BABYLON.Scalar.Clamp(t,0,1),o=r<i?this.wheelSkidFadeInSpeed:this.wheelSkidFadeOutSpeed,a=BABYLON.Scalar.Clamp(n*o,0,1);return i=BABYLON.Scalar.Lerp(i,r,a),Math.abs(i-r)<.001&&(i=r),this._arcadeSkidInfo[e]=i,i},n.prototype.updateFriction=function(e){var t=this._wheelInfo.length;if(0!==t){for(var n=0,i=0;i<t;i++)(le=this._wheelInfo[i]).raycastInfo.groundObject&&n++,this._sideImpulse[i]=0,this._forwardImpulse[i]=0;for(i=0;i<t;i++)if((le=this._wheelInfo[i]).raycastInfo.groundObject){var r=this._sv5;le.raycastInfo.wheelDirectionWS.negateToRef(r),BABYLON.Quaternion.RotationAxisToRef(r,le.steering,this._sq1),BABYLON.Matrix.FromQuaternionToRef(this._sq1,this._sm2),BABYLON.Vector3.TransformNormalToRef(le.raycastInfo.wheelAxleWS,this._sm2,this._axle[i]);var o=le.raycastInfo.contactNormalWS,a=BABYLON.Vector3.Dot(this._axle[i],o);if(o.scaleToRef(a,this._sv6),this._axle[i].subtractInPlace(this._sv6),this._axle[i].normalize(),BABYLON.Vector3.CrossToRef(o,this._axle[i],this._forwardWS[i]),this._forwardWS[i].normalize(),this._sideImpulse[i]=this.resolveSingleBilateral(this._chassisBody,le.raycastInfo.contactPointWS,this._axle[i]),this._sideImpulse[i]*=this.sideFrictionStiffness,this.arcadeSideSlipSaturationEnabled&&0!==this._sideImpulse[i]){this.velocityAtWorldPoint(this._chassisBody,le.raycastInfo.contactPointWS,this._sv8);var s=BABYLON.Vector3.Dot(this._axle[i],this._sv8),l=BABYLON.Vector3.Dot(this._forwardWS[i],this._sv8),u=s*s+l*l,c=this.arcadeSideSlipMinSpeedMps;if(u>c*c){var d=Math.atan2(Math.abs(s),Math.max(Math.abs(l),.001)),h=BABYLON.Tools.ToRadians(Math.max(this.arcadeSideSlipPeakDeg,.1));if(d>h){var p=Math.sin(h)/Math.max(Math.sin(d),.001),m=Math.max(this.arcadeSideSlipFalloffDeg-this.arcadeSideSlipPeakDeg,.1),f=Math.min(Math.max((BABYLON.Tools.ToDegrees(d)-this.arcadeSideSlipPeakDeg)/m,0),1),g=BABYLON.Scalar.Lerp(1,this.arcadeSideSlipFalloffFactor,f);this._sideImpulse[i]*=p*g}}}}for(var v=!1,y=0;y<t;y++){var _=0,S=1,A=!1,b=!1,M=0,B=0,C=0;if((le=this._wheelInfo[y]).raycastInfo.groundObject)if(0!==le.engineForce)_=le.engineForce*e;else{var T=le.brake?le.brake:0;_=this.calcRollingFriction(this._chassisBody,le.raycastInfo.contactPointWS,this._forwardWS[y],T,n)}if(this._forwardImpulse[y]=0,this._wheelInfo[y].skidInfo=1,le.raycastInfo.groundObject){this._wheelInfo[y].skidInfo=1;var x=le.suspensionForce*e*le.frictionSlip,I=x*x;this._forwardImpulse[y]=_;var O=.5*this._forwardImpulse[y],L=1*this._sideImpulse[y],w=O*O+L*L,N=Math.sqrt(w);if(w>I){v=!0;var P=x/Math.sqrt(w);this._wheelInfo[y].skidInfo*=P}if(b=(A=(this.isArcadeHandBrakeActive||this.isArcadeWheelSkidActive)&&le.brake>0&&0===le.engineForce)||this.isArcadeWheelSkidActive||this.isArcadeBurnoutModeActive||this.isArcadeDonutModeActive){this.velocityAtWorldPoint(this._chassisBody,le.raycastInfo.contactPointWS,this._sv3);var R=BABYLON.Vector3.Dot(this._forwardWS[y],this._sv3);M=Math.abs(R),B=Math.abs(BABYLON.Vector3.Dot(this._axle[y],this._sv3)),C=this.getArcadeBurnoutDirectionChangeFactor(le,R)}if(this.isArcadeBurnoutModeActive&&x>0){var E=x;C>0&&(E*=BABYLON.Scalar.Lerp(1,this.arcadeBurnoutDirectionChangeGripScale,C));var k=Math.abs(this._forwardImpulse[y]);if(k>E){var D=E/k;this._forwardImpulse[y]*=D,this._wheelInfo[y].skidInfo=Math.min(this._wheelInfo[y].skidInfo,D),v=!0}if(C>0){var F=BABYLON.Scalar.Lerp(.18,.02,C);this._wheelInfo[y].skidInfo=Math.min(this._wheelInfo[y].skidInfo,F),v=!0}}if(b){var U=BABYLON.Scalar.Clamp((Math.abs(this._currentVehicleSpeedKmHour)-2)/20,0,1),Y=BABYLON.Scalar.Clamp((M-.5)/6,0,1),V=BABYLON.Scalar.Clamp((B-.2)/4,0,1),G=x>0?BABYLON.Scalar.Clamp((N/x-.55)/.45,0,1):0,z=x>0?BABYLON.Scalar.Clamp(Math.abs(this._forwardImpulse[y])/x,0,1):0;if(A){var W=Math.max(Y,U);W>0&&(S=Math.min(S,BABYLON.Scalar.Lerp(.32,.02,W)))}if(this.isArcadeWheelSkidActive){var H=Math.max(G,V,.85*Y);H>0&&(S=Math.min(S,BABYLON.Scalar.Lerp(.34,.05,H)))}if(this.isArcadeBurnoutModeActive&&0!==le.engineForce){var X=Math.max(z,Y,.7*U);if(C>0&&(X=Math.max(X,C)),X>0){var K=le.isFrontWheel?.38:.28,Q=le.isFrontWheel?.12:.04;S=Math.min(S,BABYLON.Scalar.Lerp(K,Q,X))}if(C>0){var j=le.isFrontWheel?.24:.1,Z=le.isFrontWheel?.08:.02;S=Math.min(S,BABYLON.Scalar.Lerp(j,Z,C))}}if(this.isArcadeDonutModeActive){var q=Math.max(V,z,.9*U,.75*Y);if(le.isFrontWheel||(q=Math.max(q,.55*U)),q>0){var J=le.isFrontWheel?.42:.24,$=le.isFrontWheel?.16:.03;S=Math.min(S,BABYLON.Scalar.Lerp(J,$,q))}}}}var ee=this.updateArcadeSkidInfo(y,S,e);le.raycastInfo.groundObject&&(this._wheelInfo[y].skidInfo=Math.min(this._wheelInfo[y].skidInfo,ee))}if(v)for(y=0;y<t;y++)0!==this._sideImpulse[y]&&this._wheelInfo[y].skidInfo<1&&(this.isArcadeBurnoutModeActive||(this._forwardImpulse[y]*=this._wheelInfo[y].skidInfo),this._sideImpulse[y]*=this._wheelInfo[y].skidInfo);var te=0,ne=0;for(y=0;y<t;y++)this._wheelInfo[y].raycastInfo.groundObject&&0!==this._sideImpulse[y]&&(te+=this._sideImpulse[y],ne++);ne>0&&(te/=ne);var ie=0,re=Math.abs(this._currentVehicleSpeedKmHour);if(!(this.isArcadeHandBrakeActive||this.isArcadeWheelSkidActive||this.isArcadeBurnoutModeActive||this.isArcadeDonutModeActive)&&this.sideToSideStabilityEnabled&&re>this.sideToSideStabilityStartKmh){var oe=this.sideToSideStabilityFullKmh-this.sideToSideStabilityStartKmh;oe>0&&(ie=.7*Math.min((re-this.sideToSideStabilityStartKmh)/oe,1))}this._chassisBody.getObjectCenterWorldToRef(this._sv7);var ae=this._indexUpAxis,se=this._chassisTransform.m;for(this._sv2.set(se[4*ae],se[4*ae+1],se[4*ae+2]),y=0;y<t;y++){var le=this._wheelInfo[y];if(0!==this._forwardImpulse[y]&&(this._forwardWS[y].scaleToRef(this._forwardImpulse[y],this._sv1),this._chassisBody.applyImpulse(this._sv1,this._sv7)),0!==this._sideImpulse[y]){le.raycastInfo.contactPointWS.subtractToRef(this._sv7,this._sv1);var ue=BABYLON.Vector3.Dot(this._sv2,this._sv1);this._sv2.scaleToRef(ue*(1-le.rollInfluence),this._sv3),this._sv1.subtractInPlace(this._sv3),this._sv7.addToRef(this._sv1,this._sv4);var ce=this._sideImpulse[y]-te,de=te+ce*ie,he=ce*(1-ie);this._axle[y].scaleToRef(de,this._sv5),this._chassisBody.applyImpulse(this._sv5,this._sv7),0!==he&&(this._axle[y].scaleToRef(he,this._sv5),this._chassisBody.applyImpulse(this._sv5,this._sv4))}}}},n.prototype.velocityAtWorldPoint=function(e,t,n){e.getObjectCenterWorldToRef(this._vapCenter),t.subtractToRef(this._vapCenter,this._vapRelPos),e.getAngularVelocityToRef(this._vapAngVel),BABYLON.Vector3.CrossToRef(this._vapAngVel,this._vapRelPos,this._vapCross),e.getLinearVelocityToRef(this._vapLinVel),this._vapLinVel.addToRef(this._vapCross,n)},n.prototype.resolveSingleBilateral=function(e,t,n){return n.lengthSquared()>1.1?0:(this.velocityAtWorldPoint(e,t,this._rsbVel1),-.2*BABYLON.Vector3.Dot(n,this._rsbVel1)*this._chassisMass)},n.prototype.calcRollingFriction=function(e,t,n,i,r){this.velocityAtWorldPoint(e,t,this._crfVel1);var o=-BABYLON.Vector3.Dot(n,this._crfVel1)*this._chassisMass;return r>0&&(o/=r),o>i&&(o=i),o<-i&&(o=-i),o},n.prototype.clampChassisYawRate=function(e){if(!(this.maximumYawRateLow<=0&&this.maximumYawRateHigh<=0)){var t=!0===this.isArcadeHandBrakeActive||!0===this.isArcadeBurnoutModeActive||!0===this.isArcadeDonutModeActive;if(!(!0===t&&!0===this.isArcadeHandBrakeActive&&this.arcadeHandbrakeYawCapMultiplier<=0||!0===t&&!0===this.isArcadeBurnoutModeActive&&this.arcadeBurnoutYawCapMultiplier<=0||!0===t&&!0===this.isArcadeDonutModeActive&&this.arcadeDonutYawCapMultiplier<=0)){var n=BABYLON.Scalar.Lerp(this.maximumYawRateLow,this.maximumYawRateHigh,this.smoothedGradientSpeed);if(!0===t&&(!0===this.isArcadeHandBrakeActive&&(n*=this.arcadeHandbrakeYawCapMultiplier),!0===this.isArcadeBurnoutModeActive&&(n*=this.arcadeBurnoutYawCapMultiplier),!0===this.isArcadeDonutModeActive&&(n*=this.arcadeDonutYawCapMultiplier)),!(n<=0)){var i=BABYLON.Tools.ToRadians(n),r=this._chassisBody.getAngularVelocity();if(null!=r){var o=Math.abs(r.y);if(o>i)r.y=Math.sign(r.y)*i*.95,this._chassisBody.setAngularVelocity(r);else if(o>.85*i){var a=(o-.85*i)/(.15*i);r.y*=1-.15*a,this._chassisBody.setAngularVelocity(r)}}}}}},n.prototype.getNaturalWheelSlip=function(e){var t=!1;return null!=this._wheelInfo[e]&&(t=!!this._wheelInfo[e].raycastInfo.groundObject&&this._wheelInfo[e].skidInfo<.999&&!this.isArcadeHandBrakeActive&&!this.isArcadeBurnoutModeActive&&!this.isArcadeDonutModeActive),t},n.prototype.getSignedFrontSteeringAngleRad=function(){for(var e=0,t=0,n=0;n<this._wheelInfo.length;n++)this._wheelInfo[n].isFrontWheel&&(e+=this._wheelInfo[n].steering,t++);return t>0?e/t:0},n.prototype.getApproxWheelbaseMeters=function(){for(var e=0,t=0,n=0,i=0,r=0;r<this._wheelInfo.length;r++){var o=this._wheelInfo[r].chassisConnectionPointCS.z;this._wheelInfo[r].isFrontWheel?(e+=o,n++):(t+=o,i++)}return 0===n||0===i?2.5:Math.abs(e/n-t/i)},n.prototype.dispose=function(){this._chassisBody=null,this._vehicleRaycaster=null,this._wheelInfo.length=0,this._forwardWS.length=0,this._axle.length=0,this._forwardImpulse.length=0,this._sideImpulse.length=0,this._arcadeSkidInfo.length=0,this._arcadePreviousWheelSpin.length=0},n.FILTER_GROUP_ALL_COLLIDERS=4294967295,n.FILTER_GROUP_VEHICLE_COLLIDERS=1048576,n.FILTER_GROUP_BRIDGE_COLLIDERS=2097152,n.FILTER_GROUP_ROAD_COLLIDERS=4194304,n.FILTER_GROUP_GRASS_COLLIDERS=8388608,n.FILTER_GROUP_CURB_COLLIDERS=16777216,n.FILTER_GROUP_FENCE_COLLIDERS=33554432,n.FILTER_GROUP_ALL_VEHICLE_COLLIDERS=66060288,n.VEHICLE_MESH_TAG="Vehicle",n.BRIDGE_MESH_TAG="Bridge",n.ROAD_MESH_TAG="Road",n.GRASS_MESH_TAG="Grass",n.CURB_MESH_TAG="Curb",n.FENCE_MESH_TAG="Fence",n}();e.btRaycastVehicle=o}(i||(i={})),function(e){var t=function(){function e(){}return e.CreatePostProcess=function(e,t,n){var i,r=(null==n?void 0:n.lutA)||null,o=(null==n?void 0:n.lutB)||null,a=null!==(i=null==n?void 0:n.mix)&&void 0!==i?i:0,s=new BABYLON.PostProcess("lutBlend","\n precision highp float;\n varying vec2 vUV;\n uniform sampler2D textureSampler;\n uniform sampler2D lutA;\n uniform sampler2D lutB;\n uniform float mixVal;\n uniform float lutTileCountA; // number of tiles per row for LUT A\n uniform float lutTileCountB; // number of tiles per row for LUT B\n\n vec3 sampleLUT(in sampler2D lut, in vec3 color, in float tileCount) {\n if (tileCount <= 0.5) return color;\n float tc = floor(tileCount + 0.5);\n float tileSize = 1.0 / tc;\n\n // For normalized RGB [0..1], compute position in LUT\n float r = color.r;\n float g = color.g;\n float b = color.b;\n\n // Determine slice and tile coords\n float slice = b * (tc - 1.0);\n float sliceIndex = floor(slice + 0.5);\n\n float tx = mod(sliceIndex, tc);\n float ty = floor(sliceIndex / tc);\n\n vec2 uv = vec2(tx * tileSize + r * tileSize, ty * tileSize + g * tileSize);\n vec3 sampled = texture2D(lut, uv).rgb;\n return sampled;\n }\n\n void main(void) {\n vec4 sceneColor = texture2D(textureSampler, vUV);\n vec3 a = sceneColor.rgb;\n if (lutTileCountA <= 0.5 || lutTileCountB <= 0.5) {\n // No LUT size provided fallback to passthrough\n gl_FragColor = sceneColor;\n return;\n }\n vec3 colA = sampleLUT(lutA, a, lutTileCountA);\n vec3 colB = sampleLUT(lutB, a, lutTileCountB);\n vec3 outc = mix(colA, colB, mixVal);\n gl_FragColor = vec4(outc, sceneColor.a);\n }\n ",["mixVal","lutTileCountA","lutTileCountB"],["lutA","lutB"],1,t,BABYLON.Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1);function l(e,t){if(!e||!t)return 0;if(e%t===0)return Math.round(e/t);if(t%e===0)return Math.round(t/e);if(e===t){var n=Math.round(Math.sqrt(e));return n*n===e?n:Math.round(Math.sqrt(e))}return Math.round(Math.pow(e*t,1/3))}var u=0,c=0;return s.onApply=function(t){if(t.setFloat("mixVal",a),r&&"string"==typeof r){var n=new BABYLON.Texture(r,e,!0,!1,BABYLON.Texture.TRILINEAR_SAMPLINGMODE,void 0,void 0,void 0,!1);n.onLoadObservable.addOnce(function(){u=l(n.getSize?n.getSize().width:n.width,n.getSize?n.getSize().height:n.height)}),t.setTexture("lutA",n)}else if(r instanceof BABYLON.Texture){var i=r;u=l(i.getSize?i.getSize().width:i.width,i.getSize?i.getSize().height:i.height),t.setTexture("lutA",i)}if(o&&"string"==typeof o){var s=new BABYLON.Texture(o,e,!0,!1,BABYLON.Texture.TRILINEAR_SAMPLINGMODE,void 0,void 0,void 0,!1);s.onLoadObservable.addOnce(function(){c=l(s.getSize?s.getSize().width:s.width,s.getSize?s.getSize().height:s.height)}),t.setTexture("lutB",s)}else if(o instanceof BABYLON.Texture){var d=o;c=l(d.getSize?d.getSize().width:d.width,d.getSize?d.getSize().height:d.height),t.setTexture("lutB",d)}t.setFloat("lutTileCountA",u),t.setFloat("lutTileCountB",c)},s._detectedTileCountA=function(){return u},s._detectedTileCountB=function(){return c},s},e.prototype.getWGSLShaderCode=function(){return"\n [[group(0), binding(0)]] var textureSampler: texture_2d<f32>;\n [[group(0), binding(1)]] var textureSamplerSampler: sampler;\n [[group(0), binding(2)]] var lutA: texture_2d<f32>;\n [[group(0), binding(3)]] var lutASampler: sampler;\n [[group(0), binding(4)]] var lutB: texture_2d<f32>;\n [[group(0), binding(5)]] var lutBSampler: sampler;\n\n [[block]] struct Uniforms {\n mixVal: f32;\n lutTileCountA: f32;\n lutTileCountB: f32;\n };\n [[group(0), binding(6)]] var<uniform> uniforms: Uniforms;\n\n fn sampleLUT(lut: texture_2d<f32>, lutSamp: sampler, color: vec3<f32>, tileCount: f32) -> vec3<f32> {\n if (tileCount <= 0.5) { return color; }\n let tc = floor(tileCount + 0.5);\n let tileSize = 1.0 / tc;\n\n let r = color.r;\n let g = color.g;\n let b = color.b;\n\n let slice = b * (tc - 1.0);\n let sliceIndex = floor(slice + 0.5);\n\n let tx = sliceIndex % tc;\n let ty = floor(sliceIndex / tc);\n\n let uv = vec2<f32>(tx * tileSize + r * tileSize, ty * tileSize + g * tileSize);\n let sampled = textureSample(lut, lutSamp, uv).rgb;\n return sampled;\n }\n\n fn mainImage(vUV: vec2<f32>) -> vec4<f32> {\n let sceneColor = textureSample(textureSampler, textureSamplerSampler, vUV);\n let a = sceneColor.rgb;\n if (uniforms.lutTileCountA <= 0.5 || uniforms.lutTileCountB <= 0.5) {\n return sceneColor;\n }\n let colA = sampleLUT(lutA, lutASampler, a, uniforms.lutTileCountA);\n let colB = sampleLUT(lutB, lutBSampler, a, uniforms.lutTileCountB);\n let outc = mix(colA, colB, uniforms.mixVal);\n return vec4<f32>(outc, sceneColor.a);\n }\n "},e}();e.LUTBlendPlugin=t}(i||(i={})),function(e){var t=function(){function e(e){var t,n,i,r,o,a;this._distortionIntensity=null!==(t=null==e?void 0:e.distortionIntensity)&&void 0!==t?t:0,this._distortionIntensityX=null!==(n=null==e?void 0:e.distortionIntensityX)&&void 0!==n?n:0,this._distortionIntensityY=null!==(i=null==e?void 0:e.distortionIntensityY)&&void 0!==i?i:0,this._distortionCenterX=null!==(r=null==e?void 0:e.distortionCenterX)&&void 0!==r?r:.5,this._distortionCenterY=null!==(o=null==e?void 0:e.distortionCenterY)&&void 0!==o?o:.5,this._distortionScale=null!==(a=null==e?void 0:e.distortionScale)&&void 0!==a?a:1,this._updateEnabledState()}return Object.defineProperty(e.prototype,"distortionIntensity",{get:function(){return this._distortionIntensity},set:function(e){this._distortionIntensity!==e&&(this._distortionIntensity=e,this._updateEnabledState())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"distortionIntensityX",{get:function(){return this._distortionIntensityX},set:function(e){this._distortionIntensityX!==e&&(this._distortionIntensityX=e,this._updateEnabledState())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"distortionIntensityY",{get:function(){return this._distortionIntensityY},set:function(e){this._distortionIntensityY!==e&&(this._distortionIntensityY=e,this._updateEnabledState())},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"distortionCenterX",{get:function(){return this._distortionCenterX},set:function(e){this._distortionCenterX=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"distortionCenterY",{get:function(){return this._distortionCenterY},set:function(e){this._distortionCenterY=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"distortionScale",{get:function(){return this._distortionScale},set:function(e){this._distortionScale=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"isEnabled",{get:function(){return this._isEnabled},enumerable:!1,configurable:!0}),e.prototype._updateEnabledState=function(){this._isEnabled=0!==this._distortionIntensity||0!==this._distortionIntensityX||0!==this._distortionIntensityY},e.prototype.getUniforms=function(){return{distortionIntensity:{type:"float",value:this._distortionIntensity},distortionIntensityX:{type:"float",value:this._distortionIntensityX},distortionIntensityY:{type:"float",value:this._distortionIntensityY},distortionCenter:{type:"vec2",value:[this._distortionCenterX,this._distortionCenterY]},distortionScale:{type:"float",value:this._distortionScale}}},e.prototype.getFragmentShaderCode=function(){return"\n uniform float distortionIntensity;\n uniform float distortionIntensityX;\n uniform float distortionIntensityY;\n uniform vec2 distortionCenter;\n uniform float distortionScale;\n\n void applyLensDistortion(inout vec4 color, vec2 uv) {\n // Calculate UV coordinates relative to center\n vec2 uvCentered = uv - distortionCenter;\n\n // Apply different distortion for X and Y if specified\n float intensityX = distortionIntensity + distortionIntensityX;\n float intensityY = distortionIntensity + distortionIntensityY;\n\n // Calculate distortion amount based on distance from center\n float r = length(uvCentered);\n float r2 = r * r;\n\n // Barrel distortion formula: r' = r * (1 + k1 * r^2 + k2 * r^4 + ...)\n // For simplicity, we use a quadratic approximation\n float distortion = 1.0 + intensityX * r2 + intensityY * r2 * r2;\n\n // Scale the distortion\n distortion *= distortionScale;\n\n // Apply distortion to UV coordinates\n vec2 distortedUV = distortionCenter + uvCentered * distortion;\n\n // Ensure UV coordinates stay within bounds\n distortedUV = clamp(distortedUV, vec2(0.0), vec2(1.0));\n\n // Sample the texture at the distorted position\n vec4 distortedColor = texture2D(diffuseSampler, distortedUV);\n\n // Mix with original color based on distortion strength\n float mixFactor = clamp(abs(distortionIntensity) + abs(distortionIntensityX) + abs(distortionIntensityY), 0.0, 1.0);\n color = mix(color, distortedColor, mixFactor);\n }\n "},e.prototype.getWGSLShaderCode=function(){return"\n [[group(0), binding(0)]] var diffuseSampler: texture_2d<f32>;\n [[group(0), binding(1)]] var diffuseSamplerSampler: sampler;\n\n struct Uniforms {\n distortionIntensity: f32;\n distortionIntensityX: f32;\n distortionIntensityY: f32;\n distortionCenter: vec2<f32>;\n distortionScale: f32;\n };\n\n [[group(0), binding(2)]] var<uniform> uniforms: Uniforms;\n\n fn applyLensDistortion(color: ptr<function, vec4<f32>>, uv: vec2<f32>) {\n // Calculate UV coordinates relative to center\n let uvCentered = uv - uniforms.distortionCenter;\n\n // Apply different distortion for X and Y if specified\n let intensityX = uniforms.distortionIntensity + uniforms.distortionIntensityX;\n let intensityY = uniforms.distortionIntensity + uniforms.distortionIntensityY;\n\n // Calculate distortion amount based on distance from center\n let r = length(uvCentered);\n let r2 = r * r;\n\n // Barrel distortion formula: r' = r * (1 + k1 * r^2 + k2 * r^4 + ...)\n let distortion = 1.0 + intensityX * r2 + intensityY * r2 * r2;\n\n // Scale the distortion\n let distortion_scaled = distortion * uniforms.distortionScale;\n\n // Apply distortion to UV coordinates\n let distortedUV = uniforms.distortionCenter + uvCentered * distortion_scaled;\n\n // Ensure UV coordinates stay within bounds\n let clampedUV = clamp(distortedUV, vec2<f32>(0.0), vec2<f32>(1.0));\n\n // Sample the texture at the distorted position\n let distortedColor = textureSample(diffuseSampler, diffuseSamplerSampler, clampedUV);\n\n // Mix with original color based on distortion strength\n let mixFactor = clamp(abs(uniforms.distortionIntensity) + abs(uniforms.distortionIntensityX) + abs(uniforms.distortionIntensityY), 0.0, 1.0);\n *color = mix(*color, distortedColor, mixFactor);\n }\n "},e.CreatePostProcess=function(e,t,n){var i,r,o,a,s,l,u={distortionIntensity:null!==(i=null==n?void 0:n.distortionIntensity)&&void 0!==i?i:0,distortionIntensityX:null!==(r=null==n?void 0:n.distortionIntensityX)&&void 0!==r?r:0,distortionIntensityY:null!==(o=null==n?void 0:n.distortionIntensityY)&&void 0!==o?o:0,distortionCenterX:null!==(a=null==n?void 0:n.distortionCenterX)&&void 0!==a?a:.5,distortionCenterY:null!==(s=null==n?void 0:n.distortionCenterY)&&void 0!==s?s:.5,distortionScale:null!==(l=null==n?void 0:n.distortionScale)&&void 0!==l?l:1},c=new BABYLON.PostProcess("lensDistortion","\n precision highp float;\n\n uniform float distortionIntensity;\n uniform float distortionIntensityX;\n uniform float distortionIntensityY;\n uniform vec2 distortionCenter;\n uniform float distortionScale;\n\n varying vec2 vUV;\n uniform sampler2D textureSampler;\n\n void main(void) {\n // Calculate UV coordinates relative to center\n vec2 uvCentered = vUV - distortionCenter;\n\n // Apply different distortion for X and Y if specified\n float intensityX = distortionIntensity + distortionIntensityX;\n float intensityY = distortionIntensity + distortionIntensityY;\n\n // Calculate distortion amount based on distance from center\n float r = length(uvCentered);\n float r2 = r * r;\n\n // Barrel distortion formula: r' = r * (1 + k1 * r^2 + k2 * r^4 + ...)\n float distortion = 1.0 + intensityX * r2 + intensityY * r2 * r2;\n\n // Scale the distortion\n distortion *= distortionScale;\n\n // Apply distortion to UV coordinates\n vec2 distortedUV = distortionCenter + uvCentered * distortion;\n\n // Ensure UV coordinates stay within bounds\n distortedUV = clamp(distortedUV, vec2(0.0), vec2(1.0));\n\n // Sample the texture at the distorted position\n vec4 distortedColor = texture2D(textureSampler, distortedUV);\n\n // Mix with original color based on distortion strength\n float mixFactor = clamp(abs(distortionIntensity) + abs(distortionIntensityX) + abs(distortionIntensityY), 0.0, 1.0);\n gl_FragColor = mix(texture2D(textureSampler, vUV), distortedColor, mixFactor);\n }\n ",["distortionIntensity","distortionIntensityX","distortionIntensityY","distortionCenter","distortionScale"],[],1,t,BABYLON.Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1);return c.onApply=function(e){e.setFloat("distortionIntensity",u.distortionIntensity),e.setFloat("distortionIntensityX",u.distortionIntensityX),e.setFloat("distortionIntensityY",u.distortionIntensityY),e.setVector2("distortionCenter",new BABYLON.Vector2(u.distortionCenterX,u.distortionCenterY)),e.setFloat("distortionScale",u.distortionScale)},c},e}();e.LensDistortionPlugin=t}(i||(i={})),function(e){var t,n=function(t){function n(e,n,i,r){void 0===i&&(i={}),void 0===r&&(r="TOOLKIT.NavigationAgent");var o=t.call(this,e,n,i,r)||this;return o.crowd=null,o.distanceToTarget=0,o.teleporting=!1,o.moveDirection=new BABYLON.Vector3(0,0,0),o.resetPosition=new BABYLON.Vector3(0,0,0),o.lastPosition=new BABYLON.Vector3(0,0,0),o.distancePosition=new BABYLON.Vector3(0,0,0),o.currentPosition=new BABYLON.Vector3(0,0,0),o.currentRotation=new BABYLON.Quaternion(0,0,0,1),o.currentVelocity=new BABYLON.Vector3(0,0,0),o.currentWaypoint=new BABYLON.Vector3(0,0,0),o.heightOffset=0,o.angularSpeed=0,o.updatePosition=!0,o.updateRotation=!0,o.distanceEpsilon=.1,o.velocityEpsilon=1.1,o.offMeshVelocity=1.5,o.stoppingDistance=0,o.onReadyObservable=new BABYLON.Observable,o.onPreUpdateObservable=new BABYLON.Observable,o.onPostUpdateObservable=new BABYLON.Observable,o.onNavCompleteObservable=new BABYLON.Observable,o.m_agentState=0,o.m_agentIndex=-1,o.m_agentReady=!1,o.m_agentGhost=null,o.m_agentParams=null,o.m_agentMovement=new BABYLON.Vector3(0,0,0),o.m_agentDirection=new BABYLON.Vector3(0,0,1),o.m_agentQuaternion=new BABYLON.Quaternion(0,0,0,1),o.m_agentDestination=null,o.m_debugDestinationSphere=null,o}return r(n,t),n.prototype.isReady=function(){return this.m_agentReady},n.prototype.isNavigating=function(){return null!=this.m_agentDestination},n.prototype.isTeleporting=function(){return this.teleporting},n.prototype.isOnOffMeshLink=function(){return this.m_agentState===e.CrowdAgentState.DT_CROWDAGENT_STATE_OFFMESH},n.prototype.getAgentType=function(){return this.type},n.prototype.getAgentState=function(){return this.m_agentState},n.prototype.getAgentIndex=function(){return this.m_agentIndex},n.prototype.getAgentOffset=function(){return this.baseOffset},n.prototype.getTargetDistance=function(){return this.distanceToTarget},n.prototype.getCurrentPosition=function(){return this.currentPosition},n.prototype.getCurrentRotation=function(){return this.currentRotation},n.prototype.getCurrentVelocity=function(){return this.currentVelocity},n.prototype.getAgentParameters=function(){return this.m_agentParams},n.prototype.setAgentParameters=function(e){this.m_agentParams=e,this.updateAgentParameters()},n.prototype.awake=function(){this.awakeNavigationAgent()},n.prototype.update=function(){this.updateNavigationAgent()},n.prototype.destroy=function(){this.destroyNavigationAgent()},n.prototype.awakeNavigationAgent=function(){this.type=this.getProperty("type",this.type),this.speed=this.getProperty("speed",this.speed),this.baseOffset=this.getProperty("offset",this.baseOffset),this.angularSpeed=this.getProperty("angularspeed",this.angularSpeed),this.acceleration=this.getProperty("acceleration",this.acceleration),this.stoppingDistance=this.getProperty("stoppingdistance",this.stoppingDistance),this.autoBraking=this.getProperty("autobraking",this.autoBraking),this.avoidRadius=this.getProperty("avoidradius",this.avoidRadius),this.avoidHeight=this.getProperty("avoidheight",this.avoidHeight),this.obstacleAvoidanceType=this.getProperty("avoidquality",this.obstacleAvoidanceType),this.avoidancePriority=this.getProperty("avoidpriority",this.avoidancePriority),this.autoTraverseOffMeshLink=this.getProperty("autotraverse",this.autoTraverseOffMeshLink),this.autoRepath=this.getProperty("autopepath",this.autoRepath),this.areaMask=this.getProperty("areamask",this.areaMask),e.Utilities.ValidateTransformQuaternion(this.transform),this.m_agentGhost=new BABYLON.TransformNode(this.transform.name+".Agent",this.scene),this.m_agentGhost.position=new BABYLON.Vector3(0,0,0),this.m_agentGhost.rotation=new BABYLON.Vector3(0,0,0),e.Utilities.ValidateTransformQuaternion(this.m_agentGhost),this.m_agentGhost.position.copyFrom(this.transform.position),this.lastPosition.copyFrom(this.transform.position),this.m_debugDestinationSphere=BABYLON.MeshBuilder.CreateSphere(this.transform.name+".DebugDestination",{diameter:.5},this.scene);var t=new BABYLON.StandardMaterial(this.transform.name+".DebugDestinationMat",this.scene);t.emissiveColor=new BABYLON.Color3(1,0,0),t.disableLighting=!0,this.m_debugDestinationSphere.material=t,this.m_debugDestinationSphere.isVisible=!1},n.prototype.updateNavigationAgent=function(){if(null==this.crowd)if(!0===e.NavigationAgent.GLOBAL_CROWD_INSTANCE)this.crowd=e.SceneManager.GetCrowdInterface(this.scene);else{var t=e.SceneManager.GetNavigationPlugin();null!=t&&e.SceneManager.HasNavigationData()?this.crowd=t.createCrowd(e.SceneManager.MAX_AGENT_COUNT,e.SceneManager.MAX_AGENT_RADIUS,this.scene):this.crowd=null}if(null!=this.crowd){if(this.m_agentIndex<0)return this.m_agentParams={radius:this.avoidRadius,height:this.avoidHeight,maxSpeed:this.speed,maxAcceleration:this.acceleration},e.Utilities.GetAbsolutePositionToRef(this.transform,this.resetPosition),this.m_agentIndex=this.crowd.addAgent(this.resetPosition,this.m_agentParams,this.m_agentGhost),void(this.m_agentIndex>=0&&(this.m_agentReady=!0,this.onReadyObservable&&this.onReadyObservable.hasObservers()&&this.onReadyObservable.notifyObservers(this.transform)));if(this.m_agentState=this.crowd.getAgentState(this.m_agentIndex),this.getAgentWaypointToRef(this.currentWaypoint),this.getAgentPositionToRef(this.currentPosition),this.distancePosition.copyFrom(this.currentPosition),this.isOnOffMeshLink()?(this.currentPosition.subtractToRef(this.lastPosition,this.currentVelocity),this.currentVelocity.scaleInPlace(this.speed*this.offMeshVelocity)):this.getAgentVelocityToRef(this.currentVelocity),this.onPreUpdateObservable&&this.onPreUpdateObservable.hasObservers()&&this.onPreUpdateObservable.notifyObservers(this.transform),this.currentPosition.y+=this.baseOffset+this.heightOffset,this.currentVelocity.length()>=this.velocityEpsilon){this.currentVelocity.normalize();var n=this.angularSpeed*e.NavigationAgent.ANGULAR_SPEED_RATIO*this.getDeltaSeconds();if(this.isOnOffMeshLink()){this.moveDirection.copyFrom(this.m_agentDirection),this.m_agentDirection.set(this.moveDirection.x+(this.currentVelocity.x-this.moveDirection.x),this.moveDirection.y+(this.currentVelocity.y-this.moveDirection.y),this.moveDirection.z+(this.currentVelocity.z-this.moveDirection.z)),this.m_agentDirection.normalize();var i=e.NavigationAgent.TARGET_ANGLE_FACTOR-Math.atan2(this.m_agentDirection.x,this.m_agentDirection.z);BABYLON.Quaternion.FromEulerAnglesToRef(0,i,0,this.currentRotation),this.isNavigating()&&!0===this.updateRotation&&BABYLON.Quaternion.SlerpToRef(this.transform.rotationQuaternion,this.currentRotation,n,this.transform.rotationQuaternion)}else this.m_agentQuaternion.copyFrom(this.transform.rotationQuaternion),this.isNavigating()&&!0===this.updateRotation&&this.transform.lookAt(this.currentWaypoint),this.transform.rotationQuaternion.toEulerAnglesToRef(this.m_agentDirection),BABYLON.Quaternion.FromEulerAnglesToRef(0,this.m_agentDirection.y,0,this.currentRotation),this.isNavigating()&&!0===this.updateRotation&&BABYLON.Quaternion.SlerpToRef(this.m_agentQuaternion,this.currentRotation,n,this.transform.rotationQuaternion)}this.isNavigating()&&!0===this.updatePosition&&this.transform.position.copyFrom(this.currentPosition),this.isNavigating()?(this.distanceToTarget=BABYLON.Vector3.Distance(this.distancePosition,this.m_agentDestination),this.distanceToTarget<=Math.max(this.distanceEpsilon,this.stoppingDistance)&&(this.cancelNavigation(),this.onNavCompleteObservable&&this.onNavCompleteObservable.hasObservers()&&this.onNavCompleteObservable.notifyObservers(this.transform))):this.distanceToTarget=0,this.lastPosition.copyFrom(this.currentPosition),this.onPostUpdateObservable&&this.onPostUpdateObservable.hasObservers()&&this.onPostUpdateObservable.notifyObservers(this.transform),null!=this.m_debugDestinationSphere&&(null!=this.m_agentDestination?this.m_debugDestinationSphere.position.copyFrom(this.m_agentDestination):this.m_debugDestinationSphere.position.set(0,0,0)),this.teleporting=!1}},n.prototype.updateAgentParameters=function(){null!=this.crowd&&this.m_agentIndex>=0&&this.crowd.updateAgentParameters(this.m_agentIndex,this.m_agentParams)},n.prototype.destroyNavigationAgent=function(){this.m_agentIndex=-1,this.m_agentReady=!1,this.m_agentMovement=null,this.m_agentDirection=null,this.m_agentDestination=null,this.moveDirection=null,this.resetPosition=null,this.lastPosition=null,this.currentPosition=null,this.currentRotation=null,this.currentVelocity=null,this.currentWaypoint=null,this.onReadyObservable.clear(),this.onReadyObservable=null,this.onPreUpdateObservable.clear(),this.onPreUpdateObservable=null,this.onPostUpdateObservable.clear(),this.onPostUpdateObservable=null,this.onNavCompleteObservable.clear(),this.onNavCompleteObservable=null,null!=this.m_agentGhost&&(this.m_agentGhost.dispose(),this.m_agentGhost=null),null!=this.m_debugDestinationSphere&&(this.m_debugDestinationSphere.dispose(),this.m_debugDestinationSphere=null)},n.prototype.move=function(t,n){void 0===n&&(n=!0);var i=e.SceneManager.GetNavigationPlugin();null!=i&&null!=this.crowd?(this.crowd.getAgentPosition(this.m_agentIndex).addToRef(t,this.m_agentMovement),this.m_agentDestination=!0===n?i.getClosestPoint(this.m_agentMovement):this.m_agentMovement.clone(),this.m_agentIndex>=0&&this.crowd.agentGoto(this.m_agentIndex,this.m_agentDestination)):BABYLON.Tools.Warn("No recast navigation mesh or crowd interface data available!")},n.prototype.teleport=function(t,n){void 0===n&&(n=!0);var i=e.SceneManager.GetNavigationPlugin();null!=i&&null!=this.crowd?(this.teleporting=!0,this.m_agentDestination=!0===n?i.getClosestPoint(t):t.clone(),this.m_agentIndex>=0&&this.crowd.agentTeleport(this.m_agentIndex,this.m_agentDestination)):BABYLON.Tools.Warn("No recast navigation mesh or crowd interface data available!")},n.prototype.setDestination=function(t,n){void 0===n&&(n=!0);var i=e.SceneManager.GetNavigationPlugin();null!=i&&null!=this.crowd?(this.m_agentDestination=!0===n?i.getClosestPoint(t):t.clone(),this.m_agentIndex>=0&&this.crowd.agentGoto(this.m_agentIndex,this.m_agentDestination)):BABYLON.Tools.Warn("No recast navigation mesh or crowd interface data available!")},n.prototype.setAcceleration=function(e){null!=this.m_agentParams&&(this.acceleration=e,this.m_agentParams.maxAcceleration=this.acceleration,this.updateAgentParameters())},n.prototype.setMovementSpeed=function(e){null!=this.m_agentParams&&(this.speed=e,this.m_agentParams.maxSpeed=this.speed,this.updateAgentParameters())},n.prototype.setSeparationWeight=function(e){null!=this.m_agentParams&&(this.m_agentParams.separationWeight=e,this.updateAgentParameters())},n.prototype.setOptimizationRange=function(e){null!=this.m_agentParams&&(this.m_agentParams.pathOptimizationRange=e,this.updateAgentParameters())},n.prototype.setCollisionQueryRange=function(e){null!=this.m_agentParams&&(this.m_agentParams.collisionQueryRange=e,this.updateAgentParameters())},n.prototype.setAgentRadius=function(e){null!=this.m_agentParams&&(this.m_agentParams.radius=e,this.updateAgentParameters())},n.prototype.setAgentHeight=function(e){null!=this.m_agentParams&&(this.m_agentParams.height=e,this.updateAgentParameters())},n.prototype.getAgentVelocity=function(){return null!=this.crowd&&this.m_agentIndex>=0?this.crowd.getAgentVelocity(this.m_agentIndex):null},n.prototype.getAgentVelocityToRef=function(e){null!=this.crowd&&this.m_agentIndex>=0&&this.crowd.getAgentVelocityToRef(this.m_agentIndex,e)},n.prototype.getAgentPosition=function(){return null!=this.crowd&&this.m_agentIndex>=0?this.crowd.getAgentPosition(this.m_agentIndex):null},n.prototype.getAgentPositionToRef=function(e){null!=this.crowd&&this.m_agentIndex>=0&&this.crowd.getAgentPositionToRef(this.m_agentIndex,e)},n.prototype.getAgentWaypoint=function(){return null!=this.crowd&&this.m_agentIndex>=0?this.crowd.getAgentNextTargetPath(this.m_agentIndex):null},n.prototype.getAgentWaypointToRef=function(e){null!=this.crowd&&this.m_agentIndex>=0&&this.crowd.getAgentNextTargetPathToRef(this.m_agentIndex,e)},n.prototype.cancelNavigation=function(){this.m_agentDestination=null;var e=this.getAgentPosition();null!=e&&null!=this.crowd&&this.m_agentIndex>=0&&this.crowd.agentTeleport(this.m_agentIndex,e)},n.prototype.getDebugDestinationMesh=function(){return this.m_debugDestinationSphere},n.prototype.showDebugDestination=function(e){null!=this.m_debugDestinationSphere&&(this.m_debugDestinationSphere.isVisible=e)},n.TARGET_ANGLE_FACTOR=.5*Math.PI,n.ANGULAR_SPEED_RATIO=.05,n.GLOBAL_CROWD_INSTANCE=!1,n}(e.ScriptComponent);e.NavigationAgent=n,(t=e.CrowdAgentState||(e.CrowdAgentState={}))[t.DT_CROWDAGENT_STATE_INVALID=0]="DT_CROWDAGENT_STATE_INVALID",t[t.DT_CROWDAGENT_STATE_WALKING=1]="DT_CROWDAGENT_STATE_WALKING",t[t.DT_CROWDAGENT_STATE_OFFMESH=2]="DT_CROWDAGENT_STATE_OFFMESH",e.SceneManager.RegisterClass("TOOLKIT.NavigationAgent",n)}(i||(i={})),function(e){var t=function(t){function n(n,i,r,o){void 0===r&&(r={}),void 0===o&&(o="TOOLKIT.PostProcessor");var a=t.call(this,n,i,r,o)||this;return a.highDynamicRange=!0,a.neutralToneMapping=!1,a.toneMappingMode=-1,a.defaultContrast=1,a.defaultExposure=1,a.defaultLookupTable=null,a.colorGradingSettings=null,a.bloomSettings=null,a.vignetteSettings=null,a.sharpenSettings=null,a.grainSettings=null,a.chromaticAberrationSettings=null,a.depthOfFieldSettings=null,a.motionBlurSettings=null,a.lensDistortionSettings=null,a.autoExposureSettings=null,a.colorFilterPP=null,a.coloredBloomPP=null,a.motionBlurPP=null,a.roundedVignettePP=null,a.lensDistortionPP=null,a.defaultRenderPipeline=null,a.screenSpaceAOPipeline=null,a.screenSpaceRPipeline=null,e.PostProcessor.GlobalInstance=a,a}return r(n,t),Object.defineProperty(n,"Instance",{get:function(){return n.GlobalInstance},enumerable:!1,configurable:!0}),n.prototype.GetDefaultRenderPipeline=function(){return this.defaultRenderPipeline},n.prototype.GetSSAORRenderPipeline=function(){return this.screenSpaceAOPipeline},n.prototype.GetSSRRenderPipeline=function(){return this.screenSpaceRPipeline},n.prototype.ready=function(){var e=this.getProperties();if(e.isglobal){if(null!=e.effects&&Array.isArray(e.effects))for(var t=0,n=e.effects;t<n.length;t++){var i=n[t];if(i&&i.effecttype){var r=i.effecttype.toLowerCase();switch(r){case"colorgrading":this.colorGradingSettings=this.parseColorGradingSettings(i.parameters);break;case"ambientocclusion":var o=this.parseAmbientOcclusionSettings(i.parameters);null!=o&&(this.screenSpaceAOPipeline=new BABYLON.SSAORenderingPipeline("SSAO",this.scene,1,this.scene.cameras),o.intensity&&!1!==o.intensity.overrideState&&(this.screenSpaceAOPipeline.totalStrength=Number(o.intensity.value)),o.radius&&!1!==o.radius.overrideState&&(this.screenSpaceAOPipeline.radius=Number(o.radius.value)),o.thicknessModifier&&!1!==o.thicknessModifier.overrideState&&(this.screenSpaceAOPipeline.fallOff=Number(o.thicknessModifier.value)));break;case"screenspacereflections":var a=this.parseScreenSpaceReflectionsSettings(i.parameters);if(null!=a){if(this.screenSpaceRPipeline=new BABYLON.SSRRenderingPipeline("SSR",this.scene,this.scene.cameras),a.preset&&!1!==a.preset.overrideState){var s=Number(a.preset.value);this.screenSpaceRPipeline.step=Math.max(.1,1/(s+1)),this.screenSpaceRPipeline.strength=Math.min(2,.5*s+.5)}a.maximumIterationCount&&!1!==a.maximumIterationCount.overrideState&&(this.screenSpaceRPipeline.maxSteps=Number(a.maximumIterationCount.value)),a.thickness&&!1!==a.thickness.overrideState&&(this.screenSpaceRPipeline.thickness=Number(a.thickness.value))}break;case"autoexposure":this.autoExposureSettings=this.parseAutoExposure(i.parameters);break;case"bloom":this.bloomSettings=this.parseBloomSettings(i.parameters);break;case"chromaticaberration":this.chromaticAberrationSettings=this.parseChromaticAberrationSettings(i.parameters);break;case"depthoffield":this.depthOfFieldSettings=this.parseDepthOfFieldSettings(i.parameters);break;case"grain":this.grainSettings=this.parseGrainSettings(i.parameters);break;case"lensdistortion":this.lensDistortionSettings=this.parseLensDistortionSettings(i.parameters);break;case"motionblur":this.motionBlurSettings=this.parseMotionBlurSettings(i.parameters);break;case"vignette":this.vignetteSettings=this.parseVignetteSettings(i.parameters);break;case"sharpen":this.sharpenSettings=this.parseSharpenSettings(i.parameters);break;default:console.warn("[PostProcessor] Unsupported effect type:",r)}}}}else console.warn("[PostProcessor] Non global volumes are not supported..");this.defaultRenderPipeline=new BABYLON.DefaultRenderingPipeline("DefaultPostProcessor",this.highDynamicRange,this.scene,this.scene.cameras,!0),this.defaultRenderPipeline.imageProcessingEnabled=!0,this.defaultRenderPipeline.samples=1,this.applyColorGradingSettings(),this.applyBloomSettings(),this.applyVignetteSettings(),this.applySharpenSettings(),this.applyGrainSettings(),this.applyChromaticAberrationSettings(),this.applyDepthOfFieldSettings(),this.applyMotionBlurSettings(),this.applyLensDistortionSettings(),this.applyAutoExposureSettings(),console.log("[PostProcessor] Initialized DefaultRenderingPipeline",this)},n.prototype.parseColorGradingSettings=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)},i={tonemapper:n("tonemapper"),postExposure:n("postexposure"),saturation:n("saturation"),contrast:n("contrast"),lut:n("lut")||n("externallut")||n("ldrlut"),lut2:n("lut2"),lutCrossFade:n("lutCrossFade")||n("lutBlend")||n("mix"),lift:n("lift"),gamma:n("gamma"),gain:n("gain"),tonecurvetoestrength:n("tonecurvetoestrength"),tonecurvetoelength:n("tonecurvetoelength"),tonecurveshoulderstrength:n("tonecurveshoulderstrength"),tonecurveshoulderlength:n("tonecurveshoulderlength"),tonecurveshoulderangle:n("tonecurveshoulderangle"),tonecurvegamma:n("tonecurvegamma"),temperature:n("temperature"),tint:n("tint"),colorfilter:n("colorfilter")};if(this.colorGradingSettings=i,i.tonemapper&&!1!==i.tonemapper.overrideState&&null!=i.tonemapper.value){var r=this.mapToneMapper(i.tonemapper);r&&r.enabled&&(this.toneMappingMode=1===r.type?BABYLON.ImageProcessingConfiguration.TONEMAPPING_ACES:2===r.type?BABYLON.ImageProcessingConfiguration.TONEMAPPING_KHR_PBR_NEUTRAL:BABYLON.ImageProcessingConfiguration.TONEMAPPING_STANDARD)}if(i.postExposure&&!1!==i.postExposure.overrideState&&null!=i.postExposure.value){var o=Math.pow(2,Number(i.postExposure.value));this.defaultExposure=1*o}return i.contrast&&!1!==i.contrast.overrideState&&null!=i.contrast.value&&(this.defaultContrast=.05*Number(i.contrast.value)),i},n.prototype.applyColorGradingSettings=function(){if(this.colorGradingSettings&&this.defaultRenderPipeline&&this.defaultRenderPipeline.imageProcessing){console.log("[PostProcessor] Applying Color Grading Settings:",this.colorGradingSettings),this.colorGradingSettings;var e=this.defaultRenderPipeline.imageProcessing;0!=this.defaultExposure&&(e.exposure=this.defaultExposure),0===e.exposure&&(e.exposure=1),0!=this.defaultContrast&&(e.contrast=this.defaultContrast),0===e.contrast&&(e.contrast=1),this.toneMappingMode>=0&&(e.toneMappingType=this.toneMappingMode,e.toneMappingEnabled=!0)}},n.prototype.mapToneMapper=function(t){var n=e.PostProcessor.extractParam(t);if(!n||null==n.value)return{enabled:!1,type:null};if(!1===n.overrideState)return{enabled:!1,type:null};var i=n.value,r=null;"object"==typeof i?i.name?r=(""+i.name).toUpperCase():null!=i.value&&"string"==typeof i.value&&(r=(""+i.value).toUpperCase()):r=(""+i).toUpperCase();var o=BABYLON.ImageProcessingConfiguration.TONEMAPPING_ACES,a=BABYLON.ImageProcessingConfiguration.TONEMAPPING_KHR_PBR_NEUTRAL,s=BABYLON.ImageProcessingConfiguration.TONEMAPPING_STANDARD;return r&&r.indexOf("ACES")>=0?{enabled:!0,type:o}:r&&r.indexOf("NEUTRAL")>=0?{enabled:!0,type:a}:r&&(r.indexOf("NONE")>=0||r.indexOf("DISABLED")>=0)||isNaN(Number(i))?{enabled:!1,type:s}:{enabled:!0,type:Number(i)}},n.prototype.parseBloomSettings=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)};return{intensity:n("intensity"),threshold:n("threshold"),softKnee:n("softKnee")||n("softknee"),clamp:n("clamp"),diffusion:n("diffusion"),anamorphicRatio:n("anamorphicRatio")||n("anamorphicratio"),color:n("color"),fastMode:n("fastMode")||n("fastmode")}},n.prototype.applyBloomSettings=function(){var t;if(this.bloomSettings&&this.defaultRenderPipeline){console.log("[PostProcessor] Applying Bloom Settings:",this.bloomSettings);var n=this.bloomSettings,i=this.defaultRenderPipeline;if(n.intensity&&!1!==n.intensity.overrideState&&null!=n.intensity.value&&(i.bloomWeight=Number(n.intensity.value)),n.threshold&&!1!==n.threshold.overrideState&&null!=n.threshold.value&&(i.bloomThreshold=Number(n.threshold.value)),n.diffusion&&!1!==n.diffusion.overrideState&&null!=n.diffusion.value){var r=Number(n.diffusion.value);i.bloomKernel=Math.max(1,Math.floor(10*r)),i.bloomScale=r}n.color&&!1!==n.color.overrideState&&Array.isArray(n.color.value)&&(i.bloomWeight=0,this.coloredBloomPP=e.ColoredBloomPlugin.CreateColoredBloom(this.scene,this.scene.activeCamera,{threshold:i.bloomThreshold,color:n.color.value,weight:Number((null===(t=n.intensity)||void 0===t?void 0:t.value)||1),kernel:i.bloomKernel,saturation:1}),this.coloredBloomPP.name="ColoredBloomPostProcess")}},n.prototype.parseSharpenSettings=function(t){return t?{intensity:function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)}("intensity")}:null},n.prototype.applySharpenSettings=function(){if(this.sharpenSettings&&this.defaultRenderPipeline&&this.defaultRenderPipeline.sharpen){console.log("[PostProcessor] Applying Sharpen Settings:",this.sharpenSettings);var e=this.sharpenSettings,t=this.defaultRenderPipeline.sharpen;e.intensity&&!1!==e.intensity.overrideState&&null!=e.intensity.value&&(t.edgeAmount=Number(e.intensity.value))}},n.prototype.parseGrainSettings=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)};return{intensity:n("intensity"),size:n("size"),lumContrib:n("lumContrib")||n("lumcontrib"),colored:n("colored")}},n.prototype.applyGrainSettings=function(){if(this.grainSettings&&this.defaultRenderPipeline&&this.defaultRenderPipeline.grain){console.log("[PostProcessor] Applying Grain Settings:",this.grainSettings);var e=this.grainSettings,t=this.defaultRenderPipeline.grain;e.intensity&&!1!==e.intensity.overrideState&&null!=e.intensity.value&&(t.intensity=Number(e.intensity.value))}},n.prototype.parseVignetteSettings=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)};return{color:n("color"),center:n("center"),intensity:n("intensity"),smoothness:n("smoothness"),rounded:n("rounded"),mode:n("mode")||n("blendMode")}},n.prototype.applyVignetteSettings=function(){if(this.vignetteSettings&&this.defaultRenderPipeline&&this.defaultRenderPipeline.imageProcessing){console.log("[PostProcessor] Applying Vignette Settings:",this.vignetteSettings);var t=this.vignetteSettings,n=this.defaultRenderPipeline.imageProcessing;t.color&&!1!==t.color.overrideState&&Array.isArray(t.color.value)&&(n.vignetteColor=new BABYLON.Color4(t.color.value[0]||0,t.color.value[1]||0,t.color.value[2]||0,null!=t.color.value[3]?t.color.value[3]:1)),t.center&&!1!==t.center.overrideState&&Array.isArray(t.center.value)&&(n.vignetteCenterX=(t.center.value[0]||.5)-.5,n.vignetteCenterY=(t.center.value[1]||.5)-.5),t.intensity&&!1!==t.intensity.overrideState&&null!=t.intensity.value&&(n.vignetteWeight=10*Number(t.intensity.value)),t.smoothness&&!1!==t.smoothness.overrideState&&null!=t.smoothness.value&&(n.vignetteBlendMode=Number(t.smoothness.value)),t.rounded&&!1!==t.rounded.overrideState&&!0===t.rounded.value&&(n.vignetteWeight=0,this.roundedVignettePP=e.RoundedVignettePlugin.CreatePostProcess(this.scene,this.scene.activeCamera,{color:n.vignetteColor?[n.vignetteColor.r,n.vignetteColor.g,n.vignetteColor.b,n.vignetteColor.a]:[0,0,0,1],center:[(n.vignetteCenterX||.5)-.5,(n.vignetteCenterY||.5)-.5],intensity:n.vignetteWeight,smoothness:n.vignetteBlendMode,rounded:!0,blendMode:t.mode&&t.mode.value?t.mode.value:"multiply"}),this.roundedVignettePP.name="RoundedVignettePostProcess"),n.vignetteEnabled=!0}},n.prototype.parseDepthOfFieldSettings=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)};return{focusDistance:n("focusDistance")||n("focusdistance"),aperture:n("aperture"),focalLength:n("focalLength")||n("focallength"),kernelSize:n("kernelSize")||n("kernelsize")}},n.prototype.applyDepthOfFieldSettings=function(){if(this.depthOfFieldSettings&&this.defaultRenderPipeline&&this.defaultRenderPipeline.depthOfField){console.log("[PostProcessor] Applying Depth Of Field Settings:",this.depthOfFieldSettings);var e=this.depthOfFieldSettings,t=this.defaultRenderPipeline.depthOfField;if(e.focusDistance&&!1!==e.focusDistance.overrideState&&null!=e.focusDistance.value&&(t.focusDistance=Number(e.focusDistance.value)),e.aperture&&!1!==e.aperture.overrideState&&null!=e.aperture.value&&(t.fStop=Number(e.aperture.value)),e.focalLength&&!1!==e.focalLength.overrideState&&null!=e.focalLength.value&&(t.focalLength=Number(e.focalLength.value)),e.kernelSize&&!1!==e.kernelSize.overrideState&&null!=e.kernelSize.value){var n=Number(e.kernelSize.value);t.fStop=Math.max(.1,2-n)}t._enable([this.scene.activeCamera])}},n.prototype.parseMotionBlurSettings=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)};return{shutterAngle:n("shutterAngle")||n("shutterangle"),sampleCount:n("sampleCount")||n("samplecount")}},n.prototype.applyMotionBlurSettings=function(){if(this.motionBlurSettings){console.log("[PostProcessor] Applying Motion Blur Settings:",this.motionBlurSettings);var e=this.motionBlurSettings;this.motionBlurPP=new BABYLON.MotionBlurPostProcess("motionBlur",this.scene,1,this.scene.activeCamera),this.motionBlurPP.name="MotionBlurPostProcess",e.sampleCount&&!1!==e.sampleCount.overrideState&&null!=e.sampleCount.value&&(this.motionBlurPP.samples=Number(e.sampleCount.value))}},n.prototype.parseAutoExposure=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)};return{filtering:n("filtering"),minimum:n("minimum"),maximum:n("maximum"),speedUp:n("speedUp")||n("speedup"),speedDown:n("speedDown")||n("speeddown")}},n.prototype.applyAutoExposureSettings=function(){if(this.autoExposureSettings&&this.defaultRenderPipeline&&this.defaultRenderPipeline.imageProcessing){console.log("[PostProcessor] Applying Auto Exposure Settings:",this.autoExposureSettings);var e=this.autoExposureSettings;this.defaultRenderPipeline.imageProcessing,e.minimum&&!1!==e.minimum.overrideState&&e.minimum.value,e.maximum&&!1!==e.maximum.overrideState&&e.maximum.value,console.warn("[PostProcessor] Auto-exposure is partially supported; full adaptive exposure requires custom implementation.")}},n.prototype.parseLensDistortionSettings=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)};return{intensity:n("intensity"),intensityX:n("intensityX")||n("intensityx"),intensityY:n("intensityY")||n("intensityy"),centerX:n("centerX")||n("centerx"),centerY:n("centerY")||n("centery"),scale:n("scale")}},n.prototype.applyLensDistortionSettings=function(){var t,n,i,r,o,a;if(this.lensDistortionSettings){console.log("[PostProcessor] Applying Lens Distortion Settings:",this.lensDistortionSettings);var s=this.lensDistortionSettings;this.lensDistortionPP=e.LensDistortionPlugin.CreatePostProcess(this.scene,this.scene.activeCamera,{distortionIntensity:(null===(t=s.intensity)||void 0===t?void 0:t.value)||0,distortionIntensityX:(null===(n=s.intensityX)||void 0===n?void 0:n.value)||0,distortionIntensityY:(null===(i=s.intensityY)||void 0===i?void 0:i.value)||0,distortionCenterX:(null===(r=s.centerX)||void 0===r?void 0:r.value)||.5,distortionCenterY:(null===(o=s.centerY)||void 0===o?void 0:o.value)||.5,distortionScale:(null===(a=s.scale)||void 0===a?void 0:a.value)||1}),this.lensDistortionPP.name="LensDistortionPostProcess"}},n.prototype.parseChromaticAberrationSettings=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)};return{intensity:n("intensity"),fastMode:n("fastMode")||n("fastmode")}},n.prototype.applyChromaticAberrationSettings=function(){if(this.chromaticAberrationSettings&&this.defaultRenderPipeline&&this.defaultRenderPipeline.chromaticAberration){console.log("[PostProcessor] Applying Chromatic Aberration Settings:",this.chromaticAberrationSettings);var e=this.chromaticAberrationSettings,t=this.defaultRenderPipeline.chromaticAberration;e.intensity&&!1!==e.intensity.overrideState&&null!=e.intensity.value&&(t.aberrationAmount=Number(e.intensity.value))}},n.prototype.parseAmbientOcclusionSettings=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)};return{intensity:n("intensity"),radius:n("radius"),sampleCount:n("sampleCount")||n("samplecount"),downsampling:n("downsampling"),thicknessModifier:n("thicknessModifier")||n("thicknessmodifier")}},n.prototype.parseScreenSpaceReflectionsSettings=function(t){if(!t)return null;var n=function(n){if(!t)return{value:null,overrideState:null};var i=null!=t[n]?t[n]:null!=t[n.toLowerCase()]?t[n.toLowerCase()]:null;return e.PostProcessor.extractParam(i)};return{preset:n("preset"),maximumIterationCount:n("maximumIterationCount")||n("maximumiterationcount"),thickness:n("thickness"),resolution:n("resolution"),bounce:n("bounce")}},n.unwrapParam=function(e){if(null==e)return e;try{if("object"==typeof e&&"value"in e)return e.value}catch(e){}return e},n.extractParam=function(e){if(null==e)return{value:null,overrideState:null};try{if("object"==typeof e&&"value"in e){var t=null!=e.overrideState?!!e.overrideState:null;return{value:e.value,overrideState:t}}}catch(e){}return{value:e,overrideState:null}},n.GlobalInstance=null,n}(e.ScriptComponent);e.PostProcessor=t,e.SceneManager.RegisterClass("TOOLKIT.PostProcessor",t)}(i||(i={})),function(e){var t=function(){function t(t,n,i){this._centerMass=new BABYLON.Vector3(0,0,0),this._chassisMesh=null,this._tempVectorPos=new BABYLON.Vector3(0,0,0),this.lockedWheelIndexes=null,this.m_scene=null,this.m_vehicle=null,this.m_vehicleTuning=null,this.m_vehicleRaycaster=null,this.m_vehicleColliders=null,this.m_tempPosition=null,this.m_wheelDirectionCS0=null,this.m_wheelAxleCS=null,this._chassisMesh=n,this._centerMass=i,this.m_scene=t,this.m_vehicleTuning=new e.btVehicleTuning,this.m_vehicleRaycaster=new e.btDefaultVehicleRaycaster({shouldHitTriggers:!1,ignoreBody:this._chassisMesh.physicsBody}),this.m_vehicleColliders=null!=this._chassisMesh.metadata&&null!=this._chassisMesh.metadata.toolkit&&null!=this._chassisMesh.metadata.toolkit.wheels?this._chassisMesh.metadata.toolkit.wheels:null,this.m_vehicle=new e.btRaycastVehicle(this.m_vehicleTuning,this._chassisMesh.physicsBody,this.m_vehicleRaycaster),this.m_vehicle.setCoordinateSystem(0,1,2),this.m_wheelDirectionCS0=new BABYLON.Vector3(0,-1,0),this.m_wheelAxleCS=new BABYLON.Vector3(-1,0,0),this.m_tempPosition=null,this.setupWheelInformation()}return t.prototype.getCenterMassOffset=function(){return this._centerMass},t.prototype.getInternalVehicle=function(){return this.m_vehicle},t.prototype.getUpAxis=function(){return null!=this.m_vehicle?this.m_vehicle.getUpAxis():null},t.prototype.getRightAxis=function(){return null!=this.m_vehicle?this.m_vehicle.getRightAxis():null},t.prototype.getForwardAxis=function(){return null!=this.m_vehicle?this.m_vehicle.getForwardAxis():null},t.prototype.getForwardVector=function(){return null!=this.m_vehicle?this.m_vehicle.getForwardVector():null},t.prototype.getNumWheels=function(){return null!=this.m_vehicle?this.m_vehicle.getNumWheels():null},t.prototype.getWheelInfo=function(e){return null!=this.m_vehicle?this.m_vehicle.getWheelInfo(e):null},t.prototype.resetSuspension=function(){null!=this.m_vehicle&&this.m_vehicle.resetSuspension()},t.prototype.setEngineForce=function(e,t){null!=this.m_vehicle&&this.m_vehicle.applyEngineForce(e,t)},t.prototype.setBrakingForce=function(e,t){null!=this.m_vehicle&&this.m_vehicle.setBrake(e,t)},t.prototype.updateWheelTransform=function(e,t){null!=this.m_vehicle&&this.m_vehicle.updateWheelTransform(e,t)},t.prototype.getWheelTransformPosition=function(e){return null!=this.m_vehicle?this.m_vehicle.getWheelInfo(e).worldTransformPosition:null},t.prototype.getWheelTransformRotation=function(e){return null!=this.m_vehicle?this.m_vehicle.getWheelInfo(e).worldTransformRotation:null},t.prototype.getRawCurrentSpeedKph=function(){return null!=this.m_vehicle?this.m_vehicle.getCurrentSpeedKmHour():null},t.prototype.getRawCurrentSpeedMph=function(){return null!=this.m_vehicle?this.m_vehicle.getCurrentSpeedKmHour()*e.System.Kph2Mph:null},t.prototype.getAbsCurrentSpeedKph=function(){return null!=this.m_vehicle?Math.abs(this.m_vehicle.getCurrentSpeedKmHour()):null},t.prototype.getAbsCurrentSpeedMph=function(){return null!=this.m_vehicle?Math.abs(this.m_vehicle.getCurrentSpeedKmHour())*e.System.Kph2Mph:null},t.prototype.getVehicleTuningSystem=function(){return this.m_vehicleTuning},t.prototype.getChassisWorldTransform=function(){return null!=this.m_vehicle?this.m_vehicle.getChassisWorldTransform():null},t.prototype.dispose=function(){this.deleteWheelInformation(),null!=this.m_vehicle&&(this.m_vehicle=null),null!=this.m_vehicleTuning&&(this.m_vehicleTuning=null),null!=this.m_vehicleRaycaster&&(this.m_vehicleRaycaster=null),null!=this.m_wheelDirectionCS0&&(this.m_wheelDirectionCS0=null),null!=this.m_wheelAxleCS&&(this.m_wheelAxleCS=null),null!=this.m_tempPosition&&(this.m_tempPosition=null),this.m_vehicleColliders=null},t.GetInstance=function(t,n){var i=n;return null==i.m_raycastVehicle&&(n.hasWheelColliders()?i.m_raycastVehicle=new e.RaycastVehicle(t,i.transform,i._centerOfMass):BABYLON.Tools.Warn("No wheel collider metadata found for: "+i.transform.name)),i.m_raycastVehicle},t.prototype.tickVehicleController=function(e){null!=this.m_vehicle&&this.m_vehicle.updateVehicle(e)},t.prototype.getEnableMultiRaycast=function(){var e=!1;return null!=this.m_vehicle&&(e=this.m_vehicle.enableMultiRaycast),e},t.prototype.setEnableMultiRaycast=function(e){null!=this.m_vehicle&&(this.m_vehicle.enableMultiRaycast=e)},t.prototype.getSmoothedGradientSpeed=function(){var e=-1;return null!=this.m_vehicle&&(e=this.m_vehicle.smoothedGradientSpeed),e},t.prototype.setSmoothedGradientSpeed=function(e){null!=this.m_vehicle&&(this.m_vehicle.smoothedGradientSpeed=e)},t.prototype.getMaximumYawRateLow=function(){var e=-1;return null!=this.m_vehicle&&(e=this.m_vehicle.maximumYawRateLow),e},t.prototype.setMaximumYawRateLow=function(e){null!=this.m_vehicle&&(this.m_vehicle.maximumYawRateLow=e)},t.prototype.getMaximumYawRateHigh=function(){var e=-1;return null!=this.m_vehicle&&(e=this.m_vehicle.maximumYawRateHigh),e},t.prototype.setMaximumYawRateHigh=function(e){null!=this.m_vehicle&&(this.m_vehicle.maximumYawRateHigh=e)},t.prototype.getAngularDampingControl=function(){var e=new BABYLON.Vector3;return null!=this.m_vehicle&&(e=this.m_vehicle.angularDamping),e},t.prototype.setAngularDampingControl=function(e){null!=this.m_vehicle&&(this.m_vehicle.angularDamping=e)},t.prototype.getSmoothFlyingImpulse=function(){var e=-1;return null!=this.m_vehicle&&this.m_vehicle.smoothFlyingImpulse&&(e=this.m_vehicle.smoothFlyingImpulse),e},t.prototype.setSmoothFlyingImpulse=function(e){null!=this.m_vehicle&&(this.m_vehicle.smoothFlyingImpulse=e)},t.prototype.setGroundedAutoLevelEnabled=function(e){null!=this.m_vehicle&&(this.m_vehicle.groundedAutoLevelEnabled=e)},t.prototype.setGroundedAutoLevelStrength=function(e){null!=this.m_vehicle&&(this.m_vehicle.groundedAutoLevelStrength=e)},t.prototype.setGroundedAutoLevelDeadzone=function(e){null!=this.m_vehicle&&(this.m_vehicle.groundedAutoLevelDeadzoneDeg=e)},t.prototype.setGroundedAutoLevelSettleDeg=function(e){null!=this.m_vehicle&&(this.m_vehicle.groundedAutoLevelSettleDeg=e)},t.prototype.setGroundedAutoLevelSettleScale=function(e){null!=this.m_vehicle&&(this.m_vehicle.groundedAutoLevelSettleScale=e)},t.prototype.setGroundedAutoLevelHysteresis=function(e){null!=this.m_vehicle&&(this.m_vehicle.groundedAutoLevelHysteresisDeg=e)},t.prototype.setGroundedAutoLevelSpeedRange=function(e,t){null!=this.m_vehicle&&(this.m_vehicle.groundedAutoLevelStartKmh=e,this.m_vehicle.groundedAutoLevelFullKmh=t)},t.prototype.setGroundedAutoLevelMaxRate=function(e){null!=this.m_vehicle&&(this.m_vehicle.groundedAutoLevelMaxRate=e)},t.prototype.getTrackConnectionAccel=function(){var e=-1;return null!=this.m_vehicle&&this.m_vehicle.trackConnectionAccel&&(e=this.m_vehicle.trackConnectionAccel),e},t.prototype.setTrackConnectionAccel=function(e){null!=this.m_vehicle&&(this.m_vehicle.trackConnectionAccel=e)},t.prototype.setAirborneTrackConnectionMaxAccel=function(e){null!=this.m_vehicle&&(this.m_vehicle.airborneTrackConnectionMaxAccel=e)},t.prototype.setAirborneTrackConnectionSpeedRange=function(e,t){null!=this.m_vehicle&&(this.m_vehicle.airborneTrackConnectionStartKmh=e,this.m_vehicle.airborneTrackConnectionFullKmh=t)},t.prototype.setAirborneRiseDamping=function(e){null!=this.m_vehicle&&(this.m_vehicle.airborneRiseDamping=e)},t.prototype.setAirborneMaxRiseSpeed=function(e){null!=this.m_vehicle&&(this.m_vehicle.airborneMaxRiseSpeed=e)},t.prototype.getMinimumWheelContacts=function(){var e=-1;return null!=this.m_vehicle&&this.m_vehicle.minimumWheelContacts&&(e=this.m_vehicle.minimumWheelContacts),e},t.prototype.setMinimumWheelContacts=function(e){null!=this.m_vehicle&&(this.m_vehicle.minimumWheelContacts=e)},t.prototype.getDownforceCoefficient=function(){return null!=this.m_vehicle?this.m_vehicle.downforceCoefficient:0},t.prototype.setDownforceCoefficient=function(e){null!=this.m_vehicle&&(this.m_vehicle.downforceCoefficient=e)},t.prototype.getConstantDownforce=function(){return null!=this.m_vehicle?this.m_vehicle.constantDownforce:0},t.prototype.setConstantDownforce=function(e){null!=this.m_vehicle&&(this.m_vehicle.constantDownforce=e)},t.prototype.getWheelIndexByID=function(e){var t=-1;if(null!=this.m_vehicleColliders&&this.m_vehicleColliders.length>0)for(var n=0;n<this.m_vehicleColliders.length;n++){var i=this.m_vehicleColliders[n];if(e.toLowerCase()===i.id.toLowerCase()){t=n;break}}return t},t.prototype.getWheelIndexByName=function(e){var t=-1;if(null!=this.m_vehicleColliders&&this.m_vehicleColliders.length>0)for(var n=0;n<this.m_vehicleColliders.length;n++){var i=this.m_vehicleColliders[n];if(e.toLowerCase()===i.name.toLowerCase()){t=n;break}}return t},t.prototype.getWheelColliderInfo=function(e){var t=-1;return null!=this.m_vehicleColliders&&this.m_vehicleColliders.length>0&&this.m_vehicleColliders.length>e&&(t=this.m_vehicleColliders[e]),t},t.prototype.setWheelTransformMesh=function(e,t){if(null!=t){var n=this.getWheelInfo(e);null!=n&&(n.transform=t)}},t.prototype.ensureNodeRotationQuaternion=function(e){return null==e.rotationQuaternion&&(e.rotationQuaternion=BABYLON.Quaternion.FromEulerAngles(e.rotation.x,e.rotation.y,e.rotation.z)),e.rotationQuaternion},t.prototype.normalizeWheelRotation=function(e){var t=2*Math.PI;return isFinite(e)?((e%=t)>Math.PI&&(e-=t),e<-Math.PI&&(e+=t),e):0},t.prototype.syncWheelSpinnerRotation=function(e){var t=e.spinner;if(null!=t){var n=this.ensureNodeRotationQuaternion(t);null!=e.spinnerBaseRotation&&e.spinnerBaseNode===t||(e.spinnerBaseRotation=n.clone(),e.spinnerBaseNode=t);var i=this.normalizeWheelRotation(e.rotation||0);!0===e.invertWheelDirection&&(i=-i),n.copyFrom(e.spinnerBaseRotation),t.rotate(BABYLON.Axis.X,i,BABYLON.Space.LOCAL)}},t.prototype.rebaseWheelSpinnerRotation=function(e){var t=e.spinner;if(null!=t){var n=this.ensureNodeRotationQuaternion(t),i=this.normalizeWheelRotation(e.rotation||0);!0===e.invertWheelDirection&&(i=-i);var r=n.clone();n.copyFrom(r),t.rotate(BABYLON.Axis.X,-i,BABYLON.Space.LOCAL),e.spinnerBaseRotation=n.clone(),e.spinnerBaseNode=t,n.copyFrom(r)}},t.prototype.getWheelSkidFadeInSpeed=function(){return this.m_vehicle,3},t.prototype.setWheelSkidFadeInSpeed=function(e){this.m_vehicle},t.prototype.getWheelSkidFadeOutSpeed=function(){return this.m_vehicle,3.5},t.prototype.setWheelSkidFadeOutSpeed=function(e){this.m_vehicle},t.prototype.isArcadeYawAssistActive=function(){var e=!1;return null!=this.m_vehicle&&(e=this.m_vehicle.isArcadeYawAssistActive),e},t.prototype.getArcadeSteeringAssist=function(){return null!=this.m_vehicle?this.m_vehicle.arcadeSteeringAssist:1},t.prototype.setArcadeSteeringAssist=function(e){null!=this.m_vehicle&&(this.m_vehicle.arcadeSteeringAssist=e)},t.prototype.getArcadeDonutDirectYawEnabled=function(){return null!=this.m_vehicle&&this.m_vehicle.arcadeDonutDirectYawEnabled},t.prototype.setArcadeDonutDirectYawEnabled=function(e){null!=this.m_vehicle&&(this.m_vehicle.arcadeDonutDirectYawEnabled=e)},t.prototype.getArcadeDonutDirectYawDegPerSec=function(){return null!=this.m_vehicle?this.m_vehicle.arcadeDonutDirectYawDegPerSec:1},t.prototype.setArcadeDonutDirectYawDegPerSec=function(e){null!=this.m_vehicle&&(this.m_vehicle.arcadeDonutDirectYawDegPerSec=e)},t.prototype.getArcadeHandbrakeYawCapMultiplier=function(){return null!=this.m_vehicle?this.m_vehicle.arcadeHandbrakeYawCapMultiplier:1},t.prototype.setArcadeHandbrakeYawCapMultiplier=function(e){null!=this.m_vehicle&&(this.m_vehicle.arcadeHandbrakeYawCapMultiplier=e)},t.prototype.getArcadeBurnoutYawCapMultiplier=function(){return null!=this.m_vehicle?this.m_vehicle.arcadeBurnoutYawCapMultiplier:1},t.prototype.setArcadeBurnoutYawCapMultiplier=function(e){null!=this.m_vehicle&&(this.m_vehicle.arcadeBurnoutYawCapMultiplier=e)},t.prototype.getArcadeDonutYawCapMultiplier=function(){return null!=this.m_vehicle?this.m_vehicle.arcadeDonutYawCapMultiplier:1},t.prototype.setArcadeDonutYawCapMultiplier=function(e){null!=this.m_vehicle&&(this.m_vehicle.arcadeDonutYawCapMultiplier=e)},t.prototype.getArcadeBurnoutActive=function(){var e=!1;return null!=this.m_vehicle&&(e=this.m_vehicle.getIsArcadeBurnoutActive()),e},t.prototype.setArcadeBurnoutActive=function(e){null!=this.m_vehicle&&this.m_vehicle.setIsArcadeBurnoutActive(e)},t.prototype.getArcadeDonutActive=function(){var e=!1;return null!=this.m_vehicle&&(e=this.m_vehicle.getIsArcadeDonutActive()),e},t.prototype.setArcadeDonutActive=function(e){null!=this.m_vehicle&&this.m_vehicle.setIsArcadeDonutActive(e)},t.prototype.getArcadeFootBrakeActive=function(){var e=!1;return null!=this.m_vehicle&&(e=this.m_vehicle.getIsArcadeFootBrakeActive()),e},t.prototype.setArcadeFootBrakeActive=function(e){null!=this.m_vehicle&&this.m_vehicle.setIsArcadeFootBrakeActive(e)},t.prototype.getArcadeHandBrakeActive=function(){var e=!1;return null!=this.m_vehicle&&(e=this.m_vehicle.getIsArcadeHandBrakeActive()),e},t.prototype.setArcadeHandBrakeActive=function(e){null!=this.m_vehicle&&this.m_vehicle.setIsArcadeHandBrakeActive(e)},t.prototype.setArcadeBurnoutDirectionChangeSpeed=function(t){null!=this.m_vehicle&&(this.m_vehicle.arcadeBurnoutDirectionChangeSpeedKmh=t*e.System.Mph2Kph)},t.prototype.getApproxWheelbaseMeters=function(){var e=2.5;return null!=this.m_vehicle&&(e=this.m_vehicle.getApproxWheelbaseMeters()),e},t.prototype.getSignedFrontSteeringAngleRad=function(){var e=0;return null!=this.m_vehicle&&(e=this.m_vehicle.getSignedFrontSteeringAngleRad()),e},t.prototype.getVisualSteeringAngle=function(e){var t=0,n=this.getWheelInfo(e);return null!=n&&null!=n.steeringAngle&&(t=n.steeringAngle),t},t.prototype.setVisualSteeringAngle=function(e,t){var n=this.getWheelInfo(t);null!=n&&(n.steeringAngle=e)},t.prototype.getPhysicsSteeringAngle=function(e){return null!=this.m_vehicle?Math.abs(this.m_vehicle.getSteeringValue(e)):0},t.prototype.setPhysicsSteeringAngle=function(e,t){null!=this.m_vehicle&&this.m_vehicle.setSteeringValue(e,t)},t.prototype.setupWheelInformation=function(){if(null!=this._chassisMesh&&this._chassisMesh.physicsBody,null!=this.m_vehicle&&null!=this.m_vehicleColliders&&this.m_vehicleColliders.length>0){var t=-1;for(t=0;t<this.m_vehicleColliders.length;t++){var n=null!=(m=this.m_vehicleColliders[t]).name?m.name:"Unknown",i=null!=m.radius?m.radius:.35,r=null!=m.position&&m.position.length>=3?m.position[0]:1,o=null!=m.position&&m.position.length>=3?m.position[2]:-1,a=null!=m.wheelconnectionpoint?m.wheelconnectionpoint:.5,s=null!=m.suspensionrestlength?m.suspensionrestlength:.3,l=null!=m.frontwheel||n.toLowerCase().indexOf("front")>=0,u=o,c=r,d=-this._centerMass.x,h=-this._centerMass.z;null==e.RaycastVehicle.TempVector&&(e.RaycastVehicle.TempVector=new BABYLON.Vector3(0,0,0)),e.RaycastVehicle.TempVector.set(c+d,a,u+h),this.m_vehicle.addWheel(e.RaycastVehicle.TempVector,this.m_wheelDirectionCS0,this.m_wheelAxleCS,s,i,this.m_vehicleTuning,l)}if(this.m_vehicle.getNumWheels()===this.m_vehicleColliders.length){var p=[];for(t=0;t<this.m_vehicleColliders.length;t++){var m,f=null!=(m=this.m_vehicleColliders[t]).totalsuspensionforces?m.totalsuspensionforces:0,g=null!=m.suspensiontravelcm?m.suspensiontravelcm:50,v=null!=m.rollinfluence?m.rollinfluence:.1,y=null!=m.frictionslip?m.frictionslip:10,_=null!=m.suspensionstiffness?m.suspensionstiffness:50,S=null!=m.dampingcompression?m.dampingcompression:2.5,A=null!=m.dampingrelaxation?m.dampingrelaxation:4.5,b=null!=m.invertWheelDirection&&m.invertWheelDirection,M=null!=m.maxVisualTravelRange?m.maxVisualTravelRange:0,B=this.m_vehicle.getWheelInfo(t);null!=B&&(B.steeringAngle=0,B.rotationBoost=0,B.defaultFriction=y,B.invertWheelDirection=b,B.maxVisualTravelRange=M,B.frictionSlip=y,B.rollInfluence=v,B.maxSuspensionTravelCm=g,B.suspensionStiffness=_,B.dampingCompression=S,B.dampingRelaxation=A,f>0?B.maxSuspensionForce=f:p.push(t))}this.applyAutoSuspensionForce(p)}else BABYLON.Tools.Warn("Failed to create proper number of wheels for: "+this._chassisMesh.name);this.m_vehicle.cacheMassProperties()}},t.prototype.applyAutoSuspensionForce=function(t){if(null!=this.m_vehicle&&null!=t&&0!==t.length){var n=null!=this._chassisMesh?this._chassisMesh.physicsBody:null;if(null!=n){var i=n.getMassProperties(),r=null!=i&&null!=i.mass?i.mass:0;if(r>0){var o=9.81;if(null!=this.m_scene&&null!=this.m_scene.gravity){var a=this.m_scene.gravity.length();a>1e-4&&(o=a)}var s=e.RaycastVehicle.AutoSuspensionForceReserve,l=this.m_vehicle.getNumWheels();if(!(l<=0)){for(var u=0,c=0,d=0,h=0,p=0;p<l;p++)if(null!=(M=this.m_vehicle.getWheelInfo(p))){var m=this.getWheelForwardPosition(M.chassisConnectionPointCS);M.isFrontWheel?(u+=m,d++):(c+=m,h++)}var f=0,g=0;if(d>0&&h>0){var v=u/d,y=c/h,_=Math.abs(v-y);if((v>=0&&y<=0||v<=0&&y>=0)&&_>1e-4){var S=Math.abs(v),A=r*o;f=A*(Math.abs(y)/_)/d,g=A*(S/_)/h}}if(!(f>0&&g>0)){var b=r*o/l;f=b,g=b}for(p=0;p<t.length;p++){var M,B=t[p];if(null!=(M=this.m_vehicle.getWheelInfo(B))){var C=M.isFrontWheel?f:g;M.maxSuspensionForce=C*s}}}}}}},t.prototype.getWheelForwardPosition=function(e){if(null==e||null==this.m_vehicle)return 0;switch(this.m_vehicle.getForwardAxis()){case 0:return e.x;case 1:return e.y;default:return e.z}},t.prototype.getNaturalWheelSlip=function(e){var t=!1;return null!=this.m_vehicle&&(t=this.m_vehicle.getNaturalWheelSlip(e)),t},t.prototype.getWheelAtRestSpeedThresholdKmh=function(){return null!=this.m_vehicle?this.m_vehicle.wheelAtRestSpeedThresholdKmh:1},t.prototype.setWheelAtRestSpeedThresholdKmh=function(e){null!=this.m_vehicle&&(this.m_vehicle.wheelAtRestSpeedThresholdKmh=e)},t.prototype.updateWheelInformation=function(){var t=this.getNumWheels();if(t>0)for(var n=0;n<t;n++){var i=this.getWheelInfo(n);if(null!=i){var r=this.lockedWheelInformation(n);if(this.updateWheelTransform(n,!1),this.m_tempPosition=this.getWheelTransformPosition(n),null!=i.transform){var o=i.transform;if(null!=o.parent){this._tempVectorPos.copyFrom(this.m_tempPosition),e.Utilities.InverseTransformPointToRef(o.parent,this._tempVectorPos,this._tempVectorPos),o.position.y=this._tempVectorPos.y,this.ensureNodeRotationQuaternion(o);var a=null!=i.steeringAngle?i.steeringAngle:0;BABYLON.Quaternion.FromEulerAnglesToRef(0,a,0,o.rotationQuaternion),null!=i.spinner&&(!0===r?i.spinnerLocked=!0:(!0===i.spinnerLocked&&(this.rebaseWheelSpinnerRotation(i),i.spinnerLocked=!1),this.syncWheelSpinnerRotation(i)))}}}}},t.prototype.lockedWheelInformation=function(e){var t=!1;if(null!=this.lockedWheelIndexes&&this.lockedWheelIndexes.length>0)for(var n=0;n<this.lockedWheelIndexes.length;n++)if(this.lockedWheelIndexes[n]===e){t=!0;break}return t},t.prototype.deleteWheelInformation=function(){var e=this.getNumWheels();if(e>0)for(var t=0;t<e;t++){var n=this.getWheelInfo(t);null!=n&&(null!=n.transform&&delete n.transform,null!=n.spinner&&delete n.spinner,null!=n.steeringAngle&&delete n.steeringAngle,null!=n.rotationBoost&&delete n.rotationBoost,null!=n.invertWheelDirection&&delete n.invertWheelDirection,null!=n.defaultFriction&&delete n.defaultFriction,null!=n.spinnerBaseRotation&&delete n.spinnerBaseRotation,null!=n.spinnerBaseNode&&delete n.spinnerBaseNode,null!=n.spinnerLocked&&delete n.spinnerLocked)}},t.TempVector=null,t.AutoSuspensionForceReserve=3.5,t}();e.RaycastVehicle=t}(i||(i={})),function(e){var t=function(t){function n(e,n,i,r){void 0===i&&(i={}),void 0===r&&(r="TOOLKIT.RigidbodyPhysics");var o=t.call(this,e,n,i,r)||this;return o._isKinematic=!1,o._centerOfMass=new BABYLON.Vector3(0,0,0),o.m_raycastVehicle=null,o}return r(n,t),n.prototype.awake=function(){this.awakeRigidbodyState()},n.prototype.update=function(){this.updateRigidbodyState()},n.prototype.fixed=function(){this.fixedRigidbodyState()},n.prototype.destroy=function(){this.destroyRigidbodyState()},n.prototype.awakeRigidbodyState=function(){this._isKinematic=this.getProperty("isKinematic",this._isKinematic),null!=this.transform.metadata&&null!=this.transform.metadata.toolkit&&null!=this.transform.metadata.toolkit.physics&&(this._centerOfMass=null!=this.transform.metadata.toolkit.physics.center?e.Utilities.ParseVector3(this.transform.metadata.toolkit.physics.center,this._centerOfMass):this._centerOfMass),this.hasWheelColliders()&&(this._isKinematic=!1,this.transform.physicsBody.disablePreStep=!1,this.m_raycastVehicle=new e.RaycastVehicle(this.scene,this.transform,this._centerOfMass),e.Utilities.ShowDebugColliders()&&console.log("Raycase Vehicle Created For: "+this.transform.name))},n.prototype.updateRigidbodyState=function(){null!=this.m_raycastVehicle&&this.m_raycastVehicle.updateWheelInformation()},n.prototype.fixedRigidbodyState=function(){null!=this.m_raycastVehicle&&this.m_raycastVehicle.tickVehicleController(e.RigidbodyPhysics.PHYSICS_STEP_TIME)},n.prototype.destroyRigidbodyState=function(){null!=this.m_raycastVehicle&&(this.m_raycastVehicle.dispose(),this.m_raycastVehicle=null)},n.prototype.isKinematic=function(){return this._isKinematic},n.prototype.hasWheelColliders=function(){return null!=this.transform.metadata&&null!=this.transform.metadata.toolkit&&null!=this.transform.metadata.toolkit.wheels},n.prototype.getRaycastVehicle=function(){return this.m_raycastVehicle},n.GetHavokInstance=function(){return globalThis.HK},n.Raycast=function(t,n,i,r){return null==e.RigidbodyPhysics.RaycastResult&&(e.RigidbodyPhysics.RaycastResult=new BABYLON.PhysicsRaycastResult),null==e.RigidbodyPhysics.RaycastDestination&&(e.RigidbodyPhysics.RaycastDestination=new BABYLON.Vector3(0,0,0)),e.RigidbodyPhysics.RaycastResult.reset(),e.RigidbodyPhysics.RaycastDestination.set(0,0,0),e.Utilities.CalculateDestinationPointToRef(t,n,i,e.RigidbodyPhysics.RaycastDestination),e.RigidbodyPhysics.RaycastToRef(t,e.RigidbodyPhysics.RaycastDestination,e.RigidbodyPhysics.RaycastResult,r),e.RigidbodyPhysics.RaycastResult},n.Shapecast=function(t){return null==e.RigidbodyPhysics.LocalShapeResult&&(e.RigidbodyPhysics.LocalShapeResult=new BABYLON.ShapeCastResult),null==e.RigidbodyPhysics.WorldShapeResult&&(e.RigidbodyPhysics.WorldShapeResult=new BABYLON.ShapeCastResult),e.RigidbodyPhysics.LocalShapeResult.reset(),e.RigidbodyPhysics.WorldShapeResult.reset(),e.RigidbodyPhysics.ShapecastToRef(t,e.RigidbodyPhysics.LocalShapeResult,e.RigidbodyPhysics.WorldShapeResult),{local:e.RigidbodyPhysics.LocalShapeResult,world:e.RigidbodyPhysics.WorldShapeResult}},n.RaycastToRef=function(t,n,i,r){var o=e.Utilities.GetHavokPlugin();if(o){null==e.RigidbodyPhysics.RaycastResult&&(e.RigidbodyPhysics.RaycastResult=new BABYLON.PhysicsRaycastResult),null==e.RigidbodyPhysics.RaycastDestination&&(e.RigidbodyPhysics.RaycastDestination=new BABYLON.Vector3(0,0,0)),e.RigidbodyPhysics.RaycastResult.reset(),e.RigidbodyPhysics.RaycastDestination.set(0,0,0);var a=null!=i?i:e.RigidbodyPhysics.RaycastResult;o.raycast(t,n,a,r)}else BABYLON.Tools.Warn("Havok.js physics library not loaded")},n.ShapecastToRef=function(t,n,i){var r=e.Utilities.GetHavokPlugin();if(r){null==e.RigidbodyPhysics.LocalShapeResult&&(e.RigidbodyPhysics.LocalShapeResult=new BABYLON.ShapeCastResult),null==e.RigidbodyPhysics.WorldShapeResult&&(e.RigidbodyPhysics.WorldShapeResult=new BABYLON.ShapeCastResult),e.RigidbodyPhysics.LocalShapeResult.reset(),e.RigidbodyPhysics.WorldShapeResult.reset();var o=null!=n?n:e.RigidbodyPhysics.LocalShapeResult,a=null!=i?i:e.RigidbodyPhysics.WorldShapeResult;r.shapeCast(t,o,a)}else BABYLON.Tools.Warn("Havok.js physics library not loaded")},n.SetMaxVelocities=function(t,n){var i=e.Utilities.GetHavokPlugin();if(i){var r=i._hknp.HEAP8.buffer,o=new Int32Array(r,Number(i.world),100),a=new Int32Array(r,o[8],500),s=new Int32Array(r,a[428],100),l=new Float32Array(r,s[8],300);l[32]=t,l[33]=n,l[60]=t,l[61]=n,l[88]=t,l[89]=n,l[144]=t,l[145]=n,l[172]=t,l[173]=n,l[200]=t,l[201]=n,l[228]=t}else BABYLON.Tools.Warn("Havok.js physics library not loaded")},n.ConfigurePhysicsEngine=function(t){return a(this,arguments,void 0,function(t,n,i,r,o,a,l){var u,c,d,h,p,m,f;return void 0===n&&(n=!0),void 0===i&&(i=0),void 0===r&&(r=0),void 0===o&&(o=!0),void 0===a&&(a=1e-4),void 0===l&&(l=null),s(this,function(r){switch(r.label){case 0:if(!BABYLON.HavokPlugin)return[3,7];r.label=1;case 1:return r.trys.push([1,5,6,7]),t.isPhysicsEnabled()?[3,4]:null!=(u=e.RigidbodyPhysics.GetHavokInstance())?[3,3]:(c=globalThis,[4,BABYLON.HavokPhysics()]);case 2:c.HK=r.sent(),u=globalThis.HK,r.label=3;case 3:return d=new BABYLON.Vector3(0,-9.81,0),h=null!=l?l:d,globalThis.HKP=new BABYLON.HavokPlugin(!n,u),t.enablePhysics(h,globalThis.HKP),[3,4];case 4:return[3,7];case 5:return p=r.sent(),console.warn(p),[3,7];case 6:e.RigidbodyPhysics.PhysicsShapeCache={},e.RigidbodyPhysics.NewPhysicsShapeCount=0,e.RigidbodyPhysics.CachedPhysicsShapeCount=0;try{null===(f=t.getPhysicsEngine())||void 0===f||f.setSubTimeStep(i),BABYLON.Tools.Log("Havok.js initialized with sub time step of "+i),m=e.RigidbodyPhysics.GetPhysicsHeapSize(),BABYLON.Tools.Log("Havok.js initialized with a heap size of "+m+" MB")}catch(e){console.warn(e)}try{null!=e.RigidbodyPhysics.OnSetupPhysicsPlugin&&e.RigidbodyPhysics.OnSetupPhysicsPlugin(t)}catch(e){console.warn(e)}return[7];case 7:return[2]}})})},n.SetupPhysicsComponent=function(t,n){var i=null!=n.metadata&&null!=n.metadata.toolkit?n.metadata.toolkit:null,r=null!=i.layermask?i.layermask:-1;if(null!=i&&(null!=i.physics||null!=i.collision)){var o=null!=i.physics,a=null!=i.physics&&null!=i.physics.filter?i.physics.filter:-1,s=null!=i.physics&&null!=i.physics.vehicle&&i.physics.vehicle,l=null!=i.physics&&null!=i.physics.root&&i.physics.root,u=null!=i.collision&&null!=i.collision.compoundcolliders,c=null!=i.physics&&null!=i.physics.mass?i.physics.mass:0,d=null!=i.physics&&null!=i.physics.center?i.physics.center:{x:0,y:0,z:0},h=null==i.physics||null==i.physics.kinematic||i.physics.kinematic,p=null==i.physics||null==i.physics.truestatic||i.physics.truestatic,m=BABYLON.PhysicsMotionType.DYNAMIC;if(m=!0===p?BABYLON.PhysicsMotionType.STATIC:!0===h?BABYLON.PhysicsMotionType.ANIMATED:BABYLON.PhysicsMotionType.DYNAMIC,!0===o){if(s){var f=null,g=n.getChildren(null,!1);null!=g&&g.length>0&&g.forEach(function(t){if(null!=t.metadata&&null!=t.metadata.toolkit&&null!=t.metadata.toolkit.collision){var i=t.metadata.toolkit.collision,r=null!=i.wheelinformation?i.wheelinformation:null;null!=r&&(e.Utilities.ShowDebugColliders()&&console.log("Setup raycast wheel collider: "+t.name+" --\x3e on to: "+n.name,n),null==f&&(f=[]),f.push(r))}}),null!=f&&f.length>0&&(null==n.metadata&&(n.metadata={}),null==n.metadata.toolkit&&(n.metadata.toolkit={}),n.metadata.toolkit.wheels=f)}if(u){var v=i.collision.compoundcolliders;if(null!=v&&v.length>0){var y=0,_=0,S=0,A=!1,b=[];if(v.forEach(function(i){if(null!=i){var o=null!=i.type?i.type:"BoxCollider",s=null!=i.restitutioncombine?e.RigidbodyPhysics.GetPhysicsMaterialCombine(i.restitutioncombine):0,l=null!=i.frictioncombine?e.RigidbodyPhysics.GetPhysicsMaterialCombine(i.frictioncombine):0,u=null!=i.dynamicfriction?i.dynamicfriction:.6,c=null!=i.staticfriction?i.staticfriction:.6,d=null!=i.restitution?i.restitution:0,h=null!=i.trigger&&i.trigger;u>y&&(y=u),c>_&&(_=c),d>S&&(S=d),1==h&&(A=!0);var p=e.RigidbodyPhysics.BoxImpostor;p="MeshCollider"===o?e.RigidbodyPhysics.ConvexHullImpostor:"CapsuleCollider"===o?e.RigidbodyPhysics.CapsuleImpostor:"SphereCollider"===o?e.RigidbodyPhysics.SphereImpostor:e.RigidbodyPhysics.BoxImpostor;var m=i,f=null!=m.center?m.center:{x:0,y:0,z:0},g=null!=m.persist&&m.persist,v=new e.PhyscisContainerData;e.Utilities.ShowDebugColliders()&&console.log("Setup simple compound child collider type ("+o+") --\x3e on to: "+n.name,n),e.RigidbodyPhysics.CreateCompoundPhysicsShapeAndBody(t,n,n,m,p,c,u,d,l,s,b,v,f,!1,h,g,r,a)}}),b.length>0){e.Utilities.ReparentColliders()||n.setParent(null,!0,!0);var M=new BABYLON.Vector3(d.x,d.y,d.z),B=new BABYLON.PhysicsShapeContainer(t);b.forEach(function(e){B.addChild(e.shape,e.translation,e.rotation,e.scale)}),B.material=b[0].shape.material;var C=new BABYLON.PhysicsBody(n,m,!1,t);C.shape=B,e.RigidbodyPhysics.ConfigRigidbodyPhysics(t,n,!1,A,i.physics,c,M),e.Utilities.ShowDebugColliders()||null!=(E=n).material&&"CenterBox-Material"===E.material.name&&(E.isVisible=!1),e.Utilities.ShowDebugColliders()&&(null==e.RigidbodyPhysics.DebugPhysicsViewer&&(e.RigidbodyPhysics.DebugPhysicsViewer=new BABYLON.Debug.PhysicsViewer),null!=e.RigidbodyPhysics.DebugPhysicsViewer&&e.RigidbodyPhysics.DebugPhysicsViewer.showBody(C))}}}else if(l){var T=0,x=0,I=0,O=!1,L=[],w=null!=i.physics&&null!=i.physics.center?e.Utilities.ParseVector3(i.physics.center,BABYLON.Vector3.Zero()):BABYLON.Vector3.Zero(),N=n.getChildren(null,!0);null!=N&&N.length>0&&N.forEach(function(e){e.position.subtractInPlace(w)});var P=n.getChildren(null,!1);if(null!=P&&P.length>0&&P.forEach(function(i){if(null!=i.metadata&&null!=i.metadata.toolkit&&null!=i.metadata.toolkit.collision){var o=i.metadata.toolkit.collision,s=null!=o.restitutioncombine?e.RigidbodyPhysics.GetPhysicsMaterialCombine(o.restitutioncombine):0,u=null!=o.frictioncombine?e.RigidbodyPhysics.GetPhysicsMaterialCombine(o.frictioncombine):0,c=null!=o.dynamicfriction?o.dynamicfriction:.6,d=null!=o.staticfriction?o.staticfriction:.6,h=null!=o.restitution?o.restitution:0,p=null!=o.trigger&&o.trigger,m=null!=o.type?o.type:"BoxCollider";c>T&&(T=c),d>x&&(x=d),h>I&&(I=h),1==p&&(O=!0);var f=e.RigidbodyPhysics.BoxImpostor;f="MeshCollider"===m?e.RigidbodyPhysics.ConvexHullImpostor:"CapsuleCollider"===m?e.RigidbodyPhysics.CapsuleImpostor:"SphereCollider"===m?e.RigidbodyPhysics.SphereImpostor:e.RigidbodyPhysics.BoxImpostor;var g=o,v=null!=g.center?g.center:{x:0,y:0,z:0},y=null!=g.persist&&g.persist,_=new e.PhyscisContainerData;e.Utilities.ShowDebugColliders()&&console.log("Setup complex compound child collider type ("+m+") --\x3e on to: "+n.name,n),e.RigidbodyPhysics.CreateCompoundPhysicsShapeAndBody(t,n,i,g,f,d,c,h,u,s,L,_,v,l,p,y,r,a)}}),L.length>0){e.Utilities.ReparentColliders()||n.setParent(null,!0,!0),M=new BABYLON.Vector3(d.x,d.y,d.z);var R=new BABYLON.PhysicsShapeContainer(t);R.material=L[0].shape.material,L.forEach(function(e){R.addChild(e.shape,e.translation,e.rotation,e.scale)});var E,k=new BABYLON.PhysicsBody(n,m,!1,t);k.shape=R,e.RigidbodyPhysics.ConfigRigidbodyPhysics(t,n,!1,O,i.physics,c,M),e.Utilities.ShowDebugColliders()||null!=(E=n).material&&"CenterBox-Material"===E.material.name&&(E.isVisible=!1),e.Utilities.ShowDebugColliders()&&(null==e.RigidbodyPhysics.DebugPhysicsViewer&&(e.RigidbodyPhysics.DebugPhysicsViewer=new BABYLON.Debug.PhysicsViewer),null!=e.RigidbodyPhysics.DebugPhysicsViewer&&e.RigidbodyPhysics.DebugPhysicsViewer.showBody(k))}}else if(null!=i.collision){var D=null!=i.collision.type?i.collision.type:"BoxCollider",F=null!=i.collision.convexmesh&&i.collision.convexmesh,U=null!=i.collision.restitutioncombine?e.RigidbodyPhysics.GetPhysicsMaterialCombine(i.collision.restitutioncombine):0,Y=null!=i.collision.frictioncombine?e.RigidbodyPhysics.GetPhysicsMaterialCombine(i.collision.frictioncombine):0,V=null!=i.collision.dynamicfriction?i.collision.dynamicfriction:.6,G=null!=i.collision.staticfriction?i.collision.staticfriction:.6,z=null!=i.collision.restitution?i.collision.restitution:0,W=null!=i.collision.terraindata?i.collision.terraindata:null,H=null!=i.collision.trigger&&i.collision.trigger,X=null!=i.collision.persist&&i.collision.persist,K=e.RigidbodyPhysics.BoxImpostor;K="MeshCollider"===D?!0===F?e.RigidbodyPhysics.ConvexHullImpostor:e.RigidbodyPhysics.MeshImpostor:"TerrainCollider"===D?e.RigidbodyPhysics.HeightmapImpostor:"CapsuleCollider"===D?e.RigidbodyPhysics.CapsuleImpostor:"SphereCollider"===D?e.RigidbodyPhysics.SphereImpostor:e.RigidbodyPhysics.BoxImpostor,e.RigidbodyPhysics.CreateStandardPhysicsShapeAndBody(t,n,i,K,H,p,m,c,G,V,z,Y,U,W,d,X,r,a)}}null!=n&&null!=n.physicsBody&&!0===h&&(n.physicsBody.disablePreStep=!1)}},n.GetPhysicsMaterialCombine=function(e){switch(e){case 0:default:return BABYLON.PhysicsMaterialCombineMode.ARITHMETIC_MEAN;case 1:return BABYLON.PhysicsMaterialCombineMode.MULTIPLY;case 2:return BABYLON.PhysicsMaterialCombineMode.MINIMUM;case 3:return BABYLON.PhysicsMaterialCombineMode.MAXIMUM}},n.GetCachedPhysicsMeshShape=function(t,n,i,r,o,a,s,l,u,c){if(null==i||""===i)return console.warn("Invalid mesh key specfifed for child collider: "+n.name),null;i+="_SF"+r+"_DF"+o+"_R"+a+"_T0_L"+u+"_X"+c;var d=e.RigidbodyPhysics.PhysicsShapeCache[i];return null==d?((d=new BABYLON.PhysicsShapeMesh(n,t)).material={friction:o,staticFriction:r,restitution:a,frictionCombine:s,restitutionCombine:l},d.isTrigger=!1,d.filterMembershipMask=u,e.RigidbodyPhysics.NewPhysicsShapeCount++,e.RigidbodyPhysics.PhysicsShapeCache[i]=d):e.RigidbodyPhysics.CachedPhysicsShapeCount++,d},n.GetCachedPhysicsConvexHullShape=function(t,n,i,r,o,a,s,l,u,c){if(null==i||""===i)return console.warn("Invalid mesh key specfifed for child collider: "+n.name),null;i+="_SF"+r+"_DF"+o+"_R"+a+"_T0_L"+u+"_X"+c;var d=e.RigidbodyPhysics.PhysicsShapeCache[i];return null==d?((d=new BABYLON.PhysicsShapeConvexHull(n,t)).material={friction:o,staticFriction:r,restitution:a,frictionCombine:s,restitutionCombine:l},d.isTrigger=!1,d.filterMembershipMask=u,e.RigidbodyPhysics.NewPhysicsShapeCount++,e.RigidbodyPhysics.PhysicsShapeCache[i]=d):e.RigidbodyPhysics.CachedPhysicsShapeCount++,d},n.GetCachedPhysicsBoxShape=function(t,n,i,r,o,a,s,l,u){var c="SHAPE_BOX_SF"+i+"_DF"+r+"_R"+o+"_T"+(1==n?"1":"0")+"_L"+l+"_X"+u,d=e.RigidbodyPhysics.PhysicsShapeCache[c];return null==d?((d=new BABYLON.PhysicsShapeBox(new BABYLON.Vector3(0,0,0),new BABYLON.Quaternion(0,0,0,1),new BABYLON.Vector3(1,1,1),t)).material={friction:r,staticFriction:i,restitution:o,frictionCombine:a,restitutionCombine:s},d.isTrigger=n,d.filterMembershipMask=l,e.RigidbodyPhysics.NewPhysicsShapeCount++,e.RigidbodyPhysics.PhysicsShapeCache[c]=d):e.RigidbodyPhysics.CachedPhysicsShapeCount++,d},n.GetCachedPhysicsSphereShape=function(t,n,i,r,o,a,s,l,u){var c="SHAPE_SPHERE_SF"+i+"_DF"+r+"_R"+o+"_T"+(1==n?"1":"0")+"_L"+l+"_X"+u,d=e.RigidbodyPhysics.PhysicsShapeCache[c];return null==d?((d=new BABYLON.PhysicsShapeSphere(new BABYLON.Vector3(0,0,0),1,t)).material={friction:r,staticFriction:i,restitution:o,frictionCombine:a,restitutionCombine:s},d.isTrigger=n,d.filterMembershipMask=l,e.RigidbodyPhysics.NewPhysicsShapeCount++,e.RigidbodyPhysics.PhysicsShapeCache[c]=d):e.RigidbodyPhysics.CachedPhysicsShapeCount++,d},n.GetCachedPhysicsCapsuleShape=function(t,n,i,r,o,a,s,l,u){var c="SHAPE_CAPSULE_SF"+i+"_DF"+r+"_R"+o+"_T"+(1==n?"1":"0")+"_L"+l+"_X"+u,d=e.RigidbodyPhysics.PhysicsShapeCache[c];return null==d?((d=new BABYLON.PhysicsShapeCapsule(new BABYLON.Vector3(0,-1,0),new BABYLON.Vector3(0,1,0),1,t)).material={friction:r,staticFriction:i,restitution:o,frictionCombine:a,restitutionCombine:s},d.isTrigger=n,d.filterMembershipMask=l,e.RigidbodyPhysics.NewPhysicsShapeCount++,e.RigidbodyPhysics.PhysicsShapeCache[c]=d):e.RigidbodyPhysics.CachedPhysicsShapeCount++,d},n.GetCachedPhysicsCylinderShape=function(t,n,i,r,o,a,s,l,u){var c="SHAPE_CYLINDER_SF"+i+"_DF"+r+"_R"+o+"_T"+(1==n?"1":"0")+"_L"+l+"_X"+u,d=e.RigidbodyPhysics.PhysicsShapeCache[c];return null==d?((d=new BABYLON.PhysicsShapeCylinder(new BABYLON.Vector3(0,-.5,0),new BABYLON.Vector3(0,.5,0),1,t)).material={friction:r,staticFriction:i,restitution:o,frictionCombine:a,restitutionCombine:s},d.isTrigger=n,d.filterMembershipMask=l,e.RigidbodyPhysics.NewPhysicsShapeCount++,e.RigidbodyPhysics.PhysicsShapeCache[c]=d):e.RigidbodyPhysics.CachedPhysicsShapeCount++,d},n.CreateStandardPhysicsShapeAndBody=function(t,n,i,r,o,a,s,l,u,c,d,h,p,m,f,g,v,y){var _=i.collision,S=null!=_.meshkey?_.meshkey:null,A=null!=_.center?_.center:{x:0,y:0,z:0};if(r==e.RigidbodyPhysics.HeightmapImpostor)if(null!=m){e.Utilities.ReparentColliders()||n.setParent(null,!0,!0);var b=n,M=m.index,B=m.segments,C=m.resolution,T=m.width,x=(m.height,m.length);if(1===(null!=m.collider?m.collider:0)){var I=1,O=1,L=0,w=0;if(1===B)L=.5*(T+(I=T/(C-1))),w=.5*(x-(O=x/(C-1)));else if(2===B){var N=T/B,P=x/B;I=T/(C-1),O=x/(C-1),0===M?(L=.5*(N+I)+0,w=.5*(P-O)+0):1===M?(L=.5*(1*N+I)+0,w=.5*(P-O)+P):2===M?(L=.5*(1*N+I)+N,w=.5*(P-O)+0):3===M&&(L=.5*(1*N+I)+N,w=.5*(P-O)+P)}var R=e.RigidbodyPhysics.CreateHeightFieldTerrainShapeFromMesh(b,I,O),E=new BABYLON.PhysicsShape({type:BABYLON.PhysicsShapeType.HEIGHTFIELD,pluginData:R},t);E.filterMembershipMask=v,E.material={friction:c,staticFriction:u,restitution:d,frictionCombine:h,restitutionCombine:p};var k="TERRAIN_MESH_ID"+b.uniqueId+"_SF"+u+"_DF"+c+"_R"+d+"_T0_L"+v+"_X"+y;e.RigidbodyPhysics.NewPhysicsShapeCount++,e.RigidbodyPhysics.PhysicsShapeCache[k]=E;var D=new BABYLON.Vector3(L,0,w),F=new BABYLON.Quaternion(0,0,0,1),U=new BABYLON.Vector3(1,1,1),Y=new BABYLON.PhysicsShapeContainer(t);Y.material=E.material,e.Utilities.FromEulerToRef(0,90,0,F),E.isTrigger=!1,Y.addChild(E,D,F,U);var V=new BABYLON.PhysicsBody(n,BABYLON.PhysicsMotionType.STATIC,!1,t);V.shape=Y,e.Utilities.ShowDebugColliders()&&console.log("Setup standard terrain heightmap physics collider for: "+n.name,n),e.RigidbodyPhysics.ConfigRigidbodyPhysics(t,n,!1,o,i.physics,0,new BABYLON.Vector3(f.x,f.y,f.z)),e.Utilities.ShowDebugColliders()||null!=(be=n).material&&"CenterBox-Material"===be.material.name&&(be.isVisible=!1),e.Utilities.ShowDebugColliders()&&(null==e.RigidbodyPhysics.DebugPhysicsViewer&&(e.RigidbodyPhysics.DebugPhysicsViewer=new BABYLON.Debug.PhysicsViewer),null!=e.RigidbodyPhysics.DebugPhysicsViewer&&e.RigidbodyPhysics.DebugPhysicsViewer.showBody(V))}else(W=new BABYLON.PhysicsShapeMesh(b,t)).filterMembershipMask=v,W.material={friction:c,staticFriction:u,restitution:d,frictionCombine:h,restitutionCombine:p},(z=new BABYLON.PhysicsBody(n,BABYLON.PhysicsMotionType.STATIC,!1,t)).shape=W,e.Utilities.ShowDebugColliders()&&console.log("Setup terrain mesh physics collider for: "+n.name,n),e.RigidbodyPhysics.ConfigRigidbodyPhysics(t,n,!1,o,i.physics,0,new BABYLON.Vector3(f.x,f.y,f.z)),e.Utilities.ShowDebugColliders()||null!=(be=n).material&&"CenterBox-Material"===be.material.name&&(be.isVisible=!1),e.Utilities.ShowDebugColliders()&&(null==e.RigidbodyPhysics.DebugPhysicsViewer&&(e.RigidbodyPhysics.DebugPhysicsViewer=new BABYLON.Debug.PhysicsViewer),null!=e.RigidbodyPhysics.DebugPhysicsViewer&&e.RigidbodyPhysics.DebugPhysicsViewer.showBody(z))}else BABYLON.Tools.Warn("No terrain collision data found for: "+n.name+". No terrain collision impostor will be created.");else if(r==e.RigidbodyPhysics.MeshImpostor){var G=e.SceneManager.FindChildTransformNode(n,n.name+".Collider",e.SearchType.ExactMatch,!0);if(null!=G){e.Utilities.ReparentColliders()||n.setParent(null,!0,!0);var z=new BABYLON.PhysicsBody(n,BABYLON.PhysicsMotionType.STATIC,!1,t),W=e.RigidbodyPhysics.GetCachedPhysicsMeshShape(t,G,S,u,c,d,h,p,v,y),H=new BABYLON.PhysicsShapeContainer(t);H.material=W.material,e.RigidbodyPhysics.AddChildShapeFromParent(H,n,W,G),z.shape=H,!1===g&&e.Utilities.AddLoaderItemMarkedForDisposal(G),e.Utilities.ShowDebugColliders()&&console.log("Setup standard mesh physics collider for: "+n.name,n),e.RigidbodyPhysics.ConfigRigidbodyPhysics(t,n,!1,o,i.physics,0,new BABYLON.Vector3(f.x,f.y,f.z)),e.Utilities.ShowDebugColliders()||null!=(be=n).material&&"CenterBox-Material"===be.material.name&&(be.isVisible=!1),e.Utilities.ShowDebugColliders()&&(null==e.RigidbodyPhysics.DebugPhysicsViewer&&(e.RigidbodyPhysics.DebugPhysicsViewer=new BABYLON.Debug.PhysicsViewer),null!=e.RigidbodyPhysics.DebugPhysicsViewer&&e.RigidbodyPhysics.DebugPhysicsViewer.showBody(z))}else BABYLON.Tools.Warn("No mesh collider found for: "+n.name+".")}else if(r==e.RigidbodyPhysics.ConvexHullImpostor){var X=e.SceneManager.FindChildTransformNode(n,n.name+".Collider",e.SearchType.ExactMatch,!0);if(null!=X){!1===g&&e.Utilities.AddLoaderItemMarkedForDisposal(X),e.Utilities.ReparentColliders()||n.setParent(null,!0,!0);var K=e.RigidbodyPhysics.GetCachedPhysicsConvexHullShape(t,X,S,u,c,d,h,p,v,y),Q=new BABYLON.PhysicsShapeContainer(t);Q.material=K.material,e.RigidbodyPhysics.AddChildShapeFromParent(Q,n,K,X);var j=new BABYLON.PhysicsBody(n,s,!1,t);j.shape=Q,e.Utilities.ShowDebugColliders()&&console.log("Setup standard convex hull physics collider for: "+n.name,n),e.RigidbodyPhysics.ConfigRigidbodyPhysics(t,n,!0,!1,i.physics,l,new BABYLON.Vector3(f.x,f.y,f.z)),e.Utilities.ShowDebugColliders()||null!=(be=n).material&&"CenterBox-Material"===be.material.name&&(be.isVisible=!1),e.Utilities.ShowDebugColliders()&&(null==e.RigidbodyPhysics.DebugPhysicsViewer&&(e.RigidbodyPhysics.DebugPhysicsViewer=new BABYLON.Debug.PhysicsViewer),null!=e.RigidbodyPhysics.DebugPhysicsViewer&&e.RigidbodyPhysics.DebugPhysicsViewer.showBody(j))}else BABYLON.Tools.Warn("No convex hull child mesh collider found for: "+n.name+".")}else if(r==e.RigidbodyPhysics.BoxImpostor){e.Utilities.ReparentColliders()||n.setParent(null,!0,!0);var Z=null!=_.boxsize?_.boxsize:{x:1,y:1,z:1},q=Z.x*parseFloat(n.scaling.x.toFixed(4)),J=Z.y*parseFloat(n.scaling.y.toFixed(4)),$=Z.z*parseFloat(n.scaling.z.toFixed(4)),ee=A.x*parseFloat(n.scaling.x.toFixed(4)),te=A.y*parseFloat(n.scaling.y.toFixed(4)),ne=A.z*parseFloat(n.scaling.z.toFixed(4)),ie=new BABYLON.Vector3(ee,te,ne),re=e.RigidbodyPhysics.GetCachedPhysicsBoxShape(t,o,u,c,d,h,p,v,y),oe=new BABYLON.PhysicsShapeContainer(t);oe.material=re.material,oe.addChild(re,ie,new BABYLON.Quaternion(0,0,0,1),new BABYLON.Vector3(q,J,$));var ae=new BABYLON.PhysicsBody(n,s,!1,t);ae.shape=oe,e.Utilities.ShowDebugColliders()&&console.log("Setup standard box physics collider for: "+n.name,n),e.RigidbodyPhysics.ConfigRigidbodyPhysics(t,n,!1,!1,i.physics,l,ie.add(new BABYLON.Vector3(f.x,f.y,f.z))),e.Utilities.ShowDebugColliders()||null!=(be=n).material&&"CenterBox-Material"===be.material.name&&(be.isVisible=!1),e.Utilities.ShowDebugColliders()&&(null==e.RigidbodyPhysics.DebugPhysicsViewer&&(e.RigidbodyPhysics.DebugPhysicsViewer=new BABYLON.Debug.PhysicsViewer),null!=e.RigidbodyPhysics.DebugPhysicsViewer&&e.RigidbodyPhysics.DebugPhysicsViewer.showBody(ae))}else if(r==e.RigidbodyPhysics.SphereImpostor){e.Utilities.ReparentColliders()||n.setParent(null,!0,!0);var se=null!=_.sphereradius?_.sphereradius:.5,le=parseFloat(n.scaling.x.toFixed(4)),ue=parseFloat(n.scaling.y.toFixed(4)),ce=parseFloat(n.scaling.z.toFixed(4)),de=Math.max(le,ue,ce)*se,he=(ee=A.x*parseFloat(n.scaling.x.toFixed(4)),te=A.y*parseFloat(n.scaling.y.toFixed(4)),ne=A.z*parseFloat(n.scaling.z.toFixed(4)),ie=new BABYLON.Vector3(ee,te,ne),e.RigidbodyPhysics.GetCachedPhysicsSphereShape(t,o,u,c,d,h,p,v,y)),pe=new BABYLON.PhysicsShapeContainer(t);pe.material=he.material,pe.addChild(he,ie,new BABYLON.Quaternion(0,0,0,1),new BABYLON.Vector3(de,de,de));var me=new BABYLON.PhysicsBody(n,s,!1,t);me.shape=pe,e.Utilities.ShowDebugColliders()&&console.log("Setup standard sphere physics collider for: "+n.name,n),e.RigidbodyPhysics.ConfigRigidbodyPhysics(t,n,!1,!1,i.physics,l,ie.add(new BABYLON.Vector3(f.x,f.y,f.z))),e.Utilities.ShowDebugColliders()||null!=(be=n).material&&"CenterBox-Material"===be.material.name&&(be.isVisible=!1),e.Utilities.ShowDebugColliders()&&(null==e.RigidbodyPhysics.DebugPhysicsViewer&&(e.RigidbodyPhysics.DebugPhysicsViewer=new BABYLON.Debug.PhysicsViewer),null!=e.RigidbodyPhysics.DebugPhysicsViewer&&e.RigidbodyPhysics.DebugPhysicsViewer.showBody(me))}else if(r==e.RigidbodyPhysics.CapsuleImpostor){e.Utilities.ReparentColliders()||n.setParent(null,!0,!0);var fe=null!=_.cylinder&&_.cylinder,ge=null!=_.capsulesize?_.capsulesize:{x:.5,y:2,z:1},ve=ge.x*parseFloat(n.scaling.x.toFixed(4)),ye=ge.y*parseFloat(n.scaling.y.toFixed(4)),_e=parseFloat(n.scaling.z.toFixed(4));_e=!0===fe?e.RigidbodyPhysics.GetCachedPhysicsCylinderShape(t,o,u,c,d,h,p,v,y):e.RigidbodyPhysics.GetCachedPhysicsCapsuleShape(t,o,u,c,d,h,p,v,y);var Se=new BABYLON.Quaternion(0,0,0,1);0!==ge.z&&2!==ge.z||(0===ge.z?e.Utilities.FromEulerToRef(0,0,90,Se):2===ge.z&&e.Utilities.FromEulerToRef(90,0,0,Se)),ee=A.x*parseFloat(n.scaling.x.toFixed(4)),te=A.y*parseFloat(n.scaling.y.toFixed(4)),ne=A.z*parseFloat(n.scaling.z.toFixed(4)),ie=new BABYLON.Vector3(ee,te,ne);var Ae=new BABYLON.PhysicsShapeContainer(t);Ae.material=_e.material,Ae.addChild(_e,ie,Se,new BABYLON.Vector3(ve,ye,ve));var be,Me=new BABYLON.PhysicsBody(n,s,!1,t);Me.shape=Ae,e.Utilities.ShowDebugColliders()&&console.log("Setup standard "+(!0===fe?"cylinder":"capsule")+" physics collider for: "+n.name,n),e.RigidbodyPhysics.ConfigRigidbodyPhysics(t,n,!1,!1,i.physics,l,ie.add(new BABYLON.Vector3(f.x,f.y,f.z))),e.Utilities.ShowDebugColliders()||null!=(be=n).material&&"CenterBox-Material"===be.material.name&&(be.isVisible=!1),e.Utilities.ShowDebugColliders()&&(null==e.RigidbodyPhysics.DebugPhysicsViewer&&(e.RigidbodyPhysics.DebugPhysicsViewer=new BABYLON.Debug.PhysicsViewer),null!=e.RigidbodyPhysics.DebugPhysicsViewer&&e.RigidbodyPhysics.DebugPhysicsViewer.showBody(Me))}},n.CreateCompoundPhysicsShapeAndBody=function(t,n,i,r,o,a,s,l,u,c,d,h,p,m,f,g,v,y){var _=0,S=0,A=0,b=new BABYLON.Vector3(0,0,0),M=new BABYLON.Quaternion(0,0,0,1),B=new BABYLON.Vector3(1,1,1);if(!1===g&&!0===m&&e.Utilities.AddLoaderItemMarkedForDisposal(i),o==e.RigidbodyPhysics.ConvexHullImpostor){var C=e.SceneManager.FindChildTransformNode(i,i.name+".Collider",e.SearchType.ExactMatch,!0);if(null!=C){var T=1,x=1,I=1;if(C instanceof BABYLON.InstancedMesh){!0===m&&(T*=parseFloat(n.scaling.x.toFixed(4)),x*=parseFloat(n.scaling.y.toFixed(4)),I*=parseFloat(n.scaling.z.toFixed(4))),B.set(T,x,I);var O=C.sourceMesh;if(null!=O){var L=null!=C.metadata&&null!=C.metadata.toolkit&&null!=C.metadata.toolkit.collision&&null!=C.metadata.toolkit.collision.sourcescale?C.metadata.toolkit.collision.sourcescale:null,w=null!=O.metadata&&null!=O.metadata.toolkit&&null!=O.metadata.toolkit.collision&&null!=O.metadata.toolkit.collision.sourcescale?O.metadata.toolkit.collision.sourcescale:null;if(null!=w&&null!=L){var N=new BABYLON.Vector3(1,1,1),P=new BABYLON.Vector3(L.x,L.y,L.z),R=new BABYLON.Vector3(w.x,w.y,w.z);P.divideToRef(R,N),B.multiplyInPlace(N)}}}else B.set(T,x,I);var E=null!=r.meshkey?r.meshkey:null,k=e.RigidbodyPhysics.GetCachedPhysicsConvexHullShape(t,C,E,a,s,l,u,c,v,y);if(!0===m){var D=i.position.x*parseFloat(n.scaling.x.toFixed(4)),F=i.position.y*parseFloat(n.scaling.y.toFixed(4)),U=i.position.z*parseFloat(n.scaling.z.toFixed(4));b.set(D,F,U),M.multiplyInPlace(i.rotationQuaternion)}else _=p.x*parseFloat(i.scaling.x.toFixed(4)),S=p.y*parseFloat(i.scaling.y.toFixed(4)),A=p.z*parseFloat(i.scaling.z.toFixed(4)),b.set(_,S,A);h.shape=k,h.translation=b,h.rotation=M,h.scale=B,d.push(h)}}else if(o==e.RigidbodyPhysics.CapsuleImpostor){var Y=null!=r.cylinder&&r.cylinder,V=null!=r.capsulesize?r.capsulesize:{x:.5,y:2,z:1},G=V.x*parseFloat(i.scaling.x.toFixed(4)),z=V.y*parseFloat(i.scaling.y.toFixed(4));parseFloat(i.scaling.z.toFixed(4)),!0===m&&(G*=parseFloat(n.scaling.x.toFixed(4)),z*=parseFloat(n.scaling.y.toFixed(4)),parseFloat(n.scaling.z.toFixed(4))),B.set(G,z,G);var W;W=!0===Y?e.RigidbodyPhysics.GetCachedPhysicsCylinderShape(t,f,a,s,l,u,c,v,y):e.RigidbodyPhysics.GetCachedPhysicsCapsuleShape(t,f,a,s,l,u,c,v,y),0!==V.z&&2!==V.z||(0===V.z?e.Utilities.FromEulerToRef(0,0,90,M):2===V.z&&e.Utilities.FromEulerToRef(90,0,0,M)),!0===m?(0===p.x&&0===p.y&&0===p.z||console.warn("WARNING: Center offset not supported for complex compound item: "+i.name),D=i.position.x*parseFloat(n.scaling.x.toFixed(4)),F=i.position.y*parseFloat(n.scaling.y.toFixed(4)),U=i.position.z*parseFloat(n.scaling.z.toFixed(4)),b.set(D,F,U),M.multiplyInPlace(i.rotationQuaternion)):(_=p.x*parseFloat(i.scaling.x.toFixed(4)),S=p.y*parseFloat(i.scaling.y.toFixed(4)),A=p.z*parseFloat(i.scaling.z.toFixed(4)),b.set(_,S,A)),h.shape=W,h.translation=b,h.rotation=M,h.scale=B,d.push(h)}else if(o==e.RigidbodyPhysics.SphereImpostor){var H=null!=r.sphereradius?r.sphereradius:.5,X=parseFloat(i.scaling.x.toFixed(4)),K=parseFloat(i.scaling.y.toFixed(4)),Q=parseFloat(i.scaling.z.toFixed(4)),j=Math.max(X,K,Q)*H;if(!0===m){var Z=parseFloat(n.scaling.x.toFixed(4)),q=parseFloat(n.scaling.y.toFixed(4)),J=parseFloat(n.scaling.z.toFixed(4));j*=Math.max(Z,q,J)}B.set(j,j,j);var $=e.RigidbodyPhysics.GetCachedPhysicsSphereShape(t,f,a,s,l,u,c,v,y);!0===m?(0===p.x&&0===p.y&&0===p.z||console.warn("WARNING: Center offset not supported for complex compound item: "+i.name),D=i.position.x*parseFloat(n.scaling.x.toFixed(4)),F=i.position.y*parseFloat(n.scaling.y.toFixed(4)),U=i.position.z*parseFloat(n.scaling.z.toFixed(4)),b.set(D,F,U),M.multiplyInPlace(i.rotationQuaternion)):(_=p.x*parseFloat(i.scaling.x.toFixed(4)),S=p.y*parseFloat(i.scaling.y.toFixed(4)),A=p.z*parseFloat(i.scaling.z.toFixed(4)),b.set(_,S,A)),h.shape=$,h.translation=b,h.rotation=M,h.scale=B,d.push(h)}else if(o==e.RigidbodyPhysics.BoxImpostor){var ee=null!=r.boxsize?r.boxsize:{x:1,y:1,z:1},te=ee.x*parseFloat(i.scaling.x.toFixed(4)),ne=ee.y*parseFloat(i.scaling.y.toFixed(4)),ie=ee.z*parseFloat(i.scaling.z.toFixed(4));!0===m&&(te*=parseFloat(n.scaling.x.toFixed(4)),ne*=parseFloat(n.scaling.y.toFixed(4)),ie*=parseFloat(n.scaling.z.toFixed(4))),B.set(te,ne,ie);var re=e.RigidbodyPhysics.GetCachedPhysicsBoxShape(t,f,a,s,l,u,c,v,y);!0===m?(0===p.x&&0===p.y&&0===p.z||console.warn("WARNING: Center offset not supported for complex compound item: "+i.name),D=i.position.x*parseFloat(n.scaling.x.toFixed(4)),F=i.position.y*parseFloat(n.scaling.y.toFixed(4)),U=i.position.z*parseFloat(n.scaling.z.toFixed(4)),b.set(D,F,U),M.multiplyInPlace(i.rotationQuaternion)):(_=p.x*parseFloat(i.scaling.x.toFixed(4)),S=p.y*parseFloat(i.scaling.y.toFixed(4)),A=p.z*parseFloat(i.scaling.z.toFixed(4)),b.set(_,S,A)),h.shape=re,h.translation=b,h.rotation=M,h.scale=B,d.push(h)}},n.CreateHeightFieldTerrainShapeFromMesh=function(t,n,i){var r=e.RigidbodyPhysics.GetHavokInstance();if(!r)return BABYLON.Tools.Warn("Havok.js physics library not loaded"),null;var o=t.getVerticesData(BABYLON.VertexBuffer.PositionKind),a=o.length/3,s=r._malloc(4*a),l=Math.sqrt(a),u=l;if(l%1!=0)return console.error("Terrain mesh does not seem to be a regular square grid: "+t.name),null;for(var c=0,d=u-1;d>=0;d--)for(var h=0;h<l;h++){var p=d*l+h;r.HEAPF32[s+c>>2]=o[3*p+1],c+=4}var m=r.HP_Shape_CreateHeightField(l,u,[n,1,i],s)[1];return r._free(s),m},n.GetPhysicsHeapSize=function(){var t=e.RigidbodyPhysics.GetHavokInstance();if(!t)return BABYLON.Tools.Warn("Havok.js physics library not loaded"),0;var n=0;return t.HEAP8&&t.HEAP8.length&&(n=t.HEAP8.length/1048576),n},n.ConfigRigidbodyPhysics=function(e,t,n,i,r,o,a){if(null!=t&&null!=t.physicsBody){!1===(null==r||null==r.gravity||r.gravity)&&t.physicsBody.setGravityFactor(0);var s=null!=r&&null!=r.ldrag?r.ldrag:0,l=null!=r&&null!=r.adrag?r.adrag:.05;t.physicsBody.setLinearDamping(s),t.physicsBody.setAngularDamping(l);var u=null!=r&&null!=r.freeze?r.freeze:null,c=1,d=1,h=1;null!=u&&(null!=u.positionx&&u.positionx,null!=u.positiony&&u.positiony,null!=u.positionz&&u.positionz,c=null!=u.rotationx&&!0===u.rotationx?0:1,d=null!=u.rotationy&&!0===u.rotationy?0:1,h=null!=u.rotationz&&!0===u.rotationz?0:1),t.physicsBody.setMassProperties({mass:o,centerOfMass:a,inertia:new BABYLON.Vector3(c,d,h)})}},n.CreatePhysicsMetadata=function(e,t,n,i){void 0===t&&(t=0),void 0===n&&(n=.05),void 0===i&&(i=null);var r=null!=i?i:new BABYLON.Vector3(0,0,0);return{type:"rigidbody",mass:e,ldrag:t,adrag:n,center:{x:r.x,y:r.y,z:r.z}}},n.CreateCollisionMetadata=function(e,t,n,i,r,o){return void 0===t&&(t=!1),void 0===n&&(n=!1),void 0===i&&(i=0),void 0===r&&(r=.6),void 0===o&&(o=.6),{type:e,trigger:t,convexmesh:n,restitution:i,dynamicfriction:r,staticfriction:o,wheelinformation:null}},n.CreatePhysicsProperties=function(e,t,n,i,r){return void 0===t&&(t=0),void 0===n&&(n=.05),void 0===i&&(i=!0),void 0===r&&(r=!1),{mass:e,drag:t,angularDrag:n,useGravity:i,isKinematic:r}},n.AddChildShapeFromParent=function(t,n,i,r){var o,a=r.computeWorldMatrix(!0),s=n.computeWorldMatrix(!0),l=BABYLON.TmpVectors.Matrix[0];a.multiplyToRef(BABYLON.Matrix.Invert(s),l);var u=BABYLON.TmpVectors.Vector3[0],c=BABYLON.TmpVectors.Quaternion[0],d=BABYLON.TmpVectors.Vector3[1];l.decompose(d,c,u);var h=new BABYLON.Vector3(d.x,d.y,d.z);if(r instanceof BABYLON.InstancedMesh){var p=r.sourceMesh;if(null!=p){var m=null!=r.metadata&&null!=r.metadata.toolkit&&null!=r.metadata.toolkit.collision&&null!=r.metadata.toolkit.collision.sourcescale?r.metadata.toolkit.collision.sourcescale:null,f=null!=p.metadata&&null!=p.metadata.toolkit&&null!=p.metadata.toolkit.collision&&null!=p.metadata.toolkit.collision.sourcescale?p.metadata.toolkit.collision.sourcescale:null;if(null!=f&&null!=m){var g=new BABYLON.Vector3(1,1,1),v=new BABYLON.Vector3(m.x,m.y,m.z),y=new BABYLON.Vector3(f.x,f.y,f.z);v.divideToRef(y,g),h.multiplyInPlace(g)}}}null===(o=e.Utilities.GetHavokPlugin())||void 0===o||o.addChild(t,i,u,c,h)},n.PHYSICS_STEP_TIME=.016,n.RaycastResult=null,n.LocalShapeResult=null,n.WorldShapeResult=null,n.RaycastDestination=null,n.PhysicsShapeCache={},n.NewPhysicsShapeCount=0,n.CachedPhysicsShapeCount=0,n.DebugPhysicsViewer=null,n.OnSetupPhysicsPlugin=null,n.NoImpostor=0,n.SphereImpostor=1,n.BoxImpostor=2,n.PlaneImpostor=3,n.MeshImpostor=4,n.CapsuleImpostor=6,n.CylinderImpostor=7,n.ParticleImpostor=8,n.HeightmapImpostor=9,n.ConvexHullImpostor=10,n.CustomImpostor=100,n.RopeImpostor=101,n.ClothImpostor=102,n.SoftbodyImpostor=103,n._factorAngVel=new BABYLON.Vector3,n._factorLinVel=new BABYLON.Vector3,n._factorLocalVel=new BABYLON.Vector3,n._dampingAngVel=new BABYLON.Vector3,n._dampingLinVel=new BABYLON.Vector3,n._dampingLocalVel=new BABYLON.Vector3,n._tempMatrix=new BABYLON.Matrix,n.SetDamping=function(e,t,n){e.setLinearDamping(Math.max(0,Math.min(1,t))),e.setAngularDamping(Math.max(0,Math.min(1,n)))},n.GetDamping=function(e){return{linearDamping:e.getLinearDamping(),angularDamping:e.getAngularDamping()}},n.ApplyDamping=function(t,n,i,r){var o=Math.pow(1-Math.max(0,Math.min(1,n)),r),a=Math.pow(1-Math.max(0,Math.min(1,i)),r);t.getLinearVelocityToRef(e.RigidbodyPhysics._dampingLinVel),e.RigidbodyPhysics._dampingLinVel.scaleInPlace(o),t.setLinearVelocity(e.RigidbodyPhysics._dampingLinVel),t.getAngularVelocityToRef(e.RigidbodyPhysics._dampingAngVel),e.RigidbodyPhysics._dampingAngVel.scaleInPlace(a),t.setAngularVelocity(e.RigidbodyPhysics._dampingAngVel)},n.ApplyPerAxisAngularDamping=function(t,n,i,r,o){t.getAngularVelocityToRef(e.RigidbodyPhysics._dampingAngVel);var a=t.transformNode.getWorldMatrix();a.invertToRef(e.RigidbodyPhysics._tempMatrix),BABYLON.Vector3.TransformNormalToRef(e.RigidbodyPhysics._dampingAngVel,e.RigidbodyPhysics._tempMatrix,e.RigidbodyPhysics._dampingLocalVel),e.RigidbodyPhysics._dampingLocalVel.x*=Math.pow(1-Math.max(0,Math.min(1,n)),o),e.RigidbodyPhysics._dampingLocalVel.y*=Math.pow(1-Math.max(0,Math.min(1,i)),o),e.RigidbodyPhysics._dampingLocalVel.z*=Math.pow(1-Math.max(0,Math.min(1,r)),o),BABYLON.Vector3.TransformNormalToRef(e.RigidbodyPhysics._dampingLocalVel,a,e.RigidbodyPhysics._dampingAngVel),t.setAngularVelocity(e.RigidbodyPhysics._dampingAngVel)},n.SetAngularFactor=function(t,n,i,r){var o=Math.max(0,Math.min(1,n)),a=Math.max(0,Math.min(1,i)),s=Math.max(0,Math.min(1,r));t.getAngularVelocityToRef(e.RigidbodyPhysics._factorAngVel);var l=t.transformNode.getWorldMatrix();l.invertToRef(e.RigidbodyPhysics._tempMatrix),BABYLON.Vector3.TransformNormalToRef(e.RigidbodyPhysics._factorAngVel,e.RigidbodyPhysics._tempMatrix,e.RigidbodyPhysics._factorLocalVel),e.RigidbodyPhysics._factorLocalVel.x*=o,e.RigidbodyPhysics._factorLocalVel.y*=a,e.RigidbodyPhysics._factorLocalVel.z*=s,BABYLON.Vector3.TransformNormalToRef(e.RigidbodyPhysics._factorLocalVel,l,e.RigidbodyPhysics._factorAngVel),t.setAngularVelocity(e.RigidbodyPhysics._factorAngVel)},n.SetLinearFactor=function(t,n,i,r){var o=Math.max(0,Math.min(1,n)),a=Math.max(0,Math.min(1,i)),s=Math.max(0,Math.min(1,r));t.getLinearVelocityToRef(e.RigidbodyPhysics._factorLinVel),e.RigidbodyPhysics._factorLinVel.x*=o,e.RigidbodyPhysics._factorLinVel.y*=a,e.RigidbodyPhysics._factorLinVel.z*=s,t.setLinearVelocity(e.RigidbodyPhysics._factorLinVel)},n.SetFactors=function(t,n,i){e.RigidbodyPhysics.SetLinearFactor(t,n.x,n.y,n.z),e.RigidbodyPhysics.SetAngularFactor(t,i.x,i.y,i.z)},n}(e.ScriptComponent);e.RigidbodyPhysics=t;e.PhyscisContainerData=function(){},e.SceneManager.RegisterClass("TOOLKIT.RigidbodyPhysics",t)}(i||(i={})),function(e){var t=function(){function e(){}return e.CreatePostProcess=function(e,t,n){var i=n||{},r=Array.isArray(i.color)?i.color:i.color?[i.color.r||0,i.color.g||0,i.color.b||0,i.color.a||1]:[0,0,0,1],o=i.center&&Array.isArray(i.center)?i.center:[.5,.5],a=null!=i.intensity?i.intensity:1,s=null!=i.smoothness?i.smoothness:.5,l=!!i.rounded,u=new BABYLON.PostProcess("roundedVignette","\n precision highp float;\n varying vec2 vUV;\n uniform sampler2D textureSampler;\n uniform vec4 vignetteColor;\n uniform vec2 center;\n uniform float intensity;\n uniform float smoothness;\n uniform float rounded; // 0 or 1\n uniform int blendMode; // 0 = multiply, 1 = overlay\n\n vec3 overlayBlend(vec3 base, vec3 blend) {\n vec3 res;\n for (int i = 0; i < 3; i++) {\n float b = base[i];\n float f = blend[i];\n float outv = (b < 0.5) ? (2.0 * b * f) : (1.0 - 2.0 * (1.0 - b) * (1.0 - f));\n res[i] = outv;\n }\n return res;\n }\n\n void main(void) {\n vec4 scene = texture2D(textureSampler, vUV);\n vec2 p = vUV - center;\n float d;\n if (rounded > 0.5) {\n d = length(p);\n } else {\n // ellipse based on aspect ratio (approx using normalized coords)\n d = sqrt((p.x*p.x) + (p.y*p.y));\n }\n float vig = 1.0 - smoothstep(0.0, 1.0, (d - (1.0 - intensity)) / smoothness);\n float weight = (1.0 - vig);\n vec3 vcol = vignetteColor.rgb;\n vec3 outc;\n if (blendMode == 1) {\n outc = mix(scene.rgb, overlayBlend(scene.rgb, vcol), weight);\n } else {\n // multiply\n outc = mix(scene.rgb, scene.rgb * vcol, weight);\n }\n gl_FragColor = vec4(outc, scene.a);\n }\n ",["vignetteColor","center","intensity","smoothness","rounded","blendMode"],[],1,t,BABYLON.Texture.BILINEAR_SAMPLINGMODE,e.getEngine(),!1);return u.onApply=function(e){e.setFloat4("vignetteColor",r[0]||0,r[1]||0,r[2]||0,null!=r[3]?r[3]:1),e.setVector2("center",new BABYLON.Vector2(o[0]||.5,o[1]||.5)),e.setFloat("intensity",a),e.setFloat("smoothness",s),e.setFloat("rounded",l?1:0),e.setInt("blendMode","overlay"===i.blendMode||1===i.blendMode?1:0)},u._blendMode="overlay"===i.blendMode||1===i.blendMode?"overlay":"multiply",u},e}();e.RoundedVignettePlugin=t}(i||(i={})),function(e){var t=function(t){function n(e,n,i,r){void 0===i&&(i={}),void 0===r&&(r="TOOLKIT.ShurikenParticles");var o=t.call(this,e,n,i,r)||this;return o.m_particleSystem=null,o.m_emitterMesh=null,o.m_systemProperties=null,o.m_isInitialized=!1,o.m_playOnAwake=!0,o.m_autoStart=!0,o.m_systemTime=0,o.m_isLooping=!0,o.m_duration=5,o.m_emissionTimer=0,o.m_burstTimers=[],o.m_prewarm=!1,o.m_startDelay=null,o.m_simulationSpeed=1,o.m_scalingMode=0,o.m_emitterVelocityMode=0,o.m_customSimulationSpace=0,o.m_emitterVelocity=new BABYLON.Vector3(0,0,0),o.m_gravitySource=0,o.m_useUnscaledTime=!1,o.m_reportedDeltaTime=0,o.m_isSystemRunning=!1,o.m_cullingMode=0,o.m_isVisible=!0,o.m_pausedTime=0,o.m_lastVisibilityCheck=0,o.m_animationCurves=new Map,o.m_gradients=new Map,o}return r(n,t),n.prototype.getParticleSystem=function(){return this.m_particleSystem},n.prototype.getEmitterMesh=function(){return this.m_emitterMesh},n.prototype.internalPlay=function(){var e=this;if(this.m_particleSystem){if(this.m_prewarm&&this.m_isLooping&&this.m_duration>0)if(this.m_systemTime=this.m_duration,this.m_emissionTimer=this.m_duration,this.m_particleSystem instanceof BABYLON.ParticleSystem){var t=this.m_particleSystem.emitRate,n=Math.min(Math.ceil(t*this.m_duration),this.m_particleSystem.getCapacity());this.m_particleSystem.emitRate=60*n,this.m_particleSystem.start(),setTimeout(function(){e.m_particleSystem instanceof BABYLON.ParticleSystem&&(e.m_particleSystem.emitRate=t)},16)}else this.m_particleSystem.start();else this.m_systemTime=0,this.m_emissionTimer=0,this.m_particleSystem.start();this.m_isSystemRunning=!0,this.resetBurstTimers()}},n.prototype.play=function(){var t=this,n=this.calculateStartDelay();n>0?(this.m_systemTime=0,this.m_emissionTimer=0,this.m_isSystemRunning=!1,e.WindowManager.SetTimeout(1e3*n,function(){t.internalPlay()})):(this.m_systemTime=0,this.m_emissionTimer=0,this.internalPlay())},n.prototype.stop=function(){this.m_particleSystem&&(this.m_particleSystem.stop(),this.m_isSystemRunning=!1)},n.prototype.pause=function(){var e,t;this.m_particleSystem&&(this.m_particleSystem instanceof BABYLON.ParticleSystem?this.m_particleSystem.stop():null===(t=(e=this.m_particleSystem).pause)||void 0===t||t.call(e),this.m_isSystemRunning=!1)},n.prototype.reset=function(){this.m_particleSystem&&(this.m_particleSystem.reset(),this.m_systemTime=0,this.m_emissionTimer=0,this.resetBurstTimers(),this.m_isSystemRunning=!1)},n.prototype.isPlaying=function(){return this.m_isSystemRunning&&this.m_isInitialized},n.prototype.getParticleCount=function(){return this.m_particleSystem?this.m_particleSystem.getActiveCount():0},n.prototype.getCustomSimulationSpace=function(){return this.m_customSimulationSpace},n.prototype.getEmitterVelocity=function(){return this.m_emitterVelocity.clone()},n.prototype.getGravitySource=function(){return this.m_gravitySource},n.prototype.getUseUnscaledTime=function(){return this.m_useUnscaledTime},n.prototype.getCustomDeltaTime=function(){return this.m_reportedDeltaTime},n.prototype.getReportedDeltaTime=function(){return this.m_reportedDeltaTime},n.prototype.getEffectiveDeltaTime=function(){return(this.m_useUnscaledTime?this.scene.getEngine().getDeltaTime()/1e3:this.getDeltaTime())*this.m_simulationSpeed},n.prototype.calculateStartDelay=function(){var e,t,n=0;if(null!=this.m_startDelay){var i=this.convertMinMaxCurve(this.m_startDelay);switch(null!==(e=this.m_startDelay.mode)&&void 0!==e?e:0){case 0:case 1:default:n=i.value;break;case 2:case 3:n=Math.random()*(i.max-i.min)+i.min}void 0!==(null===(t=this.m_systemProperties.main)||void 0===t?void 0:t.startDelayMultiplier)&&(n*=this.m_systemProperties.main.startDelayMultiplier)}return parseFloat(Math.max(0,n).toFixed(2))},n.prototype.awake=function(){this.initializeParticleSystem()},n.prototype.start=function(){this.m_isInitialized&&this.m_autoStart&&this.m_playOnAwake&&this.play()},n.prototype.ready=function(){},n.prototype.update=function(){if(this.m_particleSystem&&this.m_systemProperties&&this.m_isSystemRunning){if(!this.shouldSimulateThisFrame()){if(1===this.m_cullingMode){var e=this.m_useUnscaledTime?this.scene.getEngine().getDeltaTime()/1e3:this.getDeltaTime();this.m_pausedTime+=e}return}var t=(this.m_useUnscaledTime?this.scene.getEngine().getDeltaTime()/1e3:this.getDeltaTime())*this.m_simulationSpeed;this.updateSystem(t),this.updateEmission(t),this.updateAnimationProperties(),this.updateBursts(t),this.updateEmitterVelocityInheritance(t),this.updateCustomSimulationSpace(t),this.updateRingBufferMode(t),!this.m_isLooping&&this.m_duration>0&&this.m_systemTime>=this.m_duration&&this.handleStopAction()}},n.prototype.shouldSimulateThisFrame=function(){switch(this.m_cullingMode){case 0:case 1:case 2:default:return this.m_isVisible;case 3:return!0}},n.prototype.late=function(){},n.prototype.step=function(){},n.prototype.fixed=function(){},n.prototype.after=function(){},n.prototype.destroy=function(){this.disposeParticleSystem()},n.mergeWithDefaults=function(e){return e?n.deepMerge(JSON.parse(JSON.stringify(n.DEFAULT_PARTICLE_PROPERTIES)),e):JSON.parse(JSON.stringify(n.DEFAULT_PARTICLE_PROPERTIES))},n.deepMerge=function(e,t){if(!t||"object"!=typeof t)return e;if(!e||"object"!=typeof e)return t;for(var i in t)t.hasOwnProperty(i)&&(t[i]&&"object"==typeof t[i]&&!Array.isArray(t[i])?e[i]=n.deepMerge(e[i]||{},t[i]):e[i]=t[i]);return e},n.getPropertyWithDefault=function(e,t){for(var i=e.split("."),r=t,o=n.DEFAULT_PARTICLE_PROPERTIES,a=0,s=i;a<s.length;a++){var l=s[a];r=null==r?void 0:r[l],o=null==o?void 0:o[l]}return void 0!==r?r:o},n.getMinimalSerializationData=function(e){if(!e)return{};var t=n.DEFAULT_PARTICLE_PROPERTIES;return n.extractDifferences(e,t)},n.extractDifferences=function(e,t){if(!e||"object"!=typeof e)return e;if(!t||"object"!=typeof t)return e;var i={};for(var r in e)if(e.hasOwnProperty(r)){var o=e[r],a=t[r];if(void 0!==o)if(Array.isArray(o))Array.isArray(a)&&o.length===a.length&&n.arraysEqual(o,a)||(i[r]=o);else if(o&&"object"==typeof o){var s=n.extractDifferences(o,a);Object.keys(s).length>0&&(i[r]=s)}else o!==a&&(i[r]=o)}return i},n.arraysEqual=function(e,t){if(e.length!==t.length)return!1;for(var i=0;i<e.length;i++){var r=e[i],o=t[i];if(Array.isArray(r)&&Array.isArray(o)){if(!n.arraysEqual(r,o))return!1}else if(r&&"object"==typeof r&&o&&"object"==typeof o){var a=n.extractDifferences(r,o);if(Object.keys(a).length>0)return!1}else if(r!==o)return!1}return!0},n.getDefaultProperties=function(){return JSON.parse(JSON.stringify(n.DEFAULT_PARTICLE_PROPERTIES))},n.prototype.initializeParticleSystem=function(){try{var e=this._properties;if(this.m_systemProperties=n.mergeWithDefaults(e),!this.m_systemProperties)return void BABYLON.Tools.Warn("ShurikenParticles: Failed to create merged particle system properties");if(!this.m_systemProperties.main)return void BABYLON.Tools.Warn("### ShurikenParticles: No main module found in merged properties");this.createEmitterMesh(),this.shouldUseGPUParticles()?this.createGPUParticleSystem():this.createCPUParticleSystem(),this.configureMainModule(),this.configureEmissionModule(),this.configureShapeModule(),this.configureRendererModule(),this.configureVelocityOverLifetimeModule(),this.configureLimitVelocityOverLifetimeModule(),this.configureColorOverLifetimeModule(),this.configureSizeOverLifetimeModule(),this.configureRotationOverLifetimeModule(),this.configureTextureSheetAnimationModule(),this.configureNoiseModule(),this.configureCollisionModule(),this.configureTrailsModule(),this.configureSubEmittersModule(),this.ensureBasicConfiguration(),this.m_isInitialized=!0}catch(e){BABYLON.Tools.Error("ShurikenParticles: Failed to initialize particle system: "+e)}},n.prototype.shouldUseGPUParticles=function(){var e,t,n,i,r,o,a=null!==(t=null===(e=this.m_systemProperties.main)||void 0===e?void 0:e.maxParticles)&&void 0!==t?t:1e3,s=(null===(n=this.m_systemProperties.noise)||void 0===n?void 0:n.enabled)||(null===(i=this.m_systemProperties.collision)||void 0===i?void 0:i.enabled)||(null===(r=this.m_systemProperties.trails)||void 0===r?void 0:r.enabled)||(null===(o=this.m_systemProperties.subEmitters)||void 0===o?void 0:o.enabled);return a>5e3&&!s},n.prototype.createEmitterMesh=function(){this.m_emitterMesh=BABYLON.MeshBuilder.CreateBox(this.transform.name+"_ParticleProxy",{size:.1},this.scene);var e=null!=n.EMITTER_POSITION_OFFSET?n.EMITTER_POSITION_OFFSET:new BABYLON.Vector3(0,0,0),t=null!=n.EMITTER_ROTATION_OFFSET?n.EMITTER_ROTATION_OFFSET:new BABYLON.Vector3(0,0,0);this.m_emitterMesh.parent=this.transform,this.m_emitterMesh.position.copyFrom(e),this.m_systemProperties.shape,t.set(90,0,0),this.m_emitterMesh.rotationQuaternion=BABYLON.Quaternion.FromEulerAngles(BABYLON.Tools.ToRadians(t.x),BABYLON.Tools.ToRadians(t.y),BABYLON.Tools.ToRadians(t.z)),this.m_emitterMesh.isVisible=!1,this.m_emitterMesh.isPickable=!1},n.prototype.createDefaultParticleTexture=function(){if(null!=e.ShurikenParticles.DefaultParticleTexture)return e.ShurikenParticles.DefaultParticleTexture;var t=64,n=document.createElement("canvas");n.width=t,n.height=t;var i=n.getContext("2d");i.clearRect(0,0,t,t);var r=i.createRadialGradient(32,32,0,32,32,32);r.addColorStop(0,"rgba(255, 255, 255, 1.0)"),r.addColorStop(.15,"rgba(255, 255, 255, 0.95)"),r.addColorStop(.3,"rgba(255, 255, 255, 0.7)"),r.addColorStop(.6,"rgba(255, 255, 255, 0.2)"),r.addColorStop(.85,"rgba(255, 255, 255, 0.05)"),r.addColorStop(1,"rgba(255, 255, 255, 0.0)"),i.fillStyle=r,i.fillRect(0,0,t,t);var o=n.toDataURL("image/png"),a=new BABYLON.Texture(o,this.scene);return a.name=this.transform.name+"_DefaultParticleTexture",a.hasAlpha=!0,a.wrapU=BABYLON.Texture.CLAMP_ADDRESSMODE,a.wrapV=BABYLON.Texture.CLAMP_ADDRESSMODE,e.ShurikenParticles.DefaultParticleTexture=a,e.ShurikenParticles.DefaultParticleTexture},n.prototype.createCPUParticleSystem=function(){var e,t,n=null!==(t=null===(e=this.m_systemProperties.main)||void 0===e?void 0:e.maxParticles)&&void 0!==t?t:1e3;this.m_particleSystem=new BABYLON.ParticleSystem(this.transform.name+"_ParticleSystem",n,this.scene),this.m_particleSystem.emitter=this.m_emitterMesh,this.m_particleSystem.particleTexture||(this.m_particleSystem.particleTexture=this.createDefaultParticleTexture()),this.m_particleSystem.blendMode=BABYLON.ParticleSystem.BLENDMODE_STANDARD,this.m_particleSystem.particleTexture&&(this.m_particleSystem.particleTexture.wrapU=BABYLON.Texture.CLAMP_ADDRESSMODE,this.m_particleSystem.particleTexture.wrapV=BABYLON.Texture.CLAMP_ADDRESSMODE),this.m_particleSystem.color1=new BABYLON.Color4(1,1,1,1),this.m_particleSystem.color2=new BABYLON.Color4(1,1,1,1),this.m_particleSystem.colorDead=new BABYLON.Color4(1,1,1,0),this.m_particleSystem.minSize=1,this.m_particleSystem.maxSize=1,this.m_particleSystem.minInitialRotation=0,this.m_particleSystem.maxInitialRotation=0,this.m_particleSystem.minAngularSpeed=0,this.m_particleSystem.maxAngularSpeed=0},n.prototype.createGPUParticleSystem=function(){var e,t,n=null!==(t=null===(e=this.m_systemProperties.main)||void 0===e?void 0:e.maxParticles)&&void 0!==t?t:1e3;this.m_particleSystem=new BABYLON.GPUParticleSystem(this.transform.name+"_GPUParticleSystem",{capacity:n},this.scene),this.m_particleSystem.emitter=this.m_emitterMesh,this.m_particleSystem.particleTexture||(this.m_particleSystem.particleTexture=this.createDefaultParticleTexture()),this.m_particleSystem.blendMode=BABYLON.GPUParticleSystem.BLENDMODE_STANDARD,this.m_particleSystem.particleTexture&&(this.m_particleSystem.particleTexture.wrapU=BABYLON.Texture.CLAMP_ADDRESSMODE,this.m_particleSystem.particleTexture.wrapV=BABYLON.Texture.CLAMP_ADDRESSMODE),this.m_particleSystem.color1=new BABYLON.Color4(1,1,1,1),this.m_particleSystem.color2=new BABYLON.Color4(1,1,1,1),this.m_particleSystem.colorDead=new BABYLON.Color4(1,1,1,0),this.m_particleSystem.minSize=.25,this.m_particleSystem.maxSize=.25,this.m_particleSystem.minInitialRotation=0,this.m_particleSystem.maxInitialRotation=0,this.m_particleSystem.minAngularSpeed=0,this.m_particleSystem.maxAngularSpeed=0},n.prototype.configureMainModule=function(){var e,t,i,r,o,a,s,l,u,c,d,h,p,m,f,g,v,y,_,S,A,b;if(this.m_systemProperties.main&&this.m_particleSystem){var M=this.m_systemProperties.main;if(void 0!==M.loop&&(this.m_isLooping=M.loop),void 0!==M.duration&&(this.m_duration=M.duration),this.m_isLooping&&(this.m_duration=0),M.prewarm&&M.loop?this.m_prewarm=!0:this.m_prewarm=!1,M.startDelay?this.m_startDelay=M.startDelay:this.m_startDelay=null,void 0!==M.playOnAwake&&(this.m_playOnAwake=M.playOnAwake,this.m_autoStart=M.playOnAwake),M.maxParticles,void 0!==M.scalingMode){var B=M.scalingMode;this.m_scalingMode=B}if(void 0!==M.emitterVelocityMode){var C=M.emitterVelocityMode;this.m_emitterVelocityMode=C}if(void 0!==M.emitterVelocity){var T=M.emitterVelocity;this.m_emitterVelocity.set(T.x||0,T.y||0,T.z||0),this.m_emitterVelocity.length()}if(void 0!==M.customSimulationSpace){var x=M.customSimulationSpace;this.m_customSimulationSpace=x}if(void 0!==M.stopAction&&M.stopAction,void 0!==M.ringBufferMode)M.ringBufferMode>0&&M.ringBufferLoopRange&&M.ringBufferLoopRange;var I=this.convertMinMaxGradient(M.startColor),O=null!==(t=null===(e=M.startColor)||void 0===e?void 0:e.mode)&&void 0!==t?t:0,L=(null===(i=M.startColor)||void 0===i?void 0:i.color)||{r:1,g:1,b:1,a:1};0===O?(this.m_particleSystem.color1=new BABYLON.Color4(L.r,L.g,L.b,L.a),this.m_particleSystem.color2=new BABYLON.Color4(L.r,L.g,L.b,L.a),this.m_particleSystem.colorDead=new BABYLON.Color4(L.r,L.g,L.b,n.UNITY_TO_BABYLON_DEATH_FADE_ALPHA)):(this.m_particleSystem.color1=I.colorMin,this.m_particleSystem.color2=I.colorMax,this.m_particleSystem.colorDead=new BABYLON.Color4(I.colorMin.r,I.colorMin.g,I.colorMin.b,n.UNITY_TO_BABYLON_DEATH_FADE_ALPHA));var w=this.convertMinMaxCurve(M.startLifetime);0===(null!==(o=null===(r=M.startLifetime)||void 0===r?void 0:r.mode)&&void 0!==o?o:0)?(this.m_particleSystem.minLifeTime=w.value*n.UNITY_TO_BABYLON_LIFETIME_RATIO,this.m_particleSystem.maxLifeTime=w.value*n.UNITY_TO_BABYLON_LIFETIME_RATIO):(this.m_particleSystem.minLifeTime=w.min*n.UNITY_TO_BABYLON_LIFETIME_RATIO,this.m_particleSystem.maxLifeTime=w.max*n.UNITY_TO_BABYLON_LIFETIME_RATIO);var N=this.convertMinMaxCurve(M.startSpeed),P=null!==(s=null===(a=M.startSpeed)||void 0===a?void 0:a.mode)&&void 0!==s?s:0;if(0===N.min&&0===N.max?(this.m_particleSystem.minEmitPower=0,this.m_particleSystem.maxEmitPower=0):0===P?(this.m_particleSystem.minEmitPower=N.value*n.UNITY_TO_BABYLON_EMIT_POWER_RATIO,this.m_particleSystem.maxEmitPower=N.value*n.UNITY_TO_BABYLON_EMIT_POWER_RATIO):(this.m_particleSystem.minEmitPower=N.min*n.UNITY_TO_BABYLON_EMIT_POWER_RATIO,this.m_particleSystem.maxEmitPower=N.max*n.UNITY_TO_BABYLON_EMIT_POWER_RATIO),M.startSize3D){var R=this.convertMinMaxCurve(M.startSizeX),E=this.convertMinMaxCurve(M.startSizeY),k=this.convertMinMaxCurve(M.startSizeZ),D=null!==(u=null===(l=M.startSizeX)||void 0===l?void 0:l.mode)&&void 0!==u?u:0,F=null!==(d=null===(c=M.startSizeY)||void 0===c?void 0:c.mode)&&void 0!==d?d:0,U=null!==(p=null===(h=M.startSizeZ)||void 0===h?void 0:h.mode)&&void 0!==p?p:0,Y=void 0,V=void 0;0===D&&0===F&&0===U?V=Y=Math.max(R.value,E.value,k.value):(Y=Math.max(R.min,E.min,k.min),V=Math.max(R.max,E.max,k.max)),this.m_particleSystem.minSize=Y*n.UNITY_TO_BABYLON_SIZE_RATIO,this.m_particleSystem.maxSize=V*n.UNITY_TO_BABYLON_SIZE_RATIO}else{var G=this.convertMinMaxCurve(M.startSize);0===(null!==(f=null===(m=M.startSize)||void 0===m?void 0:m.mode)&&void 0!==f?f:0)?(this.m_particleSystem.minSize=G.value*n.UNITY_TO_BABYLON_SIZE_RATIO,this.m_particleSystem.maxSize=G.value*n.UNITY_TO_BABYLON_SIZE_RATIO):(this.m_particleSystem.minSize=G.min*n.UNITY_TO_BABYLON_SIZE_RATIO,this.m_particleSystem.maxSize=G.max*n.UNITY_TO_BABYLON_SIZE_RATIO)}if(M.startRotation3D){this.convertMinMaxCurve(M.startRotationX),this.convertMinMaxCurve(M.startRotationY);var z=this.convertMinMaxCurve(M.startRotationZ),W=(null===(g=M.startRotationX)||void 0===g?void 0:g.mode,void(null===(v=M.startRotationY)||void 0===v?void 0:v.mode)),H=void 0;0===(null!==(_=null===(y=M.startRotationZ)||void 0===y?void 0:y.mode)&&void 0!==_?_:0)?(W=z.value,H=z.value):(W=z.min,H=z.max),this.m_particleSystem instanceof BABYLON.ParticleSystem&&(this.m_particleSystem.minInitialRotation=W,this.m_particleSystem.maxInitialRotation=H)}else{var X=this.convertMinMaxCurve(M.startRotation);0===(null!==(A=null===(S=M.startRotation)||void 0===S?void 0:S.mode)&&void 0!==A?A:0)?this.m_particleSystem instanceof BABYLON.ParticleSystem&&(this.m_particleSystem.minInitialRotation=X.value,this.m_particleSystem.maxInitialRotation=X.value):this.m_particleSystem instanceof BABYLON.ParticleSystem&&(this.m_particleSystem.minInitialRotation=X.min,this.m_particleSystem.maxInitialRotation=X.max)}if(M.flipRotation&&M.flipRotation>0){if(this.m_particleSystem instanceof BABYLON.ParticleSystem){var K=this.m_particleSystem.minAngularSpeed||0,Q=this.m_particleSystem.maxAngularSpeed||0,j=Math.max(Math.abs(K),Math.abs(Q));this.m_particleSystem.minAngularSpeed=-j*M.flipRotation,this.m_particleSystem.maxAngularSpeed=j*M.flipRotation}}else this.m_particleSystem instanceof BABYLON.ParticleSystem&&(this.m_particleSystem.minAngularSpeed=0,this.m_particleSystem.maxAngularSpeed=0);if(void 0!==M.cullingMode){var Z=M.cullingMode;this.m_cullingMode=Z,3!==Z?this.setupCullingVisibilityCheck():this.m_isVisible=!0}var q,J=this.convertMinMaxCurve(M.gravityModifier);if(null===(b=M.gravityModifier)||void 0===b?void 0:b.mode,q=J.value*n.UNITY_TO_BABYLON_GRAVITY_RATIO,this.m_particleSystem.gravity=new BABYLON.Vector3(0,-9.81*q,0),void 0!==M.gravitySource){var $=M.gravitySource;this.m_gravitySource=$}if(void 0!==M.gravitySource&&1===this.m_gravitySource){var ee=this.m_particleSystem.gravity;this.m_particleSystem.gravity=new BABYLON.Vector3(0,ee.y,0)}this.m_particleSystem.worldOffset=BABYLON.Vector3.Zero(),1===M.simulationSpace?this.m_particleSystem.emitter=this.m_emitterMesh.getAbsolutePosition().clone():this.m_particleSystem.emitter=this.m_emitterMesh;var te=M.simulationSpeed||1;if(this.m_simulationSpeed=1!==te?te:1,void 0!==M.useUnscaledTime){var ne=M.useUnscaledTime;this.m_useUnscaledTime=ne}void 0!==M.deltaTime?this.m_reportedDeltaTime=M.deltaTime:this.m_reportedDeltaTime=0}},n.prototype.configureEmissionModule=function(){var e,t;if(this.m_systemProperties.emission&&this.m_particleSystem){var i=this.m_systemProperties.emission;if(i.enabled){if(i.rateOverTime){var r=this.convertMinMaxCurve(i.rateOverTime),o=(null===(e=i.rateOverTime)||void 0===e?void 0:e.mode,r.value*n.UNITY_TO_BABYLON_EMIT_RATE_RATIO);this.m_particleSystem.emitRate=o}else this.m_particleSystem.emitRate=0;if(i.rateOverDistance){var a=this.convertMinMaxCurve(i.rateOverDistance);null===(t=i.rateOverDistance)||void 0===t?void 0:t.mode,a.value,void 0!==i.rateOverDistanceMultiplier&&i.rateOverDistanceMultiplier}if(i.bursts&&i.bursts.length>0){var s=i.bursts.filter(function(e){return e&&"number"==typeof e.time&&void 0!==e.count});s.length>0&&(this.setupBursts(s),void 0!==i.burstCount&&(i.burstCount,s.length))}else i.burstCount&&i.burstCount}else this.m_particleSystem.emitRate=0;i.enabled&&this.m_particleSystem.emitRate>0&&this.m_particleSystem.emitRate<.1&&(this.m_particleSystem.emitRate=.1)}},n.prototype.configureShapeModule=function(){var e;if(this.m_systemProperties.shape&&this.m_particleSystem){var t=this.m_systemProperties.shape;if(t.enabled)this.configureEmissionShape(t);else if(this.m_particleSystem instanceof BABYLON.ParticleSystem){var i=this.m_systemProperties.shape,r=null!==(e=null==i?void 0:i.radius)&&void 0!==e?e:n.DEFAULT_PARTICLE_PROPERTIES.shape.radius;this.createSphereShapeEmitter(r,0,0)}}},n.prototype.configureRendererModule=function(){var e,t;if(this.m_systemProperties.renderer&&this.m_particleSystem){var n=this.m_systemProperties.renderer;if(void 0!==n.renderMode)switch(n.renderMode){case 0:break;case 1:void 0!==n.lengthScale&&n.lengthScale>0&&this.implementStretchRendering(n.lengthScale,n.velocityScale,n.freeformStretching);break;case 2:this.implementConstrainedBillboarding("horizontal");break;case 3:this.implementConstrainedBillboarding("vertical");break;case 4:this.implementMeshRendering(n);break;case 5:this.m_particleSystem instanceof BABYLON.ParticleSystem&&(this.m_particleSystem.renderingGroupId=-1)}if(void 0!==n.minParticleSize||void 0!==n.maxParticleSize){var i=null!==(e=n.minParticleSize)&&void 0!==e?e:0,r=null!==(t=n.maxParticleSize)&&void 0!==t?t:.5;this.m_particleSystem.minSize<i&&(this.m_particleSystem.minSize=i),this.m_particleSystem.maxSize>r&&(this.m_particleSystem.maxSize=r)}void 0!==n.sortMode&&this.implementParticleSorting(n.sortMode,n.sortingFudge),void 0!==n.alignment&&this.implementParticleAlignment(n.alignment),!n.flip||0===n.flip.x&&0===n.flip.y||this.implementParticleFlipping(n.flip),!n.pivot||0===n.pivot.x&&0===n.pivot.y&&0===n.pivot.z||this.implementParticlePivot(n.pivot),void 0!==n.allowRoll&&this.implementParticleRoll(n.allowRoll),void 0!==n.velocityScale&&n.velocityScale>0&&this.implementVelocityScaling(n.velocityScale,n.cameraVelocityScale),void 0!==n.normalDirection&&this.implementNormalDirection(n.normalDirection),void 0!==n.freeformStretching&&this.implementFreeformStretching(n.freeformStretching),void 0!==n.maskInteraction&&n.maskInteraction>0&&this.implementMaskInteraction(n.maskInteraction),void 0!==n.rotateWithStretchDirection&&this.implementStretchRotation(n.rotateWithStretchDirection),void 0!==n.shadowBias&&0!==n.shadowBias&&this.implementShadowBias(n.shadowBias),void 0!==n.meshCount&&n.meshCount>1&&n.meshes&&this.implementMultiMeshRendering(n.meshes,n.meshDistribution),void 0!==n.activeVertexStreamsCount&&n.activeVertexStreamsCount>0&&this.implementCustomVertexStreams(n.activeVertexStreamsCount),n.trailMaterial&&this.implementTrailMaterial(n.trailMaterial),n.materials&&n.materials.length>0&&this.implementMaterialConfiguration(n.materials),void 0===n.shadowCastingMode&&void 0===n.receiveShadows||this.implementShadowConfiguration(n.shadowCastingMode,n.receiveShadows),void 0===n.lightProbeUsage&&void 0===n.reflectionProbeUsage||this.implementProbeConfiguration(n.lightProbeUsage,n.reflectionProbeUsage),void 0===n.enableGPUInstancing&&void 0===n.supportsMeshInstancing||this.implementGPUInstancing(n.enableGPUInstancing,n.supportsMeshInstancing),void 0===n.sortingLayerID&&void 0===n.sortingOrder||this.implementSortingLayer(n.sortingLayerID,n.sortingOrder)}},n.prototype.implementStretchRendering=function(e,t,n){this.m_particleSystem instanceof BABYLON.ParticleSystem&&(this.m_particleSystem.stretchSettings={lengthScale:e,velocityScale:null!=t?t:1,freeform:null!=n&&n})},n.prototype.implementConstrainedBillboarding=function(e){this.m_particleSystem instanceof BABYLON.ParticleSystem&&(this.m_particleSystem.billboardConstraint=e)},n.prototype.implementMeshRendering=function(e){e.mesh&&(this.m_particleSystem,BABYLON.GPUParticleSystem)},n.prototype.implementParticleSorting=function(e,t){switch(e){case 1:this.m_particleSystem instanceof BABYLON.ParticleSystem&&(this.m_particleSystem.blendMode=BABYLON.ParticleSystem.BLENDMODE_ONEONE);break;case 2:case 3:this.m_particleSystem.customSortMode=e,void 0!==t&&(this.m_particleSystem.sortingFudge=t)}},n.prototype.implementParticleAlignment=function(e){switch(e){case 1:this.m_particleSystem.worldAlignment=!0;break;case 2:this.m_particleSystem.localAlignment=!0;break;case 3:case 4:this.m_particleSystem.velocityAlignment=!0}},n.prototype.implementParticleFlipping=function(e){this.m_particleSystem.flipSettings={x:e.x,y:e.y}},n.prototype.implementParticlePivot=function(e){this.m_particleSystem.pivotOffset=new BABYLON.Vector3(e.x,e.y,e.z)},n.prototype.implementParticleRoll=function(e){this.m_particleSystem.allowRoll=e},n.prototype.implementVelocityScaling=function(e,t){this.m_particleSystem.velocityScaling={scale:e,cameraScale:null!=t?t:1}},n.prototype.implementNormalDirection=function(e){this.m_particleSystem.normalDirection=e},n.prototype.implementFreeformStretching=function(e){this.m_particleSystem.freeformStretching=e},n.prototype.implementMaskInteraction=function(e){switch(e){case 1:this.m_particleSystem.maskMode="inside";break;case 2:this.m_particleSystem.maskMode="outside"}},n.prototype.implementStretchRotation=function(e){this.m_particleSystem.rotateWithStretch=e},n.prototype.implementShadowBias=function(e){this.m_particleSystem.shadowBias=e},n.prototype.implementMultiMeshRendering=function(e,t){this.m_particleSystem.multiMeshSettings={meshes:e,distribution:t}},n.prototype.implementCustomVertexStreams=function(e){this.m_particleSystem.customVertexStreams=e},n.prototype.implementTrailMaterial=function(e){this.m_particleSystem.trailMaterial=e},n.prototype.implementMaterialConfiguration=function(e){if(e.length>0){var t=e[0];t&&t.name,e.length>1&&(this.m_particleSystem.additionalMaterials=e.slice(1))}},n.prototype.implementShadowConfiguration=function(e,t){void 0!==e&&(this.m_particleSystem.shadowCastingMode=e),void 0!==t&&(this.m_particleSystem.receiveShadows=t)},n.prototype.implementProbeConfiguration=function(e,t){void 0!==e&&(this.m_particleSystem.lightProbeUsage=e),void 0!==t&&(this.m_particleSystem.reflectionProbeUsage=t)},n.prototype.implementGPUInstancing=function(e,t){void 0!==e&&(this.m_particleSystem.gpuInstancesEnabled=e),void 0!==t&&(this.m_particleSystem.meshInstancingSupported=t)},n.prototype.implementSortingLayer=function(e,t){void 0!==e&&(this.m_particleSystem.sortingLayerID=e),void 0!==t&&(this.m_particleSystem instanceof BABYLON.ParticleSystem&&(this.m_particleSystem.renderingGroupId=Math.max(0,Math.min(3,t))),this.m_particleSystem.sortingOrder=t)},n.prototype.configureVelocityOverLifetimeModule=function(){var e,t,n,i,r,o,a,s,l,u,c;if(this.m_systemProperties.velocityOverLifetime&&this.m_particleSystem){var d=this.m_systemProperties.velocityOverLifetime;d.enabled&&(this.convertMinMaxCurve(d.x),this.convertMinMaxCurve(d.y),this.convertMinMaxCurve(d.z),null===(e=d.x)||void 0===e?void 0:e.mode,null===(t=d.y)||void 0===t?void 0:t.mode,null===(n=d.z)||void 0===n?void 0:n.mode,(d.orbitalX||d.orbitalY||d.orbitalZ)&&(this.convertMinMaxCurve(d.orbitalX),this.convertMinMaxCurve(d.orbitalY),this.convertMinMaxCurve(d.orbitalZ),null===(i=d.orbitalX)||void 0===i?void 0:i.mode,null===(r=d.orbitalY)||void 0===r?void 0:r.mode,null===(o=d.orbitalZ)||void 0===o?void 0:o.mode),(d.orbitalOffsetX||d.orbitalOffsetY||d.orbitalOffsetZ)&&(this.convertMinMaxCurve(d.orbitalOffsetX),this.convertMinMaxCurve(d.orbitalOffsetY),this.convertMinMaxCurve(d.orbitalOffsetZ),null===(a=d.orbitalOffsetX)||void 0===a?void 0:a.mode,null===(s=d.orbitalOffsetY)||void 0===s?void 0:s.mode,null===(l=d.orbitalOffsetZ)||void 0===l?void 0:l.mode),d.radial&&(this.convertMinMaxCurve(d.radial),null===(u=d.radial)||void 0===u?void 0:u.mode),d.speedModifier&&(this.convertMinMaxCurve(d.speedModifier),null===(c=d.speedModifier)||void 0===c?void 0:c.mode),this.setupVelocityOverLifetime(d))}},n.prototype.configureLimitVelocityOverLifetimeModule=function(){if(this.m_systemProperties.limitVelocityOverLifetime&&this.m_particleSystem){var e=this.m_systemProperties.limitVelocityOverLifetime;e.enabled&&this.setupLimitVelocity(e)}},n.prototype.configureColorOverLifetimeModule=function(){if(this.m_systemProperties.colorOverLifetime&&this.m_particleSystem){var e=this.m_systemProperties.colorOverLifetime;if(e.enabled&&e.color&&this.m_particleSystem instanceof BABYLON.ParticleSystem){var t=this.convertMinMaxGradient(e.color);if(this.m_particleSystem.addColorGradient(0,t.colorMin),this.m_particleSystem.addColorGradient(1,t.colorMax),e.color.gradient&&e.color.gradient.colorKeys){this.m_particleSystem.removeColorGradient(0),this.m_particleSystem.removeColorGradient(1);for(var n=0,i=e.color.gradient.colorKeys;n<i.length;n++){var r=i[n],o=this.convertColor(r.color);this.m_particleSystem.addColorGradient(r.time,o)}if(e.color.gradient.alphaKeys)for(var a=0,s=e.color.gradient.alphaKeys;a<s.length;a++)s[a]}}else e.enabled}},n.prototype.configureSizeOverLifetimeModule=function(){var e,t,n,i,r;if(this.m_systemProperties.sizeOverLifetime&&this.m_particleSystem){var o=this.m_systemProperties.sizeOverLifetime;if(o.enabled&&this.m_particleSystem instanceof BABYLON.ParticleSystem)if(o.separateAxes){var a=this.convertMinMaxCurve(o.x),s=this.convertMinMaxCurve(o.y),l=this.convertMinMaxCurve(o.z),u=(null===(e=o.x)||void 0===e?void 0:e.mode,null===(t=o.y)||void 0===t?void 0:t.mode,null===(n=o.z)||void 0===n?void 0:n.mode,Math.max(a.min,s.min,l.min)),c=Math.max(a.max,s.max,l.max);this.m_particleSystem.addSizeGradient(0,u),this.m_particleSystem.addSizeGradient(1,c)}else{var d=this.convertMinMaxCurve(o.size);u=void 0,c=void 0,0===(null!==(r=null===(i=o.size)||void 0===i?void 0:i.mode)&&void 0!==r?r:0)?(u=d.value,c=d.value):(u=d.min,c=d.max),this.m_particleSystem.addSizeGradient(0,u),this.m_particleSystem.addSizeGradient(1,c)}else o.enabled}},n.prototype.configureRotationOverLifetimeModule=function(){var e,t,n,i,r,o;if(this.m_systemProperties.rotationOverLifetime&&this.m_particleSystem){var a=this.m_systemProperties.rotationOverLifetime;if(a.enabled&&this.m_particleSystem instanceof BABYLON.ParticleSystem)if(a.separateAxes){this.convertMinMaxCurve(a.x),this.convertMinMaxCurve(a.y);var s=this.convertMinMaxCurve(a.z),l=(null===(e=a.x)||void 0===e?void 0:e.mode,void(null===(t=a.y)||void 0===t?void 0:t.mode)),u=void 0;0===(null!==(i=null===(n=a.z)||void 0===n?void 0:n.mode)&&void 0!==i?i:0)?(l=s.value,u=s.value):(l=s.min,u=s.max),this.m_particleSystem.addAngularSpeedGradient(0,l),this.m_particleSystem.addAngularSpeedGradient(1,u)}else{var c=this.convertMinMaxCurve(a.z);l=void 0,u=void 0,0===(null!==(o=null===(r=a.z)||void 0===r?void 0:r.mode)&&void 0!==o?o:0)?(l=c.value,u=c.value):(l=c.min,u=c.max),this.m_particleSystem.addAngularSpeedGradient(0,l),this.m_particleSystem.addAngularSpeedGradient(1,u)}}},n.prototype.configureTextureSheetAnimationModule=function(){if(this.m_systemProperties.textureSheetAnimation&&this.m_particleSystem){var e=this.m_systemProperties.textureSheetAnimation;e.enabled&&this.m_particleSystem instanceof BABYLON.ParticleSystem?(this.m_particleSystem.spriteCellChangeSpeed=e.fps||1,this.m_particleSystem.spriteCellWidth=1/(e.numTilesX||1),this.m_particleSystem.spriteCellHeight=1/(e.numTilesY||1),this.m_particleSystem.spriteRandomStartCell=e.useRandomRow||!1,e.frameOverTime&&this.convertMinMaxCurve(e.frameOverTime),e.startFrame&&this.convertMinMaxCurve(e.startFrame),e.speedRange):e.enabled}},n.prototype.ensureBasicConfiguration=function(){var e;if(this.m_particleSystem&&(this.m_particleSystem.emitRate<0&&(this.m_particleSystem.emitRate=0),this.m_particleSystem.minLifeTime<=0&&(this.m_particleSystem.minLifeTime=5*n.UNITY_TO_BABYLON_LIFETIME_RATIO,this.m_particleSystem.maxLifeTime=5*n.UNITY_TO_BABYLON_LIFETIME_RATIO),this.m_particleSystem.minSize<=0&&(this.m_particleSystem.minSize=1*n.UNITY_TO_BABYLON_SIZE_RATIO,this.m_particleSystem.maxSize=1*n.UNITY_TO_BABYLON_SIZE_RATIO),this.m_particleSystem instanceof BABYLON.ParticleSystem&&(!this.m_particleSystem.direction1||!this.m_particleSystem.direction2||this.m_particleSystem.direction1.equals(new BABYLON.Vector3(-1,1,-1))&&this.m_particleSystem.direction2.equals(new BABYLON.Vector3(1,1,1))))){var t=this.m_systemProperties.shape,i=null!==(e=null==t?void 0:t.radius)&&void 0!==e?e:n.DEFAULT_PARTICLE_PROPERTIES.shape.radius;this.createSphereShapeEmitter(i,0,0)}},n.prototype.convertMinMaxCurve=function(e){var t,n,i,r,o,a,s,l;if(!e)return console.warn("### ShurikenParticles: ERROR - No curve data provided from Unity export"),{min:0,max:0,value:0};var u=null!==(t=e.mode)&&void 0!==t?t:0;(u<0||u>3)&&console.warn("### ShurikenParticles: WARNING - Invalid Unity curve mode:",u,"using mode 0 (Constant)");var c=e.multiplier||1;switch(u){case 0:var d=null!==(n=e.constant)&&void 0!==n?n:0;return{min:d,max:d,value:d};case 1:if(e.curve&&e.curve.keys&&e.curve.keys.length>0){var h=this.evaluateCurveAtTime(e.curve,0)*c,p=this.evaluateCurveAtTime(e.curve,.5)*c,m=this.evaluateCurveAtTime(e.curve,1)*c;return{min:Math.min(h,p,m),max:Math.max(h,p,m),value:(h+p+m)/3}}var f=(null!==(i=e.constant)&&void 0!==i?i:1)*c;return{min:f,max:f,value:f};case 2:var g=null!==(r=e.constantMin)&&void 0!==r?r:0,v=null!==(o=e.constantMax)&&void 0!==o?o:0;return{min:g,max:v,value:(g+v)/2};case 3:if(e.curveMin&&e.curveMax&&e.curveMin.keys&&e.curveMax.keys){var y=this.evaluateCurveAtTime(e.curveMin,0)*c,_=this.evaluateCurveAtTime(e.curveMin,.5)*c,S=this.evaluateCurveAtTime(e.curveMin,1)*c,A=this.evaluateCurveAtTime(e.curveMax,0)*c,b=this.evaluateCurveAtTime(e.curveMax,.5)*c,M=this.evaluateCurveAtTime(e.curveMax,1)*c,B=Math.min(y,_,S,A,b,M),C=Math.max(y,_,S,A,b,M);return{min:B,max:C,value:(B+C)/2}}var T=(null!==(a=e.constantMin)&&void 0!==a?a:0)*c,x=(null!==(s=e.constantMax)&&void 0!==s?s:0)*c;return{min:T,max:x,value:(T+x)/2};default:var I=null!==(l=e.constant)&&void 0!==l?l:0;return{min:I,max:I,value:I}}},n.prototype.convertMinMaxGradient=function(e){if(!e){var t=new BABYLON.Color4(1,1,1,1);return{colorMin:t,colorMax:t}}var n,i;switch(e.mode){case 0:var r=this.convertColor(e.color);n=r,i=r;break;case 2:n=this.convertColor(e.colorMin),i=this.convertColor(e.colorMax);break;case 1:if(e.gradient&&e.gradient.colorKeys&&e.gradient.colorKeys.length>0){var o=e.gradient.colorKeys[0],a=e.gradient.colorKeys[e.gradient.colorKeys.length-1];n=this.convertColor(o.color),i=this.convertColor(a.color)}else if(e.color)n=l=this.convertColor(e.color),i=l;else{var s=new BABYLON.Color4(1,1,1,1);n=s,i=s}break;case 3:e.gradientMin&&e.gradientMax&&e.gradientMin.colorKeys&&e.gradientMin.colorKeys.length>0&&e.gradientMax.colorKeys&&e.gradientMax.colorKeys.length>0?(n=this.convertColor(e.gradientMin.colorKeys[0].color),i=this.convertColor(e.gradientMax.colorKeys[0].color)):(n=this.convertColor(e.colorMin),i=this.convertColor(e.colorMax));break;case 4:e.gradient&&e.gradient.colorKeys&&e.gradient.colorKeys.length>0?(o=e.gradient.colorKeys[0],a=e.gradient.colorKeys[e.gradient.colorKeys.length-1],n=this.convertColor(o.color),i=this.convertColor(a.color)):(n=this.convertColor(e.colorMin),i=this.convertColor(e.colorMax));break;default:var l;e.color?(n=l=this.convertColor(e.color),i=l):(n=this.convertColor(e.colorMin),i=this.convertColor(e.colorMax))}return{colorMin:n,colorMax:i}},n.prototype.convertColor=function(e){if(!e)return new BABYLON.Color4(1,1,1,1);var t="number"==typeof e.r&&!isNaN(e.r)&&isFinite(e.r)?e.r:1,n="number"==typeof e.g&&!isNaN(e.g)&&isFinite(e.g)?e.g:1,i="number"==typeof e.b&&!isNaN(e.b)&&isFinite(e.b)?e.b:1,r="number"==typeof e.a&&!isNaN(e.a)&&isFinite(e.a)?e.a:1;return 1!==t||1!==n||1!==i||1!==r||1===e.r&&1===e.g&&1===e.b&&1===e.a?new BABYLON.Color4(t,n,i,r):new BABYLON.Color4(1,1,1,1)},n.prototype.colorsEqual=function(e,t){if(!e&&!t)return!0;if(!e||!t)return!1;var n=1e-4;return Math.abs(e.r-t.r)<n&&Math.abs(e.g-t.g)<n&&Math.abs(e.b-t.b)<n&&Math.abs(e.a-t.a)<n},n.prototype.applyUnityGradientToBabylon=function(e,t){if(!e||!e.colorKeys||0===e.colorKeys.length)return!1;t.removeColorGradient(0),t.removeColorGradient(1);for(var n=0,i=e.colorKeys;n<i.length;n++){var r=i[n],o=this.convertColor(r.color);t.addColorGradient(r.time,o)}return e.alphaKeys&&e.alphaKeys.length>0&&console.warn("### ShurikenParticles: Alpha keys detected but not fully supported yet"),!0},n.prototype.convertVector3=function(e){return e?new BABYLON.Vector3(e.x,e.y,e.z):BABYLON.Vector3.Zero()},n.prototype.evaluateCurveAtTime=function(e,t){if(!e||!e.keys||0===e.keys.length)return 1;var n=e.keys;if(t<=n[0].time)return n[0].value;if(t>=n[n.length-1].time)return n[n.length-1].value;for(var i=0;i<n.length-1;i++){var r=n[i],o=n[i+1];if(t>=r.time&&t<=o.time){var a=(t-r.time)/(o.time-r.time);return r.value+a*(o.value-r.value)}}return n[0].value},n.prototype.setupBursts=function(e){if(this.m_burstTimers=[],e&&e.length>0)for(var t=0;t<e.length;t++){var n=e[t];this.m_burstTimers.push(-n.time)}},n.prototype.resetBurstTimers=function(){var e;if((null===(e=this.m_systemProperties.emission)||void 0===e?void 0:e.bursts)&&this.m_burstTimers)for(var t=0;t<this.m_systemProperties.emission.bursts.length;t++){var n=this.m_systemProperties.emission.bursts[t];this.m_burstTimers[t]=-n.time}},n.prototype.updateSystem=function(e){this.m_systemTime+=e},n.prototype.updateEmission=function(e){this.m_emissionTimer+=e},n.prototype.updateAnimationProperties=function(){},n.prototype.updateBursts=function(e){var t,n,i;if(null===(t=this.m_systemProperties.emission)||void 0===t?void 0:t.bursts)for(var r=0;r<this.m_systemProperties.emission.bursts.length;r++){var o=this.m_systemProperties.emission.bursts[r];if(this.m_systemTime>=o.time&&this.m_burstTimers[r]<0){var a=void 0!==o.probability?o.probability:1;if(Math.random()>a){this.m_burstTimers[r]=this.m_systemTime;continue}var s=this.convertMinMaxCurve(o.count),l=void 0;switch(null!==(i=null===(n=o.count)||void 0===n?void 0:n.mode)&&void 0!==i?i:0){case 0:case 1:default:l=s.value;break;case 2:case 3:l=Math.random()*(s.max-s.min)+s.min}(l=Math.max(0,Math.round(l)))>0&&this.triggerBurst(l),this.m_burstTimers[r]=this.m_systemTime;var u=void 0!==o.cycleCount?o.cycleCount:1;(-1===u||u>1)&&void 0!==o.repeatInterval&&o.repeatInterval}}},n.prototype.triggerBurst=function(e){var t=this;if(this.m_particleSystem instanceof BABYLON.ParticleSystem){var n=this.m_particleSystem.emitRate;this.m_particleSystem.emitRate=60*e,setTimeout(function(){t.m_particleSystem&&(t.m_particleSystem.emitRate=n)},16)}},n.prototype.configureEmissionShape=function(e){var t,n,i;if(e.radiusSpeed&&(this.convertMinMaxCurve(e.radiusSpeed),null===(t=e.radiusSpeed)||void 0===t?void 0:t.mode),e.meshSpawnSpeed&&(this.convertMinMaxCurve(e.meshSpawnSpeed),null===(n=e.meshSpawnSpeed)||void 0===n?void 0:n.mode),e.arcSpeed&&(this.convertMinMaxCurve(e.arcSpeed),null===(i=e.arcSpeed)||void 0===i?void 0:i.mode),e.rotation&&this.m_emitterMesh){var r=this.convertVector3(e.rotation),o=BABYLON.Quaternion.FromEulerAngles(BABYLON.Tools.ToRadians(r.x),BABYLON.Tools.ToRadians(r.y),BABYLON.Tools.ToRadians(r.z)),a=this.m_emitterMesh.rotationQuaternion||BABYLON.Quaternion.Identity();this.m_emitterMesh.rotationQuaternion=a.multiply(o)}switch(e.shapeType){case 4:case 7:case 8:case 9:var s=e.radius||1,l=e.angle||25,u=(e.length,e.arc,e.radiusSpread,e.scale||{x:1,y:1,z:1}),c=(e.radiusMode,s*((u.x+u.z)/2)),d=Math.max(.1,l*Math.PI/180),h=Math.max(.5,c);this.createConeShapeEmitter(h,d);break;case 0:case 1:var p=e.radius||1,m=e.scale||{x:1,y:1,z:1},f=e.radiusSpread||0,g=e.radiusMode||0,v=(e.donutRadius,p);2===g&&f>0&&(v=p*(1+.5*f));var y=v*((m.x+m.y+m.z)/3);e.shapeType,this.m_particleSystem.createSphereEmitter(y);break;case 2:case 3:var _=e.radius||1,S=e.scale||{x:1,y:1,z:1},A=e.radiusSpread||0,b=e.radiusMode||0,M=(e.donutRadius,e.arc,_);2===b&&A>0&&(M=_*(1+.5*A));var B=M*((S.x+S.y+S.z)/3);e.shapeType,this.m_particleSystem.createHemisphericEmitter(B);break;case 10:case 11:var C=e.radius||1,T=e.scale||{x:1,y:1,z:1},x=(e.arc,e.donutRadius,e.radiusSpread||0),I=e.radiusMode||0,O=(e.length,C);2===I&&x>0&&(O=C*(1+.5*x));var L=O*((T.x+T.z)/2);T.y,this.m_particleSystem.createDirectedSphereEmitter(L,new BABYLON.Vector3(0,1,0),new BABYLON.Vector3(0,1,0));break;case 5:case 15:case 16:var w=e.scale||{x:1,y:1,z:1},N=e.boxThickness||{x:0,y:0,z:0};15!==e.shapeType&&16!==e.shapeType||(w={x:Math.max(.1,w.x-N.x),y:Math.max(.1,w.y-N.y),z:Math.max(.1,w.z-N.z)}),this.m_particleSystem.createBoxEmitter(new BABYLON.Vector3(-w.x/2,-w.y/2,-w.z/2),new BABYLON.Vector3(w.x/2,w.y/2,w.z/2),new BABYLON.Vector3(0,1,0),new BABYLON.Vector3(0,1,0));break;case 17:var P=e.radius||1,R=e.donutRadius||.2,E=e.scale||{x:1,y:1,z:1},k=(e.arc,e.radiusSpread||0),D=P;2===(e.radiusMode||0)&&k>0&&(D=P*(1+.5*k));var F=(E.x+E.z)/2,U=(D*F+R*F)/2;this.m_particleSystem.createDirectedSphereEmitter(U,new BABYLON.Vector3(0,1,0),new BABYLON.Vector3(0,1,0));break;case 18:var Y=e.scale||{x:1,y:1,z:1},V=e.length||1,G=(e.arc,Y.x),z=Y.z,W=V*Y.y;this.m_particleSystem.createBoxEmitter(new BABYLON.Vector3(-G/2,-W/2,-z/2),new BABYLON.Vector3(G/2,W/2,z/2),new BABYLON.Vector3(0,1,0),new BABYLON.Vector3(0,1,0));break;case 12:var H=e.length||1,X=e.scale||{x:1,y:1,z:1},K=e.radius||.1,Q=H*X.x,j=K*Math.max(X.y,X.z);this.m_particleSystem.createBoxEmitter(new BABYLON.Vector3(-Q/2,-j/2,-j/2),new BABYLON.Vector3(Q/2,j/2,j/2),new BABYLON.Vector3(0,1,0),new BABYLON.Vector3(0,1,0));break;default:if(6===e.shapeType||13===e.shapeType||14===e.shapeType){var Z=e.radius||1,q=e.scale||{x:1,y:1,z:1},J=Z*((q.x+q.y+q.z)/3);this.m_particleSystem.createSphereEmitter(J)}else if(19===e.shapeType||20===e.shapeType){var $=e.scale||{x:1,y:1,z:1};this.m_particleSystem.createBoxEmitter(new BABYLON.Vector3(-$.x/2,-$.y/2,-.1),new BABYLON.Vector3($.x/2,$.y/2,.1),new BABYLON.Vector3(0,0,1),new BABYLON.Vector3(0,0,1))}else{var ee=e.radius||1,te=(e.angle||25)*Math.PI/180,ne=e.length||1,ie=e.scale||{x:1,y:1,z:1},re=te,oe=(ee+(ee+ne*Math.tan(re)))/2,ae=3*ee;(oe*=(ie.x+ie.z)/2)>ae&&(oe=ae);var se=Math.min(re,Math.PI/4);this.createConeShapeEmitter(oe,se)}}if(e.position&&(0!==e.position.x||0!==e.position.y||0!==e.position.z)){var le=this.convertVector3(e.position);this.m_emitterMesh&&(this.m_emitterMesh.position.clone(),this.m_emitterMesh.position.addInPlace(le))}!e.rotation||0===e.rotation.x&&0===e.rotation.y&&0===e.rotation.z||this.m_emitterMesh,e.randomDirectionAmount,e.randomPositionAmount,e.sphericalDirectionAmount,e.alignToDirection,e.arc,void 0!==e.normalOffset&&e.normalOffset},n.prototype.setupVelocityOverLifetime=function(e){},n.prototype.setupLimitVelocity=function(e){},n.prototype.createColorGradient=function(e){return this.convertMinMaxGradient(e)},n.prototype.setupSpriteAnimation=function(e){this.m_particleSystem instanceof BABYLON.ParticleSystem&&(this.m_particleSystem.spriteCellChangeSpeed=e.fps||1,this.m_particleSystem.spriteCellWidth=1/e.numTilesX,this.m_particleSystem.spriteCellHeight=1/e.numTilesY,this.m_particleSystem.spriteRandomStartCell=e.useRandomRow)},n.prototype.createBoxShapeEmitter=function(e,t){if(this.m_particleSystem instanceof BABYLON.ParticleSystem){var n=e||{x:1,y:1,z:1};this.m_particleSystem.createBoxEmitter(new BABYLON.Vector3(-n.x/2,-n.y/2,-n.z/2),new BABYLON.Vector3(n.x/2,n.y/2,n.z/2),new BABYLON.Vector3(0,1,0),new BABYLON.Vector3(0,1,0))}},n.prototype.createSphereShapeEmitter=function(e,t,n){if(this.m_particleSystem instanceof BABYLON.ParticleSystem){var i=e||1;this.m_particleSystem.createSphereEmitter(i)}},n.prototype.createConeShapeEmitter=function(e,t){if(this.m_particleSystem instanceof BABYLON.ParticleSystem){var i=e||1,r=t||Math.PI/7.2,o=this.m_particleSystem.createConeEmitter(i*n.UNITY_TO_BABYLON_CONE_SCALE_RATIO,r*n.UNITY_TO_BABYLON_CONE_SCALE_RATIO);o.radiusRange=1,o.heightRange=1,o.directionRandomizer=1,o.emitFromSpawnPointOnly=!1}},n.prototype.configureNoiseModule=function(){},n.prototype.configureCollisionModule=function(){},n.prototype.configureTrailsModule=function(){},n.prototype.configureSubEmittersModule=function(){},n.prototype.updateEmitterVelocityInheritance=function(e){var t;this.m_emitterVelocity.length()>0&&void 0!==(null===(t=this.m_systemProperties.main)||void 0===t?void 0:t.emitterVelocityMode)&&this.m_systemProperties.main.emitterVelocityMode},n.prototype.updateCustomSimulationSpace=function(e){this.m_customSimulationSpace},n.prototype.updateRingBufferMode=function(e){var t=this.m_systemProperties.main;(null==t?void 0:t.ringBufferMode)&&t.ringBufferMode>0&&t.ringBufferLoopRange&&(t.ringBufferLoopRange,2===t.ringBufferMode||t.ringBufferMode)},n.prototype.handleStopAction=function(){var e=this,t=this.m_systemProperties.main;void 0!==(null==t?void 0:t.stopAction)?1===t.stopAction?setTimeout(function(){e.transform&&e.transform.dispose&&e.transform.dispose()},0):this.stop():this.stop()},n.prototype.setupCullingVisibilityCheck=function(){var e=this,t=function(){if(e.m_isInitialized&&e.m_emitterMesh){var t=Date.now();if(!(t-e.m_lastVisibilityCheck<100)){e.m_lastVisibilityCheck=t;var n=e.m_isVisible;e.m_isVisible=e.isEmitterVisible(),n!==e.m_isVisible&&e.handleVisibilityChange(n,e.m_isVisible)}}};this.scene.registerBeforeRender(t);var n=this.disposeParticleSystem.bind(this);this.disposeParticleSystem=function(){e.scene.unregisterBeforeRender(t),n()}},n.prototype.isEmitterVisible=function(){if(!this.m_emitterMesh||!this.scene.activeCamera)return!0;var e=this.m_emitterMesh.getBoundingInfo();if(!e)return!0;var t=this.scene.activeCamera;if(t.isInFrustum&&e.boundingBox)return t.isInFrustum(e.boundingBox);var n=this.m_emitterMesh.getAbsolutePosition(),i=t.position;return BABYLON.Vector3.Distance(n,i)<=1e3},n.prototype.handleVisibilityChange=function(e,t){var n=this.m_cullingMode;!e&&t?1===n&&this.m_pausedTime>0&&(this.m_pausedTime=0):e&&!t&&(this.m_pausedTime=0)},n.prototype.disposeParticleSystem=function(){this.m_particleSystem&&(this.m_particleSystem.dispose(),this.m_particleSystem=null),this.m_emitterMesh&&this.m_emitterMesh.parent===this.transform&&(this.m_emitterMesh.dispose(),this.m_emitterMesh=null),this.m_animationCurves.clear(),this.m_gradients.clear(),this.m_isInitialized=!1},n.DefaultParticleTexture=null,n.DEFAULT_PARTICLE_PROPERTIES={isPlaying:!0,isPaused:!1,isStopped:!1,isEmitting:!0,particleCount:50,time:0,randomSeed:0,useAutoRandomSeed:!0,name:"",instanceId:0,enabled:!0,transformPosition:{x:0,y:0,z:0},transformRotation:{x:0,y:0,z:0},transformScale:{x:1,y:1,z:1},main:{duration:5,loop:!0,prewarm:!0,startDelay:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},startDelayMultiplier:0,startLifetime:{mode:0,constant:5,constantMin:0,constantMax:5,multiplier:1},startLifetimeMultiplier:5,startSpeed:{mode:0,constant:5,constantMin:0,constantMax:5,multiplier:1},startSpeedMultiplier:5,startSize3D:!1,startSize:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},startSizeMultiplier:1,startSizeX:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},startSizeXMultiplier:1,startSizeY:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},startSizeYMultiplier:1,startSizeZ:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},startSizeZMultiplier:1,startRotation3D:!1,startRotation:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},startRotationMultiplier:0,startRotationX:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},startRotationXMultiplier:0,startRotationY:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},startRotationYMultiplier:0,startRotationZ:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},startRotationZMultiplier:0,flipRotation:0,startColor:{mode:0,color:{r:1,g:1,b:1,a:1},colorMin:{r:0,g:0,b:0,a:0},colorMax:{r:1,g:1,b:1,a:1}},gravityModifier:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},gravityModifierMultiplier:0,simulationSpace:0,simulationSpeed:1,deltaTime:0,scalingMode:1,playOnAwake:!0,emitterVelocityMode:1,maxParticles:1e3,stopAction:0,cullingMode:0,ringBufferMode:0,ringBufferLoopRange:{x:0,y:1},customSimulationSpace:0,emitterVelocity:{x:0,y:0,z:0},gravitySource:0,useUnscaledTime:!1},emission:{enabled:!0,rateOverTime:{mode:0,constant:10,constantMin:0,constantMax:10,multiplier:1},rateOverTimeMultiplier:10,rateOverDistance:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},rateOverDistanceMultiplier:0,burstCount:0,bursts:[]},shape:{enabled:!0,shapeType:0,angle:25,radius:.025,radiusMode:0,radiusSpread:0,radiusSpeed:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},radiusSpeedMultiplier:1,donutRadius:.2,position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0},scale:{x:1,y:1,z:1},alignToDirection:!1,randomDirectionAmount:0,sphericalDirectionAmount:0,randomPositionAmount:0,biasOnTriangles:!1,useMeshMaterialIndex:!1,meshMaterialIndex:0,useMeshColors:!0,normalOffset:0,meshSpawnMode:0,meshSpawnSpread:0,meshSpawnSpeed:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},meshSpawnSpeedMultiplier:1,arc:360,arcMode:0,arcSpread:0,arcSpeed:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},arcSpeedMultiplier:1,length:5,boxThickness:{x:0,y:0,z:0}},renderer:{enabled:!0,materials:[],renderMode:0,cameraVelocityScale:0,velocityScale:0,lengthScale:2,normalDirection:1,sortMode:0,sortingFudge:0,minParticleSize:0,maxParticleSize:.5,alignment:0,flip:{x:0,y:0},allowRoll:!0,pivot:{x:0,y:0,z:0},shadowCastingMode:1,receiveShadows:!0,motionVectorGenerationMode:1,lightProbeUsage:1,reflectionProbeUsage:1,enableGPUInstancing:!0,mesh:null,sortingLayerID:0,sortingOrder:0,freeformStretching:!1,maskInteraction:0,meshCount:0,meshDistribution:0,rotateWithStretchDirection:!1,shadowBias:0,supportsMeshInstancing:!0,activeVertexStreamsCount:0,activeTrailVertexStreamsCount:0,meshes:[],trailMaterial:null},velocityOverLifetime:{enabled:!1,space:0,x:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},y:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},z:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},xMultiplier:0,yMultiplier:0,zMultiplier:0,orbitalX:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},orbitalY:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},orbitalZ:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},orbitalXMultiplier:0,orbitalYMultiplier:0,orbitalZMultiplier:0,orbitalOffsetX:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},orbitalOffsetY:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},orbitalOffsetZ:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},orbitalOffsetXMultiplier:0,orbitalOffsetYMultiplier:0,orbitalOffsetZMultiplier:0,radial:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},radialMultiplier:0,speedModifier:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},speedModifierMultiplier:1},limitVelocityOverLifetime:{enabled:!1,limitX:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},limitY:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},limitZ:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},limitXMultiplier:1,limitYMultiplier:1,limitZMultiplier:1,limit:{mode:0,constant:1,constantMin:0,constantMax:1,multiplier:1},limitMultiplier:1,dampen:0,separateAxes:!1,space:0,drag:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},dragMultiplier:0,multiplyDragByParticleSize:!0,multiplyDragByParticleVelocity:!0},colorOverLifetime:{enabled:!1,color:{mode:1,color:{r:0,g:0,b:0,a:0},colorMin:{r:0,g:0,b:0,a:0},colorMax:{r:0,g:0,b:0,a:0}}},sizeOverLifetime:{enabled:!1,size:{mode:1,constant:0,constantMin:0,constantMax:0,multiplier:1},sizeMultiplier:1,x:{mode:1,constant:0,constantMin:0,constantMax:0,multiplier:1},xMultiplier:1,y:{mode:1,constant:0,constantMin:0,constantMax:0,multiplier:1},yMultiplier:1,z:{mode:1,constant:0,constantMin:0,constantMax:0,multiplier:1},zMultiplier:1,separateAxes:!1},rotationOverLifetime:{enabled:!1,x:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},xMultiplier:0,y:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},yMultiplier:0,z:{mode:0,constant:.7853982,constantMin:0,constantMax:.7853982,multiplier:1},zMultiplier:.7853982,separateAxes:!1},textureSheetAnimation:{enabled:!1,mode:0,timeMode:0,fps:30,numTilesX:1,numTilesY:1,animation:0,useRandomRow:!0,frameOverTime:{mode:1,constant:0,constantMin:0,constantMax:0,multiplier:.9999},frameOverTimeMultiplier:.9999,startFrame:{mode:0,constant:0,constantMin:0,constantMax:0,multiplier:1},startFrameMultiplier:0,cycleCount:1,rowIndex:0,rowMode:1,uvChannelMask:-1,flipU:0,flipV:0,speedRange:{x:0,y:1}}},n.UNITY_TO_BABYLON_SIZE_RATIO=1,n.UNITY_TO_BABYLON_GRAVITY_RATIO=1,n.UNITY_TO_BABYLON_EMIT_RATE_RATIO=2,n.UNITY_TO_BABYLON_EMIT_POWER_RATIO=2,n.UNITY_TO_BABYLON_CONE_SCALE_RATIO=2,n.UNITY_TO_BABYLON_LIFETIME_RATIO=.65,n.UNITY_TO_BABYLON_DEATH_FADE_ALPHA=.2,n.EMITTER_POSITION_OFFSET=new BABYLON.Vector3(0,0,0),n.EMITTER_ROTATION_OFFSET=new BABYLON.Vector3(90,0,0),n}(e.ScriptComponent);e.ShurikenParticles=t,e.SceneManager.RegisterClass("TOOLKIT.ShurikenParticles",t)}(i||(i={})),function(e){var t=function(){function e(){this.blendWithPhysicsNormal=0,this.maxLookupDistance=8,this.searchRadius=1,this.useProjectionTest=!0,this._v0x=null,this._v0y=null,this._v0z=null,this._v1x=null,this._v1y=null,this._v1z=null,this._v2x=null,this._v2y=null,this._v2z=null,this._n0x=null,this._n0y=null,this._n0z=null,this._n1x=null,this._n1y=null,this._n1z=null,this._n2x=null,this._n2y=null,this._n2z=null,this._fnx=null,this._fny=null,this._fnz=null,this._cx=null,this._cy=null,this._cz=null,this._triangleCount=0,this._cellTriangles=null,this._htKeys=null,this._htStarts=null,this._htCounts=null,this._cellSize=2,this._hashOriginX=0,this._hashOriginZ=0,this._sourceMesh=null,this._worldMatrix=BABYLON.Matrix.Identity(),this._invWorldMatrix=BABYLON.Matrix.Identity(),this._matrixDirty=!0,this._scratchV0=new BABYLON.Vector3,this._scratchLocal=new BABYLON.Vector3,this._candidatesBuf=[],this._uniqueBuf=[],this._seenSet=new Set,this._barycentricScratch=[0,0,0]}return Object.defineProperty(e.prototype,"triangleCount",{get:function(){return this._triangleCount},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"cellSize",{get:function(){return this._cellSize},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"sourceMesh",{get:function(){return this._sourceMesh},enumerable:!1,configurable:!0}),e.prototype.buildFromMesh=function(e,t){void 0===t&&(t=2),this._sourceMesh=e,this._cellSize=Math.max(.01,t),this._htKeys=null,this._htStarts=null,this._htCounts=null,this._cellTriangles=null,this._triangleCount=0,this._matrixDirty=!0;var n=e.geometry;if(!n)return console.warn("[MeshNormalProxy] Mesh '"+e.name+"' has no geometry. Ensure the mesh is fully loaded before calling buildFromMesh."),!1;var i=n.getVerticesData(BABYLON.VertexBuffer.PositionKind),r=n.getVerticesData(BABYLON.VertexBuffer.NormalKind),o=n.getIndices();if(!i||0===i.length)return console.warn("[MeshNormalProxy] Mesh '"+e.name+"' has no position data."),!1;if(!r||0===r.length)return console.warn("[MeshNormalProxy] Mesh '"+e.name+"' has no normal data. Ensure normals are baked into the mesh."),!1;if(!o||0===o.length)return console.warn("[MeshNormalProxy] Mesh '"+e.name+"' has no index data."),!1;var a=Math.floor(o.length/3);if(0===a)return console.warn("[MeshNormalProxy] Mesh '"+e.name+"' has zero triangles."),!1;this._v0x=new Float32Array(a),this._v0y=new Float32Array(a),this._v0z=new Float32Array(a),this._v1x=new Float32Array(a),this._v1y=new Float32Array(a),this._v1z=new Float32Array(a),this._v2x=new Float32Array(a),this._v2y=new Float32Array(a),this._v2z=new Float32Array(a),this._n0x=new Float32Array(a),this._n0y=new Float32Array(a),this._n0z=new Float32Array(a),this._n1x=new Float32Array(a),this._n1y=new Float32Array(a),this._n1z=new Float32Array(a),this._n2x=new Float32Array(a),this._n2y=new Float32Array(a),this._n2z=new Float32Array(a),this._fnx=new Float32Array(a),this._fny=new Float32Array(a),this._fnz=new Float32Array(a),this._cx=new Float32Array(a),this._cy=new Float32Array(a),this._cz=new Float32Array(a);for(var s=1/0,l=1/0,u=-1/0,c=-1/0,d=0;d<a;d++){var h=o[3*d+0],p=o[3*d+1],m=o[3*d+2],f=i[3*h],g=i[3*h+1],v=i[3*h+2],y=i[3*p],_=i[3*p+1],S=i[3*p+2],A=i[3*m],b=i[3*m+1],M=i[3*m+2];this._v0x[d]=f,this._v0y[d]=g,this._v0z[d]=v,this._v1x[d]=y,this._v1y[d]=_,this._v1z[d]=S,this._v2x[d]=A,this._v2y[d]=b,this._v2z[d]=M,this._n0x[d]=r[3*h],this._n0y[d]=r[3*h+1],this._n0z[d]=r[3*h+2],this._n1x[d]=r[3*p],this._n1y[d]=r[3*p+1],this._n1z[d]=r[3*p+2],this._n2x[d]=r[3*m],this._n2y[d]=r[3*m+1],this._n2z[d]=r[3*m+2];var B=y-f,C=_-g,T=S-v,x=A-f,I=b-g,O=M-v,L=C*O-T*I,w=T*x-B*O,N=B*I-C*x,P=Math.sqrt(L*L+w*w+N*N);P>1e-10&&(L/=P,w/=P,N/=P),this._fnx[d]=L,this._fny[d]=w,this._fnz[d]=N;var R=(f+y+A)/3,E=(g+_+b)/3,k=(v+S+M)/3;this._cx[d]=R,this._cy[d]=E,this._cz[d]=k,(F=Math.min(f,y,A))<s&&(s=F),(U=Math.max(f,y,A))>u&&(u=U),(Y=Math.min(v,S,M))<l&&(l=Y),(V=Math.max(v,S,M))>c&&(c=V)}this._triangleCount=a,this._hashOriginX=s-this._cellSize,this._hashOriginZ=l-this._cellSize;var D=new Map;for(d=0;d<a;d++)for(var F=Math.min(this._v0x[d],this._v1x[d],this._v2x[d]),U=Math.max(this._v0x[d],this._v1x[d],this._v2x[d]),Y=Math.min(this._v0z[d],this._v1z[d],this._v2z[d]),V=Math.max(this._v0z[d],this._v1z[d],this._v2z[d]),G=Math.floor((F-this._hashOriginX)/this._cellSize),z=Math.floor((U-this._hashOriginX)/this._cellSize),W=Math.floor((Y-this._hashOriginZ)/this._cellSize),H=Math.floor((V-this._hashOriginZ)/this._cellSize),X=G;X<=z;X++)for(var K=W;K<=H;K++){var Q=this._makeHashKey(X,K),j=D.get(Q);D.set(Q,void 0!==j?j+1:1)}var Z=D.size,q=new Uint32Array(Z),J=0;D.forEach(function(e,t){q[J++]=t}),q.sort(),this._htKeys=new Uint32Array(Z),this._htStarts=new Int32Array(Z),this._htCounts=new Int32Array(Z);for(var $=0,ee=0;ee<Z;ee++){var te=q[ee];this._htKeys[ee]=te,this._htStarts[ee]=$,this._htCounts[ee]=D.get(te),$+=this._htCounts[ee]}this._cellTriangles=new Int32Array($);var ne=new Map;for(ee=0;ee<Z;ee++)ne.set(this._htKeys[ee],this._htStarts[ee]);for(d=0;d<a;d++)for(F=Math.min(this._v0x[d],this._v1x[d],this._v2x[d]),U=Math.max(this._v0x[d],this._v1x[d],this._v2x[d]),Y=Math.min(this._v0z[d],this._v1z[d],this._v2z[d]),V=Math.max(this._v0z[d],this._v1z[d],this._v2z[d]),G=Math.floor((F-this._hashOriginX)/this._cellSize),z=Math.floor((U-this._hashOriginX)/this._cellSize),W=Math.floor((Y-this._hashOriginZ)/this._cellSize),H=Math.floor((V-this._hashOriginZ)/this._cellSize),X=G;X<=z;X++)for(K=W;K<=H;K++){Q=this._makeHashKey(X,K);var ie=ne.get(Q);this._cellTriangles[ie]=d,ne.set(Q,ie+1)}return!0},e.prototype.invalidateTransform=function(){this._matrixDirty=!0},e.prototype.getNormalAtPointToRef=function(e,t,n){if(void 0===n&&(n=null),0===this._triangleCount||!this._sourceMesh)return!1;this._matrixDirty&&(this._worldMatrix.copyFrom(this._sourceMesh.getWorldMatrix()),this._worldMatrix.invertToRef(this._invWorldMatrix),this._matrixDirty=!1),BABYLON.Vector3.TransformCoordinatesToRef(e,this._invWorldMatrix,this._scratchLocal);var i=this._scratchLocal.x,r=this._scratchLocal.y,o=this._scratchLocal.z,a=Math.floor((i-this._hashOriginX)/this._cellSize),s=Math.floor((o-this._hashOriginZ)/this._cellSize),l=this._candidatesBuf;l.length=0;for(var u=this.searchRadius,c=-u;c<=u;c++)for(var d=-u;d<=u;d++)if((f=this._bsearchCell(this._makeHashKey(a+c,s+d)))>=0)for(var h=(g=this._htStarts[f])+this._htCounts[f],p=g;p<h;p++)l.push(this._cellTriangles[p]);if(0===l.length){var m=u+1;for(c=-m;c<=m;c++)for(d=-m;d<=m;d++){var f,g;if((f=this._bsearchCell(this._makeHashKey(a+c,s+d)))>=0)for(h=(g=this._htStarts[f])+this._htCounts[f],p=g;p<h;p++)l.push(this._cellTriangles[p])}}if(0===l.length)return!1;var v=this._seenSet;v.clear();var y=this._uniqueBuf;for(y.length=0,p=0;p<l.length;p++)v.has(l[p])||(v.add(l[p]),y.push(l[p]));for(var _=-1,S=1/0,A=-1,b=1/0,M=this.maxLookupDistance*this.maxLookupDistance,B=0;B<y.length;B++){var C=y[B],T=i-this._cx[C],x=o-this._cz[C],I=T*T+x*x;if(!(I>M))if(this.useProjectionTest){var O,L=this._fnx[C],w=this._fny[C],N=this._fnz[C],P=(c=i-this._v0x[C])*L+(r-this._v0y[C])*w+(d=o-this._v0z[C])*N,R=Math.abs(P),E=i-P*L,k=r-P*w,D=o-P*N,F=(G=this._computeBarycentricInline(E,k,D,C))[0],U=G[1],Y=G[2];F>=-.01&&U>=-.01&&Y>=-.01?(O=R+.001*I)<b&&(b=O,A=C):(O=R+.1*I)<S&&(S=O,_=C)}else I<S&&(S=I,_=C)}var V=A>=0?A:_;if(V<0)return!1;L=this._fnx[V],w=this._fny[V],N=this._fnz[V],E=i-(P=(c=i-this._v0x[V])*L+(r-this._v0y[V])*w+(d=o-this._v0z[V])*N)*L,k=r-P*w,D=o-P*N;var G=this._computeBarycentricInline(E,k,D,V),z=Math.max(0,G[0]),W=Math.max(0,G[1]),H=Math.max(0,G[2]),X=z+W+H;X<1e-8?z=W=H=1/3:(z/=X,W/=X,H/=X);var K=z*this._n0x[V]+W*this._n1x[V]+H*this._n2x[V],Q=z*this._n0y[V]+W*this._n1y[V]+H*this._n2y[V],j=z*this._n0z[V]+W*this._n1z[V]+H*this._n2z[V];if(this._scratchV0.set(K,Q,j),BABYLON.Vector3.TransformNormalToRef(this._scratchV0,this._worldMatrix,t),t.normalize(),this.blendWithPhysicsNormal>0&&n){var Z=this.blendWithPhysicsNormal;t.x=t.x*(1-Z)+n.x*Z,t.y=t.y*(1-Z)+n.y*Z,t.z=t.z*(1-Z)+n.z*Z,t.normalize()}return!0},e.prototype.dispose=function(){this._v0x=null,this._v0y=null,this._v0z=null,this._v1x=null,this._v1y=null,this._v1z=null,this._v2x=null,this._v2y=null,this._v2z=null,this._n0x=null,this._n0y=null,this._n0z=null,this._n1x=null,this._n1y=null,this._n1z=null,this._n2x=null,this._n2y=null,this._n2z=null,this._fnx=null,this._fny=null,this._fnz=null,this._cx=null,this._cy=null,this._cz=null,this._cellTriangles=null,this._htKeys=null,this._htStarts=null,this._htCounts=null,this._triangleCount=0,this._sourceMesh=null},e.prototype._makeHashKey=function(e,t){return e+32768+65536*(t+32768)>>>0},e.prototype._bsearchCell=function(e){for(var t=0,n=this._htKeys.length-1;t<=n;){var i=t+n>>>1,r=this._htKeys[i];if(r===e)return i;r<e?t=i+1:n=i-1}return-1},e.prototype._computeBarycentricInline=function(e,t,n,i){var r=this._v0x[i],o=this._v0y[i],a=this._v0z[i],s=this._v1x[i]-r,l=this._v1y[i]-o,u=this._v1z[i]-a,c=this._v2x[i]-r,d=this._v2y[i]-o,h=this._v2z[i]-a,p=e-r,m=t-o,f=n-a,g=s*s+l*l+u*u,v=s*c+l*d+u*h,y=c*c+d*d+h*h,_=p*s+m*l+f*u,S=p*c+m*d+f*h,A=g*y-v*v;if(Math.abs(A)<1e-12)return this._barycentricScratch[0]=1/3,this._barycentricScratch[1]=1/3,this._barycentricScratch[2]=1/3,this._barycentricScratch;var b=(y*_-v*S)/A,M=(g*S-v*_)/A,B=1-b-M;return this._barycentricScratch[0]=B,this._barycentricScratch[1]=b,this._barycentricScratch[2]=M,this._barycentricScratch},e}();e.MeshNormalProxy=t;var n=function(){function e(){this._registry=new Map}return Object.defineProperty(e,"instance",{get:function(){return e._instance||(e._instance=new e),e._instance},enumerable:!1,configurable:!0}),e.prototype.register=function(e,t){e?t&&0!==t.triangleCount?this._registry.set(e,t):console.warn("[SmoothMeshNormalSystem] register: proxy is null or empty — did you call buildFromMesh()?"):console.warn("[SmoothMeshNormalSystem] register: body is null.")},e.prototype.unregister=function(e,t){void 0===t&&(t=!1);var n=this._registry.get(e);n&&(t&&n.dispose(),this._registry.delete(e))},e.prototype.lookup=function(e){return this._registry.get(e)||null},e.prototype.has=function(e){return this._registry.has(e)},Object.defineProperty(e.prototype,"count",{get:function(){return this._registry.size},enumerable:!1,configurable:!0}),e.prototype.disposeAll=function(){this._registry.forEach(function(e){e.dispose()}),this._registry.clear()},e.buildAndRegister=function(n,i,r,o){if(void 0===r&&(r=2),void 0===o&&(o=0),!n)return console.warn("[SmoothMeshNormalSystem] buildAndRegister: mesh is null."),null;if(!n.geometry)return console.warn("[SmoothMeshNormalSystem] buildAndRegister: mesh '"+n.name+"' has no geometry. Ensure the mesh has been properly initialized."),null;if(!i)return console.warn("[SmoothMeshNormalSystem] buildAndRegister: mesh '"+n.name+"' has no physicsBody. Ensure RigidbodyPhysics has run first."),null;var a=new t;return a.blendWithPhysicsNormal=Math.max(0,Math.min(1,o)),a.buildFromMesh(n,r)?(e.instance.register(i,a),a):(a.dispose(),null)},e._instance=null,e}();e.SmoothMeshNormalSystem=n}(i||(i={})),function(e){var t;!function(e){e[e.None=0]="None",e[e.ToGamma=1]="ToGamma",e[e.ToLinear=2]="ToLinear"}(t=e.ColorCorrectionMode||(e.ColorCorrectionMode={}));var n=function(n){function i(e,t,i,r){void 0===i&&(i={}),void 0===r&&(r="TOOLKIT.TerrainBuilder");var o=n.call(this,e,t,i,r)||this;return o.detailLayerContainers=[],o.detailMeshSources=new Map,o}return r(i,n),i.prototype.awake=function(){var t=this.getProperties();t&&e.TerrainBuilder.BuildDetailPrototypes(t,this.transform,this.scene,this)},i.prototype.destroy=function(){this.disposeDetailLayers()},i.prototype.disposeDetailLayers=function(){for(var e=0,t=this.detailLayerContainers;e<t.length;e++)t[e].dispose();this.detailLayerContainers=[],this.detailMeshSources.forEach(function(e,t){try{e.dispose()}catch(e){}}),this.detailMeshSources.clear()},i.BuildDetailPrototypes=function(t,n,i,r){if(t&&t.detaillayers&&0!==t.detaillayers.length)for(var o=t.terrainsize?new BABYLON.Vector3(t.terrainsize[0],t.terrainsize[1],t.terrainsize[2]):new BABYLON.Vector3(500,100,500),a=n.position||BABYLON.Vector3.Zero(),s=t.detailobjectdensity||1,l=null!=t.detailbillboardingmode?t.detailbillboardingmode:0,u=null!=t.detailgrassshadowlevel?t.detailgrassshadowlevel:.7,c=null==t.detailgrassreceiveshadows||t.detailgrassreceiveshadows,d=null!=t.wavinggrassamount?t.wavinggrassamount:.5,h=null!=t.wavinggrassspeed?t.wavinggrassspeed:.5,p=null!=t.wavinggrasssize?t.wavinggrasssize:.5,m=t.wavinggrasstint?new BABYLON.Color4(t.wavinggrasstint[0],t.wavinggrasstint[1],t.wavinggrasstint[2],t.wavinggrasstint[3]||1):new BABYLON.Color4(.7,.8,.5,1),f=0;f<t.detaillayers.length;f++){var g=t.detaillayers[f];if(g.detailscattermode=t.detailscattermode,g.isvalid)try{if(g.useprototypemesh)e.TerrainBuilder.BuildMeshDetailLayer(g,o,a,n,i,s,r);else{var v=null!=s?s:1;e.TerrainBuilder.BuildGrassDetailLayer(g,o,a,n,i,v,d,h,p,m,l,u,c,r)}}catch(e){}}},i.BuildMeshDetailLayer=function(t,n,i,r,o,a,s){var l=t.prototypemeshnodeid?o.getNodeById(t.prototypemeshnodeid):null;if(l&&l instanceof BABYLON.Mesh){var u=new BABYLON.TransformNode("DetailLayer_".concat(t.layerindex,"_").concat(t.prototypemeshname),o);u.parent=r,s&&s.detailLayerContainers.push(u);var c=t.detailinstancepatches&&t.detailinstancepatches.length>0?e.TerrainBuilder.GenerateMeshInstancesFromUnityPatches(t,n,i):null;if(null!=c&&0!==c.length){var d=e.TerrainBuilder.CreateDetailThinInstancesFromDensityMap(l,c,u,o,t);d&&s&&s.detailMeshSources.set("layer_".concat(t.layerindex),d)}}},i.BuildGrassDetailLayer=function(t,n,i,r,o,a,s,l,u,c,d,h,p,m){var f=new BABYLON.TransformNode("DetailLayer_".concat(t.layerindex,"_Grass"),o);f.parent=r,m&&m.detailLayerContainers.push(f);var g=e.TerrainBuilder.CreateGrassPrototype(t,f,o,s,l,u,c,d,h);if(g){var v=e.TerrainBuilder.CreateGrassThinInstancesFromDensityMap(g,t,n,i,a,p,f,o);v&&m&&m.detailMeshSources.set("layer_".concat(t.layerindex),v)}else console.warn("Failed to create grass prototype mesh for layer ".concat(t.layerindex))},i.GenerateMeshInstancesFromUnityPatches=function(t,n,i){var r=[],o=t.detailinstancepatches;if(!o||0===o.length)return r;for(var a=0;a<o.length;a++){var s=o[a],l=s&&s.transforms?s.transforms:null;if(l&&!(l.length<6))for(var u=0;u+5<l.length;u+=6){var c=l[u+0],d=l[u+1],h=l[u+2],p=l[u+3],m=l[u+4],f=l[u+5],g=i.x+c-.5*n.x,v=i.z+h-.5*n.z,y=i.y+d,_=new BABYLON.Vector3(g,y,v),S=e.TerrainBuilder.NormalizeRotation(p),A=new BABYLON.Vector3(m,f,m),b=new BABYLON.Color4(1,1,1,1);r.push({position:_,rotation:S,scale:A,color:b})}}return r},i.CreateGrassThinInstancesFromDensityMap=function(t,n,i,r,o,a,s,l){var u;if(!n.densitymap||!n.densitywidth||!n.densityheight)return null;for(var c=n.densitywidth,d=n.densityheight,h=!1===n.usedensityscaling?1:null!=o?o:1,p=null!=n.targetcoverage?n.targetcoverage:null!=n.density?n.density:1,m=Math.max(0,Math.min(1,p)),f="CoverageMode"===(n.detailscattermode||n.detailScatterMode),g=null!=n.positionjitter?n.positionjitter:null!=n.positionsjitter?n.positionsjitter:null,v=null!=g?g:1,y=null!=n.noisespread?n.noisespread:1,_=i.x/c,S=i.z/d,A=n.minwidth||1,b=n.maxwidth||2,M=n.minheight||1,B=n.maxheight||2,C=Math.max(1e-4,.5*(A+b)),T=Math.max(1e-4,.5*(M+B)),x=_*S,I=C*T,O=!n.useprototypemesh&&(n.healthycolor||n.drycolor),L=n.healthycolor?n.healthycolor[0]:.3,w=n.healthycolor?n.healthycolor[1]:.8,N=n.healthycolor?n.healthycolor[2]:.2,P=n.healthycolor&&n.healthycolor[3]||1,R=n.drycolor?n.drycolor[0]:.8,E=n.drycolor?n.drycolor[1]:.7,k=n.drycolor?n.drycolor[2]:.3,D=n.drycolor&&n.drycolor[3]||1,F=null!=n.noiseseed?n.noiseseed:(null!=n.layerindex?n.layerindex:0)+1,U=function(t,n,i,r){var o=Math.floor(1e3*(y||1));return e.TerrainBuilder.HashToUnitFloat(t+o,n-o,i,F,r)},Y=function(e,t,n){if(n<=0)return 0;var i=0;if((i=f?Math.max(0,Math.min(1,n/255))*m*h*(x/I):n*h*m)<=0)return 0;var r=Math.floor(i),o=i-r;return o<=0?r:r+(U(e,t,0,907)<o?1:0)},V=0,G=0;G<d;G++)for(var z=0;z<c;z++){var W=G*c+z;(re=n.densitymap[W]||0)<=0||(V+=Y(z,G,re))}if(V<=0)return null;var H=new Float32Array(3*V),X=new Float32Array(V),K=new Float32Array(V),Q=new Float32Array(V),j=O?new Float32Array(4*V):null,Z=Number.POSITIVE_INFINITY,q=Number.POSITIVE_INFINITY,J=Number.NEGATIVE_INFINITY,$=Number.NEGATIVE_INFINITY,ee=n&&n.cellcornerheights?n.cellcornerheights:null,te=n&&n.cellheights?n.cellheights:null,ne=null!=n.groundOffset?n.groundOffset:.02,ie=0;for(G=0;G<d;G++)for(z=0;z<c;z++){var re;if(W=G*c+z,!((re=n.densitymap[W]||0)<=0)){var oe=Y(z,G,re);if(!(oe<=0))for(var ae=0;ae<oe;ae++){var se=U(z,G,ae,11),le=U(z,G,ae,43),ue=Math.min(Math.max(v,0),1),ce=G*S+(.5+(le-.5)*ue)*S,de=z*_+(.5+(se-.5)*ue)*_,he=r.x+ce-.5*i.z,pe=r.z+de-.5*i.x,me=r.y;if(ee&&ee.length===(c+1)*(d+1)){var fe=(he-(r.x-.5*i.x))/i.x,ge=(pe-(r.z-.5*i.z))/i.z,ve=Math.max(0,Math.min(1,fe))*c,ye=Math.max(0,Math.min(1,ge))*d,_e=ve-(Bt=Math.floor(ve)),Se=ye-(Te=Math.floor(ye)),Ae=Math.max(0,Math.min(c,Bt)),be=Math.max(0,Math.min(c,Bt+1)),Me=Math.max(0,Math.min(d,Te)),Be=Math.max(0,Math.min(d,Te+1)),Ce=c+1;me=(we=(xe=ee[Me*Ce+Ae])+((Ie=ee[Me*Ce+be])-xe)*_e)+((Oe=ee[Be*Ce+Ae])+((Le=ee[Be*Ce+be])-Oe)*_e-we)*Se,me+=ne}else if(te&&te.length===c*d){var Te,xe,Ie,Oe,Le,we;fe=(he-(r.x-.5*i.x))/i.x,ge=(pe-(r.z-.5*i.z))/i.z,ve=Math.max(0,Math.min(1,fe))*c-.5,ye=Math.max(0,Math.min(1,ge))*d-.5,_e=ve-(Bt=Math.floor(ve)),Se=ye-(Te=Math.floor(ye)),Ae=Math.max(0,Math.min(c-1,Bt)),be=Math.max(0,Math.min(c-1,Bt+1)),Me=Math.max(0,Math.min(d-1,Te)),Be=Math.max(0,Math.min(d-1,Te+1)),me=(we=(xe=te[Me*c+Ae])+((Ie=te[Me*c+be])-xe)*_e)+((Oe=te[Be*c+Ae])+((Le=te[Be*c+be])-Oe)*_e-we)*Se,me+=ne;try{var Ne=Math.max(xe,Ie,Oe,Le);Ne-me>.05&&(me=.6*me+.4*Ne)}catch(e){}}else me=r.y;H[0+(Mt=3*ie)]=he,H[Mt+1]=me,H[Mt+2]=pe,he<Z&&(Z=he),pe<q&&(q=pe),he>J&&(J=he),pe>$&&($=pe);var Pe=A+U(z,G,ae,71)*(b-A),Re=(M+U(z,G,ae,17)*(B-M))*e.TerrainBuilder.grassHeightScale;X[ie]=Pe,K[ie]=Re;var Ee=2*Math.PI,ke=0;if("GrassBillboard"!==(n&&n.rendermode?n.rendermode:"GrassBillboard")&&(ke=U(z,G,ae,131)*Ee,e.TerrainBuilder.grassRandomFlip&&U(z,G,ae,997)<.5&&(ke+=Math.PI)),Q[ie]=ke,j){var De=.5;if(n.colorvariationmap&&n.colorvariationmap.length===c*d){var Fe=G*c+z;if(De=n.colorvariationmap[Fe],0===ie&&0===n.layerindex){for(var Ue=1,Ye=0,Ve=0,Ge=0;Ge<n.colorvariationmap.length;Ge++){var ze=n.colorvariationmap[Ge];ze<Ue&&(Ue=ze),ze>Ye&&(Ye=ze),Ve+=ze}Ve/=n.colorvariationmap.length,console.log("[TerrainBuilder] Color variation map stats: min=".concat(Ue.toFixed(3),", max=").concat(Ye.toFixed(3),", avg=").concat(Ve.toFixed(3)))}}else De=U(z,G,ae,101),0===ie&&0===n.layerindex&&console.warn("[TerrainBuilder] No color variation map found for layer ".concat(n.layerindex,". Using per-instance random. Export colorvariationmap from Unity for exact matching."));var We=L+(R-L)*(De=1-(De=Math.min(1,Math.max(0,De)))),He=w+(E-w)*De,Xe=N+(k-N)*De,Ke=P+(D-P)*De;j[0+(Lt=4*ie)]=We,j[Lt+1]=He,j[Lt+2]=Xe,j[Lt+3]=Ke}ie++}}}var Qe=Math.min(ie,V);if(Qe<=0)return null;var je=null!==(u=e.TerrainBuilder.detailChunkMode)&&void 0!==u?u:0,Ze=Math.max(1,e.TerrainBuilder.detailChunkTargetInstances||8e3),qe=Math.max(1e-4,e.TerrainBuilder.detailChunkWorldSize||32),Je=Math.max(1,e.TerrainBuilder.detailChunkMaxChunksPerAxis||64),$e=Math.max(1,e.TerrainBuilder.detailChunkMaxTotalChunks||256),et=Math.max(1e-4,J-Z),tt=Math.max(1e-4,$-q),nt=1,it=1;if(0===je){if(nt=Math.ceil(et/qe),it=Math.ceil(tt/qe),nt=Math.max(1,Math.min(Je,nt)),it=Math.max(1,Math.min(Je,it)),(lt=nt*it)>$e){var rt=Math.sqrt(lt/$e);nt=Math.max(1,Math.min(Je,Math.ceil(nt/rt))),it=Math.max(1,Math.min(Je,Math.ceil(it/rt)))}}else{var ot=Math.max(1,Math.ceil(Qe/Ze)),at=Math.ceil(Math.sqrt(ot)),st=Math.max(1,Math.floor(Math.sqrt($e)));at=Math.max(1,Math.min(Je,Math.min(st,at)));var lt,ut=et/tt;nt=at,it=at,ut>1.5?(nt=Math.min(Je,Math.ceil(at*Math.sqrt(ut))),it=Math.max(1,Math.ceil(at/Math.sqrt(ut)))):ut<1/1.5&&(it=Math.min(Je,Math.ceil(at*Math.sqrt(1/ut))),nt=Math.max(1,Math.ceil(at/Math.sqrt(1/ut)))),(lt=nt*it)>$e&&(rt=Math.sqrt(lt/$e),nt=Math.max(1,Math.min(Je,Math.ceil(nt/rt))),it=Math.max(1,Math.min(Je,Math.ceil(it/rt))),lt=nt*it)}var ct=et/nt,dt=tt/it,ht=new BABYLON.TransformNode("".concat(t.name,"_Chunks_L").concat(n.layerindex),l);ht.parent=s;try{t.setEnabled(!1),t.isVisible=!1}catch(e){}var pt=new Map;for(ae=0;ae<Qe;ae++){var mt=H[0+(Mt=3*ae)],ft=H[Mt+2];(Bt=Math.floor((mt-Z)/ct))<0&&(Bt=0),(Ct=Math.floor((ft-q)/dt))<0&&(Ct=0),Bt>=nt&&(Bt=nt-1),Ct>=it&&(Ct=it-1);var gt=Bt+Ct*nt;pt.set(gt,(pt.get(gt)||0)+1)}var vt=new Map;pt.forEach(function(e,t){var n=new Float32Array(16*e),i=j?new Float32Array(4*e):null;vt.set(t,{count:e,write:0,matrices:n,colors:i})});var yt=new BABYLON.Matrix,_t=new BABYLON.Vector3(1,1,1),St=new BABYLON.Vector3(0,0,0),At=new BABYLON.Quaternion,bt=BABYLON.Axis.Y;for(ae=0;ae<Qe;ae++){mt=H[0+(Mt=3*ae)];var Mt,Bt,Ct,Tt=H[Mt+1];ft=H[Mt+2],(Bt=Math.floor((mt-Z)/ct))<0&&(Bt=0),(Ct=Math.floor((ft-q)/dt))<0&&(Ct=0),Bt>=nt&&(Bt=nt-1),Ct>=it&&(Ct=it-1),gt=Bt+Ct*nt;var xt=vt.get(gt);if(xt){var It=xt.write++;St.x=mt,St.y=Tt,St.z=ft;var Ot=X[ae];if(_t.x=Ot,_t.y=K[ae],_t.z=Ot,BABYLON.Quaternion.RotationAxisToRef(bt,Q[ae],At),BABYLON.Matrix.ComposeToRef(_t,At,St,yt),yt.copyToArray(xt.matrices,16*It),xt.colors&&j){var Lt=4*ae,wt=(We=Math.min(1,j[Lt+0]),He=Math.min(1,j[Lt+1]),Xe=Math.min(1,j[Lt+2]),Ke=j[Lt+3],4*It);xt.colors[wt+0]=e.TerrainBuilder.DoColorCorrection(We,e.TerrainBuilder.grassColorCorrectionMode),xt.colors[wt+1]=e.TerrainBuilder.DoColorCorrection(He,e.TerrainBuilder.grassColorCorrectionMode),xt.colors[wt+2]=e.TerrainBuilder.DoColorCorrection(Xe,e.TerrainBuilder.grassColorCorrectionMode),xt.colors[wt+3]=Ke}}}var Nt=null,Pt=0;return vt.forEach(function(i,r){if(i&&!(i.count<=0)){var o=function(i,r){var o,s,u,c,d,h;if(!i||i.count<=0)return null;var p=r%nt,m=Math.floor(r/nt),f="".concat(t.name,"_L").concat(n.layerindex,"_C").concat(p,"_").concat(m,"_").concat(Pt),g=t.clone(f,ht);if(!g)return null;try{g.makeGeometryUnique()}catch(e){}g.setEnabled(!0),g.isVisible=!0,g.applyFog=e.TerrainBuilder.grassReceiveFog,g.receiveShadows=a,g.thinInstanceEnablePicking=!1;try{null===(s=(o=g).thinInstanceSetBuffer)||void 0===s||s.call(o,"matrix",null,16,!0)}catch(e){}try{null===(c=(u=g).thinInstanceSetBuffer)||void 0===c||c.call(u,"color",null,4,!0)}catch(e){}g.thinInstanceSetBuffer("matrix",i.matrices,16,!0),i.colors&&(g.thinInstanceSetBuffer("color",i.colors,4,!0),g.useVertexColors=!0,g.hasVertexAlpha=!0);try{null===(h=(d=g).thinInstanceRefreshBoundingInfo)||void 0===h||h.call(d,!0)}catch(e){}try{var v=g.material;if(v&&"function"==typeof v.setFloatValue){var y=null!=n.maxdistance?n.maxdistance:0;v.setFloatValue("g_maxDistance",y);var _=y>0?Math.max(0,.75*y):0;v.setFloatValue("g_fadeStart",_)}}catch(e){}try{l&&l.lights&&l.lights.forEach(function(t){try{var n=t.getShadowGenerator?t.getShadowGenerator():null;if(n){var i=n.getShadowMap?n.getShadowMap():null;if(i)if(e.TerrainBuilder.grassCastShadows)i.renderList||(i.renderList=[]),-1===i.renderList.indexOf(g)&&i.renderList.push(g);else if(i.renderList){var r=i.renderList.indexOf(g);-1!==r&&i.renderList.splice(r,1)}}}catch(e){}})}catch(e){}return g.metadata=g.metadata||{},g.metadata.toolkit=g.metadata.toolkit||{},g.metadata.toolkit.castRealtimeShadow=e.TerrainBuilder.grassCastShadows,g.metadata.toolkit.terrainDetailLayer=n.layerindex,g.metadata.toolkit.terrainDetailChunked=!0,g}(i,r);o&&(Pt++,Nt||(Nt=o))}}),Nt||(ht.dispose(),null)},i.CreateDetailThinInstancesFromDensityMap=function(t,n,i,r,o){var a,s;if(!n||0===n.length)return null;var l=t;try{var u=t.clone("".concat(t.name,"_DetailSourceNorm_L").concat(o.layerindex),i,!1,!1);if(u){try{u.makeGeometryUnique()}catch(e){}try{u.bakeCurrentTransformIntoVertices()}catch(e){}u.position.set(0,0,0),u.rotationQuaternion=BABYLON.Quaternion.Identity(),u.scaling.set(1,1,1),u.setEnabled(!1),u.isVisible=!1,l=u}}catch(e){l=t}for(var c=!!o.useprototypemesh,d=c?null!==(a=e.TerrainBuilder.meshDetailChunkMode)&&void 0!==a?a:1:null!==(s=e.TerrainBuilder.detailChunkMode)&&void 0!==s?s:0,h=Math.max(1,(c?e.TerrainBuilder.meshDetailChunkTargetInstances:e.TerrainBuilder.detailChunkTargetInstances)||8e3),p=Math.max(1e-4,(c?e.TerrainBuilder.meshDetailChunkWorldSize:e.TerrainBuilder.detailChunkWorldSize)||32),m=Math.max(1,e.TerrainBuilder.detailChunkMaxChunksPerAxis||64),f=Math.max(1,e.TerrainBuilder.detailChunkMaxTotalChunks||256),g=Number.POSITIVE_INFINITY,v=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,_=Number.NEGATIVE_INFINITY,S=0;S<n.length;S++){var A=n[S].position;A.x<g&&(g=A.x),A.z<v&&(v=A.z),A.x>y&&(y=A.x),A.z>_&&(_=A.z)}var b=Math.max(1e-4,y-g),M=Math.max(1e-4,_-v),B=1,C=1;if(0===d){if(B=Math.ceil(b/p),C=Math.ceil(M/p),B=Math.max(1,Math.min(m,B)),C=Math.max(1,Math.min(m,C)),(L=B*C)>f){var T=Math.sqrt(L/f);B=Math.max(1,Math.min(m,Math.ceil(B/T))),C=Math.max(1,Math.min(m,Math.ceil(C/T)))}}else{var x=Math.max(1,Math.ceil(n.length/h)),I=Math.ceil(Math.sqrt(x)),O=Math.max(1,Math.floor(Math.sqrt(f)));I=Math.max(1,Math.min(m,Math.min(O,I)));var L,w=b/M;B=I,C=I,w>1.5?(B=Math.min(m,Math.ceil(I*Math.sqrt(w))),C=Math.max(1,Math.ceil(I/Math.sqrt(w)))):w<1/1.5&&(C=Math.min(m,Math.ceil(I*Math.sqrt(1/w))),B=Math.max(1,Math.ceil(I/Math.sqrt(1/w)))),(L=B*C)>f&&(T=Math.sqrt(L/f),B=Math.max(1,Math.min(m,Math.ceil(B/T))),C=Math.max(1,Math.min(m,Math.ceil(C/T))),L=B*C)}var N=b/B,P=M/C,R=new BABYLON.TransformNode("".concat(t.name,"_Chunks_L").concat(o.layerindex),r);R.parent=i;var E=new Map;for(S=0;S<n.length;S++){var k=n[S],D=Math.floor((k.position.x-g)/N),F=Math.floor((k.position.z-v)/P);D<0&&(D=0),F<0&&(F=0),D>=B&&(D=B-1),F>=C&&(F=C-1);var U=D+F*B,Y=E.get(U);Y?Y.push(k):E.set(U,[k])}try{t.setEnabled(!1),t.isVisible=!1}catch(e){}var V=!o.useprototypemesh&&(o.healthycolor||o.drycolor),G=null,z=0;return E.forEach(function(n,i){if(n&&0!==n.length){var a=i%B,s=Math.floor(i/B),u=function(t,n){var i,a,s,u,c,d;if(!t||0===t.length)return null;var h=l.clone(n,R);if(!h)return null;try{h.makeGeometryUnique()}catch(e){}h.setEnabled(!0),h.isVisible=!0,h.receiveShadows=!1,h.applyFog=!0,h.thinInstanceEnablePicking=!1;for(var p=new Float32Array(16*t.length),m=V?new Float32Array(4*t.length):null,f=new BABYLON.Matrix,g=new BABYLON.Quaternion,v=0;v<t.length;v++){var y=t[v],_=16*v,S=y.scale;if(BABYLON.Quaternion.RotationAxisToRef(BABYLON.Axis.Y,y.rotation,g),BABYLON.Matrix.ComposeToRef(S,g,y.position,f),f.copyToArray(p,_),m){var A=4*v,b=Math.min(1,y.color.r),M=Math.min(1,y.color.g),B=Math.min(1,y.color.b);m[A]=e.TerrainBuilder.DoColorCorrection(b,e.TerrainBuilder.grassColorCorrectionMode),m[A+1]=e.TerrainBuilder.DoColorCorrection(M,e.TerrainBuilder.grassColorCorrectionMode),m[A+2]=e.TerrainBuilder.DoColorCorrection(B,e.TerrainBuilder.grassColorCorrectionMode),m[A+3]=y.color.a}}try{null===(a=(i=h).thinInstanceSetBuffer)||void 0===a||a.call(i,"matrix",null,16,!0)}catch(e){}try{null===(u=(s=h).thinInstanceSetBuffer)||void 0===u||u.call(s,"color",null,4,!0)}catch(e){}h.thinInstanceSetBuffer("matrix",p,16,!0),m&&(h.thinInstanceSetBuffer("color",m,4,!0),h.useVertexColors=!0,h.hasVertexAlpha=!0);try{null===(d=(c=h).thinInstanceRefreshBoundingInfo)||void 0===d||d.call(c,!0)}catch(e){}try{var C=h.material;if(C&&"function"==typeof C.setFloatValue){var T=null!=o.maxdistance?o.maxdistance:0;C.setFloatValue("g_maxDistance",T);var x=T>0?Math.max(0,.75*T):0;C.setFloatValue("g_fadeStart",x)}}catch(e){}try{r&&r.lights&&r.lights.forEach(function(t){try{var n=t.getShadowGenerator?t.getShadowGenerator():null;if(n){var i=n.getShadowMap?n.getShadowMap():null;if(i)if(e.TerrainBuilder.grassCastShadows)i.renderList||(i.renderList=[]),-1===i.renderList.indexOf(h)&&i.renderList.push(h);else if(i.renderList){var r=i.renderList.indexOf(h);-1!==r&&i.renderList.splice(r,1)}}}catch(e){}})}catch(e){}return h.metadata=h.metadata||{},h.metadata.toolkit=h.metadata.toolkit||{},h.metadata.toolkit.castRealtimeShadow=e.TerrainBuilder.grassCastShadows,h.metadata.toolkit.terrainDetailLayer=o.layerindex,h.metadata.toolkit.terrainDetailChunked=!0,h}(n,"".concat(t.name,"_L").concat(o.layerindex,"_C").concat(a,"_").concat(s,"_").concat(z));u&&(z++,G||(G=u))}}),G||(R.dispose(),null)},i.CreateGrassPrototype=function(t,n,i,r,o,a,s,l,u){var c=t.rendermode||"GrassBillboard",d=(null!=t.prototypetexture&&null!=t.prototypetexture.filename&&t.prototypetexture.filename,((t.minwidth||1)+(t.maxwidth||2))/2),h=((t.minheight||1)+(t.maxheight||2))/2*e.TerrainBuilder.grassHeightScale,p=null;if("GrassBillboard"===c?p=e.TerrainBuilder.CreateSingleQuadBillboard("GrassBillboard_".concat(t.layerindex),d,h,i):"Grass"===c?p=e.TerrainBuilder.CreateCrossQuadGrass("GrassCross_".concat(t.layerindex),d,h,i):"VertexLit"===c&&((p=BABYLON.MeshBuilder.CreatePlane("GrassPlane_".concat(t.layerindex),{width:d,height:h},i)).rotation.x=Math.PI/2),!p)return null;p.parent=n,p.isVisible=!1,p.applyFog=!0,"VertexLit"!==c&&e.TerrainBuilder.ApplyUpNormals(p);var m="GrassBillboard"===c?new e.GrassBillboardMaterial("GrassBillboardMaterial_".concat(t.layerindex),i):new e.GrassStandardMaterial("GrassStandardMaterial_".concat(t.layerindex),i);if(null!=t.prototypetexture&&null!=t.prototypetexture.filename&&""!==t.prototypetexture.filename){var f="scenes/".concat(t.prototypetexture.filename),g=new BABYLON.Texture(f,i);g.hasAlpha=!0,g.gammaSpace=!0,g.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE),g.anisotropicFilteringLevel=4,g.wrapU=BABYLON.Texture.CLAMP_ADDRESSMODE,g.wrapV=BABYLON.Texture.CLAMP_ADDRESSMODE,(m instanceof e.GrassStandardMaterial||m instanceof e.GrassBillboardMaterial)&&(m.diffuseTexture=g,m.useAlphaFromDiffuseTexture=!0),m.alphaCutOff=.3;try{m.setFloatValue("g_alphaCutoff",null!=m.alphaCutOff?m.alphaCutOff:.3)}catch(e){}}else m.alphaCutOff=.3,m.emissiveColor=new BABYLON.Color3(0,0,0),t&&t.healthycolor&&(m instanceof e.GrassStandardMaterial||m instanceof e.GrassBillboardMaterial)&&(m.diffuseColor=new BABYLON.Color3(e.TerrainBuilder.DoColorCorrection(t.healthycolor[0],e.TerrainBuilder.grassColorCorrectionMode),e.TerrainBuilder.DoColorCorrection(t.healthycolor[1],e.TerrainBuilder.grassColorCorrectionMode),e.TerrainBuilder.DoColorCorrection(t.healthycolor[2],e.TerrainBuilder.grassColorCorrectionMode)));if(m instanceof e.GrassStandardMaterial){if(m.diffuseTexture){m.diffuseColor=new BABYLON.Color3(1,1,1);try{m.setFloatValue("g_alphaCutoff",null!=m.alphaCutOff?m.alphaCutOff:.3)}catch(e){}}}else if(m instanceof e.GrassBillboardMaterial&&m.diffuseTexture){m.diffuseColor=new BABYLON.Color3(1,1,1);try{m.setFloatValue("g_alphaCutoff",null!=m.alphaCutOff?m.alphaCutOff:.3)}catch(e){}}return m.roughness=1,m.twoSidedLighting=!0,m.backFaceCulling=!1,m.emissiveColor=new BABYLON.Color3(0,0,0),m.transparencyMode=BABYLON.Material.MATERIAL_ALPHATEST,m.separateCullingPass=!0,p.material=m,m.setFloatValue("g_maxDistance",0),m.setFloatValue("g_fadeStart",0),m.setFloatValue("g_windAmount",null!=r?r:.5),m.setFloatValue("g_waveSpeed",null!=o?o:.5),m.setFloatValue("g_waveSize",null!=a?a:.5),m.setVector4Value("g_windTint",new BABYLON.Vector4(s.r,s.g,s.b,s.a)),m.setShadowIntensity(u),m instanceof e.GrassBillboardMaterial&&m.setSphericalBillboardEnabled(0===l),p},i.CreateSingleQuadBillboard=function(e,t,n,i){var r=[],o=[],a=[],s=[],l=t/2;r.push(-l,0,0,l,0,0,l,n,0,-l,n,0),o.push(0,1,2,0,2,3),s.push(0,0,1,0,1,1,0,1);for(var u=0;u<4;u++)a.push(0,1,0);var c=new BABYLON.Mesh(e,i),d=new BABYLON.VertexData;return d.positions=r,d.indices=o,d.normals=a,d.uvs=s,d.applyToMesh(c),c},i.CreateCrossQuadGrass=function(e,t,n,i){var r=[],o=[],a=[],s=[],l=t/2;r.push(-l,0,0,l,0,0,l,n,0,-l,n,0),r.push(0,0,-l,0,0,l,0,n,l,0,n,-l),o.push(0,1,2,0,2,3,4,5,6,4,6,7),s.push(0,0,1,0,1,1,0,1,0,0,1,0,1,1,0,1);for(var u=0;u<8;u++)a.push(0,1,0);var c=new BABYLON.Mesh(e,i),d=new BABYLON.VertexData;return d.positions=r,d.indices=o,d.normals=a,d.uvs=s,d.applyToMesh(c),c},i.ApplyUpNormals=function(e){var t=e.getVerticesData(BABYLON.VertexBuffer.PositionKind);if(t){for(var n=new Array(t.length),i=0;i<t.length;i+=3)n[i]=0,n[i+1]=1,n[i+2]=0;e.setVerticesData(BABYLON.VertexBuffer.NormalKind,n,!1)}},i.HashToUnitFloat=function(e,t,n,i,r){var o=374761393*e+668265263*t+1442695041*n+374761393*i+374761393*r;return o=1274126177*(o^o>>13),((o^=o>>16)>>>0)/4294967296},i.NormalizeRotation=function(e){var t=2*Math.PI,n=e%t;return n<0&&(n+=t),n},i.DoColorCorrection=function(n,i){switch(i){case t.ToGamma:return e.TerrainBuilder.LinearToGamma(n);case t.ToLinear:return e.TerrainBuilder.GammaToLinear(n);case t.None:default:return n}},i.GammaToLinear=function(e){var t=Math.max(0,Math.min(1,e));return Math.pow(t,2.2)},i.LinearToGamma=function(e){var t=Math.max(0,Math.min(1,e));return Math.pow(t,1/2.2)},i.grassHeightScale=.85,i.grassRandomFlip=!1,i.grassCastShadows=!1,i.grassReceiveFog=!0,i.grassColorCorrectionMode=1,i.detailChunkMode=0,i.detailChunkTargetInstances=8e3,i.detailChunkWorldSize=32,i.detailChunkMaxChunksPerAxis=64,i.detailChunkMaxTotalChunks=256,i.meshDetailChunkMode=1,i.meshDetailChunkTargetInstances=2e4,i.meshDetailChunkWorldSize=64,i}(e.ScriptComponent);e.TerrainBuilder=n,e.SceneManager.RegisterClass("TOOLKIT.TerrainBuilder",n)}(i||(i={})),function(e){var t=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return r(t,e),t}(BABYLON.GUI.Slider);e.UnitySlider=t;var n=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._direction="LeftToRight",t}return r(t,e),Object.defineProperty(t.prototype,"direction",{get:function(){return this._direction},set:function(e){this._direction=e,this._markAsDirty()},enumerable:!1,configurable:!0}),t.prototype._getThumbPosition=function(){var e=(this.value-this.minimum)/(this.maximum-this.minimum),t=this.isVertical?this._currentMeasure.height-this._effectiveThumbThickness:this._currentMeasure.width-this._effectiveThumbThickness,n=e*t;return"RightToLeft"!==this._direction||this.isVertical?"TopToBottom"===this._direction&&this.isVertical&&(n=t-n):n=t-n,n},t.prototype.serialize=function(t){e.prototype.serialize.call(this,t),t.direction=this._direction},t.prototype._parseFromContent=function(t,n){e.prototype._parseFromContent.call(this,t,n),t.direction&&(this._direction=t.direction)},t}(BABYLON.GUI.ScrollBar);e.UnityScrollBar=n;var i=function(e){function t(t){var n=e.call(this,t||"dropdownMenu")||this;n._button=null,n._popup=null,n._options=[],n._selectedIndex=0,n.width="150px",n.height="30px",n.thickness=1,n.cornerRadius=3,n.color="#333333",n.background="transparent",console.warn("DropdownMenu is a custom control and may not be fully supported in all environments."),n._button=BABYLON.GUI.Button.CreateSimpleButton((n.name||"")+"_btn",""),n._button.width="100%",n._button.height="100%",n._button.horizontalAlignment=BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT,n._button.verticalAlignment=BABYLON.GUI.Control.VERTICAL_ALIGNMENT_CENTER,n._button.cornerRadius=3,n._button.thickness=0,n._button.color="#000000",n._button.background="#ffffff00";var i=new BABYLON.GUI.TextBlock((n.name||"")+"_label","");i.textHorizontalAlignment=BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT,i.paddingLeft="8px",i.resizeToFit=!1,i.text="",i.color="#000000",i.fontSize="14px",i.textWrapping=!0,n._button.addControl(i);var r=new BABYLON.GUI.TextBlock((n.name||"")+"_arrow","▼");r.width="24px",r.textHorizontalAlignment=BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER,r.horizontalAlignment=BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT,r.paddingRight="6px",r.color="#222222",n._button.addControl(r),n._popup=new BABYLON.GUI.Container((n.name||"")+"_popup"),n._popup.width="150px",n._popup.isVisible=!1,n._popup.background="#ffffff",n._popup.thickness=1,n._popup.cornerRadius=3,n._popup.zIndex=1e3,n._popup.verticalAlignment=BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;var o=new BABYLON.GUI.StackPanel((n.name||"")+"_stack");return o.isVertical=!0,n._popup.addControl(o),n._button.onPointerUpObservable.add(function(){n._popup&&(n._popup.isVisible=!n._popup.isVisible)}),n.addControl(n._button),n.addControl(n._popup),n}return r(t,e),Object.defineProperty(t.prototype,"selectedIndex",{get:function(){return this._selectedIndex},set:function(e){this._selectedIndex=e,this._updateSelectedText()},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"options",{set:function(e){this._options=e||[],this._rebuildOptions()},enumerable:!1,configurable:!0}),t.prototype._updateSelectedText=function(){if(this._button){var e=this._button.getChildByName((this.name||"")+"_label");if(e){var t=this._options[this._selectedIndex];e.text=t?t.text:""}}},t.prototype._rebuildOptions=function(){var e=this;if(this._popup){this._popup.dispose(),this._popup=new BABYLON.GUI.Container((this.name||"")+"_popup"),this._popup.width="150px",this._popup.isVisible=!1,this._popup.background="#ffffff",this._popup.thickness=1,this._popup.cornerRadius=3,this._popup.zIndex=1e3,this._popup.verticalAlignment=BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP;var t=new BABYLON.GUI.StackPanel((this.name||"")+"_stack");t.isVertical=!0,this._popup.addControl(t);for(var n=function(n){var r=i._options[n],o=BABYLON.GUI.Button.CreateSimpleButton((i.name||"")+"_opt_"+n,r.text||"");o.width="100%",o.height="28px",o.thickness=0,o.cornerRadius=0,o.color="#000000",o.horizontalAlignment=BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT,o.onPointerUpObservable.add(function(){e.selectedIndex=n,e._popup&&(e._popup.isVisible=!1),e.onSelectionChanged&&e.onSelectionChanged(n)}),t.addControl(o)},i=this,r=0;r<this._options.length;r++)n(r);this.addControl(this._popup),this._updateSelectedText()}},t.prototype.serialize=function(){var e={};try{var t=BABYLON.GUI.Container.prototype.serialize;"function"==typeof t&&(e=t.call(this)||{})}catch(t){e={}}return(e=e||{}).className="UnityDropdownMenu",e.options=this._options.map(function(e){return{text:e.text,imageSource:e.imageSource}}),e.selectedIndex=this._selectedIndex,e},t.Parse=function(e,n,i){var r=new t(e.name||"dropdownMenu");try{Array.isArray(e.options)&&(r.options=e.options.map(function(e){return{text:e.text||"",imageSource:e.imageSource}})),"number"==typeof e.selectedIndex&&(r.selectedIndex=e.selectedIndex)}catch(e){console.warn(e)}return r},t}(BABYLON.GUI.Container);e.UnityDropdownMenu=i,e.SceneManager.RegisterClass("BABYLON.GUI.UnitySlider",t),e.SceneManager.RegisterClass("BABYLON.GUI.UnityScrollBar",n),e.SceneManager.RegisterClass("BABYLON.GUI.UnityDropdownMenu",i)}(i||(i={})),function(e){var t=function(t){function n(e,n,i,r){return void 0===i&&(i={}),void 0===r&&(r="TOOLKIT.UserInterface"),t.call(this,e,n,i,r)||this}return r(n,t),n.prototype.start=function(){return a(this,void 0,void 0,function(){var t,n,i,r,o;return s(this,function(a){switch(a.label){case 0:return null==(t=this.getProperty("gui"))?[3,2]:(n=e.SceneManager.GetRootUrl(this.scene)||"",i=!1,r=!0,o=this.extractRequiredFonts(t),[4,this.loadRequiredFonts(o,n)]);case 1:if(a.sent(),this.parseNodeObject(t.root||t.controls,n),e.UserInterface.LoadForegroundInterfaceData(this.scene,t,BABYLON.Texture.BILINEAR_SAMPLINGMODE,r,null,i),e.UserInterface.OnInterfaceLoaded&&e.UserInterface.OnInterfaceLoaded.hasObservers())try{e.UserInterface.OnInterfaceLoaded.notifyObservers(this.transform.name)}catch(e){console.warn(e instanceof Error?e.message:String(e))}a.label=2;case 2:return[2]}})})},n.prototype.parseNodeObject=function(e,t){var i=this;if(null!=e&&(this.processNodeSources(e,t),null!=e.children&&Array.isArray(e.children)&&e.children.forEach(function(e){i.parseNodeObject(e,t)}),n.OnParseNodeObject&&n.OnParseNodeObject.hasObservers()))try{n.OnParseNodeObject.notifyObservers(e)}catch(e){console.warn(e instanceof Error?e.message:String(e))}},n.prototype.processNodeSources=function(e,t){if(null!=e&&"object"==typeof e){if(e.source&&"string"==typeof e.source&&e.source.startsWith("assets/")){var n=t&&!t.endsWith("/")?t+"/":t;e.source,e.source=n+e.source}for(var i in e)e.hasOwnProperty(i)&&"object"==typeof e[i]&&null!==e[i]&&"children"!==i&&this.processNodeSources(e[i],t)}},n.prototype.extractRequiredFonts=function(e){var t=new Set,n=function(e){e.fontFamily&&"Arial"!==e.fontFamily&&"sans-serif"!==e.fontFamily&&t.add(e.fontFamily),e.children&&Array.isArray(e.children)&&e.children.forEach(n)};return e.root&&n(e.root),Array.from(t)},n.prototype.loadRequiredFonts=function(e,t){return a(this,void 0,void 0,function(){var n,i,r=this;return s(this,function(o){switch(o.label){case 0:return e&&0!==e.length?[4,this.loadFontManifest(t)]:[2];case 1:return n=o.sent(),i=e.map(function(e){return r.loadSingleFont(e,n,t)}),[4,Promise.allSettled(i)];case 2:return o.sent().forEach(function(t,n){"fulfilled"===t.status||console.warn("✗ Font failed: ".concat(e[n]),t.reason)}),[4,document.fonts.ready];case 3:return o.sent(),[2]}})})},n.prototype.loadFontManifest=function(e){return a(this,void 0,void 0,function(){var t;return s(this,function(n){switch(n.label){case 0:return n.trys.push([0,4,,5]),[4,fetch(e+"font-manifest.json")];case 1:return(t=n.sent()).ok?[4,t.json()]:[3,3];case 2:return[2,n.sent()];case 3:return[3,5];case 4:return n.sent(),console.warn("No Font Manifest Found, Using Web Fonts Fallback"),[3,5];case 5:return[2,[]]}})})},n.prototype.loadSingleFont=function(e,t,n){return a(this,void 0,void 0,function(){var i;return s(this,function(r){switch(r.label){case 0:return(i=t.find(function(t){return t.family===e}))?[4,this.loadUnityFont(i,n)]:[3,2];case 1:case 3:return r.sent(),[2];case 2:return this.isGoogleFont(e)?[4,this.loadGoogleFont(e)]:[3,4];case 4:return this.isSystemFontAvailable(e)||console.warn("Font Not Available: ".concat(e)),[2]}})})},n.prototype.loadUnityFont=function(e,t){return a(this,void 0,void 0,function(){var n,i,r;return s(this,function(o){switch(o.label){case 0:n=t+e.path,o.label=1;case 1:return o.trys.push([1,3,,4]),[4,(i=new FontFace(e.family,"url('".concat(n,"') format('truetype')"),{style:e.style||"normal",weight:e.weight||"normal",display:"swap"})).load()];case 2:return o.sent(),document.fonts.add(i),[3,4];case 3:return r=o.sent(),console.warn("Failed To Load Unity Font: ".concat(e.family),r),[3,4];case 4:return[2]}})})},n.prototype.loadGoogleFont=function(e){return a(this,void 0,void 0,function(){return s(this,function(t){return[2,new Promise(function(t,n){var i=document.createElement("link");i.rel="stylesheet",i.href="https://fonts.googleapis.com/css2?family=".concat(encodeURIComponent(e),":wght@400;700&display=swap"),i.onload=function(){t()},i.onerror=function(){return n(new Error("Failed To Load Google Font: ".concat(e)))},document.head.appendChild(i)})]})})},n.prototype.isGoogleFont=function(e){return["Roboto","Open Sans","Lato","Montserrat","Source Sans Pro","Oswald","Raleway","Poppins","Merriweather","Nunito","Ubuntu","Playfair Display","Work Sans","Fira Sans","Noto Sans","PT Sans","Crimson Text","Inter"].includes(e)},n.prototype.isSystemFontAvailable=function(e){var t=document.createElement("canvas").getContext("2d"),n="mmmmmmmmmmlli";t.font="72px monospace";var i=t.measureText(n).width;return t.font='72px "'.concat(e,'", monospace'),t.measureText(n).width!==i},n.CreateInternalUserInterface=function(e,t,n,i){return 1==t?(e._foregroundTexture=BABYLON.GUI.AdvancedDynamicTexture.CreateFullscreenUI("Default-Screen-UI",!0,e,n,i),e._foregroundTexture):(e._backgroundTexture=BABYLON.GUI.AdvancedDynamicTexture.CreateFullscreenUI("Background-Screen-UI",!1,e,n,i),e._backgroundTexture)},n.LoadForegroundInterfaceData=function(t,n,i,r,o,a){if(null==t._foregroundTexture&&(t._foregroundTexture=e.UserInterface.CreateInternalUserInterface(t,!0,i,a)),null!=n){var s=t._foregroundTexture&&null!=t._foregroundTexture._textureInitialized&&!0===t._foregroundTexture._textureInitialized;e.UserInterface.ParseUserInterfaceObject(t,t._foregroundTexture,n,r,o,s),t._foregroundTexture._textureInitialized=!0}t.getEngine().resize(!0)},n.LoadBackgroundInterfaceData=function(t,n,i,r,o,a){if(null==t._backgroundTexture&&(t._backgroundTexture=e.UserInterface.CreateInternalUserInterface(t,!1,i,a)),null!=n){var s=t._backgroundTexture&&null!=t._backgroundTexture._textureInitialized&&!0===t._backgroundTexture._textureInitialized;e.UserInterface.ParseUserInterfaceObject(t,t._backgroundTexture,n,r,o,s),t._backgroundTexture._textureInitialized=!0}t.getEngine().resize(!0)},n.ParseUserInterfaceObject=function(t,n,i,r,o,a){if(i&&n){e.UserInterface.FixUserInterfacePrototypes();var s=t.getEngine().getHardwareScalingLevel()||1,l=Number.isFinite(+i.canvasScalerMode)?+i.canvasScalerMode:1,u=Number.isFinite(+i.renderScaleFactor)&&+i.renderScaleFactor>0?+i.renderScaleFactor:1,c=Number.isFinite(+i.fallbackScreenDpi)&&+i.fallbackScreenDpi>0?+i.fallbackScreenDpi:72,d=Number.isFinite(+i.defaultSpriteDpi)&&+i.defaultSpriteDpi>0?+i.defaultSpriteDpi:72,h=Number.isFinite(+i.referencePixelsPerUnit)&&+i.referencePixelsPerUnit>0?+i.referencePixelsPerUnit:100,p=Number.isFinite(+i.pixelScaleFactor)&&+i.pixelScaleFactor>0?+i.pixelScaleFactor:1,m=e.UserInterface.PHYSICAL_SIZE_POINT_FACTOR,f=Number(i.width),g=Number(i.height),v=Number.isFinite(f)&&f>0&&Number.isFinite(g)&&g>0,y=v?f:1920,_=v?g:1080,S=function(e){e.width="100%",e.height="100%",e.left="0px",e.top="0px",e.horizontalAlignment=BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_LEFT,e.verticalAlignment=BABYLON.GUI.Control.VERTICAL_ALIGNMENT_TOP},A=function(e){return JSON.parse(JSON.stringify(e))},b=function(e){if("number"==typeof e)return Number.isFinite(e);if("string"==typeof e){var t=e.trim().toLowerCase();return!t.endsWith("%")&&(t.endsWith("px")?Number.isFinite(parseFloat(t)):/^-?\d+(\.\d+)?$/.test(t))}return!1},M=function(e,t){if(e&&"object"==typeof e){var n=new Set(["left","top","width","height","minWidth","minHeight","maxWidth","maxHeight","marginLeft","marginRight","marginTop","marginBottom","paddingLeft","paddingRight","paddingTop","paddingBottom","fontSize","thickness","cornerRadius","shadowOffsetX","shadowOffsetY","shadowBlur","linkOffsetX","linkOffsetY"]),i=new Set(["cornerRadiusX","cornerRadiusY","cornerRadiusZ","cornerRadiusW"]),r=function(e){if(null==e)return e;if("number"==typeof e)return Math.round(e*t);if("string"==typeof e){var n=e.trim();if(n.endsWith("%"))return e;if(n.toLowerCase().endsWith("px")){var i=parseFloat(n);return Number.isFinite(i)?"".concat(Math.round(i*t),"px"):e}return/^-?\d+(\.\d+)?$/.test(n)?(i=parseFloat(n),Number.isFinite(i)?"".concat(Math.round(i*t),"px"):e):e}if("object"==typeof e){for(var o=0,a=["left","top","right","bottom","x","y","w","h","value"];o<a.length;o++){var s=a[o];s in e&&b(e[s])&&(e[s]=r(e[s]))}return e}return e};for(var o in e)(n.has(o)||i.has(o))&&(e[o]=r(e[o]));if(e.style&&"object"==typeof e.style)for(var o in e.style)(n.has(o)||i.has(o))&&(e.style[o]=r(e.style[o]));var a=e.children;if(Array.isArray(a))for(var s=0,l=a;s<l.length;s++){var u=l[s];M(u,t)}}};if(!0!==a){if(1===l){var B=Number(i.idealWidth),C=Number(i.idealHeight),T=Number.isFinite(B)&&B>0?B:NaN,x=Number.isFinite(C)&&C>0?C:NaN;!Number.isFinite(T)&&Number.isFinite(x)&&v?T=Math.round(x*y/_):!Number.isFinite(x)&&Number.isFinite(T)&&v&&(x=Math.round(T*_/y)),n.renderScale=1/s*u,Number.isFinite(T)&&Number.isFinite(x)?(n.idealWidth=T,n.idealHeight=x,n.useSmallestIdeal=!!i.useSmallestIdeal,n.renderAtIdealSize=!0):v?(n.idealWidth=y,n.idealHeight=_,n.useSmallestIdeal=!0,n.renderAtIdealSize=!0):n.renderAtIdealSize=!1;var I=BABYLON.GUI.Control.Parse(i.root,n,o);return S(I),n._rootContainer=I,e.UserInterface.ProcessTextSpacingProperties(I,i.root),e.UserInterface.ProcessHdrColors(I,i.root),e.UserInterface.ApplyHdrVisualEnhancements(I),e.UserInterface.ProcessPreserveAspectRatio(I,i.root),e.UserInterface.ProcessControlEvents(t,I,i.root),n.__canvasScalerMode=l,n.__cpsScale=1,n.__defaultSpriteDpi=d,n.__fallbackScreenDpi=c,n.__referencePixelsPerUnit=h,r&&!n.renderAtIdealSize&&n.scaleTo(y,_),void n.markAsDirty()}n.renderScale=1,n.renderAtIdealSize=!1,n.idealWidth=void 0,n.idealHeight=void 0,n.useSmallestIdeal=void 0;var O=0===l?p:m,L=A(i.root);Number.isFinite(O)&&1!==O&&M(L,O);var w=BABYLON.GUI.Control.Parse(L,n,o);S(w),n._rootContainer=w,e.UserInterface.ProcessTextSpacingProperties(w,i.root),e.UserInterface.ProcessHdrColors(w,i.root),e.UserInterface.ApplyHdrVisualEnhancements(w),e.UserInterface.ProcessPreserveAspectRatio(w,i.root),e.UserInterface.ProcessControlEvents(t,w,i.root),n.__canvasScalerMode=l,n.__cpsScale=0===l?p:1,n.__defaultSpriteDpi=d,n.__fallbackScreenDpi=c,n.__referencePixelsPerUnit=h,n.markAsDirty()}else{for(var N=null!=i.root&&null!=i.root.children&&i.root.children.length>0?i.root.children[0]:i.root,P=0===l?p:2===l?m:1,R=0,E=Array.isArray(null==N?void 0:N.children)&&(null==N?void 0:N.typeName)?N.children:[N];R<E.length;R++){var k=E[R],D=k;1===P||0!==l&&2!==l||(D=A(k),M(D,P));var F=BABYLON.GUI.Control.Parse(D,n,o);F&&(n.addControl(F),e.UserInterface.ProcessTextSpacingProperties(F,k),e.UserInterface.ProcessHdrColors(F,k),e.UserInterface.ApplyHdrVisualEnhancements(F),e.UserInterface.ProcessPreserveAspectRatio(F,k),e.UserInterface.ProcessControlEvents(t,F,k))}n.markAsDirty()}}},n.FixUserInterfacePrototypes=function(){var t=globalThis||window,n=t&&t.BABYLON,i=n&&n.GUI,r=i&&i.Image,o=i&&i.Control;o&&(o.__prototypeFunctionsPatched||(o.__prototypeFunctionsPatched=!0,o.prototype.getScene=function(){var e;return null===(e=this._host)||void 0===e?void 0:e.getScene()},r.prototype._renderNinePatch=function(t,n,i,r,o){var a,s,l,u,c,d,h,p,m,f,g,v,y,_=null!==(s=null===(a=this.host)||void 0===a?void 0:a.__canvasScalerMode)&&void 0!==s?s:1,S=null!==(u=null===(l=this.host)||void 0===l?void 0:l.__cpsScale)&&void 0!==u?u:1,A=null!==(d=null===(c=this.host)||void 0===c?void 0:c.__referencePixelsPerUnit)&&void 0!==d?d:100,b=null!==(p=null===(h=this.host)||void 0===h?void 0:h.__defaultSpriteDpi)&&void 0!==p?p:96,M=(null===(m=this.host)||void 0===m?void 0:m.__fallbackScreenDpi,null!==(g=null===(f=this.metadata)||void 0===f?void 0:f.spritePixelsPerUnit)&&void 0!==g?g:A),B=this.host.idealWidth?this._currentMeasure.width/this.host.idealWidth:this.host.idealHeight?this._currentMeasure.height/this.host.idealHeight:1;0===_?(B*=S,B*=A/M):1===_?(B=null!==(y=null===(v=this.host)||void 0===v?void 0:v.idealRatio)&&void 0!==y?y:1,B*=A/M):2===_&&(B*=e.UserInterface.PHYSICAL_SIZE_SLICE_FACTOR,B*=A/M,B*=1/(b/96*1));var C=this._sliceLeft,T=this._sliceTop,x=r-this._sliceRight,I=o-this._sliceBottom,O=this._sliceRight-this._sliceLeft,L=this._sliceBottom-this._sliceTop,w=Math.round(C*B),N=Math.round(T*B),P=Math.round(I*B),R=Math.round(x*B),E=Math.max(0,Math.round(this._currentMeasure.width)-R-w+2),k=Math.max(0,Math.round(this._currentMeasure.height)-P-N+2),D=Math.round(this._currentMeasure.left)+w-1,F=Math.round(this._currentMeasure.top)+N-1,U=Math.round(this._currentMeasure.left+this._currentMeasure.width)-R,Y=Math.round(this._currentMeasure.top+this._currentMeasure.height)-P;this._drawImage(t,n,i,C,T,this._currentMeasure.left,this._currentMeasure.top,w,N),this._drawImage(t,n+this._sliceLeft,i,O,T,D+1,this._currentMeasure.top,E-2,N),this._drawImage(t,n+this._sliceRight,i,x,T,U,this._currentMeasure.top,R,N),this._drawImage(t,n,i+this._sliceTop,C,L,this._currentMeasure.left,F+1,w,k-2),this._drawImage(t,n+this._sliceLeft,i+this._sliceTop,O,L,D+1,F+1,E-2,k-2),this._drawImage(t,n+this._sliceRight,i+this._sliceTop,x,L,U,F+1,R,k-2),this._drawImage(t,n,i+this._sliceBottom,C,I,this._currentMeasure.left,Y,w,P),this._drawImage(t,n+this._sliceLeft,i+this._sliceBottom,O,I,D+1,Y,E-2,P),this._drawImage(t,n+this._sliceRight,i+this._sliceBottom,x,I,U,Y,R,P)}))},n.ProcessControlEvents=function(e,t,n){var i=this,r=function(t,n){n&&t&&(i.processUnityUIEvents(e,t,n),i.processUIToolkitEvents(e,t,n),t instanceof BABYLON.GUI.Container&&t.children.forEach(function(e,t){var i=n&&n.children?n.children[t]:null;r(e,i)}))};r(t,n)},n.processUnityUIEvents=function(e,t,n){n.onClick&&this.isUnityUIEvent(n.onClick)&&this.wireUnityUIButtonEvents(e,t,n.onClick),n.onValueChanged&&this.isUnityUIEvent(n.onValueChanged)&&"Toggle"===n.className&&this.wireUnityUIToggleEvents(e,t,n.onValueChanged),n.onValueChanged&&this.isUnityUIEvent(n.onValueChanged)&&"Slider"===n.className&&this.wireUnityUISliderEvents(e,t,n.onValueChanged),n.onValueChanged&&this.isUnityUIEvent(n.onValueChanged)&&"Dropdown"===n.className&&this.wireUnityUIDropdownEvents(e,t,n.onValueChanged),n.onValueChanged&&this.isUnityUIEvent(n.onValueChanged)&&"ScrollRect"===n.className&&this.wireUnityUIScrollRectEvents(e,t,n.onValueChanged),"InputField"===n.className&&this.wireUnityUIInputFieldEvents(e,t,n)},n.processUIToolkitEvents=function(e,t,n){n.isUIToolkit&&(n.events&&"Button"===n.className&&this.wireUIToolkitButtonEvents(e,t,n),n.events&&"Toggle"===n.className&&this.wireUIToolkitToggleEvents(e,t,n),!n.events||"Slider"!==n.className&&"SliderInt"!==n.className||this.wireUIToolkitSliderEvents(e,t,n),n.events&&"DropdownField"===n.className&&this.wireUIToolkitDropdownEvents(e,t,n))},n.isUnityUIEvent=function(e){return e&&e.events&&Array.isArray(e.events)&&e.events.some(function(e){return e.targetName||e.targetType||e.methodName})},n.wireUnityUIButtonEvents=function(e,t,n){var i=this;n.events&&Array.isArray(n.events)&&n.events.forEach(function(n){var r=i.findTargetObject(e,n.targetName,n.targetPath,n.targetInstanceId,n.targetType);null!=r&&(r.args=i.extractParameters(n.mode,n.parameters),t.onPointerClickObservable.add(function(){i.executeUnityUIEvent(r,n)}))})},n.wireUnityUIToggleEvents=function(e,t,n){n.events&&Array.isArray(n.events)},n.wireUnityUISliderEvents=function(e,t,n){n.events&&Array.isArray(n.events)},n.wireUnityUIDropdownEvents=function(e,t,n){n.events&&Array.isArray(n.events)},n.wireUnityUIScrollRectEvents=function(e,t,n){n.events&&Array.isArray(n.events)},n.wireUnityUIInputFieldEvents=function(e,t,n){BABYLON.GUI.InputText},n.wireUIToolkitButtonEvents=function(e,t,n){n.events&&Array.isArray(n.events)},n.wireUIToolkitToggleEvents=function(e,t,n){n.events&&Array.isArray(n.events)},n.wireUIToolkitSliderEvents=function(e,t,n){n.events&&Array.isArray(n.events)},n.wireUIToolkitDropdownEvents=function(e,t,n){n.events&&Array.isArray(n.events)},n.executeUnityUIEvent=function(e,t){for(var n,i=[],r=2;r<arguments.length;r++)i[r-2]=arguments[r];try{e.instance&&e.instance[t.methodName]&&"function"==typeof e.instance[t.methodName]?null!=e.args?(n=e.instance)[t.methodName].apply(n,e.args):e.instance[t.methodName]():console.warn("⚠️ UI Event: Target not found or method missing: ".concat(t.targetPath||t.targetName,".").concat(t.methodName))}catch(e){console.error("❌ Error Executing UI event: ".concat(t.methodName),e)}},n.executeUIToolkitEvent=function(e,t){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i]},n.findTargetObject=function(e,t,n,i,r){var o=null;if(null!=e&&null!=t){var a=e.getNodeByName(t);if(null!=a&&null!=a.metadata&&null!=a.metadata.toolkit&&null!=a.metadata.toolkit.components&&a.metadata.toolkit.components.length>0)for(var s=a.metadata.toolkit.components.length,l=0;l<s;l++){var u=a.metadata.toolkit.components[l],c=u.klass,d=c.lastIndexOf(".");if(-1!==d&&(c=c.substring(d+1)),c===r&&u.instanceID===i){o=u;break}}}return o},n.extractParameters=function(e,t){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];var r=[];return n&&n.length>0&&r.push.apply(r,n),t?(6===e&&null!=t.boolArgument&&r.push(t.boolArgument),5===e&&null!=t.stringArgument&&r.push(t.stringArgument),4===e&&null!=t.floatArgument&&r.push(t.floatArgument),3===e&&null!=t.intArgument&&r.push(t.intArgument),2===e&&t.objectArgument,r):r},n.resolveObjectReference=function(e){return BABYLON.EngineStore.LastCreatedScene,null},n.executeUIToolkitCallback=function(e,t){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];var r=window.uiToolkitCallbackRegistry;if(r&&r[e]&&r[e][t]){var o=r[e][t];"function"==typeof o&&o.apply(void 0,n)}else console.warn("⚠️ UI Toolkit callback not registered: ".concat(e,".").concat(t))},n.ProcessHdrColors=function(e,t){var n=this,i=function(e,t){if(e instanceof BABYLON.GUI.TextBlock&&t&&"TextBlock"===t.className){var r=e;if(t.colorIsHDR&&t.colorHdrMultiplier&&t.colorHdrMultiplier>1){var o=n.emulateUnityHDR(t.color,t.colorHdrMultiplier,t.hdrToneMapping);r.color=o.color,r._hdrMultiplier=t.colorHdrMultiplier,r._originalColor=t.color,n.applyHdrEffects(r,o,t.hdrToneMapping)}if(t.outlineColorIsHDR&&t.outlineColorHdrMultiplier&&t.outlineColorHdrMultiplier>1){var a=n.emulateUnityHDR(t.outlineColor,t.outlineColorHdrMultiplier,t.hdrToneMapping);r._hdrOutlineColor=a.color,r._hdrOutlineMultiplier=t.outlineColorHdrMultiplier}if(t.outlineBlur&&t.outlineBlur>0&&(r.outlineBlur=t.outlineBlur),t.faceSoftness&&t.faceSoftness>0&&(r.faceSoftness=t.faceSoftness),t.faceDilate&&0!==t.faceDilate&&(r.faceDilate=t.faceDilate),t.shadowColorIsHDR&&t.shadowColorHdrMultiplier&&t.shadowColorHdrMultiplier>1){var s=n.emulateUnityHDR(t.shadowColor,t.shadowColorHdrMultiplier,t.hdrToneMapping);r._hdrShadowColor=s.color,r._hdrShadowMultiplier=t.shadowColorHdrMultiplier}if(t.glowEnabled&&t.glowColor){var l=t.glowColorIsHDR&&t.glowColorHdrMultiplier>1?n.emulateUnityHDR(t.glowColor,t.glowColorHdrMultiplier,t.hdrToneMapping):{color:t.glowColor,cssFilter:""};r._glowEnabled=!0,r._glowColor=l.color,r._glowOffset=t.glowOffset||0,r._glowInner=t.glowInner||0,r._glowOuter=t.glowOuter||0,r._glowPower=t.glowPower||1,r._hdrGlowMultiplier=t.glowColorHdrMultiplier||1,n.applyGlowEffects(r,l,t)}if(t.lightingEnabled){var u=t.lightColorIsHDR&&t.lightColorHdrMultiplier>1?n.emulateUnityHDR(t.lightColor,t.lightColorHdrMultiplier,t.hdrToneMapping):{color:t.lightColor||"#ffffff",cssFilter:""},c=t.specularColorIsHDR&&t.specularColorHdrMultiplier>1?n.emulateUnityHDR(t.specularColor,t.specularColorHdrMultiplier,t.hdrToneMapping):{color:t.specularColor||"#ffffff",cssFilter:""},d=t.envMapColorIsHDR&&t.envMapColorHdrMultiplier>1?n.emulateUnityHDR(t.envMapColor,t.envMapColorHdrMultiplier,t.hdrToneMapping):{color:t.envMapColor||"#88aadd",cssFilter:""};r._lightingEnabled=!0,r._lightColor=u.color,r._bevelAmount=t.bevelAmount||0,r._bevelOffset=t.bevelOffset||0,r._bevelWidth=t.bevelWidth||0,r._bevelRoundness=t.bevelRoundness||0,r._bevelClamp=t.bevelClamp||1,r._lightAngle=t.lightAngle||0,r._specularPower=t.specularPower||1,r._reflectance=t.reflectance||.5,r._hdrLightMultiplier=t.lightColorHdrMultiplier||1,r._specularColor=c.color,r._shininess=t.shininess||1,r._envMapSampling=t.envMapSampling||0,r._envMapColor=d.color,r._bumpIntensity=t.bumpIntensity||0,r._hdrSpecularMultiplier=t.specularColorHdrMultiplier||1,r._hdrEnvMapMultiplier=t.envMapColorHdrMultiplier||1,n.applyAdvancedLightingEffects(r,u,c,d,t)}}e instanceof BABYLON.GUI.Container&&e.children.forEach(function(e,n){var r=t&&t.children?t.children[n]:null;i(e,r)})};i(e,t)},n.emulateUnityHDR=function(e,t,n){var i=this.parseRgbaColor(e);if(!i)return{color:e,cssFilter:""};var r=(null==n?void 0:n.exposure)||1,o=(null==n?void 0:n.gamma)||2.2,a=(null==n?void 0:n.saturation)||.9,s=(null==n?void 0:n.brightness)||1.1;return this.applyUnityHDRToneMapping(i,t,{exposure:r,gamma:o,saturation:a,brightness:s})},n.applyUnityHDRToneMapping=function(e,t,n){var i=Math.min(t*n.exposure,3),r=e.r/255,o=e.g/255,a=e.b/255,s=.299*(r=1-Math.exp(-r*i))+.587*(o=1-Math.exp(-o*i))+.114*(a=1-Math.exp(-a*i)),l=Math.min(.2*(t-1),.5);r=r*(1-l)+s*l,o=o*(1-l)+s*l,a=a*(1-l)+s*l;var u=1/n.gamma;r=Math.pow(r,u),o=Math.pow(o,u),a=Math.pow(a,u);var c=1+.3*(t-1);r=Math.min(r*c,1),o=Math.min(o*c,1),a=Math.min(a*c,1);var d=Math.round(255*r),h=Math.round(255*o),p=Math.round(255*a),m="rgba(".concat(d,",").concat(h,",").concat(p,",").concat(e.a,")"),f=Math.min(1+.15*(t-1),1.5),g=Math.max(n.saturation,.7);return{color:m,cssFilter:"brightness(".concat(f,") saturate(").concat(g,")")}},n.applyHdrEffects=function(e,t,n){e.color=t.color,e._hdrEnabled=!0,e._hdrCssFilter=t.cssFilter,e._hdrToneMapping=n},n.applyGlowEffects=function(e,t,n){e._glowEnabled=!0,e._glowColor=t.color,e._glowOffset=n.glowOffset||0,e._glowInner=n.glowInner||0,e._glowOuter=n.glowOuter||0,e._glowPower=n.glowPower||1;var i=n.glowInner||0,r=n.glowOuter||0,o=n.glowOffset||0,a=n.glowPower||1,s=Math.max(i,r),l=Math.max(2,8*s*a),u=[];if(i>0){var c=.3*l;u.push("0 0 ".concat(c,"px ").concat(t.color))}if(r>0){var d=l;if(u.push("".concat(o,"px ").concat(o,"px ").concat(d,"px ").concat(t.color)),r>.5){var h=1.5*l;u.push("0 0 ".concat(h,"px ").concat(t.color))}}u.length>0&&(e._glowCssFilter="drop-shadow(".concat(u.join(") drop-shadow("),")"))},n.applyLightingEffects=function(e,t,n){e._lightingEnabled=!0,e._lightColor=t.color,e._bevelAmount=n.bevelAmount||0,e._bevelOffset=n.bevelOffset||0,e._bevelWidth=n.bevelWidth||0,e._bevelRoundness=n.bevelRoundness||0,e._bevelClamp=n.bevelClamp||1,e._lightAngle=n.lightAngle||0,e._specularPower=n.specularPower||1,e._reflectance=n.reflectance||.5;var i=n.bevelAmount||0,r=n.bevelWidth||0,o=(n.lightAngle||0)*Math.PI/180;if(i>0&&r>0){var a=Math.cos(o)*r,s=Math.sin(o)*r,l=-a,u=-s,c=this.parseRgbaColor(t.color),d=c?"rgba(".concat(Math.min(255,c.r+50),", ").concat(Math.min(255,c.g+50),", ").concat(Math.min(255,c.b+50),", ").concat(.6*c.a,")"):"rgba(255, 255, 255, 0.6)",h=c?"rgba(".concat(Math.max(0,c.r-100),", ").concat(Math.max(0,c.g-100),", ").concat(Math.max(0,c.b-100),", ").concat(.4*c.a,")"):"rgba(0, 0, 0, 0.4)",p=[];if(p.push("".concat(a,"px ").concat(s,"px 0px ").concat(d)),p.push("".concat(l,"px ").concat(u,"px 0px ").concat(h)),i>.5){var m=c?"rgba(".concat(c.r,", ").concat(c.g,", ").concat(c.b,", ").concat(.3*c.a,")"):"rgba(255, 255, 255, 0.3)";p.push("".concat(.5*a,"px ").concat(.5*s,"px 1px ").concat(m))}e._lightingCssFilter="drop-shadow(".concat(p.join(") drop-shadow("),")")}},n.applyAdvancedLightingEffects=function(e,t,n,i,r){e._lightingEnabled=!0,e._lightColor=t.color,e._specularColor=n.color,e._envMapColor=i.color;var o=r.bevelAmount||0,a=r.bevelWidth||0,s=(r.lightAngle||0)*Math.PI/180,l=r.shininess||1,u=r.envMapSampling||0,c=r.bumpIntensity||0,d=r.specularPower||1,h=[];if(o>0&&a>0){var p=Math.cos(s)*a,m=Math.sin(s)*a,f=-p,g=-m,v=this.parseRgbaColor(t.color),y=v?"rgba(".concat(Math.min(255,v.r+50),", ").concat(Math.min(255,v.g+50),", ").concat(Math.min(255,v.b+50),", ").concat(.6*v.a,")"):"rgba(255, 255, 255, 0.6)",_=v?"rgba(".concat(Math.max(0,v.r-100),", ").concat(Math.max(0,v.g-100),", ").concat(Math.max(0,v.b-100),", ").concat(.4*v.a,")"):"rgba(0, 0, 0, 0.4)";h.push("".concat(p,"px ").concat(m,"px 0px ").concat(y)),h.push("".concat(f,"px ").concat(g,"px 0px ").concat(_))}if(l>1&&"#ffffff"!==n.color){var S=this.parseRgbaColor(n.color);if(S){var A=Math.min(1,l/10),b="rgba(".concat(S.r,", ").concat(S.g,", ").concat(S.b,", ").concat(.8*A,")"),M=Math.cos(s+Math.PI)*(.3*a),B=Math.sin(s+Math.PI)*(.3*a);if(h.push("".concat(M,"px ").concat(B,"px ").concat(Math.max(1,l),"px ").concat(b)),d>2){var C="rgba(".concat(S.r,", ").concat(S.g,", ").concat(S.b,", ").concat(.4*A,")");h.push("".concat(1.5*M,"px ").concat(1.5*B,"px ").concat(2*l,"px ").concat(C))}}}if(u>0&&"#88aadd"!==i.color){var T=this.parseRgbaColor(i.color);if(T){var x=Math.min(.6,u),I="rgba(".concat(T.r,", ").concat(T.g,", ").concat(T.b,", ").concat(x,")"),O=Math.max(2,5*u);h.push("0 0 ".concat(O,"px ").concat(I));var L=2*Math.cos(s+Math.PI/2),w=2*Math.sin(s+Math.PI/2);h.push("".concat(L,"px ").concat(w,"px ").concat(.7*O,"px ").concat(I))}}if(c>0){var N="rgba(0, 0, 0, ".concat(Math.min(.3,.5*c),")"),P="rgba(255, 255, 255, ".concat(Math.min(.2,.3*c),")"),R=.5*Math.cos(s),E=.5*Math.sin(s);h.push("".concat(R,"px ").concat(E,"px 0px ").concat(P)),h.push("".concat(-R,"px ").concat(-E,"px 0px ").concat(N))}h.length>0&&(e._lightingCssFilter="drop-shadow(".concat(h.join(") drop-shadow("),")"))},n.parseRgbaColor=function(e){var t=e.match(/rgba?\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/);return t?{r:parseInt(t[1]),g:parseInt(t[2]),b:parseInt(t[3]),a:t[4]?parseFloat(t[4]):1}:null},n.ApplyHdrVisualEnhancements=function(e){var t=function(e){if(e instanceof BABYLON.GUI.TextBlock){var n=e;if(n._hdrEnabled){n._hdrCssFilter;var i=n._hdrMultiplier;i&&i>2&&(n._needsGlowEffect=!0)}}e instanceof BABYLON.GUI.Container&&e.children.forEach(function(e){t(e)})};t(e)},n.ProcessPreserveAspectRatio=function(e,t){},n.applyPreserveAspectRatio=function(e,t){},n.ProcessTextSpacingProperties=function(t,n){var i=this,r=function(t,n){if(t instanceof BABYLON.GUI.TextBlock&&n&&"TextBlock"===n.className){var o=t,a=o.fontSize||"18px",s=parseFloat(a.toString().replace(/px$/,""));if(n.characterSpacing&&0!==n.characterSpacing){var l=parseFloat(n.characterSpacing);if(!isNaN(l)&&0!==l){var u=l*(s*e.UserInterface.CHARACTER_WORD_SPACE_FACTOR);o._characterSpacing=u,i.applyCharacterSpacing(o,u)}}if(n.wordSpacing&&0!==n.wordSpacing&&(l=parseFloat(n.wordSpacing),isNaN(l)||0===l||(u=l*(s*e.UserInterface.CHARACTER_WORD_SPACE_FACTOR),o._wordSpacing=u,i.applyWordSpacing(o,u))),n.paragraphSpacing&&0!==n.paragraphSpacing&&(l=parseFloat(n.paragraphSpacing),!isNaN(l)&&0!==l))if(u=l*s,o._paragraphSpacing=u,o.lineSpacing){var c=parseFloat(o.lineSpacing.toString().replace(/px$/,""));o.lineSpacing=c+u+"px"}else o.lineSpacing=u+"px"}t instanceof BABYLON.GUI.Container&&t.children.forEach(function(e,t){var i=n&&n.children?n.children[t]:null;r(e,i)})};r(t,n)},n.applyCharacterSpacing=function(e,t){var n=e.text;if(n&&t>0){var i=e._drawText;if(i&&(e._drawText=function(e,n,r,o){if(t>0){o.save();var a=this.shadowOffsetX||0,s=this.shadowOffsetY||0,l=this.shadowBlur||0,u=this._hdrShadowColor||this.shadowColor||"transparent",c=this.outlineWidth||0,d=this.outlineBlur||0,h=this._hdrOutlineColor||this.outlineColor||"transparent",p=this.faceSoftness||0,m=this.faceDilate||0;if(0!==m){var f=Math.max(0,1+2*m);f>0&&(o.lineWidth=f,o.strokeStyle=o.fillStyle)}var g=this._hdrCssFilter,v=this._glowCssFilter,y=this._lightingCssFilter,_="";if(p>0){var S=Math.min(3,2*p);_="blur(".concat(S,"px)")}var A=[];g&&A.push(g),v&&A.push(v),y&&A.push(y),_&&A.push(_),A.length>0&&void 0!==o.filter&&(o.filter=A.join(" ")),(0!==a||0!==s||l>0)&&(o.shadowOffsetX=a,o.shadowOffsetY=s,o.shadowBlur=l,o.shadowColor=u),c>0&&(o.strokeStyle=h,o.lineWidth=c);for(var b=e.split(""),M=this._currentMeasure.left,B=0,C=0;C<b.length;C++)B+=o.measureText(b[C]).width,C<b.length-1&&(B+=t);for(this.textHorizontalAlignment===BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER?M+=(this._currentMeasure.width-B)/2:this.textHorizontalAlignment===BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT&&(M+=this._currentMeasure.width-B),C=0;C<b.length;C++)c>0&&(d>0?(o.save(),o.shadowColor=h,o.shadowBlur=d,o.shadowOffsetX=0,o.shadowOffsetY=0,o.strokeStyle=h,o.lineWidth=c,o.strokeText(b[C],M,r),o.restore()):o.strokeText(b[C],M,r)),0!==m&&(o.save(),o.strokeStyle=o.fillStyle,o.lineWidth=Math.abs(2*m),o.strokeText(b[C],M,r),o.restore()),o.fillText(b[C],M,r),M+=o.measureText(b[C]).width+t;o.restore()}else i.call(this,e,n,r,o)}),!i){var r=n.split("").join(" ");e.text=r}}},n.applyWordSpacing=function(e,t){var n=e._drawText;if(n)e._drawText=function(e,i,r,o){if(t>0){o.save();var a=this.shadowOffsetX||0,s=this.shadowOffsetY||0,l=this.shadowBlur||0,u=this._hdrShadowColor||this.shadowColor||"transparent",c=this.outlineWidth||0,d=this.outlineBlur||0,h=this._hdrOutlineColor||this.outlineColor||"transparent",p=this.faceSoftness||0,m=this.faceDilate||0,f=this._hdrCssFilter,g=this._glowCssFilter,v=this._lightingCssFilter,y="";if(p>0){var _=Math.min(3,2*p);y="blur(".concat(_,"px)")}var S=[];f&&S.push(f),g&&S.push(g),v&&S.push(v),y&&S.push(y),S.length>0&&void 0!==o.filter&&(o.filter=S.join(" ")),(0!==a||0!==s||l>0)&&(o.shadowOffsetX=a,o.shadowOffsetY=s,o.shadowBlur=l,o.shadowColor=u),c>0&&(o.strokeStyle=h,o.lineWidth=c);for(var A=e.split(" "),b=this._currentMeasure.left,M=0,B=0;B<A.length;B++)M+=o.measureText(A[B]).width,B<A.length-1&&(M+=o.measureText(" ").width+t);for(this.textHorizontalAlignment===BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_CENTER?b+=(this._currentMeasure.width-M)/2:this.textHorizontalAlignment===BABYLON.GUI.Control.HORIZONTAL_ALIGNMENT_RIGHT&&(b+=this._currentMeasure.width-M),B=0;B<A.length;B++)c>0&&(d>0?(o.save(),o.shadowColor=h,o.shadowBlur=d,o.shadowOffsetX=0,o.shadowOffsetY=0,o.strokeStyle=h,o.lineWidth=c,o.strokeText(A[B],b,r),o.restore()):o.strokeText(A[B],b,r)),0!==m&&(o.save(),o.strokeStyle=o.fillStyle,o.lineWidth=Math.abs(2*m),o.strokeText(A[B],b,r),o.restore()),o.fillText(A[B],b,r),b+=o.measureText(A[B]).width,B<A.length-1&&(b+=o.measureText(" ").width+t);o.restore()}else n.call(this,e,i,r,o)};else{var i=e.text.split(" ").join(" ");e.text=i}},n.IsForegroundReady=function(e){return null!=e._foregroundTexture},n.SetForegroundTexture=function(e,t){e._foregroundTexture=t},n.GetForegroundTexture=function(t,n){return void 0===n&&(n=null),null==t._foregroundTexture&&null!=n&&(t._foregroundTexture=e.UserInterface.CreateInternalUserInterface(t,!0,null==n?void 0:n.samplerMode,null==n?void 0:n.adaptiveHardwareScaling)),t._foregroundTexture},n.IsBackgroundReady=function(e){return null!=e._backgroundTexture},n.SetBackgroundTexture=function(e,t){e._backgroundTexture=t},n.GetBackgroundTexture=function(t,n){return void 0===n&&(n=null),null==t._backgroundTexture&&null!=n&&(t._backgroundTexture=e.UserInterface.CreateInternalUserInterface(t,!1,null==n?void 0:n.samplerMode,null==n?void 0:n.adaptiveHardwareScaling)),t._backgroundTexture},n.GetCanvasElement=function(e,t){var n=t||BABYLON.EngineStore.LastCreatedScene;return null!=n._foregroundTexture?n._foregroundTexture.getControlByName(e):null},n.ShowCanvasElement=function(t){return a(this,arguments,void 0,function(t,n,i){var r;return void 0===n&&(n=0),void 0===i&&(i=1),s(this,function(o){switch(o.label){case 0:return null==t?[3,3]:n>0?(r=t.alpha,t.isVisible=!0,[4,e.SceneManager.TweenFromToAsync(t,{alpha:r},{alpha:1},{duration:n,speed:i})]):[3,2];case 1:return o.sent(),t.isEnabled=!0,[3,3];case 2:t.isEnabled=!0,t.isVisible=!0,t.alpha=1,o.label=3;case 3:return[2]}})})},n.HideCanvasElement=function(t){return a(this,arguments,void 0,function(t,n,i){var r;return void 0===n&&(n=0),void 0===i&&(i=1),s(this,function(o){switch(o.label){case 0:return null==t?[3,3]:n>0?(t.isEnabled=!1,r=t.alpha,t.isEnabled=!1,[4,e.SceneManager.TweenFromToAsync(t,{alpha:r},{alpha:0},{duration:n,speed:i})]):[3,2];case 1:return o.sent(),t.isVisible=!1,[3,3];case 2:t.isEnabled=!1,t.isVisible=!1,t.alpha=0,o.label=3;case 3:return[2]}})})},n.AttachClickHandler=function(e,t){return null==e||null==t?null:e.onPointerClickObservable.add(t)},n.PHYSICAL_SIZE_SLICE_FACTOR=1.5,n.PHYSICAL_SIZE_POINT_FACTOR=1.915,n.CHARACTER_WORD_SPACE_FACTOR=.01,n.OnParseNodeObject=new BABYLON.Observable,n.OnInterfaceLoaded=new BABYLON.Observable,n}(e.ScriptComponent);e.UserInterface=t,e.SceneManager.RegisterClass("TOOLKIT.UserInterface",t)}(i||(i={})),function(e){var t=function(t){function n(e,n,i,r){void 0===i&&(i={}),void 0===r&&(r="TOOLKIT.WebVideoPlayer");var o=t.call(this,e,n,i,r)||this;return o.videoLoop=!1,o.videoMuted=!1,o.videoAlpha=!1,o.videoFaded=!1,o.videoPoster=null,o.videoInvert=!0,o.videoSample=3,o.videoVolume=1,o.videoMipmaps=!1,o.videoPlayback=1,o.videoPlayOnAwake=!0,o.videoPreloaderUrl=null,o.videoBlobUrl=null,o.videoPreload=!1,o._initializedReadyInstance=!1,o.onReadyObservable=new BABYLON.Observable,o.m_abstractMesh=null,o.m_videoTexture=null,o.m_videoMaterial=null,o.m_diffuseIntensity=1,o}return r(n,t),n.prototype.getVideoMaterial=function(){return this.m_videoMaterial},n.prototype.getVideoTexture=function(){return this.m_videoTexture},n.prototype.getVideoElement=function(){return null!=this.m_videoTexture?this.m_videoTexture.video:null},n.prototype.getVideoScreen=function(){return this.m_abstractMesh},n.prototype.getVideoBlobUrl=function(){return this.videoBlobUrl},n.prototype.awake=function(){this.awakeWebVideoPlayer()},n.prototype.destroy=function(){this.destroyWebVideoPlayer()},n.prototype.awakeWebVideoPlayer=function(){this.videoLoop=this.getProperty("looping",!1),this.videoMuted=this.getProperty("muted",!1),this.videoInvert=this.getProperty("inverty",!0),this.videoSample=this.getProperty("sampling",3),this.videoVolume=this.getProperty("volume",1),this.videoMipmaps=this.getProperty("mipmaps",!1),this.videoAlpha=this.getProperty("texturealpha",!1),this.videoFaded=this.getProperty("diffusealpha",!1),this.videoPlayback=this.getProperty("playbackspeed",1),this.videoPlayOnAwake=this.getProperty("playonawake",!0),this.videoPreload=this.getProperty("preload",this.videoPreload),this.m_diffuseIntensity=this.getProperty("intensity",1),this.m_abstractMesh=this.getAbstractMesh(),!0===this.getProperty("poster")&&null!=this.m_abstractMesh&&null!=this.m_abstractMesh.material&&(this.m_abstractMesh.material instanceof BABYLON.PBRMaterial?null!=this.m_abstractMesh.material.albedoTexture&&null!=this.m_abstractMesh.material.albedoTexture.url&&""!==this.m_abstractMesh.material.albedoTexture.url&&(this.videoPoster=this.m_abstractMesh.material.albedoTexture.url.replace("data:","")):this.m_abstractMesh.material instanceof BABYLON.StandardMaterial&&null!=this.m_abstractMesh.material.diffuseTexture&&null!=this.m_abstractMesh.material.diffuseTexture.url&&""!==this.m_abstractMesh.material.diffuseTexture.url&&(this.videoPoster=this.m_abstractMesh.material.diffuseTexture.url.replace("data:","")));var t=this.getProperty("url",null),n=this.getProperty("source",null),i=t;null!=n&&null!=n.filename&&""!==n.filename&&(i=e.SceneManager.GetRootUrl(this.scene)+n.filename),null!=i&&""!==i&&(!0===this.videoPreload?this.videoPreloaderUrl=i:this.setDataSource(i))},n.prototype.destroyWebVideoPlayer=function(){this.m_abstractMesh=null,null!=this.m_videoTexture&&(this.m_videoTexture.dispose(),this.m_videoTexture=null),null!=this.m_videoMaterial&&(this.m_videoMaterial.dispose(),this.m_videoMaterial=null),this.revokeVideoBlobUrl()},n.prototype.isReady=function(){return null!=this.getVideoElement()},n.prototype.isPlaying=function(){var e=!1,t=this.getVideoElement();return null!=t&&(e=!1===t.paused),e},n.prototype.isPaused=function(){var e=!1,t=this.getVideoElement();return null!=t&&(e=!0===t.paused),e},n.prototype.play=function(){return a(this,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return[4,e.AudioSource.UnlockAudioEngine()];case 1:return t.sent(),this.internalPlay(),[2,!0]}})})},n.prototype.internalPlay=function(){var e=this;!0===this._initializedReadyInstance?this.checkedPlay():this.onReadyObservable.addOnce(function(){e.checkedPlay()})},n.prototype.checkedPlay=function(){var e=this,t=this.getVideoElement();null!=t&&t.play().then(function(){!0===t.paused&&e.checkedRePlay()})},n.prototype.checkedRePlay=function(){var e=this.getVideoElement();null!=e&&e.play().then(function(){})},n.prototype.pause=function(){var e=!1,t=this.getVideoElement();return null!=t&&(t.pause(),e=!0),e},n.prototype.mute=function(){var e=!1,t=this.getVideoElement();return null!=t&&(t.muted=!0,e=!0),e},n.prototype.unmute=function(){var e=!1,t=this.getVideoElement();return null!=t&&(t.muted=!1,e=!0),e},n.prototype.getVolume=function(){var e=0,t=this.getVideoElement();return null!=t&&(e=t.volume),e},n.prototype.setVolume=function(e){var t=!1,n=this.getVideoElement();return null!=n&&(n.volume=e,t=!0),t},n.prototype.setDataSource=function(e){var t=this;null!=this.m_abstractMesh&&(null==this.m_videoMaterial&&(this.m_videoMaterial=new BABYLON.StandardMaterial(this.transform.name+".VideoMat",this.scene),this.m_videoMaterial.roughness=1,this.m_videoMaterial.diffuseColor=new BABYLON.Color3(1,1,1),this.m_videoMaterial.emissiveColor=new BABYLON.Color3(1,1,1),this.m_videoMaterial.useAlphaFromDiffuseTexture=this.videoFaded,this.m_abstractMesh.material=this.m_videoMaterial),null!=this.m_videoMaterial?(this.m_videoMaterial.diffuseTexture=null,null!=this.m_videoTexture&&(this.m_videoTexture.dispose(),this.m_videoTexture=null),this._initializedReadyInstance=!1,this.m_videoTexture=new BABYLON.VideoTexture(this.transform.name+".VideoTex",e,this.scene,this.videoMipmaps,this.videoInvert,this.videoSample,{autoUpdateTexture:!0,poster:this.videoPoster}),null!=this.m_videoTexture&&(this.m_videoTexture.hasAlpha=this.videoAlpha,null!=this.m_videoTexture.video&&(this.m_videoTexture.video.loop=this.videoLoop,this.m_videoTexture.video.muted=this.videoMuted,this.m_videoTexture.video.volume=this.videoVolume,this.m_videoTexture.video.playbackRate=this.videoPlayback,this.m_videoTexture.video.addEventListener("loadeddata",function(){t._initializedReadyInstance=!0,t.onReadyObservable&&t.onReadyObservable.hasObservers()&&t.onReadyObservable.notifyObservers(t.m_videoTexture),!0===t.videoPlayOnAwake&&t.play()}),this.m_videoTexture.video.load())),null!=this.m_videoTexture&&(this.m_videoTexture.level=this.m_diffuseIntensity,this.m_videoMaterial.diffuseTexture=this.m_videoTexture)):BABYLON.Tools.Warn("No video mesh or material available for: "+this.transform.name))},n.prototype.revokeVideoBlobUrl=function(){null!=this.videoBlobUrl&&(URL.revokeObjectURL(this.videoBlobUrl),this.videoBlobUrl=null)},n.prototype.addPreloaderTasks=function(e){var t=this;if(!0===this.videoPreload){var n=e.addBinaryFileTask(this.transform.name+".VideoTask",this.videoPreloaderUrl);n.onSuccess=function(e){t.revokeVideoBlobUrl(),t.videoBlobUrl=URL.createObjectURL(new Blob([e.data])),t.setDataSource(t.videoBlobUrl)},n.onError=function(e,t,n){console.error(t,n)}}},n}(e.ScriptComponent);e.WebVideoPlayer=t,e.SceneManager.RegisterClass("TOOLKIT.WebVideoPlayer",t)}(i||(i={})),"undefined"!=typeof window?(window.TOOLKIT=i,window.SM=i.SceneManager,window.WM=i.WindowManager,window.UI=i.UserInterface,window.IC=i.InputController):(globalThis.TOOLKIT=i,globalThis.SM=i.SceneManager,globalThis.WM=i.WindowManager,globalThis.UI=i.UserInterface,globalThis.IC=i.InputController);const u=i;return t.default})());