@babylonjs/viewer 7.23.0-alpha → 7.23.0

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.
Files changed (286) hide show
  1. package/configuration/configuration.d.ts +107 -0
  2. package/configuration/configuration.js +16 -0
  3. package/configuration/configuration.js.map +1 -0
  4. package/configuration/configurationCompatibility.d.ts +8 -0
  5. package/configuration/configurationCompatibility.js +66 -0
  6. package/configuration/configurationCompatibility.js.map +1 -0
  7. package/configuration/configurationContainer.d.ts +10 -0
  8. package/configuration/configurationContainer.js +10 -0
  9. package/configuration/configurationContainer.js.map +1 -0
  10. package/configuration/globals.d.ts +6 -0
  11. package/configuration/globals.js +18 -0
  12. package/configuration/globals.js.map +1 -0
  13. package/configuration/index.d.ts +2 -0
  14. package/configuration/index.js +4 -0
  15. package/configuration/index.js.map +1 -0
  16. package/configuration/interfaces/cameraConfiguration.d.ts +31 -0
  17. package/configuration/interfaces/cameraConfiguration.js +2 -0
  18. package/configuration/interfaces/cameraConfiguration.js.map +1 -0
  19. package/configuration/interfaces/colorGradingConfiguration.d.ts +81 -0
  20. package/configuration/interfaces/colorGradingConfiguration.js +2 -0
  21. package/configuration/interfaces/colorGradingConfiguration.js.map +1 -0
  22. package/configuration/interfaces/defaultRenderingPipelineConfiguration.d.ts +20 -0
  23. package/configuration/interfaces/defaultRenderingPipelineConfiguration.js +2 -0
  24. package/configuration/interfaces/defaultRenderingPipelineConfiguration.js.map +1 -0
  25. package/configuration/interfaces/environmentMapConfiguration.d.ts +22 -0
  26. package/configuration/interfaces/environmentMapConfiguration.js +2 -0
  27. package/configuration/interfaces/environmentMapConfiguration.js.map +1 -0
  28. package/configuration/interfaces/groundConfiguration.d.ts +24 -0
  29. package/configuration/interfaces/groundConfiguration.js +2 -0
  30. package/configuration/interfaces/groundConfiguration.js.map +1 -0
  31. package/configuration/interfaces/imageProcessingConfiguration.d.ts +45 -0
  32. package/configuration/interfaces/imageProcessingConfiguration.js +2 -0
  33. package/configuration/interfaces/imageProcessingConfiguration.js.map +1 -0
  34. package/configuration/interfaces/index.d.ts +15 -0
  35. package/configuration/interfaces/index.js +16 -0
  36. package/configuration/interfaces/index.js.map +1 -0
  37. package/configuration/interfaces/lightConfiguration.d.ts +60 -0
  38. package/configuration/interfaces/lightConfiguration.js +2 -0
  39. package/configuration/interfaces/lightConfiguration.js.map +1 -0
  40. package/configuration/interfaces/modelAnimationConfiguration.d.ts +26 -0
  41. package/configuration/interfaces/modelAnimationConfiguration.js +2 -0
  42. package/configuration/interfaces/modelAnimationConfiguration.js.map +1 -0
  43. package/configuration/interfaces/modelConfiguration.d.ts +65 -0
  44. package/configuration/interfaces/modelConfiguration.js +2 -0
  45. package/configuration/interfaces/modelConfiguration.js.map +1 -0
  46. package/configuration/interfaces/observersConfiguration.d.ts +5 -0
  47. package/configuration/interfaces/observersConfiguration.js +2 -0
  48. package/configuration/interfaces/observersConfiguration.js.map +1 -0
  49. package/configuration/interfaces/sceneConfiguration.d.ts +48 -0
  50. package/configuration/interfaces/sceneConfiguration.js +2 -0
  51. package/configuration/interfaces/sceneConfiguration.js.map +1 -0
  52. package/configuration/interfaces/sceneOptimizerConfiguration.d.ts +23 -0
  53. package/configuration/interfaces/sceneOptimizerConfiguration.js +2 -0
  54. package/configuration/interfaces/sceneOptimizerConfiguration.js.map +1 -0
  55. package/configuration/interfaces/skyboxConfiguration.d.ts +21 -0
  56. package/configuration/interfaces/skyboxConfiguration.js +2 -0
  57. package/configuration/interfaces/skyboxConfiguration.js.map +1 -0
  58. package/configuration/interfaces/templateConfiguration.d.ts +67 -0
  59. package/configuration/interfaces/templateConfiguration.js +2 -0
  60. package/configuration/interfaces/templateConfiguration.js.map +1 -0
  61. package/configuration/interfaces/vrConfiguration.d.ts +16 -0
  62. package/configuration/interfaces/vrConfiguration.js +2 -0
  63. package/configuration/interfaces/vrConfiguration.js.map +1 -0
  64. package/configuration/loader.d.ts +4 -0
  65. package/configuration/loader.js +17 -0
  66. package/configuration/loader.js.map +1 -0
  67. package/configuration/mappers.d.ts +43 -0
  68. package/configuration/mappers.js +192 -0
  69. package/configuration/mappers.js.map +1 -0
  70. package/configuration/renderOnlyLoader.d.ts +33 -0
  71. package/configuration/renderOnlyLoader.js +162 -0
  72. package/configuration/renderOnlyLoader.js.map +1 -0
  73. package/configuration/types/default.d.ts +6 -0
  74. package/configuration/types/default.js +121 -0
  75. package/configuration/types/default.js.map +1 -0
  76. package/configuration/types/environmentMap.d.ts +5 -0
  77. package/configuration/types/environmentMap.js +14 -0
  78. package/configuration/types/environmentMap.js.map +1 -0
  79. package/configuration/types/extended.d.ts +6 -0
  80. package/configuration/types/extended.js +317 -0
  81. package/configuration/types/extended.js.map +1 -0
  82. package/configuration/types/index.d.ts +14 -0
  83. package/configuration/types/index.js +51 -0
  84. package/configuration/types/index.js.map +1 -0
  85. package/configuration/types/minimal.d.ts +6 -0
  86. package/configuration/types/minimal.js +43 -0
  87. package/configuration/types/minimal.js.map +1 -0
  88. package/configuration/types/renderOnlyDefault.d.ts +30 -0
  89. package/configuration/types/renderOnlyDefault.js +31 -0
  90. package/configuration/types/renderOnlyDefault.js.map +1 -0
  91. package/configuration/types/shadowLight.d.ts +9 -0
  92. package/configuration/types/shadowLight.js +64 -0
  93. package/configuration/types/shadowLight.js.map +1 -0
  94. package/helper/index.d.ts +29 -0
  95. package/helper/index.js +66 -0
  96. package/helper/index.js.map +1 -0
  97. package/index.d.ts +30 -0
  98. package/index.js +46 -0
  99. package/index.js.map +1 -0
  100. package/initializer.d.ts +11 -0
  101. package/initializer.js +35 -0
  102. package/initializer.js.map +1 -0
  103. package/interfaces.d.ts +5 -0
  104. package/interfaces.js +7 -0
  105. package/interfaces.js.map +1 -0
  106. package/labs/environmentSerializer.d.ts +126 -0
  107. package/labs/environmentSerializer.js +191 -0
  108. package/labs/environmentSerializer.js.map +1 -0
  109. package/labs/texture.d.ts +183 -0
  110. package/labs/texture.js +351 -0
  111. package/labs/texture.js.map +1 -0
  112. package/labs/viewerLabs.d.ts +51 -0
  113. package/labs/viewerLabs.js +134 -0
  114. package/labs/viewerLabs.js.map +1 -0
  115. package/loader/modelLoader.d.ts +56 -0
  116. package/loader/modelLoader.js +199 -0
  117. package/loader/modelLoader.js.map +1 -0
  118. package/loader/plugins/applyMaterialConfig.d.ts +12 -0
  119. package/loader/plugins/applyMaterialConfig.js +16 -0
  120. package/loader/plugins/applyMaterialConfig.js.map +1 -0
  121. package/loader/plugins/extendedMaterialLoaderPlugin.d.ts +9 -0
  122. package/loader/plugins/extendedMaterialLoaderPlugin.js +16 -0
  123. package/loader/plugins/extendedMaterialLoaderPlugin.js.map +1 -0
  124. package/loader/plugins/index.d.ts +19 -0
  125. package/loader/plugins/index.js +44 -0
  126. package/loader/plugins/index.js.map +1 -0
  127. package/loader/plugins/loaderPlugin.d.ts +24 -0
  128. package/loader/plugins/loaderPlugin.js +2 -0
  129. package/loader/plugins/loaderPlugin.js.map +1 -0
  130. package/loader/plugins/msftLodLoaderPlugin.d.ts +12 -0
  131. package/loader/plugins/msftLodLoaderPlugin.js +21 -0
  132. package/loader/plugins/msftLodLoaderPlugin.js.map +1 -0
  133. package/loader/plugins/telemetryLoaderPlugin.d.ts +12 -0
  134. package/loader/plugins/telemetryLoaderPlugin.js +36 -0
  135. package/loader/plugins/telemetryLoaderPlugin.js.map +1 -0
  136. package/managers/observablesManager.d.ts +66 -0
  137. package/managers/observablesManager.js +35 -0
  138. package/managers/observablesManager.js.map +1 -0
  139. package/managers/sceneManager.d.ts +245 -0
  140. package/managers/sceneManager.js +1375 -0
  141. package/managers/sceneManager.js.map +1 -0
  142. package/managers/telemetryManager.d.ts +78 -0
  143. package/managers/telemetryManager.js +117 -0
  144. package/managers/telemetryManager.js.map +1 -0
  145. package/model/modelAnimation.d.ts +215 -0
  146. package/model/modelAnimation.js +237 -0
  147. package/model/modelAnimation.js.map +1 -0
  148. package/model/viewerModel.d.ts +233 -0
  149. package/model/viewerModel.js +673 -0
  150. package/model/viewerModel.js.map +1 -0
  151. package/optimizer/custom/extended.d.ts +13 -0
  152. package/optimizer/custom/extended.js +101 -0
  153. package/optimizer/custom/extended.js.map +1 -0
  154. package/optimizer/custom/index.d.ts +9 -0
  155. package/optimizer/custom/index.js +26 -0
  156. package/optimizer/custom/index.js.map +1 -0
  157. package/package.json +27 -17
  158. package/readme.md +21 -35
  159. package/renderOnlyIndex.d.ts +11 -0
  160. package/renderOnlyIndex.js +18 -0
  161. package/renderOnlyIndex.js.map +1 -0
  162. package/templating/eventManager.d.ts +35 -0
  163. package/templating/eventManager.js +66 -0
  164. package/templating/eventManager.js.map +1 -0
  165. package/templating/plugins/hdButtonPlugin.d.ts +9 -0
  166. package/templating/plugins/hdButtonPlugin.js +21 -0
  167. package/templating/plugins/hdButtonPlugin.js.map +1 -0
  168. package/templating/plugins/printButton.d.ts +9 -0
  169. package/templating/plugins/printButton.js +40 -0
  170. package/templating/plugins/printButton.js.map +1 -0
  171. package/templating/templateManager.d.ts +197 -0
  172. package/templating/templateManager.js +561 -0
  173. package/templating/templateManager.js.map +1 -0
  174. package/templating/viewerTemplatePlugin.d.ts +21 -0
  175. package/templating/viewerTemplatePlugin.js +69 -0
  176. package/templating/viewerTemplatePlugin.js.map +1 -0
  177. package/viewer/defaultViewer.d.ts +130 -0
  178. package/viewer/defaultViewer.js +675 -0
  179. package/viewer/defaultViewer.js.map +1 -0
  180. package/viewer/renderOnlyViewer.d.ts +9 -0
  181. package/viewer/renderOnlyViewer.js +46 -0
  182. package/viewer/renderOnlyViewer.js.map +1 -0
  183. package/viewer/viewer.d.ts +258 -0
  184. package/viewer/viewer.js +783 -0
  185. package/viewer/viewer.js.map +1 -0
  186. package/viewer/viewerManager.d.ts +58 -0
  187. package/viewer/viewerManager.js +91 -0
  188. package/viewer/viewerManager.js.map +1 -0
  189. package/viewer/viewerWithTemplate.d.ts +9 -0
  190. package/viewer/viewerWithTemplate.js +20 -0
  191. package/viewer/viewerWithTemplate.js.map +1 -0
  192. package/dist/babylon-viewer.esm.js +0 -2
  193. package/dist/babylon-viewer.esm.js.map +0 -1
  194. package/dist/babylon-viewer.esm.min.js +0 -2
  195. package/dist/babylon-viewer.esm.min.js.map +0 -1
  196. package/dist/chunks/basisTextureLoader-BnIeLUi5.esm.min.js +0 -2
  197. package/dist/chunks/basisTextureLoader-BnIeLUi5.esm.min.js.map +0 -1
  198. package/dist/chunks/basisTextureLoader-D5DAa_qR.esm.js +0 -600
  199. package/dist/chunks/basisTextureLoader-D5DAa_qR.esm.js.map +0 -1
  200. package/dist/chunks/ddsTextureLoader-D9xNsYAT.esm.min.js +0 -2
  201. package/dist/chunks/ddsTextureLoader-D9xNsYAT.esm.min.js.map +0 -1
  202. package/dist/chunks/ddsTextureLoader-DCv39Yn8.esm.js +0 -87
  203. package/dist/chunks/ddsTextureLoader-DCv39Yn8.esm.js.map +0 -1
  204. package/dist/chunks/envTextureLoader-Cmuugxf1.esm.min.js +0 -2
  205. package/dist/chunks/envTextureLoader-Cmuugxf1.esm.min.js.map +0 -1
  206. package/dist/chunks/envTextureLoader-Dl0xiO1G.esm.js +0 -62
  207. package/dist/chunks/envTextureLoader-Dl0xiO1G.esm.js.map +0 -1
  208. package/dist/chunks/exrTextureLoader-C0UEUMfH.esm.js +0 -1682
  209. package/dist/chunks/exrTextureLoader-C0UEUMfH.esm.js.map +0 -1
  210. package/dist/chunks/exrTextureLoader-DVZGHvAz.esm.min.js +0 -2
  211. package/dist/chunks/exrTextureLoader-DVZGHvAz.esm.min.js.map +0 -1
  212. package/dist/chunks/hdrTextureLoader-BM271mLj.esm.min.js +0 -2
  213. package/dist/chunks/hdrTextureLoader-BM271mLj.esm.min.js.map +0 -1
  214. package/dist/chunks/hdrTextureLoader-CrHh5vTV.esm.js +0 -252
  215. package/dist/chunks/hdrTextureLoader-CrHh5vTV.esm.js.map +0 -1
  216. package/dist/chunks/helperFunctions-BQ8X1piK.esm.min.js +0 -2
  217. package/dist/chunks/helperFunctions-BQ8X1piK.esm.min.js.map +0 -1
  218. package/dist/chunks/helperFunctions-CUX6uz_w.esm.js +0 -108
  219. package/dist/chunks/helperFunctions-CUX6uz_w.esm.js.map +0 -1
  220. package/dist/chunks/helperFunctions-ChWwJuKv.esm.min.js +0 -2
  221. package/dist/chunks/helperFunctions-ChWwJuKv.esm.min.js.map +0 -1
  222. package/dist/chunks/helperFunctions-DpMCqZKL.esm.js +0 -80
  223. package/dist/chunks/helperFunctions-DpMCqZKL.esm.js.map +0 -1
  224. package/dist/chunks/index-DHuuBhpP.esm.js +0 -102146
  225. package/dist/chunks/index-DHuuBhpP.esm.js.map +0 -1
  226. package/dist/chunks/index-EA8kJjBu.esm.min.js +0 -56
  227. package/dist/chunks/index-EA8kJjBu.esm.min.js.map +0 -1
  228. package/dist/chunks/ktxTextureLoader-BRR5FQro.esm.min.js +0 -2
  229. package/dist/chunks/ktxTextureLoader-BRR5FQro.esm.min.js.map +0 -1
  230. package/dist/chunks/ktxTextureLoader-gZQU7w7m.esm.js +0 -813
  231. package/dist/chunks/ktxTextureLoader-gZQU7w7m.esm.js.map +0 -1
  232. package/dist/chunks/logDepthDeclaration-B1MaqbwG.esm.min.js +0 -2
  233. package/dist/chunks/logDepthDeclaration-B1MaqbwG.esm.min.js.map +0 -1
  234. package/dist/chunks/logDepthDeclaration-B2UkQWK5.esm.min.js +0 -2
  235. package/dist/chunks/logDepthDeclaration-B2UkQWK5.esm.min.js.map +0 -1
  236. package/dist/chunks/logDepthDeclaration-COhUDa1N.esm.js +0 -73
  237. package/dist/chunks/logDepthDeclaration-COhUDa1N.esm.js.map +0 -1
  238. package/dist/chunks/logDepthDeclaration-CojhsbFY.esm.js +0 -76
  239. package/dist/chunks/logDepthDeclaration-CojhsbFY.esm.js.map +0 -1
  240. package/dist/chunks/pass.fragment-BNKAdmAy.esm.min.js +0 -2
  241. package/dist/chunks/pass.fragment-BNKAdmAy.esm.min.js.map +0 -1
  242. package/dist/chunks/pass.fragment-CDiei_Sn.esm.js +0 -15
  243. package/dist/chunks/pass.fragment-CDiei_Sn.esm.js.map +0 -1
  244. package/dist/chunks/pbr.fragment-BN71FgFx.esm.min.js +0 -2
  245. package/dist/chunks/pbr.fragment-BN71FgFx.esm.min.js.map +0 -1
  246. package/dist/chunks/pbr.fragment-BvCEmvwh.esm.js +0 -4530
  247. package/dist/chunks/pbr.fragment-BvCEmvwh.esm.js.map +0 -1
  248. package/dist/chunks/pbr.fragment-DU4hy3T_.esm.min.js +0 -2
  249. package/dist/chunks/pbr.fragment-DU4hy3T_.esm.min.js.map +0 -1
  250. package/dist/chunks/pbr.fragment-QxF1RFoh.esm.js +0 -4323
  251. package/dist/chunks/pbr.fragment-QxF1RFoh.esm.js.map +0 -1
  252. package/dist/chunks/pbr.vertex-62J9fbA6.esm.js +0 -932
  253. package/dist/chunks/pbr.vertex-62J9fbA6.esm.js.map +0 -1
  254. package/dist/chunks/pbr.vertex-C8vOdMd6.esm.min.js +0 -2
  255. package/dist/chunks/pbr.vertex-C8vOdMd6.esm.min.js.map +0 -1
  256. package/dist/chunks/pbr.vertex-Cp4yABqq.esm.js +0 -809
  257. package/dist/chunks/pbr.vertex-Cp4yABqq.esm.js.map +0 -1
  258. package/dist/chunks/pbr.vertex-DPPPQSbX.esm.min.js +0 -2
  259. package/dist/chunks/pbr.vertex-DPPPQSbX.esm.min.js.map +0 -1
  260. package/dist/chunks/postprocess.vertex-5WWqPw1s.esm.js +0 -20
  261. package/dist/chunks/postprocess.vertex-5WWqPw1s.esm.js.map +0 -1
  262. package/dist/chunks/postprocess.vertex-DzqXlss5.esm.min.js +0 -2
  263. package/dist/chunks/postprocess.vertex-DzqXlss5.esm.min.js.map +0 -1
  264. package/dist/chunks/rgbdDecode.fragment-BdggM8VZ.esm.min.js +0 -2
  265. package/dist/chunks/rgbdDecode.fragment-BdggM8VZ.esm.min.js.map +0 -1
  266. package/dist/chunks/rgbdDecode.fragment-Bpslxg4R.esm.js +0 -17
  267. package/dist/chunks/rgbdDecode.fragment-Bpslxg4R.esm.js.map +0 -1
  268. package/dist/chunks/rgbdDecode.fragment-By7Rc7Xz.esm.js +0 -17
  269. package/dist/chunks/rgbdDecode.fragment-By7Rc7Xz.esm.js.map +0 -1
  270. package/dist/chunks/rgbdDecode.fragment-CnUoEV03.esm.min.js +0 -2
  271. package/dist/chunks/rgbdDecode.fragment-CnUoEV03.esm.min.js.map +0 -1
  272. package/dist/chunks/rgbdEncode.fragment-BBl79-3e.esm.js +0 -17
  273. package/dist/chunks/rgbdEncode.fragment-BBl79-3e.esm.js.map +0 -1
  274. package/dist/chunks/rgbdEncode.fragment-BGkuZmHn.esm.min.js +0 -2
  275. package/dist/chunks/rgbdEncode.fragment-BGkuZmHn.esm.min.js.map +0 -1
  276. package/dist/chunks/rgbdEncode.fragment-LUPpF87m.esm.min.js +0 -2
  277. package/dist/chunks/rgbdEncode.fragment-LUPpF87m.esm.min.js.map +0 -1
  278. package/dist/chunks/rgbdEncode.fragment-PJDNuVns.esm.js +0 -17
  279. package/dist/chunks/rgbdEncode.fragment-PJDNuVns.esm.js.map +0 -1
  280. package/dist/chunks/tgaTextureLoader-CccJYauf.esm.min.js +0 -2
  281. package/dist/chunks/tgaTextureLoader-CccJYauf.esm.min.js.map +0 -1
  282. package/dist/chunks/tgaTextureLoader-DdDpL5u3.esm.js +0 -349
  283. package/dist/chunks/tgaTextureLoader-DdDpL5u3.esm.js.map +0 -1
  284. package/lib/index.d.ts +0 -237
  285. package/lib/index.js +0 -869
  286. package/lib/index.js.map +0 -1
@@ -1,56 +0,0 @@
1
- function e(e,t,s,i){var r,n=arguments.length,a=n<3?t:null===i?i=Object.getOwnPropertyDescriptor(t,s):i;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,s,i);else for(var o=e.length-1;o>=0;o--)(r=e[o])&&(a=(n<3?r(a):n>3?r(t,s,a):r(t,s))||a);return n>3&&a&&Object.defineProperty(t,s,a),a}"function"==typeof SuppressedError&&SuppressedError;const t={},s={};function i(e){const i=e.getClassName();if(t[i])return t[i];t[i]={};const r=t[i];let n=e,a=i;for(;a;){const e=s[a];for(const t in e)r[t]=e[t];let t,i=!1;do{if(t=Object.getPrototypeOf(n),!t.getClassName){i=!0;break}if(t.getClassName()!==a)break;n=t}while(t);if(i)break;a=t.getClassName(),n=t}return r}function r(e,t){return(i,r)=>{const n=function(e){const t=e.getClassName();return s[t]||(s[t]={}),s[t]}(i);n[r]||(n[r]={type:e,sourceName:t})}}function n(e,t=null){return function(e,t=null){return(s,i)=>{const r=t||"_"+i;Object.defineProperty(s,i,{get:function(){return this[r]},set:function(t){"function"==typeof this.equals&&this.equals(t)||this[r]!==t&&(this[r]=t,s[e].apply(this))},enumerable:!0,configurable:!0})}}(e,t)}function a(e){return r(0,e)}function o(e){return r(1,e)}function h(e){return r(2,e)}function l(e){return r(4,e)}function c(e){return r(5,e)}function u(e){return r(6,e)}function d(e){return r(8,e)}function _(e){return r(12,e)}function f(e,t,s,i){const r=s.value;s.value=(...s)=>{let n=r;if("undefined"!=typeof _native&&_native[t]){const e=_native[t];n=i?(...t)=>i(...t)?e(...t):r(...t):e}return e[t]=n,n(...s)}}f.filter=function(e){return(t,s,i)=>f(t,s,i,e)};class p{constructor(e,t=!1,s,i){this.initialize(e,t,s,i)}initialize(e,t=!1,s,i){return this.mask=e,this.skipNextObservers=t,this.target=s,this.currentTarget=i,this}}class m{constructor(e,t,s=null){this.callback=e,this.mask=t,this.scope=s,this._willBeUnregistered=!1,this.unregisterOnNextCall=!1,this._remove=null}remove(){this._remove&&this._remove()}}class g{static FromPromise(e,t){const s=new g;return e.then((e=>{s.notifyObservers(e)})).catch((e=>{if(!t)throw e;t.notifyObservers(e)})),s}get observers(){return this._observers}constructor(e,t=!1){this.notifyIfTriggered=t,this._observers=new Array,this._numObserversMarkedAsDeleted=0,this._hasNotified=!1,this._eventState=new p(0),e&&(this._onObserverAdded=e)}add(e,t=-1,s=!1,i=null,r=!1){if(!e)return null;const n=new m(e,t,i);return n.unregisterOnNextCall=r,s?this._observers.unshift(n):this._observers.push(n),this._onObserverAdded&&this._onObserverAdded(n),this._hasNotified&&this.notifyIfTriggered&&void 0!==this._lastNotifiedValue&&this.notifyObserver(n,this._lastNotifiedValue),n._remove=()=>{this.remove(n)},n}addOnce(e){return this.add(e,void 0,void 0,void 0,!0)}remove(e){if(!e)return!1;e._remove=null;return-1!==this._observers.indexOf(e)&&(this._deferUnregister(e),!0)}removeCallback(e,t){for(let s=0;s<this._observers.length;s++){const i=this._observers[s];if(!i._willBeUnregistered&&(i.callback===e&&(!t||t===i.scope)))return this._deferUnregister(i),!0}return!1}_deferUnregister(e){e._willBeUnregistered||(this._numObserversMarkedAsDeleted++,e.unregisterOnNextCall=!1,e._willBeUnregistered=!0,setTimeout((()=>{this._remove(e)}),0))}_remove(e,t=!0){if(!e)return!1;const s=this._observers.indexOf(e);return-1!==s&&(t&&this._numObserversMarkedAsDeleted--,this._observers.splice(s,1),!0)}makeObserverTopPriority(e){this._remove(e,!1),this._observers.unshift(e)}makeObserverBottomPriority(e){this._remove(e,!1),this._observers.push(e)}notifyObservers(e,t=-1,s,i,r){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=e),!this._observers.length)return!0;const n=this._eventState;n.mask=t,n.target=s,n.currentTarget=i,n.skipNextObservers=!1,n.lastReturnValue=e,n.userInfo=r;for(const s of this._observers)if(!s._willBeUnregistered&&(s.mask&t&&(s.unregisterOnNextCall&&this._deferUnregister(s),s.scope?n.lastReturnValue=s.callback.apply(s.scope,[e,n]):n.lastReturnValue=s.callback(e,n)),n.skipNextObservers))return!1;return!0}notifyObserver(e,t,s=-1){if(this.notifyIfTriggered&&(this._hasNotified=!0,this._lastNotifiedValue=t),e._willBeUnregistered)return;const i=this._eventState;i.mask=s,i.skipNextObservers=!1,e.unregisterOnNextCall&&this._deferUnregister(e),e.callback(t,i)}hasObservers(){return this._observers.length-this._numObserversMarkedAsDeleted>0}clear(){for(;this._observers.length;){const e=this._observers.pop();e&&(e._remove=null)}this._onObserverAdded=null,this._numObserversMarkedAsDeleted=0,this.cleanLastNotifiedState()}cleanLastNotifiedState(){this._hasNotified=!1,this._lastNotifiedValue=void 0}clone(){const e=new g;return e._observers=this._observers.slice(0),e}hasSpecificMask(e=-1){for(const t of this._observers)if(t.mask&e||t.mask===e)return!0;return!1}}const T=1/2.2,E=2.2,A=.001;function y(e,t){const s=[];for(let i=0;i<e;++i)s.push(t());return s}function b(e,t){return y(e,t)}const R=["push","splice","pop","shift","unshift"];function x(e,t){const s=R.map((s=>function(e,t,s){const i=e[t];if("function"!=typeof i)return null;const r=function(){const i=e.length,n=r.previous.apply(e,arguments);return s(t,i),n};return i.next=r,r.previous=i,e[t]=r,()=>{const s=r.previous;if(!s)return;const i=r.next;i?(s.next=i,i.previous=s):(s.next=void 0,e[t]=s),r.next=void 0,r.previous=void 0}}(e,s,t)));return()=>{s.forEach((e=>{e?.()}))}}const M={};function I(e,t){M[e]=t}function S(e){return M[e]}class v{static SetMatrixPrecision(e){if(v.MatrixTrackPrecisionChange=!1,e&&!v.MatrixUse64Bits&&v.MatrixTrackedMatrices)for(let e=0;e<v.MatrixTrackedMatrices.length;++e){const t=v.MatrixTrackedMatrices[e],s=t._m;t._m=new Array(16);for(let e=0;e<16;++e)t._m[e]=s[e]}v.MatrixUse64Bits=e,v.MatrixCurrentType=v.MatrixUse64Bits?Array:Float32Array,v.MatrixTrackedMatrices=null}}v.MatrixUse64Bits=!1,v.MatrixTrackPrecisionChange=!0,v.MatrixCurrentType=Float32Array,v.MatrixTrackedMatrices=[];class C{static get LastCreatedEngine(){return 0===this.Instances.length?null:this.Instances[this.Instances.length-1]}static get LastCreatedScene(){return this._LastCreatedScene}}function P(e,t,s=1401298e-51){return Math.abs(e-t)<=s}function O(e,t){return e===t?e:Math.random()*(t-e)+e}function D(e,t,s){return e+(t-e)*s}function L(e,t=0,s=1){return Math.min(s,Math.max(t,e))}function F(e){return e-=2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function N(e){const t=e.toString(16);return e<=15?("0"+t).toUpperCase():t.toUpperCase()}C.Instances=[],C.OnEnginesDisposedObservable=new g,C._LastCreatedScene=null,C.UseFallbackTexture=!0,C.FallbackTexture="";const w=e=>parseInt(e.toString().replace(/\W/g,""));class B{constructor(e=0,t=0){this.x=e,this.y=t}toString(){return`{X: ${this.x} Y: ${this.y}}`}getClassName(){return"Vector2"}getHashCode(){let e=w(this.x);return e=397*e^w(this.y),e}toArray(e,t=0){return e[t]=this.x,e[t+1]=this.y,this}fromArray(e,t=0){return B.FromArrayToRef(e,t,this),this}asArray(){return[this.x,this.y]}copyFrom(e){return this.x=e.x,this.y=e.y,this}copyFromFloats(e,t){return this.x=e,this.y=t,this}set(e,t){return this.copyFromFloats(e,t)}setAll(e){return this.copyFromFloats(e,e)}add(e){return new B(this.x+e.x,this.y+e.y)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t}addInPlace(e){return this.x+=e.x,this.y+=e.y,this}addInPlaceFromFloats(e,t){return this.x+=e,this.y+=t,this}addVector3(e){return new B(this.x+e.x,this.y+e.y)}subtract(e){return new B(this.x-e.x,this.y-e.y)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this}multiply(e){return new B(this.x*e.x,this.y*e.y)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t}multiplyByFloats(e,t){return new B(this.x*e,this.y*t)}divide(e){return new B(this.x/e.x,this.y/e.y)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t}divideInPlace(e){return this.x=this.x/e.x,this.y=this.y/e.y,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.x,e.y)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.x,e.y)}minimizeInPlaceFromFloats(e,t){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this}maximizeInPlaceFromFloats(e,t){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this}subtractFromFloats(e,t){return new B(this.x-e,this.y-t)}subtractFromFloatsToRef(e,t,s){return s.x=this.x-e,s.y=this.y-t,s}negate(){return new B(-this.x,-this.y)}negateInPlace(){return this.x*=-1,this.y*=-1,this}negateToRef(e){return e.x=-this.x,e.y=-this.y,e}scaleInPlace(e){return this.x*=e,this.y*=e,this}scale(e){return new B(this.x*e,this.y*e)}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y}equalsWithEpsilon(e,t=A){return e&&P(this.x,e.x,t)&&P(this.y,e.y,t)}equalsToFloats(e,t){return this.x===e&&this.y===t}floor(){return new B(Math.floor(this.x),Math.floor(this.y))}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e}fract(){return new B(this.x-Math.floor(this.x),this.y-Math.floor(this.y))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e}rotateToRef(e,t){const s=Math.cos(e),i=Math.sin(e),r=s*this.x-i*this.y,n=i*this.x+s*this.y;return t.x=r,t.y=n,t}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}lengthSquared(){return this.x*this.x+this.y*this.y}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new B;return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t&&(e.x=this.x,e.y=this.y),this.scaleToRef(1/t,e)}clone(){return new B(this.x,this.y)}dot(e){return this.x*e.x+this.y*e.y}static Zero(){return new B(0,0)}static One(){return new B(1,1)}static Random(e=0,t=1){return new B(O(e,t),O(e,t))}static RandomToRef(e=0,t=1,s){return s.copyFromFloats(O(e,t),O(e,t))}static get ZeroReadOnly(){return B._ZeroReadOnly}static FromArray(e,t=0){return new B(e[t],e[t+1])}static FromArrayToRef(e,t,s){return s.x=e[t],s.y=e[t+1],s}static FromFloatsToRef(e,t,s){return s.copyFromFloats(e,t),s}static CatmullRom(e,t,s,i,r){const n=r*r,a=r*n,o=.5*(2*t.x+(-e.x+s.x)*r+(2*e.x-5*t.x+4*s.x-i.x)*n+(-e.x+3*t.x-3*s.x+i.x)*a),h=.5*(2*t.y+(-e.y+s.y)*r+(2*e.y-5*t.y+4*s.y-i.y)*n+(-e.y+3*t.y-3*s.y+i.y)*a);return new B(o,h)}static ClampToRef(e,t,s,i){return i.x=L(e.x,t.x,s.x),i.y=L(e.y,t.y,s.y),i}static Clamp(e,t,s){const i=L(e.x,t.x,s.x),r=L(e.y,t.y,s.y);return new B(i,r)}static Hermite(e,t,s,i,r){const n=r*r,a=r*n,o=2*a-3*n+1,h=-2*a+3*n,l=a-2*n+r,c=a-n,u=e.x*o+s.x*h+t.x*l+i.x*c,d=e.y*o+s.y*h+t.y*l+i.y*c;return new B(u,d)}static Hermite1stDerivative(e,t,s,i,r){return this.Hermite1stDerivativeToRef(e,t,s,i,r,new B)}static Hermite1stDerivativeToRef(e,t,s,i,r,n){const a=r*r;return n.x=6*(a-r)*e.x+(3*a-4*r+1)*t.x+6*(-a+r)*s.x+(3*a-2*r)*i.x,n.y=6*(a-r)*e.y+(3*a-4*r+1)*t.y+6*(-a+r)*s.y+(3*a-2*r)*i.y,n}static Lerp(e,t,s){return B.LerpToRef(e,t,s,new B)}static LerpToRef(e,t,s,i){return i.x=e.x+(t.x-e.x)*s,i.y=e.y+(t.y-e.y)*s,i}static Dot(e,t){return e.x*t.x+e.y*t.y}static Normalize(e){return B.NormalizeToRef(e,new B)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const s=e.x<t.x?e.x:t.x,i=e.y<t.y?e.y:t.y;return new B(s,i)}static Maximize(e,t){const s=e.x>t.x?e.x:t.x,i=e.y>t.y?e.y:t.y;return new B(s,i)}static Transform(e,t){return B.TransformToRef(e,t,new B)}static TransformToRef(e,t,s){const i=t.m,r=e.x*i[0]+e.y*i[4]+i[12],n=e.x*i[1]+e.y*i[5]+i[13];return s.x=r,s.y=n,s}static PointInTriangle(e,t,s,i){const r=.5*(-s.y*i.x+t.y*(-s.x+i.x)+t.x*(s.y-i.y)+s.x*i.y),n=r<0?-1:1,a=(t.y*i.x-t.x*i.y+(i.y-t.y)*e.x+(t.x-i.x)*e.y)*n,o=(t.x*s.y-t.y*s.x+(t.y-s.y)*e.x+(s.x-t.x)*e.y)*n;return a>0&&o>0&&a+o<2*r*n}static Distance(e,t){return Math.sqrt(B.DistanceSquared(e,t))}static DistanceSquared(e,t){const s=e.x-t.x,i=e.y-t.y;return s*s+i*i}static Center(e,t){return B.CenterToRef(e,t,new B)}static CenterToRef(e,t,s){return s.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2)}static DistanceOfPointFromSegment(e,t,s){const i=B.DistanceSquared(t,s);if(0===i)return B.Distance(e,t);const r=s.subtract(t),n=Math.max(0,Math.min(1,B.Dot(e.subtract(t),r)/i)),a=t.add(r.multiplyByFloats(n,n));return B.Distance(e,a)}}B._ZeroReadOnly=B.Zero(),Object.defineProperties(B.prototype,{dimension:{value:[2]},rank:{value:1}});class U{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}constructor(e=0,t=0,s=0){this._isDirty=!0,this._x=e,this._y=t,this._z=s}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z}}`}getClassName(){return"Vector3"}getHashCode(){let e=w(this._x);return e=397*e^w(this._y),e=397*e^w(this._z),e}asArray(){return[this._x,this._y,this._z]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,this}fromArray(e,t=0){return U.FromArrayToRef(e,t,this),this}toQuaternion(){return G.RotationYawPitchRoll(this._y,this._x,this._z)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._isDirty=!0,this}addInPlaceFromFloats(e,t,s){return this._x+=e,this._y+=t,this._z+=s,this._isDirty=!0,this}add(e){return new U(this._x+e._x,this._y+e._y,this._z+e._z)}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._isDirty=!0,t}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._isDirty=!0,this}subtract(e){return new U(this._x-e._x,this._y-e._y,this._z-e._z)}subtractToRef(e,t){return this.subtractFromFloatsToRef(e._x,e._y,e._z,t)}subtractFromFloats(e,t,s){return new U(this._x-e,this._y-t,this._z-s)}subtractFromFloatsToRef(e,t,s,i){return i._x=this._x-e,i._y=this._y-t,i._z=this._z-s,i._isDirty=!0,i}negate(){return new U(-this._x,-this._y,-this._z)}negateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}negateToRef(e){return e._x=-1*this._x,e._y=-1*this._y,e._z=-1*this._z,e._isDirty=!0,e}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._isDirty=!0,this}scale(e){return new U(this._x*e,this._y*e,this._z*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._isDirty=!0,t}getNormalToRef(e){const t=this.length();let s=Math.acos(this.y/t);const i=Math.atan2(this.z,this.x);s>Math.PI/2?s-=Math.PI/2:s+=Math.PI/2;const r=t*Math.sin(s)*Math.cos(i),n=t*Math.cos(s),a=t*Math.sin(s)*Math.sin(i);return e.set(r,n,a),e}applyRotationQuaternionToRef(e,t){const s=this._x,i=this._y,r=this._z,n=e._x,a=e._y,o=e._z,h=e._w,l=2*(a*r-o*i),c=2*(o*s-n*r),u=2*(n*i-a*s);return t._x=s+h*l+a*u-o*c,t._y=i+h*c+o*l-n*u,t._z=r+h*u+n*c-a*l,t._isDirty=!0,t}applyRotationQuaternionInPlace(e){return this.applyRotationQuaternionToRef(e,this)}applyRotationQuaternion(e){return this.applyRotationQuaternionToRef(e,new U)}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._isDirty=!0,t}projectOnPlane(e,t){return this.projectOnPlaneToRef(e,t,new U)}projectOnPlaneToRef(e,t,s){const i=e.normal,r=e.d,n=H.Vector3[0];this.subtractToRef(t,n),n.normalize();const a=U.Dot(n,i);if(Math.abs(a)<1e-10)s.setAll(1/0);else{const e=-(U.Dot(t,i)+r)/a,o=n.scaleInPlace(e);t.addToRef(o,s)}return s}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z}equalsWithEpsilon(e,t=A){return e&&P(this._x,e._x,t)&&P(this._y,e._y,t)&&P(this._z,e._z,t)}equalsToFloats(e,t,s){return this._x===e&&this._y===t&&this._z===s}multiplyInPlace(e){return this._x*=e._x,this._y*=e._y,this._z*=e._z,this._isDirty=!0,this}multiply(e){return this.multiplyByFloats(e._x,e._y,e._z)}multiplyToRef(e,t){return t._x=this._x*e._x,t._y=this._y*e._y,t._z=this._z*e._z,t._isDirty=!0,t}multiplyByFloats(e,t,s){return new U(this._x*e,this._y*t,this._z*s)}divide(e){return new U(this._x/e._x,this._y/e._y,this._z/e._z)}divideToRef(e,t){return t._x=this._x/e._x,t._y=this._y/e._y,t._z=this._z/e._z,t._isDirty=!0,t}divideInPlace(e){return this._x=this._x/e._x,this._y=this._y/e._y,this._z=this._z/e._z,this._isDirty=!0,this}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e._x,e._y,e._z)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e._x,e._y,e._z)}minimizeInPlaceFromFloats(e,t,s){return e<this._x&&(this.x=e),t<this._y&&(this.y=t),s<this._z&&(this.z=s),this}maximizeInPlaceFromFloats(e,t,s){return e>this._x&&(this.x=e),t>this._y&&(this.y=t),s>this._z&&(this.z=s),this}isNonUniformWithinEpsilon(e){const t=Math.abs(this._x),s=Math.abs(this._y);if(!P(t,s,e))return!0;const i=Math.abs(this._z);return!P(t,i,e)||!P(s,i,e)}get isNonUniform(){const e=Math.abs(this._x);if(e!==Math.abs(this._y))return!0;return e!==Math.abs(this._z)}floorToRef(e){return e._x=Math.floor(this._x),e._y=Math.floor(this._y),e._z=Math.floor(this._z),e._isDirty=!0,e}floor(){return new U(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z))}fractToRef(e){return e._x=this.x-Math.floor(this._x),e._y=this.y-Math.floor(this._y),e._z=this.z-Math.floor(this._z),e._isDirty=!0,e}fract(){return new U(this.x-Math.floor(this._x),this.y-Math.floor(this._y),this.z-Math.floor(this._z))}length(){return Math.sqrt(this.lengthSquared())}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z}get hasAZeroComponent(){return this._x*this._y*this._z==0}normalize(){return this.normalizeFromLength(this.length())}reorderInPlace(e){if("xyz"===(e=e.toLowerCase()))return this;const t=H.Vector3[0].copyFrom(this);return this.x=t[e[0]],this.y=t[e[1]],this.z=t[e[2]],this}rotateByQuaternionToRef(e,t){return e.toRotationMatrix(H.Matrix[0]),U.TransformCoordinatesToRef(this,H.Matrix[0],t),t}rotateByQuaternionAroundPointToRef(e,t,s){return this.subtractToRef(t,H.Vector3[0]),H.Vector3[0].rotateByQuaternionToRef(e,H.Vector3[0]),t.addToRef(H.Vector3[0],s),s}cross(e){return U.CrossToRef(this,e,new U)}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new U)}normalizeToRef(e){const t=this.length();return 0===t||1===t?(e._x=this._x,e._y=this._y,e._z=this._z,e._isDirty=!0,e):this.scaleToRef(1/t,e)}clone(){return new U(this._x,this._y,this._z)}copyFrom(e){return this.copyFromFloats(e._x,e._y,e._z)}copyFromFloats(e,t,s){return this._x=e,this._y=t,this._z=s,this._isDirty=!0,this}set(e,t,s){return this.copyFromFloats(e,t,s)}setAll(e){return this._x=this._y=this._z=e,this._isDirty=!0,this}static GetClipFactor(e,t,s,i){const r=U.Dot(e,s);return(r-i)/(r-U.Dot(t,s))}static GetAngleBetweenVectors(e,t,s){const i=e.normalizeToRef(H.Vector3[1]),r=t.normalizeToRef(H.Vector3[2]);let n=U.Dot(i,r);n=L(n,-1,1);const a=Math.acos(n),o=H.Vector3[3];return U.CrossToRef(i,r,o),U.Dot(o,s)>0?isNaN(a)?0:a:isNaN(a)?-Math.PI:-Math.acos(n)}static GetAngleBetweenVectorsOnPlane(e,t,s){H.Vector3[0].copyFrom(e);const i=H.Vector3[0];H.Vector3[1].copyFrom(t);const r=H.Vector3[1];H.Vector3[2].copyFrom(s);const n=H.Vector3[2],a=H.Vector3[3],o=H.Vector3[4];i.normalize(),r.normalize(),n.normalize(),U.CrossToRef(n,i,a),U.CrossToRef(a,n,o);return F(Math.atan2(U.Dot(r,a),U.Dot(r,o)))}static PitchYawRollToMoveBetweenPointsToRef(e,t,s){const i=z.Vector3[0];return t.subtractToRef(e,i),s._y=Math.atan2(i.x,i.z)||0,s._x=Math.atan2(Math.sqrt(i.x**2+i.z**2),i.y)||0,s._z=0,s._isDirty=!0,s}static PitchYawRollToMoveBetweenPoints(e,t){const s=U.Zero();return U.PitchYawRollToMoveBetweenPointsToRef(e,t,s)}static SlerpToRef(e,t,s,i){s=L(s,0,1);const r=H.Vector3[0],n=H.Vector3[1];r.copyFrom(e);const a=r.length();r.normalizeFromLength(a),n.copyFrom(t);const o=n.length();n.normalizeFromLength(o);const h=U.Dot(r,n);let l,c;if(h<1-A){const e=Math.acos(h),t=1/Math.sin(e);l=Math.sin((1-s)*e)*t,c=Math.sin(s*e)*t}else l=1-s,c=s;return r.scaleInPlace(l),n.scaleInPlace(c),i.copyFrom(r).addInPlace(n),i.scaleInPlace(D(a,o,s)),i}static SmoothToRef(e,t,s,i,r){return U.SlerpToRef(e,t,0===i?1:s/i,r),r}static FromArray(e,t=0){return new U(e[t],e[t+1],e[t+2])}static FromFloatArray(e,t){return U.FromArray(e,t)}static FromArrayToRef(e,t,s){return s._x=e[t],s._y=e[t+1],s._z=e[t+2],s._isDirty=!0,s}static FromFloatArrayToRef(e,t,s){return U.FromArrayToRef(e,t,s)}static FromFloatsToRef(e,t,s,i){return i.copyFromFloats(e,t,s),i}static Zero(){return new U(0,0,0)}static One(){return new U(1,1,1)}static Up(){return new U(0,1,0)}static get UpReadOnly(){return U._UpReadOnly}static get DownReadOnly(){return U._DownReadOnly}static get RightReadOnly(){return U._RightReadOnly}static get LeftReadOnly(){return U._LeftReadOnly}static get LeftHandedForwardReadOnly(){return U._LeftHandedForwardReadOnly}static get RightHandedForwardReadOnly(){return U._RightHandedForwardReadOnly}static get LeftHandedBackwardReadOnly(){return U._LeftHandedBackwardReadOnly}static get RightHandedBackwardReadOnly(){return U._RightHandedBackwardReadOnly}static get ZeroReadOnly(){return U._ZeroReadOnly}static get OneReadOnly(){return U._OneReadOnly}static Down(){return new U(0,-1,0)}static Forward(e=!1){return new U(0,0,e?-1:1)}static Backward(e=!1){return new U(0,0,e?1:-1)}static Right(){return new U(1,0,0)}static Left(){return new U(-1,0,0)}static Random(e=0,t=1){return new U(O(e,t),O(e,t),O(e,t))}static RandomToRef(e=0,t=1,s){return s.copyFromFloats(O(e,t),O(e,t),O(e,t))}static TransformCoordinates(e,t){const s=U.Zero();return U.TransformCoordinatesToRef(e,t,s),s}static TransformCoordinatesToRef(e,t,s){return U.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,s),s}static TransformCoordinatesFromFloatsToRef(e,t,s,i,r){const n=i.m,a=e*n[0]+t*n[4]+s*n[8]+n[12],o=e*n[1]+t*n[5]+s*n[9]+n[13],h=e*n[2]+t*n[6]+s*n[10]+n[14],l=1/(e*n[3]+t*n[7]+s*n[11]+n[15]);return r._x=a*l,r._y=o*l,r._z=h*l,r._isDirty=!0,r}static TransformNormal(e,t){const s=U.Zero();return U.TransformNormalToRef(e,t,s),s}static TransformNormalToRef(e,t,s){return this.TransformNormalFromFloatsToRef(e._x,e._y,e._z,t,s),s}static TransformNormalFromFloatsToRef(e,t,s,i,r){const n=i.m;return r._x=e*n[0]+t*n[4]+s*n[8],r._y=e*n[1]+t*n[5]+s*n[9],r._z=e*n[2]+t*n[6]+s*n[10],r._isDirty=!0,r}static CatmullRom(e,t,s,i,r){const n=r*r,a=r*n,o=.5*(2*t._x+(-e._x+s._x)*r+(2*e._x-5*t._x+4*s._x-i._x)*n+(-e._x+3*t._x-3*s._x+i._x)*a),h=.5*(2*t._y+(-e._y+s._y)*r+(2*e._y-5*t._y+4*s._y-i._y)*n+(-e._y+3*t._y-3*s._y+i._y)*a),l=.5*(2*t._z+(-e._z+s._z)*r+(2*e._z-5*t._z+4*s._z-i._z)*n+(-e._z+3*t._z-3*s._z+i._z)*a);return new U(o,h,l)}static Clamp(e,t,s){const i=new U;return U.ClampToRef(e,t,s,i),i}static ClampToRef(e,t,s,i){let r=e._x;r=r>s._x?s._x:r,r=r<t._x?t._x:r;let n=e._y;n=n>s._y?s._y:n,n=n<t._y?t._y:n;let a=e._z;return a=a>s._z?s._z:a,a=a<t._z?t._z:a,i.copyFromFloats(r,n,a),i}static CheckExtends(e,t,s){t.minimizeInPlace(e),s.maximizeInPlace(e)}static Hermite(e,t,s,i,r){const n=r*r,a=r*n,o=2*a-3*n+1,h=-2*a+3*n,l=a-2*n+r,c=a-n,u=e._x*o+s._x*h+t._x*l+i._x*c,d=e._y*o+s._y*h+t._y*l+i._y*c,_=e._z*o+s._z*h+t._z*l+i._z*c;return new U(u,d,_)}static Hermite1stDerivative(e,t,s,i,r){const n=new U;return this.Hermite1stDerivativeToRef(e,t,s,i,r,n),n}static Hermite1stDerivativeToRef(e,t,s,i,r,n){const a=r*r;return n._x=6*(a-r)*e._x+(3*a-4*r+1)*t._x+6*(-a+r)*s._x+(3*a-2*r)*i._x,n._y=6*(a-r)*e._y+(3*a-4*r+1)*t._y+6*(-a+r)*s._y+(3*a-2*r)*i._y,n._z=6*(a-r)*e._z+(3*a-4*r+1)*t._z+6*(-a+r)*s._z+(3*a-2*r)*i._z,n._isDirty=!0,n}static Lerp(e,t,s){const i=new U(0,0,0);return U.LerpToRef(e,t,s,i),i}static LerpToRef(e,t,s,i){return i._x=e._x+(t._x-e._x)*s,i._y=e._y+(t._y-e._y)*s,i._z=e._z+(t._z-e._z)*s,i._isDirty=!0,i}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z}static Cross(e,t){const s=new U;return U.CrossToRef(e,t,s),s}static CrossToRef(e,t,s){const i=e._y*t._z-e._z*t._y,r=e._z*t._x-e._x*t._z,n=e._x*t._y-e._y*t._x;return s.copyFromFloats(i,r,n),s}static Normalize(e){const t=U.Zero();return U.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Project(e,t,s,i){const r=new U;return U.ProjectToRef(e,t,s,i,r),r}static ProjectToRef(e,t,s,i,r){const n=i.width,a=i.height,o=i.x,h=i.y,l=H.Matrix[1],c=C.LastCreatedEngine?.isNDCHalfZRange,u=c?1:.5,d=c?0:.5;V.FromValuesToRef(n/2,0,0,0,0,-a/2,0,0,0,0,u,0,o+n/2,a/2+h,d,1,l);const _=H.Matrix[0];return t.multiplyToRef(s,_),_.multiplyToRef(l,_),U.TransformCoordinatesToRef(e,_,r),r}static Reflect(e,t){return this.ReflectToRef(e,t,new U)}static ReflectToRef(e,t,s){const i=z.Vector3[0];return i.copyFrom(t).scaleInPlace(2*U.Dot(e,t)),s.copyFrom(e).subtractInPlace(i)}static _UnprojectFromInvertedMatrixToRef(e,t,s){U.TransformCoordinatesToRef(e,t,s);const i=t.m,r=e._x*i[3]+e._y*i[7]+e._z*i[11]+i[15];return P(r,1)&&s.scaleInPlace(1/r),s}static UnprojectFromTransform(e,t,s,i,r){return this.Unproject(e,t,s,i,r,V.IdentityReadOnly)}static Unproject(e,t,s,i,r,n){const a=new U;return U.UnprojectToRef(e,t,s,i,r,n,a),a}static UnprojectToRef(e,t,s,i,r,n,a){return U.UnprojectFloatsToRef(e._x,e._y,e._z,t,s,i,r,n,a),a}static UnprojectFloatsToRef(e,t,s,i,r,n,a,o,h){const l=H.Matrix[0];n.multiplyToRef(a,l),l.multiplyToRef(o,l),l.invert();const c=H.Vector3[0];return c.x=e/i*2-1,c.y=-(t/r*2-1),C.LastCreatedEngine?.isNDCHalfZRange?c.z=s:c.z=2*s-1,U._UnprojectFromInvertedMatrixToRef(c,l,h),h}static Minimize(e,t){const s=new U;return s.copyFrom(e),s.minimizeInPlace(t),s}static Maximize(e,t){const s=new U;return s.copyFrom(e),s.maximizeInPlace(t),s}static Distance(e,t){return Math.sqrt(U.DistanceSquared(e,t))}static DistanceSquared(e,t){const s=e._x-t._x,i=e._y-t._y,r=e._z-t._z;return s*s+i*i+r*r}static ProjectOnTriangleToRef(e,t,s,i,r){const n=H.Vector3[0],a=H.Vector3[1],o=H.Vector3[2],h=H.Vector3[3],l=H.Vector3[4];s.subtractToRef(t,n),i.subtractToRef(t,a),i.subtractToRef(s,o);const c=n.length(),u=a.length(),d=o.length();if(c<A||u<A||d<A)return r.copyFrom(t),U.Distance(e,t);e.subtractToRef(t,l),U.CrossToRef(n,a,h);const _=h.length();if(_<A)return r.copyFrom(t),U.Distance(e,t);h.normalizeFromLength(_);let f=l.length();if(f<A)return r.copyFrom(t),0;l.normalizeFromLength(f);const p=U.Dot(h,l),m=H.Vector3[5],g=H.Vector3[6];m.copyFrom(h).scaleInPlace(-f*p),g.copyFrom(e).addInPlace(m);const T=H.Vector3[4],E=H.Vector3[5],y=H.Vector3[7],b=H.Vector3[8];T.copyFrom(n).scaleInPlace(1/c),b.copyFrom(a).scaleInPlace(1/u),T.addInPlace(b).scaleInPlace(-1),E.copyFrom(n).scaleInPlace(-1/c),b.copyFrom(o).scaleInPlace(1/d),E.addInPlace(b).scaleInPlace(-1),y.copyFrom(o).scaleInPlace(-1/d),b.copyFrom(a).scaleInPlace(-1/u),y.addInPlace(b).scaleInPlace(-1);const R=H.Vector3[9];let x;R.copyFrom(g).subtractInPlace(t),U.CrossToRef(T,R,b),x=U.Dot(b,h);const M=x;R.copyFrom(g).subtractInPlace(s),U.CrossToRef(E,R,b),x=U.Dot(b,h);const I=x;R.copyFrom(g).subtractInPlace(i),U.CrossToRef(y,R,b),x=U.Dot(b,h);const S=x,v=H.Vector3[10];let C,P;M>0&&I<0?(v.copyFrom(n),C=t,P=s):I>0&&S<0?(v.copyFrom(o),C=s,P=i):(v.copyFrom(a).scaleInPlace(-1),C=i,P=t);const O=H.Vector3[9],D=H.Vector3[4];C.subtractToRef(g,b),P.subtractToRef(g,O),U.CrossToRef(b,O,D);if(!(U.Dot(D,h)<0))return r.copyFrom(g),Math.abs(f*p);const F=H.Vector3[5];U.CrossToRef(v,D,F),F.normalize();const N=H.Vector3[9];N.copyFrom(C).subtractInPlace(g);const w=N.length();if(w<A)return r.copyFrom(C),U.Distance(e,C);N.normalizeFromLength(w);const B=U.Dot(F,N),k=H.Vector3[7];k.copyFrom(g).addInPlace(F.scaleInPlace(w*B)),b.copyFrom(k).subtractInPlace(C),f=v.length(),v.normalizeFromLength(f);let G=U.Dot(b,v)/Math.max(f,A);return G=L(G,0,1),k.copyFrom(C).addInPlace(v.scaleInPlace(G*f)),r.copyFrom(k),U.Distance(e,k)}static Center(e,t){return U.CenterToRef(e,t,U.Zero())}static CenterToRef(e,t,s){return s.copyFromFloats((e._x+t._x)/2,(e._y+t._y)/2,(e._z+t._z)/2)}static RotationFromAxis(e,t,s){const i=new U;return U.RotationFromAxisToRef(e,t,s,i),i}static RotationFromAxisToRef(e,t,s,i){const r=H.Quaternion[0];return G.RotationQuaternionFromAxisToRef(e,t,s,r),r.toEulerAnglesToRef(i),i}}U._UpReadOnly=U.Up(),U._DownReadOnly=U.Down(),U._LeftHandedForwardReadOnly=U.Forward(!1),U._RightHandedForwardReadOnly=U.Forward(!0),U._LeftHandedBackwardReadOnly=U.Backward(!1),U._RightHandedBackwardReadOnly=U.Backward(!0),U._RightReadOnly=U.Right(),U._LeftReadOnly=U.Left(),U._ZeroReadOnly=U.Zero(),U._OneReadOnly=U.One(),Object.defineProperties(U.prototype,{dimension:{value:[3]},rank:{value:1}});class k{constructor(e=0,t=0,s=0,i=0){this.x=e,this.y=t,this.z=s,this.w=i}toString(){return`{X: ${this.x} Y: ${this.y} Z: ${this.z} W: ${this.w}}`}getClassName(){return"Vector4"}getHashCode(){let e=w(this.x);return e=397*e^w(this.y),e=397*e^w(this.z),e=397*e^w(this.w),e}asArray(){return[this.x,this.y,this.z,this.w]}toArray(e,t){return void 0===t&&(t=0),e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,this}fromArray(e,t=0){return k.FromArrayToRef(e,t,this),this}addInPlace(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addInPlaceFromFloats(e,t,s,i){return this.x+=e,this.y+=t,this.z+=s,this.w+=i,this}add(e){return new k(this.x+e.x,this.y+e.y,this.z+e.z,this.w+e.w)}addToRef(e,t){return t.x=this.x+e.x,t.y=this.y+e.y,t.z=this.z+e.z,t.w=this.w+e.w,t}subtractInPlace(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subtract(e){return new k(this.x-e.x,this.y-e.y,this.z-e.z,this.w-e.w)}subtractToRef(e,t){return t.x=this.x-e.x,t.y=this.y-e.y,t.z=this.z-e.z,t.w=this.w-e.w,t}subtractFromFloats(e,t,s,i){return new k(this.x-e,this.y-t,this.z-s,this.w-i)}subtractFromFloatsToRef(e,t,s,i,r){return r.x=this.x-e,r.y=this.y-t,r.z=this.z-s,r.w=this.w-i,r}negate(){return new k(-this.x,-this.y,-this.z,-this.w)}negateInPlace(){return this.x*=-1,this.y*=-1,this.z*=-1,this.w*=-1,this}negateToRef(e){return e.x=-this.x,e.y=-this.y,e.z=-this.z,e.w=-this.w,e}scaleInPlace(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}scale(e){return new k(this.x*e,this.y*e,this.z*e,this.w*e)}scaleToRef(e,t){return t.x=this.x*e,t.y=this.y*e,t.z=this.z*e,t.w=this.w*e,t}scaleAndAddToRef(e,t){return t.x+=this.x*e,t.y+=this.y*e,t.z+=this.z*e,t.w+=this.w*e,t}equals(e){return e&&this.x===e.x&&this.y===e.y&&this.z===e.z&&this.w===e.w}equalsWithEpsilon(e,t=A){return e&&P(this.x,e.x,t)&&P(this.y,e.y,t)&&P(this.z,e.z,t)&&P(this.w,e.w,t)}equalsToFloats(e,t,s,i){return this.x===e&&this.y===t&&this.z===s&&this.w===i}multiplyInPlace(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiply(e){return new k(this.x*e.x,this.y*e.y,this.z*e.z,this.w*e.w)}multiplyToRef(e,t){return t.x=this.x*e.x,t.y=this.y*e.y,t.z=this.z*e.z,t.w=this.w*e.w,t}multiplyByFloats(e,t,s,i){return new k(this.x*e,this.y*t,this.z*s,this.w*i)}divide(e){return new k(this.x/e.x,this.y/e.y,this.z/e.z,this.w/e.w)}divideToRef(e,t){return t.x=this.x/e.x,t.y=this.y/e.y,t.z=this.z/e.z,t.w=this.w/e.w,t}divideInPlace(e){return this.divideToRef(e,this)}minimizeInPlace(e){return e.x<this.x&&(this.x=e.x),e.y<this.y&&(this.y=e.y),e.z<this.z&&(this.z=e.z),e.w<this.w&&(this.w=e.w),this}maximizeInPlace(e){return e.x>this.x&&(this.x=e.x),e.y>this.y&&(this.y=e.y),e.z>this.z&&(this.z=e.z),e.w>this.w&&(this.w=e.w),this}minimizeInPlaceFromFloats(e,t,s,i){return this.x=Math.min(e,this.x),this.y=Math.min(t,this.y),this.z=Math.min(s,this.z),this.w=Math.min(i,this.w),this}maximizeInPlaceFromFloats(e,t,s,i){return this.x=Math.max(e,this.x),this.y=Math.max(t,this.y),this.z=Math.max(s,this.z),this.w=Math.max(i,this.w),this}floorToRef(e){return e.x=Math.floor(this.x),e.y=Math.floor(this.y),e.z=Math.floor(this.z),e.w=Math.floor(this.w),e}floor(){return new k(Math.floor(this.x),Math.floor(this.y),Math.floor(this.z),Math.floor(this.w))}fractToRef(e){return e.x=this.x-Math.floor(this.x),e.y=this.y-Math.floor(this.y),e.z=this.z-Math.floor(this.z),e.w=this.w-Math.floor(this.w),e}fract(){return new k(this.x-Math.floor(this.x),this.y-Math.floor(this.y),this.z-Math.floor(this.z),this.w-Math.floor(this.w))}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}lengthSquared(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){return this.normalizeToRef(new k)}normalizeToRef(e){const t=this.length();return 0===t||1===t?(e.x=this.x,e.y=this.y,e.z=this.z,e.w=this.w,e):this.scaleToRef(1/t,e)}toVector3(){return new U(this.x,this.y,this.z)}clone(){return new k(this.x,this.y,this.z,this.w)}copyFrom(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w,this}copyFromFloats(e,t,s,i){return this.x=e,this.y=t,this.z=s,this.w=i,this}set(e,t,s,i){return this.copyFromFloats(e,t,s,i)}setAll(e){return this.x=this.y=this.z=this.w=e,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}static FromArray(e,t){return t||(t=0),new k(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,s){return s.x=e[t],s.y=e[t+1],s.z=e[t+2],s.w=e[t+3],s}static FromFloatArrayToRef(e,t,s){return k.FromArrayToRef(e,t,s),s}static FromFloatsToRef(e,t,s,i,r){return r.x=e,r.y=t,r.z=s,r.w=i,r}static Zero(){return new k(0,0,0,0)}static One(){return new k(1,1,1,1)}static Random(e=0,t=1){return new k(O(e,t),O(e,t),O(e,t),O(e,t))}static RandomToRef(e=0,t=1,s){return s.x=O(e,t),s.y=O(e,t),s.z=O(e,t),s.w=O(e,t),s}static Clamp(e,t,s){return k.ClampToRef(e,t,s,new k)}static ClampToRef(e,t,s,i){return i.x=L(e.x,t.x,s.x),i.y=L(e.y,t.y,s.y),i.z=L(e.z,t.z,s.z),i.w=L(e.w,t.w,s.w),i}static CheckExtends(e,t,s){t.minimizeInPlace(e),s.maximizeInPlace(e)}static get ZeroReadOnly(){return k._ZeroReadOnly}static Normalize(e){return k.NormalizeToRef(e,new k)}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Minimize(e,t){const s=new k;return s.copyFrom(e),s.minimizeInPlace(t),s}static Maximize(e,t){const s=new k;return s.copyFrom(e),s.maximizeInPlace(t),s}static Distance(e,t){return Math.sqrt(k.DistanceSquared(e,t))}static DistanceSquared(e,t){const s=e.x-t.x,i=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return s*s+i*i+r*r+n*n}static Center(e,t){return k.CenterToRef(e,t,new k)}static CenterToRef(e,t,s){return s.x=(e.x+t.x)/2,s.y=(e.y+t.y)/2,s.z=(e.z+t.z)/2,s.w=(e.w+t.w)/2,s}static TransformCoordinates(e,t){return k.TransformCoordinatesToRef(e,t,new k)}static TransformCoordinatesToRef(e,t,s){return k.TransformCoordinatesFromFloatsToRef(e._x,e._y,e._z,t,s),s}static TransformCoordinatesFromFloatsToRef(e,t,s,i,r){const n=i.m,a=e*n[0]+t*n[4]+s*n[8]+n[12],o=e*n[1]+t*n[5]+s*n[9]+n[13],h=e*n[2]+t*n[6]+s*n[10]+n[14],l=e*n[3]+t*n[7]+s*n[11]+n[15];return r.x=a,r.y=o,r.z=h,r.w=l,r}static TransformNormal(e,t){return k.TransformNormalToRef(e,t,new k)}static TransformNormalToRef(e,t,s){const i=t.m,r=e.x*i[0]+e.y*i[4]+e.z*i[8],n=e.x*i[1]+e.y*i[5]+e.z*i[9],a=e.x*i[2]+e.y*i[6]+e.z*i[10];return s.x=r,s.y=n,s.z=a,s.w=e.w,s}static TransformNormalFromFloatsToRef(e,t,s,i,r,n){const a=r.m;return n.x=e*a[0]+t*a[4]+s*a[8],n.y=e*a[1]+t*a[5]+s*a[9],n.z=e*a[2]+t*a[6]+s*a[10],n.w=i,n}static FromVector3(e,t=0){return new k(e._x,e._y,e._z,t)}static Dot(e,t){return e.x*t.x+e.y*t.y+e.z*t.z+e.w*t.w}}k._ZeroReadOnly=k.Zero(),Object.defineProperties(k.prototype,{dimension:{value:[4]},rank:{value:1}});class G{get x(){return this._x}set x(e){this._x=e,this._isDirty=!0}get y(){return this._y}set y(e){this._y=e,this._isDirty=!0}get z(){return this._z}set z(e){this._z=e,this._isDirty=!0}get w(){return this._w}set w(e){this._w=e,this._isDirty=!0}constructor(e=0,t=0,s=0,i=1){this._isDirty=!0,this._x=e,this._y=t,this._z=s,this._w=i}toString(){return`{X: ${this._x} Y: ${this._y} Z: ${this._z} W: ${this._w}}`}getClassName(){return"Quaternion"}getHashCode(){let e=w(this._x);return e=397*e^w(this._y),e=397*e^w(this._z),e=397*e^w(this._w),e}asArray(){return[this._x,this._y,this._z,this._w]}toArray(e,t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,this}fromArray(e,t=0){return G.FromArrayToRef(e,t,this)}equals(e){return e&&this._x===e._x&&this._y===e._y&&this._z===e._z&&this._w===e._w}equalsWithEpsilon(e,t=A){return e&&P(this._x,e._x,t)&&P(this._y,e._y,t)&&P(this._z,e._z,t)&&P(this._w,e._w,t)}clone(){return new G(this._x,this._y,this._z,this._w)}copyFrom(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._w=e._w,this._isDirty=!0,this}copyFromFloats(e,t,s,i){return this._x=e,this._y=t,this._z=s,this._w=i,this._isDirty=!0,this}set(e,t,s,i){return this.copyFromFloats(e,t,s,i)}setAll(e){return this.copyFromFloats(e,e,e,e)}add(e){return new G(this._x+e._x,this._y+e._y,this._z+e._z,this._w+e._w)}addInPlace(e){return this._x+=e._x,this._y+=e._y,this._z+=e._z,this._w+=e._w,this._isDirty=!0,this}addToRef(e,t){return t._x=this._x+e._x,t._y=this._y+e._y,t._z=this._z+e._z,t._w=this._w+e._w,t._isDirty=!0,t}addInPlaceFromFloats(e,t,s,i){return this._x+=e,this._y+=t,this._z+=s,this._w+=i,this._isDirty=!0,this}subtractToRef(e,t){return t._x=this._x-e._x,t._y=this._y-e._y,t._z=this._z-e._z,t._w=this._w-e._w,t._isDirty=!0,t}subtractFromFloats(e,t,s,i){return this.subtractFromFloatsToRef(e,t,s,i,new G)}subtractFromFloatsToRef(e,t,s,i,r){return r._x=this._x-e,r._y=this._y-t,r._z=this._z-s,r._w=this._w-i,r._isDirty=!0,r}subtract(e){return new G(this._x-e._x,this._y-e._y,this._z-e._z,this._w-e._w)}subtractInPlace(e){return this._x-=e._x,this._y-=e._y,this._z-=e._z,this._w-=e._w,this._isDirty=!0,this}scale(e){return new G(this._x*e,this._y*e,this._z*e,this._w*e)}scaleToRef(e,t){return t._x=this._x*e,t._y=this._y*e,t._z=this._z*e,t._w=this._w*e,t._isDirty=!0,t}scaleInPlace(e){return this._x*=e,this._y*=e,this._z*=e,this._w*=e,this._isDirty=!0,this}scaleAndAddToRef(e,t){return t._x+=this._x*e,t._y+=this._y*e,t._z+=this._z*e,t._w+=this._w*e,t._isDirty=!0,t}multiply(e){const t=new G(0,0,0,1);return this.multiplyToRef(e,t),t}multiplyToRef(e,t){const s=this._x*e._w+this._y*e._z-this._z*e._y+this._w*e._x,i=-this._x*e._z+this._y*e._w+this._z*e._x+this._w*e._y,r=this._x*e._y-this._y*e._x+this._z*e._w+this._w*e._z,n=-this._x*e._x-this._y*e._y-this._z*e._z+this._w*e._w;return t.copyFromFloats(s,i,r,n),t}multiplyInPlace(e){return this.multiplyToRef(e,this)}multiplyByFloats(e,t,s,i){return this._x*=e,this._y*=t,this._z*=s,this._w*=i,this._isDirty=!0,this}divide(e){throw new ReferenceError("Can not divide a quaternion")}divideToRef(e,t){throw new ReferenceError("Can not divide a quaternion")}divideInPlace(e){throw new ReferenceError("Can not divide a quaternion")}minimizeInPlace(){throw new ReferenceError("Can not minimize a quaternion")}minimizeInPlaceFromFloats(){throw new ReferenceError("Can not minimize a quaternion")}maximizeInPlace(){throw new ReferenceError("Can not maximize a quaternion")}maximizeInPlaceFromFloats(){throw new ReferenceError("Can not maximize a quaternion")}negate(){return this.negateToRef(new G)}negateInPlace(){return this._x=-this._x,this._y=-this._y,this._z=-this._z,this._w=-this._w,this._isDirty=!0,this}negateToRef(e){return e._x=-this._x,e._y=-this._y,e._z=-this._z,e._w=-this._w,e._isDirty=!0,e}equalsToFloats(e,t,s,i){return this._x===e&&this._y===t&&this._z===s&&this._w===i}floorToRef(e){throw new ReferenceError("Can not floor a quaternion")}floor(){throw new ReferenceError("Can not floor a quaternion")}fractToRef(e){throw new ReferenceError("Can not fract a quaternion")}fract(){throw new ReferenceError("Can not fract a quaternion")}conjugateToRef(e){return e.copyFromFloats(-this._x,-this._y,-this._z,this._w),e}conjugateInPlace(){return this._x*=-1,this._y*=-1,this._z*=-1,this._isDirty=!0,this}conjugate(){return new G(-this._x,-this._y,-this._z,this._w)}invert(){const e=this.conjugate(),t=this.lengthSquared();return 0==t||1==t||e.scaleInPlace(1/t),e}invertInPlace(){this.conjugateInPlace();const e=this.lengthSquared();return 0==e||1==e||this.scaleInPlace(1/e),this}lengthSquared(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this.lengthSquared())}normalize(){return this.normalizeFromLength(this.length())}normalizeFromLength(e){return 0===e||1===e?this:this.scaleInPlace(1/e)}normalizeToNew(){const e=new G(0,0,0,1);return this.normalizeToRef(e),e}normalizeToRef(e){const t=this.length();return 0===t||1===t?e.copyFromFloats(this._x,this._y,this._z,this._w):this.scaleToRef(1/t,e)}toEulerAngles(){const e=U.Zero();return this.toEulerAnglesToRef(e),e}toEulerAnglesToRef(e){const t=this._z,s=this._x,i=this._y,r=this._w,n=i*t-s*r,a=.4999999;if(n<-a)e._y=2*Math.atan2(i,r),e._x=Math.PI/2,e._z=0,e._isDirty=!0;else if(n>a)e._y=2*Math.atan2(i,r),e._x=-Math.PI/2,e._z=0,e._isDirty=!0;else{const a=r*r,o=t*t,h=s*s,l=i*i;e._z=Math.atan2(2*(s*i+t*r),-o-h+l+a),e._x=Math.asin(-2*n),e._y=Math.atan2(2*(t*s+i*r),o-h-l+a),e._isDirty=!0}return e}toAlphaBetaGammaToRef(e){const t=this._z,s=this._x,i=this._y,r=this._w,n=Math.sqrt(s*s+i*i),a=Math.sqrt(t*t+r*r),o=2*Math.atan2(n,a),h=2*Math.atan2(t,r),l=2*Math.atan2(i,s),c=(h+l)/2,u=(h-l)/2;return e.set(u,o,c),e}toRotationMatrix(e){return V.FromQuaternionToRef(this,e),e}fromRotationMatrix(e){return G.FromRotationMatrixToRef(e,this),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}static FromRotationMatrix(e){const t=new G;return G.FromRotationMatrixToRef(e,t),t}static FromRotationMatrixToRef(e,t){const s=e.m,i=s[0],r=s[4],n=s[8],a=s[1],o=s[5],h=s[9],l=s[2],c=s[6],u=s[10],d=i+o+u;let _;return d>0?(_=.5/Math.sqrt(d+1),t._w=.25/_,t._x=(c-h)*_,t._y=(n-l)*_,t._z=(a-r)*_,t._isDirty=!0):i>o&&i>u?(_=2*Math.sqrt(1+i-o-u),t._w=(c-h)/_,t._x=.25*_,t._y=(r+a)/_,t._z=(n+l)/_,t._isDirty=!0):o>u?(_=2*Math.sqrt(1+o-i-u),t._w=(n-l)/_,t._x=(r+a)/_,t._y=.25*_,t._z=(h+c)/_,t._isDirty=!0):(_=2*Math.sqrt(1+u-i-o),t._w=(a-r)/_,t._x=(n+l)/_,t._y=(h+c)/_,t._z=.25*_,t._isDirty=!0),t}static Dot(e,t){return e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w}static AreClose(e,t,s=.1){const i=G.Dot(e,t);return 1-i*i<=s}static SmoothToRef(e,t,s,i,r){let n=0===i?1:s/i;return n=L(n,0,1),G.SlerpToRef(e,t,n,r),r}static Zero(){return new G(0,0,0,0)}static Inverse(e){return new G(-e._x,-e._y,-e._z,e._w)}static InverseToRef(e,t){return t.set(-e._x,-e._y,-e._z,e._w),t}static Identity(){return new G(0,0,0,1)}static IsIdentity(e){return e&&0===e._x&&0===e._y&&0===e._z&&1===e._w}static RotationAxis(e,t){return G.RotationAxisToRef(e,t,new G)}static RotationAxisToRef(e,t,s){s._w=Math.cos(t/2);const i=Math.sin(t/2)/e.length();return s._x=e._x*i,s._y=e._y*i,s._z=e._z*i,s._isDirty=!0,s}static FromArray(e,t){return t||(t=0),new G(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t,s){return s._x=e[t],s._y=e[t+1],s._z=e[t+2],s._w=e[t+3],s._isDirty=!0,s}static FromFloatsToRef(e,t,s,i,r){return r.copyFromFloats(e,t,s,i),r}static FromEulerAngles(e,t,s){const i=new G;return G.RotationYawPitchRollToRef(t,e,s,i),i}static FromEulerAnglesToRef(e,t,s,i){return G.RotationYawPitchRollToRef(t,e,s,i),i}static FromEulerVector(e){const t=new G;return G.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromEulerVectorToRef(e,t){return G.RotationYawPitchRollToRef(e._y,e._x,e._z,t),t}static FromUnitVectorsToRef(e,t,s,i=A){const r=U.Dot(e,t)+1;return r<i?Math.abs(e.x)>Math.abs(e.z)?s.set(-e.y,e.x,0,0):s.set(0,-e.z,e.y,0):(U.CrossToRef(e,t,z.Vector3[0]),s.set(z.Vector3[0].x,z.Vector3[0].y,z.Vector3[0].z,r)),s.normalize()}static RotationYawPitchRoll(e,t,s){const i=new G;return G.RotationYawPitchRollToRef(e,t,s,i),i}static RotationYawPitchRollToRef(e,t,s,i){const r=.5*s,n=.5*t,a=.5*e,o=Math.sin(r),h=Math.cos(r),l=Math.sin(n),c=Math.cos(n),u=Math.sin(a),d=Math.cos(a);return i._x=d*l*h+u*c*o,i._y=u*c*h-d*l*o,i._z=d*c*o-u*l*h,i._w=d*c*h+u*l*o,i._isDirty=!0,i}static RotationAlphaBetaGamma(e,t,s){const i=new G;return G.RotationAlphaBetaGammaToRef(e,t,s,i),i}static RotationAlphaBetaGammaToRef(e,t,s,i){const r=.5*(s+e),n=.5*(s-e),a=.5*t;return i._x=Math.cos(n)*Math.sin(a),i._y=Math.sin(n)*Math.sin(a),i._z=Math.sin(r)*Math.cos(a),i._w=Math.cos(r)*Math.cos(a),i._isDirty=!0,i}static RotationQuaternionFromAxis(e,t,s){const i=new G(0,0,0,0);return G.RotationQuaternionFromAxisToRef(e,t,s,i),i}static RotationQuaternionFromAxisToRef(e,t,s,i){const r=H.Matrix[0];return e=e.normalizeToRef(H.Vector3[0]),t=t.normalizeToRef(H.Vector3[1]),s=s.normalizeToRef(H.Vector3[2]),V.FromXYZAxesToRef(e,t,s,r),G.FromRotationMatrixToRef(r,i),i}static FromLookDirectionLH(e,t){const s=new G;return G.FromLookDirectionLHToRef(e,t,s),s}static FromLookDirectionLHToRef(e,t,s){const i=H.Matrix[0];return V.LookDirectionLHToRef(e,t,i),G.FromRotationMatrixToRef(i,s),s}static FromLookDirectionRH(e,t){const s=new G;return G.FromLookDirectionRHToRef(e,t,s),s}static FromLookDirectionRHToRef(e,t,s){const i=H.Matrix[0];return V.LookDirectionRHToRef(e,t,i),G.FromRotationMatrixToRef(i,s)}static Slerp(e,t,s){const i=G.Identity();return G.SlerpToRef(e,t,s,i),i}static SlerpToRef(e,t,s,i){let r,n,a=e._x*t._x+e._y*t._y+e._z*t._z+e._w*t._w,o=!1;if(a<0&&(o=!0,a=-a),a>.999999)n=1-s,r=o?-s:s;else{const e=Math.acos(a),t=1/Math.sin(e);n=Math.sin((1-s)*e)*t,r=o?-Math.sin(s*e)*t:Math.sin(s*e)*t}return i._x=n*e._x+r*t._x,i._y=n*e._y+r*t._y,i._z=n*e._z+r*t._z,i._w=n*e._w+r*t._w,i._isDirty=!0,i}static Hermite(e,t,s,i,r){const n=r*r,a=r*n,o=2*a-3*n+1,h=-2*a+3*n,l=a-2*n+r,c=a-n,u=e._x*o+s._x*h+t._x*l+i._x*c,d=e._y*o+s._y*h+t._y*l+i._y*c,_=e._z*o+s._z*h+t._z*l+i._z*c,f=e._w*o+s._w*h+t._w*l+i._w*c;return new G(u,d,_,f)}static Hermite1stDerivative(e,t,s,i,r){const n=new G;return this.Hermite1stDerivativeToRef(e,t,s,i,r,n),n}static Hermite1stDerivativeToRef(e,t,s,i,r,n){const a=r*r;return n._x=6*(a-r)*e._x+(3*a-4*r+1)*t._x+6*(-a+r)*s._x+(3*a-2*r)*i._x,n._y=6*(a-r)*e._y+(3*a-4*r+1)*t._y+6*(-a+r)*s._y+(3*a-2*r)*i._y,n._z=6*(a-r)*e._z+(3*a-4*r+1)*t._z+6*(-a+r)*s._z+(3*a-2*r)*i._z,n._w=6*(a-r)*e._w+(3*a-4*r+1)*t._w+6*(-a+r)*s._w+(3*a-2*r)*i._w,n._isDirty=!0,n}static Normalize(e){const t=G.Zero();return G.NormalizeToRef(e,t),t}static NormalizeToRef(e,t){return e.normalizeToRef(t),t}static Clamp(e,t,s){const i=new G;return G.ClampToRef(e,t,s,i),i}static ClampToRef(e,t,s,i){return i.copyFromFloats(L(e.x,t.x,s.x),L(e.y,t.y,s.y),L(e.z,t.z,s.z),L(e.w,t.w,s.w))}static Random(e=0,t=1){return new G(O(e,t),O(e,t),O(e,t),O(e,t))}static RandomToRef(e=0,t=1,s){return s.copyFromFloats(O(e,t),O(e,t),O(e,t),O(e,t))}static Minimize(){throw new ReferenceError("Quaternion.Minimize does not make sense")}static Maximize(){throw new ReferenceError("Quaternion.Maximize does not make sense")}static Distance(e,t){return Math.sqrt(G.DistanceSquared(e,t))}static DistanceSquared(e,t){const s=e.x-t.x,i=e.y-t.y,r=e.z-t.z,n=e.w-t.w;return s*s+i*i+r*r+n*n}static Center(e,t){return G.CenterToRef(e,t,G.Zero())}static CenterToRef(e,t,s){return s.copyFromFloats((e.x+t.x)/2,(e.y+t.y)/2,(e.z+t.z)/2,(e.w+t.w)/2)}}Object.defineProperties(G.prototype,{dimension:{value:[4]},rank:{value:1}});class V{static get Use64Bits(){return v.MatrixUse64Bits}get m(){return this._m}markAsUpdated(){this.updateFlag=V._UpdateFlagSeed++,this._isIdentity=!1,this._isIdentity3x2=!1,this._isIdentityDirty=!0,this._isIdentity3x2Dirty=!0}_updateIdentityStatus(e,t=!1,s=!1,i=!0){this._isIdentity=e,this._isIdentity3x2=e||s,this._isIdentityDirty=!this._isIdentity&&t,this._isIdentity3x2Dirty=!this._isIdentity3x2&&i}constructor(){this._isIdentity=!1,this._isIdentityDirty=!0,this._isIdentity3x2=!0,this._isIdentity3x2Dirty=!0,this.updateFlag=-1,v.MatrixTrackPrecisionChange&&v.MatrixTrackedMatrices.push(this),this._m=new v.MatrixCurrentType(16),this.markAsUpdated()}isIdentity(){if(this._isIdentityDirty){this._isIdentityDirty=!1;const e=this._m;this._isIdentity=1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]}return this._isIdentity}isIdentityAs3x2(){return this._isIdentity3x2Dirty&&(this._isIdentity3x2Dirty=!1,1!==this._m[0]||1!==this._m[5]||1!==this._m[15]||0!==this._m[1]||0!==this._m[2]||0!==this._m[3]||0!==this._m[4]||0!==this._m[6]||0!==this._m[7]||0!==this._m[8]||0!==this._m[9]||0!==this._m[10]||0!==this._m[11]||0!==this._m[12]||0!==this._m[13]||0!==this._m[14]?this._isIdentity3x2=!1:this._isIdentity3x2=!0),this._isIdentity3x2}determinant(){if(!0===this._isIdentity)return 1;const e=this._m,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],a=e[5],o=e[6],h=e[7],l=e[8],c=e[9],u=e[10],d=e[11],_=e[12],f=e[13],p=e[14],m=e[15],g=u*m-p*d,T=c*m-f*d,E=c*p-f*u,A=l*m-_*d,y=l*p-u*_,b=l*f-_*c;return t*+(a*g-o*T+h*E)+s*-(n*g-o*A+h*y)+i*+(n*T-a*A+h*b)+r*-(n*E-a*y+o*b)}toString(){return`{${this.m[0]}, ${this.m[1]}, ${this.m[2]}, ${this.m[3]}\n${this.m[4]}, ${this.m[5]}, ${this.m[6]}, ${this.m[7]}\n${this.m[8]}, ${this.m[9]}, ${this.m[10]}, ${this.m[11]}\n${this.m[12]}, ${this.m[13]}, ${this.m[14]}, ${this.m[15]}}`}toArray(e=null,t=0){if(!e)return this._m;const s=this._m;for(let i=0;i<16;i++)e[t+i]=s[i];return this}asArray(){return this._m}fromArray(e,t=0){return V.FromArrayToRef(e,t,this)}copyFromFloats(...e){return V.FromArrayToRef(e,0,this)}set(...e){const t=this._m;for(let s=0;s<16;s++)t[s]=e[s];return this.markAsUpdated(),this}setAll(e){const t=this._m;for(let s=0;s<16;s++)t[s]=e;return this.markAsUpdated(),this}invert(){return this.invertToRef(this),this}reset(){return V.FromValuesToRef(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,this),this._updateIdentityStatus(!1),this}add(e){const t=new V;return this.addToRef(e,t),t}addToRef(e,t){const s=this._m,i=t._m,r=e.m;for(let e=0;e<16;e++)i[e]=s[e]+r[e];return t.markAsUpdated(),t}addToSelf(e){const t=this._m,s=e.m;return t[0]+=s[0],t[1]+=s[1],t[2]+=s[2],t[3]+=s[3],t[4]+=s[4],t[5]+=s[5],t[6]+=s[6],t[7]+=s[7],t[8]+=s[8],t[9]+=s[9],t[10]+=s[10],t[11]+=s[11],t[12]+=s[12],t[13]+=s[13],t[14]+=s[14],t[15]+=s[15],this.markAsUpdated(),this}addInPlace(e){const t=this._m,s=e.m;for(let e=0;e<16;e++)t[e]+=s[e];return this.markAsUpdated(),this}addInPlaceFromFloats(...e){const t=this._m;for(let s=0;s<16;s++)t[s]+=e[s];return this.markAsUpdated(),this}subtract(e){const t=this._m,s=e.m;for(let e=0;e<16;e++)t[e]-=s[e];return this.markAsUpdated(),this}subtractToRef(e,t){const s=this._m,i=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=s[e]-i[e];return t.markAsUpdated(),t}subtractInPlace(e){const t=this._m,s=e.m;for(let e=0;e<16;e++)t[e]-=s[e];return this.markAsUpdated(),this}subtractFromFloats(...e){return this.subtractFromFloatsToRef(...e,new V)}subtractFromFloatsToRef(...e){const t=e.pop(),s=this._m,i=t._m,r=e;for(let e=0;e<16;e++)i[e]=s[e]-r[e];return t.markAsUpdated(),t}invertToRef(e){if(!0===this._isIdentity)return V.IdentityToRef(e),e;const t=this._m,s=t[0],i=t[1],r=t[2],n=t[3],a=t[4],o=t[5],h=t[6],l=t[7],c=t[8],u=t[9],d=t[10],_=t[11],f=t[12],p=t[13],m=t[14],g=t[15],T=d*g-m*_,E=u*g-p*_,A=u*m-p*d,y=c*g-f*_,b=c*m-d*f,R=c*p-f*u,x=+(o*T-h*E+l*A),M=-(a*T-h*y+l*b),I=+(a*E-o*y+l*R),S=-(a*A-o*b+h*R),v=s*x+i*M+r*I+n*S;if(0===v)return e.copyFrom(this),e;const C=1/v,P=h*g-m*l,O=o*g-p*l,D=o*m-p*h,L=a*g-f*l,F=a*m-f*h,N=a*p-f*o,w=h*_-d*l,B=o*_-u*l,U=o*d-u*h,k=a*_-c*l,G=a*d-c*h,H=a*u-c*o,z=-(i*T-r*E+n*A),X=+(s*T-r*y+n*b),W=-(s*E-i*y+n*R),Y=+(s*A-i*b+r*R),K=+(i*P-r*O+n*D),q=-(s*P-r*L+n*F),Q=+(s*O-i*L+n*N),j=-(s*D-i*F+r*N),Z=-(i*w-r*B+n*U),$=+(s*w-r*k+n*G),J=-(s*B-i*k+n*H),ee=+(s*U-i*G+r*H);return V.FromValuesToRef(x*C,z*C,K*C,Z*C,M*C,X*C,q*C,$*C,I*C,W*C,Q*C,J*C,S*C,Y*C,j*C,ee*C,e),e}addAtIndex(e,t){return this._m[e]+=t,this.markAsUpdated(),this}multiplyAtIndex(e,t){return this._m[e]*=t,this.markAsUpdated(),this}setTranslationFromFloats(e,t,s){return this._m[12]=e,this._m[13]=t,this._m[14]=s,this.markAsUpdated(),this}addTranslationFromFloats(e,t,s){return this._m[12]+=e,this._m[13]+=t,this._m[14]+=s,this.markAsUpdated(),this}setTranslation(e){return this.setTranslationFromFloats(e._x,e._y,e._z)}getTranslation(){return new U(this._m[12],this._m[13],this._m[14])}getTranslationToRef(e){return e.x=this._m[12],e.y=this._m[13],e.z=this._m[14],e}removeRotationAndScaling(){const e=this.m;return V.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e[12],e[13],e[14],e[15],this),this._updateIdentityStatus(0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]),this}copyFrom(e){e.copyToArray(this._m);const t=e;return this.updateFlag=t.updateFlag,this._updateIdentityStatus(t._isIdentity,t._isIdentityDirty,t._isIdentity3x2,t._isIdentity3x2Dirty),this}copyToArray(e,t=0){const s=this._m;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e[t+9]=s[9],e[t+10]=s[10],e[t+11]=s[11],e[t+12]=s[12],e[t+13]=s[13],e[t+14]=s[14],e[t+15]=s[15],this}multiply(e){const t=new V;return this.multiplyToRef(e,t),t}multiplyInPlace(e){const t=this._m,s=e.m;for(let e=0;e<16;e++)t[e]*=s[e];return this.markAsUpdated(),this}multiplyByFloats(...e){const t=this._m;for(let s=0;s<16;s++)t[s]*=e[s];return this.markAsUpdated(),this}multiplyByFloatsToRef(...e){const t=e.pop(),s=this._m,i=t._m,r=e;for(let e=0;e<16;e++)i[e]=s[e]*r[e];return t.markAsUpdated(),t}multiplyToRef(e,t){return this._isIdentity?(t.copyFrom(e),t):e._isIdentity?(t.copyFrom(this),t):(this.multiplyToArray(e,t._m,0),t.markAsUpdated(),t)}multiplyToArray(e,t,s){const i=this._m,r=e.m,n=i[0],a=i[1],o=i[2],h=i[3],l=i[4],c=i[5],u=i[6],d=i[7],_=i[8],f=i[9],p=i[10],m=i[11],g=i[12],T=i[13],E=i[14],A=i[15],y=r[0],b=r[1],R=r[2],x=r[3],M=r[4],I=r[5],S=r[6],v=r[7],C=r[8],P=r[9],O=r[10],D=r[11],L=r[12],F=r[13],N=r[14],w=r[15];return t[s]=n*y+a*M+o*C+h*L,t[s+1]=n*b+a*I+o*P+h*F,t[s+2]=n*R+a*S+o*O+h*N,t[s+3]=n*x+a*v+o*D+h*w,t[s+4]=l*y+c*M+u*C+d*L,t[s+5]=l*b+c*I+u*P+d*F,t[s+6]=l*R+c*S+u*O+d*N,t[s+7]=l*x+c*v+u*D+d*w,t[s+8]=_*y+f*M+p*C+m*L,t[s+9]=_*b+f*I+p*P+m*F,t[s+10]=_*R+f*S+p*O+m*N,t[s+11]=_*x+f*v+p*D+m*w,t[s+12]=g*y+T*M+E*C+A*L,t[s+13]=g*b+T*I+E*P+A*F,t[s+14]=g*R+T*S+E*O+A*N,t[s+15]=g*x+T*v+E*D+A*w,this}divide(e){return this.divideToRef(e,new V)}divideToRef(e,t){const s=this._m,i=e.m,r=t._m;for(let e=0;e<16;e++)r[e]=s[e]/i[e];return t.markAsUpdated(),t}divideInPlace(e){const t=this._m,s=e.m;for(let e=0;e<16;e++)t[e]/=s[e];return this.markAsUpdated(),this}minimizeInPlace(e){const t=this._m,s=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],s[e]);return this.markAsUpdated(),this}minimizeInPlaceFromFloats(...e){const t=this._m;for(let s=0;s<16;s++)t[s]=Math.min(t[s],e[s]);return this.markAsUpdated(),this}maximizeInPlace(e){const t=this._m,s=e.m;for(let e=0;e<16;e++)t[e]=Math.min(t[e],s[e]);return this.markAsUpdated(),this}maximizeInPlaceFromFloats(...e){const t=this._m;for(let s=0;s<16;s++)t[s]=Math.min(t[s],e[s]);return this.markAsUpdated(),this}negate(){return this.negateToRef(new V)}negateInPlace(){const e=this._m;for(let t=0;t<16;t++)e[t]=-e[t];return this.markAsUpdated(),this}negateToRef(e){const t=this._m,s=e._m;for(let e=0;e<16;e++)s[e]=-t[e];return e.markAsUpdated(),e}equals(e){const t=e;if(!t)return!1;if((this._isIdentity||t._isIdentity)&&!this._isIdentityDirty&&!t._isIdentityDirty)return this._isIdentity&&t._isIdentity;const s=this.m,i=t.m;return s[0]===i[0]&&s[1]===i[1]&&s[2]===i[2]&&s[3]===i[3]&&s[4]===i[4]&&s[5]===i[5]&&s[6]===i[6]&&s[7]===i[7]&&s[8]===i[8]&&s[9]===i[9]&&s[10]===i[10]&&s[11]===i[11]&&s[12]===i[12]&&s[13]===i[13]&&s[14]===i[14]&&s[15]===i[15]}equalsWithEpsilon(e,t=0){const s=this._m,i=e.m;for(let e=0;e<16;e++)if(!P(s[e],i[e],t))return!1;return!0}equalsToFloats(...e){const t=this._m;for(let s=0;s<16;s++)if(t[s]!=e[s])return!1;return!0}floor(){return this.floorToRef(new V)}floorToRef(e){const t=this._m,s=e._m;for(let e=0;e<16;e++)s[e]=Math.floor(t[e]);return e.markAsUpdated(),e}fract(){return this.fractToRef(new V)}fractToRef(e){const t=this._m,s=e._m;for(let e=0;e<16;e++)s[e]=t[e]-Math.floor(t[e]);return e.markAsUpdated(),e}clone(){const e=new V;return e.copyFrom(this),e}getClassName(){return"Matrix"}getHashCode(){let e=w(this._m[0]);for(let t=1;t<16;t++)e=397*e^w(this._m[t]);return e}decomposeToTransformNode(e){return e.rotationQuaternion=e.rotationQuaternion||new G,this.decompose(e.scaling,e.rotationQuaternion,e.position)}decompose(e,t,s,i,r=!0){if(this._isIdentity)return s&&s.setAll(0),e&&e.setAll(1),t&&t.copyFromFloats(0,0,0,1),!0;const n=this._m;if(s&&s.copyFromFloats(n[12],n[13],n[14]),(e=e||H.Vector3[0]).x=Math.sqrt(n[0]*n[0]+n[1]*n[1]+n[2]*n[2]),e.y=Math.sqrt(n[4]*n[4]+n[5]*n[5]+n[6]*n[6]),e.z=Math.sqrt(n[8]*n[8]+n[9]*n[9]+n[10]*n[10]),i){const t=(r?i.absoluteScaling.x:i.scaling.x)<0?-1:1,s=(r?i.absoluteScaling.y:i.scaling.y)<0?-1:1,n=(r?i.absoluteScaling.z:i.scaling.z)<0?-1:1;e.x*=t,e.y*=s,e.z*=n}else this.determinant()<=0&&(e.y*=-1);if(0===e._x||0===e._y||0===e._z)return t&&t.copyFromFloats(0,0,0,1),!1;if(t){const s=1/e._x,i=1/e._y,r=1/e._z;V.FromValuesToRef(n[0]*s,n[1]*s,n[2]*s,0,n[4]*i,n[5]*i,n[6]*i,0,n[8]*r,n[9]*r,n[10]*r,0,0,0,0,1,H.Matrix[0]),G.FromRotationMatrixToRef(H.Matrix[0],t)}return!0}getRow(e){if(e<0||e>3)return null;const t=4*e;return new k(this._m[t+0],this._m[t+1],this._m[t+2],this._m[t+3])}getRowToRef(e,t){if(e>=0&&e<=3){const s=4*e;t.x=this._m[s+0],t.y=this._m[s+1],t.z=this._m[s+2],t.w=this._m[s+3]}return t}setRow(e,t){return this.setRowFromFloats(e,t.x,t.y,t.z,t.w)}transpose(){const e=new V;return V.TransposeToRef(this,e),e}transposeToRef(e){return V.TransposeToRef(this,e),e}setRowFromFloats(e,t,s,i,r){if(e<0||e>3)return this;const n=4*e;return this._m[n+0]=t,this._m[n+1]=s,this._m[n+2]=i,this._m[n+3]=r,this.markAsUpdated(),this}scale(e){const t=new V;return this.scaleToRef(e,t),t}scaleToRef(e,t){for(let s=0;s<16;s++)t._m[s]=this._m[s]*e;return t.markAsUpdated(),t}scaleAndAddToRef(e,t){for(let s=0;s<16;s++)t._m[s]+=this._m[s]*e;return t.markAsUpdated(),t}scaleInPlace(e){const t=this._m;for(let s=0;s<16;s++)t[s]*=e;return this.markAsUpdated(),this}toNormalMatrix(e){const t=H.Matrix[0];this.invertToRef(t),t.transposeToRef(e);const s=e._m;return V.FromValuesToRef(s[0],s[1],s[2],0,s[4],s[5],s[6],0,s[8],s[9],s[10],0,0,0,0,1,e),e}getRotationMatrix(){const e=new V;return this.getRotationMatrixToRef(e),e}getRotationMatrixToRef(e){const t=H.Vector3[0];if(!this.decompose(t))return V.IdentityToRef(e),e;const s=this._m,i=1/t._x,r=1/t._y,n=1/t._z;return V.FromValuesToRef(s[0]*i,s[1]*i,s[2]*i,0,s[4]*r,s[5]*r,s[6]*r,0,s[8]*n,s[9]*n,s[10]*n,0,0,0,0,1,e),e}toggleModelMatrixHandInPlace(){const e=this._m;return e[2]*=-1,e[6]*=-1,e[8]*=-1,e[9]*=-1,e[14]*=-1,this.markAsUpdated(),this}toggleProjectionMatrixHandInPlace(){const e=this._m;return e[8]*=-1,e[9]*=-1,e[10]*=-1,e[11]*=-1,this.markAsUpdated(),this}static FromArray(e,t=0){const s=new V;return V.FromArrayToRef(e,t,s),s}static FromArrayToRef(e,t,s){for(let i=0;i<16;i++)s._m[i]=e[i+t];return s.markAsUpdated(),s}static FromFloat32ArrayToRefScaled(e,t,s,i){return i._m[0]=e[0+t]*s,i._m[1]=e[1+t]*s,i._m[2]=e[2+t]*s,i._m[3]=e[3+t]*s,i._m[4]=e[4+t]*s,i._m[5]=e[5+t]*s,i._m[6]=e[6+t]*s,i._m[7]=e[7+t]*s,i._m[8]=e[8+t]*s,i._m[9]=e[9+t]*s,i._m[10]=e[10+t]*s,i._m[11]=e[11+t]*s,i._m[12]=e[12+t]*s,i._m[13]=e[13+t]*s,i._m[14]=e[14+t]*s,i._m[15]=e[15+t]*s,i.markAsUpdated(),i}static get IdentityReadOnly(){return V._IdentityReadOnly}static FromValuesToRef(e,t,s,i,r,n,a,o,h,l,c,u,d,_,f,p,m){const g=m._m;g[0]=e,g[1]=t,g[2]=s,g[3]=i,g[4]=r,g[5]=n,g[6]=a,g[7]=o,g[8]=h,g[9]=l,g[10]=c,g[11]=u,g[12]=d,g[13]=_,g[14]=f,g[15]=p,m.markAsUpdated()}static FromValues(e,t,s,i,r,n,a,o,h,l,c,u,d,_,f,p){const m=new V,g=m._m;return g[0]=e,g[1]=t,g[2]=s,g[3]=i,g[4]=r,g[5]=n,g[6]=a,g[7]=o,g[8]=h,g[9]=l,g[10]=c,g[11]=u,g[12]=d,g[13]=_,g[14]=f,g[15]=p,m.markAsUpdated(),m}static Compose(e,t,s){const i=new V;return V.ComposeToRef(e,t,s,i),i}static ComposeToRef(e,t,s,i){const r=i._m,n=t._x,a=t._y,o=t._z,h=t._w,l=n+n,c=a+a,u=o+o,d=n*l,_=n*c,f=n*u,p=a*c,m=a*u,g=o*u,T=h*l,E=h*c,A=h*u,y=e._x,b=e._y,R=e._z;return r[0]=(1-(p+g))*y,r[1]=(_+A)*y,r[2]=(f-E)*y,r[3]=0,r[4]=(_-A)*b,r[5]=(1-(d+g))*b,r[6]=(m+T)*b,r[7]=0,r[8]=(f+E)*R,r[9]=(m-T)*R,r[10]=(1-(d+p))*R,r[11]=0,r[12]=s._x,r[13]=s._y,r[14]=s._z,r[15]=1,i.markAsUpdated(),i}static Identity(){const e=V.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return e._updateIdentityStatus(!0),e}static IdentityToRef(e){return V.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,e),e._updateIdentityStatus(!0),e}static Zero(){const e=V.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return e._updateIdentityStatus(!1),e}static RotationX(e){const t=new V;return V.RotationXToRef(e,t),t}static Invert(e){const t=new V;return e.invertToRef(t),t}static RotationXToRef(e,t){const s=Math.sin(e),i=Math.cos(e);return V.FromValuesToRef(1,0,0,0,0,i,s,0,0,-s,i,0,0,0,0,1,t),t._updateIdentityStatus(1===i&&0===s),t}static RotationY(e){const t=new V;return V.RotationYToRef(e,t),t}static RotationYToRef(e,t){const s=Math.sin(e),i=Math.cos(e);return V.FromValuesToRef(i,0,-s,0,0,1,0,0,s,0,i,0,0,0,0,1,t),t._updateIdentityStatus(1===i&&0===s),t}static RotationZ(e){const t=new V;return V.RotationZToRef(e,t),t}static RotationZToRef(e,t){const s=Math.sin(e),i=Math.cos(e);return V.FromValuesToRef(i,s,0,0,-s,i,0,0,0,0,1,0,0,0,0,1,t),t._updateIdentityStatus(1===i&&0===s),t}static RotationAxis(e,t){const s=new V;return V.RotationAxisToRef(e,t,s),s}static RotationAxisToRef(e,t,s){const i=Math.sin(-t),r=Math.cos(-t),n=1-r;e=e.normalizeToRef(H.Vector3[0]);const a=s._m;return a[0]=e._x*e._x*n+r,a[1]=e._x*e._y*n-e._z*i,a[2]=e._x*e._z*n+e._y*i,a[3]=0,a[4]=e._y*e._x*n+e._z*i,a[5]=e._y*e._y*n+r,a[6]=e._y*e._z*n-e._x*i,a[7]=0,a[8]=e._z*e._x*n-e._y*i,a[9]=e._z*e._y*n+e._x*i,a[10]=e._z*e._z*n+r,a[11]=0,a[12]=0,a[13]=0,a[14]=0,a[15]=1,s.markAsUpdated(),s}static RotationAlignToRef(e,t,s,i=!1){const r=U.Dot(t,e),n=s._m;if(r<-1+A)n[0]=-1,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=i?1:-1,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=i?-1:1,n[11]=0;else{const s=U.Cross(t,e),i=1/(1+r);n[0]=s._x*s._x*i+r,n[1]=s._y*s._x*i-s._z,n[2]=s._z*s._x*i+s._y,n[3]=0,n[4]=s._x*s._y*i+s._z,n[5]=s._y*s._y*i+r,n[6]=s._z*s._y*i-s._x,n[7]=0,n[8]=s._x*s._z*i-s._y,n[9]=s._y*s._z*i+s._x,n[10]=s._z*s._z*i+r,n[11]=0}return n[12]=0,n[13]=0,n[14]=0,n[15]=1,s.markAsUpdated(),s}static RotationYawPitchRoll(e,t,s){const i=new V;return V.RotationYawPitchRollToRef(e,t,s,i),i}static RotationYawPitchRollToRef(e,t,s,i){return G.RotationYawPitchRollToRef(e,t,s,H.Quaternion[0]),H.Quaternion[0].toRotationMatrix(i),i}static Scaling(e,t,s){const i=new V;return V.ScalingToRef(e,t,s,i),i}static ScalingToRef(e,t,s,i){return V.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1,i),i._updateIdentityStatus(1===e&&1===t&&1===s),i}static Translation(e,t,s){const i=new V;return V.TranslationToRef(e,t,s,i),i}static TranslationToRef(e,t,s,i){return V.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,e,t,s,1,i),i._updateIdentityStatus(0===e&&0===t&&0===s),i}static Lerp(e,t,s){const i=new V;return V.LerpToRef(e,t,s,i),i}static LerpToRef(e,t,s,i){const r=i._m,n=e.m,a=t.m;for(let e=0;e<16;e++)r[e]=n[e]*(1-s)+a[e]*s;return i.markAsUpdated(),i}static DecomposeLerp(e,t,s){const i=new V;return V.DecomposeLerpToRef(e,t,s,i),i}static DecomposeLerpToRef(e,t,s,i){const r=H.Vector3[0],n=H.Quaternion[0],a=H.Vector3[1];e.decompose(r,n,a);const o=H.Vector3[2],h=H.Quaternion[1],l=H.Vector3[3];t.decompose(o,h,l);const c=H.Vector3[4];U.LerpToRef(r,o,s,c);const u=H.Quaternion[2];G.SlerpToRef(n,h,s,u);const d=H.Vector3[5];return U.LerpToRef(a,l,s,d),V.ComposeToRef(c,u,d,i),i}static LookAtLH(e,t,s){const i=new V;return V.LookAtLHToRef(e,t,s,i),i}static LookAtLHToRef(e,t,s,i){const r=H.Vector3[0],n=H.Vector3[1],a=H.Vector3[2];t.subtractToRef(e,a),a.normalize(),U.CrossToRef(s,a,r);const o=r.lengthSquared();0===o?r.x=1:r.normalizeFromLength(Math.sqrt(o)),U.CrossToRef(a,r,n),n.normalize();const h=-U.Dot(r,e),l=-U.Dot(n,e),c=-U.Dot(a,e);return V.FromValuesToRef(r._x,n._x,a._x,0,r._y,n._y,a._y,0,r._z,n._z,a._z,0,h,l,c,1,i),i}static LookAtRH(e,t,s){const i=new V;return V.LookAtRHToRef(e,t,s,i),i}static LookAtRHToRef(e,t,s,i){const r=H.Vector3[0],n=H.Vector3[1],a=H.Vector3[2];e.subtractToRef(t,a),a.normalize(),U.CrossToRef(s,a,r);const o=r.lengthSquared();0===o?r.x=1:r.normalizeFromLength(Math.sqrt(o)),U.CrossToRef(a,r,n),n.normalize();const h=-U.Dot(r,e),l=-U.Dot(n,e),c=-U.Dot(a,e);return V.FromValuesToRef(r._x,n._x,a._x,0,r._y,n._y,a._y,0,r._z,n._z,a._z,0,h,l,c,1,i),i}static LookDirectionLH(e,t){const s=new V;return V.LookDirectionLHToRef(e,t,s),s}static LookDirectionLHToRef(e,t,s){const i=H.Vector3[0];i.copyFrom(e),i.scaleInPlace(-1);const r=H.Vector3[1];return U.CrossToRef(t,i,r),V.FromValuesToRef(r._x,r._y,r._z,0,t._x,t._y,t._z,0,i._x,i._y,i._z,0,0,0,0,1,s),s}static LookDirectionRH(e,t){const s=new V;return V.LookDirectionRHToRef(e,t,s),s}static LookDirectionRHToRef(e,t,s){const i=H.Vector3[2];return U.CrossToRef(t,e,i),V.FromValuesToRef(i._x,i._y,i._z,0,t._x,t._y,t._z,0,e._x,e._y,e._z,0,0,0,0,1,s),s}static OrthoLH(e,t,s,i,r){const n=new V;return V.OrthoLHToRef(e,t,s,i,n,r),n}static OrthoLHToRef(e,t,s,i,r,n){const a=2/e,o=2/t,h=2/(i-s),l=-(i+s)/(i-s);return V.FromValuesToRef(a,0,0,0,0,o,0,0,0,0,h,0,0,0,l,1,r),n&&r.multiplyToRef(X,r),r._updateIdentityStatus(1===a&&1===o&&1===h&&0===l),r}static OrthoOffCenterLH(e,t,s,i,r,n,a){const o=new V;return V.OrthoOffCenterLHToRef(e,t,s,i,r,n,o,a),o}static OrthoOffCenterLHToRef(e,t,s,i,r,n,a,o){const h=2/(t-e),l=2/(i-s),c=2/(n-r),u=-(n+r)/(n-r),d=(e+t)/(e-t),_=(i+s)/(s-i);return V.FromValuesToRef(h,0,0,0,0,l,0,0,0,0,c,0,d,_,u,1,a),o&&a.multiplyToRef(X,a),a.markAsUpdated(),a}static ObliqueOffCenterLHToRef(e,t,s,i,r,n,a,o,h,l,c){const u=-a*Math.cos(o),d=-a*Math.sin(o);return V.TranslationToRef(0,0,-h,H.Matrix[1]),V.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,H.Matrix[0]),H.Matrix[1].multiplyToRef(H.Matrix[0],H.Matrix[0]),V.TranslationToRef(0,0,h,H.Matrix[1]),H.Matrix[0].multiplyToRef(H.Matrix[1],H.Matrix[0]),V.OrthoOffCenterLHToRef(e,t,s,i,r,n,l,c),H.Matrix[0].multiplyToRef(l,l),l}static OrthoOffCenterRH(e,t,s,i,r,n,a){const o=new V;return V.OrthoOffCenterRHToRef(e,t,s,i,r,n,o,a),o}static OrthoOffCenterRHToRef(e,t,s,i,r,n,a,o){return V.OrthoOffCenterLHToRef(e,t,s,i,r,n,a,o),a._m[10]*=-1,a}static ObliqueOffCenterRHToRef(e,t,s,i,r,n,a,o,h,l,c){const u=a*Math.cos(o),d=a*Math.sin(o);return V.TranslationToRef(0,0,h,H.Matrix[1]),V.FromValuesToRef(1,0,0,0,0,1,0,0,u,d,1,0,0,0,0,1,H.Matrix[0]),H.Matrix[1].multiplyToRef(H.Matrix[0],H.Matrix[0]),V.TranslationToRef(0,0,-h,H.Matrix[1]),H.Matrix[0].multiplyToRef(H.Matrix[1],H.Matrix[0]),V.OrthoOffCenterRHToRef(e,t,s,i,r,n,l,c),H.Matrix[0].multiplyToRef(l,l),l}static PerspectiveLH(e,t,s,i,r,n=0){const a=new V,o=2*s/e,h=2*s/t,l=(i+s)/(i-s),c=-2*i*s/(i-s),u=Math.tan(n);return V.FromValuesToRef(o,0,0,0,0,h,0,u,0,0,l,1,0,0,c,0,a),r&&a.multiplyToRef(X,a),a._updateIdentityStatus(!1),a}static PerspectiveFovLH(e,t,s,i,r,n=0,a=!1){const o=new V;return V.PerspectiveFovLHToRef(e,t,s,i,o,!0,r,n,a),o}static PerspectiveFovLHToRef(e,t,s,i,r,n=!0,a,o=0,h=!1){const l=s,c=i,u=1/Math.tan(.5*e),d=n?u/t:u,_=n?u:u*t,f=h&&0===l?-1:0!==c?(c+l)/(c-l):1,p=h&&0===l?2*c:0!==c?-2*c*l/(c-l):-2*l,m=Math.tan(o);return V.FromValuesToRef(d,0,0,0,0,_,0,m,0,0,f,1,0,0,p,0,r),a&&r.multiplyToRef(X,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseLHToRef(e,t,s,i,r,n=!0,a,o=0){const h=1/Math.tan(.5*e),l=n?h/t:h,c=n?h:h*t,u=Math.tan(o);return V.FromValuesToRef(l,0,0,0,0,c,0,u,0,0,-s,1,0,0,1,0,r),a&&r.multiplyToRef(X,r),r._updateIdentityStatus(!1),r}static PerspectiveFovRH(e,t,s,i,r,n=0,a=!1){const o=new V;return V.PerspectiveFovRHToRef(e,t,s,i,o,!0,r,n,a),o}static PerspectiveFovRHToRef(e,t,s,i,r,n=!0,a,o=0,h=!1){const l=s,c=i,u=1/Math.tan(.5*e),d=n?u/t:u,_=n?u:u*t,f=h&&0===l?1:0!==c?-(c+l)/(c-l):-1,p=h&&0===l?2*c:0!==c?-2*c*l/(c-l):-2*l,m=Math.tan(o);return V.FromValuesToRef(d,0,0,0,0,_,0,m,0,0,f,-1,0,0,p,0,r),a&&r.multiplyToRef(X,r),r._updateIdentityStatus(!1),r}static PerspectiveFovReverseRHToRef(e,t,s,i,r,n=!0,a,o=0){const h=1/Math.tan(.5*e),l=n?h/t:h,c=n?h:h*t,u=Math.tan(o);return V.FromValuesToRef(l,0,0,0,0,c,0,u,0,0,-s,-1,0,0,-1,0,r),a&&r.multiplyToRef(X,r),r._updateIdentityStatus(!1),r}static GetFinalMatrix(e,t,s,i,r,n){const a=e.width,o=e.height,h=e.x,l=e.y,c=V.FromValues(a/2,0,0,0,0,-o/2,0,0,0,0,n-r,0,h+a/2,o/2+l,r,1),u=new V;return t.multiplyToRef(s,u),u.multiplyToRef(i,u),u.multiplyToRef(c,u)}static GetAsMatrix2x2(e){const t=e.m,s=[t[0],t[1],t[4],t[5]];return v.MatrixUse64Bits?s:new Float32Array(s)}static GetAsMatrix3x3(e){const t=e.m,s=[t[0],t[1],t[2],t[4],t[5],t[6],t[8],t[9],t[10]];return v.MatrixUse64Bits?s:new Float32Array(s)}static Transpose(e){const t=new V;return V.TransposeToRef(e,t),t}static TransposeToRef(e,t){const s=e.m,i=s[0],r=s[4],n=s[8],a=s[12],o=s[1],h=s[5],l=s[9],c=s[13],u=s[2],d=s[6],_=s[10],f=s[14],p=s[3],m=s[7],g=s[11],T=s[15],E=t._m;return E[0]=i,E[1]=r,E[2]=n,E[3]=a,E[4]=o,E[5]=h,E[6]=l,E[7]=c,E[8]=u,E[9]=d,E[10]=_,E[11]=f,E[12]=p,E[13]=m,E[14]=g,E[15]=T,t.markAsUpdated(),t._updateIdentityStatus(e._isIdentity,e._isIdentityDirty),t}static Reflection(e){const t=new V;return V.ReflectionToRef(e,t),t}static ReflectionToRef(e,t){e.normalize();const s=e.normal.x,i=e.normal.y,r=e.normal.z,n=-2*s,a=-2*i,o=-2*r;return V.FromValuesToRef(n*s+1,a*s,o*s,0,n*i,a*i+1,o*i,0,n*r,a*r,o*r+1,0,n*e.d,a*e.d,o*e.d,1,t),t}static FromXYZAxesToRef(e,t,s,i){return V.FromValuesToRef(e._x,e._y,e._z,0,t._x,t._y,t._z,0,s._x,s._y,s._z,0,0,0,0,1,i),i}static FromQuaternionToRef(e,t){const s=e._x*e._x,i=e._y*e._y,r=e._z*e._z,n=e._x*e._y,a=e._z*e._w,o=e._z*e._x,h=e._y*e._w,l=e._y*e._z,c=e._x*e._w;return t._m[0]=1-2*(i+r),t._m[1]=2*(n+a),t._m[2]=2*(o-h),t._m[3]=0,t._m[4]=2*(n-a),t._m[5]=1-2*(r+s),t._m[6]=2*(l+c),t._m[7]=0,t._m[8]=2*(o+h),t._m[9]=2*(l-c),t._m[10]=1-2*(i+s),t._m[11]=0,t._m[12]=0,t._m[13]=0,t._m[14]=0,t._m[15]=1,t.markAsUpdated(),t}}V._UpdateFlagSeed=0,V._IdentityReadOnly=V.Identity(),Object.defineProperties(V.prototype,{dimension:{value:[4,4]},rank:{value:2}});class H{}H.Vector3=b(11,U.Zero),H.Matrix=b(2,V.Identity),H.Quaternion=b(3,G.Zero);class z{}z.Vector2=b(3,B.Zero),z.Vector3=b(13,U.Zero),z.Vector4=b(3,k.Zero),z.Quaternion=b(3,G.Zero),z.Matrix=b(8,V.Identity),I("BABYLON.Vector2",B),I("BABYLON.Vector3",U),I("BABYLON.Vector4",k),I("BABYLON.Matrix",V);const X=V.FromValues(1,0,0,0,0,1,0,0,0,0,.5,0,0,0,.5,1),W={};function Y(e,t=!1){if(!t||!W[e])return W[e]=!0,`${e} needs to be imported before as it contains a side-effect required by your code.`}class K{static Eval(e,t){return e=e.match(/\([^()]*\)/g)?e.replace(/\([^()]*\)/g,(e=>(e=e.slice(1,e.length-1),K._HandleParenthesisContent(e,t)))):K._HandleParenthesisContent(e,t),"true"===e||"false"!==e&&K.Eval(e,t)}static _HandleParenthesisContent(e,t){let s;t=t||(e=>"true"===e);const i=e.split("||");for(const e in i)if(Object.prototype.hasOwnProperty.call(i,e)){let r=K._SimplifyNegation(i[e].trim());const n=r.split("&&");if(n.length>1)for(let e=0;e<n.length;++e){const i=K._SimplifyNegation(n[e].trim());if(s="true"!==i&&"false"!==i?"!"===i[0]?!t(i.substring(1)):t(i):"true"===i,!s){r="false";break}}if(s||"true"===r){s=!0;break}s="true"!==r&&"false"!==r?"!"===r[0]?!t(r.substring(1)):t(r):"true"===r}return s?"true":"false"}static _SimplifyNegation(e){return e=e.replace(/^[\s!]+/,(e=>(e=e.replace(/[\s]/g,(()=>""))).length%2?"!":"")),"!true"===(e=e.trim())?e="false":"!false"===e&&(e="true"),e}}class q{static EnableFor(e){e._tags=e._tags||{},e.hasTags=()=>q.HasTags(e),e.addTags=t=>q.AddTagsTo(e,t),e.removeTags=t=>q.RemoveTagsFrom(e,t),e.matchesTagsQuery=t=>q.MatchesQuery(e,t)}static DisableFor(e){delete e._tags,delete e.hasTags,delete e.addTags,delete e.removeTags,delete e.matchesTagsQuery}static HasTags(e){if(!e._tags)return!1;const t=e._tags;for(const e in t)if(Object.prototype.hasOwnProperty.call(t,e))return!0;return!1}static GetTags(e,t=!0){if(!e._tags)return null;if(t){const t=[];for(const s in e._tags)Object.prototype.hasOwnProperty.call(e._tags,s)&&!0===e._tags[s]&&t.push(s);return t.join(" ")}return e._tags}static AddTagsTo(e,t){if(!t)return;if("string"!=typeof t)return;t.split(" ").forEach((function(t){q._AddTagTo(e,t)}))}static _AddTagTo(e,t){""!==(t=t.trim())&&"true"!==t&&"false"!==t&&(t.match(/[\s]/)||t.match(/^([!]|([|]|[&]){2})/)||(q.EnableFor(e),e._tags[t]=!0))}static RemoveTagsFrom(e,t){if(!q.HasTags(e))return;const s=t.split(" ");for(const t in s)q._RemoveTagFrom(e,s[t])}static _RemoveTagFrom(e,t){delete e._tags[t]}static MatchesQuery(e,t){return void 0===t||(""===t?q.HasTags(e):K.Eval(t,(t=>q.HasTags(e)&&e._tags[t])))}}class Q{static Sign(e){return 0===(e=+e)||isNaN(e)?e:e>0?1:-1}static Log2(e){return Math.log(e)*Math.LOG2E}static ILog2(e){if(Math.log2)return Math.floor(Math.log2(e));if(e<0)return NaN;if(0===e)return-1/0;let t=0;if(e<1){for(;e<1;)t++,e*=2;t=-t}else if(e>1)for(;e>1;)t++,e=Math.floor(e/2);return t}static Repeat(e,t){return e-Math.floor(e/t)*t}static Normalize(e,t,s){return(e-t)/(s-t)}static Denormalize(e,t,s){return e*(s-t)+t}static DeltaAngle(e,t){let s=Q.Repeat(t-e,360);return s>180&&(s-=360),s}static PingPong(e,t){const s=Q.Repeat(e,2*t);return t-Math.abs(s-t)}static SmoothStep(e,t,s){let i=Q.Clamp(s);return i=-2*i*i*i+3*i*i,t*i+e*(1-i)}static MoveTowards(e,t,s){let i=0;return i=Math.abs(t-e)<=s?t:e+Q.Sign(t-e)*s,i}static MoveTowardsAngle(e,t,s){const i=Q.DeltaAngle(e,t);let r=0;return-s<i&&i<s?r=t:(t=e+i,r=Q.MoveTowards(e,t,s)),r}static LerpAngle(e,t,s){let i=Q.Repeat(t-e,360);return i>180&&(i-=360),e+i*L(s)}static InverseLerp(e,t,s){let i=0;return i=e!=t?L((s-e)/(t-e)):0,i}static Hermite(e,t,s,i,r){const n=r*r,a=r*n;return e*(2*a-3*n+1)+s*(-2*a+3*n)+t*(a-2*n+r)+i*(a-n)}static Hermite1stDerivative(e,t,s,i,r){const n=r*r;return 6*(n-r)*e+(3*n-4*r+1)*t+6*(-n+r)*s+(3*n-2*r)*i}static RangeToPercent(e,t,s){return(e-t)/(s-t)}static PercentToRange(e,t,s){return(s-t)*e+t}static HCF(e,t){const s=e%t;return 0===s?t:Q.HCF(t,s)}}function j(e){return Math.pow(e,E)}function Z(e){return e<=.04045?.0773993808*e:Math.pow(.947867299*(e+.055),2.4)}function $(e){return Math.pow(e,T)}function J(e){return e<=.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}Q.TwoPi=2*Math.PI,Q.WithinEpsilon=P,Q.ToHex=N,Q.Clamp=L,Q.Lerp=D,Q.RandomRange=O,Q.NormalizeRadians=F;class ee{constructor(e=0,t=0,s=0){this.r=e,this.g=t,this.b=s}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+"}"}getClassName(){return"Color3"}getHashCode(){let e=255*this.r|0;return e=397*e^255*this.g,e=397*e^255*this.b,e}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,this}fromArray(e,t=0){return ee.FromArrayToRef(e,t,this),this}toColor4(e=1){return new te(this.r,this.g,this.b,e)}asArray(){return[this.r,this.g,this.b]}toLuminance(){return.3*this.r+.59*this.g+.11*this.b}multiply(e){return new ee(this.r*e.r,this.g*e.g,this.b*e.b)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyByFloats(e,t,s){return new ee(this.r*e,this.g*t,this.b*s)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.minimizeInPlaceFromFloats(e.r,e.g,e.b)}maximizeInPlace(e){return this.maximizeInPlaceFromFloats(e.r,e.g,e.b)}minimizeInPlaceFromFloats(e,t,s){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(s,this.b),this}maximizeInPlaceFromFloats(e,t,s){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(s,this.b),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b}equalsFloats(e,t,s){return this.equalsToFloats(e,t,s)}equalsToFloats(e,t,s){return this.r===e&&this.g===t&&this.b===s}equalsWithEpsilon(e,t=A){return Q.WithinEpsilon(this.r,e.r,t)&&Q.WithinEpsilon(this.g,e.g,t)&&Q.WithinEpsilon(this.b,e.b,t)}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}scale(e){return new ee(this.r*e,this.g*e,this.b*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t}clampToRef(e=0,t=1,s){return s.r=L(this.r,e,t),s.g=L(this.g,e,t),s.b=L(this.b,e,t),s}add(e){return new ee(this.r+e.r,this.g+e.g,this.b+e.b)}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addInPlaceFromFloats(e,t,s){return this.r+=e,this.g+=t,this.b+=s,this}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t}subtract(e){return new ee(this.r-e.r,this.g-e.g,this.b-e.b)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this}subtractFromFloats(e,t,s){return new ee(this.r-e,this.g-t,this.b-s)}subtractFromFloatsToRef(e,t,s,i){return i.r=this.r-e,i.g=this.g-t,i.b=this.b-s,i}clone(){return new ee(this.r,this.g,this.b)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copyFromFloats(e,t,s){return this.r=e,this.g=t,this.b=s,this}set(e,t,s){return this.copyFromFloats(e,t,s)}setAll(e){return this.r=this.g=this.b=e,this}toHexString(){const e=Math.round(255*this.r),t=Math.round(255*this.g),s=Math.round(255*this.b);return"#"+N(e)+N(t)+N(s)}toHSV(){return this.toHSVToRef(new ee)}toHSVToRef(e){const t=this.r,s=this.g,i=this.b,r=Math.max(t,s,i),n=Math.min(t,s,i);let a=0,o=0;const h=r,l=r-n;return 0!==r&&(o=l/r),r!=n&&(r==t?(a=(s-i)/l,s<i&&(a+=6)):r==s?a=(i-t)/l+2:r==i&&(a=(t-s)/l+4),a*=60),e.r=a,e.g=o,e.b=h,e}toLinearSpace(e=!1){const t=new ee;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=Z(this.r),e.g=Z(this.g),e.b=Z(this.b)):(e.r=j(this.r),e.g=j(this.g),e.b=j(this.b)),this}toGammaSpace(e=!1){const t=new ee;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=J(this.r),e.g=J(this.g),e.b=J(this.b)):(e.r=$(this.r),e.g=$(this.g),e.b=$(this.b)),this}static HSVtoRGBToRef(e,t,s,i){const r=s*t,n=e/60,a=r*(1-Math.abs(n%2-1));let o=0,h=0,l=0;n>=0&&n<=1?(o=r,h=a):n>=1&&n<=2?(o=a,h=r):n>=2&&n<=3?(h=r,l=a):n>=3&&n<=4?(h=a,l=r):n>=4&&n<=5?(o=a,l=r):n>=5&&n<=6&&(o=r,l=a);const c=s-r;return i.r=o+c,i.g=h+c,i.b=l+c,i}static FromHSV(e,t,s){const i=new ee(0,0,0);return ee.HSVtoRGBToRef(e,t,s,i),i}static FromHexString(e){if("#"!==e.substring(0,1)||7!==e.length)return new ee(0,0,0);const t=parseInt(e.substring(1,3),16),s=parseInt(e.substring(3,5),16),i=parseInt(e.substring(5,7),16);return ee.FromInts(t,s,i)}static FromArray(e,t=0){return new ee(e[t],e[t+1],e[t+2])}static FromArrayToRef(e,t=0,s){s.r=e[t],s.g=e[t+1],s.b=e[t+2]}static FromInts(e,t,s){return new ee(e/255,t/255,s/255)}static Lerp(e,t,s){const i=new ee(0,0,0);return ee.LerpToRef(e,t,s,i),i}static LerpToRef(e,t,s,i){i.r=e.r+(t.r-e.r)*s,i.g=e.g+(t.g-e.g)*s,i.b=e.b+(t.b-e.b)*s}static Hermite(e,t,s,i,r){const n=r*r,a=r*n,o=2*a-3*n+1,h=-2*a+3*n,l=a-2*n+r,c=a-n,u=e.r*o+s.r*h+t.r*l+i.r*c,d=e.g*o+s.g*h+t.g*l+i.g*c,_=e.b*o+s.b*h+t.b*l+i.b*c;return new ee(u,d,_)}static Hermite1stDerivative(e,t,s,i,r){const n=ee.Black();return this.Hermite1stDerivativeToRef(e,t,s,i,r,n),n}static Hermite1stDerivativeToRef(e,t,s,i,r,n){const a=r*r;n.r=6*(a-r)*e.r+(3*a-4*r+1)*t.r+6*(-a+r)*s.r+(3*a-2*r)*i.r,n.g=6*(a-r)*e.g+(3*a-4*r+1)*t.g+6*(-a+r)*s.g+(3*a-2*r)*i.g,n.b=6*(a-r)*e.b+(3*a-4*r+1)*t.b+6*(-a+r)*s.b+(3*a-2*r)*i.b}static Red(){return new ee(1,0,0)}static Green(){return new ee(0,1,0)}static Blue(){return new ee(0,0,1)}static Black(){return new ee(0,0,0)}static get BlackReadOnly(){return ee._BlackReadOnly}static White(){return new ee(1,1,1)}static Purple(){return new ee(.5,0,.5)}static Magenta(){return new ee(1,0,1)}static Yellow(){return new ee(1,1,0)}static Gray(){return new ee(.5,.5,.5)}static Teal(){return new ee(0,1,1)}static Random(){return new ee(Math.random(),Math.random(),Math.random())}}ee._BlackReadOnly=ee.Black(),Object.defineProperties(ee.prototype,{dimension:{value:[3]},rank:{value:1}});class te{constructor(e=0,t=0,s=0,i=1){this.r=e,this.g=t,this.b=s,this.a=i}asArray(){return[this.r,this.g,this.b,this.a]}toArray(e,t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e[t+3]=this.a,this}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this.a=e[t+3],this}equals(e){return e&&this.r===e.r&&this.g===e.g&&this.b===e.b&&this.a===e.a}add(e){return new te(this.r+e.r,this.g+e.g,this.b+e.b,this.a+e.a)}addToRef(e,t){return t.r=this.r+e.r,t.g=this.g+e.g,t.b=this.b+e.b,t.a=this.a+e.a,t}addInPlace(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this.a+=e.a,this}addInPlaceFromFloats(e,t,s,i){return this.r+=e,this.g+=t,this.b+=s,this.a+=i,this}subtract(e){return new te(this.r-e.r,this.g-e.g,this.b-e.b,this.a-e.a)}subtractToRef(e,t){return t.r=this.r-e.r,t.g=this.g-e.g,t.b=this.b-e.b,t.a=this.a-e.a,t}subtractInPlace(e){return this.r-=e.r,this.g-=e.g,this.b-=e.b,this.a-=e.a,this}subtractFromFloats(e,t,s,i){return new te(this.r-e,this.g-t,this.b-s,this.a-i)}subtractFromFloatsToRef(e,t,s,i,r){return r.r=this.r-e,r.g=this.g-t,r.b=this.b-s,r.a=this.a-i,r}scale(e){return new te(this.r*e,this.g*e,this.b*e,this.a*e)}scaleInPlace(e){return this.r*=e,this.g*=e,this.b*=e,this.a*=e,this}scaleToRef(e,t){return t.r=this.r*e,t.g=this.g*e,t.b=this.b*e,t.a=this.a*e,t}scaleAndAddToRef(e,t){return t.r+=this.r*e,t.g+=this.g*e,t.b+=this.b*e,t.a+=this.a*e,t}clampToRef(e=0,t=1,s){return s.r=L(this.r,e,t),s.g=L(this.g,e,t),s.b=L(this.b,e,t),s.a=L(this.a,e,t),s}multiply(e){return new te(this.r*e.r,this.g*e.g,this.b*e.b,this.a*e.a)}multiplyToRef(e,t){return t.r=this.r*e.r,t.g=this.g*e.g,t.b=this.b*e.b,t.a=this.a*e.a,t}multiplyInPlace(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this.a*=e.a,this}multiplyByFloats(e,t,s,i){return new te(this.r*e,this.g*t,this.b*s,this.a*i)}divide(e){throw new ReferenceError("Can not divide a color")}divideToRef(e,t){throw new ReferenceError("Can not divide a color")}divideInPlace(e){throw new ReferenceError("Can not divide a color")}minimizeInPlace(e){return this.r=Math.min(this.r,e.r),this.g=Math.min(this.g,e.g),this.b=Math.min(this.b,e.b),this.a=Math.min(this.a,e.a),this}maximizeInPlace(e){return this.r=Math.max(this.r,e.r),this.g=Math.max(this.g,e.g),this.b=Math.max(this.b,e.b),this.a=Math.max(this.a,e.a),this}minimizeInPlaceFromFloats(e,t,s,i){return this.r=Math.min(e,this.r),this.g=Math.min(t,this.g),this.b=Math.min(s,this.b),this.a=Math.min(i,this.a),this}maximizeInPlaceFromFloats(e,t,s,i){return this.r=Math.max(e,this.r),this.g=Math.max(t,this.g),this.b=Math.max(s,this.b),this.a=Math.max(i,this.a),this}floorToRef(e){throw new ReferenceError("Can not floor a color")}floor(){throw new ReferenceError("Can not floor a color")}fractToRef(e){throw new ReferenceError("Can not fract a color")}fract(){throw new ReferenceError("Can not fract a color")}negate(){throw new ReferenceError("Can not negate a color")}negateInPlace(){throw new ReferenceError("Can not negate a color")}negateToRef(e){throw new ReferenceError("Can not negate a color")}equalsWithEpsilon(e,t=A){return Q.WithinEpsilon(this.r,e.r,t)&&Q.WithinEpsilon(this.g,e.g,t)&&Q.WithinEpsilon(this.b,e.b,t)&&Q.WithinEpsilon(this.a,e.a,t)}equalsToFloats(e,t,s,i){return this.r===e&&this.g===t&&this.b===s&&this.a===i}toString(){return"{R: "+this.r+" G:"+this.g+" B:"+this.b+" A:"+this.a+"}"}getClassName(){return"Color4"}getHashCode(){let e=255*this.r|0;return e=397*e^255*this.g,e=397*e^255*this.b,e=397*e^255*this.a,e}clone(){return(new te).copyFrom(this)}copyFrom(e){return this.r=e.r,this.g=e.g,this.b=e.b,this.a=e.a,this}copyFromFloats(e,t,s,i){return this.r=e,this.g=t,this.b=s,this.a=i,this}set(e,t,s,i){return this.copyFromFloats(e,t,s,i)}setAll(e){return this.r=this.g=this.b=this.a=e,this}toHexString(e=!1){const t=Math.round(255*this.r),s=Math.round(255*this.g),i=Math.round(255*this.b);if(e)return"#"+N(t)+N(s)+N(i);const r=Math.round(255*this.a);return"#"+N(t)+N(s)+N(i)+N(r)}toLinearSpace(e=!1){const t=new te;return this.toLinearSpaceToRef(t,e),t}toLinearSpaceToRef(e,t=!1){return t?(e.r=Z(this.r),e.g=Z(this.g),e.b=Z(this.b)):(e.r=j(this.r),e.g=j(this.g),e.b=j(this.b)),e.a=this.a,this}toGammaSpace(e=!1){const t=new te;return this.toGammaSpaceToRef(t,e),t}toGammaSpaceToRef(e,t=!1){return t?(e.r=J(this.r),e.g=J(this.g),e.b=J(this.b)):(e.r=$(this.r),e.g=$(this.g),e.b=$(this.b)),e.a=this.a,this}static FromHexString(e){if("#"!==e.substring(0,1)||9!==e.length&&7!==e.length)return new te(0,0,0,0);const t=parseInt(e.substring(1,3),16),s=parseInt(e.substring(3,5),16),i=parseInt(e.substring(5,7),16),r=9===e.length?parseInt(e.substring(7,9),16):255;return te.FromInts(t,s,i,r)}static Lerp(e,t,s){return te.LerpToRef(e,t,s,new te)}static LerpToRef(e,t,s,i){return i.r=e.r+(t.r-e.r)*s,i.g=e.g+(t.g-e.g)*s,i.b=e.b+(t.b-e.b)*s,i.a=e.a+(t.a-e.a)*s,i}static Hermite(e,t,s,i,r){const n=r*r,a=r*n,o=2*a-3*n+1,h=-2*a+3*n,l=a-2*n+r,c=a-n,u=e.r*o+s.r*h+t.r*l+i.r*c,d=e.g*o+s.g*h+t.g*l+i.g*c,_=e.b*o+s.b*h+t.b*l+i.b*c,f=e.a*o+s.a*h+t.a*l+i.a*c;return new te(u,d,_,f)}static Hermite1stDerivative(e,t,s,i,r){const n=new te;return this.Hermite1stDerivativeToRef(e,t,s,i,r,n),n}static Hermite1stDerivativeToRef(e,t,s,i,r,n){const a=r*r;n.r=6*(a-r)*e.r+(3*a-4*r+1)*t.r+6*(-a+r)*s.r+(3*a-2*r)*i.r,n.g=6*(a-r)*e.g+(3*a-4*r+1)*t.g+6*(-a+r)*s.g+(3*a-2*r)*i.g,n.b=6*(a-r)*e.b+(3*a-4*r+1)*t.b+6*(-a+r)*s.b+(3*a-2*r)*i.b,n.a=6*(a-r)*e.a+(3*a-4*r+1)*t.a+6*(-a+r)*s.a+(3*a-2*r)*i.a}static FromColor3(e,t=1){return new te(e.r,e.g,e.b,t)}static FromArray(e,t=0){return new te(e[t],e[t+1],e[t+2],e[t+3])}static FromArrayToRef(e,t=0,s){s.r=e[t],s.g=e[t+1],s.b=e[t+2],s.a=e[t+3]}static FromInts(e,t,s,i){return new te(e/255,t/255,s/255,i/255)}static CheckColors4(e,t){if(e.length===3*t){const t=[];for(let s=0;s<e.length;s+=3){const i=s/3*4;t[i]=e[s],t[i+1]=e[s+1],t[i+2]=e[s+2],t[i+3]=1}return t}return e}}Object.defineProperties(te.prototype,{dimension:{value:[4]},rank:{value:1}});class se{}se.Color3=y(3,ee.Black),se.Color4=y(3,(()=>new te(0,0,0,0))),I("BABYLON.Color3",ee),I("BABYLON.Color4",te);const ie=function(e,t,s,r={}){const n=e();q&&q.HasTags(t)&&q.AddTagsTo(n,q.GetTags(t,!0));const a=i(n),o={};for(const e in a){const i=a[e],h=t[e],l=i.type;if(null!=h&&("uniqueId"!==e||re.AllowLoadingUniqueId))switch(l){case 0:case 6:case 11:n[e]=h;break;case 1:r.cloneTexturesOnlyOnce&&o[h.uniqueId]?n[e]=o[h.uniqueId]:(n[e]=s||h.isRenderTarget?h:h.clone(),o[h.uniqueId]=n[e]);break;case 2:case 3:case 4:case 5:case 7:case 10:case 12:n[e]=s?h:h.clone()}}return n};class re{static AppendSerializedAnimations(e,t){if(e.animations){t.animations=[];for(let s=0;s<e.animations.length;s++){const i=e.animations[s];t.animations.push(i.serialize())}}}static Serialize(e,t){t||(t={}),q&&(t.tags=q.GetTags(e));const s=i(e);for(const i in s){const r=s[i],n=r.sourceName||i,a=r.type,o=e[i];if(null!=o&&("uniqueId"!==i||re.AllowLoadingUniqueId))switch(a){case 0:t[n]=o;break;case 1:case 3:case 7:case 9:t[n]=o.serialize();break;case 2:case 4:case 5:case 8:case 10:case 12:t[n]=o.asArray();break;case 6:case 11:t[n]=o.id}}return t}static ParseProperties(e,t,s,r){r||(r="");const n=i(t);for(const i in n){const a=n[i],o=e[a.sourceName||i],h=a.type;if(null!=o&&("uniqueId"!==i||re.AllowLoadingUniqueId)){const e=t;switch(h){case 0:e[i]=o;break;case 1:s&&(e[i]=re._TextureParser(o,s,r));break;case 2:e[i]=ee.FromArray(o);break;case 3:e[i]=re._FresnelParametersParser(o);break;case 4:e[i]=B.FromArray(o);break;case 5:e[i]=U.FromArray(o);break;case 6:s&&(e[i]=s.getLastMeshById(o));break;case 7:e[i]=re._ColorCurvesParser(o);break;case 8:e[i]=te.FromArray(o);break;case 9:e[i]=re._ImageProcessingConfigurationParser(o);break;case 10:e[i]=G.FromArray(o);break;case 11:s&&(e[i]=s.getCameraById(o));break;case 12:e[i]=V.FromArray(o)}}}}static Parse(e,t,s,i=null){const r=e();return q&&q.AddTagsTo(r,t.tags),re.ParseProperties(t,r,s,i),r}static Clone(e,t,s={}){return ie(e,t,!1,s)}static Instanciate(e,t){return ie(e,t,!0)}}re.AllowLoadingUniqueId=!1,re._ImageProcessingConfigurationParser=e=>{throw Y("ImageProcessingConfiguration")},re._FresnelParametersParser=e=>{throw Y("FresnelParameters")},re._ColorCurvesParser=e=>{throw Y("ColorCurves")},re._TextureParser=(e,t,s)=>{throw Y("Texture")};class ne{constructor(){this._doNotSerialize=!1,this._isDisposed=!1,this._sceneRootNodesIndex=-1,this._isEnabled=!0,this._isParentEnabled=!0,this._isReady=!0,this._onEnabledStateChangedObservable=new g,this._onClonedObservable=new g}}class ae{static AddNodeConstructor(e,t){this._NodeConstructors[e]=t}static Construct(e,t,s,i){const r=this._NodeConstructors[e];return r?r(t,s,i):null}set accessibilityTag(e){this._accessibilityTag=e,this.onAccessibilityTagChangedObservable.notifyObservers(e)}get accessibilityTag(){return this._accessibilityTag}get doNotSerialize(){return!!this._nodeDataStorage._doNotSerialize||!!this._parentNode&&this._parentNode.doNotSerialize}set doNotSerialize(e){this._nodeDataStorage._doNotSerialize=e}isDisposed(){return this._nodeDataStorage._isDisposed}set parent(e){if(this._parentNode===e)return;const t=this._parentNode;if(this._parentNode&&void 0!==this._parentNode._children&&null!==this._parentNode._children){const t=this._parentNode._children.indexOf(this);-1!==t&&this._parentNode._children.splice(t,1),e||this._nodeDataStorage._isDisposed||this._addToSceneRootNodes()}this._parentNode=e,this._isDirty=!0,this._parentNode&&(void 0!==this._parentNode._children&&null!==this._parentNode._children||(this._parentNode._children=new Array),this._parentNode._children.push(this),t||this._removeFromSceneRootNodes()),this._syncParentEnabledState()}get parent(){return this._parentNode}_serializeAsParent(e){e.parentId=this.uniqueId}_addToSceneRootNodes(){-1===this._nodeDataStorage._sceneRootNodesIndex&&(this._nodeDataStorage._sceneRootNodesIndex=this._scene.rootNodes.length,this._scene.rootNodes.push(this))}_removeFromSceneRootNodes(){if(-1!==this._nodeDataStorage._sceneRootNodesIndex){const e=this._scene.rootNodes,t=e.length-1;e[this._nodeDataStorage._sceneRootNodesIndex]=e[t],e[this._nodeDataStorage._sceneRootNodesIndex]._nodeDataStorage._sceneRootNodesIndex=this._nodeDataStorage._sceneRootNodesIndex,this._scene.rootNodes.pop(),this._nodeDataStorage._sceneRootNodesIndex=-1}}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}getClassName(){return"Node"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onEnabledStateChangedObservable(){return this._nodeDataStorage._onEnabledStateChangedObservable}get onClonedObservable(){return this._nodeDataStorage._onClonedObservable}constructor(e,t=null,s=!0){this._isDirty=!1,this._nodeDataStorage=new ne,this.state="",this.metadata=null,this.reservedDataStore=null,this._accessibilityTag=null,this.onAccessibilityTagChangedObservable=new g,this._parentContainer=null,this.animations=[],this._ranges={},this.onReady=null,this._currentRenderId=-1,this._parentUpdateId=-1,this._childUpdateId=-1,this._waitingParentId=null,this._waitingParentInstanceIndex=null,this._waitingParsedUniqueId=null,this._cache={},this._parentNode=null,this._children=null,this._worldMatrix=V.Identity(),this._worldMatrixDeterminant=0,this._worldMatrixDeterminantIsDirty=!0,this._animationPropertiesOverride=null,this._isNode=!0,this.onDisposeObservable=new g,this._onDisposeObserver=null,this._behaviors=new Array,this.name=e,this.id=e,this._scene=t||C.LastCreatedScene,this.uniqueId=this._scene.getUniqueId(),this._initCache(),s&&this._addToSceneRootNodes()}getScene(){return this._scene}getEngine(){return this._scene.getEngine()}addBehavior(e,t=!1){return-1!==this._behaviors.indexOf(e)||(e.init(),this._scene.isLoading&&!t?this._scene.onDataLoadedObservable.addOnce((()=>{e.attach(this)})):e.attach(this),this._behaviors.push(e)),this}removeBehavior(e){const t=this._behaviors.indexOf(e);return-1===t||(this._behaviors[t].detach(),this._behaviors.splice(t,1)),this}get behaviors(){return this._behaviors}getBehaviorByName(e){for(const t of this._behaviors)if(t.name===e)return t;return null}getWorldMatrix(){return this._currentRenderId!==this._scene.getRenderId()&&this.computeWorldMatrix(),this._worldMatrix}_getWorldMatrixDeterminant(){return this._worldMatrixDeterminantIsDirty&&(this._worldMatrixDeterminantIsDirty=!1,this._worldMatrixDeterminant=this._worldMatrix.determinant()),this._worldMatrixDeterminant}get worldMatrixFromCache(){return this._worldMatrix}_initCache(){this._cache={}}updateCache(e){!e&&this.isSynchronized()||this._updateCache()}_getActionManagerForTrigger(e,t=!0){return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_updateCache(e){}_isSynchronized(){return!0}_markSyncedWithParent(){this._parentNode&&(this._parentUpdateId=this._parentNode._childUpdateId)}isSynchronizedWithParent(){return!this._parentNode||!this._parentNode._isDirty&&this._parentUpdateId===this._parentNode._childUpdateId&&this._parentNode.isSynchronized()}isSynchronized(){return!(this._parentNode&&!this.isSynchronizedWithParent())&&this._isSynchronized()}isReady(e=!1){return this._nodeDataStorage._isReady}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}isEnabled(e=!0){return!1===e?this._nodeDataStorage._isEnabled:!!this._nodeDataStorage._isEnabled&&this._nodeDataStorage._isParentEnabled}_syncParentEnabledState(){this._nodeDataStorage._isParentEnabled=!this._parentNode||this._parentNode.isEnabled(),this._children&&this._children.forEach((e=>{e._syncParentEnabledState()}))}setEnabled(e){this._nodeDataStorage._isEnabled!==e&&(this._nodeDataStorage._isEnabled=e,this._syncParentEnabledState(),this._nodeDataStorage._onEnabledStateChangedObservable.notifyObservers(e))}isDescendantOf(e){return!!this.parent&&(this.parent===e||this.parent.isDescendantOf(e))}_getDescendants(e,t=!1,s){if(this._children)for(let i=0;i<this._children.length;i++){const r=this._children[i];s&&!s(r)||e.push(r),t||r._getDescendants(e,!1,s)}}getDescendants(e,t){const s=[];return this._getDescendants(s,e,t),s}getChildMeshes(e,t){const s=[];return this._getDescendants(s,e,(e=>(!t||t(e))&&void 0!==e.cullingStrategy)),s}getChildren(e,t=!0){return this.getDescendants(t,e)}_setReady(e){e!==this._nodeDataStorage._isReady&&(e?(this.onReady&&this.onReady(this),this._nodeDataStorage._isReady=!0):this._nodeDataStorage._isReady=!1)}getAnimationByName(e){for(let t=0;t<this.animations.length;t++){const s=this.animations[t];if(s.name===e)return s}return null}createAnimationRange(e,t,s){if(!this._ranges[e]){this._ranges[e]=ae._AnimationRangeFactory(e,t,s);for(let i=0,r=this.animations.length;i<r;i++)this.animations[i]&&this.animations[i].createRange(e,t,s)}}deleteAnimationRange(e,t=!0){for(let s=0,i=this.animations.length;s<i;s++)this.animations[s]&&this.animations[s].deleteRange(e,t);this._ranges[e]=null}getAnimationRange(e){return this._ranges[e]||null}clone(e,t,s){const i=re.Clone((()=>new ae(e,this.getScene())),this);if(t&&(i.parent=t),!s){const t=this.getDescendants(!0);for(let s=0;s<t.length;s++){const r=t[s];r.clone(e+"."+r.name,i)}}return i}getAnimationRanges(){const e=[];let t;for(t in this._ranges)e.push(this._ranges[t]);return e}beginAnimation(e,t,s,i){const r=this.getAnimationRange(e);return r?this._scene.beginAnimation(this,r.from,r.to,t,s,i):null}serializeAnimationRanges(){const e=[];for(const t in this._ranges){const s=this._ranges[t];if(!s)continue;const i={};i.name=t,i.from=s.from,i.to=s.to,e.push(i)}return e}computeWorldMatrix(e){return this._worldMatrix||(this._worldMatrix=V.Identity()),this._worldMatrix}dispose(e,t=!1){if(this._nodeDataStorage._isDisposed=!0,!e){const s=this.getDescendants(!0);for(const i of s)i.dispose(e,t)}this.parent?this.parent=null:this._removeFromSceneRootNodes(),this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onEnabledStateChangedObservable.clear(),this.onClonedObservable.clear();for(const e of this._behaviors)e.detach();this._behaviors.length=0,this.metadata=null}static ParseAnimationRanges(e,t,s){if(t.ranges)for(let s=0;s<t.ranges.length;s++){const i=t.ranges[s];e.createAnimationRange(i.name,i.from,i.to)}}getHierarchyBoundingVectors(e=!0,t=null){let s,i;this.getScene().incrementRenderId(),this.computeWorldMatrix(!0);const r=this;if(r.getBoundingInfo&&r.subMeshes){const e=r.getBoundingInfo();s=e.boundingBox.minimumWorld.clone(),i=e.boundingBox.maximumWorld.clone()}else s=new U(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),i=new U(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);if(e){const e=this.getDescendants(!1);for(const r of e){const e=r;if(e.computeWorldMatrix(!0),t&&!t(e))continue;if(!e.getBoundingInfo||0===e.getTotalVertices())continue;const n=e.getBoundingInfo().boundingBox,a=n.minimumWorld,o=n.maximumWorld;U.CheckExtends(a,s,i),U.CheckExtends(o,s,i)}}return{min:s,max:i}}}function oe(){return"undefined"!=typeof window}function he(){return"undefined"!=typeof navigator}function le(){return"undefined"!=typeof document}function ce(e){let t="",s=e.firstChild;for(;s;)3===s.nodeType&&(t+=s.textContent),s=s.nextSibling;return t}ae._AnimationRangeFactory=(e,t,s)=>{throw Y("AnimationRange")},ae._NodeConstructors={},e([a()],ae.prototype,"name",void 0),e([a()],ae.prototype,"id",void 0),e([a()],ae.prototype,"uniqueId",void 0),e([a()],ae.prototype,"state",void 0),e([a()],ae.prototype,"metadata",void 0);class ue{static _CheckLimit(e,t){let s=ue._LogLimitOutputs[e];return s?s.current++:(s={limit:t,current:1},ue._LogLimitOutputs[e]=s),s.current<=s.limit}static _GenerateLimitMessage(e,t=1){const s=ue._LogLimitOutputs[e];if(!s||!ue.MessageLimitReached)return;const i=this._Levels[t];s.current===s.limit&&ue[i.name](ue.MessageLimitReached.replace(/%LIMIT%/g,""+s.limit).replace(/%TYPE%/g,i.name??""))}static _AddLogEntry(e){ue._LogCache=e+ue._LogCache,ue.OnNewCacheEntry&&ue.OnNewCacheEntry(e)}static _FormatMessage(e){const t=e=>e<10?"0"+e:""+e,s=new Date;return"["+t(s.getHours())+":"+t(s.getMinutes())+":"+t(s.getSeconds())+"]: "+e}static _LogDisabled(e,t){}static _LogEnabled(e=1,t,s){const i=Array.isArray(t)?t[0]:t;if(void 0!==s&&!ue._CheckLimit(i,s))return;const r=ue._FormatMessage(i),n=this._Levels[e],a=Array.isArray(t)?t.slice(1):[];n.logFunc&&n.logFunc("BJS - "+r,...a);const o=`<div style='color:${n.color}'>${r}</div><br>`;ue._AddLogEntry(o),ue._GenerateLimitMessage(i,e)}static get LogCache(){return ue._LogCache}static ClearLogCache(){ue._LogCache="",ue._LogLimitOutputs={},ue.errorsCount=0}static set LogLevels(e){ue.Log=ue._LogDisabled,ue.Warn=ue._LogDisabled,ue.Error=ue._LogDisabled,[ue.MessageLogLevel,ue.WarningLogLevel,ue.ErrorLogLevel].forEach((t=>{if((e&t)===t){const e=this._Levels[t];ue[e.name]=ue._LogEnabled.bind(ue,t)}}))}}ue.NoneLogLevel=0,ue.MessageLogLevel=1,ue.WarningLogLevel=2,ue.ErrorLogLevel=4,ue.AllLogLevel=7,ue.MessageLimitReached="Too many %TYPE%s (%LIMIT%), no more %TYPE%s will be reported for this message.",ue._LogCache="",ue._LogLimitOutputs={},ue._Levels=[{},{color:"white",logFunc:console.log,name:"Log"},{color:"orange",logFunc:console.warn,name:"Warn"},{},{color:"red",logFunc:console.error,name:"Error"}],ue.errorsCount=0,ue.Log=ue._LogEnabled.bind(ue,ue.MessageLogLevel),ue.Warn=ue._LogEnabled.bind(ue,ue.WarningLogLevel),ue.Error=ue._LogEnabled.bind(ue,ue.ErrorLogLevel);const de=(e,t,s)=>e?e.getClassName&&"Mesh"===e.getClassName()?null:!e.getClassName||"SubMesh"!==e.getClassName()&&"PhysicsBody"!==e.getClassName()?e.clone?e.clone():Array.isArray(e)?e.slice():s&&"object"==typeof e?{...e}:null:e.clone(t):null;class _e{static DeepCopy(e,t,s,i,r=!1){const n=function(e){const t=[];do{Object.getOwnPropertyNames(e).forEach((function(e){-1===t.indexOf(e)&&t.push(e)}))}while(e=Object.getPrototypeOf(e));return t}(e);for(const a of n){if("_"===a[0]&&(!i||-1===i.indexOf(a)))continue;if(a.endsWith("Observable"))continue;if(s&&-1!==s.indexOf(a))continue;const n=e[a],o=typeof n;if("function"!==o)try{if("object"===o)if(n instanceof Uint8Array)t[a]=Uint8Array.from(n);else if(n instanceof Array){if(t[a]=[],n.length>0)if("object"==typeof n[0])for(let e=0;e<n.length;e++){const s=de(n[e],t,r);-1===t[a].indexOf(s)&&t[a].push(s)}else t[a]=n.slice(0)}else t[a]=de(n,t,r);else t[a]=n}catch(e){ue.Warn(e.message)}}}}class fe{static get Now(){return oe()&&window.performance&&window.performance.now?window.performance.now():Date.now()}}class pe{constructor(){this._xhr="undefined"!=typeof _native&&_native.XMLHttpRequest?new _native.XMLHttpRequest:new XMLHttpRequest,this._requestURL=""}static get IsCustomRequestAvailable(){return Object.keys(pe.CustomRequestHeaders).length>0||pe.CustomRequestModifiers.length>0}_injectCustomRequestHeaders(){if(!this._shouldSkipRequestModifications(this._requestURL))for(const e in pe.CustomRequestHeaders){const t=pe.CustomRequestHeaders[e];t&&this._xhr.setRequestHeader(e,t)}}_shouldSkipRequestModifications(e){return pe.SkipRequestModificationForBabylonCDN&&(e.includes("preview.babylonjs.com")||e.includes("cdn.babylonjs.com"))}get onprogress(){return this._xhr.onprogress}set onprogress(e){this._xhr.onprogress=e}get readyState(){return this._xhr.readyState}get status(){return this._xhr.status}get statusText(){return this._xhr.statusText}get response(){return this._xhr.response}get responseURL(){return this._xhr.responseURL}get responseText(){return this._xhr.responseText}get responseType(){return this._xhr.responseType}set responseType(e){this._xhr.responseType=e}get timeout(){return this._xhr.timeout}set timeout(e){this._xhr.timeout=e}addEventListener(e,t,s){this._xhr.addEventListener(e,t,s)}removeEventListener(e,t,s){this._xhr.removeEventListener(e,t,s)}abort(){this._xhr.abort()}send(e){pe.CustomRequestHeaders&&this._injectCustomRequestHeaders(),this._xhr.send(e)}open(e,t){for(const e of pe.CustomRequestModifiers){if(this._shouldSkipRequestModifications(t))return;e(this._xhr,t)}t=(t=t.replace("file:http:","http:")).replace("file:https:","https:"),this._requestURL=t,this._xhr.open(e,t,!0)}setRequestHeader(e,t){this._xhr.setRequestHeader(e,t)}getResponseHeader(e){return this._xhr.getResponseHeader(e)}}pe.CustomRequestHeaders={},pe.CustomRequestModifiers=new Array,pe.SkipRequestModificationForBabylonCDN=!0;class me{}me.FilesToLoad={};class ge extends Error{}ge._setPrototypeOf=Object.setPrototypeOf||((e,t)=>(e.__proto__=t,e));const Te={MeshInvalidPositionsError:0,UnsupportedTextureError:1e3,GLTFLoaderUnexpectedMagicError:2e3,SceneLoaderError:3e3,LoadFileError:4e3,RequestFileError:4001,ReadFileError:4002};class Ee extends ge{constructor(e,t,s){super(e),this.errorCode=t,this.innerError=s,this.name="RuntimeError",ge._setPrototypeOf(this,Ee.prototype)}}const Ae=e=>{const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let s,i,r,n,a,o,h,l="",c=0;const u=ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);for(;c<u.length;)s=u[c++],i=c<u.length?u[c++]:Number.NaN,r=c<u.length?u[c++]:Number.NaN,n=s>>2,a=(3&s)<<4|i>>4,o=(15&i)<<2|r>>6,h=63&r,isNaN(i)?o=h=64:isNaN(r)&&(h=64),l+=t.charAt(n)+t.charAt(a)+t.charAt(o)+t.charAt(h);return l},ye=e=>atob(e);class be{constructor(){this.children=[]}isValid(e){return!0}process(e,t){let s="";if(this.line){let i=this.line;const r=t.processor;if(r){r.lineProcessor&&(i=r.lineProcessor(i,t.isFragment,t.processingContext));const s=t.processor?.attributeKeywordName??"attribute",n=t.isFragment&&t.processor?.varyingFragmentKeywordName?t.processor?.varyingFragmentKeywordName:!t.isFragment&&t.processor?.varyingVertexKeywordName?t.processor?.varyingVertexKeywordName:"varying";if(!t.isFragment&&r.attributeProcessor&&this.line.startsWith(s))i=r.attributeProcessor(this.line,e,t.processingContext);else if(r.varyingProcessor&&(r.varyingCheck?.(this.line,t.isFragment)||!r.varyingCheck&&this.line.startsWith(n)))i=r.varyingProcessor(this.line,t.isFragment,e,t.processingContext);else if(r.uniformProcessor&&r.uniformRegexp&&r.uniformRegexp.test(this.line))t.lookForClosingBracketForUniformBuffer||(i=r.uniformProcessor(this.line,t.isFragment,e,t.processingContext));else if(r.uniformBufferProcessor&&r.uniformBufferRegexp&&r.uniformBufferRegexp.test(this.line))t.lookForClosingBracketForUniformBuffer||(i=r.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0);else if(r.textureProcessor&&r.textureRegexp&&r.textureRegexp.test(this.line))i=r.textureProcessor(this.line,t.isFragment,e,t.processingContext);else if((r.uniformProcessor||r.uniformBufferProcessor)&&this.line.startsWith("uniform")&&!t.lookForClosingBracketForUniformBuffer){/uniform\s+(?:(?:highp)?|(?:lowp)?)\s*(\S+)\s+(\S+)\s*;/.test(this.line)?r.uniformProcessor&&(i=r.uniformProcessor(this.line,t.isFragment,e,t.processingContext)):r.uniformBufferProcessor&&(i=r.uniformBufferProcessor(this.line,t.isFragment,t.processingContext),t.lookForClosingBracketForUniformBuffer=!0)}t.lookForClosingBracketForUniformBuffer&&-1!==this.line.indexOf("}")&&(t.lookForClosingBracketForUniformBuffer=!1,r.endOfUniformBufferProcessor&&(i=r.endOfUniformBufferProcessor(this.line,t.isFragment,t.processingContext)))}s+=i+"\n"}return this.children.forEach((i=>{s+=i.process(e,t)})),this.additionalDefineKey&&(e[this.additionalDefineKey]=this.additionalDefineValue||"true"),s}}class Re{constructor(){this._lines=[]}get currentLine(){return this._lines[this.lineIndex]}get canRead(){return this.lineIndex<this._lines.length-1}set lines(e){this._lines.length=0;for(const t of e){if(!t||"\r"===t)continue;if("#"===t[0]){this._lines.push(t);continue}const e=t.trim();if(!e)continue;if(e.startsWith("//")){this._lines.push(t);continue}const s=e.indexOf(";");if(-1===s)this._lines.push(e);else if(s===e.length-1)e.length>1&&this._lines.push(e);else{const e=t.split(";");for(let t=0;t<e.length;t++){let s=e[t];s&&(s=s.trim(),s&&this._lines.push(s+(t!==e.length-1?";":"")))}}}}}class xe extends be{process(e,t){for(let s=0;s<this.children.length;s++){const i=this.children[s];if(i.isValid(e))return i.process(e,t)}return""}}class Me extends be{isValid(e){return this.testExpression.isTrue(e)}}class Ie{isTrue(e){return!0}static postfixToInfix(e){const t=[];for(const s of e)if(void 0===Ie._OperatorPriority[s])t.push(s);else{const e=t[t.length-1],i=t[t.length-2];t.length-=2,t.push(`(${i}${s}${e})`)}return t[t.length-1]}static infixToPostfix(e){const t=Ie._InfixToPostfixCache.get(e);if(t)return t.accessTime=Date.now(),t.result;if(!(e.includes("&&")||e.includes("||")||e.includes(")")||e.includes("(")))return[e];const s=[];let i=-1;const r=()=>{l=l.trim(),""!==l&&(s.push(l),l="")},n=e=>{i<Ie._Stack.length-1&&(Ie._Stack[++i]=e)},a=()=>Ie._Stack[i],o=()=>-1===i?"!!INVALID EXPRESSION!!":Ie._Stack[i--];let h=0,l="";for(;h<e.length;){const t=e.charAt(h),c=h<e.length-1?e.substr(h,2):"";if("("===t)l="",n(t);else if(")"===t){for(r();-1!==i&&"("!==a();)s.push(o());o()}else if(Ie._OperatorPriority[c]>1){for(r();-1!==i&&Ie._OperatorPriority[a()]>=Ie._OperatorPriority[c];)s.push(o());n(c),h++}else l+=t;h++}for(r();-1!==i;)"("===a()?o():s.push(o());return Ie._InfixToPostfixCache.size>=Ie.InfixToPostfixCacheLimitSize&&Ie.ClearCache(),Ie._InfixToPostfixCache.set(e,{result:s,accessTime:Date.now()}),s}static ClearCache(){const e=Array.from(Ie._InfixToPostfixCache.entries()).sort(((e,t)=>e[1].accessTime-t[1].accessTime));for(let t=0;t<Ie.InfixToPostfixCacheCleanupSize;t++)Ie._InfixToPostfixCache.delete(e[t][0])}}Ie.InfixToPostfixCacheLimitSize=5e4,Ie.InfixToPostfixCacheCleanupSize=25e3,Ie._InfixToPostfixCache=new Map,Ie._OperatorPriority={")":0,"(":1,"||":2,"&&":3},Ie._Stack=["","","","","","","","","","","","","","","","","","","",""];class Se extends Ie{constructor(e,t=!1){super(),this.define=e,this.not=t}isTrue(e){let t=void 0!==e[this.define];return this.not&&(t=!t),t}}class ve extends Ie{isTrue(e){return this.leftOperand.isTrue(e)||this.rightOperand.isTrue(e)}}class Ce extends Ie{isTrue(e){return this.leftOperand.isTrue(e)&&this.rightOperand.isTrue(e)}}class Pe extends Ie{constructor(e,t,s){super(),this.define=e,this.operand=t,this.testValue=s}isTrue(e){let t=e[this.define];void 0===t&&(t=this.define);let s=!1;const i=parseInt(t),r=parseInt(this.testValue);switch(this.operand){case">":s=i>r;break;case"<":s=i<r;break;case"<=":s=i<=r;break;case">=":s=i>=r;break;case"==":s=i===r;break;case"!=":s=i!==r}return s}}const Oe={};function De(e,t,s=""){return s+(t?t+"\n":"")+e}function Le(e,t,s,i,r,n,a){const o=a||Oe.loadFile;if(o){return o(e,t,s,i,r,n)}throw Y("FileTools")}function Fe(e,t,s,i){if(e)return t?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,s?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(i?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return t&&(e+="#define IS_NDC_HALF_ZRANGE"),s&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),i&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}const Ne=/defined\s*?\((.+?)\)/g,we=/defined\s*?\[(.+?)\]/g,Be=/#include\s?<(.+)>(\((.*)\))*(\[(.*)\])*/g,Ue=/__decl__/,ke=/light\{X\}.(\w*)/g,Ge=/\{X\}/g,Ve=[],He=/(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;function ze(e,t,s,i){t.processor?.preProcessShaderCode&&(e=t.processor.preProcessShaderCode(e,t.isFragment)),qe(e,t,(e=>{t.processCodeAfterIncludes&&(e=t.processCodeAfterIncludes(t.isFragment?"fragment":"vertex",e,t.defines));const r=function(e,t,s){let i=function(e,t){if(t.processor?.noPrecision)return e;const s=t.shouldUseHighPrecisionShader;-1===e.indexOf("precision highp float")?e=s?"precision highp float;\n"+e:"precision mediump float;\n"+e:s||(e=e.replace("precision highp float","precision mediump float"));return e}(e,t);if(!t.processor)return i;if(0===t.processor.shaderLanguage&&-1!==i.indexOf("#version 3")&&(i=i.replace("#version 300 es",""),!t.processor.parseGLES3))return i;const r=t.defines,n=function(e,t){const s=e.defines,i={};for(const e of s){const t=e.replace("#define","").replace(";","").trim().split(" ");i[t[0]]=t.length>1?t[1]:""}0===e.processor?.shaderLanguage&&(i.GL_ES="true");return i.__VERSION__=e.version,i[e.platformName]="true",Fe(i,t?.isNDCHalfZRange,t?.useReverseDepthBuffer,t?.useExactSrgbConversions),i}(t,s);t.processor.preProcessor&&(i=t.processor.preProcessor(i,r,n,t.isFragment,t.processingContext));i=function(e,t,s){const i=new be,r=new Re;return r.lineIndex=-1,r.lines=e.split("\n"),Ke(r,i),i.process(t,s)}(i,n,t),t.processor.postProcessor&&(i=t.processor.postProcessor(i,r,t.isFragment,t.processingContext,s?{drawBuffersExtensionDisabled:!s.getCaps().drawBuffersExtension}:{}));s?._features.needShaderCodeInlining&&(i=s.inlineShaderCode(i));return i}(e,t,i);s(r,e)}))}function Xe(e){const t=/defined\((.+)\)/.exec(e);if(t&&t.length)return new Se(t[1].trim(),"!"===e[0]);const s=["==","!=",">=","<=","<",">"];let i="",r=0;for(i of s)if(r=e.indexOf(i),r>-1)break;if(-1===r)return new Se(e);const n=e.substring(0,r).trim(),a=e.substring(r+i.length).trim();return new Pe(n,i,a)}function We(e,t){const s=new Me,i=e.substring(0,t);let r=e.substring(t);return r=r.substring(0,(r.indexOf("//")+1||r.length+1)-1).trim(),s.testExpression="#ifdef"===i?new Se(r):"#ifndef"===i?new Se(r,!0):function(e){e=e.replace(Ne,"defined[$1]");const t=Ie.infixToPostfix(e),s=[];for(const e of t)if("||"!==e&&"&&"!==e)s.push(e);else if(s.length>=2){let t=s[s.length-1],i=s[s.length-2];s.length-=2;const r="&&"==e?new Ce:new ve;"string"==typeof t&&(t=t.replace(we,"defined($1)")),"string"==typeof i&&(i=i.replace(we,"defined($1)")),r.leftOperand="string"==typeof i?Xe(i):i,r.rightOperand="string"==typeof t?Xe(t):t,s.push(r)}let i=s[s.length-1];return"string"==typeof i&&(i=i.replace(we,"defined($1)")),"string"==typeof i?Xe(i):i}(r),s}function Ye(e,t,s){let i=e.currentLine;for(;Ke(e,s);){i=e.currentLine;const r=i.substring(0,5).toLowerCase();if("#else"===r){const s=new be;return t.children.push(s),void Ke(e,s)}if("#elif"===r){const e=We(i,5);t.children.push(e),s=e}}}function Ke(e,t){for(;e.canRead;){e.lineIndex++;const s=e.currentLine;if(s.indexOf("#")>=0){const i=He.exec(s);if(i&&i.length){switch(i[0]){case"#ifdef":{const i=new xe;t.children.push(i);const r=We(s,6);i.children.push(r),Ye(e,i,r);break}case"#else":case"#elif":return!0;case"#endif":return!1;case"#ifndef":{const i=new xe;t.children.push(i);const r=We(s,7);i.children.push(r),Ye(e,i,r);break}case"#if":{const i=new xe,r=We(s,3);t.children.push(i),i.children.push(r),Ye(e,i,r);break}}continue}}const i=new be;if(i.line=s,t.children.push(i),"#"===s[0]&&"d"===s[1]){const e=s.replace(";","").split(" ");i.additionalDefineKey=e[1],3===e.length&&(i.additionalDefineValue=e[2])}}return!1}function qe(e,t,s){let i;for(Ve.length=0;null!==(i=Be.exec(e));)Ve.push(i);let r=String(e),n=[e],a=!1;for(const e of Ve){let i=e[1];if(-1!==i.indexOf("__decl__")&&(i=i.replace(Ue,""),t.supportsUniformBuffers&&(i=i.replace("Vertex","Ubo").replace("Fragment","Ubo")),i+="Declaration"),!t.includesShadersStore[i]){const e=t.shadersRepository+"ShadersInclude/"+i+".fx";return void Qe.loadFile(e,(e=>{t.includesShadersStore[i]=e,qe(n.join(""),t,s)}))}{let s=t.includesShadersStore[i];if(e[2]){const t=e[3].split(",");for(let e=0;e<t.length;e+=2){const i=new RegExp(t[e],"g"),r=t[e+1];s=s.replace(i,r)}}if(e[4]){const i=e[5];if(-1!==i.indexOf("..")){const e=i.split(".."),r=parseInt(e[0]);let n=parseInt(e[1]),a=s.slice(0);s="",isNaN(n)&&(n=t.indexParameters[e[1]]);for(let e=r;e<n;e++)t.supportsUniformBuffers||(a=a.replace(ke,((e,t)=>t+"{X}"))),s+=a.replace(Ge,e.toString())+"\n"}else t.supportsUniformBuffers||(s=s.replace(ke,((e,t)=>t+"{X}"))),s=s.replace(Ge,i)}const r=[];for(const t of n){const i=t.split(e[0]);for(let e=0;e<i.length-1;e++)r.push(i[e]),r.push(s);r.push(i[i.length-1])}n=r,a=a||s.indexOf("#include<")>=0||s.indexOf("#include <")>=0}}Ve.length=0,r=n.join(""),a?qe(r.toString(),t,s):s(r)}const Qe={loadFile:(e,t,s,i,r,n)=>{throw Y("FileTools")}};class je{static SetImmediate(e){oe()&&window.setImmediate?window.setImmediate(e):setTimeout(e,1)}}class Ze{}Ze.AUTOSAMPLERSUFFIX="Sampler",Ze.DISABLEUA="#define DISABLE_UNIFORMITY_ANALYSIS",Ze.ALPHA_DISABLE=0,Ze.ALPHA_ADD=1,Ze.ALPHA_COMBINE=2,Ze.ALPHA_SUBTRACT=3,Ze.ALPHA_MULTIPLY=4,Ze.ALPHA_MAXIMIZED=5,Ze.ALPHA_ONEONE=6,Ze.ALPHA_PREMULTIPLIED=7,Ze.ALPHA_PREMULTIPLIED_PORTERDUFF=8,Ze.ALPHA_INTERPOLATE=9,Ze.ALPHA_SCREENMODE=10,Ze.ALPHA_ONEONE_ONEONE=11,Ze.ALPHA_ALPHATOCOLOR=12,Ze.ALPHA_REVERSEONEMINUS=13,Ze.ALPHA_SRC_DSTONEMINUSSRCALPHA=14,Ze.ALPHA_ONEONE_ONEZERO=15,Ze.ALPHA_EXCLUSION=16,Ze.ALPHA_LAYER_ACCUMULATE=17,Ze.ALPHA_EQUATION_ADD=0,Ze.ALPHA_EQUATION_SUBSTRACT=1,Ze.ALPHA_EQUATION_REVERSE_SUBTRACT=2,Ze.ALPHA_EQUATION_MAX=3,Ze.ALPHA_EQUATION_MIN=4,Ze.ALPHA_EQUATION_DARKEN=5,Ze.DELAYLOADSTATE_NONE=0,Ze.DELAYLOADSTATE_LOADED=1,Ze.DELAYLOADSTATE_LOADING=2,Ze.DELAYLOADSTATE_NOTLOADED=4,Ze.NEVER=512,Ze.ALWAYS=519,Ze.LESS=513,Ze.EQUAL=514,Ze.LEQUAL=515,Ze.GREATER=516,Ze.GEQUAL=518,Ze.NOTEQUAL=517,Ze.KEEP=7680,Ze.ZERO=0,Ze.REPLACE=7681,Ze.INCR=7682,Ze.DECR=7683,Ze.INVERT=5386,Ze.INCR_WRAP=34055,Ze.DECR_WRAP=34056,Ze.TEXTURE_CLAMP_ADDRESSMODE=0,Ze.TEXTURE_WRAP_ADDRESSMODE=1,Ze.TEXTURE_MIRROR_ADDRESSMODE=2,Ze.TEXTURE_CREATIONFLAG_STORAGE=1,Ze.TEXTUREFORMAT_ALPHA=0,Ze.TEXTUREFORMAT_LUMINANCE=1,Ze.TEXTUREFORMAT_LUMINANCE_ALPHA=2,Ze.TEXTUREFORMAT_RGB=4,Ze.TEXTUREFORMAT_RGBA=5,Ze.TEXTUREFORMAT_RED=6,Ze.TEXTUREFORMAT_R=6,Ze.TEXTUREFORMAT_RG=7,Ze.TEXTUREFORMAT_RED_INTEGER=8,Ze.TEXTUREFORMAT_R_INTEGER=8,Ze.TEXTUREFORMAT_RG_INTEGER=9,Ze.TEXTUREFORMAT_RGB_INTEGER=10,Ze.TEXTUREFORMAT_RGBA_INTEGER=11,Ze.TEXTUREFORMAT_BGRA=12,Ze.TEXTUREFORMAT_DEPTH24_STENCIL8=13,Ze.TEXTUREFORMAT_DEPTH32_FLOAT=14,Ze.TEXTUREFORMAT_DEPTH16=15,Ze.TEXTUREFORMAT_DEPTH24=16,Ze.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8=17,Ze.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8=18,Ze.TEXTUREFORMAT_STENCIL8=19,Ze.TEXTUREFORMAT_UNDEFINED=4294967295,Ze.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM=36492,Ze.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_BPTC_UNORM=36493,Ze.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT=36495,Ze.TEXTUREFORMAT_COMPRESSED_RGB_BPTC_SIGNED_FLOAT=36494,Ze.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5=33779,Ze.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919,Ze.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3=33778,Ze.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918,Ze.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1=33777,Ze.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1=33776,Ze.TEXTUREFORMAT_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917,Ze.TEXTUREFORMAT_COMPRESSED_SRGB_S3TC_DXT1_EXT=35916,Ze.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4=37808,Ze.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=37840,Ze.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL=36196,Ze.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2=37492,Ze.TEXTUREFORMAT_COMPRESSED_SRGB8_ETC2=37493,Ze.TEXTUREFORMAT_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=37494,Ze.TEXTUREFORMAT_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=37495,Ze.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC=37496,Ze.TEXTUREFORMAT_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=37497,Ze.TEXTURETYPE_UNSIGNED_BYTE=0,Ze.TEXTURETYPE_UNSIGNED_INT=0,Ze.TEXTURETYPE_FLOAT=1,Ze.TEXTURETYPE_HALF_FLOAT=2,Ze.TEXTURETYPE_BYTE=3,Ze.TEXTURETYPE_SHORT=4,Ze.TEXTURETYPE_UNSIGNED_SHORT=5,Ze.TEXTURETYPE_INT=6,Ze.TEXTURETYPE_UNSIGNED_INTEGER=7,Ze.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=8,Ze.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=9,Ze.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=10,Ze.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=11,Ze.TEXTURETYPE_UNSIGNED_INT_24_8=12,Ze.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=13,Ze.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=14,Ze.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=15,Ze.TEXTURETYPE_UNDEFINED=16,Ze.TEXTURE_2D=3553,Ze.TEXTURE_2D_ARRAY=35866,Ze.TEXTURE_CUBE_MAP=34067,Ze.TEXTURE_CUBE_MAP_ARRAY=3735928559,Ze.TEXTURE_3D=32879,Ze.TEXTURE_NEAREST_SAMPLINGMODE=1,Ze.TEXTURE_NEAREST_NEAREST=1,Ze.TEXTURE_BILINEAR_SAMPLINGMODE=2,Ze.TEXTURE_LINEAR_LINEAR=2,Ze.TEXTURE_TRILINEAR_SAMPLINGMODE=3,Ze.TEXTURE_LINEAR_LINEAR_MIPLINEAR=3,Ze.TEXTURE_NEAREST_NEAREST_MIPNEAREST=4,Ze.TEXTURE_NEAREST_LINEAR_MIPNEAREST=5,Ze.TEXTURE_NEAREST_LINEAR_MIPLINEAR=6,Ze.TEXTURE_NEAREST_LINEAR=7,Ze.TEXTURE_NEAREST_NEAREST_MIPLINEAR=8,Ze.TEXTURE_LINEAR_NEAREST_MIPNEAREST=9,Ze.TEXTURE_LINEAR_NEAREST_MIPLINEAR=10,Ze.TEXTURE_LINEAR_LINEAR_MIPNEAREST=11,Ze.TEXTURE_LINEAR_NEAREST=12,Ze.TEXTURE_EXPLICIT_MODE=0,Ze.TEXTURE_SPHERICAL_MODE=1,Ze.TEXTURE_PLANAR_MODE=2,Ze.TEXTURE_CUBIC_MODE=3,Ze.TEXTURE_PROJECTION_MODE=4,Ze.TEXTURE_SKYBOX_MODE=5,Ze.TEXTURE_INVCUBIC_MODE=6,Ze.TEXTURE_EQUIRECTANGULAR_MODE=7,Ze.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=8,Ze.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=9,Ze.TEXTURE_FILTERING_QUALITY_OFFLINE=4096,Ze.TEXTURE_FILTERING_QUALITY_HIGH=64,Ze.TEXTURE_FILTERING_QUALITY_MEDIUM=16,Ze.TEXTURE_FILTERING_QUALITY_LOW=8,Ze.SCALEMODE_FLOOR=1,Ze.SCALEMODE_NEAREST=2,Ze.SCALEMODE_CEILING=3,Ze.MATERIAL_TextureDirtyFlag=1,Ze.MATERIAL_LightDirtyFlag=2,Ze.MATERIAL_FresnelDirtyFlag=4,Ze.MATERIAL_AttributesDirtyFlag=8,Ze.MATERIAL_MiscDirtyFlag=16,Ze.MATERIAL_PrePassDirtyFlag=32,Ze.MATERIAL_AllDirtyFlag=63,Ze.MATERIAL_TriangleFillMode=0,Ze.MATERIAL_WireFrameFillMode=1,Ze.MATERIAL_PointFillMode=2,Ze.MATERIAL_PointListDrawMode=3,Ze.MATERIAL_LineListDrawMode=4,Ze.MATERIAL_LineLoopDrawMode=5,Ze.MATERIAL_LineStripDrawMode=6,Ze.MATERIAL_TriangleStripDrawMode=7,Ze.MATERIAL_TriangleFanDrawMode=8,Ze.MATERIAL_ClockWiseSideOrientation=0,Ze.MATERIAL_CounterClockWiseSideOrientation=1,Ze.ACTION_NothingTrigger=0,Ze.ACTION_OnPickTrigger=1,Ze.ACTION_OnLeftPickTrigger=2,Ze.ACTION_OnRightPickTrigger=3,Ze.ACTION_OnCenterPickTrigger=4,Ze.ACTION_OnPickDownTrigger=5,Ze.ACTION_OnDoublePickTrigger=6,Ze.ACTION_OnPickUpTrigger=7,Ze.ACTION_OnPickOutTrigger=16,Ze.ACTION_OnLongPressTrigger=8,Ze.ACTION_OnPointerOverTrigger=9,Ze.ACTION_OnPointerOutTrigger=10,Ze.ACTION_OnEveryFrameTrigger=11,Ze.ACTION_OnIntersectionEnterTrigger=12,Ze.ACTION_OnIntersectionExitTrigger=13,Ze.ACTION_OnKeyDownTrigger=14,Ze.ACTION_OnKeyUpTrigger=15,Ze.PARTICLES_BILLBOARDMODE_Y=2,Ze.PARTICLES_BILLBOARDMODE_ALL=7,Ze.PARTICLES_BILLBOARDMODE_STRETCHED=8,Ze.PARTICLES_BILLBOARDMODE_STRETCHED_LOCAL=9,Ze.MESHES_CULLINGSTRATEGY_STANDARD=0,Ze.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=1,Ze.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=2,Ze.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=3,Ze.SCENELOADER_NO_LOGGING=0,Ze.SCENELOADER_MINIMAL_LOGGING=1,Ze.SCENELOADER_SUMMARY_LOGGING=2,Ze.SCENELOADER_DETAILED_LOGGING=3,Ze.PREPASS_IRRADIANCE_TEXTURE_TYPE=0,Ze.PREPASS_POSITION_TEXTURE_TYPE=1,Ze.PREPASS_VELOCITY_TEXTURE_TYPE=2,Ze.PREPASS_REFLECTIVITY_TEXTURE_TYPE=3,Ze.PREPASS_COLOR_TEXTURE_TYPE=4,Ze.PREPASS_DEPTH_TEXTURE_TYPE=5,Ze.PREPASS_NORMAL_TEXTURE_TYPE=6,Ze.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE=7,Ze.PREPASS_WORLD_NORMAL_TEXTURE_TYPE=8,Ze.PREPASS_LOCAL_POSITION_TEXTURE_TYPE=9,Ze.PREPASS_NDC_DEPTH_TEXTURE_TYPE=10,Ze.PREPASS_VELOCITY_LINEAR_TEXTURE_TYPE=11,Ze.BUFFER_CREATIONFLAG_READ=1,Ze.BUFFER_CREATIONFLAG_WRITE=2,Ze.BUFFER_CREATIONFLAG_READWRITE=3,Ze.BUFFER_CREATIONFLAG_UNIFORM=4,Ze.BUFFER_CREATIONFLAG_VERTEX=8,Ze.BUFFER_CREATIONFLAG_INDEX=16,Ze.BUFFER_CREATIONFLAG_STORAGE=32,Ze.BUFFER_CREATIONFLAG_INDIRECT=64,Ze.RENDERPASS_MAIN=0,Ze.INPUT_ALT_KEY=18,Ze.INPUT_CTRL_KEY=17,Ze.INPUT_META_KEY1=91,Ze.INPUT_META_KEY2=92,Ze.INPUT_META_KEY3=93,Ze.INPUT_SHIFT_KEY=16,Ze.SNAPSHOTRENDERING_STANDARD=0,Ze.SNAPSHOTRENDERING_FAST=1,Ze.PERSPECTIVE_CAMERA=0,Ze.ORTHOGRAPHIC_CAMERA=1,Ze.FOVMODE_VERTICAL_FIXED=0,Ze.FOVMODE_HORIZONTAL_FIXED=1,Ze.RIG_MODE_NONE=0,Ze.RIG_MODE_STEREOSCOPIC_ANAGLYPH=10,Ze.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=11,Ze.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=12,Ze.RIG_MODE_STEREOSCOPIC_OVERUNDER=13,Ze.RIG_MODE_STEREOSCOPIC_INTERLACED=14,Ze.RIG_MODE_VR=20,Ze.RIG_MODE_CUSTOM=22,Ze.MAX_SUPPORTED_UV_SETS=6,Ze.GL_ALPHA_EQUATION_ADD=32774,Ze.GL_ALPHA_EQUATION_MIN=32775,Ze.GL_ALPHA_EQUATION_MAX=32776,Ze.GL_ALPHA_EQUATION_SUBTRACT=32778,Ze.GL_ALPHA_EQUATION_REVERSE_SUBTRACT=32779,Ze.GL_ALPHA_FUNCTION_SRC=768,Ze.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_COLOR=769,Ze.GL_ALPHA_FUNCTION_SRC_ALPHA=770,Ze.GL_ALPHA_FUNCTION_ONE_MINUS_SRC_ALPHA=771,Ze.GL_ALPHA_FUNCTION_DST_ALPHA=772,Ze.GL_ALPHA_FUNCTION_ONE_MINUS_DST_ALPHA=773,Ze.GL_ALPHA_FUNCTION_DST_COLOR=774,Ze.GL_ALPHA_FUNCTION_ONE_MINUS_DST_COLOR=775,Ze.GL_ALPHA_FUNCTION_SRC_ALPHA_SATURATED=776,Ze.GL_ALPHA_FUNCTION_CONSTANT_COLOR=32769,Ze.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_COLOR=32770,Ze.GL_ALPHA_FUNCTION_CONSTANT_ALPHA=32771,Ze.GL_ALPHA_FUNCTION_ONE_MINUS_CONSTANT_ALPHA=32772,Ze.SnippetUrl="https://snippet.babylonjs.com",Ze.FOGMODE_NONE=0,Ze.FOGMODE_EXP=1,Ze.FOGMODE_EXP2=2,Ze.FOGMODE_LINEAR=3,Ze.BYTE=5120,Ze.UNSIGNED_BYTE=5121,Ze.SHORT=5122,Ze.UNSIGNED_SHORT=5123,Ze.INT=5124,Ze.UNSIGNED_INT=5125,Ze.FLOAT=5126,Ze.PositionKind="position",Ze.NormalKind="normal",Ze.TangentKind="tangent",Ze.UVKind="uv",Ze.UV2Kind="uv2",Ze.UV3Kind="uv3",Ze.UV4Kind="uv4",Ze.UV5Kind="uv5",Ze.UV6Kind="uv6",Ze.ColorKind="color",Ze.ColorInstanceKind="instanceColor",Ze.MatricesIndicesKind="matricesIndices",Ze.MatricesWeightsKind="matricesWeights",Ze.MatricesIndicesExtraKind="matricesIndicesExtra",Ze.MatricesWeightsExtraKind="matricesWeightsExtra";class $e{static GetShadersRepository(e=0){return 0===e?$e.ShadersRepository:$e.ShadersRepositoryWGSL}static GetShadersStore(e=0){return 0===e?$e.ShadersStore:$e.ShadersStoreWGSL}static GetIncludesShadersStore(e=0){return 0===e?$e.IncludesShadersStore:$e.IncludesShadersStoreWGSL}}$e.ShadersRepository="src/Shaders/",$e.ShadersStore={},$e.IncludesShadersStore={},$e.ShadersRepositoryWGSL="src/ShadersWGSL/",$e.ShadersStoreWGSL={},$e.IncludesShadersStoreWGSL={};class Je{constructor(){this._valueCache={},this.vertexCompilationError=null,this.fragmentCompilationError=null,this.programLinkError=null,this.programValidationError=null,this._isDisposed=!1}get isAsync(){return this.isParallelCompiled}get isReady(){return!!this.program&&(!this.isParallelCompiled||this.engine._isRenderingStateCompiled(this))}_handlesSpectorRebuildCallback(e){e&&this.program&&e(this.program)}setEngine(e){this.engine=e}_fillEffectInformation(e,t,s,i,r,n,a,o){const h=this.engine;if(h.supportsUniformBuffers)for(const s in t)e.bindUniformBlock(s,t[s]);let l;for(this.engine.getUniforms(this,s).forEach(((e,t)=>{i[s[t]]=e})),this._uniforms=i,l=0;l<r.length;l++){null==e.getUniform(r[l])&&(r.splice(l,1),l--)}r.forEach(((e,t)=>{n[e]=t}));for(const e of h.getAttributes(this,a))o.push(e)}dispose(){this._uniforms={},this._isDisposed=!0}_cacheMatrix(e,t){const s=this._valueCache[e],i=t.updateFlag;return(void 0===s||s!==i)&&(this._valueCache[e]=i,!0)}_cacheFloat2(e,t,s){let i=this._valueCache[e];if(!i||2!==i.length)return i=[t,s],this._valueCache[e]=i,!0;let r=!1;return i[0]!==t&&(i[0]=t,r=!0),i[1]!==s&&(i[1]=s,r=!0),r}_cacheFloat3(e,t,s,i){let r=this._valueCache[e];if(!r||3!==r.length)return r=[t,s,i],this._valueCache[e]=r,!0;let n=!1;return r[0]!==t&&(r[0]=t,n=!0),r[1]!==s&&(r[1]=s,n=!0),r[2]!==i&&(r[2]=i,n=!0),n}_cacheFloat4(e,t,s,i,r){let n=this._valueCache[e];if(!n||4!==n.length)return n=[t,s,i,r],this._valueCache[e]=n,!0;let a=!1;return n[0]!==t&&(n[0]=t,a=!0),n[1]!==s&&(n[1]=s,a=!0),n[2]!==i&&(n[2]=i,a=!0),n[3]!==r&&(n[3]=r,a=!0),a}setInt(e,t){const s=this._valueCache[e];void 0!==s&&s===t||this.engine.setInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setInt2(e,t,s){this._cacheFloat2(e,t,s)&&(this.engine.setInt2(this._uniforms[e],t,s)||(this._valueCache[e]=null))}setInt3(e,t,s,i){this._cacheFloat3(e,t,s,i)&&(this.engine.setInt3(this._uniforms[e],t,s,i)||(this._valueCache[e]=null))}setInt4(e,t,s,i,r){this._cacheFloat4(e,t,s,i,r)&&(this.engine.setInt4(this._uniforms[e],t,s,i,r)||(this._valueCache[e]=null))}setIntArray(e,t){this._valueCache[e]=null,this.engine.setIntArray(this._uniforms[e],t)}setIntArray2(e,t){this._valueCache[e]=null,this.engine.setIntArray2(this._uniforms[e],t)}setIntArray3(e,t){this._valueCache[e]=null,this.engine.setIntArray3(this._uniforms[e],t)}setIntArray4(e,t){this._valueCache[e]=null,this.engine.setIntArray4(this._uniforms[e],t)}setUInt(e,t){const s=this._valueCache[e];void 0!==s&&s===t||this.engine.setUInt(this._uniforms[e],t)&&(this._valueCache[e]=t)}setUInt2(e,t,s){this._cacheFloat2(e,t,s)&&(this.engine.setUInt2(this._uniforms[e],t,s)||(this._valueCache[e]=null))}setUInt3(e,t,s,i){this._cacheFloat3(e,t,s,i)&&(this.engine.setUInt3(this._uniforms[e],t,s,i)||(this._valueCache[e]=null))}setUInt4(e,t,s,i,r){this._cacheFloat4(e,t,s,i,r)&&(this.engine.setUInt4(this._uniforms[e],t,s,i,r)||(this._valueCache[e]=null))}setUIntArray(e,t){this._valueCache[e]=null,this.engine.setUIntArray(this._uniforms[e],t)}setUIntArray2(e,t){this._valueCache[e]=null,this.engine.setUIntArray2(this._uniforms[e],t)}setUIntArray3(e,t){this._valueCache[e]=null,this.engine.setUIntArray3(this._uniforms[e],t)}setUIntArray4(e,t){this._valueCache[e]=null,this.engine.setUIntArray4(this._uniforms[e],t)}setArray(e,t){this._valueCache[e]=null,this.engine.setArray(this._uniforms[e],t)}setArray2(e,t){this._valueCache[e]=null,this.engine.setArray2(this._uniforms[e],t)}setArray3(e,t){this._valueCache[e]=null,this.engine.setArray3(this._uniforms[e],t)}setArray4(e,t){this._valueCache[e]=null,this.engine.setArray4(this._uniforms[e],t)}setMatrices(e,t){t&&(this._valueCache[e]=null,this.engine.setMatrices(this._uniforms[e],t))}setMatrix(e,t){this._cacheMatrix(e,t)&&(this.engine.setMatrices(this._uniforms[e],t.asArray())||(this._valueCache[e]=null))}setMatrix3x3(e,t){this._valueCache[e]=null,this.engine.setMatrix3x3(this._uniforms[e],t)}setMatrix2x2(e,t){this._valueCache[e]=null,this.engine.setMatrix2x2(this._uniforms[e],t)}setFloat(e,t){const s=this._valueCache[e];void 0!==s&&s===t||this.engine.setFloat(this._uniforms[e],t)&&(this._valueCache[e]=t)}setVector2(e,t){this._cacheFloat2(e,t.x,t.y)&&(this.engine.setFloat2(this._uniforms[e],t.x,t.y)||(this._valueCache[e]=null))}setFloat2(e,t,s){this._cacheFloat2(e,t,s)&&(this.engine.setFloat2(this._uniforms[e],t,s)||(this._valueCache[e]=null))}setVector3(e,t){this._cacheFloat3(e,t.x,t.y,t.z)&&(this.engine.setFloat3(this._uniforms[e],t.x,t.y,t.z)||(this._valueCache[e]=null))}setFloat3(e,t,s,i){this._cacheFloat3(e,t,s,i)&&(this.engine.setFloat3(this._uniforms[e],t,s,i)||(this._valueCache[e]=null))}setVector4(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setQuaternion(e,t){this._cacheFloat4(e,t.x,t.y,t.z,t.w)&&(this.engine.setFloat4(this._uniforms[e],t.x,t.y,t.z,t.w)||(this._valueCache[e]=null))}setFloat4(e,t,s,i,r){this._cacheFloat4(e,t,s,i,r)&&(this.engine.setFloat4(this._uniforms[e],t,s,i,r)||(this._valueCache[e]=null))}setColor3(e,t){this._cacheFloat3(e,t.r,t.g,t.b)&&(this.engine.setFloat3(this._uniforms[e],t.r,t.g,t.b)||(this._valueCache[e]=null))}setColor4(e,t,s){this._cacheFloat4(e,t.r,t.g,t.b,s)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,s)||(this._valueCache[e]=null))}setDirectColor4(e,t){this._cacheFloat4(e,t.r,t.g,t.b,t.a)&&(this.engine.setFloat4(this._uniforms[e],t.r,t.g,t.b,t.a)||(this._valueCache[e]=null))}_getVertexShaderCode(){return this.vertexShader?this.engine._getShaderSource(this.vertexShader):null}_getFragmentShaderCode(){return this.fragmentShader?this.engine._getShaderSource(this.fragmentShader):null}}const et=new WeakMap,tt={_webGLVersion:2,cachedPipelines:{}};function st(e){let t=et.get(e);if(!t){if(!e)return tt;t={_webGLVersion:e.TEXTURE_BINDING_3D?2:1,_context:e,cachedPipelines:{}},et.set(e,t)}return t}function it(e,t,s,i,r,n){const a=st(i);n||(n=a._createShaderProgramInjection??nt);return n(e,ht(t,"vertex",i,a._contextWasLost),ht(s,"fragment",i,a._contextWasLost),i,r,a.validateShaderPrograms)}function rt(e,t,s,i,r,n=null,a){const o=st(r);a||(a=o._createShaderProgramInjection??nt);const h=o._webGLVersion>1?"#version 300 es\n#define WEBGL2 \n":"";return a(e,ot(t,"vertex",i,h,r,o._contextWasLost),ot(s,"fragment",i,h,r,o._contextWasLost),r,n,o.validateShaderPrograms)}function nt(e,t,s,i,r=null,n){const a=i.createProgram();if(e.program=a,!a)throw new Error("Unable to create program");return i.attachShader(a,t),i.attachShader(a,s),i.linkProgram(a),e.context=i,e.vertexShader=t,e.fragmentShader=s,e.isParallelCompiled||at(e,i,n),a}function at(e,t,s){const i=e.context,r=e.vertexShader,n=e.fragmentShader,a=e.program;if(!i.getProgramParameter(a,i.LINK_STATUS)){if(!t.getShaderParameter(r,t.COMPILE_STATUS)){const s=t.getShaderInfoLog(r);if(s)throw e.vertexCompilationError=s,new Error("VERTEX SHADER "+s)}if(!t.getShaderParameter(n,t.COMPILE_STATUS)){const s=t.getShaderInfoLog(n);if(s)throw e.fragmentCompilationError=s,new Error("FRAGMENT SHADER "+s)}const s=i.getProgramInfoLog(a);if(s)throw e.programLinkError=s,new Error(s)}if(s){i.validateProgram(a);if(!i.getProgramParameter(a,i.VALIDATE_STATUS)){const t=i.getProgramInfoLog(a);if(t)throw e.programValidationError=t,new Error(t)}}i.deleteShader(r),i.deleteShader(n),e.vertexShader=void 0,e.fragmentShader=void 0,e.onCompiled&&(e.onCompiled(),e.onCompiled=void 0)}function ot(e,t,s,i,r,n){return ht(De(e,s,i),t,r,n)}function ht(e,t,s,i){const r=s.createShader("vertex"===t?s.VERTEX_SHADER:s.FRAGMENT_SHADER);if(!r){let e=s.NO_ERROR,r=s.NO_ERROR;for(;(r=s.getError())!==s.NO_ERROR;)e=r;throw new Error(`Something went wrong while creating a gl ${t} shader object. gl error=${e}, gl isContextLost=${s.isContextLost()}, _contextWasLost=${i}`)}return s.shaderSource(r,e),s.compileShader(r),r}function lt(e){const t=e._name,s=e.context;if(t&&s){const e=st(s),i=e.cachedPipelines[t];i?.dispose(),delete e.cachedPipelines[t]}}function ct(e,t,s,i,r,n){if("undefined"!=typeof HTMLElement&&e instanceof HTMLElement){return void i(ce(e))}if("source:"===e.substr(0,7))return void i(e.substr(7));if("base64:"===e.substr(0,7)){return void i(window.atob(e.substr(7)))}const a=$e.GetShadersStore(r);if(a[e+t+"Shader"])return void i(a[e+t+"Shader"]);if(s&&a[e+s+"Shader"])return void i(a[e+s+"Shader"]);let o;if(o="."===e[0]||"/"===e[0]||e.indexOf("http")>-1?e:$e.GetShadersRepository(r)+e,!(n=n||Le))throw new Error("loadFileInjection is not defined");n(o+"."+t.toLowerCase()+".fx",i)}class ut{static get ShadersRepository(){return $e.ShadersRepository}static set ShadersRepository(e){$e.ShadersRepository=e}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new g),this._onBindObservable}get shaderLanguage(){return this._shaderLanguage}constructor(e,t,s,i=null,r,n=null,a=null,o=null,h=null,l,c="",u=0,d){this.defines="",this.onCompiled=null,this.onError=null,this.onBind=null,this.uniqueId=0,this.onCompileObservable=new g,this.onErrorObservable=new g,this._onBindObservable=null,this._isDisposed=!1,this._refCount=1,this._bonesComputationForcedToCPU=!1,this._uniformBuffersNames={},this._multiTarget=!1,this._samplers={},this._isReady=!1,this._compilationError="",this._allFallbacksProcessed=!1,this._uniforms={},this._key="",this._fallbacks=null,this._vertexSourceCodeOverride="",this._fragmentSourceCodeOverride="",this._transformFeedbackVaryings=null,this._pipelineContext=null,this._vertexSourceCode="",this._fragmentSourceCode="",this._vertexSourceCodeBeforeMigration="",this._fragmentSourceCodeBeforeMigration="",this._rawVertexSourceCode="",this._rawFragmentSourceCode="",this._processCodeAfterIncludes=void 0,this._processFinalCode=null,this.name=e,this._key=c;const _=this._key.replace(/\r/g,"").replace(/\n/g,"|");let f;if(t.attributes){const e=t;if(this._engine=s,this._attributesNames=e.attributes,this._uniformsNames=e.uniformsNames.concat(e.samplers),this._samplerList=e.samplers.slice(),this.defines=e.defines,this.onError=e.onError,this.onCompiled=e.onCompiled,this._fallbacks=e.fallbacks,this._indexParameters=e.indexParameters,this._transformFeedbackVaryings=e.transformFeedbackVaryings||null,this._multiTarget=!!e.multiTarget,this._shaderLanguage=e.shaderLanguage??0,e.uniformBuffersNames){this._uniformBuffersNamesList=e.uniformBuffersNames.slice();for(let t=0;t<e.uniformBuffersNames.length;t++)this._uniformBuffersNames[e.uniformBuffersNames[t]]=t}this._processFinalCode=e.processFinalCode??null,this._processCodeAfterIncludes=e.processCodeAfterIncludes??void 0,f=e.existingPipelineContext}else this._engine=r,this.defines=null==n?"":n,this._uniformsNames=s.concat(i),this._samplerList=i?i.slice():[],this._attributesNames=t,this._uniformBuffersNamesList=[],this._shaderLanguage=u,this.onError=h,this.onCompiled=o,this._indexParameters=l,this._fallbacks=a;"WEBGL2"===this._engine.shaderPlatformName&&(f=function(e,t){return st(t).cachedPipelines[e]}(_,this._engine._gl)??f),this._attributeLocationByName={},this.uniqueId=ut._UniqueIdSeed++,f?(this._pipelineContext=f,this._pipelineContext.setEngine(this._engine),this._onRenderingStateCompiled(this._pipelineContext),this._pipelineContext.program&&(this._pipelineContext.program.__SPECTOR_rebuildProgram=this._rebuildProgram.bind(this))):this._processShaderCodeAsync(null,!1,null,d)}async _processShaderCodeAsync(e=null,t=!1,s=null,i){i&&await i(),this._processingContext=s||this._engine._getShaderProcessingContext(this._shaderLanguage,!1);!function(e,t,s,i,r,n,a){let o,h;const l=oe()?n?.getHostDocument():null;o="string"==typeof t?t:t.vertexSource?"source:"+t.vertexSource:t.vertexElement?l?.getElementById(t.vertexElement)||t.vertexElement:t.vertex||t,h="string"==typeof t?t:t.fragmentSource?"source:"+t.fragmentSource:t.fragmentElement?l?.getElementById(t.fragmentElement)||t.fragmentElement:t.fragment||t;const c=[void 0,void 0],u=()=>{if(c[0]&&c[1]){e.isFragment=!0;const[o,h]=c;ze(h,e,((n,h)=>{a&&(a._fragmentSourceCodeBeforeMigration=h),s&&(n=s("fragment",n));const l=function(e,t,s){return s.processor&&s.processor.finalizeShaders?s.processor.finalizeShaders(e,t,s.processingContext):{vertexCode:e,fragmentCode:t}}(o,n,e);e=null;const c=function(e,t,s,i){return s?{vertexSourceCode:(1===i?"//":"")+"#define SHADER_NAME vertex:"+(s.vertexElement||s.vertex||s.spectorName||s)+"\n"+e,fragmentSourceCode:(1===i?"//":"")+"#define SHADER_NAME fragment:"+(s.fragmentElement||s.fragment||s.spectorName||s)+"\n"+t}:{vertexSourceCode:e,fragmentSourceCode:t}}(l.vertexCode,l.fragmentCode,t,r);i?.(c.vertexSourceCode,c.fragmentSourceCode)}),n)}};ct(o,"Vertex","",(t=>{var i;(i=e).processor&&i.processor.initializeShaders&&i.processor.initializeShaders(i.processingContext),ze(t,e,((e,i)=>{a&&(a._rawVertexSourceCode=t,a._vertexSourceCodeBeforeMigration=i),s&&(e=s("vertex",e)),c[0]=e,u()}),n)}),r),ct(h,"Fragment","Pixel",(e=>{a&&(a._rawFragmentSourceCode=e),c[1]=e,u()}),r)}({defines:this.defines.split("\n"),indexParameters:this._indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:e??this._engine._getShaderProcessor(this._shaderLanguage),supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:$e.GetShadersRepository(this._shaderLanguage),includesShadersStore:$e.GetIncludesShadersStore(this._shaderLanguage),version:(100*this._engine.version).toString(),platformName:this._engine.shaderPlatformName,processingContext:this._processingContext,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:this._processCodeAfterIncludes},this.name,this._processFinalCode,((e,s)=>{this._vertexSourceCode=e,this._fragmentSourceCode=s,this._prepareEffect(t)}),this._shaderLanguage,this._engine,this)}get key(){return this._key}isReady(){try{return this._isReadyInternal()}catch{return!1}}_isReadyInternal(){return!!this._isReady||!!this._pipelineContext&&this._pipelineContext.isReady}getEngine(){return this._engine}getPipelineContext(){return this._pipelineContext}getAttributesNames(){return this._attributesNames}getAttributeLocation(e){return this._attributes[e]}getAttributeLocationByName(e){return this._attributeLocationByName[e]}getAttributesCount(){return this._attributes.length}getUniformIndex(e){return this._uniformsNames.indexOf(e)}getUniform(e){return this._uniforms[e]}getSamplers(){return this._samplerList}getUniformNames(){return this._uniformsNames}getUniformBuffersNames(){return this._uniformBuffersNamesList}getIndexParameters(){return this._indexParameters}getCompilationError(){return this._compilationError}allFallbacksProcessed(){return this._allFallbacksProcessed}executeWhenCompiled(e){this.isReady()?e(this):(this.onCompileObservable.add((t=>{e(t)})),this._pipelineContext&&!this._pipelineContext.isAsync||setTimeout((()=>{this._checkIsReady(null)}),16))}_checkIsReady(e){try{if(this._isReadyInternal())return}catch(t){return void this._processCompilationErrors(t,e)}this._isDisposed||setTimeout((()=>{this._checkIsReady(e)}),16)}get vertexSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._vertexSourceCodeOverride:this._pipelineContext?._getVertexShaderCode()??this._vertexSourceCode}get fragmentSourceCode(){return this._vertexSourceCodeOverride&&this._fragmentSourceCodeOverride?this._fragmentSourceCodeOverride:this._pipelineContext?._getFragmentShaderCode()??this._fragmentSourceCode}get vertexSourceCodeBeforeMigration(){return this._vertexSourceCodeBeforeMigration}get fragmentSourceCodeBeforeMigration(){return this._fragmentSourceCodeBeforeMigration}get rawVertexSourceCode(){return this._rawVertexSourceCode}get rawFragmentSourceCode(){return this._rawFragmentSourceCode}getPipelineGenerationOptions(){return{platformName:this._engine.shaderPlatformName,shaderLanguage:this._shaderLanguage,shaderNameOrContent:this.name,key:this._key,defines:this.defines.split("\n"),addGlobalDefines:!1,extendedProcessingOptions:{indexParameters:this._indexParameters,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,supportsUniformBuffers:this._engine.supportsUniformBuffers},extendedCreatePipelineOptions:{transformFeedbackVaryings:this._transformFeedbackVaryings,createAsRaw:!(!this._vertexSourceCodeOverride||!this._fragmentSourceCodeOverride)}}}_rebuildProgram(e,t,s,i){this._isReady=!1,this._vertexSourceCodeOverride=e,this._fragmentSourceCodeOverride=t,this.onError=(e,t)=>{i&&i(t)},this.onCompiled=()=>{const e=this.getEngine().scenes;if(e)for(let t=0;t<e.length;t++)e[t].markAllMaterialsAsDirty(Ze.MATERIAL_AllDirtyFlag);this._pipelineContext._handlesSpectorRebuildCallback?.(s)},this._fallbacks=null,this._prepareEffect()}_onRenderingStateCompiled(e){if(this._pipelineContext=e,this._pipelineContext.setEngine(this._engine),this._attributes=[],this._pipelineContext._fillEffectInformation(this,this._uniformBuffersNames,this._uniformsNames,this._uniforms,this._samplerList,this._samplers,this._attributesNames,this._attributes),this._attributesNames)for(let e=0;e<this._attributesNames.length;e++){const t=this._attributesNames[e];this._attributeLocationByName[t]=this._attributes[e]}this._engine.bindSamplers(this),this._compilationError="",this._isReady=!0,this.onCompiled&&this.onCompiled(this),this.onCompileObservable.notifyObservers(this),this.onCompileObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh()}_prepareEffect(e=!1){const t=this._pipelineContext;this._isReady=!1;try{const s=!(!this._vertexSourceCodeOverride||!this._fragmentSourceCodeOverride),i=s?null:this.defines,r=s?this._vertexSourceCodeOverride:this._vertexSourceCode,n=s?this._fragmentSourceCodeOverride:this._fragmentSourceCode,a=this._engine;this._pipelineContext=((e,t,s,i)=>{try{const r=e.existingPipelineContext||t(e.shaderProcessingContext);return r._name=e.name,e.name&&e.context&&(st(e.context).cachedPipelines[e.name]=r),s(r,e.vertex,e.fragment,!!e.createAsRaw,"","",e.rebuildRebind,e.defines,e.transformFeedbackVaryings,"",(()=>{i(r,(()=>{e.onRenderingStateCompiled?.(r)}))})),r}catch(e){throw ue.Error("Error compiling effect"),e}})({existingPipelineContext:e?t:null,vertex:r,fragment:n,context:"WEBGL2"===a.shaderPlatformName?a._gl:void 0,rebuildRebind:(e,t,s,i)=>this._rebuildProgram(e,t,s,i),defines:i,transformFeedbackVaryings:this._transformFeedbackVaryings,name:this._key.replace(/\r/g,"").replace(/\n/g,"|"),createAsRaw:s,parallelShaderCompile:a._caps.parallelShaderCompile,shaderProcessingContext:this._processingContext,onRenderingStateCompiled:s=>{t&&!e&&this._engine._deletePipelineContext(t),s&&this._onRenderingStateCompiled(s)}},this._engine.createPipelineContext.bind(this._engine),this._engine._preparePipelineContext.bind(this._engine),this._engine._executeWhenRenderingStateIsCompiled.bind(this._engine)),this._pipelineContext.isAsync&&this._checkIsReady(t)}catch(e){this._processCompilationErrors(e,t)}}_getShaderCodeAndErrorLine(e,t,s){const i=s?/FRAGMENT SHADER ERROR: 0:(\d+?):/:/VERTEX SHADER ERROR: 0:(\d+?):/;let r=null;if(t&&e){const n=t.match(i);if(n&&2===n.length){const t=parseInt(n[1]),i=e.split("\n",-1);i.length>=t&&(r=`Offending line [${t}] in ${s?"fragment":"vertex"} code: ${i[t-1]}`)}}return[e,r]}_processCompilationErrors(e,t=null){this._compilationError=e.message;const s=this._attributesNames,i=this._fallbacks;if(ue.Error("Unable to compile effect:"),ue.Error("Uniforms: "+this._uniformsNames.map((function(e){return" "+e}))),ue.Error("Attributes: "+s.map((function(e){return" "+e}))),ue.Error("Defines:\n"+this.defines),ut.LogShaderCodeOnCompilationError){let e=null,t=null,s=null;this._pipelineContext?._getVertexShaderCode()&&([s,e]=this._getShaderCodeAndErrorLine(this._pipelineContext._getVertexShaderCode(),this._compilationError,!1),s&&(ue.Error("Vertex code:"),ue.Error(s))),this._pipelineContext?._getFragmentShaderCode()&&([s,t]=this._getShaderCodeAndErrorLine(this._pipelineContext?._getFragmentShaderCode(),this._compilationError,!0),s&&(ue.Error("Fragment code:"),ue.Error(s))),e&&ue.Error(e),t&&ue.Error(t)}ue.Error("Error: "+this._compilationError);const r=()=>{this.onError&&this.onError(this,this._compilationError),this.onErrorObservable.notifyObservers(this)};t&&(this._pipelineContext=t,this._isReady=!0,r()),i?(this._pipelineContext=null,i.hasMoreFallbacks?(this._allFallbacksProcessed=!1,ue.Error("Trying next fallback."),this.defines=i.reduce(this.defines,this),this._prepareEffect()):(this._allFallbacksProcessed=!0,r(),this.onErrorObservable.clear(),this._fallbacks&&this._fallbacks.unBindMesh())):(this._allFallbacksProcessed=!0,t||r())}get isSupported(){return""===this._compilationError}_bindTexture(e,t){this._engine._bindTexture(this._samplers[e],t,e)}setTexture(e,t){this._engine.setTexture(this._samplers[e],this._uniforms[e],t,e)}setTextureArray(e,t){const s=e+"Ex";if(-1===this._samplerList.indexOf(s+"0")){const i=this._samplerList.indexOf(e);for(let e=1;e<t.length;e++){const t=s+(e-1).toString();this._samplerList.splice(i+e,0,t)}let r=0;for(const e of this._samplerList)this._samplers[e]=r,r+=1}this._engine.setTextureArray(this._samplers[e],this._uniforms[e],t,e)}bindUniformBuffer(e,t){const s=this._uniformBuffersNames[t];void 0===s||ut._BaseCache[s]===e&&this._engine._features.useUBOBindingCache||(ut._BaseCache[s]=e,this._engine.bindUniformBufferBase(e,s,t))}bindUniformBlock(e,t){this._engine.bindUniformBlock(this._pipelineContext,e,t)}setInt(e,t){return this._pipelineContext.setInt(e,t),this}setInt2(e,t,s){return this._pipelineContext.setInt2(e,t,s),this}setInt3(e,t,s,i){return this._pipelineContext.setInt3(e,t,s,i),this}setInt4(e,t,s,i,r){return this._pipelineContext.setInt4(e,t,s,i,r),this}setIntArray(e,t){return this._pipelineContext.setIntArray(e,t),this}setIntArray2(e,t){return this._pipelineContext.setIntArray2(e,t),this}setIntArray3(e,t){return this._pipelineContext.setIntArray3(e,t),this}setIntArray4(e,t){return this._pipelineContext.setIntArray4(e,t),this}setUInt(e,t){return this._pipelineContext.setUInt(e,t),this}setUInt2(e,t,s){return this._pipelineContext.setUInt2(e,t,s),this}setUInt3(e,t,s,i){return this._pipelineContext.setUInt3(e,t,s,i),this}setUInt4(e,t,s,i,r){return this._pipelineContext.setUInt4(e,t,s,i,r),this}setUIntArray(e,t){return this._pipelineContext.setUIntArray(e,t),this}setUIntArray2(e,t){return this._pipelineContext.setUIntArray2(e,t),this}setUIntArray3(e,t){return this._pipelineContext.setUIntArray3(e,t),this}setUIntArray4(e,t){return this._pipelineContext.setUIntArray4(e,t),this}setFloatArray(e,t){return this._pipelineContext.setArray(e,t),this}setFloatArray2(e,t){return this._pipelineContext.setArray2(e,t),this}setFloatArray3(e,t){return this._pipelineContext.setArray3(e,t),this}setFloatArray4(e,t){return this._pipelineContext.setArray4(e,t),this}setArray(e,t){return this._pipelineContext.setArray(e,t),this}setArray2(e,t){return this._pipelineContext.setArray2(e,t),this}setArray3(e,t){return this._pipelineContext.setArray3(e,t),this}setArray4(e,t){return this._pipelineContext.setArray4(e,t),this}setMatrices(e,t){return this._pipelineContext.setMatrices(e,t),this}setMatrix(e,t){return this._pipelineContext.setMatrix(e,t),this}setMatrix3x3(e,t){return this._pipelineContext.setMatrix3x3(e,t),this}setMatrix2x2(e,t){return this._pipelineContext.setMatrix2x2(e,t),this}setFloat(e,t){return this._pipelineContext.setFloat(e,t),this}setBool(e,t){return this._pipelineContext.setInt(e,t?1:0),this}setVector2(e,t){return this._pipelineContext.setVector2(e,t),this}setFloat2(e,t,s){return this._pipelineContext.setFloat2(e,t,s),this}setVector3(e,t){return this._pipelineContext.setVector3(e,t),this}setFloat3(e,t,s,i){return this._pipelineContext.setFloat3(e,t,s,i),this}setVector4(e,t){return this._pipelineContext.setVector4(e,t),this}setQuaternion(e,t){return this._pipelineContext.setQuaternion(e,t),this}setFloat4(e,t,s,i,r){return this._pipelineContext.setFloat4(e,t,s,i,r),this}setColor3(e,t){return this._pipelineContext.setColor3(e,t),this}setColor4(e,t,s){return this._pipelineContext.setColor4(e,t,s),this}setDirectColor4(e,t){return this._pipelineContext.setDirectColor4(e,t),this}dispose(){this._refCount--,this._refCount>0||(this._pipelineContext&&lt(this._pipelineContext),this._engine._releaseEffect(this),this._isDisposed=!0)}static RegisterShader(e,t,s,i=0){t&&($e.GetShadersStore(i)[`${e}PixelShader`]=t),s&&($e.GetShadersStore(i)[`${e}VertexShader`]=s)}static ResetCache(){ut._BaseCache={}}}ut.LogShaderCodeOnCompilationError=!0,ut._UniqueIdSeed=0,ut._BaseCache={},ut.ShadersStore=$e.ShadersStore,ut.IncludesShadersStore=$e.IncludesShadersStore;class dt{constructor(e=!0){this._isDepthTestDirty=!1,this._isDepthMaskDirty=!1,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!1,this._isFrontFaceDirty=!1,e&&this.reset()}get isDirty(){return this._isDepthFuncDirty||this._isDepthTestDirty||this._isDepthMaskDirty||this._isCullFaceDirty||this._isCullDirty||this._isZOffsetDirty||this._isFrontFaceDirty}get zOffset(){return this._zOffset}set zOffset(e){this._zOffset!==e&&(this._zOffset=e,this._isZOffsetDirty=!0)}get zOffsetUnits(){return this._zOffsetUnits}set zOffsetUnits(e){this._zOffsetUnits!==e&&(this._zOffsetUnits=e,this._isZOffsetDirty=!0)}get cullFace(){return this._cullFace}set cullFace(e){this._cullFace!==e&&(this._cullFace=e,this._isCullFaceDirty=!0)}get cull(){return this._cull}set cull(e){this._cull!==e&&(this._cull=e,this._isCullDirty=!0)}get depthFunc(){return this._depthFunc}set depthFunc(e){this._depthFunc!==e&&(this._depthFunc=e,this._isDepthFuncDirty=!0)}get depthMask(){return this._depthMask}set depthMask(e){this._depthMask!==e&&(this._depthMask=e,this._isDepthMaskDirty=!0)}get depthTest(){return this._depthTest}set depthTest(e){this._depthTest!==e&&(this._depthTest=e,this._isDepthTestDirty=!0)}get frontFace(){return this._frontFace}set frontFace(e){this._frontFace!==e&&(this._frontFace=e,this._isFrontFaceDirty=!0)}reset(){this._depthMask=!0,this._depthTest=!0,this._depthFunc=null,this._cullFace=null,this._cull=null,this._zOffset=0,this._zOffsetUnits=0,this._frontFace=null,this._isDepthTestDirty=!0,this._isDepthMaskDirty=!0,this._isDepthFuncDirty=!1,this._isCullFaceDirty=!1,this._isCullDirty=!1,this._isZOffsetDirty=!0,this._isFrontFaceDirty=!1}apply(e){this.isDirty&&(this._isCullDirty&&(this.cull?e.enable(e.CULL_FACE):e.disable(e.CULL_FACE),this._isCullDirty=!1),this._isCullFaceDirty&&(e.cullFace(this.cullFace),this._isCullFaceDirty=!1),this._isDepthMaskDirty&&(e.depthMask(this.depthMask),this._isDepthMaskDirty=!1),this._isDepthTestDirty&&(this.depthTest?e.enable(e.DEPTH_TEST):e.disable(e.DEPTH_TEST),this._isDepthTestDirty=!1),this._isDepthFuncDirty&&(e.depthFunc(this.depthFunc),this._isDepthFuncDirty=!1),this._isZOffsetDirty&&(this.zOffset||this.zOffsetUnits?(e.enable(e.POLYGON_OFFSET_FILL),e.polygonOffset(this.zOffset,this.zOffsetUnits)):e.disable(e.POLYGON_OFFSET_FILL),this._isZOffsetDirty=!1),this._isFrontFaceDirty&&(e.frontFace(this.frontFace),this._isFrontFaceDirty=!1))}}class _t{get isDirty(){return this._isStencilTestDirty||this._isStencilMaskDirty||this._isStencilFuncDirty||this._isStencilOpDirty}get func(){return this._func}set func(e){this._func!==e&&(this._func=e,this._isStencilFuncDirty=!0)}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef!==e&&(this._funcRef=e,this._isStencilFuncDirty=!0)}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask!==e&&(this._funcMask=e,this._isStencilFuncDirty=!0)}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail!==e&&(this._opStencilFail=e,this._isStencilOpDirty=!0)}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail!==e&&(this._opDepthFail=e,this._isStencilOpDirty=!0)}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass!==e&&(this._opStencilDepthPass=e,this._isStencilOpDirty=!0)}get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this._isStencilMaskDirty=!0)}get enabled(){return this._enabled}set enabled(e){this._enabled!==e&&(this._enabled=e,this._isStencilTestDirty=!0)}constructor(e=!0){this._isStencilTestDirty=!1,this._isStencilMaskDirty=!1,this._isStencilFuncDirty=!1,this._isStencilOpDirty=!1,this.useStencilGlobalOnly=!1,e&&this.reset()}reset(){this.stencilMaterial=void 0,this.stencilGlobal?.reset(),this._isStencilTestDirty=!0,this._isStencilMaskDirty=!0,this._isStencilFuncDirty=!0,this._isStencilOpDirty=!0}apply(e){if(!e)return;const t=!this.useStencilGlobalOnly&&!!this.stencilMaterial?.enabled;this.enabled=t?this.stencilMaterial.enabled:this.stencilGlobal.enabled,this.func=t?this.stencilMaterial.func:this.stencilGlobal.func,this.funcRef=t?this.stencilMaterial.funcRef:this.stencilGlobal.funcRef,this.funcMask=t?this.stencilMaterial.funcMask:this.stencilGlobal.funcMask,this.opStencilFail=t?this.stencilMaterial.opStencilFail:this.stencilGlobal.opStencilFail,this.opDepthFail=t?this.stencilMaterial.opDepthFail:this.stencilGlobal.opDepthFail,this.opStencilDepthPass=t?this.stencilMaterial.opStencilDepthPass:this.stencilGlobal.opStencilDepthPass,this.mask=t?this.stencilMaterial.mask:this.stencilGlobal.mask,this.isDirty&&(this._isStencilTestDirty&&(this.enabled?e.enable(e.STENCIL_TEST):e.disable(e.STENCIL_TEST),this._isStencilTestDirty=!1),this._isStencilMaskDirty&&(e.stencilMask(this.mask),this._isStencilMaskDirty=!1),this._isStencilFuncDirty&&(e.stencilFunc(this.func,this.funcRef,this.funcMask),this._isStencilFuncDirty=!1),this._isStencilOpDirty&&(e.stencilOp(this.opStencilFail,this.opDepthFail,this.opStencilDepthPass),this._isStencilOpDirty=!1))}}class ft{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=ft.ALWAYS,this.funcRef=1,this.funcMask=255,this.opStencilFail=ft.KEEP,this.opDepthFail=ft.KEEP,this.opStencilDepthPass=ft.REPLACE}get stencilFunc(){return this.func}set stencilFunc(e){this.func=e}get stencilFuncRef(){return this.funcRef}set stencilFuncRef(e){this.funcRef=e}get stencilFuncMask(){return this.funcMask}set stencilFuncMask(e){this.funcMask=e}get stencilOpStencilFail(){return this.opStencilFail}set stencilOpStencilFail(e){this.opStencilFail=e}get stencilOpDepthFail(){return this.opDepthFail}set stencilOpDepthFail(e){this.opDepthFail=e}get stencilOpStencilDepthPass(){return this.opStencilDepthPass}set stencilOpStencilDepthPass(e){this.opStencilDepthPass=e}get stencilMask(){return this.mask}set stencilMask(e){this.mask=e}get stencilTest(){return this.enabled}set stencilTest(e){this.enabled=e}}ft.ALWAYS=Ze.ALWAYS,ft.KEEP=Ze.KEEP,ft.REPLACE=Ze.REPLACE;class pt{constructor(){this._blendFunctionParameters=new Array(4),this._blendEquationParameters=new Array(2),this._blendConstants=new Array(4),this._isBlendConstantsDirty=!1,this._alphaBlend=!1,this._isAlphaBlendDirty=!1,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this.reset()}get isDirty(){return this._isAlphaBlendDirty||this._isBlendFunctionParametersDirty||this._isBlendEquationParametersDirty}get alphaBlend(){return this._alphaBlend}set alphaBlend(e){this._alphaBlend!==e&&(this._alphaBlend=e,this._isAlphaBlendDirty=!0)}setAlphaBlendConstants(e,t,s,i){this._blendConstants[0]===e&&this._blendConstants[1]===t&&this._blendConstants[2]===s&&this._blendConstants[3]===i||(this._blendConstants[0]=e,this._blendConstants[1]=t,this._blendConstants[2]=s,this._blendConstants[3]=i,this._isBlendConstantsDirty=!0)}setAlphaBlendFunctionParameters(e,t,s,i){this._blendFunctionParameters[0]===e&&this._blendFunctionParameters[1]===t&&this._blendFunctionParameters[2]===s&&this._blendFunctionParameters[3]===i||(this._blendFunctionParameters[0]=e,this._blendFunctionParameters[1]=t,this._blendFunctionParameters[2]=s,this._blendFunctionParameters[3]=i,this._isBlendFunctionParametersDirty=!0)}setAlphaEquationParameters(e,t){this._blendEquationParameters[0]===e&&this._blendEquationParameters[1]===t||(this._blendEquationParameters[0]=e,this._blendEquationParameters[1]=t,this._isBlendEquationParametersDirty=!0)}reset(){this._alphaBlend=!1,this._blendFunctionParameters[0]=null,this._blendFunctionParameters[1]=null,this._blendFunctionParameters[2]=null,this._blendFunctionParameters[3]=null,this._blendEquationParameters[0]=null,this._blendEquationParameters[1]=null,this._blendConstants[0]=null,this._blendConstants[1]=null,this._blendConstants[2]=null,this._blendConstants[3]=null,this._isAlphaBlendDirty=!0,this._isBlendFunctionParametersDirty=!1,this._isBlendEquationParametersDirty=!1,this._isBlendConstantsDirty=!1}apply(e){this.isDirty&&(this._isAlphaBlendDirty&&(this._alphaBlend?e.enable(e.BLEND):e.disable(e.BLEND),this._isAlphaBlendDirty=!1),this._isBlendFunctionParametersDirty&&(e.blendFuncSeparate(this._blendFunctionParameters[0],this._blendFunctionParameters[1],this._blendFunctionParameters[2],this._blendFunctionParameters[3]),this._isBlendFunctionParametersDirty=!1),this._isBlendEquationParametersDirty&&(e.blendEquationSeparate(this._blendEquationParameters[0],this._blendEquationParameters[1]),this._isBlendEquationParametersDirty=!1),this._isBlendConstantsDirty&&(e.blendColor(this._blendConstants[0],this._blendConstants[1],this._blendConstants[2],this._blendConstants[3]),this._isBlendConstantsDirty=!1))}}class mt{get wrapU(){return this._cachedWrapU}set wrapU(e){this._cachedWrapU=e}get wrapV(){return this._cachedWrapV}set wrapV(e){this._cachedWrapV=e}get wrapR(){return this._cachedWrapR}set wrapR(e){this._cachedWrapR=e}get anisotropicFilteringLevel(){return this._cachedAnisotropicFilteringLevel}set anisotropicFilteringLevel(e){this._cachedAnisotropicFilteringLevel=e}get comparisonFunction(){return this._comparisonFunction}set comparisonFunction(e){this._comparisonFunction=e}get useMipMaps(){return this._useMipMaps}set useMipMaps(e){this._useMipMaps=e}constructor(){this.samplingMode=-1,this._useMipMaps=!0,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this._comparisonFunction=0}setParameters(e=Ze.TEXTURE_WRAP_ADDRESSMODE,t=Ze.TEXTURE_WRAP_ADDRESSMODE,s=Ze.TEXTURE_WRAP_ADDRESSMODE,i=1,r=Ze.TEXTURE_BILINEAR_SAMPLINGMODE,n=0){return this._cachedWrapU=e,this._cachedWrapV=t,this._cachedWrapR=s,this._cachedAnisotropicFilteringLevel=i,this.samplingMode=r,this._comparisonFunction=n,this}compareSampler(e){return this._cachedWrapU===e._cachedWrapU&&this._cachedWrapV===e._cachedWrapV&&this._cachedWrapR===e._cachedWrapR&&this._cachedAnisotropicFilteringLevel===e._cachedAnisotropicFilteringLevel&&this.samplingMode===e.samplingMode&&this._comparisonFunction===e._comparisonFunction&&this._useMipMaps===e._useMipMaps}}var gt;!function(e){e[e.Unknown=0]="Unknown",e[e.Url=1]="Url",e[e.Temp=2]="Temp",e[e.Raw=3]="Raw",e[e.Dynamic=4]="Dynamic",e[e.RenderTarget=5]="RenderTarget",e[e.MultiRenderTarget=6]="MultiRenderTarget",e[e.Cube=7]="Cube",e[e.CubeRaw=8]="CubeRaw",e[e.CubePrefiltered=9]="CubePrefiltered",e[e.Raw3D=10]="Raw3D",e[e.Raw2DArray=11]="Raw2DArray",e[e.DepthStencil=12]="DepthStencil",e[e.CubeRawRGBD=13]="CubeRawRGBD",e[e.Depth=14]="Depth"}(gt||(gt={}));class Tt extends mt{get useMipMaps(){return this.generateMipMaps}set useMipMaps(e){this.generateMipMaps=e}get uniqueId(){return this._uniqueId}_setUniqueId(e){this._uniqueId=e}getEngine(){return this._engine}get source(){return this._source}constructor(e,t,s=!1){super(),this.isReady=!1,this.isCube=!1,this.is3D=!1,this.is2DArray=!1,this.isMultiview=!1,this.url="",this.generateMipMaps=!1,this.samples=0,this.type=-1,this.format=-1,this.onLoadedObservable=new g,this.onErrorObservable=new g,this.onRebuildCallback=null,this.width=0,this.height=0,this.depth=0,this.baseWidth=0,this.baseHeight=0,this.baseDepth=0,this.invertY=!1,this._invertVScale=!1,this._associatedChannel=-1,this._source=0,this._buffer=null,this._bufferView=null,this._bufferViewArray=null,this._bufferViewArrayArray=null,this._size=0,this._extension="",this._files=null,this._workingCanvas=null,this._workingContext=null,this._cachedCoordinatesMode=null,this._isDisabled=!1,this._compression=null,this._sphericalPolynomial=null,this._sphericalPolynomialPromise=null,this._sphericalPolynomialComputed=!1,this._lodGenerationScale=0,this._lodGenerationOffset=0,this._useSRGBBuffer=!1,this._creationFlags=0,this._lodTextureHigh=null,this._lodTextureMid=null,this._lodTextureLow=null,this._isRGBD=!1,this._linearSpecularLOD=!1,this._irradianceTexture=null,this._hardwareTexture=null,this._maxLodLevel=null,this._references=1,this._gammaSpace=null,this._premulAlpha=!1,this._dynamicTextureSource=null,this._engine=e,this._source=t,this._uniqueId=Tt._Counter++,s||(this._hardwareTexture=e._createHardwareTexture())}incrementReferences(){this._references++}updateSize(e,t,s=1){this._engine.updateTextureDimensions(this,e,t,s),this.width=e,this.height=t,this.depth=s,this.baseWidth=e,this.baseHeight=t,this.baseDepth=s,this._size=e*t*s}_rebuild(){if(this.isReady=!1,this._cachedCoordinatesMode=null,this._cachedWrapU=null,this._cachedWrapV=null,this._cachedWrapR=null,this._cachedAnisotropicFilteringLevel=null,this.onRebuildCallback){const e=this.onRebuildCallback(this),t=t=>{t._swapAndDie(this,!1),this.isReady=e.isReady};return void(e.isAsync?e.proxy.then(t):t(e.proxy))}let e;switch(this.source){case 2:break;case 1:return void(e=this._engine.createTexture(this._originalUrl??this.url,!this.generateMipMaps,this.invertY,null,this.samplingMode,(e=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this._buffer,void 0,this.format,this._extension,void 0,void 0,void 0,this._useSRGBBuffer));case 3:e=this._engine.createRawTexture(this._bufferView,this.baseWidth,this.baseHeight,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type,this._creationFlags,this._useSRGBBuffer),e._swapAndDie(this,!1),this.isReady=!0;break;case 10:e=this._engine.createRawTexture3D(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case 11:e=this._engine.createRawTexture2DArray(this._bufferView,this.baseWidth,this.baseHeight,this.baseDepth,this.format,this.generateMipMaps,this.invertY,this.samplingMode,this._compression,this.type),e._swapAndDie(this,!1),this.isReady=!0;break;case 4:e=this._engine.createDynamicTexture(this.baseWidth,this.baseHeight,this.generateMipMaps,this.samplingMode),e._swapAndDie(this,!1),this._dynamicTextureSource&&this._engine.updateDynamicTexture(this,this._dynamicTextureSource,this.invertY,this._premulAlpha,this.format,!0);break;case 7:return void(e=this._engine.createCubeTexture(this.url,null,this._files,!this.generateMipMaps,(()=>{e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension,!1,0,0,null,void 0,this._useSRGBBuffer,ArrayBuffer.isView(this._buffer)?this._buffer:null));case 8:e=this._engine.createRawCubeTexture(this._bufferViewArray,this.width,this._originalFormat??this.format,this.type,this.generateMipMaps,this.invertY,this.samplingMode,this._compression),e._swapAndDie(this,!1),this.isReady=!0;break;case 13:return;case 9:return e=this._engine.createPrefilteredCubeTexture(this.url,null,this._lodGenerationScale,this._lodGenerationOffset,(e=>{e&&e._swapAndDie(this,!1),this.isReady=!0}),null,this.format,this._extension),void(e._sphericalPolynomial=this._sphericalPolynomial)}}_swapAndDie(e,t=!0){this._hardwareTexture?.setUsage(e._source,this.generateMipMaps,this.is2DArray,this.isCube,this.is3D,this.width,this.height,this.depth),e._hardwareTexture=this._hardwareTexture,t&&(e._isRGBD=this._isRGBD),this._lodTextureHigh&&(e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureHigh=this._lodTextureHigh),this._lodTextureMid&&(e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureMid=this._lodTextureMid),this._lodTextureLow&&(e._lodTextureLow&&e._lodTextureLow.dispose(),e._lodTextureLow=this._lodTextureLow),this._irradianceTexture&&(e._irradianceTexture&&e._irradianceTexture.dispose(),e._irradianceTexture=this._irradianceTexture);const s=this._engine.getLoadedTexturesCache();let i=s.indexOf(this);-1!==i&&s.splice(i,1),i=s.indexOf(e),-1===i&&s.push(e)}dispose(){this._references--,this.onLoadedObservable.clear(),this.onErrorObservable.clear(),0===this._references&&(this._engine._releaseTexture(this),this._hardwareTexture=null,this._dynamicTextureSource=null)}}function Et(e,t){return e.endsWith(".dds")?import("./ddsTextureLoader-D9xNsYAT.esm.min.js").then((e=>new e._DDSTextureLoader)):e.endsWith(".basis")?import("./basisTextureLoader-BnIeLUi5.esm.min.js").then((e=>new e._BasisTextureLoader)):e.endsWith(".env")?import("./envTextureLoader-Cmuugxf1.esm.min.js").then((e=>new e._ENVTextureLoader)):e.endsWith(".hdr")?import("./hdrTextureLoader-BM271mLj.esm.min.js").then((e=>new e._HDRTextureLoader)):e.endsWith(".ktx")||e.endsWith(".ktx2")||"image/ktx"===t||"image/ktx2"===t?import("./ktxTextureLoader-BRR5FQro.esm.min.js").then((e=>new e._KTXTextureLoader)):e.endsWith(".tga")?import("./tgaTextureLoader-CccJYauf.esm.min.js").then((e=>new e._TGATextureLoader)):e.endsWith(".exr")?import("./exrTextureLoader-DVZGHvAz.esm.min.js").then((e=>new e._ExrTextureLoader)):null}function At(e,t){if(oe()){const{requestAnimationFrame:s}=t||window;if("function"==typeof s)return s(e)}else if("function"==typeof requestAnimationFrame)return requestAnimationFrame(e);return setTimeout(e,16)}Tt._Counter=0;class yt{get frameId(){return this._frameId}get isWebGPU(){return this._isWebGPU}_getShaderProcessor(e){return this._shaderProcessor}get shaderPlatformName(){return this._shaderPlatformName}_clearEmptyResources(){this._emptyTexture=null,this._emptyCubeTexture=null,this._emptyTexture3D=null,this._emptyTexture2DArray=null}get useReverseDepthBuffer(){return this._useReverseDepthBuffer}set useReverseDepthBuffer(e){e!==this._useReverseDepthBuffer&&(this._useReverseDepthBuffer=e,this._depthCullingState.depthFunc=e?Ze.GEQUAL:Ze.LEQUAL)}setColorWrite(e){e!==this._colorWrite&&(this._colorWriteChanged=!0,this._colorWrite=e)}getColorWrite(){return this._colorWrite}get depthCullingState(){return this._depthCullingState}get alphaState(){return this._alphaState}get stencilState(){return this._stencilState}get stencilStateComposer(){return this._stencilStateComposer}_getGlobalDefines(e){if(e)return this.isNDCHalfZRange?e.IS_NDC_HALF_ZRANGE="":delete e.IS_NDC_HALF_ZRANGE,this.useReverseDepthBuffer?e.USE_REVERSE_DEPTHBUFFER="":delete e.USE_REVERSE_DEPTHBUFFER,void(this.useExactSrgbConversions?e.USE_EXACT_SRGB_CONVERSIONS="":delete e.USE_EXACT_SRGB_CONVERSIONS);{let e="";return this.isNDCHalfZRange&&(e+="#define IS_NDC_HALF_ZRANGE"),this.useReverseDepthBuffer&&(e&&(e+="\n"),e+="#define USE_REVERSE_DEPTHBUFFER"),this.useExactSrgbConversions&&(e&&(e+="\n"),e+="#define USE_EXACT_SRGB_CONVERSIONS"),e}}_rebuildInternalTextures(){const e=this._internalTexturesCache.slice();for(const t of e)t._rebuild()}_rebuildRenderTargetWrappers(){const e=this._renderTargetWrapperCache.slice();for(const t of e)t._rebuild()}_rebuildEffects(){for(const e in this._compiledEffects){const t=this._compiledEffects[e];t._pipelineContext=null,t._prepareEffect()}ut.ResetCache()}_rebuildGraphicsResources(){this.wipeCaches(!0),this._rebuildEffects(),this._rebuildComputeEffects?.(),this._rebuildBuffers(),this._rebuildInternalTextures(),this._rebuildTextures(),this._rebuildRenderTargetWrappers(),this.wipeCaches(!0)}_flagContextRestored(){ue.Warn(this.name+" context successfully restored."),this.onContextRestoredObservable.notifyObservers(this),this._contextWasLost=!1}_restoreEngineAfterContextLost(e){setTimeout((async()=>{this._clearEmptyResources();const t=this._depthCullingState.depthTest,s=this._depthCullingState.depthFunc,i=this._depthCullingState.depthMask,r=this._stencilState.stencilTest;await e(),this._rebuildGraphicsResources(),this._depthCullingState.depthTest=t,this._depthCullingState.depthFunc=s,this._depthCullingState.depthMask=i,this._stencilState.stencilTest=r,this._flagContextRestored()}),0)}get isDisposed(){return this._isDisposed}get snapshotRendering(){return!1}set snapshotRendering(e){}get snapshotRenderingMode(){return Ze.SNAPSHOTRENDERING_STANDARD}set snapshotRenderingMode(e){}getClassName(){return"AbstractEngine"}get emptyTexture(){return this._emptyTexture||(this._emptyTexture=this.createRawTexture(new Uint8Array(4),1,1,Ze.TEXTUREFORMAT_RGBA,!1,!1,Ze.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture}get emptyTexture3D(){return this._emptyTexture3D||(this._emptyTexture3D=this.createRawTexture3D(new Uint8Array(4),1,1,1,Ze.TEXTUREFORMAT_RGBA,!1,!1,Ze.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture3D}get emptyTexture2DArray(){return this._emptyTexture2DArray||(this._emptyTexture2DArray=this.createRawTexture2DArray(new Uint8Array(4),1,1,1,Ze.TEXTUREFORMAT_RGBA,!1,!1,Ze.TEXTURE_NEAREST_SAMPLINGMODE)),this._emptyTexture2DArray}get emptyCubeTexture(){if(!this._emptyCubeTexture){const e=new Uint8Array(4),t=[e,e,e,e,e,e];this._emptyCubeTexture=this.createRawCubeTexture(t,1,Ze.TEXTUREFORMAT_RGBA,Ze.TEXTURETYPE_UNSIGNED_INT,!1,!1,Ze.TEXTURE_NEAREST_SAMPLINGMODE)}return this._emptyCubeTexture}get activeRenderLoops(){return this._activeRenderLoops}stopRenderLoop(e){if(!e)return this._activeRenderLoops.length=0,void this._cancelFrame();const t=this._activeRenderLoops.indexOf(e);t>=0&&(this._activeRenderLoops.splice(t,1),0==this._activeRenderLoops.length&&this._cancelFrame())}_cancelFrame(){if(0!==this._frameHandler){const e=this._frameHandler;if(this._frameHandler=0,oe()){const{cancelAnimationFrame:t}=this.getHostWindow()||window;if("function"==typeof t)return t(e)}else if("function"==typeof cancelAnimationFrame)return cancelAnimationFrame(e);return clearTimeout(e)}}beginFrame(){this.onBeginFrameObservable.notifyObservers(this)}endFrame(){this._frameId++,this.onEndFrameObservable.notifyObservers(this)}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this._isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&0===this._frameHandler&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}_renderFrame(){for(let e=0;e<this._activeRenderLoops.length;e++){(0,this._activeRenderLoops[e])()}}_renderViews(){return!1}_queueNewFrame(e,t){return At(e,t)}runRenderLoop(e){-1===this._activeRenderLoops.indexOf(e)&&(this._activeRenderLoops.push(e),1===this._activeRenderLoops.length&&0===this._frameHandler&&(this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow())))}getDepthBuffer(){return this._depthCullingState.depthTest}setDepthBuffer(e){this._depthCullingState.depthTest=e}setZOffset(e){this._depthCullingState.zOffset=this.useReverseDepthBuffer?-e:e}getZOffset(){const e=this._depthCullingState.zOffset;return this.useReverseDepthBuffer?-e:e}setZOffsetUnits(e){this._depthCullingState.zOffsetUnits=this.useReverseDepthBuffer?-e:e}getZOffsetUnits(){const e=this._depthCullingState.zOffsetUnits;return this.useReverseDepthBuffer?-e:e}getHostWindow(){return oe()?this._renderingCanvas&&this._renderingCanvas.ownerDocument&&this._renderingCanvas.ownerDocument.defaultView?this._renderingCanvas.ownerDocument.defaultView:window:null}get compatibilityMode(){return this._compatibilityMode}set compatibilityMode(e){this._compatibilityMode=!0}_rebuildTextures(){for(const e of this.scenes)e._rebuildTextures();for(const e of this._virtualScenes)e._rebuildTextures()}_releaseRenderTargetWrapper(e){const t=this._renderTargetWrapperCache.indexOf(e);-1!==t&&this._renderTargetWrapperCache.splice(t,1)}get currentViewport(){return this._cachedViewport}setViewport(e,t,s){const i=t||this.getRenderWidth(),r=s||this.getRenderHeight(),n=e.x||0,a=e.y||0;this._cachedViewport=e,this._viewport(n*i,a*r,i*e.width,r*e.height)}createCanvasImage(){return document.createElement("img")}get description(){let e=this.name+this.version;return this._caps.parallelShaderCompile&&(e+=" - Parallel shader compilation"),e}_createTextureBase(e,t,s,i,r=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,n=null,a=null,o,h,l=null,c=null,u=null,d=null,_,f,p){const m="data:"===(e=e||"").substr(0,5),g="blob:"===e.substr(0,5),T=m&&-1!==e.indexOf(";base64,"),E=c||new Tt(this,1);E!==c&&(E.label=e.substring(0,60));const A=e;!this._transformTextureUrl||T||c||l||(e=this._transformTextureUrl(e)),A!==e&&(E._originalUrl=A);const y=e.lastIndexOf(".");let b=d||(y>-1?e.substring(y).toLowerCase():"");b.indexOf("?")>-1&&(b=b.split("?")[0]);const R=Et(b,_);i&&i.addPendingData(E),E.url=e,E.generateMipMaps=!t,E.samplingMode=r,E.invertY=s,E._useSRGBBuffer=this._getUseSRGBBuffer(!!p,t),this._doNotHandleContextLost||(E._buffer=l);let x=null;n&&!c&&(x=E.onLoadedObservable.add(n)),c||this._internalTexturesCache.push(E);const M=(s,c)=>{i&&i.removePendingData(E),e===A?(x&&E.onLoadedObservable.remove(x),C.UseFallbackTexture&&e!==C.FallbackTexture&&this._createTextureBase(C.FallbackTexture,t,E.invertY,i,r,null,a,o,h,l,E),s=(s||"Unknown error")+(C.UseFallbackTexture?" - Fallback texture was used":""),E.onErrorObservable.notifyObservers({message:s,exception:c}),a&&a(s,c)):(ue.Warn(`Failed to load ${e}, falling back to ${A}`),this._createTextureBase(A,t,E.invertY,i,r,n,a,o,h,l,E,u,d,_,f,p))};if(R){const t=async e=>{(await R).loadData(e,E,((e,t,s,n,a,h)=>{h?M("TextureLoader failed to load data"):o(E,b,i,{width:e,height:t},E.invertY,!s,n,(()=>(a(),!1)),r)}),f)};l?l instanceof ArrayBuffer?t(new Uint8Array(l)):ArrayBuffer.isView(l)?t(l):a&&a("Unable to load: only ArrayBuffer or ArrayBufferView is supported",null):this._loadFile(e,(e=>t(new Uint8Array(e))),void 0,i?i.offlineProvider:void 0,!0,((e,t)=>{M("Unable to load "+(e&&e.responseURL,t))}))}else{const s=e=>{g&&!this._doNotHandleContextLost&&(E._buffer=e),o(E,b,i,e,E.invertY,t,!1,h,r)};!m||T?l&&("string"==typeof l.decoding||l.close)?s(l):yt._FileToolsLoadImage(e||"",s,M,i?i.offlineProvider:null,_,E.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):"string"==typeof l||l instanceof ArrayBuffer||ArrayBuffer.isView(l)||l instanceof Blob?yt._FileToolsLoadImage(l,s,M,i?i.offlineProvider:null,_,E.invertY&&this._features.needsInvertingBitmap?{imageOrientation:"flipY"}:void 0):l&&s(l)}return E}_rebuildBuffers(){for(const e of this._uniformBuffers)e._rebuildAfterContextLost()}get _shouldUseHighPrecisionShader(){return!(!this._caps.highPrecisionShaderSupported||!this._highPrecisionShadersAllowed)}getHostDocument(){return this._renderingCanvas&&this._renderingCanvas.ownerDocument?this._renderingCanvas.ownerDocument:le()?document:null}getLoadedTexturesCache(){return this._internalTexturesCache}clearInternalTexturesCache(){this._internalTexturesCache.length=0}getCaps(){return this._caps}resetTextureCache(){for(const e in this._boundTexturesCache)Object.prototype.hasOwnProperty.call(this._boundTexturesCache,e)&&(this._boundTexturesCache[e]=null);this._currentTextureChannel=-1}get name(){return this._name}set name(e){this._name=e}static get NpmPackage(){return"babylonjs@7.23.0"}static get Version(){return"7.23.0"}getRenderingCanvas(){return this._renderingCanvas}getAudioContext(){return this._audioContext}getAudioDestination(){return this._audioDestination}setHardwareScalingLevel(e){this._hardwareScalingLevel=e,this.resize()}getHardwareScalingLevel(){return this._hardwareScalingLevel}get doNotHandleContextLost(){return this._doNotHandleContextLost}set doNotHandleContextLost(e){this._doNotHandleContextLost=e}get isStencilEnable(){return this._isStencilEnable}getCreationOptions(){return this._creationOptions}constructor(e,t,s){this._colorWrite=!0,this._colorWriteChanged=!0,this._depthCullingState=new dt,this._stencilStateComposer=new _t,this._stencilState=new ft,this._alphaState=new pt,this._alphaMode=Ze.ALPHA_ADD,this._alphaEquation=Ze.ALPHA_DISABLE,this._activeRequests=[],this._badOS=!1,this._badDesktopOS=!1,this._compatibilityMode=!0,this._internalTexturesCache=new Array,this._currentRenderTarget=null,this._boundTexturesCache={},this._activeChannel=0,this._currentTextureChannel=-1,this._viewportCached={x:0,y:0,z:0,w:0},this._isWebGPU=!1,this.onCanvasBlurObservable=new g,this.onCanvasFocusObservable=new g,this.onNewSceneAddedObservable=new g,this.onResizeObservable=new g,this.onCanvasPointerOutObservable=new g,this.disablePerformanceMonitorInBackground=!1,this.disableVertexArrayObjects=!1,this._frameId=0,this.hostInformation={isMobile:!1},this.isFullscreen=!1,this.enableOfflineSupport=!1,this.disableManifestCheck=!1,this.disableContextMenu=!0,this.currentRenderPassId=Ze.RENDERPASS_MAIN,this.isPointerLock=!1,this.postProcesses=[],this.canvasTabIndex=1,this._contextWasLost=!1,this._useReverseDepthBuffer=!1,this.isNDCHalfZRange=!1,this.hasOriginBottomLeft=!0,this._renderTargetWrapperCache=new Array,this._compiledEffects={},this._isDisposed=!1,this.scenes=[],this._virtualScenes=new Array,this.onBeforeTextureInitObservable=new g,this.renderEvenInBackground=!0,this.preventCacheWipeBetweenFrames=!1,this._frameHandler=0,this._activeRenderLoops=new Array,this._windowIsBackground=!1,this._boundRenderFunction=()=>this._renderLoop(),this.onBeforeShaderCompilationObservable=new g,this.onAfterShaderCompilationObservable=new g,this.onBeginFrameObservable=new g,this.onEndFrameObservable=new g,this._transformTextureUrl=null,this._uniformBuffers=new Array,this._storageBuffers=new Array,this._highPrecisionShadersAllowed=!0,this.onContextLostObservable=new g,this.onContextRestoredObservable=new g,this._name="",this.premultipliedAlpha=!0,this.adaptToDeviceRatio=!1,this._lastDevicePixelRatio=1,this._doNotHandleContextLost=!1,this.cullBackFaces=null,this._renderPassNames=["main"],this._fps=60,this._deltaTime=0,this._deterministicLockstep=!1,this._lockstepMaxSteps=4,this._timeStep=1/60,this.onDisposeObservable=new g,C.Instances.push(this),this.startTime=fe.Now,this._stencilStateComposer.stencilGlobal=this._stencilState,v.SetMatrixPrecision(!!t.useHighPrecisionMatrix),he()&&navigator.userAgent&&(this._badOS=/iPad/i.test(navigator.userAgent)||/iPhone/i.test(navigator.userAgent),this._badDesktopOS=/^((?!chrome|android).)*safari/i.test(navigator.userAgent)),this.adaptToDeviceRatio=s??!1,t.antialias=e??t.antialias,t.deterministicLockstep=t.deterministicLockstep??!1,t.lockstepMaxSteps=t.lockstepMaxSteps??4,t.timeStep=t.timeStep??1/60,t.audioEngine=t.audioEngine??!0,t.stencil=t.stencil??!0,this._audioContext=t.audioEngineOptions?.audioContext??null,this._audioDestination=t.audioEngineOptions?.audioDestination??null,this.premultipliedAlpha=t.premultipliedAlpha??!0,this._doNotHandleContextLost=!!t.doNotHandleContextLost,this._isStencilEnable=!!t.stencil,this.useExactSrgbConversions=t.useExactSrgbConversions??!1;const i=oe()&&window.devicePixelRatio||1,r=t.limitDeviceRatio||i;s=s||t.adaptToDeviceRatio||!1,this._hardwareScalingLevel=s?1/Math.min(r,i):1,this._lastDevicePixelRatio=i,this._creationOptions=t}resize(e=!1){let t,s;if(this.adaptToDeviceRatio){const e=oe()&&window.devicePixelRatio||1,t=this._lastDevicePixelRatio/e;this._lastDevicePixelRatio=e,this._hardwareScalingLevel*=t}if(oe()&&le())if(this._renderingCanvas){const e=this._renderingCanvas.getBoundingClientRect?this._renderingCanvas.getBoundingClientRect():{width:this._renderingCanvas.width*this._hardwareScalingLevel,height:this._renderingCanvas.height*this._hardwareScalingLevel};t=this._renderingCanvas.clientWidth||e.width||this._renderingCanvas.width||100,s=this._renderingCanvas.clientHeight||e.height||this._renderingCanvas.height||100}else t=window.innerWidth,s=window.innerHeight;else t=this._renderingCanvas?this._renderingCanvas.width:100,s=this._renderingCanvas?this._renderingCanvas.height:100;this.setSize(t/this._hardwareScalingLevel,s/this._hardwareScalingLevel,e)}setSize(e,t,s=!1){if(!this._renderingCanvas)return!1;if(e|=0,t|=0,!s&&this._renderingCanvas.width===e&&this._renderingCanvas.height===t)return!1;if(this._renderingCanvas.width=e,this._renderingCanvas.height=t,this.scenes){for(let e=0;e<this.scenes.length;e++){const t=this.scenes[e];for(let e=0;e<t.cameras.length;e++){t.cameras[e]._currentRenderId=0}}this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this)}return!0}createRawTexture(e,t,s,i,r,n,a,o,h,l,c){throw Y("engine.rawTexture")}createRawCubeTexture(e,t,s,i,r,n,a,o){throw Y("engine.rawTexture")}createRawTexture3D(e,t,s,i,r,n,a,o,h,l,c){throw Y("engine.rawTexture")}createRawTexture2DArray(e,t,s,i,r,n,a,o,h,l,c){throw Y("engine.rawTexture")}_sharedInit(e){this._renderingCanvas=e}_setupMobileChecks(){navigator&&navigator.userAgent&&(this._checkForMobile=()=>{const e=navigator.userAgent;this.hostInformation.isMobile=-1!==e.indexOf("Mobile")||-1!==e.indexOf("Mac")&&le()&&"ontouchend"in document},this._checkForMobile(),oe()&&window.addEventListener("resize",this._checkForMobile))}createVideoElement(e){return document.createElement("video")}_reportDrawCall(e=1){this._drawCalls?.addCount(e,!1)}getFps(){return this._fps}getDeltaTime(){return this._deltaTime}isDeterministicLockStep(){return this._deterministicLockstep}getLockstepMaxSteps(){return this._lockstepMaxSteps}getTimeStep(){return 1e3*this._timeStep}_createImageBitmapFromSource(e,t){throw new Error("createImageBitmapFromSource is not implemented")}createImageBitmap(e,t){return createImageBitmap(e,t)}resizeImageBitmap(e,t,s){throw new Error("resizeImageBitmap is not implemented")}getFontOffset(e){throw new Error("getFontOffset is not implemented")}static _CreateCanvas(e,t){if("undefined"==typeof document)return new OffscreenCanvas(e,t);const s=document.createElement("canvas");return s.width=e,s.height=t,s}createCanvas(e,t){return yt._CreateCanvas(e,t)}static _FileToolsLoadImage(e,t,s,i,r,n){throw Y("FileTools")}_loadFile(e,t,s,i,r,n){const a=Le(e,t,s,i,r,n);return this._activeRequests.push(a),a.onCompleteObservable.add((()=>{const e=this._activeRequests.indexOf(a);-1!==e&&this._activeRequests.splice(e,1)})),a}static _FileToolsLoadFile(e,t,s,i,r,n){if(Oe.loadFile)return Oe.loadFile(e,t,s,i,r,n);throw Y("FileTools")}dispose(){for(this.releaseEffects(),this._isDisposed=!0,this.stopRenderLoop(),this._emptyTexture&&(this._releaseTexture(this._emptyTexture),this._emptyTexture=null),this._emptyCubeTexture&&(this._releaseTexture(this._emptyCubeTexture),this._emptyCubeTexture=null),this._renderingCanvas=null,this.onBeforeTextureInitObservable&&this.onBeforeTextureInitObservable.clear();this.postProcesses.length;)this.postProcesses[0].dispose();for(;this.scenes.length;)this.scenes[0].dispose();for(;this._virtualScenes.length;)this._virtualScenes[0].dispose();this.releaseComputeEffects?.(),ut.ResetCache();for(const e of this._activeRequests)e.abort();this._boundRenderFunction=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.onResizeObservable.clear(),this.onCanvasBlurObservable.clear(),this.onCanvasFocusObservable.clear(),this.onCanvasPointerOutObservable.clear(),this.onNewSceneAddedObservable.clear(),oe()&&window.removeEventListener("resize",this._checkForMobile);const e=C.Instances.indexOf(this);e>=0&&C.Instances.splice(e,1),C.Instances.length||(C.OnEnginesDisposedObservable.notifyObservers(this),C.OnEnginesDisposedObservable.clear()),this.onBeginFrameObservable.clear(),this.onEndFrameObservable.clear()}static DefaultLoadingScreenFactory(e){throw Y("LoadingScreen")}static MarkAllMaterialsAsDirty(e,t){for(let s=0;s<C.Instances.length;s++){const i=C.Instances[s];for(let s=0;s<i.scenes.length;s++)i.scenes[s].markAllMaterialsAsDirty(e,t)}}}yt._RenderPassIdCounter=0,yt._RescalePostProcessFactory=null,yt.CollisionsEpsilon=.001,yt.QueueNewFrame=At;const bt=new RegExp(/^data:([^,]+\/[^,]+)?;base64,/i);class Rt extends Ee{constructor(e,t){super(e,Te.LoadFileError),this.name="LoadFileError",ge._setPrototypeOf(this,Rt.prototype),t instanceof pe?this.request=t:this.file=t}}class xt extends Ee{constructor(e,t){super(e,Te.RequestFileError),this.request=t,this.name="RequestFileError",ge._setPrototypeOf(this,xt.prototype)}}class Mt extends Ee{constructor(e,t){super(e,Te.ReadFileError),this.file=t,this.name="ReadFileError",ge._setPrototypeOf(this,Mt.prototype)}}const It={DefaultRetryStrategy:class{static ExponentialBackoff(e=3,t=500){return(s,i,r)=>0!==i.status||r>=e||-1!==s.indexOf("file:")?-1:Math.pow(2,r)*t}}.ExponentialBackoff(),BaseUrl:"",CorsBehavior:"anonymous",PreprocessUrl:e=>e,ScriptBaseUrl:"",ScriptPreprocessUrl:e=>e,CleanUrl:e=>e=e.replace(/#/gm,"%23")},St=(e,t)=>{if((!e||0!==e.indexOf("data:"))&&It.CorsBehavior)if("string"==typeof It.CorsBehavior||It.CorsBehavior instanceof String)t.crossOrigin=It.CorsBehavior;else{const s=It.CorsBehavior(e);s&&(t.crossOrigin=s)}},vt=(e,t,s,i,r="",n)=>{const a=C.LastCreatedEngine;if("undefined"==typeof HTMLImageElement&&!a?._features.forceBitmapOverHTMLImageElement)return s("LoadImage is only supported in web or BabylonNative environments."),null;let o,h=!1;e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"undefined"!=typeof Blob&&"undefined"!=typeof URL?(o=URL.createObjectURL(new Blob([e],{type:r})),h=!0):o=`data:${r};base64,`+Ae(e):e instanceof Blob?(o=URL.createObjectURL(e),h=!0):(o=It.CleanUrl(e),o=It.PreprocessUrl(o));const l=t=>{if(s){const i=o||e.toString();s(`Error while trying to load image: ${0===i.indexOf("http")||i.length<=128?i:i.slice(0,128)+"..."}`,t)}};if(a?._features.forceBitmapOverHTMLImageElement)return Pt(o,(i=>{a.createImageBitmap(new Blob([i],{type:r}),{premultiplyAlpha:"none",...n}).then((e=>{t(e),h&&URL.revokeObjectURL(o)})).catch((t=>{s&&s("Error while trying to load image: "+e,t)}))}),void 0,i||void 0,!0,((e,t)=>{l(t)})),null;const c=new Image;St(o,c);const u=[],d=()=>{u.forEach((e=>{e.target.removeEventListener(e.name,e.handler)})),u.length=0};u.push({target:c,name:"load",handler:()=>{d(),t(c),h&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:c,name:"error",handler:e=>{d(),l(e),h&&c.src&&URL.revokeObjectURL(c.src)}}),u.push({target:document,name:"securitypolicyviolation",handler:e=>{if(e.blockedURI!==c.src||"report"===e.disposition)return;d();const t=new Error(`CSP violation of policy ${e.effectiveDirective} ${e.blockedURI}. Current policy is ${e.originalPolicy}`);C.UseFallbackTexture=!1,l(t),h&&c.src&&URL.revokeObjectURL(c.src),c.src=""}}),u.forEach((e=>{e.target.addEventListener(e.name,e.handler)}));const _="blob:"===o.substring(0,5),f="data:"===o.substring(0,5),p=()=>{_||f||!pe.IsCustomRequestAvailable?c.src=o:Pt(o,((e,t,s)=>{const i=new Blob([e],{type:!r&&s?s:r}),n=URL.createObjectURL(i);h=!0,c.src=n}),void 0,i||void 0,!0,((e,t)=>{l(t)}))},m=()=>{i&&i.loadImage(o,c)};if(!_&&!f&&i&&i.enableTexturesOffline)i.open(m,p);else{if(-1!==o.indexOf("file:")){const e=decodeURIComponent(o.substring(5).toLowerCase());if(me.FilesToLoad[e]&&"undefined"!=typeof URL){try{let t;try{t=URL.createObjectURL(me.FilesToLoad[e])}catch(s){t=URL.createObjectURL(me.FilesToLoad[e])}c.src=t,h=!0}catch(e){c.src=""}return c}}p()}return c},Ct=(e,t,s,i,r)=>{const n=new FileReader,a={onCompleteObservable:new g,abort:()=>n.abort()};return n.onloadend=()=>a.onCompleteObservable.notifyObservers(a),r&&(n.onerror=()=>{r(new Mt(`Unable to read ${e.name}`,e))}),n.onload=e=>{t(e.target.result)},s&&(n.onprogress=s),i?n.readAsArrayBuffer(e):n.readAsText(e),a},Pt=(e,t,s,i,r,n,a)=>{if(e.name)return Ct(e,t,s,r,n?e=>{n(void 0,e)}:void 0);const o=e;if(-1!==o.indexOf("file:")){let e=decodeURIComponent(o.substring(5).toLowerCase());0===e.indexOf("./")&&(e=e.substring(2));const i=me.FilesToLoad[e];if(i)return Ct(i,t,s,r,n?e=>n(void 0,new Rt(e.message,e.file)):void 0)}const{match:h,type:l}=Ft(o);if(h){const e={onCompleteObservable:new g,abort:()=>()=>{}};try{const e=r?Nt(o):wt(o);t(e,void 0,l)}catch(e){n?n(void 0,e):ue.Error(e.message||"Failed to parse the Data URL")}return je.SetImmediate((()=>{e.onCompleteObservable.notifyObservers(e)})),e}return Ot(o,((e,s)=>{t(e,s?.responseURL,s?.getResponseHeader("content-type"))}),s,i,r,n?e=>{n(e.request,new Rt(e.message,e.request))}:void 0,a)},Ot=(e,t,s,i,r,n,a)=>{e=It.CleanUrl(e),e=It.PreprocessUrl(e);const o=It.BaseUrl+e;let h=!1;const l={onCompleteObservable:new g,abort:()=>h=!0},c=()=>{let e,i=new pe,c=null;const u=()=>{i&&(s&&i.removeEventListener("progress",s),e&&i.removeEventListener("readystatechange",e),i.removeEventListener("loadend",d))};let d=()=>{u(),l.onCompleteObservable.notifyObservers(l),l.onCompleteObservable.clear(),s=void 0,e=null,d=null,n=void 0,a=void 0,t=void 0};l.abort=()=>{h=!0,d&&d(),i&&i.readyState!==(XMLHttpRequest.DONE||4)&&i.abort(),null!==c&&(clearTimeout(c),c=null),i=null};const _=e=>{const t=e.message||"Unknown error";n&&i?n(new xt(t,i)):ue.Error(t)},f=l=>{if(i){if(i.open("GET",o),a)try{a(i)}catch(e){return void _(e)}r&&(i.responseType="arraybuffer"),s&&i.addEventListener("progress",s),d&&i.addEventListener("loadend",d),e=()=>{if(!h&&i&&i.readyState===(XMLHttpRequest.DONE||4)){if(e&&i.removeEventListener("readystatechange",e),i.status>=200&&i.status<300||0===i.status&&(!oe()||Dt())){try{t&&t(r?i.response:i.responseText,i)}catch(e){_(e)}return}const s=It.DefaultRetryStrategy;if(s){const e=s(o,i,l);if(-1!==e)return u(),i=new pe,void(c=setTimeout((()=>f(l+1)),e))}const a=new xt("Error status: "+i.status+" "+i.statusText+" - Unable to load "+o,i);n&&n(a)}},i.addEventListener("readystatechange",e),i.send()}};f(0)};if(i&&i.enableSceneOffline){const a=e=>{e&&e.status>400?n&&n(e):c()},o=()=>{i&&i.loadFile(It.BaseUrl+e,(e=>{!h&&t&&t(e),l.onCompleteObservable.notifyObservers(l)}),s?e=>{!h&&s&&s(e)}:void 0,a,r)};i.open(o,a)}else c();return l},Dt=()=>"undefined"!=typeof location&&"file:"===location.protocol,Lt=e=>bt.test(e),Ft=e=>{const t=bt.exec(e);if(null===t||0===t.length)return{match:!1,type:""};return{match:!0,type:t[0].replace("data:","").replace("base64,","")}};function Nt(e){return(e=>{const t=ye(e),s=t.length,i=new Uint8Array(new ArrayBuffer(s));for(let e=0;e<s;e++)i[e]=t.charCodeAt(e);return i.buffer})(e.split(",")[1])}const wt=e=>ye(e.split(",")[1]);let Bt;yt._FileToolsLoadImage=vt,Oe.loadFile=Pt,Qe.loadFile=Pt;((e,t,s,i,r,n,a,o,h,l)=>{Bt={DecodeBase64UrlToBinary:e,DecodeBase64UrlToString:t,DefaultRetryStrategy:s.DefaultRetryStrategy,BaseUrl:s.BaseUrl,CorsBehavior:s.CorsBehavior,PreprocessUrl:s.PreprocessUrl,IsBase64DataUrl:i,IsFileURL:r,LoadFile:n,LoadImage:a,ReadFile:o,RequestFile:h,SetCorsBehavior:l},Object.defineProperty(Bt,"DefaultRetryStrategy",{get:function(){return s.DefaultRetryStrategy},set:function(e){s.DefaultRetryStrategy=e}}),Object.defineProperty(Bt,"BaseUrl",{get:function(){return s.BaseUrl},set:function(e){s.BaseUrl=e}}),Object.defineProperty(Bt,"PreprocessUrl",{get:function(){return s.PreprocessUrl},set:function(e){s.PreprocessUrl=e}}),Object.defineProperty(Bt,"CorsBehavior",{get:function(){return s.CorsBehavior},set:function(e){s.CorsBehavior=e}})})(Nt,wt,It,Lt,Dt,Pt,vt,Ct,Ot,St);class Ut{static Instantiate(e){if(this.RegisteredExternalClasses&&this.RegisteredExternalClasses[e])return this.RegisteredExternalClasses[e];const t=S(e);if(t)return t;ue.Warn(e+" not found, you may have missed an import.");const s=e.split(".");let i=window||this;for(let e=0,t=s.length;e<t;e++)i=i[s[e]];return"function"!=typeof i?null:i}}function kt(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}))}function Gt(e){let t=1;do{t*=2}while(t<e);return t===e}function Vt(e,t,s){return e*(1-s)+t*s}function Ht(e){const t=zt(e),s=Xt(e);return t-e>e-s?s:t}function zt(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}function Xt(e){return e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,(e|=e>>16)-(e>>1)}function Wt(e,t,s=Ze.SCALEMODE_NEAREST){let i;switch(s){case Ze.SCALEMODE_FLOOR:i=Xt(e);break;case Ze.SCALEMODE_NEAREST:i=Ht(e);break;case Ze.SCALEMODE_CEILING:default:i=zt(e)}return Math.min(i,t)}Ut.RegisteredExternalClasses={};class Yt{static get BaseUrl(){return It.BaseUrl}static set BaseUrl(e){It.BaseUrl=e}static get CleanUrl(){return It.CleanUrl}static set CleanUrl(e){It.CleanUrl=e}static IsAbsoluteUrl(e){return 0===e.indexOf("//")||-1!==e.indexOf("://")&&(-1!==e.indexOf(".")&&(-1!==e.indexOf("/")&&(!(e.indexOf(":")>e.indexOf("/"))&&(e.indexOf("://")<e.indexOf(".")||(0===e.indexOf("data:")||0===e.indexOf("blob:"))))))}static set ScriptBaseUrl(e){It.ScriptBaseUrl=e}static get ScriptBaseUrl(){return It.ScriptBaseUrl}static set ScriptPreprocessUrl(e){It.ScriptPreprocessUrl=e}static get ScriptPreprocessUrl(){return It.ScriptPreprocessUrl}static get DefaultRetryStrategy(){return It.DefaultRetryStrategy}static set DefaultRetryStrategy(e){It.DefaultRetryStrategy=e}static get CorsBehavior(){return It.CorsBehavior}static set CorsBehavior(e){It.CorsBehavior=e}static get UseFallbackTexture(){return C.UseFallbackTexture}static set UseFallbackTexture(e){C.UseFallbackTexture=e}static get RegisteredExternalClasses(){return Ut.RegisteredExternalClasses}static set RegisteredExternalClasses(e){Ut.RegisteredExternalClasses=e}static get fallbackTexture(){return C.FallbackTexture}static set fallbackTexture(e){C.FallbackTexture=e}static FetchToRef(e,t,s,i,r,n){const a=4*((Math.abs(e)*s%s|0)+(Math.abs(t)*i%i|0)*s);n.r=r[a]/255,n.g=r[a+1]/255,n.b=r[a+2]/255,n.a=r[a+3]/255}static Mix(e,t,s){return 0}static Instantiate(e){return Ut.Instantiate(e)}static SetImmediate(e){je.SetImmediate(e)}static IsExponentOfTwo(e){return!0}static FloatRound(e){return Math.fround(e)}static GetFilename(e){const t=e.lastIndexOf("/");return t<0?e:e.substring(t+1)}static GetFolderPath(e,t=!1){const s=e.lastIndexOf("/");return s<0?t?e:"":e.substring(0,s+1)}static ToDegrees(e){return 180*e/Math.PI}static ToRadians(e){return e*Math.PI/180}static SmoothAngleChange(e,t,s=.9){const i=this.ToRadians(e),r=this.ToRadians(t);return this.ToDegrees(Math.atan2((1-s)*Math.sin(r)+s*Math.sin(i),(1-s)*Math.cos(r)+s*Math.cos(i)))}static MakeArray(e,t){return!0===t||void 0!==e&&null!=e?Array.isArray(e)?e:[e]:null}static GetPointerPrefix(e){let t="pointer";return oe()&&!window.PointerEvent&&(t="mouse"),!e._badDesktopOS||e._badOS||document&&"ontouchend"in document||(t="mouse"),t}static SetCorsBehavior(e,t){St(e,t)}static SetReferrerPolicyBehavior(e,t){t.referrerPolicy=e}static get PreprocessUrl(){return It.PreprocessUrl}static set PreprocessUrl(e){It.PreprocessUrl=e}static LoadImage(e,t,s,i,r,n){return vt(e,t,s,i,r,n)}static LoadFile(e,t,s,i,r,n){return Pt(e,t,s,i,r,n)}static LoadFileAsync(e,t=!0){return new Promise(((s,i)=>{Pt(e,(e=>{s(e)}),void 0,void 0,t,((e,t)=>{i(t)}))}))}static GetBabylonScriptURL(e,t){if(!e)return"";if(Yt.ScriptBaseUrl&&e.startsWith(Yt._DefaultCdnUrl)){const t="/"===Yt.ScriptBaseUrl[Yt.ScriptBaseUrl.length-1]?Yt.ScriptBaseUrl.substring(0,Yt.ScriptBaseUrl.length-1):Yt.ScriptBaseUrl;e=e.replace(Yt._DefaultCdnUrl,t)}return e=Yt.ScriptPreprocessUrl(e),t&&(e=Yt.GetAbsoluteUrl(e)),e}static LoadBabylonScript(e,t,s,i){e=Yt.GetBabylonScriptURL(e),Yt.LoadScript(e,t,s)}static LoadBabylonScriptAsync(e){return e=Yt.GetBabylonScriptURL(e),Yt.LoadScriptAsync(e)}static LoadScript(e,t,s,i){if("function"==typeof importScripts){try{importScripts(e),t()}catch(t){s?.(`Unable to load script '${e}' in worker`,t)}return}if(!oe())return void s?.(`Cannot load script '${e}' outside of a window or a worker`);const r=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("src",e),i&&(n.id=i),n.onload=()=>{t&&t()},n.onerror=t=>{s&&s(`Unable to load script '${e}'`,t)},r.appendChild(n)}static LoadScriptAsync(e,t){return new Promise(((s,i)=>{this.LoadScript(e,(()=>{s()}),((e,t)=>{i(t||new Error(e))}),t)}))}static ReadFileAsDataURL(e,t,s){const i=new FileReader,r={onCompleteObservable:new g,abort:()=>i.abort()};return i.onloadend=()=>{r.onCompleteObservable.notifyObservers(r)},i.onload=e=>{t(e.target.result)},i.onprogress=s,i.readAsDataURL(e),r}static ReadFile(e,t,s,i,r){return Ct(e,t,s,i,r)}static FileAsURL(e){const t=new Blob([e]);return window.URL.createObjectURL(t)}static Format(e,t=2){return e.toFixed(t)}static DeepCopy(e,t,s,i){_e.DeepCopy(e,t,s,i)}static IsEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}static RegisterTopRootEvents(e,t){for(let s=0;s<t.length;s++){const i=t[s];e.addEventListener(i.name,i.handler,!1);try{window.parent&&window.parent.addEventListener(i.name,i.handler,!1)}catch(e){}}}static UnregisterTopRootEvents(e,t){for(let s=0;s<t.length;s++){const i=t[s];e.removeEventListener(i.name,i.handler);try{e.parent&&e.parent.removeEventListener(i.name,i.handler)}catch(e){}}}static async DumpFramebuffer(e,t,s,i,r="image/png",n,a){throw Y("DumpTools")}static DumpData(e,t,s,i,r="image/png",n,a=!1,o=!1,h){throw Y("DumpTools")}static DumpDataAsync(e,t,s,i="image/png",r,n=!1,a=!1,o){throw Y("DumpTools")}static _IsOffScreenCanvas(e){return void 0!==e.convertToBlob}static ToBlob(e,t,s="image/png",i){Yt._IsOffScreenCanvas(e)||e.toBlob||(e.toBlob=function(e,t,s){setTimeout((()=>{const i=atob(this.toDataURL(t,s).split(",")[1]),r=i.length,n=new Uint8Array(r);for(let e=0;e<r;e++)n[e]=i.charCodeAt(e);e(new Blob([n]))}))}),Yt._IsOffScreenCanvas(e)?e.convertToBlob({type:s,quality:i}).then((e=>t(e))):e.toBlob((function(e){t(e)}),s,i)}static DownloadBlob(e,t){if("download"in document.createElement("a")){if(!t){const e=new Date;t="screenshot_"+((e.getFullYear()+"-"+(e.getMonth()+1)).slice(2)+"-"+e.getDate()+"_"+e.getHours()+"-"+("0"+e.getMinutes()).slice(-2))+".png"}Yt.Download(e,t)}else if(e&&"undefined"!=typeof URL){const t=URL.createObjectURL(e),s=window.open("");if(!s)return;const i=s.document.createElement("img");i.onload=function(){URL.revokeObjectURL(t)},i.src=t,s.document.body.appendChild(i)}}static EncodeScreenshotCanvasData(e,t,s="image/png",i,r){if("string"!=typeof i&&t){if(t){if(Yt._IsOffScreenCanvas(e))return void e.convertToBlob({type:s,quality:r}).then((e=>{const s=new FileReader;s.readAsDataURL(e),s.onloadend=()=>{const e=s.result;t(e)}}));const i=e.toDataURL(s,r);t(i)}}else this.ToBlob(e,(function(e){e&&Yt.DownloadBlob(e,i),t&&t("")}),s,r)}static Download(e,t){if("undefined"==typeof URL)return;const s=window.URL.createObjectURL(e),i=document.createElement("a");document.body.appendChild(i),i.style.display="none",i.href=s,i.download=t,i.addEventListener("click",(()=>{i.parentElement&&i.parentElement.removeChild(i)})),i.click(),window.URL.revokeObjectURL(s)}static BackCompatCameraNoPreventDefault(e){return"boolean"==typeof e[0]?e[0]:"boolean"==typeof e[1]&&e[1]}static CreateScreenshot(e,t,s,i,r="image/png",n=!1,a){throw Y("ScreenshotTools")}static CreateScreenshotAsync(e,t,s,i="image/png",r){throw Y("ScreenshotTools")}static CreateScreenshotUsingRenderTarget(e,t,s,i,r="image/png",n=1,a=!1,o,h=!1,l=!1,c=!0,u){throw Y("ScreenshotTools")}static CreateScreenshotUsingRenderTargetAsync(e,t,s,i="image/png",r=1,n=!1,a,o=!1,h=!1,l=!0,c){throw Y("ScreenshotTools")}static RandomId(){return kt()}static IsBase64(e){return Lt(e)}static DecodeBase64(e){return Nt(e)}static get errorsCount(){return ue.errorsCount}static Log(e){ue.Log(e)}static Warn(e){ue.Warn(e)}static Error(e){ue.Error(e)}static get LogCache(){return ue.LogCache}static ClearLogCache(){ue.ClearLogCache()}static set LogLevels(e){ue.LogLevels=e}static set PerformanceLogLevel(e){return(e&Yt.PerformanceUserMarkLogLevel)===Yt.PerformanceUserMarkLogLevel?(Yt.StartPerformanceCounter=Yt._StartUserMark,void(Yt.EndPerformanceCounter=Yt._EndUserMark)):(e&Yt.PerformanceConsoleLogLevel)===Yt.PerformanceConsoleLogLevel?(Yt.StartPerformanceCounter=Yt._StartPerformanceConsole,void(Yt.EndPerformanceCounter=Yt._EndPerformanceConsole)):(Yt.StartPerformanceCounter=Yt._StartPerformanceCounterDisabled,void(Yt.EndPerformanceCounter=Yt._EndPerformanceCounterDisabled))}static _StartPerformanceCounterDisabled(e,t){}static _EndPerformanceCounterDisabled(e,t){}static _StartUserMark(e,t=!0){if(!Yt._Performance){if(!oe())return;Yt._Performance=window.performance}t&&Yt._Performance.mark&&Yt._Performance.mark(e+"-Begin")}static _EndUserMark(e,t=!0){t&&Yt._Performance.mark&&(Yt._Performance.mark(e+"-End"),Yt._Performance.measure(e,e+"-Begin",e+"-End"))}static _StartPerformanceConsole(e,t=!0){t&&(Yt._StartUserMark(e,t),console.time&&console.time(e))}static _EndPerformanceConsole(e,t=!0){t&&(Yt._EndUserMark(e,t),console.timeEnd(e))}static get Now(){return fe.Now}static GetClassName(e,t=!1){let s=null;if(!t&&e.getClassName)s=e.getClassName();else{if(e instanceof Object){s=(t?e:Object.getPrototypeOf(e)).constructor.__bjsclassName__}s||(s=typeof e)}return s}static First(e,t){for(const s of e)if(t(s))return s;return null}static getFullClassName(e,t=!1){let s=null,i=null;if(!t&&e.getClassName)s=e.getClassName();else{if(e instanceof Object){const r=t?e:Object.getPrototypeOf(e);s=r.constructor.__bjsclassName__,i=r.constructor.__bjsmoduleName__}s||(s=typeof e)}return s?(null!=i?i+".":"")+s:null}static DelayAsync(e){return new Promise((t=>{setTimeout((()=>{t()}),e)}))}static IsSafari(){return!!he()&&/^((?!chrome|android).)*safari/i.test(navigator.userAgent)}}Yt.UseCustomRequestHeaders=!1,Yt.CustomRequestHeaders=pe.CustomRequestHeaders,Yt.GetDOMTextContent=ce,Yt._DefaultCdnUrl="https://cdn.babylonjs.com",Yt.GetAbsoluteUrl="object"==typeof document?e=>{const t=document.createElement("a");return t.href=e,t.href}:"function"==typeof URL&&"object"==typeof location?e=>new URL(e,location.origin).href:()=>{throw new Error("Unable to get absolute URL. Override BABYLON.Tools.GetAbsoluteUrl to a custom implementation for the current context.")},Yt.NoneLogLevel=ue.NoneLogLevel,Yt.MessageLogLevel=ue.MessageLogLevel,Yt.WarningLogLevel=ue.WarningLogLevel,Yt.ErrorLogLevel=ue.ErrorLogLevel,Yt.AllLogLevel=ue.AllLogLevel,Yt.IsWindowObjectExist=oe,Yt.PerformanceNoneLogLevel=0,Yt.PerformanceUserMarkLogLevel=1,Yt.PerformanceConsoleLogLevel=2,Yt.StartPerformanceCounter=Yt._StartPerformanceCounterDisabled,Yt.EndPerformanceCounter=Yt._EndPerformanceCounterDisabled;class Kt{constructor(e,t,s,i=0){this.iterations=e,this.index=i-1,this._done=!1,this._fn=t,this._successCallback=s}executeNext(){this._done||(this.index+1<this.iterations?(++this.index,this._fn(this)):this.breakLoop())}breakLoop(){this._done=!0,this._successCallback()}static Run(e,t,s,i=0){const r=new Kt(e,t,s,i);return r.executeNext(),r}static SyncAsyncForLoop(e,t,s,i,r,n=0){return Kt.Run(Math.ceil(e/t),(i=>{r&&r()?i.breakLoop():setTimeout((()=>{for(let n=0;n<t;++n){const a=i.index*t+n;if(a>=e)break;if(s(a),r&&r()){i.breakLoop();break}}i.executeNext()}),n)}),i)}}function qt(e,t,s){try{const i=e.next();i.done?t(i):i.value?i.value.then((()=>{i.value=void 0,t(i)}),s):t(i)}catch(e){s(e)}}function Qt(e,t,s,i,r){const n=()=>{let r;const a=e=>{e.done?s(e.value):void 0===r?r=!0:n()};do{r=void 0,t(e,a,i),void 0===r&&(r=!1)}while(r)};n()}function jt(e,t){let s;return Qt(e,qt,(e=>s=e),(e=>{throw e})),s}Yt.Mix=Vt,Yt.IsExponentOfTwo=Gt,C.FallbackTexture="data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";class Zt{constructor(e){this.length=0,this.data=new Array(e),this._id=Zt._GlobalId++}push(e){this.data[this.length++]=e,this.length>this.data.length&&(this.data.length*=2)}forEach(e){for(let t=0;t<this.length;t++)e(this.data[t])}sort(e){this.data.sort(e)}reset(){this.length=0}dispose(){this.reset(),this.data&&(this.data.length=0)}concat(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;t<e.length;t++)this.data[this.length++]=(e.data||e)[t]}}indexOf(e){const t=this.data.indexOf(e);return t>=this.length?-1:t}contains(e){return-1!==this.indexOf(e)}}Zt._GlobalId=0;class $t extends Zt{constructor(){super(...arguments),this._duplicateId=0}push(e){super.push(e),e.__smartArrayFlags||(e.__smartArrayFlags={}),e.__smartArrayFlags[this._id]=this._duplicateId}pushNoDuplicate(e){return(!e.__smartArrayFlags||e.__smartArrayFlags[this._id]!==this._duplicateId)&&(this.push(e),!0)}reset(){super.reset(),this._duplicateId++}concatWithNoDuplicate(e){if(0!==e.length){this.length+e.length>this.data.length&&(this.data.length=2*(this.length+e.length));for(let t=0;t<e.length;t++){const s=(e.data||e)[t];this.pushNoDuplicate(s)}}}}class Jt{constructor(e,t,s,i){this.x=e,this.y=t,this.width=s,this.height=i}toGlobal(e,t){return new Jt(this.x*e,this.y*t,this.width*e,this.height*t)}toGlobalToRef(e,t,s){return s.x=this.x*e,s.y=this.y*t,s.width=this.width*e,s.height=this.height*t,this}clone(){return new Jt(this.x,this.y,this.width,this.height)}}class es{constructor(e,t,s,i){this.normal=new U(e,t,s),this.d=i}asArray(){return[this.normal.x,this.normal.y,this.normal.z,this.d]}clone(){return new es(this.normal.x,this.normal.y,this.normal.z,this.d)}getClassName(){return"Plane"}getHashCode(){let e=this.normal.getHashCode();return e=397*e^this.d,e}normalize(){const e=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z);let t=0;return 0!==e&&(t=1/e),this.normal.x*=t,this.normal.y*=t,this.normal.z*=t,this.d*=t,this}transform(e){const t=es._TmpMatrix;e.invertToRef(t);const s=t.m,i=this.normal.x,r=this.normal.y,n=this.normal.z,a=this.d,o=i*s[0]+r*s[1]+n*s[2]+a*s[3],h=i*s[4]+r*s[5]+n*s[6]+a*s[7],l=i*s[8]+r*s[9]+n*s[10]+a*s[11],c=i*s[12]+r*s[13]+n*s[14]+a*s[15];return new es(o,h,l,c)}dotCoordinate(e){return this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z+this.d}copyFromPoints(e,t,s){const i=t.x-e.x,r=t.y-e.y,n=t.z-e.z,a=s.x-e.x,o=s.y-e.y,h=s.z-e.z,l=r*h-n*o,c=n*a-i*h,u=i*o-r*a,d=Math.sqrt(l*l+c*c+u*u);let _;return _=0!==d?1/d:0,this.normal.x=l*_,this.normal.y=c*_,this.normal.z=u*_,this.d=-(this.normal.x*e.x+this.normal.y*e.y+this.normal.z*e.z),this}isFrontFacingTo(e,t){return U.Dot(this.normal,e)<=t}signedDistanceTo(e){return U.Dot(e,this.normal)+this.d}static FromArray(e){return new es(e[0],e[1],e[2],e[3])}static FromPoints(e,t,s){const i=new es(0,0,0,0);return i.copyFromPoints(e,t,s),i}static FromPositionAndNormal(e,t){const s=new es(0,0,0,0);return this.FromPositionAndNormalToRef(e,t,s)}static FromPositionAndNormalToRef(e,t,s){return s.normal.copyFrom(t),s.normal.normalize(),s.d=-e.dot(s.normal),s}static SignedDistanceToPlaneFromPositionAndNormal(e,t,s){const i=-(t.x*e.x+t.y*e.y+t.z*e.z);return U.Dot(s,t)+i}}es._TmpMatrix=V.Identity();class ts{static GetPlanes(e){const t=[];for(let e=0;e<6;e++)t.push(new es(0,0,0,0));return ts.GetPlanesToRef(e,t),t}static GetNearPlaneToRef(e,t){const s=e.m;t.normal.x=s[3]+s[2],t.normal.y=s[7]+s[6],t.normal.z=s[11]+s[10],t.d=s[15]+s[14],t.normalize()}static GetFarPlaneToRef(e,t){const s=e.m;t.normal.x=s[3]-s[2],t.normal.y=s[7]-s[6],t.normal.z=s[11]-s[10],t.d=s[15]-s[14],t.normalize()}static GetLeftPlaneToRef(e,t){const s=e.m;t.normal.x=s[3]+s[0],t.normal.y=s[7]+s[4],t.normal.z=s[11]+s[8],t.d=s[15]+s[12],t.normalize()}static GetRightPlaneToRef(e,t){const s=e.m;t.normal.x=s[3]-s[0],t.normal.y=s[7]-s[4],t.normal.z=s[11]-s[8],t.d=s[15]-s[12],t.normalize()}static GetTopPlaneToRef(e,t){const s=e.m;t.normal.x=s[3]-s[1],t.normal.y=s[7]-s[5],t.normal.z=s[11]-s[9],t.d=s[15]-s[13],t.normalize()}static GetBottomPlaneToRef(e,t){const s=e.m;t.normal.x=s[3]+s[1],t.normal.y=s[7]+s[5],t.normal.z=s[11]+s[9],t.d=s[15]+s[13],t.normalize()}static GetPlanesToRef(e,t){ts.GetNearPlaneToRef(e,t[0]),ts.GetFarPlaneToRef(e,t[1]),ts.GetLeftPlaneToRef(e,t[2]),ts.GetRightPlaneToRef(e,t[3]),ts.GetTopPlaneToRef(e,t[4]),ts.GetBottomPlaneToRef(e,t[5])}static IsPointInFrustum(e,t){for(let s=0;s<6;s++)if(t[s].dotCoordinate(e)<0)return!1;return!0}}class ss extends ae{get position(){return this._position}set position(e){this._position=e}set upVector(e){this._upVector=e}get upVector(){return this._upVector}get screenArea(){let e=0,t=0;if(this.mode===ss.PERSPECTIVE_CAMERA)this.fovMode===ss.FOVMODE_VERTICAL_FIXED?(t=2*this.minZ*Math.tan(this.fov/2),e=this.getEngine().getAspectRatio(this)*t):(e=2*this.minZ*Math.tan(this.fov/2),t=e/this.getEngine().getAspectRatio(this));else{const s=this.getEngine().getRenderWidth()/2,i=this.getEngine().getRenderHeight()/2;e=(this.orthoRight??s)-(this.orthoLeft??-s),t=(this.orthoTop??i)-(this.orthoBottom??-i)}return e*t}set orthoLeft(e){this._orthoLeft=e;for(const t of this._rigCameras)t.orthoLeft=e}get orthoLeft(){return this._orthoLeft}set orthoRight(e){this._orthoRight=e;for(const t of this._rigCameras)t.orthoRight=e}get orthoRight(){return this._orthoRight}set orthoBottom(e){this._orthoBottom=e;for(const t of this._rigCameras)t.orthoBottom=e}get orthoBottom(){return this._orthoBottom}set orthoTop(e){this._orthoTop=e;for(const t of this._rigCameras)t.orthoTop=e}get orthoTop(){return this._orthoTop}set mode(e){this._mode=e;for(const t of this._rigCameras)t.mode=e}get mode(){return this._mode}get hasMoved(){return this._hasMoved}constructor(e,t,s,i=!0){super(e,s,!1),this._position=U.Zero(),this._upVector=U.Up(),this.oblique=null,this._orthoLeft=null,this._orthoRight=null,this._orthoBottom=null,this._orthoTop=null,this.fov=.8,this.projectionPlaneTilt=0,this.minZ=1,this.maxZ=1e4,this.inertia=.9,this._mode=ss.PERSPECTIVE_CAMERA,this.isIntermediate=!1,this.viewport=new Jt(0,0,1,1),this.layerMask=268435455,this.fovMode=ss.FOVMODE_VERTICAL_FIXED,this.cameraRigMode=ss.RIG_MODE_NONE,this.customRenderTargets=[],this.outputRenderTarget=null,this.onViewMatrixChangedObservable=new g,this.onProjectionMatrixChangedObservable=new g,this.onAfterCheckInputsObservable=new g,this.onRestoreStateObservable=new g,this.isRigCamera=!1,this._hasMoved=!1,this._rigCameras=new Array,this._skipRendering=!1,this._projectionMatrix=new V,this._postProcesses=new Array,this._activeMeshes=new Zt(256),this._globalPosition=U.Zero(),this._computedViewMatrix=V.Identity(),this._doNotComputeProjectionMatrix=!1,this._transformMatrix=V.Zero(),this._refreshFrustumPlanes=!0,this._absoluteRotation=G.Identity(),this._isCamera=!0,this._isLeftCamera=!1,this._isRightCamera=!1,this.getScene().addCamera(this),i&&!this.getScene().activeCamera&&(this.getScene().activeCamera=this),this.position=t,this.renderPassId=this.getScene().getEngine().createRenderPassId(`Camera ${e}`)}storeState(){return this._stateStored=!0,this._storedFov=this.fov,this}hasStateStored(){return!!this._stateStored}_restoreStateValues(){return!!this._stateStored&&(this.fov=this._storedFov,!0)}restoreState(){return!!this._restoreStateValues()&&(this.onRestoreStateObservable.notifyObservers(this),!0)}getClassName(){return"Camera"}toString(e){let t="Name: "+this.name;if(t+=", type: "+this.getClassName(),this.animations)for(let s=0;s<this.animations.length;s++)t+=", animation[0]: "+this.animations[s].toString(e);return t}applyVerticalCorrection(){const e=this.absoluteRotation.toEulerAngles();this.projectionPlaneTilt=this._scene.useRightHandedSystem?-e.x:e.x}get globalPosition(){return this._globalPosition}getActiveMeshes(){return this._activeMeshes}isActiveMesh(e){return-1!==this._activeMeshes.indexOf(e)}isReady(e=!1){if(e)for(const e of this._postProcesses)if(e&&!e.isReady())return!1;return super.isReady(e)}_initCache(){super._initCache(),this._cache.position=new U(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.upVector=new U(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.mode=void 0,this._cache.minZ=void 0,this._cache.maxZ=void 0,this._cache.fov=void 0,this._cache.fovMode=void 0,this._cache.aspectRatio=void 0,this._cache.orthoLeft=void 0,this._cache.orthoRight=void 0,this._cache.orthoBottom=void 0,this._cache.orthoTop=void 0,this._cache.obliqueAngle=void 0,this._cache.obliqueLength=void 0,this._cache.obliqueOffset=void 0,this._cache.renderWidth=void 0,this._cache.renderHeight=void 0}_updateCache(e){e||super._updateCache(),this._cache.position.copyFrom(this.position),this._cache.upVector.copyFrom(this.upVector)}_isSynchronized(){return this._isSynchronizedViewMatrix()&&this._isSynchronizedProjectionMatrix()}_isSynchronizedViewMatrix(){return!!super._isSynchronized()&&(this._cache.position.equals(this.position)&&this._cache.upVector.equals(this.upVector)&&this.isSynchronizedWithParent())}_isSynchronizedProjectionMatrix(){let e=this._cache.mode===this.mode&&this._cache.minZ===this.minZ&&this._cache.maxZ===this.maxZ;if(!e)return!1;const t=this.getEngine();return this.mode===ss.PERSPECTIVE_CAMERA?e=this._cache.fov===this.fov&&this._cache.fovMode===this.fovMode&&this._cache.aspectRatio===t.getAspectRatio(this)&&this._cache.projectionPlaneTilt===this.projectionPlaneTilt:(e=this._cache.orthoLeft===this.orthoLeft&&this._cache.orthoRight===this.orthoRight&&this._cache.orthoBottom===this.orthoBottom&&this._cache.orthoTop===this.orthoTop&&this._cache.renderWidth===t.getRenderWidth()&&this._cache.renderHeight===t.getRenderHeight(),this.oblique&&(e=e&&this._cache.obliqueAngle===this.oblique.angle&&this._cache.obliqueLength===this.oblique.length&&this._cache.obliqueOffset===this.oblique.offset)),e}attachControl(e,t){}detachControl(e){}update(){this._hasMoved=!1,this._checkInputs(),this.cameraRigMode!==ss.RIG_MODE_NONE&&this._updateRigCameras(),this.getViewMatrix(),this.getProjectionMatrix()}_checkInputs(){this.onAfterCheckInputsObservable.notifyObservers(this)}get rigCameras(){return this._rigCameras}get rigPostProcess(){return this._rigPostProcess}_getFirstPostProcess(){for(let e=0;e<this._postProcesses.length;e++)if(null!==this._postProcesses[e])return this._postProcesses[e];return null}_cascadePostProcessesToRigCams(){const e=this._getFirstPostProcess();e&&e.markTextureDirty();for(let e=0,t=this._rigCameras.length;e<t;e++){const t=this._rigCameras[e],s=t._rigPostProcess;if(s){"pass"===s.getEffectName()&&(t.isIntermediate=0===this._postProcesses.length),t._postProcesses=this._postProcesses.slice(0).concat(s),s.markTextureDirty()}else t._postProcesses=this._postProcesses.slice(0)}}attachPostProcess(e,t=null){return!e.isReusable()&&this._postProcesses.indexOf(e)>-1?(ue.Error("You're trying to reuse a post process not defined as reusable."),0):(null==t||t<0?this._postProcesses.push(e):null===this._postProcesses[t]?this._postProcesses[t]=e:this._postProcesses.splice(t,0,e),this._cascadePostProcessesToRigCams(),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._postProcesses.indexOf(e))}detachPostProcess(e){const t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses[t]=null),this._scene.prePassRenderer&&this._scene.prePassRenderer.markAsDirty(),this._cascadePostProcessesToRigCams()}getWorldMatrix(){return this._isSynchronizedViewMatrix()||this.getViewMatrix(),this._worldMatrix}_getViewMatrix(){return V.Identity()}getViewMatrix(e){return!e&&this._isSynchronizedViewMatrix()||(this._hasMoved=!0,this.updateCache(),this._computedViewMatrix=this._getViewMatrix(),this._currentRenderId=this.getScene().getRenderId(),this._childUpdateId++,this._refreshFrustumPlanes=!0,this._cameraRigParams&&this._cameraRigParams.vrPreViewMatrix&&this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix,this._computedViewMatrix),this.parent&&this.parent.onViewMatrixChangedObservable&&this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent),this.onViewMatrixChangedObservable.notifyObservers(this),this._computedViewMatrix.invertToRef(this._worldMatrix)),this._computedViewMatrix}freezeProjectionMatrix(e){this._doNotComputeProjectionMatrix=!0,void 0!==e&&(this._projectionMatrix=e)}unfreezeProjectionMatrix(){this._doNotComputeProjectionMatrix=!1}getProjectionMatrix(e){if(this._doNotComputeProjectionMatrix||!e&&this._isSynchronizedProjectionMatrix())return this._projectionMatrix;this._cache.mode=this.mode,this._cache.minZ=this.minZ,this._cache.maxZ=this.maxZ,this._refreshFrustumPlanes=!0;const t=this.getEngine(),s=this.getScene(),i=t.useReverseDepthBuffer;if(this.mode===ss.PERSPECTIVE_CAMERA){let e;this._cache.fov=this.fov,this._cache.fovMode=this.fovMode,this._cache.aspectRatio=t.getAspectRatio(this),this._cache.projectionPlaneTilt=this.projectionPlaneTilt,this.minZ<=0&&(this.minZ=.1),e=s.useRightHandedSystem?V.PerspectiveFovRHToRef:V.PerspectiveFovLHToRef,e(this.fov,t.getAspectRatio(this),i?this.maxZ:this.minZ,i?this.minZ:this.maxZ,this._projectionMatrix,this.fovMode===ss.FOVMODE_VERTICAL_FIXED,t.isNDCHalfZRange,this.projectionPlaneTilt,i)}else{const e=t.getRenderWidth()/2,r=t.getRenderHeight()/2;s.useRightHandedSystem?this.oblique?V.ObliqueOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,i?this.maxZ:this.minZ,i?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):V.OrthoOffCenterRHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,i?this.maxZ:this.minZ,i?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange):this.oblique?V.ObliqueOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,i?this.maxZ:this.minZ,i?this.minZ:this.maxZ,this.oblique.length,this.oblique.angle,this._computeObliqueDistance(this.oblique.offset),this._projectionMatrix,t.isNDCHalfZRange):V.OrthoOffCenterLHToRef(this.orthoLeft??-e,this.orthoRight??e,this.orthoBottom??-r,this.orthoTop??r,i?this.maxZ:this.minZ,i?this.minZ:this.maxZ,this._projectionMatrix,t.isNDCHalfZRange),this._cache.orthoLeft=this.orthoLeft,this._cache.orthoRight=this.orthoRight,this._cache.orthoBottom=this.orthoBottom,this._cache.orthoTop=this.orthoTop,this._cache.obliqueAngle=this.oblique?.angle,this._cache.obliqueLength=this.oblique?.length,this._cache.obliqueOffset=this.oblique?.offset,this._cache.renderWidth=t.getRenderWidth(),this._cache.renderHeight=t.getRenderHeight()}return this.onProjectionMatrixChangedObservable.notifyObservers(this),this._projectionMatrix}getTransformationMatrix(){return this._computedViewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._transformMatrix}_computeObliqueDistance(e){return(this.radius||(this.target?U.Distance(this.position,this.target):this.position.length()))+e}_updateFrustumPlanes(){this._refreshFrustumPlanes&&(this.getTransformationMatrix(),this._frustumPlanes?ts.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=ts.GetPlanes(this._transformMatrix),this._refreshFrustumPlanes=!1)}isInFrustum(e,t=!1){if(this._updateFrustumPlanes(),t&&this.rigCameras.length>0){let t=!1;return this.rigCameras.forEach((s=>{s._updateFrustumPlanes(),t=t||e.isInFrustum(s._frustumPlanes)})),t}return e.isInFrustum(this._frustumPlanes)}isCompletelyInFrustum(e){return this._updateFrustumPlanes(),e.isCompletelyInFrustum(this._frustumPlanes)}getForwardRay(e=100,t,s){throw Y("Ray")}getForwardRayToRef(e,t=100,s,i){throw Y("Ray")}dispose(e,t=!1){for(this.onViewMatrixChangedObservable.clear(),this.onProjectionMatrixChangedObservable.clear(),this.onAfterCheckInputsObservable.clear(),this.onRestoreStateObservable.clear(),this.inputs&&this.inputs.clear(),this.getScene().stopAnimation(this),this.getScene().removeCamera(this);this._rigCameras.length>0;){const e=this._rigCameras.pop();e&&e.dispose()}if(this._parentContainer){const e=this._parentContainer.cameras.indexOf(this);e>-1&&this._parentContainer.cameras.splice(e,1),this._parentContainer=null}if(this._rigPostProcess)this._rigPostProcess.dispose(this),this._rigPostProcess=null,this._postProcesses.length=0;else if(this.cameraRigMode!==ss.RIG_MODE_NONE)this._rigPostProcess=null,this._postProcesses.length=0;else{let e=this._postProcesses.length;for(;--e>=0;){const t=this._postProcesses[e];t&&t.dispose(this)}}let s=this.customRenderTargets.length;for(;--s>=0;)this.customRenderTargets[s].dispose();this.customRenderTargets.length=0,this._activeMeshes.dispose(),this.getScene().getEngine().releaseRenderPassId(this.renderPassId),super.dispose(e,t)}get isLeftCamera(){return this._isLeftCamera}get isRightCamera(){return this._isRightCamera}get leftCamera(){return this._rigCameras.length<1?null:this._rigCameras[0]}get rightCamera(){return this._rigCameras.length<2?null:this._rigCameras[1]}getLeftTarget(){return this._rigCameras.length<1?null:this._rigCameras[0].getTarget()}getRightTarget(){return this._rigCameras.length<2?null:this._rigCameras[1].getTarget()}setCameraRigMode(e,t){if(this.cameraRigMode!==e){for(;this._rigCameras.length>0;){const e=this._rigCameras.pop();e&&e.dispose()}if(this.cameraRigMode=e,this._cameraRigParams={},this._cameraRigParams.interaxialDistance=t.interaxialDistance||.0637,this._cameraRigParams.stereoHalfAngle=Yt.ToRadians(this._cameraRigParams.interaxialDistance/.0637),this.cameraRigMode!==ss.RIG_MODE_NONE){const e=this.createRigCamera(this.name+"_L",0);e&&(e._isLeftCamera=!0);const t=this.createRigCamera(this.name+"_R",1);t&&(t._isRightCamera=!0),e&&t&&(this._rigCameras.push(e),this._rigCameras.push(t))}this._setRigMode(t),this._cascadePostProcessesToRigCams(),this.update()}}_setRigMode(e){}_getVRProjectionMatrix(){return V.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov,this._cameraRigParams.vrMetrics.aspectRatio,this.minZ,this.maxZ,this._cameraRigParams.vrWorkMatrix,!0,this.getEngine().isNDCHalfZRange),this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix,this._projectionMatrix),this._projectionMatrix}setCameraRigParameter(e,t){this._cameraRigParams||(this._cameraRigParams={}),this._cameraRigParams[e]=t,"interaxialDistance"===e&&(this._cameraRigParams.stereoHalfAngle=Yt.ToRadians(t/.0637))}createRigCamera(e,t){return null}_updateRigCameras(){for(let e=0;e<this._rigCameras.length;e++)this._rigCameras[e].minZ=this.minZ,this._rigCameras[e].maxZ=this.maxZ,this._rigCameras[e].fov=this.fov,this._rigCameras[e].upVector.copyFrom(this.upVector);this.cameraRigMode===ss.RIG_MODE_STEREOSCOPIC_ANAGLYPH&&(this._rigCameras[0].viewport=this._rigCameras[1].viewport=this.viewport)}_setupInputs(){}serialize(){const e=re.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getClassName(),this.parent&&this.parent._serializeAsParent(e),this.inputs&&this.inputs.serialize(e),re.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}clone(e,t=null){const s=re.Clone(ss.GetConstructorFromName(this.getClassName(),e,this.getScene(),this.interaxialDistance,this.isStereoscopicSideBySide),this);return s.name=e,s.parent=t,this.onClonedObservable.notifyObservers(s),s}getDirection(e){const t=U.Zero();return this.getDirectionToRef(e,t),t}get absoluteRotation(){return this.getWorldMatrix().decompose(void 0,this._absoluteRotation),this._absoluteRotation}getDirectionToRef(e,t){U.TransformNormalToRef(e,this.getWorldMatrix(),t)}static GetConstructorFromName(e,t,s,i=0,r=!0){const n=ae.Construct(e,t,s,{interaxial_distance:i,isStereoscopicSideBySide:r});return n||(()=>ss._CreateDefaultParsedCamera(t,s))}computeWorldMatrix(){return this.getWorldMatrix()}static Parse(e,t){const s=e.type,i=ss.GetConstructorFromName(s,e.name,t,e.interaxial_distance,e.isStereoscopicSideBySide),r=re.Parse(i,e,t);if(void 0!==e.parentId&&(r._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(r._waitingParentInstanceIndex=e.parentInstanceIndex),r.inputs&&(r.inputs.parse(e),r._setupInputs()),e.upVector&&(r.upVector=U.FromArray(e.upVector)),r.setPosition&&(r.position.copyFromFloats(0,0,0),r.setPosition(U.FromArray(e.position))),e.target&&r.setTarget&&r.setTarget(U.FromArray(e.target)),e.cameraRigMode){const t=e.interaxial_distance?{interaxialDistance:e.interaxial_distance}:{};r.setCameraRigMode(e.cameraRigMode,t)}if(e.animations){for(let t=0;t<e.animations.length;t++){const s=e.animations[t],i=S("BABYLON.Animation");i&&r.animations.push(i.Parse(s))}ae.ParseAnimationRanges(r,e,t)}return e.autoAnimate&&t.beginAnimation(r,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),void 0!==e.isEnabled&&r.setEnabled(e.isEnabled),r}_calculateHandednessMultiplier(){let e=this.getScene().useRightHandedSystem?-1:1;return this.parent&&this.parent._getWorldMatrixDeterminant()<0&&(e*=-1),e}}ss._CreateDefaultParsedCamera=(e,t)=>{throw Y("UniversalCamera")},ss.PERSPECTIVE_CAMERA=Ze.PERSPECTIVE_CAMERA,ss.ORTHOGRAPHIC_CAMERA=Ze.ORTHOGRAPHIC_CAMERA,ss.FOVMODE_VERTICAL_FIXED=Ze.FOVMODE_VERTICAL_FIXED,ss.FOVMODE_HORIZONTAL_FIXED=Ze.FOVMODE_HORIZONTAL_FIXED,ss.RIG_MODE_NONE=Ze.RIG_MODE_NONE,ss.RIG_MODE_STEREOSCOPIC_ANAGLYPH=Ze.RIG_MODE_STEREOSCOPIC_ANAGLYPH,ss.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL=Ze.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL,ss.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED=Ze.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED,ss.RIG_MODE_STEREOSCOPIC_OVERUNDER=Ze.RIG_MODE_STEREOSCOPIC_OVERUNDER,ss.RIG_MODE_STEREOSCOPIC_INTERLACED=Ze.RIG_MODE_STEREOSCOPIC_INTERLACED,ss.RIG_MODE_VR=Ze.RIG_MODE_VR,ss.RIG_MODE_CUSTOM=Ze.RIG_MODE_CUSTOM,ss.ForceAttachControlToAlwaysPreventDefault=!1,e([c("position")],ss.prototype,"_position",void 0),e([c("upVector")],ss.prototype,"_upVector",void 0),e([a()],ss.prototype,"orthoLeft",null),e([a()],ss.prototype,"orthoRight",null),e([a()],ss.prototype,"orthoBottom",null),e([a()],ss.prototype,"orthoTop",null),e([a()],ss.prototype,"fov",void 0),e([a()],ss.prototype,"projectionPlaneTilt",void 0),e([a()],ss.prototype,"minZ",void 0),e([a()],ss.prototype,"maxZ",void 0),e([a()],ss.prototype,"inertia",void 0),e([a()],ss.prototype,"mode",null),e([a()],ss.prototype,"layerMask",void 0),e([a()],ss.prototype,"fovMode",void 0),e([a()],ss.prototype,"cameraRigMode",void 0),e([a()],ss.prototype,"interaxialDistance",void 0),e([a()],ss.prototype,"isStereoscopicSideBySide",void 0);class is{get underlyingResource(){return null}constructor(){this.references=0,this.capacity=0,this.is32Bits=!1,this.uniqueId=is._Counter++}}is._Counter=0;class rs{get isDisposed(){return this._isDisposed}constructor(e,t,s,i=0,r=!1,n=!1,a=!1,o,h){this._isAlreadyOwned=!1,this._isDisposed=!1,e&&e.getScene?this._engine=e.getScene().getEngine():this._engine=e,this._updatable=s,this._instanced=n,this._divisor=o||1,this._label=h,t instanceof is?(this._data=null,this._buffer=t):(this._data=t,this._buffer=null),this.byteStride=a?i:i*Float32Array.BYTES_PER_ELEMENT,r||this.create()}createVertexBuffer(e,t,s,i,r,n=!1,a){const o=n?t:t*Float32Array.BYTES_PER_ELEMENT,h=i?n?i:i*Float32Array.BYTES_PER_ELEMENT:this.byteStride;return new ns(this._engine,this,e,this._updatable,!0,h,void 0===r?this._instanced:r,o,s,void 0,void 0,!0,this._divisor||a)}isUpdatable(){return this._updatable}getData(){return this._data}getBuffer(){return this._buffer}getStrideSize(){return this.byteStride/Float32Array.BYTES_PER_ELEMENT}create(e=null){!e&&this._buffer||(e=e||this._data)&&(this._buffer?this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e),this._data=e):this._updatable?(this._buffer=this._engine.createDynamicVertexBuffer(e,this._label),this._data=e):this._buffer=this._engine.createVertexBuffer(e,void 0,this._label))}_rebuild(){if(this._data)this._buffer=null,this.create(this._data);else{if(!this._buffer)return;if(this._buffer.capacity>0)return void(this._updatable?this._buffer=this._engine.createDynamicVertexBuffer(this._buffer.capacity,this._label):this._buffer=this._engine.createVertexBuffer(this._buffer.capacity,void 0,this._label));ue.Warn(`Missing data for buffer "${this._label}" ${this._buffer?"(uniqueId: "+this._buffer.uniqueId+")":""}. Buffer reconstruction failed.`),this._buffer=null}}update(e){this.create(e)}updateDirectly(e,t,s,i=!1){this._buffer&&this._updatable&&(this._engine.updateDynamicVertexBuffer(this._buffer,e,i?t:t*Float32Array.BYTES_PER_ELEMENT,s?s*this.byteStride:void 0),this._data=0===t&&void 0===s?e:null)}_increaseReferences(){this._buffer&&(this._isAlreadyOwned?this._buffer.references++:this._isAlreadyOwned=!0)}dispose(){this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._isDisposed=!0,this._data=null,this._buffer=null)}}class ns{get isDisposed(){return this._isDisposed}get instanceDivisor(){return this._instanceDivisor}set instanceDivisor(e){const t=0!=e;this._instanceDivisor=e,t!==this._instanced&&(this._instanced=t,this._computeHashCode())}get _maxVerticesCount(){const e=this.getData();return e?Array.isArray(e)?e.length/(this.byteStride/4)-this.byteOffset/4:(e.byteLength-this.byteOffset)/this.byteStride:0}constructor(e,t,s,i,r,n,a,o,h,l,c=!1,u=!1,d=1,_=!1){this._isDisposed=!1;let f=!1;if(this.engine=e,"object"==typeof i&&null!==i?(f=i.updatable??!1,r=i.postponeInternalCreation,n=i.stride,a=i.instanced,o=i.offset,h=i.size,l=i.type,c=i.normalized??!1,u=i.useBytes??!1,d=i.divisor??1,_=i.takeBufferOwnership??!1,this._label=i.label):f=!!i,t instanceof rs?(this._buffer=t,this._ownsBuffer=_):(this._buffer=new rs(e,t,f,n,r,a,u,d,this._label),this._ownsBuffer=!0),this.uniqueId=ns._Counter++,this._kind=s,void 0===l){const e=this.getData();this.type=e?ns.GetDataType(e):ns.FLOAT}else this.type=l;const p=ns.GetTypeByteLength(this.type);u?(this._size=h||(n?n/p:ns.DeduceStride(s)),this.byteStride=n||this._buffer.byteStride||this._size*p,this.byteOffset=o||0):(this._size=h||n||ns.DeduceStride(s),this.byteStride=n?n*p:this._buffer.byteStride||this._size*p,this.byteOffset=(o||0)*p),this.normalized=c,this._instanced=void 0!==a&&a,this._instanceDivisor=a?d:0,this._alignBuffer(),this._computeHashCode()}_computeHashCode(){this.hashCode=(this.type-5120|0)+((this.normalized?1:0)<<3)+(this._size<<4)+((this._instanced?1:0)<<6)+(this.byteStride<<12)}_rebuild(){this._buffer?._rebuild()}getKind(){return this._kind}isUpdatable(){return this._buffer.isUpdatable()}getData(){return this._buffer.getData()}getFloatData(e,t){const s=this.getData();return s?ns.GetFloatData(s,this._size,this.type,this.byteOffset,this.byteStride,this.normalized,e,t):null}getBuffer(){return this._buffer.getBuffer()}getWrapperBuffer(){return this._buffer}getStrideSize(){return this.byteStride/ns.GetTypeByteLength(this.type)}getOffset(){return this.byteOffset/ns.GetTypeByteLength(this.type)}getSize(e=!1){return e?this._size*ns.GetTypeByteLength(this.type):this._size}getIsInstanced(){return this._instanced}getInstanceDivisor(){return this._instanceDivisor}create(e){this._buffer.create(e),this._alignBuffer()}update(e){this._buffer.update(e),this._alignBuffer()}updateDirectly(e,t,s=!1){this._buffer.updateDirectly(e,t,void 0,s),this._alignBuffer()}dispose(){this._ownsBuffer&&this._buffer.dispose(),this._isDisposed=!0}forEach(e,t){ns.ForEach(this._buffer.getData(),this.byteOffset,this.byteStride,this._size,this.type,e,this.normalized,t)}_alignBuffer(){}static DeduceStride(e){switch(e){case ns.UVKind:case ns.UV2Kind:case ns.UV3Kind:case ns.UV4Kind:case ns.UV5Kind:case ns.UV6Kind:return 2;case ns.NormalKind:case ns.PositionKind:return 3;case ns.ColorKind:case ns.ColorInstanceKind:case ns.MatricesIndicesKind:case ns.MatricesIndicesExtraKind:case ns.MatricesWeightsKind:case ns.MatricesWeightsExtraKind:case ns.TangentKind:return 4;default:throw new Error("Invalid kind '"+e+"'")}}static GetDataType(e){return e instanceof Int8Array?ns.BYTE:e instanceof Uint8Array?ns.UNSIGNED_BYTE:e instanceof Int16Array?ns.SHORT:e instanceof Uint16Array?ns.UNSIGNED_SHORT:e instanceof Int32Array?ns.INT:e instanceof Uint32Array?ns.UNSIGNED_INT:ns.FLOAT}static GetTypeByteLength(e){switch(e){case ns.BYTE:case ns.UNSIGNED_BYTE:return 1;case ns.SHORT:case ns.UNSIGNED_SHORT:return 2;case ns.INT:case ns.UNSIGNED_INT:case ns.FLOAT:return 4;default:throw new Error(`Invalid type '${e}'`)}}static ForEach(e,t,s,i,r,n,a,o){if(e instanceof Array){let r=t/4;const a=s/4;for(let t=0;t<n;t+=i){for(let s=0;s<i;s++)o(e[r+s],t+s);r+=a}}else{const h=e instanceof ArrayBuffer?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength),l=ns.GetTypeByteLength(r);for(let e=0;e<n;e+=i){let n=t;for(let t=0;t<i;t++){o(ns._GetFloatValue(h,r,n,a),e+t),n+=l}t+=s}}}static _GetFloatValue(e,t,s,i){switch(t){case ns.BYTE:{let t=e.getInt8(s);return i&&(t=Math.max(t/127,-1)),t}case ns.UNSIGNED_BYTE:{let t=e.getUint8(s);return i&&(t/=255),t}case ns.SHORT:{let t=e.getInt16(s,!0);return i&&(t=Math.max(t/32767,-1)),t}case ns.UNSIGNED_SHORT:{let t=e.getUint16(s,!0);return i&&(t/=65535),t}case ns.INT:return e.getInt32(s,!0);case ns.UNSIGNED_INT:return e.getUint32(s,!0);case ns.FLOAT:return e.getFloat32(s,!0);default:throw new Error(`Invalid component type ${t}`)}}static GetFloatData(e,t,s,i,r,n,a,o){const h=t*ns.GetTypeByteLength(s),l=a*t;if(s!==ns.FLOAT||r!==h){const a=new Float32Array(l);return ns.ForEach(e,i,r,t,s,l,n,((e,t)=>a[t]=e)),a}if(!(e instanceof Array||e instanceof Float32Array)||0!==i||e.length!==l){if(e instanceof Array){const t=i/4;return e.slice(t,t+l)}if(e instanceof ArrayBuffer)return new Float32Array(e,i,l);{const t=e.byteOffset+i;if(3&t&&(ue.Warn("Float array must be aligned to 4-bytes border"),o=!0),o){const s=new Uint8Array(l*Float32Array.BYTES_PER_ELEMENT),i=new Uint8Array(e.buffer,t,s.length);return s.set(i),new Float32Array(s.buffer)}return new Float32Array(e.buffer,t,l)}}return o?e.slice():e}}ns._Counter=0,ns.BYTE=Ze.BYTE,ns.UNSIGNED_BYTE=Ze.UNSIGNED_BYTE,ns.SHORT=Ze.SHORT,ns.UNSIGNED_SHORT=Ze.UNSIGNED_SHORT,ns.INT=Ze.INT,ns.UNSIGNED_INT=Ze.UNSIGNED_INT,ns.FLOAT=Ze.FLOAT,ns.PositionKind=Ze.PositionKind,ns.NormalKind=Ze.NormalKind,ns.TangentKind=Ze.TangentKind,ns.UVKind=Ze.UVKind,ns.UV2Kind=Ze.UV2Kind,ns.UV3Kind=Ze.UV3Kind,ns.UV4Kind=Ze.UV4Kind,ns.UV5Kind=Ze.UV5Kind,ns.UV6Kind=Ze.UV6Kind,ns.ColorKind=Ze.ColorKind,ns.ColorInstanceKind=Ze.ColorInstanceKind,ns.MatricesIndicesKind=Ze.MatricesIndicesKind,ns.MatricesWeightsKind=Ze.MatricesWeightsKind,ns.MatricesIndicesExtraKind=Ze.MatricesIndicesExtraKind,ns.MatricesWeightsExtraKind=Ze.MatricesWeightsExtraKind;class as{constructor(e,t,s){this.bu=e,this.bv=t,this.distance=s,this.faceId=0,this.subMeshId=0}}class os{constructor(e,t,s){this.vectors=y(8,U.Zero),this.center=U.Zero(),this.centerWorld=U.Zero(),this.extendSize=U.Zero(),this.extendSizeWorld=U.Zero(),this.directions=y(3,U.Zero),this.vectorsWorld=y(8,U.Zero),this.minimumWorld=U.Zero(),this.maximumWorld=U.Zero(),this.minimum=U.Zero(),this.maximum=U.Zero(),this._drawWrapperFront=null,this._drawWrapperBack=null,this.reConstruct(e,t,s)}reConstruct(e,t,s){const i=e.x,r=e.y,n=e.z,a=t.x,o=t.y,h=t.z,l=this.vectors;this.minimum.copyFromFloats(i,r,n),this.maximum.copyFromFloats(a,o,h),l[0].copyFromFloats(i,r,n),l[1].copyFromFloats(a,o,h),l[2].copyFromFloats(a,r,n),l[3].copyFromFloats(i,o,n),l[4].copyFromFloats(i,r,h),l[5].copyFromFloats(a,o,n),l[6].copyFromFloats(i,o,h),l[7].copyFromFloats(a,r,h),t.addToRef(e,this.center).scaleInPlace(.5),t.subtractToRef(e,this.extendSize).scaleInPlace(.5),this._worldMatrix=s||V.IdentityReadOnly,this._update(this._worldMatrix)}scale(e){const t=os._TmpVector3,s=this.maximum.subtractToRef(this.minimum,t[0]),i=s.length();s.normalizeFromLength(i);const r=i*e,n=s.scaleInPlace(.5*r),a=this.center.subtractToRef(n,t[1]),o=this.center.addToRef(n,t[2]);return this.reConstruct(a,o,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){const t=this.minimumWorld,s=this.maximumWorld,i=this.directions,r=this.vectorsWorld,n=this.vectors;if(e.isIdentity()){t.copyFrom(this.minimum),s.copyFrom(this.maximum);for(let e=0;e<8;++e)r[e].copyFrom(n[e]);this.extendSizeWorld.copyFrom(this.extendSize),this.centerWorld.copyFrom(this.center)}else{t.setAll(Number.MAX_VALUE),s.setAll(-Number.MAX_VALUE);for(let i=0;i<8;++i){const a=r[i];U.TransformCoordinatesToRef(n[i],e,a),t.minimizeInPlace(a),s.maximizeInPlace(a)}s.subtractToRef(t,this.extendSizeWorld).scaleInPlace(.5),s.addToRef(t,this.centerWorld).scaleInPlace(.5)}U.FromArrayToRef(e.m,0,i[0]),U.FromArrayToRef(e.m,4,i[1]),U.FromArrayToRef(e.m,8,i[2]),this._worldMatrix=e}isInFrustum(e){return os.IsInFrustum(this.vectorsWorld,e)}isCompletelyInFrustum(e){return os.IsCompletelyInFrustum(this.vectorsWorld,e)}intersectsPoint(e){const t=this.minimumWorld,s=this.maximumWorld,i=t.x,r=t.y,n=t.z,a=s.x,o=s.y,h=s.z,l=e.x,c=e.y,u=e.z,d=-A;return!(a-l<d||d>l-i)&&(!(o-c<d||d>c-r)&&!(h-u<d||d>u-n))}intersectsSphere(e){return os.IntersectsSphere(this.minimumWorld,this.maximumWorld,e.centerWorld,e.radiusWorld)}intersectsMinMax(e,t){const s=this.minimumWorld,i=this.maximumWorld,r=s.x,n=s.y,a=s.z,o=i.x,h=i.y,l=i.z,c=e.x,u=e.y,d=e.z,_=t.x,f=t.y,p=t.z;return!(o<c||r>_)&&(!(h<u||n>f)&&!(l<d||a>p))}dispose(){this._drawWrapperFront?.dispose(),this._drawWrapperBack?.dispose()}static Intersects(e,t){return e.intersectsMinMax(t.minimumWorld,t.maximumWorld)}static IntersectsSphere(e,t,s,i){const r=os._TmpVector3[0];U.ClampToRef(s,e,t,r);return U.DistanceSquared(s,r)<=i*i}static IsCompletelyInFrustum(e,t){for(let s=0;s<6;++s){const i=t[s];for(let t=0;t<8;++t)if(i.dotCoordinate(e[t])<0)return!1}return!0}static IsInFrustum(e,t){for(let s=0;s<6;++s){let i=!0;const r=t[s];for(let t=0;t<8;++t)if(r.dotCoordinate(e[t])>=0){i=!1;break}if(i)return!1}return!0}}os._TmpVector3=y(3,U.Zero);class hs{constructor(e,t,s){this.center=U.Zero(),this.centerWorld=U.Zero(),this.minimum=U.Zero(),this.maximum=U.Zero(),this.reConstruct(e,t,s)}reConstruct(e,t,s){this.minimum.copyFrom(e),this.maximum.copyFrom(t);const i=U.Distance(e,t);t.addToRef(e,this.center).scaleInPlace(.5),this.radius=.5*i,this._update(s||V.IdentityReadOnly)}scale(e){const t=this.radius*e,s=hs._TmpVector3,i=s[0].setAll(t),r=this.center.subtractToRef(i,s[1]),n=this.center.addToRef(i,s[2]);return this.reConstruct(r,n,this._worldMatrix),this}getWorldMatrix(){return this._worldMatrix}_update(e){if(e.isIdentity())this.centerWorld.copyFrom(this.center),this.radiusWorld=this.radius;else{U.TransformCoordinatesToRef(this.center,e,this.centerWorld);const t=hs._TmpVector3[0];U.TransformNormalFromFloatsToRef(1,1,1,e,t),this.radiusWorld=Math.max(Math.abs(t.x),Math.abs(t.y),Math.abs(t.z))*this.radius}}isInFrustum(e){const t=this.centerWorld,s=this.radiusWorld;for(let i=0;i<6;i++)if(e[i].dotCoordinate(t)<=-s)return!1;return!0}isCenterInFrustum(e){const t=this.centerWorld;for(let s=0;s<6;s++)if(e[s].dotCoordinate(t)<0)return!1;return!0}intersectsPoint(e){const t=U.DistanceSquared(this.centerWorld,e);return!(this.radiusWorld*this.radiusWorld<t)}static Intersects(e,t){const s=U.DistanceSquared(e.centerWorld,t.centerWorld),i=e.radiusWorld+t.radiusWorld;return!(i*i<s)}static CreateFromCenterAndRadius(e,t,s){this._TmpVector3[0].copyFrom(e),this._TmpVector3[1].copyFromFloats(0,0,t),this._TmpVector3[2].copyFrom(e),this._TmpVector3[0].addInPlace(this._TmpVector3[1]),this._TmpVector3[2].subtractInPlace(this._TmpVector3[1]);const i=new hs(this._TmpVector3[0],this._TmpVector3[2]);return i._worldMatrix=s||V.Identity(),i}}hs._TmpVector3=y(3,U.Zero);const ls={min:0,max:0},cs={min:0,max:0},us=(e,t,s)=>{const i=U.Dot(t.centerWorld,e),r=Math.abs(U.Dot(t.directions[0],e))*t.extendSize.x+Math.abs(U.Dot(t.directions[1],e))*t.extendSize.y+Math.abs(U.Dot(t.directions[2],e))*t.extendSize.z;s.min=i-r,s.max=i+r},ds=(e,t,s)=>(us(e,t,ls),us(e,s,cs),!(ls.min>cs.max||cs.min>ls.max));class _s{constructor(e,t,s){this._isLocked=!1,this.boundingBox=new os(e,t,s),this.boundingSphere=new hs(e,t,s)}reConstruct(e,t,s){this.boundingBox.reConstruct(e,t,s),this.boundingSphere.reConstruct(e,t,s)}get minimum(){return this.boundingBox.minimum}get maximum(){return this.boundingBox.maximum}get isLocked(){return this._isLocked}set isLocked(e){this._isLocked=e}update(e){this._isLocked||(this.boundingBox._update(e),this.boundingSphere._update(e))}centerOn(e,t){const s=_s._TmpVector3[0].copyFrom(e).subtractInPlace(t),i=_s._TmpVector3[1].copyFrom(e).addInPlace(t);return this.boundingBox.reConstruct(s,i,this.boundingBox.getWorldMatrix()),this.boundingSphere.reConstruct(s,i,this.boundingBox.getWorldMatrix()),this}encapsulate(e){const t=U.Minimize(this.minimum,e),s=U.Maximize(this.maximum,e);return this.reConstruct(t,s,this.boundingBox.getWorldMatrix()),this}encapsulateBoundingInfo(e){const t=z.Matrix[0];this.boundingBox.getWorldMatrix().invertToRef(t);const s=z.Vector3[0];return U.TransformCoordinatesToRef(e.boundingBox.minimumWorld,t,s),this.encapsulate(s),U.TransformCoordinatesToRef(e.boundingBox.maximumWorld,t,s),this.encapsulate(s),this}scale(e){return this.boundingBox.scale(e),this.boundingSphere.scale(e),this}isInFrustum(e,t=Ze.MESHES_CULLINGSTRATEGY_STANDARD){if((t===Ze.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION||t===Ze.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY)&&this.boundingSphere.isCenterInFrustum(e))return!0;if(!this.boundingSphere.isInFrustum(e))return!1;return!(t!==Ze.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY&&t!==Ze.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY)||this.boundingBox.isInFrustum(e)}get diagonalLength(){const e=this.boundingBox;return e.maximumWorld.subtractToRef(e.minimumWorld,_s._TmpVector3[0]).length()}isCompletelyInFrustum(e){return this.boundingBox.isCompletelyInFrustum(e)}_checkCollision(e){return e._canDoCollision(this.boundingSphere.centerWorld,this.boundingSphere.radiusWorld,this.boundingBox.minimumWorld,this.boundingBox.maximumWorld)}intersectsPoint(e){return!!this.boundingSphere.centerWorld&&(!!this.boundingSphere.intersectsPoint(e)&&!!this.boundingBox.intersectsPoint(e))}intersects(e,t){if(!hs.Intersects(this.boundingSphere,e.boundingSphere))return!1;if(!os.Intersects(this.boundingBox,e.boundingBox))return!1;if(!t)return!0;const s=this.boundingBox,i=e.boundingBox;return!!ds(s.directions[0],s,i)&&(!!ds(s.directions[1],s,i)&&(!!ds(s.directions[2],s,i)&&(!!ds(i.directions[0],s,i)&&(!!ds(i.directions[1],s,i)&&(!!ds(i.directions[2],s,i)&&(!!ds(U.Cross(s.directions[0],i.directions[0]),s,i)&&(!!ds(U.Cross(s.directions[0],i.directions[1]),s,i)&&(!!ds(U.Cross(s.directions[0],i.directions[2]),s,i)&&(!!ds(U.Cross(s.directions[1],i.directions[0]),s,i)&&(!!ds(U.Cross(s.directions[1],i.directions[1]),s,i)&&(!!ds(U.Cross(s.directions[1],i.directions[2]),s,i)&&(!!ds(U.Cross(s.directions[2],i.directions[0]),s,i)&&(!!ds(U.Cross(s.directions[2],i.directions[1]),s,i)&&!!ds(U.Cross(s.directions[2],i.directions[2]),s,i))))))))))))))}}_s._TmpVector3=y(2,U.Zero);class fs{static extractMinAndMaxIndexed(e,t,s,i,r,n){for(let a=s;a<s+i;a++){const s=3*t[a],i=e[s],o=e[s+1],h=e[s+2];r.minimizeInPlaceFromFloats(i,o,h),n.maximizeInPlaceFromFloats(i,o,h)}}static extractMinAndMax(e,t,s,i,r,n){for(let a=t,o=t*i;a<t+s;a++,o+=i){const t=e[o],s=e[o+1],i=e[o+2];r.minimizeInPlaceFromFloats(t,s,i),n.maximizeInPlaceFromFloats(t,s,i)}}}function ps(e,t,s,i=null,r){const n=new U(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new U(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return r||(r=3),fs.extractMinAndMax(e,t,s,r,n,a),i&&(n.x-=n.x*i.x+i.y,n.y-=n.y*i.x+i.y,n.z-=n.z*i.x+i.y,a.x+=a.x*i.x+i.y,a.y+=a.y*i.x+i.y,a.z+=a.z*i.x+i.y),{minimum:n,maximum:a}}e([f.filter(((...[e,t])=>!Array.isArray(e)&&!Array.isArray(t)))],fs,"extractMinAndMaxIndexed",null),e([f.filter(((...[e])=>!Array.isArray(e)))],fs,"extractMinAndMax",null);class ms{static GetEffect(e){return void 0===e.getPipelineContext?e.effect:e}constructor(e,t=!0){this._wasPreviouslyReady=!1,this._forceRebindOnNextCall=!0,this._wasPreviouslyUsingInstances=null,this.effect=null,this.defines=null,this.drawContext=e.createDrawContext(),t&&(this.materialContext=e.createMaterialContext())}setEffect(e,t,s=!0){this.effect=e,void 0!==t&&(this.defines=t),s&&this.drawContext?.reset()}dispose(){this.drawContext?.dispose()}}class gs{get materialDefines(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.defines:this._getDrawWrapper()?.defines}set materialDefines(e){(this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)).defines=e}_getDrawWrapper(e,t=!1){e=e??this._engine.currentRenderPassId;let s=this._drawWrappers[e];return!s&&t&&(this._drawWrappers[e]=s=new ms(this._mesh.getScene().getEngine())),s}_removeDrawWrapper(e,t=!0){t&&this._drawWrappers[e]?.dispose(),this._drawWrappers[e]=void 0}get effect(){return this._mainDrawWrapperOverride?this._mainDrawWrapperOverride.effect:this._getDrawWrapper()?.effect??null}get _drawWrapper(){return this._mainDrawWrapperOverride??this._getDrawWrapper(void 0,!0)}get _drawWrapperOverride(){return this._mainDrawWrapperOverride}_setMainDrawWrapperOverride(e){this._mainDrawWrapperOverride=e}setEffect(e,t=null,s,i=!0){const r=this._drawWrapper;r.setEffect(e,t,i),void 0!==s&&(r.materialContext=s),e||(r.defines=null,r.materialContext=void 0)}resetDrawCache(e){if(this._drawWrappers){if(void 0!==e)return void this._removeDrawWrapper(e);for(const e of this._drawWrappers)e?.dispose()}this._drawWrappers=[]}static AddToMesh(e,t,s,i,r,n,a,o=!0){return new gs(e,t,s,i,r,n,a,o)}constructor(e,t,s,i,r,n,a,o=!0,h=!0){this.materialIndex=e,this.verticesStart=t,this.verticesCount=s,this.indexStart=i,this.indexCount=r,this._mainDrawWrapperOverride=null,this._linesIndexCount=0,this._linesIndexBuffer=null,this._lastColliderWorldVertices=null,this._lastColliderTransformMatrix=null,this._wasDispatched=!1,this._renderId=0,this._alphaIndex=0,this._distanceToCamera=0,this._currentMaterial=null,this._mesh=n,this._renderingMesh=a||n,h&&n.subMeshes.push(this),this._engine=this._mesh.getScene().getEngine(),this.resetDrawCache(),this._trianglePlanes=[],this._id=n.subMeshes.length-1,o&&(this.refreshBoundingInfo(),n.computeWorldMatrix(!0))}get IsGlobal(){return 0===this.verticesStart&&this.verticesCount===this._mesh.getTotalVertices()&&0===this.indexStart&&this.indexCount===this._mesh.getTotalIndices()}getBoundingInfo(){return this.IsGlobal||this._mesh.hasThinInstances?this._mesh.getBoundingInfo():this._boundingInfo}setBoundingInfo(e){return this._boundingInfo=e,this}getMesh(){return this._mesh}getRenderingMesh(){return this._renderingMesh}getReplacementMesh(){return this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null}getEffectiveMesh(){const e=this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:null;return e||this._renderingMesh}getMaterial(e=!0){const t=this._renderingMesh.getMaterialForRenderPass(this._engine.currentRenderPassId)??this._renderingMesh.material;if(!t)return e?this._mesh.getScene().defaultMaterial:null;if(this._isMultiMaterial(t)){const e=t.getSubMaterial(this.materialIndex);return this._currentMaterial!==e&&(this._currentMaterial=e,this.resetDrawCache()),e}return t}_isMultiMaterial(e){return void 0!==e.getSubMaterial}refreshBoundingInfo(e=null){if(this._lastColliderWorldVertices=null,this.IsGlobal||!this._renderingMesh||!this._renderingMesh.geometry)return this;if(e||(e=this._renderingMesh.getVerticesData(ns.PositionKind)),!e)return this._boundingInfo=this._mesh.getBoundingInfo(),this;const t=this._renderingMesh.getIndices();let s;if(0===this.indexStart&&this.indexCount===t.length){const e=this._renderingMesh.getBoundingInfo();s={minimum:e.minimum.clone(),maximum:e.maximum.clone()}}else s=function(e,t,s,i,r=null){const n=new U(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),a=new U(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return fs.extractMinAndMaxIndexed(e,t,s,i,n,a),r&&(n.x-=n.x*r.x+r.y,n.y-=n.y*r.x+r.y,n.z-=n.z*r.x+r.y,a.x+=a.x*r.x+r.y,a.y+=a.y*r.x+r.y,a.z+=a.z*r.x+r.y),{minimum:n,maximum:a}}(e,t,this.indexStart,this.indexCount,this._renderingMesh.geometry.boundingBias);return this._boundingInfo?this._boundingInfo.reConstruct(s.minimum,s.maximum):this._boundingInfo=new _s(s.minimum,s.maximum),this}_checkCollision(e){return this.getBoundingInfo()._checkCollision(e)}updateBoundingInfo(e){let t=this.getBoundingInfo();return t||(this.refreshBoundingInfo(),t=this.getBoundingInfo()),t&&t.update(e),this}isInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isInFrustum(e,this._mesh.cullingStrategy)}isCompletelyInFrustum(e){const t=this.getBoundingInfo();return!!t&&t.isCompletelyInFrustum(e)}render(e){return this._renderingMesh.render(this,e,this._mesh._internalAbstractMeshDataInfo._actAsRegularMesh?this._mesh:void 0),this}_getLinesIndexBuffer(e,t){if(!this._linesIndexBuffer){const s=[];for(let t=this.indexStart;t<this.indexStart+this.indexCount;t+=3)s.push(e[t],e[t+1],e[t+1],e[t+2],e[t+2],e[t]);this._linesIndexBuffer=t.createIndexBuffer(s),this._linesIndexCount=s.length}return this._linesIndexBuffer}canIntersects(e){const t=this.getBoundingInfo();return!!t&&e.intersectsBox(t.boundingBox)}intersects(e,t,s,i,r){const n=this.getMaterial();if(!n)return null;let a=3,o=!1;switch(n.fillMode){case Ze.MATERIAL_PointListDrawMode:case Ze.MATERIAL_LineLoopDrawMode:case Ze.MATERIAL_LineStripDrawMode:case Ze.MATERIAL_TriangleFanDrawMode:return null;case Ze.MATERIAL_TriangleStripDrawMode:a=1,o=!0}return n.fillMode===Ze.MATERIAL_LineListDrawMode?s.length?this._intersectLines(e,t,s,this._mesh.intersectionThreshold,i):this._intersectUnIndexedLines(e,t,s,this._mesh.intersectionThreshold,i):!s.length&&this._mesh._unIndexed?this._intersectUnIndexedTriangles(e,t,s,i,r):this._intersectTriangles(e,t,s,a,o,i,r)}_intersectLines(e,t,s,i,r){let n=null;for(let a=this.indexStart;a<this.indexStart+this.indexCount;a+=2){const o=t[s[a]],h=t[s[a+1]],l=e.intersectionSegment(o,h,i);if(!(l<0)&&((r||!n||l<n.distance)&&(n=new as(null,null,l),n.faceId=a/2,r)))break}return n}_intersectUnIndexedLines(e,t,s,i,r){let n=null;for(let s=this.verticesStart;s<this.verticesStart+this.verticesCount;s+=2){const a=t[s],o=t[s+1],h=e.intersectionSegment(a,o,i);if(!(h<0)&&((r||!n||h<n.distance)&&(n=new as(null,null,h),n.faceId=s/2,r)))break}return n}_intersectTriangles(e,t,s,i,r,n,a){let o=null,h=-1;for(let l=this.indexStart;l<this.indexStart+this.indexCount-(3-i);l+=i){h++;const i=s[l],c=s[l+1],u=s[l+2];if(r&&4294967295===u){l+=2;continue}const d=t[i],_=t[c],f=t[u];if(!d||!_||!f)continue;if(a&&!a(d,_,f,e,i,c,u))continue;const p=e.intersectsTriangle(d,_,f);if(p){if(p.distance<0)continue;if((n||!o||p.distance<o.distance)&&(o=p,o.faceId=h,n))break}}return o}_intersectUnIndexedTriangles(e,t,s,i,r){let n=null;for(let s=this.verticesStart;s<this.verticesStart+this.verticesCount;s+=3){const a=t[s],o=t[s+1],h=t[s+2];if(r&&!r(a,o,h,e,-1,-1,-1))continue;const l=e.intersectsTriangle(a,o,h);if(l){if(l.distance<0)continue;if((i||!n||l.distance<n.distance)&&(n=l,n.faceId=s/3,i))break}}return n}_rebuild(){this._linesIndexBuffer&&(this._linesIndexBuffer=null)}clone(e,t){const s=new gs(this.materialIndex,this.verticesStart,this.verticesCount,this.indexStart,this.indexCount,e,t,!1);if(!this.IsGlobal){const e=this.getBoundingInfo();if(!e)return s;s._boundingInfo=new _s(e.minimum,e.maximum)}return s}dispose(){this._linesIndexBuffer&&(this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer),this._linesIndexBuffer=null);const e=this._mesh.subMeshes.indexOf(this);this._mesh.subMeshes.splice(e,1),this.resetDrawCache()}getClassName(){return"SubMesh"}static CreateFromIndices(e,t,s,i,r,n=!0){let a=Number.MAX_VALUE,o=-Number.MAX_VALUE;const h=(r||i).getIndices();for(let e=t;e<t+s;e++){const t=h[e];t<a&&(a=t),t>o&&(o=t)}return new gs(e,a,o-a+1,t,s,i,r,n)}}class Ts{}class Es{constructor(){var e;this.uniqueId=0,this.metadata={},this._applyTo=(e=this._applyToCoroutine.bind(this),(...t)=>jt(e(...t))),this.uniqueId=Es._UniqueIDGenerator,Es._UniqueIDGenerator++}set(e,t){switch(e.length||ue.Warn(`Setting vertex data kind '${t}' with an empty array`),t){case ns.PositionKind:this.positions=e;break;case ns.NormalKind:this.normals=e;break;case ns.TangentKind:this.tangents=e;break;case ns.UVKind:this.uvs=e;break;case ns.UV2Kind:this.uvs2=e;break;case ns.UV3Kind:this.uvs3=e;break;case ns.UV4Kind:this.uvs4=e;break;case ns.UV5Kind:this.uvs5=e;break;case ns.UV6Kind:this.uvs6=e;break;case ns.ColorKind:this.colors=e;break;case ns.MatricesIndicesKind:this.matricesIndices=e;break;case ns.MatricesWeightsKind:this.matricesWeights=e;break;case ns.MatricesIndicesExtraKind:this.matricesIndicesExtra=e;break;case ns.MatricesWeightsExtraKind:this.matricesWeightsExtra=e}}applyToMesh(e,t){return this._applyTo(e,t,!1),this}applyToGeometry(e,t){return this._applyTo(e,t,!1),this}updateMesh(e){return this._update(e),this}updateGeometry(e){return this._update(e),this}*_applyToCoroutine(e,t=!1,s){if(this.positions&&(e.setVerticesData(ns.PositionKind,this.positions,t),s&&(yield)),this.normals&&(e.setVerticesData(ns.NormalKind,this.normals,t),s&&(yield)),this.tangents&&(e.setVerticesData(ns.TangentKind,this.tangents,t),s&&(yield)),this.uvs&&(e.setVerticesData(ns.UVKind,this.uvs,t),s&&(yield)),this.uvs2&&(e.setVerticesData(ns.UV2Kind,this.uvs2,t),s&&(yield)),this.uvs3&&(e.setVerticesData(ns.UV3Kind,this.uvs3,t),s&&(yield)),this.uvs4&&(e.setVerticesData(ns.UV4Kind,this.uvs4,t),s&&(yield)),this.uvs5&&(e.setVerticesData(ns.UV5Kind,this.uvs5,t),s&&(yield)),this.uvs6&&(e.setVerticesData(ns.UV6Kind,this.uvs6,t),s&&(yield)),this.colors&&(e.setVerticesData(ns.ColorKind,this.colors,t),this.hasVertexAlpha&&void 0!==e.hasVertexAlpha&&(e.hasVertexAlpha=!0),s&&(yield)),this.matricesIndices&&(e.setVerticesData(ns.MatricesIndicesKind,this.matricesIndices,t),s&&(yield)),this.matricesWeights&&(e.setVerticesData(ns.MatricesWeightsKind,this.matricesWeights,t),s&&(yield)),this.matricesIndicesExtra&&(e.setVerticesData(ns.MatricesIndicesExtraKind,this.matricesIndicesExtra,t),s&&(yield)),this.matricesWeightsExtra&&(e.setVerticesData(ns.MatricesWeightsExtraKind,this.matricesWeightsExtra,t),s&&(yield)),this.indices?(e.setIndices(this.indices,null,t),s&&(yield)):e.setIndices([],null),e.subMeshes&&this.materialInfos&&this.materialInfos.length>1){const t=e;t.subMeshes=[];for(const e of this.materialInfos)new gs(e.materialIndex,e.verticesStart,e.verticesCount,e.indexStart,e.indexCount,t)}return this}_update(e,t,s){return this.positions&&e.updateVerticesData(ns.PositionKind,this.positions,t,s),this.normals&&e.updateVerticesData(ns.NormalKind,this.normals,t,s),this.tangents&&e.updateVerticesData(ns.TangentKind,this.tangents,t,s),this.uvs&&e.updateVerticesData(ns.UVKind,this.uvs,t,s),this.uvs2&&e.updateVerticesData(ns.UV2Kind,this.uvs2,t,s),this.uvs3&&e.updateVerticesData(ns.UV3Kind,this.uvs3,t,s),this.uvs4&&e.updateVerticesData(ns.UV4Kind,this.uvs4,t,s),this.uvs5&&e.updateVerticesData(ns.UV5Kind,this.uvs5,t,s),this.uvs6&&e.updateVerticesData(ns.UV6Kind,this.uvs6,t,s),this.colors&&e.updateVerticesData(ns.ColorKind,this.colors,t,s),this.matricesIndices&&e.updateVerticesData(ns.MatricesIndicesKind,this.matricesIndices,t,s),this.matricesWeights&&e.updateVerticesData(ns.MatricesWeightsKind,this.matricesWeights,t,s),this.matricesIndicesExtra&&e.updateVerticesData(ns.MatricesIndicesExtraKind,this.matricesIndicesExtra,t,s),this.matricesWeightsExtra&&e.updateVerticesData(ns.MatricesWeightsExtraKind,this.matricesWeightsExtra,t,s),this.indices&&e.setIndices(this.indices,null),this}static _TransformVector3Coordinates(e,t,s=0,i=e.length){const r=z.Vector3[0],n=z.Vector3[1];for(let a=s;a<s+i;a+=3)U.FromArrayToRef(e,a,r),U.TransformCoordinatesToRef(r,t,n),e[a]=n.x,e[a+1]=n.y,e[a+2]=n.z}static _TransformVector3Normals(e,t,s=0,i=e.length){const r=z.Vector3[0],n=z.Vector3[1];for(let a=s;a<s+i;a+=3)U.FromArrayToRef(e,a,r),U.TransformNormalToRef(r,t,n),e[a]=n.x,e[a+1]=n.y,e[a+2]=n.z}static _TransformVector4Normals(e,t,s=0,i=e.length){const r=z.Vector4[0],n=z.Vector4[1];for(let a=s;a<s+i;a+=4)k.FromArrayToRef(e,a,r),k.TransformNormalToRef(r,t,n),e[a]=n.x,e[a+1]=n.y,e[a+2]=n.z,e[a+3]=n.w}static _FlipFaces(e,t=0,s=e.length){for(let i=t;i<t+s;i+=3){const t=e[i+1];e[i+1]=e[i+2],e[i+2]=t}}transform(e){const t=e.determinant()<0;return this.positions&&Es._TransformVector3Coordinates(this.positions,e),this.normals&&Es._TransformVector3Normals(this.normals,e),this.tangents&&Es._TransformVector4Normals(this.tangents,e),t&&this.indices&&Es._FlipFaces(this.indices),this}splitBasedOnMaterialID(){if(!this.materialInfos||this.materialInfos.length<2)return[this];const e=[];for(const t of this.materialInfos){const s=new Es;if(this.positions&&(s.positions=this.positions.slice(3*t.verticesStart,3*(t.verticesCount+t.verticesStart))),this.normals&&(s.normals=this.normals.slice(3*t.verticesStart,3*(t.verticesCount+t.verticesStart))),this.tangents&&(s.tangents=this.tangents.slice(4*t.verticesStart,4*(t.verticesCount+t.verticesStart))),this.colors&&(s.colors=this.colors.slice(4*t.verticesStart,4*(t.verticesCount+t.verticesStart))),this.uvs&&(s.uvs=this.uvs.slice(2*t.verticesStart,2*(t.verticesCount+t.verticesStart))),this.uvs2&&(s.uvs2=this.uvs2.slice(2*t.verticesStart,2*(t.verticesCount+t.verticesStart))),this.uvs3&&(s.uvs3=this.uvs3.slice(2*t.verticesStart,2*(t.verticesCount+t.verticesStart))),this.uvs4&&(s.uvs4=this.uvs4.slice(2*t.verticesStart,2*(t.verticesCount+t.verticesStart))),this.uvs5&&(s.uvs5=this.uvs5.slice(2*t.verticesStart,2*(t.verticesCount+t.verticesStart))),this.uvs6&&(s.uvs6=this.uvs6.slice(2*t.verticesStart,2*(t.verticesCount+t.verticesStart))),this.matricesIndices&&(s.matricesIndices=this.matricesIndices.slice(4*t.verticesStart,4*(t.verticesCount+t.verticesStart))),this.matricesIndicesExtra&&(s.matricesIndicesExtra=this.matricesIndicesExtra.slice(4*t.verticesStart,4*(t.verticesCount+t.verticesStart))),this.matricesWeights&&(s.matricesWeights=this.matricesWeights.slice(4*t.verticesStart,4*(t.verticesCount+t.verticesStart))),this.matricesWeightsExtra&&(s.matricesWeightsExtra=this.matricesWeightsExtra.slice(4*t.verticesStart,4*(t.verticesCount+t.verticesStart))),this.indices){s.indices=[];for(let e=t.indexStart;e<t.indexStart+t.indexCount;e++)s.indices.push(this.indices[e]-t.verticesStart)}const i=new Ts;i.indexStart=0,i.indexCount=s.indices?s.indices.length:0,i.materialIndex=t.materialIndex,i.verticesStart=0,i.verticesCount=(s.positions?s.positions.length:0)/3,s.materialInfos=[i],e.push(s)}return e}merge(e,t=!1,s=!1,i=!1,r=!1){const n=Array.isArray(e)?e.map((e=>({vertexData:e}))):[{vertexData:e}];return jt(this._mergeCoroutine(void 0,n,t,!1,s,i,r))}*_mergeCoroutine(e,t,s=!1,i,r,n=!1,a=!1){this._validate();let o=t.map((e=>e.vertexData)),h=this;if(a)for(const e of o)e&&(e._validate(),!this.normals&&e.normals&&(this.normals=new Float32Array(this.positions.length)),!this.tangents&&e.tangents&&(this.tangents=new Float32Array(this.positions.length/3*4)),!this.uvs&&e.uvs&&(this.uvs=new Float32Array(this.positions.length/3*2)),!this.uvs2&&e.uvs2&&(this.uvs2=new Float32Array(this.positions.length/3*2)),!this.uvs3&&e.uvs3&&(this.uvs3=new Float32Array(this.positions.length/3*2)),!this.uvs4&&e.uvs4&&(this.uvs4=new Float32Array(this.positions.length/3*2)),!this.uvs5&&e.uvs5&&(this.uvs5=new Float32Array(this.positions.length/3*2)),!this.uvs6&&e.uvs6&&(this.uvs6=new Float32Array(this.positions.length/3*2)),!this.colors&&e.colors&&(this.colors=new Float32Array(this.positions.length/3*4),this.colors.fill(1)),!this.matricesIndices&&e.matricesIndices&&(this.matricesIndices=new Float32Array(this.positions.length/3*4)),!this.matricesWeights&&e.matricesWeights&&(this.matricesWeights=new Float32Array(this.positions.length/3*4)),!this.matricesIndicesExtra&&e.matricesIndicesExtra&&(this.matricesIndicesExtra=new Float32Array(this.positions.length/3*4)),!this.matricesWeightsExtra&&e.matricesWeightsExtra&&(this.matricesWeightsExtra=new Float32Array(this.positions.length/3*4)));for(const e of o)if(e)if(a)this.normals&&!e.normals&&(e.normals=new Float32Array(e.positions.length)),this.tangents&&!e.tangents&&(e.tangents=new Float32Array(e.positions.length/3*4)),this.uvs&&!e.uvs&&(e.uvs=new Float32Array(e.positions.length/3*2)),this.uvs2&&!e.uvs2&&(e.uvs2=new Float32Array(e.positions.length/3*2)),this.uvs3&&!e.uvs3&&(e.uvs3=new Float32Array(e.positions.length/3*2)),this.uvs4&&!e.uvs4&&(e.uvs4=new Float32Array(e.positions.length/3*2)),this.uvs5&&!e.uvs5&&(e.uvs5=new Float32Array(e.positions.length/3*2)),this.uvs6&&!e.uvs6&&(e.uvs6=new Float32Array(e.positions.length/3*2)),this.colors&&!e.colors&&(e.colors=new Float32Array(e.positions.length/3*4),e.colors.fill(1)),this.matricesIndices&&!e.matricesIndices&&(e.matricesIndices=new Float32Array(e.positions.length/3*4)),this.matricesWeights&&!e.matricesWeights&&(e.matricesWeights=new Float32Array(e.positions.length/3*4)),this.matricesIndicesExtra&&!e.matricesIndicesExtra&&(e.matricesIndicesExtra=new Float32Array(e.positions.length/3*4)),this.matricesWeightsExtra&&!e.matricesWeightsExtra&&(e.matricesWeightsExtra=new Float32Array(e.positions.length/3*4));else if(e._validate(),!this.normals!=!e.normals||!this.tangents!=!e.tangents||!this.uvs!=!e.uvs||!this.uvs2!=!e.uvs2||!this.uvs3!=!e.uvs3||!this.uvs4!=!e.uvs4||!this.uvs5!=!e.uvs5||!this.uvs6!=!e.uvs6||!this.colors!=!e.colors||!this.matricesIndices!=!e.matricesIndices||!this.matricesWeights!=!e.matricesWeights||!this.matricesIndicesExtra!=!e.matricesIndicesExtra||!this.matricesWeightsExtra!=!e.matricesWeightsExtra)throw new Error("Cannot merge vertex data that do not have the same set of attributes");if(n){let s=0,i=0,r=0;const n=[];let a=null;const l=[];for(const t of this.splitBasedOnMaterialID())l.push({vertexData:t,transform:e});for(const e of t)if(e.vertexData)for(const t of e.vertexData.splitBasedOnMaterialID())l.push({vertexData:t,transform:e.transform});l.sort(((e,t)=>{const s=e.vertexData.materialInfos?e.vertexData.materialInfos[0].materialIndex:0,i=t.vertexData.materialInfos?t.vertexData.materialInfos[0].materialIndex:0;return s>i?1:s===i?0:-1}));for(const e of l){const t=e.vertexData;if(s=t.materialInfos?t.materialInfos[0].materialIndex:0,a&&a.materialIndex===s)a.indexCount+=t.indices.length,a.verticesCount+=t.positions.length/3;else{const e=new Ts;e.materialIndex=s,e.indexStart=i,e.indexCount=t.indices.length,e.verticesStart=r,e.verticesCount=t.positions.length/3,n.push(e),a=e}i+=t.indices.length,r+=t.positions.length/3}const c=l.splice(0,1)[0];h=c.vertexData,e=c.transform,o=l.map((e=>e.vertexData)),t=l,this.materialInfos=n}const l=o.reduce(((e,t)=>e+(t.indices?.length??0)),h.indices?.length??0);let c=r||o.some((e=>e.indices===h.indices))?h.indices?.slice():h.indices;if(l>0){let r=c?.length??0;if(c||(c=new Array(l)),c.length!==l){if(Array.isArray(c))c.length=l;else{const e=s||c instanceof Uint32Array?new Uint32Array(l):new Uint16Array(l);e.set(c),c=e}e&&e.determinant()<0&&Es._FlipFaces(c,0,r)}let n=h.positions?h.positions.length/3:0;for(const{vertexData:e,transform:s}of t)if(e.indices){for(let t=0;t<e.indices.length;t++)c[r+t]=e.indices[t]+n;s&&s.determinant()<0&&Es._FlipFaces(c,r,e.indices.length),n+=e.positions.length/3,r+=e.indices.length,i&&(yield)}}return this.indices=c,this.positions=Es._MergeElement(ns.PositionKind,h.positions,e,t.map((e=>[e.vertexData.positions,e.transform]))),i&&(yield),h.normals&&(this.normals=Es._MergeElement(ns.NormalKind,h.normals,e,t.map((e=>[e.vertexData.normals,e.transform]))),i&&(yield)),h.tangents&&(this.tangents=Es._MergeElement(ns.TangentKind,h.tangents,e,t.map((e=>[e.vertexData.tangents,e.transform]))),i&&(yield)),h.uvs&&(this.uvs=Es._MergeElement(ns.UVKind,h.uvs,e,t.map((e=>[e.vertexData.uvs,e.transform]))),i&&(yield)),h.uvs2&&(this.uvs2=Es._MergeElement(ns.UV2Kind,h.uvs2,e,t.map((e=>[e.vertexData.uvs2,e.transform]))),i&&(yield)),h.uvs3&&(this.uvs3=Es._MergeElement(ns.UV3Kind,h.uvs3,e,t.map((e=>[e.vertexData.uvs3,e.transform]))),i&&(yield)),h.uvs4&&(this.uvs4=Es._MergeElement(ns.UV4Kind,h.uvs4,e,t.map((e=>[e.vertexData.uvs4,e.transform]))),i&&(yield)),h.uvs5&&(this.uvs5=Es._MergeElement(ns.UV5Kind,h.uvs5,e,t.map((e=>[e.vertexData.uvs5,e.transform]))),i&&(yield)),h.uvs6&&(this.uvs6=Es._MergeElement(ns.UV6Kind,h.uvs6,e,t.map((e=>[e.vertexData.uvs6,e.transform]))),i&&(yield)),h.colors&&(this.colors=Es._MergeElement(ns.ColorKind,h.colors,e,t.map((e=>[e.vertexData.colors,e.transform]))),(void 0!==h.hasVertexAlpha||t.some((e=>void 0!==e.vertexData.hasVertexAlpha)))&&(this.hasVertexAlpha=h.hasVertexAlpha||t.some((e=>e.vertexData.hasVertexAlpha))),i&&(yield)),h.matricesIndices&&(this.matricesIndices=Es._MergeElement(ns.MatricesIndicesKind,h.matricesIndices,e,t.map((e=>[e.vertexData.matricesIndices,e.transform]))),i&&(yield)),h.matricesWeights&&(this.matricesWeights=Es._MergeElement(ns.MatricesWeightsKind,h.matricesWeights,e,t.map((e=>[e.vertexData.matricesWeights,e.transform]))),i&&(yield)),h.matricesIndicesExtra&&(this.matricesIndicesExtra=Es._MergeElement(ns.MatricesIndicesExtraKind,h.matricesIndicesExtra,e,t.map((e=>[e.vertexData.matricesIndicesExtra,e.transform]))),i&&(yield)),h.matricesWeightsExtra&&(this.matricesWeightsExtra=Es._MergeElement(ns.MatricesWeightsExtraKind,h.matricesWeightsExtra,e,t.map((e=>[e.vertexData.matricesWeightsExtra,e.transform])))),this}static _MergeElement(e,t,s,i){const r=i.filter((e=>null!==e[0]&&void 0!==e[0]));if(!t&&0==r.length)return t;if(!t)return this._MergeElement(e,r[0][0],r[0][1],r.slice(1));const n=r.reduce(((e,t)=>e+t[0].length),t.length),a=e===ns.PositionKind?Es._TransformVector3Coordinates:e===ns.NormalKind?Es._TransformVector3Normals:e===ns.TangentKind?Es._TransformVector4Normals:()=>{};if(t instanceof Float32Array){const e=new Float32Array(n);e.set(t),s&&a(e,s,0,t.length);let i=t.length;for(const[t,s]of r)e.set(t,i),s&&a(e,s,i,t.length),i+=t.length;return e}{const e=new Array(n);for(let s=0;s<t.length;s++)e[s]=t[s];s&&a(e,s,0,t.length);let i=t.length;for(const[t,s]of r){for(let s=0;s<t.length;s++)e[i+s]=t[s];s&&a(e,s,i,t.length),i+=t.length}return e}}_validate(){if(!this.positions)throw new Ee("Positions are required",Te.MeshInvalidPositionsError);const e=(e,t)=>{const s=ns.DeduceStride(e);if(t.length%s!=0)throw new Error("The "+e+"s array count must be a multiple of "+s);return t.length/s},t=e(ns.PositionKind,this.positions),s=(s,i)=>{const r=e(s,i);if(r!==t)throw new Error("The "+s+"s element count ("+r+") does not match the positions count ("+t+")")};this.normals&&s(ns.NormalKind,this.normals),this.tangents&&s(ns.TangentKind,this.tangents),this.uvs&&s(ns.UVKind,this.uvs),this.uvs2&&s(ns.UV2Kind,this.uvs2),this.uvs3&&s(ns.UV3Kind,this.uvs3),this.uvs4&&s(ns.UV4Kind,this.uvs4),this.uvs5&&s(ns.UV5Kind,this.uvs5),this.uvs6&&s(ns.UV6Kind,this.uvs6),this.colors&&s(ns.ColorKind,this.colors),this.matricesIndices&&s(ns.MatricesIndicesKind,this.matricesIndices),this.matricesWeights&&s(ns.MatricesWeightsKind,this.matricesWeights),this.matricesIndicesExtra&&s(ns.MatricesIndicesExtraKind,this.matricesIndicesExtra),this.matricesWeightsExtra&&s(ns.MatricesWeightsExtraKind,this.matricesWeightsExtra)}clone(){const e=this.serialize();return Es.Parse(e)}serialize(){const e={};if(this.positions&&(e.positions=Array.from(this.positions)),this.normals&&(e.normals=Array.from(this.normals)),this.tangents&&(e.tangents=Array.from(this.tangents)),this.uvs&&(e.uvs=Array.from(this.uvs)),this.uvs2&&(e.uvs2=Array.from(this.uvs2)),this.uvs3&&(e.uvs3=Array.from(this.uvs3)),this.uvs4&&(e.uvs4=Array.from(this.uvs4)),this.uvs5&&(e.uvs5=Array.from(this.uvs5)),this.uvs6&&(e.uvs6=Array.from(this.uvs6)),this.colors&&(e.colors=Array.from(this.colors),e.hasVertexAlpha=this.hasVertexAlpha),this.matricesIndices&&(e.matricesIndices=Array.from(this.matricesIndices),e.matricesIndices._isExpanded=!0),this.matricesWeights&&(e.matricesWeights=Array.from(this.matricesWeights)),this.matricesIndicesExtra&&(e.matricesIndicesExtra=Array.from(this.matricesIndicesExtra),e.matricesIndicesExtra._isExpanded=!0),this.matricesWeightsExtra&&(e.matricesWeightsExtra=Array.from(this.matricesWeightsExtra)),e.indices=Array.from(this.indices),this.materialInfos){e.materialInfos=[];for(const t of this.materialInfos){const s={indexStart:t.indexStart,indexCount:t.indexCount,materialIndex:t.materialIndex,verticesStart:t.verticesStart,verticesCount:t.verticesCount};e.materialInfos.push(s)}}return e}static ExtractFromMesh(e,t,s){return Es._ExtractFrom(e,t,s)}static ExtractFromGeometry(e,t,s){return Es._ExtractFrom(e,t,s)}static _ExtractFrom(e,t,s){const i=new Es;if(e.isVerticesDataPresent(ns.PositionKind)&&(i.positions=e.getVerticesData(ns.PositionKind,t,s)),e.isVerticesDataPresent(ns.NormalKind)&&(i.normals=e.getVerticesData(ns.NormalKind,t,s)),e.isVerticesDataPresent(ns.TangentKind)&&(i.tangents=e.getVerticesData(ns.TangentKind,t,s)),e.isVerticesDataPresent(ns.UVKind)&&(i.uvs=e.getVerticesData(ns.UVKind,t,s)),e.isVerticesDataPresent(ns.UV2Kind)&&(i.uvs2=e.getVerticesData(ns.UV2Kind,t,s)),e.isVerticesDataPresent(ns.UV3Kind)&&(i.uvs3=e.getVerticesData(ns.UV3Kind,t,s)),e.isVerticesDataPresent(ns.UV4Kind)&&(i.uvs4=e.getVerticesData(ns.UV4Kind,t,s)),e.isVerticesDataPresent(ns.UV5Kind)&&(i.uvs5=e.getVerticesData(ns.UV5Kind,t,s)),e.isVerticesDataPresent(ns.UV6Kind)&&(i.uvs6=e.getVerticesData(ns.UV6Kind,t,s)),e.isVerticesDataPresent(ns.ColorKind)){const r=e.geometry||e,n=r.getVertexBuffer(ns.ColorKind),a=r.getVerticesData(ns.ColorKind,t,s);if(3===n.getSize()){const e=new Float32Array(4*a.length/3);for(let t=0,s=0;t<a.length;t+=3,s+=4)e[s]=a[t],e[s+1]=a[t+1],e[s+2]=a[t+2],e[s+3]=1;i.colors=e}else{if(4!==n.getSize())throw new Error(`Unexpected number of color components: ${n.getSize()}`);i.colors=a}}return e.isVerticesDataPresent(ns.MatricesIndicesKind)&&(i.matricesIndices=e.getVerticesData(ns.MatricesIndicesKind,t,s)),e.isVerticesDataPresent(ns.MatricesWeightsKind)&&(i.matricesWeights=e.getVerticesData(ns.MatricesWeightsKind,t,s)),e.isVerticesDataPresent(ns.MatricesIndicesExtraKind)&&(i.matricesIndicesExtra=e.getVerticesData(ns.MatricesIndicesExtraKind,t,s)),e.isVerticesDataPresent(ns.MatricesWeightsExtraKind)&&(i.matricesWeightsExtra=e.getVerticesData(ns.MatricesWeightsExtraKind,t,s)),i.indices=e.getIndices(t,s),i}static CreateRibbon(e){throw Y("ribbonBuilder")}static CreateBox(e){throw Y("boxBuilder")}static CreateTiledBox(e){throw Y("tiledBoxBuilder")}static CreateTiledPlane(e){throw Y("tiledPlaneBuilder")}static CreateSphere(e){throw Y("sphereBuilder")}static CreateCylinder(e){throw Y("cylinderBuilder")}static CreateTorus(e){throw Y("torusBuilder")}static CreateLineSystem(e){throw Y("linesBuilder")}static CreateDashedLines(e){throw Y("linesBuilder")}static CreateGround(e){throw Y("groundBuilder")}static CreateTiledGround(e){throw Y("groundBuilder")}static CreateGroundFromHeightMap(e){throw Y("groundBuilder")}static CreatePlane(e){throw Y("planeBuilder")}static CreateDisc(e){throw Y("discBuilder")}static CreatePolygon(e,t,s,i,r,n,a){throw Y("polygonBuilder")}static CreateIcoSphere(e){throw Y("icoSphereBuilder")}static CreatePolyhedron(e){throw Y("polyhedronBuilder")}static CreateCapsule(e={orientation:U.Up(),subdivisions:2,tessellation:16,height:1,radius:.25,capSubdivisions:6}){throw Y("capsuleBuilder")}static CreateTorusKnot(e){throw Y("torusKnotBuilder")}static ComputeNormals(e,t,s,i){let r=0,n=0,a=0,o=0,h=0,l=0,c=0,u=0,d=0,_=0,f=0,p=0,m=0,g=0,T=0,E=0,A=0,y=0,b=0,R=0,x=!1,M=!1,I=!1,S=!1,v=1,C=0,P=null;i&&(x=!!i.facetNormals,M=!!i.facetPositions,I=!!i.facetPartitioning,v=!0===i.useRightHandedSystem?-1:1,C=i.ratio||0,S=!!i.depthSort,P=i.distanceTo,S&&void 0===P&&(P=U.Zero()));let O=0,D=0,L=0,F=0;for(I&&i&&i.bbSize&&(O=i.subDiv.X*C/i.bbSize.x,D=i.subDiv.Y*C/i.bbSize.y,L=i.subDiv.Z*C/i.bbSize.z,F=i.subDiv.max*i.subDiv.max,i.facetPartitioning.length=0),r=0;r<e.length;r++)s[r]=0;const N=t.length/3|0;for(r=0;r<N;r++){if(p=3*t[3*r],m=p+1,g=p+2,T=3*t[3*r+1],E=T+1,A=T+2,y=3*t[3*r+2],b=y+1,R=y+2,n=e[p]-e[T],a=e[m]-e[E],o=e[g]-e[A],h=e[y]-e[T],l=e[b]-e[E],c=e[R]-e[A],u=v*(a*c-o*l),d=v*(o*h-n*c),_=v*(n*l-a*h),f=Math.sqrt(u*u+d*d+_*_),f=0===f?1:f,u/=f,d/=f,_/=f,x&&i&&(i.facetNormals[r].x=u,i.facetNormals[r].y=d,i.facetNormals[r].z=_),M&&i&&(i.facetPositions[r].x=(e[p]+e[T]+e[y])/3,i.facetPositions[r].y=(e[m]+e[E]+e[b])/3,i.facetPositions[r].z=(e[g]+e[A]+e[R])/3),I&&i){const t=Math.floor((i.facetPositions[r].x-i.bInfo.minimum.x*C)*O),s=Math.floor((i.facetPositions[r].y-i.bInfo.minimum.y*C)*D),n=Math.floor((i.facetPositions[r].z-i.bInfo.minimum.z*C)*L),a=Math.floor((e[p]-i.bInfo.minimum.x*C)*O),o=Math.floor((e[m]-i.bInfo.minimum.y*C)*D),h=Math.floor((e[g]-i.bInfo.minimum.z*C)*L),l=Math.floor((e[T]-i.bInfo.minimum.x*C)*O),c=Math.floor((e[E]-i.bInfo.minimum.y*C)*D),u=Math.floor((e[A]-i.bInfo.minimum.z*C)*L),d=Math.floor((e[y]-i.bInfo.minimum.x*C)*O),_=Math.floor((e[b]-i.bInfo.minimum.y*C)*D),f=Math.floor((e[R]-i.bInfo.minimum.z*C)*L),x=a+i.subDiv.max*o+F*h,M=l+i.subDiv.max*c+F*u,I=d+i.subDiv.max*_+F*f,S=t+i.subDiv.max*s+F*n;i.facetPartitioning[S]=i.facetPartitioning[S]?i.facetPartitioning[S]:new Array,i.facetPartitioning[x]=i.facetPartitioning[x]?i.facetPartitioning[x]:new Array,i.facetPartitioning[M]=i.facetPartitioning[M]?i.facetPartitioning[M]:new Array,i.facetPartitioning[I]=i.facetPartitioning[I]?i.facetPartitioning[I]:new Array,i.facetPartitioning[x].push(r),M!=x&&i.facetPartitioning[M].push(r),I!=M&&I!=x&&i.facetPartitioning[I].push(r),S!=x&&S!=M&&S!=I&&i.facetPartitioning[S].push(r)}if(S&&i&&i.facetPositions){const e=i.depthSortedFacets[r];e.ind=3*r,e.sqDistance=U.DistanceSquared(i.facetPositions[r],P)}s[p]+=u,s[m]+=d,s[g]+=_,s[T]+=u,s[E]+=d,s[A]+=_,s[y]+=u,s[b]+=d,s[R]+=_}for(r=0;r<s.length/3;r++)u=s[3*r],d=s[3*r+1],_=s[3*r+2],f=Math.sqrt(u*u+d*d+_*_),f=0===f?1:f,u/=f,d/=f,_/=f,s[3*r]=u,s[3*r+1]=d,s[3*r+2]=_}static _ComputeSides(e,t,s,i,r,n,a){const o=s.length,h=i.length;let l,c;switch(e=e||Es.DEFAULTSIDE){case Es.FRONTSIDE:break;case Es.BACKSIDE:for(l=0;l<o;l+=3){const e=s[l];s[l]=s[l+2],s[l+2]=e}for(c=0;c<h;c++)i[c]=-i[c];break;case Es.DOUBLESIDE:{const e=t.length,u=e/3;for(let s=0;s<e;s++)t[e+s]=t[s];for(l=0;l<o;l+=3)s[l+o]=s[l+2]+u,s[l+1+o]=s[l+1]+u,s[l+2+o]=s[l]+u;for(c=0;c<h;c++)i[h+c]=-i[c];const d=r.length;let _=0;for(_=0;_<d;_++)r[_+d]=r[_];for(n=n||new k(0,0,1,1),a=a||new k(0,0,1,1),_=0,l=0;l<d/2;l++)r[_]=n.x+(n.z-n.x)*r[_],r[_+1]=n.y+(n.w-n.y)*r[_+1],r[_+d]=a.x+(a.z-a.x)*r[_+d],r[_+d+1]=a.y+(a.w-a.y)*r[_+d+1],_+=2;break}}}static Parse(e){const t=new Es,s=e.positions;s&&t.set(s,ns.PositionKind);const i=e.normals;i&&t.set(i,ns.NormalKind);const r=e.tangents;r&&t.set(r,ns.TangentKind);const n=e.uvs;n&&t.set(n,ns.UVKind);const a=e.uvs2;a&&t.set(a,ns.UV2Kind);const o=e.uvs3;o&&t.set(o,ns.UV3Kind);const h=e.uvs4;h&&t.set(h,ns.UV4Kind);const l=e.uvs5;l&&t.set(l,ns.UV5Kind);const c=e.uvs6;c&&t.set(c,ns.UV6Kind);const u=e.colors;u&&(t.set(te.CheckColors4(u,s.length/3),ns.ColorKind),void 0!==e.hasVertexAlpha&&(t.hasVertexAlpha=e.hasVertexAlpha));const d=e.matricesIndices;d&&t.set(d,ns.MatricesIndicesKind);const _=e.matricesWeights;_&&t.set(_,ns.MatricesWeightsKind);const f=e.indices;f&&(t.indices=f);const p=e.materialInfos;if(p){t.materialInfos=[];for(const e of p){const s=new Ts;s.indexCount=e.indexCount,s.indexStart=e.indexStart,s.verticesCount=e.verticesCount,s.verticesStart=e.verticesStart,s.materialIndex=e.materialIndex,t.materialInfos.push(s)}}return t}static ImportVertexData(e,t){const s=Es.Parse(e);t.setAllVerticesData(s,e.updatable)}}Es.FRONTSIDE=0,Es.BACKSIDE=1,Es.DOUBLESIDE=2,Es.DEFAULTSIDE=0,Es._UniqueIDGenerator=0,e([f.filter(((...[e])=>!Array.isArray(e)))],Es,"_TransformVector3Coordinates",null),e([f.filter(((...[e])=>!Array.isArray(e)))],Es,"_TransformVector3Normals",null),e([f.filter(((...[e])=>!Array.isArray(e)))],Es,"_TransformVector4Normals",null),e([f.filter(((...[e])=>!Array.isArray(e)))],Es,"_FlipFaces",null);class As{static get ForceFullSceneLoadingForIncremental(){return As._ForceFullSceneLoadingForIncremental}static set ForceFullSceneLoadingForIncremental(e){As._ForceFullSceneLoadingForIncremental=e}static get ShowLoadingScreen(){return As._ShowLoadingScreen}static set ShowLoadingScreen(e){As._ShowLoadingScreen=e}static get loggingLevel(){return As._LoggingLevel}static set loggingLevel(e){As._LoggingLevel=e}static get CleanBoneMatrixWeights(){return As._CleanBoneMatrixWeights}static set CleanBoneMatrixWeights(e){As._CleanBoneMatrixWeights=e}}As._ForceFullSceneLoadingForIncremental=!1,As._ShowLoadingScreen=!0,As._CleanBoneMatrixWeights=!1,As._LoggingLevel=Ze.SCENELOADER_NO_LOGGING;class ys{get boundingBias(){return this._boundingBias}set boundingBias(e){this._boundingBias?this._boundingBias.copyFrom(e):this._boundingBias=e.clone(),this._updateBoundingInfo(!0,null)}static CreateGeometryForMesh(e){const t=new ys(ys.RandomId(),e.getScene());return t.applyToMesh(e),t}get meshes(){return this._meshes}constructor(e,t,s,i=!1,r=null){this.delayLoadState=Ze.DELAYLOADSTATE_NONE,this._totalVertices=0,this._isDisposed=!1,this._indexBufferIsUpdatable=!1,this._positionsCache=[],this._parentContainer=null,this.useBoundingInfoFromGeometry=!1,this._scene=t||C.LastCreatedScene,this._scene&&(this.id=e,this.uniqueId=this._scene.getUniqueId(),this._engine=this._scene.getEngine(),this._meshes=[],this._vertexBuffers={},this._indices=[],this._updatable=i,s?this.setAllVerticesData(s,i):this._totalVertices=0,this._engine.getCaps().vertexArrayObject&&(this._vertexArrayObjects={}),r&&(this.applyToMesh(r),r.computeWorldMatrix(!0)))}get extend(){return this._extend}getScene(){return this._scene}getEngine(){return this._engine}isReady(){return this.delayLoadState===Ze.DELAYLOADSTATE_LOADED||this.delayLoadState===Ze.DELAYLOADSTATE_NONE}get doNotSerialize(){for(let e=0;e<this._meshes.length;e++)if(!this._meshes[e].doNotSerialize)return!1;return!0}_rebuild(){this._vertexArrayObjects&&(this._vertexArrayObjects={}),0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer"));const e=new Set;for(const t in this._vertexBuffers)e.add(this._vertexBuffers[t].getWrapperBuffer());e.forEach((e=>{e._rebuild()}))}setAllVerticesData(e,t){e.applyToGeometry(this,t),this._notifyUpdate()}setVerticesData(e,t,s=!1,i){s&&Array.isArray(t)&&(t=new Float32Array(t));const r=new ns(this._engine,t,e,{updatable:s,postponeInternalCreation:0===this._meshes.length,stride:i,label:"Geometry_"+this.id+"_"+e});this.setVerticesBuffer(r)}removeVerticesData(e){this._vertexBuffers[e]&&(this._vertexBuffers[e].dispose(),delete this._vertexBuffers[e]),this._vertexArrayObjects&&this._disposeVertexArrayObjects()}setVerticesBuffer(e,t=null,s=!0){const i=e.getKind();this._vertexBuffers[i]&&s&&this._vertexBuffers[i].dispose(),e._buffer&&e._buffer._increaseReferences(),this._vertexBuffers[i]=e;const r=this._meshes,n=r.length;if(i===ns.PositionKind){this._totalVertices=t??e._maxVerticesCount,this._updateExtend(e.getFloatData(this._totalVertices)),this._resetPointsArrayCache();const s=this._extend&&this._extend.minimum||new U(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),i=this._extend&&this._extend.maximum||new U(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE);for(let e=0;e<n;e++){const t=r[e];t.buildBoundingInfo(s,i),t._createGlobalSubMesh(t.isUnIndexed),t.computeWorldMatrix(!0),t.synchronizeInstances()}}this._notifyUpdate(i)}updateVerticesDataDirectly(e,t,s,i=!1){const r=this.getVertexBuffer(e);r&&(r.updateDirectly(t,s,i),this._notifyUpdate(e))}updateVerticesData(e,t,s=!1){const i=this.getVertexBuffer(e);i&&(i.update(t),e===ns.PositionKind&&this._updateBoundingInfo(s,t),this._notifyUpdate(e))}_updateBoundingInfo(e,t){if(e&&this._updateExtend(t),this._resetPointsArrayCache(),e){const e=this._meshes;for(const t of e){t.hasBoundingInfo?t.getBoundingInfo().reConstruct(this._extend.minimum,this._extend.maximum):t.buildBoundingInfo(this._extend.minimum,this._extend.maximum);const e=t.subMeshes;for(const t of e)t.refreshBoundingInfo()}}}_bind(e,t,s,i){if(!e)return;void 0===t&&(t=this._indexBuffer);const r=this.getVertexBuffers();if(!r)return;if(t!=this._indexBuffer||!this._vertexArrayObjects&&!i)return void this._engine.bindBuffers(r,t,e,s);const n=i||this._vertexArrayObjects,a=this._engine;n[e.key]||(n[e.key]=a.recordVertexArrayObject(r,t,e,s)),a.bindVertexArrayObject(n[e.key],t)}getTotalVertices(){return this.isReady()?this._totalVertices:0}getVerticesData(e,t,s){const i=this.getVertexBuffer(e);return i?i.getFloatData(this._totalVertices,s||t&&1!==this._meshes.length):null}copyVerticesData(e,t){const s=this.getVertexBuffer(e);if(!s)return;t[e]||=new Float32Array(this._totalVertices*s.getSize());const i=s.getData();i&&function(e,t,s,i,r,n,a,o){const h=t*ns.GetTypeByteLength(s),l=a*t;if(o.length!==l)throw new Error("Output length is not valid");if(s===ns.FLOAT&&r===h)if(e instanceof Array){const t=i/4;o.set(e,t)}else if(e instanceof ArrayBuffer){const t=new Float32Array(e,i,l);o.set(t)}else{const t=e.byteOffset+i;if(t%4)return ue.Warn("CopyFloatData: copied misaligned data."),void o.set(new Float32Array(e.buffer.slice(t,t+4*l)));const s=new Float32Array(e.buffer,t,l);o.set(s)}else ns.ForEach(e,i,r,t,s,l,n,((e,t)=>o[t]=e))}(i,s.getSize(),s.type,s.byteOffset,s.byteStride,s.normalized,this._totalVertices,t[e])}isVertexBufferUpdatable(e){const t=this._vertexBuffers[e];return!!t&&t.isUpdatable()}getVertexBuffer(e){return this.isReady()?this._vertexBuffers[e]:null}getVertexBuffers(){return this.isReady()?this._vertexBuffers:null}isVerticesDataPresent(e){return this._vertexBuffers?void 0!==this._vertexBuffers[e]:!!this._delayInfo&&-1!==this._delayInfo.indexOf(e)}getVerticesDataKinds(){const e=[];let t;if(!this._vertexBuffers&&this._delayInfo)for(t in this._delayInfo)e.push(t);else for(t in this._vertexBuffers)e.push(t);return e}updateIndices(e,t,s=!1){if(this._indexBuffer)if(this._indexBufferIsUpdatable){const i=e.length!==this._indices.length;if(s||(this._indices=e.slice()),this._engine.updateDynamicIndexBuffer(this._indexBuffer,e,t),i)for(const e of this._meshes)e._createGlobalSubMesh(!0)}else this.setIndices(e,null,!0)}setIndexBuffer(e,t,s){this._indices=[],this._indexBufferIsUpdatable=!1,this._indexBuffer=e,this._totalVertices=t,this._totalIndices=s,e.is32Bits||=this._totalIndices>65535;for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}setIndices(e,t=null,s=!1){this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indices=e,this._indexBufferIsUpdatable=s,0!==this._meshes.length&&this._indices&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,s,"Geometry_"+this.id+"_IndexBuffer")),null!=t&&(this._totalVertices=t);for(const e of this._meshes)e._createGlobalSubMesh(!0),e.synchronizeInstances();this._notifyUpdate()}getTotalIndices(){return this.isReady()?void 0!==this._totalIndices?this._totalIndices:this._indices.length:0}getIndices(e,t){if(!this.isReady())return null;const s=this._indices;return t||e&&1!==this._meshes.length?s.slice():s}getIndexBuffer(){return this.isReady()?this._indexBuffer:null}_releaseVertexArrayObject(e=null){e&&this._vertexArrayObjects&&this._vertexArrayObjects[e.key]&&(this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e.key]),delete this._vertexArrayObjects[e.key])}releaseForMesh(e,t){const s=this._meshes,i=s.indexOf(e);-1!==i&&(s.splice(i,1),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject(),e._geometry=null,0===s.length&&t&&this.dispose())}applyToMesh(e){if(e._geometry===this)return;const t=e._geometry;t&&t.releaseForMesh(e),this._vertexArrayObjects&&e._invalidateInstanceVertexArrayObject();const s=this._meshes;e._geometry=this,e._internalAbstractMeshDataInfo._positions=null,this._scene.pushGeometry(this),s.push(e),this.isReady()?this._applyToMesh(e):this._boundingInfo&&e.setBoundingInfo(this._boundingInfo)}_updateExtend(e=null){if(this.useBoundingInfoFromGeometry&&this._boundingInfo)this._extend={minimum:this._boundingInfo.minimum.clone(),maximum:this._boundingInfo.maximum.clone()};else{if(!e&&!(e=this.getVerticesData(ns.PositionKind)))return;this._extend=ps(e,0,this._totalVertices,this.boundingBias,3)}}_applyToMesh(e){const t=this._meshes.length;for(const s in this._vertexBuffers)1===t&&this._vertexBuffers[s].create(),s===ns.PositionKind&&(this._extend||this._updateExtend(),e.buildBoundingInfo(this._extend.minimum,this._extend.maximum),e._createGlobalSubMesh(e.isUnIndexed),e._updateBoundingInfo());1===t&&this._indices&&this._indices.length>0&&(this._indexBuffer=this._engine.createIndexBuffer(this._indices,this._updatable,"Geometry_"+this.id+"_IndexBuffer")),e._syncGeometryWithMorphTargetManager(),e.synchronizeInstances()}_notifyUpdate(e){this.onGeometryUpdated&&this.onGeometryUpdated(this,e),this._vertexArrayObjects&&this._disposeVertexArrayObjects();for(const e of this._meshes)e._markSubMeshesAsAttributesDirty()}load(e,t){this.delayLoadState!==Ze.DELAYLOADSTATE_LOADING&&(this.isReady()?t&&t():(this.delayLoadState=Ze.DELAYLOADSTATE_LOADING,this._queueLoad(e,t)))}_queueLoad(e,t){this.delayLoadingFile&&(e.addPendingData(this),e._loadFile(this.delayLoadingFile,(s=>{if(!this._delayLoadingFunction)return;this._delayLoadingFunction(JSON.parse(s),this),this.delayLoadState=Ze.DELAYLOADSTATE_LOADED,this._delayInfo=[],e.removePendingData(this);const i=this._meshes,r=i.length;for(let e=0;e<r;e++)this._applyToMesh(i[e]);t&&t()}),void 0,!0))}toLeftHanded(){const e=this.getIndices(!1);if(null!=e&&e.length>0){for(let t=0;t<e.length;t+=3){const s=e[t+0];e[t+0]=e[t+2],e[t+2]=s}this.setIndices(e)}const t=this.getVerticesData(ns.PositionKind,!1);if(null!=t&&t.length>0){for(let e=0;e<t.length;e+=3)t[e+2]=-t[e+2];this.setVerticesData(ns.PositionKind,t,!1)}const s=this.getVerticesData(ns.NormalKind,!1);if(null!=s&&s.length>0){for(let e=0;e<s.length;e+=3)s[e+2]=-s[e+2];this.setVerticesData(ns.NormalKind,s,!1)}}_resetPointsArrayCache(){this._positions=null}_generatePointsArray(){if(this._positions)return!0;const e=this.getVerticesData(ns.PositionKind);if(!e||0===e.length)return!1;for(let t=3*this._positionsCache.length,s=this._positionsCache.length;t<e.length;t+=3,++s)this._positionsCache[s]=U.FromArray(e,t);for(let t=0,s=0;t<e.length;t+=3,++s)this._positionsCache[s].set(e[0+t],e[1+t],e[2+t]);return this._positionsCache.length=e.length/3,this._positions=this._positionsCache,!0}isDisposed(){return this._isDisposed}_disposeVertexArrayObjects(){if(this._vertexArrayObjects){for(const e in this._vertexArrayObjects)this._engine.releaseVertexArrayObject(this._vertexArrayObjects[e]);this._vertexArrayObjects={};const e=this._meshes,t=e.length;for(let s=0;s<t;s++)e[s]._invalidateInstanceVertexArrayObject()}}dispose(){const e=this._meshes,t=e.length;let s;for(s=0;s<t;s++)this.releaseForMesh(e[s]);this._meshes.length=0,this._disposeVertexArrayObjects();for(const e in this._vertexBuffers)this._vertexBuffers[e].dispose();if(this._vertexBuffers={},this._totalVertices=0,this._indexBuffer&&this._engine._releaseBuffer(this._indexBuffer),this._indexBuffer=null,this._indices=[],this.delayLoadState=Ze.DELAYLOADSTATE_NONE,this.delayLoadingFile=null,this._delayLoadingFunction=null,this._delayInfo=[],this._boundingInfo=null,this._scene.removeGeometry(this),this._parentContainer){const e=this._parentContainer.geometries.indexOf(this);e>-1&&this._parentContainer.geometries.splice(e,1),this._parentContainer=null}this._isDisposed=!0}copy(e){const t=new Es;t.indices=[];const s=this.getIndices();if(s)for(let e=0;e<s.length;e++)t.indices.push(s[e]);let i,r=!1,n=!1;for(i in this._vertexBuffers){const e=this.getVerticesData(i);if(e&&(e instanceof Float32Array?t.set(new Float32Array(e),i):t.set(e.slice(0),i),!n)){const e=this.getVertexBuffer(i);e&&(r=e.isUpdatable(),n=!r)}}const a=new ys(e,this._scene,t,r);for(i in a.delayLoadState=this.delayLoadState,a.delayLoadingFile=this.delayLoadingFile,a._delayLoadingFunction=this._delayLoadingFunction,this._delayInfo)a._delayInfo=a._delayInfo||[],a._delayInfo.push(i);return a._boundingInfo=new _s(this._extend.minimum,this._extend.maximum),a}serialize(){const e={};return e.id=this.id,e.uniqueId=this.uniqueId,e.updatable=this._updatable,q&&q.HasTags(this)&&(e.tags=q.GetTags(this)),e}_toNumberArray(e){return Array.isArray(e)?e:Array.prototype.slice.call(e)}clearCachedData(){this._indices=[],this._resetPointsArrayCache();for(const e in this._vertexBuffers)Object.prototype.hasOwnProperty.call(this._vertexBuffers,e)&&(this._vertexBuffers[e]._buffer._data=null)}serializeVerticeData(){const e=this.serialize();return this.isVerticesDataPresent(ns.PositionKind)&&(e.positions=this._toNumberArray(this.getVerticesData(ns.PositionKind)),this.isVertexBufferUpdatable(ns.PositionKind)&&(e.positions._updatable=!0)),this.isVerticesDataPresent(ns.NormalKind)&&(e.normals=this._toNumberArray(this.getVerticesData(ns.NormalKind)),this.isVertexBufferUpdatable(ns.NormalKind)&&(e.normals._updatable=!0)),this.isVerticesDataPresent(ns.TangentKind)&&(e.tangents=this._toNumberArray(this.getVerticesData(ns.TangentKind)),this.isVertexBufferUpdatable(ns.TangentKind)&&(e.tangents._updatable=!0)),this.isVerticesDataPresent(ns.UVKind)&&(e.uvs=this._toNumberArray(this.getVerticesData(ns.UVKind)),this.isVertexBufferUpdatable(ns.UVKind)&&(e.uvs._updatable=!0)),this.isVerticesDataPresent(ns.UV2Kind)&&(e.uvs2=this._toNumberArray(this.getVerticesData(ns.UV2Kind)),this.isVertexBufferUpdatable(ns.UV2Kind)&&(e.uvs2._updatable=!0)),this.isVerticesDataPresent(ns.UV3Kind)&&(e.uvs3=this._toNumberArray(this.getVerticesData(ns.UV3Kind)),this.isVertexBufferUpdatable(ns.UV3Kind)&&(e.uvs3._updatable=!0)),this.isVerticesDataPresent(ns.UV4Kind)&&(e.uvs4=this._toNumberArray(this.getVerticesData(ns.UV4Kind)),this.isVertexBufferUpdatable(ns.UV4Kind)&&(e.uvs4._updatable=!0)),this.isVerticesDataPresent(ns.UV5Kind)&&(e.uvs5=this._toNumberArray(this.getVerticesData(ns.UV5Kind)),this.isVertexBufferUpdatable(ns.UV5Kind)&&(e.uvs5._updatable=!0)),this.isVerticesDataPresent(ns.UV6Kind)&&(e.uvs6=this._toNumberArray(this.getVerticesData(ns.UV6Kind)),this.isVertexBufferUpdatable(ns.UV6Kind)&&(e.uvs6._updatable=!0)),this.isVerticesDataPresent(ns.ColorKind)&&(e.colors=this._toNumberArray(this.getVerticesData(ns.ColorKind)),this.isVertexBufferUpdatable(ns.ColorKind)&&(e.colors._updatable=!0)),this.isVerticesDataPresent(ns.MatricesIndicesKind)&&(e.matricesIndices=this._toNumberArray(this.getVerticesData(ns.MatricesIndicesKind)),e.matricesIndices._isExpanded=!0,this.isVertexBufferUpdatable(ns.MatricesIndicesKind)&&(e.matricesIndices._updatable=!0)),this.isVerticesDataPresent(ns.MatricesWeightsKind)&&(e.matricesWeights=this._toNumberArray(this.getVerticesData(ns.MatricesWeightsKind)),this.isVertexBufferUpdatable(ns.MatricesWeightsKind)&&(e.matricesWeights._updatable=!0)),e.indices=this._toNumberArray(this.getIndices()),e}static ExtractFromMesh(e,t){const s=e._geometry;return s?s.copy(t):null}static RandomId(){return Yt.RandomId()}static _GetGeometryByLoadedUniqueId(e,t){for(let s=0;s<t.geometries.length;s++)if(t.geometries[s]._loadedUniqueId===e)return t.geometries[s];return null}static _ImportGeometry(e,t){const s=t.getScene(),i=e.geometryUniqueId,r=e.geometryId;if(i||r){const e=i?this._GetGeometryByLoadedUniqueId(i,s):s.getGeometryById(r);e&&e.applyToMesh(t)}else if(e instanceof ArrayBuffer){const s=t._binaryInfo;if(s.positionsAttrDesc&&s.positionsAttrDesc.count>0){const i=new Float32Array(e,s.positionsAttrDesc.offset,s.positionsAttrDesc.count);t.setVerticesData(ns.PositionKind,i,!1)}if(s.normalsAttrDesc&&s.normalsAttrDesc.count>0){const i=new Float32Array(e,s.normalsAttrDesc.offset,s.normalsAttrDesc.count);t.setVerticesData(ns.NormalKind,i,!1)}if(s.tangetsAttrDesc&&s.tangetsAttrDesc.count>0){const i=new Float32Array(e,s.tangetsAttrDesc.offset,s.tangetsAttrDesc.count);t.setVerticesData(ns.TangentKind,i,!1)}if(s.uvsAttrDesc&&s.uvsAttrDesc.count>0){const i=new Float32Array(e,s.uvsAttrDesc.offset,s.uvsAttrDesc.count);t.setVerticesData(ns.UVKind,i,!1)}if(s.uvs2AttrDesc&&s.uvs2AttrDesc.count>0){const i=new Float32Array(e,s.uvs2AttrDesc.offset,s.uvs2AttrDesc.count);t.setVerticesData(ns.UV2Kind,i,!1)}if(s.uvs3AttrDesc&&s.uvs3AttrDesc.count>0){const i=new Float32Array(e,s.uvs3AttrDesc.offset,s.uvs3AttrDesc.count);t.setVerticesData(ns.UV3Kind,i,!1)}if(s.uvs4AttrDesc&&s.uvs4AttrDesc.count>0){const i=new Float32Array(e,s.uvs4AttrDesc.offset,s.uvs4AttrDesc.count);t.setVerticesData(ns.UV4Kind,i,!1)}if(s.uvs5AttrDesc&&s.uvs5AttrDesc.count>0){const i=new Float32Array(e,s.uvs5AttrDesc.offset,s.uvs5AttrDesc.count);t.setVerticesData(ns.UV5Kind,i,!1)}if(s.uvs6AttrDesc&&s.uvs6AttrDesc.count>0){const i=new Float32Array(e,s.uvs6AttrDesc.offset,s.uvs6AttrDesc.count);t.setVerticesData(ns.UV6Kind,i,!1)}if(s.colorsAttrDesc&&s.colorsAttrDesc.count>0){const i=new Float32Array(e,s.colorsAttrDesc.offset,s.colorsAttrDesc.count);t.setVerticesData(ns.ColorKind,i,!1,s.colorsAttrDesc.stride)}if(s.matricesIndicesAttrDesc&&s.matricesIndicesAttrDesc.count>0){const i=new Int32Array(e,s.matricesIndicesAttrDesc.offset,s.matricesIndicesAttrDesc.count),r=[];for(let e=0;e<i.length;e++){const t=i[e];r.push(255&t),r.push((65280&t)>>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(ns.MatricesIndicesKind,r,!1)}if(s.matricesIndicesExtraAttrDesc&&s.matricesIndicesExtraAttrDesc.count>0){const i=new Int32Array(e,s.matricesIndicesExtraAttrDesc.offset,s.matricesIndicesExtraAttrDesc.count),r=[];for(let e=0;e<i.length;e++){const t=i[e];r.push(255&t),r.push((65280&t)>>8),r.push((16711680&t)>>16),r.push(t>>24&255)}t.setVerticesData(ns.MatricesIndicesExtraKind,r,!1)}if(s.matricesWeightsAttrDesc&&s.matricesWeightsAttrDesc.count>0){const i=new Float32Array(e,s.matricesWeightsAttrDesc.offset,s.matricesWeightsAttrDesc.count);t.setVerticesData(ns.MatricesWeightsKind,i,!1)}if(s.indicesAttrDesc&&s.indicesAttrDesc.count>0){const i=new Int32Array(e,s.indicesAttrDesc.offset,s.indicesAttrDesc.count);t.setIndices(i,null)}if(s.subMeshesAttrDesc&&s.subMeshesAttrDesc.count>0){const i=new Int32Array(e,s.subMeshesAttrDesc.offset,5*s.subMeshesAttrDesc.count);t.subMeshes=[];for(let e=0;e<s.subMeshesAttrDesc.count;e++){const s=i[5*e+0],r=i[5*e+1],n=i[5*e+2],a=i[5*e+3],o=i[5*e+4];gs.AddToMesh(s,r,n,a,o,t)}}}else if(e.positions&&e.normals&&e.indices){if(t.setVerticesData(ns.PositionKind,e.positions,e.positions._updatable),t.setVerticesData(ns.NormalKind,e.normals,e.normals._updatable),e.tangents&&t.setVerticesData(ns.TangentKind,e.tangents,e.tangents._updatable),e.uvs&&t.setVerticesData(ns.UVKind,e.uvs,e.uvs._updatable),e.uvs2&&t.setVerticesData(ns.UV2Kind,e.uvs2,e.uvs2._updatable),e.uvs3&&t.setVerticesData(ns.UV3Kind,e.uvs3,e.uvs3._updatable),e.uvs4&&t.setVerticesData(ns.UV4Kind,e.uvs4,e.uvs4._updatable),e.uvs5&&t.setVerticesData(ns.UV5Kind,e.uvs5,e.uvs5._updatable),e.uvs6&&t.setVerticesData(ns.UV6Kind,e.uvs6,e.uvs6._updatable),e.colors&&t.setVerticesData(ns.ColorKind,te.CheckColors4(e.colors,e.positions.length/3),e.colors._updatable),e.matricesIndices)if(e.matricesIndices._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(ns.MatricesIndicesKind,e.matricesIndices,e.matricesIndices._updatable);else{const s=[];for(let t=0;t<e.matricesIndices.length;t++){const i=e.matricesIndices[t];s.push(255&i),s.push((65280&i)>>8),s.push((16711680&i)>>16),s.push(i>>24&255)}t.setVerticesData(ns.MatricesIndicesKind,s,e.matricesIndices._updatable)}if(e.matricesIndicesExtra)if(e.matricesIndicesExtra._isExpanded)delete e.matricesIndices._isExpanded,t.setVerticesData(ns.MatricesIndicesExtraKind,e.matricesIndicesExtra,e.matricesIndicesExtra._updatable);else{const s=[];for(let t=0;t<e.matricesIndicesExtra.length;t++){const i=e.matricesIndicesExtra[t];s.push(255&i),s.push((65280&i)>>8),s.push((16711680&i)>>16),s.push(i>>24&255)}t.setVerticesData(ns.MatricesIndicesExtraKind,s,e.matricesIndicesExtra._updatable)}e.matricesWeights&&(ys._CleanMatricesWeights(e,t),t.setVerticesData(ns.MatricesWeightsKind,e.matricesWeights,e.matricesWeights._updatable)),e.matricesWeightsExtra&&t.setVerticesData(ns.MatricesWeightsExtraKind,e.matricesWeightsExtra,e.matricesWeights._updatable),t.setIndices(e.indices,null)}if(e.subMeshes){t.subMeshes=[];for(let s=0;s<e.subMeshes.length;s++){const i=e.subMeshes[s];gs.AddToMesh(i.materialIndex,i.verticesStart,i.verticesCount,i.indexStart,i.indexCount,t)}}t._shouldGenerateFlatShading&&(t.convertToFlatShadedMesh(),t._shouldGenerateFlatShading=!1),t.computeWorldMatrix(!0),s.onMeshImportedObservable.notifyObservers(t)}static _CleanMatricesWeights(e,t){const s=.001;if(!As.CleanBoneMatrixWeights)return;let i=0;if(!(e.skeletonId>-1))return;{const s=t.getScene().getLastSkeletonById(e.skeletonId);if(!s)return;i=s.bones.length}const r=t.getVerticesData(ns.MatricesIndicesKind),n=t.getVerticesData(ns.MatricesIndicesExtraKind),a=e.matricesWeights,o=e.matricesWeightsExtra,h=e.numBoneInfluencer,l=a.length;for(let e=0;e<l;e+=4){let t=0,l=-1;for(let i=0;i<4;i++){const r=a[e+i];t+=r,r<s&&l<0&&(l=i)}if(o)for(let i=0;i<4;i++){const r=o[e+i];t+=r,r<s&&l<0&&(l=i+4)}if((l<0||l>h-1)&&(l=h-1),t>s){const s=1/t;for(let t=0;t<4;t++)a[e+t]*=s;if(o)for(let t=0;t<4;t++)o[e+t]*=s}else l>=4?(o[e+l-4]=1-t,n[e+l-4]=i):(a[e+l]=1-t,r[e+l]=i)}t.setVerticesData(ns.MatricesIndicesKind,r),e.matricesWeightsExtra&&t.setVerticesData(ns.MatricesIndicesExtraKind,n)}static Parse(e,t,s){const i=new ys(e.id,t,void 0,e.updatable);return i._loadedUniqueId=e.uniqueId,q&&q.AddTagsTo(i,e.tags),e.delayLoadingFile?(i.delayLoadState=Ze.DELAYLOADSTATE_NOTLOADED,i.delayLoadingFile=s+e.delayLoadingFile,i._boundingInfo=new _s(U.FromArray(e.boundingBoxMinimum),U.FromArray(e.boundingBoxMaximum)),i._delayInfo=[],e.hasUVs&&i._delayInfo.push(ns.UVKind),e.hasUVs2&&i._delayInfo.push(ns.UV2Kind),e.hasUVs3&&i._delayInfo.push(ns.UV3Kind),e.hasUVs4&&i._delayInfo.push(ns.UV4Kind),e.hasUVs5&&i._delayInfo.push(ns.UV5Kind),e.hasUVs6&&i._delayInfo.push(ns.UV6Kind),e.hasColors&&i._delayInfo.push(ns.ColorKind),e.hasMatricesIndices&&i._delayInfo.push(ns.MatricesIndicesKind),e.hasMatricesWeights&&i._delayInfo.push(ns.MatricesWeightsKind),i._delayLoadingFunction=Es.ImportVertexData):Es.ImportVertexData(e,i),t.pushGeometry(i,!0),i}}const bs=V.Compose(U.One(),G.FromEulerAngles(0,Math.PI,0),U.Zero());class Rs extends ae{get billboardMode(){return this._billboardMode}set billboardMode(e){this._billboardMode!==e&&(this._billboardMode=e,this._cache.useBillboardPosition=!!(this._billboardMode&Rs.BILLBOARDMODE_USE_POSITION),this._computeUseBillboardPath())}get preserveParentRotationForBillboard(){return this._preserveParentRotationForBillboard}set preserveParentRotationForBillboard(e){e!==this._preserveParentRotationForBillboard&&(this._preserveParentRotationForBillboard=e,this._computeUseBillboardPath())}_computeUseBillboardPath(){this._cache.useBillboardPath=this._billboardMode!==Rs.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}get infiniteDistance(){return this._infiniteDistance}set infiniteDistance(e){this._infiniteDistance!==e&&(this._infiniteDistance=e)}constructor(e,t=null,s=!0){super(e,t,!1),this._forward=new U(0,0,1),this._up=new U(0,1,0),this._right=new U(1,0,0),this._position=U.Zero(),this._rotation=U.Zero(),this._rotationQuaternion=null,this._scaling=U.One(),this._transformToBoneReferal=null,this._isAbsoluteSynced=!1,this._billboardMode=Rs.BILLBOARDMODE_NONE,this._preserveParentRotationForBillboard=!1,this.scalingDeterminant=1,this._infiniteDistance=!1,this.ignoreNonUniformScaling=!1,this.reIntegrateRotationIntoRotationQuaternion=!1,this._poseMatrix=null,this._localMatrix=V.Zero(),this._usePivotMatrix=!1,this._absolutePosition=U.Zero(),this._absoluteScaling=U.Zero(),this._absoluteRotationQuaternion=G.Identity(),this._pivotMatrix=V.Identity(),this._postMultiplyPivotMatrix=!1,this._isWorldMatrixFrozen=!1,this._indexInSceneTransformNodesArray=-1,this.onAfterWorldMatrixUpdateObservable=new g,this._nonUniformScaling=!1,s&&this.getScene().addTransformNode(this)}getClassName(){return"TransformNode"}get position(){return this._position}set position(e){this._position=e,this._isDirty=!0}isUsingPivotMatrix(){return this._usePivotMatrix}isUsingPostMultiplyPivotMatrix(){return this._postMultiplyPivotMatrix}get rotation(){return this._rotation}set rotation(e){this._rotation=e,this._rotationQuaternion=null,this._isDirty=!0}get scaling(){return this._scaling}set scaling(e){this._scaling=e,this._isDirty=!0}get rotationQuaternion(){return this._rotationQuaternion}set rotationQuaternion(e){this._rotationQuaternion=e,e&&this._rotation.setAll(0),this._isDirty=!0}get forward(){return U.TransformNormalFromFloatsToRef(0,0,this.getScene().useRightHandedSystem?-1:1,this.getWorldMatrix(),this._forward),this._forward.normalize()}get up(){return U.TransformNormalFromFloatsToRef(0,1,0,this.getWorldMatrix(),this._up),this._up.normalize()}get right(){return U.TransformNormalFromFloatsToRef(this.getScene().useRightHandedSystem?-1:1,0,0,this.getWorldMatrix(),this._right),this._right.normalize()}updatePoseMatrix(e){return this._poseMatrix?(this._poseMatrix.copyFrom(e),this):(this._poseMatrix=e.clone(),this)}getPoseMatrix(){return this._poseMatrix||(this._poseMatrix=V.Identity()),this._poseMatrix}_isSynchronized(){const e=this._cache;return this._billboardMode===e.billboardMode&&this._billboardMode===Rs.BILLBOARDMODE_NONE&&(!e.pivotMatrixUpdated&&(!this._infiniteDistance&&(!this._position._isDirty&&(!this._scaling._isDirty&&!(this._rotationQuaternion&&this._rotationQuaternion._isDirty||this._rotation._isDirty)))))}_initCache(){super._initCache();const e=this._cache;e.localMatrixUpdated=!1,e.billboardMode=-1,e.infiniteDistance=!1,e.useBillboardPosition=!1,e.useBillboardPath=!1}get absolutePosition(){return this.getAbsolutePosition()}get absoluteScaling(){return this._syncAbsoluteScalingAndRotation(),this._absoluteScaling}get absoluteRotationQuaternion(){return this._syncAbsoluteScalingAndRotation(),this._absoluteRotationQuaternion}setPreTransformMatrix(e){return this.setPivotMatrix(e,!1)}setPivotMatrix(e,t=!0){return this._pivotMatrix.copyFrom(e),this._usePivotMatrix=!this._pivotMatrix.isIdentity(),this._cache.pivotMatrixUpdated=!0,this._postMultiplyPivotMatrix=t,this._postMultiplyPivotMatrix&&(this._pivotMatrixInverse?this._pivotMatrix.invertToRef(this._pivotMatrixInverse):this._pivotMatrixInverse=V.Invert(this._pivotMatrix)),this}getPivotMatrix(){return this._pivotMatrix}instantiateHierarchy(e=null,t,s){const i=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0);i&&s&&s(this,i);for(const e of this.getChildTransformNodes(!0))e.instantiateHierarchy(i,t,s);return i}freezeWorldMatrix(e=null,t=!1){return e?t?(this._rotation.setAll(0),this._rotationQuaternion=this._rotationQuaternion||G.Identity(),e.decompose(this._scaling,this._rotationQuaternion,this._position),this.computeWorldMatrix(!0)):(this._worldMatrix=e,this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._afterComputeWorldMatrix()):(this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0)),this._isDirty=!1,this._isWorldMatrixFrozen=!0,this}unfreezeWorldMatrix(){return this._isWorldMatrixFrozen=!1,this.computeWorldMatrix(!0),this}get isWorldMatrixFrozen(){return this._isWorldMatrixFrozen}getAbsolutePosition(){return this.computeWorldMatrix(),this._absolutePosition}setAbsolutePosition(e){if(!e)return this;let t,s,i;if(void 0===e.x){if(arguments.length<3)return this;t=arguments[0],s=arguments[1],i=arguments[2]}else t=e.x,s=e.y,i=e.z;if(this.parent){const e=z.Matrix[0];this.parent.getWorldMatrix().invertToRef(e),U.TransformCoordinatesFromFloatsToRef(t,s,i,e,this.position)}else this.position.x=t,this.position.y=s,this.position.z=i;return this._absolutePosition.copyFrom(e),this}setPositionWithLocalVector(e){return this.computeWorldMatrix(),this.position=U.TransformNormal(e,this._localMatrix),this}getPositionExpressedInLocalSpace(){this.computeWorldMatrix();const e=z.Matrix[0];return this._localMatrix.invertToRef(e),U.TransformNormal(this.position,e)}locallyTranslate(e){return this.computeWorldMatrix(!0),this.position=U.TransformCoordinates(e,this._localMatrix),this}lookAt(e,t=0,s=0,i=0,r=0){const n=Rs._LookAtVectorCache,a=0===r?this.position:this.getAbsolutePosition();if(e.subtractToRef(a,n),this.setDirection(n,t,s,i),1===r&&this.parent)if(this.rotationQuaternion){const e=z.Matrix[0];this.rotationQuaternion.toRotationMatrix(e);const t=z.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(t),t.invert(),e.multiplyToRef(t,e),this.rotationQuaternion.fromRotationMatrix(e)}else{const e=z.Quaternion[0];G.FromEulerVectorToRef(this.rotation,e);const t=z.Matrix[0];e.toRotationMatrix(t);const s=z.Matrix[1];this.parent.getWorldMatrix().getRotationMatrixToRef(s),s.invert(),t.multiplyToRef(s,t),e.fromRotationMatrix(t),e.toEulerAnglesToRef(this.rotation)}return this}getDirection(e){const t=U.Zero();return this.getDirectionToRef(e,t),t}getDirectionToRef(e,t){return U.TransformNormalToRef(e,this.getWorldMatrix(),t),this}setDirection(e,t=0,s=0,i=0){const r=-Math.atan2(e.z,e.x)+Math.PI/2,n=Math.sqrt(e.x*e.x+e.z*e.z),a=-Math.atan2(e.y,n);return this.rotationQuaternion?G.RotationYawPitchRollToRef(r+t,a+s,i,this.rotationQuaternion):(this.rotation.x=a+s,this.rotation.y=r+t,this.rotation.z=i),this}setPivotPoint(e,t=0){0==this.getScene().getRenderId()&&this.computeWorldMatrix(!0);const s=this.getWorldMatrix();if(1==t){const t=z.Matrix[0];s.invertToRef(t),e=U.TransformCoordinates(e,t)}return this.setPivotMatrix(V.Translation(-e.x,-e.y,-e.z),!0)}getPivotPoint(){const e=U.Zero();return this.getPivotPointToRef(e),e}getPivotPointToRef(e){return e.x=-this._pivotMatrix.m[12],e.y=-this._pivotMatrix.m[13],e.z=-this._pivotMatrix.m[14],this}getAbsolutePivotPoint(){const e=U.Zero();return this.getAbsolutePivotPointToRef(e),e}getAbsolutePivotPointToRef(e){return this.getPivotPointToRef(e),U.TransformCoordinatesToRef(e,this.getWorldMatrix(),e),this}markAsDirty(e){if(this._isDirty)return this;if(this._children)for(const t of this._children)t.markAsDirty(e);return super.markAsDirty(e)}setParent(e,t=!1,s=!1){if(!e&&!this.parent)return this;const i=z.Quaternion[0],r=z.Vector3[0],n=z.Vector3[1],a=z.Matrix[1];V.IdentityToRef(a);const o=z.Matrix[0];this.computeWorldMatrix(!0);let h=this.rotationQuaternion;return h||(h=Rs._TmpRotation,G.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,h)),V.ComposeToRef(this.scaling,h,this.position,o),this.parent&&o.multiplyToRef(this.parent.computeWorldMatrix(!0),o),e&&(e.computeWorldMatrix(!0).invertToRef(a),o.multiplyToRef(a,o)),o.decompose(n,i,r,t?this:void 0),this.rotationQuaternion?this.rotationQuaternion.copyFrom(i):i.toEulerAnglesToRef(this.rotation),this.scaling.copyFrom(n),this.position.copyFrom(r),this.parent=e,s&&this.setPivotMatrix(V.Identity()),this}addChild(e,t=!1){return e.setParent(this,t),this}removeChild(e,t=!1){return e.setParent(null,t),this}get nonUniformScaling(){return this._nonUniformScaling}_updateNonUniformScalingState(e){return this._nonUniformScaling!==e&&(this._nonUniformScaling=e,!0)}attachToBone(e,t){return this._currentParentWhenAttachingToBone=this.parent,this._transformToBoneReferal=t,this.parent=e,e.getSkeleton().prepare(!0),e.getFinalMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this}detachFromBone(e=!1){return this.parent?(this.parent.getWorldMatrix().determinant()<0&&(this.scalingDeterminant*=-1),this._transformToBoneReferal=null,this.parent=e?this._currentParentWhenAttachingToBone:null,this):(e&&(this.parent=this._currentParentWhenAttachingToBone),this)}rotate(e,t,s){let i;if(e.normalize(),this.rotationQuaternion||(this.rotationQuaternion=this.rotation.toQuaternion(),this.rotation.setAll(0)),s&&0!==s){if(this.parent){const s=this.parent.getWorldMatrix(),i=z.Matrix[0];s.invertToRef(i),e=U.TransformNormal(e,i),s.determinant()<0&&(t*=-1)}i=G.RotationAxisToRef(e,t,Rs._RotationAxisCache),i.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion)}else i=G.RotationAxisToRef(e,t,Rs._RotationAxisCache),this.rotationQuaternion.multiplyToRef(i,this.rotationQuaternion);return this}rotateAround(e,t,s){t.normalize(),this.rotationQuaternion||(this.rotationQuaternion=G.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z),this.rotation.setAll(0));const i=z.Vector3[0],r=z.Vector3[1],n=z.Vector3[2],a=z.Quaternion[0],o=z.Matrix[0],h=z.Matrix[1],l=z.Matrix[2],c=z.Matrix[3];return e.subtractToRef(this.position,i),V.TranslationToRef(i.x,i.y,i.z,o),V.TranslationToRef(-i.x,-i.y,-i.z,h),V.RotationAxisToRef(t,s,l),h.multiplyToRef(l,c),c.multiplyToRef(o,c),c.decompose(r,a,n),this.position.addInPlace(n),a.multiplyToRef(this.rotationQuaternion,this.rotationQuaternion),this}translate(e,t,s){const i=e.scale(t);if(s&&0!==s)this.setAbsolutePosition(this.getAbsolutePosition().add(i));else{const e=this.getPositionExpressedInLocalSpace().add(i);this.setPositionWithLocalVector(e)}return this}addRotation(e,t,s){let i;this.rotationQuaternion?i=this.rotationQuaternion:(i=z.Quaternion[1],G.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,i));const r=z.Quaternion[0];return G.RotationYawPitchRollToRef(t,e,s,r),i.multiplyInPlace(r),this.rotationQuaternion||i.toEulerAnglesToRef(this.rotation),this}_getEffectiveParent(){return this.parent}isWorldMatrixCameraDependent(){return this._infiniteDistance&&!this.parent||this._billboardMode!==Rs.BILLBOARDMODE_NONE&&!this.preserveParentRotationForBillboard}computeWorldMatrix(e=!1,t=null){if(this._isWorldMatrixFrozen&&!this._isDirty)return this._worldMatrix;const s=this.getScene().getRenderId();if(!this._isDirty&&!e&&(this._currentRenderId===s||this.isSynchronized()))return this._currentRenderId=s,this._worldMatrix;t=t||this.getScene().activeCamera,this._updateCache();const i=this._cache;i.pivotMatrixUpdated=!1,i.billboardMode=this.billboardMode,i.infiniteDistance=this.infiniteDistance,i.parent=this._parentNode,this._currentRenderId=s,this._childUpdateId+=1,this._isDirty=!1,this._position._isDirty=!1,this._rotation._isDirty=!1,this._scaling._isDirty=!1;const r=this._getEffectiveParent(),n=Rs._TmpScaling;let a,o=this._position;if(this._infiniteDistance&&!this.parent&&t){const e=t.getWorldMatrix(),s=new U(e.m[12],e.m[13],e.m[14]);o=Rs._TmpTranslation,o.copyFromFloats(this._position.x+s.x,this._position.y+s.y,this._position.z+s.z)}if(n.copyFromFloats(this._scaling.x*this.scalingDeterminant,this._scaling.y*this.scalingDeterminant,this._scaling.z*this.scalingDeterminant),this._rotationQuaternion){if(this._rotationQuaternion._isDirty=!1,a=this._rotationQuaternion,this.reIntegrateRotationIntoRotationQuaternion){this.rotation.lengthSquared()&&(this._rotationQuaternion.multiplyInPlace(G.RotationYawPitchRoll(this._rotation.y,this._rotation.x,this._rotation.z)),this._rotation.copyFromFloats(0,0,0))}}else a=Rs._TmpRotation,G.RotationYawPitchRollToRef(this._rotation.y,this._rotation.x,this._rotation.z,a);if(this._usePivotMatrix){const e=z.Matrix[1];V.ScalingToRef(n.x,n.y,n.z,e);const t=z.Matrix[0];a.toRotationMatrix(t),this._pivotMatrix.multiplyToRef(e,z.Matrix[4]),z.Matrix[4].multiplyToRef(t,this._localMatrix),this._postMultiplyPivotMatrix&&this._localMatrix.multiplyToRef(this._pivotMatrixInverse,this._localMatrix),this._localMatrix.addTranslationFromFloats(o.x,o.y,o.z)}else V.ComposeToRef(n,a,o,this._localMatrix);if(r&&r.getWorldMatrix){if(e&&r.computeWorldMatrix(e),i.useBillboardPath){if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),e.getFinalMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),z.Matrix[7])}else z.Matrix[7].copyFrom(r.getWorldMatrix());const e=z.Vector3[5],t=z.Vector3[6],s=z.Quaternion[0];z.Matrix[7].decompose(t,s,e),V.ScalingToRef(t.x,t.y,t.z,z.Matrix[7]),z.Matrix[7].setTranslation(e),Rs.BillboardUseParentOrientation&&(this._position.applyRotationQuaternionToRef(s,e),this._localMatrix.setTranslation(e)),this._localMatrix.multiplyToRef(z.Matrix[7],this._worldMatrix)}else if(this._transformToBoneReferal){const e=this.parent;e.getSkeleton().prepare(),this._localMatrix.multiplyToRef(e.getFinalMatrix(),z.Matrix[6]),z.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(),this._worldMatrix)}else this._localMatrix.multiplyToRef(r.getWorldMatrix(),this._worldMatrix);this._markSyncedWithParent()}else this._worldMatrix.copyFrom(this._localMatrix);if(i.useBillboardPath&&t&&this.billboardMode&&!i.useBillboardPosition){const e=z.Vector3[0];if(this._worldMatrix.getTranslationToRef(e),z.Matrix[1].copyFrom(t.getViewMatrix()),this._scene.useRightHandedSystem&&z.Matrix[1].multiplyToRef(bs,z.Matrix[1]),z.Matrix[1].setTranslationFromFloats(0,0,0),z.Matrix[1].invertToRef(z.Matrix[0]),(this.billboardMode&Rs.BILLBOARDMODE_ALL)!==Rs.BILLBOARDMODE_ALL){z.Matrix[0].decompose(void 0,z.Quaternion[0],void 0);const e=z.Vector3[1];z.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&Rs.BILLBOARDMODE_X)!==Rs.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&Rs.BILLBOARDMODE_Y)!==Rs.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&Rs.BILLBOARDMODE_Z)!==Rs.BILLBOARDMODE_Z&&(e.z=0),V.RotationYawPitchRollToRef(e.y,e.x,e.z,z.Matrix[0])}this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(z.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(z.Vector3[0])}else if(i.useBillboardPath&&t&&i.useBillboardPosition){const e=z.Vector3[0];this._worldMatrix.getTranslationToRef(e);const s=t.globalPosition;this._worldMatrix.invertToRef(z.Matrix[1]);const i=z.Vector3[1];U.TransformCoordinatesToRef(s,z.Matrix[1],i),i.normalize();const r=-Math.atan2(i.z,i.x)+Math.PI/2,n=Math.sqrt(i.x*i.x+i.z*i.z),a=-Math.atan2(i.y,n);if(G.RotationYawPitchRollToRef(r,a,0,z.Quaternion[0]),(this.billboardMode&Rs.BILLBOARDMODE_ALL)!==Rs.BILLBOARDMODE_ALL){const e=z.Vector3[1];z.Quaternion[0].toEulerAnglesToRef(e),(this.billboardMode&Rs.BILLBOARDMODE_X)!==Rs.BILLBOARDMODE_X&&(e.x=0),(this.billboardMode&Rs.BILLBOARDMODE_Y)!==Rs.BILLBOARDMODE_Y&&(e.y=0),(this.billboardMode&Rs.BILLBOARDMODE_Z)!==Rs.BILLBOARDMODE_Z&&(e.z=0),V.RotationYawPitchRollToRef(e.y,e.x,e.z,z.Matrix[0])}else V.FromQuaternionToRef(z.Quaternion[0],z.Matrix[0]);this._worldMatrix.setTranslationFromFloats(0,0,0),this._worldMatrix.multiplyToRef(z.Matrix[0],this._worldMatrix),this._worldMatrix.setTranslation(z.Vector3[0])}return this.ignoreNonUniformScaling?this._updateNonUniformScalingState(!1):this._scaling.isNonUniformWithinEpsilon(1e-6)?this._updateNonUniformScalingState(!0):r&&r._nonUniformScaling?this._updateNonUniformScalingState(r._nonUniformScaling):this._updateNonUniformScalingState(!1),this._afterComputeWorldMatrix(),this._absolutePosition.copyFromFloats(this._worldMatrix.m[12],this._worldMatrix.m[13],this._worldMatrix.m[14]),this._isAbsoluteSynced=!1,this.onAfterWorldMatrixUpdateObservable.notifyObservers(this),this._poseMatrix||(this._poseMatrix=V.Invert(this._worldMatrix)),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix}resetLocalMatrix(e=!0){if(this.computeWorldMatrix(),e){const e=this.getChildren();for(let t=0;t<e.length;++t){const s=e[t];if(s){s.computeWorldMatrix();const e=z.Matrix[0];s._localMatrix.multiplyToRef(this._localMatrix,e);const t=z.Quaternion[0];e.decompose(s.scaling,t,s.position),s.rotationQuaternion?s.rotationQuaternion.copyFrom(t):t.toEulerAnglesToRef(s.rotation)}}}this.scaling.copyFromFloats(1,1,1),this.position.copyFromFloats(0,0,0),this.rotation.copyFromFloats(0,0,0),this.rotationQuaternion&&(this.rotationQuaternion=G.Identity()),this._worldMatrix=V.Identity()}_afterComputeWorldMatrix(){}registerAfterWorldMatrixUpdate(e){return this.onAfterWorldMatrixUpdateObservable.add(e),this}unregisterAfterWorldMatrixUpdate(e){return this.onAfterWorldMatrixUpdateObservable.removeCallback(e),this}getPositionInCameraSpace(e=null){return e||(e=this.getScene().activeCamera),U.TransformCoordinates(this.getAbsolutePosition(),e.getViewMatrix())}getDistanceToCamera(e=null){return e||(e=this.getScene().activeCamera),this.getAbsolutePosition().subtract(e.globalPosition).length()}clone(e,t,s){const i=re.Clone((()=>new Rs(e,this.getScene())),this);if(i.name=e,i.id=e,t&&(i.parent=t),!s){const t=this.getDescendants(!0);for(let s=0;s<t.length;s++){const r=t[s];r.clone&&r.clone(e+"."+r.name,i)}}return i}serialize(e){const t=re.Serialize(this,e);return t.type=this.getClassName(),t.uniqueId=this.uniqueId,this.parent&&this.parent._serializeAsParent(t),t.localMatrix=this.getPivotMatrix().asArray(),t.isEnabled=this.isEnabled(),re.AppendSerializedAnimations(this,t),t.ranges=this.serializeAnimationRanges(),t}static Parse(e,t,s){const i=re.Parse((()=>new Rs(e.name,t)),e,t,s);if(e.localMatrix?i.setPreTransformMatrix(V.FromArray(e.localMatrix)):e.pivotMatrix&&i.setPivotMatrix(V.FromArray(e.pivotMatrix)),i.setEnabled(e.isEnabled),i._waitingParsedUniqueId=e.uniqueId,void 0!==e.parentId&&(i._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(i._waitingParentInstanceIndex=e.parentInstanceIndex),e.animations){for(let t=0;t<e.animations.length;t++){const s=e.animations[t],r=S("BABYLON.Animation");r&&i.animations.push(r.Parse(s))}ae.ParseAnimationRanges(i,e,t)}return e.autoAnimate&&t.beginAnimation(i,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),i}getChildTransformNodes(e,t){const s=[];return this._getDescendants(s,e,(e=>(!t||t(e))&&e instanceof Rs)),s}dispose(e,t=!1){if(this.getScene().stopAnimation(this),this.getScene().removeTransformNode(this),this._parentContainer){const e=this._parentContainer.transformNodes.indexOf(this);e>-1&&this._parentContainer.transformNodes.splice(e,1),this._parentContainer=null}if(this.onAfterWorldMatrixUpdateObservable.clear(),e){const e=this.getChildTransformNodes(!0);for(const t of e)t.parent=null,t.computeWorldMatrix(!0)}super.dispose(e,t)}normalizeToUnitCube(e=!0,t=!1,s){let i=null,r=null;t&&(this.rotationQuaternion?(r=this.rotationQuaternion.clone(),this.rotationQuaternion.copyFromFloats(0,0,0,1)):this.rotation&&(i=this.rotation.clone(),this.rotation.copyFromFloats(0,0,0)));const n=this.getHierarchyBoundingVectors(e,s),a=n.max.subtract(n.min),o=Math.max(a.x,a.y,a.z);if(0===o)return this;const h=1/o;return this.scaling.scaleInPlace(h),t&&(this.rotationQuaternion&&r?this.rotationQuaternion.copyFrom(r):this.rotation&&i&&this.rotation.copyFrom(i)),this}_syncAbsoluteScalingAndRotation(){this._isAbsoluteSynced||(this._worldMatrix.decompose(this._absoluteScaling,this._absoluteRotationQuaternion),this._isAbsoluteSynced=!0)}}var xs;Rs.BILLBOARDMODE_NONE=0,Rs.BILLBOARDMODE_X=1,Rs.BILLBOARDMODE_Y=2,Rs.BILLBOARDMODE_Z=4,Rs.BILLBOARDMODE_ALL=7,Rs.BILLBOARDMODE_USE_POSITION=128,Rs.BillboardUseParentOrientation=!1,Rs._TmpRotation=G.Zero(),Rs._TmpScaling=U.Zero(),Rs._TmpTranslation=U.Zero(),Rs._LookAtVectorCache=new U(0,0,0),Rs._RotationAxisCache=new G,e([c("position")],Rs.prototype,"_position",void 0),e([c("rotation")],Rs.prototype,"_rotation",void 0),e([(xs="rotationQuaternion",r(10,xs))],Rs.prototype,"_rotationQuaternion",void 0),e([c("scaling")],Rs.prototype,"_scaling",void 0),e([a("billboardMode")],Rs.prototype,"_billboardMode",void 0),e([a()],Rs.prototype,"scalingDeterminant",void 0),e([a("infiniteDistance")],Rs.prototype,"_infiniteDistance",void 0),e([a()],Rs.prototype,"ignoreNonUniformScaling",void 0),e([a()],Rs.prototype,"reIntegrateRotationIntoRotationQuaternion",void 0);class Ms{constructor(){this.hit=!1,this.distance=0,this.pickedPoint=null,this.pickedMesh=null,this.bu=0,this.bv=0,this.faceId=-1,this.subMeshFaceId=-1,this.subMeshId=0,this.pickedSprite=null,this.thinInstanceIndex=-1,this.ray=null,this.originMesh=null,this.aimTransform=null,this.gripTransform=null}getNormal(e=!1,t=!0){if(!this.pickedMesh||t&&!this.pickedMesh.isVerticesDataPresent(ns.NormalKind))return null;let s,i=this.pickedMesh.getIndices();0===i?.length&&(i=null);const r=z.Vector3[0],n=z.Vector3[1],a=z.Vector3[2];if(t){const e=this.pickedMesh.getVerticesData(ns.NormalKind);let t=i?U.FromArrayToRef(e,3*i[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),o=i?U.FromArrayToRef(e,3*i[3*this.faceId+1],n):n.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),h=i?U.FromArrayToRef(e,3*i[3*this.faceId+2],a):a.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]);t=t.scale(this.bu),o=o.scale(this.bv),h=h.scale(1-this.bu-this.bv),s=new U(t.x+o.x+h.x,t.y+o.y+h.y,t.z+o.z+h.z)}else{const e=this.pickedMesh.getVerticesData(ns.PositionKind),t=i?U.FromArrayToRef(e,3*i[3*this.faceId],r):r.copyFromFloats(e[3*this.faceId*3],e[3*this.faceId*3+1],e[3*this.faceId*3+2]),o=i?U.FromArrayToRef(e,3*i[3*this.faceId+1],n):n.copyFromFloats(e[3*(3*this.faceId+1)],e[3*(3*this.faceId+1)+1],e[3*(3*this.faceId+1)+2]),h=i?U.FromArrayToRef(e,3*i[3*this.faceId+2],a):a.copyFromFloats(e[3*(3*this.faceId+2)],e[3*(3*this.faceId+2)+1],e[3*(3*this.faceId+2)+2]),l=t.subtract(o),c=h.subtract(o);s=U.Cross(l,c)}const o=(e,t)=>{let s=e.getWorldMatrix();e.nonUniformScaling&&(z.Matrix[0].copyFrom(s),s=z.Matrix[0],s.setTranslationFromFloats(0,0,0),s.invert(),s.transposeToRef(z.Matrix[1]),s=z.Matrix[1]),U.TransformNormalToRef(t,s,t)};if(e&&o(this.pickedMesh,s),this.ray){const t=z.Vector3[0].copyFrom(s);e||o(this.pickedMesh,t),U.Dot(t,this.ray.direction)>0&&s.negateInPlace()}return s.normalize(),s}getTextureCoordinates(e=ns.UVKind){if(!this.pickedMesh||!this.pickedMesh.isVerticesDataPresent(e))return null;const t=this.pickedMesh.getIndices();if(!t)return null;const s=this.pickedMesh.getVerticesData(e);if(!s)return null;let i=B.FromArray(s,2*t[3*this.faceId]),r=B.FromArray(s,2*t[3*this.faceId+1]),n=B.FromArray(s,2*t[3*this.faceId+2]);return i=i.scale(this.bu),r=r.scale(this.bv),n=n.scale(1-this.bu-this.bv),new B(i.x+r.x+n.x,i.y+r.y+n.y)}}class Is{constructor(){this.shaderLanguage=0}postProcessor(e,t,s,i,r){if(r.drawBuffersExtensionDisabled){const t=/#extension.+GL_EXT_draw_buffers.+(enable|require)/g;e=e.replace(t,"")}return e}}const Ss=/(flat\s)?\s*varying\s*.*/;class vs{constructor(){this.shaderLanguage=0}attributeProcessor(e){return e.replace("attribute","in")}varyingCheck(e,t){return Ss.test(e)}varyingProcessor(e,t){return e.replace("varying",t?"in":"out")}postProcessor(e,t,s){const i=-1!==e.search(/#extension.+GL_EXT_draw_buffers.+require/);if(e=(e=e.replace(/#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g,"")).replace(/texture2D\s*\(/g,"texture("),s){const t=-1!==e.search(/layout *\(location *= *0\) *out/g);e=(e=(e=(e=(e=(e=(e=e.replace(/texture2DLodEXT\s*\(/g,"textureLod(")).replace(/textureCubeLodEXT\s*\(/g,"textureLod(")).replace(/textureCube\s*\(/g,"texture(")).replace(/gl_FragDepthEXT/g,"gl_FragDepth")).replace(/gl_FragColor/g,"glFragColor")).replace(/gl_FragData/g,"glFragData")).replace(/void\s+?main\s*\(/g,(i||t?"":"layout(location = 0) out vec4 glFragColor;\n")+"void main(")}else{if(-1!==t.indexOf("#define MULTIVIEW"))return"#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n"+e}return e}}class Cs extends is{constructor(e){super(),this._buffer=e}get underlyingResource(){return this._buffer}}class Ps{get underlyingResource(){return this._webGLTexture}constructor(e=null,t){if(this._MSAARenderBuffers=null,this._context=t,!e&&!(e=t.createTexture()))throw new Error("Unable to create webGL texture");this.set(e)}setUsage(){}set(e){this._webGLTexture=e}reset(){this._webGLTexture=null,this._MSAARenderBuffers=null}addMSAARenderBuffer(e){this._MSAARenderBuffers||(this._MSAARenderBuffers=[]),this._MSAARenderBuffers.push(e)}releaseMSAARenderBuffers(){if(this._MSAARenderBuffers){for(const e of this._MSAARenderBuffers)this._context.deleteRenderbuffer(e);this._MSAARenderBuffers=null}}getMSAARenderBuffer(e=0){return this._MSAARenderBuffers?.[e]??null}release(){this.releaseMSAARenderBuffers(),this._webGLTexture&&this._context.deleteTexture(this._webGLTexture),this.reset()}}class Os{}class Ds extends yt{get name(){return this._name}set name(e){this._name=e}get version(){return this._webGLVersion}static get ShadersRepository(){return ut.ShadersRepository}static set ShadersRepository(e){ut.ShadersRepository=e}get supportsUniformBuffers(){return this.webGLVersion>1&&!this.disableUniformBuffers}get needPOTTextures(){return this._webGLVersion<2||this.forcePOTTextures}get _supportsHardwareTextureRescaling(){return!1}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e}snapshotRenderingReset(){this.snapshotRendering=!1}constructor(e,t,s,i){if(s=s||{},super(t??s.antialias,s,i),this._name="WebGL",this.forcePOTTextures=!1,this.validateShaderPrograms=!1,this.disableUniformBuffers=!1,this._webGLVersion=1,this._vertexAttribArraysEnabled=[],this._uintIndicesCurrentlySet=!1,this._currentBoundBuffer=new Array,this._currentFramebuffer=null,this._dummyFramebuffer=null,this._currentBufferPointers=new Array,this._currentInstanceLocations=new Array,this._currentInstanceBuffers=new Array,this._vaoRecordInProgress=!1,this._mustWipeVertexAttributes=!1,this._nextFreeTextureSlots=new Array,this._maxSimultaneousTextures=0,this._maxMSAASamplesOverride=null,this._unpackFlipYCached=null,this.enableUnpackFlipYCached=!0,this._boundUniforms={},!e)return;let r=null;if(e.getContext){if(r=e,this._renderingCanvas=r,void 0===s.preserveDrawingBuffer&&(s.preserveDrawingBuffer=!1),void 0===s.xrCompatible&&(s.xrCompatible=!1),navigator&&navigator.userAgent){this._setupMobileChecks();const e=navigator.userAgent;for(const t of Ds.ExceptionList){const i=t.key,r=t.targets;if(new RegExp(i).test(e)){if(t.capture&&t.captureConstraint){const s=t.capture,i=t.captureConstraint,r=new RegExp(s).exec(e);if(r&&r.length>0){if(parseInt(r[r.length-1])>=i)continue}}for(const e of r)switch(e){case"uniformBuffer":this.disableUniformBuffers=!0;break;case"vao":this.disableVertexArrayObjects=!0;break;case"antialias":s.antialias=!1;break;case"maxMSAASamples":this._maxMSAASamplesOverride=1}}}}if(this._doNotHandleContextLost||(this._onContextLost=e=>{e.preventDefault(),this._contextWasLost=!0,ue.Warn("WebGL context lost."),this.onContextLostObservable.notifyObservers(this)},this._onContextRestored=()=>{this._restoreEngineAfterContextLost((()=>this._initGLContext()))},r.addEventListener("webglcontextlost",this._onContextLost,!1),r.addEventListener("webglcontextrestored",this._onContextRestored,!1),s.powerPreference=s.powerPreference||"high-performance"),this._badDesktopOS&&(s.xrCompatible=!1),!s.disableWebGL2Support)try{this._gl=r.getContext("webgl2",s)||r.getContext("experimental-webgl2",s),this._gl&&(this._webGLVersion=2,this._shaderPlatformName="WEBGL2",this._gl.deleteQuery||(this._webGLVersion=1,this._shaderPlatformName="WEBGL1"))}catch(e){}if(!this._gl){if(!r)throw new Error("The provided canvas is null or undefined.");try{this._gl=r.getContext("webgl",s)||r.getContext("experimental-webgl",s)}catch(e){throw new Error("WebGL not supported")}}if(!this._gl)throw new Error("WebGL not supported")}else{this._gl=e,this._renderingCanvas=this._gl.canvas,this._gl.renderbufferStorageMultisample?(this._webGLVersion=2,this._shaderPlatformName="WEBGL2"):this._shaderPlatformName="WEBGL1";const t=this._gl.getContextAttributes();t&&(s.stencil=t.stencil)}this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),void 0!==s.useHighPrecisionFloats&&(this._highPrecisionShadersAllowed=s.useHighPrecisionFloats),this.resize(),this._initGLContext(),this._initFeatures();for(let e=0;e<this._caps.maxVertexAttribs;e++)this._currentBufferPointers[e]=new Os;this._shaderProcessor=this.webGLVersion>1?new vs:new Is;const n=`Babylon.js v${Ds.Version}`;ue.Log(n+` - ${this.description}`),this._renderingCanvas&&this._renderingCanvas.setAttribute&&this._renderingCanvas.setAttribute("data-engine",n);const a=st(this._gl);a.validateShaderPrograms=this.validateShaderPrograms,a.parallelShaderCompile=this._caps.parallelShaderCompile}_clearEmptyResources(){this._dummyFramebuffer=null,super._clearEmptyResources()}_getShaderProcessingContext(e){return null}areAllEffectsReady(){for(const e in this._compiledEffects){if(!this._compiledEffects[e].isReady())return!1}return!0}_initGLContext(){this._caps={maxTexturesImageUnits:this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),maxCombinedTexturesImageUnits:this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxVertexTextureImageUnits:this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxTextureSize:this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),maxSamples:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_SAMPLES):1,maxCubemapTextureSize:this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderTextureSize:this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),maxVertexAttribs:this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),maxVaryingVectors:this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),maxFragmentUniformVectors:this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),maxVertexUniformVectors:this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),parallelShaderCompile:this._gl.getExtension("KHR_parallel_shader_compile")||void 0,standardDerivatives:this._webGLVersion>1||null!==this._gl.getExtension("OES_standard_derivatives"),maxAnisotropy:1,astc:this._gl.getExtension("WEBGL_compressed_texture_astc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_astc"),bptc:this._gl.getExtension("EXT_texture_compression_bptc")||this._gl.getExtension("WEBKIT_EXT_texture_compression_bptc"),s3tc:this._gl.getExtension("WEBGL_compressed_texture_s3tc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc"),s3tc_srgb:this._gl.getExtension("WEBGL_compressed_texture_s3tc_srgb")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc_srgb"),pvrtc:this._gl.getExtension("WEBGL_compressed_texture_pvrtc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),etc1:this._gl.getExtension("WEBGL_compressed_texture_etc1")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc1"),etc2:this._gl.getExtension("WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBKIT_WEBGL_compressed_texture_etc")||this._gl.getExtension("WEBGL_compressed_texture_es3_0"),textureAnisotropicFilterExtension:this._gl.getExtension("EXT_texture_filter_anisotropic")||this._gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this._gl.getExtension("MOZ_EXT_texture_filter_anisotropic"),uintIndices:this._webGLVersion>1||null!==this._gl.getExtension("OES_element_index_uint"),fragmentDepthSupported:this._webGLVersion>1||null!==this._gl.getExtension("EXT_frag_depth"),highPrecisionShaderSupported:!1,timerQuery:this._gl.getExtension("EXT_disjoint_timer_query_webgl2")||this._gl.getExtension("EXT_disjoint_timer_query"),supportOcclusionQuery:this._webGLVersion>1,canUseTimestampForTimerQuery:!1,drawBuffersExtension:!1,maxMSAASamples:1,colorBufferFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_float")),supportFloatTexturesResolve:!1,rg11b10ufColorRenderable:!1,colorBufferHalfFloat:!!(this._webGLVersion>1&&this._gl.getExtension("EXT_color_buffer_half_float")),textureFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_float")),textureHalfFloat:!!(this._webGLVersion>1||this._gl.getExtension("OES_texture_half_float")),textureHalfFloatRender:!1,textureFloatLinearFiltering:!1,textureFloatRender:!1,textureHalfFloatLinearFiltering:!1,vertexArrayObject:!1,instancedArrays:!1,textureLOD:!!(this._webGLVersion>1||this._gl.getExtension("EXT_shader_texture_lod")),texelFetch:1!==this._webGLVersion,blendMinMax:!1,multiview:this._gl.getExtension("OVR_multiview2"),oculusMultiview:this._gl.getExtension("OCULUS_multiview"),depthTextureExtension:!1,canUseGLInstanceID:this._webGLVersion>1,canUseGLVertexID:this._webGLVersion>1,supportComputeShaders:!1,supportSRGBBuffers:!1,supportTransformFeedbacks:this._webGLVersion>1,textureMaxLevel:this._webGLVersion>1,texture2DArrayMaxLayerCount:this._webGLVersion>1?this._gl.getParameter(this._gl.MAX_ARRAY_TEXTURE_LAYERS):128,disableMorphTargetTexture:!1},this._caps.supportFloatTexturesResolve=this._caps.colorBufferFloat,this._caps.rg11b10ufColorRenderable=this._caps.colorBufferFloat,this._glVersion=this._gl.getParameter(this._gl.VERSION);const e=this._gl.getExtension("WEBGL_debug_renderer_info");if(null!=e&&(this._glRenderer=this._gl.getParameter(e.UNMASKED_RENDERER_WEBGL),this._glVendor=this._gl.getParameter(e.UNMASKED_VENDOR_WEBGL)),this._glVendor||(this._glVendor=this._gl.getParameter(this._gl.VENDOR)||"Unknown vendor"),this._glRenderer||(this._glRenderer=this._gl.getParameter(this._gl.RENDERER)||"Unknown renderer"),36193!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=36193),34842!==this._gl.RGBA16F&&(this._gl.RGBA16F=34842),34836!==this._gl.RGBA32F&&(this._gl.RGBA32F=34836),35056!==this._gl.DEPTH24_STENCIL8&&(this._gl.DEPTH24_STENCIL8=35056),this._caps.timerQuery&&(1===this._webGLVersion&&(this._gl.getQuery=this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery)),this._caps.canUseTimestampForTimerQuery=(this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT,this._caps.timerQuery.QUERY_COUNTER_BITS_EXT)??0)>0),this._caps.maxAnisotropy=this._caps.textureAnisotropicFilterExtension?this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT):0,this._caps.textureFloatLinearFiltering=!(!this._caps.textureFloat||!this._gl.getExtension("OES_texture_float_linear")),this._caps.textureFloatRender=!(!this._caps.textureFloat||!this._canRenderToFloatFramebuffer()),this._caps.textureHalfFloatLinearFiltering=!!(this._webGLVersion>1||this._caps.textureHalfFloat&&this._gl.getExtension("OES_texture_half_float_linear")),this._caps.astc&&(this._gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR=this._caps.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR),this._caps.bptc&&(this._gl.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT=this._caps.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT),this._caps.s3tc_srgb&&(this._gl.COMPRESSED_SRGB_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,this._gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=this._caps.s3tc_srgb.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT),this._caps.etc2&&(this._gl.COMPRESSED_SRGB8_ETC2=this._caps.etc2.COMPRESSED_SRGB8_ETC2,this._gl.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=this._caps.etc2.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC),this._webGLVersion>1&&5131!==this._gl.HALF_FLOAT_OES&&(this._gl.HALF_FLOAT_OES=5131),this._caps.textureHalfFloatRender=this._caps.textureHalfFloat&&this._canRenderToHalfFloatFramebuffer(),this._webGLVersion>1)this._caps.drawBuffersExtension=!0,this._caps.maxMSAASamples=null!==this._maxMSAASamplesOverride?this._maxMSAASamplesOverride:this._gl.getParameter(this._gl.MAX_SAMPLES);else{const e=this._gl.getExtension("WEBGL_draw_buffers");if(null!==e){this._caps.drawBuffersExtension=!0,this._gl.drawBuffers=e.drawBuffersWEBGL.bind(e),this._gl.DRAW_FRAMEBUFFER=this._gl.FRAMEBUFFER;for(let t=0;t<16;t++)this._gl["COLOR_ATTACHMENT"+t+"_WEBGL"]=e["COLOR_ATTACHMENT"+t+"_WEBGL"]}}if(this._webGLVersion>1)this._caps.depthTextureExtension=!0;else{const e=this._gl.getExtension("WEBGL_depth_texture");null!=e&&(this._caps.depthTextureExtension=!0,this._gl.UNSIGNED_INT_24_8=e.UNSIGNED_INT_24_8_WEBGL)}if(this.disableVertexArrayObjects)this._caps.vertexArrayObject=!1;else if(this._webGLVersion>1)this._caps.vertexArrayObject=!0;else{const e=this._gl.getExtension("OES_vertex_array_object");null!=e&&(this._caps.vertexArrayObject=!0,this._gl.createVertexArray=e.createVertexArrayOES.bind(e),this._gl.bindVertexArray=e.bindVertexArrayOES.bind(e),this._gl.deleteVertexArray=e.deleteVertexArrayOES.bind(e))}if(this._webGLVersion>1)this._caps.instancedArrays=!0;else{const e=this._gl.getExtension("ANGLE_instanced_arrays");null!=e?(this._caps.instancedArrays=!0,this._gl.drawArraysInstanced=e.drawArraysInstancedANGLE.bind(e),this._gl.drawElementsInstanced=e.drawElementsInstancedANGLE.bind(e),this._gl.vertexAttribDivisor=e.vertexAttribDivisorANGLE.bind(e)):this._caps.instancedArrays=!1}if(this._gl.getShaderPrecisionFormat){const e=this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER,this._gl.HIGH_FLOAT),t=this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER,this._gl.HIGH_FLOAT);e&&t&&(this._caps.highPrecisionShaderSupported=0!==e.precision&&0!==t.precision)}if(this._webGLVersion>1)this._caps.blendMinMax=!0;else{const e=this._gl.getExtension("EXT_blend_minmax");null!=e&&(this._caps.blendMinMax=!0,this._gl.MAX=e.MAX_EXT,this._gl.MIN=e.MIN_EXT)}if(!this._caps.supportSRGBBuffers){if(this._webGLVersion>1)this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:WebGL2RenderingContext.SRGB,SRGB8:WebGL2RenderingContext.SRGB8,SRGB8_ALPHA8:WebGL2RenderingContext.SRGB8_ALPHA8};else{const e=this._gl.getExtension("EXT_sRGB");null!=e&&(this._caps.supportSRGBBuffers=!0,this._glSRGBExtensionValues={SRGB:e.SRGB_EXT,SRGB8:e.SRGB_ALPHA_EXT,SRGB8_ALPHA8:e.SRGB_ALPHA_EXT})}this._caps.supportSRGBBuffers=this._caps.supportSRGBBuffers&&!(!this._creationOptions||!this._creationOptions.forceSRGBBufferSupportState)}this._depthCullingState.depthTest=!0,this._depthCullingState.depthFunc=this._gl.LEQUAL,this._depthCullingState.depthMask=!0,this._maxSimultaneousTextures=this._caps.maxCombinedTexturesImageUnits;for(let e=0;e<this._maxSimultaneousTextures;e++)this._nextFreeTextureSlots.push(e);"Mali-G72"===this._glRenderer&&(this._caps.disableMorphTargetTexture=!0)}_initFeatures(){this._features={forceBitmapOverHTMLImageElement:"undefined"==typeof HTMLImageElement,supportRenderAndCopyToLodForFloatTextures:1!==this._webGLVersion,supportDepthStencilTexture:1!==this._webGLVersion,supportShadowSamplers:1!==this._webGLVersion,uniformBufferHardCheckMatrix:!1,allowTexturePrefiltering:1!==this._webGLVersion,trackUbosInFrame:!1,checkUbosContentBeforeUpload:!1,supportCSM:1!==this._webGLVersion,basisNeedsPOT:1===this._webGLVersion,support3DTextures:1!==this._webGLVersion,needTypeSuffixInShaderConstants:1!==this._webGLVersion,supportMSAA:1!==this._webGLVersion,supportSSAO2:1!==this._webGLVersion,supportIBLShadows:1!==this._webGLVersion,supportExtendedTextureFormats:1!==this._webGLVersion,supportSwitchCaseInShader:1!==this._webGLVersion,supportSyncTextureRead:!0,needsInvertingBitmap:!0,useUBOBindingCache:!0,needShaderCodeInlining:!1,needToAlwaysBindUniformBuffers:!1,supportRenderPasses:!1,supportSpriteInstancing:!0,forceVertexBufferStrideAndOffsetMultiple4Bytes:!1,_checkNonFloatVertexBuffersDontRecreatePipelineContext:!1,_collectUbosUpdatedInFrame:!1}}get webGLVersion(){return this._webGLVersion}getClassName(){return"ThinEngine"}_prepareWorkingCanvas(){if(this._workingCanvas)return;this._workingCanvas=this.createCanvas(1,1);const e=this._workingCanvas.getContext("2d");e&&(this._workingContext=e)}getInfo(){return this.getGlInfo()}getGlInfo(){return{vendor:this._glVendor,renderer:this._glRenderer,version:this._glVersion}}extractDriverInfo(){const e=this.getGlInfo();return e&&e.renderer?e.renderer:""}getRenderWidth(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.width:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferWidth:this._gl.drawingBufferWidth}getRenderHeight(e=!1){return!e&&this._currentRenderTarget?this._currentRenderTarget.height:this._framebufferDimensionsObject?this._framebufferDimensionsObject.framebufferHeight:this._gl.drawingBufferHeight}clear(e,t,s,i=!1){const r=this.stencilStateComposer.useStencilGlobalOnly;this.stencilStateComposer.useStencilGlobalOnly=!0,this.applyStates(),this.stencilStateComposer.useStencilGlobalOnly=r;let n=0;if(t&&e){let t=!0;if(this._currentRenderTarget){const s=this._currentRenderTarget.texture?.format;if(s===Ze.TEXTUREFORMAT_RED_INTEGER||s===Ze.TEXTUREFORMAT_RG_INTEGER||s===Ze.TEXTUREFORMAT_RGB_INTEGER||s===Ze.TEXTUREFORMAT_RGBA_INTEGER){const s=this._currentRenderTarget.texture?.type;s===Ze.TEXTURETYPE_UNSIGNED_INTEGER||s===Ze.TEXTURETYPE_UNSIGNED_SHORT?(Ds._TempClearColorUint32[0]=255*e.r,Ds._TempClearColorUint32[1]=255*e.g,Ds._TempClearColorUint32[2]=255*e.b,Ds._TempClearColorUint32[3]=255*e.a,this._gl.clearBufferuiv(this._gl.COLOR,0,Ds._TempClearColorUint32),t=!1):(Ds._TempClearColorInt32[0]=255*e.r,Ds._TempClearColorInt32[1]=255*e.g,Ds._TempClearColorInt32[2]=255*e.b,Ds._TempClearColorInt32[3]=255*e.a,this._gl.clearBufferiv(this._gl.COLOR,0,Ds._TempClearColorInt32),t=!1)}}t&&(this._gl.clearColor(e.r,e.g,e.b,void 0!==e.a?e.a:1),n|=this._gl.COLOR_BUFFER_BIT)}s&&(this.useReverseDepthBuffer?(this._depthCullingState.depthFunc=this._gl.GEQUAL,this._gl.clearDepth(0)):this._gl.clearDepth(1),n|=this._gl.DEPTH_BUFFER_BIT),i&&(this._gl.clearStencil(0),n|=this._gl.STENCIL_BUFFER_BIT),this._gl.clear(n)}_viewport(e,t,s,i){e===this._viewportCached.x&&t===this._viewportCached.y&&s===this._viewportCached.z&&i===this._viewportCached.w||(this._viewportCached.x=e,this._viewportCached.y=t,this._viewportCached.z=s,this._viewportCached.w=i,this._gl.viewport(e,t,s,i))}endFrame(){super.endFrame(),this._badOS&&this.flushFramebuffer()}get performanceMonitor(){throw new Error("Not Supported by ThinEngine")}bindFramebuffer(e,t=0,s,i,r,n=0,a=0){const o=e;this._currentRenderTarget&&this.unBindFramebuffer(this._currentRenderTarget),this._currentRenderTarget=e,this._bindUnboundFramebuffer(o._MSAAFramebuffer?o._MSAAFramebuffer:o._framebuffer);const h=this._gl;e.isMulti||(e.is2DArray||e.is3D?(h.framebufferTextureLayer(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,e.texture._hardwareTexture?.underlyingResource,n,a),o._currentLOD=n):e.isCube?h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,h.TEXTURE_CUBE_MAP_POSITIVE_X+t,e.texture._hardwareTexture?.underlyingResource,n):o._currentLOD!==n&&(h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,h.TEXTURE_2D,e.texture._hardwareTexture?.underlyingResource,n),o._currentLOD=n));const l=e._depthStencilTexture;if(l){e.is3D&&(e.texture.width===l.width&&e.texture.height===l.height&&e.texture.depth===l.depth||ue.Warn("Depth/Stencil attachment for 3D target must have same dimensions as color attachment"));const s=e._depthStencilTextureWithStencil?h.DEPTH_STENCIL_ATTACHMENT:h.DEPTH_ATTACHMENT;e.is2DArray||e.is3D?h.framebufferTextureLayer(h.FRAMEBUFFER,s,l._hardwareTexture?.underlyingResource,n,a):e.isCube?h.framebufferTexture2D(h.FRAMEBUFFER,s,h.TEXTURE_CUBE_MAP_POSITIVE_X+t,l._hardwareTexture?.underlyingResource,n):h.framebufferTexture2D(h.FRAMEBUFFER,s,h.TEXTURE_2D,l._hardwareTexture?.underlyingResource,n)}this._cachedViewport&&!r?this.setViewport(this._cachedViewport,s,i):(s||(s=e.width,n&&(s/=Math.pow(2,n))),i||(i=e.height,n&&(i/=Math.pow(2,n))),this._viewport(0,0,s,i)),this.wipeCaches()}setState(e,t=0,s,i=!1,r,n,a=0){(this._depthCullingState.cull!==e||s)&&(this._depthCullingState.cull=e);const o=this.cullBackFaces??r??1?this._gl.BACK:this._gl.FRONT;(this._depthCullingState.cullFace!==o||s)&&(this._depthCullingState.cullFace=o),this.setZOffset(t),this.setZOffsetUnits(a);const h=i?this._gl.CW:this._gl.CCW;(this._depthCullingState.frontFace!==h||s)&&(this._depthCullingState.frontFace=h),this._stencilStateComposer.stencilMaterial=n}_bindUnboundFramebuffer(e){this._currentFramebuffer!==e&&(this._gl.bindFramebuffer(this._gl.FRAMEBUFFER,e),this._currentFramebuffer=e)}_currentFrameBufferIsDefaultFrameBuffer(){return null===this._currentFramebuffer}generateMipmaps(e){const t=this._getTextureTarget(e);this._bindTextureDirectly(t,e,!0),this._gl.generateMipmap(t),this._bindTextureDirectly(t,null)}unBindFramebuffer(e,t=!1,s){const i=e;this._currentRenderTarget=null;const r=this._gl;if(i._MSAAFramebuffer){if(e.isMulti)return void this.unBindMultiColorAttachmentFramebuffer(e,t,s);r.bindFramebuffer(r.READ_FRAMEBUFFER,i._MSAAFramebuffer),r.bindFramebuffer(r.DRAW_FRAMEBUFFER,i._framebuffer),r.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,r.COLOR_BUFFER_BIT,r.NEAREST)}!e.texture?.generateMipMaps||t||e.isCube||this.generateMipmaps(e.texture),s&&(i._MSAAFramebuffer&&this._bindUnboundFramebuffer(i._framebuffer),s()),this._bindUnboundFramebuffer(null)}flushFramebuffer(){this._gl.flush()}restoreDefaultFramebuffer(){this._currentRenderTarget?this.unBindFramebuffer(this._currentRenderTarget):this._bindUnboundFramebuffer(null),this._cachedViewport&&this.setViewport(this._cachedViewport),this.wipeCaches()}_resetVertexBufferBinding(){this.bindArrayBuffer(null),this._cachedVertexBuffers=null}createVertexBuffer(e,t,s){return this._createVertexBuffer(e,this._gl.STATIC_DRAW)}_createVertexBuffer(e,t){const s=this._gl.createBuffer();if(!s)throw new Error("Unable to create vertex buffer");const i=new Cs(s);return this.bindArrayBuffer(i),"number"!=typeof e?e instanceof Array?(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Float32Array(e),t),i.capacity=4*e.length):(this._gl.bufferData(this._gl.ARRAY_BUFFER,e,t),i.capacity=e.byteLength):(this._gl.bufferData(this._gl.ARRAY_BUFFER,new Uint8Array(e),t),i.capacity=e),this._resetVertexBufferBinding(),i.references=1,i}createDynamicVertexBuffer(e,t){return this._createVertexBuffer(e,this._gl.DYNAMIC_DRAW)}_resetIndexBufferBinding(){this.bindIndexBuffer(null),this._cachedIndexBuffer=null}createIndexBuffer(e,t,s){const i=this._gl.createBuffer(),r=new Cs(i);if(!i)throw new Error("Unable to create index buffer");this.bindIndexBuffer(r);const n=this._normalizeIndexData(e);return this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,n,t?this._gl.DYNAMIC_DRAW:this._gl.STATIC_DRAW),this._resetIndexBufferBinding(),r.references=1,r.is32Bits=4===n.BYTES_PER_ELEMENT,r}_normalizeIndexData(e){if(2===e.BYTES_PER_ELEMENT)return e;if(this._caps.uintIndices){if(e instanceof Uint32Array)return e;for(let t=0;t<e.length;t++)if(e[t]>=65535)return new Uint32Array(e);return new Uint16Array(e)}return new Uint16Array(e)}bindArrayBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ARRAY_BUFFER)}bindUniformBlock(e,t,s){const i=e.program,r=this._gl.getUniformBlockIndex(i,t);this._gl.uniformBlockBinding(i,r,s)}bindIndexBuffer(e){this._vaoRecordInProgress||this._unbindVertexArrayObject(),this._bindBuffer(e,this._gl.ELEMENT_ARRAY_BUFFER)}_bindBuffer(e,t){(this._vaoRecordInProgress||this._currentBoundBuffer[t]!==e)&&(this._gl.bindBuffer(t,e?e.underlyingResource:null),this._currentBoundBuffer[t]=e)}updateArrayBuffer(e){this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,e)}_vertexAttribPointer(e,t,s,i,r,n,a){const o=this._currentBufferPointers[t];if(!o)return;let h=!1;o.active?(o.buffer!==e&&(o.buffer=e,h=!0),o.size!==s&&(o.size=s,h=!0),o.type!==i&&(o.type=i,h=!0),o.normalized!==r&&(o.normalized=r,h=!0),o.stride!==n&&(o.stride=n,h=!0),o.offset!==a&&(o.offset=a,h=!0)):(h=!0,o.active=!0,o.index=t,o.size=s,o.type=i,o.normalized=r,o.stride=n,o.offset=a,o.buffer=e),(h||this._vaoRecordInProgress)&&(this.bindArrayBuffer(e),i===this._gl.UNSIGNED_INT||i===this._gl.INT?this._gl.vertexAttribIPointer(t,s,i,n,a):this._gl.vertexAttribPointer(t,s,i,r,n,a))}_bindIndexBufferWithCache(e){null!=e&&this._cachedIndexBuffer!==e&&(this._cachedIndexBuffer=e,this.bindIndexBuffer(e),this._uintIndicesCurrentlySet=e.is32Bits)}_bindVertexBuffersAttributes(e,t,s){const i=t.getAttributesNames();this._vaoRecordInProgress||this._unbindVertexArrayObject(),this.unbindAllAttributes();for(let r=0;r<i.length;r++){const n=t.getAttributeLocation(r);if(n>=0){const t=i[r];let a=null;if(s&&(a=s[t]),a||(a=e[t]),!a)continue;this._gl.enableVertexAttribArray(n),this._vaoRecordInProgress||(this._vertexAttribArraysEnabled[n]=!0);const o=a.getBuffer();o&&(this._vertexAttribPointer(o,n,a.getSize(),a.type,a.normalized,a.byteStride,a.byteOffset),a.getIsInstanced()&&(this._gl.vertexAttribDivisor(n,a.getInstanceDivisor()),this._vaoRecordInProgress||(this._currentInstanceLocations.push(n),this._currentInstanceBuffers.push(o))))}}}recordVertexArrayObject(e,t,s,i){const r=this._gl.createVertexArray();if(!r)throw new Error("Unable to create VAO");return this._vaoRecordInProgress=!0,this._gl.bindVertexArray(r),this._mustWipeVertexAttributes=!0,this._bindVertexBuffersAttributes(e,s,i),this.bindIndexBuffer(t),this._vaoRecordInProgress=!1,this._gl.bindVertexArray(null),r}bindVertexArrayObject(e,t){this._cachedVertexArrayObject!==e&&(this._cachedVertexArrayObject=e,this._gl.bindVertexArray(e),this._cachedVertexBuffers=null,this._cachedIndexBuffer=null,this._uintIndicesCurrentlySet=null!=t&&t.is32Bits,this._mustWipeVertexAttributes=!0)}bindBuffersDirectly(e,t,s,i,r){if(this._cachedVertexBuffers!==e||this._cachedEffectForVertexBuffers!==r){this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=r;const t=r.getAttributesCount();this._unbindVertexArrayObject(),this.unbindAllAttributes();let n=0;for(let a=0;a<t;a++)if(a<s.length){const t=r.getAttributeLocation(a);t>=0&&(this._gl.enableVertexAttribArray(t),this._vertexAttribArraysEnabled[t]=!0,this._vertexAttribPointer(e,t,s[a],this._gl.FLOAT,!1,i,n)),n+=4*s[a]}}this._bindIndexBufferWithCache(t)}_unbindVertexArrayObject(){this._cachedVertexArrayObject&&(this._cachedVertexArrayObject=null,this._gl.bindVertexArray(null))}bindBuffers(e,t,s,i){this._cachedVertexBuffers===e&&this._cachedEffectForVertexBuffers===s||(this._cachedVertexBuffers=e,this._cachedEffectForVertexBuffers=s,this._bindVertexBuffersAttributes(e,s,i)),this._bindIndexBufferWithCache(t)}unbindInstanceAttributes(){let e;for(let t=0,s=this._currentInstanceLocations.length;t<s;t++){const s=this._currentInstanceBuffers[t];e!=s&&s.references&&(e=s,this.bindArrayBuffer(s));const i=this._currentInstanceLocations[t];this._gl.vertexAttribDivisor(i,0)}this._currentInstanceBuffers.length=0,this._currentInstanceLocations.length=0}releaseVertexArrayObject(e){this._gl.deleteVertexArray(e)}_releaseBuffer(e){return e.references--,0===e.references&&(this._deleteBuffer(e),!0)}_deleteBuffer(e){this._gl.deleteBuffer(e.underlyingResource)}updateAndBindInstancesBuffer(e,t,s){if(this.bindArrayBuffer(e),t&&this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t),void 0!==s[0].index)this.bindInstancesBuffer(e,s,!0);else for(let t=0;t<4;t++){const i=s[t];this._vertexAttribArraysEnabled[i]||(this._gl.enableVertexAttribArray(i),this._vertexAttribArraysEnabled[i]=!0),this._vertexAttribPointer(e,i,4,this._gl.FLOAT,!1,64,16*t),this._gl.vertexAttribDivisor(i,1),this._currentInstanceLocations.push(i),this._currentInstanceBuffers.push(e)}}bindInstancesBuffer(e,t,s=!0){this.bindArrayBuffer(e);let i=0;if(s)for(let e=0;e<t.length;e++){i+=4*t[e].attributeSize}for(let s=0;s<t.length;s++){const r=t[s];void 0===r.index&&(r.index=this._currentEffect.getAttributeLocationByName(r.attributeName)),r.index<0||(this._vertexAttribArraysEnabled[r.index]||(this._gl.enableVertexAttribArray(r.index),this._vertexAttribArraysEnabled[r.index]=!0),this._vertexAttribPointer(e,r.index,r.attributeSize,r.attributeType||this._gl.FLOAT,r.normalized||!1,i,r.offset),this._gl.vertexAttribDivisor(r.index,void 0===r.divisor?1:r.divisor),this._currentInstanceLocations.push(r.index),this._currentInstanceBuffers.push(e))}}disableInstanceAttributeByName(e){if(!this._currentEffect)return;const t=this._currentEffect.getAttributeLocationByName(e);this.disableInstanceAttribute(t)}disableInstanceAttribute(e){let t,s=!1;for(;-1!==(t=this._currentInstanceLocations.indexOf(e));)this._currentInstanceLocations.splice(t,1),this._currentInstanceBuffers.splice(t,1),s=!0,t=this._currentInstanceLocations.indexOf(e);s&&(this._gl.vertexAttribDivisor(e,0),this.disableAttributeByIndex(e))}disableAttributeByIndex(e){this._gl.disableVertexAttribArray(e),this._vertexAttribArraysEnabled[e]=!1,this._currentBufferPointers[e].active=!1}draw(e,t,s,i){this.drawElementsType(e?Ze.MATERIAL_TriangleFillMode:Ze.MATERIAL_WireFrameFillMode,t,s,i)}drawPointClouds(e,t,s){this.drawArraysType(Ze.MATERIAL_PointFillMode,e,t,s)}drawUnIndexed(e,t,s,i){this.drawArraysType(e?Ze.MATERIAL_TriangleFillMode:Ze.MATERIAL_WireFrameFillMode,t,s,i)}drawElementsType(e,t,s,i){this.applyStates(),this._reportDrawCall();const r=this._drawMode(e),n=this._uintIndicesCurrentlySet?this._gl.UNSIGNED_INT:this._gl.UNSIGNED_SHORT,a=this._uintIndicesCurrentlySet?4:2;i?this._gl.drawElementsInstanced(r,s,n,t*a,i):this._gl.drawElements(r,s,n,t*a)}drawArraysType(e,t,s,i){this.applyStates(),this._reportDrawCall();const r=this._drawMode(e);i?this._gl.drawArraysInstanced(r,t,s,i):this._gl.drawArrays(r,t,s)}_drawMode(e){switch(e){case Ze.MATERIAL_TriangleFillMode:return this._gl.TRIANGLES;case Ze.MATERIAL_PointFillMode:return this._gl.POINTS;case Ze.MATERIAL_WireFrameFillMode:return this._gl.LINES;case Ze.MATERIAL_PointListDrawMode:return this._gl.POINTS;case Ze.MATERIAL_LineListDrawMode:return this._gl.LINES;case Ze.MATERIAL_LineLoopDrawMode:return this._gl.LINE_LOOP;case Ze.MATERIAL_LineStripDrawMode:return this._gl.LINE_STRIP;case Ze.MATERIAL_TriangleStripDrawMode:return this._gl.TRIANGLE_STRIP;case Ze.MATERIAL_TriangleFanDrawMode:return this._gl.TRIANGLE_FAN;default:return this._gl.TRIANGLES}}_releaseEffect(e){this._compiledEffects[e._key]&&delete this._compiledEffects[e._key];const t=e.getPipelineContext();t&&this._deletePipelineContext(t)}_deletePipelineContext(e){const t=e;t&&t.program&&(t.program.__SPECTOR_rebuildProgram=null,lt(t),this._gl.deleteProgram(t.program))}_getGlobalDefines(e){return Fe(e,this.isNDCHalfZRange,this.useReverseDepthBuffer,this.useExactSrgbConversions)}createEffect(e,t,s,i,r,n,a,o,h,l=0,c){const u="string"==typeof e?e:e.vertexToken||e.vertexSource||e.vertexElement||e.vertex,d="string"==typeof e?e:e.fragmentToken||e.fragmentSource||e.fragmentElement||e.fragment,_=this._getGlobalDefines();let f=r??t.defines??"";_&&(f+=_);const p=u+"+"+d+"@"+f;if(this._compiledEffects[p]){const e=this._compiledEffects[p];return a&&e.isReady()&&a(e),e._refCount++,e}this._gl&&st(this._gl);const m=new ut(e,t,s,i,this,r,n,a,o,h,p,t.shaderLanguage??l,t.extraInitializationsAsync??c);return this._compiledEffects[p]=m,m}_getShaderSource(e){return this._gl.getShaderSource(e)}createRawShaderProgram(e,t,s,i,r=null){const n=st(this._gl);return n._contextWasLost=this._contextWasLost,n.validateShaderPrograms=this.validateShaderPrograms,it(e,t,s,i||this._gl,r)}createShaderProgram(e,t,s,i,r,n=null){const a=st(this._gl);return a._contextWasLost=this._contextWasLost,a.validateShaderPrograms=this.validateShaderPrograms,rt(e,t,s,i,r||this._gl,n)}inlineShaderCode(e){return e}createPipelineContext(e){if(this._gl){st(this._gl).parallelShaderCompile=this._caps.parallelShaderCompile}const t=function(e){const t=new Je,s=st(e);return s.parallelShaderCompile&&(t.isParallelCompiled=!0),t.context=s._context,t}(this._gl);return t.engine=this,t}createMaterialContext(){}createDrawContext(){}_finalizePipelineContext(e){return at(e,this._gl,this.validateShaderPrograms)}_preparePipelineContext(e,t,s,i,r,n,a,o,h,l,c){const u=st(this._gl);return u._contextWasLost=this._contextWasLost,u.validateShaderPrograms=this.validateShaderPrograms,u._createShaderProgramInjection=this._createShaderProgram.bind(this),u.createRawShaderProgramInjection=this.createRawShaderProgram.bind(this),u.createShaderProgramInjection=this.createShaderProgram.bind(this),u.loadFileInjection=this._loadFile.bind(this),function(e,t,s,i,r,n,a,o,h,l="",c,u,d){const _=st(e.context);u||(u=_.createRawShaderProgramInjection??it),d||(d=_.createShaderProgramInjection??rt);const f=e;f.program=i?u(f,t,s,f.context,h):d(f,t,s,o,f.context,h),f.program.__SPECTOR_rebuildProgram=a,c()}(e,t,s,i,0,0,a,o,h,l,c)}_createShaderProgram(e,t,s,i,r=null){return nt(e,t,s,i,r)}_isRenderingStateCompiled(e){const t=e;return!this._isDisposed&&!t._isDisposed&&(!!this._gl.getProgramParameter(t.program,this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)&&(this._finalizePipelineContext(t),!0))}_executeWhenRenderingStateIsCompiled(e,t){!function(e,t){const s=e;if(!s.isParallelCompiled)return void t(e);const i=s.onCompiled;s.onCompiled=()=>{i?.(),t(e)}}(e,t)}getUniforms(e,t){const s=new Array,i=e;for(let e=0;e<t.length;e++)s.push(this._gl.getUniformLocation(i.program,t[e]));return s}getAttributes(e,t){const s=[],i=e;for(let e=0;e<t.length;e++)try{s.push(this._gl.getAttribLocation(i.program,t[e]))}catch(e){s.push(-1)}return s}enableEffect(e){(e=null!==e&&function(e){return void 0===e.getPipelineContext}(e)?e.effect:e)&&e!==this._currentEffect&&(this._stencilStateComposer.stencilMaterial=void 0,this.bindSamplers(e),this._currentEffect=e,e.onBind&&e.onBind(e),e._onBindObservable&&e._onBindObservable.notifyObservers(e))}setInt(e,t){return!!e&&(this._gl.uniform1i(e,t),!0)}setInt2(e,t,s){return!!e&&(this._gl.uniform2i(e,t,s),!0)}setInt3(e,t,s,i){return!!e&&(this._gl.uniform3i(e,t,s,i),!0)}setInt4(e,t,s,i,r){return!!e&&(this._gl.uniform4i(e,t,s,i,r),!0)}setIntArray(e,t){return!!e&&(this._gl.uniform1iv(e,t),!0)}setIntArray2(e,t){return!(!e||t.length%2!=0)&&(this._gl.uniform2iv(e,t),!0)}setIntArray3(e,t){return!(!e||t.length%3!=0)&&(this._gl.uniform3iv(e,t),!0)}setIntArray4(e,t){return!(!e||t.length%4!=0)&&(this._gl.uniform4iv(e,t),!0)}setUInt(e,t){return!!e&&(this._gl.uniform1ui(e,t),!0)}setUInt2(e,t,s){return!!e&&(this._gl.uniform2ui(e,t,s),!0)}setUInt3(e,t,s,i){return!!e&&(this._gl.uniform3ui(e,t,s,i),!0)}setUInt4(e,t,s,i,r){return!!e&&(this._gl.uniform4ui(e,t,s,i,r),!0)}setUIntArray(e,t){return!!e&&(this._gl.uniform1uiv(e,t),!0)}setUIntArray2(e,t){return!(!e||t.length%2!=0)&&(this._gl.uniform2uiv(e,t),!0)}setUIntArray3(e,t){return!(!e||t.length%3!=0)&&(this._gl.uniform3uiv(e,t),!0)}setUIntArray4(e,t){return!(!e||t.length%4!=0)&&(this._gl.uniform4uiv(e,t),!0)}setArray(e,t){return!!e&&(!(t.length<1)&&(this._gl.uniform1fv(e,t),!0))}setArray2(e,t){return!(!e||t.length%2!=0)&&(this._gl.uniform2fv(e,t),!0)}setArray3(e,t){return!(!e||t.length%3!=0)&&(this._gl.uniform3fv(e,t),!0)}setArray4(e,t){return!(!e||t.length%4!=0)&&(this._gl.uniform4fv(e,t),!0)}setMatrices(e,t){return!!e&&(this._gl.uniformMatrix4fv(e,!1,t),!0)}setMatrix3x3(e,t){return!!e&&(this._gl.uniformMatrix3fv(e,!1,t),!0)}setMatrix2x2(e,t){return!!e&&(this._gl.uniformMatrix2fv(e,!1,t),!0)}setFloat(e,t){return!!e&&(this._gl.uniform1f(e,t),!0)}setFloat2(e,t,s){return!!e&&(this._gl.uniform2f(e,t,s),!0)}setFloat3(e,t,s,i){return!!e&&(this._gl.uniform3f(e,t,s,i),!0)}setFloat4(e,t,s,i,r){return!!e&&(this._gl.uniform4f(e,t,s,i,r),!0)}applyStates(){if(this._depthCullingState.apply(this._gl),this._stencilStateComposer.apply(this._gl),this._alphaState.apply(this._gl),this._colorWriteChanged){this._colorWriteChanged=!1;const e=this._colorWrite;this._gl.colorMask(e,e,e,e)}}wipeCaches(e){this.preventCacheWipeBetweenFrames&&!e||(this._currentEffect=null,this._viewportCached.x=0,this._viewportCached.y=0,this._viewportCached.z=0,this._viewportCached.w=0,this._unbindVertexArrayObject(),e&&(this._currentProgram=null,this.resetTextureCache(),this._stencilStateComposer.reset(),this._depthCullingState.reset(),this._depthCullingState.depthFunc=this._gl.LEQUAL,this._alphaState.reset(),this._alphaMode=Ze.ALPHA_ADD,this._alphaEquation=Ze.ALPHA_DISABLE,this._colorWrite=!0,this._colorWriteChanged=!0,this._unpackFlipYCached=null,this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,this._gl.NONE),this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,0),this._mustWipeVertexAttributes=!0,this.unbindAllAttributes()),this._resetVertexBufferBinding(),this._cachedIndexBuffer=null,this._cachedEffectForVertexBuffers=null,this.bindIndexBuffer(null))}_getSamplingParameters(e,t){const s=this._gl;let i=s.NEAREST,r=s.NEAREST;switch(e){case Ze.TEXTURE_LINEAR_LINEAR_MIPNEAREST:i=s.LINEAR,r=t?s.LINEAR_MIPMAP_NEAREST:s.LINEAR;break;case Ze.TEXTURE_LINEAR_LINEAR_MIPLINEAR:i=s.LINEAR,r=t?s.LINEAR_MIPMAP_LINEAR:s.LINEAR;break;case Ze.TEXTURE_NEAREST_NEAREST_MIPLINEAR:i=s.NEAREST,r=t?s.NEAREST_MIPMAP_LINEAR:s.NEAREST;break;case Ze.TEXTURE_NEAREST_NEAREST_MIPNEAREST:i=s.NEAREST,r=t?s.NEAREST_MIPMAP_NEAREST:s.NEAREST;break;case Ze.TEXTURE_NEAREST_LINEAR_MIPNEAREST:i=s.NEAREST,r=t?s.LINEAR_MIPMAP_NEAREST:s.LINEAR;break;case Ze.TEXTURE_NEAREST_LINEAR_MIPLINEAR:i=s.NEAREST,r=t?s.LINEAR_MIPMAP_LINEAR:s.LINEAR;break;case Ze.TEXTURE_NEAREST_LINEAR:i=s.NEAREST,r=s.LINEAR;break;case Ze.TEXTURE_NEAREST_NEAREST:i=s.NEAREST,r=s.NEAREST;break;case Ze.TEXTURE_LINEAR_NEAREST_MIPNEAREST:i=s.LINEAR,r=t?s.NEAREST_MIPMAP_NEAREST:s.NEAREST;break;case Ze.TEXTURE_LINEAR_NEAREST_MIPLINEAR:i=s.LINEAR,r=t?s.NEAREST_MIPMAP_LINEAR:s.NEAREST;break;case Ze.TEXTURE_LINEAR_LINEAR:i=s.LINEAR,r=s.LINEAR;break;case Ze.TEXTURE_LINEAR_NEAREST:i=s.LINEAR,r=s.NEAREST}return{min:r,mag:i}}_createTexture(){const e=this._gl.createTexture();if(!e)throw new Error("Unable to create texture");return e}_createHardwareTexture(){return new Ps(this._createTexture(),this._gl)}_createInternalTexture(e,t,s=!0,i=0){let r,n=!1,a=Ze.TEXTURETYPE_UNSIGNED_INT,o=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,h=Ze.TEXTUREFORMAT_RGBA,l=!1,c=1;void 0!==t&&"object"==typeof t?(n=!!t.generateMipMaps,a=void 0===t.type?Ze.TEXTURETYPE_UNSIGNED_INT:t.type,o=void 0===t.samplingMode?Ze.TEXTURE_TRILINEAR_SAMPLINGMODE:t.samplingMode,h=void 0===t.format?Ze.TEXTUREFORMAT_RGBA:t.format,l=void 0!==t.useSRGBBuffer&&t.useSRGBBuffer,c=t.samples??1,r=t.label):n=!!t,l&&=this._caps.supportSRGBBuffers&&(this.webGLVersion>1||this.isWebGPU),(a!==Ze.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(a!==Ze.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(o=Ze.TEXTURE_NEAREST_SAMPLINGMODE),a!==Ze.TEXTURETYPE_FLOAT||this._caps.textureFloat||(a=Ze.TEXTURETYPE_UNSIGNED_INT,ue.Warn("Float textures are not supported. Type forced to TEXTURETYPE_UNSIGNED_BYTE"));const u=this._gl,d=new Tt(this,i),_=e.width||e,f=e.height||e,p=e.depth||0,m=e.layers||0,g=this._getSamplingParameters(o,n),T=0!==m?u.TEXTURE_2D_ARRAY:0!==p?u.TEXTURE_3D:u.TEXTURE_2D,E=this._getRGBABufferInternalSizedFormat(a,h,l),A=this._getInternalFormat(h),y=this._getWebGLTextureType(a);return this._bindTextureDirectly(T,d),0!==m?(d.is2DArray=!0,u.texImage3D(T,0,E,_,f,m,0,A,y,null)):0!==p?(d.is3D=!0,u.texImage3D(T,0,E,_,f,p,0,A,y,null)):u.texImage2D(T,0,E,_,f,0,A,y,null),u.texParameteri(T,u.TEXTURE_MAG_FILTER,g.mag),u.texParameteri(T,u.TEXTURE_MIN_FILTER,g.min),u.texParameteri(T,u.TEXTURE_WRAP_S,u.CLAMP_TO_EDGE),u.texParameteri(T,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE),n&&this._gl.generateMipmap(T),this._bindTextureDirectly(T,null),d._useSRGBBuffer=l,d.baseWidth=_,d.baseHeight=f,d.width=_,d.height=f,d.depth=m,d.isReady=!0,d.samples=c,d.generateMipMaps=n,d.samplingMode=o,d.type=a,d.format=h,d.label=r,this._internalTexturesCache.push(d),d}_getUseSRGBBuffer(e,t){return e&&this._caps.supportSRGBBuffers&&(this.webGLVersion>1||t)}createTexture(e,t,s,i,r=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,n=null,a=null,o=null,h=null,l=null,c=null,u,d,_,f){return this._createTextureBase(e,t,s,i,r,n,a,((...e)=>this._prepareWebGLTexture(...e,l)),((e,t,s,r,n,a)=>{const o=this._gl,h=s.width===e&&s.height===t;n._creationFlags=_??0;const l=this._getTexImageParametersForCreateTexture(n.format,n._useSRGBBuffer);if(h)return o.texImage2D(o.TEXTURE_2D,0,l.internalFormat,l.format,l.type,s),!1;const c=this._caps.maxTextureSize;if(s.width>c||s.height>c||!this._supportsHardwareTextureRescaling)return this._prepareWorkingCanvas(),!(!this._workingCanvas||!this._workingContext)&&(this._workingCanvas.width=e,this._workingCanvas.height=t,this._workingContext.drawImage(s,0,0,s.width,s.height,0,0,e,t),o.texImage2D(o.TEXTURE_2D,0,l.internalFormat,l.format,l.type,this._workingCanvas),n.width=e,n.height=t,!1);{const e=new Tt(this,2);this._bindTextureDirectly(o.TEXTURE_2D,e,!0),o.texImage2D(o.TEXTURE_2D,0,l.internalFormat,l.format,l.type,s),this._rescaleTexture(e,n,i,l.format,(()=>{this._releaseTexture(e),this._bindTextureDirectly(o.TEXTURE_2D,n,!0),a()}))}return!0}),o,h,l,c,u,d,f)}_getTexImageParametersForCreateTexture(e,t){let s,i;return 1===this.webGLVersion?(s=this._getInternalFormat(e,t),i=s):(s=this._getInternalFormat(e,!1),i=this._getRGBABufferInternalSizedFormat(Ze.TEXTURETYPE_UNSIGNED_BYTE,e,t)),{internalFormat:i,format:s,type:this._gl.UNSIGNED_BYTE}}_rescaleTexture(e,t,s,i,r){}_unpackFlipY(e){this._unpackFlipYCached!==e&&(this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL,e?1:0),this.enableUnpackFlipYCached&&(this._unpackFlipYCached=e))}_getUnpackAlignement(){return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT)}_getTextureTarget(e){return e.isCube?this._gl.TEXTURE_CUBE_MAP:e.is3D?this._gl.TEXTURE_3D:e.is2DArray||e.isMultiview?this._gl.TEXTURE_2D_ARRAY:this._gl.TEXTURE_2D}updateTextureSamplingMode(e,t,s=!1){const i=this._getTextureTarget(t),r=this._getSamplingParameters(e,t.useMipMaps||s);this._setTextureParameterInteger(i,this._gl.TEXTURE_MAG_FILTER,r.mag,t),this._setTextureParameterInteger(i,this._gl.TEXTURE_MIN_FILTER,r.min),s&&(t.generateMipMaps=!0,this._gl.generateMipmap(i)),this._bindTextureDirectly(i,null),t.samplingMode=e}updateTextureDimensions(e,t,s,i=1){}updateTextureWrappingMode(e,t,s=null,i=null){const r=this._getTextureTarget(e);null!==t&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t),e),e._cachedWrapU=t),null!==s&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(s),e),e._cachedWrapV=s),(e.is2DArray||e.is3D)&&null!==i&&(this._setTextureParameterInteger(r,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(i),e),e._cachedWrapR=i),this._bindTextureDirectly(r,null)}_uploadCompressedDataToTextureDirectly(e,t,s,i,r,n=0,a=0){const o=this._gl;let h=o.TEXTURE_2D;if(e.isCube&&(h=o.TEXTURE_CUBE_MAP_POSITIVE_X+n),e._useSRGBBuffer)switch(t){case Ze.TEXTUREFORMAT_COMPRESSED_RGB8_ETC2:case Ze.TEXTUREFORMAT_COMPRESSED_RGB_ETC1_WEBGL:this._caps.etc2?t=o.COMPRESSED_SRGB8_ETC2:e._useSRGBBuffer=!1;break;case Ze.TEXTUREFORMAT_COMPRESSED_RGBA8_ETC2_EAC:this._caps.etc2?t=o.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:e._useSRGBBuffer=!1;break;case Ze.TEXTUREFORMAT_COMPRESSED_RGBA_BPTC_UNORM:t=o.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT;break;case Ze.TEXTUREFORMAT_COMPRESSED_RGBA_ASTC_4x4:t=o.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;break;case Ze.TEXTUREFORMAT_COMPRESSED_RGB_S3TC_DXT1:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case Ze.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:e._useSRGBBuffer=!1;break;case Ze.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5:this._caps.s3tc_srgb?t=o.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:e._useSRGBBuffer=!1;break;default:e._useSRGBBuffer=!1}this._gl.compressedTexImage2D(h,a,t,s,i,0,r)}_uploadDataToTextureDirectly(e,t,s=0,i=0,r,n=!1){const a=this._gl,o=this._getWebGLTextureType(e.type),h=this._getInternalFormat(e.format),l=void 0===r?this._getRGBABufferInternalSizedFormat(e.type,e.format,e._useSRGBBuffer):this._getInternalFormat(r,e._useSRGBBuffer);this._unpackFlipY(e.invertY);let c=a.TEXTURE_2D;e.isCube&&(c=a.TEXTURE_CUBE_MAP_POSITIVE_X+s);const u=Math.round(Math.log(e.width)*Math.LOG2E),d=Math.round(Math.log(e.height)*Math.LOG2E),_=n?e.width:Math.pow(2,Math.max(u-i,0)),f=n?e.height:Math.pow(2,Math.max(d-i,0));a.texImage2D(c,i,l,_,f,0,h,o,t)}updateTextureData(e,t,s,i,r,n,a=0,o=0,h=!1){const l=this._gl,c=this._getWebGLTextureType(e.type),u=this._getInternalFormat(e.format);this._unpackFlipY(e.invertY);let d=l.TEXTURE_2D,_=l.TEXTURE_2D;e.isCube&&(_=l.TEXTURE_CUBE_MAP_POSITIVE_X+a,d=l.TEXTURE_CUBE_MAP),this._bindTextureDirectly(d,e,!0),l.texSubImage2D(_,o,s,i,r,n,u,c,t),h&&this._gl.generateMipmap(_),this._bindTextureDirectly(d,null)}_uploadArrayBufferViewToTexture(e,t,s=0,i=0){const r=this._gl,n=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(n,e,!0),this._uploadDataToTextureDirectly(e,t,s,i),this._bindTextureDirectly(n,null,!0)}_prepareWebGLTextureContinuation(e,t,s,i,r){const n=this._gl;if(!n)return;const a=this._getSamplingParameters(r,!s);n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,a.mag),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,a.min),s||i||n.generateMipmap(n.TEXTURE_2D),this._bindTextureDirectly(n.TEXTURE_2D,null),t&&t.removePendingData(e),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear()}_prepareWebGLTexture(e,t,s,i,r,n,a,o,h,l){const c=this.getCaps().maxTextureSize,u=Math.min(c,this.needPOTTextures?Wt(i.width,c):i.width),d=Math.min(c,this.needPOTTextures?Wt(i.height,c):i.height),_=this._gl;_&&(e._hardwareTexture?(this._bindTextureDirectly(_.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===r||!!r),e.baseWidth=i.width,e.baseHeight=i.height,e.width=u,e.height=d,e.isReady=!0,e.type=-1!==e.type?e.type:Ze.TEXTURETYPE_UNSIGNED_BYTE,e.format=-1!==e.format?e.format:l??(".jpg"!==t||e._useSRGBBuffer?Ze.TEXTUREFORMAT_RGBA:Ze.TEXTUREFORMAT_RGB),o(u,d,i,t,e,(()=>{this._prepareWebGLTextureContinuation(e,s,n,a,h)}))||this._prepareWebGLTextureContinuation(e,s,n,a,h)):s&&s.removePendingData(e))}_setupFramebufferDepthAttachments(e,t,s,i,r=1){const n=this._gl;if(e&&t)return this._createRenderBuffer(s,i,r,n.DEPTH_STENCIL,n.DEPTH24_STENCIL8,n.DEPTH_STENCIL_ATTACHMENT);if(t){let e=n.DEPTH_COMPONENT16;return this._webGLVersion>1&&(e=n.DEPTH_COMPONENT32F),this._createRenderBuffer(s,i,r,e,e,n.DEPTH_ATTACHMENT)}return e?this._createRenderBuffer(s,i,r,n.STENCIL_INDEX8,n.STENCIL_INDEX8,n.STENCIL_ATTACHMENT):null}_createRenderBuffer(e,t,s,i,r,n,a=!0){const o=this._gl.createRenderbuffer();return this._updateRenderBuffer(o,e,t,s,i,r,n,a)}_updateRenderBuffer(e,t,s,i,r,n,a,o=!0){const h=this._gl;return h.bindRenderbuffer(h.RENDERBUFFER,e),i>1&&h.renderbufferStorageMultisample?h.renderbufferStorageMultisample(h.RENDERBUFFER,i,n,t,s):h.renderbufferStorage(h.RENDERBUFFER,r,t,s),h.framebufferRenderbuffer(h.FRAMEBUFFER,a,h.RENDERBUFFER,e),o&&h.bindRenderbuffer(h.RENDERBUFFER,null),e}_releaseTexture(e){this._deleteTexture(e._hardwareTexture),this.unbindAllTextures();const t=this._internalTexturesCache.indexOf(e);-1!==t&&this._internalTexturesCache.splice(t,1),e._lodTextureHigh&&e._lodTextureHigh.dispose(),e._lodTextureMid&&e._lodTextureMid.dispose(),e._lodTextureLow&&e._lodTextureLow.dispose(),e._irradianceTexture&&e._irradianceTexture.dispose()}_deleteTexture(e){e?.release()}_setProgram(e){this._currentProgram!==e&&(!function(e,t){t.useProgram(e)}(e,this._gl),this._currentProgram=e)}bindSamplers(e){const t=e.getPipelineContext();this._setProgram(t.program);const s=e.getSamplers();for(let t=0;t<s.length;t++){const i=e.getUniform(s[t]);i&&(this._boundUniforms[t]=i)}this._currentEffect=null}_activateCurrentTexture(){this._currentTextureChannel!==this._activeChannel&&(this._gl.activeTexture(this._gl.TEXTURE0+this._activeChannel),this._currentTextureChannel=this._activeChannel)}_bindTextureDirectly(e,t,s=!1,i=!1){let r=!1;const n=t&&t._associatedChannel>-1;s&&n&&(this._activeChannel=t._associatedChannel);if(this._boundTexturesCache[this._activeChannel]!==t||i){if(this._activateCurrentTexture(),t&&t.isMultiview)throw ue.Error(["_bindTextureDirectly called with a multiview texture!",e,t]),"_bindTextureDirectly called with a multiview texture!";this._gl.bindTexture(e,t?._hardwareTexture?.underlyingResource??null),this._boundTexturesCache[this._activeChannel]=t,t&&(t._associatedChannel=this._activeChannel)}else s&&(r=!0,this._activateCurrentTexture());return n&&!s&&this._bindSamplerUniformToChannel(t._associatedChannel,this._activeChannel),r}_bindTexture(e,t,s){if(void 0===e)return;t&&(t._associatedChannel=e),this._activeChannel=e;const i=t?this._getTextureTarget(t):this._gl.TEXTURE_2D;this._bindTextureDirectly(i,t)}unbindAllTextures(){for(let e=0;e<this._maxSimultaneousTextures;e++)this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))}setTexture(e,t,s,i){void 0!==e&&(t&&(this._boundUniforms[e]=t),this._setTexture(e,s))}_bindSamplerUniformToChannel(e,t){const s=this._boundUniforms[e];s&&s._currentState!==t&&(this._gl.uniform1i(s,t),s._currentState=t)}_getTextureWrapMode(e){switch(e){case Ze.TEXTURE_WRAP_ADDRESSMODE:return this._gl.REPEAT;case Ze.TEXTURE_CLAMP_ADDRESSMODE:return this._gl.CLAMP_TO_EDGE;case Ze.TEXTURE_MIRROR_ADDRESSMODE:return this._gl.MIRRORED_REPEAT}return this._gl.REPEAT}_setTexture(e,t,s=!1,i=!1,r=""){if(!t)return null!=this._boundTexturesCache[e]&&(this._activeChannel=e,this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),this.webGLVersion>1&&(this._bindTextureDirectly(this._gl.TEXTURE_3D,null),this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY,null))),!1;if(t.video){this._activeChannel=e;const s=t.getInternalTexture();s&&(s._associatedChannel=e),t.update()}else if(t.delayLoadState===Ze.DELAYLOADSTATE_NOTLOADED)return t.delayLoad(),!1;let n;n=i?t.depthStencilTexture:t.isReady()?t.getInternalTexture():t.isCube?this.emptyCubeTexture:t.is3D?this.emptyTexture3D:t.is2DArray?this.emptyTexture2DArray:this.emptyTexture,!s&&n&&(n._associatedChannel=e);let a=!0;this._boundTexturesCache[e]===n&&(s||this._bindSamplerUniformToChannel(n._associatedChannel,e),a=!1),this._activeChannel=e;const o=this._getTextureTarget(n);if(a&&this._bindTextureDirectly(o,n,s),n&&!n.isMultiview){if(n.isCube&&n._cachedCoordinatesMode!==t.coordinatesMode){n._cachedCoordinatesMode=t.coordinatesMode;const e=t.coordinatesMode!==Ze.TEXTURE_CUBIC_MODE&&t.coordinatesMode!==Ze.TEXTURE_SKYBOX_MODE?Ze.TEXTURE_WRAP_ADDRESSMODE:Ze.TEXTURE_CLAMP_ADDRESSMODE;t.wrapU=e,t.wrapV=e}n._cachedWrapU!==t.wrapU&&(n._cachedWrapU=t.wrapU,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_S,this._getTextureWrapMode(t.wrapU),n)),n._cachedWrapV!==t.wrapV&&(n._cachedWrapV=t.wrapV,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_T,this._getTextureWrapMode(t.wrapV),n)),n.is3D&&n._cachedWrapR!==t.wrapR&&(n._cachedWrapR=t.wrapR,this._setTextureParameterInteger(o,this._gl.TEXTURE_WRAP_R,this._getTextureWrapMode(t.wrapR),n)),this._setAnisotropicLevel(o,n,t.anisotropicFilteringLevel)}return!0}setTextureArray(e,t,s,i){if(void 0!==e&&t){this._textureUnits&&this._textureUnits.length===s.length||(this._textureUnits=new Int32Array(s.length));for(let t=0;t<s.length;t++){const i=s[t].getInternalTexture();i?(this._textureUnits[t]=e+t,i._associatedChannel=e+t):this._textureUnits[t]=-1}this._gl.uniform1iv(t,this._textureUnits);for(let e=0;e<s.length;e++)this._setTexture(this._textureUnits[e],s[e],!0)}}_setAnisotropicLevel(e,t,s){const i=this._caps.textureAnisotropicFilterExtension;t.samplingMode!==Ze.TEXTURE_LINEAR_LINEAR_MIPNEAREST&&t.samplingMode!==Ze.TEXTURE_LINEAR_LINEAR_MIPLINEAR&&t.samplingMode!==Ze.TEXTURE_LINEAR_LINEAR&&(s=1),i&&t._cachedAnisotropicFilteringLevel!==s&&(this._setTextureParameterFloat(e,i.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(s,this._caps.maxAnisotropy),t),t._cachedAnisotropicFilteringLevel=s)}_setTextureParameterFloat(e,t,s,i){this._bindTextureDirectly(e,i,!0,!0),this._gl.texParameterf(e,t,s)}_setTextureParameterInteger(e,t,s,i){i&&this._bindTextureDirectly(e,i,!0,!0),this._gl.texParameteri(e,t,s)}unbindAllAttributes(){if(this._mustWipeVertexAttributes){this._mustWipeVertexAttributes=!1;for(let e=0;e<this._caps.maxVertexAttribs;e++)this.disableAttributeByIndex(e)}else for(let e=0,t=this._vertexAttribArraysEnabled.length;e<t;e++)e>=this._caps.maxVertexAttribs||!this._vertexAttribArraysEnabled[e]||this.disableAttributeByIndex(e)}releaseEffects(){const e=Object.keys(this._compiledEffects);for(const t of e){this._compiledEffects[t].dispose()}this._compiledEffects={}}dispose(){var e;oe()&&this._renderingCanvas&&(this._doNotHandleContextLost||(this._renderingCanvas.removeEventListener("webglcontextlost",this._onContextLost),this._renderingCanvas.removeEventListener("webglcontextrestored",this._onContextRestored))),super.dispose(),this._dummyFramebuffer&&this._gl.deleteFramebuffer(this._dummyFramebuffer),this.unbindAllAttributes(),this._boundUniforms={},this._workingCanvas=null,this._workingContext=null,this._currentBufferPointers.length=0,this._currentProgram=null,this._creationOptions.loseContextOnDispose&&this._gl.getExtension("WEBGL_lose_context")?.loseContext(),e=this._gl,et.delete(e)}attachContextLostEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextlost",e,!1)}attachContextRestoredEvent(e){this._renderingCanvas&&this._renderingCanvas.addEventListener("webglcontextrestored",e,!1)}getError(){return this._gl.getError()}_canRenderToFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(Ze.TEXTURETYPE_FLOAT)}_canRenderToHalfFloatFramebuffer(){return this._webGLVersion>1?this._caps.colorBufferFloat:this._canRenderToFramebuffer(Ze.TEXTURETYPE_HALF_FLOAT)}_canRenderToFramebuffer(e){const t=this._gl;for(;t.getError()!==t.NO_ERROR;);let s=!0;const i=t.createTexture();t.bindTexture(t.TEXTURE_2D,i),t.texImage2D(t.TEXTURE_2D,0,this._getRGBABufferInternalSizedFormat(e),1,1,0,t.RGBA,this._getWebGLTextureType(e),null),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.NEAREST);const r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i,0);const n=t.checkFramebufferStatus(t.FRAMEBUFFER);if(s=s&&n===t.FRAMEBUFFER_COMPLETE,s=s&&t.getError()===t.NO_ERROR,s&&(t.clear(t.COLOR_BUFFER_BIT),s=s&&t.getError()===t.NO_ERROR),s){t.bindFramebuffer(t.FRAMEBUFFER,null);const e=t.RGBA,i=t.UNSIGNED_BYTE,r=new Uint8Array(4);t.readPixels(0,0,1,1,e,i,r),s=s&&t.getError()===t.NO_ERROR}for(t.deleteTexture(i),t.deleteFramebuffer(r),t.bindFramebuffer(t.FRAMEBUFFER,null);!s&&t.getError()!==t.NO_ERROR;);return s}_getWebGLTextureType(e){if(1===this._webGLVersion){switch(e){case Ze.TEXTURETYPE_FLOAT:return this._gl.FLOAT;case Ze.TEXTURETYPE_HALF_FLOAT:return this._gl.HALF_FLOAT_OES;case Ze.TEXTURETYPE_UNSIGNED_BYTE:return this._gl.UNSIGNED_BYTE;case Ze.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.UNSIGNED_SHORT_4_4_4_4;case Ze.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.UNSIGNED_SHORT_5_5_5_1;case Ze.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.UNSIGNED_SHORT_5_6_5}return this._gl.UNSIGNED_BYTE}switch(e){case Ze.TEXTURETYPE_BYTE:return this._gl.BYTE;case Ze.TEXTURETYPE_UNSIGNED_BYTE:return this._gl.UNSIGNED_BYTE;case Ze.TEXTURETYPE_SHORT:return this._gl.SHORT;case Ze.TEXTURETYPE_UNSIGNED_SHORT:return this._gl.UNSIGNED_SHORT;case Ze.TEXTURETYPE_INT:return this._gl.INT;case Ze.TEXTURETYPE_UNSIGNED_INTEGER:return this._gl.UNSIGNED_INT;case Ze.TEXTURETYPE_FLOAT:return this._gl.FLOAT;case Ze.TEXTURETYPE_HALF_FLOAT:return this._gl.HALF_FLOAT;case Ze.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.UNSIGNED_SHORT_4_4_4_4;case Ze.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.UNSIGNED_SHORT_5_5_5_1;case Ze.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.UNSIGNED_SHORT_5_6_5;case Ze.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:return this._gl.UNSIGNED_INT_2_10_10_10_REV;case Ze.TEXTURETYPE_UNSIGNED_INT_24_8:return this._gl.UNSIGNED_INT_24_8;case Ze.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:return this._gl.UNSIGNED_INT_10F_11F_11F_REV;case Ze.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:return this._gl.UNSIGNED_INT_5_9_9_9_REV;case Ze.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV}return this._gl.UNSIGNED_BYTE}_getInternalFormat(e,t=!1){let s=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA;switch(e){case Ze.TEXTUREFORMAT_ALPHA:s=this._gl.ALPHA;break;case Ze.TEXTUREFORMAT_LUMINANCE:s=this._gl.LUMINANCE;break;case Ze.TEXTUREFORMAT_LUMINANCE_ALPHA:s=this._gl.LUMINANCE_ALPHA;break;case Ze.TEXTUREFORMAT_RED:s=this._gl.RED;break;case Ze.TEXTUREFORMAT_RG:s=this._gl.RG;break;case Ze.TEXTUREFORMAT_RGB:s=t?this._glSRGBExtensionValues.SRGB:this._gl.RGB;break;case Ze.TEXTUREFORMAT_RGBA:s=t?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA}if(this._webGLVersion>1)switch(e){case Ze.TEXTUREFORMAT_RED_INTEGER:s=this._gl.RED_INTEGER;break;case Ze.TEXTUREFORMAT_RG_INTEGER:s=this._gl.RG_INTEGER;break;case Ze.TEXTUREFORMAT_RGB_INTEGER:s=this._gl.RGB_INTEGER;break;case Ze.TEXTUREFORMAT_RGBA_INTEGER:s=this._gl.RGBA_INTEGER}return s}_getRGBABufferInternalSizedFormat(e,t,s=!1){if(1===this._webGLVersion){if(void 0!==t)switch(t){case Ze.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA;case Ze.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case Ze.TEXTUREFORMAT_LUMINANCE_ALPHA:return this._gl.LUMINANCE_ALPHA;case Ze.TEXTUREFORMAT_RGB:return s?this._glSRGBExtensionValues.SRGB:this._gl.RGB}return this._gl.RGBA}switch(e){case Ze.TEXTURETYPE_BYTE:switch(t){case Ze.TEXTUREFORMAT_RED:return this._gl.R8_SNORM;case Ze.TEXTUREFORMAT_RG:return this._gl.RG8_SNORM;case Ze.TEXTUREFORMAT_RGB:return this._gl.RGB8_SNORM;case Ze.TEXTUREFORMAT_RED_INTEGER:return this._gl.R8I;case Ze.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG8I;case Ze.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB8I;case Ze.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGBA8I;default:return this._gl.RGBA8_SNORM}case Ze.TEXTURETYPE_UNSIGNED_BYTE:switch(t){case Ze.TEXTUREFORMAT_RED:return this._gl.R8;case Ze.TEXTUREFORMAT_RG:return this._gl.RG8;case Ze.TEXTUREFORMAT_RGB:return s?this._glSRGBExtensionValues.SRGB8:this._gl.RGB8;case Ze.TEXTUREFORMAT_RGBA:return s?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8;case Ze.TEXTUREFORMAT_RED_INTEGER:return this._gl.R8UI;case Ze.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG8UI;case Ze.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB8UI;case Ze.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGBA8UI;case Ze.TEXTUREFORMAT_ALPHA:return this._gl.ALPHA;case Ze.TEXTUREFORMAT_LUMINANCE:return this._gl.LUMINANCE;case Ze.TEXTUREFORMAT_LUMINANCE_ALPHA:return this._gl.LUMINANCE_ALPHA;default:return this._gl.RGBA8}case Ze.TEXTURETYPE_SHORT:switch(t){case Ze.TEXTUREFORMAT_RED_INTEGER:return this._gl.R16I;case Ze.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG16I;case Ze.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB16I;case Ze.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA16I}case Ze.TEXTURETYPE_UNSIGNED_SHORT:switch(t){case Ze.TEXTUREFORMAT_RED_INTEGER:return this._gl.R16UI;case Ze.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG16UI;case Ze.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB16UI;case Ze.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA16UI}case Ze.TEXTURETYPE_INT:switch(t){case Ze.TEXTUREFORMAT_RED_INTEGER:return this._gl.R32I;case Ze.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG32I;case Ze.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB32I;case Ze.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA32I}case Ze.TEXTURETYPE_UNSIGNED_INTEGER:switch(t){case Ze.TEXTUREFORMAT_RED_INTEGER:return this._gl.R32UI;case Ze.TEXTUREFORMAT_RG_INTEGER:return this._gl.RG32UI;case Ze.TEXTUREFORMAT_RGB_INTEGER:return this._gl.RGB32UI;case Ze.TEXTUREFORMAT_RGBA_INTEGER:default:return this._gl.RGBA32UI}case Ze.TEXTURETYPE_FLOAT:switch(t){case Ze.TEXTUREFORMAT_RED:return this._gl.R32F;case Ze.TEXTUREFORMAT_RG:return this._gl.RG32F;case Ze.TEXTUREFORMAT_RGB:return this._gl.RGB32F;case Ze.TEXTUREFORMAT_RGBA:default:return this._gl.RGBA32F}case Ze.TEXTURETYPE_HALF_FLOAT:switch(t){case Ze.TEXTUREFORMAT_RED:return this._gl.R16F;case Ze.TEXTUREFORMAT_RG:return this._gl.RG16F;case Ze.TEXTUREFORMAT_RGB:return this._gl.RGB16F;case Ze.TEXTUREFORMAT_RGBA:default:return this._gl.RGBA16F}case Ze.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:return this._gl.RGB565;case Ze.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:return this._gl.R11F_G11F_B10F;case Ze.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:return this._gl.RGB9_E5;case Ze.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:return this._gl.RGBA4;case Ze.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:return this._gl.RGB5_A1;case Ze.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:switch(t){case Ze.TEXTUREFORMAT_RGBA:return this._gl.RGB10_A2;case Ze.TEXTUREFORMAT_RGBA_INTEGER:return this._gl.RGB10_A2UI;default:return this._gl.RGB10_A2}}return s?this._glSRGBExtensionValues.SRGB8_ALPHA8:this._gl.RGBA8}readPixels(e,t,s,i,r=!0,n=!0){const a=r?4:3,o=r?this._gl.RGBA:this._gl.RGB,h=new Uint8Array(i*s*a);return n&&this.flushFramebuffer(),this._gl.readPixels(e,t,s,i,o,this._gl.UNSIGNED_BYTE,h),Promise.resolve(h)}static get IsSupportedAsync(){return Promise.resolve(this.isSupported())}static get IsSupported(){return this.isSupported()}static isSupported(){if(null!==this._HasMajorPerformanceCaveat)return!this._HasMajorPerformanceCaveat;if(null===this._IsSupported)try{const e=yt._CreateCanvas(1,1),t=e.getContext("webgl")||e.getContext("experimental-webgl");this._IsSupported=null!=t&&!!window.WebGLRenderingContext}catch(e){this._IsSupported=!1}return this._IsSupported}static get HasMajorPerformanceCaveat(){if(null===this._HasMajorPerformanceCaveat)try{const e=yt._CreateCanvas(1,1),t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0})||e.getContext("experimental-webgl",{failIfMajorPerformanceCaveat:!0});this._HasMajorPerformanceCaveat=!t}catch(e){this._HasMajorPerformanceCaveat=!1}return this._HasMajorPerformanceCaveat}}Ds._TempClearColorUint32=new Uint32Array(4),Ds._TempClearColorInt32=new Int32Array(4),Ds.ExceptionList=[{key:"Chrome/63.0",capture:"63\\.0\\.3239\\.(\\d+)",captureConstraint:108,targets:["uniformBuffer"]},{key:"Firefox/58",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Firefox/59",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/72.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/73.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Chrome/74.+?Mobile",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/71",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome/72",capture:null,captureConstraint:null,targets:["vao"]},{key:"Mac OS.+Chrome",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:"Chrome/12\\d\\..+?Mobile",capture:null,captureConstraint:null,targets:["uniformBuffer"]},{key:".*AppleWebKit.*(15.4).*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]},{key:".*(15.4).*AppleWebKit.*Safari",capture:null,captureConstraint:null,targets:["antialias","maxMSAASamples"]}],Ds._ConcatenateShader=De,Ds._IsSupported=null,Ds._HasMajorPerformanceCaveat=null,Ds.prototype.createUniformBuffer=function(e,t){const s=this._gl.createBuffer();if(!s)throw new Error("Unable to create uniform buffer");const i=new Cs(s);return this.bindUniformBuffer(i),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.STATIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.STATIC_DRAW),this.bindUniformBuffer(null),i.references=1,i},Ds.prototype.createDynamicUniformBuffer=function(e,t){const s=this._gl.createBuffer();if(!s)throw new Error("Unable to create dynamic uniform buffer");const i=new Cs(s);return this.bindUniformBuffer(i),e instanceof Float32Array?this._gl.bufferData(this._gl.UNIFORM_BUFFER,e,this._gl.DYNAMIC_DRAW):this._gl.bufferData(this._gl.UNIFORM_BUFFER,new Float32Array(e),this._gl.DYNAMIC_DRAW),this.bindUniformBuffer(null),i.references=1,i},Ds.prototype.updateUniformBuffer=function(e,t,s,i){this.bindUniformBuffer(e),void 0===s&&(s=0),void 0===i?t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,s,t):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,s,new Float32Array(t)):t instanceof Float32Array?this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,t.subarray(s,s+i)):this._gl.bufferSubData(this._gl.UNIFORM_BUFFER,0,new Float32Array(t).subarray(s,s+i)),this.bindUniformBuffer(null)},Ds.prototype.bindUniformBuffer=function(e){this._gl.bindBuffer(this._gl.UNIFORM_BUFFER,e?e.underlyingResource:null)},Ds.prototype.bindUniformBufferBase=function(e,t,s){this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER,t,e?e.underlyingResource:null)},Ds.prototype.bindUniformBlock=function(e,t,s){const i=e.program,r=this._gl.getUniformBlockIndex(i,t);4294967295!==r&&this._gl.uniformBlockBinding(i,r,s)};class Ls{constructor(e,t,s,i,r=!1){this._valueCache={},this._engine=e,this._noUBO=!e.supportsUniformBuffers||r,this._dynamic=s,this._name=i??"no-name",this._data=t||[],this._uniformLocations={},this._uniformSizes={},this._uniformArraySizes={},this._uniformLocationPointer=0,this._needSync=!1,this._engine._features.trackUbosInFrame&&(this._buffers=[],this._bufferIndex=-1,this._createBufferOnWrite=!1,this._currentFrameId=0),this._noUBO?(this.updateMatrix3x3=this._updateMatrix3x3ForEffect,this.updateMatrix2x2=this._updateMatrix2x2ForEffect,this.updateFloat=this._updateFloatForEffect,this.updateFloat2=this._updateFloat2ForEffect,this.updateFloat3=this._updateFloat3ForEffect,this.updateFloat4=this._updateFloat4ForEffect,this.updateFloatArray=this._updateFloatArrayForEffect,this.updateArray=this._updateArrayForEffect,this.updateIntArray=this._updateIntArrayForEffect,this.updateUIntArray=this._updateUIntArrayForEffect,this.updateMatrix=this._updateMatrixForEffect,this.updateMatrices=this._updateMatricesForEffect,this.updateVector3=this._updateVector3ForEffect,this.updateVector4=this._updateVector4ForEffect,this.updateColor3=this._updateColor3ForEffect,this.updateColor4=this._updateColor4ForEffect,this.updateDirectColor4=this._updateDirectColor4ForEffect,this.updateInt=this._updateIntForEffect,this.updateInt2=this._updateInt2ForEffect,this.updateInt3=this._updateInt3ForEffect,this.updateInt4=this._updateInt4ForEffect,this.updateUInt=this._updateUIntForEffect,this.updateUInt2=this._updateUInt2ForEffect,this.updateUInt3=this._updateUInt3ForEffect,this.updateUInt4=this._updateUInt4ForEffect):(this._engine._uniformBuffers.push(this),this.updateMatrix3x3=this._updateMatrix3x3ForUniform,this.updateMatrix2x2=this._updateMatrix2x2ForUniform,this.updateFloat=this._updateFloatForUniform,this.updateFloat2=this._updateFloat2ForUniform,this.updateFloat3=this._updateFloat3ForUniform,this.updateFloat4=this._updateFloat4ForUniform,this.updateFloatArray=this._updateFloatArrayForUniform,this.updateArray=this._updateArrayForUniform,this.updateIntArray=this._updateIntArrayForUniform,this.updateUIntArray=this._updateUIntArrayForUniform,this.updateMatrix=this._updateMatrixForUniform,this.updateMatrices=this._updateMatricesForUniform,this.updateVector3=this._updateVector3ForUniform,this.updateVector4=this._updateVector4ForUniform,this.updateColor3=this._updateColor3ForUniform,this.updateColor4=this._updateColor4ForUniform,this.updateDirectColor4=this._updateDirectColor4ForUniform,this.updateInt=this._updateIntForUniform,this.updateInt2=this._updateInt2ForUniform,this.updateInt3=this._updateInt3ForUniform,this.updateInt4=this._updateInt4ForUniform,this.updateUInt=this._updateUIntForUniform,this.updateUInt2=this._updateUInt2ForUniform,this.updateUInt3=this._updateUInt3ForUniform,this.updateUInt4=this._updateUInt4ForUniform)}get useUbo(){return!this._noUBO}get isSync(){return!this._needSync}isDynamic(){return void 0!==this._dynamic}getData(){return this._bufferData}getBuffer(){return this._buffer}_fillAlignment(e){let t;if(t=e<=2?e:4,this._uniformLocationPointer%t!=0){const e=this._uniformLocationPointer;this._uniformLocationPointer+=t-this._uniformLocationPointer%t;const s=this._uniformLocationPointer-e;for(let e=0;e<s;e++)this._data.push(0)}}addUniform(e,t,s=0){if(this._noUBO)return;if(void 0!==this._uniformLocations[e])return;let i;if(s>0){if(t instanceof Array)throw"addUniform should not be use with Array in UBO: "+e;if(this._fillAlignment(4),this._uniformArraySizes[e]={strideSize:t,arraySize:s},16==t)t*=s;else{t=t*s+(4-t)*s}i=[];for(let e=0;e<t;e++)i.push(0)}else{if(t instanceof Array)i=t,t=i.length;else{i=[];for(let e=0;e<t;e++)i.push(0)}this._fillAlignment(t)}this._uniformSizes[e]=t,this._uniformLocations[e]=this._uniformLocationPointer,this._uniformLocationPointer+=t;for(let e=0;e<t;e++)this._data.push(i[e]);this._needSync=!0}addMatrix(e,t){this.addUniform(e,Array.prototype.slice.call(t.asArray()))}addFloat2(e,t,s){const i=[t,s];this.addUniform(e,i)}addFloat3(e,t,s,i){const r=[t,s,i];this.addUniform(e,r)}addColor3(e,t){const s=[t.r,t.g,t.b];this.addUniform(e,s)}addColor4(e,t,s){const i=[t.r,t.g,t.b,s];this.addUniform(e,i)}addVector3(e,t){const s=[t.x,t.y,t.z];this.addUniform(e,s)}addMatrix3x3(e){this.addUniform(e,12)}addMatrix2x2(e){this.addUniform(e,8)}create(){this._noUBO||this._buffer||(this._fillAlignment(4),this._bufferData=new Float32Array(this._data),this._rebuild(),this._needSync=!0)}_getNames(){const e=[];let t=0;for(const s in this._uniformLocations)if(e.push(s),10==++t)break;return e.join(",")}_rebuild(){!this._noUBO&&this._bufferData&&(this._dynamic?this._buffer=this._engine.createDynamicUniformBuffer(this._bufferData,this._name+"_UniformList:"+this._getNames()):this._buffer=this._engine.createUniformBuffer(this._bufferData,this._name+"_UniformList:"+this._getNames()),this._engine._features.trackUbosInFrame&&(this._buffers.push([this._buffer,this._engine._features.checkUbosContentBeforeUpload?this._bufferData.slice():void 0]),this._bufferIndex=this._buffers.length-1,this._createBufferOnWrite=!1))}_rebuildAfterContextLost(){this._engine._features.trackUbosInFrame&&(this._buffers=[],this._currentFrameId=0),this._rebuild()}get _numBuffers(){return this._buffers.length}get _indexBuffer(){return this._bufferIndex}get name(){return this._name}get currentEffect(){return this._currentEffect}_buffersEqual(e,t){for(let s=0;s<e.length;++s)if(e[s]!==t[s])return!1;return!0}_copyBuffer(e,t){for(let s=0;s<e.length;++s)t[s]=e[s]}update(){if(!this._noUBO)if(this.bindUniformBuffer(),this._buffer)if(this._dynamic||this._needSync){if(this._buffers&&this._buffers.length>1&&this._buffers[this._bufferIndex][1]){if(this._buffersEqual(this._bufferData,this._buffers[this._bufferIndex][1]))return this._needSync=!1,void(this._createBufferOnWrite=this._engine._features.trackUbosInFrame);this._copyBuffer(this._bufferData,this._buffers[this._bufferIndex][1])}this._engine.updateUniformBuffer(this._buffer,this._bufferData),this._engine._features._collectUbosUpdatedInFrame&&(Ls._UpdatedUbosInFrame[this._name]||(Ls._UpdatedUbosInFrame[this._name]=0),Ls._UpdatedUbosInFrame[this._name]++),this._needSync=!1,this._createBufferOnWrite=this._engine._features.trackUbosInFrame}else this._createBufferOnWrite=this._engine._features.trackUbosInFrame;else this.create()}_createNewBuffer(){this._bufferIndex+1<this._buffers.length?(this._bufferIndex++,this._buffer=this._buffers[this._bufferIndex][0],this._createBufferOnWrite=!1,this._needSync=!0):this._rebuild()}_checkNewFrame(){this._engine._features.trackUbosInFrame&&this._currentFrameId!==this._engine.frameId&&(this._currentFrameId=this._engine.frameId,this._createBufferOnWrite=!1,this._buffers&&this._buffers.length>0?(this._needSync=0!==this._bufferIndex,this._bufferIndex=0,this._buffer=this._buffers[this._bufferIndex][0]):this._bufferIndex=-1)}updateUniform(e,t,s){this._checkNewFrame();let i=this._uniformLocations[e];if(void 0===i){if(this._buffer)return void ue.Error("Cannot add an uniform after UBO has been created. uniformName="+e);this.addUniform(e,s),i=this._uniformLocations[e]}if(this._buffer||this.create(),this._dynamic)for(let e=0;e<s;e++)this._bufferData[i+e]=t[e];else{let e=!1;for(let r=0;r<s;r++)(16===s&&!this._engine._features.uniformBufferHardCheckMatrix||this._bufferData[i+r]!==Math.fround(t[r]))&&(e=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[i+r]=t[r]);this._needSync=this._needSync||e}}updateUniformArray(e,t,s){this._checkNewFrame();const i=this._uniformLocations[e];if(void 0===i)return void ue.Error("Cannot add an uniform Array dynamically. Please, add it using addUniform and make sure that uniform buffers are supported by the current engine.");this._buffer||this.create();const r=this._uniformArraySizes[e];if(this._dynamic)for(let e=0;e<s;e++)this._bufferData[i+e]=t[e];else{let e=!1,n=0,a=0;for(let o=0;o<s;o++)if(this._bufferData[i+4*a+n]!==Yt.FloatRound(t[o])&&(e=!0,this._createBufferOnWrite&&this._createNewBuffer(),this._bufferData[i+4*a+n]=t[o]),n++,n===r.strideSize){for(;n<4;n++)this._bufferData[i+4*a+n]=0;n=0,a++}this._needSync=this._needSync||e}}_cacheMatrix(e,t){this._checkNewFrame();const s=this._valueCache[e],i=t.updateFlag;return(void 0===s||s!==i)&&(this._valueCache[e]=i,!0)}_updateMatrix3x3ForUniform(e,t){for(let e=0;e<3;e++)Ls._TempBuffer[4*e]=t[3*e],Ls._TempBuffer[4*e+1]=t[3*e+1],Ls._TempBuffer[4*e+2]=t[3*e+2],Ls._TempBuffer[4*e+3]=0;this.updateUniform(e,Ls._TempBuffer,12)}_updateMatrix3x3ForEffect(e,t){this._currentEffect.setMatrix3x3(e,t)}_updateMatrix2x2ForEffect(e,t){this._currentEffect.setMatrix2x2(e,t)}_updateMatrix2x2ForUniform(e,t){for(let e=0;e<2;e++)Ls._TempBuffer[4*e]=t[2*e],Ls._TempBuffer[4*e+1]=t[2*e+1],Ls._TempBuffer[4*e+2]=0,Ls._TempBuffer[4*e+3]=0;this.updateUniform(e,Ls._TempBuffer,8)}_updateFloatForEffect(e,t){this._currentEffect.setFloat(e,t)}_updateFloatForUniform(e,t){Ls._TempBuffer[0]=t,this.updateUniform(e,Ls._TempBuffer,1)}_updateFloat2ForEffect(e,t,s,i=""){this._currentEffect.setFloat2(e+i,t,s)}_updateFloat2ForUniform(e,t,s){Ls._TempBuffer[0]=t,Ls._TempBuffer[1]=s,this.updateUniform(e,Ls._TempBuffer,2)}_updateFloat3ForEffect(e,t,s,i,r=""){this._currentEffect.setFloat3(e+r,t,s,i)}_updateFloat3ForUniform(e,t,s,i){Ls._TempBuffer[0]=t,Ls._TempBuffer[1]=s,Ls._TempBuffer[2]=i,this.updateUniform(e,Ls._TempBuffer,3)}_updateFloat4ForEffect(e,t,s,i,r,n=""){this._currentEffect.setFloat4(e+n,t,s,i,r)}_updateFloat4ForUniform(e,t,s,i,r){Ls._TempBuffer[0]=t,Ls._TempBuffer[1]=s,Ls._TempBuffer[2]=i,Ls._TempBuffer[3]=r,this.updateUniform(e,Ls._TempBuffer,4)}_updateFloatArrayForEffect(e,t){this._currentEffect.setFloatArray(e,t)}_updateFloatArrayForUniform(e,t){this.updateUniformArray(e,t,t.length)}_updateArrayForEffect(e,t){this._currentEffect.setArray(e,t)}_updateArrayForUniform(e,t){this.updateUniformArray(e,t,t.length)}_updateIntArrayForEffect(e,t){this._currentEffect.setIntArray(e,t)}_updateIntArrayForUniform(e,t){Ls._TempBufferInt32View.set(t),this.updateUniformArray(e,Ls._TempBuffer,t.length)}_updateUIntArrayForEffect(e,t){this._currentEffect.setUIntArray(e,t)}_updateUIntArrayForUniform(e,t){Ls._TempBufferUInt32View.set(t),this.updateUniformArray(e,Ls._TempBuffer,t.length)}_updateMatrixForEffect(e,t){this._currentEffect.setMatrix(e,t)}_updateMatrixForUniform(e,t){this._cacheMatrix(e,t)&&this.updateUniform(e,t.asArray(),16)}_updateMatricesForEffect(e,t){this._currentEffect.setMatrices(e,t)}_updateMatricesForUniform(e,t){this.updateUniform(e,t,t.length)}_updateVector3ForEffect(e,t){this._currentEffect.setVector3(e,t)}_updateVector3ForUniform(e,t){Ls._TempBuffer[0]=t.x,Ls._TempBuffer[1]=t.y,Ls._TempBuffer[2]=t.z,this.updateUniform(e,Ls._TempBuffer,3)}_updateVector4ForEffect(e,t){this._currentEffect.setVector4(e,t)}_updateVector4ForUniform(e,t){Ls._TempBuffer[0]=t.x,Ls._TempBuffer[1]=t.y,Ls._TempBuffer[2]=t.z,Ls._TempBuffer[3]=t.w,this.updateUniform(e,Ls._TempBuffer,4)}_updateColor3ForEffect(e,t,s=""){this._currentEffect.setColor3(e+s,t)}_updateColor3ForUniform(e,t){Ls._TempBuffer[0]=t.r,Ls._TempBuffer[1]=t.g,Ls._TempBuffer[2]=t.b,this.updateUniform(e,Ls._TempBuffer,3)}_updateColor4ForEffect(e,t,s,i=""){this._currentEffect.setColor4(e+i,t,s)}_updateDirectColor4ForEffect(e,t,s=""){this._currentEffect.setDirectColor4(e+s,t)}_updateColor4ForUniform(e,t,s){Ls._TempBuffer[0]=t.r,Ls._TempBuffer[1]=t.g,Ls._TempBuffer[2]=t.b,Ls._TempBuffer[3]=s,this.updateUniform(e,Ls._TempBuffer,4)}_updateDirectColor4ForUniform(e,t){Ls._TempBuffer[0]=t.r,Ls._TempBuffer[1]=t.g,Ls._TempBuffer[2]=t.b,Ls._TempBuffer[3]=t.a,this.updateUniform(e,Ls._TempBuffer,4)}_updateIntForEffect(e,t,s=""){this._currentEffect.setInt(e+s,t)}_updateIntForUniform(e,t){Ls._TempBufferInt32View[0]=t,this.updateUniform(e,Ls._TempBuffer,1)}_updateInt2ForEffect(e,t,s,i=""){this._currentEffect.setInt2(e+i,t,s)}_updateInt2ForUniform(e,t,s){Ls._TempBufferInt32View[0]=t,Ls._TempBufferInt32View[1]=s,this.updateUniform(e,Ls._TempBuffer,2)}_updateInt3ForEffect(e,t,s,i,r=""){this._currentEffect.setInt3(e+r,t,s,i)}_updateInt3ForUniform(e,t,s,i){Ls._TempBufferInt32View[0]=t,Ls._TempBufferInt32View[1]=s,Ls._TempBufferInt32View[2]=i,this.updateUniform(e,Ls._TempBuffer,3)}_updateInt4ForEffect(e,t,s,i,r,n=""){this._currentEffect.setInt4(e+n,t,s,i,r)}_updateInt4ForUniform(e,t,s,i,r){Ls._TempBufferInt32View[0]=t,Ls._TempBufferInt32View[1]=s,Ls._TempBufferInt32View[2]=i,Ls._TempBufferInt32View[3]=r,this.updateUniform(e,Ls._TempBuffer,4)}_updateUIntForEffect(e,t,s=""){this._currentEffect.setUInt(e+s,t)}_updateUIntForUniform(e,t){Ls._TempBufferUInt32View[0]=t,this.updateUniform(e,Ls._TempBuffer,1)}_updateUInt2ForEffect(e,t,s,i=""){this._currentEffect.setUInt2(e+i,t,s)}_updateUInt2ForUniform(e,t,s){Ls._TempBufferUInt32View[0]=t,Ls._TempBufferUInt32View[1]=s,this.updateUniform(e,Ls._TempBuffer,2)}_updateUInt3ForEffect(e,t,s,i,r=""){this._currentEffect.setUInt3(e+r,t,s,i)}_updateUInt3ForUniform(e,t,s,i){Ls._TempBufferUInt32View[0]=t,Ls._TempBufferUInt32View[1]=s,Ls._TempBufferUInt32View[2]=i,this.updateUniform(e,Ls._TempBuffer,3)}_updateUInt4ForEffect(e,t,s,i,r,n=""){this._currentEffect.setUInt4(e+n,t,s,i,r)}_updateUInt4ForUniform(e,t,s,i,r){Ls._TempBufferUInt32View[0]=t,Ls._TempBufferUInt32View[1]=s,Ls._TempBufferUInt32View[2]=i,Ls._TempBufferUInt32View[3]=r,this.updateUniform(e,Ls._TempBuffer,4)}setTexture(e,t){this._currentEffect.setTexture(e,t)}bindTexture(e,t){this._currentEffect._bindTexture(e,t)}updateUniformDirectly(e,t){this.updateUniform(e,t,t.length),this.update()}bindToEffect(e,t){this._currentEffect=e,this._currentEffectName=t}bindUniformBuffer(){!this._noUBO&&this._buffer&&this._currentEffect&&this._currentEffect.bindUniformBuffer(this._buffer,this._currentEffectName)}unbindEffect(){this._currentEffect=void 0,this._currentEffectName=void 0}setDataBuffer(e){if(!this._buffers)return this._buffer===e;for(let t=0;t<this._buffers.length;++t){if(this._buffers[t][0]===e)return this._bufferIndex=t,this._buffer=e,this._createBufferOnWrite=!1,this._currentEffect=void 0,!0}return!1}dispose(){if(this._noUBO)return;const e=this._engine._uniformBuffers,t=e.indexOf(this);if(-1!==t&&(e[t]=e[e.length-1],e.pop()),this._engine._features.trackUbosInFrame&&this._buffers)for(let e=0;e<this._buffers.length;++e){const t=this._buffers[e][0];this._engine._releaseBuffer(t)}else this._buffer&&this._engine._releaseBuffer(this._buffer)&&(this._buffer=null)}}Ls._UpdatedUbosInFrame={},Ls._MAX_UNIFORM_SIZE=256,Ls._TempBuffer=new Float32Array(Ls._MAX_UNIFORM_SIZE),Ls._TempBufferInt32View=new Int32Array(Ls._TempBuffer.buffer),Ls._TempBufferUInt32View=new Uint32Array(Ls._TempBuffer.buffer);class Fs{constructor(){this._checkCollisions=!1,this._collisionMask=-1,this._collisionGroup=-1,this._surroundingMeshes=null,this._collider=null,this._oldPositionForCollisions=new U(0,0,0),this._diffPositionForCollisions=new U(0,0,0),this._collisionResponse=!0}}var Ns,ws;!function(e){e[e.LOCAL=0]="LOCAL",e[e.WORLD=1]="WORLD",e[e.BONE=2]="BONE"}(Ns||(Ns={}));class Bs{}Bs.X=new U(1,0,0),Bs.Y=new U(0,1,0),Bs.Z=new U(0,0,1),function(e){e[e.X=0]="X",e[e.Y=1]="Y",e[e.Z=2]="Z"}(ws||(ws={}));class Us{constructor(){this.facetNb=0,this.partitioningSubdivisions=10,this.partitioningBBoxRatio=1.01,this.facetDataEnabled=!1,this.facetParameters={},this.bbSize=U.Zero(),this.subDiv={max:1,X:1,Y:1,Z:1},this.facetDepthSort=!1,this.facetDepthSortEnabled=!1}}class ks{constructor(){this._hasVertexAlpha=!1,this._useVertexColors=!0,this._numBoneInfluencers=4,this._applyFog=!0,this._receiveShadows=!1,this._facetData=new Us,this._visibility=1,this._skeleton=null,this._layerMask=268435455,this._computeBonesUsingShaders=!0,this._isActive=!1,this._onlyForInstances=!1,this._isActiveIntermediate=!1,this._onlyForInstancesIntermediate=!1,this._actAsRegularMesh=!1,this._currentLOD=null,this._currentLODIsUpToDate=!1,this._collisionRetryCount=3,this._morphTargetManager=null,this._renderingGroupId=0,this._bakedVertexAnimationManager=null,this._material=null,this._positions=null,this._pointerOverDisableMeshTesting=!1,this._meshCollisionData=new Fs,this._enableDistantPicking=!1,this._rawBoundingInfo=null,this._sideOrientationHint=!1,this._inheritVisibility=!1}}class Gs extends Rs{static get BILLBOARDMODE_NONE(){return Rs.BILLBOARDMODE_NONE}static get BILLBOARDMODE_X(){return Rs.BILLBOARDMODE_X}static get BILLBOARDMODE_Y(){return Rs.BILLBOARDMODE_Y}static get BILLBOARDMODE_Z(){return Rs.BILLBOARDMODE_Z}static get BILLBOARDMODE_ALL(){return Rs.BILLBOARDMODE_ALL}static get BILLBOARDMODE_USE_POSITION(){return Rs.BILLBOARDMODE_USE_POSITION}get facetNb(){return this._internalAbstractMeshDataInfo._facetData.facetNb}get partitioningSubdivisions(){return this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions}set partitioningSubdivisions(e){this._internalAbstractMeshDataInfo._facetData.partitioningSubdivisions=e}get partitioningBBoxRatio(){return this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio}set partitioningBBoxRatio(e){this._internalAbstractMeshDataInfo._facetData.partitioningBBoxRatio=e}get mustDepthSortFacets(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSort}set mustDepthSortFacets(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSort=e}get facetDepthSortFrom(){return this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom}set facetDepthSortFrom(e){this._internalAbstractMeshDataInfo._facetData.facetDepthSortFrom=e}get collisionRetryCount(){return this._internalAbstractMeshDataInfo._collisionRetryCount}set collisionRetryCount(e){this._internalAbstractMeshDataInfo._collisionRetryCount=e}get isFacetDataEnabled(){return this._internalAbstractMeshDataInfo._facetData.facetDataEnabled}get morphTargetManager(){return this._internalAbstractMeshDataInfo._morphTargetManager}set morphTargetManager(e){this._internalAbstractMeshDataInfo._morphTargetManager!==e&&(this._internalAbstractMeshDataInfo._morphTargetManager=e,this._syncGeometryWithMorphTargetManager())}get bakedVertexAnimationManager(){return this._internalAbstractMeshDataInfo._bakedVertexAnimationManager}set bakedVertexAnimationManager(e){this._internalAbstractMeshDataInfo._bakedVertexAnimationManager!==e&&(this._internalAbstractMeshDataInfo._bakedVertexAnimationManager=e,this._markSubMeshesAsAttributesDirty())}_syncGeometryWithMorphTargetManager(){}_updateNonUniformScalingState(e){return!!super._updateNonUniformScalingState(e)&&(this._markSubMeshesAsMiscDirty(),!0)}get rawBoundingInfo(){return this._internalAbstractMeshDataInfo._rawBoundingInfo}set rawBoundingInfo(e){this._internalAbstractMeshDataInfo._rawBoundingInfo=e}set onCollide(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver&&this.onCollideObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollideObserver=this.onCollideObservable.add(e)}set onCollisionPositionChange(e){this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver&&this.onCollisionPositionChangeObservable.remove(this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver),this._internalAbstractMeshDataInfo._meshCollisionData._onCollisionPositionChangeObserver=this.onCollisionPositionChangeObservable.add(e)}get visibility(){return this._internalAbstractMeshDataInfo._visibility}set visibility(e){if(this._internalAbstractMeshDataInfo._visibility===e)return;const t=this._internalAbstractMeshDataInfo._visibility;this._internalAbstractMeshDataInfo._visibility=e,(1===t&&1!==e||1!==t&&1===e)&&this._markSubMeshesAsDirty((e=>{e.markAsMiscDirty(),e.markAsPrePassDirty()}))}get inheritVisibility(){return this._internalAbstractMeshDataInfo._inheritVisibility}set inheritVisibility(e){this._internalAbstractMeshDataInfo._inheritVisibility=e}get isVisible(){if(!this._isVisible||!this.inheritVisibility||!this._parentNode)return this._isVisible;if(this._isVisible){let e=this._parentNode;for(;e;){const t=e.isVisible;if(void 0!==t)return t;e=e.parent}}return this._isVisible}set isVisible(e){this._isVisible=e}get pointerOverDisableMeshTesting(){return this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting}set pointerOverDisableMeshTesting(e){this._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting=e}get renderingGroupId(){return this._internalAbstractMeshDataInfo._renderingGroupId}set renderingGroupId(e){this._internalAbstractMeshDataInfo._renderingGroupId=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){this._setMaterial(e)}_setMaterial(e){this._internalAbstractMeshDataInfo._material!==e&&(this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),this._internalAbstractMeshDataInfo._material=e,e&&e.meshMap&&(e.meshMap[this.uniqueId]=this),this.onMaterialChangedObservable.hasObservers()&&this.onMaterialChangedObservable.notifyObservers(this),this.subMeshes&&(this.resetDrawCache(),this._unBindEffect()))}getMaterialForRenderPass(e){return this._internalAbstractMeshDataInfo._materialForRenderPass?.[e]}setMaterialForRenderPass(e,t){this.resetDrawCache(e),this._internalAbstractMeshDataInfo._materialForRenderPass||(this._internalAbstractMeshDataInfo._materialForRenderPass=[]),this._internalAbstractMeshDataInfo._materialForRenderPass[e]=t}get receiveShadows(){return this._internalAbstractMeshDataInfo._receiveShadows}set receiveShadows(e){this._internalAbstractMeshDataInfo._receiveShadows!==e&&(this._internalAbstractMeshDataInfo._receiveShadows=e,this._markSubMeshesAsLightDirty())}get hasVertexAlpha(){return this._internalAbstractMeshDataInfo._hasVertexAlpha}set hasVertexAlpha(e){this._internalAbstractMeshDataInfo._hasVertexAlpha!==e&&(this._internalAbstractMeshDataInfo._hasVertexAlpha=e,this._markSubMeshesAsAttributesDirty(),this._markSubMeshesAsMiscDirty())}get useVertexColors(){return this._internalAbstractMeshDataInfo._useVertexColors}set useVertexColors(e){this._internalAbstractMeshDataInfo._useVertexColors!==e&&(this._internalAbstractMeshDataInfo._useVertexColors=e,this._markSubMeshesAsAttributesDirty())}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get numBoneInfluencers(){return this._internalAbstractMeshDataInfo._numBoneInfluencers}set numBoneInfluencers(e){this._internalAbstractMeshDataInfo._numBoneInfluencers!==e&&(this._internalAbstractMeshDataInfo._numBoneInfluencers=e,this._markSubMeshesAsAttributesDirty())}get applyFog(){return this._internalAbstractMeshDataInfo._applyFog}set applyFog(e){this._internalAbstractMeshDataInfo._applyFog!==e&&(this._internalAbstractMeshDataInfo._applyFog=e,this._markSubMeshesAsMiscDirty())}get enableDistantPicking(){return this._internalAbstractMeshDataInfo._enableDistantPicking}set enableDistantPicking(e){this._internalAbstractMeshDataInfo._enableDistantPicking=e}get layerMask(){return this._internalAbstractMeshDataInfo._layerMask}set layerMask(e){e!==this._internalAbstractMeshDataInfo._layerMask&&(this._internalAbstractMeshDataInfo._layerMask=e,this._resyncLightSources())}get collisionMask(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask}set collisionMask(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionMask=isNaN(e)?-1:e}get collisionResponse(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse}set collisionResponse(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionResponse=e}get collisionGroup(){return this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup}set collisionGroup(e){this._internalAbstractMeshDataInfo._meshCollisionData._collisionGroup=isNaN(e)?-1:e}get surroundingMeshes(){return this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes}set surroundingMeshes(e){this._internalAbstractMeshDataInfo._meshCollisionData._surroundingMeshes=e}get lightSources(){return this._lightSources}set skeleton(e){const t=this._internalAbstractMeshDataInfo._skeleton;t&&t.needInitialSkinMatrix&&t._unregisterMeshWithPoseMatrix(this),e&&e.needInitialSkinMatrix&&e._registerMeshWithPoseMatrix(this),this._internalAbstractMeshDataInfo._skeleton=e,this._internalAbstractMeshDataInfo._skeleton||(this._bonesTransformMatrices=null),this._markSubMeshesAsAttributesDirty()}get skeleton(){return this._internalAbstractMeshDataInfo._skeleton}constructor(e,t=null){switch(super(e,t,!1),this._internalAbstractMeshDataInfo=new ks,this._waitingMaterialId=null,this.cullingStrategy=Gs.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,this.onCollideObservable=new g,this.onCollisionPositionChangeObservable=new g,this.onMaterialChangedObservable=new g,this.definedFacingForward=!0,this._occlusionQuery=null,this._renderingGroup=null,this.alphaIndex=Number.MAX_VALUE,this._isVisible=!0,this.isPickable=!0,this.isNearPickable=!1,this.isNearGrabbable=!1,this.showSubMeshesBoundingBox=!1,this.isBlocker=!1,this.enablePointerMoveEvents=!1,this.outlineColor=ee.Red(),this.outlineWidth=.02,this.overlayColor=ee.Red(),this.overlayAlpha=.5,this.useOctreeForRenderingSelection=!0,this.useOctreeForPicking=!0,this.useOctreeForCollisions=!0,this.alwaysSelectAsActiveMesh=!1,this.doNotSyncBoundingInfo=!1,this.actionManager=null,this.ellipsoid=new U(.5,1,.5),this.ellipsoidOffset=new U(0,0,0),this.edgesWidth=1,this.edgesColor=new te(1,0,0,1),this._edgesRenderer=null,this._masterMesh=null,this._boundingInfo=null,this._boundingInfoIsDirty=!0,this._renderId=0,this._intersectionsInProgress=new Array,this._unIndexed=!1,this._lightSources=new Array,this._waitingData={lods:null,actions:null,freezeWorldMatrix:null},this._bonesTransformMatrices=null,this._transformMatrixTexture=null,this.onRebuildObservable=new g,this._onCollisionPositionChange=(e,t,s=null)=>{t.subtractToRef(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions.length()>yt.CollisionsEpsilon&&this.position.addInPlace(this._internalAbstractMeshDataInfo._meshCollisionData._diffPositionForCollisions),s&&this.onCollideObservable.notifyObservers(s),this.onCollisionPositionChangeObservable.notifyObservers(this.position)},(t=this.getScene()).addMesh(this),this._resyncLightSources(),this._uniformBuffer=new Ls(this.getScene().getEngine(),void 0,void 0,e,!this.getScene().getEngine().isWebGPU),this._buildUniformLayout(),t.performancePriority){case 2:this.doNotSyncBoundingInfo=!0;case 1:this.alwaysSelectAsActiveMesh=!0,this.isPickable=!1}}_buildUniformLayout(){this._uniformBuffer.addUniform("world",16),this._uniformBuffer.addUniform("visibility",1),this._uniformBuffer.create()}transferToEffect(e){const t=this._uniformBuffer;t.updateMatrix("world",e),t.updateFloat("visibility",this._internalAbstractMeshDataInfo._visibility),t.update()}getMeshUniformBuffer(){return this._uniformBuffer}getClassName(){return"AbstractMesh"}toString(e){let t="Name: "+this.name+", isInstance: "+("InstancedMesh"!==this.getClassName()?"YES":"NO");t+=", # of submeshes: "+(this.subMeshes?this.subMeshes.length:0);const s=this._internalAbstractMeshDataInfo._skeleton;return s&&(t+=", skeleton: "+s.name),e&&(t+=", billboard mode: "+["NONE","X","Y",null,"Z",null,null,"ALL"][this.billboardMode],t+=", freeze wrld mat: "+(this._isWorldMatrixFrozen||this._waitingData.freezeWorldMatrix?"YES":"NO")),t}_getEffectiveParent(){return this._masterMesh&&this.billboardMode!==Rs.BILLBOARDMODE_NONE?this._masterMesh:super._getEffectiveParent()}_getActionManagerForTrigger(e,t=!0){if(this.actionManager&&(t||this.actionManager.isRecursive)){if(!e)return this.actionManager;if(this.actionManager.hasSpecificTrigger(e))return this.actionManager}return this.parent?this.parent._getActionManagerForTrigger(e,!1):null}_rebuild(e=!1){if(this.onRebuildObservable.notifyObservers(this),null!==this._occlusionQuery&&(this._occlusionQuery=null),this.subMeshes){for(const e of this.subMeshes)e._rebuild();this.resetDrawCache()}}_resyncLightSources(){this._lightSources.length=0;for(const e of this.getScene().lights)e.isEnabled()&&e.canAffectMesh(this)&&this._lightSources.push(e);this._markSubMeshesAsLightDirty()}_resyncLightSource(e){const t=e.isEnabled()&&e.canAffectMesh(this),s=this._lightSources.indexOf(e);let i=!1;if(-1===s){if(!t)return;this._lightSources.push(e)}else{if(t)return;i=!0,this._lightSources.splice(s,1)}this._markSubMeshesAsLightDirty(i)}_unBindEffect(){for(const e of this.subMeshes)e.setEffect(null)}_removeLightSource(e,t){const s=this._lightSources.indexOf(e);-1!==s&&(this._lightSources.splice(s,1),this._markSubMeshesAsLightDirty(t))}_markSubMeshesAsDirty(e){if(this.subMeshes)for(const t of this.subMeshes)for(let s=0;s<t._drawWrappers.length;++s){const i=t._drawWrappers[s];i&&i.defines&&i.defines.markAllAsDirty&&e(i.defines)}}_markSubMeshesAsLightDirty(e=!1){this._markSubMeshesAsDirty((t=>t.markAsLightDirty(e)))}_markSubMeshesAsAttributesDirty(){this._markSubMeshesAsDirty((e=>e.markAsAttributesDirty()))}_markSubMeshesAsMiscDirty(){this._markSubMeshesAsDirty((e=>e.markAsMiscDirty()))}markAsDirty(e){return this._currentRenderId=Number.MAX_VALUE,this._isDirty=!0,this}resetDrawCache(e){if(this.subMeshes)for(const t of this.subMeshes)t.resetDrawCache(e)}get isBlocked(){return!1}getLOD(e){return this}getTotalVertices(){return 0}getTotalIndices(){return 0}getIndices(){return null}getVerticesData(e){return null}setVerticesData(e,t,s,i){return this}updateVerticesData(e,t,s,i){return this}setIndices(e,t){return this}isVerticesDataPresent(e){return!1}getBoundingInfo(){return this._masterMesh?this._masterMesh.getBoundingInfo():(this._boundingInfoIsDirty&&(this._boundingInfoIsDirty=!1,this._updateBoundingInfo()),this._boundingInfo)}getRawBoundingInfo(){return this.rawBoundingInfo??this.getBoundingInfo()}setBoundingInfo(e){return this._boundingInfo=e,this}get hasBoundingInfo(){return null!==this._boundingInfo}buildBoundingInfo(e,t,s){return this._boundingInfo=new _s(e,t,s),this._boundingInfo}normalizeToUnitCube(e=!0,t=!1,s){return super.normalizeToUnitCube(e,t,s)}get useBones(){return this.skeleton&&this.getScene().skeletonsEnabled&&this.isVerticesDataPresent(ns.MatricesIndicesKind)&&this.isVerticesDataPresent(ns.MatricesWeightsKind)}_preActivate(){}_preActivateForIntermediateRendering(e){}_activate(e,t){return this._renderId=e,!0}_postActivate(){}_freeze(){}_unFreeze(){}getWorldMatrix(){return this._masterMesh&&this.billboardMode===Rs.BILLBOARDMODE_NONE?this._masterMesh.getWorldMatrix():super.getWorldMatrix()}_getWorldMatrixDeterminant(){return this._masterMesh?this._masterMesh._getWorldMatrixDeterminant():super._getWorldMatrixDeterminant()}get isAnInstance(){return!1}get hasInstances(){return!1}get hasThinInstances(){return!1}movePOV(e,t,s){return this.position.addInPlace(this.calcMovePOV(e,t,s)),this}calcMovePOV(e,t,s){const i=new V;(this.rotationQuaternion?this.rotationQuaternion:G.RotationYawPitchRoll(this.rotation.y,this.rotation.x,this.rotation.z)).toRotationMatrix(i);const r=U.Zero(),n=this.definedFacingForward?-1:1;return U.TransformCoordinatesFromFloatsToRef(e*n,t,s*n,i,r),r}rotatePOV(e,t,s){return this.rotation.addInPlace(this.calcRotatePOV(e,t,s)),this}calcRotatePOV(e,t,s){const i=this.definedFacingForward?1:-1;return new U(e*i,t,s*i)}_refreshBoundingInfo(e,t){if(e){const s=ps(e,0,this.getTotalVertices(),t);this._boundingInfo?this._boundingInfo.reConstruct(s.minimum,s.maximum):this._boundingInfo=new _s(s.minimum,s.maximum)}if(this.subMeshes)for(let t=0;t<this.subMeshes.length;t++)this.subMeshes[t].refreshBoundingInfo(e);this._updateBoundingInfo()}_refreshBoundingInfoDirect(e){if(this._boundingInfo?this._boundingInfo.reConstruct(e.minimum,e.maximum):this._boundingInfo=new _s(e.minimum,e.maximum),this.subMeshes)for(let e=0;e<this.subMeshes.length;e++)this.subMeshes[e].refreshBoundingInfo(null);this._updateBoundingInfo()}static _ApplySkeleton(e,t,s,i,r,n,a){!function(e,t,s,i,r,n,a){const o=z.Vector3[0],h=z.Matrix[0],l=z.Matrix[1],c=t===ns.NormalKind?U.TransformNormalFromFloatsToRef:U.TransformCoordinatesFromFloatsToRef;for(let t=0,u=0;t<e.length;t+=3,u+=4){let d,_;for(h.reset(),d=0;d<4;d++)_=r[u+d],_>0&&(V.FromFloat32ArrayToRefScaled(s,Math.floor(16*i[u+d]),_,l),h.addToSelf(l));if(n&&a)for(d=0;d<4;d++)_=a[u+d],_>0&&(V.FromFloat32ArrayToRefScaled(s,Math.floor(16*n[u+d]),_,l),h.addToSelf(l));c(e[t],e[t+1],e[t+2],h,o),o.toArray(e,t)}}(e,t,s,i,r,n,a)}_getData(e,t,s=ns.PositionKind){const i=e.cache,r=e=>{if(i){const t=i._vertexData||={};return t[e]||this.copyVerticesData(e,t),t[e]}return this.getVerticesData(e)};if(t||=r(s),!t)return null;if(i?(i._outputData?i._outputData.set(t):i._outputData=new Float32Array(t),t=i._outputData):(e.applyMorph&&this.morphTargetManager||e.applySkeleton&&this.skeleton)&&(t=t.slice()),e.applyMorph&&this.morphTargetManager&&function(e,t,s){let i=null;switch(t){case ns.PositionKind:i=e=>e.getPositions();break;case ns.NormalKind:i=e=>e.getNormals();break;case ns.TangentKind:i=e=>e.getTangents();break;case ns.UVKind:i=e=>e.getUVs();break;default:return}for(let t=0;t<e.length;t++){let r=e[t];for(let n=0;n<s.numTargets;n++){const a=s.getTarget(n),o=a.influence;if(0!==o){const s=i(a);s&&(r+=(s[t]-e[t])*o)}}e[t]=r}}(t,s,this.morphTargetManager),e.applySkeleton&&this.skeleton){const e=r(ns.MatricesIndicesKind),i=r(ns.MatricesWeightsKind);if(i&&e){const n=this.numBoneInfluencers>4,a=n?r(ns.MatricesIndicesExtraKind):null,o=n?r(ns.MatricesWeightsExtraKind):null,h=this.skeleton.getTransformMatrices(this);Gs._ApplySkeleton(t,s,h,e,i,a,o)}}if(!1!==e.updatePositionsArray&&s===ns.PositionKind){const e=this._internalAbstractMeshDataInfo._positions||[],s=e.length;if(e.length=t.length/3,s<e.length)for(let t=s;t<e.length;t++)e[t]=new U;for(let s=0,i=0;s<e.length;s++,i+=3)e[s].copyFromFloats(t[i],t[i+1],t[i+2]);this._internalAbstractMeshDataInfo._positions=e}return t}getNormalsData(e=!1,t=!1){return this._getData({applySkeleton:e,applyMorph:t,updatePositionsArray:!1},null,ns.NormalKind)}getPositionData(e=!1,t=!1,s=null){return this._getData({applySkeleton:e,applyMorph:t,updatePositionsArray:!1},s,ns.PositionKind)}_updateBoundingInfo(){return this._boundingInfo?this._boundingInfo.update(this.worldMatrixFromCache):this._boundingInfo=new _s(U.Zero(),U.Zero(),this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}_updateSubMeshesBoundingInfo(e){if(!this.subMeshes)return this;const t=this.subMeshes.length;for(let s=0;s<t;s++){const i=this.subMeshes[s];(t>1||!i.IsGlobal)&&i.updateBoundingInfo(e)}return this}_afterComputeWorldMatrix(){this.doNotSyncBoundingInfo||(this._boundingInfoIsDirty=!0)}isInFrustum(e){return this.getBoundingInfo().isInFrustum(e,this.cullingStrategy)}isCompletelyInFrustum(e){return this.getBoundingInfo().isCompletelyInFrustum(e)}intersectsMesh(e,t=!1,s){const i=this.getBoundingInfo(),r=e.getBoundingInfo();if(i.intersects(r,t))return!0;if(s)for(const s of this.getChildMeshes())if(s.intersectsMesh(e,t,!0))return!0;return!1}intersectsPoint(e){return this.getBoundingInfo().intersectsPoint(e)}get checkCollisions(){return this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions}set checkCollisions(e){this._internalAbstractMeshDataInfo._meshCollisionData._checkCollisions=e}get collider(){return this._internalAbstractMeshDataInfo._meshCollisionData._collider}moveWithCollisions(e){this.getAbsolutePosition().addToRef(this.ellipsoidOffset,this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions);const t=this.getScene().collisionCoordinator;return this._internalAbstractMeshDataInfo._meshCollisionData._collider||(this._internalAbstractMeshDataInfo._meshCollisionData._collider=t.createCollider()),this._internalAbstractMeshDataInfo._meshCollisionData._collider._radius=this.ellipsoid,t.getNewPosition(this._internalAbstractMeshDataInfo._meshCollisionData._oldPositionForCollisions,e,this._internalAbstractMeshDataInfo._meshCollisionData._collider,this.collisionRetryCount,this,this._onCollisionPositionChange,this.uniqueId),this}_collideForSubMesh(e,t,s){if(this._generatePointsArray(),!this._positions)return this;if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(t)){e._lastColliderTransformMatrix=t.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];const s=e.verticesStart,i=e.verticesStart+e.verticesCount;for(let r=s;r<i;r++)e._lastColliderWorldVertices.push(U.TransformCoordinates(this._positions[r],t))}return s._collide(e._trianglePlanes,e._lastColliderWorldVertices,this.getIndices(),e.indexStart,e.indexStart+e.indexCount,e.verticesStart,!!e.getMaterial(),this,this._shouldConvertRHS(),e.getMaterial()?.fillMode===Ze.MATERIAL_TriangleStripDrawMode),this}_processCollisionsForSubMeshes(e,t){const s=this._scene.getCollidingSubMeshCandidates(this,e),i=s.length;for(let r=0;r<i;r++){const n=s.data[r];i>1&&!n._checkCollision(e)||this._collideForSubMesh(n,t,e)}return this}_shouldConvertRHS(){return!1}_checkCollision(e){if(!this.getBoundingInfo()._checkCollision(e))return this;const t=z.Matrix[0],s=z.Matrix[1];return V.ScalingToRef(1/e._radius.x,1/e._radius.y,1/e._radius.z,t),this.worldMatrixFromCache.multiplyToRef(t,s),this._processCollisionsForSubMeshes(e,s),this}_generatePointsArray(){return!1}intersects(e,t,s,i=!1,r,n=!1){const a=new Ms,o=this.getClassName(),h="InstancedLinesMesh"===o||"LinesMesh"===o||"GreasedLineMesh"===o?this.intersectionThreshold:0,l=this.getBoundingInfo();if(!this.subMeshes)return a;if(!(n||e.intersectsSphere(l.boundingSphere,h)&&e.intersectsBox(l.boundingBox,h)))return a;if(i)return a.hit=!n,a.pickedMesh=n?null:this,a.distance=n?0:U.Distance(e.origin,l.boundingSphere.center),a.subMeshId=0,a;if(!this._generatePointsArray())return a;let c=null;const u=this._scene.getIntersectingSubMeshCandidates(this,e),d=u.length;let _=!1;for(let e=0;e<d;e++){const t=u.data[e].getMaterial();if(t&&(t.fillMode==Ze.MATERIAL_TriangleStripDrawMode||t.fillMode==Ze.MATERIAL_TriangleFillMode||t.fillMode==Ze.MATERIAL_WireFrameFillMode||t.fillMode==Ze.MATERIAL_PointFillMode||t.fillMode==Ze.MATERIAL_LineListDrawMode)){_=!0;break}}if(!_)return a.hit=!0,a.pickedMesh=this,a.distance=U.Distance(e.origin,l.boundingSphere.center),a.subMeshId=-1,a;for(let i=0;i<d;i++){const r=u.data[i];if(d>1&&!n&&!r.canIntersects(e))continue;const a=r.intersects(e,this._positions,this.getIndices(),t,s);if(a&&(t||!c||a.distance<c.distance)&&(c=a,c.subMeshId=i,t))break}if(c){const t=r??this.getWorldMatrix(),s=z.Vector3[0],i=z.Vector3[1];U.TransformCoordinatesToRef(e.origin,t,s),e.direction.scaleToRef(c.distance,i);const n=U.TransformNormal(i,t).addInPlace(s);return a.hit=!0,a.distance=U.Distance(s,n),a.pickedPoint=n,a.pickedMesh=this,a.bu=c.bu||0,a.bv=c.bv||0,a.subMeshFaceId=c.faceId,a.faceId=c.faceId+u.data[c.subMeshId].indexStart/(-1!==this.getClassName().indexOf("LinesMesh")?2:3),a.subMeshId=c.subMeshId,a}return a}clone(e,t,s){return null}releaseSubMeshes(){if(this.subMeshes)for(;this.subMeshes.length;)this.subMeshes[0].dispose();else this.subMeshes=[];return this}dispose(e,t=!1){let s;const i=this.getScene();for(this._scene.useMaterialMeshMap&&this._internalAbstractMeshDataInfo._material&&this._internalAbstractMeshDataInfo._material.meshMap&&(this._internalAbstractMeshDataInfo._material.meshMap[this.uniqueId]=void 0),i.freeActiveMeshes(),i.freeRenderingGroups(),i.renderingManager.maintainStateBetweenFrames&&i.renderingManager.restoreDispachedFlags(),void 0!==this.actionManager&&null!==this.actionManager&&(this.actionManager.disposeWhenUnowned&&!this._scene.meshes.some((e=>e!==this&&e.actionManager===this.actionManager))&&this.actionManager.dispose(),this.actionManager=null),this._internalAbstractMeshDataInfo._skeleton=null,this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null),s=0;s<this._intersectionsInProgress.length;s++){const e=this._intersectionsInProgress[s],t=e._intersectionsInProgress.indexOf(this);e._intersectionsInProgress.splice(t,1)}this._intersectionsInProgress.length=0;i.lights.forEach((e=>{let t=e.includedOnlyMeshes.indexOf(this);-1!==t&&e.includedOnlyMeshes.splice(t,1),t=e.excludedMeshes.indexOf(this),-1!==t&&e.excludedMeshes.splice(t,1);const s=e.getShadowGenerators();if(s){const e=s.values();for(let s=e.next();!0!==s.done;s=e.next()){const e=s.value.getShadowMap();e&&e.renderList&&(t=e.renderList.indexOf(this),-1!==t&&e.renderList.splice(t,1))}}})),"InstancedMesh"===this.getClassName()&&"InstancedLinesMesh"===this.getClassName()||this.releaseSubMeshes();const r=i.getEngine();if(null!==this._occlusionQuery&&(this.isOcclusionQueryInProgress=!1,r.deleteQuery(this._occlusionQuery),this._occlusionQuery=null),r.wipeCaches(),i.removeMesh(this),this._parentContainer){const e=this._parentContainer.meshes.indexOf(this);e>-1&&this._parentContainer.meshes.splice(e,1),this._parentContainer=null}if(t&&this.material&&("MultiMaterial"===this.material.getClassName()?this.material.dispose(!1,!0,!0):this.material.dispose(!1,!0)),!e)for(s=0;s<i.particleSystems.length;s++)i.particleSystems[s].emitter===this&&(i.particleSystems[s].dispose(),s--);this._internalAbstractMeshDataInfo._facetData.facetDataEnabled&&this.disableFacetData(),this._uniformBuffer.dispose(),this.onAfterWorldMatrixUpdateObservable.clear(),this.onCollideObservable.clear(),this.onCollisionPositionChangeObservable.clear(),this.onRebuildObservable.clear(),super.dispose(e,t)}_initFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;e.facetNormals||(e.facetNormals=[]),e.facetPositions||(e.facetPositions=[]),e.facetPartitioning||(e.facetPartitioning=new Array),e.facetNb=this.getIndices().length/3|0,e.partitioningSubdivisions=e.partitioningSubdivisions?e.partitioningSubdivisions:10,e.partitioningBBoxRatio=e.partitioningBBoxRatio?e.partitioningBBoxRatio:1.01;for(let t=0;t<e.facetNb;t++)e.facetNormals[t]=U.Zero(),e.facetPositions[t]=U.Zero();return e.facetDataEnabled=!0,this}updateFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;e.facetDataEnabled||this._initFacetData();const t=this.getVerticesData(ns.PositionKind),s=this.getIndices(),i=this.getVerticesData(ns.NormalKind),r=this.getBoundingInfo();if(e.facetDepthSort&&!e.facetDepthSortEnabled){if(e.facetDepthSortEnabled=!0,s instanceof Uint16Array)e.depthSortedIndices=new Uint16Array(s);else if(s instanceof Uint32Array)e.depthSortedIndices=new Uint32Array(s);else{let t=!1;for(let e=0;e<s.length;e++)if(s[e]>65535){t=!0;break}e.depthSortedIndices=t?new Uint32Array(s):new Uint16Array(s)}if(e.facetDepthSortFunction=function(e,t){return t.sqDistance-e.sqDistance},!e.facetDepthSortFrom){const t=this.getScene().activeCamera;e.facetDepthSortFrom=t?t.position:U.Zero()}e.depthSortedFacets=[];for(let t=0;t<e.facetNb;t++){const s={ind:3*t,sqDistance:0};e.depthSortedFacets.push(s)}e.invertedMatrix=V.Identity(),e.facetDepthSortOrigin=U.Zero()}e.bbSize.x=r.maximum.x-r.minimum.x>A?r.maximum.x-r.minimum.x:A,e.bbSize.y=r.maximum.y-r.minimum.y>A?r.maximum.y-r.minimum.y:A,e.bbSize.z=r.maximum.z-r.minimum.z>A?r.maximum.z-r.minimum.z:A;let n=e.bbSize.x>e.bbSize.y?e.bbSize.x:e.bbSize.y;if(n=n>e.bbSize.z?n:e.bbSize.z,e.subDiv.max=e.partitioningSubdivisions,e.subDiv.X=Math.floor(e.subDiv.max*e.bbSize.x/n),e.subDiv.Y=Math.floor(e.subDiv.max*e.bbSize.y/n),e.subDiv.Z=Math.floor(e.subDiv.max*e.bbSize.z/n),e.subDiv.X=e.subDiv.X<1?1:e.subDiv.X,e.subDiv.Y=e.subDiv.Y<1?1:e.subDiv.Y,e.subDiv.Z=e.subDiv.Z<1?1:e.subDiv.Z,e.facetParameters.facetNormals=this.getFacetLocalNormals(),e.facetParameters.facetPositions=this.getFacetLocalPositions(),e.facetParameters.facetPartitioning=this.getFacetLocalPartitioning(),e.facetParameters.bInfo=r,e.facetParameters.bbSize=e.bbSize,e.facetParameters.subDiv=e.subDiv,e.facetParameters.ratio=this.partitioningBBoxRatio,e.facetParameters.depthSort=e.facetDepthSort,e.facetDepthSort&&e.facetDepthSortEnabled&&(this.computeWorldMatrix(!0),this._worldMatrix.invertToRef(e.invertedMatrix),U.TransformCoordinatesToRef(e.facetDepthSortFrom,e.invertedMatrix,e.facetDepthSortOrigin),e.facetParameters.distanceTo=e.facetDepthSortOrigin),e.facetParameters.depthSortedFacets=e.depthSortedFacets,i&&Es.ComputeNormals(t,s,i,e.facetParameters),e.facetDepthSort&&e.facetDepthSortEnabled){e.depthSortedFacets.sort(e.facetDepthSortFunction);const t=e.depthSortedIndices.length/3|0;for(let i=0;i<t;i++){const t=e.depthSortedFacets[i].ind;e.depthSortedIndices[3*i]=s[t],e.depthSortedIndices[3*i+1]=s[t+1],e.depthSortedIndices[3*i+2]=s[t+2]}this.updateIndices(e.depthSortedIndices,void 0,!0)}return this}getFacetLocalNormals(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetNormals||this.updateFacetData(),e.facetNormals}getFacetLocalPositions(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetPositions||this.updateFacetData(),e.facetPositions}getFacetLocalPartitioning(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetPartitioning||this.updateFacetData(),e.facetPartitioning}getFacetPosition(e){const t=U.Zero();return this.getFacetPositionToRef(e,t),t}getFacetPositionToRef(e,t){const s=this.getFacetLocalPositions()[e],i=this.getWorldMatrix();return U.TransformCoordinatesToRef(s,i,t),this}getFacetNormal(e){const t=U.Zero();return this.getFacetNormalToRef(e,t),t}getFacetNormalToRef(e,t){const s=this.getFacetLocalNormals()[e];return U.TransformNormalToRef(s,this.getWorldMatrix(),t),this}getFacetsAtLocalCoordinates(e,t,s){const i=this.getBoundingInfo(),r=this._internalAbstractMeshDataInfo._facetData,n=Math.floor((e-i.minimum.x*r.partitioningBBoxRatio)*r.subDiv.X*r.partitioningBBoxRatio/r.bbSize.x),a=Math.floor((t-i.minimum.y*r.partitioningBBoxRatio)*r.subDiv.Y*r.partitioningBBoxRatio/r.bbSize.y),o=Math.floor((s-i.minimum.z*r.partitioningBBoxRatio)*r.subDiv.Z*r.partitioningBBoxRatio/r.bbSize.z);return n<0||n>r.subDiv.max||a<0||a>r.subDiv.max||o<0||o>r.subDiv.max?null:r.facetPartitioning[n+r.subDiv.max*a+r.subDiv.max*r.subDiv.max*o]}getClosestFacetAtCoordinates(e,t,s,i,r=!1,n=!0){const a=this.getWorldMatrix(),o=z.Matrix[5];a.invertToRef(o);const h=z.Vector3[8];U.TransformCoordinatesFromFloatsToRef(e,t,s,o,h);const l=this.getClosestFacetAtLocalCoordinates(h.x,h.y,h.z,i,r,n);return i&&U.TransformCoordinatesFromFloatsToRef(i.x,i.y,i.z,a,i),l}getClosestFacetAtLocalCoordinates(e,t,s,i,r=!1,n=!0){let a=null,o=0,h=0,l=0,c=0,u=0,d=0,_=0,f=0;const p=this.getFacetLocalPositions(),m=this.getFacetLocalNormals(),g=this.getFacetsAtLocalCoordinates(e,t,s);if(!g)return null;let T,E,A,y=Number.MAX_VALUE,b=y;for(let R=0;R<g.length;R++)T=g[R],E=m[T],A=p[T],c=(e-A.x)*E.x+(t-A.y)*E.y+(s-A.z)*E.z,(!r||r&&n&&c>=0||r&&!n&&c<=0)&&(c=E.x*A.x+E.y*A.y+E.z*A.z,u=-(E.x*e+E.y*t+E.z*s-c)/(E.x*E.x+E.y*E.y+E.z*E.z),d=e+E.x*u,_=t+E.y*u,f=s+E.z*u,o=d-e,h=_-t,l=f-s,b=o*o+h*h+l*l,b<y&&(y=b,a=T,i&&(i.x=d,i.y=_,i.z=f)));return a}getFacetDataParameters(){return this._internalAbstractMeshDataInfo._facetData.facetParameters}disableFacetData(){const e=this._internalAbstractMeshDataInfo._facetData;return e.facetDataEnabled&&(e.facetDataEnabled=!1,e.facetPositions=[],e.facetNormals=[],e.facetPartitioning=new Array,e.facetParameters=null,e.depthSortedIndices=new Uint32Array(0)),this}updateIndices(e,t,s=!1){return this}createNormals(e){const t=this.getVerticesData(ns.PositionKind),s=this.getIndices();let i;return i=this.isVerticesDataPresent(ns.NormalKind)?this.getVerticesData(ns.NormalKind):[],Es.ComputeNormals(t,s,i,{useRightHandedSystem:this.getScene().useRightHandedSystem}),this.setVerticesData(ns.NormalKind,i,e),this}alignWithNormal(e,t){t||(t=Bs.Y);const s=z.Vector3[0],i=z.Vector3[1];return U.CrossToRef(t,e,i),U.CrossToRef(e,i,s),this.rotationQuaternion?G.RotationQuaternionFromAxisToRef(s,e,i,this.rotationQuaternion):U.RotationFromAxisToRef(s,e,i,this.rotation),this}_checkOcclusionQuery(){return!1}disableEdgesRendering(){throw Y("EdgesRenderer")}enableEdgesRendering(e,t,s){throw Y("EdgesRenderer")}getConnectedParticleSystems(){return this._scene.particleSystems.filter((e=>e.emitter===this))}}Gs.OCCLUSION_TYPE_NONE=0,Gs.OCCLUSION_TYPE_OPTIMISTIC=1,Gs.OCCLUSION_TYPE_STRICT=2,Gs.OCCLUSION_ALGORITHM_TYPE_ACCURATE=0,Gs.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE=1,Gs.CULLINGSTRATEGY_STANDARD=Ze.MESHES_CULLINGSTRATEGY_STANDARD,Gs.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY=Ze.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY,Gs.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION=Ze.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION,Gs.CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY=Ze.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY,e([f.filter(((...[e,t,s,i,r])=>!(Array.isArray(e)||Array.isArray(t)||Array.isArray(s)||Array.isArray(i)||Array.isArray(r))))],Gs,"_ApplySkeleton",null),I("BABYLON.AbstractMesh",Gs);class Vs{constructor(){this.reset()}reset(){this.enabled=!1,this.mask=255,this.func=Ze.ALWAYS,this.funcRef=1,this.funcMask=255,this.opStencilFail=Ze.KEEP,this.opDepthFail=Ze.KEEP,this.opStencilDepthPass=Ze.REPLACE}get func(){return this._func}set func(e){this._func=e}get funcRef(){return this._funcRef}set funcRef(e){this._funcRef=e}get funcMask(){return this._funcMask}set funcMask(e){this._funcMask=e}get opStencilFail(){return this._opStencilFail}set opStencilFail(e){this._opStencilFail=e}get opDepthFail(){return this._opDepthFail}set opDepthFail(e){this._opDepthFail=e}get opStencilDepthPass(){return this._opStencilDepthPass}set opStencilDepthPass(e){this._opStencilDepthPass=e}get mask(){return this._mask}set mask(e){this._mask=e}get enabled(){return this._enabled}set enabled(e){this._enabled=e}getClassName(){return"MaterialStencilState"}copyTo(e){re.Clone((()=>e),this)}serialize(){return re.Serialize(this)}parse(e,t,s){re.Parse((()=>this),e,t,s)}}e([a()],Vs.prototype,"func",null),e([a()],Vs.prototype,"funcRef",null),e([a()],Vs.prototype,"funcMask",null),e([a()],Vs.prototype,"opStencilFail",null),e([a()],Vs.prototype,"opDepthFail",null),e([a()],Vs.prototype,"opStencilDepthPass",null),e([a()],Vs.prototype,"mask",null),e([a()],Vs.prototype,"enabled",null);class Hs{static CompareLightsPriority(e,t){return e.shadowEnabled!==t.shadowEnabled?(t.shadowEnabled?1:0)-(e.shadowEnabled?1:0):t.renderPriority-e.renderPriority}}function zs(e,t,s){s&&e.setFloat4(t,s.normal.x,s.normal.y,s.normal.z,s.d)}Hs.FALLOFF_DEFAULT=0,Hs.FALLOFF_PHYSICAL=1,Hs.FALLOFF_GLTF=2,Hs.FALLOFF_STANDARD=3,Hs.LIGHTMAP_DEFAULT=0,Hs.LIGHTMAP_SPECULAR=1,Hs.LIGHTMAP_SHADOWSONLY=2,Hs.INTENSITYMODE_AUTOMATIC=0,Hs.INTENSITYMODE_LUMINOUSPOWER=1,Hs.INTENSITYMODE_LUMINOUSINTENSITY=2,Hs.INTENSITYMODE_ILLUMINANCE=3,Hs.INTENSITYMODE_LUMINANCE=4,Hs.LIGHTTYPEID_POINTLIGHT=0,Hs.LIGHTTYPEID_DIRECTIONALLIGHT=1,Hs.LIGHTTYPEID_SPOTLIGHT=2,Hs.LIGHTTYPEID_HEMISPHERICLIGHT=3;const Xs=ee.Black();function Ws(e,t,s){t._needUVs=!0,t[s]=!0,e.optimizeUVAllocation&&e.getTextureMatrix().isIdentityAs3x2()?(t[s+"DIRECTUV"]=e.coordinatesIndex+1,t["MAINUV"+(e.coordinatesIndex+1)]=!0):t[s+"DIRECTUV"]=0}function Ys(e,t,s){const i=e.getTextureMatrix();t.updateMatrix(s+"Matrix",i)}function Ks(e,t,s,i,r,n=!0){e._bindLight(t,s,i,r,n)}function qs(e,t,s,i,r,n,a,o=!1){a._areMiscDirty&&(a.LOGARITHMICDEPTH=s,a.POINTSIZE=i,a.FOG=r&&function(e,t){return t.fogEnabled&&e.applyFog&&t.fogMode!==Ze.FOGMODE_NONE}(e,t),a.NONUNIFORMSCALING=e.nonUniformScaling,a.ALPHATEST=n,a.DECAL_AFTER_DETAIL=o)}function Qs(e,t,s,i,r,n,a){switch(a.needNormals=!0,void 0===r["LIGHT"+i]&&(a.needRebuild=!0),r["LIGHT"+i]=!0,r["SPOTLIGHT"+i]=!1,r["HEMILIGHT"+i]=!1,r["POINTLIGHT"+i]=!1,r["DIRLIGHT"+i]=!1,s.prepareLightSpecificDefines(r,i),r["LIGHT_FALLOFF_PHYSICAL"+i]=!1,r["LIGHT_FALLOFF_GLTF"+i]=!1,r["LIGHT_FALLOFF_STANDARD"+i]=!1,s.falloffType){case Hs.FALLOFF_GLTF:r["LIGHT_FALLOFF_GLTF"+i]=!0;break;case Hs.FALLOFF_PHYSICAL:r["LIGHT_FALLOFF_PHYSICAL"+i]=!0;break;case Hs.FALLOFF_STANDARD:r["LIGHT_FALLOFF_STANDARD"+i]=!0}if(s.specular.equalsFloats(0,0,0)||(a.specularEnabled=!0),r["SHADOW"+i]=!1,r["SHADOWCSM"+i]=!1,r["SHADOWCSMDEBUG"+i]=!1,r["SHADOWCSMNUM_CASCADES"+i]=!1,r["SHADOWCSMUSESHADOWMAXZ"+i]=!1,r["SHADOWCSMNOBLEND"+i]=!1,r["SHADOWCSM_RIGHTHANDED"+i]=!1,r["SHADOWPCF"+i]=!1,r["SHADOWPCSS"+i]=!1,r["SHADOWPOISSON"+i]=!1,r["SHADOWESM"+i]=!1,r["SHADOWCLOSEESM"+i]=!1,r["SHADOWCUBE"+i]=!1,r["SHADOWLOWQUALITY"+i]=!1,r["SHADOWMEDIUMQUALITY"+i]=!1,t&&t.receiveShadows&&e.shadowsEnabled&&s.shadowEnabled){const t=s.getShadowGenerator(e.activeCamera)??s.getShadowGenerator();if(t){const e=t.getShadowMap();e&&e.renderList&&e.renderList.length>0&&(a.shadowEnabled=!0,t.prepareDefines(r,i))}}s.lightmapMode!=Hs.LIGHTMAP_DEFAULT?(a.lightmapMode=!0,r["LIGHTMAPEXCLUDED"+i]=!0,r["LIGHTMAPNOSPECULAR"+i]=s.lightmapMode==Hs.LIGHTMAP_SHADOWSONLY):(r["LIGHTMAPEXCLUDED"+i]=!1,r["LIGHTMAPNOSPECULAR"+i]=!1)}function js(e,t,s,i,r,n=null,a=!1){let o=function(e,t){let s=!1;if(e.activeCamera){const i=t.CAMERA_ORTHOGRAPHIC?1:0,r=t.CAMERA_PERSPECTIVE?1:0,n=e.activeCamera.mode===Ze.ORTHOGRAPHIC_CAMERA?1:0,a=e.activeCamera.mode===Ze.PERSPECTIVE_CAMERA?1:0;(i^n||r^a)&&(t.CAMERA_ORTHOGRAPHIC=1===n,t.CAMERA_PERSPECTIVE=1===a,s=!0)}return s}(e,i);!1!==n&&(o=function(e,t,s){let i=!1;const r=!!(e.clipPlane??t.clipPlane),n=!!(e.clipPlane2??t.clipPlane2),a=!!(e.clipPlane3??t.clipPlane3),o=!!(e.clipPlane4??t.clipPlane4),h=!!(e.clipPlane5??t.clipPlane5),l=!!(e.clipPlane6??t.clipPlane6);return s.CLIPPLANE!==r&&(s.CLIPPLANE=r,i=!0),s.CLIPPLANE2!==n&&(s.CLIPPLANE2=n,i=!0),s.CLIPPLANE3!==a&&(s.CLIPPLANE3=a,i=!0),s.CLIPPLANE4!==o&&(s.CLIPPLANE4=o,i=!0),s.CLIPPLANE5!==h&&(s.CLIPPLANE5=h,i=!0),s.CLIPPLANE6!==l&&(s.CLIPPLANE6=l,i=!0),i}(s,e,i)),i.DEPTHPREPASS!==!t.getColorWrite()&&(i.DEPTHPREPASS=!i.DEPTHPREPASS,o=!0),i.INSTANCES!==r&&(i.INSTANCES=r,o=!0),i.THIN_INSTANCES!==a&&(i.THIN_INSTANCES=a,o=!0),o&&i.markAsUnprocessed()}function Zs(e,t,s,i,r=null,n=!1){r&&r.push("Light"+e),n||(t.push("vLightData"+e,"vLightDiffuse"+e,"vLightSpecular"+e,"vLightDirection"+e,"vLightFalloff"+e,"vLightGround"+e,"lightMatrix"+e,"shadowsInfo"+e,"depthValues"+e),s.push("shadowTexture"+e),s.push("depthTexture"+e),t.push("viewFrustumZ"+e,"cascadeBlendFactor"+e,"lightSizeUVCorrection"+e,"depthCorrection"+e,"penumbraDarkness"+e,"frustumLengths"+e),i&&(s.push("projectionLightTexture"+e),t.push("textureProjectionMatrix"+e)))}class $s{get shaderLanguage(){return this._shaderLanguage}get canRenderToMRT(){return!1}set alpha(e){if(this._alpha===e)return;const t=this._alpha;this._alpha=e,1!==t&&1!==e||this.markAsDirty($s.MiscDirtyFlag+$s.PrePassDirtyFlag)}get alpha(){return this._alpha}set backFaceCulling(e){this._backFaceCulling!==e&&(this._backFaceCulling=e,this.markAsDirty($s.TextureDirtyFlag))}get backFaceCulling(){return this._backFaceCulling}set cullBackFaces(e){this._cullBackFaces!==e&&(this._cullBackFaces=e,this.markAsDirty($s.TextureDirtyFlag))}get cullBackFaces(){return this._cullBackFaces}get blockDirtyMechanism(){return this._blockDirtyMechanism}set blockDirtyMechanism(e){this._blockDirtyMechanism!==e&&(this._blockDirtyMechanism=e,e||this.markDirty())}atomicMaterialsUpdate(e){this.blockDirtyMechanism=!0;try{e(this)}finally{this.blockDirtyMechanism=!1}}get hasRenderTargetTextures(){return this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._eventInfo.hasRenderTargetTextures}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get onBindObservable(){return this._onBindObservable||(this._onBindObservable=new g),this._onBindObservable}set onBind(e){this._onBindObserver&&this.onBindObservable.remove(this._onBindObserver),this._onBindObserver=this.onBindObservable.add(e)}get onUnBindObservable(){return this._onUnBindObservable||(this._onUnBindObservable=new g),this._onUnBindObservable}get onEffectCreatedObservable(){return this._onEffectCreatedObservable||(this._onEffectCreatedObservable=new g),this._onEffectCreatedObservable}set alphaMode(e){this._alphaMode!==e&&(this._alphaMode=e,this.markAsDirty($s.TextureDirtyFlag))}get alphaMode(){return this._alphaMode}set needDepthPrePass(e){this._needDepthPrePass!==e&&(this._needDepthPrePass=e,this._needDepthPrePass&&(this.checkReadyOnEveryCall=!0))}get needDepthPrePass(){return this._needDepthPrePass}get isPrePassCapable(){return!1}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAsDirty($s.MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}get wireframe(){switch(this._fillMode){case $s.WireFrameFillMode:case $s.LineListDrawMode:case $s.LineLoopDrawMode:case $s.LineStripDrawMode:return!0}return this._scene.forceWireframe}set wireframe(e){this.fillMode=e?$s.WireFrameFillMode:$s.TriangleFillMode}get pointsCloud(){switch(this._fillMode){case $s.PointFillMode:case $s.PointListDrawMode:return!0}return this._scene.forcePointsCloud}set pointsCloud(e){this.fillMode=e?$s.PointFillMode:$s.TriangleFillMode}get fillMode(){return this._fillMode}set fillMode(e){this._fillMode!==e&&(this._fillMode=e,this.markAsDirty($s.MiscDirtyFlag))}get useLogarithmicDepth(){return this._useLogarithmicDepth}set useLogarithmicDepth(e){const t=this.getScene().getEngine().getCaps().fragmentDepthSupported;e&&!t&&ue.Warn("Logarithmic depth has been requested for a material on a device that doesn't support it."),this._useLogarithmicDepth=e&&t,this._markAllSubMeshesAsMiscDirty()}_getDrawWrapper(){return this._drawWrapper}_setDrawWrapper(e){this._drawWrapper=e}constructor(e,t,s){this.shadowDepthWrapper=null,this.allowShaderHotSwapping=!0,this._shaderLanguage=0,this.metadata=null,this.reservedDataStore=null,this.checkReadyOnEveryCall=!1,this.checkReadyOnlyOnce=!1,this.state="",this._alpha=1,this._backFaceCulling=!0,this._cullBackFaces=!0,this._blockDirtyMechanism=!1,this.sideOrientation=null,this.onCompiled=null,this.onError=null,this.getRenderTargetTextures=null,this.doNotSerialize=!1,this._storeEffectOnSubMeshes=!1,this.animations=null,this.onDisposeObservable=new g,this._onDisposeObserver=null,this._onUnBindObservable=null,this._onBindObserver=null,this._alphaMode=Ze.ALPHA_COMBINE,this._needDepthPrePass=!1,this.disableDepthWrite=!1,this.disableColorWrite=!1,this.forceDepthWrite=!1,this.depthFunction=0,this.separateCullingPass=!1,this._fogEnabled=!0,this.pointSize=1,this.zOffset=0,this.zOffsetUnits=0,this.stencil=new Vs,this._useUBO=!1,this._fillMode=$s.TriangleFillMode,this._cachedDepthWriteState=!1,this._cachedColorWriteState=!1,this._cachedDepthFunctionState=0,this._indexInSceneMaterialArray=-1,this.meshMap=null,this._parentContainer=null,this._uniformBufferLayoutBuilt=!1,this._eventInfo={},this._callbackPluginEventGeneric=()=>{},this._callbackPluginEventIsReadyForSubMesh=()=>{},this._callbackPluginEventPrepareDefines=()=>{},this._callbackPluginEventPrepareDefinesBeforeAttributes=()=>{},this._callbackPluginEventHardBindForSubMesh=()=>{},this._callbackPluginEventBindForSubMesh=()=>{},this._callbackPluginEventHasRenderTargetTextures=()=>{},this._callbackPluginEventFillRenderTargetTextures=()=>{},this._forceAlphaTest=!1,this._transparencyMode=null,this.name=e;const i=t||C.LastCreatedScene;i&&(this._scene=i,this._dirtyCallbacks={},this._dirtyCallbacks[Ze.MATERIAL_TextureDirtyFlag]=this._markAllSubMeshesAsTexturesDirty.bind(this),this._dirtyCallbacks[Ze.MATERIAL_LightDirtyFlag]=this._markAllSubMeshesAsLightsDirty.bind(this),this._dirtyCallbacks[Ze.MATERIAL_FresnelDirtyFlag]=this._markAllSubMeshesAsFresnelDirty.bind(this),this._dirtyCallbacks[Ze.MATERIAL_AttributesDirtyFlag]=this._markAllSubMeshesAsAttributesDirty.bind(this),this._dirtyCallbacks[Ze.MATERIAL_MiscDirtyFlag]=this._markAllSubMeshesAsMiscDirty.bind(this),this._dirtyCallbacks[Ze.MATERIAL_PrePassDirtyFlag]=this._markAllSubMeshesAsPrePassDirty.bind(this),this._dirtyCallbacks[Ze.MATERIAL_AllDirtyFlag]=this._markAllSubMeshesAsAllDirty.bind(this),this.id=e||Yt.RandomId(),this.uniqueId=this._scene.getUniqueId(),this._materialContext=this._scene.getEngine().createMaterialContext(),this._drawWrapper=new ms(this._scene.getEngine(),!1),this._drawWrapper.materialContext=this._materialContext,this._uniformBuffer=new Ls(this._scene.getEngine(),void 0,void 0,e),this._useUBO=this.getScene().getEngine().supportsUniformBuffers,s||this._scene.addMaterial(this),this._scene.useMaterialMeshMap&&(this.meshMap={}),$s.OnEventObservable.notifyObservers(this,1))}toString(e){return"Name: "+this.name}getClassName(){return"Material"}get _isMaterial(){return!0}get isFrozen(){return this.checkReadyOnlyOnce}freeze(){this.markDirty(),this.checkReadyOnlyOnce=!0}unfreeze(){this.markDirty(),this.checkReadyOnlyOnce=!1}isReady(e,t){return!0}isReadyForSubMesh(e,t,s){const i=t.materialDefines;return!!i&&(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=i,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),this._eventInfo.isReadyForSubMesh)}getEffect(){return this._drawWrapper.effect}getScene(){return this._scene}_getEffectiveOrientation(e){return null!==this.sideOrientation?this.sideOrientation:e.sideOrientation}get transparencyMode(){return this._transparencyMode}set transparencyMode(e){this._transparencyMode!==e&&(this._transparencyMode=e,this._forceAlphaTest=e===$s.MATERIAL_ALPHATESTANDBLEND,this._markAllSubMeshesAsTexturesAndMiscDirty())}get _disableAlphaBlending(){return this._transparencyMode===$s.MATERIAL_OPAQUE||this._transparencyMode===$s.MATERIAL_ALPHATEST}needAlphaBlending(){return!this._disableAlphaBlending&&this.alpha<1}needAlphaBlendingForMesh(e){return e.visibility<1||!this._disableAlphaBlending&&(e.hasVertexAlpha||this.needAlphaBlending())}needAlphaTesting(){return!!this._forceAlphaTest}_shouldTurnAlphaTestOn(e){return!this.needAlphaBlendingForMesh(e)&&this.needAlphaTesting()}getAlphaTestTexture(){return null}markDirty(e=!1){const t=this.getScene().meshes;for(const s of t)if(s.subMeshes)for(const t of s.subMeshes)if(t.getMaterial()===this)for(const s of t._drawWrappers)s&&this._materialContext===s.materialContext&&(s._wasPreviouslyReady=!1,s._wasPreviouslyUsingInstances=null,s._forceRebindOnNextCall=e);e&&this.markAsDirty($s.AllDirtyFlag)}_preBind(e,t=null){const s=this._scene.getEngine(),i=(null==t?this.sideOrientation:t)===$s.ClockWiseSideOrientation;return s.enableEffect(e||this._getDrawWrapper()),s.setState(this.backFaceCulling,this.zOffset,!1,i,this._scene._mirroredCameraPosition?!this.cullBackFaces:this.cullBackFaces,this.stencil,this.zOffsetUnits),i}bind(e,t){}buildUniformLayout(){const e=this._uniformBuffer;this._eventInfo.ubo=e,this._callbackPluginEventGeneric(8,this._eventInfo),e.create(),this._uniformBufferLayoutBuilt=!0}bindForSubMesh(e,t,s){const i=s._drawWrapper;this._eventInfo.subMesh=s,this._callbackPluginEventBindForSubMesh(this._eventInfo),i._forceRebindOnNextCall=!1}bindOnlyWorldMatrix(e){}bindView(e){this._useUBO?this._needToBindSceneUbo=!0:e.setMatrix("view",this.getScene().getViewMatrix())}bindViewProjection(e){this._useUBO?this._needToBindSceneUbo=!0:(e.setMatrix("viewProjection",this.getScene().getTransformMatrix()),e.setMatrix("projection",this.getScene().getProjectionMatrix()))}bindEyePosition(e,t){this._useUBO?this._needToBindSceneUbo=!0:this._scene.bindEyePosition(e,t)}_afterBind(e,t=null,s){if(this._scene._cachedMaterial=this,this._needToBindSceneUbo&&t&&(this._needToBindSceneUbo=!1,function(e,t){t.bindToEffect(e,"Scene")}(t,this.getScene().getSceneUniformBuffer()),this._scene.finalizeSceneUbo()),this._scene._cachedVisibility=e?e.visibility:1,this._onBindObservable&&e&&this._onBindObservable.notifyObservers(e),this.disableDepthWrite){const e=this._scene.getEngine();this._cachedDepthWriteState=e.getDepthWrite(),e.setDepthWrite(!1)}if(this.disableColorWrite){const e=this._scene.getEngine();this._cachedColorWriteState=e.getColorWrite(),e.setColorWrite(!1)}if(0!==this.depthFunction){const e=this._scene.getEngine();this._cachedDepthFunctionState=e.getDepthFunction()||0,e.setDepthFunction(this.depthFunction)}}unbind(){if(this._onUnBindObservable&&this._onUnBindObservable.notifyObservers(this),0!==this.depthFunction){this._scene.getEngine().setDepthFunction(this._cachedDepthFunctionState)}if(this.disableDepthWrite){this._scene.getEngine().setDepthWrite(this._cachedDepthWriteState)}if(this.disableColorWrite){this._scene.getEngine().setColorWrite(this._cachedColorWriteState)}}getAnimatables(){return this._eventInfo.animatables=[],this._callbackPluginEventGeneric(256,this._eventInfo),this._eventInfo.animatables}getActiveTextures(){return this._eventInfo.activeTextures=[],this._callbackPluginEventGeneric(512,this._eventInfo),this._eventInfo.activeTextures}hasTexture(e){return this._eventInfo.hasTexture=!1,this._eventInfo.texture=e,this._callbackPluginEventGeneric(1024,this._eventInfo),this._eventInfo.hasTexture}clone(e){return null}_clonePlugins(e,t){const s={};if(this._serializePlugins(s),$s._ParsePlugins(s,e,this._scene,t),this.pluginManager)for(const t of this.pluginManager._plugins){const s=e.pluginManager.getPlugin(t.name);s&&t.copyTo(s)}}getBindedMeshes(){if(this.meshMap){const e=[];for(const t in this.meshMap){const s=this.meshMap[t];s&&e.push(s)}return e}return this._scene.meshes.filter((e=>e.material===this))}forceCompilation(e,t,s,i){const r={clipPlane:!1,useInstances:!1,...s},n=this.getScene(),a=this.allowShaderHotSwapping;this.allowShaderHotSwapping=!1;const o=()=>{if(!this._scene||!this._scene.getEngine())return;const s=n.clipPlane;if(r.clipPlane&&(n.clipPlane=new es(0,0,0,1)),this._storeEffectOnSubMeshes){let s=!0,n=null;if(e.subMeshes){const t=new gs(0,0,0,0,0,e,void 0,!1,!1);t.materialDefines&&(t.materialDefines._renderId=-1),this.isReadyForSubMesh(e,t,r.useInstances)||(t.effect&&t.effect.getCompilationError()&&t.effect.allFallbacksProcessed()?n=t.effect.getCompilationError():(s=!1,setTimeout(o,16)))}s&&(this.allowShaderHotSwapping=a,n&&i&&i(n),t&&t(this))}else this.isReady()?(this.allowShaderHotSwapping=a,t&&t(this)):setTimeout(o,16);r.clipPlane&&(n.clipPlane=s)};o()}forceCompilationAsync(e,t){return new Promise(((s,i)=>{this.forceCompilation(e,(()=>{s()}),t,(e=>{i(e)}))}))}markAsDirty(e){this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism||($s._DirtyCallbackArray.length=0,e&$s.TextureDirtyFlag&&$s._DirtyCallbackArray.push($s._TextureDirtyCallBack),e&$s.LightDirtyFlag&&$s._DirtyCallbackArray.push($s._LightsDirtyCallBack),e&$s.FresnelDirtyFlag&&$s._DirtyCallbackArray.push($s._FresnelDirtyCallBack),e&$s.AttributesDirtyFlag&&$s._DirtyCallbackArray.push($s._AttributeDirtyCallBack),e&$s.MiscDirtyFlag&&$s._DirtyCallbackArray.push($s._MiscDirtyCallBack),e&$s.PrePassDirtyFlag&&$s._DirtyCallbackArray.push($s._PrePassDirtyCallBack),$s._DirtyCallbackArray.length&&this._markAllSubMeshesAsDirty($s._RunDirtyCallBacks),this.getScene().resetCachedMaterial())}resetDrawCache(){const e=this.getScene().meshes;for(const t of e)if(t.subMeshes)for(const e of t.subMeshes)e.getMaterial()===this&&e.resetDrawCache()}_markAllSubMeshesAsDirty(e){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const t=this.getScene().meshes;for(const s of t)if(s.subMeshes)for(const t of s.subMeshes)if(t.getMaterial(!1)===this)for(const s of t._drawWrappers)s&&s.defines&&s.defines.markAllAsDirty&&this._materialContext===s.materialContext&&e(s.defines)}_markScenePrePassDirty(){if(this.getScene().blockMaterialDirtyMechanism||this._blockDirtyMechanism)return;const e=this.getScene().enablePrePassRenderer();e&&e.markAsDirty()}_markAllSubMeshesAsAllDirty(){this._markAllSubMeshesAsDirty($s._AllDirtyCallBack)}_markAllSubMeshesAsImageProcessingDirty(){this._markAllSubMeshesAsDirty($s._ImageProcessingDirtyCallBack)}_markAllSubMeshesAsTexturesDirty(){this._markAllSubMeshesAsDirty($s._TextureDirtyCallBack)}_markAllSubMeshesAsFresnelDirty(){this._markAllSubMeshesAsDirty($s._FresnelDirtyCallBack)}_markAllSubMeshesAsFresnelAndMiscDirty(){this._markAllSubMeshesAsDirty($s._FresnelAndMiscDirtyCallBack)}_markAllSubMeshesAsLightsDirty(){this._markAllSubMeshesAsDirty($s._LightsDirtyCallBack)}_markAllSubMeshesAsAttributesDirty(){this._markAllSubMeshesAsDirty($s._AttributeDirtyCallBack)}_markAllSubMeshesAsMiscDirty(){this._markAllSubMeshesAsDirty($s._MiscDirtyCallBack)}_markAllSubMeshesAsPrePassDirty(){this._markAllSubMeshesAsDirty($s._MiscDirtyCallBack)}_markAllSubMeshesAsTexturesAndMiscDirty(){this._markAllSubMeshesAsDirty($s._TextureAndMiscDirtyCallBack)}_checkScenePerformancePriority(){if(0!==this._scene.performancePriority){this.checkReadyOnlyOnce=!0;const e=this._scene.onScenePerformancePriorityChangedObservable.addOnce((()=>{this.checkReadyOnlyOnce=!1}));this.onDisposeObservable.add((()=>{this._scene.onScenePerformancePriorityChangedObservable.remove(e)}))}}setPrePassRenderer(e){return!1}dispose(e,t,s){const i=this.getScene();if(i.stopAnimation(this),i.freeProcessedMaterials(),i.removeMaterial(this),this._eventInfo.forceDisposeTextures=t,this._callbackPluginEventGeneric(2,this._eventInfo),this._parentContainer){const e=this._parentContainer.materials.indexOf(this);e>-1&&this._parentContainer.materials.splice(e,1),this._parentContainer=null}if(!0!==s)if(this.meshMap)for(const t in this.meshMap){const s=this.meshMap[t];s&&(s.material=null,this.releaseVertexArrayObject(s,e))}else{const t=i.meshes;for(const s of t)s.material!==this||s.sourceMesh||(s.material=null,this.releaseVertexArrayObject(s,e))}this._uniformBuffer.dispose(),e&&this._drawWrapper.effect&&(this._storeEffectOnSubMeshes||this._drawWrapper.effect.dispose(),this._drawWrapper.effect=null),this.metadata=null,this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this._onBindObservable&&this._onBindObservable.clear(),this._onUnBindObservable&&this._onUnBindObservable.clear(),this._onEffectCreatedObservable&&this._onEffectCreatedObservable.clear(),this._eventInfo&&(this._eventInfo={})}releaseVertexArrayObject(e,t){const s=e.geometry;if(s)if(this._storeEffectOnSubMeshes){if(e.subMeshes)for(const i of e.subMeshes)s._releaseVertexArrayObject(i.effect),t&&i.effect&&i.effect.dispose()}else s._releaseVertexArrayObject(this._drawWrapper.effect)}serialize(){const e=re.Serialize(this);return e.stencil=this.stencil.serialize(),e.uniqueId=this.uniqueId,this._serializePlugins(e),e}_serializePlugins(e){if(e.plugins={},this.pluginManager)for(const t of this.pluginManager._plugins)e.plugins[t.getClassName()]=t.serialize()}static Parse(e,t,s){if(e.customType){if("BABYLON.PBRMaterial"===e.customType&&e.overloadedAlbedo&&(e.customType="BABYLON.LegacyPBRMaterial",!BABYLON.LegacyPBRMaterial))return ue.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library."),null}else e.customType="BABYLON.StandardMaterial";const i=Yt.Instantiate(e.customType).Parse(e,t,s);return i._loadedUniqueId=e.uniqueId,i}static _ParsePlugins(e,t,s,i){if(e.plugins)for(const r in e.plugins){const n=e.plugins[r];let a=t.pluginManager?.getPlugin(n.name);if(!a){const e=Yt.Instantiate("BABYLON."+r);e&&(a=new e(t))}a?.parse(n,s,i)}}}$s.TriangleFillMode=Ze.MATERIAL_TriangleFillMode,$s.WireFrameFillMode=Ze.MATERIAL_WireFrameFillMode,$s.PointFillMode=Ze.MATERIAL_PointFillMode,$s.PointListDrawMode=Ze.MATERIAL_PointListDrawMode,$s.LineListDrawMode=Ze.MATERIAL_LineListDrawMode,$s.LineLoopDrawMode=Ze.MATERIAL_LineLoopDrawMode,$s.LineStripDrawMode=Ze.MATERIAL_LineStripDrawMode,$s.TriangleStripDrawMode=Ze.MATERIAL_TriangleStripDrawMode,$s.TriangleFanDrawMode=Ze.MATERIAL_TriangleFanDrawMode,$s.ClockWiseSideOrientation=Ze.MATERIAL_ClockWiseSideOrientation,$s.CounterClockWiseSideOrientation=Ze.MATERIAL_CounterClockWiseSideOrientation,$s.TextureDirtyFlag=Ze.MATERIAL_TextureDirtyFlag,$s.LightDirtyFlag=Ze.MATERIAL_LightDirtyFlag,$s.FresnelDirtyFlag=Ze.MATERIAL_FresnelDirtyFlag,$s.AttributesDirtyFlag=Ze.MATERIAL_AttributesDirtyFlag,$s.MiscDirtyFlag=Ze.MATERIAL_MiscDirtyFlag,$s.PrePassDirtyFlag=Ze.MATERIAL_PrePassDirtyFlag,$s.AllDirtyFlag=Ze.MATERIAL_AllDirtyFlag,$s.MATERIAL_OPAQUE=0,$s.MATERIAL_ALPHATEST=1,$s.MATERIAL_ALPHABLEND=2,$s.MATERIAL_ALPHATESTANDBLEND=3,$s.MATERIAL_NORMALBLENDMETHOD_WHITEOUT=0,$s.MATERIAL_NORMALBLENDMETHOD_RNM=1,$s.OnEventObservable=new g,$s._AllDirtyCallBack=e=>e.markAllAsDirty(),$s._ImageProcessingDirtyCallBack=e=>e.markAsImageProcessingDirty(),$s._TextureDirtyCallBack=e=>e.markAsTexturesDirty(),$s._FresnelDirtyCallBack=e=>e.markAsFresnelDirty(),$s._MiscDirtyCallBack=e=>e.markAsMiscDirty(),$s._PrePassDirtyCallBack=e=>e.markAsPrePassDirty(),$s._LightsDirtyCallBack=e=>e.markAsLightDirty(),$s._AttributeDirtyCallBack=e=>e.markAsAttributesDirty(),$s._FresnelAndMiscDirtyCallBack=e=>{$s._FresnelDirtyCallBack(e),$s._MiscDirtyCallBack(e)},$s._TextureAndMiscDirtyCallBack=e=>{$s._TextureDirtyCallBack(e),$s._MiscDirtyCallBack(e)},$s._DirtyCallbackArray=[],$s._RunDirtyCallBacks=e=>{for(const t of $s._DirtyCallbackArray)t(e)},e([a()],$s.prototype,"id",void 0),e([a()],$s.prototype,"uniqueId",void 0),e([a()],$s.prototype,"name",void 0),e([a()],$s.prototype,"metadata",void 0),e([a()],$s.prototype,"checkReadyOnEveryCall",void 0),e([a()],$s.prototype,"checkReadyOnlyOnce",void 0),e([a()],$s.prototype,"state",void 0),e([a("alpha")],$s.prototype,"_alpha",void 0),e([a("backFaceCulling")],$s.prototype,"_backFaceCulling",void 0),e([a("cullBackFaces")],$s.prototype,"_cullBackFaces",void 0),e([a()],$s.prototype,"sideOrientation",void 0),e([a("alphaMode")],$s.prototype,"_alphaMode",void 0),e([a()],$s.prototype,"_needDepthPrePass",void 0),e([a()],$s.prototype,"disableDepthWrite",void 0),e([a()],$s.prototype,"disableColorWrite",void 0),e([a()],$s.prototype,"forceDepthWrite",void 0),e([a()],$s.prototype,"depthFunction",void 0),e([a()],$s.prototype,"separateCullingPass",void 0),e([a("fogEnabled")],$s.prototype,"_fogEnabled",void 0),e([a()],$s.prototype,"pointSize",void 0),e([a()],$s.prototype,"zOffset",void 0),e([a()],$s.prototype,"zOffsetUnits",void 0),e([a()],$s.prototype,"pointsCloud",null),e([a()],$s.prototype,"fillMode",null),e([a()],$s.prototype,"useLogarithmicDepth",null),e([a()],$s.prototype,"transparencyMode",null);class Js extends $s{get subMaterials(){return this._subMaterials}set subMaterials(e){this._subMaterials=e,this._hookArray(e)}getChildren(){return this.subMaterials}constructor(e,t){super(e,t,!0),this._waitingSubMaterialsUniqueIds=[],this.getScene().addMultiMaterial(this),this.subMaterials=[],this._storeEffectOnSubMeshes=!0}_hookArray(e){const t=e.push;e.push=(...s)=>{const i=t.apply(e,s);return this._markAllSubMeshesAsTexturesDirty(),i};const s=e.splice;e.splice=(t,i)=>{const r=s.apply(e,[t,i]);return this._markAllSubMeshesAsTexturesDirty(),r}}getSubMaterial(e){return e<0||e>=this.subMaterials.length?this.getScene().defaultMaterial:this.subMaterials[e]}getActiveTextures(){return super.getActiveTextures().concat(...this.subMaterials.map((e=>e?e.getActiveTextures():[])))}hasTexture(e){if(super.hasTexture(e))return!0;for(let t=0;t<this.subMaterials.length;t++)if(this.subMaterials[t]?.hasTexture(e))return!0;return!1}getClassName(){return"MultiMaterial"}isReadyForSubMesh(e,t,s){for(let i=0;i<this.subMaterials.length;i++){const r=this.subMaterials[i];if(r){if(r._storeEffectOnSubMeshes){if(!r.isReadyForSubMesh(e,t,s))return!1;continue}if(!r.isReady(e))return!1}}return!0}clone(e,t){const s=new Js(e,this.getScene());for(let i=0;i<this.subMaterials.length;i++){let r=null;const n=this.subMaterials[i];r=t&&n?n.clone(e+"-"+n.name):this.subMaterials[i],s.subMaterials.push(r)}return s}serialize(){const e={};e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,q&&(e.tags=q.GetTags(this)),e.materialsUniqueIds=[],e.materials=[];for(let t=0;t<this.subMaterials.length;t++){const s=this.subMaterials[t];s?(e.materialsUniqueIds.push(s.uniqueId),e.materials.push(s.id)):(e.materialsUniqueIds.push(null),e.materials.push(null))}return e}dispose(e,t,s){const i=this.getScene();if(!i)return;if(s)for(let s=0;s<this.subMaterials.length;s++){const i=this.subMaterials[s];i&&i.dispose(e,t)}const r=i.multiMaterials.indexOf(this);r>=0&&i.multiMaterials.splice(r,1),super.dispose(e,t)}static ParseMultiMaterial(e,t){const s=new Js(e.name,t);return s.id=e.id,s._loadedUniqueId=e.uniqueId,q&&q.AddTagsTo(s,e.tags),e.materialsUniqueIds?s._waitingSubMaterialsUniqueIds=e.materialsUniqueIds:e.materials.forEach((e=>s.subMaterials.push(t.getLastMaterialById(e)))),s}}I("BABYLON.MultiMaterial",Js);class ei{}ei.NAME_EFFECTLAYER="EffectLayer",ei.NAME_LAYER="Layer",ei.NAME_LENSFLARESYSTEM="LensFlareSystem",ei.NAME_BOUNDINGBOXRENDERER="BoundingBoxRenderer",ei.NAME_PARTICLESYSTEM="ParticleSystem",ei.NAME_GAMEPAD="Gamepad",ei.NAME_SIMPLIFICATIONQUEUE="SimplificationQueue",ei.NAME_GEOMETRYBUFFERRENDERER="GeometryBufferRenderer",ei.NAME_PREPASSRENDERER="PrePassRenderer",ei.NAME_DEPTHRENDERER="DepthRenderer",ei.NAME_DEPTHPEELINGRENDERER="DepthPeelingRenderer",ei.NAME_IBLSHADOWSRENDERER="IblShadowsRenderer",ei.NAME_POSTPROCESSRENDERPIPELINEMANAGER="PostProcessRenderPipelineManager",ei.NAME_SPRITE="Sprite",ei.NAME_SUBSURFACE="SubSurface",ei.NAME_OUTLINERENDERER="Outline",ei.NAME_PROCEDURALTEXTURE="ProceduralTexture",ei.NAME_SHADOWGENERATOR="ShadowGenerator",ei.NAME_OCTREE="Octree",ei.NAME_PHYSICSENGINE="PhysicsEngine",ei.NAME_AUDIO="Audio",ei.NAME_FLUIDRENDERER="FluidRenderer",ei.STEP_ISREADYFORMESH_EFFECTLAYER=0,ei.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER=0,ei.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER=0,ei.STEP_PREACTIVEMESH_BOUNDINGBOXRENDERER=0,ei.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER=1,ei.STEP_BEFORECAMERADRAW_PREPASS=0,ei.STEP_BEFORECAMERADRAW_EFFECTLAYER=1,ei.STEP_BEFORECAMERADRAW_LAYER=2,ei.STEP_BEFORERENDERTARGETDRAW_PREPASS=0,ei.STEP_BEFORERENDERTARGETDRAW_LAYER=1,ei.STEP_BEFORERENDERINGMESH_PREPASS=0,ei.STEP_BEFORERENDERINGMESH_OUTLINE=1,ei.STEP_AFTERRENDERINGMESH_PREPASS=0,ei.STEP_AFTERRENDERINGMESH_OUTLINE=1,ei.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW=0,ei.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER=1,ei.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE=0,ei.STEP_BEFORECAMERAUPDATE_GAMEPAD=1,ei.STEP_BEFORECLEAR_PROCEDURALTEXTURE=0,ei.STEP_BEFORECLEAR_PREPASS=1,ei.STEP_BEFORERENDERTARGETCLEAR_PREPASS=0,ei.STEP_AFTERRENDERTARGETDRAW_PREPASS=0,ei.STEP_AFTERRENDERTARGETDRAW_LAYER=1,ei.STEP_AFTERCAMERADRAW_PREPASS=0,ei.STEP_AFTERCAMERADRAW_EFFECTLAYER=1,ei.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM=2,ei.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW=3,ei.STEP_AFTERCAMERADRAW_LAYER=4,ei.STEP_AFTERCAMERADRAW_FLUIDRENDERER=5,ei.STEP_AFTERCAMERAPOSTPROCESS_LAYER=0,ei.STEP_AFTERRENDERTARGETPOSTPROCESS_LAYER=0,ei.STEP_AFTERRENDER_AUDIO=0,ei.STEP_GATHERRENDERTARGETS_DEPTHRENDERER=0,ei.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER=1,ei.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR=2,ei.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER=3,ei.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER=0,ei.STEP_GATHERACTIVECAMERARENDERTARGETS_FLUIDRENDERER=1,ei.STEP_POINTERMOVE_SPRITE=0,ei.STEP_POINTERDOWN_SPRITE=0,ei.STEP_POINTERUP_SPRITE=0;class ti extends Array{constructor(e){super(...e)}static Create(){return Object.create(ti.prototype)}registerStep(e,t,s){let i=0,r=Number.MAX_VALUE;for(;i<this.length;i++){if(r=this[i].index,e<r)break}this.splice(i,0,{index:e,component:t,action:s.bind(t)})}clear(){this.length=0}}class si{constructor(e,t){this.distanceOrScreenCoverage=e,this.mesh=t}}class ii{constructor(){this.visibleInstances={},this.batchCache=new ri,this.batchCacheReplacementModeInFrozenMode=new ri,this.instancesBufferSize=2048}}class ri{constructor(){this.mustReturn=!1,this.visibleInstances=new Array,this.renderSelf=[],this.hardwareInstancedRendering=[]}}class ni{constructor(){this.instancesCount=0,this.matrixBuffer=null,this.previousMatrixBuffer=null,this.matrixBufferSize=512,this.matrixData=null,this.boundingVectors=[],this.worldMatrices=null}}class ai{constructor(){this._areNormalsFrozen=!1,this._source=null,this.meshMap=null,this._preActivateId=-1,this._LODLevels=new Array,this._useLODScreenCoverage=!1,this._effectiveMaterial=null,this._forcedInstanceCount=0,this._overrideRenderingFillMode=null}}class oi extends Gs{static _GetDefaultSideOrientation(e){return e||oi.FRONTSIDE}get useLODScreenCoverage(){return this._internalMeshDataInfo._useLODScreenCoverage}set useLODScreenCoverage(e){this._internalMeshDataInfo._useLODScreenCoverage=e,this._sortLODLevels()}get computeBonesUsingShaders(){return this._internalAbstractMeshDataInfo._computeBonesUsingShaders}set computeBonesUsingShaders(e){this._internalAbstractMeshDataInfo._computeBonesUsingShaders!==e&&(e&&this._internalMeshDataInfo._sourcePositions&&(this.setVerticesData(ns.PositionKind,this._internalMeshDataInfo._sourcePositions,!0),this._internalMeshDataInfo._sourceNormals&&this.setVerticesData(ns.NormalKind,this._internalMeshDataInfo._sourceNormals,!0),this._internalMeshDataInfo._sourcePositions=null,this._internalMeshDataInfo._sourceNormals=null),this._internalAbstractMeshDataInfo._computeBonesUsingShaders=e,this._markSubMeshesAsAttributesDirty())}get onBeforeRenderObservable(){return this._internalMeshDataInfo._onBeforeRenderObservable||(this._internalMeshDataInfo._onBeforeRenderObservable=new g),this._internalMeshDataInfo._onBeforeRenderObservable}get onBeforeBindObservable(){return this._internalMeshDataInfo._onBeforeBindObservable||(this._internalMeshDataInfo._onBeforeBindObservable=new g),this._internalMeshDataInfo._onBeforeBindObservable}get onAfterRenderObservable(){return this._internalMeshDataInfo._onAfterRenderObservable||(this._internalMeshDataInfo._onAfterRenderObservable=new g),this._internalMeshDataInfo._onAfterRenderObservable}get onBetweenPassObservable(){return this._internalMeshDataInfo._onBetweenPassObservable||(this._internalMeshDataInfo._onBetweenPassObservable=new g),this._internalMeshDataInfo._onBetweenPassObservable}get onBeforeDrawObservable(){return this._internalMeshDataInfo._onBeforeDrawObservable||(this._internalMeshDataInfo._onBeforeDrawObservable=new g),this._internalMeshDataInfo._onBeforeDrawObservable}set onBeforeDraw(e){this._onBeforeDrawObserver&&this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver),this._onBeforeDrawObserver=this.onBeforeDrawObservable.add(e)}get hasInstances(){return this.instances.length>0}get hasThinInstances(){return(this.forcedInstanceCount||this._thinInstanceDataStorage.instancesCount||0)>0}get forcedInstanceCount(){return this._internalMeshDataInfo._forcedInstanceCount}set forcedInstanceCount(e){this._internalMeshDataInfo._forcedInstanceCount=e}get sideOrientation(){return this._internalMeshDataInfo._sideOrientation}set sideOrientation(e){this._internalMeshDataInfo._sideOrientation=e,this._internalAbstractMeshDataInfo._sideOrientationHint=this._scene.useRightHandedSystem&&e===Ze.MATERIAL_CounterClockWiseSideOrientation||!this._scene.useRightHandedSystem&&e===Ze.MATERIAL_ClockWiseSideOrientation}get overrideMaterialSideOrientation(){return this.sideOrientation}set overrideMaterialSideOrientation(e){this.sideOrientation=e,this.material&&(this.material.sideOrientation=null)}get overrideRenderingFillMode(){return this._internalMeshDataInfo._overrideRenderingFillMode}set overrideRenderingFillMode(e){this._internalMeshDataInfo._overrideRenderingFillMode=e}get material(){return this._internalAbstractMeshDataInfo._material}set material(e){e&&(this.material&&null===this.material.sideOrientation||this._internalAbstractMeshDataInfo._sideOrientationHint)&&(e.sideOrientation=null),this._setMaterial(e)}get source(){return this._internalMeshDataInfo._source}get cloneMeshMap(){return this._internalMeshDataInfo.meshMap}get isUnIndexed(){return this._unIndexed}set isUnIndexed(e){this._unIndexed!==e&&(this._unIndexed=e,this._markSubMeshesAsAttributesDirty())}get worldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesData}get previousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.instancesPreviousData}get manualUpdateOfWorldMatrixInstancedBuffer(){return this._instanceDataStorage.manualUpdate}set manualUpdateOfWorldMatrixInstancedBuffer(e){this._instanceDataStorage.manualUpdate=e}get manualUpdateOfPreviousWorldMatrixInstancedBuffer(){return this._instanceDataStorage.previousManualUpdate}set manualUpdateOfPreviousWorldMatrixInstancedBuffer(e){this._instanceDataStorage.previousManualUpdate=e}get forceWorldMatrixInstancedBufferUpdate(){return this._instanceDataStorage.forceMatrixUpdates}set forceWorldMatrixInstancedBufferUpdate(e){this._instanceDataStorage.forceMatrixUpdates=e}_copySource(e,t,s=!0){const i=this.getScene();if(e._geometry&&e._geometry.applyToMesh(this),_e.DeepCopy(e,this,["name","material","skeleton","instances","parent","uniqueId","source","metadata","morphTargetManager","hasInstances","worldMatrixInstancedBuffer","previousWorldMatrixInstancedBuffer","hasLODLevels","geometry","isBlocked","areNormalsFrozen","facetNb","isFacetDataEnabled","lightSources","useBones","isAnInstance","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","cloneMeshMap","hasBoundingInfo","physicsBody","physicsImpostor"],["_poseMatrix"]),this._internalMeshDataInfo._source=e,i.useClonedMeshMap&&(e._internalMeshDataInfo.meshMap||(e._internalMeshDataInfo.meshMap={}),e._internalMeshDataInfo.meshMap[this.uniqueId]=this),this._originalBuilderSideOrientation=e._originalBuilderSideOrientation,this._creationDataStorage=e._creationDataStorage,e._ranges){const t=e._ranges;for(const e in t)Object.prototype.hasOwnProperty.call(t,e)&&t[e]&&this.createAnimationRange(e,t[e].from,t[e].to)}if(e.metadata&&e.metadata.clone?this.metadata=e.metadata.clone():this.metadata=e.metadata,this._internalMetadata=e._internalMetadata,q&&q.HasTags(e)&&q.AddTagsTo(this,q.GetTags(e,!0)),this.setEnabled(e.isEnabled(!1)),this.parent=e.parent,this.setPivotMatrix(e.getPivotMatrix(),this._postMultiplyPivotMatrix),this.id=this.name+"."+e.id,this.material=e.material,!t){const t=e.getDescendants(!0);for(let e=0;e<t.length;e++){const s=t[e];s.clone&&s.clone(this.name+"."+s.name,this)}}if(e.morphTargetManager&&(this.morphTargetManager=e.morphTargetManager),i.getPhysicsEngine){const t=i.getPhysicsEngine();if(s&&t)if(1===t.getPluginVersion()){const s=t.getImpostorForPhysicsObject(e);s&&(this.physicsImpostor=s.clone(this))}else 2===t.getPluginVersion()&&e.physicsBody&&e.physicsBody.clone(this)}for(let t=0;t<i.particleSystems.length;t++){const s=i.particleSystems[t];s.emitter===e&&s.clone(s.name,this)}this.skeleton=e.skeleton,this.refreshBoundingInfo(!0,!0),this.computeWorldMatrix(!0)}constructor(e,t=null,s=null,i=null,r,n=!0){super(e,t),this._internalMeshDataInfo=new ai,this.delayLoadState=Ze.DELAYLOADSTATE_NONE,this.instances=[],this._creationDataStorage=null,this._geometry=null,this._instanceDataStorage=new ii,this._thinInstanceDataStorage=new ni,this._shouldGenerateFlatShading=!1,this._originalBuilderSideOrientation=oi.DEFAULTSIDE,this.ignoreCameraMaxZ=!1,t=this.getScene(),this._scene.useRightHandedSystem?this.sideOrientation=Ze.MATERIAL_ClockWiseSideOrientation:this.sideOrientation=Ze.MATERIAL_CounterClockWiseSideOrientation,this._onBeforeDraw=(e,t,s)=>{e&&s&&(this._uniformBuffer?this.transferToEffect(t):s.bindOnlyWorldMatrix(t))},i&&this._copySource(i,r,n),null!==s&&(this.parent=s),this._instanceDataStorage.hardwareInstancedRendering=this.getEngine().getCaps().instancedArrays,this._internalMeshDataInfo._onMeshReadyObserverAdded=e=>{e.unregisterOnNextCall=!0,this.isReady(!0)?this.onMeshReadyObservable.notifyObservers(this):this._internalMeshDataInfo._checkReadinessObserver||(this._internalMeshDataInfo._checkReadinessObserver=this._scene.onBeforeRenderObservable.add((()=>{this.isReady(!0)&&(this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),this._internalMeshDataInfo._checkReadinessObserver=null,this.onMeshReadyObservable.notifyObservers(this))})))},this.onMeshReadyObservable=new g(this._internalMeshDataInfo._onMeshReadyObserverAdded),i&&i.onClonedObservable.notifyObservers(this)}instantiateHierarchy(e=null,t,s){const i=0===this.getTotalVertices()||t&&t.doNotInstantiate&&(!0===t.doNotInstantiate||t.doNotInstantiate(this))?this.clone("Clone of "+(this.name||this.id),e||this.parent,!0):this.createInstance("instance of "+(this.name||this.id));i.parent=e||this.parent,i.position=this.position.clone(),i.scaling=this.scaling.clone(),this.rotationQuaternion?i.rotationQuaternion=this.rotationQuaternion.clone():i.rotation=this.rotation.clone(),s&&s(this,i);for(const e of this.getChildTransformNodes(!0))"InstancedMesh"===e.getClassName()&&"Mesh"===i.getClassName()&&e.sourceMesh===this?e.instantiateHierarchy(i,{doNotInstantiate:t&&t.doNotInstantiate||!1,newSourcedMesh:i},s):e.instantiateHierarchy(i,t,s);return i}getClassName(){return"Mesh"}get _isMesh(){return!0}toString(e){let t=super.toString(e);if(t+=", n vertices: "+this.getTotalVertices(),t+=", parent: "+(this._waitingParentId?this._waitingParentId:this.parent?this.parent.name:"NONE"),this.animations)for(let s=0;s<this.animations.length;s++)t+=", animation[0]: "+this.animations[s].toString(e);if(e)if(this._geometry){const e=this.getIndices(),s=this.getVerticesData(ns.PositionKind);s&&e&&(t+=", flat shading: "+(s.length/3===e.length?"YES":"NO"))}else t+=", flat shading: UNKNOWN";return t}_unBindEffect(){super._unBindEffect();for(const e of this.instances)e._unBindEffect()}get hasLODLevels(){return this._internalMeshDataInfo._LODLevels.length>0}getLODLevels(){return this._internalMeshDataInfo._LODLevels}_sortLODLevels(){const e=this._internalMeshDataInfo._useLODScreenCoverage?-1:1;this._internalMeshDataInfo._LODLevels.sort(((t,s)=>t.distanceOrScreenCoverage<s.distanceOrScreenCoverage?e:t.distanceOrScreenCoverage>s.distanceOrScreenCoverage?-e:0))}addLODLevel(e,t){if(t&&t._masterMesh)return ue.Warn("You cannot use a mesh as LOD level twice"),this;const s=new si(e,t);return this._internalMeshDataInfo._LODLevels.push(s),t&&(t._masterMesh=this),this._sortLODLevels(),this}getLODLevelAtDistance(e){const t=this._internalMeshDataInfo;for(let s=0;s<t._LODLevels.length;s++){const i=t._LODLevels[s];if(i.distanceOrScreenCoverage===e)return i.mesh}return null}removeLODLevel(e){const t=this._internalMeshDataInfo;for(let s=0;s<t._LODLevels.length;s++)t._LODLevels[s].mesh===e&&(t._LODLevels.splice(s,1),e&&(e._masterMesh=null));return this._sortLODLevels(),this}getLOD(e,t){const s=this._internalMeshDataInfo;if(!s._LODLevels||0===s._LODLevels.length)return this;const i=t||this.getBoundingInfo().boundingSphere,r=e.mode===ss.ORTHOGRAPHIC_CAMERA?e.minZ:i.centerWorld.subtract(e.globalPosition).length();let n=r,a=1;if(s._useLODScreenCoverage){const t=e.screenArea;let s=i.radiusWorld*e.minZ/r;s=s*s*Math.PI,n=s/t,a=-1}if(a*s._LODLevels[s._LODLevels.length-1].distanceOrScreenCoverage>a*n)return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this;for(let e=0;e<s._LODLevels.length;e++){const t=s._LODLevels[e];if(a*t.distanceOrScreenCoverage<a*n){if(t.mesh){if(t.mesh.delayLoadState===Ze.DELAYLOADSTATE_NOTLOADED)return t.mesh._checkDelayState(),this;if(t.mesh.delayLoadState===Ze.DELAYLOADSTATE_LOADING)return this;t.mesh._preActivate(),t.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache)}return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,t.mesh),t.mesh}}return this.onLODLevelSelection&&this.onLODLevelSelection(n,this,this),this}get geometry(){return this._geometry}getTotalVertices(){return null===this._geometry||void 0===this._geometry?0:this._geometry.getTotalVertices()}getVerticesData(e,t,s,i){if(!this._geometry)return null;let r=i?void 0:this._userInstancedBuffersStorage?.vertexBuffers[e]?.getFloatData(this.instances.length+1,s||t&&1!==this._geometry.meshes.length);return r||(r=this._geometry.getVerticesData(e,t,s)),r}copyVerticesData(e,t){this._geometry&&this._geometry.copyVerticesData(e,t)}getVertexBuffer(e,t){return this._geometry?(t?void 0:this._userInstancedBuffersStorage?.vertexBuffers[e])??this._geometry.getVertexBuffer(e):null}isVerticesDataPresent(e,t){return this._geometry?!t&&void 0!==this._userInstancedBuffersStorage?.vertexBuffers[e]||this._geometry.isVerticesDataPresent(e):!!this._delayInfo&&-1!==this._delayInfo.indexOf(e)}isVertexBufferUpdatable(e,t){if(!this._geometry)return!!this._delayInfo&&-1!==this._delayInfo.indexOf(e);if(!t){const t=this._userInstancedBuffersStorage?.vertexBuffers[e];if(t)return t.isUpdatable()}return this._geometry.isVertexBufferUpdatable(e)}getVerticesDataKinds(e){if(!this._geometry){const e=[];return this._delayInfo&&this._delayInfo.forEach((function(t){e.push(t)})),e}const t=this._geometry.getVerticesDataKinds();if(!e&&this._userInstancedBuffersStorage)for(const e in this._userInstancedBuffersStorage.vertexBuffers)-1===t.indexOf(e)&&t.push(e);return t}getTotalIndices(){return this._geometry?this._geometry.getTotalIndices():0}getIndices(e,t){return this._geometry?this._geometry.getIndices(e,t):[]}get isBlocked(){return null!==this._masterMesh&&void 0!==this._masterMesh}isReady(e=!1,t=!1){if(this.delayLoadState===Ze.DELAYLOADSTATE_LOADING)return!1;if(!super.isReady(e))return!1;if(!this.subMeshes||0===this.subMeshes.length)return!0;if(!e)return!0;const s=this.getEngine(),i=this.getScene(),r=t||s.getCaps().instancedArrays&&(this.instances.length>0||this.hasThinInstances);this.computeWorldMatrix();const n=this.material||i.defaultMaterial;if(n)if(n._storeEffectOnSubMeshes)for(const e of this.subMeshes){const t=e.getMaterial();if(t)if(t._storeEffectOnSubMeshes){if(!t.isReadyForSubMesh(this,e,r))return!1}else if(!t.isReady(this,r))return!1}else if(!n.isReady(this,r))return!1;const a=s.currentRenderPassId;for(const e of this.lightSources){const t=e.getShadowGenerators();if(!t)continue;const i=t.values();for(let e=i.next();!0!==e.done;e=i.next()){const t=e.value;if(t&&(!t.getShadowMap()?.renderList||t.getShadowMap()?.renderList&&-1!==t.getShadowMap()?.renderList?.indexOf(this))){const e=t.getShadowMap().renderPassIds??[s.currentRenderPassId];for(let i=0;i<e.length;++i){s.currentRenderPassId=e[i];for(const e of this.subMeshes)if(!t.isReady(e,r,e.getMaterial()?.needAlphaBlendingForMesh(this)??!1))return s.currentRenderPassId=a,!1}s.currentRenderPassId=a}}}for(const e of this._internalMeshDataInfo._LODLevels)if(e.mesh&&!e.mesh.isReady(r))return!1;return!0}get areNormalsFrozen(){return this._internalMeshDataInfo._areNormalsFrozen}freezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!0,this}unfreezeNormals(){return this._internalMeshDataInfo._areNormalsFrozen=!1,this}set overridenInstanceCount(e){this._instanceDataStorage.overridenInstanceCount=e}_preActivate(){const e=this._internalMeshDataInfo,t=this.getScene().getRenderId();return e._preActivateId===t||(e._preActivateId=t,this._instanceDataStorage.visibleInstances=null),this}_preActivateForIntermediateRendering(e){return this._instanceDataStorage.visibleInstances&&(this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId=e),this}_registerInstanceForRenderId(e,t){return this._instanceDataStorage.visibleInstances||(this._instanceDataStorage.visibleInstances={defaultRenderId:t,selfDefaultRenderId:this._renderId}),this._instanceDataStorage.visibleInstances[t]||(void 0!==this._instanceDataStorage.previousRenderId&&this._instanceDataStorage.isFrozen&&(this._instanceDataStorage.visibleInstances[this._instanceDataStorage.previousRenderId]=null),this._instanceDataStorage.previousRenderId=t,this._instanceDataStorage.visibleInstances[t]=new Array),this._instanceDataStorage.visibleInstances[t].push(e),this}_afterComputeWorldMatrix(){super._afterComputeWorldMatrix(),this.hasThinInstances&&(this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1))}_postActivate(){this.edgesShareWithInstances&&this.edgesRenderer&&this.edgesRenderer.isEnabled&&this._renderingGroup&&(this._renderingGroup._edgesRenderers.pushNoDuplicate(this.edgesRenderer),this.edgesRenderer.customInstances.push(this.getWorldMatrix()))}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let s;s="object"==typeof e?e:{applySkeleton:e,applyMorph:t};const i=this.geometry?this.geometry.boundingBias:null;return this._refreshBoundingInfo(this._getData(s,null,ns.PositionKind),i),this}_createGlobalSubMesh(e){const t=this.getTotalVertices();if(!t||!this.getIndices())return null;if(this.subMeshes&&this.subMeshes.length>0){const s=this.getIndices();if(!s)return null;const i=s.length;let r=!1;if(e)r=!0;else for(const e of this.subMeshes){if(e.indexStart+e.indexCount>i){r=!0;break}if(e.verticesStart+e.verticesCount>t){r=!0;break}}if(!r)return this.subMeshes[0]}return this.releaseSubMeshes(),new gs(0,0,t,0,this.getTotalIndices(),this)}subdivide(e){if(e<1)return;const t=this.getTotalIndices();let s=t/e|0,i=0;for(;s%3!=0;)s++;this.releaseSubMeshes();for(let r=0;r<e&&!(i>=t);r++)gs.CreateFromIndices(0,i,r===e-1?t-i:s,this,void 0,!1),i+=s;this.refreshBoundingInfo(),this.synchronizeInstances()}setVerticesData(e,t,s=!1,i){if(this._geometry)this._geometry.setVerticesData(e,t,s,i);else{const i=new Es;i.set(t,e);const r=this.getScene();new ys(ys.RandomId(),r,i,s,this)}return this}removeVerticesData(e){this._geometry&&this._geometry.removeVerticesData(e)}markVerticesDataAsUpdatable(e,t=!0){const s=this.getVertexBuffer(e);s&&s.isUpdatable()!==t&&this.setVerticesData(e,this.getVerticesData(e),t)}setVerticesBuffer(e,t=!0){return this._geometry||(this._geometry=ys.CreateGeometryForMesh(this)),this._geometry.setVerticesBuffer(e,null,t),this}updateVerticesData(e,t,s,i){return this._geometry?(i?(this.makeGeometryUnique(),this.updateVerticesData(e,t,s,!1)):this._geometry.updateVerticesData(e,t,s),this):this}updateMeshPositions(e,t=!0){const s=this.getVerticesData(ns.PositionKind);if(!s)return this;if(e(s),this.updateVerticesData(ns.PositionKind,s,!1,!1),t){const e=this.getIndices(),t=this.getVerticesData(ns.NormalKind);if(!t)return this;Es.ComputeNormals(s,e,t),this.updateVerticesData(ns.NormalKind,t,!1,!1)}return this}makeGeometryUnique(){if(!this._geometry)return this;if(1===this._geometry.meshes.length)return this;const e=this._geometry,t=this._geometry.copy(ys.RandomId());return e.releaseForMesh(this,!0),t.applyToMesh(this),this}setIndexBuffer(e,t,s){let i=this._geometry;i||(i=new ys(ys.RandomId(),this.getScene(),void 0,void 0,this)),i.setIndexBuffer(e,t,s)}setIndices(e,t=null,s=!1){if(this._geometry)this._geometry.setIndices(e,t,s);else{const t=new Es;t.indices=e;const i=this.getScene();new ys(ys.RandomId(),i,t,s,this)}return this}updateIndices(e,t,s=!1){return this._geometry?(this._geometry.updateIndices(e,t,s),this):this}toLeftHanded(){return this._geometry?(this._geometry.toLeftHanded(),this):this}_bind(e,t,s,i=!0){if(!this._geometry)return this;const r=this.getScene().getEngine();let n;if(this._unIndexed)n=null;else switch(this._getRenderingFillMode(s)){case $s.PointFillMode:n=null;break;case $s.WireFrameFillMode:n=e._getLinesIndexBuffer(this.getIndices(),r);break;default:case $s.TriangleFillMode:n=this._geometry.getIndexBuffer()}return this._bindDirect(t,n,i)}_bindDirect(e,t,s=!0){return this._geometry?(this.morphTargetManager&&this.morphTargetManager.isUsingTextureForTargets&&this.morphTargetManager._bind(e),s&&this._userInstancedBuffersStorage&&!this.hasThinInstances?this._geometry._bind(e,t,this._userInstancedBuffersStorage.vertexBuffers,this._userInstancedBuffersStorage.vertexArrayObjects):this._geometry._bind(e,t),this):this}_draw(e,t,s){if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;this._internalMeshDataInfo._onBeforeDrawObservable&&this._internalMeshDataInfo._onBeforeDrawObservable.notifyObservers(this);const i=this.getScene().getEngine();return this._unIndexed||t==$s.PointFillMode?i.drawArraysType(t,e.verticesStart,e.verticesCount,this.forcedInstanceCount||s):t==$s.WireFrameFillMode?i.drawElementsType(t,0,e._linesIndexCount,this.forcedInstanceCount||s):i.drawElementsType(t,e.indexStart,e.indexCount,this.forcedInstanceCount||s),this}registerBeforeRender(e){return this.onBeforeRenderObservable.add(e),this}unregisterBeforeRender(e){return this.onBeforeRenderObservable.removeCallback(e),this}registerAfterRender(e){return this.onAfterRenderObservable.add(e),this}unregisterAfterRender(e){return this.onAfterRenderObservable.removeCallback(e),this}_getInstancesRenderList(e,t=!1){if(this._instanceDataStorage.isFrozen){if(t)return this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.hardwareInstancedRendering[e]=!1,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode.renderSelf[e]=!0,this._instanceDataStorage.batchCacheReplacementModeInFrozenMode;if(this._instanceDataStorage.previousBatch)return this._instanceDataStorage.previousBatch}const s=this.getScene(),i=s._isInIntermediateRendering(),r=i?this._internalAbstractMeshDataInfo._onlyForInstancesIntermediate:this._internalAbstractMeshDataInfo._onlyForInstances,n=this._instanceDataStorage.batchCache;if(n.mustReturn=!1,n.renderSelf[e]=t||!r&&this.isEnabled()&&this.isVisible,n.visibleInstances[e]=null,this._instanceDataStorage.visibleInstances&&!t){const t=this._instanceDataStorage.visibleInstances,r=s.getRenderId(),a=i?t.intermediateDefaultRenderId:t.defaultRenderId;n.visibleInstances[e]=t[r],!n.visibleInstances[e]&&a&&(n.visibleInstances[e]=t[a])}return n.hardwareInstancedRendering[e]=!t&&this._instanceDataStorage.hardwareInstancedRendering&&null!==n.visibleInstances[e]&&void 0!==n.visibleInstances[e],this._instanceDataStorage.previousBatch=n,n}_renderWithInstances(e,t,s,i,r){const n=s.visibleInstances[e._id],a=n?n.length:0,o=this._instanceDataStorage,h=o.instancesBufferSize;let l=o.instancesBuffer,c=o.instancesPreviousBuffer;const u=16*(a+1)*4;for(;o.instancesBufferSize<u;)o.instancesBufferSize*=2;o.instancesData&&h==o.instancesBufferSize||(o.instancesData=new Float32Array(o.instancesBufferSize/4)),(this._scene.needsPreviousWorldMatrices&&!o.instancesPreviousData||h!=o.instancesBufferSize)&&(o.instancesPreviousData=new Float32Array(o.instancesBufferSize/4));let d=0,_=0;const f=s.renderSelf[e._id],p=!l||h!==o.instancesBufferSize||this._scene.needsPreviousWorldMatrices&&!o.instancesPreviousBuffer;if(this._instanceDataStorage.manualUpdate||o.isFrozen&&!p)_=(f?1:0)+a;else{const t=this.getWorldMatrix();if(f&&(this._scene.needsPreviousWorldMatrices&&(o.masterMeshPreviousWorldMatrix?(o.masterMeshPreviousWorldMatrix.copyToArray(o.instancesPreviousData,d),o.masterMeshPreviousWorldMatrix.copyFrom(t)):(o.masterMeshPreviousWorldMatrix=t.clone(),o.masterMeshPreviousWorldMatrix.copyToArray(o.instancesPreviousData,d))),t.copyToArray(o.instancesData,d),d+=16,_++),n){if(oi.INSTANCEDMESH_SORT_TRANSPARENT&&this._scene.activeCamera&&e.getMaterial()?.needAlphaBlendingForMesh(e.getRenderingMesh())){const e=this._scene.activeCamera.globalPosition;for(let t=0;t<n.length;t++){const s=n[t];s._distanceToCamera=U.Distance(s.getBoundingInfo().boundingSphere.centerWorld,e)}n.sort(((e,t)=>e._distanceToCamera>t._distanceToCamera?-1:e._distanceToCamera<t._distanceToCamera?1:0))}for(let e=0;e<n.length;e++){const t=n[e],s=t.getWorldMatrix();s.copyToArray(o.instancesData,d),this._scene.needsPreviousWorldMatrices&&(t._previousWorldMatrix?(t._previousWorldMatrix.copyToArray(o.instancesPreviousData,d),t._previousWorldMatrix.copyFrom(s)):(t._previousWorldMatrix=s.clone(),t._previousWorldMatrix.copyToArray(o.instancesPreviousData,d))),d+=16,_++}}}return p?(l&&l.dispose(),c&&c.dispose(),l=new rs(r,o.instancesData,!0,16,!1,!0),o.instancesBuffer=l,this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this._userInstancedBuffersStorage.vertexBuffers.world0=l.createVertexBuffer("world0",0,4),this._userInstancedBuffersStorage.vertexBuffers.world1=l.createVertexBuffer("world1",4,4),this._userInstancedBuffersStorage.vertexBuffers.world2=l.createVertexBuffer("world2",8,4),this._userInstancedBuffersStorage.vertexBuffers.world3=l.createVertexBuffer("world3",12,4),this._scene.needsPreviousWorldMatrices&&(c=new rs(r,o.instancesPreviousData,!0,16,!1,!0),o.instancesPreviousBuffer=c,this._userInstancedBuffersStorage.vertexBuffers.previousWorld0=c.createVertexBuffer("previousWorld0",0,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld1=c.createVertexBuffer("previousWorld1",4,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld2=c.createVertexBuffer("previousWorld2",8,4),this._userInstancedBuffersStorage.vertexBuffers.previousWorld3=c.createVertexBuffer("previousWorld3",12,4)),this._invalidateInstanceVertexArrayObject()):this._instanceDataStorage.isFrozen&&!this._instanceDataStorage.forceMatrixUpdates||(l.updateDirectly(o.instancesData,0,_),!this._scene.needsPreviousWorldMatrices||this._instanceDataStorage.manualUpdate&&!this._instanceDataStorage.previousManualUpdate||c.updateDirectly(o.instancesPreviousData,0,_)),this._processInstancedBuffers(n,f),this.getScene()._activeIndices.addCount(e.indexCount*_,!1),r._currentDrawContext&&(r._currentDrawContext.useInstancing=!0),this._bind(e,i,t),this._draw(e,t,_),!this._scene.needsPreviousWorldMatrices||p||!this._instanceDataStorage.manualUpdate||this._instanceDataStorage.isFrozen&&!this._instanceDataStorage.forceMatrixUpdates||this._instanceDataStorage.previousManualUpdate||c.updateDirectly(o.instancesData,0,_),r.unbindInstanceAttributes(),this}_renderWithThinInstances(e,t,s,i){const r=this._thinInstanceDataStorage?.instancesCount??0;this.getScene()._activeIndices.addCount(e.indexCount*r,!1),i._currentDrawContext&&(i._currentDrawContext.useInstancing=!0),this._bind(e,s,t),this._draw(e,t,r),this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&this._thinInstanceDataStorage.matrixData&&(this._thinInstanceDataStorage.previousMatrixBuffer?this._thinInstanceDataStorage.previousMatrixBuffer.updateDirectly(this._thinInstanceDataStorage.matrixData,0,r):this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",this._thinInstanceDataStorage.matrixData,!1)),i.unbindInstanceAttributes()}_processInstancedBuffers(e,t){}_processRendering(e,t,s,i,r,n,a,o){const h=this.getScene(),l=h.getEngine();if(i=this._getRenderingFillMode(i),n&&t.getRenderingMesh().hasThinInstances)return this._renderWithThinInstances(t,i,s,l),this;if(n)this._renderWithInstances(t,i,r,s,l);else{l._currentDrawContext&&(l._currentDrawContext.useInstancing=!1);let s=0;r.renderSelf[t._id]&&(a&&a(!1,e.getWorldMatrix(),o),s++,this._draw(t,i,this._instanceDataStorage.overridenInstanceCount));const n=r.visibleInstances[t._id];if(n){const e=n.length;s+=e;for(let s=0;s<e;s++){const e=n[s].getWorldMatrix();a&&a(!0,e,o),this._draw(t,i)}}h._activeIndices.addCount(t.indexCount*s,!1)}return this}_rebuild(e=!1){if(this._instanceDataStorage.instancesBuffer&&(e&&this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null),this._userInstancedBuffersStorage){for(const t in this._userInstancedBuffersStorage.vertexBuffers){const s=this._userInstancedBuffersStorage.vertexBuffers[t];s&&(e&&s.dispose(),this._userInstancedBuffersStorage.vertexBuffers[t]=null)}this._userInstancedBuffersStorage.vertexArrayObjects&&(this._userInstancedBuffersStorage.vertexArrayObjects={})}this._internalMeshDataInfo._effectiveMaterial=null,super._rebuild(e)}_freeze(){if(this.subMeshes){for(let e=0;e<this.subMeshes.length;e++)this._getInstancesRenderList(e);this._internalMeshDataInfo._effectiveMaterial=null,this._instanceDataStorage.isFrozen=!0}}_unFreeze(){this._instanceDataStorage.isFrozen=!1,this._instanceDataStorage.previousBatch=null}renderWithRenderPassId(e,t,s,i,r=!0){const n=this._scene.getEngine(),a=n.currentRenderPassId;if(void 0!==e&&(n.currentRenderPassId=e),i)(!r||r&&i.isInFrustum(this._scene._frustumPlanes))&&this.render(i,!!t,s);else for(let e=0;e<this.subMeshes.length;e++){const i=this.subMeshes[e];(!r||r&&i.isInFrustum(this._scene._frustumPlanes))&&this.render(i,!!t,s)}return void 0!==e&&(n.currentRenderPassId=a),this}render(e,t,s){const i=this.getScene();this._internalAbstractMeshDataInfo._isActiveIntermediate?this._internalAbstractMeshDataInfo._isActiveIntermediate=!1:this._internalAbstractMeshDataInfo._isActive=!1;const r=i.activeCameras?.length??0;if((r>1&&i.activeCamera===i.activeCameras[0]||r<=1)&&this._checkOcclusionQuery()&&!this._occlusionDataStorage.forceRenderingWhenOccluded)return this;const n=this._getInstancesRenderList(e._id,!!s);if(n.mustReturn)return this;if(!this._geometry||!this._geometry.getVertexBuffers()||!this._unIndexed&&!this._geometry.getIndexBuffer())return this;const a=i.getEngine();let o=0,h=null;this.ignoreCameraMaxZ&&i.activeCamera&&!i._isInIntermediateRendering()&&(o=i.activeCamera.maxZ,h=i.activeCamera,i.activeCamera.maxZ=0,i.updateTransformMatrix(!0)),this._internalMeshDataInfo._onBeforeRenderObservable&&this._internalMeshDataInfo._onBeforeRenderObservable.notifyObservers(this);const l=e.getRenderingMesh(),c=n.hardwareInstancedRendering[e._id]||l.hasThinInstances||!!this._userInstancedBuffersStorage&&!e.getMesh()._internalAbstractMeshDataInfo._actAsRegularMesh,u=this._instanceDataStorage,d=e.getMaterial();if(!d)return h&&(h.maxZ=o,i.updateTransformMatrix(!0)),this;if(u.isFrozen&&this._internalMeshDataInfo._effectiveMaterial&&this._internalMeshDataInfo._effectiveMaterial===d){if(d._storeEffectOnSubMeshes&&!e._drawWrapper?._wasPreviouslyReady||!d._storeEffectOnSubMeshes&&!d._getDrawWrapper()._wasPreviouslyReady)return h&&(h.maxZ=o,i.updateTransformMatrix(!0)),this}else{if(d._storeEffectOnSubMeshes){if(!d.isReadyForSubMesh(this,e,c))return h&&(h.maxZ=o,i.updateTransformMatrix(!0)),this}else if(!d.isReady(this,c))return h&&(h.maxZ=o,i.updateTransformMatrix(!0)),this;this._internalMeshDataInfo._effectiveMaterial=d}let _;t&&a.setAlphaMode(this._internalMeshDataInfo._effectiveMaterial.alphaMode),_=this._internalMeshDataInfo._effectiveMaterial._storeEffectOnSubMeshes?e._drawWrapper:this._internalMeshDataInfo._effectiveMaterial._getDrawWrapper();const f=_?.effect??null;for(const t of i._beforeRenderingMeshStage)t.action(this,e,n,f);if(!_||!f)return h&&(h.maxZ=o,i.updateTransformMatrix(!0)),this;const p=s||this;let m;if(u.isFrozen||!this._internalMeshDataInfo._effectiveMaterial.backFaceCulling&&null===this._internalMeshDataInfo._effectiveMaterial.sideOrientation&&!this._internalMeshDataInfo._effectiveMaterial.twoSidedLighting)m=u.sideOrientation;else{const e=p._getWorldMatrixDeterminant();m=this._internalMeshDataInfo._effectiveMaterial._getEffectiveOrientation(this),e<0&&(m=m===$s.ClockWiseSideOrientation?$s.CounterClockWiseSideOrientation:$s.ClockWiseSideOrientation),u.sideOrientation=m}const g=this._internalMeshDataInfo._effectiveMaterial._preBind(_,m);this._internalMeshDataInfo._effectiveMaterial.forceDepthWrite&&a.setDepthWrite(!0);const T=this._internalMeshDataInfo._effectiveMaterial,E=T.fillMode;this._internalMeshDataInfo._onBeforeBindObservable&&this._internalMeshDataInfo._onBeforeBindObservable.notifyObservers(this),c||this._bind(e,f,E,!1);const A=p.getWorldMatrix();T._storeEffectOnSubMeshes?T.bindForSubMesh(A,this,e):T.bind(A,this),!T.backFaceCulling&&T.separateCullingPass&&(a.setState(!0,T.zOffset,!1,!g,T.cullBackFaces,T.stencil,T.zOffsetUnits),this._processRendering(this,e,f,E,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),a.setState(!0,T.zOffset,!1,g,T.cullBackFaces,T.stencil,T.zOffsetUnits),this._internalMeshDataInfo._onBetweenPassObservable&&this._internalMeshDataInfo._onBetweenPassObservable.notifyObservers(e)),this._processRendering(this,e,f,E,n,c,this._onBeforeDraw,this._internalMeshDataInfo._effectiveMaterial),this._internalMeshDataInfo._effectiveMaterial.unbind();for(const t of i._afterRenderingMeshStage)t.action(this,e,n,f);return this._internalMeshDataInfo._onAfterRenderObservable&&this._internalMeshDataInfo._onAfterRenderObservable.notifyObservers(this),h&&(h.maxZ=o,i.updateTransformMatrix(!0)),2!==i.performancePriority||u.isFrozen||this._freeze(),this}cleanMatrixWeights(){this.isVerticesDataPresent(ns.MatricesWeightsKind)&&(this.isVerticesDataPresent(ns.MatricesWeightsExtraKind)?this._normalizeSkinWeightsAndExtra():this._normalizeSkinFourWeights())}_normalizeSkinFourWeights(){const e=this.getVerticesData(ns.MatricesWeightsKind),t=e.length;for(let s=0;s<t;s+=4){const t=e[s]+e[s+1]+e[s+2]+e[s+3];if(0===t)e[s]=1;else{const i=1/t;e[s]*=i,e[s+1]*=i,e[s+2]*=i,e[s+3]*=i}}this.setVerticesData(ns.MatricesWeightsKind,e)}_normalizeSkinWeightsAndExtra(){const e=this.getVerticesData(ns.MatricesWeightsExtraKind),t=this.getVerticesData(ns.MatricesWeightsKind),s=t.length;for(let i=0;i<s;i+=4){let s=t[i]+t[i+1]+t[i+2]+t[i+3];if(s+=e[i]+e[i+1]+e[i+2]+e[i+3],0===s)t[i]=1;else{const r=1/s;t[i]*=r,t[i+1]*=r,t[i+2]*=r,t[i+3]*=r,e[i]*=r,e[i+1]*=r,e[i+2]*=r,e[i+3]*=r}}this.setVerticesData(ns.MatricesWeightsKind,t),this.setVerticesData(ns.MatricesWeightsKind,e)}validateSkinning(){const e=this.getVerticesData(ns.MatricesWeightsExtraKind),t=this.getVerticesData(ns.MatricesWeightsKind);if(null===t||null==this.skeleton)return{skinned:!1,valid:!0,report:"not skinned"};const s=t.length;let i=0,r=0,n=0,a=0;const o=null===e?4:8,h=[];for(let e=0;e<=o;e++)h[e]=0;for(let l=0;l<s;l+=4){let s=t[l],c=s,u=0===c?0:1;for(let r=1;r<o;r++){const n=r<4?t[l+r]:e[l+r-4];n>s&&i++,0!==n&&u++,c+=n,s=n}if(h[u]++,u>n&&(n=u),0===c)r++;else{const s=1/c;let i=0;for(let r=0;r<o;r++)i+=r<4?Math.abs(t[l+r]-t[l+r]*s):Math.abs(e[l+r-4]-e[l+r-4]*s);i>.001&&a++}}const l=this.skeleton.bones.length,c=this.getVerticesData(ns.MatricesIndicesKind),u=this.getVerticesData(ns.MatricesIndicesExtraKind);let d=0;for(let e=0;e<s;e+=4)for(let t=0;t<o;t++){const s=t<4?c[e+t]:u[e+t-4];(s>=l||s<0)&&d++}return{skinned:!0,valid:0===r&&0===a&&0===d,report:"Number of Weights = "+s/4+"\nMaximum influences = "+n+"\nMissing Weights = "+r+"\nNot Sorted = "+i+"\nNot Normalized = "+a+"\nWeightCounts = ["+h+"]\nNumber of bones = "+l+"\nBad Bone Indices = "+d}}_checkDelayState(){const e=this.getScene();return this._geometry?this._geometry.load(e):this.delayLoadState===Ze.DELAYLOADSTATE_NOTLOADED&&(this.delayLoadState=Ze.DELAYLOADSTATE_LOADING,this._queueLoad(e)),this}_queueLoad(e){e.addPendingData(this);const t=-1!==this.delayLoadingFile.indexOf(".babylonbinarymeshdata");return Yt.LoadFile(this.delayLoadingFile,(t=>{t instanceof ArrayBuffer?this._delayLoadingFunction(t,this):this._delayLoadingFunction(JSON.parse(t),this),this.instances.forEach((e=>{e.refreshBoundingInfo(),e._syncSubMeshes()})),this.delayLoadState=Ze.DELAYLOADSTATE_LOADED,e.removePendingData(this)}),(()=>{}),e.offlineProvider,t),this}isInFrustum(e){return this.delayLoadState!==Ze.DELAYLOADSTATE_LOADING&&(!!super.isInFrustum(e)&&(this._checkDelayState(),!0))}setMaterialById(e){const t=this.getScene().materials;let s;for(s=t.length-1;s>-1;s--)if(t[s].id===e)return this.material=t[s],this;const i=this.getScene().multiMaterials;for(s=i.length-1;s>-1;s--)if(i[s].id===e)return this.material=i[s],this;return this}getAnimatables(){const e=[];return this.material&&e.push(this.material),this.skeleton&&e.push(this.skeleton),e}bakeTransformIntoVertices(e){if(!this.isVerticesDataPresent(ns.PositionKind))return this;const t=this.subMeshes.splice(0);this._resetPointsArrayCache();let s=this.getVerticesData(ns.PositionKind);const i=U.Zero();let r;for(r=0;r<s.length;r+=3)U.TransformCoordinatesFromFloatsToRef(s[r],s[r+1],s[r+2],e,i).toArray(s,r);if(this.setVerticesData(ns.PositionKind,s,this.getVertexBuffer(ns.PositionKind).isUpdatable()),this.isVerticesDataPresent(ns.NormalKind)){for(s=this.getVerticesData(ns.NormalKind),r=0;r<s.length;r+=3)U.TransformNormalFromFloatsToRef(s[r],s[r+1],s[r+2],e,i).normalize().toArray(s,r);this.setVerticesData(ns.NormalKind,s,this.getVertexBuffer(ns.NormalKind).isUpdatable())}if(this.isVerticesDataPresent(ns.TangentKind)){for(s=this.getVerticesData(ns.TangentKind),r=0;r<s.length;r+=4)U.TransformNormalFromFloatsToRef(s[r],s[r+1],s[r+2],e,i).normalize().toArray(s,r);this.setVerticesData(ns.TangentKind,s,this.getVertexBuffer(ns.TangentKind).isUpdatable())}return e.determinant()<0&&this.flipFaces(),this.releaseSubMeshes(),this.subMeshes=t,this}bakeCurrentTransformIntoVertices(e=!0){return this.bakeTransformIntoVertices(this.computeWorldMatrix(!0)),this.resetLocalMatrix(e),this}get _positions(){return this._internalAbstractMeshDataInfo._positions||this._geometry&&this._geometry._positions||null}_resetPointsArrayCache(){return this._geometry&&this._geometry._resetPointsArrayCache(),this}_generatePointsArray(){return!!this._geometry&&this._geometry._generatePointsArray()}clone(e="",t=null,s,i=!0){return new oi(e,this.getScene(),t,this,s,i)}dispose(e,t=!1){this.morphTargetManager=null,this._geometry&&this._geometry.releaseForMesh(this,!0);const s=this._internalMeshDataInfo;if(s._onBeforeDrawObservable&&s._onBeforeDrawObservable.clear(),s._onBeforeBindObservable&&s._onBeforeBindObservable.clear(),s._onBeforeRenderObservable&&s._onBeforeRenderObservable.clear(),s._onAfterRenderObservable&&s._onAfterRenderObservable.clear(),s._onBetweenPassObservable&&s._onBetweenPassObservable.clear(),this._scene.useClonedMeshMap){if(s.meshMap)for(const e in s.meshMap){const t=s.meshMap[e];t&&(t._internalMeshDataInfo._source=null,s.meshMap[e]=void 0)}s._source&&s._source._internalMeshDataInfo.meshMap&&(s._source._internalMeshDataInfo.meshMap[this.uniqueId]=void 0)}else{const e=this.getScene().meshes;for(const t of e){const e=t;e._internalMeshDataInfo&&e._internalMeshDataInfo._source&&e._internalMeshDataInfo._source===this&&(e._internalMeshDataInfo._source=null)}}s._source=null,this._instanceDataStorage.visibleInstances={},this._disposeInstanceSpecificData(),this._disposeThinInstanceSpecificData(),this._internalMeshDataInfo._checkReadinessObserver&&this._scene.onBeforeRenderObservable.remove(this._internalMeshDataInfo._checkReadinessObserver),super.dispose(e,t)}_disposeInstanceSpecificData(){}_disposeThinInstanceSpecificData(){}_invalidateInstanceVertexArrayObject(){}applyDisplacementMap(e,t,s,i,r,n,a=!1,o){const h=this.getScene();return Yt.LoadImage(e,(e=>{const o=e.width,h=e.height,l=this.getEngine().createCanvas(o,h).getContext("2d");l.drawImage(e,0,0);const c=l.getImageData(0,0,o,h).data;this.applyDisplacementMapFromBuffer(c,o,h,t,s,r,n,a),i&&i(this)}),o||(()=>{}),h.offlineProvider),this}applyDisplacementMapFromBuffer(e,t,s,i,r,n,a,o=!1){if(!this.isVerticesDataPresent(ns.PositionKind)||!this.isVerticesDataPresent(ns.NormalKind)||!this.isVerticesDataPresent(ns.UVKind))return ue.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing"),this;const h=this.getVerticesData(ns.PositionKind,!0,!0),l=this.getVerticesData(ns.NormalKind),c=this.getVerticesData(ns.UVKind);let u=U.Zero();const d=U.Zero(),_=B.Zero();n=n||B.Zero(),a=a||new B(1,1);for(let o=0;o<h.length;o+=3){U.FromArrayToRef(h,o,u),U.FromArrayToRef(l,o,d),B.FromArrayToRef(c,o/3*2,_);const f=4*((Math.abs(_.x*a.x+n.x%1)*(t-1)%t|0)+(Math.abs(_.y*a.y+n.y%1)*(s-1)%s|0)*t),p=.3*(e[f]/255)+.59*(e[f+1]/255)+.11*(e[f+2]/255);d.normalize(),d.scaleInPlace(i+(r-i)*p),u=u.add(d),u.toArray(h,o)}return Es.ComputeNormals(h,this.getIndices(),l),o?(this.setVerticesData(ns.PositionKind,h),this.setVerticesData(ns.NormalKind,l),this.setVerticesData(ns.UVKind,c)):(this.updateVerticesData(ns.PositionKind,h),this.updateVerticesData(ns.NormalKind,l)),this}_getFlattenedNormals(e,t){const s=new Float32Array(3*e.length);let i=0;const r=this.sideOrientation===(this._scene.useRightHandedSystem?Ze.MATERIAL_CounterClockWiseSideOrientation:Ze.MATERIAL_ClockWiseSideOrientation);for(let n=0;n<e.length;n+=3){const a=U.FromArray(t,3*e[n]),o=U.FromArray(t,3*e[n+1]),h=U.FromArray(t,3*e[n+2]),l=a.subtract(o),c=h.subtract(o),u=U.Normalize(U.Cross(l,c));r&&u.scaleInPlace(-1);for(let e=0;e<3;e++)s[i++]=u.x,s[i++]=u.y,s[i++]=u.z}return s}_convertToUnIndexedMesh(e=!1){const t=this.getVerticesDataKinds().filter((e=>!this.getVertexBuffer(e)?.getIsInstanced())),s=this.getIndices(),i={},r=(e,t)=>{const i=new Float32Array(s.length*t);let r=0;for(let n=0;n<s.length;n++)for(let a=0;a<t;a++)i[r++]=e[s[n]*t+a];return i},n=this.getBoundingInfo(),a=this.geometry?this.subMeshes.slice(0):[];for(const e of t)i[e]=this.getVerticesData(e);for(const n of t){const t=this.getVertexBuffer(n),a=t.getSize();if(e&&n===ns.NormalKind){const e=this._getFlattenedNormals(s,i[ns.PositionKind]);this.setVerticesData(ns.NormalKind,e,t.isUpdatable(),a)}else this.setVerticesData(n,r(i[n],a),t.isUpdatable(),a)}if(this.morphTargetManager){for(let t=0;t<this.morphTargetManager.numTargets;t++){const i=this.morphTargetManager.getTarget(t),n=i.getPositions();i.setPositions(r(n,3));const a=i.getNormals();a&&i.setNormals(e?this._getFlattenedNormals(s,n):r(a,3));const o=i.getTangents();o&&i.setTangents(r(o,3));const h=i.getUVs();h&&i.setUVs(r(h,2))}this.morphTargetManager.synchronize()}for(let e=0;e<s.length;e++)s[e]=e;this.setIndices(s),this._unIndexed=!0,this.releaseSubMeshes();for(const e of a){const t=e.getBoundingInfo();gs.AddToMesh(e.materialIndex,e.indexStart,e.indexCount,e.indexStart,e.indexCount,this).setBoundingInfo(t)}return this.setBoundingInfo(n),this.synchronizeInstances(),this}convertToFlatShadedMesh(){return this._convertToUnIndexedMesh(!0)}convertToUnIndexedMesh(){return this._convertToUnIndexedMesh()}flipFaces(e=!1){const t=Es.ExtractFromMesh(this);let s;if(e&&this.isVerticesDataPresent(ns.NormalKind)&&t.normals)for(s=0;s<t.normals.length;s++)t.normals[s]*=-1;if(t.indices){let e;for(s=0;s<t.indices.length;s+=3)e=t.indices[s+1],t.indices[s+1]=t.indices[s+2],t.indices[s+2]=e}return t.applyToMesh(this,this.isVertexBufferUpdatable(ns.PositionKind)),this}increaseVertices(e=1){const t=Es.ExtractFromMesh(this),s=t.indices&&!Array.isArray(t.indices)&&Array.from?Array.from(t.indices):t.indices,i=t.positions&&!Array.isArray(t.positions)&&Array.from?Array.from(t.positions):t.positions,r=t.uvs&&!Array.isArray(t.uvs)&&Array.from?Array.from(t.uvs):t.uvs,n=t.normals&&!Array.isArray(t.normals)&&Array.from?Array.from(t.normals):t.normals;if(s&&i){t.indices=s,t.positions=i,r&&(t.uvs=r),n&&(t.normals=n);const a=e+1,o=new Array;for(let e=0;e<a+1;e++)o[e]=new Array;let h,l;const c=new U(0,0,0),u=new U(0,0,0),d=new B(0,0),_=new Array,f=new Array,p=new Array;let m,g,T,E=i.length;r&&(g=r.length),n&&(T=n.length);for(let e=0;e<s.length;e+=3){f[0]=s[e],f[1]=s[e+1],f[2]=s[e+2];for(let e=0;e<3;e++)if(h=f[e],l=f[(e+1)%3],void 0===p[h]&&void 0===p[l]?(p[h]=new Array,p[l]=new Array):(void 0===p[h]&&(p[h]=new Array),void 0===p[l]&&(p[l]=new Array)),void 0===p[h][l]&&void 0===p[l][h]){p[h][l]=[],c.x=(i[3*l]-i[3*h])/a,c.y=(i[3*l+1]-i[3*h+1])/a,c.z=(i[3*l+2]-i[3*h+2])/a,n&&(u.x=(n[3*l]-n[3*h])/a,u.y=(n[3*l+1]-n[3*h+1])/a,u.z=(n[3*l+2]-n[3*h+2])/a),r&&(d.x=(r[2*l]-r[2*h])/a,d.y=(r[2*l+1]-r[2*h+1])/a),p[h][l].push(h);for(let e=1;e<a;e++)p[h][l].push(i.length/3),i[E++]=i[3*h]+e*c.x,i[E++]=i[3*h+1]+e*c.y,i[E++]=i[3*h+2]+e*c.z,n&&(n[T++]=n[3*h]+e*u.x,n[T++]=n[3*h+1]+e*u.y,n[T++]=n[3*h+2]+e*u.z),r&&(r[g++]=r[2*h]+e*d.x,r[g++]=r[2*h+1]+e*d.y);p[h][l].push(l),p[l][h]=new Array,m=p[h][l].length;for(let e=0;e<m;e++)p[l][h][e]=p[h][l][m-1-e]}o[0][0]=s[e],o[1][0]=p[s[e]][s[e+1]][1],o[1][1]=p[s[e]][s[e+2]][1];for(let t=2;t<a;t++){o[t][0]=p[s[e]][s[e+1]][t],o[t][t]=p[s[e]][s[e+2]][t],c.x=(i[3*o[t][t]]-i[3*o[t][0]])/t,c.y=(i[3*o[t][t]+1]-i[3*o[t][0]+1])/t,c.z=(i[3*o[t][t]+2]-i[3*o[t][0]+2])/t,n&&(u.x=(n[3*o[t][t]]-n[3*o[t][0]])/t,u.y=(n[3*o[t][t]+1]-n[3*o[t][0]+1])/t,u.z=(n[3*o[t][t]+2]-n[3*o[t][0]+2])/t),r&&(d.x=(r[2*o[t][t]]-r[2*o[t][0]])/t,d.y=(r[2*o[t][t]+1]-r[2*o[t][0]+1])/t);for(let e=1;e<t;e++)o[t][e]=i.length/3,i[E++]=i[3*o[t][0]]+e*c.x,i[E++]=i[3*o[t][0]+1]+e*c.y,i[E++]=i[3*o[t][0]+2]+e*c.z,n&&(n[T++]=n[3*o[t][0]]+e*u.x,n[T++]=n[3*o[t][0]+1]+e*u.y,n[T++]=n[3*o[t][0]+2]+e*u.z),r&&(r[g++]=r[2*o[t][0]]+e*d.x,r[g++]=r[2*o[t][0]+1]+e*d.y)}o[a]=p[s[e+1]][s[e+2]],_.push(o[0][0],o[1][0],o[1][1]);for(let e=1;e<a;e++){let t;for(t=0;t<e;t++)_.push(o[e][t],o[e+1][t],o[e+1][t+1]),_.push(o[e][t],o[e+1][t+1],o[e][t+1]);_.push(o[e][t],o[e+1][t],o[e+1][t+1])}}t.indices=_,t.applyToMesh(this,this.isVertexBufferUpdatable(ns.PositionKind))}else ue.Warn("Couldn't increase number of vertices : VertexData must contain at least indices and positions")}forceSharedVertices(){const e=Es.ExtractFromMesh(this),t=e.uvs,s=e.indices,i=e.positions,r=e.colors,n=e.matricesIndices,a=e.matricesWeights,o=e.matricesIndicesExtra,h=e.matricesWeightsExtra;if(void 0===s||void 0===i||null===s||null===i)ue.Warn("VertexData contains empty entries");else{const l=new Array,c=new Array,u=new Array,d=new Array,_=new Array,f=new Array,p=new Array,m=new Array;let g=new Array,T=0;const E={};let A,y;for(let e=0;e<s.length;e+=3){y=[s[e],s[e+1],s[e+2]],g=[];for(let e=0;e<3;e++){g[e]="";for(let t=0;t<3;t++)Math.abs(i[3*y[e]+t])<1e-8&&(i[3*y[e]+t]=0),g[e]+=i[3*y[e]+t]+"|"}if(g[0]!=g[1]&&g[0]!=g[2]&&g[1]!=g[2])for(let e=0;e<3;e++){if(A=E[g[e]],void 0===A){E[g[e]]=T,A=T++;for(let t=0;t<3;t++)l.push(i[3*y[e]+t]);if(null!=r)for(let t=0;t<4;t++)d.push(r[4*y[e]+t]);if(null!=t)for(let s=0;s<2;s++)u.push(t[2*y[e]+s]);if(null!=n)for(let t=0;t<4;t++)_.push(n[4*y[e]+t]);if(null!=a)for(let t=0;t<4;t++)f.push(a[4*y[e]+t]);if(null!=o)for(let t=0;t<4;t++)p.push(o[4*y[e]+t]);if(null!=h)for(let t=0;t<4;t++)m.push(h[4*y[e]+t])}c.push(A)}}const b=new Array;Es.ComputeNormals(l,c,b),e.positions=l,e.indices=c,e.normals=b,null!=t&&(e.uvs=u),null!=r&&(e.colors=d),null!=n&&(e.matricesIndices=_),null!=a&&(e.matricesWeights=f),null!=o&&(e.matricesIndicesExtra=p),null!=a&&(e.matricesWeightsExtra=m),e.applyToMesh(this,this.isVertexBufferUpdatable(ns.PositionKind))}}static _instancedMeshFactory(e,t){throw Y("InstancedMesh")}static _PhysicsImpostorParser(e,t,s){throw Y("PhysicsImpostor")}createInstance(e){return oi._instancedMeshFactory(e,this)}synchronizeInstances(){for(let e=0;e<this.instances.length;e++){this.instances[e]._syncSubMeshes()}return this}optimizeIndices(e){const t=this.getIndices(),s=this.getVerticesData(ns.PositionKind);if(!s||!t)return this;const i=[];for(let e=0;e<s.length;e+=3)i.push(U.FromArray(s,e));const r=[];return Kt.SyncAsyncForLoop(i.length,40,(e=>{const t=i.length-1-e,s=i[t];for(let e=0;e<t;++e){const n=i[e];if(s.equals(n)){r[t]=e;break}}}),(()=>{for(let e=0;e<t.length;++e)t[e]=r[t[e]]||t[e];const s=this.subMeshes.slice(0);this.setIndices(t),this.subMeshes=s,e&&e(this)})),this}serialize(e={}){e.name=this.name,e.id=this.id,e.uniqueId=this.uniqueId,e.type=this.getClassName(),q&&q.HasTags(this)&&(e.tags=q.GetTags(this)),e.position=this.position.asArray(),this.rotationQuaternion?e.rotationQuaternion=this.rotationQuaternion.asArray():this.rotation&&(e.rotation=this.rotation.asArray()),e.scaling=this.scaling.asArray(),this._postMultiplyPivotMatrix?e.pivotMatrix=this.getPivotMatrix().asArray():e.localMatrix=this.getPivotMatrix().asArray(),e.isEnabled=this.isEnabled(!1),e.isVisible=this.isVisible,e.infiniteDistance=this.infiniteDistance,e.pickable=this.isPickable,e.receiveShadows=this.receiveShadows,e.billboardMode=this.billboardMode,e.visibility=this.visibility,e.alwaysSelectAsActiveMesh=this.alwaysSelectAsActiveMesh,e.checkCollisions=this.checkCollisions,e.ellipsoid=this.ellipsoid.asArray(),e.ellipsoidOffset=this.ellipsoidOffset.asArray(),e.doNotSyncBoundingInfo=this.doNotSyncBoundingInfo,e.isBlocker=this.isBlocker,e.sideOrientation=this.sideOrientation,this.parent&&this.parent._serializeAsParent(e),e.isUnIndexed=this.isUnIndexed;const t=this._geometry;if(t&&this.subMeshes){e.geometryUniqueId=t.uniqueId,e.geometryId=t.id,e.subMeshes=[];for(let t=0;t<this.subMeshes.length;t++){const s=this.subMeshes[t];e.subMeshes.push({materialIndex:s.materialIndex,verticesStart:s.verticesStart,verticesCount:s.verticesCount,indexStart:s.indexStart,indexCount:s.indexCount})}}if(this.material?this.material.doNotSerialize||(e.materialUniqueId=this.material.uniqueId,e.materialId=this.material.id):(this.material=null,e.materialUniqueId=this._scene.defaultMaterial.uniqueId,e.materialId=this._scene.defaultMaterial.id),this.morphTargetManager&&(e.morphTargetManagerId=this.morphTargetManager.uniqueId),this.skeleton&&(e.skeletonId=this.skeleton.id,e.numBoneInfluencers=this.numBoneInfluencers),this.getScene()._getComponent(ei.NAME_PHYSICSENGINE)){const t=this.getPhysicsImpostor();t&&(e.physicsMass=t.getParam("mass"),e.physicsFriction=t.getParam("friction"),e.physicsRestitution=t.getParam("mass"),e.physicsImpostor=t.type)}this.metadata&&(e.metadata=this.metadata),e.instances=[];for(let t=0;t<this.instances.length;t++){const s=this.instances[t];if(s.doNotSerialize)continue;const i={name:s.name,id:s.id,isEnabled:s.isEnabled(!1),isVisible:s.isVisible,isPickable:s.isPickable,checkCollisions:s.checkCollisions,position:s.position.asArray(),scaling:s.scaling.asArray()};if(s.parent&&s.parent._serializeAsParent(i),s.rotationQuaternion?i.rotationQuaternion=s.rotationQuaternion.asArray():s.rotation&&(i.rotation=s.rotation.asArray()),this.getScene()._getComponent(ei.NAME_PHYSICSENGINE)){const e=s.getPhysicsImpostor();e&&(i.physicsMass=e.getParam("mass"),i.physicsFriction=e.getParam("friction"),i.physicsRestitution=e.getParam("mass"),i.physicsImpostor=e.type)}s.metadata&&(i.metadata=s.metadata),s.actionManager&&(i.actions=s.actionManager.serialize(s.name)),e.instances.push(i),re.AppendSerializedAnimations(s,i),i.ranges=s.serializeAnimationRanges()}if(this._thinInstanceDataStorage.instancesCount&&this._thinInstanceDataStorage.matrixData&&(e.thinInstances={instancesCount:this._thinInstanceDataStorage.instancesCount,matrixData:Array.from(this._thinInstanceDataStorage.matrixData),matrixBufferSize:this._thinInstanceDataStorage.matrixBufferSize,enablePicking:this.thinInstanceEnablePicking},this._userThinInstanceBuffersStorage)){const t={data:{},sizes:{},strides:{}};for(const e in this._userThinInstanceBuffersStorage.data)t.data[e]=Array.from(this._userThinInstanceBuffersStorage.data[e]),t.sizes[e]=this._userThinInstanceBuffersStorage.sizes[e],t.strides[e]=this._userThinInstanceBuffersStorage.strides[e];e.thinInstances.userThinInstance=t}return re.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.layerMask=this.layerMask,e.alphaIndex=this.alphaIndex,e.hasVertexAlpha=this.hasVertexAlpha,e.overlayAlpha=this.overlayAlpha,e.overlayColor=this.overlayColor.asArray(),e.renderOverlay=this.renderOverlay,e.applyFog=this.applyFog,this.actionManager&&(e.actions=this.actionManager.serialize(this.name)),e}_syncGeometryWithMorphTargetManager(){if(!this.geometry)return;this._markSubMeshesAsAttributesDirty();const e=this._internalAbstractMeshDataInfo._morphTargetManager;if(e&&e.vertexCount){if(e.vertexCount!==this.getTotalVertices())return ue.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count."),void(this.morphTargetManager=null);if(e.isUsingTextureForTargets)return;for(let t=0;t<e.numInfluencers;t++){const s=e.getActiveTarget(t),i=s.getPositions();if(!i)return void ue.Error("Invalid morph target. Target must have positions.");this.geometry.setVerticesData(ns.PositionKind+t,i,!1,3);const r=s.getNormals();r&&this.geometry.setVerticesData(ns.NormalKind+t,r,!1,3);const n=s.getTangents();n&&this.geometry.setVerticesData(ns.TangentKind+t,n,!1,3);const a=s.getUVs();a&&this.geometry.setVerticesData(ns.UVKind+"_"+t,a,!1,2)}}else{let e=0;for(;this.geometry.isVerticesDataPresent(ns.PositionKind+e);)this.geometry.removeVerticesData(ns.PositionKind+e),this.geometry.isVerticesDataPresent(ns.NormalKind+e)&&this.geometry.removeVerticesData(ns.NormalKind+e),this.geometry.isVerticesDataPresent(ns.TangentKind+e)&&this.geometry.removeVerticesData(ns.TangentKind+e),this.geometry.isVerticesDataPresent(ns.UVKind+e)&&this.geometry.removeVerticesData(ns.UVKind+"_"+e),e++}}static Parse(e,t,s){let i;if(i=e.type&&"LinesMesh"===e.type?oi._LinesMeshParser(e,t):e.type&&"GroundMesh"===e.type?oi._GroundMeshParser(e,t):e.type&&"GoldbergMesh"===e.type?oi._GoldbergMeshParser(e,t):e.type&&"GreasedLineMesh"===e.type?oi._GreasedLineMeshParser(e,t):e.type&&"TrailMesh"===e.type?oi._TrailMeshParser(e,t):new oi(e.name,t),i.id=e.id,i._waitingParsedUniqueId=e.uniqueId,q&&q.AddTagsTo(i,e.tags),i.position=U.FromArray(e.position),void 0!==e.metadata&&(i.metadata=e.metadata),e.rotationQuaternion?i.rotationQuaternion=G.FromArray(e.rotationQuaternion):e.rotation&&(i.rotation=U.FromArray(e.rotation)),i.scaling=U.FromArray(e.scaling),e.localMatrix?i.setPreTransformMatrix(V.FromArray(e.localMatrix)):e.pivotMatrix&&i.setPivotMatrix(V.FromArray(e.pivotMatrix)),i.setEnabled(e.isEnabled),i.isVisible=e.isVisible,i.infiniteDistance=e.infiniteDistance,i.alwaysSelectAsActiveMesh=!!e.alwaysSelectAsActiveMesh,i.showBoundingBox=e.showBoundingBox,i.showSubMeshesBoundingBox=e.showSubMeshesBoundingBox,void 0!==e.applyFog&&(i.applyFog=e.applyFog),void 0!==e.pickable&&(i.isPickable=e.pickable),void 0!==e.alphaIndex&&(i.alphaIndex=e.alphaIndex),i.receiveShadows=e.receiveShadows,void 0!==e.billboardMode&&(i.billboardMode=e.billboardMode),void 0!==e.visibility&&(i.visibility=e.visibility),i.checkCollisions=e.checkCollisions,i.doNotSyncBoundingInfo=!!e.doNotSyncBoundingInfo,e.ellipsoid&&(i.ellipsoid=U.FromArray(e.ellipsoid)),e.ellipsoidOffset&&(i.ellipsoidOffset=U.FromArray(e.ellipsoidOffset)),null!=e.overrideMaterialSideOrientation&&(i.sideOrientation=e.overrideMaterialSideOrientation),void 0!==e.sideOrientation&&(i.sideOrientation=e.sideOrientation),void 0!==e.isBlocker&&(i.isBlocker=e.isBlocker),i._shouldGenerateFlatShading=e.useFlatShading,e.freezeWorldMatrix&&(i._waitingData.freezeWorldMatrix=e.freezeWorldMatrix),void 0!==e.parentId&&(i._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(i._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.actions&&(i._waitingData.actions=e.actions),void 0!==e.overlayAlpha&&(i.overlayAlpha=e.overlayAlpha),void 0!==e.overlayColor&&(i.overlayColor=ee.FromArray(e.overlayColor)),void 0!==e.renderOverlay&&(i.renderOverlay=e.renderOverlay),i.isUnIndexed=!!e.isUnIndexed,i.hasVertexAlpha=e.hasVertexAlpha,e.delayLoadingFile?(i.delayLoadState=Ze.DELAYLOADSTATE_NOTLOADED,i.delayLoadingFile=s+e.delayLoadingFile,i.buildBoundingInfo(U.FromArray(e.boundingBoxMinimum),U.FromArray(e.boundingBoxMaximum)),e._binaryInfo&&(i._binaryInfo=e._binaryInfo),i._delayInfo=[],e.hasUVs&&i._delayInfo.push(ns.UVKind),e.hasUVs2&&i._delayInfo.push(ns.UV2Kind),e.hasUVs3&&i._delayInfo.push(ns.UV3Kind),e.hasUVs4&&i._delayInfo.push(ns.UV4Kind),e.hasUVs5&&i._delayInfo.push(ns.UV5Kind),e.hasUVs6&&i._delayInfo.push(ns.UV6Kind),e.hasColors&&i._delayInfo.push(ns.ColorKind),e.hasMatricesIndices&&i._delayInfo.push(ns.MatricesIndicesKind),e.hasMatricesWeights&&i._delayInfo.push(ns.MatricesWeightsKind),i._delayLoadingFunction=ys._ImportGeometry,As.ForceFullSceneLoadingForIncremental&&i._checkDelayState()):ys._ImportGeometry(e,i),e.materialUniqueId?i._waitingMaterialId=e.materialUniqueId:e.materialId&&(i._waitingMaterialId=e.materialId),e.morphTargetManagerId>-1&&(i.morphTargetManager=t.getMorphTargetManagerById(e.morphTargetManagerId)),void 0!==e.skeletonId&&null!==e.skeletonId&&(i.skeleton=t.getLastSkeletonById(e.skeletonId),e.numBoneInfluencers&&(i.numBoneInfluencers=e.numBoneInfluencers)),e.animations){for(let t=0;t<e.animations.length;t++){const s=e.animations[t],r=S("BABYLON.Animation");r&&i.animations.push(r.Parse(s))}ae.ParseAnimationRanges(i,e,t)}if(e.autoAnimate&&t.beginAnimation(i,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),e.layerMask&&!isNaN(e.layerMask)?i.layerMask=Math.abs(parseInt(e.layerMask)):i.layerMask=268435455,e.physicsImpostor&&(i.physicsImpostor=oi._PhysicsImpostorParser(t,i,e)),e.lodMeshIds&&(i._waitingData.lods={ids:e.lodMeshIds,distances:e.lodDistances?e.lodDistances:null,coverages:e.lodCoverages?e.lodCoverages:null}),e.instances)for(let s=0;s<e.instances.length;s++){const r=e.instances[s],n=i.createInstance(r.name);if(r.id&&(n.id=r.id),q&&(r.tags?q.AddTagsTo(n,r.tags):q.AddTagsTo(n,e.tags)),n.position=U.FromArray(r.position),void 0!==r.metadata&&(n.metadata=r.metadata),void 0!==r.parentId&&(n._waitingParentId=r.parentId),void 0!==r.parentInstanceIndex&&(n._waitingParentInstanceIndex=r.parentInstanceIndex),void 0!==r.isEnabled&&null!==r.isEnabled&&n.setEnabled(r.isEnabled),void 0!==r.isVisible&&null!==r.isVisible&&(n.isVisible=r.isVisible),void 0!==r.isPickable&&null!==r.isPickable&&(n.isPickable=r.isPickable),r.rotationQuaternion?n.rotationQuaternion=G.FromArray(r.rotationQuaternion):r.rotation&&(n.rotation=U.FromArray(r.rotation)),n.scaling=U.FromArray(r.scaling),null!=r.checkCollisions&&null!=r.checkCollisions&&(n.checkCollisions=r.checkCollisions),null!=r.pickable&&null!=r.pickable&&(n.isPickable=r.pickable),null!=r.showBoundingBox&&null!=r.showBoundingBox&&(n.showBoundingBox=r.showBoundingBox),null!=r.showSubMeshesBoundingBox&&null!=r.showSubMeshesBoundingBox&&(n.showSubMeshesBoundingBox=r.showSubMeshesBoundingBox),null!=r.alphaIndex&&null!=r.showSubMeshesBoundingBox&&(n.alphaIndex=r.alphaIndex),r.physicsImpostor&&(n.physicsImpostor=oi._PhysicsImpostorParser(t,n,r)),void 0!==r.actions&&(n._waitingData.actions=r.actions),r.animations){for(let e=0;e<r.animations.length;e++){const t=r.animations[e],s=S("BABYLON.Animation");s&&n.animations.push(s.Parse(t))}ae.ParseAnimationRanges(n,r,t),r.autoAnimate&&t.beginAnimation(n,r.autoAnimateFrom,r.autoAnimateTo,r.autoAnimateLoop,r.autoAnimateSpeed||1)}}if(e.thinInstances){const t=e.thinInstances;if(i.thinInstanceEnablePicking=!!t.enablePicking,t.matrixData?(i.thinInstanceSetBuffer("matrix",new Float32Array(t.matrixData),16,!1),i._thinInstanceDataStorage.matrixBufferSize=t.matrixBufferSize,i._thinInstanceDataStorage.instancesCount=t.instancesCount):i._thinInstanceDataStorage.matrixBufferSize=t.matrixBufferSize,e.thinInstances.userThinInstance){const t=e.thinInstances.userThinInstance;for(const e in t.data)i.thinInstanceSetBuffer(e,new Float32Array(t.data[e]),t.strides[e],!1),i._userThinInstanceBuffersStorage.sizes[e]=t.sizes[e]}}return i}setPositionsForCPUSkinning(){const e=this._internalMeshDataInfo;if(!e._sourcePositions){const t=this.getVerticesData(ns.PositionKind);if(!t)return e._sourcePositions;e._sourcePositions=new Float32Array(t),this.isVertexBufferUpdatable(ns.PositionKind)||this.setVerticesData(ns.PositionKind,t,!0)}return e._sourcePositions}setNormalsForCPUSkinning(){const e=this._internalMeshDataInfo;if(!e._sourceNormals){const t=this.getVerticesData(ns.NormalKind);if(!t)return e._sourceNormals;e._sourceNormals=new Float32Array(t),this.isVertexBufferUpdatable(ns.NormalKind)||this.setVerticesData(ns.NormalKind,t,!0)}return e._sourceNormals}applySkeleton(e){if(!this.geometry)return this;if(this.geometry._softwareSkinningFrameId==this.getScene().getFrameId())return this;if(this.geometry._softwareSkinningFrameId=this.getScene().getFrameId(),!this.isVerticesDataPresent(ns.PositionKind))return this;if(!this.isVerticesDataPresent(ns.MatricesIndicesKind))return this;if(!this.isVerticesDataPresent(ns.MatricesWeightsKind))return this;const t=this.isVerticesDataPresent(ns.NormalKind),s=this._internalMeshDataInfo;if(!s._sourcePositions){const e=this.subMeshes.slice();this.setPositionsForCPUSkinning(),this.subMeshes=e}t&&!s._sourceNormals&&this.setNormalsForCPUSkinning();let i=this.getVerticesData(ns.PositionKind);if(!i)return this;i instanceof Float32Array||(i=new Float32Array(i));let r=this.getVerticesData(ns.NormalKind);if(t){if(!r)return this;r instanceof Float32Array||(r=new Float32Array(r))}const n=this.getVerticesData(ns.MatricesIndicesKind),a=this.getVerticesData(ns.MatricesWeightsKind);if(!a||!n)return this;const o=this.numBoneInfluencers>4,h=o?this.getVerticesData(ns.MatricesIndicesExtraKind):null,l=o?this.getVerticesData(ns.MatricesWeightsExtraKind):null,c=e.getTransformMatrices(this),u=U.Zero(),d=new V,_=new V;let f,p=0;for(let e=0;e<i.length;e+=3,p+=4){let m;for(f=0;f<4;f++)m=a[p+f],m>0&&(V.FromFloat32ArrayToRefScaled(c,Math.floor(16*n[p+f]),m,_),d.addToSelf(_));if(o)for(f=0;f<4;f++)m=l[p+f],m>0&&(V.FromFloat32ArrayToRefScaled(c,Math.floor(16*h[p+f]),m,_),d.addToSelf(_));U.TransformCoordinatesFromFloatsToRef(s._sourcePositions[e],s._sourcePositions[e+1],s._sourcePositions[e+2],d,u),u.toArray(i,e),t&&(U.TransformNormalFromFloatsToRef(s._sourceNormals[e],s._sourceNormals[e+1],s._sourceNormals[e+2],d,u),u.toArray(r,e)),d.reset()}return this.updateVerticesData(ns.PositionKind,i),t&&this.updateVerticesData(ns.NormalKind,r),this}static MinMax(e){let t=null,s=null;return e.forEach((function(e){const i=e.getBoundingInfo().boundingBox;t&&s?(t.minimizeInPlace(i.minimumWorld),s.maximizeInPlace(i.maximumWorld)):(t=i.minimumWorld,s=i.maximumWorld)})),t&&s?{min:t,max:s}:{min:U.Zero(),max:U.Zero()}}static Center(e){const t=e instanceof Array?oi.MinMax(e):e;return U.Center(t.min,t.max)}static MergeMeshes(e,t=!0,s,i,r,n){return jt(oi._MergeMeshesCoroutine(e,t,s,i,r,n,!1))}static MergeMeshesAsync(e,t=!0,s,i,r,n){return a=oi._MergeMeshesCoroutine(e,t,s,i,r,n,!0),o=function(e=25){let t;return(s,i,r)=>{const n=performance.now();void 0===t||n-t>e?(t=n,setTimeout((()=>{qt(s,i,r)}),0)):qt(s,i,r)}}(),new Promise(((e,t)=>{Qt(a,o,e,t)}));var a,o}static*_MergeMeshesCoroutine(e,t=!0,s,i,r,n,a){if(0===(e=e.filter(Boolean)).length)return null;let o;if(!s){let t=0;for(o=0;o<e.length;o++)if(t+=e[o].getTotalVertices(),t>=65536)return ue.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices"),null}n&&(r=!1);const h=new Array,l=new Array,c=new Array,u=e[0].sideOrientation;for(o=0;o<e.length;o++){const t=e[o];if(t.isAnInstance)return ue.Warn("Cannot merge instance meshes."),null;if(u!==t.sideOrientation)return ue.Warn("Cannot merge meshes with different sideOrientation values."),null;if(r&&c.push(t.getTotalIndices()),n)if(t.material){const e=t.material;if(e instanceof Js){for(let t=0;t<e.subMaterials.length;t++)h.indexOf(e.subMaterials[t])<0&&h.push(e.subMaterials[t]);for(let s=0;s<t.subMeshes.length;s++)l.push(h.indexOf(e.subMaterials[t.subMeshes[s].materialIndex])),c.push(t.subMeshes[s].indexCount)}else{h.indexOf(e)<0&&h.push(e);for(let s=0;s<t.subMeshes.length;s++)l.push(h.indexOf(e)),c.push(t.subMeshes[s].indexCount)}}else for(let e=0;e<t.subMeshes.length;e++)l.push(0),c.push(t.subMeshes[e].indexCount)}const d=e[0],_=e=>{const t=e.computeWorldMatrix(!0);return{vertexData:Es.ExtractFromMesh(e,!1,!1),transform:t}},{vertexData:f,transform:p}=_(d);a&&(yield);const m=new Array(e.length-1);for(let t=1;t<e.length;t++)m[t-1]=_(e[t]),a&&(yield);const g=f._mergeCoroutine(p,m,s,a,!t);let T=g.next();for(;!T.done;)a&&(yield),T=g.next();const E=T.value;i||(i=new oi(d.name+"_merged",d.getScene()));const A=E._applyToCoroutine(i,void 0,a);let y=A.next();for(;!y.done;)a&&(yield),y=A.next();if(i.checkCollisions=d.checkCollisions,i.sideOrientation=d.sideOrientation,t)for(o=0;o<e.length;o++)e[o].dispose();if(r||n){i.releaseSubMeshes(),o=0;let e=0;for(;o<c.length;)gs.CreateFromIndices(0,e,c[o],i,void 0,!1),e+=c[o],o++;for(const e of i.subMeshes)e.refreshBoundingInfo();i.computeWorldMatrix(!0)}if(n){const e=new Js(d.name+"_merged",d.getScene());e.subMaterials=h;for(let e=0;e<i.subMeshes.length;e++)i.subMeshes[e].materialIndex=l[e];i.material=e}else i.material=d.material;return i}addInstance(e){e._indexInSourceMeshInstanceArray=this.instances.length,this.instances.push(e)}removeInstance(e){const t=e._indexInSourceMeshInstanceArray;if(-1!=t){if(t!==this.instances.length-1){const e=this.instances[this.instances.length-1];this.instances[t]=e,e._indexInSourceMeshInstanceArray=t}e._indexInSourceMeshInstanceArray=-1,this.instances.pop()}}_shouldConvertRHS(){return this._scene.useRightHandedSystem&&this.sideOrientation===$s.CounterClockWiseSideOrientation}_getRenderingFillMode(e){const t=this.getScene();return t.forcePointsCloud?$s.PointFillMode:t.forceWireframe?$s.WireFrameFillMode:this.overrideRenderingFillMode??e}setMaterialByID(e){return this.setMaterialById(e)}static CreateRibbon(e,t,s,i,r,n,a,o,h){throw new Error("Import MeshBuilder to populate this function")}static CreateDisc(e,t,s,i,r,n){throw new Error("Import MeshBuilder to populate this function")}static CreateBox(e,t,s,i,r){throw new Error("Import MeshBuilder to populate this function")}static CreateSphere(e,t,s,i,r,n){throw new Error("Import MeshBuilder to populate this function")}static CreateHemisphere(e,t,s,i){throw new Error("Import MeshBuilder to populate this function")}static CreateCylinder(e,t,s,i,r,n,a,o,h){throw new Error("Import MeshBuilder to populate this function")}static CreateTorus(e,t,s,i,r,n,a){throw new Error("Import MeshBuilder to populate this function")}static CreateTorusKnot(e,t,s,i,r,n,a,o,h,l){throw new Error("Import MeshBuilder to populate this function")}static CreateLines(e,t,s,i,r){throw new Error("Import MeshBuilder to populate this function")}static CreateDashedLines(e,t,s,i,r,n,a,o){throw new Error("Import MeshBuilder to populate this function")}static CreatePolygon(e,t,s,i,r,n,a){throw new Error("Import MeshBuilder to populate this function")}static ExtrudePolygon(e,t,s,i,r,n,a,o){throw new Error("Import MeshBuilder to populate this function")}static ExtrudeShape(e,t,s,i,r,n,a,o,h,l){throw new Error("Import MeshBuilder to populate this function")}static ExtrudeShapeCustom(e,t,s,i,r,n,a,o,h,l,c,u){throw new Error("Import MeshBuilder to populate this function")}static CreateLathe(e,t,s,i,r,n,a){throw new Error("Import MeshBuilder to populate this function")}static CreatePlane(e,t,s,i,r){throw new Error("Import MeshBuilder to populate this function")}static CreateGround(e,t,s,i,r,n){throw new Error("Import MeshBuilder to populate this function")}static CreateTiledGround(e,t,s,i,r,n,a,o,h){throw new Error("Import MeshBuilder to populate this function")}static CreateGroundFromHeightMap(e,t,s,i,r,n,a,o,h,l,c){throw new Error("Import MeshBuilder to populate this function")}static CreateTube(e,t,s,i,r,n,a,o,h,l){throw new Error("Import MeshBuilder to populate this function")}static CreatePolyhedron(e,t,s){throw new Error("Import MeshBuilder to populate this function")}static CreateIcoSphere(e,t,s){throw new Error("Import MeshBuilder to populate this function")}static CreateDecal(e,t,s,i,r,n){throw new Error("Import MeshBuilder to populate this function")}static CreateCapsule(e,t,s){throw new Error("Import MeshBuilder to populate this function")}static ExtendToGoldberg(e){throw new Error("Import MeshBuilder to populate this function")}}oi.FRONTSIDE=Es.FRONTSIDE,oi.BACKSIDE=Es.BACKSIDE,oi.DOUBLESIDE=Es.DOUBLESIDE,oi.DEFAULTSIDE=Es.DEFAULTSIDE,oi.NO_CAP=0,oi.CAP_START=1,oi.CAP_END=2,oi.CAP_ALL=3,oi.NO_FLIP=0,oi.FLIP_TILE=1,oi.ROTATE_TILE=2,oi.FLIP_ROW=3,oi.ROTATE_ROW=4,oi.FLIP_N_ROTATE_TILE=5,oi.FLIP_N_ROTATE_ROW=6,oi.CENTER=0,oi.LEFT=1,oi.RIGHT=2,oi.TOP=3,oi.BOTTOM=4,oi.INSTANCEDMESH_SORT_TRANSPARENT=!1,oi._GroundMeshParser=(e,t)=>{throw Y("GroundMesh")},oi._GoldbergMeshParser=(e,t)=>{throw Y("GoldbergMesh")},oi._LinesMeshParser=(e,t)=>{throw Y("LinesMesh")},oi._GreasedLineMeshParser=(e,t)=>{throw Y("GreasedLineMesh")},oi._GreasedLineRibbonMeshParser=(e,t)=>{throw Y("GreasedLineRibbonMesh")},oi._TrailMeshParser=(e,t)=>{throw Y("TrailMesh")},I("BABYLON.Mesh",oi);class hi{}hi.POINTERDOWN=1,hi.POINTERUP=2,hi.POINTERMOVE=4,hi.POINTERWHEEL=8,hi.POINTERPICK=16,hi.POINTERTAP=32,hi.POINTERDOUBLETAP=64;class li{constructor(e,t){this.type=e,this.event=t}}class ci extends li{constructor(e,t,s,i){super(e,t),this.ray=null,this.originalPickingInfo=null,this.skipOnPointerObservable=!1,this.localPosition=new B(s,i)}}class ui extends li{get pickInfo(){return this._pickInfo||this._generatePickInfo(),this._pickInfo}constructor(e,t,s,i=null){super(e,t),this._pickInfo=s,this._inputManager=i}_generatePickInfo(){this._inputManager&&(this._pickInfo=this._inputManager._pickMove(this.event),this._inputManager._setRayOnPointerInfo(this._pickInfo,this.event),this._inputManager=null)}}class di{constructor(){this._zoomStopsAnimation=!1,this._idleRotationSpeed=.05,this._idleRotationWaitTime=2e3,this._idleRotationSpinupTime=2e3,this.targetAlpha=null,this._isPointerDown=!1,this._lastFrameTime=null,this._lastInteractionTime=-1/0,this._cameraRotationSpeed=0,this._lastFrameRadius=0}get name(){return"AutoRotation"}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set idleRotationSpeed(e){this._idleRotationSpeed=e}get idleRotationSpeed(){return this._idleRotationSpeed}set idleRotationWaitTime(e){this._idleRotationWaitTime=e}get idleRotationWaitTime(){return this._idleRotationWaitTime}set idleRotationSpinupTime(e){this._idleRotationSpinupTime=e}get idleRotationSpinupTime(){return this._idleRotationSpinupTime}get rotationInProgress(){return Math.abs(this._cameraRotationSpeed)>0}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==hi.POINTERDOWN?e.type===hi.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{if(this._reachTargetAlpha())return;const e=fe.Now;let t=0;null!=this._lastFrameTime&&(t=e-this._lastFrameTime),this._lastFrameTime=e,this._applyUserInteraction();const s=e-this._lastInteractionTime-this._idleRotationWaitTime,i=Math.max(Math.min(s/this._idleRotationSpinupTime,1),0);this._cameraRotationSpeed=this._idleRotationSpeed*i,this._attachedCamera&&(this._attachedCamera.alpha-=this._cameraRotationSpeed*(t/1e3))}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._attachedCamera=null}resetLastInteractionTime(e){this._lastInteractionTime=e??fe.Now}_reachTargetAlpha(){return!(!this._attachedCamera||!this.targetAlpha)&&Math.abs(this._attachedCamera.alpha-this.targetAlpha)<A}_userIsZooming(){return!!this._attachedCamera&&0!==this._attachedCamera.inertialRadiusOffset}_shouldAnimationStopForInteraction(){if(!this._attachedCamera)return!1;let e=!1;return this._lastFrameRadius===this._attachedCamera.radius&&0!==this._attachedCamera.inertialRadiusOffset&&(e=!0),this._lastFrameRadius=this._attachedCamera.radius,this._zoomStopsAnimation?e:this._userIsZooming()}_applyUserInteraction(){this._userIsMoving()&&!this._shouldAnimationStopForInteraction()&&(this._lastInteractionTime=fe.Now)}_userIsMoving(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)}}var _i;!function(e){e[e.CW=0]="CW",e[e.CCW=1]="CCW"}(_i||(_i={}));class fi{constructor(){this._easingMode=fi.EASINGMODE_EASEIN}setEasingMode(e){const t=Math.min(Math.max(e,0),2);this._easingMode=t}getEasingMode(){return this._easingMode}easeInCore(e){throw new Error("You must implement this method")}ease(e){switch(this._easingMode){case fi.EASINGMODE_EASEIN:return this.easeInCore(e);case fi.EASINGMODE_EASEOUT:return 1-this.easeInCore(1-e)}return e>=.5?.5*(1-this.easeInCore(2*(1-e)))+.5:.5*this.easeInCore(2*e)}}fi.EASINGMODE_EASEIN=0,fi.EASINGMODE_EASEOUT=1,fi.EASINGMODE_EASEINOUT=2;class pi{constructor(e,t,s){this.name=e,this.from=t,this.to=s}clone(){return new pi(this.name,this.from,this.to)}}class mi{constructor(e,t){this.width=e,this.height=t}toString(){return`{W: ${this.width}, H: ${this.height}}`}getClassName(){return"Size"}getHashCode(){let e=0|this.width;return e=397*e^this.height,e}copyFrom(e){this.width=e.width,this.height=e.height}copyFromFloats(e,t){return this.width=e,this.height=t,this}set(e,t){return this.copyFromFloats(e,t)}multiplyByFloats(e,t){return new mi(this.width*e,this.height*t)}clone(){return new mi(this.width,this.height)}equals(e){return!!e&&(this.width===e.width&&this.height===e.height)}get surface(){return this.width*this.height}static Zero(){return new mi(0,0)}add(e){return new mi(this.width+e.width,this.height+e.height)}subtract(e){return new mi(this.width-e.width,this.height-e.height)}scale(e){return new mi(this.width*e,this.height*e)}static Lerp(e,t,s){const i=e.width+(t.width-e.width)*s,r=e.height+(t.height-e.height)*s;return new mi(i,r)}}const gi=Object.freeze(new G(0,0,0,0)),Ti=Object.freeze(U.Zero()),Ei=Object.freeze(B.Zero()),Ai=Object.freeze(mi.Zero()),yi=Object.freeze(ee.Black()),bi=Object.freeze(new te(0,0,0,0)),Ri={key:0,repeatCount:0,loopMode:2};class xi{static _PrepareAnimation(e,t,s,i,r,n,a,o){let h;if(!isNaN(parseFloat(r))&&isFinite(r)?h=xi.ANIMATIONTYPE_FLOAT:r instanceof G?h=xi.ANIMATIONTYPE_QUATERNION:r instanceof U?h=xi.ANIMATIONTYPE_VECTOR3:r instanceof B?h=xi.ANIMATIONTYPE_VECTOR2:r instanceof ee?h=xi.ANIMATIONTYPE_COLOR3:r instanceof te?h=xi.ANIMATIONTYPE_COLOR4:r instanceof mi&&(h=xi.ANIMATIONTYPE_SIZE),null==h)return null;const l=new xi(e,t,s,h,a),c=[{frame:0,value:r},{frame:i,value:n}];return l.setKeys(c),void 0!==o&&l.setEasingFunction(o),l}static CreateAnimation(e,t,s,i){const r=new xi(e+"Animation",e,s,t,xi.ANIMATIONLOOPMODE_CONSTANT);return r.setEasingFunction(i),r}static CreateAndStartAnimation(e,t,s,i,r,n,a,o,h,l,c){const u=xi._PrepareAnimation(e,s,i,r,n,a,o,h);return u?(t.getScene&&(c=t.getScene()),c?c.beginDirectAnimation(t,[u],0,r,1===u.loopMode,1,l):null):null}static CreateAndStartHierarchyAnimation(e,t,s,i,r,n,a,o,h,l,c){const u=xi._PrepareAnimation(e,i,r,n,a,o,h,l);if(!u)return null;return t.getScene().beginDirectHierarchyAnimation(t,s,[u],0,n,1===u.loopMode,1,c)}static CreateMergeAndStartAnimation(e,t,s,i,r,n,a,o,h,l){const c=xi._PrepareAnimation(e,s,i,r,n,a,o,h);return c?(t.animations.push(c),t.getScene().beginAnimation(t,0,r,1===c.loopMode,1,l)):null}static MakeAnimationAdditive(e,t,s,i=!1,r){let n;n="object"==typeof t?t:{referenceFrame:t??0,range:s,cloneOriginalAnimation:i,clonedAnimationName:r};let a=e;if(n.cloneOriginalAnimation&&(a=e.clone(),a.name=n.clonedAnimationName||a.name),!a._keys.length)return a;const o=n.referenceFrame&&n.referenceFrame>=0?n.referenceFrame:0;let h=0;const l=a._keys[0];let c=a._keys.length-1;const u=a._keys[c],d={referenceValue:l.value,referencePosition:z.Vector3[0],referenceQuaternion:z.Quaternion[0],referenceScaling:z.Vector3[1],keyPosition:z.Vector3[2],keyQuaternion:z.Quaternion[1],keyScaling:z.Vector3[3]};let _=l.frame,f=u.frame;if(n.range){const e=a.getRange(n.range);e&&(_=e.from,f=e.to)}else _=n.fromFrame??_,f=n.toFrame??f;if(_!==l.frame&&(h=a.createKeyForFrame(_)),f!==u.frame&&(c=a.createKeyForFrame(f)),1===a._keys.length){const e=a._getKeyValue(a._keys[0]);d.referenceValue=e.clone?e.clone():e}else if(o<=l.frame){const e=a._getKeyValue(l.value);d.referenceValue=e.clone?e.clone():e}else if(o>=u.frame){const e=a._getKeyValue(u.value);d.referenceValue=e.clone?e.clone():e}else{Ri.key=0;const e=a._interpolate(o,Ri);d.referenceValue=e.clone?e.clone():e}a.dataType===xi.ANIMATIONTYPE_QUATERNION?d.referenceValue.normalize().conjugateInPlace():a.dataType===xi.ANIMATIONTYPE_MATRIX&&(d.referenceValue.decompose(d.referenceScaling,d.referenceQuaternion,d.referencePosition),d.referenceQuaternion.normalize().conjugateInPlace());let p=Number.MAX_VALUE;const m=n.clipKeys?[]:null;for(let e=h;e<=c;e++){let t=a._keys[e];if((m||n.cloneOriginalAnimation)&&(t={frame:t.frame,value:t.value.clone?t.value.clone():t.value,inTangent:t.inTangent,outTangent:t.outTangent,interpolation:t.interpolation,lockedTangent:t.lockedTangent},m&&(p===Number.MAX_VALUE&&(p=t.frame),t.frame-=p,m.push(t))),!e||a.dataType===xi.ANIMATIONTYPE_FLOAT||t.value!==l.value)switch(a.dataType){case xi.ANIMATIONTYPE_MATRIX:t.value.decompose(d.keyScaling,d.keyQuaternion,d.keyPosition),d.keyPosition.subtractInPlace(d.referencePosition),d.keyScaling.divideInPlace(d.referenceScaling),d.referenceQuaternion.multiplyToRef(d.keyQuaternion,d.keyQuaternion),V.ComposeToRef(d.keyScaling,d.keyQuaternion,d.keyPosition,t.value);break;case xi.ANIMATIONTYPE_QUATERNION:d.referenceValue.multiplyToRef(t.value,t.value);break;case xi.ANIMATIONTYPE_VECTOR2:case xi.ANIMATIONTYPE_VECTOR3:case xi.ANIMATIONTYPE_COLOR3:case xi.ANIMATIONTYPE_COLOR4:t.value.subtractToRef(d.referenceValue,t.value);break;case xi.ANIMATIONTYPE_SIZE:t.value.width-=d.referenceValue.width,t.value.height-=d.referenceValue.height;break;default:t.value-=d.referenceValue}}return m&&a.setKeys(m,!0),a}static TransitionTo(e,t,s,i,r,n,a,o=null){if(a<=0)return s[e]=t,o&&o(),null;const h=r*(a/1e3);n.setKeys([{frame:0,value:s[e].clone?s[e].clone():s[e]},{frame:h,value:t}]),s.animations||(s.animations=[]),s.animations.push(n);const l=i.beginAnimation(s,0,h,!1);return l.onAnimationEnd=o,l}get runtimeAnimations(){return this._runtimeAnimations}get hasRunningRuntimeAnimations(){for(const e of this._runtimeAnimations)if(!e.isStopped())return!0;return!1}constructor(e,t,s,i,r,n){this.name=e,this.targetProperty=t,this.framePerSecond=s,this.dataType=i,this.loopMode=r,this.enableBlending=n,this._easingFunction=null,this._runtimeAnimations=new Array,this._events=new Array,this.blendingSpeed=.01,this._ranges={},this.targetPropertyPath=t.split("."),this.dataType=i,this.loopMode=void 0===r?xi.ANIMATIONLOOPMODE_CYCLE:r,this.uniqueId=xi._UniqueIdGenerator++}toString(e){let t="Name: "+this.name+", property: "+this.targetProperty;if(t+=", datatype: "+["Float","Vector3","Quaternion","Matrix","Color3","Vector2"][this.dataType],t+=", nKeys: "+(this._keys?this._keys.length:"none"),t+=", nRanges: "+(this._ranges?Object.keys(this._ranges).length:"none"),e){t+=", Ranges: {";let e=!0;for(const s in this._ranges)e&&(t+=", ",e=!1),t+=s;t+="}"}return t}addEvent(e){this._events.push(e),this._events.sort(((e,t)=>e.frame-t.frame))}removeEvents(e){for(let t=0;t<this._events.length;t++)this._events[t].frame===e&&(this._events.splice(t,1),t--)}getEvents(){return this._events}createRange(e,t,s){this._ranges[e]||(this._ranges[e]=new pi(e,t,s))}deleteRange(e,t=!0){const s=this._ranges[e];if(s){if(t){const e=s.from,t=s.to;for(let s=this._keys.length-1;s>=0;s--)this._keys[s].frame>=e&&this._keys[s].frame<=t&&this._keys.splice(s,1)}this._ranges[e]=null}}getRange(e){return this._ranges[e]}getKeys(){return this._keys}getHighestFrame(){let e=0;for(let t=0,s=this._keys.length;t<s;t++)e<this._keys[t].frame&&(e=this._keys[t].frame);return e}getEasingFunction(){return this._easingFunction}setEasingFunction(e){this._easingFunction=e}floatInterpolateFunction(e,t,s){return Q.Lerp(e,t,s)}floatInterpolateFunctionWithTangents(e,t,s,i,r){return Q.Hermite(e,t,s,i,r)}quaternionInterpolateFunction(e,t,s){return G.Slerp(e,t,s)}quaternionInterpolateFunctionWithTangents(e,t,s,i,r){return G.Hermite(e,t,s,i,r).normalize()}vector3InterpolateFunction(e,t,s){return U.Lerp(e,t,s)}vector3InterpolateFunctionWithTangents(e,t,s,i,r){return U.Hermite(e,t,s,i,r)}vector2InterpolateFunction(e,t,s){return B.Lerp(e,t,s)}vector2InterpolateFunctionWithTangents(e,t,s,i,r){return B.Hermite(e,t,s,i,r)}sizeInterpolateFunction(e,t,s){return mi.Lerp(e,t,s)}color3InterpolateFunction(e,t,s){return ee.Lerp(e,t,s)}color3InterpolateFunctionWithTangents(e,t,s,i,r){return ee.Hermite(e,t,s,i,r)}color4InterpolateFunction(e,t,s){return te.Lerp(e,t,s)}color4InterpolateFunctionWithTangents(e,t,s,i,r){return te.Hermite(e,t,s,i,r)}_getKeyValue(e){return"function"==typeof e?e():e}evaluate(e){return Ri.key=0,this._interpolate(e,Ri)}_interpolate(e,t,s=!1){if(t.loopMode===xi.ANIMATIONLOOPMODE_CONSTANT&&t.repeatCount>0)return t.highLimitValue.clone?t.highLimitValue.clone():t.highLimitValue;const i=this._keys,r=i.length;let n=t.key;for(;n>=0&&e<i[n].frame;)--n;for(;n+1<=r-1&&e>=i[n+1].frame;)++n;if(t.key=n,n<0)return s?void 0:this._getKeyValue(i[0].value);if(n+1>r-1)return s?void 0:this._getKeyValue(i[r-1].value);const a=i[n],o=i[n+1];if(s&&(e===a.frame||e===o.frame))return;const h=this._getKeyValue(a.value),l=this._getKeyValue(o.value);if(1===a.interpolation)return o.frame>e?h:l;const c=void 0!==a.outTangent&&void 0!==o.inTangent,u=o.frame-a.frame;let d=(e-a.frame)/u;const _=a.easingFunction||this.getEasingFunction();switch(null!==_&&(d=_.ease(d)),this.dataType){case xi.ANIMATIONTYPE_FLOAT:{const e=c?this.floatInterpolateFunctionWithTangents(h,a.outTangent*u,l,o.inTangent*u,d):this.floatInterpolateFunction(h,l,d);switch(t.loopMode){case xi.ANIMATIONLOOPMODE_CYCLE:case xi.ANIMATIONLOOPMODE_CONSTANT:case xi.ANIMATIONLOOPMODE_YOYO:return e;case xi.ANIMATIONLOOPMODE_RELATIVE:case xi.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return(t.offsetValue??0)*t.repeatCount+e}break}case xi.ANIMATIONTYPE_QUATERNION:{const e=c?this.quaternionInterpolateFunctionWithTangents(h,a.outTangent.scale(u),l,o.inTangent.scale(u),d):this.quaternionInterpolateFunction(h,l,d);switch(t.loopMode){case xi.ANIMATIONLOOPMODE_CYCLE:case xi.ANIMATIONLOOPMODE_CONSTANT:case xi.ANIMATIONLOOPMODE_YOYO:return e;case xi.ANIMATIONLOOPMODE_RELATIVE:case xi.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.addInPlace((t.offsetValue||gi).scale(t.repeatCount))}return e}case xi.ANIMATIONTYPE_VECTOR3:{const e=c?this.vector3InterpolateFunctionWithTangents(h,a.outTangent.scale(u),l,o.inTangent.scale(u),d):this.vector3InterpolateFunction(h,l,d);switch(t.loopMode){case xi.ANIMATIONLOOPMODE_CYCLE:case xi.ANIMATIONLOOPMODE_CONSTANT:case xi.ANIMATIONLOOPMODE_YOYO:return e;case xi.ANIMATIONLOOPMODE_RELATIVE:case xi.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Ti).scale(t.repeatCount))}break}case xi.ANIMATIONTYPE_VECTOR2:{const e=c?this.vector2InterpolateFunctionWithTangents(h,a.outTangent.scale(u),l,o.inTangent.scale(u),d):this.vector2InterpolateFunction(h,l,d);switch(t.loopMode){case xi.ANIMATIONLOOPMODE_CYCLE:case xi.ANIMATIONLOOPMODE_CONSTANT:case xi.ANIMATIONLOOPMODE_YOYO:return e;case xi.ANIMATIONLOOPMODE_RELATIVE:case xi.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||Ei).scale(t.repeatCount))}break}case xi.ANIMATIONTYPE_SIZE:switch(t.loopMode){case xi.ANIMATIONLOOPMODE_CYCLE:case xi.ANIMATIONLOOPMODE_CONSTANT:case xi.ANIMATIONLOOPMODE_YOYO:return this.sizeInterpolateFunction(h,l,d);case xi.ANIMATIONLOOPMODE_RELATIVE:case xi.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return this.sizeInterpolateFunction(h,l,d).add((t.offsetValue||Ai).scale(t.repeatCount))}break;case xi.ANIMATIONTYPE_COLOR3:{const e=c?this.color3InterpolateFunctionWithTangents(h,a.outTangent.scale(u),l,o.inTangent.scale(u),d):this.color3InterpolateFunction(h,l,d);switch(t.loopMode){case xi.ANIMATIONLOOPMODE_CYCLE:case xi.ANIMATIONLOOPMODE_CONSTANT:case xi.ANIMATIONLOOPMODE_YOYO:return e;case xi.ANIMATIONLOOPMODE_RELATIVE:case xi.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||yi).scale(t.repeatCount))}break}case xi.ANIMATIONTYPE_COLOR4:{const e=c?this.color4InterpolateFunctionWithTangents(h,a.outTangent.scale(u),l,o.inTangent.scale(u),d):this.color4InterpolateFunction(h,l,d);switch(t.loopMode){case xi.ANIMATIONLOOPMODE_CYCLE:case xi.ANIMATIONLOOPMODE_CONSTANT:case xi.ANIMATIONLOOPMODE_YOYO:return e;case xi.ANIMATIONLOOPMODE_RELATIVE:case xi.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return e.add((t.offsetValue||bi).scale(t.repeatCount))}break}case xi.ANIMATIONTYPE_MATRIX:switch(t.loopMode){case xi.ANIMATIONLOOPMODE_CYCLE:case xi.ANIMATIONLOOPMODE_CONSTANT:case xi.ANIMATIONLOOPMODE_YOYO:return xi.AllowMatricesInterpolation?this.matrixInterpolateFunction(h,l,d,t.workValue):h;case xi.ANIMATIONLOOPMODE_RELATIVE:case xi.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT:return h}}return 0}matrixInterpolateFunction(e,t,s,i){return xi.AllowMatrixDecomposeForInterpolation?i?(V.DecomposeLerpToRef(e,t,s,i),i):V.DecomposeLerp(e,t,s):i?(V.LerpToRef(e,t,s,i),i):V.Lerp(e,t,s)}clone(){const e=new xi(this.name,this.targetPropertyPath.join("."),this.framePerSecond,this.dataType,this.loopMode);if(e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,this._keys&&e.setKeys(this._keys),this._ranges){e._ranges={};for(const t in this._ranges){const s=this._ranges[t];s&&(e._ranges[t]=s.clone())}}return e}setKeys(e,t=!1){this._keys=t?e:e.slice(0)}createKeyForFrame(e){Ri.key=0;const t=this._interpolate(e,Ri,!0);if(!t)return this._keys[Ri.key].frame===e?Ri.key:Ri.key+1;const s={frame:e,value:t.clone?t.clone():t};return this._keys.splice(Ri.key+1,0,s),Ri.key+1}serialize(){const e={};e.name=this.name,e.property=this.targetProperty,e.framePerSecond=this.framePerSecond,e.dataType=this.dataType,e.loopBehavior=this.loopMode,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed;const t=this.dataType;e.keys=[];const s=this.getKeys();for(let i=0;i<s.length;i++){const r=s[i],n={};switch(n.frame=r.frame,t){case xi.ANIMATIONTYPE_FLOAT:n.values=[r.value],void 0!==r.inTangent&&n.values.push(r.inTangent),void 0!==r.outTangent&&(void 0===r.inTangent&&n.values.push(void 0),n.values.push(r.outTangent)),void 0!==r.interpolation&&(void 0===r.inTangent&&n.values.push(void 0),void 0===r.outTangent&&n.values.push(void 0),n.values.push(r.interpolation));break;case xi.ANIMATIONTYPE_QUATERNION:case xi.ANIMATIONTYPE_MATRIX:case xi.ANIMATIONTYPE_VECTOR3:case xi.ANIMATIONTYPE_COLOR3:case xi.ANIMATIONTYPE_COLOR4:n.values=r.value.asArray(),null!=r.inTangent&&n.values.push(r.inTangent.asArray()),null!=r.outTangent&&(void 0===r.inTangent&&n.values.push(void 0),n.values.push(r.outTangent.asArray())),void 0!==r.interpolation&&(void 0===r.inTangent&&n.values.push(void 0),void 0===r.outTangent&&n.values.push(void 0),n.values.push(r.interpolation))}e.keys.push(n)}e.ranges=[];for(const t in this._ranges){const s=this._ranges[t];if(!s)continue;const i={};i.name=t,i.from=s.from,i.to=s.to,e.ranges.push(i)}return e}static _UniversalLerp(e,t,s){const i=e.constructor;return i.Lerp?i.Lerp(e,t,s):i.Slerp?i.Slerp(e,t,s):e.toFixed?e*(1-s)+s*t:t}static Parse(e){const t=new xi(e.name,e.property,e.framePerSecond,e.dataType,e.loopBehavior),s=e.dataType,i=[];let r,n;for(e.enableBlending&&(t.enableBlending=e.enableBlending),e.blendingSpeed&&(t.blendingSpeed=e.blendingSpeed),n=0;n<e.keys.length;n++){const t=e.keys[n];let a,o,h;switch(s){case xi.ANIMATIONTYPE_FLOAT:r=t.values[0],t.values.length>=2&&(a=t.values[1]),t.values.length>=3&&(o=t.values[2]),t.values.length>=4&&(h=t.values[3]);break;case xi.ANIMATIONTYPE_QUATERNION:if(r=G.FromArray(t.values),t.values.length>=8){const e=G.FromArray(t.values.slice(4,8));e.equals(G.Zero())||(a=e)}if(t.values.length>=12){const e=G.FromArray(t.values.slice(8,12));e.equals(G.Zero())||(o=e)}t.values.length>=13&&(h=t.values[12]);break;case xi.ANIMATIONTYPE_MATRIX:r=V.FromArray(t.values),t.values.length>=17&&(h=t.values[16]);break;case xi.ANIMATIONTYPE_COLOR3:r=ee.FromArray(t.values),t.values[3]&&(a=ee.FromArray(t.values[3])),t.values[4]&&(o=ee.FromArray(t.values[4])),t.values[5]&&(h=t.values[5]);break;case xi.ANIMATIONTYPE_COLOR4:r=te.FromArray(t.values),t.values[4]&&(a=te.FromArray(t.values[4])),t.values[5]&&(o=te.FromArray(t.values[5])),t.values[6]&&(h=te.FromArray(t.values[6]));break;case xi.ANIMATIONTYPE_VECTOR3:default:r=U.FromArray(t.values),t.values[3]&&(a=U.FromArray(t.values[3])),t.values[4]&&(o=U.FromArray(t.values[4])),t.values[5]&&(h=t.values[5])}const l={};l.frame=t.frame,l.value=r,null!=a&&(l.inTangent=a),null!=o&&(l.outTangent=o),null!=h&&(l.interpolation=h),i.push(l)}if(t.setKeys(i),e.ranges)for(n=0;n<e.ranges.length;n++)r=e.ranges[n],t.createRange(r.name,r.from,r.to);return t}static AppendSerializedAnimations(e,t){re.AppendSerializedAnimations(e,t)}static ParseFromFileAsync(e,t){return new Promise(((s,i)=>{const r=new pe;r.addEventListener("readystatechange",(()=>{if(4==r.readyState)if(200==r.status){let t=JSON.parse(r.responseText);if(t.animations&&(t=t.animations),t.length){const e=[];for(const s of t)e.push(this.Parse(s));s(e)}else{const i=this.Parse(t);e&&(i.name=e),s(i)}}else i("Unable to load the animation")})),r.open("GET",t),r.send()}))}static ParseFromSnippetAsync(e){return new Promise(((t,s)=>{const i=new pe;i.addEventListener("readystatechange",(()=>{if(4==i.readyState)if(200==i.status){const s=JSON.parse(JSON.parse(i.responseText).jsonPayload);if(s.animations){const i=JSON.parse(s.animations),r=[];for(const t of i.animations){const s=this.Parse(t);s.snippetId=e,r.push(s)}t(r)}else{const i=JSON.parse(s.animation),r=this.Parse(i);r.snippetId=e,t(r)}}else s("Unable to load the snippet "+e)})),i.open("GET",this.SnippetUrl+"/"+e.replace(/#/g,"/")),i.send()}))}}xi._UniqueIdGenerator=0,xi.AllowMatricesInterpolation=!1,xi.AllowMatrixDecomposeForInterpolation=!0,xi.SnippetUrl=Ze.SnippetUrl,xi.ANIMATIONTYPE_FLOAT=0,xi.ANIMATIONTYPE_VECTOR3=1,xi.ANIMATIONTYPE_QUATERNION=2,xi.ANIMATIONTYPE_MATRIX=3,xi.ANIMATIONTYPE_COLOR3=4,xi.ANIMATIONTYPE_COLOR4=7,xi.ANIMATIONTYPE_VECTOR2=5,xi.ANIMATIONTYPE_SIZE=6,xi.ANIMATIONLOOPMODE_RELATIVE=0,xi.ANIMATIONLOOPMODE_CYCLE=1,xi.ANIMATIONLOOPMODE_CONSTANT=2,xi.ANIMATIONLOOPMODE_YOYO=4,xi.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT=5,xi.CreateFromSnippetAsync=xi.ParseFromSnippetAsync,I("BABYLON.Animation",xi),ae._AnimationRangeFactory=(e,t,s)=>new pi(e,t,s);class Mi{constructor(){this.transitionDuration=450,this.lowerRadiusTransitionRange=2,this.upperRadiusTransitionRange=-2,this._autoTransitionRange=!1,this._radiusIsAnimating=!1,this._radiusBounceTransition=null,this._animatables=new Array}get name(){return"Bouncing"}get autoTransitionRange(){return this._autoTransitionRange}set autoTransitionRange(e){if(this._autoTransitionRange===e)return;this._autoTransitionRange=e;const t=this._attachedCamera;t&&(e?this._onMeshTargetChangedObserver=t.onMeshTargetChangedObservable.add((e=>{if(e&&(e.computeWorldMatrix(!0),e.getBoundingInfo)){const t=e.getBoundingInfo().diagonalLength;this.lowerRadiusTransitionRange=.05*t,this.upperRadiusTransitionRange=.05*t}})):this._onMeshTargetChangedObserver&&t.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver))}init(){}attach(e){this._attachedCamera=e,this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{this._attachedCamera&&(this._isRadiusAtLimit(this._attachedCamera.lowerRadiusLimit)&&this._applyBoundRadiusAnimation(this.lowerRadiusTransitionRange),this._isRadiusAtLimit(this._attachedCamera.upperRadiusLimit)&&this._applyBoundRadiusAnimation(this.upperRadiusTransitionRange))}))}detach(){this._attachedCamera&&(this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null)}_isRadiusAtLimit(e){return!!this._attachedCamera&&(this._attachedCamera.radius===e&&!this._radiusIsAnimating)}_applyBoundRadiusAnimation(e){if(!this._attachedCamera)return;this._radiusBounceTransition||(Mi.EasingFunction.setEasingMode(Mi.EasingMode),this._radiusBounceTransition=xi.CreateAnimation("radius",xi.ANIMATIONTYPE_FLOAT,60,Mi.EasingFunction)),this._cachedWheelPrecision=this._attachedCamera.wheelPrecision,this._attachedCamera.wheelPrecision=1/0,this._attachedCamera.inertialRadiusOffset=0,this.stopAllAnimations(),this._radiusIsAnimating=!0;const t=xi.TransitionTo("radius",this._attachedCamera.radius+e,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusBounceTransition,this.transitionDuration,(()=>this._clearAnimationLocks()));t&&this._animatables.push(t)}_clearAnimationLocks(){this._radiusIsAnimating=!1,this._attachedCamera&&(this._attachedCamera.wheelPrecision=this._cachedWheelPrecision)}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0].onAnimationEnd=null,this._animatables[0].stop(),this._animatables.shift()}}Mi.EasingFunction=new class extends fi{constructor(e=1){super(),this.amplitude=e}easeInCore(e){const t=Math.max(0,this.amplitude);return Math.pow(e,3)-e*t*Math.sin(3.141592653589793*e)}}(.3),Mi.EasingMode=fi.EASINGMODE_EASEOUT;class Ii{constructor(){this.onTargetFramingAnimationEndObservable=new g,this._mode=Ii.FitFrustumSidesMode,this._radiusScale=1,this._positionScale=.5,this._defaultElevation=.3,this._elevationReturnTime=1500,this._elevationReturnWaitTime=1e3,this._zoomStopsAnimation=!1,this._framingTime=1500,this.autoCorrectCameraLimitsAndSensibility=!0,this._isPointerDown=!1,this._lastInteractionTime=-1/0,this._animatables=new Array,this._betaIsAnimating=!1}get name(){return"Framing"}set mode(e){this._mode=e}get mode(){return this._mode}set radiusScale(e){this._radiusScale=e}get radiusScale(){return this._radiusScale}set positionScale(e){this._positionScale=e}get positionScale(){return this._positionScale}set defaultElevation(e){this._defaultElevation=e}get defaultElevation(){return this._defaultElevation}set elevationReturnTime(e){this._elevationReturnTime=e}get elevationReturnTime(){return this._elevationReturnTime}set elevationReturnWaitTime(e){this._elevationReturnWaitTime=e}get elevationReturnWaitTime(){return this._elevationReturnWaitTime}set zoomStopsAnimation(e){this._zoomStopsAnimation=e}get zoomStopsAnimation(){return this._zoomStopsAnimation}set framingTime(e){this._framingTime=e}get framingTime(){return this._framingTime}init(){}attach(e){this._attachedCamera=e;const t=this._attachedCamera.getScene();Ii.EasingFunction.setEasingMode(Ii.EasingMode),this._onPrePointerObservableObserver=t.onPrePointerObservable.add((e=>{e.type!==hi.POINTERDOWN?e.type===hi.POINTERUP&&(this._isPointerDown=!1):this._isPointerDown=!0})),this._onMeshTargetChangedObserver=e.onMeshTargetChangedObservable.add((e=>{e&&e.getBoundingInfo&&this.zoomOnMesh(e,void 0,(()=>{this.onTargetFramingAnimationEndObservable.notifyObservers()}))})),this._onAfterCheckInputsObserver=e.onAfterCheckInputsObservable.add((()=>{this._applyUserInteraction(),this._maintainCameraAboveGround()}))}detach(){if(!this._attachedCamera)return;const e=this._attachedCamera.getScene();this._onPrePointerObservableObserver&&e.onPrePointerObservable.remove(this._onPrePointerObservableObserver),this._onAfterCheckInputsObserver&&this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver),this._onMeshTargetChangedObserver&&this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver),this._attachedCamera=null}zoomOnMesh(e,t=!1,s=null){e.computeWorldMatrix(!0);const i=e.getBoundingInfo().boundingBox;this.zoomOnBoundingInfo(i.minimumWorld,i.maximumWorld,t,s)}zoomOnMeshHierarchy(e,t=!1,s=null){e.computeWorldMatrix(!0);const i=e.getHierarchyBoundingVectors(!0);this.zoomOnBoundingInfo(i.min,i.max,t,s)}zoomOnMeshesHierarchy(e,t=!1,s=null){const i=new U(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),r=new U(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);for(let t=0;t<e.length;t++){const s=e[t].getHierarchyBoundingVectors(!0);U.CheckExtends(s.min,i,r),U.CheckExtends(s.max,i,r)}this.zoomOnBoundingInfo(i,r,t,s)}zoomOnBoundingInfo(e,t,s=!1,i=null){let r;if(!this._attachedCamera)return!1;const n=e.y,a=n+(t.y-n)*this._positionScale,o=t.subtract(e).scale(.5);if(s)r=new U(0,a,0);else{const t=e.add(o);r=new U(t.x,a,t.z)}this._vectorTransition||(this._vectorTransition=xi.CreateAnimation("target",xi.ANIMATIONTYPE_VECTOR3,60,Ii.EasingFunction)),this._betaIsAnimating=!0;let h=xi.TransitionTo("target",r,this._attachedCamera,this._attachedCamera.getScene(),60,this._vectorTransition,this._framingTime);h&&this._animatables.push(h);let l=0;if(this._mode===Ii.FitFrustumSidesMode){const s=this._calculateLowerRadiusFromModelBoundingSphere(e,t);this.autoCorrectCameraLimitsAndSensibility&&(this._attachedCamera.lowerRadiusLimit=o.length()+this._attachedCamera.minZ),l=s}else this._mode===Ii.IgnoreBoundsSizeMode&&(l=this._calculateLowerRadiusFromModelBoundingSphere(e,t),this.autoCorrectCameraLimitsAndSensibility&&null===this._attachedCamera.lowerRadiusLimit&&(this._attachedCamera.lowerRadiusLimit=this._attachedCamera.minZ));if(this.autoCorrectCameraLimitsAndSensibility){const s=t.subtract(e).length();this._attachedCamera.panningSensibility=5e3/s,this._attachedCamera.wheelPrecision=100/l}return this._radiusTransition||(this._radiusTransition=xi.CreateAnimation("radius",xi.ANIMATIONTYPE_FLOAT,60,Ii.EasingFunction)),h=xi.TransitionTo("radius",l,this._attachedCamera,this._attachedCamera.getScene(),60,this._radiusTransition,this._framingTime,(()=>{this.stopAllAnimations(),i&&i(),this._attachedCamera&&this._attachedCamera.useInputToRestoreState&&this._attachedCamera.storeState()})),h&&this._animatables.push(h),!0}_calculateLowerRadiusFromModelBoundingSphere(e,t){const s=this._attachedCamera;if(!s)return 0;let i=s._calculateLowerRadiusFromModelBoundingSphere(e,t,this._radiusScale);return s.lowerRadiusLimit&&this._mode===Ii.IgnoreBoundsSizeMode&&(i=i<s.lowerRadiusLimit?s.lowerRadiusLimit:i),s.upperRadiusLimit&&(i=i>s.upperRadiusLimit?s.upperRadiusLimit:i),i}_maintainCameraAboveGround(){if(this._elevationReturnTime<0)return;const e=fe.Now-this._lastInteractionTime,t=.5*Math.PI-this._defaultElevation,s=.5*Math.PI;if(this._attachedCamera&&!this._betaIsAnimating&&this._attachedCamera.beta>s&&e>=this._elevationReturnWaitTime){this._betaIsAnimating=!0,this.stopAllAnimations(),this._betaTransition||(this._betaTransition=xi.CreateAnimation("beta",xi.ANIMATIONTYPE_FLOAT,60,Ii.EasingFunction));const e=xi.TransitionTo("beta",t,this._attachedCamera,this._attachedCamera.getScene(),60,this._betaTransition,this._elevationReturnTime,(()=>{this._clearAnimationLocks(),this.stopAllAnimations()}));e&&this._animatables.push(e)}}_clearAnimationLocks(){this._betaIsAnimating=!1}_applyUserInteraction(){this.isUserIsMoving&&(this._lastInteractionTime=fe.Now,this.stopAllAnimations(),this._clearAnimationLocks())}stopAllAnimations(){for(this._attachedCamera&&(this._attachedCamera.animations=[]);this._animatables.length;)this._animatables[0]&&(this._animatables[0].onAnimationEnd=null,this._animatables[0].stop()),this._animatables.shift()}get isUserIsMoving(){return!!this._attachedCamera&&(0!==this._attachedCamera.inertialAlphaOffset||0!==this._attachedCamera.inertialBetaOffset||0!==this._attachedCamera.inertialRadiusOffset||0!==this._attachedCamera.inertialPanningX||0!==this._attachedCamera.inertialPanningY||this._isPointerDown)}}Ii.EasingFunction=new class extends fi{constructor(e=2){super(),this.exponent=e}easeInCore(e){return this.exponent<=0?e:(Math.exp(this.exponent*e)-1)/(Math.exp(this.exponent)-1)}},Ii.EasingMode=fi.EASINGMODE_EASEINOUT,Ii.IgnoreBoundsSizeMode=0,Ii.FitFrustumSidesMode=1,ae.AddNodeConstructor("TargetCamera",((e,t)=>()=>new Si(e,U.Zero(),t)));class Si extends ss{constructor(e,t,s,i=!0){super(e,t,s,i),this._tmpUpVector=U.Zero(),this._tmpTargetVector=U.Zero(),this.cameraDirection=new U(0,0,0),this.cameraRotation=new B(0,0),this.ignoreParentScaling=!1,this.updateUpVectorFromRotation=!1,this._tmpQuaternion=new G,this.rotation=new U(0,0,0),this.speed=2,this.noRotationConstraint=!1,this.invertRotation=!1,this.inverseRotationSpeed=.2,this.lockedTarget=null,this._currentTarget=U.Zero(),this._initialFocalDistance=1,this._viewMatrix=V.Zero(),this._camMatrix=V.Zero(),this._cameraTransformMatrix=V.Zero(),this._cameraRotationMatrix=V.Zero(),this._referencePoint=new U(0,0,1),this._transformedReferencePoint=U.Zero(),this._deferredPositionUpdate=new U,this._deferredRotationQuaternionUpdate=new G,this._deferredRotationUpdate=new U,this._deferredUpdated=!1,this._deferOnly=!1,this._defaultUp=U.Up(),this._cachedRotationZ=0,this._cachedQuaternionRotationZ=0}getFrontPosition(e){this.getWorldMatrix();const t=this.getTarget().subtract(this.position);return t.normalize(),t.scaleInPlace(e),this.globalPosition.add(t)}_getLockedTargetPosition(){if(!this.lockedTarget)return null;if(this.lockedTarget.absolutePosition){const e=this.lockedTarget;e.computeWorldMatrix().getTranslationToRef(e.absolutePosition)}return this.lockedTarget.absolutePosition||this.lockedTarget}storeState(){return this._storedPosition=this.position.clone(),this._storedRotation=this.rotation.clone(),this.rotationQuaternion&&(this._storedRotationQuaternion=this.rotationQuaternion.clone()),super.storeState()}_restoreStateValues(){return!!super._restoreStateValues()&&(this.position=this._storedPosition.clone(),this.rotation=this._storedRotation.clone(),this.rotationQuaternion&&(this.rotationQuaternion=this._storedRotationQuaternion.clone()),this.cameraDirection.copyFromFloats(0,0,0),this.cameraRotation.copyFromFloats(0,0),!0)}_initCache(){super._initCache(),this._cache.lockedTarget=new U(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotation=new U(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.rotationQuaternion=new G(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)}_updateCache(e){e||super._updateCache();const t=this._getLockedTargetPosition();t?this._cache.lockedTarget?this._cache.lockedTarget.copyFrom(t):this._cache.lockedTarget=t.clone():this._cache.lockedTarget=null,this._cache.rotation.copyFrom(this.rotation),this.rotationQuaternion&&this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion)}_isSynchronizedViewMatrix(){if(!super._isSynchronizedViewMatrix())return!1;const e=this._getLockedTargetPosition();return(this._cache.lockedTarget?this._cache.lockedTarget.equals(e):!e)&&(this.rotationQuaternion?this.rotationQuaternion.equals(this._cache.rotationQuaternion):this._cache.rotation.equals(this.rotation))}_computeLocalCameraSpeed(){const e=this.getEngine();return this.speed*Math.sqrt(e.getDeltaTime()/(100*e.getFps()))}setTarget(e){this.upVector.normalize(),this._initialFocalDistance=e.subtract(this.position).length(),this.position.z===e.z&&(this.position.z+=A),this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance),V.LookAtLHToRef(this.position,e,this._defaultUp,this._camMatrix),this._camMatrix.invert(),this.rotation.x=Math.atan(this._camMatrix.m[6]/this._camMatrix.m[10]);const t=e.subtract(this.position);t.x>=0?this.rotation.y=-Math.atan(t.z/t.x)+Math.PI/2:this.rotation.y=-Math.atan(t.z/t.x)-Math.PI/2,this.rotation.z=0,isNaN(this.rotation.x)&&(this.rotation.x=0),isNaN(this.rotation.y)&&(this.rotation.y=0),isNaN(this.rotation.z)&&(this.rotation.z=0),this.rotationQuaternion&&G.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this.rotationQuaternion)}get target(){return this.getTarget()}set target(e){this.setTarget(e)}getTarget(){return this._currentTarget}_decideIfNeedsToMove(){return Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){if(this.parent)return this.parent.getWorldMatrix().invertToRef(z.Matrix[0]),U.TransformNormalToRef(this.cameraDirection,z.Matrix[0],z.Vector3[0]),this._deferredPositionUpdate.addInPlace(z.Vector3[0]),void(this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate));this._deferredPositionUpdate.addInPlace(this.cameraDirection),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate)}_checkInputs(){const e=this.invertRotation?-this.inverseRotationSpeed:1,t=this._decideIfNeedsToMove(),s=this.cameraRotation.x||this.cameraRotation.y;if(this._deferredUpdated=!1,this._deferredRotationUpdate.copyFrom(this.rotation),this._deferredPositionUpdate.copyFrom(this.position),this.rotationQuaternion&&this._deferredRotationQuaternionUpdate.copyFrom(this.rotationQuaternion),t&&this._updatePosition(),s){if(this.rotationQuaternion&&this.rotationQuaternion.toEulerAnglesToRef(this._deferredRotationUpdate),this._deferredRotationUpdate.x+=this.cameraRotation.x*e,this._deferredRotationUpdate.y+=this.cameraRotation.y*e,!this.noRotationConstraint){const e=1.570796;this._deferredRotationUpdate.x>e&&(this._deferredRotationUpdate.x=e),this._deferredRotationUpdate.x<-e&&(this._deferredRotationUpdate.x=-e)}if(this._deferOnly?this._deferredUpdated=!0:this.rotation.copyFrom(this._deferredRotationUpdate),this.rotationQuaternion){this._deferredRotationUpdate.lengthSquared()&&(G.RotationYawPitchRollToRef(this._deferredRotationUpdate.y,this._deferredRotationUpdate.x,this._deferredRotationUpdate.z,this._deferredRotationQuaternionUpdate),this._deferOnly?this._deferredUpdated=!0:this.rotationQuaternion.copyFrom(this._deferredRotationQuaternionUpdate))}}t&&(Math.abs(this.cameraDirection.x)<this.speed*A&&(this.cameraDirection.x=0),Math.abs(this.cameraDirection.y)<this.speed*A&&(this.cameraDirection.y=0),Math.abs(this.cameraDirection.z)<this.speed*A&&(this.cameraDirection.z=0),this.cameraDirection.scaleInPlace(this.inertia)),s&&(Math.abs(this.cameraRotation.x)<this.speed*A&&(this.cameraRotation.x=0),Math.abs(this.cameraRotation.y)<this.speed*A&&(this.cameraRotation.y=0),this.cameraRotation.scaleInPlace(this.inertia)),super._checkInputs()}_updateCameraRotationMatrix(){this.rotationQuaternion?this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix):V.RotationYawPitchRollToRef(this.rotation.y,this.rotation.x,this.rotation.z,this._cameraRotationMatrix)}_rotateUpVectorWithCameraRotationMatrix(){return U.TransformNormalToRef(this._defaultUp,this._cameraRotationMatrix,this.upVector),this}_getViewMatrix(){return this.lockedTarget&&this.setTarget(this._getLockedTargetPosition()),this._updateCameraRotationMatrix(),this.rotationQuaternion&&this._cachedQuaternionRotationZ!=this.rotationQuaternion.z?(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedQuaternionRotationZ=this.rotationQuaternion.z):this._cachedRotationZ!==this.rotation.z&&(this._rotateUpVectorWithCameraRotationMatrix(),this._cachedRotationZ=this.rotation.z),U.TransformCoordinatesToRef(this._referencePoint,this._cameraRotationMatrix,this._transformedReferencePoint),this.position.addToRef(this._transformedReferencePoint,this._currentTarget),this.updateUpVectorFromRotation&&(this.rotationQuaternion?Bs.Y.rotateByQuaternionToRef(this.rotationQuaternion,this.upVector):(G.FromEulerVectorToRef(this.rotation,this._tmpQuaternion),Bs.Y.rotateByQuaternionToRef(this._tmpQuaternion,this.upVector))),this._computeViewMatrix(this.position,this._currentTarget,this.upVector),this._viewMatrix}_computeViewMatrix(e,t,s){if(this.ignoreParentScaling){if(this.parent){const i=this.parent.getWorldMatrix();U.TransformCoordinatesToRef(e,i,this._globalPosition),U.TransformCoordinatesToRef(t,i,this._tmpTargetVector),U.TransformNormalToRef(s,i,this._tmpUpVector),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e),this._tmpTargetVector.copyFrom(t),this._tmpUpVector.copyFrom(s);this.getScene().useRightHandedSystem?V.LookAtRHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix):V.LookAtLHToRef(this._globalPosition,this._tmpTargetVector,this._tmpUpVector,this._viewMatrix)}else if(this.getScene().useRightHandedSystem?V.LookAtRHToRef(e,t,s,this._viewMatrix):V.LookAtLHToRef(e,t,s,this._viewMatrix),this.parent){const e=this.parent.getWorldMatrix();this._viewMatrix.invert(),this._viewMatrix.multiplyToRef(e,this._viewMatrix),this._viewMatrix.getTranslationToRef(this._globalPosition),this._viewMatrix.invert(),this._markSyncedWithParent()}else this._globalPosition.copyFrom(e)}createRigCamera(e,t){if(this.cameraRigMode!==ss.RIG_MODE_NONE){const t=new Si(e,this.position.clone(),this.getScene());return t.isRigCamera=!0,t.rigParent=this,this.cameraRigMode===ss.RIG_MODE_VR&&(this.rotationQuaternion||(this.rotationQuaternion=new G),t._cameraRigParams={},t.rotationQuaternion=new G),t.mode=this.mode,t.orthoLeft=this.orthoLeft,t.orthoRight=this.orthoRight,t.orthoTop=this.orthoTop,t.orthoBottom=this.orthoBottom,t}return null}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(this.computeWorldMatrix(),this.cameraRigMode){case ss.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ss.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ss.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:case ss.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ss.RIG_MODE_STEREOSCOPIC_INTERLACED:{const s=this.cameraRigMode===ss.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?1:-1,i=this.cameraRigMode===ss.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED?-1:1;this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*s,e),this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle*i,t);break}case ss.RIG_MODE_VR:e.rotationQuaternion?(e.rotationQuaternion.copyFrom(this.rotationQuaternion),t.rotationQuaternion.copyFrom(this.rotationQuaternion)):(e.rotation.copyFrom(this.rotation),t.rotation.copyFrom(this.rotation)),e.position.copyFrom(this.position),t.position.copyFrom(this.position)}super._updateRigCameras()}_getRigCamPositionAndTarget(e,t){this.getTarget().subtractToRef(this.position,Si._TargetFocalPoint),Si._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);const s=Si._TargetFocalPoint.addInPlace(this.position);V.TranslationToRef(-s.x,-s.y,-s.z,Si._TargetTransformMatrix),Si._TargetTransformMatrix.multiplyToRef(V.RotationAxis(t.upVector,e),Si._RigCamTransformMatrix),V.TranslationToRef(s.x,s.y,s.z,Si._TargetTransformMatrix),Si._RigCamTransformMatrix.multiplyToRef(Si._TargetTransformMatrix,Si._RigCamTransformMatrix),U.TransformCoordinatesToRef(this.position,Si._RigCamTransformMatrix,t.position),t.setTarget(s)}getClassName(){return"TargetCamera"}}Si._RigCamTransformMatrix=new V,Si._TargetTransformMatrix=new V,Si._TargetFocalPoint=new U,e([c()],Si.prototype,"rotation",void 0),e([a()],Si.prototype,"speed",void 0),e([u("lockedTargetId")],Si.prototype,"lockedTarget",void 0);var vi,Ci={};class Pi{constructor(e){this.attachedToElement=!1,this.attached={},this.camera=e,this.checkInputs=()=>{}}add(e){const t=e.getSimpleName();this.attached[t]?ue.Warn("camera input of type "+t+" already exists on camera"):(this.attached[t]=e,e.camera=this.camera,e.checkInputs&&(this.checkInputs=this._addCheckInputs(e.checkInputs.bind(e))),this.attachedToElement&&e.attachControl(this.noPreventDefault))}remove(e){for(const t in this.attached){const s=this.attached[t];if(s===e)return s.detachControl(),s.camera=null,delete this.attached[t],void this.rebuildInputCheck()}}removeByType(e){for(const t in this.attached){const s=this.attached[t];s.getClassName()===e&&(s.detachControl(),s.camera=null,delete this.attached[t],this.rebuildInputCheck())}}_addCheckInputs(e){const t=this.checkInputs;return()=>{t(),e()}}attachInput(e){this.attachedToElement&&e.attachControl(this.noPreventDefault)}attachElement(e=!1){if(!this.attachedToElement){e=!ss.ForceAttachControlToAlwaysPreventDefault&&e,this.attachedToElement=!0,this.noPreventDefault=e;for(const t in this.attached)this.attached[t].attachControl(e)}}detachElement(e=!1){for(const t in this.attached)this.attached[t].detachControl(),e&&(this.attached[t].camera=null);this.attachedToElement=!1}rebuildInputCheck(){this.checkInputs=()=>{};for(const e in this.attached){const t=this.attached[e];t.checkInputs&&(this.checkInputs=this._addCheckInputs(t.checkInputs.bind(t)))}}clear(){this.attachedToElement&&this.detachElement(!0),this.attached={},this.attachedToElement=!1,this.checkInputs=()=>{}}serialize(e){const t={};for(const e in this.attached){const s=this.attached[e],i=re.Serialize(s);t[s.getClassName()]=i}e.inputsmgr=t}parse(e){const t=e.inputsmgr;if(t){this.clear();for(const e in t){const s=Ci[e];if(s){const i=t[e],r=re.Parse((()=>new s),i,null);this.add(r)}}}else for(const t in this.attached){const s=Ci[this.attached[t].getClassName()];if(s){const i=re.Parse((()=>new s),e,null);this.remove(this.attached[t]),this.add(i)}}}}class Oi{constructor(){this._currentActiveButton=-1,this.buttons=[0,1,2]}attachControl(e){e=Yt.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),s=t.getInputElement();let i=0,r=null;this._pointA=null,this._pointB=null,this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._pointerInput=n=>{const a=n.event,o="touch"===a.pointerType;if(n.type!==hi.POINTERMOVE&&-1===this.buttons.indexOf(a.button))return;const h=a.target;if(this._altKey=a.altKey,this._ctrlKey=a.ctrlKey,this._metaKey=a.metaKey,this._shiftKey=a.shiftKey,this._buttonsPressed=a.buttons,t.isPointerLock){const e=a.movementX,t=a.movementY;this.onTouch(null,e,t),this._pointA=null,this._pointB=null}else{if(n.type!==hi.POINTERDOWN&&n.type!==hi.POINTERDOUBLETAP&&o&&this._pointA?.pointerId!==a.pointerId&&this._pointB?.pointerId!==a.pointerId)return;if(n.type!==hi.POINTERDOWN||-1!==this._currentActiveButton&&!o)if(n.type===hi.POINTERDOUBLETAP)this.onDoubleTap(a.pointerType);else if(n.type!==hi.POINTERUP||this._currentActiveButton!==a.button&&!o){if(n.type===hi.POINTERMOVE)if(e||a.preventDefault(),this._pointA&&null===this._pointB){const e=a.clientX-this._pointA.x,t=a.clientY-this._pointA.y;this._pointA.x=a.clientX,this._pointA.y=a.clientY,this.onTouch(this._pointA,e,t)}else if(this._pointA&&this._pointB){const e=this._pointA.pointerId===a.pointerId?this._pointA:this._pointB;e.x=a.clientX,e.y=a.clientY;const t=this._pointA.x-this._pointB.x,s=this._pointA.y-this._pointB.y,o=t*t+s*s,h={x:(this._pointA.x+this._pointB.x)/2,y:(this._pointA.y+this._pointB.y)/2,pointerId:a.pointerId,type:n.type};this.onMultiTouch(this._pointA,this._pointB,i,o,r,h),r=h,i=o}}else{try{h?.releasePointerCapture(a.pointerId)}catch(e){}o||(this._pointB=null),t._badOS?this._pointA=this._pointB=null:this._pointB&&this._pointA&&this._pointA.pointerId==a.pointerId?(this._pointA=this._pointB,this._pointB=null):this._pointA&&this._pointB&&this._pointB.pointerId==a.pointerId?this._pointB=null:this._pointA=this._pointB=null,(0!==i||r)&&(this.onMultiTouch(this._pointA,this._pointB,i,0,r,null),i=0,r=null),this._currentActiveButton=-1,this.onButtonUp(a),e||a.preventDefault()}else{try{h?.setPointerCapture(a.pointerId)}catch(e){}if(null===this._pointA)this._pointA={x:a.clientX,y:a.clientY,pointerId:a.pointerId,type:a.pointerType};else{if(null!==this._pointB)return;this._pointB={x:a.clientX,y:a.clientY,pointerId:a.pointerId,type:a.pointerType}}-1!==this._currentActiveButton||o||(this._currentActiveButton=a.button),this.onButtonDown(a),e||(a.preventDefault(),s&&s.focus())}}},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,hi.POINTERDOWN|hi.POINTERUP|hi.POINTERMOVE|hi.POINTERDOUBLETAP),this._onLostFocus=()=>{this._pointA=this._pointB=null,i=0,r=null,this.onLostFocus()},this._contextMenuBind=e=>this.onContextMenu(e),s&&s.addEventListener("contextmenu",this._contextMenuBind,!1);const n=this.camera.getScene().getEngine().getHostWindow();n&&Yt.RegisterTopRootEvents(n,[{name:"blur",handler:this._onLostFocus}])}detachControl(){if(this._onLostFocus){const e=this.camera.getScene().getEngine().getHostWindow();e&&Yt.UnregisterTopRootEvents(e,[{name:"blur",handler:this._onLostFocus}])}if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._contextMenuBind){const e=this.camera.getScene().getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this._onLostFocus=null}this._altKey=!1,this._ctrlKey=!1,this._metaKey=!1,this._shiftKey=!1,this._buttonsPressed=0,this._currentActiveButton=-1}getClassName(){return"BaseCameraPointersInput"}getSimpleName(){return"pointers"}onDoubleTap(e){}onTouch(e,t,s){}onMultiTouch(e,t,s,i,r,n){}onContextMenu(e){e.preventDefault()}onButtonDown(e){}onButtonUp(e){}onLostFocus(){}}e([a()],Oi.prototype,"buttons",void 0);class Di extends Oi{constructor(){super(...arguments),this.buttons=[0,1,2],this.angularSensibilityX=1e3,this.angularSensibilityY=1e3,this.pinchPrecision=12,this.pinchDeltaPercentage=0,this.useNaturalPinchZoom=!1,this.pinchZoom=!0,this.panningSensibility=1e3,this.multiTouchPanning=!0,this.multiTouchPanAndZoom=!0,this.pinchInwards=!0,this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}getClassName(){return"ArcRotateCameraPointersInput"}_computeMultiTouchPanning(e,t){if(0!==this.panningSensibility&&e&&t){const s=t.x-e.x,i=t.y-e.y;this.camera.inertialPanningX+=-s/this.panningSensibility,this.camera.inertialPanningY+=i/this.panningSensibility}}_computePinchZoom(e,t){const s=this.camera.radius||Di.MinimumRadiusForPinch;this.useNaturalPinchZoom?this.camera.radius=s*Math.sqrt(e)/Math.sqrt(t):this.pinchDeltaPercentage?this.camera.inertialRadiusOffset+=.001*(t-e)*s*this.pinchDeltaPercentage:this.camera.inertialRadiusOffset+=(t-e)/(this.pinchPrecision*(this.pinchInwards?1:-1)*(this.angularSensibilityX+this.angularSensibilityY)/2)}onTouch(e,t,s){0!==this.panningSensibility&&(this._ctrlKey&&this.camera._useCtrlForPanning||this._isPanClick)?(this.camera.inertialPanningX+=-t/this.panningSensibility,this.camera.inertialPanningY+=s/this.panningSensibility):(this.camera.inertialAlphaOffset-=t/this.angularSensibilityX,this.camera.inertialBetaOffset-=s/this.angularSensibilityY)}onDoubleTap(){this.camera.useInputToRestoreState&&this.camera.restoreState()}onMultiTouch(e,t,s,i,r,n){0===s&&null===r||0===i&&null===n||(this.multiTouchPanAndZoom?(this._computePinchZoom(s,i),this._computeMultiTouchPanning(r,n)):this.multiTouchPanning&&this.pinchZoom?(this._twoFingerActivityCount++,this._isPinching||this._twoFingerActivityCount<20&&Math.abs(Math.sqrt(i)-Math.sqrt(s))>this.camera.pinchToPanMaxDistance?(this._computePinchZoom(s,i),this._isPinching=!0):this._computeMultiTouchPanning(r,n)):this.multiTouchPanning?this._computeMultiTouchPanning(r,n):this.pinchZoom&&this._computePinchZoom(s,i))}onButtonDown(e){this._isPanClick=e.button===this.camera._panningMouseButton}onButtonUp(e){this._twoFingerActivityCount=0,this._isPinching=!1}onLostFocus(){this._isPanClick=!1,this._twoFingerActivityCount=0,this._isPinching=!1}}Di.MinimumRadiusForPinch=.001,e([a()],Di.prototype,"buttons",void 0),e([a()],Di.prototype,"angularSensibilityX",void 0),e([a()],Di.prototype,"angularSensibilityY",void 0),e([a()],Di.prototype,"pinchPrecision",void 0),e([a()],Di.prototype,"pinchDeltaPercentage",void 0),e([a()],Di.prototype,"useNaturalPinchZoom",void 0),e([a()],Di.prototype,"pinchZoom",void 0),e([a()],Di.prototype,"panningSensibility",void 0),e([a()],Di.prototype,"multiTouchPanning",void 0),e([a()],Di.prototype,"multiTouchPanAndZoom",void 0),Ci.ArcRotateCameraPointersInput=Di;class Li{}Li.KEYDOWN=1,Li.KEYUP=2;class Fi{constructor(e,t){this.type=e,this.event=t}}class Ni extends Fi{get skipOnPointerObservable(){return this.skipOnKeyboardObservable}set skipOnPointerObservable(e){this.skipOnKeyboardObservable=e}constructor(e,t){super(e,t),this.type=e,this.event=t,this.skipOnKeyboardObservable=!1}}class wi{constructor(){this.keysUp=[38],this.keysDown=[40],this.keysLeft=[37],this.keysRight=[39],this.keysReset=[220],this.panningSensibility=50,this.zoomingSensibility=25,this.useAltToZoom=!0,this.angularSpeed=.01,this._keys=new Array}attachControl(e){e=Yt.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const s=t.event;if(!s.metaKey)if(t.type===Li.KEYDOWN){if(this._ctrlPressed=s.ctrlKey,this._altPressed=s.altKey,-1!==this.keysUp.indexOf(s.keyCode)||-1!==this.keysDown.indexOf(s.keyCode)||-1!==this.keysLeft.indexOf(s.keyCode)||-1!==this.keysRight.indexOf(s.keyCode)||-1!==this.keysReset.indexOf(s.keyCode)){-1===this._keys.indexOf(s.keyCode)&&this._keys.push(s.keyCode),s.preventDefault&&(e||s.preventDefault())}}else if(-1!==this.keysUp.indexOf(s.keyCode)||-1!==this.keysDown.indexOf(s.keyCode)||-1!==this.keysLeft.indexOf(s.keyCode)||-1!==this.keysRight.indexOf(s.keyCode)||-1!==this.keysReset.indexOf(s.keyCode)){const t=this._keys.indexOf(s.keyCode);t>=0&&this._keys.splice(t,1),s.preventDefault&&(e||s.preventDefault())}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t<this._keys.length;t++){const s=this._keys[t];-1!==this.keysLeft.indexOf(s)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX-=1/this.panningSensibility:e.inertialAlphaOffset-=this.angularSpeed:-1!==this.keysUp.indexOf(s)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY+=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset+=1/this.zoomingSensibility:e.inertialBetaOffset-=this.angularSpeed:-1!==this.keysRight.indexOf(s)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningX+=1/this.panningSensibility:e.inertialAlphaOffset+=this.angularSpeed:-1!==this.keysDown.indexOf(s)?this._ctrlPressed&&this.camera._useCtrlForPanning?e.inertialPanningY-=1/this.panningSensibility:this._altPressed&&this.useAltToZoom?e.inertialRadiusOffset-=1/this.zoomingSensibility:e.inertialBetaOffset+=this.angularSpeed:-1!==this.keysReset.indexOf(s)&&e.useInputToRestoreState&&e.restoreState()}}}getClassName(){return"ArcRotateCameraKeyboardMoveInput"}getSimpleName(){return"keyboard"}}e([a()],wi.prototype,"keysUp",void 0),e([a()],wi.prototype,"keysDown",void 0),e([a()],wi.prototype,"keysLeft",void 0),e([a()],wi.prototype,"keysRight",void 0),e([a()],wi.prototype,"keysReset",void 0),e([a()],wi.prototype,"panningSensibility",void 0),e([a()],wi.prototype,"zoomingSensibility",void 0),e([a()],wi.prototype,"useAltToZoom",void 0),e([a()],wi.prototype,"angularSpeed",void 0),Ci.ArcRotateCameraKeyboardMoveInput=wi,function(e){e[e.PointerMove=0]="PointerMove",e[e.PointerDown=1]="PointerDown",e[e.PointerUp=2]="PointerUp"}(vi||(vi={}));class Bi{}Bi.DOM_DELTA_PIXEL=0,Bi.DOM_DELTA_LINE=1,Bi.DOM_DELTA_PAGE=2;class Ui{constructor(){this.wheelPrecision=3,this.zoomToMouseLocation=!1,this.wheelDeltaPercentage=0,this.customComputeDeltaFromMouseWheel=null,this._viewOffset=new U(0,0,0),this._globalOffset=new U(0,0,0),this._inertialPanning=U.Zero()}_computeDeltaFromMouseWheelLegacyEvent(e,t){let s=0;const i=.01*e*this.wheelDeltaPercentage*t;return s=e>0?i/(1+this.wheelDeltaPercentage):i*(1+this.wheelDeltaPercentage),s}attachControl(e){e=Yt.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==hi.POINTERWHEEL)return;const s=t.event;let i=0;const r=s.deltaMode===Bi.DOM_DELTA_LINE?40:1,n=-s.deltaY*r;if(this.customComputeDeltaFromMouseWheel)i=this.customComputeDeltaFromMouseWheel(n,this,s);else if(this.wheelDeltaPercentage){if(i=this._computeDeltaFromMouseWheelLegacyEvent(n,this.camera.radius),i>0){let e=this.camera.radius,t=this.camera.inertialRadiusOffset+i;for(let s=0;s<20&&Math.abs(t)>.001;s++)e-=t,t*=this.camera.inertia;e=Q.Clamp(e,0,Number.MAX_VALUE),i=this._computeDeltaFromMouseWheelLegacyEvent(n,e)}}else i=n/(40*this.wheelPrecision);i&&(this.zoomToMouseLocation?(this._hitPlane||this._updateHitPlane(),this._zoomToMouse(i)):this.camera.inertialRadiusOffset+=i),s.preventDefault&&(e||s.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,hi.POINTERWHEEL),this.zoomToMouseLocation&&this._inertialPanning.setAll(0)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null)}checkInputs(){if(!this.zoomToMouseLocation)return;const e=this.camera;0+e.inertialAlphaOffset+e.inertialBetaOffset+e.inertialRadiusOffset&&(this._updateHitPlane(),e.target.addInPlace(this._inertialPanning),this._inertialPanning.scaleInPlace(e.inertia),this._zeroIfClose(this._inertialPanning))}getClassName(){return"ArcRotateCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}_updateHitPlane(){const e=this.camera,t=e.target.subtract(e.position);this._hitPlane=es.FromPositionAndNormal(e.target,t)}_getPosition(){const e=this.camera,t=e.getScene(),s=t.createPickingRay(t.pointerX,t.pointerY,V.Identity(),e,!1);0===e.targetScreenOffset.x&&0===e.targetScreenOffset.y||(this._viewOffset.set(e.targetScreenOffset.x,e.targetScreenOffset.y,0),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),this._globalOffset=U.TransformNormal(this._viewOffset,e._cameraTransformMatrix),s.origin.addInPlace(this._globalOffset));let i=0;return this._hitPlane&&(i=s.intersectsPlane(this._hitPlane)??0),s.origin.addInPlace(s.direction.scaleInPlace(i))}_zoomToMouse(e){const t=this.camera,s=1-t.inertia;if(t.lowerRadiusLimit){const i=t.lowerRadiusLimit??0;t.radius-(t.inertialRadiusOffset+e)/s<i&&(e=(t.radius-i)*s-t.inertialRadiusOffset)}if(t.upperRadiusLimit){const i=t.upperRadiusLimit??0;t.radius-(t.inertialRadiusOffset+e)/s>i&&(e=(t.radius-i)*s-t.inertialRadiusOffset)}const i=e/s/t.radius,r=this._getPosition(),n=z.Vector3[6];r.subtractToRef(t.target,n),n.scaleInPlace(i),n.scaleInPlace(s),this._inertialPanning.addInPlace(n),t.inertialRadiusOffset+=e}_zeroIfClose(e){Math.abs(e.x)<A&&(e.x=0),Math.abs(e.y)<A&&(e.y=0),Math.abs(e.z)<A&&(e.z=0)}}e([a()],Ui.prototype,"wheelPrecision",void 0),e([a()],Ui.prototype,"zoomToMouseLocation",void 0),e([a()],Ui.prototype,"wheelDeltaPercentage",void 0),Ci.ArcRotateCameraMouseWheelInput=Ui;class ki extends Pi{constructor(e){super(e)}addMouseWheel(){return this.add(new Ui),this}addPointers(){return this.add(new Di),this}addKeyboard(){return this.add(new wi),this}}ae.AddNodeConstructor("ArcRotateCamera",((e,t)=>()=>new Gi(e,0,0,1,U.Zero(),t)));class Gi extends Si{get target(){return this._target}set target(e){this.setTarget(e)}get targetHost(){return this._targetHost}set targetHost(e){e&&this.setTarget(e)}getTarget(){return this.target}get position(){return this._position}set position(e){this.setPosition(e)}set upVector(e){this._upToYMatrix||(this._yToUpMatrix=new V,this._upToYMatrix=new V,this._upVector=U.Zero()),e.normalize(),this._upVector.copyFrom(e),this.setMatUp()}get upVector(){return this._upVector}setMatUp(){V.RotationAlignToRef(U.UpReadOnly,this._upVector,this._yToUpMatrix),V.RotationAlignToRef(this._upVector,U.UpReadOnly,this._upToYMatrix)}get angularSensibilityX(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityX:0}set angularSensibilityX(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityX=e)}get angularSensibilityY(){const e=this.inputs.attached.pointers;return e?e.angularSensibilityY:0}set angularSensibilityY(e){const t=this.inputs.attached.pointers;t&&(t.angularSensibilityY=e)}get pinchPrecision(){const e=this.inputs.attached.pointers;return e?e.pinchPrecision:0}set pinchPrecision(e){const t=this.inputs.attached.pointers;t&&(t.pinchPrecision=e)}get pinchDeltaPercentage(){const e=this.inputs.attached.pointers;return e?e.pinchDeltaPercentage:0}set pinchDeltaPercentage(e){const t=this.inputs.attached.pointers;t&&(t.pinchDeltaPercentage=e)}get useNaturalPinchZoom(){const e=this.inputs.attached.pointers;return!!e&&e.useNaturalPinchZoom}set useNaturalPinchZoom(e){const t=this.inputs.attached.pointers;t&&(t.useNaturalPinchZoom=e)}get panningSensibility(){const e=this.inputs.attached.pointers;return e?e.panningSensibility:0}set panningSensibility(e){const t=this.inputs.attached.pointers;t&&(t.panningSensibility=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get wheelPrecision(){const e=this.inputs.attached.mousewheel;return e?e.wheelPrecision:0}set wheelPrecision(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelPrecision=e)}get zoomToMouseLocation(){const e=this.inputs.attached.mousewheel;return!!e&&e.zoomToMouseLocation}set zoomToMouseLocation(e){const t=this.inputs.attached.mousewheel;t&&(t.zoomToMouseLocation=e)}get wheelDeltaPercentage(){const e=this.inputs.attached.mousewheel;return e?e.wheelDeltaPercentage:0}set wheelDeltaPercentage(e){const t=this.inputs.attached.mousewheel;t&&(t.wheelDeltaPercentage=e)}get bouncingBehavior(){return this._bouncingBehavior}get useBouncingBehavior(){return null!=this._bouncingBehavior}set useBouncingBehavior(e){e!==this.useBouncingBehavior&&(e?(this._bouncingBehavior=new Mi,this.addBehavior(this._bouncingBehavior)):this._bouncingBehavior&&(this.removeBehavior(this._bouncingBehavior),this._bouncingBehavior=null))}get framingBehavior(){return this._framingBehavior}get useFramingBehavior(){return null!=this._framingBehavior}set useFramingBehavior(e){e!==this.useFramingBehavior&&(e?(this._framingBehavior=new Ii,this.addBehavior(this._framingBehavior)):this._framingBehavior&&(this.removeBehavior(this._framingBehavior),this._framingBehavior=null))}get autoRotationBehavior(){return this._autoRotationBehavior}get useAutoRotationBehavior(){return null!=this._autoRotationBehavior}set useAutoRotationBehavior(e){e!==this.useAutoRotationBehavior&&(e?(this._autoRotationBehavior=new di,this.addBehavior(this._autoRotationBehavior)):this._autoRotationBehavior&&(this.removeBehavior(this._autoRotationBehavior),this._autoRotationBehavior=null))}constructor(e,t,s,i,r,n,a=!0){super(e,U.Zero(),n,a),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.lowerAlphaLimit=null,this.upperAlphaLimit=null,this.lowerBetaLimit=.01,this.upperBetaLimit=Math.PI-.01,this.lowerRadiusLimit=null,this.upperRadiusLimit=null,this.inertialPanningX=0,this.inertialPanningY=0,this.pinchToPanMaxDistance=20,this.panningDistanceLimit=null,this.panningOriginTarget=U.Zero(),this.panningInertia=.9,this.zoomOnFactor=1,this.targetScreenOffset=B.Zero(),this.allowUpsideDown=!0,this.useInputToRestoreState=!0,this.restoreStateInterpolationFactor=0,this._viewMatrix=new V,this.panningAxis=new U(1,1,0),this._transformedDirection=new U,this.mapPanning=!1,this._progressiveRestore=!1,this.onMeshTargetChangedObservable=new g,this.checkCollisions=!1,this.collisionRadius=new U(.5,.5,.5),this._previousPosition=U.Zero(),this._collisionVelocity=U.Zero(),this._newPosition=U.Zero(),this._computationVector=U.Zero(),this._onCollisionPositionChange=(e,t,s=null)=>{s?(this.setPosition(t),this.onCollide&&this.onCollide(s)):this._previousPosition.copyFrom(this._position);const i=Math.cos(this.alpha),r=Math.sin(this.alpha),n=Math.cos(this.beta);let a=Math.sin(this.beta);0===a&&(a=1e-4);const o=this._getTargetPosition();this._computationVector.copyFromFloats(this.radius*i*a,this.radius*n,this.radius*r*a),o.addToRef(this._computationVector,this._newPosition),this._position.copyFrom(this._newPosition);let h=this.upVector;this.allowUpsideDown&&this.beta<0&&(h=h.clone(),h=h.negate()),this._computeViewMatrix(this._position,o,h),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y),this._collisionTriggered=!1},this._target=U.Zero(),r&&this.setTarget(r),this.alpha=t,this.beta=s,this.radius=i,this.getViewMatrix(),this.inputs=new ki(this),this.inputs.addKeyboard().addMouseWheel().addPointers()}_initCache(){super._initCache(),this._cache._target=new U(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),this._cache.alpha=void 0,this._cache.beta=void 0,this._cache.radius=void 0,this._cache.targetScreenOffset=B.Zero()}_updateCache(e){e||super._updateCache(),this._cache._target.copyFrom(this._getTargetPosition()),this._cache.alpha=this.alpha,this._cache.beta=this.beta,this._cache.radius=this.radius,this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset)}_getTargetPosition(){if(this._targetHost&&this._targetHost.getAbsolutePosition){const e=this._targetHost.getAbsolutePosition();this._targetBoundingCenter?e.addToRef(this._targetBoundingCenter,this._target):this._target.copyFrom(e)}const e=this._getLockedTargetPosition();return e||this._target}storeState(){return this._storedAlpha=this.alpha,this._storedBeta=this.beta,this._storedRadius=this.radius,this._storedTarget=this._getTargetPosition().clone(),this._storedTargetScreenOffset=this.targetScreenOffset.clone(),super.storeState()}_restoreStateValues(){return this.hasStateStored()&&this.restoreStateInterpolationFactor>A&&this.restoreStateInterpolationFactor<1?(this._progressiveRestore=!0,this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0):!!super._restoreStateValues()&&(this.setTarget(this._storedTarget.clone()),this.alpha=this._storedAlpha,this.beta=this._storedBeta,this.radius=this._storedRadius,this.targetScreenOffset=this._storedTargetScreenOffset.clone(),this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0,!0)}_isSynchronizedViewMatrix(){return!!super._isSynchronizedViewMatrix()&&(this._cache._target.equals(this._getTargetPosition())&&this._cache.alpha===this.alpha&&this._cache.beta===this.beta&&this._cache.radius===this.radius&&this._cache.targetScreenOffset.equals(this.targetScreenOffset))}attachControl(e,t,s=!0,i=2){const r=arguments;t=Yt.BackCompatCameraNoPreventDefault(r),this._useCtrlForPanning=s,this._panningMouseButton=i,"boolean"==typeof r[0]&&(r.length>1&&(this._useCtrlForPanning=r[1]),r.length>2&&(this._panningMouseButton=r[2])),this.inputs.attachElement(t),this._reset=()=>{this.inertialAlphaOffset=0,this.inertialBetaOffset=0,this.inertialRadiusOffset=0,this.inertialPanningX=0,this.inertialPanningY=0}}detachControl(){this.inputs.detachElement(),this._reset&&this._reset()}_checkInputs(){if(!this._collisionTriggered){if(this.inputs.checkInputs(),this._progressiveRestore){const e=this._scene.getEngine().getDeltaTime()/1e3,t=1-Math.pow(2,-e/this.restoreStateInterpolationFactor);this.setTarget(U.Lerp(this.getTarget(),this._storedTarget,t)),G.RotationAlphaBetaGammaToRef(this._storedAlpha,this._storedBeta,0,z.Quaternion[0]),G.RotationAlphaBetaGammaToRef(this.alpha,this.beta,0,z.Quaternion[1]),G.SlerpToRef(z.Quaternion[1],z.Quaternion[0],t,z.Quaternion[2]),z.Quaternion[2].normalize(),z.Quaternion[2].toAlphaBetaGammaToRef(z.Vector3[0]),this.alpha=z.Vector3[0].x,this.beta=z.Vector3[0].y,this.radius+=(this._storedRadius-this.radius)*t,B.LerpToRef(this.targetScreenOffset,this._storedTargetScreenOffset,t,this.targetScreenOffset),(U.DistanceSquared(this.getTarget(),this._storedTarget)<A&&z.Quaternion[2].equalsWithEpsilon(z.Quaternion[0])&&Math.pow(this._storedRadius-this.radius,2)<A&&B.Distance(this.targetScreenOffset,this._storedTargetScreenOffset)<A||0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset||0!==this.inertialPanningX||0!==this.inertialPanningY)&&(this._progressiveRestore=!1)}if(0!==this.inertialAlphaOffset||0!==this.inertialBetaOffset||0!==this.inertialRadiusOffset){const e=this.invertRotation?-1:1,t=this._calculateHandednessMultiplier();let s=this.inertialAlphaOffset*t;this.beta<0&&(s*=-1),this.alpha+=s*e,this.beta+=this.inertialBetaOffset*e,this.radius-=this.inertialRadiusOffset,this.inertialAlphaOffset*=this.inertia,this.inertialBetaOffset*=this.inertia,this.inertialRadiusOffset*=this.inertia,Math.abs(this.inertialAlphaOffset)<A&&(this.inertialAlphaOffset=0),Math.abs(this.inertialBetaOffset)<A&&(this.inertialBetaOffset=0),Math.abs(this.inertialRadiusOffset)<this.speed*A&&(this.inertialRadiusOffset=0)}if(0!==this.inertialPanningX||0!==this.inertialPanningY){const e=new U(this.inertialPanningX,this.inertialPanningY,this.inertialPanningY);if(this._viewMatrix.invertToRef(this._cameraTransformMatrix),e.multiplyInPlace(this.panningAxis),U.TransformNormalToRef(e,this._cameraTransformMatrix,this._transformedDirection),this.mapPanning){const e=this.upVector,t=U.CrossToRef(this._transformedDirection,e,this._transformedDirection);U.CrossToRef(e,t,this._transformedDirection)}else this.panningAxis.y||(this._transformedDirection.y=0);if(!this._targetHost)if(this.panningDistanceLimit){this._transformedDirection.addInPlace(this._target);U.DistanceSquared(this._transformedDirection,this.panningOriginTarget)<=this.panningDistanceLimit*this.panningDistanceLimit&&this._target.copyFrom(this._transformedDirection)}else{if(this.parent){const e=z.Matrix[0];this.parent.getWorldMatrix().getRotationMatrixToRef(e),e.transposeToRef(e),U.TransformCoordinatesToRef(this._transformedDirection,e,this._transformedDirection)}this._target.addInPlace(this._transformedDirection)}this.inertialPanningX*=this.panningInertia,this.inertialPanningY*=this.panningInertia,Math.abs(this.inertialPanningX)<this.speed*A&&(this.inertialPanningX=0),Math.abs(this.inertialPanningY)<this.speed*A&&(this.inertialPanningY=0)}this._checkLimits(),super._checkInputs()}}_checkLimits(){null===this.lowerBetaLimit||void 0===this.lowerBetaLimit?this.allowUpsideDown&&this.beta>Math.PI&&(this.beta=this.beta-2*Math.PI):this.beta<this.lowerBetaLimit&&(this.beta=this.lowerBetaLimit),null===this.upperBetaLimit||void 0===this.upperBetaLimit?this.allowUpsideDown&&this.beta<-Math.PI&&(this.beta=this.beta+2*Math.PI):this.beta>this.upperBetaLimit&&(this.beta=this.upperBetaLimit),null!==this.lowerAlphaLimit&&this.alpha<this.lowerAlphaLimit&&(this.alpha=this.lowerAlphaLimit),null!==this.upperAlphaLimit&&this.alpha>this.upperAlphaLimit&&(this.alpha=this.upperAlphaLimit),null!==this.lowerRadiusLimit&&this.radius<this.lowerRadiusLimit&&(this.radius=this.lowerRadiusLimit,this.inertialRadiusOffset=0),null!==this.upperRadiusLimit&&this.radius>this.upperRadiusLimit&&(this.radius=this.upperRadiusLimit,this.inertialRadiusOffset=0)}rebuildAnglesAndRadius(){this._position.subtractToRef(this._getTargetPosition(),this._computationVector),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||U.TransformCoordinatesToRef(this._computationVector,this._upToYMatrix,this._computationVector),this.radius=this._computationVector.length(),0===this.radius&&(this.radius=1e-4);const e=this.alpha;0===this._computationVector.x&&0===this._computationVector.z?this.alpha=Math.PI/2:this.alpha=Math.acos(this._computationVector.x/Math.sqrt(Math.pow(this._computationVector.x,2)+Math.pow(this._computationVector.z,2))),this._computationVector.z<0&&(this.alpha=2*Math.PI-this.alpha);const t=Math.round((e-this.alpha)/(2*Math.PI));this.alpha+=2*t*Math.PI,this.beta=Math.acos(this._computationVector.y/this.radius),this._checkLimits()}setPosition(e){this._position.equals(e)||(this._position.copyFrom(e),this.rebuildAnglesAndRadius())}setTarget(e,t=!1,s=!1,i=!1){if(i=this.overrideCloneAlphaBetaRadius??i,e.computeWorldMatrix)t&&e.getBoundingInfo?this._targetBoundingCenter=e.getBoundingInfo().boundingBox.centerWorld.clone():this._targetBoundingCenter=null,e.computeWorldMatrix(),this._targetHost=e,this._target=this._getTargetPosition(),this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);else{const t=e,i=this._getTargetPosition();if(i&&!s&&i.equals(t))return;this._targetHost=null,this._target=t,this._targetBoundingCenter=null,this.onMeshTargetChangedObservable.notifyObservers(null)}i||this.rebuildAnglesAndRadius()}_getViewMatrix(){const e=Math.cos(this.alpha),t=Math.sin(this.alpha),s=Math.cos(this.beta);let i=Math.sin(this.beta);0===i&&(i=1e-4),0===this.radius&&(this.radius=1e-4);const r=this._getTargetPosition();if(this._computationVector.copyFromFloats(this.radius*e*i,this.radius*s,this.radius*t*i),0===this._upVector.x&&1===this._upVector.y&&0===this._upVector.z||U.TransformCoordinatesToRef(this._computationVector,this._yToUpMatrix,this._computationVector),r.addToRef(this._computationVector,this._newPosition),this.getScene().collisionsEnabled&&this.checkCollisions){const e=this.getScene().collisionCoordinator;this._collider||(this._collider=e.createCollider()),this._collider._radius=this.collisionRadius,this._newPosition.subtractToRef(this._position,this._collisionVelocity),this._collisionTriggered=!0,e.getNewPosition(this._position,this._collisionVelocity,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}else{this._position.copyFrom(this._newPosition);let e=this.upVector;this.allowUpsideDown&&i<0&&(e=e.negate()),this._computeViewMatrix(this._position,r,e),this._viewMatrix.addAtIndex(12,this.targetScreenOffset.x),this._viewMatrix.addAtIndex(13,this.targetScreenOffset.y)}return this._currentTarget=r,this._viewMatrix}zoomOn(e,t=!1){e=e||this.getScene().meshes;const s=oi.MinMax(e);let i=this._calculateLowerRadiusFromModelBoundingSphere(s.min,s.max);i=Math.max(Math.min(i,this.upperRadiusLimit||Number.MAX_VALUE),this.lowerRadiusLimit||0),this.radius=i*this.zoomOnFactor,this.focusOn({min:s.min,max:s.max,distance:i},t)}focusOn(e,t=!1){let s,i;if(void 0===e.min){const t=e||this.getScene().meshes;s=oi.MinMax(t),i=U.Distance(s.min,s.max)}else{s=e,i=e.distance}this._target=oi.Center(s),t||(this.maxZ=2*i)}createRigCamera(e,t){let s=0;switch(this.cameraRigMode){case ss.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ss.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ss.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ss.RIG_MODE_STEREOSCOPIC_INTERLACED:case ss.RIG_MODE_VR:s=this._cameraRigParams.stereoHalfAngle*(0===t?1:-1);break;case ss.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:s=this._cameraRigParams.stereoHalfAngle*(0===t?-1:1)}const i=new Gi(e,this.alpha+s,this.beta,this.radius,this._target,this.getScene());return i._cameraRigParams={},i.isRigCamera=!0,i.rigParent=this,i.upVector=this.upVector,i.mode=this.mode,i.orthoLeft=this.orthoLeft,i.orthoRight=this.orthoRight,i.orthoBottom=this.orthoBottom,i.orthoTop=this.orthoTop,i}_updateRigCameras(){const e=this._rigCameras[0],t=this._rigCameras[1];switch(e.beta=t.beta=this.beta,this.cameraRigMode){case ss.RIG_MODE_STEREOSCOPIC_ANAGLYPH:case ss.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:case ss.RIG_MODE_STEREOSCOPIC_OVERUNDER:case ss.RIG_MODE_STEREOSCOPIC_INTERLACED:case ss.RIG_MODE_VR:e.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle;break;case ss.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:e.alpha=this.alpha+this._cameraRigParams.stereoHalfAngle,t.alpha=this.alpha-this._cameraRigParams.stereoHalfAngle}super._updateRigCameras()}_calculateLowerRadiusFromModelBoundingSphere(e,t,s=1){const i=U.Distance(e,t),r=this.getScene().getEngine().getAspectRatio(this),n=Math.tan(this.fov/2),a=n*r,o=.5*i*s,h=o*Math.sqrt(1+1/(a*a)),l=o*Math.sqrt(1+1/(n*n));return Math.max(h,l)}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"ArcRotateCamera"}}e([a()],Gi.prototype,"alpha",void 0),e([a()],Gi.prototype,"beta",void 0),e([a()],Gi.prototype,"radius",void 0),e([a()],Gi.prototype,"overrideCloneAlphaBetaRadius",void 0),e([c("target")],Gi.prototype,"_target",void 0),e([u("targetHost")],Gi.prototype,"_targetHost",void 0),e([a()],Gi.prototype,"inertialAlphaOffset",void 0),e([a()],Gi.prototype,"inertialBetaOffset",void 0),e([a()],Gi.prototype,"inertialRadiusOffset",void 0),e([a()],Gi.prototype,"lowerAlphaLimit",void 0),e([a()],Gi.prototype,"upperAlphaLimit",void 0),e([a()],Gi.prototype,"lowerBetaLimit",void 0),e([a()],Gi.prototype,"upperBetaLimit",void 0),e([a()],Gi.prototype,"lowerRadiusLimit",void 0),e([a()],Gi.prototype,"upperRadiusLimit",void 0),e([a()],Gi.prototype,"inertialPanningX",void 0),e([a()],Gi.prototype,"inertialPanningY",void 0),e([a()],Gi.prototype,"pinchToPanMaxDistance",void 0),e([a()],Gi.prototype,"panningDistanceLimit",void 0),e([c()],Gi.prototype,"panningOriginTarget",void 0),e([a()],Gi.prototype,"panningInertia",void 0),e([a()],Gi.prototype,"zoomToMouseLocation",null),e([a()],Gi.prototype,"zoomOnFactor",void 0),e([l()],Gi.prototype,"targetScreenOffset",void 0),e([a()],Gi.prototype,"allowUpsideDown",void 0),e([a()],Gi.prototype,"useInputToRestoreState",void 0),e([a()],Gi.prototype,"restoreStateInterpolationFactor",void 0),I("BABYLON.ArcRotateCamera",Gi);class Vi extends ae{get range(){return this._range}set range(e){this._range=e,this._inverseSquaredRange=1/(this.range*this.range)}get intensityMode(){return this._intensityMode}set intensityMode(e){this._intensityMode=e,this._computePhotometricScale()}get radius(){return this._radius}set radius(e){this._radius=e,this._computePhotometricScale()}get shadowEnabled(){return this._shadowEnabled}set shadowEnabled(e){this._shadowEnabled!==e&&(this._shadowEnabled=e,this._markMeshesAsLightDirty())}get includedOnlyMeshes(){return this._includedOnlyMeshes}set includedOnlyMeshes(e){this._includedOnlyMeshes=e,this._hookArrayForIncludedOnly(e)}get excludedMeshes(){return this._excludedMeshes}set excludedMeshes(e){this._excludedMeshes=e,this._hookArrayForExcluded(e)}get excludeWithLayerMask(){return this._excludeWithLayerMask}set excludeWithLayerMask(e){this._excludeWithLayerMask=e,this._resyncMeshes()}get includeOnlyWithLayerMask(){return this._includeOnlyWithLayerMask}set includeOnlyWithLayerMask(e){this._includeOnlyWithLayerMask=e,this._resyncMeshes()}get lightmapMode(){return this._lightmapMode}set lightmapMode(e){this._lightmapMode!==e&&(this._lightmapMode=e,this._markMeshesAsLightDirty())}getViewMatrix(e){return null}getProjectionMatrix(e,t){return null}constructor(e,t){super(e,t,!1),this.diffuse=new ee(1,1,1),this.specular=new ee(1,1,1),this.falloffType=Vi.FALLOFF_DEFAULT,this.intensity=1,this._range=Number.MAX_VALUE,this._inverseSquaredRange=0,this._photometricScale=1,this._intensityMode=Vi.INTENSITYMODE_AUTOMATIC,this._radius=1e-5,this.renderPriority=0,this._shadowEnabled=!0,this._excludeWithLayerMask=0,this._includeOnlyWithLayerMask=0,this._lightmapMode=0,this._shadowGenerators=null,this._excludedMeshesIds=new Array,this._includedOnlyMeshesIds=new Array,this._isLight=!0,this.getScene().addLight(this),this._uniformBuffer=new Ls(this.getScene().getEngine(),void 0,void 0,e),this._buildUniformLayout(),this.includedOnlyMeshes=[],this.excludedMeshes=[],this._resyncMeshes()}transferTexturesToEffect(e,t){return this}_bindLight(e,t,s,i,r=!0){const n=e.toString();let a=!1;if(this._uniformBuffer.bindToEffect(s,"Light"+n),this._renderId!==t.getRenderId()||this._lastUseSpecular!==i||!this._uniformBuffer.useUbo){this._renderId=t.getRenderId(),this._lastUseSpecular=i;const e=this.getScaledIntensity();this.transferToEffect(s,n),this.diffuse.scaleToRef(e,se.Color3[0]),this._uniformBuffer.updateColor4("vLightDiffuse",se.Color3[0],this.range,n),i&&(this.specular.scaleToRef(e,se.Color3[1]),this._uniformBuffer.updateColor4("vLightSpecular",se.Color3[1],this.radius,n)),a=!0}if(this.transferTexturesToEffect(s,n),t.shadowsEnabled&&this.shadowEnabled&&r){const e=this.getShadowGenerator(t.activeCamera)??this.getShadowGenerator();e&&(e.bindShadowLight(n,s),a=!0)}a?this._uniformBuffer.update():this._uniformBuffer.bindUniformBuffer()}getClassName(){return"Light"}toString(e){let t="Name: "+this.name;if(t+=", type: "+["Point","Directional","Spot","Hemispheric"][this.getTypeID()],this.animations)for(let s=0;s<this.animations.length;s++)t+=", animation[0]: "+this.animations[s].toString(e);return t}_syncParentEnabledState(){super._syncParentEnabledState(),this.isDisposed()||this._resyncMeshes()}setEnabled(e){super.setEnabled(e),this._resyncMeshes()}getShadowGenerator(e=null){return null===this._shadowGenerators?null:this._shadowGenerators.get(e)??null}getShadowGenerators(){return this._shadowGenerators}getAbsolutePosition(){return U.Zero()}canAffectMesh(e){return!e||!(this.includedOnlyMeshes&&this.includedOnlyMeshes.length>0&&-1===this.includedOnlyMeshes.indexOf(e))&&(!(this.excludedMeshes&&this.excludedMeshes.length>0&&-1!==this.excludedMeshes.indexOf(e))&&(!!(0===this.includeOnlyWithLayerMask||this.includeOnlyWithLayerMask&e.layerMask)&&!(0!==this.excludeWithLayerMask&&this.excludeWithLayerMask&e.layerMask)))}dispose(e,t=!1){if(this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next()){t.value.dispose()}this._shadowGenerators=null}if(this.getScene().stopAnimation(this),this._parentContainer){const e=this._parentContainer.lights.indexOf(this);e>-1&&this._parentContainer.lights.splice(e,1),this._parentContainer=null}for(const e of this.getScene().meshes)e._removeLightSource(this,!0);this._uniformBuffer.dispose(),this.getScene().removeLight(this),super.dispose(e,t)}getTypeID(){return 0}getScaledIntensity(){return this._photometricScale*this.intensity}clone(e,t=null){const s=Vi.GetConstructorFromName(this.getTypeID(),e,this.getScene());if(!s)return null;const i=re.Clone(s,this);return e&&(i.name=e),t&&(i.parent=t),i.setEnabled(this.isEnabled()),this.onClonedObservable.notifyObservers(i),i}serialize(){const e=re.Serialize(this);return e.uniqueId=this.uniqueId,e.type=this.getTypeID(),this.parent&&this.parent._serializeAsParent(e),this.excludedMeshes.length>0&&(e.excludedMeshesIds=[],this.excludedMeshes.forEach((t=>{e.excludedMeshesIds.push(t.id)}))),this.includedOnlyMeshes.length>0&&(e.includedOnlyMeshesIds=[],this.includedOnlyMeshes.forEach((t=>{e.includedOnlyMeshesIds.push(t.id)}))),re.AppendSerializedAnimations(this,e),e.ranges=this.serializeAnimationRanges(),e.isEnabled=this.isEnabled(),e}static GetConstructorFromName(e,t,s){const i=ae.Construct("Light_Type_"+e,t,s);return i||null}static Parse(e,t){const s=Vi.GetConstructorFromName(e.type,e.name,t);if(!s)return null;const i=re.Parse(s,e,t);if(e.excludedMeshesIds&&(i._excludedMeshesIds=e.excludedMeshesIds),e.includedOnlyMeshesIds&&(i._includedOnlyMeshesIds=e.includedOnlyMeshesIds),void 0!==e.parentId&&(i._waitingParentId=e.parentId),void 0!==e.parentInstanceIndex&&(i._waitingParentInstanceIndex=e.parentInstanceIndex),void 0!==e.falloffType&&(i.falloffType=e.falloffType),void 0!==e.lightmapMode&&(i.lightmapMode=e.lightmapMode),e.animations){for(let t=0;t<e.animations.length;t++){const s=e.animations[t],r=S("BABYLON.Animation");r&&i.animations.push(r.Parse(s))}ae.ParseAnimationRanges(i,e,t)}return e.autoAnimate&&t.beginAnimation(i,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1),void 0!==e.isEnabled&&i.setEnabled(e.isEnabled),i}_hookArrayForExcluded(e){const t=e.push;e.push=(...s)=>{const i=t.apply(e,s);for(const e of s)e._resyncLightSource(this);return i};const s=e.splice;e.splice=(t,i)=>{const r=s.apply(e,[t,i]);for(const e of r)e._resyncLightSource(this);return r};for(const t of e)t._resyncLightSource(this)}_hookArrayForIncludedOnly(e){const t=e.push;e.push=(...s)=>{const i=t.apply(e,s);return this._resyncMeshes(),i};const s=e.splice;e.splice=(t,i)=>{const r=s.apply(e,[t,i]);return this._resyncMeshes(),r},this._resyncMeshes()}_resyncMeshes(){for(const e of this.getScene().meshes)e._resyncLightSource(this)}_markMeshesAsLightDirty(){for(const e of this.getScene().meshes)-1!==e.lightSources.indexOf(this)&&e._markSubMeshesAsLightDirty()}_computePhotometricScale(){this._photometricScale=this._getPhotometricScale(),this.getScene().resetCachedMaterial()}_getPhotometricScale(){let e=0;const t=this.getTypeID();let s=this.intensityMode;switch(s===Vi.INTENSITYMODE_AUTOMATIC&&(s=t===Vi.LIGHTTYPEID_DIRECTIONALLIGHT?Vi.INTENSITYMODE_ILLUMINANCE:Vi.INTENSITYMODE_LUMINOUSINTENSITY),t){case Vi.LIGHTTYPEID_POINTLIGHT:case Vi.LIGHTTYPEID_SPOTLIGHT:switch(s){case Vi.INTENSITYMODE_LUMINOUSPOWER:e=1/(4*Math.PI);break;case Vi.INTENSITYMODE_LUMINOUSINTENSITY:e=1;break;case Vi.INTENSITYMODE_LUMINANCE:e=this.radius*this.radius}break;case Vi.LIGHTTYPEID_DIRECTIONALLIGHT:switch(s){case Vi.INTENSITYMODE_ILLUMINANCE:e=1;break;case Vi.INTENSITYMODE_LUMINANCE:{let t=this.radius;t=Math.max(t,.001);e=2*Math.PI*(1-Math.cos(t));break}}break;case Vi.LIGHTTYPEID_HEMISPHERICLIGHT:e=1}return e}_reorderLightsInScene(){const e=this.getScene();0!=this._renderPriority&&(e.requireLightSorting=!0),this.getScene().sortLightsByPriority()}}Vi.FALLOFF_DEFAULT=Hs.FALLOFF_DEFAULT,Vi.FALLOFF_PHYSICAL=Hs.FALLOFF_PHYSICAL,Vi.FALLOFF_GLTF=Hs.FALLOFF_GLTF,Vi.FALLOFF_STANDARD=Hs.FALLOFF_STANDARD,Vi.LIGHTMAP_DEFAULT=Hs.LIGHTMAP_DEFAULT,Vi.LIGHTMAP_SPECULAR=Hs.LIGHTMAP_SPECULAR,Vi.LIGHTMAP_SHADOWSONLY=Hs.LIGHTMAP_SHADOWSONLY,Vi.INTENSITYMODE_AUTOMATIC=Hs.INTENSITYMODE_AUTOMATIC,Vi.INTENSITYMODE_LUMINOUSPOWER=Hs.INTENSITYMODE_LUMINOUSPOWER,Vi.INTENSITYMODE_LUMINOUSINTENSITY=Hs.INTENSITYMODE_LUMINOUSINTENSITY,Vi.INTENSITYMODE_ILLUMINANCE=Hs.INTENSITYMODE_ILLUMINANCE,Vi.INTENSITYMODE_LUMINANCE=Hs.INTENSITYMODE_LUMINANCE,Vi.LIGHTTYPEID_POINTLIGHT=Hs.LIGHTTYPEID_POINTLIGHT,Vi.LIGHTTYPEID_DIRECTIONALLIGHT=Hs.LIGHTTYPEID_DIRECTIONALLIGHT,Vi.LIGHTTYPEID_SPOTLIGHT=Hs.LIGHTTYPEID_SPOTLIGHT,Vi.LIGHTTYPEID_HEMISPHERICLIGHT=Hs.LIGHTTYPEID_HEMISPHERICLIGHT,e([h()],Vi.prototype,"diffuse",void 0),e([h()],Vi.prototype,"specular",void 0),e([a()],Vi.prototype,"falloffType",void 0),e([a()],Vi.prototype,"intensity",void 0),e([a()],Vi.prototype,"range",null),e([a()],Vi.prototype,"intensityMode",null),e([a()],Vi.prototype,"radius",null),e([a()],Vi.prototype,"_renderPriority",void 0),e([n("_reorderLightsInScene")],Vi.prototype,"renderPriority",void 0),e([a("shadowEnabled")],Vi.prototype,"_shadowEnabled",void 0),e([a("excludeWithLayerMask")],Vi.prototype,"_excludeWithLayerMask",void 0),e([a("includeOnlyWithLayerMask")],Vi.prototype,"_includeOnlyWithLayerMask",void 0),e([a("lightmapMode")],Vi.prototype,"_lightmapMode",void 0),ae.AddNodeConstructor("Light_Type_3",((e,t)=>()=>new Hi(e,U.Zero(),t)));class Hi extends Vi{constructor(e,t,s){super(e,s),this.groundColor=new ee(0,0,0),this.direction=t||U.Up()}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightGround",3),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}getClassName(){return"HemisphericLight"}setDirectionToTarget(e){return this.direction=U.Normalize(e.subtract(U.Zero())),this.direction}getShadowGenerator(){return null}transferToEffect(e,t){const s=U.Normalize(this.direction);return this._uniformBuffer.updateFloat4("vLightData",s.x,s.y,s.z,0,t),this._uniformBuffer.updateColor3("vLightGround",this.groundColor.scale(this.intensity),t),this}transferToNodeMaterialEffect(e,t){const s=U.Normalize(this.direction);return e.setFloat3(t,s.x,s.y,s.z),this}computeWorldMatrix(){return this._worldMatrix||(this._worldMatrix=V.Identity()),this._worldMatrix}getTypeID(){return Vi.LIGHTTYPEID_HEMISPHERICLIGHT}prepareLightSpecificDefines(e,t){e["HEMILIGHT"+t]=!0}}e([h()],Hi.prototype,"groundColor",void 0),e([c()],Hi.prototype,"direction",void 0),I("BABYLON.HemisphericLight",Hi);class zi{constructor(){this._count=0,this._data={}}copyFrom(e){this.clear(),e.forEach(((e,t)=>this.add(e,t)))}get(e){const t=this._data[e];if(void 0!==t)return t}getOrAddWithFactory(e,t){let s=this.get(e);return void 0!==s||(s=t(e),s&&this.add(e,s)),s}getOrAdd(e,t){const s=this.get(e);return void 0!==s?s:(this.add(e,t),t)}contains(e){return void 0!==this._data[e]}add(e,t){return void 0===this._data[e]&&(this._data[e]=t,++this._count,!0)}set(e,t){return void 0!==this._data[e]&&(this._data[e]=t,!0)}getAndRemove(e){const t=this.get(e);return void 0!==t?(delete this._data[e],--this._count,t):null}remove(e){return!!this.contains(e)&&(delete this._data[e],--this._count,!0)}clear(){this._data={},this._count=0}get count(){return this._count}forEach(e){for(const t in this._data){e(t,this._data[t])}}first(e){for(const t in this._data){const s=e(t,this._data[t]);if(s)return s}return null}}class Xi{constructor(){this.rootNodes=[],this.cameras=[],this.lights=[],this.meshes=[],this.skeletons=[],this.particleSystems=[],this.animations=[],this.animationGroups=[],this.multiMaterials=[],this.materials=[],this.morphTargetManagers=[],this.geometries=[],this.transformNodes=[],this.actionManagers=[],this.textures=[],this._environmentTexture=null,this.postProcesses=[]}static AddParser(e,t){this._BabylonFileParsers[e]=t}static GetParser(e){return this._BabylonFileParsers[e]?this._BabylonFileParsers[e]:null}static AddIndividualParser(e,t){this._IndividualBabylonFileParsers[e]=t}static GetIndividualParser(e){return this._IndividualBabylonFileParsers[e]?this._IndividualBabylonFileParsers[e]:null}static Parse(e,t,s,i){for(const r in this._BabylonFileParsers)Object.prototype.hasOwnProperty.call(this._BabylonFileParsers,r)&&this._BabylonFileParsers[r](e,t,s,i)}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture=e}getNodes(){let e=[];return e=e.concat(this.meshes),e=e.concat(this.lights),e=e.concat(this.cameras),e=e.concat(this.transformNodes),this.skeletons.forEach((t=>e=e.concat(t.bones))),e}}function Wi(e){e.push("vCameraColorCurveNeutral","vCameraColorCurvePositive","vCameraColorCurveNegative")}Xi._BabylonFileParsers={},Xi._IndividualBabylonFileParsers={},I("BABYLON.AbstractScene",Xi);class Yi{constructor(){this._dirty=!0,this._tempColor=new te(0,0,0,0),this._globalCurve=new te(0,0,0,0),this._highlightsCurve=new te(0,0,0,0),this._midtonesCurve=new te(0,0,0,0),this._shadowsCurve=new te(0,0,0,0),this._positiveCurve=new te(0,0,0,0),this._negativeCurve=new te(0,0,0,0),this._globalHue=30,this._globalDensity=0,this._globalSaturation=0,this._globalExposure=0,this._highlightsHue=30,this._highlightsDensity=0,this._highlightsSaturation=0,this._highlightsExposure=0,this._midtonesHue=30,this._midtonesDensity=0,this._midtonesSaturation=0,this._midtonesExposure=0,this._shadowsHue=30,this._shadowsDensity=0,this._shadowsSaturation=0,this._shadowsExposure=0}get globalHue(){return this._globalHue}set globalHue(e){this._globalHue=e,this._dirty=!0}get globalDensity(){return this._globalDensity}set globalDensity(e){this._globalDensity=e,this._dirty=!0}get globalSaturation(){return this._globalSaturation}set globalSaturation(e){this._globalSaturation=e,this._dirty=!0}get globalExposure(){return this._globalExposure}set globalExposure(e){this._globalExposure=e,this._dirty=!0}get highlightsHue(){return this._highlightsHue}set highlightsHue(e){this._highlightsHue=e,this._dirty=!0}get highlightsDensity(){return this._highlightsDensity}set highlightsDensity(e){this._highlightsDensity=e,this._dirty=!0}get highlightsSaturation(){return this._highlightsSaturation}set highlightsSaturation(e){this._highlightsSaturation=e,this._dirty=!0}get highlightsExposure(){return this._highlightsExposure}set highlightsExposure(e){this._highlightsExposure=e,this._dirty=!0}get midtonesHue(){return this._midtonesHue}set midtonesHue(e){this._midtonesHue=e,this._dirty=!0}get midtonesDensity(){return this._midtonesDensity}set midtonesDensity(e){this._midtonesDensity=e,this._dirty=!0}get midtonesSaturation(){return this._midtonesSaturation}set midtonesSaturation(e){this._midtonesSaturation=e,this._dirty=!0}get midtonesExposure(){return this._midtonesExposure}set midtonesExposure(e){this._midtonesExposure=e,this._dirty=!0}get shadowsHue(){return this._shadowsHue}set shadowsHue(e){this._shadowsHue=e,this._dirty=!0}get shadowsDensity(){return this._shadowsDensity}set shadowsDensity(e){this._shadowsDensity=e,this._dirty=!0}get shadowsSaturation(){return this._shadowsSaturation}set shadowsSaturation(e){this._shadowsSaturation=e,this._dirty=!0}get shadowsExposure(){return this._shadowsExposure}set shadowsExposure(e){this._shadowsExposure=e,this._dirty=!0}getClassName(){return"ColorCurves"}static Bind(e,t,s="vCameraColorCurvePositive",i="vCameraColorCurveNeutral",r="vCameraColorCurveNegative"){e._dirty&&(e._dirty=!1,e._getColorGradingDataToRef(e._globalHue,e._globalDensity,e._globalSaturation,e._globalExposure,e._globalCurve),e._getColorGradingDataToRef(e._highlightsHue,e._highlightsDensity,e._highlightsSaturation,e._highlightsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._highlightsCurve),e._getColorGradingDataToRef(e._midtonesHue,e._midtonesDensity,e._midtonesSaturation,e._midtonesExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._midtonesCurve),e._getColorGradingDataToRef(e._shadowsHue,e._shadowsDensity,e._shadowsSaturation,e._shadowsExposure,e._tempColor),e._tempColor.multiplyToRef(e._globalCurve,e._shadowsCurve),e._highlightsCurve.subtractToRef(e._midtonesCurve,e._positiveCurve),e._midtonesCurve.subtractToRef(e._shadowsCurve,e._negativeCurve)),t&&(t.setFloat4(s,e._positiveCurve.r,e._positiveCurve.g,e._positiveCurve.b,e._positiveCurve.a),t.setFloat4(i,e._midtonesCurve.r,e._midtonesCurve.g,e._midtonesCurve.b,e._midtonesCurve.a),t.setFloat4(r,e._negativeCurve.r,e._negativeCurve.g,e._negativeCurve.b,e._negativeCurve.a))}_getColorGradingDataToRef(e,t,s,i,r){null!=e&&(e=Yi._Clamp(e,0,360),t=Yi._Clamp(t,-100,100),s=Yi._Clamp(s,-100,100),i=Yi._Clamp(i,-100,100),t=Yi._ApplyColorGradingSliderNonlinear(t),t*=.5,i=Yi._ApplyColorGradingSliderNonlinear(i),t<0&&(t*=-1,e=(e+180)%360),Yi._FromHSBToRef(e,t,50+.25*i,r),r.scaleToRef(2,r),r.a=1+.01*s)}static _ApplyColorGradingSliderNonlinear(e){e/=100;let t=Math.abs(e);return t=Math.pow(t,2),e<0&&(t*=-1),t*=100,t}static _FromHSBToRef(e,t,s,i){let r=Yi._Clamp(e,0,360);const n=Yi._Clamp(t/100,0,1),a=Yi._Clamp(s/100,0,1);if(0===n)i.r=a,i.g=a,i.b=a;else{r/=60;const e=Math.floor(r),t=r-e,s=a*(1-n),o=a*(1-n*t),h=a*(1-n*(1-t));switch(e){case 0:i.r=a,i.g=h,i.b=s;break;case 1:i.r=o,i.g=a,i.b=s;break;case 2:i.r=s,i.g=a,i.b=h;break;case 3:i.r=s,i.g=o,i.b=a;break;case 4:i.r=h,i.g=s,i.b=a;break;default:i.r=a,i.g=s,i.b=o}}i.a=1}static _Clamp(e,t,s){return Math.min(Math.max(e,t),s)}clone(){return re.Clone((()=>new Yi),this)}serialize(){return re.Serialize(this)}static Parse(e){return re.Parse((()=>new Yi),e,null,null)}}Yi.PrepareUniforms=Wi,e([a()],Yi.prototype,"_globalHue",void 0),e([a()],Yi.prototype,"_globalDensity",void 0),e([a()],Yi.prototype,"_globalSaturation",void 0),e([a()],Yi.prototype,"_globalExposure",void 0),e([a()],Yi.prototype,"_highlightsHue",void 0),e([a()],Yi.prototype,"_highlightsDensity",void 0),e([a()],Yi.prototype,"_highlightsSaturation",void 0),e([a()],Yi.prototype,"_highlightsExposure",void 0),e([a()],Yi.prototype,"_midtonesHue",void 0),e([a()],Yi.prototype,"_midtonesDensity",void 0),e([a()],Yi.prototype,"_midtonesSaturation",void 0),e([a()],Yi.prototype,"_midtonesExposure",void 0),re._ColorCurvesParser=Yi.Parse;class Ki{constructor(){this.colorCurves=new Yi,this._colorCurvesEnabled=!1,this._colorGradingEnabled=!1,this._colorGradingWithGreenDepth=!0,this._colorGradingBGR=!0,this._exposure=1,this._toneMappingEnabled=!1,this._toneMappingType=Ki.TONEMAPPING_STANDARD,this._contrast=1,this.vignetteStretch=0,this.vignetteCenterX=0,this.vignetteCenterY=0,this.vignetteWeight=1.5,this.vignetteColor=new te(0,0,0,0),this.vignetteCameraFov=.5,this._vignetteBlendMode=Ki.VIGNETTEMODE_MULTIPLY,this._vignetteEnabled=!1,this._ditheringEnabled=!1,this._ditheringIntensity=1/255,this._skipFinalColorClamp=!1,this._applyByPostProcess=!1,this._isEnabled=!0,this.onUpdateParameters=new g}get colorCurvesEnabled(){return this._colorCurvesEnabled}set colorCurvesEnabled(e){this._colorCurvesEnabled!==e&&(this._colorCurvesEnabled=e,this._updateParameters())}get colorGradingTexture(){return this._colorGradingTexture}set colorGradingTexture(e){this._colorGradingTexture!==e&&(this._colorGradingTexture=e,this._updateParameters())}get colorGradingEnabled(){return this._colorGradingEnabled}set colorGradingEnabled(e){this._colorGradingEnabled!==e&&(this._colorGradingEnabled=e,this._updateParameters())}get colorGradingWithGreenDepth(){return this._colorGradingWithGreenDepth}set colorGradingWithGreenDepth(e){this._colorGradingWithGreenDepth!==e&&(this._colorGradingWithGreenDepth=e,this._updateParameters())}get colorGradingBGR(){return this._colorGradingBGR}set colorGradingBGR(e){this._colorGradingBGR!==e&&(this._colorGradingBGR=e,this._updateParameters())}get exposure(){return this._exposure}set exposure(e){this._exposure!==e&&(this._exposure=e,this._updateParameters())}get toneMappingEnabled(){return this._toneMappingEnabled}set toneMappingEnabled(e){this._toneMappingEnabled!==e&&(this._toneMappingEnabled=e,this._updateParameters())}get toneMappingType(){return this._toneMappingType}set toneMappingType(e){this._toneMappingType!==e&&(this._toneMappingType=e,this._updateParameters())}get contrast(){return this._contrast}set contrast(e){this._contrast!==e&&(this._contrast=e,this._updateParameters())}get vignetteCentreY(){return this.vignetteCenterY}set vignetteCentreY(e){this.vignetteCenterY=e}get vignetteCentreX(){return this.vignetteCenterX}set vignetteCentreX(e){this.vignetteCenterX=e}get vignetteBlendMode(){return this._vignetteBlendMode}set vignetteBlendMode(e){this._vignetteBlendMode!==e&&(this._vignetteBlendMode=e,this._updateParameters())}get vignetteEnabled(){return this._vignetteEnabled}set vignetteEnabled(e){this._vignetteEnabled!==e&&(this._vignetteEnabled=e,this._updateParameters())}get ditheringEnabled(){return this._ditheringEnabled}set ditheringEnabled(e){this._ditheringEnabled!==e&&(this._ditheringEnabled=e,this._updateParameters())}get ditheringIntensity(){return this._ditheringIntensity}set ditheringIntensity(e){this._ditheringIntensity!==e&&(this._ditheringIntensity=e,this._updateParameters())}get skipFinalColorClamp(){return this._skipFinalColorClamp}set skipFinalColorClamp(e){this._skipFinalColorClamp!==e&&(this._skipFinalColorClamp=e,this._updateParameters())}get applyByPostProcess(){return this._applyByPostProcess}set applyByPostProcess(e){this._applyByPostProcess!==e&&(this._applyByPostProcess=e,this._updateParameters())}get isEnabled(){return this._isEnabled}set isEnabled(e){this._isEnabled!==e&&(this._isEnabled=e,this._updateParameters())}_updateParameters(){this.onUpdateParameters.notifyObservers(this)}getClassName(){return"ImageProcessingConfiguration"}prepareDefines(e,t=!1){if(t!==this.applyByPostProcess||!this._isEnabled)return e.VIGNETTE=!1,e.TONEMAPPING=0,e.CONTRAST=!1,e.EXPOSURE=!1,e.COLORCURVES=!1,e.COLORGRADING=!1,e.COLORGRADING3D=!1,e.DITHER=!1,e.IMAGEPROCESSING=!1,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,void(e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess&&this._isEnabled);if(e.VIGNETTE=this.vignetteEnabled,e.VIGNETTEBLENDMODEMULTIPLY=this.vignetteBlendMode===Ki._VIGNETTEMODE_MULTIPLY,e.VIGNETTEBLENDMODEOPAQUE=!e.VIGNETTEBLENDMODEMULTIPLY,this._toneMappingEnabled)switch(this._toneMappingType){case Ki.TONEMAPPING_KHR_PBR_NEUTRAL:e.TONEMAPPING=3;break;case Ki.TONEMAPPING_ACES:e.TONEMAPPING=2;break;default:e.TONEMAPPING=1}else e.TONEMAPPING=0;e.CONTRAST=1!==this.contrast,e.EXPOSURE=1!==this.exposure,e.COLORCURVES=this.colorCurvesEnabled&&!!this.colorCurves,e.COLORGRADING=this.colorGradingEnabled&&!!this.colorGradingTexture,e.COLORGRADING?e.COLORGRADING3D=this.colorGradingTexture.is3D:e.COLORGRADING3D=!1,e.SAMPLER3DGREENDEPTH=this.colorGradingWithGreenDepth,e.SAMPLER3DBGRMAP=this.colorGradingBGR,e.DITHER=this._ditheringEnabled,e.IMAGEPROCESSINGPOSTPROCESS=this.applyByPostProcess,e.SKIPFINALCOLORCLAMP=this.skipFinalColorClamp,e.IMAGEPROCESSING=e.VIGNETTE||!!e.TONEMAPPING||e.CONTRAST||e.EXPOSURE||e.COLORCURVES||e.COLORGRADING||e.DITHER}isReady(){return!this.colorGradingEnabled||!this.colorGradingTexture||this.colorGradingTexture.isReady()}bind(e,t){if(this._colorCurvesEnabled&&this.colorCurves&&Yi.Bind(this.colorCurves,e),this._vignetteEnabled||this._ditheringEnabled){const s=1/e.getEngine().getRenderWidth(),i=1/e.getEngine().getRenderHeight();if(e.setFloat2("vInverseScreenSize",s,i),this._ditheringEnabled&&e.setFloat("ditherIntensity",.5*this._ditheringIntensity),this._vignetteEnabled){const r=null!=t?t:i/s;let n=Math.tan(.5*this.vignetteCameraFov),a=n*r;const o=Math.sqrt(a*n);a=Vt(a,o,this.vignetteStretch),n=Vt(n,o,this.vignetteStretch),e.setFloat4("vignetteSettings1",a,n,-a*this.vignetteCenterX,-n*this.vignetteCenterY);const h=-2*this.vignetteWeight;e.setFloat4("vignetteSettings2",this.vignetteColor.r,this.vignetteColor.g,this.vignetteColor.b,h)}}if(e.setFloat("exposureLinear",this.exposure),e.setFloat("contrast",this.contrast),this.colorGradingTexture){e.setTexture("txColorTransform",this.colorGradingTexture);const t=this.colorGradingTexture.getSize().height;e.setFloat4("colorTransformSettings",(t-1)/t,.5/t,t,this.colorGradingTexture.level)}}clone(){return re.Clone((()=>new Ki),this)}serialize(){return re.Serialize(this)}static Parse(e){const t=re.Parse((()=>new Ki),e,null,null);return void 0!==e.vignetteCentreX&&(t.vignetteCenterX=e.vignetteCentreX),void 0!==e.vignetteCentreY&&(t.vignetteCenterY=e.vignetteCentreY),t}static get VIGNETTEMODE_MULTIPLY(){return this._VIGNETTEMODE_MULTIPLY}static get VIGNETTEMODE_OPAQUE(){return this._VIGNETTEMODE_OPAQUE}}Ki.TONEMAPPING_STANDARD=0,Ki.TONEMAPPING_ACES=1,Ki.TONEMAPPING_KHR_PBR_NEUTRAL=2,Ki.PrepareUniforms=function(e,t){t.EXPOSURE&&e.push("exposureLinear"),t.CONTRAST&&e.push("contrast"),t.COLORGRADING&&e.push("colorTransformSettings"),(t.VIGNETTE||t.DITHER)&&e.push("vInverseScreenSize"),t.VIGNETTE&&(e.push("vignetteSettings1"),e.push("vignetteSettings2")),t.COLORCURVES&&Wi(e),t.DITHER&&e.push("ditherIntensity")},Ki.PrepareSamplers=function(e,t){t.COLORGRADING&&e.push("txColorTransform")},Ki._VIGNETTEMODE_MULTIPLY=0,Ki._VIGNETTEMODE_OPAQUE=1,e([function(e){return r(7,e)}()],Ki.prototype,"colorCurves",void 0),e([a()],Ki.prototype,"_colorCurvesEnabled",void 0),e([o("colorGradingTexture")],Ki.prototype,"_colorGradingTexture",void 0),e([a()],Ki.prototype,"_colorGradingEnabled",void 0),e([a()],Ki.prototype,"_colorGradingWithGreenDepth",void 0),e([a()],Ki.prototype,"_colorGradingBGR",void 0),e([a()],Ki.prototype,"_exposure",void 0),e([a()],Ki.prototype,"_toneMappingEnabled",void 0),e([a()],Ki.prototype,"_toneMappingType",void 0),e([a()],Ki.prototype,"_contrast",void 0),e([a()],Ki.prototype,"vignetteStretch",void 0),e([a()],Ki.prototype,"vignetteCenterX",void 0),e([a()],Ki.prototype,"vignetteCenterY",void 0),e([a()],Ki.prototype,"vignetteWeight",void 0),e([d()],Ki.prototype,"vignetteColor",void 0),e([a()],Ki.prototype,"vignetteCameraFov",void 0),e([a()],Ki.prototype,"_vignetteBlendMode",void 0),e([a()],Ki.prototype,"_vignetteEnabled",void 0),e([a()],Ki.prototype,"_ditheringEnabled",void 0),e([a()],Ki.prototype,"_ditheringIntensity",void 0),e([a()],Ki.prototype,"_skipFinalColorClamp",void 0),e([a()],Ki.prototype,"_applyByPostProcess",void 0),e([a()],Ki.prototype,"_isEnabled",void 0),re._ImageProcessingConfigurationParser=Ki.Parse,I("BABYLON.ImageProcessingConfiguration",Ki);class qi{constructor(e,t,s,i,r,n){this.source=e,this.pointerX=t,this.pointerY=s,this.meshUnderPointer=i,this.sourceEvent=r,this.additionalData=n}static CreateNew(e,t,s){const i=e.getScene();return new qi(e,i.pointerX,i.pointerY,i.meshUnderPointer||e,t,s)}static CreateNewFromSprite(e,t,s,i){return new qi(e,t.pointerX,t.pointerY,t.meshUnderPointer,s,i)}static CreateNewFromScene(e,t){return new qi(null,e.pointerX,e.pointerY,e.meshUnderPointer,t)}static CreateNewFromPrimitive(e,t,s,i){return new qi(e,t.x,t.y,null,s,i)}}class Qi{constructor(e){this._vertexBuffers={},this.onBeforeRenderObservable=new g,this._scene=e}_prepareBuffers(){if(this._vertexBuffers[ns.PositionKind])return;const e=[];e.push(1,1),e.push(-1,1),e.push(-1,-1),e.push(1,-1),this._vertexBuffers[ns.PositionKind]=new ns(this._scene.getEngine(),e,ns.PositionKind,!1,!1,2),this._buildIndexBuffer()}_buildIndexBuffer(){const e=[];e.push(0),e.push(1),e.push(2),e.push(0),e.push(2),e.push(3),this._indexBuffer=this._scene.getEngine().createIndexBuffer(e)}_rebuild(){const e=this._vertexBuffers[ns.PositionKind];e&&(e._rebuild(),this._buildIndexBuffer())}_prepareFrame(e=null,t=null){const s=this._scene.activeCamera;return!!s&&(!(!(t=t||s._postProcesses.filter((e=>null!=e)))||0===t.length||!this._scene.postProcessesEnabled)&&(t[0].activate(s,e,null!=t),!0))}directRender(e,t=null,s=!1,i=0,r=0,n=!1){const a=this._scene.getEngine();for(let o=0;o<e.length;o++){o<e.length-1?e[o+1].activate(this._scene.activeCamera,t?.texture):(t?a.bindFramebuffer(t,i,void 0,void 0,s,r):n||a.restoreDefaultFramebuffer(),a._debugInsertMarker?.(`post process ${e[o].name} output`));const h=e[o],l=h.apply();l&&(h.onBeforeRenderObservable.notifyObservers(l),this._prepareBuffers(),a.bindBuffers(this._vertexBuffers,this._indexBuffer,l),a.drawElementsType(Ze.MATERIAL_TriangleFillMode,0,6),h.onAfterRenderObservable.notifyObservers(l))}a.setDepthBuffer(!0),a.setDepthWrite(!0)}_finalizeFrame(e,t,s,i,r=!1){const n=this._scene.activeCamera;if(!n)return;if(this.onBeforeRenderObservable.notifyObservers(this),0===(i=i||n._postProcesses.filter((e=>null!=e))).length||!this._scene.postProcessesEnabled)return;const a=this._scene.getEngine();for(let o=0,h=i.length;o<h;o++){const l=i[o];if(o<h-1?l._outputTexture=i[o+1].activate(n,t?.texture):(t?(a.bindFramebuffer(t,s,void 0,void 0,r),l._outputTexture=t):(a.restoreDefaultFramebuffer(),l._outputTexture=null),a._debugInsertMarker?.(`post process ${i[o].name} output`)),e)break;const c=l.apply();c&&(l.onBeforeRenderObservable.notifyObservers(c),this._prepareBuffers(),a.bindBuffers(this._vertexBuffers,this._indexBuffer,c),a.drawElementsType(Ze.MATERIAL_TriangleFillMode,0,6),l.onAfterRenderObservable.notifyObservers(c))}a.setDepthBuffer(!0),a.setDepthWrite(!0),a.setAlphaMode(Ze.ALPHA_DISABLE)}dispose(){const e=this._vertexBuffers[ns.PositionKind];e&&(e.dispose(),this._vertexBuffers[ns.PositionKind]=null),this._indexBuffer&&(this._scene.getEngine()._releaseBuffer(this._indexBuffer),this._indexBuffer=null)}}class ji{set opaqueSortCompareFn(e){this._opaqueSortCompareFn=e||ji.PainterSortCompare,this._renderOpaque=this._renderOpaqueSorted}set alphaTestSortCompareFn(e){this._alphaTestSortCompareFn=e||ji.PainterSortCompare,this._renderAlphaTest=this._renderAlphaTestSorted}set transparentSortCompareFn(e){this._transparentSortCompareFn=e||ji.defaultTransparentSortCompare,this._renderTransparent=this._renderTransparentSorted}constructor(e,t,s=null,i=null,r=null){this.index=e,this._opaqueSubMeshes=new Zt(256),this._transparentSubMeshes=new Zt(256),this._alphaTestSubMeshes=new Zt(256),this._depthOnlySubMeshes=new Zt(256),this._particleSystems=new Zt(256),this._spriteManagers=new Zt(256),this._empty=!0,this._edgesRenderers=new $t(16),this._scene=t,this.opaqueSortCompareFn=s,this.alphaTestSortCompareFn=i,this.transparentSortCompareFn=r}render(e,t,s,i){if(e)return void e(this._opaqueSubMeshes,this._alphaTestSubMeshes,this._transparentSubMeshes,this._depthOnlySubMeshes);const r=this._scene.getEngine();0!==this._depthOnlySubMeshes.length&&(r.setColorWrite(!1),this._renderAlphaTest(this._depthOnlySubMeshes),r.setColorWrite(!0)),0!==this._opaqueSubMeshes.length&&this._renderOpaque(this._opaqueSubMeshes),0!==this._alphaTestSubMeshes.length&&this._renderAlphaTest(this._alphaTestSubMeshes);const n=r.getStencilBuffer();if(r.setStencilBuffer(!1),t&&this._renderSprites(),s&&this._renderParticles(i),this.onBeforeTransparentRendering&&this.onBeforeTransparentRendering(),0!==this._transparentSubMeshes.length||this._scene.useOrderIndependentTransparency){if(r.setStencilBuffer(n),this._scene.useOrderIndependentTransparency){const e=this._scene.depthPeelingRenderer.render(this._transparentSubMeshes);e.length&&this._renderTransparent(e)}else this._renderTransparent(this._transparentSubMeshes);r.setAlphaMode(Ze.ALPHA_DISABLE)}if(r.setStencilBuffer(!1),this._edgesRenderers.length){for(let e=0;e<this._edgesRenderers.length;e++)this._edgesRenderers.data[e].render();r.setAlphaMode(Ze.ALPHA_DISABLE)}r.setStencilBuffer(n)}_renderOpaqueSorted(e){ji._RenderSorted(e,this._opaqueSortCompareFn,this._scene.activeCamera,!1)}_renderAlphaTestSorted(e){ji._RenderSorted(e,this._alphaTestSortCompareFn,this._scene.activeCamera,!1)}_renderTransparentSorted(e){ji._RenderSorted(e,this._transparentSortCompareFn,this._scene.activeCamera,!0)}static _RenderSorted(e,t,s,i){let r,n=0;const a=s?s.globalPosition:ji._ZeroVector;if(i)for(;n<e.length;n++)r=e.data[n],r._alphaIndex=r.getMesh().alphaIndex,r._distanceToCamera=U.Distance(r.getBoundingInfo().boundingSphere.centerWorld,a);const o=e.length===e.data.length?e.data:e.data.slice(0,e.length);t&&o.sort(t);const h=o[0].getMesh().getScene();for(n=0;n<o.length;n++)if(r=o[n],!h._activeMeshesFrozenButKeepClipping||r.isInFrustum(h._frustumPlanes)){if(i){const e=r.getMaterial();if(e&&e.needDepthPrePass){const t=e.getScene().getEngine();t.setColorWrite(!1),t.setAlphaMode(Ze.ALPHA_DISABLE),r.render(!1),t.setColorWrite(!0)}}r.render(i)}}static defaultTransparentSortCompare(e,t){return e._alphaIndex>t._alphaIndex?1:e._alphaIndex<t._alphaIndex?-1:ji.backToFrontSortCompare(e,t)}static backToFrontSortCompare(e,t){return e._distanceToCamera<t._distanceToCamera?1:e._distanceToCamera>t._distanceToCamera?-1:0}static frontToBackSortCompare(e,t){return e._distanceToCamera<t._distanceToCamera?-1:e._distanceToCamera>t._distanceToCamera?1:0}static PainterSortCompare(e,t){const s=e.getMesh(),i=t.getMesh();return s.material&&i.material?s.material.uniqueId-i.material.uniqueId:s.uniqueId-i.uniqueId}prepare(){this._opaqueSubMeshes.reset(),this._transparentSubMeshes.reset(),this._alphaTestSubMeshes.reset(),this._depthOnlySubMeshes.reset(),this._particleSystems.reset(),this.prepareSprites(),this._edgesRenderers.reset(),this._empty=!0}prepareSprites(){this._spriteManagers.reset()}dispose(){this._opaqueSubMeshes.dispose(),this._transparentSubMeshes.dispose(),this._alphaTestSubMeshes.dispose(),this._depthOnlySubMeshes.dispose(),this._particleSystems.dispose(),this._spriteManagers.dispose(),this._edgesRenderers.dispose()}dispatch(e,t,s){void 0===t&&(t=e.getMesh()),void 0===s&&(s=e.getMaterial()),null!=s&&(s.needAlphaBlendingForMesh(t)?this._transparentSubMeshes.push(e):s.needAlphaTesting()?(s.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._alphaTestSubMeshes.push(e)):(s.needDepthPrePass&&this._depthOnlySubMeshes.push(e),this._opaqueSubMeshes.push(e)),t._renderingGroup=this,t._edgesRenderer&&t.isEnabled()&&t.isVisible&&t._edgesRenderer.isEnabled&&this._edgesRenderers.pushNoDuplicate(t._edgesRenderer),this._empty=!1)}dispatchSprites(e){this._spriteManagers.push(e),this._empty=!1}dispatchParticles(e){this._particleSystems.push(e),this._empty=!1}_renderParticles(e){if(0===this._particleSystems.length)return;const t=this._scene.activeCamera;this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);for(let s=0;s<this._particleSystems.length;s++){const i=this._particleSystems.data[s];if(0===(t&&t.layerMask&i.layerMask))continue;const r=i.emitter;r.position&&e&&-1===e.indexOf(r)||this._scene._activeParticles.addCount(i.render(),!1)}this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene)}_renderSprites(){if(!this._scene.spritesEnabled||0===this._spriteManagers.length)return;const e=this._scene.activeCamera;this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);for(let t=0;t<this._spriteManagers.length;t++){const s=this._spriteManagers.data[t];0!==(e&&e.layerMask&s.layerMask)&&s.render()}this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene)}}ji._ZeroVector=U.Zero();class Zi{}class $i{get maintainStateBetweenFrames(){return this._maintainStateBetweenFrames}set maintainStateBetweenFrames(e){e!==this._maintainStateBetweenFrames&&(this._maintainStateBetweenFrames=e,this._maintainStateBetweenFrames||this.restoreDispachedFlags())}restoreDispachedFlags(){for(const e of this._scene.meshes)if(e.subMeshes)for(const t of e.subMeshes)t._wasDispatched=!1;if(this._scene.spriteManagers)for(const e of this._scene.spriteManagers)e._wasDispatched=!1;for(const e of this._scene.particleSystems)e._wasDispatched=!1}constructor(e){this._useSceneAutoClearSetup=!1,this._renderingGroups=new Array,this._autoClearDepthStencil={},this._customOpaqueSortCompareFn={},this._customAlphaTestSortCompareFn={},this._customTransparentSortCompareFn={},this._renderingGroupInfo=new Zi,this._maintainStateBetweenFrames=!1,this._scene=e;for(let e=$i.MIN_RENDERINGGROUPS;e<$i.MAX_RENDERINGGROUPS;e++)this._autoClearDepthStencil[e]={autoClear:!0,depth:!0,stencil:!0}}getRenderingGroup(e){const t=e||0;return this._prepareRenderingGroup(t),this._renderingGroups[t]}_clearDepthStencilBuffer(e=!0,t=!0){this._depthStencilBufferAlreadyCleaned||(this._scene.getEngine().clear(null,!1,e,t),this._depthStencilBufferAlreadyCleaned=!0)}render(e,t,s,i){const r=this._renderingGroupInfo;if(r.scene=this._scene,r.camera=this._scene.activeCamera,this._scene.spriteManagers&&i)for(let e=0;e<this._scene.spriteManagers.length;e++){const t=this._scene.spriteManagers[e];this.dispatchSprites(t)}for(let n=$i.MIN_RENDERINGGROUPS;n<$i.MAX_RENDERINGGROUPS;n++){this._depthStencilBufferAlreadyCleaned=n===$i.MIN_RENDERINGGROUPS;const a=this._renderingGroups[n];if(!a||a._empty)continue;const o=1<<n;if(r.renderingGroupId=n,this._scene.onBeforeRenderingGroupObservable.notifyObservers(r,o),$i.AUTOCLEAR){const e=this._useSceneAutoClearSetup?this._scene.getAutoClearDepthStencilSetup(n):this._autoClearDepthStencil[n];e&&e.autoClear&&this._clearDepthStencilBuffer(e.depth,e.stencil)}for(const e of this._scene._beforeRenderingGroupDrawStage)e.action(n);a.render(e,i,s,t);for(const e of this._scene._afterRenderingGroupDrawStage)e.action(n);this._scene.onAfterRenderingGroupObservable.notifyObservers(r,o)}}reset(){if(!this.maintainStateBetweenFrames)for(let e=$i.MIN_RENDERINGGROUPS;e<$i.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.prepare()}}resetSprites(){if(!this.maintainStateBetweenFrames)for(let e=$i.MIN_RENDERINGGROUPS;e<$i.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.prepareSprites()}}dispose(){this.freeRenderingGroups(),this._renderingGroups.length=0,this._renderingGroupInfo=null}freeRenderingGroups(){for(let e=$i.MIN_RENDERINGGROUPS;e<$i.MAX_RENDERINGGROUPS;e++){const t=this._renderingGroups[e];t&&t.dispose()}}_prepareRenderingGroup(e){void 0===this._renderingGroups[e]&&(this._renderingGroups[e]=new ji(e,this._scene,this._customOpaqueSortCompareFn[e],this._customAlphaTestSortCompareFn[e],this._customTransparentSortCompareFn[e]))}dispatchSprites(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchSprites(e))}dispatchParticles(e){this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(e.renderingGroupId).dispatchParticles(e))}dispatch(e,t,s){void 0===t&&(t=e.getMesh()),this.maintainStateBetweenFrames&&e._wasDispatched||(e._wasDispatched=!0,this.getRenderingGroup(t.renderingGroupId).dispatch(e,t,s))}setRenderingOrder(e,t=null,s=null,i=null){if(this._customOpaqueSortCompareFn[e]=t,this._customAlphaTestSortCompareFn[e]=s,this._customTransparentSortCompareFn[e]=i,this._renderingGroups[e]){const t=this._renderingGroups[e];t.opaqueSortCompareFn=this._customOpaqueSortCompareFn[e],t.alphaTestSortCompareFn=this._customAlphaTestSortCompareFn[e],t.transparentSortCompareFn=this._customTransparentSortCompareFn[e]}}setRenderingAutoClearDepthStencil(e,t,s=!0,i=!0){this._autoClearDepthStencil[e]={autoClear:t,depth:s,stencil:i}}getAutoClearDepthStencilSetup(e){return this._autoClearDepthStencil[e]}}$i.MAX_RENDERINGGROUPS=4,$i.MIN_RENDERINGGROUPS=0,$i.AUTOCLEAR=!0;class Ji{constructor(){this.hoverCursor="",this.actions=[],this.isRecursive=!1,this.disposeWhenUnowned=!0}static get HasTriggers(){for(const e in Ji.Triggers)if(Object.prototype.hasOwnProperty.call(Ji.Triggers,e))return!0;return!1}static get HasPickTriggers(){for(const e in Ji.Triggers)if(Object.prototype.hasOwnProperty.call(Ji.Triggers,e)){const t=parseInt(e);if(t>=Ze.ACTION_OnPickTrigger&&t<=Ze.ACTION_OnPickUpTrigger)return!0}return!1}static HasSpecificTrigger(e){for(const t in Ji.Triggers)if(Object.prototype.hasOwnProperty.call(Ji.Triggers,t)){if(parseInt(t)===e)return!0}return!1}}var er,tr,sr,ir,rr,nr,ar;Ji.Triggers={},function(e){e[e.Generic=0]="Generic",e[e.Keyboard=1]="Keyboard",e[e.Mouse=2]="Mouse",e[e.Touch=3]="Touch",e[e.DualShock=4]="DualShock",e[e.Xbox=5]="Xbox",e[e.Switch=6]="Switch",e[e.DualSense=7]="DualSense"}(er||(er={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical",e[e.LeftClick=2]="LeftClick",e[e.MiddleClick=3]="MiddleClick",e[e.RightClick=4]="RightClick",e[e.BrowserBack=5]="BrowserBack",e[e.BrowserForward=6]="BrowserForward",e[e.MouseWheelX=7]="MouseWheelX",e[e.MouseWheelY=8]="MouseWheelY",e[e.MouseWheelZ=9]="MouseWheelZ",e[e.Move=12]="Move"}(tr||(tr={})),function(e){e[e.Horizontal=0]="Horizontal",e[e.Vertical=1]="Vertical",e[e.LeftClick=2]="LeftClick",e[e.MiddleClick=3]="MiddleClick",e[e.RightClick=4]="RightClick",e[e.BrowserBack=5]="BrowserBack",e[e.BrowserForward=6]="BrowserForward",e[e.MouseWheelX=7]="MouseWheelX",e[e.MouseWheelY=8]="MouseWheelY",e[e.MouseWheelZ=9]="MouseWheelZ",e[e.DeltaHorizontal=10]="DeltaHorizontal",e[e.DeltaVertical=11]="DeltaVertical"}(sr||(sr={})),function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.L2=6]="L2",e[e.R2=7]="R2",e[e.Share=8]="Share",e[e.Options=9]="Options",e[e.L3=10]="L3",e[e.R3=11]="R3",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.TouchPad=17]="TouchPad",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(ir||(ir={})),function(e){e[e.Cross=0]="Cross",e[e.Circle=1]="Circle",e[e.Square=2]="Square",e[e.Triangle=3]="Triangle",e[e.L1=4]="L1",e[e.R1=5]="R1",e[e.L2=6]="L2",e[e.R2=7]="R2",e[e.Create=8]="Create",e[e.Options=9]="Options",e[e.L3=10]="L3",e[e.R3=11]="R3",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.TouchPad=17]="TouchPad",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(rr||(rr={})),function(e){e[e.A=0]="A",e[e.B=1]="B",e[e.X=2]="X",e[e.Y=3]="Y",e[e.LB=4]="LB",e[e.RB=5]="RB",e[e.LT=6]="LT",e[e.RT=7]="RT",e[e.Back=8]="Back",e[e.Start=9]="Start",e[e.LS=10]="LS",e[e.RS=11]="RS",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.LStickXAxis=17]="LStickXAxis",e[e.LStickYAxis=18]="LStickYAxis",e[e.RStickXAxis=19]="RStickXAxis",e[e.RStickYAxis=20]="RStickYAxis"}(nr||(nr={})),function(e){e[e.B=0]="B",e[e.A=1]="A",e[e.Y=2]="Y",e[e.X=3]="X",e[e.L=4]="L",e[e.R=5]="R",e[e.ZL=6]="ZL",e[e.ZR=7]="ZR",e[e.Minus=8]="Minus",e[e.Plus=9]="Plus",e[e.LS=10]="LS",e[e.RS=11]="RS",e[e.DPadUp=12]="DPadUp",e[e.DPadDown=13]="DPadDown",e[e.DPadLeft=14]="DPadLeft",e[e.DPadRight=15]="DPadRight",e[e.Home=16]="Home",e[e.Capture=17]="Capture",e[e.LStickXAxis=18]="LStickXAxis",e[e.LStickYAxis=19]="LStickYAxis",e[e.RStickXAxis=20]="RStickXAxis",e[e.RStickYAxis=21]="RStickYAxis"}(ar||(ar={}));class or{static CreateDeviceEvent(e,t,s,i,r,n,a){switch(e){case er.Keyboard:return this._CreateKeyboardEvent(s,i,r,n);case er.Mouse:if(s===tr.MouseWheelX||s===tr.MouseWheelY||s===tr.MouseWheelZ)return this._CreateWheelEvent(e,t,s,i,r,n);case er.Touch:return this._CreatePointerEvent(e,t,s,i,r,n,a);default:throw`Unable to generate event for device ${er[e]}`}}static _CreatePointerEvent(e,t,s,i,r,n,a){const o=this._CreateMouseEvent(e,t,s,i,r,n);e===er.Mouse?(o.deviceType=er.Mouse,o.pointerId=1,o.pointerType="mouse"):(o.deviceType=er.Touch,o.pointerId=a??t,o.pointerType="touch");let h=0;return h+=r.pollInput(e,t,tr.LeftClick),h+=2*r.pollInput(e,t,tr.RightClick),h+=4*r.pollInput(e,t,tr.MiddleClick),o.buttons=h,s===tr.Move?o.type="pointermove":s>=tr.LeftClick&&s<=tr.RightClick&&(o.type=1===i?"pointerdown":"pointerup",o.button=s-2),o}static _CreateWheelEvent(e,t,s,i,r,n){const a=this._CreateMouseEvent(e,t,s,i,r,n);switch(a.pointerId=1,a.type="wheel",a.deltaMode=Bi.DOM_DELTA_PIXEL,a.deltaX=0,a.deltaY=0,a.deltaZ=0,s){case tr.MouseWheelX:a.deltaX=i;break;case tr.MouseWheelY:a.deltaY=i;break;case tr.MouseWheelZ:a.deltaZ=i}return a}static _CreateMouseEvent(e,t,s,i,r,n){const a=this._CreateEvent(n),o=r.pollInput(e,t,tr.Horizontal),h=r.pollInput(e,t,tr.Vertical);return n?(a.movementX=0,a.movementY=0,a.offsetX=a.movementX-n.getBoundingClientRect().x,a.offsetY=a.movementY-n.getBoundingClientRect().y):(a.movementX=r.pollInput(e,t,10),a.movementY=r.pollInput(e,t,11),a.offsetX=0,a.offsetY=0),this._CheckNonCharacterKeys(a,r),a.clientX=o,a.clientY=h,a.x=o,a.y=h,a.deviceType=e,a.deviceSlot=t,a.inputIndex=s,a}static _CreateKeyboardEvent(e,t,s,i){const r=this._CreateEvent(i);return this._CheckNonCharacterKeys(r,s),r.deviceType=er.Keyboard,r.deviceSlot=0,r.inputIndex=e,r.type=1===t?"keydown":"keyup",r.key=String.fromCharCode(e),r.keyCode=e,r}static _CheckNonCharacterKeys(e,t){const s=t.isDeviceAvailable(er.Keyboard),i=s&&1===t.pollInput(er.Keyboard,0,Ze.INPUT_ALT_KEY),r=s&&1===t.pollInput(er.Keyboard,0,Ze.INPUT_CTRL_KEY),n=s&&(1===t.pollInput(er.Keyboard,0,Ze.INPUT_META_KEY1)||1===t.pollInput(er.Keyboard,0,Ze.INPUT_META_KEY2)||1===t.pollInput(er.Keyboard,0,Ze.INPUT_META_KEY3)),a=s&&1===t.pollInput(er.Keyboard,0,Ze.INPUT_SHIFT_KEY);e.altKey=i,e.ctrlKey=r,e.metaKey=n,e.shiftKey=a}static _CreateEvent(e){const t={preventDefault:()=>{}};return t.target=e,t}}class hr{constructor(e,t,s){this._nativeInput=_native.DeviceInputSystem?new _native.DeviceInputSystem(e,t,((e,t,i,r)=>{const n=or.CreateDeviceEvent(e,t,i,r,this);s(e,t,n)})):this._createDummyNativeInput()}pollInput(e,t,s){return this._nativeInput.pollInput(e,t,s)}isDeviceAvailable(e){return e===er.Mouse||e===er.Touch}dispose(){this._nativeInput.dispose()}_createDummyNativeInput(){return{pollInput:()=>0,isDeviceAvailable:()=>!1,dispose:()=>{}}}}const lr=Object.keys(tr).length/2;class cr{constructor(e,t,s,i){this._inputs=[],this._keyboardActive=!1,this._pointerActive=!1,this._usingSafari=Yt.IsSafari(),this._usingMacOS=he()&&/(Mac|iPhone|iPod|iPad)/i.test(navigator.platform),this._keyboardDownEvent=e=>{},this._keyboardUpEvent=e=>{},this._keyboardBlurEvent=e=>{},this._pointerMoveEvent=e=>{},this._pointerDownEvent=e=>{},this._pointerUpEvent=e=>{},this._pointerCancelEvent=e=>{},this._pointerWheelEvent=e=>{},this._pointerBlurEvent=e=>{},this._pointerMacOSChromeOutEvent=e=>{},this._eventsAttached=!1,this._mouseId=-1,this._isUsingFirefox=he()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Firefox"),this._isUsingChromium=he()&&navigator.userAgent&&-1!==navigator.userAgent.indexOf("Chrome"),this._maxTouchPoints=0,this._pointerInputClearObserver=null,this._gamepadConnectedEvent=e=>{},this._gamepadDisconnectedEvent=e=>{},this._eventPrefix=Yt.GetPointerPrefix(e),this._engine=e,this._onDeviceConnected=t,this._onDeviceDisconnected=s,this._onInputChanged=i,this._mouseId=this._isUsingFirefox?0:1,this._enableEvents(),this._usingMacOS&&(this._metaKeys=[]),this._engine._onEngineViewChanged||(this._engine._onEngineViewChanged=()=>{this._enableEvents()})}pollInput(e,t,s){const i=this._inputs[e][t];if(!i)throw`Unable to find device ${er[e]}`;e>=er.DualShock&&e<=er.DualSense&&this._updateDevice(e,t,s);const r=i[s];if(void 0===r)throw`Unable to find input ${s} for device ${er[e]} in slot ${t}`;return s===tr.Move&&Yt.Warn("Unable to provide information for PointerInput.Move. Try using PointerInput.Horizontal or PointerInput.Vertical for move data."),r}isDeviceAvailable(e){return void 0!==this._inputs[e]}dispose(){this._onDeviceConnected=()=>{},this._onDeviceDisconnected=()=>{},this._onInputChanged=()=>{},delete this._engine._onEngineViewChanged,this._elementToAttachTo&&this._disableEvents()}_enableEvents(){const e=this?._engine.getInputElement();if(e&&(!this._eventsAttached||this._elementToAttachTo!==e)){if(this._disableEvents(),this._inputs)for(const e of this._inputs)if(e)for(const t in e){const s=e[+t];if(s)for(let e=0;e<s.length;e++)s[e]=0}this._elementToAttachTo=e,this._elementToAttachTo.tabIndex=-1!==this._elementToAttachTo.tabIndex?this._elementToAttachTo.tabIndex:this._engine.canvasTabIndex,this._handleKeyActions(),this._handlePointerActions(),this._handleGamepadActions(),this._eventsAttached=!0,this._checkForConnectedDevices()}}_disableEvents(){this._elementToAttachTo&&(this._elementToAttachTo.removeEventListener("blur",this._keyboardBlurEvent),this._elementToAttachTo.removeEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.removeEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.removeEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.removeEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.removeEventListener(this._wheelEventName,this._pointerWheelEvent),this._usingMacOS&&this._isUsingChromium&&this._elementToAttachTo.removeEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent),window.removeEventListener("gamepadconnected",this._gamepadConnectedEvent),window.removeEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)),this._pointerInputClearObserver&&this._engine.onEndFrameObservable.remove(this._pointerInputClearObserver),this._eventsAttached=!1}_checkForConnectedDevices(){if(navigator.getGamepads){const e=navigator.getGamepads();for(const t of e)t&&this._addGamePad(t)}"function"==typeof matchMedia&&matchMedia("(pointer:fine)").matches&&this._addPointerDevice(er.Mouse,0,0,0)}_addGamePad(e){const t=this._getGamepadDeviceType(e.id),s=e.index;this._gamepads=this._gamepads||new Array(e.index+1),this._registerDevice(t,s,e.buttons.length+e.axes.length),this._gamepads[s]=t}_addPointerDevice(e,t,s,i){this._pointerActive||(this._pointerActive=!0),this._registerDevice(e,t,lr);const r=this._inputs[e][t];r[0]=s,r[1]=i}_registerDevice(e,t,s){if(void 0===t)throw`Unable to register device ${er[e]} to undefined slot.`;if(this._inputs[e]||(this._inputs[e]={}),!this._inputs[e][t]){const i=new Array(s);i.fill(0),this._inputs[e][t]=i,this._onDeviceConnected(e,t)}}_unregisterDevice(e,t){this._inputs[e][t]&&(delete this._inputs[e][t],this._onDeviceDisconnected(e,t))}_handleKeyActions(){this._keyboardDownEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(er.Keyboard,0,255));const t=this._inputs[er.Keyboard][0];if(t){t[e.keyCode]=1;const s=e;s.inputIndex=e.keyCode,this._usingMacOS&&e.metaKey&&"Meta"!==e.key&&(this._metaKeys.includes(e.keyCode)||this._metaKeys.push(e.keyCode)),this._onInputChanged(er.Keyboard,0,s)}},this._keyboardUpEvent=e=>{this._keyboardActive||(this._keyboardActive=!0,this._registerDevice(er.Keyboard,0,255));const t=this._inputs[er.Keyboard][0];if(t){t[e.keyCode]=0;const s=e;if(s.inputIndex=e.keyCode,this._usingMacOS&&"Meta"===e.key&&this._metaKeys.length>0){for(const e of this._metaKeys){const s=or.CreateDeviceEvent(er.Keyboard,0,e,0,this,this._elementToAttachTo);t[e]=0,this._onInputChanged(er.Keyboard,0,s)}this._metaKeys.splice(0,this._metaKeys.length)}this._onInputChanged(er.Keyboard,0,s)}},this._keyboardBlurEvent=()=>{if(this._keyboardActive){const e=this._inputs[er.Keyboard][0];for(let t=0;t<e.length;t++)if(0!==e[t]){e[t]=0;const s=or.CreateDeviceEvent(er.Keyboard,0,t,0,this,this._elementToAttachTo);this._onInputChanged(er.Keyboard,0,s)}this._usingMacOS&&this._metaKeys.splice(0,this._metaKeys.length)}},this._elementToAttachTo.addEventListener("keydown",this._keyboardDownEvent),this._elementToAttachTo.addEventListener("keyup",this._keyboardUpEvent),this._elementToAttachTo.addEventListener("blur",this._keyboardBlurEvent)}_handlePointerActions(){this._maxTouchPoints=he()&&navigator.maxTouchPoints||2,this._activeTouchIds||(this._activeTouchIds=new Array(this._maxTouchPoints));for(let e=0;e<this._maxTouchPoints;e++)this._activeTouchIds[e]=-1;this._pointerMoveEvent=e=>{const t=this._getPointerType(e);let s=t===er.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===er.Touch&&-1===s){const i=this._activeTouchIds.indexOf(-1);if(!(i>=0))return void Yt.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);s=i,this._activeTouchIds[i]=e.pointerId,this._onDeviceConnected(t,s)}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][s]||this._addPointerDevice(t,s,e.clientX,e.clientY);const i=this._inputs[t][s];if(i){const r=e;r.inputIndex=tr.Move,i[tr.Horizontal]=e.clientX,i[tr.Vertical]=e.clientY,t===er.Touch&&0===i[tr.LeftClick]&&(i[tr.LeftClick]=1),void 0===e.pointerId&&(e.pointerId=this._mouseId),this._onInputChanged(t,s,r),this._usingSafari||-1===e.button||(r.inputIndex=e.button+2,i[e.button+2]=i[e.button+2]?0:1,this._onInputChanged(t,s,r))}},this._pointerDownEvent=e=>{const t=this._getPointerType(e);let s=t===er.Mouse?0:e.pointerId;if(t===er.Touch){let t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t&&(t=this._activeTouchIds.indexOf(-1)),!(t>=0))return void Yt.Warn(`Max number of touches exceeded. Ignoring touches in excess of ${this._maxTouchPoints}`);s=t,this._activeTouchIds[t]=e.pointerId}this._inputs[t]||(this._inputs[t]={}),this._inputs[t][s]?t===er.Touch&&this._onDeviceConnected(t,s):this._addPointerDevice(t,s,e.clientX,e.clientY);const i=this._inputs[t][s];if(i){const r=i[tr.Horizontal],n=i[tr.Vertical];if(t===er.Mouse){if(void 0===e.pointerId&&(e.pointerId=this._mouseId),!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(this._mouseId)}catch(e){}}else if(e.pointerId&&!document.pointerLockElement)try{this._elementToAttachTo.setPointerCapture(e.pointerId)}catch(e){}i[tr.Horizontal]=e.clientX,i[tr.Vertical]=e.clientY,i[e.button+2]=1;const a=e;a.inputIndex=e.button+2,this._onInputChanged(t,s,a),r===e.clientX&&n===e.clientY||(a.inputIndex=tr.Move,this._onInputChanged(t,s,a))}},this._pointerUpEvent=e=>{const t=this._getPointerType(e),s=t===er.Mouse?0:this._activeTouchIds.indexOf(e.pointerId);if(t===er.Touch){if(-1===s)return;this._activeTouchIds[s]=-1}const i=this._inputs[t]?.[s];if(i&&0!==i[e.button+2]){const r=i[tr.Horizontal],n=i[tr.Vertical];i[tr.Horizontal]=e.clientX,i[tr.Vertical]=e.clientY,i[e.button+2]=0;const a=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),r===e.clientX&&n===e.clientY||(a.inputIndex=tr.Move,this._onInputChanged(t,s,a)),a.inputIndex=e.button+2,t===er.Mouse&&this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)?this._elementToAttachTo.releasePointerCapture(this._mouseId):e.pointerId&&this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._onInputChanged(t,s,a),t===er.Touch&&this._onDeviceDisconnected(t,s)}},this._pointerCancelEvent=e=>{if("mouse"===e.pointerType){const e=this._inputs[er.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=tr.LeftClick;t<=tr.BrowserForward;t++)if(1===e[t]){e[t]=0;const s=or.CreateDeviceEvent(er.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(er.Mouse,0,s)}}else{const t=this._activeTouchIds.indexOf(e.pointerId);if(-1===t)return;this._elementToAttachTo.hasPointerCapture?.(e.pointerId)&&this._elementToAttachTo.releasePointerCapture(e.pointerId),this._inputs[er.Touch][t][tr.LeftClick]=0;const s=or.CreateDeviceEvent(er.Touch,t,tr.LeftClick,0,this,this._elementToAttachTo,e.pointerId);this._onInputChanged(er.Touch,t,s),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(er.Touch,t)}},this._wheelEventName="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";let e=!1;const t=function(){};try{const s=Object.defineProperty({},"passive",{get:function(){e=!0}});this._elementToAttachTo.addEventListener("test",t,s),this._elementToAttachTo.removeEventListener("test",t,s)}catch(e){}this._pointerBlurEvent=()=>{if(this.isDeviceAvailable(er.Mouse)){const e=this._inputs[er.Mouse][0];this._mouseId>=0&&this._elementToAttachTo.hasPointerCapture?.(this._mouseId)&&this._elementToAttachTo.releasePointerCapture(this._mouseId);for(let t=tr.LeftClick;t<=tr.BrowserForward;t++)if(1===e[t]){e[t]=0;const s=or.CreateDeviceEvent(er.Mouse,0,t,0,this,this._elementToAttachTo);this._onInputChanged(er.Mouse,0,s)}}if(this.isDeviceAvailable(er.Touch)){const e=this._inputs[er.Touch];for(let t=0;t<this._activeTouchIds.length;t++){const s=this._activeTouchIds[t];if(this._elementToAttachTo.hasPointerCapture?.(s)&&this._elementToAttachTo.releasePointerCapture(s),-1!==s&&1===e[t]?.[tr.LeftClick]){e[t][tr.LeftClick]=0;const i=or.CreateDeviceEvent(er.Touch,t,tr.LeftClick,0,this,this._elementToAttachTo,s);this._onInputChanged(er.Touch,t,i),this._activeTouchIds[t]=-1,this._onDeviceDisconnected(er.Touch,t)}}}},this._pointerWheelEvent=e=>{const t=er.Mouse;this._inputs[t]||(this._inputs[t]=[]),this._inputs[t][0]||(this._pointerActive=!0,this._registerDevice(t,0,lr));const s=this._inputs[t][0];if(s){s[tr.MouseWheelX]=e.deltaX||0,s[tr.MouseWheelY]=e.deltaY||e.wheelDelta||0,s[tr.MouseWheelZ]=e.deltaZ||0;const i=e;void 0===e.pointerId&&(e.pointerId=this._mouseId),0!==s[tr.MouseWheelX]&&(i.inputIndex=tr.MouseWheelX,this._onInputChanged(t,0,i)),0!==s[tr.MouseWheelY]&&(i.inputIndex=tr.MouseWheelY,this._onInputChanged(t,0,i)),0!==s[tr.MouseWheelZ]&&(i.inputIndex=tr.MouseWheelZ,this._onInputChanged(t,0,i))}},this._usingMacOS&&this._isUsingChromium&&(this._pointerMacOSChromeOutEvent=e=>{e.buttons>1&&this._pointerCancelEvent(e)},this._elementToAttachTo.addEventListener("lostpointercapture",this._pointerMacOSChromeOutEvent)),this._elementToAttachTo.addEventListener(this._eventPrefix+"move",this._pointerMoveEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"down",this._pointerDownEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"up",this._pointerUpEvent),this._elementToAttachTo.addEventListener(this._eventPrefix+"cancel",this._pointerCancelEvent),this._elementToAttachTo.addEventListener("blur",this._pointerBlurEvent),this._elementToAttachTo.addEventListener(this._wheelEventName,this._pointerWheelEvent,!!e&&{passive:!1}),this._pointerInputClearObserver=this._engine.onEndFrameObservable.add((()=>{if(this.isDeviceAvailable(er.Mouse)){const e=this._inputs[er.Mouse][0];e[tr.MouseWheelX]=0,e[tr.MouseWheelY]=0,e[tr.MouseWheelZ]=0}}))}_handleGamepadActions(){this._gamepadConnectedEvent=e=>{this._addGamePad(e.gamepad)},this._gamepadDisconnectedEvent=e=>{if(this._gamepads){const t=this._getGamepadDeviceType(e.gamepad.id),s=e.gamepad.index;this._unregisterDevice(t,s),delete this._gamepads[s]}},window.addEventListener("gamepadconnected",this._gamepadConnectedEvent),window.addEventListener("gamepaddisconnected",this._gamepadDisconnectedEvent)}_updateDevice(e,t,s){const i=navigator.getGamepads()[t];if(i&&e===this._gamepads[t]){const r=this._inputs[e][t];s>=i.buttons.length?r[s]=i.axes[s-i.buttons.length].valueOf():r[s]=i.buttons[s].value}}_getGamepadDeviceType(e){return-1!==e.indexOf("054c")?-1!==e.indexOf("0ce6")?er.DualSense:er.DualShock:-1!==e.indexOf("Xbox One")||-1!==e.search("Xbox 360")||-1!==e.search("xinput")?er.Xbox:-1!==e.indexOf("057e")?er.Switch:er.Generic}_getPointerType(e){let t=er.Mouse;return("touch"===e.pointerType||"pen"===e.pointerType||e.touches)&&(t=er.Touch),t}}class ur{constructor(e,t,s=0){this.deviceType=t,this.deviceSlot=s,this.onInputChangedObservable=new g,this._deviceInputSystem=e}getInput(e){return this._deviceInputSystem.pollInput(this.deviceType,this.deviceSlot,e)}}class dr{constructor(e){this._registeredManagers=new Array,this._refCount=0,this.registerManager=e=>{for(let t=0;t<this._devices.length;t++){const s=this._devices[t];for(const i in s){const s=+i;e._addDevice(new ur(this._deviceInputSystem,t,s))}}this._registeredManagers.push(e)},this.unregisterManager=e=>{const t=this._registeredManagers.indexOf(e);t>-1&&this._registeredManagers.splice(t,1)};const t=Object.keys(er).length/2;this._devices=new Array(t);const s=(e,t)=>{this._devices[e]||(this._devices[e]=new Array),this._devices[e][t]||(this._devices[e][t]=t);for(const s of this._registeredManagers){const i=new ur(this._deviceInputSystem,e,t);s._addDevice(i)}},i=(e,t)=>{this._devices[e]?.[t]&&delete this._devices[e][t];for(const s of this._registeredManagers)s._removeDevice(e,t)},r=(e,t,s)=>{if(s)for(const i of this._registeredManagers)i._onInputChanged(e,t,s)};"undefined"!=typeof _native?this._deviceInputSystem=new hr(s,i,r):this._deviceInputSystem=new cr(e,s,i,r)}dispose(){this._deviceInputSystem.dispose()}}class _r{getDeviceSource(e,t){if(void 0===t){if(void 0===this._firstDevice[e])return null;t=this._firstDevice[e]}return this._devices[e]&&void 0!==this._devices[e][t]?this._devices[e][t]:null}getDeviceSources(e){return this._devices[e]?this._devices[e].filter((e=>!!e)):[]}constructor(e){const t=Object.keys(er).length/2;this._devices=new Array(t),this._firstDevice=new Array(t),this._engine=e,this._engine._deviceSourceManager||(this._engine._deviceSourceManager=new dr(e)),this._engine._deviceSourceManager._refCount++,this.onDeviceConnectedObservable=new g((e=>{for(const t of this._devices)if(t)for(const s of t)s&&this.onDeviceConnectedObservable.notifyObserver(e,s)})),this.onDeviceDisconnectedObservable=new g,this._engine._deviceSourceManager.registerManager(this),this._onDisposeObserver=e.onDisposeObservable.add((()=>{this.dispose()}))}dispose(){this.onDeviceConnectedObservable.clear(),this.onDeviceDisconnectedObservable.clear(),this._engine._deviceSourceManager&&(this._engine._deviceSourceManager.unregisterManager(this),--this._engine._deviceSourceManager._refCount<1&&(this._engine._deviceSourceManager.dispose(),delete this._engine._deviceSourceManager)),this._engine.onDisposeObservable.remove(this._onDisposeObserver)}_addDevice(e){this._devices[e.deviceType]||(this._devices[e.deviceType]=new Array),this._devices[e.deviceType][e.deviceSlot]||(this._devices[e.deviceType][e.deviceSlot]=e,this._updateFirstDevices(e.deviceType)),this.onDeviceConnectedObservable.notifyObservers(e)}_removeDevice(e,t){const s=this._devices[e]?.[t];this.onDeviceDisconnectedObservable.notifyObservers(s),this._devices[e]?.[t]&&delete this._devices[e][t],this._updateFirstDevices(e)}_onInputChanged(e,t,s){this._devices[e]?.[t]?.onInputChangedObservable.notifyObservers(s)}_updateFirstDevices(e){switch(e){case er.Keyboard:case er.Mouse:this._firstDevice[e]=0;break;case er.Touch:case er.DualSense:case er.DualShock:case er.Xbox:case er.Switch:case er.Generic:{delete this._firstDevice[e];const t=this._devices[e];if(t)for(let s=0;s<t.length;s++)if(t[s]){this._firstDevice[e]=s;break}break}}}}class fr{constructor(){this._singleClick=!1,this._doubleClick=!1,this._hasSwiped=!1,this._ignore=!1}get singleClick(){return this._singleClick}get doubleClick(){return this._doubleClick}get hasSwiped(){return this._hasSwiped}get ignore(){return this._ignore}set singleClick(e){this._singleClick=e}set doubleClick(e){this._doubleClick=e}set hasSwiped(e){this._hasSwiped=e}set ignore(e){this._ignore=e}}class pr{constructor(e){this._alreadyAttached=!1,this._meshPickProceed=!1,this._currentPickResult=null,this._previousPickResult=null,this._totalPointersPressed=0,this._doubleClickOccured=!1,this._isSwiping=!1,this._swipeButtonPressed=-1,this._skipPointerTap=!1,this._isMultiTouchGesture=!1,this._pointerX=0,this._pointerY=0,this._startingPointerPosition=new B(0,0),this._previousStartingPointerPosition=new B(0,0),this._startingPointerTime=0,this._previousStartingPointerTime=0,this._pointerCaptures={},this._meshUnderPointerId={},this._movePointerInfo=null,this._cameraObserverCount=0,this._delayedClicks=[null,null,null,null,null],this._deviceSourceManager=null,this._scene=e||C.LastCreatedScene,this._scene}get meshUnderPointer(){return this._movePointerInfo&&(this._movePointerInfo._generatePickInfo(),this._movePointerInfo=null),this._pointerOverMesh}getMeshUnderPointerByPointerId(e){return this._meshUnderPointerId[e]||null}get unTranslatedPointer(){return new B(this._unTranslatedPointerX,this._unTranslatedPointerY)}get pointerX(){return this._pointerX}set pointerX(e){this._pointerX=e}get pointerY(){return this._pointerY}set pointerY(e){this._pointerY=e}_updatePointerPosition(e){const t=this._scene.getEngine().getInputElementClientRect();t&&(this._pointerX=e.clientX-t.left,this._pointerY=e.clientY-t.top,this._unTranslatedPointerX=this._pointerX,this._unTranslatedPointerY=this._pointerY)}_processPointerMove(e,t){const s=this._scene,i=s.getEngine(),r=i.getInputElement();r&&(r.tabIndex=i.canvasTabIndex,s.doNotHandleCursors||(r.style.cursor=s.defaultCursor)),this._setCursorAndPointerOverMesh(e,t,s);for(const i of s._pointerMoveStage){e=e||this._pickMove(t);const s=!!e?.pickedMesh;e=i.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,s,r)}const n=t.inputIndex>=tr.MouseWheelX&&t.inputIndex<=tr.MouseWheelZ?hi.POINTERWHEEL:hi.POINTERMOVE;let a;s.onPointerMove&&(e=e||this._pickMove(t),s.onPointerMove(t,e,n)),e?(a=new ui(n,t,e),this._setRayOnPointerInfo(e,t)):(a=new ui(n,t,null,this),this._movePointerInfo=a),s.onPointerObservable.hasObservers()&&s.onPointerObservable.notifyObservers(a,n)}_setRayOnPointerInfo(e,t){const s=this._scene;e&&s._pickingAvailable&&(e.ray||(e.ray=s.createPickingRay(t.offsetX,t.offsetY,V.Identity(),s.activeCamera)))}_addCameraPointerObserver(e,t){return this._cameraObserverCount++,this._scene.onPointerObservable.add(e,t)}_removeCameraPointerObserver(e){return this._cameraObserverCount--,this._scene.onPointerObservable.remove(e)}_checkForPicking(){return!!(this._scene.onPointerObservable.observers.length>this._cameraObserverCount||this._scene.onPointerPick)}_checkPrePointerObservable(e,t,s){const i=this._scene,r=new ci(s,t,this._unTranslatedPointerX,this._unTranslatedPointerY);return e&&(r.originalPickingInfo=e,r.ray=e.ray,"xr-near"===t.pointerType&&e.originMesh&&(r.nearInteractionPickingInfo=e)),i.onPrePointerObservable.notifyObservers(r,s),!!r.skipOnPointerObservable}_pickMove(e){const t=this._scene,s=t.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,t.pointerMovePredicate,t.pointerMoveFastCheck,t.cameraToUseForPointers,t.pointerMoveTrianglePredicate);return this._setCursorAndPointerOverMesh(s,e,t),s}_setCursorAndPointerOverMesh(e,t,s){const i=s.getEngine().getInputElement();if(e?.pickedMesh){if(this.setPointerOverMesh(e.pickedMesh,t.pointerId,e,t),!s.doNotHandleCursors&&i&&this._pointerOverMesh){const e=this._pointerOverMesh._getActionManagerForTrigger();e&&e.hasPointerTriggers&&(i.style.cursor=e.hoverCursor||s.hoverCursor)}}else this.setPointerOverMesh(null,t.pointerId,e,t)}simulatePointerMove(e,t){const s=new PointerEvent("pointermove",t);s.inputIndex=tr.Move,this._checkPrePointerObservable(e,s,hi.POINTERMOVE)||this._processPointerMove(e,s)}simulatePointerDown(e,t){const s=new PointerEvent("pointerdown",t);s.inputIndex=s.button+2,this._checkPrePointerObservable(e,s,hi.POINTERDOWN)||this._processPointerDown(e,s)}_processPointerDown(e,t){const s=this._scene;if(e?.pickedMesh){this._pickedDownMesh=e.pickedMesh;const i=e.pickedMesh._getActionManagerForTrigger();if(i){if(i.hasPickTriggers)switch(i.processTrigger(Ze.ACTION_OnPickDownTrigger,qi.CreateNew(e.pickedMesh,t,e)),t.button){case 0:i.processTrigger(Ze.ACTION_OnLeftPickTrigger,qi.CreateNew(e.pickedMesh,t,e));break;case 1:i.processTrigger(Ze.ACTION_OnCenterPickTrigger,qi.CreateNew(e.pickedMesh,t,e));break;case 2:i.processTrigger(Ze.ACTION_OnRightPickTrigger,qi.CreateNew(e.pickedMesh,t,e))}i.hasSpecificTrigger(Ze.ACTION_OnLongPressTrigger)&&window.setTimeout((()=>{const e=s.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,(e=>e.isPickable&&e.isVisible&&e.isReady()&&e.actionManager&&e.actionManager.hasSpecificTrigger(Ze.ACTION_OnLongPressTrigger)&&e===this._pickedDownMesh),!1,s.cameraToUseForPointers);e?.pickedMesh&&i&&0!==this._totalPointersPressed&&Date.now()-this._startingPointerTime>pr.LongPressDelay&&!this._isPointerSwiping()&&(this._startingPointerTime=0,i.processTrigger(Ze.ACTION_OnLongPressTrigger,qi.CreateNew(e.pickedMesh,t)))}),pr.LongPressDelay)}}else for(const i of s._pointerDownStage)e=i.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,!1);let i;const r=hi.POINTERDOWN;e?(s.onPointerDown&&s.onPointerDown(t,e,r),i=new ui(r,t,e),this._setRayOnPointerInfo(e,t)):i=new ui(r,t,null,this),s.onPointerObservable.hasObservers()&&s.onPointerObservable.notifyObservers(i,r)}_isPointerSwiping(){return this._isSwiping}simulatePointerUp(e,t,s){const i=new PointerEvent("pointerup",t);i.inputIndex=tr.Move;const r=new fr;s?r.doubleClick=!0:r.singleClick=!0,this._checkPrePointerObservable(e,i,hi.POINTERUP)||this._processPointerUp(e,i,r)}_processPointerUp(e,t,s){const i=this._scene;if(e?.pickedMesh){if(this._pickedUpMesh=e.pickedMesh,this._pickedDownMesh===this._pickedUpMesh&&(i.onPointerPick&&i.onPointerPick(t,e),s.singleClick&&!s.ignore&&i.onPointerObservable.observers.length>this._cameraObserverCount)){const s=hi.POINTERPICK,r=new ui(s,t,e);this._setRayOnPointerInfo(e,t),i.onPointerObservable.notifyObservers(r,s)}const r=e.pickedMesh._getActionManagerForTrigger();if(r&&!s.ignore){r.processTrigger(Ze.ACTION_OnPickUpTrigger,qi.CreateNew(e.pickedMesh,t,e)),!s.hasSwiped&&s.singleClick&&r.processTrigger(Ze.ACTION_OnPickTrigger,qi.CreateNew(e.pickedMesh,t,e));const i=e.pickedMesh._getActionManagerForTrigger(Ze.ACTION_OnDoublePickTrigger);s.doubleClick&&i&&i.processTrigger(Ze.ACTION_OnDoublePickTrigger,qi.CreateNew(e.pickedMesh,t,e))}}else if(!s.ignore)for(const r of i._pointerUpStage)e=r.action(this._unTranslatedPointerX,this._unTranslatedPointerY,e,t,s.doubleClick);if(this._pickedDownMesh&&this._pickedDownMesh!==this._pickedUpMesh){const e=this._pickedDownMesh._getActionManagerForTrigger(Ze.ACTION_OnPickOutTrigger);e&&e.processTrigger(Ze.ACTION_OnPickOutTrigger,qi.CreateNew(this._pickedDownMesh,t))}if(!s.ignore){const r=new ui(hi.POINTERUP,t,e);if(this._setRayOnPointerInfo(e,t),i.onPointerObservable.notifyObservers(r,hi.POINTERUP),i.onPointerUp&&i.onPointerUp(t,e,hi.POINTERUP),!s.hasSwiped&&!this._skipPointerTap&&!this._isMultiTouchGesture){let r=0;if(s.singleClick?r=hi.POINTERTAP:s.doubleClick&&(r=hi.POINTERDOUBLETAP),r){const s=new ui(r,t,e);i.onPointerObservable.hasObservers()&&i.onPointerObservable.hasSpecificMask(r)&&i.onPointerObservable.notifyObservers(s,r)}}}}isPointerCaptured(e=0){return this._pointerCaptures[e]}attachControl(e=!0,t=!0,s=!0,i=null){const r=this._scene,n=r.getEngine();i||(i=n.getInputElement()),this._alreadyAttached&&this.detachControl(),i&&(this._alreadyAttachedTo=i),this._deviceSourceManager=new _r(n),this._initActionManager=e=>{if(!this._meshPickProceed){const t=r.skipPointerUpPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerUp?null:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerUpPredicate,r.pointerUpFastCheck,r.cameraToUseForPointers,r.pointerUpTrianglePredicate);this._currentPickResult=t,t&&(e=t.hit&&t.pickedMesh?t.pickedMesh._getActionManagerForTrigger():null),this._meshPickProceed=!0}return e},this._delayedSimpleClick=(e,t,s)=>{if((Date.now()-this._previousStartingPointerTime>pr.DoubleClickDelay&&!this._doubleClickOccured||e!==this._previousButtonPressed)&&(this._doubleClickOccured=!1,t.singleClick=!0,t.ignore=!1,this._delayedClicks[e])){const t=this._delayedClicks[e].evt,s=hi.POINTERTAP,i=new ui(s,t,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(s)&&r.onPointerObservable.notifyObservers(i,s),this._delayedClicks[e]=null}},this._initClickEvent=(e,t,s,i)=>{const r=new fr;this._currentPickResult=null;let n=null,a=e.hasSpecificMask(hi.POINTERPICK)||t.hasSpecificMask(hi.POINTERPICK)||e.hasSpecificMask(hi.POINTERTAP)||t.hasSpecificMask(hi.POINTERTAP)||e.hasSpecificMask(hi.POINTERDOUBLETAP)||t.hasSpecificMask(hi.POINTERDOUBLETAP);!a&&Ji&&(n=this._initActionManager(n,r),n&&(a=n.hasPickTriggers));let o=!1;if(a){const a=s.button;if(r.hasSwiped=this._isPointerSwiping(),!r.hasSwiped){let h=!pr.ExclusiveDoubleClickMode;if(h||(h=!e.hasSpecificMask(hi.POINTERDOUBLETAP)&&!t.hasSpecificMask(hi.POINTERDOUBLETAP),h&&!Ji.HasSpecificTrigger(Ze.ACTION_OnDoublePickTrigger)&&(n=this._initActionManager(n,r),n&&(h=!n.hasSpecificTrigger(Ze.ACTION_OnDoublePickTrigger)))),h)(Date.now()-this._previousStartingPointerTime>pr.DoubleClickDelay||a!==this._previousButtonPressed)&&(r.singleClick=!0,i(r,this._currentPickResult),o=!0);else{const e={evt:s,clickInfo:r,timeoutId:window.setTimeout(this._delayedSimpleClick.bind(this,a,r,i),pr.DoubleClickDelay)};this._delayedClicks[a]=e}let l=e.hasSpecificMask(hi.POINTERDOUBLETAP)||t.hasSpecificMask(hi.POINTERDOUBLETAP);!l&&Ji.HasSpecificTrigger(Ze.ACTION_OnDoublePickTrigger)&&(n=this._initActionManager(n,r),n&&(l=n.hasSpecificTrigger(Ze.ACTION_OnDoublePickTrigger))),l&&(a===this._previousButtonPressed&&Date.now()-this._previousStartingPointerTime<pr.DoubleClickDelay&&!this._doubleClickOccured?(r.hasSwiped||this._isPointerSwiping()?(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=a,pr.ExclusiveDoubleClickMode?(this._delayedClicks[a]&&(clearTimeout(this._delayedClicks[a]?.timeoutId),this._delayedClicks[a]=null),i(r,this._previousPickResult)):i(r,this._currentPickResult)):(this._previousStartingPointerTime=0,this._doubleClickOccured=!0,r.doubleClick=!0,r.ignore=!1,pr.ExclusiveDoubleClickMode&&this._delayedClicks[a]&&(clearTimeout(this._delayedClicks[a]?.timeoutId),this._delayedClicks[a]=null),i(r,this._currentPickResult)),o=!0):(this._doubleClickOccured=!1,this._previousStartingPointerTime=this._startingPointerTime,this._previousStartingPointerPosition.x=this._startingPointerPosition.x,this._previousStartingPointerPosition.y=this._startingPointerPosition.y,this._previousButtonPressed=a))}}o||i(r,this._currentPickResult)},this._onPointerMove=e=>{if(this._updatePointerPosition(e),this._isSwiping||-1===this._swipeButtonPressed||(this._isSwiping=Math.abs(this._startingPointerPosition.x-this._pointerX)>pr.DragMovementThreshold||Math.abs(this._startingPointerPosition.y-this._pointerY)>pr.DragMovementThreshold),n.isPointerLock&&n._verifyPointerLock(),this._checkPrePointerObservable(null,e,e.inputIndex>=tr.MouseWheelX&&e.inputIndex<=tr.MouseWheelZ?hi.POINTERWHEEL:hi.POINTERMOVE))return;if(!r.cameraToUseForPointers&&!r.activeCamera)return;if(r.skipPointerMovePicking)return void this._processPointerMove(new Ms,e);r.pointerMovePredicate||(r.pointerMovePredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(e.enablePointerMoveEvents||r.constantlyUpdateMeshUnderPointer||null!==e._getActionManagerForTrigger())&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask)));const t=r._registeredActions>0||r.constantlyUpdateMeshUnderPointer?this._pickMove(e):null;this._processPointerMove(t,e)},this._onPointerDown=e=>{if(this._totalPointersPressed++,this._pickedDownMesh=null,this._meshPickProceed=!1,pr.ExclusiveDoubleClickMode)for(let t=0;t<this._delayedClicks.length;t++)if(this._delayedClicks[t])if(e.button===t)clearTimeout(this._delayedClicks[t]?.timeoutId);else{const e=this._delayedClicks[t].clickInfo;this._doubleClickOccured=!1,e.singleClick=!0,e.ignore=!1;const s=this._delayedClicks[t].evt,i=hi.POINTERTAP,n=new ui(i,s,this._currentPickResult);r.onPointerObservable.hasObservers()&&r.onPointerObservable.hasSpecificMask(i)&&r.onPointerObservable.notifyObservers(n,i),this._delayedClicks[t]=null}if(this._updatePointerPosition(e),-1===this._swipeButtonPressed&&(this._swipeButtonPressed=e.button),r.preventDefaultOnPointerDown&&i&&(e.preventDefault(),i.focus()),this._startingPointerPosition.x=this._pointerX,this._startingPointerPosition.y=this._pointerY,this._startingPointerTime=Date.now(),this._checkPrePointerObservable(null,e,hi.POINTERDOWN))return;if(!r.cameraToUseForPointers&&!r.activeCamera)return;let t;this._pointerCaptures[e.pointerId]=!0,r.pointerDownPredicate||(r.pointerDownPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask))),this._pickedDownMesh=null,t=r.skipPointerDownPicking||0===r._registeredActions&&!this._checkForPicking()&&!r.onPointerDown?new Ms:r.pick(this._unTranslatedPointerX,this._unTranslatedPointerY,r.pointerDownPredicate,r.pointerDownFastCheck,r.cameraToUseForPointers,r.pointerDownTrianglePredicate),this._processPointerDown(t,e)},this._onPointerUp=e=>{0!==this._totalPointersPressed&&(this._totalPointersPressed--,this._pickedUpMesh=null,this._meshPickProceed=!1,this._updatePointerPosition(e),r.preventDefaultOnPointerUp&&i&&(e.preventDefault(),i.focus()),this._initClickEvent(r.onPrePointerObservable,r.onPointerObservable,e,((t,s)=>{if(r.onPrePointerObservable.hasObservers()&&(this._skipPointerTap=!1,!t.ignore)){if(this._checkPrePointerObservable(null,e,hi.POINTERUP))return this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1),void(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1));t.hasSwiped||(t.singleClick&&r.onPrePointerObservable.hasSpecificMask(hi.POINTERTAP)&&this._checkPrePointerObservable(null,e,hi.POINTERTAP)&&(this._skipPointerTap=!0),t.doubleClick&&r.onPrePointerObservable.hasSpecificMask(hi.POINTERDOUBLETAP)&&this._checkPrePointerObservable(null,e,hi.POINTERDOUBLETAP)&&(this._skipPointerTap=!0))}this._pointerCaptures[e.pointerId]?(0===e.buttons&&(this._pointerCaptures[e.pointerId]=!1),(r.cameraToUseForPointers||r.activeCamera)&&(r.pointerUpPredicate||(r.pointerUpPredicate=e=>e.isPickable&&e.isVisible&&e.isReady()&&e.isEnabled()&&(!r.cameraToUseForPointers||!!(r.cameraToUseForPointers.layerMask&e.layerMask))),!this._meshPickProceed&&(Ji&&Ji.HasTriggers||this._checkForPicking()||r.onPointerUp)&&this._initActionManager(null,t),s||(s=this._currentPickResult),this._processPointerUp(s,e,t),this._previousPickResult=this._currentPickResult,this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1))):this._swipeButtonPressed===e.button&&(this._isSwiping=!1,this._swipeButtonPressed=-1)})))},this._onKeyDown=e=>{const t=Li.KEYDOWN;if(r.onPreKeyboardObservable.hasObservers()){const s=new Ni(t,e);if(r.onPreKeyboardObservable.notifyObservers(s,t),s.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const s=new Fi(t,e);r.onKeyboardObservable.notifyObservers(s,t)}r.actionManager&&r.actionManager.processTrigger(Ze.ACTION_OnKeyDownTrigger,qi.CreateNewFromScene(r,e))},this._onKeyUp=e=>{const t=Li.KEYUP;if(r.onPreKeyboardObservable.hasObservers()){const s=new Ni(t,e);if(r.onPreKeyboardObservable.notifyObservers(s,t),s.skipOnKeyboardObservable)return}if(r.onKeyboardObservable.hasObservers()){const s=new Fi(t,e);r.onKeyboardObservable.notifyObservers(s,t)}r.actionManager&&r.actionManager.processTrigger(Ze.ACTION_OnKeyUpTrigger,qi.CreateNewFromScene(r,e))},this._deviceSourceManager.onDeviceConnectedObservable.add((i=>{i.deviceType===er.Mouse?i.onInputChangedObservable.add((r=>{this._originMouseEvent=r,r.inputIndex===tr.LeftClick||r.inputIndex===tr.MiddleClick||r.inputIndex===tr.RightClick||r.inputIndex===tr.BrowserBack||r.inputIndex===tr.BrowserForward?t&&1===i.getInput(r.inputIndex)?this._onPointerDown(r):e&&0===i.getInput(r.inputIndex)&&this._onPointerUp(r):s&&(r.inputIndex===tr.Move?this._onPointerMove(r):r.inputIndex!==tr.MouseWheelX&&r.inputIndex!==tr.MouseWheelY&&r.inputIndex!==tr.MouseWheelZ||this._onPointerMove(r))})):i.deviceType===er.Touch?i.onInputChangedObservable.add((r=>{r.inputIndex===tr.LeftClick&&(t&&1===i.getInput(r.inputIndex)?(this._onPointerDown(r),this._totalPointersPressed>1&&(this._isMultiTouchGesture=!0)):e&&0===i.getInput(r.inputIndex)&&(this._onPointerUp(r),0===this._totalPointersPressed&&(this._isMultiTouchGesture=!1))),s&&r.inputIndex===tr.Move&&this._onPointerMove(r)})):i.deviceType===er.Keyboard&&i.onInputChangedObservable.add((e=>{"keydown"===e.type?this._onKeyDown(e):"keyup"===e.type&&this._onKeyUp(e)}))})),this._alreadyAttached=!0}detachControl(){this._alreadyAttached&&(this._deviceSourceManager.dispose(),this._deviceSourceManager=null,this._alreadyAttachedTo&&!this._scene.doNotHandleCursors&&(this._alreadyAttachedTo.style.cursor=this._scene.defaultCursor),this._alreadyAttached=!1,this._alreadyAttachedTo=null)}setPointerOverMesh(e,t=0,s,i){if(!(this._meshUnderPointerId[t]!==e||e&&e._internalAbstractMeshDataInfo._pointerOverDisableMeshTesting))return;const r=this._meshUnderPointerId[t];let n;r&&(n=r._getActionManagerForTrigger(Ze.ACTION_OnPointerOutTrigger),n&&n.processTrigger(Ze.ACTION_OnPointerOutTrigger,qi.CreateNew(r,i,{pointerId:t}))),e?(this._meshUnderPointerId[t]=e,this._pointerOverMesh=e,n=e._getActionManagerForTrigger(Ze.ACTION_OnPointerOverTrigger),n&&n.processTrigger(Ze.ACTION_OnPointerOverTrigger,qi.CreateNew(e,i,{pointerId:t,pickResult:s}))):(delete this._meshUnderPointerId[t],this._pointerOverMesh=null)}getPointerOverMesh(){return this.meshUnderPointer}_invalidateMesh(e){this._pointerOverMesh===e&&(this._pointerOverMesh=null),this._pickedDownMesh===e&&(this._pickedDownMesh=null),this._pickedUpMesh===e&&(this._pickedUpMesh=null);for(const t in this._meshUnderPointerId)this._meshUnderPointerId[t]===e&&delete this._meshUnderPointerId[t]}}pr.DragMovementThreshold=10,pr.LongPressDelay=500,pr.DoubleClickDelay=300,pr.ExclusiveDoubleClickMode=!1;class mr{get min(){return this._min}get max(){return this._max}get average(){return this._average}get lastSecAverage(){return this._lastSecAverage}get current(){return this._current}get total(){return this._totalAccumulated}get count(){return this._totalValueCount}constructor(){this._startMonitoringTime=0,this._min=0,this._max=0,this._average=0,this._lastSecAverage=0,this._current=0,this._totalValueCount=0,this._totalAccumulated=0,this._lastSecAccumulated=0,this._lastSecTime=0,this._lastSecValueCount=0}fetchNewFrame(){this._totalValueCount++,this._current=0,this._lastSecValueCount++}addCount(e,t){mr.Enabled&&(this._current+=e,t&&this._fetchResult())}beginMonitoring(){mr.Enabled&&(this._startMonitoringTime=fe.Now)}endMonitoring(e=!0){if(!mr.Enabled)return;e&&this.fetchNewFrame();const t=fe.Now;this._current=t-this._startMonitoringTime,e&&this._fetchResult()}endFrame(){this._fetchResult()}_fetchResult(){this._totalAccumulated+=this._current,this._lastSecAccumulated+=this._current,this._min=Math.min(this._min,this._current),this._max=Math.max(this._max,this._current),this._average=this._totalAccumulated/this._totalValueCount;const e=fe.Now;e-this._lastSecTime>1e3&&(this._lastSecAverage=this._lastSecAccumulated/this._lastSecValueCount,this._lastSecTime=e,this._lastSecAccumulated=0,this._lastSecValueCount=0)}}mr.Enabled=!0;class gr{static get UniqueId(){const e=this._UniqueIdCounter;return this._UniqueIdCounter++,e}}gr._UniqueIdCounter=1;class Tr{constructor(){this.pointerDownFastCheck=!1,this.pointerUpFastCheck=!1,this.pointerMoveFastCheck=!1,this.skipPointerMovePicking=!1,this.skipPointerDownPicking=!1,this.skipPointerUpPicking=!1}}var Er,Ar;!function(e){e[e.BackwardCompatible=0]="BackwardCompatible",e[e.Intermediate=1]="Intermediate",e[e.Aggressive=2]="Aggressive"}(Er||(Er={}));class yr extends Xi{static DefaultMaterialFactory(e){throw Y("StandardMaterial")}static CollisionCoordinatorFactory(){throw Y("DefaultCollisionCoordinator")}get environmentTexture(){return this._environmentTexture}set environmentTexture(e){this._environmentTexture!==e&&(this._environmentTexture=e,this.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}get performancePriority(){return this._performancePriority}set performancePriority(e){if(e!==this._performancePriority){switch(this._performancePriority=e,e){case 0:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!1,this.autoClear=!0;break;case 1:this.skipFrustumClipping=!1,this._renderingManager.maintainStateBetweenFrames=!1,this.skipPointerMovePicking=!0,this.autoClear=!1;break;case 2:this.skipFrustumClipping=!0,this._renderingManager.maintainStateBetweenFrames=!0,this.skipPointerMovePicking=!0,this.autoClear=!1}this.onScenePerformancePriorityChangedObservable.notifyObservers(e)}}set forceWireframe(e){this._forceWireframe!==e&&(this._forceWireframe=e,this.markAllMaterialsAsDirty(Ze.MATERIAL_MiscDirtyFlag))}get forceWireframe(){return this._forceWireframe}set skipFrustumClipping(e){this._skipFrustumClipping!==e&&(this._skipFrustumClipping=e)}get skipFrustumClipping(){return this._skipFrustumClipping}set forcePointsCloud(e){this._forcePointsCloud!==e&&(this._forcePointsCloud=e,this.markAllMaterialsAsDirty(Ze.MATERIAL_MiscDirtyFlag))}get forcePointsCloud(){return this._forcePointsCloud}get animationPropertiesOverride(){return this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set beforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),e&&(this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e))}set afterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),e&&(this._onAfterRenderObserver=this.onAfterRenderObservable.add(e))}set beforeCameraRender(e){this._onBeforeCameraRenderObserver&&this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver),this._onBeforeCameraRenderObserver=this.onBeforeCameraRenderObservable.add(e)}set afterCameraRender(e){this._onAfterCameraRenderObserver&&this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver),this._onAfterCameraRenderObserver=this.onAfterCameraRenderObservable.add(e)}get pointerDownPredicate(){return this._pointerPickingConfiguration.pointerDownPredicate}set pointerDownPredicate(e){this._pointerPickingConfiguration.pointerDownPredicate=e}get pointerUpPredicate(){return this._pointerPickingConfiguration.pointerUpPredicate}set pointerUpPredicate(e){this._pointerPickingConfiguration.pointerUpPredicate=e}get pointerMovePredicate(){return this._pointerPickingConfiguration.pointerMovePredicate}set pointerMovePredicate(e){this._pointerPickingConfiguration.pointerMovePredicate=e}get pointerDownFastCheck(){return this._pointerPickingConfiguration.pointerDownFastCheck}set pointerDownFastCheck(e){this._pointerPickingConfiguration.pointerDownFastCheck=e}get pointerUpFastCheck(){return this._pointerPickingConfiguration.pointerUpFastCheck}set pointerUpFastCheck(e){this._pointerPickingConfiguration.pointerUpFastCheck=e}get pointerMoveFastCheck(){return this._pointerPickingConfiguration.pointerMoveFastCheck}set pointerMoveFastCheck(e){this._pointerPickingConfiguration.pointerMoveFastCheck=e}get skipPointerMovePicking(){return this._pointerPickingConfiguration.skipPointerMovePicking}set skipPointerMovePicking(e){this._pointerPickingConfiguration.skipPointerMovePicking=e}get skipPointerDownPicking(){return this._pointerPickingConfiguration.skipPointerDownPicking}set skipPointerDownPicking(e){this._pointerPickingConfiguration.skipPointerDownPicking=e}get skipPointerUpPicking(){return this._pointerPickingConfiguration.skipPointerUpPicking}set skipPointerUpPicking(e){this._pointerPickingConfiguration.skipPointerUpPicking=e}get unTranslatedPointer(){return this._inputManager.unTranslatedPointer}static get DragMovementThreshold(){return pr.DragMovementThreshold}static set DragMovementThreshold(e){pr.DragMovementThreshold=e}static get LongPressDelay(){return pr.LongPressDelay}static set LongPressDelay(e){pr.LongPressDelay=e}static get DoubleClickDelay(){return pr.DoubleClickDelay}static set DoubleClickDelay(e){pr.DoubleClickDelay=e}static get ExclusiveDoubleClickMode(){return pr.ExclusiveDoubleClickMode}static set ExclusiveDoubleClickMode(e){pr.ExclusiveDoubleClickMode=e}bindEyePosition(e,t="vEyePosition",s=!1){const i=this._forcedViewPosition?this._forcedViewPosition:this._mirroredCameraPosition?this._mirroredCameraPosition:this.activeCamera.globalPosition,r=this.useRightHandedSystem===(null!=this._mirroredCameraPosition);return z.Vector4[0].set(i.x,i.y,i.z,r?-1:1),e&&(s?e.setFloat3(t,z.Vector4[0].x,z.Vector4[0].y,z.Vector4[0].z):e.setVector4(t,z.Vector4[0])),z.Vector4[0]}finalizeSceneUbo(){const e=this.getSceneUniformBuffer(),t=this.bindEyePosition(null);return e.updateFloat4("vEyePosition",t.x,t.y,t.z,t.w),e.update(),e}set useRightHandedSystem(e){this._useRightHandedSystem!==e&&(this._useRightHandedSystem=e,this.markAllMaterialsAsDirty(Ze.MATERIAL_MiscDirtyFlag))}get useRightHandedSystem(){return this._useRightHandedSystem}setStepId(e){this._currentStepId=e}getStepId(){return this._currentStepId}getInternalStep(){return this._currentInternalStep}set fogEnabled(e){this._fogEnabled!==e&&(this._fogEnabled=e,this.markAllMaterialsAsDirty(Ze.MATERIAL_MiscDirtyFlag))}get fogEnabled(){return this._fogEnabled}set fogMode(e){this._fogMode!==e&&(this._fogMode=e,this.markAllMaterialsAsDirty(Ze.MATERIAL_MiscDirtyFlag))}get fogMode(){return this._fogMode}get prePass(){return!!this.prePassRenderer&&this.prePassRenderer.defaultRT.enabled}set shadowsEnabled(e){this._shadowsEnabled!==e&&(this._shadowsEnabled=e,this.markAllMaterialsAsDirty(Ze.MATERIAL_LightDirtyFlag))}get shadowsEnabled(){return this._shadowsEnabled}set lightsEnabled(e){this._lightsEnabled!==e&&(this._lightsEnabled=e,this.markAllMaterialsAsDirty(Ze.MATERIAL_LightDirtyFlag))}get lightsEnabled(){return this._lightsEnabled}get activeCameras(){return this._activeCameras}set activeCameras(e){this._unObserveActiveCameras&&(this._unObserveActiveCameras(),this._unObserveActiveCameras=null),e&&(this._unObserveActiveCameras=x(e,(()=>{this.onActiveCamerasChanged.notifyObservers(this)}))),this._activeCameras=e}get activeCamera(){return this._activeCamera}set activeCamera(e){e!==this._activeCamera&&(this._activeCamera=e,this.onActiveCameraChanged.notifyObservers(this))}get defaultMaterial(){return this._defaultMaterial||(this._defaultMaterial=yr.DefaultMaterialFactory(this)),this._defaultMaterial}set defaultMaterial(e){this._defaultMaterial=e}set texturesEnabled(e){this._texturesEnabled!==e&&(this._texturesEnabled=e,this.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}get texturesEnabled(){return this._texturesEnabled}set skeletonsEnabled(e){this._skeletonsEnabled!==e&&(this._skeletonsEnabled=e,this.markAllMaterialsAsDirty(Ze.MATERIAL_AttributesDirtyFlag))}get skeletonsEnabled(){return this._skeletonsEnabled}get collisionCoordinator(){return this._collisionCoordinator||(this._collisionCoordinator=yr.CollisionCoordinatorFactory(),this._collisionCoordinator.init(this)),this._collisionCoordinator}get renderingManager(){return this._renderingManager}get frustumPlanes(){return this._frustumPlanes}_registerTransientComponents(){if(this._transientComponents.length>0){for(const e of this._transientComponents)e.register();this._transientComponents.length=0}}_addComponent(e){this._components.push(e),this._transientComponents.push(e);const t=e;t.addFromContainer&&t.serialize&&this._serializableComponents.push(t)}_getComponent(e){for(const t of this._components)if(t.name===e)return t;return null}constructor(e,t){super(),this._inputManager=new pr(this),this.cameraToUseForPointers=null,this._isScene=!0,this._blockEntityCollection=!1,this.autoClear=!0,this.autoClearDepthAndStencil=!0,this.clearColor=new te(.2,.2,.3,1),this.ambientColor=new ee(0,0,0),this.environmentIntensity=1,this._performancePriority=0,this.onScenePerformancePriorityChangedObservable=new g,this._forceWireframe=!1,this._skipFrustumClipping=!1,this._forcePointsCloud=!1,this.animationsEnabled=!0,this._animationPropertiesOverride=null,this.useConstantAnimationDeltaTime=!1,this.constantlyUpdateMeshUnderPointer=!1,this.hoverCursor="pointer",this.defaultCursor="",this.doNotHandleCursors=!1,this.preventDefaultOnPointerDown=!0,this.preventDefaultOnPointerUp=!0,this.metadata=null,this.reservedDataStore=null,this.disableOfflineSupportExceptionRules=[],this.onDisposeObservable=new g,this._onDisposeObserver=null,this.onBeforeRenderObservable=new g,this._onBeforeRenderObserver=null,this.onAfterRenderObservable=new g,this.onAfterRenderCameraObservable=new g,this._onAfterRenderObserver=null,this.onBeforeAnimationsObservable=new g,this.onAfterAnimationsObservable=new g,this.onBeforeDrawPhaseObservable=new g,this.onAfterDrawPhaseObservable=new g,this.onReadyObservable=new g,this.onBeforeCameraRenderObservable=new g,this._onBeforeCameraRenderObserver=null,this.onAfterCameraRenderObservable=new g,this._onAfterCameraRenderObserver=null,this.onBeforeActiveMeshesEvaluationObservable=new g,this.onAfterActiveMeshesEvaluationObservable=new g,this.onBeforeParticlesRenderingObservable=new g,this.onAfterParticlesRenderingObservable=new g,this.onDataLoadedObservable=new g,this.onNewCameraAddedObservable=new g,this.onCameraRemovedObservable=new g,this.onNewLightAddedObservable=new g,this.onLightRemovedObservable=new g,this.onNewGeometryAddedObservable=new g,this.onGeometryRemovedObservable=new g,this.onNewTransformNodeAddedObservable=new g,this.onTransformNodeRemovedObservable=new g,this.onNewMeshAddedObservable=new g,this.onMeshRemovedObservable=new g,this.onNewSkeletonAddedObservable=new g,this.onSkeletonRemovedObservable=new g,this.onNewMaterialAddedObservable=new g,this.onNewMultiMaterialAddedObservable=new g,this.onMaterialRemovedObservable=new g,this.onMultiMaterialRemovedObservable=new g,this.onNewTextureAddedObservable=new g,this.onTextureRemovedObservable=new g,this.onBeforeRenderTargetsRenderObservable=new g,this.onAfterRenderTargetsRenderObservable=new g,this.onBeforeStepObservable=new g,this.onAfterStepObservable=new g,this.onActiveCameraChanged=new g,this.onActiveCamerasChanged=new g,this.onBeforeRenderingGroupObservable=new g,this.onAfterRenderingGroupObservable=new g,this.onMeshImportedObservable=new g,this.onAnimationFileImportedObservable=new g,this._registeredForLateAnimationBindings=new $t(256),this._pointerPickingConfiguration=new Tr,this.onPrePointerObservable=new g,this.onPointerObservable=new g,this.onPreKeyboardObservable=new g,this.onKeyboardObservable=new g,this._useRightHandedSystem=!1,this._timeAccumulator=0,this._currentStepId=0,this._currentInternalStep=0,this._fogEnabled=!0,this._fogMode=yr.FOGMODE_NONE,this.fogColor=new ee(.2,.2,.3),this.fogDensity=.1,this.fogStart=0,this.fogEnd=1e3,this.needsPreviousWorldMatrices=!1,this._shadowsEnabled=!0,this._lightsEnabled=!0,this._unObserveActiveCameras=null,this._texturesEnabled=!0,this.physicsEnabled=!0,this.particlesEnabled=!0,this.spritesEnabled=!0,this._skeletonsEnabled=!0,this.lensFlaresEnabled=!0,this.collisionsEnabled=!0,this.gravity=new U(0,-9.807,0),this.postProcessesEnabled=!0,this.renderTargetsEnabled=!0,this.dumpNextRenderTargets=!1,this.customRenderTargets=[],this.importedMeshesFiles=[],this.probesEnabled=!0,this._meshesForIntersections=new $t(256),this.proceduralTexturesEnabled=!0,this._totalVertices=new mr,this._activeIndices=new mr,this._activeParticles=new mr,this._activeBones=new mr,this._animationTime=0,this.animationTimeScale=1,this._renderId=0,this._frameId=0,this._executeWhenReadyTimeoutId=null,this._intermediateRendering=!1,this._defaultFrameBufferCleared=!1,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1,this._toBeDisposed=new Array(256),this._activeRequests=new Array,this._pendingData=new Array,this._isDisposed=!1,this.dispatchAllSubMeshesOfActiveMeshes=!1,this._activeMeshes=new Zt(256),this._processedMaterials=new Zt(256),this._renderTargets=new $t(256),this._materialsRenderTargets=new $t(256),this._activeParticleSystems=new Zt(256),this._activeSkeletons=new $t(32),this._softwareSkinnedMeshes=new $t(32),this._activeAnimatables=new Array,this._transformMatrix=V.Zero(),this.requireLightSorting=!1,this._components=[],this._serializableComponents=[],this._transientComponents=[],this._beforeCameraUpdateStage=ti.Create(),this._beforeClearStage=ti.Create(),this._beforeRenderTargetClearStage=ti.Create(),this._gatherRenderTargetsStage=ti.Create(),this._gatherActiveCameraRenderTargetsStage=ti.Create(),this._isReadyForMeshStage=ti.Create(),this._beforeEvaluateActiveMeshStage=ti.Create(),this._evaluateSubMeshStage=ti.Create(),this._preActiveMeshStage=ti.Create(),this._cameraDrawRenderTargetStage=ti.Create(),this._beforeCameraDrawStage=ti.Create(),this._beforeRenderTargetDrawStage=ti.Create(),this._beforeRenderingGroupDrawStage=ti.Create(),this._beforeRenderingMeshStage=ti.Create(),this._afterRenderingMeshStage=ti.Create(),this._afterRenderingGroupDrawStage=ti.Create(),this._afterCameraDrawStage=ti.Create(),this._afterCameraPostProcessStage=ti.Create(),this._afterRenderTargetDrawStage=ti.Create(),this._afterRenderTargetPostProcessStage=ti.Create(),this._afterRenderStage=ti.Create(),this._pointerMoveStage=ti.Create(),this._pointerDownStage=ti.Create(),this._pointerUpStage=ti.Create(),this._geometriesByUniqueId=null,this._defaultMeshCandidates={data:[],length:0},this._defaultSubMeshCandidates={data:[],length:0},this._preventFreeActiveMeshesAndRenderingGroups=!1,this._activeMeshesFrozen=!1,this._activeMeshesFrozenButKeepClipping=!1,this._skipEvaluateActiveMeshesCompletely=!1,this._allowPostProcessClearColor=!0,this.getDeterministicFrameTime=()=>this._engine.getTimeStep(),this._registeredActions=0,this._blockMaterialDirtyMechanism=!1,this._perfCollector=null,this.activeCameras=[];const s={useGeometryUniqueIdsMap:!0,useMaterialMeshMap:!0,useClonedMeshMap:!0,virtual:!1,...t};e=this._engine=e||C.LastCreatedEngine,s.virtual?e._virtualScenes.push(this):(C._LastCreatedScene=this,e.scenes.push(this)),this._uid=null,this._renderingManager=new $i(this),Qi&&(this.postProcessManager=new Qi(this)),oe()&&this.attachControl(),this._createUbo(),Ki&&(this._imageProcessingConfiguration=new Ki),this.setDefaultCandidateProviders(),s.useGeometryUniqueIdsMap&&(this._geometriesByUniqueId={}),this.useMaterialMeshMap=s.useMaterialMeshMap,this.useClonedMeshMap=s.useClonedMeshMap,t&&t.virtual||e.onNewSceneAddedObservable.notifyObservers(this)}getClassName(){return"Scene"}_getDefaultMeshCandidates(){return this._defaultMeshCandidates.data=this.meshes,this._defaultMeshCandidates.length=this.meshes.length,this._defaultMeshCandidates}_getDefaultSubMeshCandidates(e){return this._defaultSubMeshCandidates.data=e.subMeshes,this._defaultSubMeshCandidates.length=e.subMeshes.length,this._defaultSubMeshCandidates}setDefaultCandidateProviders(){this.getActiveMeshCandidates=()=>this._getDefaultMeshCandidates(),this.getActiveSubMeshCandidates=e=>this._getDefaultSubMeshCandidates(e),this.getIntersectingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e),this.getCollidingSubMeshCandidates=(e,t)=>this._getDefaultSubMeshCandidates(e)}get meshUnderPointer(){return this._inputManager.meshUnderPointer}get pointerX(){return this._inputManager.pointerX}set pointerX(e){this._inputManager.pointerX=e}get pointerY(){return this._inputManager.pointerY}set pointerY(e){this._inputManager.pointerY=e}getCachedMaterial(){return this._cachedMaterial}getCachedEffect(){return this._cachedEffect}getCachedVisibility(){return this._cachedVisibility}isCachedMaterialInvalid(e,t,s=1){return this._cachedEffect!==t||this._cachedMaterial!==e||this._cachedVisibility!==s}getEngine(){return this._engine}getTotalVertices(){return this._totalVertices.current}get totalVerticesPerfCounter(){return this._totalVertices}getActiveIndices(){return this._activeIndices.current}get totalActiveIndicesPerfCounter(){return this._activeIndices}getActiveParticles(){return this._activeParticles.current}get activeParticlesPerfCounter(){return this._activeParticles}getActiveBones(){return this._activeBones.current}get activeBonesPerfCounter(){return this._activeBones}getActiveMeshes(){return this._activeMeshes}getAnimationRatio(){return void 0!==this._animationRatio?this._animationRatio:1}getRenderId(){return this._renderId}getFrameId(){return this._frameId}incrementRenderId(){this._renderId++}_createUbo(){this.setSceneUniformBuffer(this.createSceneUniformBuffer())}simulatePointerMove(e,t){return this._inputManager.simulatePointerMove(e,t),this}simulatePointerDown(e,t){return this._inputManager.simulatePointerDown(e,t),this}simulatePointerUp(e,t,s){return this._inputManager.simulatePointerUp(e,t,s),this}isPointerCaptured(e=0){return this._inputManager.isPointerCaptured(e)}attachControl(e=!0,t=!0,s=!0){this._inputManager.attachControl(e,t,s)}detachControl(){this._inputManager.detachControl()}isReady(e=!0){if(this._isDisposed)return!1;let t;const s=this.getEngine(),i=s.currentRenderPassId;s.currentRenderPassId=this.activeCamera?.renderPassId??i;let r=!0;for(this._pendingData.length>0&&(r=!1),this.prePassRenderer?.update(),this.useOrderIndependentTransparency&&this.depthPeelingRenderer&&(r&&=this.depthPeelingRenderer.isReady()),e&&(this._processedMaterials.reset(),this._materialsRenderTargets.reset()),t=0;t<this.meshes.length;t++){const i=this.meshes[t];if(!i.subMeshes||0===i.subMeshes.length)continue;if(!i.isReady(!0)){r=!1;continue}const n=i.hasThinInstances||"InstancedMesh"===i.getClassName()||"InstancedLinesMesh"===i.getClassName()||s.getCaps().instancedArrays&&i.instances.length>0;for(const e of this._isReadyForMeshStage)e.action(i,n)||(r=!1);if(!e)continue;const a=i.material||this.defaultMaterial;if(a)if(a._storeEffectOnSubMeshes)for(const e of i.subMeshes){const t=e.getMaterial();t&&t.hasRenderTargetTextures&&null!=t.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(t)&&(this._processedMaterials.push(t),this._materialsRenderTargets.concatWithNoDuplicate(t.getRenderTargetTextures()))}else a.hasRenderTargetTextures&&null!=a.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(a)&&(this._processedMaterials.push(a),this._materialsRenderTargets.concatWithNoDuplicate(a.getRenderTargetTextures()))}if(e)for(t=0;t<this._materialsRenderTargets.length;++t){this._materialsRenderTargets.data[t].isReadyForRendering()||(r=!1)}for(t=0;t<this.geometries.length;t++){this.geometries[t].delayLoadState===Ze.DELAYLOADSTATE_LOADING&&(r=!1)}if(this.activeCameras&&this.activeCameras.length>0)for(const e of this.activeCameras)e.isReady(!0)||(r=!1);else this.activeCamera&&(this.activeCamera.isReady(!0)||(r=!1));for(const e of this.particleSystems)e.isReady()||(r=!1);if(this.layers)for(const e of this.layers)e.isReady()||(r=!1);return s.areAllEffectsReady()||(r=!1),s.currentRenderPassId=i,r}resetCachedMaterial(){this._cachedMaterial=null,this._cachedEffect=null,this._cachedVisibility=null}registerBeforeRender(e){this.onBeforeRenderObservable.add(e)}unregisterBeforeRender(e){this.onBeforeRenderObservable.removeCallback(e)}registerAfterRender(e){this.onAfterRenderObservable.add(e)}unregisterAfterRender(e){this.onAfterRenderObservable.removeCallback(e)}_executeOnceBeforeRender(e){const t=()=>{e(),setTimeout((()=>{this.unregisterBeforeRender(t)}))};this.registerBeforeRender(t)}executeOnceBeforeRender(e,t){void 0!==t?setTimeout((()=>{this._executeOnceBeforeRender(e)}),t):this._executeOnceBeforeRender(e)}addPendingData(e){this._pendingData.push(e)}removePendingData(e){const t=this.isLoading,s=this._pendingData.indexOf(e);-1!==s&&this._pendingData.splice(s,1),t&&!this.isLoading&&this.onDataLoadedObservable.notifyObservers(this)}getWaitingItemsCount(){return this._pendingData.length}get isLoading(){return this._pendingData.length>0}executeWhenReady(e,t=!1){this.onReadyObservable.addOnce(e),null===this._executeWhenReadyTimeoutId&&this._checkIsReady(t)}whenReadyAsync(e=!1){return new Promise((t=>{this.executeWhenReady((()=>{t()}),e)}))}_checkIsReady(e=!1){return this._registerTransientComponents(),this.isReady(e)?(this.onReadyObservable.notifyObservers(this),this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):this._isDisposed?(this.onReadyObservable.clear(),void(this._executeWhenReadyTimeoutId=null)):void(this._executeWhenReadyTimeoutId=setTimeout((()=>{this.incrementRenderId(),this._checkIsReady(e)}),100))}get animatables(){return this._activeAnimatables}resetLastAnimationTimeFrame(){this._animationTimeLast=fe.Now}getViewMatrix(){return this._viewMatrix}getProjectionMatrix(){return this._projectionMatrix}getTransformMatrix(){return this._transformMatrix}setTransformMatrix(e,t,s,i){s||i||!this._multiviewSceneUbo||(this._multiviewSceneUbo.dispose(),this._multiviewSceneUbo=null),this._viewUpdateFlag===e.updateFlag&&this._projectionUpdateFlag===t.updateFlag||(this._viewUpdateFlag=e.updateFlag,this._projectionUpdateFlag=t.updateFlag,this._viewMatrix=e,this._projectionMatrix=t,this._viewMatrix.multiplyToRef(this._projectionMatrix,this._transformMatrix),this._frustumPlanes?ts.GetPlanesToRef(this._transformMatrix,this._frustumPlanes):this._frustumPlanes=ts.GetPlanes(this._transformMatrix),this._multiviewSceneUbo&&this._multiviewSceneUbo.useUbo?this._updateMultiviewUbo(s,i):this._sceneUbo.useUbo&&(this._sceneUbo.updateMatrix("viewProjection",this._transformMatrix),this._sceneUbo.updateMatrix("view",this._viewMatrix),this._sceneUbo.updateMatrix("projection",this._projectionMatrix)))}getSceneUniformBuffer(){return this._multiviewSceneUbo?this._multiviewSceneUbo:this._sceneUbo}createSceneUniformBuffer(e){const t=new Ls(this._engine,void 0,!1,e??"scene");return t.addUniform("viewProjection",16),t.addUniform("view",16),t.addUniform("projection",16),t.addUniform("vEyePosition",4),t}setSceneUniformBuffer(e){this._sceneUbo=e,this._viewUpdateFlag=-1,this._projectionUpdateFlag=-1}getUniqueId(){return gr.UniqueId}addMesh(e,t=!1){this._blockEntityCollection||(this.meshes.push(e),e._resyncLightSources(),e.parent||e._addToSceneRootNodes(),this.onNewMeshAddedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.addMesh(e)})))}removeMesh(e,t=!1){const s=this.meshes.indexOf(e);return-1!==s&&(this.meshes.splice(s,1),e.parent||e._removeFromSceneRootNodes()),this._inputManager._invalidateMesh(e),this.onMeshRemovedObservable.notifyObservers(e),t&&e.getChildMeshes().forEach((e=>{this.removeMesh(e)})),s}addTransformNode(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneTransformNodesArray||(e._indexInSceneTransformNodesArray=this.transformNodes.length,this.transformNodes.push(e),e.parent||e._addToSceneRootNodes(),this.onNewTransformNodeAddedObservable.notifyObservers(e))}removeTransformNode(e){const t=e._indexInSceneTransformNodesArray;if(-1!==t){if(t!==this.transformNodes.length-1){const e=this.transformNodes[this.transformNodes.length-1];this.transformNodes[t]=e,e._indexInSceneTransformNodesArray=t}e._indexInSceneTransformNodesArray=-1,this.transformNodes.pop(),e.parent||e._removeFromSceneRootNodes()}return this.onTransformNodeRemovedObservable.notifyObservers(e),t}removeSkeleton(e){const t=this.skeletons.indexOf(e);return-1!==t&&(this.skeletons.splice(t,1),this.onSkeletonRemovedObservable.notifyObservers(e),this._executeActiveContainerCleanup(this._activeSkeletons)),t}removeMorphTargetManager(e){const t=this.morphTargetManagers.indexOf(e);return-1!==t&&this.morphTargetManagers.splice(t,1),t}removeLight(e){const t=this.lights.indexOf(e);if(-1!==t){for(const t of this.meshes)t._removeLightSource(e,!1);this.lights.splice(t,1),this.sortLightsByPriority(),e.parent||e._removeFromSceneRootNodes()}return this.onLightRemovedObservable.notifyObservers(e),t}removeCamera(e){const t=this.cameras.indexOf(e);if(-1!==t&&(this.cameras.splice(t,1),e.parent||e._removeFromSceneRootNodes()),this.activeCameras){const t=this.activeCameras.indexOf(e);-1!==t&&this.activeCameras.splice(t,1)}return this.activeCamera===e&&(this.cameras.length>0?this.activeCamera=this.cameras[0]:this.activeCamera=null),this.onCameraRemovedObservable.notifyObservers(e),t}removeParticleSystem(e){const t=this.particleSystems.indexOf(e);return-1!==t&&(this.particleSystems.splice(t,1),this._executeActiveContainerCleanup(this._activeParticleSystems)),t}removeAnimation(e){const t=this.animations.indexOf(e);return-1!==t&&this.animations.splice(t,1),t}stopAnimation(e,t,s){}removeAnimationGroup(e){const t=this.animationGroups.indexOf(e);return-1!==t&&this.animationGroups.splice(t,1),t}removeMultiMaterial(e){const t=this.multiMaterials.indexOf(e);return-1!==t&&this.multiMaterials.splice(t,1),this.onMultiMaterialRemovedObservable.notifyObservers(e),t}removeMaterial(e){const t=e._indexInSceneMaterialArray;if(-1!==t&&t<this.materials.length){if(t!==this.materials.length-1){const e=this.materials[this.materials.length-1];this.materials[t]=e,e._indexInSceneMaterialArray=t}e._indexInSceneMaterialArray=-1,this.materials.pop()}return this.onMaterialRemovedObservable.notifyObservers(e),t}removeActionManager(e){const t=this.actionManagers.indexOf(e);return-1!==t&&this.actionManagers.splice(t,1),t}removeTexture(e){const t=this.textures.indexOf(e);return-1!==t&&this.textures.splice(t,1),this.onTextureRemovedObservable.notifyObservers(e),t}addLight(e){if(!this._blockEntityCollection){this.lights.push(e),this.sortLightsByPriority(),e.parent||e._addToSceneRootNodes();for(const t of this.meshes)-1===t.lightSources.indexOf(e)&&(t.lightSources.push(e),t._resyncLightSources());this.onNewLightAddedObservable.notifyObservers(e)}}sortLightsByPriority(){this.requireLightSorting&&this.lights.sort(Hs.CompareLightsPriority)}addCamera(e){this._blockEntityCollection||(this.cameras.push(e),this.onNewCameraAddedObservable.notifyObservers(e),e.parent||e._addToSceneRootNodes())}addSkeleton(e){this._blockEntityCollection||(this.skeletons.push(e),this.onNewSkeletonAddedObservable.notifyObservers(e))}addParticleSystem(e){this._blockEntityCollection||this.particleSystems.push(e)}addAnimation(e){this._blockEntityCollection||this.animations.push(e)}addAnimationGroup(e){this._blockEntityCollection||this.animationGroups.push(e)}addMultiMaterial(e){this._blockEntityCollection||(this.multiMaterials.push(e),this.onNewMultiMaterialAddedObservable.notifyObservers(e))}addMaterial(e){this._blockEntityCollection||e.getScene()===this&&-1!==e._indexInSceneMaterialArray||(e._indexInSceneMaterialArray=this.materials.length,this.materials.push(e),this.onNewMaterialAddedObservable.notifyObservers(e))}addMorphTargetManager(e){this._blockEntityCollection||this.morphTargetManagers.push(e)}addGeometry(e){this._blockEntityCollection||(this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=this.geometries.length),this.geometries.push(e))}addActionManager(e){this.actionManagers.push(e)}addTexture(e){this._blockEntityCollection||(this.textures.push(e),this.onNewTextureAddedObservable.notifyObservers(e))}switchActiveCamera(e,t=!0){this._engine.getInputElement()&&(this.activeCamera&&this.activeCamera.detachControl(),this.activeCamera=e,t&&e.attachControl())}setActiveCameraById(e){const t=this.getCameraById(e);return t?(this.activeCamera=t,t):null}setActiveCameraByName(e){const t=this.getCameraByName(e);return t?(this.activeCamera=t,t):null}getAnimationGroupByName(e){for(let t=0;t<this.animationGroups.length;t++)if(this.animationGroups[t].name===e)return this.animationGroups[t];return null}_getMaterial(e,t){for(let e=0;e<this.materials.length;e++){const s=this.materials[e];if(t(s))return s}if(e)for(let e=0;e<this.multiMaterials.length;e++){const s=this.multiMaterials[e];if(t(s))return s}return null}getMaterialByUniqueID(e,t=!1){return this._getMaterial(t,(t=>t.uniqueId===e))}getMaterialById(e,t=!1){return this._getMaterial(t,(t=>t.id===e))}getMaterialByName(e,t=!1){return this._getMaterial(t,(t=>t.name===e))}getLastMaterialById(e,t=!1){for(let t=this.materials.length-1;t>=0;t--)if(this.materials[t].id===e)return this.materials[t];if(t)for(let t=this.multiMaterials.length-1;t>=0;t--)if(this.multiMaterials[t].id===e)return this.multiMaterials[t];return null}getTextureByUniqueId(e){for(let t=0;t<this.textures.length;t++)if(this.textures[t].uniqueId===e)return this.textures[t];return null}getTextureByName(e){for(let t=0;t<this.textures.length;t++)if(this.textures[t].name===e)return this.textures[t];return null}getCameraById(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].id===e)return this.cameras[t];return null}getCameraByUniqueId(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].uniqueId===e)return this.cameras[t];return null}getCameraByName(e){for(let t=0;t<this.cameras.length;t++)if(this.cameras[t].name===e)return this.cameras[t];return null}getBoneById(e){for(let t=0;t<this.skeletons.length;t++){const s=this.skeletons[t];for(let t=0;t<s.bones.length;t++)if(s.bones[t].id===e)return s.bones[t]}return null}getBoneByName(e){for(let t=0;t<this.skeletons.length;t++){const s=this.skeletons[t];for(let t=0;t<s.bones.length;t++)if(s.bones[t].name===e)return s.bones[t]}return null}getLightByName(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].name===e)return this.lights[t];return null}getLightById(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].id===e)return this.lights[t];return null}getLightByUniqueId(e){for(let t=0;t<this.lights.length;t++)if(this.lights[t].uniqueId===e)return this.lights[t];return null}getParticleSystemById(e){for(let t=0;t<this.particleSystems.length;t++)if(this.particleSystems[t].id===e)return this.particleSystems[t];return null}getGeometryById(e){for(let t=0;t<this.geometries.length;t++)if(this.geometries[t].id===e)return this.geometries[t];return null}_getGeometryByUniqueId(e){if(this._geometriesByUniqueId){const t=this._geometriesByUniqueId[e];if(void 0!==t)return this.geometries[t]}else for(let t=0;t<this.geometries.length;t++)if(this.geometries[t].uniqueId===e)return this.geometries[t];return null}pushGeometry(e,t){return!(!t&&this._getGeometryByUniqueId(e.uniqueId))&&(this.addGeometry(e),this.onNewGeometryAddedObservable.notifyObservers(e),!0)}removeGeometry(e){let t;if(this._geometriesByUniqueId){if(t=this._geometriesByUniqueId[e.uniqueId],void 0===t)return!1}else if(t=this.geometries.indexOf(e),t<0)return!1;if(t!==this.geometries.length-1){const e=this.geometries[this.geometries.length-1];e&&(this.geometries[t]=e,this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=t))}return this._geometriesByUniqueId&&(this._geometriesByUniqueId[e.uniqueId]=void 0),this.geometries.pop(),this.onGeometryRemovedObservable.notifyObservers(e),!0}getGeometries(){return this.geometries}getMeshById(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].id===e)return this.meshes[t];return null}getMeshesById(e){return this.meshes.filter((function(t){return t.id===e}))}getTransformNodeById(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getTransformNodeByUniqueId(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].uniqueId===e)return this.transformNodes[t];return null}getTransformNodesById(e){return this.transformNodes.filter((function(t){return t.id===e}))}getMeshByUniqueId(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].uniqueId===e)return this.meshes[t];return null}getLastMeshById(e){for(let t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];return null}getLastTransformNodeById(e){for(let t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];return null}getLastEntryById(e){let t;for(t=this.meshes.length-1;t>=0;t--)if(this.meshes[t].id===e)return this.meshes[t];for(t=this.transformNodes.length-1;t>=0;t--)if(this.transformNodes[t].id===e)return this.transformNodes[t];for(t=this.cameras.length-1;t>=0;t--)if(this.cameras[t].id===e)return this.cameras[t];for(t=this.lights.length-1;t>=0;t--)if(this.lights[t].id===e)return this.lights[t];return null}getNodeById(e){const t=this.getMeshById(e);if(t)return t;const s=this.getTransformNodeById(e);if(s)return s;const i=this.getLightById(e);if(i)return i;const r=this.getCameraById(e);if(r)return r;const n=this.getBoneById(e);return n||null}getNodeByName(e){const t=this.getMeshByName(e);if(t)return t;const s=this.getTransformNodeByName(e);if(s)return s;const i=this.getLightByName(e);if(i)return i;const r=this.getCameraByName(e);if(r)return r;const n=this.getBoneByName(e);return n||null}getMeshByName(e){for(let t=0;t<this.meshes.length;t++)if(this.meshes[t].name===e)return this.meshes[t];return null}getTransformNodeByName(e){for(let t=0;t<this.transformNodes.length;t++)if(this.transformNodes[t].name===e)return this.transformNodes[t];return null}getLastSkeletonById(e){for(let t=this.skeletons.length-1;t>=0;t--)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByUniqueId(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].uniqueId===e)return this.skeletons[t];return null}getSkeletonById(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].id===e)return this.skeletons[t];return null}getSkeletonByName(e){for(let t=0;t<this.skeletons.length;t++)if(this.skeletons[t].name===e)return this.skeletons[t];return null}getMorphTargetManagerById(e){for(let t=0;t<this.morphTargetManagers.length;t++)if(this.morphTargetManagers[t].uniqueId===e)return this.morphTargetManagers[t];return null}getMorphTargetById(e){for(let t=0;t<this.morphTargetManagers.length;++t){const s=this.morphTargetManagers[t];for(let t=0;t<s.numTargets;++t){const i=s.getTarget(t);if(i.id===e)return i}}return null}getMorphTargetByName(e){for(let t=0;t<this.morphTargetManagers.length;++t){const s=this.morphTargetManagers[t];for(let t=0;t<s.numTargets;++t){const i=s.getTarget(t);if(i.name===e)return i}}return null}getPostProcessByName(e){for(let t=0;t<this.postProcesses.length;++t){const s=this.postProcesses[t];if(s.name===e)return s}return null}isActiveMesh(e){return-1!==this._activeMeshes.indexOf(e)}get uid(){return this._uid||(this._uid=Yt.RandomId()),this._uid}addExternalData(e,t){return this._externalData||(this._externalData=new zi),this._externalData.add(e,t)}getExternalData(e){return this._externalData?this._externalData.get(e):null}getOrAddExternalDataWithFactory(e,t){return this._externalData||(this._externalData=new zi),this._externalData.getOrAddWithFactory(e,t)}removeExternalData(e){return this._externalData.remove(e)}_evaluateSubMesh(e,t,s,i){if(i||e.isInFrustum(this._frustumPlanes)){for(const s of this._evaluateSubMeshStage)s.action(t,e);const s=e.getMaterial();null!=s&&(s.hasRenderTargetTextures&&null!=s.getRenderTargetTextures&&-1===this._processedMaterials.indexOf(s)&&(this._processedMaterials.push(s),this._materialsRenderTargets.concatWithNoDuplicate(s.getRenderTargetTextures())),this._renderingManager.dispatch(e,t,s))}}freeProcessedMaterials(){this._processedMaterials.dispose()}get blockfreeActiveMeshesAndRenderingGroups(){return this._preventFreeActiveMeshesAndRenderingGroups}set blockfreeActiveMeshesAndRenderingGroups(e){this._preventFreeActiveMeshesAndRenderingGroups!==e&&(e&&(this.freeActiveMeshes(),this.freeRenderingGroups()),this._preventFreeActiveMeshesAndRenderingGroups=e)}freeActiveMeshes(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._activeMeshes.dispose(),this.activeCamera&&this.activeCamera._activeMeshes&&this.activeCamera._activeMeshes.dispose(),this.activeCameras))for(let e=0;e<this.activeCameras.length;e++){const t=this.activeCameras[e];t&&t._activeMeshes&&t._activeMeshes.dispose()}}freeRenderingGroups(){if(!this.blockfreeActiveMeshesAndRenderingGroups&&(this._renderingManager&&this._renderingManager.freeRenderingGroups(),this.textures))for(let e=0;e<this.textures.length;e++){const t=this.textures[e];t&&t.renderList&&t.freeRenderingGroups()}}_isInIntermediateRendering(){return this._intermediateRendering}freezeActiveMeshes(e=!1,t,s,i=!0,r=!1){return this.executeWhenReady((()=>{if(this.activeCamera){if(this._frustumPlanes||this.updateTransformMatrix(),this._evaluateActiveMeshes(),this._activeMeshesFrozen=!0,this._activeMeshesFrozenButKeepClipping=r,this._skipEvaluateActiveMeshesCompletely=e,i)for(let e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._freeze();t&&t()}else s&&s("No active camera found")})),this}unfreezeActiveMeshes(){for(let e=0;e<this.meshes.length;e++){const t=this.meshes[e];t._internalAbstractMeshDataInfo&&(t._internalAbstractMeshDataInfo._isActive=!1)}for(let e=0;e<this._activeMeshes.length;e++)this._activeMeshes.data[e]._unFreeze();return this._activeMeshesFrozen=!1,this}_executeActiveContainerCleanup(e){(!this._engine.snapshotRendering||this._engine.snapshotRenderingMode!==Ze.SNAPSHOTRENDERING_FAST)&&this._activeMeshesFrozen&&this._activeMeshes.length||this.onBeforeRenderObservable.addOnce((()=>e.dispose()))}_evaluateActiveMeshes(){if(this._engine.snapshotRendering&&this._engine.snapshotRenderingMode===Ze.SNAPSHOTRENDERING_FAST)return void(this._activeMeshes.length>0&&(this.activeCamera?._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset()));if(this._activeMeshesFrozen&&this._activeMeshes.length){if(!this._skipEvaluateActiveMeshesCompletely){const e=this._activeMeshes.length;for(let t=0;t<e;t++){this._activeMeshes.data[t].computeWorldMatrix()}}if(this._activeParticleSystems){const e=this._activeParticleSystems.length;for(let t=0;t<e;t++)this._activeParticleSystems.data[t].animate()}return void this._renderingManager.resetSprites()}if(!this.activeCamera)return;this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this),this.activeCamera._activeMeshes.reset(),this._activeMeshes.reset(),this._renderingManager.reset(),this._processedMaterials.reset(),this._activeParticleSystems.reset(),this._activeSkeletons.reset(),this._softwareSkinnedMeshes.reset(),this._materialsRenderTargets.reset();for(const e of this._beforeEvaluateActiveMeshStage)e.action();const e=this.getActiveMeshCandidates(),t=e.length;for(let s=0;s<t;s++){const t=e.data[s];if(t._internalAbstractMeshDataInfo._currentLODIsUpToDate=!1,t.isBlocked)continue;if(this._totalVertices.addCount(t.getTotalVertices(),!1),!t.isReady()||!t.isEnabled()||t.scaling.hasAZeroComponent)continue;t.computeWorldMatrix(),t.actionManager&&t.actionManager.hasSpecificTriggers2(Ze.ACTION_OnIntersectionEnterTrigger,Ze.ACTION_OnIntersectionExitTrigger)&&this._meshesForIntersections.pushNoDuplicate(t);let i=this.customLODSelector?this.customLODSelector(t,this.activeCamera):t.getLOD(this.activeCamera);if(t._internalAbstractMeshDataInfo._currentLOD=i,t._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0,null!=i&&(i!==t&&0!==i.billboardMode&&i.computeWorldMatrix(),t._preActivate(),t.isVisible&&t.visibility>0&&t.layerMask&this.activeCamera.layerMask&&(this._skipFrustumClipping||t.alwaysSelectAsActiveMesh||t.isInFrustum(this._frustumPlanes)))){this._activeMeshes.push(t),this.activeCamera._activeMeshes.push(t),i!==t&&i._activate(this._renderId,!1);for(const e of this._preActiveMeshStage)e.action(t);t._activate(this._renderId,!1)&&(t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(i=t):i._internalAbstractMeshDataInfo._onlyForInstances=!1,i._internalAbstractMeshDataInfo._isActive=!0,this._activeMesh(t,i)),t._postActivate()}}if(this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this),this.particlesEnabled){this.onBeforeParticlesRenderingObservable.notifyObservers(this);for(let e=0;e<this.particleSystems.length;e++){const t=this.particleSystems[e];if(!t.isStarted()||!t.emitter)continue;const s=t.emitter;s.position&&!s.isEnabled()||(this._activeParticleSystems.push(t),t.animate(),this._renderingManager.dispatchParticles(t))}this.onAfterParticlesRenderingObservable.notifyObservers(this)}}_activeMesh(e,t){this._skeletonsEnabled&&null!==t.skeleton&&void 0!==t.skeleton&&(this._activeSkeletons.pushNoDuplicate(t.skeleton)&&(t.skeleton.prepare(),this._activeBones.addCount(t.skeleton.bones.length,!1)),t.computeBonesUsingShaders||this._softwareSkinnedMeshes.pushNoDuplicate(t));let s=e.hasInstances||e.isAnInstance||this.dispatchAllSubMeshesOfActiveMeshes||this._skipFrustumClipping||t.alwaysSelectAsActiveMesh;if(t&&t.subMeshes&&t.subMeshes.length>0){const i=this.getActiveSubMeshCandidates(t),r=i.length;s=s||1===r;for(let n=0;n<r;n++){const r=i.data[n];this._evaluateSubMesh(r,t,e,s)}}}updateTransformMatrix(e){const t=this.activeCamera;if(t)if(t._renderingMultiview){const s=t._rigCameras[0],i=t._rigCameras[1];this.setTransformMatrix(s.getViewMatrix(),s.getProjectionMatrix(e),i.getViewMatrix(),i.getProjectionMatrix(e))}else this.setTransformMatrix(t.getViewMatrix(),t.getProjectionMatrix(e))}_bindFrameBuffer(e,t=!0){e&&e._multiviewTexture?e._multiviewTexture._bindFrameBuffer():e&&e.outputRenderTarget?e.outputRenderTarget._bindFrameBuffer():this._engine._currentFrameBufferIsDefaultFrameBuffer()||this._engine.restoreDefaultFramebuffer(),t&&this._clearFrameBuffer(e)}_clearFrameBuffer(e){if(e&&e._multiviewTexture);else if(e&&e.outputRenderTarget&&!e._renderingMultiview){const t=e.outputRenderTarget;t.onClearObservable.hasObservers()?t.onClearObservable.notifyObservers(this._engine):t.skipInitialClear||e.isRightCamera||(this.autoClear&&this._engine.clear(t.clearColor||this.clearColor,!t._cleared,!0,!0),t._cleared=!0)}else this._defaultFrameBufferCleared?this._engine.clear(null,!1,!0,!0):(this._defaultFrameBufferCleared=!0,this._clear())}_renderForCamera(e,t,s=!0){if(e&&e._skipRendering)return;const i=this._engine;if(this._activeCamera=e,!this.activeCamera)throw new Error("Active camera not set");if(i.setViewport(this.activeCamera.viewport),this.resetCachedMaterial(),this._renderId++,!this.prePass&&s){let t=!0;e._renderingMultiview&&e.outputRenderTarget&&(t=e.outputRenderTarget.skipInitialClear,this.autoClear&&(this._defaultFrameBufferCleared=!1,e.outputRenderTarget.skipInitialClear=!1)),this._bindFrameBuffer(this._activeCamera),e._renderingMultiview&&e.outputRenderTarget&&(e.outputRenderTarget.skipInitialClear=t)}this.updateTransformMatrix(),this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera),this._evaluateActiveMeshes();for(let e=0;e<this._softwareSkinnedMeshes.length;e++){const t=this._softwareSkinnedMeshes.data[e];t.applySkeleton(t.skeleton)}this.onBeforeRenderTargetsRenderObservable.notifyObservers(this),this._renderTargets.concatWithNoDuplicate(this._materialsRenderTargets),e.customRenderTargets&&e.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(e.customRenderTargets),t&&t.customRenderTargets&&t.customRenderTargets.length>0&&this._renderTargets.concatWithNoDuplicate(t.customRenderTargets),this.environmentTexture&&this.environmentTexture.isRenderTarget&&this._renderTargets.pushNoDuplicate(this.environmentTexture);for(const e of this._gatherActiveCameraRenderTargetsStage)e.action(this._renderTargets);let r=!1;if(this.renderTargetsEnabled){if(this._intermediateRendering=!0,this._renderTargets.length>0){Yt.StartPerformanceCounter("Render targets",this._renderTargets.length>0);for(let e=0;e<this._renderTargets.length;e++){const t=this._renderTargets.data[e];if(t._shouldRender()){this._renderId++;const e=t.activeCamera&&t.activeCamera!==this.activeCamera;t.render(e,this.dumpNextRenderTargets),r=!0}}Yt.EndPerformanceCounter("Render targets",this._renderTargets.length>0),this._renderId++}for(const e of this._cameraDrawRenderTargetStage)r=e.action(this.activeCamera)||r;this._intermediateRendering=!1}this._engine.currentRenderPassId=e.outputRenderTarget?.renderPassId??e.renderPassId??Ze.RENDERPASS_MAIN,r&&!this.prePass&&(this._bindFrameBuffer(this._activeCamera,!1),this.updateTransformMatrix()),this.onAfterRenderTargetsRenderObservable.notifyObservers(this),!this.postProcessManager||e._multiviewTexture||this.prePass||this.postProcessManager._prepareFrame();for(const e of this._beforeCameraDrawStage)e.action(this.activeCamera);this.onBeforeDrawPhaseObservable.notifyObservers(this),i.snapshotRendering&&i.snapshotRenderingMode===Ze.SNAPSHOTRENDERING_FAST&&this.finalizeSceneUbo(),this._renderingManager.render(null,null,!0,!0),this.onAfterDrawPhaseObservable.notifyObservers(this);for(const e of this._afterCameraDrawStage)e.action(this.activeCamera);if(this.postProcessManager&&!e._multiviewTexture){const t=e.outputRenderTarget?e.outputRenderTarget.renderTarget:void 0;this.postProcessManager._finalizeFrame(e.isIntermediate,t)}for(const e of this._afterCameraPostProcessStage)e.action(this.activeCamera);this._renderTargets.reset(),this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera)}_processSubCameras(e,t=!0){if(e.cameraRigMode===Ze.RIG_MODE_NONE||e._renderingMultiview)return e._renderingMultiview&&!this._multiviewSceneUbo&&this._createMultiviewUbo(),this._renderForCamera(e,void 0,t),void this.onAfterRenderCameraObservable.notifyObservers(e);if(e._useMultiviewToSingleView)this._renderMultiviewToSingleView(e);else{this.onBeforeCameraRenderObservable.notifyObservers(e);for(let t=0;t<e._rigCameras.length;t++)this._renderForCamera(e._rigCameras[t],e)}this._activeCamera=e,this.updateTransformMatrix(),this.onAfterRenderCameraObservable.notifyObservers(e)}_checkIntersections(){for(let e=0;e<this._meshesForIntersections.length;e++){const t=this._meshesForIntersections.data[e];if(t.actionManager)for(let e=0;t.actionManager&&e<t.actionManager.actions.length;e++){const s=t.actionManager.actions[e];if(s.trigger===Ze.ACTION_OnIntersectionEnterTrigger||s.trigger===Ze.ACTION_OnIntersectionExitTrigger){const e=s.getTriggerParameter(),i=e.mesh?e.mesh:e,r=i.intersectsMesh(t,e.usePreciseIntersection),n=t._intersectionsInProgress.indexOf(i);r&&-1===n?s.trigger===Ze.ACTION_OnIntersectionEnterTrigger?(s._executeCurrent(qi.CreateNew(t,void 0,i)),t._intersectionsInProgress.push(i)):s.trigger===Ze.ACTION_OnIntersectionExitTrigger&&t._intersectionsInProgress.push(i):!r&&n>-1&&(s.trigger===Ze.ACTION_OnIntersectionExitTrigger&&s._executeCurrent(qi.CreateNew(t,void 0,i)),t.actionManager.hasSpecificTrigger(Ze.ACTION_OnIntersectionExitTrigger,(e=>{const t=e.mesh?e.mesh:e;return i===t}))&&s.trigger!==Ze.ACTION_OnIntersectionExitTrigger||t._intersectionsInProgress.splice(n,1))}}}}_advancePhysicsEngineStep(e){}_animate(e){}animate(){if(this._engine.isDeterministicLockStep()){let e=Math.max(yr.MinDeltaTime,Math.min(this._engine.getDeltaTime(),yr.MaxDeltaTime))+this._timeAccumulator;const t=this._engine.getTimeStep(),s=1e3/t/1e3;let i=0;const r=this._engine.getLockstepMaxSteps();let n=Math.floor(e/t);for(n=Math.min(n,r);e>0&&i<n;)this.onBeforeStepObservable.notifyObservers(this),this._animationRatio=t*s,this._animate(t),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(t),this.onAfterStepObservable.notifyObservers(this),this._currentStepId++,i++,e-=t;this._timeAccumulator=e<0?0:e}else{const e=this.useConstantAnimationDeltaTime?16:Math.max(yr.MinDeltaTime,Math.min(this._engine.getDeltaTime(),yr.MaxDeltaTime));this._animationRatio=.06*e,this._animate(),this.onAfterAnimationsObservable.notifyObservers(this),this.physicsEnabled&&this._advancePhysicsEngineStep(e)}}_clear(){(this.autoClearDepthAndStencil||this.autoClear)&&this._engine.clear(this.clearColor,this.autoClear||this.forceWireframe||this.forcePointsCloud,this.autoClearDepthAndStencil,this.autoClearDepthAndStencil)}_checkCameraRenderTarget(e){if(e?.outputRenderTarget&&!e?.isRigCamera&&(e.outputRenderTarget._cleared=!1),e?.rigCameras?.length)for(let t=0;t<e.rigCameras.length;++t){const s=e.rigCameras[t].outputRenderTarget;s&&(s._cleared=!1)}}resetDrawCache(e){if(this.meshes)for(const t of this.meshes)t.resetDrawCache(e)}render(e=!0,t=!1){if(this.isDisposed)return;this.onReadyObservable.hasObservers()&&null===this._executeWhenReadyTimeoutId&&this._checkIsReady(),this._frameId++,this._defaultFrameBufferCleared=!1,this._checkCameraRenderTarget(this.activeCamera),this.activeCameras?.length&&this.activeCameras.forEach(this._checkCameraRenderTarget),this._registerTransientComponents(),this._activeParticles.fetchNewFrame(),this._totalVertices.fetchNewFrame(),this._activeIndices.fetchNewFrame(),this._activeBones.fetchNewFrame(),this._meshesForIntersections.reset(),this.resetCachedMaterial(),this.onBeforeAnimationsObservable.notifyObservers(this),this.actionManager&&this.actionManager.processTrigger(Ze.ACTION_OnEveryFrameTrigger),t||this.animate();for(const e of this._beforeCameraUpdateStage)e.action();if(e)if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e<this.activeCameras.length;e++){const t=this.activeCameras[e];if(t.update(),t.cameraRigMode!==Ze.RIG_MODE_NONE)for(let e=0;e<t._rigCameras.length;e++)t._rigCameras[e].update()}else if(this.activeCamera&&(this.activeCamera.update(),this.activeCamera.cameraRigMode!==Ze.RIG_MODE_NONE))for(let e=0;e<this.activeCamera._rigCameras.length;e++)this.activeCamera._rigCameras[e].update();this.onBeforeRenderObservable.notifyObservers(this);const s=this.getEngine();this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);const i=this.activeCameras?.length?this.activeCameras[0]:this.activeCamera;if(this.renderTargetsEnabled){Yt.StartPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!0;for(let e=0;e<this.customRenderTargets.length;e++){const t=this.customRenderTargets[e];if(t._shouldRender()){if(this._renderId++,this.activeCamera=t.activeCamera||this.activeCamera,!this.activeCamera)throw new Error("Active camera not set");s.setViewport(this.activeCamera.viewport),this.updateTransformMatrix(),t.render(i!==this.activeCamera,this.dumpNextRenderTargets)}}Yt.EndPerformanceCounter("Custom render targets",this.customRenderTargets.length>0),this._intermediateRendering=!1,this._renderId++}this._engine.currentRenderPassId=i?.renderPassId??Ze.RENDERPASS_MAIN,this.activeCamera=i,this._activeCamera&&this._activeCamera.cameraRigMode!==Ze.RIG_MODE_CUSTOM&&!this.prePass&&this._bindFrameBuffer(this._activeCamera,!1),this.onAfterRenderTargetsRenderObservable.notifyObservers(this);for(const e of this._beforeClearStage)e.action();this._clearFrameBuffer(this.activeCamera);for(const e of this._gatherRenderTargetsStage)e.action(this._renderTargets);if(this.activeCameras&&this.activeCameras.length>0)for(let e=0;e<this.activeCameras.length;e++)this._processSubCameras(this.activeCameras[e],e>0);else{if(!this.activeCamera)throw new Error("No camera defined");this._processSubCameras(this.activeCamera,!!this.activeCamera.outputRenderTarget)}this._checkIntersections();for(const e of this._afterRenderStage)e.action();if(this.afterRender&&this.afterRender(),this.onAfterRenderObservable.notifyObservers(this),this._toBeDisposed.length){for(let e=0;e<this._toBeDisposed.length;e++){const t=this._toBeDisposed[e];t&&t.dispose()}this._toBeDisposed.length=0}this.dumpNextRenderTargets&&(this.dumpNextRenderTargets=!1),this._activeBones.addCount(0,!0),this._activeIndices.addCount(0,!0),this._activeParticles.addCount(0,!0),this._engine.restoreDefaultFramebuffer()}freezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].freeze()}unfreezeMaterials(){for(let e=0;e<this.materials.length;e++)this.materials[e].unfreeze()}dispose(){if(this.isDisposed)return;this.beforeRender=null,this.afterRender=null,this.metadata=null,this.skeletons.length=0,this.morphTargetManagers.length=0,this._transientComponents.length=0,this._isReadyForMeshStage.clear(),this._beforeEvaluateActiveMeshStage.clear(),this._evaluateSubMeshStage.clear(),this._preActiveMeshStage.clear(),this._cameraDrawRenderTargetStage.clear(),this._beforeCameraDrawStage.clear(),this._beforeRenderTargetDrawStage.clear(),this._beforeRenderingGroupDrawStage.clear(),this._beforeRenderingMeshStage.clear(),this._afterRenderingMeshStage.clear(),this._afterRenderingGroupDrawStage.clear(),this._afterCameraDrawStage.clear(),this._afterRenderTargetDrawStage.clear(),this._afterRenderStage.clear(),this._beforeCameraUpdateStage.clear(),this._beforeClearStage.clear(),this._gatherRenderTargetsStage.clear(),this._gatherActiveCameraRenderTargetsStage.clear(),this._pointerMoveStage.clear(),this._pointerDownStage.clear(),this._pointerUpStage.clear(),this.importedMeshesFiles=[],this.stopAllAnimations&&(this._activeAnimatables.forEach((e=>{e.onAnimationEndObservable.clear(),e.onAnimationEnd=null})),this.stopAllAnimations()),this.resetCachedMaterial(),this.activeCamera&&(this.activeCamera._activeMeshes.dispose(),this.activeCamera=null),this.activeCameras=null,this._activeMeshes.dispose(),this._renderingManager.dispose(),this._processedMaterials.dispose(),this._activeParticleSystems.dispose(),this._activeSkeletons.dispose(),this._softwareSkinnedMeshes.dispose(),this._renderTargets.dispose(),this._materialsRenderTargets.dispose(),this._registeredForLateAnimationBindings.dispose(),this._meshesForIntersections.dispose(),this._toBeDisposed.length=0;const e=this._activeRequests.slice();for(const t of e)t.abort();this._activeRequests.length=0;try{this.onDisposeObservable.notifyObservers(this)}catch(e){ue.Error("An error occurred while calling onDisposeObservable!",e)}this.detachControl();if(this._engine.getInputElement())for(let e=0;e<this.cameras.length;e++)this.cameras[e].detachControl();this._disposeList(this.animationGroups),this._disposeList(this.lights),this._disposeList(this.meshes,(e=>e.dispose(!0))),this._disposeList(this.transformNodes,(e=>e.dispose(!0)));const t=this.cameras;this._disposeList(t),this._defaultMaterial&&this._defaultMaterial.dispose(),this._disposeList(this.multiMaterials),this._disposeList(this.materials),this._disposeList(this.particleSystems),this._disposeList(this.postProcesses),this._disposeList(this.textures),this._disposeList(this.morphTargetManagers),this._sceneUbo.dispose(),this._multiviewSceneUbo&&this._multiviewSceneUbo.dispose(),this.postProcessManager.dispose(),this._disposeList(this._components);let s=this._engine.scenes.indexOf(this);s>-1&&this._engine.scenes.splice(s,1),C._LastCreatedScene===this&&(this._engine.scenes.length>0?C._LastCreatedScene=this._engine.scenes[this._engine.scenes.length-1]:C._LastCreatedScene=null),s=this._engine._virtualScenes.indexOf(this),s>-1&&this._engine._virtualScenes.splice(s,1),this._engine.wipeCaches(!0),this.onDisposeObservable.clear(),this.onBeforeRenderObservable.clear(),this.onAfterRenderObservable.clear(),this.onBeforeRenderTargetsRenderObservable.clear(),this.onAfterRenderTargetsRenderObservable.clear(),this.onAfterStepObservable.clear(),this.onBeforeStepObservable.clear(),this.onBeforeActiveMeshesEvaluationObservable.clear(),this.onAfterActiveMeshesEvaluationObservable.clear(),this.onBeforeParticlesRenderingObservable.clear(),this.onAfterParticlesRenderingObservable.clear(),this.onBeforeDrawPhaseObservable.clear(),this.onAfterDrawPhaseObservable.clear(),this.onBeforeAnimationsObservable.clear(),this.onAfterAnimationsObservable.clear(),this.onDataLoadedObservable.clear(),this.onBeforeRenderingGroupObservable.clear(),this.onAfterRenderingGroupObservable.clear(),this.onMeshImportedObservable.clear(),this.onBeforeCameraRenderObservable.clear(),this.onAfterCameraRenderObservable.clear(),this.onAfterRenderCameraObservable.clear(),this.onReadyObservable.clear(),this.onNewCameraAddedObservable.clear(),this.onCameraRemovedObservable.clear(),this.onNewLightAddedObservable.clear(),this.onLightRemovedObservable.clear(),this.onNewGeometryAddedObservable.clear(),this.onGeometryRemovedObservable.clear(),this.onNewTransformNodeAddedObservable.clear(),this.onTransformNodeRemovedObservable.clear(),this.onNewMeshAddedObservable.clear(),this.onMeshRemovedObservable.clear(),this.onNewSkeletonAddedObservable.clear(),this.onSkeletonRemovedObservable.clear(),this.onNewMaterialAddedObservable.clear(),this.onNewMultiMaterialAddedObservable.clear(),this.onMaterialRemovedObservable.clear(),this.onMultiMaterialRemovedObservable.clear(),this.onNewTextureAddedObservable.clear(),this.onTextureRemovedObservable.clear(),this.onPrePointerObservable.clear(),this.onPointerObservable.clear(),this.onPreKeyboardObservable.clear(),this.onKeyboardObservable.clear(),this.onActiveCameraChanged.clear(),this.onScenePerformancePriorityChangedObservable.clear(),this._isDisposed=!0}_disposeList(e,t){const s=e.slice(0);t=t??(e=>e.dispose());for(const e of s)t(e);e.length=0}get isDisposed(){return this._isDisposed}clearCachedVertexData(){for(let e=0;e<this.meshes.length;e++){const t=this.meshes[e].geometry;t&&t.clearCachedData()}}cleanCachedTextureBuffer(){for(const e of this.textures){e._buffer&&(e._buffer=null)}}getWorldExtends(e){const t=new U(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE),s=new U(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE);return e=e||(()=>!0),this.meshes.filter(e).forEach((e=>{if(e.computeWorldMatrix(!0),!e.subMeshes||0===e.subMeshes.length||e.infiniteDistance)return;const i=e.getBoundingInfo(),r=i.boundingBox.minimumWorld,n=i.boundingBox.maximumWorld;U.CheckExtends(r,t,s),U.CheckExtends(n,t,s)})),{min:t,max:s}}createPickingRay(e,t,s,i,r=!1){throw Y("Ray")}createPickingRayToRef(e,t,s,i,r,n=!1,a=!1){throw Y("Ray")}createPickingRayInCameraSpace(e,t,s){throw Y("Ray")}createPickingRayInCameraSpaceToRef(e,t,s,i){throw Y("Ray")}get _pickingAvailable(){return!1}pick(e,t,s,i,r,n){const a=Y("Ray",!0);return a&&ue.Warn(a),new Ms}pickWithBoundingInfo(e,t,s,i,r){const n=Y("Ray",!0);return n&&ue.Warn(n),new Ms}pickWithRay(e,t,s,i){throw Y("Ray")}multiPick(e,t,s,i,r){throw Y("Ray")}multiPickWithRay(e,t,s){throw Y("Ray")}setPointerOverMesh(e,t,s){this._inputManager.setPointerOverMesh(e,t,s)}getPointerOverMesh(){return this._inputManager.getPointerOverMesh()}_rebuildGeometries(){for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();this.postProcessManager&&this.postProcessManager._rebuild();for(const e of this._components)e.rebuild();for(const e of this.particleSystems)e.rebuild();if(this.spriteManagers)for(const e of this.spriteManagers)e.rebuild()}_rebuildTextures(){for(const e of this.textures)e._rebuild(!0);this.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag)}_getByTags(e,t,s){if(void 0===t)return e;const i=[];for(const r in e){const n=e[r];q&&q.MatchesQuery(n,t)&&(!s||s(n))&&i.push(n)}return i}getMeshesByTags(e,t){return this._getByTags(this.meshes,e,t)}getCamerasByTags(e,t){return this._getByTags(this.cameras,e,t)}getLightsByTags(e,t){return this._getByTags(this.lights,e,t)}getMaterialByTags(e,t){return this._getByTags(this.materials,e,t).concat(this._getByTags(this.multiMaterials,e,t))}getTransformNodesByTags(e,t){return this._getByTags(this.transformNodes,e,t)}setRenderingOrder(e,t=null,s=null,i=null){this._renderingManager.setRenderingOrder(e,t,s,i)}setRenderingAutoClearDepthStencil(e,t,s=!0,i=!0){this._renderingManager.setRenderingAutoClearDepthStencil(e,t,s,i)}getAutoClearDepthStencilSetup(e){return this._renderingManager.getAutoClearDepthStencilSetup(e)}_forceBlockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism=e}get blockMaterialDirtyMechanism(){return this._blockMaterialDirtyMechanism}set blockMaterialDirtyMechanism(e){this._blockMaterialDirtyMechanism!==e&&(this._blockMaterialDirtyMechanism=e,e||this.markAllMaterialsAsDirty(Ze.MATERIAL_AllDirtyFlag))}markAllMaterialsAsDirty(e,t){if(!this._blockMaterialDirtyMechanism)for(const s of this.materials)t&&!t(s)||s.markAsDirty(e)}_loadFile(e,t,s,i,r,n,a){const o=Pt(e,t,s,i?this.offlineProvider:void 0,r,n,a);return this._activeRequests.push(o),o.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),o}_loadFileAsync(e,t,s,i,r){return new Promise(((n,a)=>{this._loadFile(e,(e=>{n(e)}),t,s,i,((e,t)=>{a(t)}),r)}))}_requestFile(e,t,s,i,r,n,a){const o=Ot(e,t,s,i?this.offlineProvider:void 0,r,n,a);return this._activeRequests.push(o),o.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),o}_requestFileAsync(e,t,s,i,r){return new Promise(((n,a)=>{this._requestFile(e,(e=>{n(e)}),t,s,i,(e=>{a(e)}),r)}))}_readFile(e,t,s,i,r){const n=Ct(e,t,s,i,r);return this._activeRequests.push(n),n.onCompleteObservable.add((e=>{this._activeRequests.splice(this._activeRequests.indexOf(e),1)})),n}_readFileAsync(e,t,s){return new Promise(((i,r)=>{this._readFile(e,(e=>{i(e)}),t,s,(e=>{r(e)}))}))}getPerfCollector(){throw Y("performanceViewerSceneExtension")}setActiveCameraByID(e){return this.setActiveCameraById(e)}getMaterialByID(e){return this.getMaterialById(e)}getLastMaterialByID(e){return this.getLastMaterialById(e)}getTextureByUniqueID(e){return this.getTextureByUniqueId(e)}getCameraByID(e){return this.getCameraById(e)}getCameraByUniqueID(e){return this.getCameraByUniqueId(e)}getBoneByID(e){return this.getBoneById(e)}getLightByID(e){return this.getLightById(e)}getLightByUniqueID(e){return this.getLightByUniqueId(e)}getParticleSystemByID(e){return this.getParticleSystemById(e)}getGeometryByID(e){return this.getGeometryById(e)}getMeshByID(e){return this.getMeshById(e)}getMeshByUniqueID(e){return this.getMeshByUniqueId(e)}getLastMeshByID(e){return this.getLastMeshById(e)}getMeshesByID(e){return this.getMeshesById(e)}getTransformNodeByID(e){return this.getTransformNodeById(e)}getTransformNodeByUniqueID(e){return this.getTransformNodeByUniqueId(e)}getTransformNodesByID(e){return this.getTransformNodesById(e)}getNodeByID(e){return this.getNodeById(e)}getLastEntryByID(e){return this.getLastEntryById(e)}getLastSkeletonByID(e){return this.getLastSkeletonById(e)}}yr.FOGMODE_NONE=Ze.FOGMODE_NONE,yr.FOGMODE_EXP=Ze.FOGMODE_EXP,yr.FOGMODE_EXP2=Ze.FOGMODE_EXP2,yr.FOGMODE_LINEAR=Ze.FOGMODE_LINEAR,yr.MinDeltaTime=1,yr.MaxDeltaTime=1e3,I("BABYLON.Scene",yr),function(e){e[e.Clean=0]="Clean",e[e.Stop=1]="Stop",e[e.Sync=2]="Sync",e[e.NoSync=3]="NoSync"}(Ar||(Ar={}));const br=new g,Rr={};function xr(){return Rr[".babylon"]}function Mr(e){const t=Rr[e];return t||(ue.Warn("Unable to find a plugin to load "+e+" files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/features/featuresDeepDive/importers/loadingFileTypes"),xr())}function Ir(e,t,s,i,r,n,a,o,h){const l="data:"===(c=e.url).substr(0,5)?c.substr(5):null;var c;if(e.rawData&&!a)throw"When using ArrayBufferView to load data the file extension must be provided.";const u=a?Mr(a):l?function(e){for(const t in Rr){const s=Rr[t].plugin;if(s.canDirectLoad&&s.canDirectLoad(e))return Rr[t]}return xr()}(e.url):function(e){const t=e.indexOf("?");-1!==t&&(e=e.substring(0,t));const s=e.lastIndexOf(".");return Mr(e.substring(s,e.length).toLowerCase())}(e.url);if(!1===h?.[u.plugin.name]?.enabled)throw new Error(`The '${u.plugin.name}' plugin is disabled via the loader options passed to the loading operation.`);if(e.rawData&&!u.isBinary)throw"Loading from ArrayBufferView can not be used with plugins that don't support binary loading.";const d=u.plugin.createPlugin?.(h??{})??u.plugin;if(!d)throw`The loader plugin corresponding to the '${a}' file type has not been found. If using es6, please import the plugin you wish to use before.`;if(br.notifyObservers(d),l&&(d.canDirectLoad&&d.canDirectLoad(e.url)||!Lt(e.url))){if(d.directLoad){const e=d.directLoad(t,l);e instanceof Promise?e.then((e=>{s(d,e)})).catch((e=>{r("Error in directLoad of _loadData: "+e,e)})):s(d,e)}else s(d,l);return d}const _=u.isBinary,f=(e,i)=>{t.isDisposed?r("Scene has been disposed"):s(d,e,i)};let p=null,m=!1;d.onDisposeObservable?.add((()=>{m=!0,p&&(p.abort(),p=null),n()}));const g=()=>{if(m)return;const s=(e,t)=>{r(e?.statusText,t)};if(!d.loadFile&&e.rawData)throw"Plugin does not support loading ArrayBufferView.";p=d.loadFile?d.loadFile(t,e.rawData||e.file||e.url,e.rootUrl,f,i,_,s,o):t._loadFile(e.file||e.url,f,i,!0,_,s)},T=t.getEngine();let E=T.enableOfflineSupport;if(E){let s=!1;for(const i of t.disableOfflineSupportExceptionRules)if(i.test(e.url)){s=!0;break}E=!s}return E&&yt.OfflineProviderFactory?t.offlineProvider=yt.OfflineProviderFactory(e.url,g,T.disableManifestCheck):g(),d}function Sr(e,t="",s=C.LastCreatedScene,i=null,r=null,n=null,a=null,o="",h={}){if(!s)return ue.Error("No scene available to load asset container to"),null;const l=function(e,t){let s,i,r=null,n=null;if(t)if(t.name)s=`file:${t.name}`,i=t.name,r=t;else if(ArrayBuffer.isView(t))s="",i=kt(),n=t;else if(t.startsWith("data:"))s=t,i="";else if(e){const r=t;if("/"===r.substr(0,1))return Yt.Error("Wrong sceneFilename parameter"),null;s=e+r,i=r}else s=t,i=Yt.GetFilename(t),e=Yt.GetFolderPath(t);else s=e,i=Yt.GetFilename(e),e=Yt.GetFolderPath(e);return{url:s,rootUrl:e,name:i,file:r,rawData:n}}(e,t);if(!l)return null;const c={};s.addPendingData(c);const u=()=>{s.removePendingData(c)},d=(e,t)=>{const i=function(e,t,s){let i="Unable to load from "+(e.rawData?"binary data":e.url);return t?i+=`: ${t}`:s&&(i+=`: ${s}`),i}(l,e,t);n?n(s,i,new Ee(i,Te.SceneLoaderError,t)):ue.Error(i),u()},_=r?e=>{try{r(e)}catch(e){d("Error in onProgress callback",e)}}:void 0,f=e=>{if(i)try{i(e)}catch(e){d("Error in onSuccess callback",e)}s.removePendingData(c)};return Ir(l,s,((e,t)=>{if(e.loadAssetContainer){const i=e.loadAssetContainer(s,t,l.rootUrl,d);if(!i)return;i.populateRootNodes(),s.loadingPluginName=e.name,f(i)}else if(e.loadAssetContainerAsync){e.loadAssetContainerAsync(s,t,l.rootUrl,_,l.name).then((t=>{t.populateRootNodes(),s.loadingPluginName=e.name,f(t)})).catch((e=>{d(e.message,e)}))}else d("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.")}),_,d,u,a,o,h)}function vr(e,t,s){const{rootUrl:i="",onProgress:r,pluginExtension:n,name:a,pluginOptions:o}=s??{};return function(e,t,s,i,r,n,a){return new Promise(((o,h)=>{Sr(e,t,s,(e=>{o(e)}),i,((e,t,s)=>{h(s||new Error(t))}),r,n,a)}))}(i,e,t,r,n,a,o)}class Cr{get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get coordinatesMode(){return 0}get isCube(){return!!this._texture&&this._texture.isCube}set isCube(e){this._texture&&(this._texture.isCube=e)}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}getClassName(){return"ThinTexture"}static _IsRenderTargetWrapper(e){return void 0!==e?.shareDepth}constructor(e){this._wrapU=Ze.TEXTURE_WRAP_ADDRESSMODE,this._wrapV=Ze.TEXTURE_WRAP_ADDRESSMODE,this.wrapR=Ze.TEXTURE_WRAP_ADDRESSMODE,this.anisotropicFilteringLevel=4,this.delayLoadState=Ze.DELAYLOADSTATE_NONE,this._texture=null,this._engine=null,this._cachedSize=mi.Zero(),this._cachedBaseSize=mi.Zero(),this._initialSamplingMode=Ze.TEXTURE_BILINEAR_SAMPLINGMODE,this._texture=Cr._IsRenderTargetWrapper(e)?e.texture:e,this._texture&&(this._engine=this._texture.getEngine())}isReady(){return this.delayLoadState===Ze.DELAYLOADSTATE_NOTLOADED?(this.delayLoad(),!1):!!this._texture&&this._texture.isReady}delayLoad(){}getInternalTexture(){return this._texture}getSize(){if(this._texture){if(this._texture.width)return this._cachedSize.width=this._texture.width,this._cachedSize.height=this._texture.height,this._cachedSize;if(this._texture._size)return this._cachedSize.width=this._texture._size,this._cachedSize.height=this._texture._size,this._cachedSize}return this._cachedSize}getBaseSize(){return this.isReady()&&this._texture?this._texture._size?(this._cachedBaseSize.width=this._texture._size,this._cachedBaseSize.height=this._texture._size,this._cachedBaseSize):(this._cachedBaseSize.width=this._texture.baseWidth,this._cachedBaseSize.height=this._texture.baseHeight,this._cachedBaseSize):(this._cachedBaseSize.width=0,this._cachedBaseSize.height=0,this._cachedBaseSize)}get samplingMode(){return this._texture?this._texture.samplingMode:this._initialSamplingMode}updateSamplingMode(e){this._texture&&this._engine&&this._engine.updateTextureSamplingMode(e,this._texture)}releaseInternalTexture(){this._texture&&(this._texture.dispose(),this._texture=null)}dispose(){this._texture&&(this.releaseInternalTexture(),this._engine=null)}}Ds.prototype._readTexturePixelsSync=function(e,t,s,i=-1,r=0,n=null,a=!0,o=!1,h=0,l=0){const c=this._gl;if(!c)throw new Error("Engine does not have gl rendering context.");if(!this._dummyFramebuffer){const e=c.createFramebuffer();if(!e)throw new Error("Unable to create dummy framebuffer");this._dummyFramebuffer=e}c.bindFramebuffer(c.FRAMEBUFFER,this._dummyFramebuffer),i>-1?c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_CUBE_MAP_POSITIVE_X+i,e._hardwareTexture?.underlyingResource,r):c.framebufferTexture2D(c.FRAMEBUFFER,c.COLOR_ATTACHMENT0,c.TEXTURE_2D,e._hardwareTexture?.underlyingResource,r);let u=void 0!==e.type?this._getWebGLTextureType(e.type):c.UNSIGNED_BYTE;if(o)n||(n=function(e,t,s=!1){switch(e){case Ze.TEXTURETYPE_BYTE:return ArrayBuffer,new Int8Array(t);case Ze.TEXTURETYPE_UNSIGNED_BYTE:return ArrayBuffer,new Uint8Array(t);case Ze.TEXTURETYPE_SHORT:return t instanceof ArrayBuffer?new Int16Array(t):new Int16Array(s?t/2:t);case Ze.TEXTURETYPE_UNSIGNED_SHORT:case Ze.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:case Ze.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:case Ze.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:case Ze.TEXTURETYPE_HALF_FLOAT:return t instanceof ArrayBuffer?new Uint16Array(t):new Uint16Array(s?t/2:t);case Ze.TEXTURETYPE_INT:return t instanceof ArrayBuffer?new Int32Array(t):new Int32Array(s?t/4:t);case Ze.TEXTURETYPE_UNSIGNED_INTEGER:case Ze.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:case Ze.TEXTURETYPE_UNSIGNED_INT_24_8:case Ze.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:case Ze.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:case Ze.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:return t instanceof ArrayBuffer?new Uint32Array(t):new Uint32Array(s?t/4:t);case Ze.TEXTURETYPE_FLOAT:return t instanceof ArrayBuffer?new Float32Array(t):new Float32Array(s?t/4:t)}return ArrayBuffer,new Uint8Array(t)}(e.type,4*t*s));else if(u===c.UNSIGNED_BYTE)n||(n=new Uint8Array(4*t*s)),u=c.UNSIGNED_BYTE;else n||(n=new Float32Array(4*t*s)),u=c.FLOAT;return a&&this.flushFramebuffer(),c.readPixels(h,l,t,s,c.RGBA,u,n),c.bindFramebuffer(c.FRAMEBUFFER,this._currentFramebuffer),n},Ds.prototype._readTexturePixels=function(e,t,s,i=-1,r=0,n=null,a=!0,o=!1,h=0,l=0){return Promise.resolve(this._readTexturePixelsSync(e,t,s,i,r,n,a,o,h,l))};class Pr extends Cr{set hasAlpha(e){this._hasAlpha!==e&&(this._hasAlpha=e,this._scene&&this._scene.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag,(e=>e.hasTexture(this))))}get hasAlpha(){return this._hasAlpha}set getAlphaFromRGB(e){this._getAlphaFromRGB!==e&&(this._getAlphaFromRGB=e,this._scene&&this._scene.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag,(e=>e.hasTexture(this))))}get getAlphaFromRGB(){return this._getAlphaFromRGB}set coordinatesIndex(e){this._coordinatesIndex!==e&&(this._coordinatesIndex=e,this._scene&&this._scene.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag,(e=>e.hasTexture(this))))}get coordinatesIndex(){return this._coordinatesIndex}set coordinatesMode(e){this._coordinatesMode!==e&&(this._coordinatesMode=e,this._scene&&this._scene.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag,(e=>e.hasTexture(this))))}get coordinatesMode(){return this._coordinatesMode}get wrapU(){return this._wrapU}set wrapU(e){this._wrapU=e}get wrapV(){return this._wrapV}set wrapV(e){this._wrapV=e}get isCube(){return this._texture?this._texture.isCube:this._isCube}set isCube(e){this._texture?this._texture.isCube=e:this._isCube=e}get is3D(){return!!this._texture&&this._texture.is3D}set is3D(e){this._texture&&(this._texture.is3D=e)}get is2DArray(){return!!this._texture&&this._texture.is2DArray}set is2DArray(e){this._texture&&(this._texture.is2DArray=e)}get gammaSpace(){return this._texture?(null===this._texture._gammaSpace&&(this._texture._gammaSpace=this._gammaSpace),this._texture._gammaSpace&&!this._texture._useSRGBBuffer):this._gammaSpace}set gammaSpace(e){if(this._texture){if(this._texture._gammaSpace===e)return;this._texture._gammaSpace=e}else{if(this._gammaSpace===e)return;this._gammaSpace=e}this.getScene()?.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag,(e=>e.hasTexture(this)))}get isRGBD(){return null!=this._texture&&this._texture._isRGBD}set isRGBD(e){e!==this.isRGBD&&(this._texture&&(this._texture._isRGBD=e),this.getScene()?.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag,(e=>e.hasTexture(this))))}get noMipmap(){return!1}get lodGenerationOffset(){return this._texture?this._texture._lodGenerationOffset:0}set lodGenerationOffset(e){this._texture&&(this._texture._lodGenerationOffset=e)}get lodGenerationScale(){return this._texture?this._texture._lodGenerationScale:0}set lodGenerationScale(e){this._texture&&(this._texture._lodGenerationScale=e)}get linearSpecularLOD(){return!!this._texture&&this._texture._linearSpecularLOD}set linearSpecularLOD(e){this._texture&&(this._texture._linearSpecularLOD=e)}get irradianceTexture(){return this._texture?this._texture._irradianceTexture:null}set irradianceTexture(e){this._texture&&(this._texture._irradianceTexture=e)}get uid(){return this._uid||(this._uid=kt()),this._uid}toString(){return this.name}getClassName(){return"BaseTexture"}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}get isBlocking(){return!0}get loadingError(){return this._loadingError}get errorObject(){return this._errorObject}constructor(e,t=null){super(null),this.metadata=null,this.reservedDataStore=null,this._hasAlpha=!1,this._getAlphaFromRGB=!1,this.level=1,this._coordinatesIndex=0,this.optimizeUVAllocation=!0,this._coordinatesMode=Ze.TEXTURE_EXPLICIT_MODE,this.wrapR=Ze.TEXTURE_WRAP_ADDRESSMODE,this.anisotropicFilteringLevel=Pr.DEFAULT_ANISOTROPIC_FILTERING_LEVEL,this._isCube=!1,this._gammaSpace=!0,this.invertZ=!1,this.lodLevelInAlpha=!1,this.isRenderTarget=!1,this._prefiltered=!1,this._forceSerialize=!1,this.animations=[],this.onDisposeObservable=new g,this._onDisposeObserver=null,this._scene=null,this._uid=null,this._parentContainer=null,this._loadingError=!1,e?Pr._IsScene(e)?this._scene=e:this._engine=e:this._scene=C.LastCreatedScene,this._scene&&(this.uniqueId=this._scene.getUniqueId(),this._scene.addTexture(this),this._engine=this._scene.getEngine()),this._texture=t,this._uid=null}getScene(){return this._scene}_getEngine(){return this._engine}getTextureMatrix(){return V.IdentityReadOnly}getReflectionTextureMatrix(){return V.IdentityReadOnly}getRefractionTextureMatrix(){return this.getReflectionTextureMatrix()}isReadyOrNotBlocking(){return!this.isBlocking||this.isReady()||this.loadingError}scale(e){}get canRescale(){return!1}_getFromCache(e,t,s,i,r,n){const a=this._getEngine();if(!a)return null;const o=a._getUseSRGBBuffer(!!r,t),h=a.getLoadedTexturesCache();for(let a=0;a<h.length;a++){const l=h[a];if(!(void 0!==r&&o!==l._useSRGBBuffer||void 0!==i&&i!==l.invertY||l.url!==e||l.generateMipMaps!==!t||s&&s!==l.samplingMode||void 0!==n&&n!==l.isCube))return l.incrementReferences(),l}return null}_rebuild(e=!1){}clone(){return null}get textureType(){return this._texture&&void 0!==this._texture.type?this._texture.type:Ze.TEXTURETYPE_UNSIGNED_INT}get textureFormat(){return this._texture&&void 0!==this._texture.format?this._texture.format:Ze.TEXTUREFORMAT_RGBA}_markAllSubMeshesAsTexturesDirty(){const e=this.getScene();e&&e.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag)}readPixels(e=0,t=0,s=null,i=!0,r=!1,n=0,a=0,o=Number.MAX_VALUE,h=Number.MAX_VALUE){if(!this._texture)return null;const l=this._getEngine();if(!l)return null;const c=this.getSize();let u=c.width,d=c.height;0!==t&&(u/=Math.pow(2,t),d/=Math.pow(2,t),u=Math.round(u),d=Math.round(d)),o=Math.min(u,o),h=Math.min(d,h);try{return this._texture.isCube?l._readTexturePixels(this._texture,o,h,e,t,s,i,r,n,a):l._readTexturePixels(this._texture,o,h,-1,t,s,i,r,n,a)}catch(e){return null}}_readPixelsSync(e=0,t=0,s=null,i=!0,r=!1){if(!this._texture)return null;const n=this.getSize();let a=n.width,o=n.height;const h=this._getEngine();if(!h)return null;0!=t&&(a/=Math.pow(2,t),o/=Math.pow(2,t),a=Math.round(a),o=Math.round(o));try{return this._texture.isCube?h._readTexturePixelsSync(this._texture,a,o,e,t,s,i,r):h._readTexturePixelsSync(this._texture,a,o,-1,t,s,i,r)}catch(e){return null}}get _lodTextureHigh(){return this._texture?this._texture._lodTextureHigh:null}get _lodTextureMid(){return this._texture?this._texture._lodTextureMid:null}get _lodTextureLow(){return this._texture?this._texture._lodTextureLow:null}dispose(){if(this._scene){this._scene.stopAnimation&&this._scene.stopAnimation(this),this._scene.removePendingData(this);const e=this._scene.textures.indexOf(this);if(e>=0&&this._scene.textures.splice(e,1),this._scene.onTextureRemovedObservable.notifyObservers(this),this._scene=null,this._parentContainer){const e=this._parentContainer.textures.indexOf(this);e>-1&&this._parentContainer.textures.splice(e,1),this._parentContainer=null}}this.onDisposeObservable.notifyObservers(this),this.onDisposeObservable.clear(),this.metadata=null,super.dispose()}serialize(e=!1){if(!this.name&&!e)return null;const t=re.Serialize(this);return re.AppendSerializedAnimations(this,t),t}static WhenAllReady(e,t){let s=e.length;if(0!==s)for(let i=0;i<e.length;i++){const r=e[i];if(r.isReady())0==--s&&t();else{const e=r.onLoadObservable;e?e.addOnce((()=>{0==--s&&t()})):0==--s&&t()}}else t()}static _IsScene(e){return"Scene"===e.getClassName()}}function Or(e,t,s=!1){const i=t.width,r=t.height;if(e instanceof Float32Array){let t=e.byteLength/e.BYTES_PER_ELEMENT;const s=new Uint8Array(t);for(;--t>=0;){let i=e[t];i<0?i=0:i>1&&(i=1),s[t]=255*i}e=s}const n=document.createElement("canvas");n.width=i,n.height=r;const a=n.getContext("2d");if(!a)return null;const o=a.createImageData(i,r);if(o.data.set(e),a.putImageData(o,0,0),s){const e=document.createElement("canvas");e.width=i,e.height=r;const t=e.getContext("2d");return t?(t.translate(0,r),t.scale(1,-1),t.drawImage(n,0,0),e.toDataURL("image/png")):null}return n.toDataURL("image/png")}Pr.DEFAULT_ANISOTROPIC_FILTERING_LEVEL=4,e([a()],Pr.prototype,"uniqueId",void 0),e([a()],Pr.prototype,"name",void 0),e([a()],Pr.prototype,"metadata",void 0),e([a("hasAlpha")],Pr.prototype,"_hasAlpha",void 0),e([a("getAlphaFromRGB")],Pr.prototype,"_getAlphaFromRGB",void 0),e([a()],Pr.prototype,"level",void 0),e([a("coordinatesIndex")],Pr.prototype,"_coordinatesIndex",void 0),e([a()],Pr.prototype,"optimizeUVAllocation",void 0),e([a("coordinatesMode")],Pr.prototype,"_coordinatesMode",void 0),e([a()],Pr.prototype,"wrapU",null),e([a()],Pr.prototype,"wrapV",null),e([a()],Pr.prototype,"wrapR",void 0),e([a()],Pr.prototype,"anisotropicFilteringLevel",void 0),e([a()],Pr.prototype,"isCube",null),e([a()],Pr.prototype,"is3D",null),e([a()],Pr.prototype,"is2DArray",null),e([a()],Pr.prototype,"gammaSpace",null),e([a()],Pr.prototype,"invertZ",void 0),e([a()],Pr.prototype,"lodLevelInAlpha",void 0),e([a()],Pr.prototype,"lodGenerationOffset",null),e([a()],Pr.prototype,"lodGenerationScale",null),e([a()],Pr.prototype,"linearSpecularLOD",null),e([o()],Pr.prototype,"irradianceTexture",null),e([a()],Pr.prototype,"isRenderTarget",void 0);class Dr extends Pr{static _CreateVideoTexture(e,t,s,i=!1,r=!1,n=Dr.TRILINEAR_SAMPLINGMODE,a={},o,h=Ze.TEXTUREFORMAT_RGBA){throw Y("VideoTexture")}get noMipmap(){return this._noMipmap}get mimeType(){return this._mimeType}set isBlocking(e){this._isBlocking=e}get isBlocking(){return this._isBlocking}get invertY(){return this._invertY}constructor(e,t,s,i,r=Dr.TRILINEAR_SAMPLINGMODE,n=null,a=null,o=null,h=!1,l,c,u,d,_){let f;super(t),this.url=null,this.uOffset=0,this.vOffset=0,this.uScale=1,this.vScale=1,this.uAng=0,this.vAng=0,this.wAng=0,this.uRotationCenter=.5,this.vRotationCenter=.5,this.wRotationCenter=.5,this.homogeneousRotationInUVTransform=!1,this.inspectableCustomProperties=null,this._noMipmap=!1,this._invertY=!1,this._rowGenerationMatrix=null,this._cachedTextureMatrix=null,this._projectionModeMatrix=null,this._t0=null,this._t1=null,this._t2=null,this._cachedUOffset=-1,this._cachedVOffset=-1,this._cachedUScale=0,this._cachedVScale=0,this._cachedUAng=-1,this._cachedVAng=-1,this._cachedWAng=-1,this._cachedReflectionProjectionMatrixId=-1,this._cachedURotationCenter=-1,this._cachedVRotationCenter=-1,this._cachedWRotationCenter=-1,this._cachedHomogeneousRotationInUVTransform=!1,this._cachedIdentity3x2=!0,this._cachedReflectionTextureMatrix=null,this._cachedReflectionUOffset=-1,this._cachedReflectionVOffset=-1,this._cachedReflectionUScale=0,this._cachedReflectionVScale=0,this._cachedReflectionCoordinatesMode=-1,this._buffer=null,this._deleteBuffer=!1,this._format=null,this._delayedOnLoad=null,this._delayedOnError=null,this.onLoadObservable=new g,this._isBlocking=!0,this.name=e||"",this.url=e;let p=!1,m=null,T=!0;"object"==typeof s&&null!==s?(f=s.noMipmap??!1,i=s.invertY??!0,r=s.samplingMode??Dr.TRILINEAR_SAMPLINGMODE,n=s.onLoad??null,a=s.onError??null,o=s.buffer??null,h=s.deleteBuffer??!1,l=s.format,c=s.mimeType,u=s.loaderOptions,d=s.creationFlags,p=s.useSRGBBuffer??!1,m=s.internalTexture??null,T=s.gammaSpace??T):f=!!s,this._gammaSpace=T,this._noMipmap=f,this._invertY=void 0===i||i,this._initialSamplingMode=r,this._buffer=o,this._deleteBuffer=h,this._mimeType=c,this._loaderOptions=u,this._creationFlags=d,this._useSRGBBuffer=p,this._forcedExtension=_,l&&(this._format=l);const E=this.getScene(),A=this._getEngine();if(!A)return;A.onBeforeTextureInitObservable.notifyObservers(this);const y=()=>{this._texture&&(this._texture._invertVScale&&(this.vScale*=-1,this.vOffset+=1),null!==this._texture._cachedWrapU&&(this.wrapU=this._texture._cachedWrapU,this._texture._cachedWrapU=null),null!==this._texture._cachedWrapV&&(this.wrapV=this._texture._cachedWrapV,this._texture._cachedWrapV=null),null!==this._texture._cachedWrapR&&(this.wrapR=this._texture._cachedWrapR,this._texture._cachedWrapR=null)),this.onLoadObservable.hasObservers()&&this.onLoadObservable.notifyObservers(this),n&&n(),!this.isBlocking&&E&&E.resetCachedMaterial()},b=(e,t)=>{this._loadingError=!0,this._errorObject={message:e,exception:t},a&&a(e,t),Dr.OnTextureLoadErrorObservable.notifyObservers(this)};if(!this.url&&!m)return this._delayedOnLoad=y,void(this._delayedOnError=b);if(this._texture=m??this._getFromCache(this.url,f,r,this._invertY,p,this.isCube),this._texture)if(this._texture.isReady)je.SetImmediate((()=>y()));else{const e=this._texture.onLoadedObservable.add(y);this._texture.onErrorObservable.add((t=>{b(t.message,t.exception),this._texture?.onLoadedObservable.remove(e)}))}else if(E&&E.useDelayedTextureLoading)this.delayLoadState=Ze.DELAYLOADSTATE_NOTLOADED,this._delayedOnLoad=y,this._delayedOnError=b;else{try{this._texture=A.createTexture(this.url,f,this._invertY,E,r,y,b,this._buffer,void 0,this._format,this._forcedExtension,c,u,d,p)}catch(e){throw b("error loading",e),e}h&&(this._buffer=null)}}updateURL(e,t=null,s,i){this.url&&(this.releaseInternalTexture(),this.getScene().markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag,(e=>e.hasTexture(this)))),this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,this._buffer=t,this._forcedExtension=i,this.delayLoadState=Ze.DELAYLOADSTATE_NOTLOADED,s&&(this._delayedOnLoad=s),this.delayLoad()}delayLoad(){if(this.delayLoadState!==Ze.DELAYLOADSTATE_NOTLOADED)return;const e=this.getScene();e&&(this.delayLoadState=Ze.DELAYLOADSTATE_LOADED,this._texture=this._getFromCache(this.url,this._noMipmap,this.samplingMode,this._invertY,this._useSRGBBuffer,this.isCube),this._texture?this._delayedOnLoad&&(this._texture.isReady?je.SetImmediate(this._delayedOnLoad):this._texture.onLoadedObservable.add(this._delayedOnLoad)):(this._texture=e.getEngine().createTexture(this.url,this._noMipmap,this._invertY,e,this.samplingMode,this._delayedOnLoad,this._delayedOnError,this._buffer,null,this._format,this._forcedExtension,this._mimeType,this._loaderOptions,this._creationFlags,this._useSRGBBuffer),this._deleteBuffer&&(this._buffer=null)),this._delayedOnLoad=null,this._delayedOnError=null)}_prepareRowForTextureGeneration(e,t,s,i){e*=this._cachedUScale,t*=this._cachedVScale,e-=this.uRotationCenter*this._cachedUScale,t-=this.vRotationCenter*this._cachedVScale,s-=this.wRotationCenter,U.TransformCoordinatesFromFloatsToRef(e,t,s,this._rowGenerationMatrix,i),i.x+=this.uRotationCenter*this._cachedUScale+this._cachedUOffset,i.y+=this.vRotationCenter*this._cachedVScale+this._cachedVOffset,i.z+=this.wRotationCenter}getTextureMatrix(e=1){if(this.uOffset===this._cachedUOffset&&this.vOffset===this._cachedVOffset&&this.uScale*e===this._cachedUScale&&this.vScale===this._cachedVScale&&this.uAng===this._cachedUAng&&this.vAng===this._cachedVAng&&this.wAng===this._cachedWAng&&this.uRotationCenter===this._cachedURotationCenter&&this.vRotationCenter===this._cachedVRotationCenter&&this.wRotationCenter===this._cachedWRotationCenter&&this.homogeneousRotationInUVTransform===this._cachedHomogeneousRotationInUVTransform)return this._cachedTextureMatrix;this._cachedUOffset=this.uOffset,this._cachedVOffset=this.vOffset,this._cachedUScale=this.uScale*e,this._cachedVScale=this.vScale,this._cachedUAng=this.uAng,this._cachedVAng=this.vAng,this._cachedWAng=this.wAng,this._cachedURotationCenter=this.uRotationCenter,this._cachedVRotationCenter=this.vRotationCenter,this._cachedWRotationCenter=this.wRotationCenter,this._cachedHomogeneousRotationInUVTransform=this.homogeneousRotationInUVTransform,this._cachedTextureMatrix&&this._rowGenerationMatrix||(this._cachedTextureMatrix=V.Zero(),this._rowGenerationMatrix=new V,this._t0=U.Zero(),this._t1=U.Zero(),this._t2=U.Zero()),V.RotationYawPitchRollToRef(this.vAng,this.uAng,this.wAng,this._rowGenerationMatrix),this.homogeneousRotationInUVTransform?(V.TranslationToRef(-this._cachedURotationCenter,-this._cachedVRotationCenter,-this._cachedWRotationCenter,z.Matrix[0]),V.TranslationToRef(this._cachedURotationCenter,this._cachedVRotationCenter,this._cachedWRotationCenter,z.Matrix[1]),V.ScalingToRef(this._cachedUScale,this._cachedVScale,0,z.Matrix[2]),V.TranslationToRef(this._cachedUOffset,this._cachedVOffset,0,z.Matrix[3]),z.Matrix[0].multiplyToRef(this._rowGenerationMatrix,this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(z.Matrix[1],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(z.Matrix[2],this._cachedTextureMatrix),this._cachedTextureMatrix.multiplyToRef(z.Matrix[3],this._cachedTextureMatrix),this._cachedTextureMatrix.setRowFromFloats(2,this._cachedTextureMatrix.m[12],this._cachedTextureMatrix.m[13],this._cachedTextureMatrix.m[14],1)):(this._prepareRowForTextureGeneration(0,0,0,this._t0),this._prepareRowForTextureGeneration(1,0,0,this._t1),this._prepareRowForTextureGeneration(0,1,0,this._t2),this._t1.subtractInPlace(this._t0),this._t2.subtractInPlace(this._t0),V.FromValuesToRef(this._t1.x,this._t1.y,this._t1.z,0,this._t2.x,this._t2.y,this._t2.z,0,this._t0.x,this._t0.y,this._t0.z,0,0,0,0,1,this._cachedTextureMatrix));const t=this.getScene();if(!t)return this._cachedTextureMatrix;const s=this._cachedIdentity3x2;return this._cachedIdentity3x2=this._cachedTextureMatrix.isIdentityAs3x2(),this.optimizeUVAllocation&&s!==this._cachedIdentity3x2&&t.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag,(e=>e.hasTexture(this))),this._cachedTextureMatrix}getReflectionTextureMatrix(){const e=this.getScene();if(!e)return this._cachedReflectionTextureMatrix;if(this.uOffset===this._cachedReflectionUOffset&&this.vOffset===this._cachedReflectionVOffset&&this.uScale===this._cachedReflectionUScale&&this.vScale===this._cachedReflectionVScale&&this.coordinatesMode===this._cachedReflectionCoordinatesMode){if(this.coordinatesMode!==Dr.PROJECTION_MODE)return this._cachedReflectionTextureMatrix;if(this._cachedReflectionProjectionMatrixId===e.getProjectionMatrix().updateFlag)return this._cachedReflectionTextureMatrix}this._cachedReflectionTextureMatrix||(this._cachedReflectionTextureMatrix=V.Zero()),this._projectionModeMatrix||(this._projectionModeMatrix=V.Zero());const t=this._cachedReflectionCoordinatesMode!==this.coordinatesMode;switch(this._cachedReflectionUOffset=this.uOffset,this._cachedReflectionVOffset=this.vOffset,this._cachedReflectionUScale=this.uScale,this._cachedReflectionVScale=this.vScale,this._cachedReflectionCoordinatesMode=this.coordinatesMode,this.coordinatesMode){case Dr.PLANAR_MODE:V.IdentityToRef(this._cachedReflectionTextureMatrix),this._cachedReflectionTextureMatrix[0]=this.uScale,this._cachedReflectionTextureMatrix[5]=this.vScale,this._cachedReflectionTextureMatrix[12]=this.uOffset,this._cachedReflectionTextureMatrix[13]=this.vOffset;break;case Dr.PROJECTION_MODE:{V.FromValuesToRef(.5,0,0,0,0,-.5,0,0,0,0,0,0,.5,.5,1,1,this._projectionModeMatrix);const t=e.getProjectionMatrix();this._cachedReflectionProjectionMatrixId=t.updateFlag,t.multiplyToRef(this._projectionModeMatrix,this._cachedReflectionTextureMatrix);break}default:V.IdentityToRef(this._cachedReflectionTextureMatrix)}return t&&e.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag,(e=>e.hasTexture(this))),this._cachedReflectionTextureMatrix}clone(){const e={noMipmap:this._noMipmap,invertY:this._invertY,samplingMode:this.samplingMode,onLoad:void 0,onError:void 0,buffer:this._texture?this._texture._buffer:void 0,deleteBuffer:this._deleteBuffer,format:this.textureFormat,mimeType:this.mimeType,loaderOptions:this._loaderOptions,creationFlags:this._creationFlags,useSRGBBuffer:this._useSRGBBuffer};return re.Clone((()=>new Dr(this._texture?this._texture.url:null,this.getScene(),e)),this)}serialize(){const e=this.name;Dr.SerializeBuffers||this.name.startsWith("data:")&&(this.name=""),this.name.startsWith("data:")&&this.url===this.name&&(this.url="");const t=super.serialize(Dr._SerializeInternalTextureUniqueId);return t?((Dr.SerializeBuffers||Dr.ForceSerializeBuffers)&&("string"==typeof this._buffer&&"data:"===this._buffer.substr(0,5)?(t.base64String=this._buffer,t.name=t.name.replace("data:","")):this.url&&this.url.startsWith("data:")&&this._buffer instanceof Uint8Array?t.base64String="data:image/png;base64,"+Ae(this._buffer):(Dr.ForceSerializeBuffers||this.url&&this.url.startsWith("blob:")||this._forceSerialize)&&(t.base64String=!this._engine||this._engine._features.supportSyncTextureRead?function(e,t=0,s=0){const i=e.getInternalTexture();if(!i)return null;const r=e._readPixelsSync(t,s);return r?Or(r,e.getSize(),i.invertY):null}(this):async function(e,t=0,s=0){const i=e.getInternalTexture();if(!i)return null;const r=await e.readPixels(t,s);return r?Or(r,e.getSize(),i.invertY):null}(this))),t.invertY=this._invertY,t.samplingMode=this.samplingMode,t._creationFlags=this._creationFlags,t._useSRGBBuffer=this._useSRGBBuffer,Dr._SerializeInternalTextureUniqueId&&(t.internalTextureUniqueId=this._texture?.uniqueId??void 0),t.noMipmap=this._noMipmap,this.name=e,t):null}getClassName(){return"Texture"}dispose(){super.dispose(),this.onLoadObservable.clear(),this._delayedOnLoad=null,this._delayedOnError=null,this._buffer=null}static Parse(e,t,s){if(e.customType){const i=Ut.Instantiate(e.customType).Parse(e,t,s);return e.samplingMode&&i.updateSamplingMode&&i._samplingMode&&i._samplingMode!==e.samplingMode&&i.updateSamplingMode(e.samplingMode),i}if(e.isCube&&!e.isRenderTarget)return Dr._CubeTextureParser(e,t,s);const i=void 0!==e.internalTextureUniqueId;if(!e.name&&!e.isRenderTarget&&!i)return null;let r;if(i){const s=t.getEngine().getLoadedTexturesCache();for(const t of s)if(t.uniqueId===e.internalTextureUniqueId){r=t;break}}const n=t=>{if(t&&t._texture&&(t._texture._cachedWrapU=null,t._texture._cachedWrapV=null,t._texture._cachedWrapR=null),e.samplingMode){const s=e.samplingMode;t&&t.samplingMode!==s&&t.updateSamplingMode(s)}if(t&&e.animations)for(let s=0;s<e.animations.length;s++){const i=e.animations[s],r=S("BABYLON.Animation");r&&t.animations.push(r.Parse(i))}i&&!r&&t?._texture?._setUniqueId(e.internalTextureUniqueId)};return re.Parse((()=>{let i=!0;if(e.noMipmap&&(i=!1),e.mirrorPlane){const s=Dr._CreateMirror(e.name,e.renderTargetSize,t,i);return s._waitingRenderList=e.renderList,s.mirrorPlane=es.FromArray(e.mirrorPlane),n(s),s}if(e.isRenderTarget){let s=null;if(e.isCube){if(t.reflectionProbes)for(let s=0;s<t.reflectionProbes.length;s++){const i=t.reflectionProbes[s];if(i.name===e.name)return i.cubeTexture}}else s=Dr._CreateRenderTargetTexture(e.name,e.renderTargetSize,t,i,e._creationFlags??0),s._waitingRenderList=e.renderList;return n(s),s}if(e.isVideo){const r=Dr._CreateVideoTexture(s+(e.url||e.name),s+(e.src||e.url),t,i,e.invertY,e.samplingMode,e.settings||{});return n(r),r}{let a;if(e.base64String&&!r)a=Dr.CreateFromBase64String(e.base64String,e.base64String,t,!i,e.invertY,e.samplingMode,(()=>{n(a)}),e._creationFlags??0,e._useSRGBBuffer??!1),a.name=e.name;else{let o;o=e.name&&(e.name.indexOf("://")>0||e.name.startsWith("data:"))?e.name:s+e.name,e.url&&(e.url.startsWith("data:")||Dr.UseSerializedUrlIfAny)&&(o=e.url);const h={noMipmap:!i,invertY:e.invertY,samplingMode:e.samplingMode,onLoad:()=>{n(a)},internalTexture:r};a=new Dr(o,t,h)}return a}}),e,t)}static CreateFromBase64String(e,t,s,i,r,n=Dr.TRILINEAR_SAMPLINGMODE,a=null,o=null,h=Ze.TEXTUREFORMAT_RGBA,l,c){return new Dr("data:"+t,s,i,r,n,a,o,e,!1,h,void 0,void 0,l,c)}static LoadFromDataString(e,t,s,i=!1,r,n=!0,a=Dr.TRILINEAR_SAMPLINGMODE,o=null,h=null,l=Ze.TEXTUREFORMAT_RGBA,c,u){return"data:"!==e.substr(0,5)&&(e="data:"+e),new Dr(e,s,r,n,a,o,h,t,i,l,void 0,void 0,c,u)}}Dr.SerializeBuffers=!0,Dr.ForceSerializeBuffers=!1,Dr.OnTextureLoadErrorObservable=new g,Dr._SerializeInternalTextureUniqueId=!1,Dr._CubeTextureParser=(e,t,s)=>{throw Y("CubeTexture")},Dr._CreateMirror=(e,t,s,i)=>{throw Y("MirrorTexture")},Dr._CreateRenderTargetTexture=(e,t,s,i,r)=>{throw Y("RenderTargetTexture")},Dr.NEAREST_SAMPLINGMODE=Ze.TEXTURE_NEAREST_SAMPLINGMODE,Dr.NEAREST_NEAREST_MIPLINEAR=Ze.TEXTURE_NEAREST_NEAREST_MIPLINEAR,Dr.BILINEAR_SAMPLINGMODE=Ze.TEXTURE_BILINEAR_SAMPLINGMODE,Dr.LINEAR_LINEAR_MIPNEAREST=Ze.TEXTURE_LINEAR_LINEAR_MIPNEAREST,Dr.TRILINEAR_SAMPLINGMODE=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,Dr.LINEAR_LINEAR_MIPLINEAR=Ze.TEXTURE_LINEAR_LINEAR_MIPLINEAR,Dr.NEAREST_NEAREST_MIPNEAREST=Ze.TEXTURE_NEAREST_NEAREST_MIPNEAREST,Dr.NEAREST_LINEAR_MIPNEAREST=Ze.TEXTURE_NEAREST_LINEAR_MIPNEAREST,Dr.NEAREST_LINEAR_MIPLINEAR=Ze.TEXTURE_NEAREST_LINEAR_MIPLINEAR,Dr.NEAREST_LINEAR=Ze.TEXTURE_NEAREST_LINEAR,Dr.NEAREST_NEAREST=Ze.TEXTURE_NEAREST_NEAREST,Dr.LINEAR_NEAREST_MIPNEAREST=Ze.TEXTURE_LINEAR_NEAREST_MIPNEAREST,Dr.LINEAR_NEAREST_MIPLINEAR=Ze.TEXTURE_LINEAR_NEAREST_MIPLINEAR,Dr.LINEAR_LINEAR=Ze.TEXTURE_LINEAR_LINEAR,Dr.LINEAR_NEAREST=Ze.TEXTURE_LINEAR_NEAREST,Dr.EXPLICIT_MODE=Ze.TEXTURE_EXPLICIT_MODE,Dr.SPHERICAL_MODE=Ze.TEXTURE_SPHERICAL_MODE,Dr.PLANAR_MODE=Ze.TEXTURE_PLANAR_MODE,Dr.CUBIC_MODE=Ze.TEXTURE_CUBIC_MODE,Dr.PROJECTION_MODE=Ze.TEXTURE_PROJECTION_MODE,Dr.SKYBOX_MODE=Ze.TEXTURE_SKYBOX_MODE,Dr.INVCUBIC_MODE=Ze.TEXTURE_INVCUBIC_MODE,Dr.EQUIRECTANGULAR_MODE=Ze.TEXTURE_EQUIRECTANGULAR_MODE,Dr.FIXED_EQUIRECTANGULAR_MODE=Ze.TEXTURE_FIXED_EQUIRECTANGULAR_MODE,Dr.FIXED_EQUIRECTANGULAR_MIRRORED_MODE=Ze.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE,Dr.CLAMP_ADDRESSMODE=Ze.TEXTURE_CLAMP_ADDRESSMODE,Dr.WRAP_ADDRESSMODE=Ze.TEXTURE_WRAP_ADDRESSMODE,Dr.MIRROR_ADDRESSMODE=Ze.TEXTURE_MIRROR_ADDRESSMODE,Dr.UseSerializedUrlIfAny=!1,e([a()],Dr.prototype,"url",void 0),e([a()],Dr.prototype,"uOffset",void 0),e([a()],Dr.prototype,"vOffset",void 0),e([a()],Dr.prototype,"uScale",void 0),e([a()],Dr.prototype,"vScale",void 0),e([a()],Dr.prototype,"uAng",void 0),e([a()],Dr.prototype,"vAng",void 0),e([a()],Dr.prototype,"wAng",void 0),e([a()],Dr.prototype,"uRotationCenter",void 0),e([a()],Dr.prototype,"vRotationCenter",void 0),e([a()],Dr.prototype,"wRotationCenter",void 0),e([a()],Dr.prototype,"homogeneousRotationInUVTransform",void 0),e([a()],Dr.prototype,"isBlocking",null),I("BABYLON.Texture",Dr),re._TextureParser=Dr.Parse;const Lr="postprocessVertexShader",Fr="attribute vec2 position;uniform vec2 scale;varying vec2 vUV;const vec2 madd=vec2(0.5,0.5);\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvUV=(position*madd+madd)*scale;gl_Position=vec4(position,0.0,1.0);\n#define CUSTOM_VERTEX_MAIN_END\n}";$e.ShadersStore[Lr]=Fr;const Nr={name:Lr,shader:Fr};var wr=Object.freeze({__proto__:null,postprocessVertexShader:Nr});class Br{get depthStencilTexture(){return this._depthStencilTexture}get depthStencilTextureWithStencil(){return this._depthStencilTextureWithStencil}get isCube(){return this._isCube}get isMulti(){return this._isMulti}get is2DArray(){return this.layers>0}get is3D(){return this.depth>0}get size(){return this.width}get width(){return this._size.width||this._size}get height(){return this._size.height||this._size}get layers(){return this._size.layers||0}get depth(){return this._size.depth||0}get texture(){return this._textures?.[0]??null}get textures(){return this._textures}get faceIndices(){return this._faceIndices}get layerIndices(){return this._layerIndices}get samples(){return this._samples}setSamples(e,t=!0,s=!1){if(this.samples===e&&!s)return e;const i=this._isMulti?this._engine.updateMultipleRenderTargetTextureSampleCount(this,e,t):this._engine.updateRenderTargetTextureSampleCount(this,e);return this._samples=e,i}constructor(e,t,s,i,r){this._textures=null,this._faceIndices=null,this._layerIndices=null,this._samples=1,this._attachments=null,this._generateStencilBuffer=!1,this._generateDepthBuffer=!1,this._depthStencilTextureWithStencil=!1,this._isMulti=e,this._isCube=t,this._size=s,this._engine=i,this._depthStencilTexture=null,this.label=r}setTextures(e){Array.isArray(e)?this._textures=e:this._textures=e?[e]:null}setTexture(e,t=0,s=!0){this._textures||(this._textures=[]),this._textures[t]!==e&&(this._textures[t]&&s&&this._textures[t].dispose(),this._textures[t]=e)}setLayerAndFaceIndices(e,t){this._layerIndices=e,this._faceIndices=t}setLayerAndFaceIndex(e=0,t,s){this._layerIndices||(this._layerIndices=[]),this._faceIndices||(this._faceIndices=[]),void 0!==t&&t>=0&&(this._layerIndices[e]=t),void 0!==s&&s>=0&&(this._faceIndices[e]=s)}createDepthStencilTexture(e=0,t=!0,s=!1,i=1,r=Ze.TEXTUREFORMAT_DEPTH32_FLOAT,n){return this._depthStencilTexture?.dispose(),this._depthStencilTextureWithStencil=s,this._depthStencilTextureLabel=n,this._depthStencilTexture=this._engine.createDepthStencilTexture(this._size,{bilinearFiltering:t,comparisonFunction:e,generateStencil:s,isCube:this._isCube,samples:i,depthTextureFormat:r,label:n},this),this._depthStencilTexture}_shareDepth(e){this.shareDepth(e)}shareDepth(e){this._depthStencilTexture&&(e._depthStencilTexture&&e._depthStencilTexture.dispose(),e._depthStencilTexture=this._depthStencilTexture,e._depthStencilTextureWithStencil=this._depthStencilTextureWithStencil,this._depthStencilTexture.incrementReferences())}_swapAndDie(e){this.texture&&this.texture._swapAndDie(e),this._textures=null,this.dispose(!0)}_cloneRenderTargetWrapper(){let e=null;if(this._isMulti){const t=this.textures;if(t&&t.length>0){let s=!1,i=t.length,r=-1;const n=t[t.length-1]._source;14!==n&&12!==n||(s=!0,r=t[t.length-1].format,i--);const a=[],o=[],h=[],l=[],c=[],u=[],d=[],_={};for(let e=0;e<i;++e){const s=t[e];a.push(s.samplingMode),o.push(s.type),h.push(s.format);void 0!==_[s.uniqueId]?(l.push(-1),d.push(0)):(_[s.uniqueId]=e,s.is2DArray?(l.push(Ze.TEXTURE_2D_ARRAY),d.push(s.depth)):s.isCube?(l.push(Ze.TEXTURE_CUBE_MAP),d.push(0)):s.is3D?(l.push(Ze.TEXTURE_3D),d.push(s.depth)):(l.push(Ze.TEXTURE_2D),d.push(0))),this._faceIndices&&c.push(this._faceIndices[e]??0),this._layerIndices&&u.push(this._layerIndices[e]??0)}const f={samplingModes:a,generateMipMaps:t[0].generateMipMaps,generateDepthBuffer:this._generateDepthBuffer,generateStencilBuffer:this._generateStencilBuffer,generateDepthTexture:s,depthTextureFormat:r,types:o,formats:h,textureCount:i,targetTypes:l,faceIndex:c,layerIndex:u,layerCounts:d,label:this.label},p={width:this.width,height:this.height,depth:this.depth};e=this._engine.createMultipleRenderTarget(p,f);for(let s=0;s<i;++s){if(-1!==l[s])continue;const i=_[t[s].uniqueId];e.setTexture(e.textures[i],s)}}}else{const t={};if(t.generateDepthBuffer=this._generateDepthBuffer,t.generateMipMaps=this.texture?.generateMipMaps??!1,t.generateStencilBuffer=this._generateStencilBuffer,t.samplingMode=this.texture?.samplingMode,t.type=this.texture?.type,t.format=this.texture?.format,t.noColorAttachment=!this._textures,t.label=this.label,this.isCube)e=this._engine.createRenderTargetCubeTexture(this.width,t);else{const s={width:this.width,height:this.height,layers:this.is2DArray||this.is3D?this.texture?.depth:void 0};e=this._engine.createRenderTargetTexture(s,t)}e.texture&&(e.texture.isReady=!0)}return e}_swapRenderTargetWrapper(e){if(this._textures&&e._textures)for(let t=0;t<this._textures.length;++t)this._textures[t]._swapAndDie(e._textures[t],!1),e._textures[t].isReady=!0;this._depthStencilTexture&&e._depthStencilTexture&&(this._depthStencilTexture._swapAndDie(e._depthStencilTexture),e._depthStencilTexture.isReady=!0),this._textures=null,this._depthStencilTexture=null}_rebuild(){const e=this._cloneRenderTargetWrapper();if(e){if(this._depthStencilTexture){const t=this._depthStencilTexture.samplingMode,s=this._depthStencilTexture.format,i=t===Ze.TEXTURE_BILINEAR_SAMPLINGMODE||t===Ze.TEXTURE_TRILINEAR_SAMPLINGMODE||t===Ze.TEXTURE_LINEAR_LINEAR_MIPNEAREST;e.createDepthStencilTexture(this._depthStencilTexture._comparisonFunction,i,this._depthStencilTextureWithStencil,this._depthStencilTexture.samples,s,this._depthStencilTextureLabel)}this.samples>1&&e.setSamples(this.samples),e._swapRenderTargetWrapper(this),e.dispose()}}releaseTextures(){if(this._textures)for(let e=0;e<this._textures?.length;++e)this._textures[e].dispose();this._textures=null}dispose(e=!1){e||(this._depthStencilTexture?.dispose(),this._depthStencilTexture=null,this.releaseTextures()),this._engine._releaseRenderTargetWrapper(this)}}class Ur extends Br{constructor(e,t,s,i,r){super(e,t,s,i),this._framebuffer=null,this._depthStencilBuffer=null,this._MSAAFramebuffer=null,this._colorTextureArray=null,this._depthStencilTextureArray=null,this._disposeOnlyFramebuffers=!1,this._currentLOD=0,this._context=r}_cloneRenderTargetWrapper(){let e=null;return this._colorTextureArray&&this._depthStencilTextureArray?(e=this._engine.createMultiviewRenderTargetTexture(this.width,this.height),e.texture.isReady=!0):e=super._cloneRenderTargetWrapper(),e}_swapRenderTargetWrapper(e){super._swapRenderTargetWrapper(e),e._framebuffer=this._framebuffer,e._depthStencilBuffer=this._depthStencilBuffer,e._MSAAFramebuffer=this._MSAAFramebuffer,e._colorTextureArray=this._colorTextureArray,e._depthStencilTextureArray=this._depthStencilTextureArray,this._framebuffer=this._depthStencilBuffer=this._MSAAFramebuffer=this._colorTextureArray=this._depthStencilTextureArray=null}createDepthStencilTexture(e=0,t=!0,s=!1,i=1,r=Ze.TEXTUREFORMAT_DEPTH32_FLOAT,n){if(this._depthStencilBuffer){const e=this._engine,t=e._currentFramebuffer,s=this._context;e._bindUnboundFramebuffer(this._framebuffer),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,null),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,null),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.STENCIL_ATTACHMENT,s.RENDERBUFFER,null),e._bindUnboundFramebuffer(t),s.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null}return super.createDepthStencilTexture(e,t,s,i,r,n)}shareDepth(e){super.shareDepth(e);const t=this._context,s=this._depthStencilBuffer,i=e._MSAAFramebuffer||e._framebuffer,r=this._engine;e._depthStencilBuffer&&e._depthStencilBuffer!==s&&t.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=s;const n=e._generateStencilBuffer?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;r._bindUnboundFramebuffer(i),t.framebufferRenderbuffer(t.FRAMEBUFFER,n,t.RENDERBUFFER,s),r._bindUnboundFramebuffer(null)}_bindTextureRenderTarget(e,t=0,s,i=0){if(!e._hardwareTexture)return;const r=this._framebuffer,n=this._engine,a=n._currentFramebuffer;if(n._bindUnboundFramebuffer(r),n.webGLVersion>1){const r=this._context,n=r["COLOR_ATTACHMENT"+t];e.is2DArray||e.is3D?(s=s??this.layerIndices?.[t]??0,r.framebufferTextureLayer(r.FRAMEBUFFER,n,e._hardwareTexture.underlyingResource,i,s)):e.isCube?(s=s??this.faceIndices?.[t]??0,r.framebufferTexture2D(r.FRAMEBUFFER,n,r.TEXTURE_CUBE_MAP_POSITIVE_X+s,e._hardwareTexture.underlyingResource,i)):r.framebufferTexture2D(r.FRAMEBUFFER,n,r.TEXTURE_2D,e._hardwareTexture.underlyingResource,i)}else{const r=this._context,n=r["COLOR_ATTACHMENT"+t+"_WEBGL"],a=void 0!==s?r.TEXTURE_CUBE_MAP_POSITIVE_X+s:r.TEXTURE_2D;r.framebufferTexture2D(r.FRAMEBUFFER,n,a,e._hardwareTexture.underlyingResource,i)}n._bindUnboundFramebuffer(a)}setTexture(e,t=0,s=!0){super.setTexture(e,t,s),this._bindTextureRenderTarget(e,t)}setLayerAndFaceIndices(e,t){if(super.setLayerAndFaceIndices(e,t),!this.textures||!this.layerIndices||!this.faceIndices)return;const s=this._attachments?.length??this.textures.length;for(let e=0;e<s;e++){const t=this.textures[e];t&&(t.is2DArray||t.is3D?this._bindTextureRenderTarget(t,e,this.layerIndices[e]):t.isCube?this._bindTextureRenderTarget(t,e,this.faceIndices[e]):this._bindTextureRenderTarget(t,e))}}setLayerAndFaceIndex(e=0,t,s){if(super.setLayerAndFaceIndex(e,t,s),!this.textures||!this.layerIndices||!this.faceIndices)return;const i=this.textures[e];i.is2DArray||i.is3D?this._bindTextureRenderTarget(this.textures[e],e,this.layerIndices[e]):i.isCube&&this._bindTextureRenderTarget(this.textures[e],e,this.faceIndices[e])}dispose(e=this._disposeOnlyFramebuffers){const t=this._context;e||(this._colorTextureArray&&(this._context.deleteTexture(this._colorTextureArray),this._colorTextureArray=null),this._depthStencilTextureArray&&(this._context.deleteTexture(this._depthStencilTextureArray),this._depthStencilTextureArray=null)),this._framebuffer&&(t.deleteFramebuffer(this._framebuffer),this._framebuffer=null),this._depthStencilBuffer&&(t.deleteRenderbuffer(this._depthStencilBuffer),this._depthStencilBuffer=null),this._MSAAFramebuffer&&(t.deleteFramebuffer(this._MSAAFramebuffer),this._MSAAFramebuffer=null),super.dispose(e)}}yt.prototype.createDepthStencilTexture=function(e,t,s){if(t.isCube){const s=e.width||e;return this._createDepthStencilCubeTexture(s,t)}return this._createDepthStencilTexture(e,t,s)},Ds.prototype._createHardwareRenderTargetWrapper=function(e,t,s){const i=new Ur(e,t,s,this,this._gl);return this._renderTargetWrapperCache.push(i),i},Ds.prototype.createRenderTargetTexture=function(e,t){const s=this._createHardwareRenderTargetWrapper(!1,!1,e);let i,r,n=!0,a=!1,o=!1,h=1;void 0!==t&&"object"==typeof t&&(n=t.generateDepthBuffer??!0,a=!!t.generateStencilBuffer,o=!!t.noColorAttachment,i=t.colorAttachment,h=t.samples??1,r=t.label);const l=i||(o?null:this._createInternalTexture(e,t,!0,5)),c=e.width||e,u=e.height||e,d=this._currentFramebuffer,_=this._gl,f=_.createFramebuffer();return this._bindUnboundFramebuffer(f),s._depthStencilBuffer=this._setupFramebufferDepthAttachments(a,n,c,u),!l||l.is2DArray||l.is3D||_.framebufferTexture2D(_.FRAMEBUFFER,_.COLOR_ATTACHMENT0,_.TEXTURE_2D,l._hardwareTexture.underlyingResource,0),this._bindUnboundFramebuffer(d),s.label=r??"RenderTargetWrapper",s._framebuffer=f,s._generateDepthBuffer=n,s._generateStencilBuffer=a,s.setTextures(l),this.updateRenderTargetTextureSampleCount(s,h),s},Ds.prototype._createDepthStencilTexture=function(e,t){const s=this._gl,i=e.layers||0,r=e.depth||0;let n=s.TEXTURE_2D;0!==i?n=s.TEXTURE_2D_ARRAY:0!==r&&(n=s.TEXTURE_3D);const a=new Tt(this,12);if(a.label=t.label,!this._caps.depthTextureExtension)return ue.Error("Depth texture is not supported by your browser or hardware."),a;const o={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t};if(this._bindTextureDirectly(n,a,!0),this._setupDepthStencilTexture(a,e,o.generateStencil,0!==o.comparisonFunction&&o.bilinearFiltering,o.comparisonFunction,o.samples),void 0!==o.depthTextureFormat){if(o.depthTextureFormat!==Ze.TEXTUREFORMAT_DEPTH16&&o.depthTextureFormat!==Ze.TEXTUREFORMAT_DEPTH24&&o.depthTextureFormat!==Ze.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8&&o.depthTextureFormat!==Ze.TEXTUREFORMAT_DEPTH24_STENCIL8&&o.depthTextureFormat!==Ze.TEXTUREFORMAT_DEPTH32_FLOAT&&o.depthTextureFormat!==Ze.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8)return ue.Error("Depth texture format is not supported."),a;a.format=o.depthTextureFormat}else a.format=o.generateStencil?Ze.TEXTUREFORMAT_DEPTH24_STENCIL8:Ze.TEXTUREFORMAT_DEPTH24;const h=a.format===Ze.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||a.format===Ze.TEXTUREFORMAT_DEPTH24_STENCIL8||a.format===Ze.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8;let l=s.UNSIGNED_INT;a.format===Ze.TEXTUREFORMAT_DEPTH16?l=s.UNSIGNED_SHORT:a.format===Ze.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||a.format===Ze.TEXTUREFORMAT_DEPTH24_STENCIL8?l=s.UNSIGNED_INT_24_8:a.format===Ze.TEXTUREFORMAT_DEPTH32_FLOAT?l=s.FLOAT:a.format===Ze.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8&&(l=s.FLOAT_32_UNSIGNED_INT_24_8_REV);const c=h?s.DEPTH_STENCIL:s.DEPTH_COMPONENT;let u=c;return this.webGLVersion>1&&(a.format===Ze.TEXTUREFORMAT_DEPTH16?u=s.DEPTH_COMPONENT16:a.format===Ze.TEXTUREFORMAT_DEPTH24?u=s.DEPTH_COMPONENT24:a.format===Ze.TEXTUREFORMAT_DEPTH24UNORM_STENCIL8||a.format===Ze.TEXTUREFORMAT_DEPTH24_STENCIL8?u=s.DEPTH24_STENCIL8:a.format===Ze.TEXTUREFORMAT_DEPTH32_FLOAT?u=s.DEPTH_COMPONENT32F:a.format===Ze.TEXTUREFORMAT_DEPTH32FLOAT_STENCIL8&&(u=s.DEPTH32F_STENCIL8)),a.is2DArray?s.texImage3D(n,0,u,a.width,a.height,i,0,c,l,null):a.is3D?s.texImage3D(n,0,u,a.width,a.height,r,0,c,l,null):s.texImage2D(n,0,u,a.width,a.height,0,c,l,null),this._bindTextureDirectly(n,null),this._internalTexturesCache.push(a),a},Ds.prototype.updateRenderTargetTextureSampleCount=function(e,t){if(this.webGLVersion<2||!e||!e.texture)return 1;if(e.samples===t)return t;const s=this._gl;t=Math.min(t,this.getCaps().maxMSAASamples),e._depthStencilBuffer&&(s.deleteRenderbuffer(e._depthStencilBuffer),e._depthStencilBuffer=null),e._MSAAFramebuffer&&(s.deleteFramebuffer(e._MSAAFramebuffer),e._MSAAFramebuffer=null);const i=e.texture._hardwareTexture;if(i.releaseMSAARenderBuffers(),t>1&&"function"==typeof s.renderbufferStorageMultisample){const r=s.createFramebuffer();if(!r)throw new Error("Unable to create multi sampled framebuffer");e._MSAAFramebuffer=r,this._bindUnboundFramebuffer(e._MSAAFramebuffer);const n=this._createRenderBuffer(e.texture.width,e.texture.height,t,-1,this._getRGBABufferInternalSizedFormat(e.texture.type,e.texture.format,e.texture._useSRGBBuffer),s.COLOR_ATTACHMENT0,!1);if(!n)throw new Error("Unable to create multi sampled framebuffer");i.addMSAARenderBuffer(n)}else this._bindUnboundFramebuffer(e._framebuffer);return e.texture.samples=t,e._samples=t,e._depthStencilBuffer=this._setupFramebufferDepthAttachments(e._generateStencilBuffer,e._generateDepthBuffer,e.texture.width,e.texture.height,t),this._bindUnboundFramebuffer(null),t},Ds.prototype._setupDepthStencilTexture=function(e,t,s,i,r,n=1){const a=t.width||t,o=t.height||t,h=t.layers||0,l=t.depth||0;e.baseWidth=a,e.baseHeight=o,e.width=a,e.height=o,e.is2DArray=h>0,e.depth=h||l,e.isReady=!0,e.samples=n,e.generateMipMaps=!1,e.samplingMode=i?Ze.TEXTURE_BILINEAR_SAMPLINGMODE:Ze.TEXTURE_NEAREST_SAMPLINGMODE,e.type=Ze.TEXTURETYPE_UNSIGNED_INT,e._comparisonFunction=r;const c=this._gl,u=this._getTextureTarget(e),d=this._getSamplingParameters(e.samplingMode,!1);c.texParameteri(u,c.TEXTURE_MAG_FILTER,d.mag),c.texParameteri(u,c.TEXTURE_MIN_FILTER,d.min),c.texParameteri(u,c.TEXTURE_WRAP_S,c.CLAMP_TO_EDGE),c.texParameteri(u,c.TEXTURE_WRAP_T,c.CLAMP_TO_EDGE),this.webGLVersion>1&&(0===r?(c.texParameteri(u,c.TEXTURE_COMPARE_FUNC,Ze.LEQUAL),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.NONE)):(c.texParameteri(u,c.TEXTURE_COMPARE_FUNC,r),c.texParameteri(u,c.TEXTURE_COMPARE_MODE,c.COMPARE_REF_TO_TEXTURE)))},yt.prototype.setTextureFromPostProcess=function(e,t,s){let i=null;t&&(t._forcedOutputTexture?i=t._forcedOutputTexture:t._textures.data[t._currentRenderTextureInd]&&(i=t._textures.data[t._currentRenderTextureInd])),this._bindTexture(e,i?.texture??null,s)},yt.prototype.setTextureFromPostProcessOutput=function(e,t,s){this._bindTexture(e,t?._outputTexture?.texture??null,s)},ut.prototype.setTextureFromPostProcess=function(e,t){this._engine.setTextureFromPostProcess(this._samplers[e],t,e)},ut.prototype.setTextureFromPostProcessOutput=function(e,t){this._engine.setTextureFromPostProcessOutput(this._samplers[e],t,e)};class kr{static RegisterShaderCodeProcessing(e,t){t?kr._CustomShaderCodeProcessing[e??""]=t:delete kr._CustomShaderCodeProcessing[e??""]}static _GetShaderCodeProcessing(e){return kr._CustomShaderCodeProcessing[e]??kr._CustomShaderCodeProcessing[""]}get samples(){return this._samples}set samples(e){this._samples=Math.min(e,this._engine.getCaps().maxMSAASamples),this._textures.forEach((e=>{e.setSamples(this._samples)}))}get shaderLanguage(){return this._shaderLanguage}getEffectName(){return this._fragmentUrl}set onActivate(e){this._onActivateObserver&&this.onActivateObservable.remove(this._onActivateObserver),e&&(this._onActivateObserver=this.onActivateObservable.add(e))}set onSizeChanged(e){this._onSizeChangedObserver&&this.onSizeChangedObservable.remove(this._onSizeChangedObserver),this._onSizeChangedObserver=this.onSizeChangedObservable.add(e)}set onApply(e){this._onApplyObserver&&this.onApplyObservable.remove(this._onApplyObserver),this._onApplyObserver=this.onApplyObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}get inputTexture(){return this._textures.data[this._currentRenderTextureInd]}set inputTexture(e){this._forcedOutputTexture=e}restoreDefaultInputTexture(){this._forcedOutputTexture&&(this._forcedOutputTexture=null,this.markTextureDirty())}getCamera(){return this._camera}get texelSize(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.texelSize:(this._forcedOutputTexture&&this._texelSize.copyFromFloats(1/this._forcedOutputTexture.width,1/this._forcedOutputTexture.height),this._texelSize)}constructor(e,t,s,i,r,n,a=Ze.TEXTURE_NEAREST_SAMPLINGMODE,o,h,l=null,c=Ze.TEXTURETYPE_UNSIGNED_INT,u="postprocess",d,_=!1,f=Ze.TEXTUREFORMAT_RGBA,p,m){this._parentContainer=null,this.width=-1,this.height=-1,this.nodeMaterialSource=null,this._outputTexture=null,this.autoClear=!0,this.forceAutoClearInAlphaMode=!1,this.alphaMode=Ze.ALPHA_DISABLE,this.animations=[],this.enablePixelPerfectMode=!1,this.forceFullscreenViewport=!0,this.scaleMode=Ze.SCALEMODE_FLOOR,this.alwaysForcePOT=!1,this._samples=1,this.adaptScaleToCurrentViewport=!1,this._shadersLoaded=!1,this._webGPUReady=!1,this._reusable=!1,this._renderId=0,this.externalTextureSamplerBinding=!1,this._textures=new Zt(2),this._textureCache=[],this._currentRenderTextureInd=0,this._scaleRatio=new B(1,1),this._texelSize=B.Zero(),this.onEffectCreatedObservable=new g(void 0,!0),this.onActivateObservable=new g,this.onSizeChangedObservable=new g,this.onApplyObservable=new g,this.onBeforeRenderObservable=new g,this.onAfterRenderObservable=new g,this._importPromises=[],this.name=e;let T=1,E=null;if(s&&!Array.isArray(s)){const e=s;s=e.uniforms??null,i=e.samplers??null,T=e.size??1,n=e.camera??null,a=e.samplingMode??Ze.TEXTURE_NEAREST_SAMPLINGMODE,o=e.engine,h=e.reusable,l=e.defines??null,c=e.textureType??Ze.TEXTURETYPE_UNSIGNED_INT,u=e.vertexUrl??"postprocess",d=e.indexParameters,_=e.blockCompilation??!1,f=e.textureFormat??Ze.TEXTUREFORMAT_RGBA,p=e.shaderLanguage??0,E=e.uniformBuffers??null}else r&&(T="number"==typeof r?r:{width:r.width,height:r.height});null!=n?(this._camera=n,this._scene=n.getScene(),n.attachPostProcess(this),this._engine=this._scene.getEngine(),this._scene.postProcesses.push(this),this.uniqueId=this._scene.getUniqueId()):o&&(this._engine=o,this._engine.postProcesses.push(this)),this._options=T,this.renderTargetSamplingMode=a||Ze.TEXTURE_NEAREST_SAMPLINGMODE,this._reusable=h||!1,this._textureType=c,this._textureFormat=f,this._shaderLanguage=p||0,this._samplers=i||[],this._samplers.push("textureSampler"),this._fragmentUrl=t,this._vertexUrl=u,this._parameters=s||[],this._parameters.push("scale"),this._uniformBuffers=E||[],this._indexParameters=d,this._drawWrapper=new ms(this._engine),this._webGPUReady=1===this._shaderLanguage,this._postConstructor(_,l,m)}_gatherImports(e=!1,t){e&&this._webGPUReady?t.push(Promise.all([import("./postprocess.vertex-DzqXlss5.esm.min.js")])):t.push(Promise.all([Promise.resolve().then((function(){return wr}))]))}_postConstructor(e,t=null,s){const i=this.getEngine().isWebGPU&&!kr.ForceGLSL;this._gatherImports(i,this._importPromises),s&&s(i,this._importPromises),i&&this._webGPUReady&&(this._shaderLanguage=1),e||this.updateEffect(t)}getClassName(){return"PostProcess"}getEngine(){return this._engine}getEffect(){return this._drawWrapper.effect}shareOutputWith(e){return this._disposeTextures(),this._shareOutputWithPostProcess=e,this}useOwnOutput(){0==this._textures.length&&(this._textures=new Zt(2)),this._shareOutputWithPostProcess=null}updateEffect(e=null,t=null,s=null,i,r,n,a,o){const h=kr._GetShaderCodeProcessing(this.name);if(h?.defineCustomBindings){const i=t?.slice()??[];i.push(...this._parameters);const r=s?.slice()??[];r.push(...this._samplers),e=h.defineCustomBindings(this.name,e,i,r),t=i,s=r}this._postProcessDefines=e,this._drawWrapper.effect=this._engine.createEffect({vertex:a??this._vertexUrl,fragment:o??this._fragmentUrl},{attributes:["position"],uniformsNames:t||this._parameters,uniformBuffersNames:this._uniformBuffers,samplers:s||this._samplers,defines:null!==e?e:"",fallbacks:null,onCompiled:r??null,onError:n??null,indexParameters:i||this._indexParameters,processCodeAfterIncludes:h?.processCodeAfterIncludes?(e,t)=>h.processCodeAfterIncludes(this.name,e,t):null,processFinalCode:h?.processFinalCode?(e,t)=>h.processFinalCode(this.name,e,t):null,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{await Promise.all(this._importPromises),this._shadersLoaded=!0}},this._engine),this.onEffectCreatedObservable.notifyObservers(this._drawWrapper.effect)}isReusable(){return this._reusable}markTextureDirty(){this.width=-1}_createRenderTargetTexture(e,t,s=0){for(let i=0;i<this._textureCache.length;i++)if(this._textureCache[i].texture.width===e.width&&this._textureCache[i].texture.height===e.height&&this._textureCache[i].postProcessChannel===s&&this._textureCache[i].texture._generateDepthBuffer===t.generateDepthBuffer&&this._textureCache[i].texture.samples===t.samples)return this._textureCache[i].texture;const i=this._engine.createRenderTargetTexture(e,t);return this._textureCache.push({texture:i,postProcessChannel:s,lastUsedRenderId:-1}),i}_flushTextureCache(){const e=this._renderId;for(let t=this._textureCache.length-1;t>=0;t--)if(e-this._textureCache[t].lastUsedRenderId>100){let e=!1;for(let s=0;s<this._textures.length;s++)if(this._textures.data[s]===this._textureCache[t].texture){e=!0;break}e||(this._textureCache[t].texture.dispose(),this._textureCache.splice(t,1))}}resize(e,t,s=null,i=!1,r=!1){this._textures.length>0&&this._textures.reset(),this.width=e,this.height=t;let n=null;if(s)for(let e=0;e<s._postProcesses.length;e++)if(null!==s._postProcesses[e]){n=s._postProcesses[e];break}const a={width:this.width,height:this.height},o={generateMipMaps:i,generateDepthBuffer:r||n===this,generateStencilBuffer:(r||n===this)&&this._engine.isStencilEnable,samplingMode:this.renderTargetSamplingMode,type:this._textureType,format:this._textureFormat,samples:this._samples,label:"PostProcessRTT-"+this.name};this._textures.push(this._createRenderTargetTexture(a,o,0)),this._reusable&&this._textures.push(this._createRenderTargetTexture(a,o,1)),this._texelSize.copyFromFloats(1/this.width,1/this.height),this.onSizeChangedObservable.notifyObservers(this)}_getTarget(){let e;if(this._shareOutputWithPostProcess)e=this._shareOutputWithPostProcess.inputTexture;else if(this._forcedOutputTexture)e=this._forcedOutputTexture,this.width=this._forcedOutputTexture.width,this.height=this._forcedOutputTexture.height;else{let t;e=this.inputTexture;for(let s=0;s<this._textureCache.length;s++)if(this._textureCache[s].texture===e){t=this._textureCache[s];break}t&&(t.lastUsedRenderId=this._renderId)}return e}activate(e,t=null,s){const i=(e=e||this._camera).getScene(),r=i.getEngine(),n=r.getCaps().maxTextureSize,a=(t?t.width:this._engine.getRenderWidth(!0))*this._options|0,o=(t?t.height:this._engine.getRenderHeight(!0))*this._options|0;let h=this._options.width||a,l=this._options.height||o;const c=this.renderTargetSamplingMode!==Ze.TEXTURE_NEAREST_LINEAR&&this.renderTargetSamplingMode!==Ze.TEXTURE_NEAREST_NEAREST&&this.renderTargetSamplingMode!==Ze.TEXTURE_LINEAR_LINEAR;let u=null;if(!this._shareOutputWithPostProcess&&!this._forcedOutputTexture){if(this.adaptScaleToCurrentViewport){const e=r.currentViewport;e&&(h*=e.width,l*=e.height)}(c||this.alwaysForcePOT)&&(this._options.width||(h=r.needPOTTextures?Wt(h,n,this.scaleMode):h),this._options.height||(l=r.needPOTTextures?Wt(l,n,this.scaleMode):l)),this.width===h&&this.height===l&&(u=this._getTarget())||this.resize(h,l,e,c,s),this._textures.forEach((e=>{e.samples!==this.samples&&this._engine.updateRenderTargetTextureSampleCount(e,this.samples)})),this._flushTextureCache(),this._renderId++}return u||(u=this._getTarget()),this.enablePixelPerfectMode?(this._scaleRatio.copyFromFloats(a/h,o/l),this._engine.bindFramebuffer(u,0,a,o,this.forceFullscreenViewport)):(this._scaleRatio.copyFromFloats(1,1),this._engine.bindFramebuffer(u,0,void 0,void 0,this.forceFullscreenViewport)),this._engine._debugInsertMarker?.(`post process ${this.name} input`),this.onActivateObservable.notifyObservers(e),this.autoClear&&(this.alphaMode===Ze.ALPHA_DISABLE||this.forceAutoClearInAlphaMode)&&this._engine.clear(this.clearColor?this.clearColor:i.clearColor,i._allowPostProcessClearColor,!0,!0),this._reusable&&(this._currentRenderTextureInd=(this._currentRenderTextureInd+1)%2),u}get isSupported(){return this._drawWrapper.effect.isSupported}get aspectRatio(){return this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.aspectRatio:this._forcedOutputTexture?this._forcedOutputTexture.width/this._forcedOutputTexture.height:this.width/this.height}isReady(){return this._drawWrapper.effect?.isReady()??!1}apply(){if(!this._drawWrapper.effect?.isReady())return null;let e;return this._engine.enableEffect(this._drawWrapper),this._engine.setState(!1),this._engine.setDepthBuffer(!1),this._engine.setDepthWrite(!1),this._engine.setAlphaMode(this.alphaMode),this.alphaConstants&&this.getEngine().setAlphaConstants(this.alphaConstants.r,this.alphaConstants.g,this.alphaConstants.b,this.alphaConstants.a),e=this._shareOutputWithPostProcess?this._shareOutputWithPostProcess.inputTexture:this._forcedOutputTexture?this._forcedOutputTexture:this.inputTexture,this.externalTextureSamplerBinding||this._drawWrapper.effect._bindTexture("textureSampler",e?.texture),this._drawWrapper.effect.setVector2("scale",this._scaleRatio),this.onApplyObservable.notifyObservers(this._drawWrapper.effect),kr._GetShaderCodeProcessing(this.name)?.bindCustomBindings?.(this.name,this._drawWrapper.effect),this._drawWrapper.effect}_disposeTextures(){this._shareOutputWithPostProcess||this._forcedOutputTexture?this._disposeTextureCache():(this._disposeTextureCache(),this._textures.dispose())}_disposeTextureCache(){for(let e=this._textureCache.length-1;e>=0;e--)this._textureCache[e].texture.dispose();this._textureCache.length=0}setPrePassRenderer(e){return!!this._prePassEffectConfiguration&&(this._prePassEffectConfiguration=e.addEffectConfiguration(this._prePassEffectConfiguration),this._prePassEffectConfiguration.enabled=!0,!0)}dispose(e){let t;if(e=e||this._camera,this._disposeTextures(),this._scene&&(t=this._scene.postProcesses.indexOf(this),-1!==t&&this._scene.postProcesses.splice(t,1)),this._parentContainer){const e=this._parentContainer.postProcesses.indexOf(this);e>-1&&this._parentContainer.postProcesses.splice(e,1),this._parentContainer=null}if(t=this._engine.postProcesses.indexOf(this),-1!==t&&this._engine.postProcesses.splice(t,1),e){if(e.detachPostProcess(this),t=e._postProcesses.indexOf(this),0===t&&e._postProcesses.length>0){const e=this._camera._getFirstPostProcess();e&&e.markTextureDirty()}this.onActivateObservable.clear(),this.onAfterRenderObservable.clear(),this.onApplyObservable.clear(),this.onBeforeRenderObservable.clear(),this.onSizeChangedObservable.clear(),this.onEffectCreatedObservable.clear()}}serialize(){const e=re.Serialize(this),t=this.getCamera()||this._scene&&this._scene.activeCamera;return e.customType="BABYLON."+this.getClassName(),e.cameraId=t?t.id:null,e.reusable=this._reusable,e.textureType=this._textureType,e.fragmentUrl=this._fragmentUrl,e.parameters=this._parameters,e.samplers=this._samplers,e.options=this._options,e.defines=this._postProcessDefines,e.textureFormat=this._textureFormat,e.vertexUrl=this._vertexUrl,e.indexParameters=this._indexParameters,e}clone(){const e=this.serialize();e._engine=this._engine,e.cameraId=null;const t=kr.Parse(e,this._scene,"");return t?(t.onActivateObservable=this.onActivateObservable.clone(),t.onSizeChangedObservable=this.onSizeChangedObservable.clone(),t.onApplyObservable=this.onApplyObservable.clone(),t.onBeforeRenderObservable=this.onBeforeRenderObservable.clone(),t.onAfterRenderObservable=this.onAfterRenderObservable.clone(),t._prePassEffectConfiguration=this._prePassEffectConfiguration,t):null}static Parse(e,t,s){const i=S(e.customType);if(!i||!i._Parse)return null;const r=t?t.getCameraById(e.cameraId):null;return i._Parse(e,r,t,s)}static _Parse(e,t,s,i){return re.Parse((()=>new kr(e.name,e.fragmentUrl,e.parameters,e.samplers,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable,e.defines,e.textureType,e.vertexUrl,e.indexParameters,!1,e.textureFormat)),e,s,i)}}kr.ForceGLSL=!1,kr._CustomShaderCodeProcessing={},e([a()],kr.prototype,"uniqueId",void 0),e([a()],kr.prototype,"name",void 0),e([a()],kr.prototype,"width",void 0),e([a()],kr.prototype,"height",void 0),e([a()],kr.prototype,"renderTargetSamplingMode",void 0),e([d()],kr.prototype,"clearColor",void 0),e([a()],kr.prototype,"autoClear",void 0),e([a()],kr.prototype,"forceAutoClearInAlphaMode",void 0),e([a()],kr.prototype,"alphaMode",void 0),e([a()],kr.prototype,"alphaConstants",void 0),e([a()],kr.prototype,"enablePixelPerfectMode",void 0),e([a()],kr.prototype,"forceFullscreenViewport",void 0),e([a()],kr.prototype,"scaleMode",void 0),e([a()],kr.prototype,"alwaysForcePOT",void 0),e([a("samples")],kr.prototype,"_samples",void 0),e([a()],kr.prototype,"adaptScaleToCurrentViewport",void 0),I("BABYLON.PostProcess",kr),Ds.prototype.createRenderTargetCubeTexture=function(e,t){const s=this._createHardwareRenderTargetWrapper(!1,!0,e),i={generateMipMaps:!0,generateDepthBuffer:!0,generateStencilBuffer:!1,type:Ze.TEXTURETYPE_UNSIGNED_INT,samplingMode:Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,format:Ze.TEXTUREFORMAT_RGBA,...t};i.generateStencilBuffer=i.generateDepthBuffer&&i.generateStencilBuffer,(i.type!==Ze.TEXTURETYPE_FLOAT||this._caps.textureFloatLinearFiltering)&&(i.type!==Ze.TEXTURETYPE_HALF_FLOAT||this._caps.textureHalfFloatLinearFiltering)||(i.samplingMode=Ze.TEXTURE_NEAREST_SAMPLINGMODE);const r=this._gl,n=new Tt(this,5);this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,n,!0);const a=this._getSamplingParameters(i.samplingMode,i.generateMipMaps);i.type!==Ze.TEXTURETYPE_FLOAT||this._caps.textureFloat||(i.type=Ze.TEXTURETYPE_UNSIGNED_INT,ue.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type")),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MAG_FILTER,a.mag),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_MIN_FILTER,a.min),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_CUBE_MAP,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE);for(let t=0;t<6;t++)r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,this._getRGBABufferInternalSizedFormat(i.type,i.format),e,e,0,this._getInternalFormat(i.format),this._getWebGLTextureType(i.type),null);const o=r.createFramebuffer();return this._bindUnboundFramebuffer(o),s._depthStencilBuffer=this._setupFramebufferDepthAttachments(i.generateStencilBuffer,i.generateDepthBuffer,e,e),i.generateMipMaps&&r.generateMipmap(r.TEXTURE_CUBE_MAP),this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._bindUnboundFramebuffer(null),s._framebuffer=o,s._generateDepthBuffer=i.generateDepthBuffer,s._generateStencilBuffer=i.generateStencilBuffer,n.width=e,n.height=e,n.isReady=!0,n.isCube=!0,n.samples=1,n.generateMipMaps=i.generateMipMaps,n.samplingMode=i.samplingMode,n.type=i.type,n.format=i.format,this._internalTexturesCache.push(n),s.setTextures(n),s},Ds.prototype.setDepthStencilTexture=function(e,t,s,i){void 0!==e&&(t&&(this._boundUniforms[e]=t),s&&s.depthStencilTexture?this._setTexture(e,s,!1,!0,i):this._setTexture(e,null,void 0,void 0,i))};const Gr={positions:[1,1,-1,1,-1,-1,1,-1],indices:[0,1,2,0,2,3]};class Vr{constructor(e,t=Gr){this._fullscreenViewport=new Jt(0,0,1,1);const s=t.positions??Gr.positions,i=t.indices??Gr.indices;this.engine=e,this._vertexBuffers={[ns.PositionKind]:new ns(e,s,ns.PositionKind,!1,!1,2)},this._indexBuffer=e.createIndexBuffer(i),this._onContextRestoredObserver=e.onContextRestoredObservable.add((()=>{this._indexBuffer=e.createIndexBuffer(i);for(const e in this._vertexBuffers){this._vertexBuffers[e]._rebuild()}}))}setViewport(e=this._fullscreenViewport){this.engine.setViewport(e)}bindBuffers(e){this.engine.bindBuffers(this._vertexBuffers,this._indexBuffer,e)}applyEffectWrapper(e){this.engine.setState(!0),this.engine.depthCullingState.depthTest=!1,this.engine.stencilState.stencilTest=!1,this.engine.enableEffect(e._drawWrapper),this.bindBuffers(e.effect),e.onApplyObservable.notifyObservers({})}saveStates(){this._savedStateDepthTest=this.engine.depthCullingState.depthTest,this._savedStateStencilTest=this.engine.stencilState.stencilTest}restoreStates(){this.engine.depthCullingState.depthTest=this._savedStateDepthTest,this.engine.stencilState.stencilTest=this._savedStateStencilTest}draw(){this.engine.drawElementsType(Ze.MATERIAL_TriangleFillMode,0,6)}_isRenderTargetTexture(e){return void 0!==e.renderTarget}render(e,t=null){if(!e.effect.isReady())return;this.saveStates(),this.setViewport();const s=null===t?null:this._isRenderTargetTexture(t)?t.renderTarget:t;s&&this.engine.bindFramebuffer(s),this.applyEffectWrapper(e),this.draw(),s&&this.engine.unBindFramebuffer(s),this.restoreStates()}dispose(){const e=this._vertexBuffers[ns.PositionKind];e&&(e.dispose(),delete this._vertexBuffers[ns.PositionKind]),this._indexBuffer&&this.engine._releaseBuffer(this._indexBuffer),this._onContextRestoredObserver&&(this.engine.onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}}class Hr{get effect(){return this._drawWrapper.effect}set effect(e){this._drawWrapper.effect=e}constructor(e){let t;this.onApplyObservable=new g;const s=e.uniformNames||[];e.vertexShader?t={fragmentSource:e.fragmentShader,vertexSource:e.vertexShader,spectorName:e.name||"effectWrapper"}:(s.push("scale"),t={fragmentSource:e.fragmentShader,vertex:"postprocess",spectorName:e.name||"effectWrapper"},this.onApplyObservable.add((()=>{this.effect.setFloat2("scale",1,1)})));const i=e.defines?e.defines.join("\n"):"";this._drawWrapper=new ms(e.engine),e.useShaderStore?(t.fragment=t.fragmentSource,t.vertex||(t.vertex=t.vertexSource),delete t.fragmentSource,delete t.vertexSource,this.effect=e.engine.createEffect(t,e.attributeNames||["position"],s,e.samplerNames,i,void 0,e.onCompiled,void 0,void 0,e.shaderLanguage,e.extraInitializationsAsync)):(this.effect=new ut(t,e.attributeNames||["position"],s,e.samplerNames,e.engine,i,void 0,e.onCompiled,void 0,void 0,void 0,e.shaderLanguage,e.extraInitializationsAsync),this._onContextRestoredObserver=e.engine.onContextRestoredObservable.add((()=>{this.effect._pipelineContext=null,this.effect._prepareEffect()})))}dispose(e=!1){this._onContextRestoredObserver&&(this.effect.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null),this.effect.dispose()}}const zr="passPixelShader",Xr="varying vec2 vUV;uniform sampler2D textureSampler;\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) \n{gl_FragColor=texture2D(textureSampler,vUV);}";$e.ShadersStore[zr]=Xr;const Wr={name:zr,shader:Xr};var Yr=Object.freeze({__proto__:null,passPixelShader:Wr});let Kr;function qr(){if(!Kr){let e,t=null;const s={preserveDrawingBuffer:!0,depth:!1,stencil:!1,alpha:!0,premultipliedAlpha:!1,antialias:!1,failIfMajorPerformanceCaveat:!1};try{e=new OffscreenCanvas(100,100),t=new Ds(e,!1,s)}catch(i){e=document.createElement("canvas"),t=new Ds(e,!1,s)}C.Instances.pop(),C.OnEnginesDisposedObservable.add((e=>{t&&e!==t&&!t.isDisposed&&0===C.Instances.length&&function(){Kr&&(Kr.wrapper.dispose(),Kr.renderer.dispose(),Kr.engine.dispose());Kr=null}()})),t.getCaps().parallelShaderCompile=void 0;const i=new Vr(t),r=new Hr({engine:t,name:Wr.name,fragmentShader:Wr.shader,samplerNames:["textureSampler"]});Kr={canvas:e,engine:t,renderer:i,wrapper:r}}return Kr}async function Qr(e,t,s,i,r="image/png",n,a){const o=await s.readPixels(0,0,e,t);Zr(e,t,new Uint8Array(o.buffer),i,r,n,!0,void 0,a)}function jr(e,t,s,i="image/png",r,n=!1,a=!1,o){return new Promise((h=>{Zr(e,t,s,(e=>h(e)),i,r,n,a,o)}))}function Zr(e,t,s,i,r="image/png",n,a=!1,o=!1,h){const l=qr();if(l.engine.setSize(e,t,!0),s instanceof Float32Array){const e=new Uint8Array(s.length);let t=s.length;for(;t--;){const i=s[t];e[t]=Math.round(255*Q.Clamp(i))}s=e}const c=l.engine.createRawTexture(s,e,t,Ze.TEXTUREFORMAT_RGBA,!1,!a,Ze.TEXTURE_NEAREST_NEAREST);l.renderer.setViewport(),l.renderer.applyEffectWrapper(l.wrapper),l.wrapper.effect._bindTexture("textureSampler",c),l.renderer.draw(),o?Yt.ToBlob(l.canvas,(e=>{const t=new FileReader;t.onload=e=>{const t=e.target.result;i&&i(t)},t.readAsArrayBuffer(e)}),r,h):Yt.EncodeScreenshotCanvasData(l.canvas,i,r,n,h),c.dispose()}Yt.DumpData=Zr,Yt.DumpDataAsync=jr,Yt.DumpFramebuffer=Qr,ut.prototype.setDepthStencilTexture=function(e,t){this._engine.setDepthStencilTexture(this._samplers[e],this._uniforms[e],t,e)};class $r extends Dr{get renderList(){return this._renderList}set renderList(e){this._unObserveRenderList&&(this._unObserveRenderList(),this._unObserveRenderList=null),e&&(this._unObserveRenderList=x(e,this._renderListHasChanged)),this._renderList=e}get postProcesses(){return this._postProcesses}get _prePassEnabled(){return!!this._prePassRenderTarget&&this._prePassRenderTarget.enabled}set onAfterUnbind(e){this._onAfterUnbindObserver&&this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver),this._onAfterUnbindObserver=this.onAfterUnbindObservable.add(e)}set onBeforeRender(e){this._onBeforeRenderObserver&&this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver),this._onBeforeRenderObserver=this.onBeforeRenderObservable.add(e)}set onAfterRender(e){this._onAfterRenderObserver&&this.onAfterRenderObservable.remove(this._onAfterRenderObserver),this._onAfterRenderObserver=this.onAfterRenderObservable.add(e)}set onClear(e){this._onClearObserver&&this.onClearObservable.remove(this._onClearObserver),this._onClearObserver=this.onClearObservable.add(e)}get renderPassIds(){return this._renderPassIds}get currentRefreshId(){return this._currentRefreshId}setMaterialForRendering(e,t){let s;s=Array.isArray(e)?e:[e];for(let e=0;e<s.length;++e)for(let i=0;i<this._renderPassIds.length;++i)s[e].setMaterialForRenderPass(this._renderPassIds[i],void 0!==t?Array.isArray(t)?t[i]:t:void 0)}get isMulti(){return this._renderTarget?.isMulti??!1}get renderTargetOptions(){return this._renderTargetOptions}get renderTarget(){return this._renderTarget}_onRatioRescale(){this._sizeRatio&&this.resize(this._initialSizeParameter)}set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag)}get boundingBoxSize(){return this._boundingBoxSize}get depthStencilTexture(){return this._renderTarget?._depthStencilTexture??null}constructor(e,t,s,i=!1,r=!0,n=Ze.TEXTURETYPE_UNSIGNED_INT,a=!1,o=Dr.TRILINEAR_SAMPLINGMODE,h=!0,l=!1,c=!1,u=Ze.TEXTUREFORMAT_RGBA,d=!1,_,f,p=!1,m=!1){let T,E=!0;if("object"==typeof i){const e=i;i=!!e.generateMipMaps,r=e.doNotChangeAspectRatio??!0,n=e.type??Ze.TEXTURETYPE_UNSIGNED_BYTE,a=!!e.isCube,o=e.samplingMode??Dr.TRILINEAR_SAMPLINGMODE,h=e.generateDepthBuffer??!0,l=!!e.generateStencilBuffer,c=!!e.isMulti,u=e.format??Ze.TEXTUREFORMAT_RGBA,d=!!e.delayAllocation,_=e.samples,f=e.creationFlags,p=!!e.noColorAttachment,m=!!e.useSRGBBuffer,T=e.colorAttachment,E=e.gammaSpace??E}if(super(null,s,!i,void 0,o,void 0,void 0,void 0,void 0,u),this._unObserveRenderList=null,this._renderListHasChanged=(e,t)=>{const s=this._renderList?this._renderList.length:0;(0===t&&s>0||0===s)&&this.getScene()?.meshes.forEach((e=>{e._markSubMeshesAsLightDirty()}))},this.renderParticles=!0,this.renderSprites=!1,this.forceLayerMaskCheck=!1,this.ignoreCameraViewport=!1,this.onBeforeBindObservable=new g,this.onAfterUnbindObservable=new g,this.onBeforeRenderObservable=new g,this.onAfterRenderObservable=new g,this.onClearObservable=new g,this.onResizeObservable=new g,this._cleared=!1,this.skipInitialClear=!1,this._currentRefreshId=-1,this._refreshRate=1,this._samples=1,this._canRescale=!0,this._renderTarget=null,this.boundingBoxPosition=U.Zero(),!(s=this.getScene()))return;const A=this.getScene().getEngine();this._gammaSpace=E,this._coordinatesMode=Dr.PROJECTION_MODE,this.renderList=[],this.name=e,this.isRenderTarget=!0,this._initialSizeParameter=t,this._renderPassIds=[],this._isCubeData=a,this._processSizeParameter(t),this.renderPassId=this._renderPassIds[0],this._resizeObserver=A.onResizeObservable.add((()=>{})),this._generateMipMaps=!!i,this._doNotChangeAspectRatio=r,this._renderingManager=new $i(s),this._renderingManager._useSceneAutoClearSetup=!0,c||(this._renderTargetOptions={generateMipMaps:i,type:n,format:this._format??void 0,samplingMode:this.samplingMode,generateDepthBuffer:h,generateStencilBuffer:l,samples:_,creationFlags:f,noColorAttachment:p,useSRGBBuffer:m,colorAttachment:T,label:this.name},this.samplingMode===Dr.NEAREST_SAMPLINGMODE&&(this.wrapU=Dr.CLAMP_ADDRESSMODE,this.wrapV=Dr.CLAMP_ADDRESSMODE),d||(a?(this._renderTarget=s.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions),this.coordinatesMode=Dr.INVCUBIC_MODE,this._textureMatrix=V.Identity()):this._renderTarget=s.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==_&&(this.samples=_)))}createDepthStencilTexture(e=0,t=!0,s=!1,i=1,r=Ze.TEXTUREFORMAT_DEPTH32_FLOAT,n){this._renderTarget?.createDepthStencilTexture(e,t,s,i,r,n)}_releaseRenderPassId(){if(this._scene){const e=this._scene.getEngine();for(let t=0;t<this._renderPassIds.length;++t)e.releaseRenderPassId(this._renderPassIds[t])}this._renderPassIds=[]}_createRenderPassId(){this._releaseRenderPassId();const e=this._scene.getEngine(),t=this._isCubeData?6:this.getRenderLayers()||1;for(let s=0;s<t;++s)this._renderPassIds[s]=e.createRenderPassId(`RenderTargetTexture - ${this.name}#${s}`)}_processSizeParameter(e,t=!0){if(e.ratio){this._sizeRatio=e.ratio;const t=this._getEngine();this._size={width:this._bestReflectionRenderTargetDimension(t.getRenderWidth(),this._sizeRatio),height:this._bestReflectionRenderTargetDimension(t.getRenderHeight(),this._sizeRatio)}}else this._size=e;t&&this._createRenderPassId()}get samples(){return this._renderTarget?.samples??this._samples}set samples(e){this._renderTarget&&(this._samples=this._renderTarget.setSamples(e))}resetRefreshCounter(){this._currentRefreshId=-1}get refreshRate(){return this._refreshRate}set refreshRate(e){this._refreshRate=e,this.resetRefreshCounter()}addPostProcess(e){if(!this._postProcessManager){const e=this.getScene();if(!e)return;this._postProcessManager=new Qi(e),this._postProcesses=new Array}this._postProcesses.push(e),this._postProcesses[0].autoClear=!1}clearPostProcesses(e=!1){if(this._postProcesses){if(e)for(const e of this._postProcesses)e.dispose();this._postProcesses=[]}}removePostProcess(e){if(!this._postProcesses)return;const t=this._postProcesses.indexOf(e);-1!==t&&(this._postProcesses.splice(t,1),this._postProcesses.length>0&&(this._postProcesses[0].autoClear=!1))}_shouldRender(){return-1===this._currentRefreshId||this.refreshRate===this._currentRefreshId?(this._currentRefreshId=1,!0):(this._currentRefreshId++,!1)}getRenderSize(){return this.getRenderWidth()}getRenderWidth(){return this._size.width?this._size.width:this._size}getRenderHeight(){return this._size.width?this._size.height:this._size}getRenderLayers(){const e=this._size.layers;if(e)return e;const t=this._size.depth;return t||0}disableRescaling(){this._canRescale=!1}get canRescale(){return this._canRescale}scale(e){const t=Math.max(1,this.getRenderSize()*e);this.resize(t)}getReflectionTextureMatrix(){return this.isCube?this._textureMatrix:super.getReflectionTextureMatrix()}resize(e){const t=this.isCube;this._renderTarget?.dispose(),this._renderTarget=null;const s=this.getScene();s&&(this._processSizeParameter(e,!1),this._renderTarget=t?s.getEngine().createRenderTargetCubeTexture(this.getRenderSize(),this._renderTargetOptions):s.getEngine().createRenderTargetTexture(this._size,this._renderTargetOptions),this._texture=this._renderTarget.texture,void 0!==this._renderTargetOptions.samples&&(this.samples=this._renderTargetOptions.samples),this.onResizeObservable.hasObservers()&&this.onResizeObservable.notifyObservers(this))}render(e=!1,t=!1){this._render(e,t)}isReadyForRendering(){return this._render(!1,!1,!0)}_render(e=!1,t=!1,s=!1){const i=this.getScene();if(!i)return s;const r=i.getEngine();if(void 0!==this.useCameraPostProcesses&&(e=this.useCameraPostProcesses),this._waitingRenderList){if(!this.renderListPredicate){this.renderList=[];for(let e=0;e<this._waitingRenderList.length;e++){const t=this._waitingRenderList[e],s=i.getMeshById(t);s&&this.renderList.push(s)}}this._waitingRenderList=void 0}if(this.renderListPredicate){this.renderList?this.renderList.length=0:this.renderList=[];const e=this.getScene();if(!e)return s;const t=e.meshes;for(let e=0;e<t.length;e++){const s=t[e];this.renderListPredicate(s)&&this.renderList.push(s)}}const n=r.currentRenderPassId;this.onBeforeBindObservable.notifyObservers(this);const a=this.activeCamera??i.activeCamera,o=i.activeCamera;a&&(a!==i.activeCamera&&(i.setTransformMatrix(a.getViewMatrix(),a.getProjectionMatrix(!0)),i.activeCamera=a),r.setViewport(a.rigParent?a.rigParent.viewport:a.viewport,this.getRenderWidth(),this.getRenderHeight())),this._defaultRenderListPrepared=!1;let h=s;if(s){i.getViewMatrix()||i.updateTransformMatrix();const e=this.is2DArray||this.is3D?this.getRenderLayers():this.isCube?6:1;for(let t=0;t<e&&h;t++){let e=null;const n=this.renderList?this.renderList:i.getActiveMeshes().data,a=this.renderList?this.renderList.length:i.getActiveMeshes().length;r.currentRenderPassId=this._renderPassIds[t],this.onBeforeRenderObservable.notifyObservers(t),this.getCustomRenderList&&(e=this.getCustomRenderList(t,n,a)),e||(e=n),this._doNotChangeAspectRatio||i.updateTransformMatrix(!0);for(let t=0;t<e.length&&h;++t){const i=e[t];if(i.isEnabled()&&!i.isBlocked&&i.isVisible&&i.subMeshes)if(this.customIsReadyFunction){if(!this.customIsReadyFunction(i,this.refreshRate,s)){h=!1;continue}}else if(!i.isReady(!0)){h=!1;continue}}this.onAfterRenderObservable.notifyObservers(t),(this.is2DArray||this.is3D||this.isCube)&&(i.incrementRenderId(),i.resetCachedMaterial())}}else if(!this.is2DArray&&!this.is3D||this.isMulti)if(this.isCube&&!this.isMulti)for(let s=0;s<6;s++)this._renderToTarget(s,e,t,void 0,a),i.incrementRenderId(),i.resetCachedMaterial();else this._renderToTarget(0,e,t,void 0,a);else for(let s=0;s<this.getRenderLayers();s++)this._renderToTarget(0,e,t,s,a),i.incrementRenderId(),i.resetCachedMaterial();return this.onAfterUnbindObservable.notifyObservers(this),r.currentRenderPassId=n,o&&(i.activeCamera=o,this.activeCamera&&this.activeCamera!==i.activeCamera&&i.setTransformMatrix(i.activeCamera.getViewMatrix(),i.activeCamera.getProjectionMatrix(!0)),r.setViewport(i.activeCamera.viewport)),i.resetCachedMaterial(),h}_bestReflectionRenderTargetDimension(e,t){const s=e*t,i=Ht(s+16384/(128+s));return Math.min(Xt(e),i)}_prepareRenderingManager(e,t,s,i){const r=this.getScene();if(!r)return;this._renderingManager.reset();const n=r.getRenderId();for(let a=0;a<t;a++){const t=e[a];if(t&&!t.isBlocked){if(this.customIsReadyFunction){if(!this.customIsReadyFunction(t,this.refreshRate,!1)){this.resetRefreshCounter();continue}}else if(!t.isReady(0===this.refreshRate)){this.resetRefreshCounter();continue}if(!t._internalAbstractMeshDataInfo._currentLODIsUpToDate&&r.activeCamera&&(t._internalAbstractMeshDataInfo._currentLOD=r.customLODSelector?r.customLODSelector(t,this.activeCamera||r.activeCamera):t.getLOD(this.activeCamera||r.activeCamera),t._internalAbstractMeshDataInfo._currentLODIsUpToDate=!0),!t._internalAbstractMeshDataInfo._currentLOD)continue;let e,a=t._internalAbstractMeshDataInfo._currentLOD;if(a._preActivateForIntermediateRendering(n),e=!(!i||!s)&&!(t.layerMask&s.layerMask),t.isEnabled()&&t.isVisible&&t.subMeshes&&!e){if(a!==t&&a._activate(n,!0),t._activate(n,!0)&&t.subMeshes.length){t.isAnInstance?t._internalAbstractMeshDataInfo._actAsRegularMesh&&(a=t):a._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!1,a._internalAbstractMeshDataInfo._isActiveIntermediate=!0;for(let e=0;e<a.subMeshes.length;e++){const t=a.subMeshes[e];this._renderingManager.dispatch(t,a)}}t._postActivate()}}}for(let e=0;e<r.particleSystems.length;e++){const t=r.particleSystems[e],s=t.emitter;t.isStarted()&&s&&(!s.position||s.isEnabled())&&this._renderingManager.dispatchParticles(t)}}_bindFrameBuffer(e=0,t=0){const s=this.getScene();if(!s)return;const i=s.getEngine();this._renderTarget&&i.bindFramebuffer(this._renderTarget,this.isCube?e:void 0,void 0,void 0,this.ignoreCameraViewport,0,t)}_unbindFrameBuffer(e,t){this._renderTarget&&e.unBindFramebuffer(this._renderTarget,this.isCube,(()=>{this.onAfterRenderObservable.notifyObservers(t)}))}_prepareFrame(e,t,s,i){this._postProcessManager?this._prePassEnabled||this._postProcessManager._prepareFrame(this._texture,this._postProcesses):i&&e.postProcessManager._prepareFrame(this._texture)||this._bindFrameBuffer(t,s)}_renderToTarget(e,t,s,i=0,r=null){const n=this.getScene();if(!n)return;const a=n.getEngine();a._debugPushGroup?.(`render to face #${e} layer #${i}`,1),this._prepareFrame(n,e,i,t),this.is2DArray||this.is3D?(a.currentRenderPassId=this._renderPassIds[i],this.onBeforeRenderObservable.notifyObservers(i)):(a.currentRenderPassId=this._renderPassIds[e],this.onBeforeRenderObservable.notifyObservers(e));if(a.snapshotRendering&&a.snapshotRenderingMode===Ze.SNAPSHOTRENDERING_FAST)this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(a):this.skipInitialClear||a.clear(this.clearColor||n.clearColor,!0,!0,!0);else{let o=null;const h=this.renderList?this.renderList:n.getActiveMeshes().data,l=this.renderList?this.renderList.length:n.getActiveMeshes().length;this.getCustomRenderList&&(o=this.getCustomRenderList(this.is2DArray||this.is3D?i:e,h,l)),o?this._prepareRenderingManager(o,o.length,r,this.forceLayerMaskCheck):(this._defaultRenderListPrepared||(this._prepareRenderingManager(h,l,r,!this.renderList||this.forceLayerMaskCheck),this._defaultRenderListPrepared=!0),o=h);for(const t of n._beforeRenderTargetClearStage)t.action(this,e,i);this.onClearObservable.hasObservers()?this.onClearObservable.notifyObservers(a):this.skipInitialClear||a.clear(this.clearColor||n.clearColor,!0,!0,!0),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0);for(const t of n._beforeRenderTargetDrawStage)t.action(this,e,i);this._renderingManager.render(this.customRenderFunction,o,this.renderParticles,this.renderSprites);for(const t of n._afterRenderTargetDrawStage)t.action(this,e,i);const c=this._texture?.generateMipMaps??!1;this._texture&&(this._texture.generateMipMaps=!1),this._postProcessManager?this._postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e,this._postProcesses,this.ignoreCameraViewport):t&&n.postProcessManager._finalizeFrame(!1,this._renderTarget??void 0,e);for(const t of n._afterRenderTargetPostProcessStage)t.action(this,e,i);this._texture&&(this._texture.generateMipMaps=c),this._doNotChangeAspectRatio||n.updateTransformMatrix(!0),s&&Qr(this.getRenderWidth(),this.getRenderHeight(),a)}this._unbindFrameBuffer(a,e),this._texture&&this.isCube&&5===e&&a.generateMipMapsForCubemap(this._texture,!0),a._debugPopGroup?.(1)}setRenderingOrder(e,t=null,s=null,i=null){this._renderingManager.setRenderingOrder(e,t,s,i)}setRenderingAutoClearDepthStencil(e,t){this._renderingManager.setRenderingAutoClearDepthStencil(e,t),this._renderingManager._useSceneAutoClearSetup=!1}clone(){const e=this.getSize(),t=new $r(this.name,e,this.getScene(),this._renderTargetOptions.generateMipMaps,this._doNotChangeAspectRatio,this._renderTargetOptions.type,this.isCube,this._renderTargetOptions.samplingMode,this._renderTargetOptions.generateDepthBuffer,this._renderTargetOptions.generateStencilBuffer,void 0,this._renderTargetOptions.format,void 0,this._renderTargetOptions.samples);return t.hasAlpha=this.hasAlpha,t.level=this.level,t.coordinatesMode=this.coordinatesMode,this.renderList&&(t.renderList=this.renderList.slice(0)),t}serialize(){if(!this.name)return null;const e=super.serialize();if(e.renderTargetSize=this.getRenderSize(),e.renderList=[],this.renderList)for(let t=0;t<this.renderList.length;t++)e.renderList.push(this.renderList[t].id);return e}disposeFramebufferObjects(){this._renderTarget?.dispose(!0)}releaseInternalTexture(){this._renderTarget?.releaseTextures(),this._texture=null}dispose(){this.onResizeObservable.clear(),this.onClearObservable.clear(),this.onAfterRenderObservable.clear(),this.onAfterUnbindObservable.clear(),this.onBeforeBindObservable.clear(),this.onBeforeRenderObservable.clear(),this._postProcessManager&&(this._postProcessManager.dispose(),this._postProcessManager=null),this._prePassRenderTarget&&this._prePassRenderTarget.dispose(),this._releaseRenderPassId(),this.clearPostProcesses(!0),this._resizeObserver&&(this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver),this._resizeObserver=null),this.renderList=null;const e=this.getScene();if(!e)return;let t=e.customRenderTargets.indexOf(this);t>=0&&e.customRenderTargets.splice(t,1);for(const s of e.cameras)t=s.customRenderTargets.indexOf(this),t>=0&&s.customRenderTargets.splice(t,1);this._renderTarget?.dispose(),this._renderTarget=null,this._texture=null,super.dispose()}_rebuild(){this.refreshRate===$r.REFRESHRATE_RENDER_ONCE&&(this.refreshRate=$r.REFRESHRATE_RENDER_ONCE),this._postProcessManager&&this._postProcessManager._rebuild()}freeRenderingGroups(){this._renderingManager&&this._renderingManager.freeRenderingGroups()}getViewCount(){return 1}}$r.REFRESHRATE_RENDER_ONCE=0,$r.REFRESHRATE_RENDER_ONEVERYFRAME=1,$r.REFRESHRATE_RENDER_ONEVERYTWOFRAMES=2,Dr._CreateRenderTargetTexture=(e,t,s,i,r)=>new $r(e,t,s,i);class Jr extends kr{getClassName(){return"PassPostProcess"}constructor(e,t,s=null,i,r,n,a=Ze.TEXTURETYPE_UNSIGNED_INT,o=!1){super(e,"pass",null,null,t,s,i,r,n,void 0,a,void 0,null,o)}_gatherImports(e,t){e?(this._webGPUReady=!0,t.push(Promise.all([import("./pass.fragment-BNKAdmAy.esm.min.js")]))):t.push(Promise.all([Promise.resolve().then((function(){return Yr}))])),super._gatherImports(e,t)}static _Parse(e,t,s,i){return re.Parse((()=>new Jr(e.name,e.options,t,e.renderTargetSamplingMode,e._engine,e.reusable)),e,s,i)}}I("BABYLON.PassPostProcess",Jr),yt._RescalePostProcessFactory=e=>new Jr("rescale",1,null,Ze.TEXTURE_BILINEAR_SAMPLINGMODE,e,!1,Ze.TEXTURETYPE_UNSIGNED_INT);$e.ShadersStore.lodPixelShader="#extension GL_EXT_shader_texture_lod : enable\nprecision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform sampler2D textureSampler;uniform float lod;uniform vec2 texSize;uniform bool gamma;void main(void)\n{gl_FragColor=textureLod(textureSampler,vUV,lod);if (!gamma) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";let en,tn;function sn(e){en||(en=new Float32Array(1),tn=new Int32Array(en.buffer)),en[0]=e;const t=tn[0];let s=t>>16&32768,i=t>>12&2047;const r=t>>23&255;return r<103?s:r>142?(s|=31744,s|=(255==r?0:1)&&8388607&t,s):r<113?(i|=2048,s|=(i>>114-r)+(i>>113-r&1),s):(s|=r-112<<10|i>>1,s+=1&i,s)}function rn(e){const t=(32768&e)>>15,s=(31744&e)>>10,i=1023&e;return 0===s?(t?-1:1)*Math.pow(2,-14)*(i/Math.pow(2,10)):31==s?i?NaN:1/0*(t?-1:1):(t?-1:1)*Math.pow(2,s-15)*(1+i/Math.pow(2,10))}$e.ShadersStore.lodCubePixelShader="precision highp float;const float GammaEncodePowerApprox=1.0/2.2;varying vec2 vUV;uniform samplerCube textureSampler;uniform float lod;uniform bool gamma;void main(void)\n{vec2 uv=vUV*2.0-1.0;\n#ifdef POSITIVEX\ngl_FragColor=textureCube(textureSampler,vec3(1.001,uv.y,uv.x),lod);\n#endif\n#ifdef NEGATIVEX\ngl_FragColor=textureCube(textureSampler,vec3(-1.001,uv.y,uv.x),lod);\n#endif\n#ifdef POSITIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,1.001,uv.x),lod);\n#endif\n#ifdef NEGATIVEY\ngl_FragColor=textureCube(textureSampler,vec3(uv.y,-1.001,uv.x),lod);\n#endif\n#ifdef POSITIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,1.001),lod);\n#endif\n#ifdef NEGATIVEZ\ngl_FragColor=textureCube(textureSampler,vec3(uv,-1.001),lod);\n#endif\nif (!gamma) {gl_FragColor.rgb=pow(gl_FragColor.rgb,vec3(GammaEncodePowerApprox));}}\n";class nn{static ExpandRGBDTexture(e){const t=e._texture;if(!t||!e.isRGBD)return;const s=t.getEngine(),i=s.getCaps(),r=t.isReady;let n=!1;i.textureHalfFloatRender&&i.textureHalfFloatLinearFiltering?(n=!0,t.type=Ze.TEXTURETYPE_HALF_FLOAT):i.textureFloatRender&&i.textureFloatLinearFiltering&&(n=!0,t.type=Ze.TEXTURETYPE_FLOAT),n&&(t.isReady=!1,t._isRGBD=!1,t.invertY=!1);const a=async()=>{const i=s.isWebGPU,r=i?1:0;t.isReady=!1,this._ShaderImported||(this._ShaderImported=!0,i?await Promise.all([import("./rgbdDecode.fragment-BdggM8VZ.esm.min.js"),import("./rgbdEncode.fragment-LUPpF87m.esm.min.js")]):await Promise.all([import("./rgbdDecode.fragment-CnUoEV03.esm.min.js"),import("./rgbdEncode.fragment-BGkuZmHn.esm.min.js")]));const n=new kr("rgbdDecode","rgbdDecode",null,null,1,null,Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,s,!1,void 0,t.type,void 0,null,!1,void 0,r);n.externalTextureSamplerBinding=!0;const a=s.createRenderTargetTexture(t.width,{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:t.samplingMode,type:t.type,format:Ze.TEXTUREFORMAT_RGBA});n.onEffectCreatedObservable.addOnce((i=>{i.executeWhenCompiled((()=>{n.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},e.getScene().postProcessManager.directRender([n],a,!0),s.restoreDefaultFramebuffer(),s._releaseTexture(t),n&&n.dispose(),a._swapAndDie(t),t.isReady=!0}))}))};n&&(r?a():e.onLoadObservable.addOnce(a))}static EncodeTextureToRGBD(e,t,s=Ze.TEXTURETYPE_UNSIGNED_BYTE){return function(e,t,s,i,r,n,a,o){const h=t.getEngine();return t.isReady=!1,r=r??t.samplingMode,i=i??t.type,n=n??t.format,a=a??t.width,o=o??t.height,-1===i&&(i=Ze.TEXTURETYPE_UNSIGNED_BYTE),new Promise((l=>{const c=new kr("postprocess",e,null,null,1,null,r,h,!1,void 0,i,void 0,null,!1,n);c.externalTextureSamplerBinding=!0;const u=h.createRenderTargetTexture({width:a,height:o},{generateDepthBuffer:!1,generateMipMaps:!1,generateStencilBuffer:!1,samplingMode:r,type:i,format:n});c.onEffectCreatedObservable.addOnce((e=>{e.executeWhenCompiled((()=>{c.onApply=e=>{e._bindTexture("textureSampler",t),e.setFloat2("scale",1,1)},s.postProcessManager.directRender([c],u,!0),h.restoreDefaultFramebuffer(),h._releaseTexture(t),c&&c.dispose(),u._swapAndDie(t),t.type=i,t.format=Ze.TEXTUREFORMAT_RGBA,t.isReady=!0,l(t)}))}))}))}("rgbdEncode",e,t,s,Ze.TEXTURE_NEAREST_SAMPLINGMODE,Ze.TEXTUREFORMAT_RGBA)}}nn._ShaderImported=!1;let an=0;const on=e=>{if(!e.environmentBRDFTexture){const t=e.useDelayedTextureLoading;e.useDelayedTextureLoading=!1;const s=e._blockEntityCollection;e._blockEntityCollection=!1;const i=Dr.CreateFromBase64String("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR42u29yY5tWXIlZnbuiSaTbZFUkZRKrCKhElASQA0EoQABgn6hJvoXzfUP+gP9hWb6Bg00IgRoQJaKqUxmZmTEe8/v0uB2u7Fm2T7HIyIrnz88uPvt3f2a2WrMbOvf/u3PvvzP/sUf/N6//i8vf/lv/3v5H//d//Sb//Uq/5u8yf8hV/m/5Cp/L1f5hVzlG7nKJ7mKyJuIXN/hPwqXI/g++zq6rPI5u8z+WqfLre+zy7PrVv9L8brsMiGvk8XLmM/sdfHXal4e3ad6GXPdyu2ij8u/+uv/5cuf/OSLfdtEfvUr+dnf/d0X//t3H/7bf/hP//N/928h/0Yg/4VA/kogfyGQP5Wr/IFAvhbIlwK5CGQTPP+9z5uPeePJSW+yo2+s/GtN30Rnv1E+f5zxof9R/lSXv/nr//mrr3+i+5dfyX7ZZQP07Tffys//8R/l/9TtX7790T/7r/8G8pdy+/8XAvnnAvkzgfwzgfyxQP5AIL8vkJ8K5KsmMVzu1U7p5PA5AXxOAJ8TwPf7sX/51ZeXfcemqnp9w/W77/S7X/6T/vzf/7383RWCX3/z05/9i3/13/0PX//eX/2FyP8tIv+PiPy9iPy/IvIzEfm5iPxCRH4lIt/c/393//9BRD6KyKf7f488fP74/PH544dJAF9cLl98IZfLBZtuqterXr/7Dt9982v95S9+Lv+gF/3i7Spv/8lf/vnf/vGf/dF/JfKnIvLnIvLvReQ/NEngn0TklyLy6/v/34jIt00iGJOBlxAsdvv54/PH5493SQCXy9t2ueh2ueimKorrFbjq9eNH+fDtb+TXv/ol/vHyhX4Fxfbx7euPf/Lnf/PfiPyeiPyhiPxxkwB+fk8AvxzQgJcIrGTwFsiAEXH4/PH54/PHUgLY7whgu2C7bLqpQgHB2xvePn6SDx8+6G9+84384vKF/IPu8iVU9Y/+7C/+jWxffiHytYj8VER+X0T+oEEBvxqQwCMJeIngo5EI3goIwVMIPn98/vj8ESaAbbtu2ybbvl8u2ybbdtluSECA65u8ffqIDx8+6G++/VZ/efkV/sO261dQXP7wT/7kX8vl8qXIFyLylbySwe/dE0CLAr65B/9vGn0gQwRMMqgmhM/J4fPH548eAezbZd/lsm3YtssNAYiqiogAAkCvb5/k46cP8u2HD/rrb7+R/2/b9Wu9yJe//8d/9Ney6S5yEZFdRL68/38khG/uKOCnAwoYkcCoEXwkEgGDDq7CeQfyOTl8/vhd1QCum26ybZtu2yabbrKpQvXue1yvuF6v+vbpTT5+/CDffviAX1++1V9sO77WXb/66R/+4V/dgkbllQi+aBLBV/dE8LWRALwkYCWCNyMZXElkwLTMeMkga/P4/PH547ccAVwuctkvdxSw6bbdtYDbTfSZBN7e8PHTR/3u4wf55vKd/nL7DX6mu3791U9//5+/gkNFZGuSgZUQvnKowKgLWLTAQgRtEniTuEfwaELw0MJvf3LQzynud+53uG+X6y3gN9kul+2y6XVT1U27JCDAFVc8ksAn/e7jR/nN5YP+avtWfq6Xy9f7Vz/9w1dgRYngiyYhfNkkgzYBWHTg44AEMmqQUYQKOmDaiCIa8TmsfmzB+DnZDQjgcpGLbti2y3bZHjRAdRMVvb/dcYU8kcDbPQlsH/CrbddfbF98+RPZfvLFnAQeieCRDC5DMvju/vmD4JkEvjRQgKULeGggowdHkAHTYxihg89vu88I5UeGAPSOAFTlrgPopiqbKPSmCKreUoAAkCcSePukHz590m8vH+WbD9/JP335k6/+tA86KxFchv8jMvhiogE4JQm8XhfKqOAqx5qRPyeGzx8/cgSwbXcUoLJtim27C4Oi93+4v6VxQwKAvl2v+Hj9pB8+fZJvt4/yzfbF9lPdv/wJnsE2BogmyeCRED40tGFvksIXiSbgiYSRRpDNDZ6BDI6ghM+J4fPHeyKAO+zX7cb9t4tedMMNAQju5V+f1uAtBSiu1zsduMrHy5t8ePsk3376KN98sX/xE5FPAnm7/782o0DiUINXMkCXCB7/P94/e87AWUmARQWVvgMuKej9t1RLBp+Tw+ePgwngsutFFdu26WXbbl+rSvdfbnqAiuA23QcBgCugV1zl7e1NPm5v+LC96XfbJ/1W9y++fgXjA3bDYXV+MuhRwSPwL3JLMFYC+HS/LU8HYrGwIhwyNOF12SvgM4SgztdifP85MXz+KGsA2C6X7aJ6bXSAOwrY5OYIqGy3d5uq4P5GhABXuV6veLvRAf10fZMPb2/y3b7vX7+g+9v98/WOBq7GG7RNAlYy+Dgkhhb+Xxp0sE8IAC4SGAP/TbgVJK/PoJPBnAiwPKxsXfbbnRg+i3s/JAK4Q/4b9NfLtomBAqCickMBjy7BuywAUVyv8na94tMjCVzf9KNcLl/0SeA6oAEYb1i9g+FtSALb/bKL8/+t+wxXFMyswqiHoK4ToIgKqslgpg1qUC0QoYbvJZg/B/q5v4szHmPX7YEAsD0CX25OwEUVm9xag1+agKg+nxQArnKjAtDr9U0+Xd/k4/UqH7bL5YsewrcBBiMJZPRAp6TwQgWfjM9vgRbgUYGL8AvLWH2gqhesCokeUmCSwPsnhs8fP2YNYMO2XeSmAWxy2VQaXeDmDIhApf33rD4PTUCuV+DtCn27XuXT5ir8VmCJ2G5BpBM8/r/dEcJb8/0lEQMtJHA5TAlqNuLRhJChhEpSqFabH3di+G1AGj+W1/dyAR4IYJNNnuLf6+tWC9CHHiAtFhAIFLjK2/Uqn65X+SS67aK+3QeTDoy/IG2ogQ7fb/dAtz5vBgrYGqrwNtCHsVfgIvwK07OTQBURVNCBFpKCOjqCHn5L/67TgTN+fpySAC56nwSUi256kXsSuFGAVyLoUIDo8/Pz7fdoErr/v17lk162HbgHvFpIYDfoAJJfW4sGPjkU4VNAF8ZEcLmLhdc7kljdY1y1Dq9yLiI4IiRqcLujb138KIPn80ejATwRwIbtBvn1cqv+2J78/5EI5N4cJA8qIPcmwRsKAHDF9WYP6mV7VmrgLuTpxYTcMEW0LAmoQxFsuvAI8tv/a/C5fV2ZMMiKg++FCM7RDPRu8ebWY7VG6VJi+Bzk35MI2LsAckMAgwvQ0gC5DQjd3ABg2HQLAPpEAlZ1Bu7VV7MGHDFRAbo3VKsTbAY9sPWC/uvx86gBbDK3D1eEQS8pbAeSgSwmhepnJb6uBv/o/PzHLzxWA/X7TH77De5j6AGQi6o0CUGfCOD2X7cXAlCFQABtEsGLDtxuOyQB2UTQBKZe5GUPXgkUYCUAbZJRhBDeuq8xBf+bgwbehDm+BFQi2IJksOocvA8ysIMfxluVcRsY/eB3JzH8GFDAXQO48X/dcIf9jyDHptIigDsFkEe066tBSETQUYF7ElDdYEBytN4+rk9UcBPfrKaZqFHWcw3i4J8/X4ev2//bSXqAhwTay6OEIPLD2Ipt8OtAGzxkwLw9WVFRjTc/qC6H3+YK/b1oAA0KuOizHfieCLaHHiAb5NYTIC9EMEbZrVEQt1xwhVy1UfBh8PUOquMizwaap3tQXfY5B//tea/NZdfhsvbz+PURQTDSGWB87VX/7WSd4KxjUqrIgE0IUkoKGnhIvwvawpGf6eECXJ7tv4qbA7DJgwpsKthEmmYgfaAAffYF3HLxo0vwNjJ0SwRWMG4db4eh1gPNm18vQ+us/0eGmxDemu/fnM/X4evq/8342ksGHgLY5LyT/zg0wM8lcMjgGFXwqIOVFJBQw99eCvF9oZL9Mfl3QwAvIXDsBRC9R+fz8x0FPBLB0xJEpwUobrfAkARgIAF41h3wQgP6QAmX5E/7eI43IxGwwf/moIkRyWRJQIPgt9CA9b39nzt4bYUWjAlCjWDPgv8IEjgLJfzuaAsrv9VdVG4OwOXW/fdoA35qAdL0BDwvf6AAUVHd8LIEu94A3K+Q+2YxaB84MOH62P//qoo38fCRDERE2zf0JfmDa+MieElAjcDPKz+mRKCOtdgGtXaBjgNJ4H2owSpNeAW/rRH4CaHSpMwnBYYycjgSJwfie9CR6mPu20Uv8kABF206AvXlBMiIBPSlB9wjBW1fwEuSb94296VCqgMaGCt/G1BbExi3IG+r3a3J6P48Gv/J0YmEYoiGY7V/SxwFCwGoE/xa0AJ0CEiV9QPCJb1OJ5F1VTjEY2/MO9AEJvj1BJTQpqLfTlGwjABuzT962e4IoKnyrdh3+/6mzDVJ4PHOxj0JqGKoy20+wBMN6D1gLWi9NQHfVP5MEEPzjGYy8BMAOnTAJgEr8HUIejRo5xrA5xkR5AngmiSHs+zDDAmMgWzTg55GSJEmHE8IvWPAoYTfhWak/Wn/bQ0CGLSAjv83SUEfKp5q24LXuQICpzrjrgWoza8xVE00CQCORdhMJuTUT/rjuls0gO4Iby8BIEgK6gS7BsGuTtDrScH/fR68biUHNVGBnxjeNyHEvQe/ve3LZQqgG3rof6cEclsNflG9J4KtaQ8WHcVBHS1BtHE4QP9OBMS98mpbKTeDW7dJwRsnHpMBTFJpV4I+b0kY/NqInVFSyBLANbnMSgBM8F+Fqfxq/h657/Up+GaBnwV9hRqc9bZ/vA6vu+T9E8KPJWns94UfTeCj2QXwCHS9dNL8Xf3Ho/rfewSeFODGDV69AU0y6NFAE1DP3qK++rdB7/1HRxf86gT376zOr99T/h/ioBiXWQkgQgVeIrCC/WomhDmQK+hASI2ARQZKooHMLdCJwGEBBXC3+uERwg+VOHZ9ioAt9H80AI06wGgJ3nQA3BoCut6AhxYwgcPOFnxuFnrphk+NIKIGrWPQtgz3b0i7Y6D5rs1GKqTop0nQX52vmQC4BkjA+r4a7Kx9WLENGeegkhSETBCrNXIMdi/444Rw1n6E96ry7OPuj8UfLxtQ78NA2iSBbg7gIiIbdDLsb5agPhLC3RkYKv8NDbS2YGsatNRAG2oQwf9ZIOydgy1MAzBkAw8UwEEIDzSAqdPQ6za0PkeJAMH3Z0wXniUSZoHvBXU2mcjQgv56TedIKglCpIoQfgwCIjOytd8WgN0bfxoR8Fn9Gx0Aj5Zgq0lIZbsH/ibSJoFnS+C98g9ooHEELI3gliy25yONIiE6pb0NfBlyNEYyENoodkKwgl6I6s8kARgJ4ZoEfuYWHLEJa0LhSBXm7kImGeSfVdoJ1DO2G7WXsehAptupSOoyrCSF904k+6vt98X/ZcM98Hsd4JYIXhQAIg3/f9AAUYhsLQKAtkHVBnzjCKhOoYl2ym+iBtvzDzQ2DLXJ4PUmbJHAVnBQX4jkxfvHhNDqAdHXGQJgv0aSDGItgOseHIU+K9hXnIJzkoGlEKzNHagTdJ6VWEUH4iCKH4fd2AwDPaYBm4Wgng4gQ9V/CoGiuNmD04AQtNGMGzSAAQ2I2pzfogY9LRh7BrbOh4+D30sAencljFu2CUFrwY8UAWRfWwGvVOVfbx2uIILM0pwDv082dUTw8hYs8L+uIWiHGpWgClnAa1lMPJogovvvbePPs/q3Xr++kgCsfgB5oQF9WYKPJqEn6G+OE3i5AqouF59FQOmahQC8rlPLj38kg1c2f30vw+XaoIX24/pMGIgSBoZqoH3wo0sIIGlA9PWcCPrAtpPB8eBf6x1o6cHra+2+tpIFP4PgBfxZtZUJfo4qxELT948D9ucK8Mt9+ccjIQw6QJcEbrD/1g340ATuDgDkFfx6twSf1f9xvuBECYxq/7ythQQGm+5JDx6Brw4CkMGT3wgscCUoQ4sU2t6DR2ciBjTgtcpenQoZVX9NuL4Owc+dVaDursYVkVALX+shjSBKBuvCYDUZjE5BdNkxdHAUBexyHwB6NP7Iyw7sxUDViwge1t+mz8B/LAvVx/c3PeBBCToB8IUGOgqA3iV4yUg6UAOxaUFHDx6CYS8SorMOue0CCJGAf5YfRhoAI+A1CvwxqNkAY5yAIx2EQmkFfeWOXi+nEdSQQA0ZHMEItiagJArQxDXIrj8nCfQi4HZPAttrIahso9oPQ/2/JwV5JQU8zw+7I4D7/sBn4EO6rjw0FR+i3Z9fHtahzsFvJgM0X+tmVH5vaYiNDGAigewAz+gyNLThnjCURQFR1b9d3lZvnVqmj9mEPDKIUIC4KCCjBXywS4N+otp/Hk3QVthOkwEKlV9PQwXjT7s/zwF4Qf9toAAzFdjuaEB6S7D1//U5FIQu2MevO0rQQH8ZmoXE6B/IkgE60XCjVoq8gt2iCG0S8L5GdxkM1cGsfsCMArSCAnrr7dzAZxCEEpepvB8tqHJ/q+bmJGGts/AcAXFOMMeTwC7Pw0B6CtCtA2vWgonqBQJFSwH0JQK29OB2kvgj2HHXAoyeAIsCQO0kMNECAhFMqCBf8mElAkyBbX1tJQP2RJ/ha0gpAfS9l+/5n00CkrQpq0MZbOdAuxmMvHswog62jZj7BnYQe19b14kxNq2D/ehX/p68HEcF+x3yP7z/V/A/q/5DA3i5A/dzA5pdgbKp3v3/wQF4Bb70WkCTHGRAA6+KL0bFl6FJaFw0ImZwm6igSwbbwPn9RMBWf3sN2JgA/BVh/Rg0kQBgePf6HglAHLFQwqQQOwDjbdVxNZjR4iM6Qa3WxwvNxh0JFb3g/WzFQQS8b/ttKcDWoABtUMAd8j9hf0MB2uDXhzX4CHj03L9DBU3Qjz0C0l4mLSLQPicOOwZoVCB6P6dA7nDbGkVuxcNr8PU2JQO4wX5trEqmccZaHU4q8oCDFOpzAnOwqyMIMktNNNAHouDGxO37DgArQZzlmp/14W1QlqHTMaIIx7SCx0+5yza7AKJ3IXBrNAHVDcMZAU/BT/vgv/ULPOA+XiLggAREDF2g0ci6xNDRglegd7P7TWWH5oJfayliEg7bScQRBVgI4Ookg/F6rvpLWP29swREqA3CaG8/FpKqS8DTAV4TiBqIqtxfzaQRLys5I0XEFIFrPbZRQb+16Fgi2LvJv8EFUPW1gGfQv1T/F/d/HBnccP7rAwnIIyHI4ArgWeGbU4eHy6Tx/EeTZIb5bo/BsMBjmjBE08f/RB0PHYBd9eVRAGY7cHRwiBf8WeCPHY1bgBTa9xKTELzEkQX9CPtl0gJiqsAmCT7I8xbjivh3JGFI+D2nBcSJQJ8agDX+O9iBL7UfG4bzAkcaICrbtYHz1ycSmGmAjJfL3CMgT3tQpmrfB7gxSzC1DnvdhQMieG47u75+kTouKNkM8c/+vq/Q7ZYjO/hhVvRq8F/9gGfhP8aqE9EIdR6LTwJ1h0BItyDqB8iFwuNqASscRnYioxOg9ApvnYA35f8e9Ohbfe8J4rknoFkO0lmA2gmAG0YK0DkB4ieEjiLoMD8wBzom27ANZkzIoU8EMHk/uo1mzeVoEoRWKn8L/62EYAX/lsB7D/LXg74uAMr9oGivJ0CNJCGD6i9DhZdQF+gtOp4S+NODRzsDVbhdgv4BqTMNyIL9SCKwL9/FGPp5oQKxIf8A/UX6r231H7YIqLML0Ae2GtrADOvRQH5b/MPE9dt9BGLNG8jVTAQvIaK5TtvvvWQgDvyXIClUA78S9Nfg7VtIBlO7cbsEYkQDMot+ygQ7QwmOawTHnAM2XUSnJvPIYRYMmYPS+sv3J+cfP3d04JYIXsF/EwMbBKB9Q9AY+BiSwFj9mzrSXmcJhFPVHySTbgHJCPvRQ/z7G/SVUETsg0ZF+i3CRoCjhf7y1A9mOiDD7TwdwEoEXjLwAv+avLE2B7Jnb+OqDpBoAchoQJskxKnss0vu7Q2YhcDv4ySeLOg9GsCKiUIihP7yfW7zbTsBh0TQfN0iAWn9f72Z56/Ax9P7j5OAH/Qvv3/QxKfk0DgDuP+R3USg3bzBC7bO/QT9Eeh9QvDPG7glBQzJwK740lAFFgFk8P88CqDGAa223YckWYhr+c0BPdwetl2ocnsfzePAWcVnnAIp6gDVhDLyfV4nqFEDPxHsbWD3k4BDkN+pARqKMLYBPzYEvxp9xmCHQQdgWH/9EtH2TIFpu3AH/cdGydv1j0TQbRrq+D/mLcX3ZACZ15bF378CG0My6Kq/zoGOQwhASDFwFbxyNGBuSxbCEhQ/uEPe/6gAERWQObCVVfjPpQX+rexxYhYFxIkgpgX7Y/vPs+Pvxf9vwt8kAs7i32t3QCP+3SPaTwIytQXP38u0PESm+YER+o9B3vr8mETAUfDrEkPI80ck0FZ0dXh9U+HRbhey0cAc2H7A4y4egoD6y8JfkBiigLdFP8v2W00E8deT2IeAKujZ/QAVKpAtKI20gLWksHedfgPcb+0+NEHefd9vB9rayi8h7J91gBbaw20MsnWAF5xHkyDUCOoXp+yrOwwxcKj0aL6fFppaaKDv6OpHR5sgx5BAlK/+fYhuP1D196o8e7lFBaKqv5YIMnFQpd0FGVR35RJCnCDaABaXBtgbiSwtICMtalKC+1JQ6bx/PLcDPQL91QFodQNKpwOgF/9eqcBxBBqRcKAAVk+ArQOMx1RYGgB6naDhlK+uQQwJYx4meQbxtNnYQwMjt/d4f3M9ZE4UOld1LAh99fbfzOxiEkKFCkTJIUIMUeVnJ/9sDt8/e1NEJOi9oVHDGYhgnSLss9DX2IAqw1zALUncKcDr0FB5NP+0cBQNrEezDiyiADPkt9qGpwoPdL0AGPx/NOKeyf3b9WJNdfcFv6bKd2cLMJVfJ6Y3B6wB9WFUfWWEwKMfGiQL+3bz9XGQz2EHKhF41GCtZyDi/gUCsNhYoAr3UNJ58YidHKqnMb/6AB5J4N73/4L+t7mAkeeP3P+1LNSB/l0SkMEd8DcEuUlguEw6t2AU/PCE/q++Akw6QFf1u6SBrj1ZnnhG50AfkoGIdf7gJv1KcSfgzWWkQ9U33Z3tHXYASKJ9e/YhU90rvD+q9Ej69/wxYJVs506Eg/r3DkMDzEdDBRGgcZay49XihLA30P+l8N+hf1f57/0AoxbQbwYaan/rBMirE9Dk+sBzTkC8JNDEUlv5McB8PP19Y01Gayep+hC/2zvQ/2HGLAurowsNGlA1cnqGGzeH5weiYLZm7h3QQC4O2tXdhvMMk1ZS5ebpgI8eMrPvPGkwaxayk8Yc6PMOBPEdC1XZ+2UfbfOPtxLMQQAG9BcZFoF0gp/RKjxe7+oAw9T7ZPWhgedodgz0gf5KBtrtIZhQAZpAV1Bi36w6t98qVfH7hqGI318lLCjLCUFlxRHwqYEH9a2qb4XjWvDT7kBwfbZA5P0+PNuRuW1yf4yNQH3zzwv6b70QOJ0G9OT/dhoYRUGT15uQH/71MjQLtQlxfDuiCXrtM+SkA+icQdH6sU/xz7Ze7FlubV4TpoTQ2osdpaEjtqADmEU7OkBEFoLeC3IWFFeswJXKXzkboNL+wzcFHU8hTGKIboO7CLi1/P+5F+gydQhuvRbwEgxvtACmANikhLTbj0gCYk8KdlYgmj+4Ymaod7TwahwadICuX0Cm2fE5iNHPK0x/CDV66Kyg1MnqjNFBnhBoLQCgUULfaVe5nq/6EQWY67bXCszUb+7232fVPz51iGB12owK9peyP1T4raMFF/OEYJP792mgXYfZ04GHMAhBkCSmSj+dKqRPgVFGHbpLEGMiGFeQWfSgrY52VxaeDUPSNJI0P7NoisG729HHl78z6hxfs9rV3m4JjgM/lsui2qmThjCfDFSb+I9vwUqG5wwL55U7C+6ot8B+7N2o6r3q37T9trfpjgmTvv7PSQATLLeRAOZhIJHBQfDQQJPBdUwEbVW3+L08EcEE/9G4ANrCeWcnPKRHDupbNynMx5AA9IRYLmrc/YLSiD5EaEBS/s/TgnU9ILcH19n+CpHwegLejx7Mn/d25fdN+e9U/1vgb7bqf08MOtf8EXxaoh+GY8L6gDfhvs4i6HQ7seYI2sv1GchdMsBIG3xlvxcCRzdgCPTn+6q/TW00VE8Q9FaFv+R2VlOM1vm/hhjhDCdgNflVKME5B47I9xT8z0YgPAJ8myb/LqHy36j/Mwqw9AALxuO1JVjiuQAYLcFzIhiEPe05fk8tRjGw7yWQbsfuLAT2VqOId1osnr0F49VM8INACPHDoBz4B5mqqSnUgyh3ArjXxfQH5BbgUS8gP7aU+w0zHD9GGD0CGHf+P1p/DeivlhU4BbxR9a2kYFR58YaDZCUR2P0DMmgED2eg77puegy6PgDphEB0CwlG/i9d+/Hs34pBEQrBn0W51mqGnJAk3ACCHeiqkQ1XFQA5AlKH7Lk8yJKWY3/nym14h2C3JvxeMwD9ZVMz0BPMi1n1RbKl1cYhIVblF3G0ATsRiCMUvoK9//OgcwYMoe+ZKOLlC6/Xk50br9NFz9fanqA8UIYSpCwlBO4kHc4WLLBfBHVaKwKgLQjmP4Un61Vq+3s7Bsyi0WztmLjJwJwFeE0I2vD/1Q6MVwefxfUf32skCPbCnxQqf+QMPEUDHZ7vGeyj020JgkPXXwsldA7SYR1RE3h94NvNtugswcgxXEkIcBPCGZ1rmrgDC0A4K88nm2fn/eTnpQtWyZfybRoK8Dro4zYDIMGsf7saTBzvX0SMbkAD6o9CYbsfMK38cJKD9l2FJt9/VGs0h5Gib33pxMKWNsigFUh3G2un+/N1WUglI/EEx8fq27vUNnwsiOoKecL7kQS8VnWAGCFUgn6dBtQhv40CmIYggwK0uwDHRGAuBXVdfwzHUjZzATLMAoyJ4FmBhzaWBlrHld9CCWpPHRqofBqMReMGTJ78q9rDes1Tv7/0m0v0AFHXNR6P6g30SHivin7V1BOhh3iWPwvps/yE836L2XiwnUT8x2iHgfqhnwn667QHEE8oLQjEvtEW7GYBZDrDVkwNIO4G5GiBDf9fGoFM6n+vbEtzXwP6u9AduaWnGYSLAlVdl/AU+ikrSeEIKgwdaZ4AACAASURBVKj4/wtgHcHtdO2nWKcBkPfxcvnNQvsj2Me9f02r76T8q0IBn9OLKfz1HX8yVXQYGoAB/2UeBQ5/5kCL6+H/OGGoRnLSwdd3oH8r7KkGTbgIxEwVWvnF8KOpHnyzfF9Jod5Px+IF1h8owyitDw/XEgRb5bPqbt1uvn7qBIQ16vtS/u+DP3cR7CH0WWJgd5mTJKYgNzoGjQrfvu99NDBC+bnyW1x/qhTatv2OaMKgJWPvv5kwnMgxHYGFRtJW8VMl3uP+MgoqSZyWFKr7+KIDw1d6+IiOgZI4+d5iYL3imzbgyO+tph9t2oSBxOM3ugHtPoFZ1LM0hF4kXNEBssvVgPdjdXZWK7uKvyS3q1Xb1WQwtVDqSUggq+Vw3t56JA2cz7PXOwGNW1ecwxPhfe3QEUsDsFaAz8jg0nf+iZMAHNg/XSazDuC18Iq1HBRrOsAQ8NLB+16g614jmuSgs3bROxE55D+WDDQNA4ivdMJ9M1b309UqknaDU8ObV9/PwmMPATvTMAxpABLBzugUtV9bLdhNDQA+7B9tQJ06/7QNDHGSwtgZOCIA47InIoDdROQGtt0U1HI3GaoUnCnC/rzBMQJteN17+VaAzYNA7e+PFqHQUyXPUYB7iQYa5ZFjq1Zqpx8Uqu/XT7+6BWC1Xaj0GlBIwMoHu7UzcI/6/Acb8KIq+hzmGWmAYnADrIpvKP7TZeLaf0LAeQkGgebbq9FToI44p654F47tekKkI0L5PQNZPsDwPBpy/ni+wKMN76Vav4+2cFZFf8+JwAraMt0DFB7beA/u4Zz/a+RXx0M/ct4/jwaNAS8G17eSwmta0Fhx0VRxJkHMivso+onMXr+YwdWKbgioy1jp4x4AzIKg5lEA7wvHEYCRmdx11TAuT6lDLVl4KvXkAET9P4RT8H2u+lg9EPQIpw+/NpJ7RwE8HaDv/Mu4f3OdNkq/EfAiEiOANjEALvcWL9gfFV4NZbgbQc6qPky4Pm35QZxtH1f4j+P/jXuaYPcWwIEH/fmEPBoAO4m4LGxV3txOQqDU+dXgey+UwSzuqP++uImO/u/6ogCb7wTc1n61sL+vZi87rxnrNas+giTg6QLzaUCjIp6JfhwtGI7AjBBB9JjDY4ePYVR6ZPgN4owVv6Q2N5hhVHwNeYrM+w6dN6K1sMHZm/Ce7bHe3dzKr1xw1w4JrSQMZtgnoQHlr18fzunAszD4qurNUg/TDqzx/lfCaO6t4tACMUQ6P6htWjDPC1hCoZ8kpODzJ70MUR9AODcgwyqyPhmE+wfHYB/hvSqt6qeXUShhXH+d9SR8DzrDaZZdpSp/HxqLMQuATgDU/qDPRgOIeT8cvz/h/XC6BtE7ACLOWPE0KIS4UUjmZaJ2grBphiWgT41BUVWZfP3AnEIT6OrfoF122l2rMycBoU5i/OXoUZ4/aglsXwLzHNU++FVF3qikOj5HXm2PBitT1WuvJRAB+6O//W0/PY8vQH5IrAsMs/WuVmAdHBrQgrbOxJShXwRSsu08h8JMBpo0+aDTALwV4tbswgzHrftG/dJKIAQb5h9KCssWIMeto+GYqG12/HWGjx8kzqNJaa0noMWOr2KwW01AMwJoNvhMQda2/RKQP/3ecABM3g9uD6BY68Ntz9+nDOMb5iV+hIE+dP/Zs/wwJhJ9mgBnohBuStABUXjugF3hkXF9ZZJAjefKdHZCc389LoStKvIl7QIEb1d9RyciQgFDI9Cjyccc/23Aam7/PZJBhgDgin5CtQvbCzX8ip9YgIFtOAt+w0owp/hOiCWgEGbVHuYjRigPGR/YOnEoqPDoV5z5YqB3mRq2ox5ICmSSgAP1Ne+XV2NE+/vuFbCTRADxtS70VRBCjgBk2OyDUQiUgfl77b7DwaHm2rAZ7osRSOOUoHgKfNBSLI767+oDYrfwZvqChSpGfj3pFwZFsCJg2jeIQQBUiyI4WgD68ww4qO8khuWkkIuDrxWv2nv+UTBpJYiPd0KemTA8qqFiuUF1jWS3BoG6pADJq751JqBI0wvAVPyMQvjcX1zbELltKK+zBiXRFiRxG+b7q3M9xuLdzR8g0gCGNzSM5gNYfqGO9CBT8OHct6oB3KsSDBisUnwsFuISQaRHxDSv0vptt2oeLHMERfRn/FG/Cx01EpgIQG8LP+/i37PKw53xn6sYCM4/JwSRrCnIeB1ZkLsawDhaPKv/njU3wnZ/dBdGE8+YTHSG8+ofGgIjsC19YnwdM/KAnTSsqj6ig7uGgIPw3nYFzhhIIvriAxFP9CQd4HSlnzgxONIdrE7A8ZDPx9fjib8ifgegNIliRgdx95+E1T7+3nQVNNhEzDgGA3T2rEDLduwtPpuuouPcs8swwXFjdTaMKt+jA5gUAQPcf95KJQxYU0cYxEDvsBSmYuukp7AwnqniC9Afa5z8vboI68ImT0t26CvwBzSggkj447r9IojvCn7U92J/Hw0QSdwZKNNjxPCfSxRqnATkdwpOwh88oc4J8KTSm/wdbZjrc+4iFP8YO0/5JJDCfaijK5xVXevqfg6zGRrQf83chvX4aRfAE//6vv5+6490U4ADdO7QgM/5bcHP/n4OtCQhBEFeDWSvos8DPq8/IwzLzjpa8/U6MMSkBklDm8e0mn3QIY7XG1Om8wzN48y7HwhOK3P0/ZwUQHHv4psbdoVeb9VlAjChBCdtDDpOKTh9ZfcagOYq31RFjN4/gwBYzp8lAwYNwBELhZoxECeZxMlAzWGdCRV0fQWGHo8+8Kx+AAxnCIzowAxy9KvNepWfsfp4RR9kUrD88CPVTuXRybhqqTHcnxEGndsgub1Gdug8yz9fHt3Hpl57x/mfCOC29FOSQ7/noAZR5W3Ob24UMpuPYAYiQrQgk1gnFoUIKr4vKFpV15pHUJO3Y5rfH3UFHU4bGkU+NKJ9f2hJyOMxDBDpjAgwiYqvk5TqNl9EH2Arb6fA3yaA4cBtPWewhkEcIQJBlGzYp6zRmr1v+e3Fv27xpzvyI44NGDkCIi7CGNV9Dw0M8NtHC2vUwHINumCGNG8erxOwtQINsW88Tlwdoc+F85nI559ngEDpt2F/Uu3hiXYrkN/pBFS26hYDAkFgErMK67y9mGBA3L5ore5izf8b3n805MOq/t7XU4WHv1DUF/5gugCSOAIW/59uMwl6CHWAib8bvfxWl9/rBGEMTTwDfG+ezEYG4yk6FvRPuPwE+wvc39IRjENWM+/cm5b0W4Pf4WuKUnw/vD6eDbB1ETs5vl77Dhnm/51g6wPWwQAqxnivgQaeS3gy/u/1H4hpTPrIgHAN0mSgXUX13YP5PMIuQAfBr/f70cdeE+QoCX3i8nFMLcAjInBoAIYqt1LhC1WdtvmSab28AYffaeivCB+ohdYQgfUa/WS4ToMsNLHLc9nnvPZLwn1/EefPVf+U/xvnCVSEQEkEQEnEQJO7S7RvYDxNeNYKrG7DKMhtsQ8cMmhgPKKKj+F7CiHYFR5KIIPxOmg5IVAtu3ACQSPh7CzUQOgAej5CWEkIe3vgxz0ROGO//qYfz/dnLT+ZxDr4QW0eNCJBorCFOVC312Ec2TiY5Bk0cAaQmiA1VH1MOwDHQ0kHdEDDf+2UTWhS4Z8diQMicLx8MLBfverLcP/jQzF0P8EJj5+NGK9RCz755S6F/f1+X/gxeP+Wsedv+vF8/54aSPJYFjIQd624MDz/UDLQnr8HU3ztKHRf8Qeno1vyAQJBaLcMtTV3cvgP56COCqd/QP9xLgBkH4BxO13n4hNUDtACC6G1S3zqooZ6Ba4lp/zcAFb7iERKQwQcF39IFJjdXECGADw0IE4gg674pYAnk4HoHPx54tD5daO5vxrugSkMjgiiqc7TVKAT6AT8R4ckbHEQCYR/IZBxJgA+XZjsR7vaoRpIxWqeqfXuGC2CxwudicwePEB1kNkaZCuwyF0DuKv/4sz9mzP/Qxdg3BDkBTMC8Q+loD6UGBzx0Kz6eAX/KArOQTlPHFoI4vVtf4rNuLrca9edRn4xBP7k8w+9AgZCgBfEUZWfEs8iFNZ3UO7TqmkjCO/rWdgco/yIqHcQWaC2EGTzgz5y/iXQAvyx3riyxxV/JeBriaGB9OrTA5g9/eokM+37GszqfA/UZk9iW5UnCtBqBl3XoNN6Ag/+zy6A5evPAp+TIFDn15gQw9rjrOzFX0s2JBVAxa/nP1a6AsNWYGjPNGPLTQgBsNUFvOA3Ht9o/rGDN0tWOCcxJGp+f7++kkP7PxcGv1+GjkaLt/fawpwwerQxBJNW4b+PJsYEgiAYYdEAGIlDNaAbRkIgK3ut0jKByp+8yz23X6GttmBmjwDvChgiYLP5V/zhH6/110sGcKo5CkggCngxnIPoPja0j2B+1BRkiYJiviaLJqghDI63G2nAgAxMCuDdnoD0wIQm+urMB3VuAwbBrFGgGgnhAFqg9+ujKsLxB3qGCQNEEtPinIQlAj4WgIw7/iXc9V/x/yUWFs2KH504bAh4aYWf4TrTLGTy9YbftyLeVOWNfYNyt/ji29mQnqMAltU3ioTtbX343yv/1u0YPUBz6zB702tQucnX0gWaFh6DgPdmhXaapGotw0SFz1qDiTMdd8h45HfcqCPRUhA3+NmKz1l9teCPaMd4urGaewRitNBDdahR5c3AfQmDCFT9vmtQEwqAYXX4XI2n23Z9B/Yb1FL+LWox6wHGbZSo6FR1LzyG+3hriSZvWT6jfXhl2cmQZJDrAbuYAqAHo1GA/EOgD8eGcU7A8eDvH4fQBuAhBL/Zp/vamPTrRENDGLTV/7E1WEPLDlP/PwzU4YhusIMUgfIPAr6Dhv5R4y2r8ldFwiFoYHnmr8TAHbhRQSZOctH598ZYhqt6wP7q/ouqe77RJxvzFYaji/z4vna4v5cUMDXqDAJ5ytktqtBDckyjvJg04hl16LB0xFfyMfD77PZjErGQRRjYIfSvoAXntks0ok8MsUC4KARWnYPlJBeIgLeFrUgDOHYCag0/XNAbWgRwQuLAsaQwIhC1g7+jCNKuT38JfnYSyTi+QQEwwHeT4/dWHYxJPxfOj5oAnRQqgU3YgGZSOaDyK3n/qkDYBKptzR3oD6B4fyRKjp2AzSl80YR/3P+/1vBjX18Jbu+YsrMRgbqPP8zrDLTAaupphfeZtyPs9BPztpLSBZjowF3woYRwBwOWaqbev15b7X4RWsiqYiY6ZkFEIoUwUA2OrkeEQE8HYNyD/rl3m88jCGgO/nPW3xy8x4Q/HBcM1dYg5q8N+B/SBSYhtD0EY1PRGLDoKIBHF3yLz4H/gSYQJRETgqeB2d4vC8L2NVnQn4PoVJJAcP0inahAfdXVI8CFszjRagCTtRdV7Sr895NBpRKXIT64RMFw/iw5eChhEvmmyUIH+k+Qu3cLzOAN6ILlFvgWnx3YWFDz0f38ze9GlfP6UQ3ojEY0gtqRIEbA5/WgQFhsEuIeL75uTzvqHktAWfj/OD6sQXssROcGiRgFn0QVkld7OznMDT7CJKzhMIqxW9B+LCOQdH4uyxIcE49VTSeLj0wKjzcp2oDXQA8YoDEGBLMW0BJw+eAxXejPV/IXd59/tp5rVyYXDw5BlRetSpQAcvgfOwVM8ObzBq/AQ2wX4lwkQV3vNhYFfn2LFgaoDU1ogqsfqGkJYmrj9Tr22KQwBLzbLuzDeA9yzyJjVRfwegWq0H+FThDPA6ZhZwX2M2Kh4waovCzAWJTzD/qY00c+6PM8coz08VNqglzx54LfHuTJK7z2rwX35ABLg1DzsZ7Qv7l/f2yXDlbf4C/irg0MJ0aCuD0wP74MrxfdFlX7tq+vtRdCpvt599EG9Yz3V+P+Oj/n4zLruZHcJ7oMt/MNp9eD6HEeFb6/TMfbWo85Pb79HJo8t3371/PuIAZqMvjPC34nVV6ZB4hEuA7AzA5cfU0y2n6ux89D/35/n2/vWY5Bf0qwf3tPLISO1Tap9qzFB6eap/beqI94NCCbGwgqOItY3CGl446CaQ8i2Q9g0AvmgJOnBoAA0gu17tsKtKS7D4udgCYERy2QIceCX/P7mBW+g/7D9S6Mn50CS0eAoQPDcBjopIA5+EcxEjLweRjXq0UbLIjcBxsGx2IZvlf0ATjz/6qypAmY7bhrk4ahsIis6ccXKHdueAfUgk+RWPCLh42c6zEeKyJpRTdRAOqBbl/Wq/uT+q+Fx3FoTIuCzc6+hN8j4veGjuAnhSE5gKnco3A3XwYlq2sq+lmP4yEOpqEoG0M+mGDYuYT0pKCFHgLHKt3T7T9p8GcWH+n1UwGa8X6kQt2x4CeqPexegT6o/Z4Cr313PHdgrsS2ZReLfpKIf+IMFnmVmwxQ9AhithYT73+p2s+JIVfrjwiHnpAZrSsr9CMstQXP1+1+510N/q8E/YoekMN9OMFvi5LvkRDsy9rgFCOoPdpgaQIWBZjf5KCSQszZJ1ivTvLokpen6tsJAVND0NFqb6GUGg2Im4Dyx9Pn7/0dm4pADAslJzTv+dKNrAPQ0wyySm7bj1RQgbAXsRa4R+mBJzpaQmHLmy0BLoL+Nh2ZRca8uUc6P37k97n451fvTieAE8BdZ2ItqFEK6oOJIYPsiU4woo140Oh+H/UC++gatHYcOFT+2y3AYvD1rM/fpxdUcsAi70c0OxAEP45X/hymE9XeoC0zfYhbcqfbhs09HpwnKMDR6g0mmYyKth/UcLl9ITGQ8N1S6s+gA1HvQCc2pluPvN2Br8SyZyfyxPP/VhCi1L1HWX2CQCuAE8TIq/sBYdANZmTIwqq0sb0HIzhhugBeUpBZLFyA8y+EErsBUYDZHYN9QAAooQwOws+uQlhdESSSqk5Qsh8LSYI6LDS1AbmOvLlRBqQIeITvM36+TP63VfE5hFClCTr9zEyVFwS3STQBy66DMHB+PJWIrfgGnYBx2dTboPa2X49GaBVlePA7CFx4iaGi4ns0aLVjMGvtPTDtmO4XEE8E5Kb/8qYai+NHl60LgAICcUCoJPVeiYG6Pxw/X9VFNVbFn9FNPzXoIRDTyzcpREYB5Fm1EQQn3KRi9wKApR8Tz48SwxnV3qM0q7ZhpdKvr0zfY+gO4oQf+EGPFYW/Xf5hwWsUgxiBbShGoGIx+D2eH1h2EeR3UQMH4zMaUKr4033nzkSkfQADelFbLOQCalxdxvN8mInhPas9bxtGJw29Fx3Y8429MAS0fL33Oeo7qFZeiToCC3B/VSNYuU0fgDnkhxGgMFdxiYEY7MYel+OHPH30IMeVFK1C79l+QdXVpFqHlMAXEf3EYDyfkkGdNvJ8f3RAXU0jpgM7jMNA5yCrtfzOicKG/M9bgEkEjqqPPDEcDfqVwGZv6zcO9avDfOhf4OmLFd9OLBHHdxp51HvOBlnAoQksYjASA1xnIhPsapTCPjbsGB2YevpPpgM73EYeSYIftgPgte6CWesVBB9QEgfnWYMgoeC8ql69bWoRIqYHvSIv/u26bj/jdqZ9KSGk74JRo6QS9PuTiSHm6Z62kLUGH0UO4rwWrhtRETkR4iKRdI8giJ2D2nUCMjsA0TXiVDb98NAf/rCMlajA9wesWHZrAe1dlwRyVI2jx4KkyUHSx7YDe6YD4tOC6XW01puEdAJwaEJzf1uATHi6ZlSCpBQscsh6C1xRcWEG4bCFeKcAVhVlDu54JQIkTT21hptIT/Afk0kMcS9BKfjBJozcDXCrtgbWXxbMAw3INQIxtQJPAGwXmYaBbYh4SCsuKwLOAQ5awKskCMmRg8P3xwlBfbosQaDqyZqBkyQe1CLQACoTgN4qbyHsPwkTiF2pYaj6MAXBmUosQHnUEYCsBL3MW39SNKMJ5PfoBsT33DVJCEbFnBCMOkHfvj6Xq8uw+dgRIhGgAiUqf5QgKDFyhe8nnYrlqn9sG1GoAfirubygX4H+8IM1CmQrMFAJ5ExzKIp54nPoVU2Auh6eBShDlTV4u5c4HE/fVvjFrsII0Ik6QX+Iq68jB19ziLoKC27FYe0gC+j1RSS+BgB7AvAM3m8HLdy5fV60C8RMVuhD1ieQB32MCCq0QPJuvuw5IHF/geMKwOPdpmsxBwVEfGEOgeincJqNmuSFIPhPq/xM81CWIIi+gCFBqDX3QPYd2OcCRo6GZBoA3AM+00aesAOQ7/2Pe/vBCXoguD4OBD1WfPwClzcui12AuH+gC0gEwW72KfjBCQRBr05D0IQc7N8PzOCMehPWK384MPVDJQim7yDdoiRTItzzFV/ZOX9sYFetP0fsQzb6O7wOoFjxk89YoQXv+BmSN+yYHYO+BsDRAXHhuJXsEFbdIEGZQWUkNVNzGA9NZUVBIQL7jASR0AclE4Pb7JN3BO72mG92+o8UG3nybj+mASh0FsLKn9GPxDrEcS2Au35BzHO1BksriIJdpqWjKR1wlpR4fN977rZqI+XbYjYDgVDpcYQalOYKMiuQbB3G6Pu/HlMbi9a0EMkksXtjvvXTfgMKAEZRN/i/O7yD8Da2S2Bdh3ICWfp8yuMkYl5a4df4vVWt4UF0yyqEnaT6swYyWB8/j111Y1ERS9oB0SLMtBGDEBD1PEHwtdjUEAHnqmoHU4wCDAoAS+lHwtu9eQLUAgmxVvAuMB9cELMV3m8EUtcBYYI9nkNIEEJYrQeUHfnzzRyC39j8CgSkir/E0P2odnAmAqDnDIhqrtV9BDNS2POjv/0pwKr6z1h/PMz3uf9ykFYq9TtoAXSwpz0HljdvBCVAPY6t7osv6gFhMpkX13rcfXQMIpuTsfTibkfOPRAC2meLRipI4mDPwMD5x+v3+Ey+qEfACwoUEkKQSMZxYJDz9R68PyP43yvo2aYf881rNQbZgRU/jp80QnW/hdXqJxMvCFxXQSNHpE8QiF4XI+wFfQcw7VL2Md7RRajsKgh2D+6SLAKPF356+/7yXYBTUgFy/38StUjFHweD+iiHh8/LV/i/TSvGk4L5x7F6AsIKbgb4C0YjgdGRIToGUx7cgS3JKP8pRcgak95BJGQbjaJdBYQ1qHYnYHL8F45QgHx2gLMQ2cDxBD/4SeR0LSDi5XzPQNjM4ySE/HGG6g+ugltLNSARn281BPtNO72eJLjdX4ITSEgpQvJYFEUg24f1qAYQNQdxx6Q/RcB85j9f+03zf2QV33IDPHegNgPABTfqFR8cZK9TA7/ll0EQbUUHW8Gr1d+MSadia+LRHwhunv87yWoJ3h/pRDwJAbDNQQFd2P2mH4kP/wDT/ZeN3CK3+ZjvgVpw4r20AMafb58j4N1UMknuj6iCx883PU9g2VHVH5JX2eEcPghSgRBCKPzK0Q3fknwPN0Hk0CyC0zBkz//7duEetgFjVtypASDI4CsknYJgYDhqsBxxy29+eyxrAZX75EEf8f+CkOcijMDDHx4ASYGGu8WHgPwpHJc0qOG8FgFTuVk0cRZVePFwHEIUEu8xSHoL5qWg4I7/HgOKXe2dcnu2SSdCGIDTA+AcxY1zYL6Q6AAFu+/1GvjKPSeEoJV3NiM4Dz9C6oWkEav+NWjPWXNOIkKgNTi2I8LeBgaZHJxqrC4oNXoB9pzzMws/OW3ghSyQJgjbygOVEDhoj4nHLld8HPD6UUMFVLIgKrTL7cFoBRLQgEdXIseZ2/HhFPKbk4d5tYWwwR0nIFQSD2P5gQhs6meVfB+Bkyz2fOIvX/zxqsSODuAGIOLtPNnmIPCrv6Kqvgz3q4tCwNl9lWYfnsdHj2HTgQw5IBHwULmfSu1jEV3gDFSxTBmqSEVqiYK2IkWcRiAkwV/cyW9YhqHXDw9dkNQAcO6HFNJT7oChfrPUYc3KY17zAd+evAwF2w5SCKLV4EuCEKsKfjBVWHu9Q9Arh4CoBqEMWYBsNX7YgKP/69uC3M7/mOOz232QT+ox4iCyJGEFP4oBHd+GVvXBwX35nqp7qeIbV6L6tdZub3ueJ+gBIKgC6S5gOQFxDoGr+Bv2nzqbknd7ph/EmXzO0o+kZdc/wqvQkAOUffVMzKtYgx5Vob1/+HAfCdzHSiXHenX35/2JTr3KZ9Ruj2lYiMhLIFoNyMq9hFroeYMTE0bSLbhb4l3YlFPa6hMd2jk8dmrDgdQCnC4/+ANFlYTB6ATlx2GDGXP1rvL+SnWHw+cJes5/rRWt4H2pw9GklD4uSMpwasIQiaYR92gIyFX5S8dtRZt/nCAH48VXW3hRE/HKOsGquj8EM85Q9cfeAV4XwNGAlmIFIwPYrfLKuxV476RRetzcdeAsRSZhiHizCKEIOHn3EMOWy5X4uIJnXX6sFiBFLaBm/THOQAkVJK9j6TKwiSDTBWpwHkSPQJX7U959uAkoaTUuug6oQCBz1Zlxm0OJSIoIw04M+7zCGuYiznCfHww9AN6Ir+HXA7lfn2oBSJ2FOOh8SzINfmcAyITq8JX/sOMPx6A9LeYtVfwgCBZhdu25OB9/XmWWNPUEPD5dUuJ68wd1AqD2+w1PI9KxE9BW5t3z/igdYGWiL7L+wPv9jgVY8f0ZcbCKCuLAHN+c5wa69Zpr0J9t2KnpAGzyiAIPiFalJ8/xXrrA6Y+/8NoDnWCPNwFJzf5DpVkHte8hx76P+HU1+HEytEeSEIzAsu5r6wPJGu6oLz8VrKofXLce+ywIHhNa/Dmw8LrptWXZ4NKZm4pr/QQ7Qk8ehMrPtAF7PQCD309QgRgRZMKgAbFREAfBBXNalbHA9cEHMo4IgIUuPjjBWEUFEQpYTkhVO43eRiynJw9Jjj8TOUIlJExK+0wA4gWgQvcFBHAc7P4/u78/Ff4CC5ATB3P3oUwFClYgcALcxzp/B9Ez4DUV8RjBbsCBrMH4dLNwIDaCGhA6o3pXksdBvYBsktrXDgNJKAFy1Z+ZGIy5NXgXoBT8a3ZgVSPIUAMV6DjLxhsV8wX4n4ibbONObHNyCr8Z4FinNFjg8ziiF5zSV8A99u7Zdf5OisvVaAAAG3VJREFU/kIPAJLWX3hUIFD6o7MD4WkHIMXBk4IftSrPNBJVk0OoC7ice8HGS8XBKDoz/YFBLaQi392lGpCMJfhD9xVkx5Xbj73P9V4m1j0v73x9FjDDPlYvATkgFAVWcdNvJBamliOjAwRV0EpeRymAe717kMYRyy/j5FwFBX0fP7Dyx8gq8wn2ZXi8GfGYR+lFcGJSxa3Y84WgzBHetlU4cvKY44Ps4iP9fsgsPGEhQTAcHqwwGCj61SoPexKwasXFqtxq8qhD9SixoBBYcJEDNzmIoi3J7QkoJActVHocTVpPBCDhElAvMDK1PT/Sq3DwB/ygmyB9GNhYDH4so4Foy48kkPtZfZEv1PQTxYpyX0EI3Bu+/5krcN8fgwVdwWu2JNVNWAk+PcOOPMNdGFyAZ5Aj6gicgzNfwuHZg0HrLxBWfjSRl88fVCo/apX/IBrIvf65ZxtEoK9Bec4KZIPLe76osQns46NwW0pUPCPAyMc4A/KXOwZzFLGbAqD5xhhbgBcWfoJBAlarcCSQgdQJ+Movnih4gjZQTw51rz588y/ZgxVUEAQ8soCfX8OR26JwujCLGFAMsOjnwGrlPuQw9D/PPv8BYVR7pG/eeFtQpsLzR2KFI8SwKj9KlX++HeLOPuSBKrKeHBi7L4b+Kx184+ptAp4Trcscv69oARVYzWgaK01H1X0K3zNSmARKtxXYHvwJuT+8gLGGWgpHcWOmBeljFB2Ckg6wiAYOqfxEK3GMCAj6kIiTWdCBCXhkjUKMgJcLk271N9uLSbtvvK0S69OXAvoA5z94VsFubbmZvx4QAnXgBnJxENyQjy38wef81uPhxMpPJIQzr5ckuUTKe0wZyN57iFTWga8GvCwlh5UqvYgmaNV9XSxEVWs40kkosFwA70RgNOu8mLZfR6wDiwRa35y7j08NksqPQhcfkRBK/J8R75Iz+9C8gJpqzwiIeZII3QnYOkJWbVEI5jNuA+o2BwK82ifwnpSgHwaC+GNAdmW2VXfC+vPu6wR6lBj84C9WfvivZyUhZMJlJhjSukDlFJ3g4AvGJfC1iEpQJ/CaEd7G9wds7p71+odruKrHip/C7RdsxeVjzIxhoNkFGOW/+sk/YVAGtltfzZAIfzix8gcHhZCXpcGN2u69qWqD9OlRFAy7x2fQBhHUiETB+DocqvArYt98f+AEAXApsEmEcNLC0t2uPHCqPQIXwHYDfI4/9+8LMpchqr5HK39MJSrBXwnutNqjovjHFdq+fcHLp7YLR4mGgduW5hFpAXUoL4cTTuW5HJSkB5PC0S7A+8c+837DyoM1J9iv/po/o3BunlDqPjOSO/YbLFd+FGy9sxKFeT8b+nLNPrkAyD53FtT27yUS32yqUaEGTMBiASGcZ0FmK8nWxbvjC1q6WQC4VdWdAcBY8eFoAzIrC0b7Wt8wlPcIdE1FhUWeKU1Igv8Q/0dl4k/NnYSxdlDon8diUDeuQB4c8XVzcahRgyyZmNC+LAgeCfSVALde8/t1DCYawNoePGT83wlOpFUdOZKwxn89OsMEf0X8CxJCBN/dwKbFwkSMgx0ACJJDJD4iC1JEYh6XcEqVHpx4+J4I4UiAl26r5x64sttvSlAn3LBuQCz6edU8C+J5epBrC4YP52EFDgHrCw1B0eU9bOaTgh3wmYvQV3Oqqcf53XnVNXUBELX1xtSgFrirlII5d3HFulxBCNEfZx0h7K2f34XwdHpuYQcguN189Ow/nPXclaUcqMH5leCXjKOjbv3F0a7i2ZaRHmBe5zwnhA9S736ZC8AH8LHkg/T5znYgmES1dtuzGo92qwHIquiWX+4KgVLd8utv9Ml1BQNhEJW/FOgweiTguCUoQHkEwYhjfQIgm8eAzPKzHqAG5xGiiPyxeGRRaYetUpDVpHVC1T9bHGyaknb/TQTnuG7rDYwYCUT7/cMjtILzA+Go/FPw581F/mWeTkDuBsBCAK8ki+A29nMzPn4Rzjv6QV7xWW4fzQFUxb9jQQ1qc28kMi4mDl1NBr4usIsz5ltZqNm7AeJXfuTHd7nioLEyPBISU+8/tP1AC4Il/n+YGmjg2NiBRdl6yCw//zG5ph7bqaBuz8B4VMU/TqSsNPbwCeZA1cdxyG9SgKzRZPL+GXFOiH1/SFZ9wX8M3zUgvH8a4rMBjZj/h1W9MrwTiN6MlsCKiI4gycBzgV/xUaQGjGDHwHiYi0VIzeEAasCpNuL76AC7BIEl7i4AIxnAfoMxk35eJbZ68wWEUChs8IPz/EEE9BkUoNA4RCWSLJkY1h0Y/dG9bVCtUVPe7QRhtStXG4nOECDfUxc4Uw/Ik8JkA9o9+a83IrfHH11EdFUWc4phNgVFWkPsIHBnCvCCYBSgqEN9qtoXuwHhByYoJJA7BxIkkRwpDGgAHo+vQ3ZGOwCFJCJKUAx4MBpFZWvReeLgtBBkDDQu2OJxXa7SE/P4ZiUPHABjY1DsFIhPAaygWewiXK72hHjow/k8gCL6gKES8qcDZ7A+EhYlWCPGCX1wXIwzkQEKt8cP6iqkC0FEhFj/ZYtvXCtwuBLcDT5wXN+9H6ZEIkTwV/x/s78fXFX3siWHEKrC3tw7EFZ31Ll7ttknQyEMGgAqCaVe1bGk8r8nFWCQQR0h7CY0dsU/mIeIuA1AGCo02Q0YVXxub36sG1Qgfo0CBBUXxap+ECFEycQVyViBEBFPt14TK9rZHB9EwMG7DPXOv0OVHkdtx7OSCXfb3av4CFZGTwQBwT7/hKPHE4PzpJ4L4+FM9r1n8B+B+9R9I4Fu9brYUZgCunZWNxdQgIs8mASBQ4F8hJpEiaf4GPihk8FdAxin/kybjZjTj+mAQy6ihZ9whDvHAWB6BKrBXQr+5SBfqPaINwiz12UIwoTmbPACZY/fshBBBKNlW8ZCHwH/cVKSOZMm4Mxk4OwE9JeB+EFkn1IzcPQoiSB4vGgNeJSoik1A7m0TCmE/HrggB+/1M12C1Z18ACGoIeH1pH2IhAqFWgBq+kDFEWAvA3X8tpW0cnSD5WAOriOHhnYraF1eLTkS8P/QsHUBdtMPnOrMaANJE9AZiaKWII5Ue/8PTHn/UcCSTgIF2xN4zdmAQYIAKeBFl6FiO0aKfq5jcImHfPwTxcEdRmD3LcFoAva1Hdjm9UgGggI9YOoPkOBYLsT8HlG3nucMDGkOOJ8CkNOELdSO7D5qqAeJYBb2GpABgRi2gxLITgrOQ9C937HgB+0i7MeRx3gfPWCXLtgbLJAu/gCFBPzRX8eADJqCvA3FViC/BlOQC4LZyrBq8BdQAOUKoKjqR7v7EFfVFMojPgEoSlJesNIePyLHwW9NRgq7E6HvUN8A0yj0wyWDHRZ3J2A1jHdMyu3hCGwSDwdRir7h9VP7AKLgPoMCgKziOFLtrUm8aIFHlgxYfz8WBYUU55iAXauo+evJaIK/NTgRJM9sUcZRzcCnMdNKMJc7usnAyrpxHYkTRHK+n1HxS01LheAHqRWwKIDqLvQC0+PupHZgBawfVGsiniTVHwZHRqbUI/D4Cd+ftgyLAR1ehkIiqaKFw7MJEwUIuK5zsu4svoFYCFKgBJZACBuppOId2RDkPZas8H9kULcA9a0KTCQDGtpnzT+RMJiOGseHl4BQ1C29AWUXIIf/OIwwqoNEK3SCuA7FRiBrE9B4/PcrGJ1OQNj83F4Xbol/TgVHfMiIZLAdcaVkgh8sLrd+liNQH/FqsNTfj15m1J0X+ffZuq/gTY7QnvIfJz6UzBJLs83ItQpt3RfZz5iuGfNPajpngUm0R8DoA5jDlzsOTAwZjzsC3Jjxg7H914PjlcskGdghgx9HG4OOQH34uwQyzz61/0qiYNQjXxECuWYbGM/DrjtPH/Mw/K+gBLLSA+cEfPr4MroArzcDuybbr8Zc72i2UnzeHnTgzD4Ug78SzIvCoARVOQxaFFR3TzWnkkHUVFShEuqKxZnKz4p4YYcf8ZhYhuu8wFgSHcuuwCJagI4bgchJQK/qe9c/RT6nGcg6KGREJpb+MI0EY/b0jcsni3AJBeCQNsBOFVYoApcM2Aom4VFgIRdHpeIG8D3YaxBD+qCiQ+rBOSVnci8hzkAG1t/pgHA4uwDzmu8xFKkkkIqCfkIRs204r/hiDgutoAAcowBMZ9+KS0CcXVBOHCvJw2jMQSJyeoeExF2DuTuRcuWAo9sefyUQ6/oBaIjPtiRH1KvQKvygAHb171d+vc4GRMDPoxN/kL5pwlVh1mBQ1quQJAJ5j0TgOAis+h8d3mnC8xTKE34+8sDNjyVXE6nFMN+H39TQDmocHScENvN74LoGScGU4f7g6IG3n3C3qnG6JBS+Z5tHOOzRYQx+u7MZmAl0OSsRLAS/VIKfRAWU92+12aaVPksGDBWQuCMvgNy2M2Mt8EwqbjosZAec5xLEAmXmcFTHiOWARWglpNpjdEtBQRxJJU5VL5/7F1X86XntXgUK4q+KggsUoIIK8oA+kgy4+zLaACqQGTVOX6MBWdehL6BxHn+tlyBMDGAqufd7WOX5WTJwKYDfXJJP2GXDPk7Tj5Ed7BOG7DMFaBRAJgI/+H2Ngeb2SKb0zkoGlQBHkefDr7xMA5HZeJPtKIzyApI9gmnPgf1c3mulfhe0gFekDCdNFnrOwi4Gs6eTACNjB+Uegcgojog4V25P8bctRYY6RL8AJklE9ACFAGZdBEahd4d4CmghFhbzcwaXYH5qTlS6DY+KfNH5Avzjo2JJ0poDkSCMxLn73H/eB+ifvgvyIFCWAji7BWC8hd0qj0FziMdrS70BlVbgamIgcmotGZDNPwm0L9l5iHv7WRoAFx57ScFS2r2iwot8oKu8l+TOCOg2mZ2nFdjTgOFQENzKkJ8OjEnsE8f6AzyXwT6MNF3RDRnuj0Lwo6wTlBMDIyqaz6G+RiLJMg/KUrQV/rh9uH0tWduwoxmky0kSMQ+rnXxZsGadgnxfgk1pCnsIsGYltvfdzTOBIclIsN8MLAGcz5gBwj94AE8DuC9Molip/JGwB57nRyJiyD3pyk6q5ij+3TzRLohcqyqCEQBTepF15+WVmW8SEr5jMUUkx3oMIsrH3ndwAQganKzyMpOJNxMQooGBYwcByw7axIhgPRGEr6GSGJhkAELoQ1YRg+dPeD5IIRDIqq5PA2Jh0Rq0YcS8XBi0ghGRFpCtWTdum5+yLOsQf2EuYY8AfnbQZDgCjHxBSKwTGpt8QCIDVH3/4H5OwEvldhliINwAFLsEyyIfGKV+vm3eEehVqKTdNxtDiPoLHCRiuwTJxCECxMDqDjTvZ63KaPKvRgV2i/F3ohm88V8LN8hgJcXD5pVGIPPNn9EBqSQC0I4AMxBUcQNCkarkFgSn/oCs9GCVep4eUG5BRAOcQOCWlGSc3If0IFqRfURQGRrKewPKEJ9sLnIowKCcw+f48N6UHjqYtgInaCCkBbPSj8VEkCr2g8U43wY1xX/BNkwreQrzg+oaJghOCGTU8RBxuIp6VFOGoEXgEsBLIgV6gBgxoLSI5CgiYNT+GBHsU01GthrceiMUtv9KgAYktgVNeGrBbtiOQVi9x8WjiAW7UNUnm4Vet7WtsFgDCDYEwQ/EVL1PnQf/xCDLTowTh4c4HPRDoQaiwhKIAae4B7xgCBydI/CDPOrevK0FR4p6w3VfoXgQiB3T1N8Y1PCD0X19JqcHGfzB5WkQE4p/kdeXBcEVUXEIFqSij82lMyrWq/7c+LFHA7z5/dwOHHg8s/Y8C2CmhbmALtare+4UWLfb25BmXABKABTniC8gRAP2yvDAiUAsElnrxFzITQa/sAFecAOY7zPV/8jMQHSbWAiUPGkQNABhw85xrSCv+mMSzFR8+7mjw01A8f4F8S/td4jnDHYxpT8/OEyV3gz2+GTfdAeAszswfJNGlQhEIjB0Bls0BKn4Iw7WKu9f1gmSagmvqleEwJwnZwjO7npz1HdCJ1hS/mlBcRXyF3i/M7NxqJFoeH27z7nnJaBmpUZKHsTbGUc1ALEoIGsGYl9ixS50gjAT/VhB8IzvGTrBVfWEz1MzAkRFTtecW731VdjNQPukVdhdn0Y8d/a7WYH6i/TBPBzUFwAlHwtGHOQISrgb1AMUgDETTA3+THAdeRJhg59V/Ektofa9I8wxVICkC7QQSAd2O3cftzPzdMK6aA4iZI4ILfYRbb9RgqICt2AxVnYZ4kkBvHOBxT/zN9ybHx/f5Ql2fkGCX6ANm6F8WCfqAS+Eq5AGcHJd2IFHagTMHAAj+mWBnDXuc81CjhsAi5dL2K8QCYI1aJ/PJtSSxEFXASv7C2I3ZB9/a0j/7nDn/j1pHsz9Jr8fNpxPBUAUUYD4wz5GBlmyAiORjtAIGDFwzSUwqiNZ1d1tPiB7/Q9VeI9KeJU16/knkEeQJEALjY4rkp74fCZiMDSA/PgvT/aT2gYgp5E/P29AKBQAo6TRth5T4VesQFb0i4K7RA2MZpgyFXCEQHCOixuYMPgy2L7+45ezSSKt2oUkURlpXkEMOLSiXPuDQZjk63N5bmzOSxQdLHX7AhwUEA0BAeQPJIQzkAuFlOK/GtyLdiGDKEBdllQ7YouxV2Xdwza9So4Kp5Z0yAgUhTlJgFzSFrznIHYIwKcCu2/L3LsCg6UI1b1/CA+ApIV5/32HqOIjdQusE4azip5Wc1b0q/QGIAlaWEJbXP3r/L+AEipw/+BtkQVY9fIM2i/ZhgVEgJO6DZ1ksVtlYdoQAPhVO0oKmYBmnAYco4DRCRB3TwCziptaE0auER9/VzRqKNOEYINOQg2m1l9GpGNQAhh1v6UmxNQh2M4+LmlUzll0OTjYQOaGlZAEMCrdhmBphaMBwBADrSQQc3//He8KgFETT7p6BHnjj2X9EXsDjrgBS6ihoAmcSQVYmE4JgYWFpp1waAQRoqDzxDhU+HxSnZHz/9JEY6Y5MJA+cwoWrt99+U3Mc/9g/NQTFaigAEtwB1yBzwzucZSX7RZEILhR1d5GDCsBLVUdIQvsldZfEJt5i/MHx2hGJZFkVVyK242iFeh58oBUFqIQbkfp2DV2X0CkAYgv1sU+P+I/HmBu8nErugdRnUWhfp+A/ddlbEH3uQlBsNobUEMHasK1HOYn8BEEvCUaiuigXRIKj+sGOPA4KAWz9/s7WxcgB4+a6/fI2osEwv4yOENAiPf+wQhbc/5f0gGisWuQaRFmGoIqguARWsBQgTTocDLMT5OJUQnhqdCEig+/EShKSEgTVV0MBMnz04BcshPnLk/+OaV0/dwKzB4QUt1NB6uTDfGOP+cNm9mEsBAFiM7AQh9AKVEU75vy68jeOxrUC4mDEuYO0oLqoSdHaEF2eXYYSm0V+oEOwpLmYFOF3Z4CmAeBTIGueiIw2xoKPzDBJVBXQ5g5O8/twwA+QguIjJt3+g0NQEcDfUXgO5gsqlTBLkQLdl86K3CWneitQ8sg/5oWAUJP2C3V3RoEyji5n4b9lB4t9pz2CA+cAFn1Z9I/uzYsU/ELtEBOCHYQQqGcFejV+yeuRJX31zsKV5IGjway9z6PLDxKwNEPsBuOEiqw57jGgOtZ1Y++T50AuMFl7hPIbhskiOwsATtRoc7rS7dXrpcgrMCGJca6ELJo+Y0be0BW5ZKGcFz4y8W9BduwcDnK9iO5fagsKpp9ANnvDPxeP8THNyIVFo1AMas8Qk5v2Ytm0LCCYAXqn+wQsPTBh/5Bcnne14Os3uCQt28vsK1WUESJFviBgAW//3u9PLxusXchcCR2WsNzv/ImvgZzzkUByDUAIrjTvmSHAowpJBQE4SUlxMxnARlQbIqkArVAJ6pBBvELCCKlkyCDAP45BYfEPfcUpfMch3Vn4bheYK4E66BxAxHSVd5INgEPgU/NBCDfNQ8Ho1CoINAPQAW/QT8OCIZlNFCB84XhoDChFByHGjx35v9BLgyhmojqHYb5QYXnuAecvua0hZe6BV9f7v4ibvgvamrmAc1TmaEir0LQ9h97eYAYVoM/nWA60i8Q3Ifezha9BqaaL3zvqd6IAuwwLSCCuCLuJWch4h30giPtyiAphKEBcCu9BV5wwzkMxID8rhMwdwMhcSFgrBT3RUTQboAUg3+p+Qe1IGarOioVnazmefV3lHpwA0AcLWCahUiXwePHWJsP+GH1gnp/we5KfOhJAbsj0H/BIEb04TbrTPsAyb2LLu93KwfCvn5PLAwrOXAa72eEQRo1CNdw5IprsAZ3hApy9zlcITG2vpCihsRSYxNS+J4vdBZ6B52eqRcQ/QXmSjAWSfa/5GA5qEg4iJFtm624AqXLrSA2gx8p1Mdqcghv41S0lSp/xAYs9gakQc4Ie2RTUYwYgt748mV+FU1Xgp14eW3XYZ6cdqGTNHwHICTwEeTPl0jEZwIgP9gDEaogeg5IHWCF+1eoAhvEKPB/EAeTRsM/pSAP5wjWEUMM1/NJRhwJbpJSgK7S7zF3EOsI5jBQBK9DV80Z8Y0COzvmWzJXgDl40KEC6cqvqgi4OB5cpgLFYK/1CvDiItXqC6/S87wfAUfPtxqfGNzlYaOjlf1IsHPPvffHgDAoEeEST4ZLZUd/RSo91/BjXY5ggWgQ4In3fyj4mUqPrInHOCLKO3wUwRsfyXpt1nEIRLrqcWeTuk7bigsbid1zD4iDRQtnIdQsyIXnFCn1I9D7ADgxEhOvR5AJosoUbu1FkJyYCi9OhQERoIx+4AX/YqUXQhtYEwKN4Cy1HntLMmtaAQpqfrT/UCoLSxeswjA5UWPPi0mjajUWxMTdVusNvt/ChMdmILK5IRMFu90BMEzFYHdg2GAgeYVHMMJIBTA7EFTx/5fpgTFXz9w/en0ZjD8kCDoKPNGwlB01BmoWQbh+AxR689mBponGJOr9OwmMu3dtJ/ylW1Tik4ElUPmR9RqII+pVhD9ychABMQ51gOIZg+/G+5mGIzLB1JJC5WhzYjhJ7IWmLDpA8jzsAafUPkB2WnFBF4iSxkq1ty7f25rv/+EQLOxs2oUdTSA9HIR9swdBlCcFe9owPC3XWDDC0ISVzsEVbSCF/sWdA5Fu4HJqankp2SeQCYYrImNalfmhpVxYrGkUS4LeSUjg8dD7+D7w/ybIfy7vlB9/HJ978zr7/45Qgajzj+4EjIK/ULHPRAOlKr/aG0AFcqCyu0GcW45Igh6JMJmhA49/U+cEssHNJhtXDC1MOya3j/sAiAGcrEtqtgjBD6wEzSDc7D8o6C8rIqAZyPk+NQoNLAZ1hR64Yl1FBY648smUYKnSg1Xwk/0DyRyArByMUobyByhCcPnOaPyoegREFS4jNfYAw+IHCjdC1J2WDZBke/OyN85J24WiXwDYPoJyYuCD238ulvuzwt6KgHf0shWKsqCFFGjB/w8HU8eeTED9wAAAAABJRU5ErkJggg==","EnvironmentBRDFTexture"+an++,e,!0,!1,Dr.BILINEAR_SAMPLINGMODE);e._blockEntityCollection=s;const r=e.getEngine().getLoadedTexturesCache(),n=r.indexOf(i.getInternalTexture());-1!==n&&r.splice(n,1),i.isRGBD=!0,i.wrapU=Dr.CLAMP_ADDRESSMODE,i.wrapV=Dr.CLAMP_ADDRESSMODE,e.environmentBRDFTexture=i,e.useDelayedTextureLoading=t,nn.ExpandRGBDTexture(i);const a=e.getEngine().onContextRestoredObservable.add((()=>{i.isRGBD=!0;const t=e.onBeforeRenderObservable.add((()=>{i.isReady()&&(e.onBeforeRenderObservable.remove(t),nn.ExpandRGBDTexture(i))}))}));e.onDisposeObservable.add((()=>{e.getEngine().onContextRestoredObservable.remove(a)}))}return e.environmentBRDFTexture};class hn{constructor(e){if(this._keys=[],this._isDirty=!0,this._areLightsDirty=!0,this._areLightsDisposed=!1,this._areAttributesDirty=!0,this._areTexturesDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!0,this._areImageProcessingDirty=!0,this._normals=!1,this._uvs=!1,this._needNormals=!1,this._needUVs=!1,this._externalProperties=e,e)for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&this._setDefaultValue(t)}get isDirty(){return this._isDirty}markAsProcessed(){this._isDirty=!1,this._areAttributesDirty=!1,this._areTexturesDirty=!1,this._areFresnelDirty=!1,this._areLightsDirty=!1,this._areLightsDisposed=!1,this._areMiscDirty=!1,this._arePrePassDirty=!1,this._areImageProcessingDirty=!1}markAsUnprocessed(){this._isDirty=!0}markAllAsDirty(){this._areTexturesDirty=!0,this._areAttributesDirty=!0,this._areLightsDirty=!0,this._areFresnelDirty=!0,this._areMiscDirty=!0,this._arePrePassDirty=!1,this._areImageProcessingDirty=!0,this._isDirty=!0}markAsImageProcessingDirty(){this._areImageProcessingDirty=!0,this._isDirty=!0}markAsLightDirty(e=!1){this._areLightsDirty=!0,this._areLightsDisposed=this._areLightsDisposed||e,this._isDirty=!0}markAsAttributesDirty(){this._areAttributesDirty=!0,this._isDirty=!0}markAsTexturesDirty(){this._areTexturesDirty=!0,this._isDirty=!0}markAsFresnelDirty(){this._areFresnelDirty=!0,this._isDirty=!0}markAsMiscDirty(){this._areMiscDirty=!0,this._isDirty=!0}markAsPrePassDirty(){this._arePrePassDirty=!0,this._isDirty=!0}rebuild(){this._keys.length=0;for(const e of Object.keys(this))"_"!==e[0]&&this._keys.push(e);if(this._externalProperties)for(const e in this._externalProperties)-1===this._keys.indexOf(e)&&this._keys.push(e)}isEqual(e){if(this._keys.length!==e._keys.length)return!1;for(let t=0;t<this._keys.length;t++){const s=this._keys[t];if(this[s]!==e[s])return!1}return!0}cloneTo(e){this._keys.length!==e._keys.length&&(e._keys=this._keys.slice(0));for(let t=0;t<this._keys.length;t++){const s=this._keys[t];e[s]=this[s]}}reset(){this._keys.forEach((e=>this._setDefaultValue(e)))}_setDefaultValue(e){const t=this._externalProperties?.[e]?.type??typeof this[e],s=this._externalProperties?.[e]?.default;switch(t){case"number":this[e]=s??0;break;case"string":this[e]=s??"";break;default:this[e]=s??!1}}toString(){let e="";for(let t=0;t<this._keys.length;t++){const s=this._keys[t],i=this[s];switch(typeof i){case"number":case"string":e+="#define "+s+" "+i+"\n";break;default:i&&(e+="#define "+s+"\n")}}return e}}const ln=new RegExp("^([gimus]+)!");class cn{constructor(e){this._plugins=[],this._activePlugins=[],this._activePluginsForExtraEvents=[],this._material=e,this._scene=e.getScene(),this._engine=this._scene.getEngine()}_addPlugin(e){for(let t=0;t<this._plugins.length;++t)if(this._plugins[t].name===e.name)return!1;if(this._material._uniformBufferLayoutBuilt)throw`The plugin "${e.name}" can't be added to the material "${this._material.name}" because this material has already been used for rendering! Please add plugins to materials before any rendering with this material occurs.`;if(!e.isCompatible(this._material.shaderLanguage))throw`The plugin "${e.name}" can't be added to the material "${this._material.name}" because the plugin is not compatible with the shader language of the material.`;const t=e.getClassName();cn._MaterialPluginClassToMainDefine[t]||(cn._MaterialPluginClassToMainDefine[t]="MATERIALPLUGIN_"+ ++cn._MaterialPluginCounter),this._material._callbackPluginEventGeneric=(e,t)=>this._handlePluginEvent(e,t),this._plugins.push(e),this._plugins.sort(((e,t)=>e.priority-t.priority)),this._codeInjectionPoints={};const s={};s[cn._MaterialPluginClassToMainDefine[t]]={type:"boolean",default:!0};for(const e of this._plugins)e.collectDefines(s),this._collectPointNames("vertex",e.getCustomCode("vertex",this._material.shaderLanguage)),this._collectPointNames("fragment",e.getCustomCode("fragment",this._material.shaderLanguage));return this._defineNamesFromPlugins=s,!0}_activatePlugin(e){-1===this._activePlugins.indexOf(e)&&(this._activePlugins.push(e),this._activePlugins.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventIsReadyForSubMesh=this._handlePluginEventIsReadyForSubMesh.bind(this),this._material._callbackPluginEventPrepareDefinesBeforeAttributes=this._handlePluginEventPrepareDefinesBeforeAttributes.bind(this),this._material._callbackPluginEventPrepareDefines=this._handlePluginEventPrepareDefines.bind(this),this._material._callbackPluginEventBindForSubMesh=this._handlePluginEventBindForSubMesh.bind(this),e.registerForExtraEvents&&(this._activePluginsForExtraEvents.push(e),this._activePluginsForExtraEvents.sort(((e,t)=>e.priority-t.priority)),this._material._callbackPluginEventHasRenderTargetTextures=this._handlePluginEventHasRenderTargetTextures.bind(this),this._material._callbackPluginEventFillRenderTargetTextures=this._handlePluginEventFillRenderTargetTextures.bind(this),this._material._callbackPluginEventHardBindForSubMesh=this._handlePluginEventHardBindForSubMesh.bind(this)))}getPlugin(e){for(let t=0;t<this._plugins.length;++t)if(this._plugins[t].name===e)return this._plugins[t];return null}_handlePluginEventIsReadyForSubMesh(e){let t=!0;for(const s of this._activePlugins)t=t&&s.isReadyForSubMesh(e.defines,this._scene,this._engine,e.subMesh);e.isReadyForSubMesh=t}_handlePluginEventPrepareDefinesBeforeAttributes(e){for(const t of this._activePlugins)t.prepareDefinesBeforeAttributes(e.defines,this._scene,e.mesh)}_handlePluginEventPrepareDefines(e){for(const t of this._activePlugins)t.prepareDefines(e.defines,this._scene,e.mesh)}_handlePluginEventHardBindForSubMesh(e){for(const t of this._activePluginsForExtraEvents)t.hardBindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)}_handlePluginEventBindForSubMesh(e){for(const t of this._activePlugins)t.bindForSubMesh(this._material._uniformBuffer,this._scene,this._engine,e.subMesh)}_handlePluginEventHasRenderTargetTextures(e){let t=!1;for(const e of this._activePluginsForExtraEvents)if(t=e.hasRenderTargetTextures(),t)break;e.hasRenderTargetTextures=t}_handlePluginEventFillRenderTargetTextures(e){for(const t of this._activePluginsForExtraEvents)t.fillRenderTargetTextures(e.renderTargets)}_handlePluginEvent(e,t){switch(e){case 512:{const e=t;for(const t of this._activePlugins)t.getActiveTextures(e.activeTextures);break}case 256:{const e=t;for(const t of this._activePlugins)t.getAnimatables(e.animatables);break}case 1024:{const e=t;let s=!1;for(const t of this._activePlugins)if(s=t.hasTexture(e.texture),s)break;e.hasTexture=s;break}case 2:{const e=t;for(const t of this._plugins)t.dispose(e.forceDisposeTextures);break}case 4:t.defineNames=this._defineNamesFromPlugins;break;case 128:{const e=t;for(const t of this._activePlugins)e.fallbackRank=t.addFallbacks(e.defines,e.fallbacks,e.fallbackRank),t.getAttributes(e.attributes,this._scene,e.mesh);this._uniformList.length>0&&e.uniforms.push(...this._uniformList),this._samplerList.length>0&&e.samplers.push(...this._samplerList),this._uboList.length>0&&e.uniformBuffersNames.push(...this._uboList),e.customCode=this._injectCustomCode(e,e.customCode);break}case 8:{const e=t;this._uboDeclaration="",this._vertexDeclaration="",this._fragmentDeclaration="",this._uniformList=[],this._samplerList=[],this._uboList=[];const s=1===this._material.shaderLanguage;for(const t of this._plugins){const i=t.getUniforms(this._material.shaderLanguage);if(i){if(i.ubo)for(const t of i.ubo){if(t.size&&t.type){const i=t.arraySize??0;if(e.ubo.addUniform(t.name,t.size,i),s){let e;switch(t.type){case"mat4":e="mat4x4f";break;case"float":e="f32";break;default:e=`${t.type}f`}this._uboDeclaration+=`uniform ${t.name}: ${e}${i>0?`[${i}]`:""};\n`}else this._uboDeclaration+=`${t.type} ${t.name}${i>0?`[${i}]`:""};\n`}this._uniformList.push(t.name)}i.vertex&&(this._vertexDeclaration+=i.vertex+"\n"),i.fragment&&(this._fragmentDeclaration+=i.fragment+"\n")}t.getSamplers(this._samplerList),t.getUniformBuffersNames(this._uboList)}break}}}_collectPointNames(e,t){if(t)for(const s in t)this._codeInjectionPoints[e]||(this._codeInjectionPoints[e]={}),this._codeInjectionPoints[e][s]=!0}_injectCustomCode(e,t){return(s,i)=>{t&&(i=t(s,i)),this._uboDeclaration&&(i=i.replace("#define ADDITIONAL_UBO_DECLARATION",this._uboDeclaration)),this._vertexDeclaration&&(i=i.replace("#define ADDITIONAL_VERTEX_DECLARATION",this._vertexDeclaration)),this._fragmentDeclaration&&(i=i.replace("#define ADDITIONAL_FRAGMENT_DECLARATION",this._fragmentDeclaration));const r=this._codeInjectionPoints?.[s];if(!r)return i;let n=null;for(let t in r){let r="";for(const i of this._activePlugins){let a=i.getCustomCode(s,this._material.shaderLanguage)?.[t];if(a){if(i.resolveIncludes){if(null===n){const t=0;n={defines:[],indexParameters:e.indexParameters,isFragment:!1,shouldUseHighPrecisionShader:this._engine._shouldUseHighPrecisionShader,processor:void 0,supportsUniformBuffers:this._engine.supportsUniformBuffers,shadersRepository:$e.GetShadersRepository(t),includesShadersStore:$e.GetIncludesShadersStore(t),version:void 0,platformName:this._engine.shaderPlatformName,processingContext:void 0,isNDCHalfZRange:this._engine.isNDCHalfZRange,useReverseDepthBuffer:this._engine.useReverseDepthBuffer,processCodeAfterIncludes:void 0}}n.isFragment="fragment"===s,qe(a,n,(e=>a=e))}r+=a+"\n"}}if(r.length>0)if("!"===t.charAt(0)){t=t.substring(1);let e="g";if("!"===t.charAt(0))e="",t=t.substring(1);else{const s=ln.exec(t);s&&s.length>=2&&(e=s[1],t=t.substring(e.length+1))}e.indexOf("g")<0&&(e+="g");const s=i,n=new RegExp(t,e);let a=n.exec(s);for(;null!==a;){let e=r;for(let t=0;t<a.length;++t)e=e.replace("$"+t,a[t]);i=i.replace(a[0],e),a=n.exec(s)}}else{const e="#define "+t;i=i.replace(e,"\n"+r+"\n"+e)}}return i}}}cn._MaterialPluginClassToMainDefine={},cn._MaterialPluginCounter=0,C.OnEnginesDisposedObservable.add((()=>{un.length=0,$s.OnEventObservable.remove(dn),dn=null}));const un=[];let dn=null;class _n{isCompatible(e){return 0===e}_enable(e){e&&this._pluginManager._activatePlugin(this)}constructor(e,t,s,i,r=!0,n=!1,a=!1){this.priority=500,this.resolveIncludes=!1,this.registerForExtraEvents=!1,this._material=e,this.name=t,this.priority=s,this.resolveIncludes=a,e.pluginManager||(e.pluginManager=new cn(e),e.onDisposeObservable.add((()=>{e.pluginManager=void 0}))),this._pluginDefineNames=i,this._pluginManager=e.pluginManager,r&&this._pluginManager._addPlugin(this),n&&this._enable(!0),this.markAllDefinesAsDirty=e._dirtyCallbacks[Ze.MATERIAL_AllDirtyFlag]}getClassName(){return"MaterialPluginBase"}isReadyForSubMesh(e,t,s,i){return!0}hardBindForSubMesh(e,t,s,i){}bindForSubMesh(e,t,s,i){}dispose(e){}getCustomCode(e,t=0){return null}collectDefines(e){if(this._pluginDefineNames)for(const t of Object.keys(this._pluginDefineNames)){if("_"===t[0])continue;const s=typeof this._pluginDefineNames[t];e[t]={type:"number"===s?"number":"string"===s?"string":"boolean"===s?"boolean":"object",default:this._pluginDefineNames[t]}}}prepareDefinesBeforeAttributes(e,t,s){}prepareDefines(e,t,s){}hasTexture(e){return!1}hasRenderTargetTextures(){return!1}fillRenderTargetTextures(e){}getActiveTextures(e){}getAnimatables(e){}addFallbacks(e,t,s){return s}getSamplers(e){}getAttributes(e,t,s){}getUniformBuffersNames(e){}getUniforms(e=0){return{}}copyTo(e){re.Clone((()=>e),this)}serialize(){return re.Serialize(this)}parse(e,t,s){re.Parse((()=>this),e,t,s)}}e([a()],_n.prototype,"name",void 0),e([a()],_n.prototype,"priority",void 0),e([a()],_n.prototype,"resolveIncludes",void 0),e([a()],_n.prototype,"registerForExtraEvents",void 0),I("BABYLON.MaterialPluginBase",_n);class fn extends hn{constructor(){super(...arguments),this.BRDF_V_HEIGHT_CORRELATED=!1,this.MS_BRDF_ENERGY_CONSERVATION=!1,this.SPHERICAL_HARMONICS=!1,this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=!1}}class pn extends _n{_markAllSubMeshesAsMiscDirty(){this._internalMarkAllSubMeshesAsMiscDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRBRDF",90,new fn,t),this._useEnergyConservation=pn.DEFAULT_USE_ENERGY_CONSERVATION,this.useEnergyConservation=pn.DEFAULT_USE_ENERGY_CONSERVATION,this._useSmithVisibilityHeightCorrelated=pn.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this.useSmithVisibilityHeightCorrelated=pn.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED,this._useSphericalHarmonics=pn.DEFAULT_USE_SPHERICAL_HARMONICS,this.useSphericalHarmonics=pn.DEFAULT_USE_SPHERICAL_HARMONICS,this._useSpecularGlossinessInputEnergyConservation=pn.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this.useSpecularGlossinessInputEnergyConservation=pn.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION,this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[Ze.MATERIAL_MiscDirtyFlag],this._enable(!0)}prepareDefines(e){e.BRDF_V_HEIGHT_CORRELATED=this._useSmithVisibilityHeightCorrelated,e.MS_BRDF_ENERGY_CONSERVATION=this._useEnergyConservation&&this._useSmithVisibilityHeightCorrelated,e.SPHERICAL_HARMONICS=this._useSphericalHarmonics,e.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION=this._useSpecularGlossinessInputEnergyConservation}getClassName(){return"PBRBRDFConfiguration"}}pn.DEFAULT_USE_ENERGY_CONSERVATION=!0,pn.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED=!0,pn.DEFAULT_USE_SPHERICAL_HARMONICS=!0,pn.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION=!0,e([a(),n("_markAllSubMeshesAsMiscDirty")],pn.prototype,"useEnergyConservation",void 0),e([a(),n("_markAllSubMeshesAsMiscDirty")],pn.prototype,"useSmithVisibilityHeightCorrelated",void 0),e([a(),n("_markAllSubMeshesAsMiscDirty")],pn.prototype,"useSphericalHarmonics",void 0),e([a(),n("_markAllSubMeshesAsMiscDirty")],pn.prototype,"useSpecularGlossinessInputEnergyConservation",void 0);class mn{constructor(){this.previousWorldMatrices={},this.previousBones={}}static AddUniforms(e){e.push("previousWorld","previousViewProjection","mPreviousBones")}static AddSamplers(e){}bindForSubMesh(e,t,s,i,r){if(t.prePassRenderer&&t.prePassRenderer.enabled&&t.prePassRenderer.currentRTisSceneRT&&(-1!==t.prePassRenderer.getIndex(Ze.PREPASS_VELOCITY_TEXTURE_TYPE)||-1!==t.prePassRenderer.getIndex(Ze.PREPASS_VELOCITY_LINEAR_TEXTURE_TYPE))){this.previousWorldMatrices[s.uniqueId]||(this.previousWorldMatrices[s.uniqueId]=i.clone()),this.previousViewProjection||(this.previousViewProjection=t.getTransformMatrix().clone(),this.currentViewProjection=t.getTransformMatrix().clone());const r=t.getEngine();this.currentViewProjection.updateFlag!==t.getTransformMatrix().updateFlag?(this._lastUpdateFrameId=r.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection),this.currentViewProjection.copyFrom(t.getTransformMatrix())):this._lastUpdateFrameId!==r.frameId&&(this._lastUpdateFrameId=r.frameId,this.previousViewProjection.copyFrom(this.currentViewProjection)),e.setMatrix("previousWorld",this.previousWorldMatrices[s.uniqueId]),e.setMatrix("previousViewProjection",this.previousViewProjection),this.previousWorldMatrices[s.uniqueId]=i.clone()}}}class gn extends $s{constructor(e,t,s=!0){super(e,t),this._normalMatrix=new V,this._storeEffectOnSubMeshes=s}getEffect(){return this._storeEffectOnSubMeshes?this._activeEffect:super.getEffect()}isReady(e,t){return!!e&&(!this._storeEffectOnSubMeshes||(!e.subMeshes||0===e.subMeshes.length||this.isReadyForSubMesh(e,e.subMeshes[0],t)))}_isReadyForSubMesh(e){const t=e.materialDefines;return!(this.checkReadyOnEveryCall||!e.effect||!t||t._renderId!==this.getScene().getRenderId())}bindOnlyWorldMatrix(e){this._activeEffect.setMatrix("world",e)}bindOnlyNormalMatrix(e){this._activeEffect.setMatrix("normalMatrix",e)}bind(e,t){t&&this.bindForSubMesh(e,t,t.subMeshes[0])}_afterBind(e,t=null,s){super._afterBind(e,t,s),this.getScene()._cachedEffect=t,s?s._drawWrapper._forceRebindOnNextCall=!1:this._drawWrapper._forceRebindOnNextCall=!1}_mustRebind(e,t,s,i=1){return s._drawWrapper._forceRebindOnNextCall||e.isCachedMaterialInvalid(this,t,i)}dispose(e,t,s){this._activeEffect=void 0,super.dispose(e,t,s)}}class Tn{static get DiffuseTextureEnabled(){return this._DiffuseTextureEnabled}static set DiffuseTextureEnabled(e){this._DiffuseTextureEnabled!==e&&(this._DiffuseTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get DetailTextureEnabled(){return this._DetailTextureEnabled}static set DetailTextureEnabled(e){this._DetailTextureEnabled!==e&&(this._DetailTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get DecalMapEnabled(){return this._DecalMapEnabled}static set DecalMapEnabled(e){this._DecalMapEnabled!==e&&(this._DecalMapEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get AmbientTextureEnabled(){return this._AmbientTextureEnabled}static set AmbientTextureEnabled(e){this._AmbientTextureEnabled!==e&&(this._AmbientTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get OpacityTextureEnabled(){return this._OpacityTextureEnabled}static set OpacityTextureEnabled(e){this._OpacityTextureEnabled!==e&&(this._OpacityTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get ReflectionTextureEnabled(){return this._ReflectionTextureEnabled}static set ReflectionTextureEnabled(e){this._ReflectionTextureEnabled!==e&&(this._ReflectionTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get EmissiveTextureEnabled(){return this._EmissiveTextureEnabled}static set EmissiveTextureEnabled(e){this._EmissiveTextureEnabled!==e&&(this._EmissiveTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get SpecularTextureEnabled(){return this._SpecularTextureEnabled}static set SpecularTextureEnabled(e){this._SpecularTextureEnabled!==e&&(this._SpecularTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get BumpTextureEnabled(){return this._BumpTextureEnabled}static set BumpTextureEnabled(e){this._BumpTextureEnabled!==e&&(this._BumpTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get LightmapTextureEnabled(){return this._LightmapTextureEnabled}static set LightmapTextureEnabled(e){this._LightmapTextureEnabled!==e&&(this._LightmapTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get RefractionTextureEnabled(){return this._RefractionTextureEnabled}static set RefractionTextureEnabled(e){this._RefractionTextureEnabled!==e&&(this._RefractionTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get ColorGradingTextureEnabled(){return this._ColorGradingTextureEnabled}static set ColorGradingTextureEnabled(e){this._ColorGradingTextureEnabled!==e&&(this._ColorGradingTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get FresnelEnabled(){return this._FresnelEnabled}static set FresnelEnabled(e){this._FresnelEnabled!==e&&(this._FresnelEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_FresnelDirtyFlag))}static get ClearCoatTextureEnabled(){return this._ClearCoatTextureEnabled}static set ClearCoatTextureEnabled(e){this._ClearCoatTextureEnabled!==e&&(this._ClearCoatTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get ClearCoatBumpTextureEnabled(){return this._ClearCoatBumpTextureEnabled}static set ClearCoatBumpTextureEnabled(e){this._ClearCoatBumpTextureEnabled!==e&&(this._ClearCoatBumpTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get ClearCoatTintTextureEnabled(){return this._ClearCoatTintTextureEnabled}static set ClearCoatTintTextureEnabled(e){this._ClearCoatTintTextureEnabled!==e&&(this._ClearCoatTintTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get SheenTextureEnabled(){return this._SheenTextureEnabled}static set SheenTextureEnabled(e){this._SheenTextureEnabled!==e&&(this._SheenTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get AnisotropicTextureEnabled(){return this._AnisotropicTextureEnabled}static set AnisotropicTextureEnabled(e){this._AnisotropicTextureEnabled!==e&&(this._AnisotropicTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get ThicknessTextureEnabled(){return this._ThicknessTextureEnabled}static set ThicknessTextureEnabled(e){this._ThicknessTextureEnabled!==e&&(this._ThicknessTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get RefractionIntensityTextureEnabled(){return this._ThicknessTextureEnabled}static set RefractionIntensityTextureEnabled(e){this._RefractionIntensityTextureEnabled!==e&&(this._RefractionIntensityTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get TranslucencyIntensityTextureEnabled(){return this._TranslucencyIntensityTextureEnabled}static set TranslucencyIntensityTextureEnabled(e){this._TranslucencyIntensityTextureEnabled!==e&&(this._TranslucencyIntensityTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get TranslucencyColorTextureEnabled(){return this._TranslucencyColorTextureEnabled}static set TranslucencyColorTextureEnabled(e){this._TranslucencyColorTextureEnabled!==e&&(this._TranslucencyColorTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}static get IridescenceTextureEnabled(){return this._IridescenceTextureEnabled}static set IridescenceTextureEnabled(e){this._IridescenceTextureEnabled!==e&&(this._IridescenceTextureEnabled=e,yt.MarkAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag))}}Tn._DiffuseTextureEnabled=!0,Tn._DetailTextureEnabled=!0,Tn._DecalMapEnabled=!0,Tn._AmbientTextureEnabled=!0,Tn._OpacityTextureEnabled=!0,Tn._ReflectionTextureEnabled=!0,Tn._EmissiveTextureEnabled=!0,Tn._SpecularTextureEnabled=!0,Tn._BumpTextureEnabled=!0,Tn._LightmapTextureEnabled=!0,Tn._RefractionTextureEnabled=!0,Tn._ColorGradingTextureEnabled=!0,Tn._FresnelEnabled=!0,Tn._ClearCoatTextureEnabled=!0,Tn._ClearCoatBumpTextureEnabled=!0,Tn._ClearCoatTintTextureEnabled=!0,Tn._SheenTextureEnabled=!0,Tn._AnisotropicTextureEnabled=!0,Tn._ThicknessTextureEnabled=!0,Tn._RefractionIntensityTextureEnabled=!0,Tn._TranslucencyIntensityTextureEnabled=!0,Tn._TranslucencyColorTextureEnabled=!0,Tn._IridescenceTextureEnabled=!0;const En=[Math.sqrt(1/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(3/(4*Math.PI)),-Math.sqrt(3/(4*Math.PI)),Math.sqrt(15/(4*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(5/(16*Math.PI)),-Math.sqrt(15/(4*Math.PI)),Math.sqrt(15/(16*Math.PI))],An=[()=>1,e=>e.y,e=>e.z,e=>e.x,e=>e.x*e.y,e=>e.y*e.z,e=>3*e.z*e.z-1,e=>e.x*e.z,e=>e.x*e.x-e.y*e.y],yn=(e,t)=>En[e]*An[e](t),bn=[Math.PI,2*Math.PI/3,2*Math.PI/3,2*Math.PI/3,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4,Math.PI/4];class Rn{constructor(){this.preScaled=!1,this.l00=U.Zero(),this.l1_1=U.Zero(),this.l10=U.Zero(),this.l11=U.Zero(),this.l2_2=U.Zero(),this.l2_1=U.Zero(),this.l20=U.Zero(),this.l21=U.Zero(),this.l22=U.Zero()}addLight(e,t,s){z.Vector3[0].set(t.r,t.g,t.b);const i=z.Vector3[0],r=z.Vector3[1];i.scaleToRef(s,r),r.scaleToRef(yn(0,e),z.Vector3[2]),this.l00.addInPlace(z.Vector3[2]),r.scaleToRef(yn(1,e),z.Vector3[2]),this.l1_1.addInPlace(z.Vector3[2]),r.scaleToRef(yn(2,e),z.Vector3[2]),this.l10.addInPlace(z.Vector3[2]),r.scaleToRef(yn(3,e),z.Vector3[2]),this.l11.addInPlace(z.Vector3[2]),r.scaleToRef(yn(4,e),z.Vector3[2]),this.l2_2.addInPlace(z.Vector3[2]),r.scaleToRef(yn(5,e),z.Vector3[2]),this.l2_1.addInPlace(z.Vector3[2]),r.scaleToRef(yn(6,e),z.Vector3[2]),this.l20.addInPlace(z.Vector3[2]),r.scaleToRef(yn(7,e),z.Vector3[2]),this.l21.addInPlace(z.Vector3[2]),r.scaleToRef(yn(8,e),z.Vector3[2]),this.l22.addInPlace(z.Vector3[2])}scaleInPlace(e){this.l00.scaleInPlace(e),this.l1_1.scaleInPlace(e),this.l10.scaleInPlace(e),this.l11.scaleInPlace(e),this.l2_2.scaleInPlace(e),this.l2_1.scaleInPlace(e),this.l20.scaleInPlace(e),this.l21.scaleInPlace(e),this.l22.scaleInPlace(e)}convertIncidentRadianceToIrradiance(){this.l00.scaleInPlace(bn[0]),this.l1_1.scaleInPlace(bn[1]),this.l10.scaleInPlace(bn[2]),this.l11.scaleInPlace(bn[3]),this.l2_2.scaleInPlace(bn[4]),this.l2_1.scaleInPlace(bn[5]),this.l20.scaleInPlace(bn[6]),this.l21.scaleInPlace(bn[7]),this.l22.scaleInPlace(bn[8])}convertIrradianceToLambertianRadiance(){this.scaleInPlace(1/Math.PI)}preScaleForRendering(){this.preScaled=!0,this.l00.scaleInPlace(En[0]),this.l1_1.scaleInPlace(En[1]),this.l10.scaleInPlace(En[2]),this.l11.scaleInPlace(En[3]),this.l2_2.scaleInPlace(En[4]),this.l2_1.scaleInPlace(En[5]),this.l20.scaleInPlace(En[6]),this.l21.scaleInPlace(En[7]),this.l22.scaleInPlace(En[8])}updateFromArray(e){return U.FromArrayToRef(e[0],0,this.l00),U.FromArrayToRef(e[1],0,this.l1_1),U.FromArrayToRef(e[2],0,this.l10),U.FromArrayToRef(e[3],0,this.l11),U.FromArrayToRef(e[4],0,this.l2_2),U.FromArrayToRef(e[5],0,this.l2_1),U.FromArrayToRef(e[6],0,this.l20),U.FromArrayToRef(e[7],0,this.l21),U.FromArrayToRef(e[8],0,this.l22),this}updateFromFloatsArray(e){return U.FromFloatsToRef(e[0],e[1],e[2],this.l00),U.FromFloatsToRef(e[3],e[4],e[5],this.l1_1),U.FromFloatsToRef(e[6],e[7],e[8],this.l10),U.FromFloatsToRef(e[9],e[10],e[11],this.l11),U.FromFloatsToRef(e[12],e[13],e[14],this.l2_2),U.FromFloatsToRef(e[15],e[16],e[17],this.l2_1),U.FromFloatsToRef(e[18],e[19],e[20],this.l20),U.FromFloatsToRef(e[21],e[22],e[23],this.l21),U.FromFloatsToRef(e[24],e[25],e[26],this.l22),this}static FromArray(e){return(new Rn).updateFromArray(e)}static FromPolynomial(e){const t=new Rn;return t.l00=e.xx.scale(.376127).add(e.yy.scale(.376127)).add(e.zz.scale(.376126)),t.l1_1=e.y.scale(.977204),t.l10=e.z.scale(.977204),t.l11=e.x.scale(.977204),t.l2_2=e.xy.scale(1.16538),t.l2_1=e.yz.scale(1.16538),t.l20=e.zz.scale(1.34567).subtract(e.xx.scale(.672834)).subtract(e.yy.scale(.672834)),t.l21=e.zx.scale(1.16538),t.l22=e.xx.scale(1.16538).subtract(e.yy.scale(1.16538)),t.l1_1.scaleInPlace(-1),t.l11.scaleInPlace(-1),t.l2_1.scaleInPlace(-1),t.l21.scaleInPlace(-1),t.scaleInPlace(Math.PI),t}}class xn{constructor(){this.x=U.Zero(),this.y=U.Zero(),this.z=U.Zero(),this.xx=U.Zero(),this.yy=U.Zero(),this.zz=U.Zero(),this.xy=U.Zero(),this.yz=U.Zero(),this.zx=U.Zero()}get preScaledHarmonics(){return this._harmonics||(this._harmonics=Rn.FromPolynomial(this)),this._harmonics.preScaled||this._harmonics.preScaleForRendering(),this._harmonics}addAmbient(e){z.Vector3[0].copyFromFloats(e.r,e.g,e.b);const t=z.Vector3[0];this.xx.addInPlace(t),this.yy.addInPlace(t),this.zz.addInPlace(t)}scaleInPlace(e){this.x.scaleInPlace(e),this.y.scaleInPlace(e),this.z.scaleInPlace(e),this.xx.scaleInPlace(e),this.yy.scaleInPlace(e),this.zz.scaleInPlace(e),this.yz.scaleInPlace(e),this.zx.scaleInPlace(e),this.xy.scaleInPlace(e)}updateFromHarmonics(e){return this._harmonics=e,this.x.copyFrom(e.l11),this.x.scaleInPlace(1.02333).scaleInPlace(-1),this.y.copyFrom(e.l1_1),this.y.scaleInPlace(1.02333).scaleInPlace(-1),this.z.copyFrom(e.l10),this.z.scaleInPlace(1.02333),this.xx.copyFrom(e.l00),z.Vector3[0].copyFrom(e.l20).scaleInPlace(.247708),z.Vector3[1].copyFrom(e.l22).scaleInPlace(.429043),this.xx.scaleInPlace(.886277).subtractInPlace(z.Vector3[0]).addInPlace(z.Vector3[1]),this.yy.copyFrom(e.l00),this.yy.scaleInPlace(.886277).subtractInPlace(z.Vector3[0]).subtractInPlace(z.Vector3[1]),this.zz.copyFrom(e.l00),z.Vector3[0].copyFrom(e.l20).scaleInPlace(.495417),this.zz.scaleInPlace(.886277).addInPlace(z.Vector3[0]),this.yz.copyFrom(e.l2_1),this.yz.scaleInPlace(.858086).scaleInPlace(-1),this.zx.copyFrom(e.l21),this.zx.scaleInPlace(.858086).scaleInPlace(-1),this.xy.copyFrom(e.l2_2),this.xy.scaleInPlace(.858086),this.scaleInPlace(1/Math.PI),this}static FromHarmonics(e){return(new xn).updateFromHarmonics(e)}static FromArray(e){const t=new xn;return U.FromArrayToRef(e[0],0,t.x),U.FromArrayToRef(e[1],0,t.y),U.FromArrayToRef(e[2],0,t.z),U.FromArrayToRef(e[3],0,t.xx),U.FromArrayToRef(e[4],0,t.yy),U.FromArrayToRef(e[5],0,t.zz),U.FromArrayToRef(e[6],0,t.yz),U.FromArrayToRef(e[7],0,t.zx),U.FromArrayToRef(e[8],0,t.xy),t}}class Mn{constructor(e,t,s,i){this.name=e,this.worldAxisForNormal=t,this.worldAxisForFileX=s,this.worldAxisForFileY=i}}class In{static ConvertCubeMapTextureToSphericalPolynomial(e){if(!e.isCube)return null;e.getScene()?.getEngine().flushFramebuffer();const t=e.getSize().width,s=e.readPixels(0,void 0,void 0,!1),i=e.readPixels(1,void 0,void 0,!1);let r,n;e.isRenderTarget?(r=e.readPixels(3,void 0,void 0,!1),n=e.readPixels(2,void 0,void 0,!1)):(r=e.readPixels(2,void 0,void 0,!1),n=e.readPixels(3,void 0,void 0,!1));const a=e.readPixels(4,void 0,void 0,!1),o=e.readPixels(5,void 0,void 0,!1),h=e.gammaSpace,l=Ze.TEXTUREFORMAT_RGBA;let c=Ze.TEXTURETYPE_UNSIGNED_INT;return e.textureType!=Ze.TEXTURETYPE_FLOAT&&e.textureType!=Ze.TEXTURETYPE_HALF_FLOAT||(c=Ze.TEXTURETYPE_FLOAT),new Promise((e=>{Promise.all([i,s,r,n,a,o]).then((([s,i,r,n,a,o])=>{const u={size:t,right:i,left:s,up:r,down:n,front:a,back:o,format:l,type:c,gammaSpace:h};e(this.ConvertCubeMapToSphericalPolynomial(u))}))}))}static _AreaElement(e,t){return Math.atan2(e*t,Math.sqrt(e*e+t*t+1))}static ConvertCubeMapToSphericalPolynomial(e){const t=new Rn;let s=0;const i=2/e.size,r=i,n=.5*i,a=n-1;for(let o=0;o<6;o++){const h=this._FileFaces[o],l=e[h.name];let c=a;const u=e.format===Ze.TEXTUREFORMAT_RGBA?4:3;for(let o=0;o<e.size;o++){let d=a;for(let r=0;r<e.size;r++){const a=h.worldAxisForFileX.scale(d).add(h.worldAxisForFileY.scale(c)).add(h.worldAxisForNormal);a.normalize();const _=this._AreaElement(d-n,c-n)-this._AreaElement(d-n,c+n)-this._AreaElement(d+n,c-n)+this._AreaElement(d+n,c+n);let f=l[o*e.size*u+r*u+0],p=l[o*e.size*u+r*u+1],m=l[o*e.size*u+r*u+2];isNaN(f)&&(f=0),isNaN(p)&&(p=0),isNaN(m)&&(m=0),e.type===Ze.TEXTURETYPE_UNSIGNED_INT&&(f/=255,p/=255,m/=255),e.gammaSpace&&(f=Math.pow(Q.Clamp(f),E),p=Math.pow(Q.Clamp(p),E),m=Math.pow(Q.Clamp(m),E));const g=this.MAX_HDRI_VALUE;if(this.PRESERVE_CLAMPED_COLORS){const e=Math.max(f,p,m);if(e>g){const t=g/e;f*=t,p*=t,m*=t}}else f=Q.Clamp(f,0,g),p=Q.Clamp(p,0,g),m=Q.Clamp(m,0,g);const T=new ee(f,p,m);t.addLight(a,T,_),s+=_,d+=i}c+=r}}const o=6*(4*Math.PI)/6/s;return t.scaleInPlace(o),t.convertIncidentRadianceToIrradiance(),t.convertIrradianceToLambertianRadiance(),xn.FromHarmonics(t)}}In._FileFaces=[new Mn("right",new U(1,0,0),new U(0,0,-1),new U(0,-1,0)),new Mn("left",new U(-1,0,0),new U(0,0,1),new U(0,-1,0)),new Mn("up",new U(0,1,0),new U(1,0,0),new U(0,0,1)),new Mn("down",new U(0,-1,0),new U(1,0,0),new U(0,0,-1)),new Mn("front",new U(0,0,1),new U(1,0,0),new U(0,-1,0)),new Mn("back",new U(0,0,-1),new U(-1,0,0),new U(0,-1,0))],In.MAX_HDRI_VALUE=4096,In.PRESERVE_CLAMPED_COLORS=!1,Pr.prototype.forceSphericalPolynomialsRecompute=function(){this._texture&&(this._texture._sphericalPolynomial=null,this._texture._sphericalPolynomialPromise=null,this._texture._sphericalPolynomialComputed=!1)},Object.defineProperty(Pr.prototype,"sphericalPolynomial",{get:function(){if(this._texture){if(this._texture._sphericalPolynomial||this._texture._sphericalPolynomialComputed)return this._texture._sphericalPolynomial;if(this._texture.isReady)return this._texture._sphericalPolynomialPromise||(this._texture._sphericalPolynomialPromise=In.ConvertCubeMapTextureToSphericalPolynomial(this),null===this._texture._sphericalPolynomialPromise?this._texture._sphericalPolynomialComputed=!0:this._texture._sphericalPolynomialPromise.then((e=>{this._texture._sphericalPolynomial=e,this._texture._sphericalPolynomialComputed=!0}))),null}return null},set:function(e){this._texture&&(this._texture._sphericalPolynomial=e)},enumerable:!0,configurable:!0});class Sn{constructor(){this._defines={},this._currentRank=32,this._maxRank=-1,this._mesh=null}unBindMesh(){this._mesh=null}addFallback(e,t){this._defines[e]||(e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e),this._defines[e]=new Array),this._defines[e].push(t)}addCPUSkinningFallback(e,t){this._mesh=t,e<this._currentRank&&(this._currentRank=e),e>this._maxRank&&(this._maxRank=e)}get hasMoreFallbacks(){return this._currentRank<=this._maxRank}reduce(e,t){if(this._mesh&&this._mesh.computeBonesUsingShaders&&this._mesh.numBoneInfluencers>0){this._mesh.computeBonesUsingShaders=!1,e=e.replace("#define NUM_BONE_INFLUENCERS "+this._mesh.numBoneInfluencers,"#define NUM_BONE_INFLUENCERS 0"),t._bonesComputationForcedToCPU=!0;const s=this._mesh.getScene();for(let e=0;e<s.meshes.length;e++){const i=s.meshes[e];if(i.material){if(i.computeBonesUsingShaders&&0!==i.numBoneInfluencers)if(i.material.getEffect()===t)i.computeBonesUsingShaders=!1;else if(i.subMeshes)for(const e of i.subMeshes){if(e.effect===t){i.computeBonesUsingShaders=!1;break}}}else!this._mesh.material&&i.computeBonesUsingShaders&&i.numBoneInfluencers>0&&(i.computeBonesUsingShaders=!1)}}else{const t=this._defines[this._currentRank];if(t)for(let s=0;s<t.length;s++)e=e.replace("#define "+t[s],"");this._currentRank++}return e}}class vn extends hn{constructor(){super(...arguments),this.CLEARCOAT=!1,this.CLEARCOAT_DEFAULTIOR=!1,this.CLEARCOAT_TEXTURE=!1,this.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this.CLEARCOAT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,this.CLEARCOAT_BUMP=!1,this.CLEARCOAT_BUMPDIRECTUV=0,this.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,this.CLEARCOAT_REMAP_F0=!1,this.CLEARCOAT_TINT=!1,this.CLEARCOAT_TINT_TEXTURE=!1,this.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,this.CLEARCOAT_TINT_GAMMATEXTURE=!1}}class Cn extends _n{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRClearCoat",100,new vn,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.roughness=0,this._indexOfRefraction=Cn._DefaultIndexOfRefraction,this.indexOfRefraction=Cn._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._textureRoughness=null,this.textureRoughness=null,this._remapF0OnInterfaceChange=!0,this.remapF0OnInterfaceChange=!0,this._bumpTexture=null,this.bumpTexture=null,this._isTintEnabled=!1,this.isTintEnabled=!1,this.tintColor=ee.White(),this.tintColorAtDistance=1,this.tintThickness=1,this._tintTexture=null,this.tintTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[Ze.MATERIAL_TextureDirtyFlag]}isReadyForSubMesh(e,t,s){if(!this._isEnabled)return!0;const i=this._material._disableBumpMap;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&Tn.ClearCoatTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&Tn.ClearCoatTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1;if(s.getCaps().standardDerivatives&&this._bumpTexture&&Tn.ClearCoatBumpTextureEnabled&&!i&&!this._bumpTexture.isReady())return!1;if(this._isTintEnabled&&this._tintTexture&&Tn.ClearCoatTintTextureEnabled&&!this._tintTexture.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.CLEARCOAT=!0,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e.CLEARCOAT_REMAP_F0=this._remapF0OnInterfaceChange,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Tn.ClearCoatTextureEnabled?Ws(this._texture,e,"CLEARCOAT_TEXTURE"):e.CLEARCOAT_TEXTURE=!1,this._textureRoughness&&Tn.ClearCoatTextureEnabled?Ws(this._textureRoughness,e,"CLEARCOAT_TEXTURE_ROUGHNESS"):e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,this._bumpTexture&&Tn.ClearCoatBumpTextureEnabled?Ws(this._bumpTexture,e,"CLEARCOAT_BUMP"):e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_DEFAULTIOR=this._indexOfRefraction===Cn._DefaultIndexOfRefraction,this._isTintEnabled?(e.CLEARCOAT_TINT=!0,this._tintTexture&&Tn.ClearCoatTintTextureEnabled?(Ws(this._tintTexture,e,"CLEARCOAT_TINT_TEXTURE"),e.CLEARCOAT_TINT_GAMMATEXTURE=this._tintTexture.gammaSpace):e.CLEARCOAT_TINT_TEXTURE=!1):(e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1))):(e.CLEARCOAT=!1,e.CLEARCOAT_TEXTURE=!1,e.CLEARCOAT_TEXTURE_ROUGHNESS=!1,e.CLEARCOAT_BUMP=!1,e.CLEARCOAT_TINT=!1,e.CLEARCOAT_TINT_TEXTURE=!1,e.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.CLEARCOAT_DEFAULTIOR=!1,e.CLEARCOAT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TEXTURE_ROUGHNESSDIRECTUV=0,e.CLEARCOAT_BUMPDIRECTUV=0,e.CLEARCOAT_REMAP_F0=!1,e.CLEARCOAT_TINT_TEXTUREDIRECTUV=0,e.CLEARCOAT_TINT_GAMMATEXTURE=!1)}bindForSubMesh(e,t,s,i){if(!this._isEnabled)return;const r=i.materialDefines,n=this._material.isFrozen,a=this._material._disableBumpMap,o=this._material._invertNormalMapX,h=this._material._invertNormalMapY;if(!e.useUbo||!n||!e.isSync){(this._texture||this._textureRoughness)&&Tn.ClearCoatTextureEnabled&&(e.updateFloat4("vClearCoatInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._textureRoughness?.coordinatesIndex??0,this._textureRoughness?.level??0),this._texture&&Ys(this._texture,e,"clearCoat"),this._textureRoughness&&!r.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&Ys(this._textureRoughness,e,"clearCoatRoughness")),this._bumpTexture&&s.getCaps().standardDerivatives&&Tn.ClearCoatTextureEnabled&&!a&&(e.updateFloat2("vClearCoatBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level),Ys(this._bumpTexture,e,"clearCoatBump"),t._mirroredCameraPosition?e.updateFloat2("vClearCoatTangentSpaceParams",o?1:-1,h?1:-1):e.updateFloat2("vClearCoatTangentSpaceParams",o?-1:1,h?-1:1)),this._tintTexture&&Tn.ClearCoatTintTextureEnabled&&(e.updateFloat2("vClearCoatTintInfos",this._tintTexture.coordinatesIndex,this._tintTexture.level),Ys(this._tintTexture,e,"clearCoatTint")),e.updateFloat2("vClearCoatParams",this.intensity,this.roughness);const i=1-this._indexOfRefraction,n=1+this._indexOfRefraction,l=Math.pow(-i/n,2),c=1/this._indexOfRefraction;e.updateFloat4("vClearCoatRefractionParams",l,c,i,n),this._isTintEnabled&&(e.updateFloat4("vClearCoatTintParams",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintThickness)),e.updateFloat("clearCoatColorAtDistance",Math.max(1e-5,this.tintColorAtDistance)))}t.texturesEnabled&&(this._texture&&Tn.ClearCoatTextureEnabled&&e.setTexture("clearCoatSampler",this._texture),this._textureRoughness&&!r.CLEARCOAT_USE_ROUGHNESS_FROM_MAINTEXTURE&&Tn.ClearCoatTextureEnabled&&e.setTexture("clearCoatRoughnessSampler",this._textureRoughness),this._bumpTexture&&s.getCaps().standardDerivatives&&Tn.ClearCoatBumpTextureEnabled&&!a&&e.setTexture("clearCoatBumpSampler",this._bumpTexture),this._isTintEnabled&&this._tintTexture&&Tn.ClearCoatTintTextureEnabled&&e.setTexture("clearCoatTintSampler",this._tintTexture))}hasTexture(e){return this._texture===e||(this._textureRoughness===e||(this._bumpTexture===e||this._tintTexture===e))}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness),this._bumpTexture&&e.push(this._bumpTexture),this._tintTexture&&e.push(this._tintTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._tintTexture&&this._tintTexture.animations&&this._tintTexture.animations.length>0&&e.push(this._tintTexture)}dispose(e){e&&(this._texture?.dispose(),this._textureRoughness?.dispose(),this._bumpTexture?.dispose(),this._tintTexture?.dispose())}getClassName(){return"PBRClearCoatConfiguration"}addFallbacks(e,t,s){return e.CLEARCOAT_BUMP&&t.addFallback(s++,"CLEARCOAT_BUMP"),e.CLEARCOAT_TINT&&t.addFallback(s++,"CLEARCOAT_TINT"),e.CLEARCOAT&&t.addFallback(s++,"CLEARCOAT"),s}getSamplers(e){e.push("clearCoatSampler","clearCoatRoughnessSampler","clearCoatBumpSampler","clearCoatTintSampler")}getUniforms(){return{ubo:[{name:"vClearCoatParams",size:2,type:"vec2"},{name:"vClearCoatRefractionParams",size:4,type:"vec4"},{name:"vClearCoatInfos",size:4,type:"vec4"},{name:"clearCoatMatrix",size:16,type:"mat4"},{name:"clearCoatRoughnessMatrix",size:16,type:"mat4"},{name:"vClearCoatBumpInfos",size:2,type:"vec2"},{name:"vClearCoatTangentSpaceParams",size:2,type:"vec2"},{name:"clearCoatBumpMatrix",size:16,type:"mat4"},{name:"vClearCoatTintParams",size:4,type:"vec4"},{name:"clearCoatColorAtDistance",size:1,type:"float"},{name:"vClearCoatTintInfos",size:2,type:"vec2"},{name:"clearCoatTintMatrix",size:16,type:"mat4"}]}}}Cn._DefaultIndexOfRefraction=1.5,e([a(),n("_markAllSubMeshesAsTexturesDirty")],Cn.prototype,"isEnabled",void 0),e([a()],Cn.prototype,"intensity",void 0),e([a()],Cn.prototype,"roughness",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],Cn.prototype,"indexOfRefraction",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],Cn.prototype,"texture",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],Cn.prototype,"useRoughnessFromMainTexture",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],Cn.prototype,"textureRoughness",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],Cn.prototype,"remapF0OnInterfaceChange",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],Cn.prototype,"bumpTexture",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],Cn.prototype,"isTintEnabled",void 0),e([h()],Cn.prototype,"tintColor",void 0),e([a()],Cn.prototype,"tintColorAtDistance",void 0),e([a()],Cn.prototype,"tintThickness",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],Cn.prototype,"tintTexture",void 0);class Pn extends hn{constructor(){super(...arguments),this.IRIDESCENCE=!1,this.IRIDESCENCE_TEXTURE=!1,this.IRIDESCENCE_TEXTUREDIRECTUV=0,this.IRIDESCENCE_THICKNESS_TEXTURE=!1,this.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0}}class On extends _n{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRIridescence",110,new Pn,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.minimumThickness=On._DefaultMinimumThickness,this.maximumThickness=On._DefaultMaximumThickness,this.indexOfRefraction=On._DefaultIndexOfRefraction,this._texture=null,this.texture=null,this._thicknessTexture=null,this.thicknessTexture=null,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[Ze.MATERIAL_TextureDirtyFlag]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&Tn.IridescenceTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._thicknessTexture&&Tn.IridescenceTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.IRIDESCENCE=!0,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Tn.IridescenceTextureEnabled?Ws(this._texture,e,"IRIDESCENCE_TEXTURE"):e.IRIDESCENCE_TEXTURE=!1,this._thicknessTexture&&Tn.IridescenceTextureEnabled?Ws(this._thicknessTexture,e,"IRIDESCENCE_THICKNESS_TEXTURE"):e.IRIDESCENCE_THICKNESS_TEXTURE=!1)):(e.IRIDESCENCE=!1,e.IRIDESCENCE_TEXTURE=!1,e.IRIDESCENCE_THICKNESS_TEXTURE=!1,e.IRIDESCENCE_TEXTUREDIRECTUV=0,e.IRIDESCENCE_THICKNESS_TEXTUREDIRECTUV=0)}bindForSubMesh(e,t){if(!this._isEnabled)return;const s=this._material.isFrozen;e.useUbo&&s&&e.isSync||((this._texture||this._thicknessTexture)&&Tn.IridescenceTextureEnabled&&(e.updateFloat4("vIridescenceInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._thicknessTexture?.coordinatesIndex??0,this._thicknessTexture?.level??0),this._texture&&Ys(this._texture,e,"iridescence"),this._thicknessTexture&&Ys(this._thicknessTexture,e,"iridescenceThickness")),e.updateFloat4("vIridescenceParams",this.intensity,this.indexOfRefraction,this.minimumThickness,this.maximumThickness)),t.texturesEnabled&&(this._texture&&Tn.IridescenceTextureEnabled&&e.setTexture("iridescenceSampler",this._texture),this._thicknessTexture&&Tn.IridescenceTextureEnabled&&e.setTexture("iridescenceThicknessSampler",this._thicknessTexture))}hasTexture(e){return this._texture===e||this._thicknessTexture===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._thicknessTexture&&e.push(this._thicknessTexture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture)}dispose(e){e&&(this._texture?.dispose(),this._thicknessTexture?.dispose())}getClassName(){return"PBRIridescenceConfiguration"}addFallbacks(e,t,s){return e.IRIDESCENCE&&t.addFallback(s++,"IRIDESCENCE"),s}getSamplers(e){e.push("iridescenceSampler","iridescenceThicknessSampler")}getUniforms(){return{ubo:[{name:"vIridescenceParams",size:4,type:"vec4"},{name:"vIridescenceInfos",size:4,type:"vec4"},{name:"iridescenceMatrix",size:16,type:"mat4"},{name:"iridescenceThicknessMatrix",size:16,type:"mat4"}]}}}On._DefaultMinimumThickness=100,On._DefaultMaximumThickness=400,On._DefaultIndexOfRefraction=1.3,e([a(),n("_markAllSubMeshesAsTexturesDirty")],On.prototype,"isEnabled",void 0),e([a()],On.prototype,"intensity",void 0),e([a()],On.prototype,"minimumThickness",void 0),e([a()],On.prototype,"maximumThickness",void 0),e([a()],On.prototype,"indexOfRefraction",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],On.prototype,"texture",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],On.prototype,"thicknessTexture",void 0);class Dn extends hn{constructor(){super(...arguments),this.ANISOTROPIC=!1,this.ANISOTROPIC_TEXTURE=!1,this.ANISOTROPIC_TEXTUREDIRECTUV=0,this.ANISOTROPIC_LEGACY=!1,this.MAINUV1=!1}}class Ln extends _n{set angle(e){this.direction.x=Math.cos(e),this.direction.y=Math.sin(e)}get angle(){return Math.atan2(this.direction.y,this.direction.x)}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markAllSubMeshesAsMiscDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsMiscDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRAnisotropic",110,new Dn,t),this._isEnabled=!1,this.isEnabled=!1,this.intensity=1,this.direction=new B(1,0),this._texture=null,this.texture=null,this._legacy=!1,this.legacy=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[Ze.MATERIAL_TextureDirtyFlag],this._internalMarkAllSubMeshesAsMiscDirty=e._dirtyCallbacks[Ze.MATERIAL_MiscDirtyFlag]}isReadyForSubMesh(e,t){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&this._texture&&Tn.AnisotropicTextureEnabled&&!this._texture.isReadyOrNotBlocking())}prepareDefinesBeforeAttributes(e,t,s){this._isEnabled?(e.ANISOTROPIC=this._isEnabled,this._isEnabled&&!s.isVerticesDataPresent(ns.TangentKind)&&(e._needUVs=!0,e.MAINUV1=!0),e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Tn.AnisotropicTextureEnabled?Ws(this._texture,e,"ANISOTROPIC_TEXTURE"):e.ANISOTROPIC_TEXTURE=!1),e._areMiscDirty&&(e.ANISOTROPIC_LEGACY=this._legacy)):(e.ANISOTROPIC=!1,e.ANISOTROPIC_TEXTURE=!1,e.ANISOTROPIC_TEXTUREDIRECTUV=0,e.ANISOTROPIC_LEGACY=!1)}bindForSubMesh(e,t){if(!this._isEnabled)return;const s=this._material.isFrozen;e.useUbo&&s&&e.isSync||(this._texture&&Tn.AnisotropicTextureEnabled&&(e.updateFloat2("vAnisotropyInfos",this._texture.coordinatesIndex,this._texture.level),Ys(this._texture,e,"anisotropy")),e.updateFloat3("vAnisotropy",this.direction.x,this.direction.y,this.intensity)),t.texturesEnabled&&this._texture&&Tn.AnisotropicTextureEnabled&&e.setTexture("anisotropySampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture&&this._texture.dispose()}getClassName(){return"PBRAnisotropicConfiguration"}addFallbacks(e,t,s){return e.ANISOTROPIC&&t.addFallback(s++,"ANISOTROPIC"),s}getSamplers(e){e.push("anisotropySampler")}getUniforms(){return{ubo:[{name:"vAnisotropy",size:3,type:"vec3"},{name:"vAnisotropyInfos",size:2,type:"vec2"},{name:"anisotropyMatrix",size:16,type:"mat4"}]}}parse(e,t,s){super.parse(e,t,s),void 0===e.legacy&&(this.legacy=!0)}}e([a(),n("_markAllSubMeshesAsTexturesDirty")],Ln.prototype,"isEnabled",void 0),e([a()],Ln.prototype,"intensity",void 0),e([l()],Ln.prototype,"direction",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],Ln.prototype,"texture",void 0),e([a(),n("_markAllSubMeshesAsMiscDirty")],Ln.prototype,"legacy",void 0);class Fn extends hn{constructor(){super(...arguments),this.SHEEN=!1,this.SHEEN_TEXTURE=!1,this.SHEEN_GAMMATEXTURE=!1,this.SHEEN_TEXTURE_ROUGHNESS=!1,this.SHEEN_TEXTUREDIRECTUV=0,this.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0,this.SHEEN_LINKWITHALBEDO=!1,this.SHEEN_ROUGHNESS=!1,this.SHEEN_ALBEDOSCALING=!1,this.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1}}class Nn extends _n{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"Sheen",120,new Fn,t),this._isEnabled=!1,this.isEnabled=!1,this._linkSheenWithAlbedo=!1,this.linkSheenWithAlbedo=!1,this.intensity=1,this.color=ee.White(),this._texture=null,this.texture=null,this._useRoughnessFromMainTexture=!0,this.useRoughnessFromMainTexture=!0,this._roughness=null,this.roughness=null,this._textureRoughness=null,this.textureRoughness=null,this._albedoScaling=!1,this.albedoScaling=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[Ze.MATERIAL_TextureDirtyFlag]}isReadyForSubMesh(e,t){if(!this._isEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._texture&&Tn.SheenTextureEnabled&&!this._texture.isReadyOrNotBlocking())return!1;if(this._textureRoughness&&Tn.SheenTextureEnabled&&!this._textureRoughness.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){this._isEnabled?(e.SHEEN=!0,e.SHEEN_LINKWITHALBEDO=this._linkSheenWithAlbedo,e.SHEEN_ROUGHNESS=null!==this._roughness,e.SHEEN_ALBEDOSCALING=this._albedoScaling,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=this._useRoughnessFromMainTexture,e._areTexturesDirty&&t.texturesEnabled&&(this._texture&&Tn.SheenTextureEnabled?(Ws(this._texture,e,"SHEEN_TEXTURE"),e.SHEEN_GAMMATEXTURE=this._texture.gammaSpace):e.SHEEN_TEXTURE=!1,this._textureRoughness&&Tn.SheenTextureEnabled?Ws(this._textureRoughness,e,"SHEEN_TEXTURE_ROUGHNESS"):e.SHEEN_TEXTURE_ROUGHNESS=!1)):(e.SHEEN=!1,e.SHEEN_TEXTURE=!1,e.SHEEN_TEXTURE_ROUGHNESS=!1,e.SHEEN_LINKWITHALBEDO=!1,e.SHEEN_ROUGHNESS=!1,e.SHEEN_ALBEDOSCALING=!1,e.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE=!1,e.SHEEN_GAMMATEXTURE=!1,e.SHEEN_TEXTUREDIRECTUV=0,e.SHEEN_TEXTURE_ROUGHNESSDIRECTUV=0)}bindForSubMesh(e,t,s,i){if(!this._isEnabled)return;const r=i.materialDefines,n=this._material.isFrozen;e.useUbo&&n&&e.isSync||((this._texture||this._textureRoughness)&&Tn.SheenTextureEnabled&&(e.updateFloat4("vSheenInfos",this._texture?.coordinatesIndex??0,this._texture?.level??0,this._textureRoughness?.coordinatesIndex??0,this._textureRoughness?.level??0),this._texture&&Ys(this._texture,e,"sheen"),this._textureRoughness&&!r.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&Ys(this._textureRoughness,e,"sheenRoughness")),e.updateFloat4("vSheenColor",this.color.r,this.color.g,this.color.b,this.intensity),null!==this._roughness&&e.updateFloat("vSheenRoughness",this._roughness)),t.texturesEnabled&&(this._texture&&Tn.SheenTextureEnabled&&e.setTexture("sheenSampler",this._texture),this._textureRoughness&&!r.SHEEN_USE_ROUGHNESS_FROM_MAINTEXTURE&&Tn.SheenTextureEnabled&&e.setTexture("sheenRoughnessSampler",this._textureRoughness))}hasTexture(e){return this._texture===e||this._textureRoughness===e}getActiveTextures(e){this._texture&&e.push(this._texture),this._textureRoughness&&e.push(this._textureRoughness)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture),this._textureRoughness&&this._textureRoughness.animations&&this._textureRoughness.animations.length>0&&e.push(this._textureRoughness)}dispose(e){e&&(this._texture?.dispose(),this._textureRoughness?.dispose())}getClassName(){return"PBRSheenConfiguration"}addFallbacks(e,t,s){return e.SHEEN&&t.addFallback(s++,"SHEEN"),s}getSamplers(e){e.push("sheenSampler","sheenRoughnessSampler")}getUniforms(){return{ubo:[{name:"vSheenColor",size:4,type:"vec4"},{name:"vSheenRoughness",size:1,type:"float"},{name:"vSheenInfos",size:4,type:"vec4"},{name:"sheenMatrix",size:16,type:"mat4"},{name:"sheenRoughnessMatrix",size:16,type:"mat4"}]}}}e([a(),n("_markAllSubMeshesAsTexturesDirty")],Nn.prototype,"isEnabled",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],Nn.prototype,"linkSheenWithAlbedo",void 0),e([a()],Nn.prototype,"intensity",void 0),e([h()],Nn.prototype,"color",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],Nn.prototype,"texture",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],Nn.prototype,"useRoughnessFromMainTexture",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],Nn.prototype,"roughness",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],Nn.prototype,"textureRoughness",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],Nn.prototype,"albedoScaling",void 0);class wn extends hn{constructor(){super(...arguments),this.SUBSURFACE=!1,this.SS_REFRACTION=!1,this.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,this.SS_TRANSLUCENCY=!1,this.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,this.SS_SCATTERING=!1,this.SS_DISPERSION=!1,this.SS_THICKNESSANDMASK_TEXTURE=!1,this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,this.SS_HAS_THICKNESS=!1,this.SS_REFRACTIONINTENSITY_TEXTURE=!1,this.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,this.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,this.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,this.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0,this.SS_REFRACTIONMAP_3D=!1,this.SS_REFRACTIONMAP_OPPOSITEZ=!1,this.SS_LODINREFRACTIONALPHA=!1,this.SS_GAMMAREFRACTION=!1,this.SS_RGBDREFRACTION=!1,this.SS_LINEARSPECULARREFRACTION=!1,this.SS_LINKREFRACTIONTOTRANSPARENCY=!1,this.SS_ALBEDOFORREFRACTIONTINT=!1,this.SS_ALBEDOFORTRANSLUCENCYTINT=!1,this.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,this.SS_USE_THICKNESS_AS_DEPTH=!1,this.SS_USE_GLTF_TEXTURES=!1}}class Bn extends _n{get scatteringDiffusionProfile(){return this._scene.subSurfaceConfiguration?this._scene.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex]:null}set scatteringDiffusionProfile(e){this._scene.enableSubSurfaceForPrePass()&&e&&(this._scatteringDiffusionProfileIndex=this._scene.subSurfaceConfiguration.addDiffusionProfile(e))}get volumeIndexOfRefraction(){return this._volumeIndexOfRefraction>=1?this._volumeIndexOfRefraction:this._indexOfRefraction}set volumeIndexOfRefraction(e){this._volumeIndexOfRefraction=e>=1?e:-1}_markAllSubMeshesAsTexturesDirty(){this._enable(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}_markScenePrePassDirty(){this._internalMarkAllSubMeshesAsTexturesDirty(),this._internalMarkScenePrePassDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"PBRSubSurface",130,new wn,t),this._isRefractionEnabled=!1,this.isRefractionEnabled=!1,this._isTranslucencyEnabled=!1,this.isTranslucencyEnabled=!1,this._isDispersionEnabled=!1,this.isDispersionEnabled=!1,this._isScatteringEnabled=!1,this.isScatteringEnabled=!1,this._scatteringDiffusionProfileIndex=0,this.refractionIntensity=1,this.translucencyIntensity=1,this.useAlbedoToTintRefraction=!1,this.useAlbedoToTintTranslucency=!1,this._thicknessTexture=null,this.thicknessTexture=null,this._refractionTexture=null,this.refractionTexture=null,this._indexOfRefraction=1.5,this.indexOfRefraction=1.5,this._volumeIndexOfRefraction=-1,this._invertRefractionY=!1,this.invertRefractionY=!1,this._linkRefractionWithTransparency=!1,this.linkRefractionWithTransparency=!1,this.minimumThickness=0,this.maximumThickness=1,this.useThicknessAsDepth=!1,this.tintColor=ee.White(),this.tintColorAtDistance=1,this.dispersion=0,this.diffusionDistance=ee.White(),this._useMaskFromThicknessTexture=!1,this.useMaskFromThicknessTexture=!1,this._refractionIntensityTexture=null,this.refractionIntensityTexture=null,this._translucencyIntensityTexture=null,this.translucencyIntensityTexture=null,this.translucencyColor=null,this._translucencyColorTexture=null,this.translucencyColorTexture=null,this._useGltfStyleTextures=!0,this.useGltfStyleTextures=!0,this._scene=e.getScene(),this.registerForExtraEvents=!0,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[Ze.MATERIAL_TextureDirtyFlag],this._internalMarkScenePrePassDirty=e._dirtyCallbacks[Ze.MATERIAL_PrePassDirtyFlag]}isReadyForSubMesh(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return!0;if(e._areTexturesDirty&&t.texturesEnabled){if(this._thicknessTexture&&Tn.ThicknessTextureEnabled&&!this._thicknessTexture.isReadyOrNotBlocking())return!1;if(this._translucencyColorTexture&&Tn.TranslucencyColorTextureEnabled&&!this._translucencyColorTexture.isReadyOrNotBlocking())return!1;if(this._translucencyIntensityTexture&&Tn.TranslucencyIntensityTextureEnabled&&!this._translucencyIntensityTexture.isReadyOrNotBlocking())return!1;const e=this._getRefractionTexture(t);if(e&&Tn.RefractionTextureEnabled&&!e.isReadyOrNotBlocking())return!1}return!0}prepareDefinesBeforeAttributes(e,t){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return e.SUBSURFACE=!1,e.SS_DISPERSION=!1,e.SS_TRANSLUCENCY=!1,e.SS_SCATTERING=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_THICKNESSANDMASK_TEXTUREDIRECTUV=0,e.SS_HAS_THICKNESS=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTUREDIRECTUV=0,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTUREDIRECTUV=0,e.SS_REFRACTIONMAP_3D=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,void(e.SS_TRANSLUCENCYCOLOR_TEXTUREDIRECTUV=0);if(e._areTexturesDirty){if(e.SUBSURFACE=!0,e.SS_DISPERSION=this._isDispersionEnabled,e.SS_TRANSLUCENCY=this._isTranslucencyEnabled,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_SCATTERING=this._isScatteringEnabled,e.SS_THICKNESSANDMASK_TEXTURE=!1,e.SS_REFRACTIONINTENSITY_TEXTURE=!1,e.SS_TRANSLUCENCYINTENSITY_TEXTURE=!1,e.SS_HAS_THICKNESS=!1,e.SS_USE_GLTF_TEXTURES=!1,e.SS_REFRACTION=!1,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=!1,e.SS_REFRACTIONMAP_3D=!1,e.SS_GAMMAREFRACTION=!1,e.SS_RGBDREFRACTION=!1,e.SS_LINEARSPECULARREFRACTION=!1,e.SS_REFRACTIONMAP_OPPOSITEZ=!1,e.SS_LODINREFRACTIONALPHA=!1,e.SS_LINKREFRACTIONTOTRANSPARENCY=!1,e.SS_ALBEDOFORREFRACTIONTINT=!1,e.SS_ALBEDOFORTRANSLUCENCYTINT=!1,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=!1,e.SS_USE_THICKNESS_AS_DEPTH=!1,e.SS_TRANSLUCENCYCOLOR_TEXTURE=!1,e._areTexturesDirty&&t.texturesEnabled&&(this._thicknessTexture&&Tn.ThicknessTextureEnabled&&Ws(this._thicknessTexture,e,"SS_THICKNESSANDMASK_TEXTURE"),this._refractionIntensityTexture&&Tn.RefractionIntensityTextureEnabled&&Ws(this._refractionIntensityTexture,e,"SS_REFRACTIONINTENSITY_TEXTURE"),this._translucencyIntensityTexture&&Tn.TranslucencyIntensityTextureEnabled&&Ws(this._translucencyIntensityTexture,e,"SS_TRANSLUCENCYINTENSITY_TEXTURE"),this._translucencyColorTexture&&Tn.TranslucencyColorTextureEnabled&&Ws(this._translucencyColorTexture,e,"SS_TRANSLUCENCYCOLOR_TEXTURE")),e.SS_HAS_THICKNESS=this.maximumThickness-this.minimumThickness!=0,e.SS_USE_GLTF_TEXTURES=this._useGltfStyleTextures,e.SS_REFRACTION_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._refractionIntensityTexture,e.SS_TRANSLUCENCY_USE_INTENSITY_FROM_THICKNESS=this._useMaskFromThicknessTexture&&!this._translucencyIntensityTexture,this._isRefractionEnabled&&t.texturesEnabled){const s=this._getRefractionTexture(t);s&&Tn.RefractionTextureEnabled&&(e.SS_REFRACTION=!0,e.SS_REFRACTIONMAP_3D=s.isCube,e.SS_GAMMAREFRACTION=s.gammaSpace,e.SS_RGBDREFRACTION=s.isRGBD,e.SS_LINEARSPECULARREFRACTION=s.linearSpecularLOD,e.SS_REFRACTIONMAP_OPPOSITEZ=this._scene.useRightHandedSystem&&s.isCube?!s.invertZ:s.invertZ,e.SS_LODINREFRACTIONALPHA=s.lodLevelInAlpha,e.SS_LINKREFRACTIONTOTRANSPARENCY=this._linkRefractionWithTransparency,e.SS_ALBEDOFORREFRACTIONTINT=this.useAlbedoToTintRefraction,e.SS_USE_LOCAL_REFRACTIONMAP_CUBIC=s.isCube&&s.boundingBoxSize,e.SS_USE_THICKNESS_AS_DEPTH=this.useThicknessAsDepth)}this._isTranslucencyEnabled&&(e.SS_ALBEDOFORTRANSLUCENCYTINT=this.useAlbedoToTintTranslucency)}}hardBindForSubMesh(e,t,s,i){if(this._isRefractionEnabled||this._isTranslucencyEnabled||this._isScatteringEnabled)if(0===this.maximumThickness&&0===this.minimumThickness)e.updateFloat2("vThicknessParam",0,0);else{i.getRenderingMesh().getWorldMatrix().decompose(z.Vector3[0]);const t=Math.max(Math.abs(z.Vector3[0].x),Math.abs(z.Vector3[0].y),Math.abs(z.Vector3[0].z));e.updateFloat2("vThicknessParam",this.minimumThickness*t,(this.maximumThickness-this.minimumThickness)*t)}}bindForSubMesh(e,t,s,i){if(!this._isRefractionEnabled&&!this._isTranslucencyEnabled&&!this._isScatteringEnabled)return;const r=i.materialDefines,n=this._material.isFrozen,a=this._material.realTimeFiltering,o=r.LODBASEDMICROSFURACE,h=this._getRefractionTexture(t);if(!e.useUbo||!n||!e.isSync){if(this._thicknessTexture&&Tn.ThicknessTextureEnabled&&(e.updateFloat2("vThicknessInfos",this._thicknessTexture.coordinatesIndex,this._thicknessTexture.level),Ys(this._thicknessTexture,e,"thickness")),this._refractionIntensityTexture&&Tn.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&(e.updateFloat2("vRefractionIntensityInfos",this._refractionIntensityTexture.coordinatesIndex,this._refractionIntensityTexture.level),Ys(this._refractionIntensityTexture,e,"refractionIntensity")),this._translucencyColorTexture&&Tn.TranslucencyColorTextureEnabled&&r.SS_TRANSLUCENCYCOLOR_TEXTURE&&(e.updateFloat2("vTranslucencyColorInfos",this._translucencyColorTexture.coordinatesIndex,this._translucencyColorTexture.level),Ys(this._translucencyColorTexture,e,"translucencyColor")),this._translucencyIntensityTexture&&Tn.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&(e.updateFloat2("vTranslucencyIntensityInfos",this._translucencyIntensityTexture.coordinatesIndex,this._translucencyIntensityTexture.level),Ys(this._translucencyIntensityTexture,e,"translucencyIntensity")),h&&Tn.RefractionTextureEnabled){e.updateMatrix("refractionMatrix",h.getRefractionTextureMatrix());let t=1;h.isCube||h.depth&&(t=h.depth);const s=h.getSize().width,i=this.volumeIndexOfRefraction;if(e.updateFloat4("vRefractionInfos",h.level,1/i,t,this._invertRefractionY?-1:1),e.updateFloat4("vRefractionMicrosurfaceInfos",s,h.lodGenerationScale,h.lodGenerationOffset,1/this.indexOfRefraction),a&&e.updateFloat2("vRefractionFilteringInfo",s,Q.Log2(s)),h.boundingBoxSize){const t=h;e.updateVector3("vRefractionPosition",t.boundingBoxPosition),e.updateVector3("vRefractionSize",t.boundingBoxSize)}}this._isScatteringEnabled&&e.updateFloat("scatteringDiffusionProfile",this._scatteringDiffusionProfileIndex),e.updateColor3("vDiffusionDistance",this.diffusionDistance),e.updateFloat4("vTintColor",this.tintColor.r,this.tintColor.g,this.tintColor.b,Math.max(1e-5,this.tintColorAtDistance)),e.updateColor4("vTranslucencyColor",this.translucencyColor??this.tintColor,0),e.updateFloat3("vSubSurfaceIntensity",this.refractionIntensity,this.translucencyIntensity,0),e.updateFloat("dispersion",this.dispersion)}t.texturesEnabled&&(this._thicknessTexture&&Tn.ThicknessTextureEnabled&&e.setTexture("thicknessSampler",this._thicknessTexture),this._refractionIntensityTexture&&Tn.RefractionIntensityTextureEnabled&&r.SS_REFRACTIONINTENSITY_TEXTURE&&e.setTexture("refractionIntensitySampler",this._refractionIntensityTexture),this._translucencyIntensityTexture&&Tn.TranslucencyIntensityTextureEnabled&&r.SS_TRANSLUCENCYINTENSITY_TEXTURE&&e.setTexture("translucencyIntensitySampler",this._translucencyIntensityTexture),this._translucencyColorTexture&&Tn.TranslucencyColorTextureEnabled&&r.SS_TRANSLUCENCYCOLOR_TEXTURE&&e.setTexture("translucencyColorSampler",this._translucencyColorTexture),h&&Tn.RefractionTextureEnabled&&(o?e.setTexture("refractionSampler",h):(e.setTexture("refractionSampler",h._lodTextureMid||h),e.setTexture("refractionSamplerLow",h._lodTextureLow||h),e.setTexture("refractionSamplerHigh",h._lodTextureHigh||h))))}_getRefractionTexture(e){return this._refractionTexture?this._refractionTexture:this._isRefractionEnabled?e.environmentTexture:null}get disableAlphaBlending(){return this._isRefractionEnabled&&this._linkRefractionWithTransparency}fillRenderTargetTextures(e){Tn.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget&&e.push(this._refractionTexture)}hasTexture(e){return this._thicknessTexture===e||(this._refractionTexture===e||(this._refractionIntensityTexture===e||(this._translucencyIntensityTexture===e||this._translucencyColorTexture===e)))}hasRenderTargetTextures(){return!!(Tn.RefractionTextureEnabled&&this._refractionTexture&&this._refractionTexture.isRenderTarget)}getActiveTextures(e){this._thicknessTexture&&e.push(this._thicknessTexture),this._refractionTexture&&e.push(this._refractionTexture),this._translucencyColorTexture&&e.push(this._translucencyColorTexture),this._translucencyIntensityTexture&&e.push(this._translucencyIntensityTexture)}getAnimatables(e){this._thicknessTexture&&this._thicknessTexture.animations&&this._thicknessTexture.animations.length>0&&e.push(this._thicknessTexture),this._refractionTexture&&this._refractionTexture.animations&&this._refractionTexture.animations.length>0&&e.push(this._refractionTexture),this._translucencyColorTexture&&this._translucencyColorTexture.animations&&this._translucencyColorTexture.animations.length>0&&e.push(this._translucencyColorTexture),this._translucencyIntensityTexture&&this._translucencyIntensityTexture.animations&&this._translucencyIntensityTexture.animations.length>0&&e.push(this._translucencyIntensityTexture)}dispose(e){e&&(this._thicknessTexture&&this._thicknessTexture.dispose(),this._refractionTexture&&this._refractionTexture.dispose(),this._translucencyColorTexture&&this._translucencyColorTexture.dispose(),this._translucencyIntensityTexture&&this._translucencyIntensityTexture.dispose())}getClassName(){return"PBRSubSurfaceConfiguration"}addFallbacks(e,t,s){return e.SS_SCATTERING&&t.addFallback(s++,"SS_SCATTERING"),e.SS_TRANSLUCENCY&&t.addFallback(s++,"SS_TRANSLUCENCY"),s}getSamplers(e){e.push("thicknessSampler","refractionIntensitySampler","translucencyIntensitySampler","refractionSampler","refractionSamplerLow","refractionSamplerHigh","translucencyColorSampler")}getUniforms(){return{ubo:[{name:"vRefractionMicrosurfaceInfos",size:4,type:"vec4"},{name:"vRefractionFilteringInfo",size:2,type:"vec2"},{name:"vTranslucencyIntensityInfos",size:2,type:"vec2"},{name:"vRefractionInfos",size:4,type:"vec4"},{name:"refractionMatrix",size:16,type:"mat4"},{name:"vThicknessInfos",size:2,type:"vec2"},{name:"vRefractionIntensityInfos",size:2,type:"vec2"},{name:"thicknessMatrix",size:16,type:"mat4"},{name:"refractionIntensityMatrix",size:16,type:"mat4"},{name:"translucencyIntensityMatrix",size:16,type:"mat4"},{name:"vThicknessParam",size:2,type:"vec2"},{name:"vDiffusionDistance",size:3,type:"vec3"},{name:"vTintColor",size:4,type:"vec4"},{name:"vSubSurfaceIntensity",size:3,type:"vec3"},{name:"vRefractionPosition",size:3,type:"vec3"},{name:"vRefractionSize",size:3,type:"vec3"},{name:"scatteringDiffusionProfile",size:1,type:"float"},{name:"dispersion",size:1,type:"float"},{name:"vTranslucencyColor",size:4,type:"vec4"},{name:"vTranslucencyColorInfos",size:2,type:"vec2"},{name:"translucencyColorMatrix",size:16,type:"mat4"}]}}}e([a(),n("_markAllSubMeshesAsTexturesDirty")],Bn.prototype,"isRefractionEnabled",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],Bn.prototype,"isTranslucencyEnabled",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],Bn.prototype,"isDispersionEnabled",void 0),e([a(),n("_markScenePrePassDirty")],Bn.prototype,"isScatteringEnabled",void 0),e([a()],Bn.prototype,"_scatteringDiffusionProfileIndex",void 0),e([a()],Bn.prototype,"refractionIntensity",void 0),e([a()],Bn.prototype,"translucencyIntensity",void 0),e([a()],Bn.prototype,"useAlbedoToTintRefraction",void 0),e([a()],Bn.prototype,"useAlbedoToTintTranslucency",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],Bn.prototype,"thicknessTexture",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],Bn.prototype,"refractionTexture",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],Bn.prototype,"indexOfRefraction",void 0),e([a()],Bn.prototype,"_volumeIndexOfRefraction",void 0),e([n("_markAllSubMeshesAsTexturesDirty")],Bn.prototype,"volumeIndexOfRefraction",null),e([a(),n("_markAllSubMeshesAsTexturesDirty")],Bn.prototype,"invertRefractionY",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],Bn.prototype,"linkRefractionWithTransparency",void 0),e([a()],Bn.prototype,"minimumThickness",void 0),e([a()],Bn.prototype,"maximumThickness",void 0),e([a()],Bn.prototype,"useThicknessAsDepth",void 0),e([h()],Bn.prototype,"tintColor",void 0),e([a()],Bn.prototype,"tintColorAtDistance",void 0),e([a()],Bn.prototype,"dispersion",void 0),e([h()],Bn.prototype,"diffusionDistance",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],Bn.prototype,"useMaskFromThicknessTexture",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],Bn.prototype,"refractionIntensityTexture",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],Bn.prototype,"translucencyIntensityTexture",void 0),e([h()],Bn.prototype,"translucencyColor",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],Bn.prototype,"translucencyColorTexture",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],Bn.prototype,"useGltfStyleTextures",void 0);class Un extends hn{constructor(){super(...arguments),this.DETAIL=!1,this.DETAILDIRECTUV=0,this.DETAIL_NORMALBLENDMETHOD=0}}class kn extends _n{_markAllSubMeshesAsTexturesDirty(){this._enable(this._isEnabled),this._internalMarkAllSubMeshesAsTexturesDirty()}isCompatible(){return!0}constructor(e,t=!0){super(e,"DetailMap",140,new Un,t),this._texture=null,this.diffuseBlendLevel=1,this.roughnessBlendLevel=1,this.bumpLevel=1,this._normalBlendMethod=$s.MATERIAL_NORMALBLENDMETHOD_WHITEOUT,this._isEnabled=!1,this.isEnabled=!1,this._internalMarkAllSubMeshesAsTexturesDirty=e._dirtyCallbacks[Ze.MATERIAL_TextureDirtyFlag]}isReadyForSubMesh(e,t,s){return!this._isEnabled||!(e._areTexturesDirty&&t.texturesEnabled&&s.getCaps().standardDerivatives&&this._texture&&Tn.DetailTextureEnabled&&!this._texture.isReady())}prepareDefines(e,t){if(this._isEnabled){e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod;const s=t.getEngine();e._areTexturesDirty&&(s.getCaps().standardDerivatives&&this._texture&&Tn.DetailTextureEnabled&&this._isEnabled?(Ws(this._texture,e,"DETAIL"),e.DETAIL_NORMALBLENDMETHOD=this._normalBlendMethod):e.DETAIL=!1)}else e.DETAIL=!1}bindForSubMesh(e,t){if(!this._isEnabled)return;const s=this._material.isFrozen;e.useUbo&&s&&e.isSync||this._texture&&Tn.DetailTextureEnabled&&(e.updateFloat4("vDetailInfos",this._texture.coordinatesIndex,this.diffuseBlendLevel,this.bumpLevel,this.roughnessBlendLevel),Ys(this._texture,e,"detail")),t.texturesEnabled&&this._texture&&Tn.DetailTextureEnabled&&e.setTexture("detailSampler",this._texture)}hasTexture(e){return this._texture===e}getActiveTextures(e){this._texture&&e.push(this._texture)}getAnimatables(e){this._texture&&this._texture.animations&&this._texture.animations.length>0&&e.push(this._texture)}dispose(e){e&&this._texture?.dispose()}getClassName(){return"DetailMapConfiguration"}getSamplers(e){e.push("detailSampler")}getUniforms(){return{ubo:[{name:"vDetailInfos",size:4,type:"vec4"},{name:"detailMatrix",size:16,type:"mat4"}]}}}e([o("detailTexture"),n("_markAllSubMeshesAsTexturesDirty")],kn.prototype,"texture",void 0),e([a()],kn.prototype,"diffuseBlendLevel",void 0),e([a()],kn.prototype,"roughnessBlendLevel",void 0),e([a()],kn.prototype,"bumpLevel",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],kn.prototype,"normalBlendMethod",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],kn.prototype,"isEnabled",void 0);const Gn={effect:null,subMesh:null};class Vn extends hn{constructor(e){super(e),this.PBR=!0,this.NUM_SAMPLES="0",this.REALTIME_FILTERING=!1,this.MAINUV1=!1,this.MAINUV2=!1,this.MAINUV3=!1,this.MAINUV4=!1,this.MAINUV5=!1,this.MAINUV6=!1,this.UV1=!1,this.UV2=!1,this.UV3=!1,this.UV4=!1,this.UV5=!1,this.UV6=!1,this.ALBEDO=!1,this.GAMMAALBEDO=!1,this.ALBEDODIRECTUV=0,this.VERTEXCOLOR=!1,this.BAKED_VERTEX_ANIMATION_TEXTURE=!1,this.AMBIENT=!1,this.AMBIENTDIRECTUV=0,this.AMBIENTINGRAYSCALE=!1,this.OPACITY=!1,this.VERTEXALPHA=!1,this.OPACITYDIRECTUV=0,this.OPACITYRGB=!1,this.ALPHATEST=!1,this.DEPTHPREPASS=!1,this.ALPHABLEND=!1,this.ALPHAFROMALBEDO=!1,this.ALPHATESTVALUE="0.5",this.SPECULAROVERALPHA=!1,this.RADIANCEOVERALPHA=!1,this.ALPHAFRESNEL=!1,this.LINEARALPHAFRESNEL=!1,this.PREMULTIPLYALPHA=!1,this.EMISSIVE=!1,this.EMISSIVEDIRECTUV=0,this.GAMMAEMISSIVE=!1,this.REFLECTIVITY=!1,this.REFLECTIVITY_GAMMA=!1,this.REFLECTIVITYDIRECTUV=0,this.SPECULARTERM=!1,this.MICROSURFACEFROMREFLECTIVITYMAP=!1,this.MICROSURFACEAUTOMATIC=!1,this.LODBASEDMICROSFURACE=!1,this.MICROSURFACEMAP=!1,this.MICROSURFACEMAPDIRECTUV=0,this.METALLICWORKFLOW=!1,this.ROUGHNESSSTOREINMETALMAPALPHA=!1,this.ROUGHNESSSTOREINMETALMAPGREEN=!1,this.METALLNESSSTOREINMETALMAPBLUE=!1,this.AOSTOREINMETALMAPRED=!1,this.METALLIC_REFLECTANCE=!1,this.METALLIC_REFLECTANCE_GAMMA=!1,this.METALLIC_REFLECTANCEDIRECTUV=0,this.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=!1,this.REFLECTANCE=!1,this.REFLECTANCE_GAMMA=!1,this.REFLECTANCEDIRECTUV=0,this.ENVIRONMENTBRDF=!1,this.ENVIRONMENTBRDF_RGBD=!1,this.NORMAL=!1,this.TANGENT=!1,this.BUMP=!1,this.BUMPDIRECTUV=0,this.OBJECTSPACE_NORMALMAP=!1,this.PARALLAX=!1,this.PARALLAX_RHS=!1,this.PARALLAXOCCLUSION=!1,this.NORMALXYSCALE=!0,this.LIGHTMAP=!1,this.LIGHTMAPDIRECTUV=0,this.USELIGHTMAPASSHADOWMAP=!1,this.GAMMALIGHTMAP=!1,this.RGBDLIGHTMAP=!1,this.REFLECTION=!1,this.REFLECTIONMAP_3D=!1,this.REFLECTIONMAP_SPHERICAL=!1,this.REFLECTIONMAP_PLANAR=!1,this.REFLECTIONMAP_CUBIC=!1,this.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,this.REFLECTIONMAP_PROJECTION=!1,this.REFLECTIONMAP_SKYBOX=!1,this.REFLECTIONMAP_EXPLICIT=!1,this.REFLECTIONMAP_EQUIRECTANGULAR=!1,this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,this.INVERTCUBICMAP=!1,this.USESPHERICALFROMREFLECTIONMAP=!1,this.USEIRRADIANCEMAP=!1,this.USESPHERICALINVERTEX=!1,this.REFLECTIONMAP_OPPOSITEZ=!1,this.LODINREFLECTIONALPHA=!1,this.GAMMAREFLECTION=!1,this.RGBDREFLECTION=!1,this.LINEARSPECULARREFLECTION=!1,this.RADIANCEOCCLUSION=!1,this.HORIZONOCCLUSION=!1,this.INSTANCES=!1,this.THIN_INSTANCES=!1,this.INSTANCESCOLOR=!1,this.PREPASS=!1,this.PREPASS_IRRADIANCE=!1,this.PREPASS_IRRADIANCE_INDEX=-1,this.PREPASS_ALBEDO_SQRT=!1,this.PREPASS_ALBEDO_SQRT_INDEX=-1,this.PREPASS_DEPTH=!1,this.PREPASS_DEPTH_INDEX=-1,this.PREPASS_NDC_DEPTH=!1,this.PREPASS_NDC_DEPTH_INDEX=-1,this.PREPASS_NORMAL=!1,this.PREPASS_NORMAL_INDEX=-1,this.PREPASS_NORMAL_WORLDSPACE=!1,this.PREPASS_WORLD_NORMAL=!1,this.PREPASS_WORLD_NORMAL_INDEX=-1,this.PREPASS_POSITION=!1,this.PREPASS_POSITION_INDEX=-1,this.PREPASS_LOCAL_POSITION=!1,this.PREPASS_LOCAL_POSITION_INDEX=-1,this.PREPASS_VELOCITY=!1,this.PREPASS_VELOCITY_INDEX=-1,this.PREPASS_VELOCITY_LINEAR=!1,this.PREPASS_VELOCITY_LINEAR_INDEX=-1,this.PREPASS_REFLECTIVITY=!1,this.PREPASS_REFLECTIVITY_INDEX=-1,this.SCENE_MRT_COUNT=0,this.NUM_BONE_INFLUENCERS=0,this.BonesPerMesh=0,this.BONETEXTURE=!1,this.BONES_VELOCITY_ENABLED=!1,this.NONUNIFORMSCALING=!1,this.MORPHTARGETS=!1,this.MORPHTARGETS_NORMAL=!1,this.MORPHTARGETS_TANGENT=!1,this.MORPHTARGETS_UV=!1,this.NUM_MORPH_INFLUENCERS=0,this.MORPHTARGETS_TEXTURE=!1,this.IMAGEPROCESSING=!1,this.VIGNETTE=!1,this.VIGNETTEBLENDMODEMULTIPLY=!1,this.VIGNETTEBLENDMODEOPAQUE=!1,this.TONEMAPPING=0,this.CONTRAST=!1,this.COLORCURVES=!1,this.COLORGRADING=!1,this.COLORGRADING3D=!1,this.SAMPLER3DGREENDEPTH=!1,this.SAMPLER3DBGRMAP=!1,this.DITHER=!1,this.IMAGEPROCESSINGPOSTPROCESS=!1,this.SKIPFINALCOLORCLAMP=!1,this.EXPOSURE=!1,this.MULTIVIEW=!1,this.ORDER_INDEPENDENT_TRANSPARENCY=!1,this.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!1,this.USEPHYSICALLIGHTFALLOFF=!1,this.USEGLTFLIGHTFALLOFF=!1,this.TWOSIDEDLIGHTING=!1,this.SHADOWFLOAT=!1,this.CLIPPLANE=!1,this.CLIPPLANE2=!1,this.CLIPPLANE3=!1,this.CLIPPLANE4=!1,this.CLIPPLANE5=!1,this.CLIPPLANE6=!1,this.POINTSIZE=!1,this.FOG=!1,this.LOGARITHMICDEPTH=!1,this.CAMERA_ORTHOGRAPHIC=!1,this.CAMERA_PERSPECTIVE=!1,this.FORCENORMALFORWARD=!1,this.SPECULARAA=!1,this.UNLIT=!1,this.DECAL_AFTER_DETAIL=!1,this.DEBUGMODE=0,this.rebuild()}reset(){super.reset(),this.ALPHATESTVALUE="0.5",this.PBR=!0,this.NORMALXYSCALE=!0}}class Hn extends gn{get realTimeFiltering(){return this._realTimeFiltering}set realTimeFiltering(e){this._realTimeFiltering=e,this.markAsDirty(Ze.MATERIAL_TextureDirtyFlag)}get realTimeFilteringQuality(){return this._realTimeFilteringQuality}set realTimeFilteringQuality(e){this._realTimeFilteringQuality=e,this.markAsDirty(Ze.MATERIAL_TextureDirtyFlag)}get canRenderToMRT(){return!0}_attachImageProcessingConfiguration(e){e!==this._imageProcessingConfiguration&&(this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),this._imageProcessingConfiguration=e||this.getScene().imageProcessingConfiguration,this._imageProcessingConfiguration&&(this._imageProcessingObserver=this._imageProcessingConfiguration.onUpdateParameters.add((()=>{this._markAllSubMeshesAsImageProcessingDirty()}))))}constructor(e,t,s=!1){super(e,t),this._directIntensity=1,this._emissiveIntensity=1,this._environmentIntensity=1,this._specularIntensity=1,this._lightingInfos=new k(this._directIntensity,this._emissiveIntensity,this._environmentIntensity,this._specularIntensity),this._disableBumpMap=!1,this._albedoTexture=null,this._ambientTexture=null,this._ambientTextureStrength=1,this._ambientTextureImpactOnAnalyticalLights=Hn.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this._opacityTexture=null,this._reflectionTexture=null,this._emissiveTexture=null,this._reflectivityTexture=null,this._metallicTexture=null,this._metallic=null,this._roughness=null,this._metallicF0Factor=1,this._metallicReflectanceColor=ee.White(),this._useOnlyMetallicFromMetallicReflectanceTexture=!1,this._metallicReflectanceTexture=null,this._reflectanceTexture=null,this._microSurfaceTexture=null,this._bumpTexture=null,this._lightmapTexture=null,this._ambientColor=new ee(0,0,0),this._albedoColor=new ee(1,1,1),this._reflectivityColor=new ee(1,1,1),this._reflectionColor=new ee(1,1,1),this._emissiveColor=new ee(0,0,0),this._microSurface=.9,this._useLightmapAsShadowmap=!1,this._useHorizonOcclusion=!0,this._useRadianceOcclusion=!0,this._useAlphaFromAlbedoTexture=!1,this._useSpecularOverAlpha=!0,this._useMicroSurfaceFromReflectivityMapAlpha=!1,this._useRoughnessFromMetallicTextureAlpha=!0,this._useRoughnessFromMetallicTextureGreen=!1,this._useMetallnessFromMetallicTextureBlue=!1,this._useAmbientOcclusionFromMetallicTextureRed=!1,this._useAmbientInGrayScale=!1,this._useAutoMicroSurfaceFromReflectivityMap=!1,this._lightFalloff=Hn.LIGHTFALLOFF_PHYSICAL,this._useRadianceOverAlpha=!0,this._useObjectSpaceNormalMap=!1,this._useParallax=!1,this._useParallaxOcclusion=!1,this._parallaxScaleBias=.05,this._disableLighting=!1,this._maxSimultaneousLights=4,this._invertNormalMapX=!1,this._invertNormalMapY=!1,this._twoSidedLighting=!1,this._alphaCutOff=.4,this._forceAlphaTest=!1,this._useAlphaFresnel=!1,this._useLinearAlphaFresnel=!1,this._environmentBRDFTexture=null,this._forceIrradianceInFragment=!1,this._realTimeFiltering=!1,this._realTimeFilteringQuality=Ze.TEXTURE_FILTERING_QUALITY_LOW,this._forceNormalForward=!1,this._enableSpecularAntiAliasing=!1,this._imageProcessingObserver=null,this._renderTargets=new Zt(16),this._globalAmbientColor=new ee(0,0,0),this._unlit=!1,this._applyDecalMapAfterDetailMap=!1,this._debugMode=0,this._shadersLoaded=!1,this._breakShaderLoadedCheck=!1,this.debugMode=0,this.debugLimit=-1,this.debugFactor=1,this._cacheHasRenderTargetTextures=!1;const i=this.getScene().getEngine();!i.isWebGPU||s||Hn.ForceGLSL||(this._uniformBuffer&&this._uniformBuffer.dispose(),this._uniformBuffer=new Ls(i,void 0,void 0,this.name,!0),this._shaderLanguage=1),this.brdf=new pn(this),this.clearCoat=new Cn(this),this.iridescence=new On(this),this.anisotropy=new Ln(this),this.sheen=new Nn(this),this.subSurface=new Bn(this),this.detailMap=new kn(this),this._attachImageProcessingConfiguration(null),this.getRenderTargetTextures=()=>(this._renderTargets.reset(),Tn.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget&&this._renderTargets.push(this._reflectionTexture),this._eventInfo.renderTargets=this._renderTargets,this._callbackPluginEventFillRenderTargetTextures(this._eventInfo),this._renderTargets),this._environmentBRDFTexture=on(this.getScene()),this.prePassConfiguration=new mn}get hasRenderTargetTextures(){return!!(Tn.ReflectionTextureEnabled&&this._reflectionTexture&&this._reflectionTexture.isRenderTarget)||this._cacheHasRenderTargetTextures}get isPrePassCapable(){return!this.disableDepthWrite}getClassName(){return"PBRBaseMaterial"}get _disableAlphaBlending(){return this._transparencyMode===Hn.PBRMATERIAL_OPAQUE||this._transparencyMode===Hn.PBRMATERIAL_ALPHATEST||this.subSurface?.disableAlphaBlending}needAlphaBlending(){return!this._disableAlphaBlending&&(this.alpha<1||null!=this._opacityTexture||this._shouldUseAlphaFromAlbedoTexture())}needAlphaTesting(){return!!this._forceAlphaTest||!this.subSurface?.disableAlphaBlending&&(this._hasAlphaChannel()&&(null==this._transparencyMode||this._transparencyMode===Hn.PBRMATERIAL_ALPHATEST))}_shouldUseAlphaFromAlbedoTexture(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha&&this._useAlphaFromAlbedoTexture&&this._transparencyMode!==Hn.PBRMATERIAL_OPAQUE}_hasAlphaChannel(){return null!=this._albedoTexture&&this._albedoTexture.hasAlpha||null!=this._opacityTexture}getAlphaTestTexture(){return this._albedoTexture}isReadyForSubMesh(e,t,s){this._uniformBufferLayoutBuilt||this.buildUniformLayout();const i=t._drawWrapper;if(i.effect&&this.isFrozen&&i._wasPreviouslyReady&&i._wasPreviouslyUsingInstances===s)return!0;t.materialDefines||(this._callbackPluginEventGeneric(4,this._eventInfo),t.materialDefines=new Vn(this._eventInfo.defineNames));const r=t.materialDefines;if(this._isReadyForSubMesh(t))return!0;const n=this.getScene(),a=n.getEngine();if(r._areTexturesDirty&&(this._eventInfo.hasRenderTargetTextures=!1,this._callbackPluginEventHasRenderTargetTextures(this._eventInfo),this._cacheHasRenderTargetTextures=this._eventInfo.hasRenderTargetTextures,n.texturesEnabled)){if(this._albedoTexture&&Tn.DiffuseTextureEnabled&&!this._albedoTexture.isReadyOrNotBlocking())return!1;if(this._ambientTexture&&Tn.AmbientTextureEnabled&&!this._ambientTexture.isReadyOrNotBlocking())return!1;if(this._opacityTexture&&Tn.OpacityTextureEnabled&&!this._opacityTexture.isReadyOrNotBlocking())return!1;const e=this._getReflectionTexture();if(e&&Tn.ReflectionTextureEnabled){if(!e.isReadyOrNotBlocking())return!1;if(e.irradianceTexture){if(!e.irradianceTexture.isReadyOrNotBlocking())return!1}else if(!e.sphericalPolynomial&&e.getInternalTexture()?._sphericalPolynomialPromise)return!1}if(this._lightmapTexture&&Tn.LightmapTextureEnabled&&!this._lightmapTexture.isReadyOrNotBlocking())return!1;if(this._emissiveTexture&&Tn.EmissiveTextureEnabled&&!this._emissiveTexture.isReadyOrNotBlocking())return!1;if(Tn.SpecularTextureEnabled){if(this._metallicTexture){if(!this._metallicTexture.isReadyOrNotBlocking())return!1}else if(this._reflectivityTexture&&!this._reflectivityTexture.isReadyOrNotBlocking())return!1;if(this._metallicReflectanceTexture&&!this._metallicReflectanceTexture.isReadyOrNotBlocking())return!1;if(this._reflectanceTexture&&!this._reflectanceTexture.isReadyOrNotBlocking())return!1;if(this._microSurfaceTexture&&!this._microSurfaceTexture.isReadyOrNotBlocking())return!1}if(a.getCaps().standardDerivatives&&this._bumpTexture&&Tn.BumpTextureEnabled&&!this._disableBumpMap&&!this._bumpTexture.isReady())return!1;if(this._environmentBRDFTexture&&Tn.ReflectionTextureEnabled&&!this._environmentBRDFTexture.isReady())return!1}if(this._eventInfo.isReadyForSubMesh=!0,this._eventInfo.defines=r,this._eventInfo.subMesh=t,this._callbackPluginEventIsReadyForSubMesh(this._eventInfo),!this._eventInfo.isReadyForSubMesh)return!1;if(r._areImageProcessingDirty&&this._imageProcessingConfiguration&&!this._imageProcessingConfiguration.isReady())return!1;a.getCaps().standardDerivatives||e.isVerticesDataPresent(ns.NormalKind)||(e.createNormals(!0),ue.Warn("PBRMaterial: Normals have been created for the mesh: "+e.name));const o=t.effect,h=r._areLightsDisposed;let l=this._prepareEffect(e,r,this.onCompiled,this.onError,s,null,t.getRenderingMesh().hasThinInstances),c=!1;if(l)if(this._onEffectCreatedObservable&&(Gn.effect=l,Gn.subMesh=t,this._onEffectCreatedObservable.notifyObservers(Gn)),this.allowShaderHotSwapping&&o&&!l.isReady()){if(l=o,r.markAsUnprocessed(),c=this.isFrozen,h)return r._areLightsDisposed=!0,!1}else n.resetCachedMaterial(),t.setEffect(l,r,this._materialContext);return!(!t.effect||!t.effect.isReady())&&(r._renderId=n.getRenderId(),i._wasPreviouslyReady=!c,i._wasPreviouslyUsingInstances=!!s,this._checkScenePerformancePriority(),!0)}isMetallicWorkflow(){return!(null==this._metallic&&null==this._roughness&&!this._metallicTexture)}_prepareEffect(e,t,s=null,i=null,r=null,n=null,a){if(this._prepareDefines(e,t,r,n,a),!t.isDirty)return null;t.markAsProcessed();const o=this.getScene().getEngine(),h=new Sn;let l=0;t.USESPHERICALINVERTEX&&h.addFallback(l++,"USESPHERICALINVERTEX"),t.FOG&&h.addFallback(l,"FOG"),t.SPECULARAA&&h.addFallback(l,"SPECULARAA"),t.POINTSIZE&&h.addFallback(l,"POINTSIZE"),t.LOGARITHMICDEPTH&&h.addFallback(l,"LOGARITHMICDEPTH"),t.PARALLAX&&h.addFallback(l,"PARALLAX"),t.PARALLAX_RHS&&h.addFallback(l,"PARALLAX_RHS"),t.PARALLAXOCCLUSION&&h.addFallback(l++,"PARALLAXOCCLUSION"),t.ENVIRONMENTBRDF&&h.addFallback(l++,"ENVIRONMENTBRDF"),t.TANGENT&&h.addFallback(l++,"TANGENT"),t.BUMP&&h.addFallback(l++,"BUMP"),l=function(e,t,s=4,i=0){let r=0;for(let n=0;n<s&&e["LIGHT"+n];n++)n>0&&(r=i+n,t.addFallback(r,"LIGHT"+n)),e.SHADOWS||(e["SHADOW"+n]&&t.addFallback(i,"SHADOW"+n),e["SHADOWPCF"+n]&&t.addFallback(i,"SHADOWPCF"+n),e["SHADOWPCSS"+n]&&t.addFallback(i,"SHADOWPCSS"+n),e["SHADOWPOISSON"+n]&&t.addFallback(i,"SHADOWPOISSON"+n),e["SHADOWESM"+n]&&t.addFallback(i,"SHADOWESM"+n),e["SHADOWCLOSEESM"+n]&&t.addFallback(i,"SHADOWCLOSEESM"+n));return r++}(t,h,this._maxSimultaneousLights,l++),t.SPECULARTERM&&h.addFallback(l++,"SPECULARTERM"),t.USESPHERICALFROMREFLECTIONMAP&&h.addFallback(l++,"USESPHERICALFROMREFLECTIONMAP"),t.USEIRRADIANCEMAP&&h.addFallback(l++,"USEIRRADIANCEMAP"),t.LIGHTMAP&&h.addFallback(l++,"LIGHTMAP"),t.NORMAL&&h.addFallback(l++,"NORMAL"),t.AMBIENT&&h.addFallback(l++,"AMBIENT"),t.EMISSIVE&&h.addFallback(l++,"EMISSIVE"),t.VERTEXCOLOR&&h.addFallback(l++,"VERTEXCOLOR"),t.MORPHTARGETS&&h.addFallback(l++,"MORPHTARGETS"),t.MULTIVIEW&&h.addFallback(0,"MULTIVIEW");const c=[ns.PositionKind];t.NORMAL&&c.push(ns.NormalKind),t.TANGENT&&c.push(ns.TangentKind);for(let e=1;e<=Ze.MAX_SUPPORTED_UV_SETS;++e)t["UV"+e]&&c.push(`uv${1===e?"":e}`);t.VERTEXCOLOR&&c.push(ns.ColorKind),function(e,t,s,i){s.NUM_BONE_INFLUENCERS>0&&(i.addCPUSkinningFallback(0,t),e.push(Ze.MatricesIndicesKind),e.push(Ze.MatricesWeightsKind),s.NUM_BONE_INFLUENCERS>4&&(e.push(Ze.MatricesIndicesExtraKind),e.push(Ze.MatricesWeightsExtraKind)))}(c,e,t,h),function(e,t){(t.INSTANCES||t.THIN_INSTANCES)&&function(e,t=!1){e.push("world0"),e.push("world1"),e.push("world2"),e.push("world3"),t&&(e.push("previousWorld0"),e.push("previousWorld1"),e.push("previousWorld2"),e.push("previousWorld3"))}(e,!!t.PREPASS_VELOCITY),t.INSTANCESCOLOR&&e.push(Ze.ColorInstanceKind)}(c,t),function(e,t,s){const i=s.NUM_MORPH_INFLUENCERS;if(i>0&&C.LastCreatedEngine){const r=C.LastCreatedEngine.getCaps().maxVertexAttribs,n=t.morphTargetManager;if(n?.isUsingTextureForTargets)return;const a=n&&n.supportsNormals&&s.NORMAL,o=n&&n.supportsTangents&&s.TANGENT,h=n&&n.supportsUVs&&s.UV1;for(let s=0;s<i;s++)e.push(Ze.PositionKind+s),a&&e.push(Ze.NormalKind+s),o&&e.push(Ze.TangentKind+s),h&&e.push(Ze.UVKind+"_"+s),e.length>r&&ue.Error("Cannot add more vertex attributes for mesh "+t.name)}}(c,e,t),function(e,t,s){s.BAKED_VERTEX_ANIMATION_TEXTURE&&s.INSTANCES&&e.push("bakedVertexAnimationSettingsInstanced")}(c,0,t);let u="pbr";const d=["world","view","viewProjection","vEyePosition","vLightsType","vAmbientColor","vAlbedoColor","vReflectivityColor","vMetallicReflectanceFactors","vEmissiveColor","visibility","vReflectionColor","vFogInfos","vFogColor","pointSize","vAlbedoInfos","vAmbientInfos","vOpacityInfos","vReflectionInfos","vReflectionPosition","vReflectionSize","vEmissiveInfos","vReflectivityInfos","vReflectionFilteringInfo","vMetallicReflectanceInfos","vReflectanceInfos","vMicroSurfaceSamplerInfos","vBumpInfos","vLightmapInfos","mBones","albedoMatrix","ambientMatrix","opacityMatrix","reflectionMatrix","emissiveMatrix","reflectivityMatrix","normalMatrix","microSurfaceSamplerMatrix","bumpMatrix","lightmapMatrix","metallicReflectanceMatrix","reflectanceMatrix","vLightingIntensity","logarithmicDepthConstant","vSphericalX","vSphericalY","vSphericalZ","vSphericalXX_ZZ","vSphericalYY_ZZ","vSphericalZZ","vSphericalXY","vSphericalYZ","vSphericalZX","vSphericalL00","vSphericalL1_1","vSphericalL10","vSphericalL11","vSphericalL2_2","vSphericalL2_1","vSphericalL20","vSphericalL21","vSphericalL22","vReflectionMicrosurfaceInfos","vTangentSpaceParams","boneTextureWidth","vDebugMode","morphTargetTextureInfo","morphTargetTextureIndices"],_=["albedoSampler","reflectivitySampler","ambientSampler","emissiveSampler","bumpSampler","lightmapSampler","opacitySampler","reflectionSampler","reflectionSamplerLow","reflectionSamplerHigh","irradianceSampler","microSurfaceSampler","environmentBrdfSampler","boneSampler","metallicReflectanceSampler","reflectanceSampler","morphTargets","oitDepthSampler","oitFrontColorSampler"],f=["Material","Scene","Mesh"],p={maxSimultaneousLights:this._maxSimultaneousLights,maxSimultaneousMorphTargets:t.NUM_MORPH_INFLUENCERS};this._eventInfo.fallbacks=h,this._eventInfo.fallbackRank=l,this._eventInfo.defines=t,this._eventInfo.uniforms=d,this._eventInfo.attributes=c,this._eventInfo.samplers=_,this._eventInfo.uniformBuffersNames=f,this._eventInfo.customCode=void 0,this._eventInfo.mesh=e,this._eventInfo.indexParameters=p,this._callbackPluginEventGeneric(128,this._eventInfo),mn.AddUniforms(d),function(e){-1===e.indexOf("vClipPlane")&&e.push("vClipPlane"),-1===e.indexOf("vClipPlane2")&&e.push("vClipPlane2"),-1===e.indexOf("vClipPlane3")&&e.push("vClipPlane3"),-1===e.indexOf("vClipPlane4")&&e.push("vClipPlane4"),-1===e.indexOf("vClipPlane5")&&e.push("vClipPlane5"),-1===e.indexOf("vClipPlane6")&&e.push("vClipPlane6")}(d),Ki&&(Ki.PrepareUniforms(d,t),Ki.PrepareSamplers(_,t)),function(e,t,s,i=4){let r,n=null;if(e.uniformsNames){const a=e;r=a.uniformsNames,n=a.uniformBuffersNames,t=a.samplers,s=a.defines,i=a.maxSimultaneousLights||0}else r=e,t||(t=[]);for(let e=0;e<i&&s["LIGHT"+e];e++)Zs(e,r,t,s["PROJECTEDLIGHTTEXTURE"+e],n);s.NUM_MORPH_INFLUENCERS&&(r.push("morphTargetInfluences"),r.push("morphTargetCount")),s.BAKED_VERTEX_ANIMATION_TEXTURE&&(r.push("bakedVertexAnimationSettings"),r.push("bakedVertexAnimationTextureSizeInverted"),r.push("bakedVertexAnimationTime"),t.push("bakedVertexAnimationTexture"))}({uniformsNames:d,uniformBuffersNames:f,samplers:_,defines:t,maxSimultaneousLights:this._maxSimultaneousLights});const m={};this.customShaderNameResolve&&(u=this.customShaderNameResolve(u,d,f,_,t,c,m));const g=t.toString(),T=o.createEffect(u,{attributes:c,uniformsNames:d,uniformBuffersNames:f,samplers:_,defines:g,fallbacks:h,onCompiled:s,onError:i,indexParameters:p,processFinalCode:m.processFinalCode,processCodeAfterIncludes:this._eventInfo.customCode,multiTarget:t.PREPASS,shaderLanguage:this._shaderLanguage,extraInitializationsAsync:this._shadersLoaded?void 0:async()=>{1===this.shaderLanguage?await Promise.all([import("./pbr.vertex-C8vOdMd6.esm.min.js"),import("./pbr.fragment-DU4hy3T_.esm.min.js")]):await Promise.all([import("./pbr.vertex-DPPPQSbX.esm.min.js"),import("./pbr.fragment-BN71FgFx.esm.min.js")]),this._shadersLoaded=!0}},o);return this._eventInfo.customCode=void 0,T}_prepareDefines(e,t,s=null,i=null,r=!1){const n=this.getScene(),a=n.getEngine();!function(e,t,s,i,r=4,n=!1){if(!s._areLightsDirty)return s._needNormals;let a=0;const o={needNormals:s._needNormals,needRebuild:!1,lightmapMode:!1,shadowEnabled:!1,specularEnabled:!1};if(e.lightsEnabled&&!n)for(const i of t.lightSources)if(Qs(e,t,i,a,s,0,o),a++,a===r)break;s.SPECULARTERM=o.specularEnabled,s.SHADOWS=o.shadowEnabled;for(let e=a;e<r;e++)void 0!==s["LIGHT"+e]&&(s["LIGHT"+e]=!1,s["HEMILIGHT"+e]=!1,s["POINTLIGHT"+e]=!1,s["DIRLIGHT"+e]=!1,s["SPOTLIGHT"+e]=!1,s["SHADOW"+e]=!1,s["SHADOWCSM"+e]=!1,s["SHADOWCSMDEBUG"+e]=!1,s["SHADOWCSMNUM_CASCADES"+e]=!1,s["SHADOWCSMUSESHADOWMAXZ"+e]=!1,s["SHADOWCSMNOBLEND"+e]=!1,s["SHADOWCSM_RIGHTHANDED"+e]=!1,s["SHADOWPCF"+e]=!1,s["SHADOWPCSS"+e]=!1,s["SHADOWPOISSON"+e]=!1,s["SHADOWESM"+e]=!1,s["SHADOWCLOSEESM"+e]=!1,s["SHADOWCUBE"+e]=!1,s["SHADOWLOWQUALITY"+e]=!1,s["SHADOWMEDIUMQUALITY"+e]=!1);const h=e.getEngine().getCaps();void 0===s.SHADOWFLOAT&&(o.needRebuild=!0),s.SHADOWFLOAT=o.shadowEnabled&&(h.textureFloatRender&&h.textureFloatLinearFiltering||h.textureHalfFloatRender&&h.textureHalfFloatLinearFiltering),s.LIGHTMAPEXCLUDED=o.lightmapMode,o.needRebuild&&s.rebuild(),o.needNormals}(n,e,t,0,this._maxSimultaneousLights,this._disableLighting),t._needNormals=!0,function(e,t){if(e.activeCamera){const s=t.MULTIVIEW;t.MULTIVIEW=null!==e.activeCamera.outputRenderTarget&&e.activeCamera.outputRenderTarget.getViewCount()>1,t.MULTIVIEW!=s&&t.markAsUnprocessed()}}(n,t);const o=this.needAlphaBlendingForMesh(e)&&this.getScene().useOrderIndependentTransparency;if(function(e,t,s){const i=t.PREPASS;if(!t._arePrePassDirty)return;const r=[{type:Ze.PREPASS_POSITION_TEXTURE_TYPE,define:"PREPASS_POSITION",index:"PREPASS_POSITION_INDEX"},{type:Ze.PREPASS_LOCAL_POSITION_TEXTURE_TYPE,define:"PREPASS_LOCAL_POSITION",index:"PREPASS_LOCAL_POSITION_INDEX"},{type:Ze.PREPASS_VELOCITY_TEXTURE_TYPE,define:"PREPASS_VELOCITY",index:"PREPASS_VELOCITY_INDEX"},{type:Ze.PREPASS_VELOCITY_LINEAR_TEXTURE_TYPE,define:"PREPASS_VELOCITY_LINEAR",index:"PREPASS_VELOCITY_LINEAR_INDEX"},{type:Ze.PREPASS_REFLECTIVITY_TEXTURE_TYPE,define:"PREPASS_REFLECTIVITY",index:"PREPASS_REFLECTIVITY_INDEX"},{type:Ze.PREPASS_IRRADIANCE_TEXTURE_TYPE,define:"PREPASS_IRRADIANCE",index:"PREPASS_IRRADIANCE_INDEX"},{type:Ze.PREPASS_ALBEDO_SQRT_TEXTURE_TYPE,define:"PREPASS_ALBEDO_SQRT",index:"PREPASS_ALBEDO_SQRT_INDEX"},{type:Ze.PREPASS_DEPTH_TEXTURE_TYPE,define:"PREPASS_DEPTH",index:"PREPASS_DEPTH_INDEX"},{type:Ze.PREPASS_NDC_DEPTH_TEXTURE_TYPE,define:"PREPASS_NDC_DEPTH",index:"PREPASS_NDC_DEPTH_INDEX"},{type:Ze.PREPASS_NORMAL_TEXTURE_TYPE,define:"PREPASS_NORMAL",index:"PREPASS_NORMAL_INDEX"},{type:Ze.PREPASS_WORLD_NORMAL_TEXTURE_TYPE,define:"PREPASS_WORLD_NORMAL",index:"PREPASS_WORLD_NORMAL_INDEX"}];if(e.prePassRenderer&&e.prePassRenderer.enabled&&s){t.PREPASS=!0,t.SCENE_MRT_COUNT=e.prePassRenderer.mrtCount,t.PREPASS_NORMAL_WORLDSPACE=e.prePassRenderer.generateNormalsInWorldSpace;for(let s=0;s<r.length;s++){const i=e.prePassRenderer.getIndex(r[s].type);-1!==i?(t[r[s].define]=!0,t[r[s].index]=i):t[r[s].define]=!1}}else{t.PREPASS=!1;for(let e=0;e<r.length;e++)t[r[e].define]=!1}t.PREPASS!=i&&(t.markAsUnprocessed(),t.markAsImageProcessingDirty())}(n,t,this.canRenderToMRT&&!o),function(e,t,s){const i=t.ORDER_INDEPENDENT_TRANSPARENCY,r=t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS;t.ORDER_INDEPENDENT_TRANSPARENCY=e.useOrderIndependentTransparency&&s,t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS=!e.getEngine().getCaps().textureFloatLinearFiltering,i===t.ORDER_INDEPENDENT_TRANSPARENCY&&r===t.ORDER_INDEPENDENT_TRANSPARENCY_16BITS||t.markAsUnprocessed()}(n,t,o),t.METALLICWORKFLOW=this.isMetallicWorkflow(),t._areTexturesDirty){t._needUVs=!1;for(let e=1;e<=Ze.MAX_SUPPORTED_UV_SETS;++e)t["MAINUV"+e]=!1;if(n.texturesEnabled){t.ALBEDODIRECTUV=0,t.AMBIENTDIRECTUV=0,t.OPACITYDIRECTUV=0,t.EMISSIVEDIRECTUV=0,t.REFLECTIVITYDIRECTUV=0,t.MICROSURFACEMAPDIRECTUV=0,t.METALLIC_REFLECTANCEDIRECTUV=0,t.REFLECTANCEDIRECTUV=0,t.BUMPDIRECTUV=0,t.LIGHTMAPDIRECTUV=0,a.getCaps().textureLOD&&(t.LODBASEDMICROSFURACE=!0),this._albedoTexture&&Tn.DiffuseTextureEnabled?(Ws(this._albedoTexture,t,"ALBEDO"),t.GAMMAALBEDO=this._albedoTexture.gammaSpace):t.ALBEDO=!1,this._ambientTexture&&Tn.AmbientTextureEnabled?(Ws(this._ambientTexture,t,"AMBIENT"),t.AMBIENTINGRAYSCALE=this._useAmbientInGrayScale):t.AMBIENT=!1,this._opacityTexture&&Tn.OpacityTextureEnabled?(Ws(this._opacityTexture,t,"OPACITY"),t.OPACITYRGB=this._opacityTexture.getAlphaFromRGB):t.OPACITY=!1;const e=this._getReflectionTexture();if(e&&Tn.ReflectionTextureEnabled){switch(t.REFLECTION=!0,t.GAMMAREFLECTION=e.gammaSpace,t.RGBDREFLECTION=e.isRGBD,t.LODINREFLECTIONALPHA=e.lodLevelInAlpha,t.LINEARSPECULARREFLECTION=e.linearSpecularLOD,this.realTimeFiltering&&this.realTimeFilteringQuality>0?(t.NUM_SAMPLES=""+this.realTimeFilteringQuality,a._features.needTypeSuffixInShaderConstants&&(t.NUM_SAMPLES=t.NUM_SAMPLES+"u"),t.REALTIME_FILTERING=!0):t.REALTIME_FILTERING=!1,t.INVERTCUBICMAP=e.coordinatesMode===Dr.INVCUBIC_MODE,t.REFLECTIONMAP_3D=e.isCube,t.REFLECTIONMAP_OPPOSITEZ=t.REFLECTIONMAP_3D&&this.getScene().useRightHandedSystem?!e.invertZ:e.invertZ,t.REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,e.coordinatesMode){case Dr.EXPLICIT_MODE:t.REFLECTIONMAP_EXPLICIT=!0;break;case Dr.PLANAR_MODE:t.REFLECTIONMAP_PLANAR=!0;break;case Dr.PROJECTION_MODE:t.REFLECTIONMAP_PROJECTION=!0;break;case Dr.SKYBOX_MODE:t.REFLECTIONMAP_SKYBOX=!0;break;case Dr.SPHERICAL_MODE:t.REFLECTIONMAP_SPHERICAL=!0;break;case Dr.EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR=!0;break;case Dr.FIXED_EQUIRECTANGULAR_MODE:t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!0;break;case Dr.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!0;break;case Dr.CUBIC_MODE:case Dr.INVCUBIC_MODE:default:t.REFLECTIONMAP_CUBIC=!0,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!!e.boundingBoxSize}e.coordinatesMode!==Dr.SKYBOX_MODE&&(e.irradianceTexture?(t.USEIRRADIANCEMAP=!0,t.USESPHERICALFROMREFLECTIONMAP=!1):e.isCube&&(t.USESPHERICALFROMREFLECTIONMAP=!0,t.USEIRRADIANCEMAP=!1,this._forceIrradianceInFragment||this.realTimeFiltering||this._twoSidedLighting||a.getCaps().maxVaryingVectors<=8?t.USESPHERICALINVERTEX=!1:t.USESPHERICALINVERTEX=!0))}else t.REFLECTION=!1,t.REFLECTIONMAP_3D=!1,t.REFLECTIONMAP_SPHERICAL=!1,t.REFLECTIONMAP_PLANAR=!1,t.REFLECTIONMAP_CUBIC=!1,t.USE_LOCAL_REFLECTIONMAP_CUBIC=!1,t.REFLECTIONMAP_PROJECTION=!1,t.REFLECTIONMAP_SKYBOX=!1,t.REFLECTIONMAP_EXPLICIT=!1,t.REFLECTIONMAP_EQUIRECTANGULAR=!1,t.REFLECTIONMAP_EQUIRECTANGULAR_FIXED=!1,t.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED=!1,t.INVERTCUBICMAP=!1,t.USESPHERICALFROMREFLECTIONMAP=!1,t.USEIRRADIANCEMAP=!1,t.USESPHERICALINVERTEX=!1,t.REFLECTIONMAP_OPPOSITEZ=!1,t.LODINREFLECTIONALPHA=!1,t.GAMMAREFLECTION=!1,t.RGBDREFLECTION=!1,t.LINEARSPECULARREFLECTION=!1;this._lightmapTexture&&Tn.LightmapTextureEnabled?(Ws(this._lightmapTexture,t,"LIGHTMAP"),t.USELIGHTMAPASSHADOWMAP=this._useLightmapAsShadowmap,t.GAMMALIGHTMAP=this._lightmapTexture.gammaSpace,t.RGBDLIGHTMAP=this._lightmapTexture.isRGBD):t.LIGHTMAP=!1,this._emissiveTexture&&Tn.EmissiveTextureEnabled?(Ws(this._emissiveTexture,t,"EMISSIVE"),t.GAMMAEMISSIVE=this._emissiveTexture.gammaSpace):t.EMISSIVE=!1,Tn.SpecularTextureEnabled?(this._metallicTexture?(Ws(this._metallicTexture,t,"REFLECTIVITY"),t.ROUGHNESSSTOREINMETALMAPALPHA=this._useRoughnessFromMetallicTextureAlpha,t.ROUGHNESSSTOREINMETALMAPGREEN=!this._useRoughnessFromMetallicTextureAlpha&&this._useRoughnessFromMetallicTextureGreen,t.METALLNESSSTOREINMETALMAPBLUE=this._useMetallnessFromMetallicTextureBlue,t.AOSTOREINMETALMAPRED=this._useAmbientOcclusionFromMetallicTextureRed,t.REFLECTIVITY_GAMMA=!1):this._reflectivityTexture?(Ws(this._reflectivityTexture,t,"REFLECTIVITY"),t.MICROSURFACEFROMREFLECTIVITYMAP=this._useMicroSurfaceFromReflectivityMapAlpha,t.MICROSURFACEAUTOMATIC=this._useAutoMicroSurfaceFromReflectivityMap,t.REFLECTIVITY_GAMMA=this._reflectivityTexture.gammaSpace):t.REFLECTIVITY=!1,this._metallicReflectanceTexture||this._reflectanceTexture?(t.METALLIC_REFLECTANCE_USE_ALPHA_ONLY=this._useOnlyMetallicFromMetallicReflectanceTexture,this._metallicReflectanceTexture?(Ws(this._metallicReflectanceTexture,t,"METALLIC_REFLECTANCE"),t.METALLIC_REFLECTANCE_GAMMA=this._metallicReflectanceTexture.gammaSpace):t.METALLIC_REFLECTANCE=!1,this._reflectanceTexture&&(!this._metallicReflectanceTexture||this._metallicReflectanceTexture&&this._useOnlyMetallicFromMetallicReflectanceTexture)?(Ws(this._reflectanceTexture,t,"REFLECTANCE"),t.REFLECTANCE_GAMMA=this._reflectanceTexture.gammaSpace):t.REFLECTANCE=!1):(t.METALLIC_REFLECTANCE=!1,t.REFLECTANCE=!1),this._microSurfaceTexture?Ws(this._microSurfaceTexture,t,"MICROSURFACEMAP"):t.MICROSURFACEMAP=!1):(t.REFLECTIVITY=!1,t.MICROSURFACEMAP=!1),a.getCaps().standardDerivatives&&this._bumpTexture&&Tn.BumpTextureEnabled&&!this._disableBumpMap?(Ws(this._bumpTexture,t,"BUMP"),this._useParallax&&this._albedoTexture&&Tn.DiffuseTextureEnabled?(t.PARALLAX=!0,t.PARALLAX_RHS=n.useRightHandedSystem,t.PARALLAXOCCLUSION=!!this._useParallaxOcclusion):t.PARALLAX=!1,t.OBJECTSPACE_NORMALMAP=this._useObjectSpaceNormalMap):(t.BUMP=!1,t.PARALLAX=!1,t.PARALLAX_RHS=!1,t.PARALLAXOCCLUSION=!1,t.OBJECTSPACE_NORMALMAP=!1),this._environmentBRDFTexture&&Tn.ReflectionTextureEnabled?(t.ENVIRONMENTBRDF=!0,t.ENVIRONMENTBRDF_RGBD=this._environmentBRDFTexture.isRGBD):(t.ENVIRONMENTBRDF=!1,t.ENVIRONMENTBRDF_RGBD=!1),this._shouldUseAlphaFromAlbedoTexture()?t.ALPHAFROMALBEDO=!0:t.ALPHAFROMALBEDO=!1}t.SPECULAROVERALPHA=this._useSpecularOverAlpha,this._lightFalloff===Hn.LIGHTFALLOFF_STANDARD?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!1):this._lightFalloff===Hn.LIGHTFALLOFF_GLTF?(t.USEPHYSICALLIGHTFALLOFF=!1,t.USEGLTFLIGHTFALLOFF=!0):(t.USEPHYSICALLIGHTFALLOFF=!0,t.USEGLTFLIGHTFALLOFF=!1),t.RADIANCEOVERALPHA=this._useRadianceOverAlpha,!this.backFaceCulling&&this._twoSidedLighting?t.TWOSIDEDLIGHTING=!0:t.TWOSIDEDLIGHTING=!1,t.SPECULARAA=a.getCaps().standardDerivatives&&this._enableSpecularAntiAliasing}(t._areTexturesDirty||t._areMiscDirty)&&(t.ALPHATESTVALUE=`${this._alphaCutOff}${this._alphaCutOff%1==0?".":""}`,t.PREMULTIPLYALPHA=this.alphaMode===Ze.ALPHA_PREMULTIPLIED||this.alphaMode===Ze.ALPHA_PREMULTIPLIED_PORTERDUFF,t.ALPHABLEND=this.needAlphaBlendingForMesh(e),t.ALPHAFRESNEL=this._useAlphaFresnel||this._useLinearAlphaFresnel,t.LINEARALPHAFRESNEL=this._useLinearAlphaFresnel),t._areImageProcessingDirty&&this._imageProcessingConfiguration&&this._imageProcessingConfiguration.prepareDefines(t),t.FORCENORMALFORWARD=this._forceNormalForward,t.RADIANCEOCCLUSION=this._useRadianceOcclusion,t.HORIZONOCCLUSION=this._useHorizonOcclusion,t._areMiscDirty&&(qs(e,n,this._useLogarithmicDepth,this.pointsCloud,this.fogEnabled,this._shouldTurnAlphaTestOn(e)||this._forceAlphaTest,t,this._applyDecalMapAfterDetailMap),t.UNLIT=this._unlit||(this.pointsCloud||this.wireframe)&&!e.isVerticesDataPresent(ns.NormalKind),t.DEBUGMODE=this._debugMode),js(n,a,this,t,!!s,i,r),this._eventInfo.defines=t,this._eventInfo.mesh=e,this._callbackPluginEventPrepareDefinesBeforeAttributes(this._eventInfo),function(e,t,s,i,r=!1,n=!0,a=!0){if(!t._areAttributesDirty&&t._needNormals===t._normals&&t._needUVs===t._uvs)return!1;t._normals=t._needNormals,t._uvs=t._needUVs,t.NORMAL=t._needNormals&&e.isVerticesDataPresent(Ze.NormalKind),t._needNormals&&e.isVerticesDataPresent(Ze.TangentKind)&&(t.TANGENT=!0);for(let s=1;s<=Ze.MAX_SUPPORTED_UV_SETS;++s)t["UV"+s]=!!t._needUVs&&e.isVerticesDataPresent(`uv${1===s?"":s}`);{const s=e.useVertexColors&&e.isVerticesDataPresent(Ze.ColorKind);t.VERTEXCOLOR=s,t.VERTEXALPHA=e.hasVertexAlpha&&s&&n}e.isVerticesDataPresent(Ze.ColorInstanceKind)&&(e.hasInstances||e.hasThinInstances)&&(t.INSTANCESCOLOR=!0),function(e,t){if(e.useBones&&e.computeBonesUsingShaders&&e.skeleton){t.NUM_BONE_INFLUENCERS=e.numBoneInfluencers;const s=void 0!==t.BONETEXTURE;if(e.skeleton.isUsingTextureForMatrices&&s)t.BONETEXTURE=!0;else{t.BonesPerMesh=e.skeleton.bones.length+1,t.BONETEXTURE=!s&&void 0;const i=e.getScene().prePassRenderer;if(i&&i.enabled){const s=-1===i.excludedSkinnedMesh.indexOf(e);t.BONES_VELOCITY_ENABLED=s}}}else t.NUM_BONE_INFLUENCERS=0,t.BonesPerMesh=0,void 0!==t.BONETEXTURE&&(t.BONETEXTURE=!1)}(e,t),r&&function(e,t){const s=e.morphTargetManager;s?(t.MORPHTARGETS_UV=s.supportsUVs&&t.UV1,t.MORPHTARGETS_TANGENT=s.supportsTangents&&t.TANGENT,t.MORPHTARGETS_NORMAL=s.supportsNormals&&t.NORMAL,t.NUM_MORPH_INFLUENCERS=s.numMaxInfluencers||s.numInfluencers,t.MORPHTARGETS=t.NUM_MORPH_INFLUENCERS>0,t.MORPHTARGETS_TEXTURE=s.isUsingTextureForTargets):(t.MORPHTARGETS_UV=!1,t.MORPHTARGETS_TANGENT=!1,t.MORPHTARGETS_NORMAL=!1,t.MORPHTARGETS=!1,t.NUM_MORPH_INFLUENCERS=0)}(e,t),a&&function(e,t){const s=e.bakedVertexAnimationManager;t.BAKED_VERTEX_ANIMATION_TEXTURE=!(!s||!s.isEnabled)}(e,t)}(e,t,0,0,!0,this._transparencyMode!==Hn.PBRMATERIAL_OPAQUE),this._callbackPluginEventPrepareDefines(this._eventInfo)}forceCompilation(e,t,s){const i={clipPlane:!1,useInstances:!1,...s};this._uniformBufferLayoutBuilt||this.buildUniformLayout(),this._callbackPluginEventGeneric(4,this._eventInfo);(()=>{if(this._breakShaderLoadedCheck)return;const s=new Vn(this._eventInfo.defineNames),r=this._prepareEffect(e,s,void 0,void 0,i.useInstances,i.clipPlane,e.hasThinInstances);this._onEffectCreatedObservable&&(Gn.effect=r,Gn.subMesh=null,this._onEffectCreatedObservable.notifyObservers(Gn)),r.isReady()?t&&t(this):r.onCompileObservable.add((()=>{t&&t(this)}))})()}buildUniformLayout(){const e=this._uniformBuffer;e.addUniform("vAlbedoInfos",2),e.addUniform("vAmbientInfos",4),e.addUniform("vOpacityInfos",2),e.addUniform("vEmissiveInfos",2),e.addUniform("vLightmapInfos",2),e.addUniform("vReflectivityInfos",3),e.addUniform("vMicroSurfaceSamplerInfos",2),e.addUniform("vReflectionInfos",2),e.addUniform("vReflectionFilteringInfo",2),e.addUniform("vReflectionPosition",3),e.addUniform("vReflectionSize",3),e.addUniform("vBumpInfos",3),e.addUniform("albedoMatrix",16),e.addUniform("ambientMatrix",16),e.addUniform("opacityMatrix",16),e.addUniform("emissiveMatrix",16),e.addUniform("lightmapMatrix",16),e.addUniform("reflectivityMatrix",16),e.addUniform("microSurfaceSamplerMatrix",16),e.addUniform("bumpMatrix",16),e.addUniform("vTangentSpaceParams",2),e.addUniform("reflectionMatrix",16),e.addUniform("vReflectionColor",3),e.addUniform("vAlbedoColor",4),e.addUniform("vLightingIntensity",4),e.addUniform("vReflectionMicrosurfaceInfos",3),e.addUniform("pointSize",1),e.addUniform("vReflectivityColor",4),e.addUniform("vEmissiveColor",3),e.addUniform("vAmbientColor",3),e.addUniform("vDebugMode",2),e.addUniform("vMetallicReflectanceFactors",4),e.addUniform("vMetallicReflectanceInfos",2),e.addUniform("metallicReflectanceMatrix",16),e.addUniform("vReflectanceInfos",2),e.addUniform("reflectanceMatrix",16),e.addUniform("vSphericalL00",3),e.addUniform("vSphericalL1_1",3),e.addUniform("vSphericalL10",3),e.addUniform("vSphericalL11",3),e.addUniform("vSphericalL2_2",3),e.addUniform("vSphericalL2_1",3),e.addUniform("vSphericalL20",3),e.addUniform("vSphericalL21",3),e.addUniform("vSphericalL22",3),e.addUniform("vSphericalX",3),e.addUniform("vSphericalY",3),e.addUniform("vSphericalZ",3),e.addUniform("vSphericalXX_ZZ",3),e.addUniform("vSphericalYY_ZZ",3),e.addUniform("vSphericalZZ",3),e.addUniform("vSphericalXY",3),e.addUniform("vSphericalYZ",3),e.addUniform("vSphericalZX",3),super.buildUniformLayout()}bindForSubMesh(e,t,s){const i=this.getScene(),r=s.materialDefines;if(!r)return;const n=s.effect;if(!n)return;this._activeEffect=n,t.getMeshUniformBuffer().bindToEffect(n,"Mesh"),t.transferToEffect(e);const a=i.getEngine();this._uniformBuffer.bindToEffect(n,"Material"),this.prePassConfiguration.bindForSubMesh(this._activeEffect,i,t,e,this.isFrozen),this._eventInfo.subMesh=s,this._callbackPluginEventHardBindForSubMesh(this._eventInfo),r.OBJECTSPACE_NORMALMAP&&(e.toNormalMatrix(this._normalMatrix),this.bindOnlyNormalMatrix(this._normalMatrix));const o=this._mustRebind(i,n,s,t.visibility);!function(e,t,s){var i;if(t&&e&&(e.computeBonesUsingShaders&&t._bonesComputationForcedToCPU&&(e.computeBonesUsingShaders=!1),e.useBones&&e.computeBonesUsingShaders&&e.skeleton)){const r=e.skeleton;if(r.isUsingTextureForMatrices&&t.getUniformIndex("boneTextureWidth")>-1){const s=r.getTransformMatrixTexture(e);t.setTexture("boneSampler",s),t.setFloat("boneTextureWidth",4*(r.bones.length+1))}else{const n=r.getTransformMatrices(e);n&&(t.setMatrices("mBones",n),s&&e.getScene().prePassRenderer&&e.getScene().prePassRenderer.getIndex(Ze.PREPASS_VELOCITY_TEXTURE_TYPE)&&(s.previousBones[e.uniqueId]||(s.previousBones[e.uniqueId]=n.slice()),t.setMatrices("mPreviousBones",s.previousBones[e.uniqueId]),i=n,s.previousBones[e.uniqueId].set(i)))}}}(t,this._activeEffect,this.prePassConfiguration);let h=null;const l=this._uniformBuffer;if(o){if(this.bindViewProjection(n),h=this._getReflectionTexture(),!l.useUbo||!this.isFrozen||!l.isSync||s._drawWrapper._forceRebindOnNextCall){if(i.texturesEnabled){if(this._albedoTexture&&Tn.DiffuseTextureEnabled&&(l.updateFloat2("vAlbedoInfos",this._albedoTexture.coordinatesIndex,this._albedoTexture.level),Ys(this._albedoTexture,l,"albedo")),this._ambientTexture&&Tn.AmbientTextureEnabled&&(l.updateFloat4("vAmbientInfos",this._ambientTexture.coordinatesIndex,this._ambientTexture.level,this._ambientTextureStrength,this._ambientTextureImpactOnAnalyticalLights),Ys(this._ambientTexture,l,"ambient")),this._opacityTexture&&Tn.OpacityTextureEnabled&&(l.updateFloat2("vOpacityInfos",this._opacityTexture.coordinatesIndex,this._opacityTexture.level),Ys(this._opacityTexture,l,"opacity")),h&&Tn.ReflectionTextureEnabled){if(l.updateMatrix("reflectionMatrix",h.getReflectionTextureMatrix()),l.updateFloat2("vReflectionInfos",h.level,0),h.boundingBoxSize){const e=h;l.updateVector3("vReflectionPosition",e.boundingBoxPosition),l.updateVector3("vReflectionSize",e.boundingBoxSize)}if(this.realTimeFiltering){const e=h.getSize().width;l.updateFloat2("vReflectionFilteringInfo",e,Q.Log2(e))}if(!r.USEIRRADIANCEMAP){const e=h.sphericalPolynomial;if(r.USESPHERICALFROMREFLECTIONMAP&&e)if(r.SPHERICAL_HARMONICS){const t=e.preScaledHarmonics;l.updateVector3("vSphericalL00",t.l00),l.updateVector3("vSphericalL1_1",t.l1_1),l.updateVector3("vSphericalL10",t.l10),l.updateVector3("vSphericalL11",t.l11),l.updateVector3("vSphericalL2_2",t.l2_2),l.updateVector3("vSphericalL2_1",t.l2_1),l.updateVector3("vSphericalL20",t.l20),l.updateVector3("vSphericalL21",t.l21),l.updateVector3("vSphericalL22",t.l22)}else l.updateFloat3("vSphericalX",e.x.x,e.x.y,e.x.z),l.updateFloat3("vSphericalY",e.y.x,e.y.y,e.y.z),l.updateFloat3("vSphericalZ",e.z.x,e.z.y,e.z.z),l.updateFloat3("vSphericalXX_ZZ",e.xx.x-e.zz.x,e.xx.y-e.zz.y,e.xx.z-e.zz.z),l.updateFloat3("vSphericalYY_ZZ",e.yy.x-e.zz.x,e.yy.y-e.zz.y,e.yy.z-e.zz.z),l.updateFloat3("vSphericalZZ",e.zz.x,e.zz.y,e.zz.z),l.updateFloat3("vSphericalXY",e.xy.x,e.xy.y,e.xy.z),l.updateFloat3("vSphericalYZ",e.yz.x,e.yz.y,e.yz.z),l.updateFloat3("vSphericalZX",e.zx.x,e.zx.y,e.zx.z)}l.updateFloat3("vReflectionMicrosurfaceInfos",h.getSize().width,h.lodGenerationScale,h.lodGenerationOffset)}this._emissiveTexture&&Tn.EmissiveTextureEnabled&&(l.updateFloat2("vEmissiveInfos",this._emissiveTexture.coordinatesIndex,this._emissiveTexture.level),Ys(this._emissiveTexture,l,"emissive")),this._lightmapTexture&&Tn.LightmapTextureEnabled&&(l.updateFloat2("vLightmapInfos",this._lightmapTexture.coordinatesIndex,this._lightmapTexture.level),Ys(this._lightmapTexture,l,"lightmap")),Tn.SpecularTextureEnabled&&(this._metallicTexture?(l.updateFloat3("vReflectivityInfos",this._metallicTexture.coordinatesIndex,this._metallicTexture.level,this._ambientTextureStrength),Ys(this._metallicTexture,l,"reflectivity")):this._reflectivityTexture&&(l.updateFloat3("vReflectivityInfos",this._reflectivityTexture.coordinatesIndex,this._reflectivityTexture.level,1),Ys(this._reflectivityTexture,l,"reflectivity")),this._metallicReflectanceTexture&&(l.updateFloat2("vMetallicReflectanceInfos",this._metallicReflectanceTexture.coordinatesIndex,this._metallicReflectanceTexture.level),Ys(this._metallicReflectanceTexture,l,"metallicReflectance")),this._reflectanceTexture&&r.REFLECTANCE&&(l.updateFloat2("vReflectanceInfos",this._reflectanceTexture.coordinatesIndex,this._reflectanceTexture.level),Ys(this._reflectanceTexture,l,"reflectance")),this._microSurfaceTexture&&(l.updateFloat2("vMicroSurfaceSamplerInfos",this._microSurfaceTexture.coordinatesIndex,this._microSurfaceTexture.level),Ys(this._microSurfaceTexture,l,"microSurfaceSampler"))),this._bumpTexture&&a.getCaps().standardDerivatives&&Tn.BumpTextureEnabled&&!this._disableBumpMap&&(l.updateFloat3("vBumpInfos",this._bumpTexture.coordinatesIndex,this._bumpTexture.level,this._parallaxScaleBias),Ys(this._bumpTexture,l,"bump"),i._mirroredCameraPosition?l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?1:-1,this._invertNormalMapY?1:-1):l.updateFloat2("vTangentSpaceParams",this._invertNormalMapX?-1:1,this._invertNormalMapY?-1:1))}if(this.pointsCloud&&l.updateFloat("pointSize",this.pointSize),r.METALLICWORKFLOW){se.Color3[0].r=void 0===this._metallic||null===this._metallic?1:this._metallic,se.Color3[0].g=void 0===this._roughness||null===this._roughness?1:this._roughness,l.updateColor4("vReflectivityColor",se.Color3[0],1);const e=this.subSurface?._indexOfRefraction??1.5,t=1,s=Math.pow((e-t)/(e+t),2);this._metallicReflectanceColor.scaleToRef(s*this._metallicF0Factor,se.Color3[0]);const i=this._metallicF0Factor;l.updateColor4("vMetallicReflectanceFactors",se.Color3[0],i)}else l.updateColor4("vReflectivityColor",this._reflectivityColor,this._microSurface);l.updateColor3("vEmissiveColor",Tn.EmissiveTextureEnabled?this._emissiveColor:ee.BlackReadOnly),l.updateColor3("vReflectionColor",this._reflectionColor),!r.SS_REFRACTION&&this.subSurface?._linkRefractionWithTransparency?l.updateColor4("vAlbedoColor",this._albedoColor,1):l.updateColor4("vAlbedoColor",this._albedoColor,this.alpha),this._lightingInfos.x=this._directIntensity,this._lightingInfos.y=this._emissiveIntensity,this._lightingInfos.z=this._environmentIntensity*i.environmentIntensity,this._lightingInfos.w=this._specularIntensity,l.updateVector4("vLightingIntensity",this._lightingInfos),i.ambientColor.multiplyToRef(this._ambientColor,this._globalAmbientColor),l.updateColor3("vAmbientColor",this._globalAmbientColor),l.updateFloat2("vDebugMode",this.debugLimit,this.debugFactor)}i.texturesEnabled&&(this._albedoTexture&&Tn.DiffuseTextureEnabled&&l.setTexture("albedoSampler",this._albedoTexture),this._ambientTexture&&Tn.AmbientTextureEnabled&&l.setTexture("ambientSampler",this._ambientTexture),this._opacityTexture&&Tn.OpacityTextureEnabled&&l.setTexture("opacitySampler",this._opacityTexture),h&&Tn.ReflectionTextureEnabled&&(r.LODBASEDMICROSFURACE?l.setTexture("reflectionSampler",h):(l.setTexture("reflectionSampler",h._lodTextureMid||h),l.setTexture("reflectionSamplerLow",h._lodTextureLow||h),l.setTexture("reflectionSamplerHigh",h._lodTextureHigh||h)),r.USEIRRADIANCEMAP&&l.setTexture("irradianceSampler",h.irradianceTexture)),r.ENVIRONMENTBRDF&&l.setTexture("environmentBrdfSampler",this._environmentBRDFTexture),this._emissiveTexture&&Tn.EmissiveTextureEnabled&&l.setTexture("emissiveSampler",this._emissiveTexture),this._lightmapTexture&&Tn.LightmapTextureEnabled&&l.setTexture("lightmapSampler",this._lightmapTexture),Tn.SpecularTextureEnabled&&(this._metallicTexture?l.setTexture("reflectivitySampler",this._metallicTexture):this._reflectivityTexture&&l.setTexture("reflectivitySampler",this._reflectivityTexture),this._metallicReflectanceTexture&&l.setTexture("metallicReflectanceSampler",this._metallicReflectanceTexture),this._reflectanceTexture&&r.REFLECTANCE&&l.setTexture("reflectanceSampler",this._reflectanceTexture),this._microSurfaceTexture&&l.setTexture("microSurfaceSampler",this._microSurfaceTexture)),this._bumpTexture&&a.getCaps().standardDerivatives&&Tn.BumpTextureEnabled&&!this._disableBumpMap&&l.setTexture("bumpSampler",this._bumpTexture)),this.getScene().useOrderIndependentTransparency&&this.needAlphaBlendingForMesh(t)&&this.getScene().depthPeelingRenderer.bind(n),this._eventInfo.subMesh=s,this._callbackPluginEventBindForSubMesh(this._eventInfo),function(e,t,s){let i=t.clipPlane??s.clipPlane;zs(e,"vClipPlane",i),i=t.clipPlane2??s.clipPlane2,zs(e,"vClipPlane2",i),i=t.clipPlane3??s.clipPlane3,zs(e,"vClipPlane3",i),i=t.clipPlane4??s.clipPlane4,zs(e,"vClipPlane4",i),i=t.clipPlane5??s.clipPlane5,zs(e,"vClipPlane5",i),i=t.clipPlane6??s.clipPlane6,zs(e,"vClipPlane6",i)}(this._activeEffect,this,i),this.bindEyePosition(n)}else i.getEngine()._features.needToAlwaysBindUniformBuffers&&(this._needToBindSceneUbo=!0);!o&&this.isFrozen||(i.lightsEnabled&&!this._disableLighting&&function(e,t,s,i,r=4){const n=Math.min(t.lightSources.length,r);for(let r=0;r<n;r++)Ks(t.lightSources[r],r,e,s,"boolean"==typeof i?i:i.SPECULARTERM,t.receiveShadows)}(i,t,this._activeEffect,r,this._maxSimultaneousLights),(i.fogEnabled&&t.applyFog&&i.fogMode!==yr.FOGMODE_NONE||h||this.subSurface.refractionTexture||t.receiveShadows||r.PREPASS)&&this.bindView(n),function(e,t,s,i=!1){s&&e.fogEnabled&&(!t||t.applyFog)&&e.fogMode!==Ze.FOGMODE_NONE&&(s.setFloat4("vFogInfos",e.fogMode,e.fogStart,e.fogEnd,e.fogDensity),i?(e.fogColor.toLinearSpaceToRef(Xs,e.getEngine().useExactSrgbConversions),s.setColor3("vFogColor",Xs)):s.setColor3("vFogColor",e.fogColor))}(i,t,this._activeEffect,!0),r.NUM_MORPH_INFLUENCERS&&function(e,t){const s=e.morphTargetManager;e&&s&&t.setFloatArray("morphTargetInfluences",s.influences)}(t,this._activeEffect),r.BAKED_VERTEX_ANIMATION_TEXTURE&&t.bakedVertexAnimationManager?.bind(n,r.INSTANCES),this._imageProcessingConfiguration.bind(this._activeEffect),function(e,t,s){if(!e||e.LOGARITHMICDEPTH||e.indexOf&&e.indexOf("LOGARITHMICDEPTH")>=0){const e=s.activeCamera;e.mode===Ze.ORTHOGRAPHIC_CAMERA&&ue.Error("Logarithmic depth is not compatible with orthographic cameras!",20),t.setFloat("logarithmicDepthConstant",2/(Math.log(e.maxZ+1)/Math.LN2))}}(r,this._activeEffect,i)),this._afterBind(t,this._activeEffect,s),l.update()}getAnimatables(){const e=super.getAnimatables();return this._albedoTexture&&this._albedoTexture.animations&&this._albedoTexture.animations.length>0&&e.push(this._albedoTexture),this._ambientTexture&&this._ambientTexture.animations&&this._ambientTexture.animations.length>0&&e.push(this._ambientTexture),this._opacityTexture&&this._opacityTexture.animations&&this._opacityTexture.animations.length>0&&e.push(this._opacityTexture),this._reflectionTexture&&this._reflectionTexture.animations&&this._reflectionTexture.animations.length>0&&e.push(this._reflectionTexture),this._emissiveTexture&&this._emissiveTexture.animations&&this._emissiveTexture.animations.length>0&&e.push(this._emissiveTexture),this._metallicTexture&&this._metallicTexture.animations&&this._metallicTexture.animations.length>0?e.push(this._metallicTexture):this._reflectivityTexture&&this._reflectivityTexture.animations&&this._reflectivityTexture.animations.length>0&&e.push(this._reflectivityTexture),this._bumpTexture&&this._bumpTexture.animations&&this._bumpTexture.animations.length>0&&e.push(this._bumpTexture),this._lightmapTexture&&this._lightmapTexture.animations&&this._lightmapTexture.animations.length>0&&e.push(this._lightmapTexture),this._metallicReflectanceTexture&&this._metallicReflectanceTexture.animations&&this._metallicReflectanceTexture.animations.length>0&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&this._reflectanceTexture.animations&&this._reflectanceTexture.animations.length>0&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&this._microSurfaceTexture.animations&&this._microSurfaceTexture.animations.length>0&&e.push(this._microSurfaceTexture),e}_getReflectionTexture(){return this._reflectionTexture?this._reflectionTexture:this.getScene().environmentTexture}getActiveTextures(){const e=super.getActiveTextures();return this._albedoTexture&&e.push(this._albedoTexture),this._ambientTexture&&e.push(this._ambientTexture),this._opacityTexture&&e.push(this._opacityTexture),this._reflectionTexture&&e.push(this._reflectionTexture),this._emissiveTexture&&e.push(this._emissiveTexture),this._reflectivityTexture&&e.push(this._reflectivityTexture),this._metallicTexture&&e.push(this._metallicTexture),this._metallicReflectanceTexture&&e.push(this._metallicReflectanceTexture),this._reflectanceTexture&&e.push(this._reflectanceTexture),this._microSurfaceTexture&&e.push(this._microSurfaceTexture),this._bumpTexture&&e.push(this._bumpTexture),this._lightmapTexture&&e.push(this._lightmapTexture),e}hasTexture(e){return!!super.hasTexture(e)||(this._albedoTexture===e||(this._ambientTexture===e||(this._opacityTexture===e||(this._reflectionTexture===e||(this._emissiveTexture===e||(this._reflectivityTexture===e||(this._metallicTexture===e||(this._metallicReflectanceTexture===e||(this._reflectanceTexture===e||(this._microSurfaceTexture===e||(this._bumpTexture===e||this._lightmapTexture===e)))))))))))}setPrePassRenderer(){if(!this.subSurface?.isScatteringEnabled)return!1;const e=this.getScene().enableSubSurfaceForPrePass();return e&&(e.enabled=!0),!0}dispose(e,t){this._breakShaderLoadedCheck=!0,t&&(this._environmentBRDFTexture&&this.getScene().environmentBRDFTexture!==this._environmentBRDFTexture&&this._environmentBRDFTexture.dispose(),this._albedoTexture?.dispose(),this._ambientTexture?.dispose(),this._opacityTexture?.dispose(),this._reflectionTexture?.dispose(),this._emissiveTexture?.dispose(),this._metallicTexture?.dispose(),this._reflectivityTexture?.dispose(),this._bumpTexture?.dispose(),this._lightmapTexture?.dispose(),this._metallicReflectanceTexture?.dispose(),this._reflectanceTexture?.dispose(),this._microSurfaceTexture?.dispose()),this._renderTargets.dispose(),this._imageProcessingConfiguration&&this._imageProcessingObserver&&this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver),super.dispose(e,t)}}Hn.PBRMATERIAL_OPAQUE=$s.MATERIAL_OPAQUE,Hn.PBRMATERIAL_ALPHATEST=$s.MATERIAL_ALPHATEST,Hn.PBRMATERIAL_ALPHABLEND=$s.MATERIAL_ALPHABLEND,Hn.PBRMATERIAL_ALPHATESTANDBLEND=$s.MATERIAL_ALPHATESTANDBLEND,Hn.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=0,Hn.LIGHTFALLOFF_PHYSICAL=0,Hn.LIGHTFALLOFF_GLTF=1,Hn.LIGHTFALLOFF_STANDARD=2,Hn.ForceGLSL=!1,e([function(e){return r(9,e)}()],Hn.prototype,"_imageProcessingConfiguration",void 0),e([n("_markAllSubMeshesAsMiscDirty")],Hn.prototype,"debugMode",void 0);class zn extends Hn{get refractionTexture(){return this.subSurface.refractionTexture}set refractionTexture(e){this.subSurface.refractionTexture=e,e?this.subSurface.isRefractionEnabled=!0:this.subSurface.linkRefractionWithTransparency||(this.subSurface.isRefractionEnabled=!1)}get indexOfRefraction(){return this.subSurface.indexOfRefraction}set indexOfRefraction(e){this.subSurface.indexOfRefraction=e}get invertRefractionY(){return this.subSurface.invertRefractionY}set invertRefractionY(e){this.subSurface.invertRefractionY=e}get linkRefractionWithTransparency(){return this.subSurface.linkRefractionWithTransparency}set linkRefractionWithTransparency(e){this.subSurface.linkRefractionWithTransparency=e,e&&(this.subSurface.isRefractionEnabled=!0)}get usePhysicalLightFalloff(){return this._lightFalloff===Hn.LIGHTFALLOFF_PHYSICAL}set usePhysicalLightFalloff(e){e!==this.usePhysicalLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Hn.LIGHTFALLOFF_PHYSICAL:Hn.LIGHTFALLOFF_STANDARD)}get useGLTFLightFalloff(){return this._lightFalloff===Hn.LIGHTFALLOFF_GLTF}set useGLTFLightFalloff(e){e!==this.useGLTFLightFalloff&&(this._markAllSubMeshesAsTexturesDirty(),this._lightFalloff=e?Hn.LIGHTFALLOFF_GLTF:Hn.LIGHTFALLOFF_STANDARD)}get imageProcessingConfiguration(){return this._imageProcessingConfiguration}set imageProcessingConfiguration(e){this._attachImageProcessingConfiguration(e),this._markAllSubMeshesAsTexturesDirty()}get cameraColorCurvesEnabled(){return this.imageProcessingConfiguration.colorCurvesEnabled}set cameraColorCurvesEnabled(e){this.imageProcessingConfiguration.colorCurvesEnabled=e}get cameraColorGradingEnabled(){return this.imageProcessingConfiguration.colorGradingEnabled}set cameraColorGradingEnabled(e){this.imageProcessingConfiguration.colorGradingEnabled=e}get cameraToneMappingEnabled(){return this._imageProcessingConfiguration.toneMappingEnabled}set cameraToneMappingEnabled(e){this._imageProcessingConfiguration.toneMappingEnabled=e}get cameraExposure(){return this._imageProcessingConfiguration.exposure}set cameraExposure(e){this._imageProcessingConfiguration.exposure=e}get cameraContrast(){return this._imageProcessingConfiguration.contrast}set cameraContrast(e){this._imageProcessingConfiguration.contrast=e}get cameraColorGradingTexture(){return this._imageProcessingConfiguration.colorGradingTexture}set cameraColorGradingTexture(e){this._imageProcessingConfiguration.colorGradingTexture=e}get cameraColorCurves(){return this._imageProcessingConfiguration.colorCurves}set cameraColorCurves(e){this._imageProcessingConfiguration.colorCurves=e}constructor(e,t,s=!1){super(e,t,s),this.directIntensity=1,this.emissiveIntensity=1,this.environmentIntensity=1,this.specularIntensity=1,this.disableBumpMap=!1,this.ambientTextureStrength=1,this.ambientTextureImpactOnAnalyticalLights=zn.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,this.metallicF0Factor=1,this.metallicReflectanceColor=ee.White(),this.useOnlyMetallicFromMetallicReflectanceTexture=!1,this.ambientColor=new ee(0,0,0),this.albedoColor=new ee(1,1,1),this.reflectivityColor=new ee(1,1,1),this.reflectionColor=new ee(1,1,1),this.emissiveColor=new ee(0,0,0),this.microSurface=1,this.useLightmapAsShadowmap=!1,this.useAlphaFromAlbedoTexture=!1,this.forceAlphaTest=!1,this.alphaCutOff=.4,this.useSpecularOverAlpha=!0,this.useMicroSurfaceFromReflectivityMapAlpha=!1,this.useRoughnessFromMetallicTextureAlpha=!0,this.useRoughnessFromMetallicTextureGreen=!1,this.useMetallnessFromMetallicTextureBlue=!1,this.useAmbientOcclusionFromMetallicTextureRed=!1,this.useAmbientInGrayScale=!1,this.useAutoMicroSurfaceFromReflectivityMap=!1,this.useRadianceOverAlpha=!0,this.useObjectSpaceNormalMap=!1,this.useParallax=!1,this.useParallaxOcclusion=!1,this.parallaxScaleBias=.05,this.disableLighting=!1,this.forceIrradianceInFragment=!1,this.maxSimultaneousLights=4,this.invertNormalMapX=!1,this.invertNormalMapY=!1,this.twoSidedLighting=!1,this.useAlphaFresnel=!1,this.useLinearAlphaFresnel=!1,this.environmentBRDFTexture=null,this.forceNormalForward=!1,this.enableSpecularAntiAliasing=!1,this.useHorizonOcclusion=!0,this.useRadianceOcclusion=!0,this.unlit=!1,this.applyDecalMapAfterDetailMap=!1,this._environmentBRDFTexture=on(this.getScene())}getClassName(){return"PBRMaterial"}clone(e,t=!0,s=""){const i=re.Clone((()=>new zn(e,this.getScene())),this,{cloneTexturesOnlyOnce:t});return i.id=e,i.name=e,this.stencil.copyTo(i.stencil),this._clonePlugins(i,s),i}serialize(){const e=super.serialize();return e.customType="BABYLON.PBRMaterial",e}static Parse(e,t,s){const i=re.Parse((()=>new zn(e.name,t)),e,t,s);return e.stencil&&i.stencil.parse(e.stencil,t,s),$s._ParsePlugins(e,i,t,s),e.clearCoat&&i.clearCoat.parse(e.clearCoat,t,s),e.anisotropy&&i.anisotropy.parse(e.anisotropy,t,s),e.brdf&&i.brdf.parse(e.brdf,t,s),e.sheen&&i.sheen.parse(e.sheen,t,s),e.subSurface&&i.subSurface.parse(e.subSurface,t,s),e.iridescence&&i.iridescence.parse(e.iridescence,t,s),i}}zn.PBRMATERIAL_OPAQUE=Hn.PBRMATERIAL_OPAQUE,zn.PBRMATERIAL_ALPHATEST=Hn.PBRMATERIAL_ALPHATEST,zn.PBRMATERIAL_ALPHABLEND=Hn.PBRMATERIAL_ALPHABLEND,zn.PBRMATERIAL_ALPHATESTANDBLEND=Hn.PBRMATERIAL_ALPHATESTANDBLEND,zn.DEFAULT_AO_ON_ANALYTICAL_LIGHTS=Hn.DEFAULT_AO_ON_ANALYTICAL_LIGHTS,e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"directIntensity",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"emissiveIntensity",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"environmentIntensity",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"specularIntensity",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"disableBumpMap",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"albedoTexture",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"ambientTexture",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"ambientTextureStrength",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"ambientTextureImpactOnAnalyticalLights",void 0),e([o(),n("_markAllSubMeshesAsTexturesAndMiscDirty")],zn.prototype,"opacityTexture",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"reflectionTexture",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"emissiveTexture",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"reflectivityTexture",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"metallicTexture",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"metallic",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"roughness",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"metallicF0Factor",void 0),e([h(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"metallicReflectanceColor",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"useOnlyMetallicFromMetallicReflectanceTexture",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"metallicReflectanceTexture",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"reflectanceTexture",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"microSurfaceTexture",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"bumpTexture",void 0),e([o(),n("_markAllSubMeshesAsTexturesDirty",null)],zn.prototype,"lightmapTexture",void 0),e([h("ambient"),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"ambientColor",void 0),e([h("albedo"),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"albedoColor",void 0),e([h("reflectivity"),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"reflectivityColor",void 0),e([h("reflection"),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"reflectionColor",void 0),e([h("emissive"),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"emissiveColor",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"microSurface",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"useLightmapAsShadowmap",void 0),e([a(),n("_markAllSubMeshesAsTexturesAndMiscDirty")],zn.prototype,"useAlphaFromAlbedoTexture",void 0),e([a(),n("_markAllSubMeshesAsTexturesAndMiscDirty")],zn.prototype,"forceAlphaTest",void 0),e([a(),n("_markAllSubMeshesAsTexturesAndMiscDirty")],zn.prototype,"alphaCutOff",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"useSpecularOverAlpha",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"useMicroSurfaceFromReflectivityMapAlpha",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"useRoughnessFromMetallicTextureAlpha",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"useRoughnessFromMetallicTextureGreen",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"useMetallnessFromMetallicTextureBlue",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"useAmbientOcclusionFromMetallicTextureRed",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"useAmbientInGrayScale",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"useAutoMicroSurfaceFromReflectivityMap",void 0),e([a()],zn.prototype,"usePhysicalLightFalloff",null),e([a()],zn.prototype,"useGLTFLightFalloff",null),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"useRadianceOverAlpha",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"useObjectSpaceNormalMap",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"useParallax",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"useParallaxOcclusion",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"parallaxScaleBias",void 0),e([a(),n("_markAllSubMeshesAsLightsDirty")],zn.prototype,"disableLighting",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"forceIrradianceInFragment",void 0),e([a(),n("_markAllSubMeshesAsLightsDirty")],zn.prototype,"maxSimultaneousLights",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"invertNormalMapX",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"invertNormalMapY",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"twoSidedLighting",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"useAlphaFresnel",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"useLinearAlphaFresnel",void 0),e([n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"environmentBRDFTexture",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"forceNormalForward",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"enableSpecularAntiAliasing",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"useHorizonOcclusion",void 0),e([a(),n("_markAllSubMeshesAsTexturesDirty")],zn.prototype,"useRadianceOcclusion",void 0),e([a(),n("_markAllSubMeshesAsMiscDirty")],zn.prototype,"unlit",void 0),e([a(),n("_markAllSubMeshesAsMiscDirty")],zn.prototype,"applyDecalMapAfterDetailMap",void 0),I("BABYLON.PBRMaterial",zn),yt.prototype._partialLoadFile=function(e,t,s,i,r=null){this._loadFile(e,(e=>{s[t]=e,s._internalCount++,6===s._internalCount&&i(s)}),void 0,void 0,!0,((e,t)=>{r&&e&&r(e.status+" "+e.statusText,t)}))},yt.prototype._cascadeLoadFiles=function(e,t,s,i=null){const r=[];r._internalCount=0;for(let e=0;e<6;e++)this._partialLoadFile(s[e],e,r,t,i)},yt.prototype._cascadeLoadImgs=function(e,t,s,i,r=null,n){const a=[];a._internalCount=0;for(let o=0;o<6;o++)this._partialLoadImg(i[o],o,a,e,t,s,r,n)},yt.prototype._partialLoadImg=function(e,t,s,i,r,n,a=null,o){const h=kt();vt(e,(e=>{s[t]=e,s._internalCount++,i&&i.removePendingData(h),6===s._internalCount&&n&&n(r,s)}),((e,t)=>{i&&i.removePendingData(h),a&&a(e,t)}),i?i.offlineProvider:null,o),i&&i.addPendingData(h)},yt.prototype.createCubeTextureBase=function(e,t,s,i,r=null,n=null,a,o=null,h=!1,l=0,c=0,u=null,d=null,_=null,f=!1,p=null){const m=u||new Tt(this,7);m.isCube=!0,m.url=e,m.generateMipMaps=!i,m._lodGenerationScale=l,m._lodGenerationOffset=c,m._useSRGBBuffer=!!f&&this._caps.supportSRGBBuffers&&(this.version>1||this.isWebGPU||!!i),m!==u&&(m.label=e.substring(0,60)),this._doNotHandleContextLost||(m._extension=o,m._files=s,m._buffer=p);const g=e;this._transformTextureUrl&&!u&&(e=this._transformTextureUrl(e));const T=e.split("?")[0],E=T.lastIndexOf("."),A=Et(o||(E>-1?T.substring(E).toLowerCase():"")),y=(u,T)=>{e===g?n&&u&&n(u.status+" "+u.statusText,T):(ue.Warn(`Failed to load ${e}, falling back to the ${g}`),this.createCubeTextureBase(g,t,s,!!i,r,n,a,o,h,l,c,m,d,_,f,p))};if(A)A.then((i=>{const a=e=>{d&&d(m,e),i.loadCubeData(e,m,h,r,n)};p?a(p):s&&6===s.length?i.supportCascades?this._cascadeLoadFiles(t,(e=>a(e.map((e=>new Uint8Array(e))))),s,n):n?n("Textures type does not support cascades."):ue.Warn("Texture loader does not support cascades."):this._loadFile(e,(e=>a(new Uint8Array(e))),void 0,void 0,!0,y)}));else{if(!s||0===s.length)throw new Error("Cannot load cubemap because files were not defined, or the correct loader was not found.");this._cascadeLoadImgs(t,m,((e,t)=>{_&&_(e,t)}),s,n)}return this._internalTexturesCache.push(m),m},Ds.prototype._createDepthStencilCubeTexture=function(e,t){const s=new Tt(this,12);if(s.isCube=!0,1===this.webGLVersion)return ue.Error("Depth cube texture is not supported by WebGL 1."),s;const i={bilinearFiltering:!1,comparisonFunction:0,generateStencil:!1,...t},r=this._gl;this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,s,!0),this._setupDepthStencilTexture(s,e,i.generateStencil,i.bilinearFiltering,i.comparisonFunction);for(let t=0;t<6;t++)i.generateStencil?r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,r.DEPTH24_STENCIL8,e,e,0,r.DEPTH_STENCIL,r.UNSIGNED_INT_24_8,null):r.texImage2D(r.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,r.DEPTH_COMPONENT24,e,e,0,r.DEPTH_COMPONENT,r.UNSIGNED_INT,null);return this._bindTextureDirectly(r.TEXTURE_CUBE_MAP,null),this._internalTexturesCache.push(s),s},Ds.prototype._setCubeMapTextureParams=function(e,t,s){const i=this._gl;i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAG_FILTER,i.LINEAR),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MIN_FILTER,t?i.LINEAR_MIPMAP_LINEAR:i.LINEAR),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),e.samplingMode=t?Ze.TEXTURE_TRILINEAR_SAMPLINGMODE:Ze.TEXTURE_LINEAR_LINEAR,t&&this.getCaps().textureMaxLevel&&void 0!==s&&s>0&&(i.texParameteri(i.TEXTURE_CUBE_MAP,i.TEXTURE_MAX_LEVEL,s),e._maxLodLevel=s),this._bindTextureDirectly(i.TEXTURE_CUBE_MAP,null)},Ds.prototype.createCubeTexture=function(e,t,s,i,r=null,n=null,a,o=null,h=!1,l=0,c=0,u=null,d,_=!1,f=null){const p=this._gl;return this.createCubeTextureBase(e,t,s,!!i,r,n,a,o,h,l,c,u,(e=>this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,e,!0)),((e,t)=>{const s=this.needPOTTextures?Wt(t[0].width,this._caps.maxCubemapTextureSize):t[0].width,n=s,o=[p.TEXTURE_CUBE_MAP_POSITIVE_X,p.TEXTURE_CUBE_MAP_POSITIVE_Y,p.TEXTURE_CUBE_MAP_POSITIVE_Z,p.TEXTURE_CUBE_MAP_NEGATIVE_X,p.TEXTURE_CUBE_MAP_NEGATIVE_Y,p.TEXTURE_CUBE_MAP_NEGATIVE_Z];this._bindTextureDirectly(p.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(!1);const h=a?this._getInternalFormat(a,e._useSRGBBuffer):e._useSRGBBuffer?this._glSRGBExtensionValues.SRGB8_ALPHA8:p.RGBA;let l=a?this._getInternalFormat(a):p.RGBA;e._useSRGBBuffer&&1===this.webGLVersion&&(l=h);for(let e=0;e<o.length;e++)if(t[e].width!==s||t[e].height!==n){if(this._prepareWorkingCanvas(),!this._workingCanvas||!this._workingContext)return void ue.Warn("Cannot create canvas to resize texture.");this._workingCanvas.width=s,this._workingCanvas.height=n,this._workingContext.drawImage(t[e],0,0,t[e].width,t[e].height,0,0,s,n),p.texImage2D(o[e],0,h,l,p.UNSIGNED_BYTE,this._workingCanvas)}else p.texImage2D(o[e],0,h,l,p.UNSIGNED_BYTE,t[e]);i||p.generateMipmap(p.TEXTURE_CUBE_MAP),this._setCubeMapTextureParams(e,!i),e.width=s,e.height=n,e.isReady=!0,a&&(e.format=a),e.onLoadedObservable.notifyObservers(e),e.onLoadedObservable.clear(),r&&r()}),!!_,f)},Ds.prototype.generateMipMapsForCubemap=function(e,t=!0){if(e.generateMipMaps){const s=this._gl;this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,e,!0),s.generateMipmap(s.TEXTURE_CUBE_MAP),t&&this._bindTextureDirectly(s.TEXTURE_CUBE_MAP,null)}};const Xn=131072,Wn=131072;function Yn(e){return e.charCodeAt(0)+(e.charCodeAt(1)<<8)+(e.charCodeAt(2)<<16)+(e.charCodeAt(3)<<24)}const Kn=Yn("DXT1"),qn=Yn("DXT3"),Qn=Yn("DXT5"),jn=Yn("DX10");class Zn{static GetDDSInfo(e){const t=new Int32Array(e.buffer,e.byteOffset,31),s=new Int32Array(e.buffer,e.byteOffset,35);let i=1;t[2]&Xn&&(i=Math.max(1,t[7]));const r=t[21],n=r===jn?s[32]:0;let a=Ze.TEXTURETYPE_UNSIGNED_INT;switch(r){case 113:a=Ze.TEXTURETYPE_HALF_FLOAT;break;case 116:a=Ze.TEXTURETYPE_FLOAT;break;case jn:if(10===n){a=Ze.TEXTURETYPE_HALF_FLOAT;break}if(2===n){a=Ze.TEXTURETYPE_FLOAT;break}}return{width:t[4],height:t[3],mipmapCount:i,isFourCC:!(4&~t[20]),isRGB:!(64&~t[20]),isLuminance:(t[20]&Wn)===Wn,isCube:!(512&~t[28]),isCompressed:r===Kn||r===qn||r===Qn,dxgiFormat:n,textureType:a}}static _GetHalfFloatAsFloatRGBAArrayBuffer(e,t,s,i,r,n){const a=new Float32Array(i),o=new Uint16Array(r,s);let h=0;for(let s=0;s<t;s++)for(let t=0;t<e;t++){const i=4*(t+s*e);a[h]=rn(o[i]),a[h+1]=rn(o[i+1]),a[h+2]=rn(o[i+2]),Zn.StoreLODInAlphaChannel?a[h+3]=n:a[h+3]=rn(o[i+3]),h+=4}return a}static _GetHalfFloatRGBAArrayBuffer(e,t,s,i,r,n){if(Zn.StoreLODInAlphaChannel){const a=new Uint16Array(i),o=new Uint16Array(r,s);let h=0;for(let s=0;s<t;s++)for(let t=0;t<e;t++){const i=4*(t+s*e);a[h]=o[i],a[h+1]=o[i+1],a[h+2]=o[i+2],a[h+3]=sn(n),h+=4}return a}return new Uint16Array(r,s,i)}static _GetFloatRGBAArrayBuffer(e,t,s,i,r,n){if(Zn.StoreLODInAlphaChannel){const a=new Float32Array(i),o=new Float32Array(r,s);let h=0;for(let s=0;s<t;s++)for(let t=0;t<e;t++){const i=4*(t+s*e);a[h]=o[i],a[h+1]=o[i+1],a[h+2]=o[i+2],a[h+3]=n,h+=4}return a}return new Float32Array(r,s,i)}static _GetFloatAsHalfFloatRGBAArrayBuffer(e,t,s,i,r,n){const a=new Uint16Array(i),o=new Float32Array(r,s);let h=0;for(let s=0;s<t;s++)for(let t=0;t<e;t++)a[h]=sn(o[h]),a[h+1]=sn(o[h+1]),a[h+2]=sn(o[h+2]),Zn.StoreLODInAlphaChannel?a[h+3]=sn(n):a[h+3]=sn(o[h+3]),h+=4;return a}static _GetFloatAsUIntRGBAArrayBuffer(e,t,s,i,r,n){const a=new Uint8Array(i),o=new Float32Array(r,s);let h=0;for(let s=0;s<t;s++)for(let t=0;t<e;t++){const i=4*(t+s*e);a[h]=255*Q.Clamp(o[i]),a[h+1]=255*Q.Clamp(o[i+1]),a[h+2]=255*Q.Clamp(o[i+2]),Zn.StoreLODInAlphaChannel?a[h+3]=n:a[h+3]=255*Q.Clamp(o[i+3]),h+=4}return a}static _GetHalfFloatAsUIntRGBAArrayBuffer(e,t,s,i,r,n){const a=new Uint8Array(i),o=new Uint16Array(r,s);let h=0;for(let s=0;s<t;s++)for(let t=0;t<e;t++){const i=4*(t+s*e);a[h]=255*Q.Clamp(rn(o[i])),a[h+1]=255*Q.Clamp(rn(o[i+1])),a[h+2]=255*Q.Clamp(rn(o[i+2])),Zn.StoreLODInAlphaChannel?a[h+3]=n:a[h+3]=255*Q.Clamp(rn(o[i+3])),h+=4}return a}static _GetRGBAArrayBuffer(e,t,s,i,r,n,a,o,h){const l=new Uint8Array(i),c=new Uint8Array(r,s);let u=0;for(let s=0;s<t;s++)for(let t=0;t<e;t++){const i=4*(t+s*e);l[u]=c[i+n],l[u+1]=c[i+a],l[u+2]=c[i+o],l[u+3]=c[i+h],u+=4}return l}static _ExtractLongWordOrder(e){return 0===e||255===e||-16777216===e?0:1+Zn._ExtractLongWordOrder(e>>8)}static _GetRGBArrayBuffer(e,t,s,i,r,n,a,o){const h=new Uint8Array(i),l=new Uint8Array(r,s);let c=0;for(let s=0;s<t;s++)for(let t=0;t<e;t++){const i=3*(t+s*e);h[c]=l[i+n],h[c+1]=l[i+a],h[c+2]=l[i+o],c+=3}return h}static _GetLuminanceArrayBuffer(e,t,s,i,r){const n=new Uint8Array(i),a=new Uint8Array(r,s);let o=0;for(let s=0;s<t;s++)for(let t=0;t<e;t++){const i=t+s*e;n[o]=a[i],o++}return n}static UploadDDSLevels(e,t,s,i,r,n,a=-1,o,h=!0){let l=null;i.sphericalPolynomial&&(l=[]);const c=!!e.getCaps().s3tc;t.generateMipMaps=r;const u=new Int32Array(s.buffer,s.byteOffset,31);let d,_,f,p,m,g,T,E=0,A=0,y=1;if(542327876!==u[0])return void ue.Error("Invalid magic number in DDS header");if(!i.isFourCC&&!i.isRGB&&!i.isLuminance)return void ue.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");if(i.isCompressed&&!c)return void ue.Error("Compressed textures are not supported on this platform.");let b=u[22];p=u[1]+4;let R=!1;if(i.isFourCC)switch(d=u[21],d){case Kn:y=8,A=Ze.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT1;break;case qn:y=16,A=Ze.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT3;break;case Qn:y=16,A=Ze.TEXTUREFORMAT_COMPRESSED_RGBA_S3TC_DXT5;break;case 113:R=!0,b=64;break;case 116:R=!0,b=128;break;case jn:{p+=20;let e=!1;switch(i.dxgiFormat){case 10:R=!0,b=64,e=!0;break;case 2:R=!0,b=128,e=!0;break;case 88:i.isRGB=!0,i.isFourCC=!1,b=32,e=!0}if(e)break}default:return void ue.Error(["Unsupported FourCC code:",(x=d,String.fromCharCode(255&x,x>>8&255,x>>16&255,x>>24&255))])}var x;const M=Zn._ExtractLongWordOrder(u[23]),I=Zn._ExtractLongWordOrder(u[24]),S=Zn._ExtractLongWordOrder(u[25]),v=Zn._ExtractLongWordOrder(u[26]);R&&(A=e._getRGBABufferInternalSizedFormat(i.textureType)),g=1,u[2]&Xn&&!1!==r&&(g=Math.max(1,u[7]));const C=o||0,P=e.getCaps();for(let r=C;r<n;r++){for(_=u[4],f=u[3],T=0;T<g;++T){if(-1===a||a===T){const n=-1===a?T:0;if(!i.isCompressed&&i.isFourCC){t.format=Ze.TEXTUREFORMAT_RGBA,E=_*f*4;let i=null;if(e._badOS||e._badDesktopOS||!P.textureHalfFloat&&!P.textureFloat)128===b?(i=Zn._GetFloatAsUIntRGBAArrayBuffer(_,f,s.byteOffset+p,E,s.buffer,n),l&&0==n&&l.push(Zn._GetFloatRGBAArrayBuffer(_,f,s.byteOffset+p,E,s.buffer,n))):64===b&&(i=Zn._GetHalfFloatAsUIntRGBAArrayBuffer(_,f,s.byteOffset+p,E,s.buffer,n),l&&0==n&&l.push(Zn._GetHalfFloatAsFloatRGBAArrayBuffer(_,f,s.byteOffset+p,E,s.buffer,n))),t.type=Ze.TEXTURETYPE_UNSIGNED_INT;else{const e=P.textureFloat&&(h&&P.textureFloatLinearFiltering||!h),r=P.textureHalfFloat&&(h&&P.textureHalfFloatLinearFiltering||!h),a=(128===b||64===b&&!r)&&e?Ze.TEXTURETYPE_FLOAT:(64===b||128===b&&!e)&&r?Ze.TEXTURETYPE_HALF_FLOAT:Ze.TEXTURETYPE_UNSIGNED_BYTE;let o,c=null;if(128===b)switch(a){case Ze.TEXTURETYPE_FLOAT:o=Zn._GetFloatRGBAArrayBuffer,c=null;break;case Ze.TEXTURETYPE_HALF_FLOAT:o=Zn._GetFloatAsHalfFloatRGBAArrayBuffer,c=Zn._GetFloatRGBAArrayBuffer;break;case Ze.TEXTURETYPE_UNSIGNED_BYTE:o=Zn._GetFloatAsUIntRGBAArrayBuffer,c=Zn._GetFloatRGBAArrayBuffer}else switch(a){case Ze.TEXTURETYPE_FLOAT:o=Zn._GetHalfFloatAsFloatRGBAArrayBuffer,c=null;break;case Ze.TEXTURETYPE_HALF_FLOAT:o=Zn._GetHalfFloatRGBAArrayBuffer,c=Zn._GetHalfFloatAsFloatRGBAArrayBuffer;break;case Ze.TEXTURETYPE_UNSIGNED_BYTE:o=Zn._GetHalfFloatAsUIntRGBAArrayBuffer,c=Zn._GetHalfFloatAsFloatRGBAArrayBuffer}t.type=a,i=o(_,f,s.byteOffset+p,E,s.buffer,n),l&&0==n&&l.push(c?c(_,f,s.byteOffset+p,E,s.buffer,n):i)}i&&e._uploadDataToTextureDirectly(t,i,r,n)}else if(i.isRGB)t.type=Ze.TEXTURETYPE_UNSIGNED_INT,24===b?(t.format=Ze.TEXTUREFORMAT_RGB,E=_*f*3,m=Zn._GetRGBArrayBuffer(_,f,s.byteOffset+p,E,s.buffer,M,I,S),e._uploadDataToTextureDirectly(t,m,r,n)):(t.format=Ze.TEXTUREFORMAT_RGBA,E=_*f*4,m=Zn._GetRGBAArrayBuffer(_,f,s.byteOffset+p,E,s.buffer,M,I,S,v),e._uploadDataToTextureDirectly(t,m,r,n));else if(i.isLuminance){const i=e._getUnpackAlignement(),a=_;E=Math.floor((_+i-1)/i)*i*(f-1)+a,m=Zn._GetLuminanceArrayBuffer(_,f,s.byteOffset+p,E,s.buffer),t.format=Ze.TEXTUREFORMAT_LUMINANCE,t.type=Ze.TEXTURETYPE_UNSIGNED_INT,e._uploadDataToTextureDirectly(t,m,r,n)}else E=Math.max(4,_)/4*Math.max(4,f)/4*y,m=new Uint8Array(s.buffer,s.byteOffset+p,E),t.type=Ze.TEXTURETYPE_UNSIGNED_INT,e._uploadCompressedDataToTextureDirectly(t,A,_,f,m,r,n)}p+=b?_*f*(b/8):E,_*=.5,f*=.5,_=Math.max(1,_),f=Math.max(1,f)}if(void 0!==o)break}l&&l.length>0?i.sphericalPolynomial=In.ConvertCubeMapToSphericalPolynomial({size:u[4],right:l[0],left:l[1],up:l[2],down:l[3],front:l[4],back:l[5],format:Ze.TEXTUREFORMAT_RGBA,type:Ze.TEXTURETYPE_FLOAT,gammaSpace:!1}):i.sphericalPolynomial=void 0}}Zn.StoreLODInAlphaChannel=!1,Ds.prototype.createPrefilteredCubeTexture=function(e,t,s,i,r=null,n=null,a,o=null,h=!0){return this.createCubeTexture(e,t,null,!1,(e=>{if(!e)return void(r&&r(null));const n=e.texture;if(h?e.info.sphericalPolynomial&&(n._sphericalPolynomial=e.info.sphericalPolynomial):n._sphericalPolynomial=new xn,n._source=9,this.getCaps().textureLOD)return void(r&&r(n));const a=this._gl,o=e.width;if(!o)return;const l=[];for(let r=0;r<3;r++){const h=1-r/2,c=i,u=Q.Log2(o)*s+i,d=c+(u-c)*h,_=Math.round(Math.min(Math.max(d,0),u)),f=new Tt(this,2);if(f.type=n.type,f.format=n.format,f.width=Math.pow(2,Math.max(Q.Log2(o)-_,0)),f.height=f.width,f.isCube=!0,f._cachedWrapU=Ze.TEXTURE_CLAMP_ADDRESSMODE,f._cachedWrapV=Ze.TEXTURE_CLAMP_ADDRESSMODE,this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,f,!0),f.samplingMode=Ze.TEXTURE_LINEAR_LINEAR,a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_CUBE_MAP,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE),e.isDDS){const t=e.info,s=e.data;this._unpackFlipY(t.isCompressed),Zn.UploadDDSLevels(this,f,s,t,!0,6,_)}else ue.Warn("DDS is the only prefiltered cube map supported so far.");this._bindTextureDirectly(a.TEXTURE_CUBE_MAP,null);const p=new Pr(t);p._isCube=!0,p._texture=f,f.isReady=!0,l.push(p)}n._lodTextureHigh=l[2],n._lodTextureMid=l[1],n._lodTextureLow=l[0],r&&r(n)}),n,a,o,h,s,i)};class $n extends Pr{set boundingBoxSize(e){if(this._boundingBoxSize&&this._boundingBoxSize.equals(e))return;this._boundingBoxSize=e;const t=this.getScene();t&&t.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag)}get boundingBoxSize(){return this._boundingBoxSize}set rotationY(e){this._rotationY=e,this.setReflectionTextureMatrix(V.RotationY(this._rotationY))}get rotationY(){return this._rotationY}get noMipmap(){return this._noMipmap}get forcedExtension(){return this._forcedExtension}static CreateFromImages(e,t,s){let i="";return e.forEach((e=>i+=e)),new $n(i,t,null,s,e)}static CreateFromPrefilteredData(e,t,s=null,i=!0){const r=t.useDelayedTextureLoading;t.useDelayedTextureLoading=!1;const n=new $n(e,t,null,!1,null,null,null,void 0,!0,s,i);return t.useDelayedTextureLoading=r,n}constructor(e,t,s=null,i=!1,r=null,n=null,a=null,o=Ze.TEXTUREFORMAT_RGBA,h=!1,l=null,c=!1,u=.8,d=0,_,f){super(t),this.onLoadObservable=new g,this.boundingBoxPosition=U.Zero(),this._rotationY=0,this._files=null,this._forcedExtension=null,this._extensions=null,this._textureMatrixRefraction=new V,this._buffer=null,this.name=e,this.url=e,this._noMipmap=i,this.hasAlpha=!1,this.isCube=!0,this._textureMatrix=V.Identity(),this.coordinatesMode=Dr.CUBIC_MODE;let p=null,m=null;null===s||Array.isArray(s)?(this._noMipmap=i,this._format=o,this._createPolynomials=c,p=s,this._loaderOptions=_,this._useSRGBBuffer=f,this._lodScale=u,this._lodOffset=d):(p=s.extensions??null,this._noMipmap=s.noMipmap??!1,r=s.files??null,m=s.buffer??null,this._format=s.format??Ze.TEXTUREFORMAT_RGBA,h=s.prefiltered??!1,l=s.forcedExtension??null,this._createPolynomials=s.createPolynomials??!1,this._lodScale=s.lodScale??.8,this._lodOffset=s.lodOffset??0,this._loaderOptions=s.loaderOptions,this._useSRGBBuffer=s.useSRGBBuffer,n=s.onLoad??null,a=s.onError??null),(e||r)&&this.updateURL(e,l,n,h,a,p,this.getScene()?.useDelayedTextureLoading,r,m)}getClassName(){return"CubeTexture"}updateURL(e,t=null,s=null,i=!1,r=null,n=null,a=!1,o=null,h=null){this.name&&!this.name.startsWith("data:")||(this.name=e),this.url=e,t&&(this._forcedExtension=t);const l=e.lastIndexOf("."),c=t||(l>-1?e.substring(l).toLowerCase():""),u=0===c.indexOf(".dds"),d=0===c.indexOf(".env"),_=0===c.indexOf(".basis");if(d?(this.gammaSpace=!1,this._prefiltered=!1,this.anisotropicFilteringLevel=1):(this._prefiltered=i,i&&(this.gammaSpace=!1,this.anisotropicFilteringLevel=1)),o)this._files=o;else if(_||d||u||n||(n=["_px.jpg","_py.jpg","_pz.jpg","_nx.jpg","_ny.jpg","_nz.jpg"]),this._files=this._files||[],this._files.length=0,n){for(let t=0;t<n.length;t++)this._files.push(e+n[t]);this._extensions=n}this._buffer=h,a?(this.delayLoadState=Ze.DELAYLOADSTATE_NOTLOADED,this._delayedOnLoad=s,this._delayedOnError=r):this._loadTexture(s,r)}delayLoad(e){this.delayLoadState===Ze.DELAYLOADSTATE_NOTLOADED&&(e&&(this._forcedExtension=e),this.delayLoadState=Ze.DELAYLOADSTATE_LOADED,this._loadTexture(this._delayedOnLoad,this._delayedOnError))}getReflectionTextureMatrix(){return this._textureMatrix}setReflectionTextureMatrix(e){if(e.updateFlag===this._textureMatrix.updateFlag)return;if(e.isIdentity()!==this._textureMatrix.isIdentity()&&this.getScene()?.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag,(e=>-1!==e.getActiveTextures().indexOf(this))),this._textureMatrix=e,!this.getScene()?.useRightHandedSystem)return;const t=z.Vector3[0],s=z.Quaternion[0],i=z.Vector3[1];this._textureMatrix.decompose(t,s,i),s.z*=-1,s.w*=-1,V.ComposeToRef(t,s,i,this._textureMatrixRefraction)}getRefractionTextureMatrix(){return this.getScene()?.useRightHandedSystem?this._textureMatrixRefraction:this._textureMatrix}_loadTexture(e=null,t=null){const s=this.getScene(),i=this._texture;this._texture=this._getFromCache(this.url,this._noMipmap,void 0,void 0,this._useSRGBBuffer,this.isCube);const r=()=>{this.onLoadObservable.notifyObservers(this),i&&(i.dispose(),this.getScene()?.markAllMaterialsAsDirty(Ze.MATERIAL_TextureDirtyFlag)),e&&e()},n=(e,s)=>{this._loadingError=!0,this._errorObject={message:e,exception:s},t&&t(e,s),Dr.OnTextureLoadErrorObservable.notifyObservers(this)};this._texture?this._texture.isReady?Yt.SetImmediate((()=>r())):this._texture.onLoadedObservable.add((()=>r())):(this._prefiltered?this._texture=this._getEngine().createPrefilteredCubeTexture(this.url,s,this._lodScale,this._lodOffset,e,n,this._format,this._forcedExtension,this._createPolynomials):this._texture=this._getEngine().createCubeTexture(this.url,s,this._files,this._noMipmap,e,n,this._format,this._forcedExtension,!1,this._lodScale,this._lodOffset,null,this._loaderOptions,!!this._useSRGBBuffer,this._buffer),this._texture?.onLoadedObservable.add((()=>this.onLoadObservable.notifyObservers(this))))}static Parse(e,t,s){const i=re.Parse((()=>{let i=!1;return e.prefiltered&&(i=e.prefiltered),new $n(s+(e.url??e.name),t,e.extensions,!1,e.files||null,null,null,void 0,i,e.forcedExtension)}),e,t);if(e.boundingBoxPosition&&(i.boundingBoxPosition=U.FromArray(e.boundingBoxPosition)),e.boundingBoxSize&&(i.boundingBoxSize=U.FromArray(e.boundingBoxSize)),e.animations)for(let t=0;t<e.animations.length;t++){const s=e.animations[t],r=S("BABYLON.Animation");r&&i.animations.push(r.Parse(s))}return i}clone(){let e=0;const t=re.Clone((()=>{const t=new $n(this.url,this.getScene()||this._getEngine(),this._extensions,this._noMipmap,this._files);return e=t.uniqueId,t}),this);return t.uniqueId=e,t}}e([a()],$n.prototype,"url",void 0),e([c()],$n.prototype,"boundingBoxPosition",void 0),e([c()],$n.prototype,"boundingBoxSize",null),e([a("rotationY")],$n.prototype,"rotationY",null),e([a("files")],$n.prototype,"_files",void 0),e([a("forcedExtension")],$n.prototype,"_forcedExtension",void 0),e([a("extensions")],$n.prototype,"_extensions",void 0),e([_("textureMatrix")],$n.prototype,"_textureMatrix",void 0),e([_("textureMatrixRefraction")],$n.prototype,"_textureMatrixRefraction",void 0),Dr._CubeTextureParser=$n.Parse,I("BABYLON.CubeTexture",$n),oi._GroundMeshParser=(e,t)=>Jn.Parse(e,t);class Jn extends oi{constructor(e,t){super(e,t),this.generateOctree=!1}getClassName(){return"GroundMesh"}get subdivisions(){return Math.min(this._subdivisionsX,this._subdivisionsY)}get subdivisionsX(){return this._subdivisionsX}get subdivisionsY(){return this._subdivisionsY}optimize(e,t=32){this._subdivisionsX=e,this._subdivisionsY=e,this.subdivide(e);const s=this;s.createOrUpdateSubmeshesOctree&&s.createOrUpdateSubmeshesOctree(t)}getHeightAtCoordinates(e,t){const s=this.getWorldMatrix(),i=z.Matrix[5];s.invertToRef(i);const r=z.Vector3[8];if(U.TransformCoordinatesFromFloatsToRef(e,0,t,i,r),e=r.x,t=r.z,e<this._minX||e>=this._maxX||t<=this._minZ||t>this._maxZ)return this.position.y;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const n=this._getFacetAt(e,t),a=-(n.x*e+n.z*t+n.w)/n.y;return U.TransformCoordinatesFromFloatsToRef(0,a,0,s,r),r.y}getNormalAtCoordinates(e,t){const s=new U(0,1,0);return this.getNormalAtCoordinatesToRef(e,t,s),s}getNormalAtCoordinatesToRef(e,t,s){const i=this.getWorldMatrix(),r=z.Matrix[5];i.invertToRef(r);const n=z.Vector3[8];if(U.TransformCoordinatesFromFloatsToRef(e,0,t,r,n),e=n.x,t=n.z,e<this._minX||e>this._maxX||t<this._minZ||t>this._maxZ)return this;this._heightQuads&&0!=this._heightQuads.length||(this._initHeightQuads(),this._computeHeightQuads());const a=this._getFacetAt(e,t);return U.TransformNormalFromFloatsToRef(a.x,a.y,a.z,i,s),this}updateCoordinateHeights(){return this._heightQuads&&0!=this._heightQuads.length||this._initHeightQuads(),this._computeHeightQuads(),this}_getFacetAt(e,t){const s=Math.floor((e+this._maxX)*this._subdivisionsX/this._width),i=Math.floor(-(t+this._maxZ)*this._subdivisionsY/this._height+this._subdivisionsY),r=this._heightQuads[i*this._subdivisionsX+s];let n;return n=t<r.slope.x*e+r.slope.y?r.facet1:r.facet2,n}_initHeightQuads(){const e=this._subdivisionsX,t=this._subdivisionsY;this._heightQuads=new Array;for(let s=0;s<t;s++)for(let t=0;t<e;t++){const i={slope:B.Zero(),facet1:new k(0,0,0,0),facet2:new k(0,0,0,0)};this._heightQuads[s*e+t]=i}return this}_computeHeightQuads(){const e=this.getVerticesData(ns.PositionKind);if(!e)return this;const t=z.Vector3[3],s=z.Vector3[2],i=z.Vector3[1],r=z.Vector3[0],n=z.Vector3[4],a=z.Vector3[5],o=z.Vector3[6],h=z.Vector3[7],l=z.Vector3[8];let c=0,u=0,d=0,_=0,f=0,p=0,m=0;const g=this._subdivisionsX,T=this._subdivisionsY;for(let E=0;E<T;E++)for(let T=0;T<g;T++){c=3*T,u=E*(g+1)*3,d=(E+1)*(g+1)*3,t.x=e[u+c],t.y=e[u+c+1],t.z=e[u+c+2],s.x=e[u+c+3],s.y=e[u+c+4],s.z=e[u+c+5],i.x=e[d+c],i.y=e[d+c+1],i.z=e[d+c+2],r.x=e[d+c+3],r.y=e[d+c+4],r.z=e[d+c+5],_=(r.z-t.z)/(r.x-t.x),f=t.z-_*t.x,s.subtractToRef(t,n),i.subtractToRef(t,a),r.subtractToRef(t,o),U.CrossToRef(o,a,h),U.CrossToRef(n,o,l),h.normalize(),l.normalize(),p=-(h.x*t.x+h.y*t.y+h.z*t.z),m=-(l.x*s.x+l.y*s.y+l.z*s.z);const A=this._heightQuads[E*g+T];A.slope.copyFromFloats(_,f),A.facet1.copyFromFloats(h.x,h.y,h.z,p),A.facet2.copyFromFloats(l.x,l.y,l.z,m)}return this}serialize(e){super.serialize(e),e.subdivisionsX=this._subdivisionsX,e.subdivisionsY=this._subdivisionsY,e.minX=this._minX,e.maxX=this._maxX,e.minZ=this._minZ,e.maxZ=this._maxZ,e.width=this._width,e.height=this._height}static Parse(e,t){const s=new Jn(e.name,t);return s._subdivisionsX=e.subdivisionsX||1,s._subdivisionsY=e.subdivisionsY||1,s._minX=e.minX,s._maxX=e.maxX,s._minZ=e.minZ,s._maxZ=e.maxZ,s._width=e.width,s._height=e.height,s}}function ea(e){const t=[],s=[],i=[],r=[];let n,a;const o=e.width||1,h=e.height||1,l=0|(e.subdivisionsX||e.subdivisions||1),c=0|(e.subdivisionsY||e.subdivisions||1);for(n=0;n<=c;n++)for(a=0;a<=l;a++){const e=new U(a*o/l-o/2,0,(c-n)*h/c-h/2),t=new U(0,1,0);s.push(e.x,e.y,e.z),i.push(t.x,t.y,t.z),r.push(a/l,1-n/c)}for(n=0;n<c;n++)for(a=0;a<l;a++)t.push(a+1+(n+1)*(l+1)),t.push(a+1+n*(l+1)),t.push(a+n*(l+1)),t.push(a+(n+1)*(l+1)),t.push(a+1+(n+1)*(l+1)),t.push(a+n*(l+1));const u=new Es;return u.indices=t,u.positions=s,u.normals=i,u.uvs=r,u}function ta(e){const t=void 0!==e.xmin&&null!==e.xmin?e.xmin:-1,s=void 0!==e.zmin&&null!==e.zmin?e.zmin:-1,i=void 0!==e.xmax&&null!==e.xmax?e.xmax:1,r=void 0!==e.zmax&&null!==e.zmax?e.zmax:1,n=e.subdivisions||{w:1,h:1},a=e.precision||{w:1,h:1},o=[],h=[],l=[],c=[];let u,d,_,f;n.h=n.h<1?1:n.h,n.w=n.w<1?1:n.w,a.w=a.w<1?1:a.w,a.h=a.h<1?1:a.h;const p=(i-t)/n.w,m=(r-s)/n.h;function g(e,t,s,i){const r=h.length/3,n=a.w+1;for(u=0;u<a.h;u++)for(d=0;d<a.w;d++){const e=[r+d+u*n,r+(d+1)+u*n,r+(d+1)+(u+1)*n,r+d+(u+1)*n];o.push(e[1]),o.push(e[2]),o.push(e[3]),o.push(e[0]),o.push(e[1]),o.push(e[3])}const _=U.Zero(),f=new U(0,1,0);for(u=0;u<=a.h;u++)for(_.z=u*(i-t)/a.h+t,d=0;d<=a.w;d++)_.x=d*(s-e)/a.w+e,_.y=0,h.push(_.x,_.y,_.z),l.push(f.x,f.y,f.z),c.push(d/a.w,u/a.h)}for(_=0;_<n.h;_++)for(f=0;f<n.w;f++)g(t+f*p,s+_*m,t+(f+1)*p,s+(_+1)*m);const T=new Es;return T.indices=o,T.positions=h,T.normals=l,T.uvs=c,T}function sa(e){const t=[],s=[],i=[],r=[];let n,a;const o=e.colorFilter||new ee(.3,.59,.11),h=e.alphaFilter||0;let l=!1;if(e.minHeight>e.maxHeight){l=!0;const t=e.maxHeight;e.maxHeight=e.minHeight,e.minHeight=t}for(n=0;n<=e.subdivisions;n++)for(a=0;a<=e.subdivisions;a++){const t=new U(a*e.width/e.subdivisions-e.width/2,0,(e.subdivisions-n)*e.height/e.subdivisions-e.height/2),c=4*(((t.x+e.width/2)/e.width*(e.bufferWidth-1)|0)+((1-(t.z+e.height/2)/e.height)*(e.bufferHeight-1)|0)*e.bufferWidth);let u=e.buffer[c]/255,d=e.buffer[c+1]/255,_=e.buffer[c+2]/255;const f=e.buffer[c+3]/255;l&&(u=1-u,d=1-d,_=1-_);const p=u*o.r+d*o.g+_*o.b;t.y=f>=h?e.minHeight+(e.maxHeight-e.minHeight)*p:e.minHeight-A,e.heightBuffer&&(e.heightBuffer[n*(e.subdivisions+1)+a]=t.y),s.push(t.x,t.y,t.z),i.push(0,0,0),r.push(a/e.subdivisions,1-n/e.subdivisions)}for(n=0;n<e.subdivisions;n++)for(a=0;a<e.subdivisions;a++){const i=a+1+(n+1)*(e.subdivisions+1),r=a+1+n*(e.subdivisions+1),o=a+n*(e.subdivisions+1),h=a+(n+1)*(e.subdivisions+1),l=s[3*i+1]>=e.minHeight,c=s[3*r+1]>=e.minHeight,u=s[3*o+1]>=e.minHeight;l&&c&&u&&(t.push(i),t.push(r),t.push(o));s[3*h+1]>=e.minHeight&&l&&u&&(t.push(h),t.push(i),t.push(o))}Es.ComputeNormals(s,t,i);const c=new Es;return c.indices=t,c.positions=s,c.normals=i,c.uvs=r,c}function ia(e){let t=[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23];const s=[0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0],i=[];let r=[];const n=e.width||e.size||1,a=e.height||e.size||1,o=e.depth||e.size||1,h=e.wrap||!1;let l=void 0===e.topBaseAt?1:e.topBaseAt,c=void 0===e.bottomBaseAt?0:e.bottomBaseAt;l=(l+4)%4,c=(c+4)%4;let u=[2,0,3,1][l],d=[2,0,1,3][c],_=[1,-1,1,-1,-1,1,-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,1,1,-1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,-1,1];if(h){t=[2,3,0,2,0,1,4,5,6,4,6,7,9,10,11,9,11,8,12,14,15,12,13,14],_=[-1,1,1,1,1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,1,1,1,1,-1,1,-1,-1,1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,-1];let e=[[1,1,1],[-1,1,1],[-1,1,-1],[1,1,-1]],s=[[-1,-1,1],[1,-1,1],[1,-1,-1],[-1,-1,-1]];const i=[17,18,19,16],r=[22,23,20,21];for(;u>0;)e.unshift(e.pop()),i.unshift(i.pop()),u--;for(;d>0;)s.unshift(s.pop()),r.unshift(r.pop()),d--;e=e.flat(),s=s.flat(),_=_.concat(e).concat(s),t.push(i[0],i[2],i[3],i[0],i[1],i[2]),t.push(r[0],r[2],r[3],r[0],r[1],r[2])}const f=[n/2,a/2,o/2];r=_.reduce(((e,t,s)=>e.concat(t*f[s%3])),[]);const p=0===e.sideOrientation?0:e.sideOrientation||Es.DEFAULTSIDE,m=e.faceUV||new Array(6),g=e.faceColors,T=[];for(let e=0;e<6;e++)void 0===m[e]&&(m[e]=new k(0,0,1,1)),g&&void 0===g[e]&&(g[e]=new te(1,1,1,1));for(let e=0;e<6;e++)if(i.push(m[e].z,m[e].w),i.push(m[e].x,m[e].w),i.push(m[e].x,m[e].y),i.push(m[e].z,m[e].y),g)for(let t=0;t<4;t++)T.push(g[e].r,g[e].g,g[e].b,g[e].a);Es._ComputeSides(p,r,t,s,i,e.frontUVs,e.backUVs);const E=new Es;if(E.indices=t,E.positions=r,E.normals=s,E.uvs=i,g){const e=p===Es.DOUBLESIDE?T.concat(T):T;E.colors=e}return E}function ra(e,t={},s=null){const i=new oi(e,s);t.sideOrientation=oi._GetDefaultSideOrientation(t.sideOrientation),i._originalBuilderSideOrientation=t.sideOrientation;return ia(t).applyToMesh(i,t.updatable),i}Es.CreateGround=ea,Es.CreateTiledGround=ta,Es.CreateGroundFromHeightMap=sa,oi.CreateGround=(e,t,s,i,r,n)=>function(e,t={},s){const i=new Jn(e,s);return i._setReady(!1),i._subdivisionsX=t.subdivisionsX||t.subdivisions||1,i._subdivisionsY=t.subdivisionsY||t.subdivisions||1,i._width=t.width||1,i._height=t.height||1,i._maxX=i._width/2,i._maxZ=i._height/2,i._minX=-i._maxX,i._minZ=-i._maxZ,ea(t).applyToMesh(i,t.updatable),i._setReady(!0),i}(e,{width:t,height:s,subdivisions:i,updatable:n},r),oi.CreateTiledGround=(e,t,s,i,r,n,a,o,h)=>function(e,t,s=null){const i=new oi(e,s);return ta(t).applyToMesh(i,t.updatable),i}(e,{xmin:t,zmin:s,xmax:i,zmax:r,subdivisions:n,precision:a,updatable:h},o),oi.CreateGroundFromHeightMap=(e,t,s,i,r,n,a,o,h,l,c)=>function(e,t,s={},i=null){const r=s.width||10,n=s.height||10,a=s.subdivisions||1,o=s.minHeight||0,h=s.maxHeight||1,l=s.colorFilter||new ee(.3,.59,.11),c=s.alphaFilter||0,u=s.updatable,d=s.onReady;i=i||C.LastCreatedScene;const _=new Jn(e,i);let f;_._subdivisionsX=a,_._subdivisionsY=a,_._width=r,_._height=n,_._maxX=_._width/2,_._maxZ=_._height/2,_._minX=-_._maxX,_._minZ=-_._maxZ,_._setReady(!1),s.passHeightBufferInCallback&&(f=new Float32Array((a+1)*(a+1)));const p=(e,t,s)=>{sa({width:r,height:n,subdivisions:a,minHeight:o,maxHeight:h,colorFilter:l,buffer:e,bufferWidth:t,bufferHeight:s,alphaFilter:c,heightBuffer:f}).applyToMesh(_,u),d&&d(_,f),_._setReady(!0)};if("string"==typeof t){const e=e=>{const t=e.width,s=e.height;if(i.isDisposed)return;const r=i?.getEngine().resizeImageBitmap(e,t,s);p(r,t,s)};Yt.LoadImage(t,e,s.onError?s.onError:()=>{},i.offlineProvider)}else p(t.data,t.width,t.height);return _}(e,t,{width:s,height:i,subdivisions:r,minHeight:n,maxHeight:a,updatable:h,onReady:l,alphaFilter:c},o),Es.CreateBox=ia,oi.CreateBox=(e,t,s=null,i,r)=>ra(e,{size:t,sideOrientation:r,updatable:i},s);class na{get resolve(){return this._resolve}get reject(){return this._reject}constructor(){this.promise=new Promise(((e,t)=>{this._resolve=e,this._reject=t}))}}class aa{constructor(){this._currentOperation=Promise.resolve()}lockAsync(e,t){t?.throwIfAborted();const s=t?()=>(t.throwIfAborted(),e()):e,i=this._currentOperation.then(s);return this._currentOperation=new Promise((e=>i.then((()=>e()),e))),i}static async LockAsync(e,t,s){if(s?.throwIfAborted(),0===t.length)return await e();const i=new na;let r=0;return t.forEach((n=>n.lockAsync((async()=>(r++,r===t.length&&i.resolve(await e()),i.promise)),s).catch((e=>i.reject(e))))),i.promise}}class oa{get currentFrame(){return this._currentFrame}get weight(){return this._weight}get currentValue(){return this._currentValue}get targetPath(){return this._targetPath}get target(){return this._currentActiveTarget}get isAdditive(){return this._host&&this._host.isAdditive}constructor(e,t,s,i){if(this._events=new Array,this._currentFrame=0,this._originalValue=new Array,this._originalBlendValue=null,this._offsetsCache={},this._highLimitsCache={},this._stopped=!1,this._blendingFactor=0,this._currentValue=null,this._currentActiveTarget=null,this._directTarget=null,this._targetPath="",this._weight=1,this._absoluteFrameOffset=0,this._previousElapsedTime=0,this._yoyoDirection=1,this._previousAbsoluteFrame=0,this._targetIsArray=!1,this._animation=t,this._target=e,this._scene=s,this._host=i,this._activeTargets=[],t._runtimeAnimations.push(this),this._animationState={key:0,repeatCount:0,loopMode:this._getCorrectLoopMode()},this._animation.dataType===xi.ANIMATIONTYPE_MATRIX&&(this._animationState.workValue=V.Zero()),this._keys=this._animation.getKeys(),this._minFrame=this._keys[0].frame,this._maxFrame=this._keys[this._keys.length-1].frame,this._minValue=this._keys[0].value,this._maxValue=this._keys[this._keys.length-1].value,0!==this._minFrame){const e={frame:0,value:this._minValue};this._keys.splice(0,0,e)}if(this._target instanceof Array){let e=0;for(const t of this._target)this._preparePath(t,e),this._getOriginalValues(e),e++;this._targetIsArray=!0}else this._preparePath(this._target),this._getOriginalValues(),this._targetIsArray=!1,this._directTarget=this._activeTargets[0];const r=t.getEvents();r&&r.length>0&&r.forEach((e=>{this._events.push(e._clone())})),this._enableBlending=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.enableBlending:this._animation.enableBlending}_preparePath(e,t=0){const s=this._animation.targetPropertyPath;if(s.length>1){let i=e;for(let e=0;e<s.length-1;e++){const t=s[e];if(i=i[t],void 0===i)throw new Error(`Invalid property (${t}) in property path (${s.join(".")})`)}this._targetPath=s[s.length-1],this._activeTargets[t]=i}else this._targetPath=s[0],this._activeTargets[t]=e;if(void 0===this._activeTargets[t][this._targetPath])throw new Error(`Invalid property (${this._targetPath}) in property path (${s.join(".")})`)}get animation(){return this._animation}reset(e=!1){if(e)if(this._target instanceof Array){let e=0;for(const t of this._target)void 0!==this._originalValue[e]&&this._setValue(t,this._activeTargets[e],this._originalValue[e],-1,e),e++}else void 0!==this._originalValue[0]&&this._setValue(this._target,this._directTarget,this._originalValue[0],-1,0);this._offsetsCache={},this._highLimitsCache={},this._currentFrame=0,this._blendingFactor=0;for(let e=0;e<this._events.length;e++)this._events[e].isDone=!1}isStopped(){return this._stopped}dispose(){const e=this._animation.runtimeAnimations.indexOf(this);e>-1&&this._animation.runtimeAnimations.splice(e,1)}setValue(e,t){if(this._targetIsArray)for(let s=0;s<this._target.length;s++){const i=this._target[s];this._setValue(i,this._activeTargets[s],e,t,s)}else this._setValue(this._target,this._directTarget,e,t,0)}_getOriginalValues(e=0){let t;const s=this._activeTargets[e];t=s.getLocalMatrix&&"_matrix"===this._targetPath?s.getLocalMatrix():s[this._targetPath],t&&t.clone?this._originalValue[e]=t.clone():this._originalValue[e]=t}_setValue(e,t,s,i,r){if(this._currentActiveTarget=t,this._weight=i,this._enableBlending&&this._blendingFactor<=1){if(!this._originalBlendValue){const e=t[this._targetPath];e.clone?this._originalBlendValue=e.clone():this._originalBlendValue=e}this._originalBlendValue.m?xi.AllowMatrixDecomposeForInterpolation?this._currentValue?V.DecomposeLerpToRef(this._originalBlendValue,s,this._blendingFactor,this._currentValue):this._currentValue=V.DecomposeLerp(this._originalBlendValue,s,this._blendingFactor):this._currentValue?V.LerpToRef(this._originalBlendValue,s,this._blendingFactor,this._currentValue):this._currentValue=V.Lerp(this._originalBlendValue,s,this._blendingFactor):this._currentValue=xi._UniversalLerp(this._originalBlendValue,s,this._blendingFactor);const i=e&&e.animationPropertiesOverride?e.animationPropertiesOverride.blendingSpeed:this._animation.blendingSpeed;this._blendingFactor+=i}else this._currentValue?this._currentValue.copyFrom?this._currentValue.copyFrom(s):this._currentValue=s:this._currentValue=s?.clone?s.clone():s;-1!==i?this._scene._registerTargetForLateAnimationBinding(this,this._originalValue[r]):this._animationState.loopMode===xi.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT?this._currentValue.addToRef?this._currentValue.addToRef(this._originalValue[r],t[this._targetPath]):t[this._targetPath]=this._originalValue[r]+this._currentValue:t[this._targetPath]=this._currentValue,e.markAsDirty&&e.markAsDirty(this._animation.targetProperty)}_getCorrectLoopMode(){return this._target&&this._target.animationPropertiesOverride?this._target.animationPropertiesOverride.loopMode:this._animation.loopMode}goToFrame(e,t=-1){const s=this._animation.getKeys();e<s[0].frame?e=s[0].frame:e>s[s.length-1].frame&&(e=s[s.length-1].frame);const i=this._events;if(i.length)for(let t=0;t<i.length;t++)i[t].onlyOnce||(i[t].isDone=i[t].frame<e);this._currentFrame=e;const r=this._animation._interpolate(e,this._animationState);this.setValue(r,t)}_prepareForSpeedRatioChange(e){const t=this._previousElapsedTime*(this._animation.framePerSecond*e)/1e3;this._absoluteFrameOffset=this._previousAbsoluteFrame-t}animate(e,t,s,i,r,n=-1){const a=this._animation,o=a.targetPropertyPath;if(!o||o.length<1)return this._stopped=!0,!1;let h=!0;(t<this._minFrame||t>this._maxFrame)&&(t=this._minFrame),(s<this._minFrame||s>this._maxFrame)&&(s=this._maxFrame);const l=s-t;let c,u=e*(a.framePerSecond*r)/1e3+this._absoluteFrameOffset,d=0,_=!1;const f=i&&this._animationState.loopMode===xi.ANIMATIONLOOPMODE_YOYO;if(f){const e=(u-t)/l,s=Math.sin(e*Math.PI);u=Math.abs(s)*l+t;const i=s>=0?1:-1;this._yoyoDirection!==i&&(_=!0),this._yoyoDirection=i}if(this._previousElapsedTime=e,this._previousAbsoluteFrame=u,!i&&s>=t&&(u>=l&&r>0||u<=0&&r<0))h=!1,d=a._getKeyValue(this._maxValue);else if(!i&&t>=s&&(u<=l&&r<0||u>=0&&r>0))h=!1,d=a._getKeyValue(this._minValue);else if(this._animationState.loopMode!==xi.ANIMATIONLOOPMODE_CYCLE){const e=s.toString()+t.toString();if(!this._offsetsCache[e]){this._animationState.repeatCount=0,this._animationState.loopMode=xi.ANIMATIONLOOPMODE_CYCLE;const i=a._interpolate(t,this._animationState),r=a._interpolate(s,this._animationState);switch(this._animationState.loopMode=this._getCorrectLoopMode(),a.dataType){case xi.ANIMATIONTYPE_FLOAT:this._offsetsCache[e]=r-i;break;case xi.ANIMATIONTYPE_QUATERNION:case xi.ANIMATIONTYPE_VECTOR3:case xi.ANIMATIONTYPE_VECTOR2:case xi.ANIMATIONTYPE_SIZE:case xi.ANIMATIONTYPE_COLOR3:this._offsetsCache[e]=r.subtract(i)}this._highLimitsCache[e]=r}d=this._highLimitsCache[e],c=this._offsetsCache[e]}if(void 0===c)switch(a.dataType){case xi.ANIMATIONTYPE_FLOAT:c=0;break;case xi.ANIMATIONTYPE_QUATERNION:c=gi;break;case xi.ANIMATIONTYPE_VECTOR3:c=Ti;break;case xi.ANIMATIONTYPE_VECTOR2:c=Ei;break;case xi.ANIMATIONTYPE_SIZE:c=Ai;break;case xi.ANIMATIONTYPE_COLOR3:c=yi;break;case xi.ANIMATIONTYPE_COLOR4:c=bi}let p;if(this._host&&this._host.syncRoot){const e=this._host.syncRoot;p=t+l*((e.masterFrame-e.fromFrame)/(e.toFrame-e.fromFrame))}else p=u>0&&t>s||u<0&&t<s?h&&0!==l?s+u%l:t:h&&0!==l?t+u%l:s;const m=this._events;if(!f&&(r>0&&this.currentFrame>p||r<0&&this.currentFrame<p)||f&&_){this._onLoop();for(let e=0;e<m.length;e++)m[e].onlyOnce||(m[e].isDone=!1);this._animationState.key=r>0?0:a.getKeys().length-1}this._currentFrame=p,this._animationState.repeatCount=0===l?0:u/l|0,this._animationState.highLimitValue=d,this._animationState.offsetValue=c;const g=a._interpolate(p,this._animationState);if(this.setValue(g,n),m.length)for(let e=0;e<m.length;e++)if(l>=0&&p>=m[e].frame&&m[e].frame>=t||l<0&&p<=m[e].frame&&m[e].frame<=t){const t=m[e];t.isDone||(t.onlyOnce&&(m.splice(e,1),e--),t.isDone=!0,t.action(p))}return h||(this._stopped=!0),h}}class ha extends ae{get _matrix(){return this._compose(),this._localMatrix}set _matrix(e){(e.updateFlag!==this._localMatrix.updateFlag||this._needToCompose)&&(this._needToCompose=!1,this._localMatrix.copyFrom(e),this._markAsDirtyAndDecompose())}constructor(e,t,s=null,i=null,r=null,n=null,a=null){super(e,t.getScene(),!1),this.name=e,this.children=[],this.animations=[],this._index=null,this._scalingDeterminant=1,this._needToDecompose=!0,this._needToCompose=!1,this._linkedTransformNode=null,this._waitingTransformNodeId=null,this._skeleton=t,this._localMatrix=i?.clone()??V.Identity(),this._restMatrix=r??this._localMatrix.clone(),this._bindMatrix=n??this._localMatrix.clone(),this._index=a,this._absoluteMatrix=new V,this._absoluteBindMatrix=new V,this._absoluteInverseBindMatrix=new V,this._finalMatrix=new V,t.bones.push(this),this.setParent(s,!1),this._updateAbsoluteBindMatrices()}getClassName(){return"Bone"}getSkeleton(){return this._skeleton}get parent(){return this._parentNode}getParent(){return this.parent}getChildren(){return this.children}getIndex(){return null===this._index?this.getSkeleton().bones.indexOf(this):this._index}set parent(e){this.setParent(e)}setParent(e,t=!0){if(this.parent!==e){if(this.parent){const e=this.parent.children.indexOf(this);-1!==e&&this.parent.children.splice(e,1)}this._parentNode=e,this.parent&&this.parent.children.push(this),t&&this._updateAbsoluteBindMatrices(),this.markAsDirty()}}getLocalMatrix(){return this._compose(),this._localMatrix}getBindMatrix(){return this._bindMatrix}getBaseMatrix(){return this.getBindMatrix()}getRestMatrix(){return this._restMatrix}getRestPose(){return this.getRestMatrix()}setRestMatrix(e){this._restMatrix.copyFrom(e)}setRestPose(e){this.setRestMatrix(e)}getBindPose(){return this.getBindMatrix()}setBindMatrix(e){this.updateMatrix(e)}setBindPose(e){this.setBindMatrix(e)}getFinalMatrix(){return this._finalMatrix}getWorldMatrix(){return this.getFinalMatrix()}returnToRest(){if(this._linkedTransformNode){const e=z.Vector3[0],t=z.Quaternion[0],s=z.Vector3[1];this.getRestMatrix().decompose(e,t,s),this._linkedTransformNode.position.copyFrom(s),this._linkedTransformNode.rotationQuaternion=this._linkedTransformNode.rotationQuaternion??G.Identity(),this._linkedTransformNode.rotationQuaternion.copyFrom(t),this._linkedTransformNode.scaling.copyFrom(e)}else this._matrix=this._restMatrix}getAbsoluteInverseBindMatrix(){return this._absoluteInverseBindMatrix}getInvertedAbsoluteTransform(){return this.getAbsoluteInverseBindMatrix()}getAbsoluteMatrix(){return this._absoluteMatrix}getAbsoluteTransform(){return this._absoluteMatrix}linkTransformNode(e){this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode--,this._linkedTransformNode=e,this._linkedTransformNode&&this._skeleton._numBonesWithLinkedTransformNode++}getTransformNode(){return this._linkedTransformNode}get position(){return this._decompose(),this._localPosition}set position(e){this._decompose(),this._localPosition.copyFrom(e),this._markAsDirtyAndCompose()}get rotation(){return this.getRotation()}set rotation(e){this.setRotation(e)}get rotationQuaternion(){return this._decompose(),this._localRotation}set rotationQuaternion(e){this.setRotationQuaternion(e)}get scaling(){return this.getScale()}set scaling(e){this.setScale(e)}get animationPropertiesOverride(){return this._skeleton.animationPropertiesOverride}_decompose(){this._needToDecompose&&(this._needToDecompose=!1,this._localScaling||(this._localScaling=U.Zero(),this._localRotation=G.Zero(),this._localPosition=U.Zero()),this._localMatrix.decompose(this._localScaling,this._localRotation,this._localPosition))}_compose(){this._needToCompose&&(this._localScaling?(this._needToCompose=!1,V.ComposeToRef(this._localScaling,this._localRotation,this._localPosition,this._localMatrix)):this._needToCompose=!1)}updateMatrix(e,t=!0,s=!0){this._bindMatrix.copyFrom(e),t&&this._updateAbsoluteBindMatrices(),s?this._matrix=e:this.markAsDirty()}_updateAbsoluteBindMatrices(e,t=!0){if(e||(e=this._bindMatrix),this.parent?e.multiplyToRef(this.parent._absoluteBindMatrix,this._absoluteBindMatrix):this._absoluteBindMatrix.copyFrom(e),this._absoluteBindMatrix.invertToRef(this._absoluteInverseBindMatrix),t)for(let e=0;e<this.children.length;e++)this.children[e]._updateAbsoluteBindMatrices();this._scalingDeterminant=this._absoluteBindMatrix.determinant()<0?-1:1}markAsDirty(){return this._currentRenderId++,this._childUpdateId++,this._skeleton._markAsDirty(),this}_markAsDirtyAndCompose(){this.markAsDirty(),this._needToCompose=!0}_markAsDirtyAndDecompose(){this.markAsDirty(),this._needToDecompose=!0}_updatePosition(e,t=0,s,i=!0){const r=this.getLocalMatrix();if(0==t)i?(r.addAtIndex(12,e.x),r.addAtIndex(13,e.y),r.addAtIndex(14,e.z)):r.setTranslationFromFloats(e.x,e.y,e.z);else{let t=null;s&&(t=s.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();const n=ha._TmpMats[0],a=ha._TmpVecs[0];this.parent?s&&t?(n.copyFrom(this.parent.getAbsoluteMatrix()),n.multiplyToRef(t,n)):n.copyFrom(this.parent.getAbsoluteMatrix()):V.IdentityToRef(n),i&&n.setTranslationFromFloats(0,0,0),n.invert(),U.TransformCoordinatesToRef(e,n,a),i?(r.addAtIndex(12,a.x),r.addAtIndex(13,a.y),r.addAtIndex(14,a.z)):r.setTranslationFromFloats(a.x,a.y,a.z)}this._markAsDirtyAndDecompose()}translate(e,t=0,s){this._updatePosition(e,t,s,!0)}setPosition(e,t=0,s){this._updatePosition(e,t,s,!1)}setAbsolutePosition(e,t){this.setPosition(e,1,t)}scale(e,t,s,i=!1){const r=this.getLocalMatrix(),n=ha._TmpMats[0];V.ScalingToRef(e,t,s,n),n.multiplyToRef(r,r),n.invert();for(const i of this.children){const r=i.getLocalMatrix();r.multiplyToRef(n,r),r.multiplyAtIndex(12,e),r.multiplyAtIndex(13,t),r.multiplyAtIndex(14,s),i._markAsDirtyAndDecompose()}if(this._markAsDirtyAndDecompose(),i)for(const r of this.children)r.scale(e,t,s,i)}setScale(e){this._decompose(),this._localScaling.copyFrom(e),this._markAsDirtyAndCompose()}getScale(){return this._decompose(),this._localScaling}getScaleToRef(e){this._decompose(),e.copyFrom(this._localScaling)}setYawPitchRoll(e,t,s,i=0,r){if(0===i){const n=ha._TmpQuat;return G.RotationYawPitchRollToRef(e,t,s,n),void this.setRotationQuaternion(n,i,r)}const n=ha._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(n,r))return;const a=ha._TmpMats[1];V.RotationYawPitchRollToRef(e,t,s,a),n.multiplyToRef(a,a),this._rotateWithMatrix(a,i,r)}rotate(e,t,s=0,i){const r=ha._TmpMats[0];r.setTranslationFromFloats(0,0,0),V.RotationAxisToRef(e,t,r),this._rotateWithMatrix(r,s,i)}setAxisAngle(e,t,s=0,i){if(0===s){const r=ha._TmpQuat;return G.RotationAxisToRef(e,t,r),void this.setRotationQuaternion(r,s,i)}const r=ha._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(r,i))return;const n=ha._TmpMats[1];V.RotationAxisToRef(e,t,n),r.multiplyToRef(n,n),this._rotateWithMatrix(n,s,i)}setRotation(e,t=0,s){this.setYawPitchRoll(e.y,e.x,e.z,t,s)}setRotationQuaternion(e,t=0,s){if(0===t)return this._decompose(),this._localRotation.copyFrom(e),void this._markAsDirtyAndCompose();const i=ha._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(i,s))return;const r=ha._TmpMats[1];V.FromQuaternionToRef(e,r),i.multiplyToRef(r,r),this._rotateWithMatrix(r,t,s)}setRotationMatrix(e,t=0,s){if(0===t){const i=ha._TmpQuat;return G.FromRotationMatrixToRef(e,i),void this.setRotationQuaternion(i,t,s)}const i=ha._TmpMats[0];if(!this._getAbsoluteInverseMatrixUnscaledToRef(i,s))return;const r=ha._TmpMats[1];r.copyFrom(e),i.multiplyToRef(e,r),this._rotateWithMatrix(r,t,s)}_rotateWithMatrix(e,t=0,s){const i=this.getLocalMatrix(),r=i.m[12],n=i.m[13],a=i.m[14],o=this.getParent(),h=ha._TmpMats[3],l=ha._TmpMats[4];o&&1==t?(s?(h.copyFrom(s.getWorldMatrix()),o.getAbsoluteMatrix().multiplyToRef(h,h)):h.copyFrom(o.getAbsoluteMatrix()),l.copyFrom(h),l.invert(),i.multiplyToRef(h,i),i.multiplyToRef(e,i),i.multiplyToRef(l,i)):1==t&&s?(h.copyFrom(s.getWorldMatrix()),l.copyFrom(h),l.invert(),i.multiplyToRef(h,i),i.multiplyToRef(e,i),i.multiplyToRef(l,i)):i.multiplyToRef(e,i),i.setTranslationFromFloats(r,n,a),this.computeAbsoluteMatrices(),this._markAsDirtyAndDecompose()}_getAbsoluteInverseMatrixUnscaledToRef(e,t){const s=ha._TmpMats[2];return e.copyFrom(this.getAbsoluteMatrix()),t?(e.multiplyToRef(t.getWorldMatrix(),e),V.ScalingToRef(t.scaling.x,t.scaling.y,t.scaling.z,s)):V.IdentityToRef(s),e.invert(),!isNaN(e.m[0])&&(s.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyToRef(s,e),!0)}getPosition(e=0,t=null){const s=U.Zero();return this.getPositionToRef(e,t,s),s}getPositionToRef(e=0,t,s){if(0==e){const e=this.getLocalMatrix();s.x=e.m[12],s.y=e.m[13],s.z=e.m[14]}else{let e=null;t&&(e=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();let i=ha._TmpMats[0];t&&e?(i.copyFrom(this.getAbsoluteMatrix()),i.multiplyToRef(e,i)):i=this.getAbsoluteMatrix(),s.x=i.m[12],s.y=i.m[13],s.z=i.m[14]}}getAbsolutePosition(e=null){const t=U.Zero();return this.getPositionToRef(1,e,t),t}getAbsolutePositionToRef(e,t){this.getPositionToRef(1,e,t)}computeAbsoluteMatrices(){if(this._compose(),this.parent)this._localMatrix.multiplyToRef(this.parent._absoluteMatrix,this._absoluteMatrix);else{this._absoluteMatrix.copyFrom(this._localMatrix);const e=this._skeleton.getPoseMatrix();e&&this._absoluteMatrix.multiplyToRef(e,this._absoluteMatrix)}const e=this.children,t=e.length;for(let s=0;s<t;s++)e[s].computeAbsoluteMatrices()}computeAbsoluteTransforms(){this.computeAbsoluteMatrices()}getDirection(e,t=null){const s=U.Zero();return this.getDirectionToRef(e,t,s),s}getDirectionToRef(e,t=null,s){let i=null;t&&(i=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();const r=ha._TmpMats[0];r.copyFrom(this.getAbsoluteMatrix()),t&&i&&r.multiplyToRef(i,r),U.TransformNormalToRef(e,r,s),s.normalize()}getRotation(e=0,t=null){const s=U.Zero();return this.getRotationToRef(e,t,s),s}getRotationToRef(e=0,t=null,s){const i=ha._TmpQuat;this.getRotationQuaternionToRef(e,t,i),i.toEulerAnglesToRef(s)}getRotationQuaternion(e=0,t=null){const s=G.Identity();return this.getRotationQuaternionToRef(e,t,s),s}getRotationQuaternionToRef(e=0,t=null,s){if(0==e)this._decompose(),s.copyFrom(this._localRotation);else{const e=ha._TmpMats[0],i=this.getAbsoluteMatrix();t?i.multiplyToRef(t.getWorldMatrix(),e):e.copyFrom(i),e.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyAtIndex(1,this._scalingDeterminant),e.multiplyAtIndex(2,this._scalingDeterminant),e.decompose(void 0,s,void 0)}}getRotationMatrix(e=0,t){const s=V.Identity();return this.getRotationMatrixToRef(e,t,s),s}getRotationMatrixToRef(e=0,t,s){if(0==e)this.getLocalMatrix().getRotationMatrixToRef(s);else{const e=ha._TmpMats[0],i=this.getAbsoluteMatrix();t?i.multiplyToRef(t.getWorldMatrix(),e):e.copyFrom(i),e.multiplyAtIndex(0,this._scalingDeterminant),e.multiplyAtIndex(1,this._scalingDeterminant),e.multiplyAtIndex(2,this._scalingDeterminant),e.getRotationMatrixToRef(s)}}getAbsolutePositionFromLocal(e,t=null){const s=U.Zero();return this.getAbsolutePositionFromLocalToRef(e,t,s),s}getAbsolutePositionFromLocalToRef(e,t=null,s){let i=null;t&&(i=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();const r=ha._TmpMats[0];r.copyFrom(this.getAbsoluteMatrix()),t&&i&&r.multiplyToRef(i,r),U.TransformCoordinatesToRef(e,r,s)}getLocalPositionFromAbsolute(e,t=null){const s=U.Zero();return this.getLocalPositionFromAbsoluteToRef(e,t,s),s}getLocalPositionFromAbsoluteToRef(e,t=null,s){let i=null;t&&(i=t.getWorldMatrix()),this._skeleton.computeAbsoluteMatrices();const r=ha._TmpMats[0];r.copyFrom(this.getAbsoluteMatrix()),t&&i&&r.multiplyToRef(i,r),r.invert(),U.TransformCoordinatesToRef(e,r,s)}setCurrentPoseAsRest(){this.setRestMatrix(this.getLocalMatrix())}}ha._TmpVecs=y(2,U.Zero),ha._TmpQuat=G.Identity(),ha._TmpMats=y(5,V.Identity);class la{get syncRoot(){return this._syncRoot}get masterFrame(){return 0===this._runtimeAnimations.length?0:this._runtimeAnimations[0].currentFrame}get weight(){return this._weight}set weight(e){this._weight=-1!==e?Math.min(Math.max(e,0),1):-1}get speedRatio(){return this._speedRatio}set speedRatio(e){for(let t=0;t<this._runtimeAnimations.length;t++){this._runtimeAnimations[t]._prepareForSpeedRatioChange(e)}this._speedRatio=e,null!==this._goToFrame&&this.goToFrame(this._goToFrame)}get elapsedTime(){return null===this._localDelayOffset?0:this._scene._animationTime-this._localDelayOffset}constructor(e,t,s=0,i=100,r=!1,n=1,a,o,h,l=!1,c=0){this.target=t,this.fromFrame=s,this.toFrame=i,this.loopAnimation=r,this.onAnimationEnd=a,this.onAnimationLoop=h,this.isAdditive=l,this.playOrder=c,this._localDelayOffset=null,this._pausedDelay=null,this._manualJumpDelay=null,this._runtimeAnimations=new Array,this._paused=!1,this._speedRatio=1,this._weight=-1,this._syncRoot=null,this._frameToSyncFromJump=null,this._goToFrame=null,this.disposeOnEnd=!0,this.animationStarted=!1,this.onAnimationEndObservable=new g,this.onAnimationLoopObservable=new g,this._scene=e,o&&this.appendAnimations(t,o),this._speedRatio=n,e._activeAnimatables.push(this)}syncWith(e){if(this._syncRoot=e,e){const e=this._scene._activeAnimatables.indexOf(this);e>-1&&(this._scene._activeAnimatables.splice(e,1),this._scene._activeAnimatables.push(this))}return this}getAnimations(){return this._runtimeAnimations}appendAnimations(e,t){for(let s=0;s<t.length;s++){const i=t[s],r=new oa(e,i,this._scene,this);r._onLoop=()=>{this.onAnimationLoopObservable.notifyObservers(this),this.onAnimationLoop&&this.onAnimationLoop()},this._runtimeAnimations.push(r)}}getAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let s=0;s<t.length;s++)if(t[s].animation.targetProperty===e)return t[s].animation;return null}getRuntimeAnimationByTargetProperty(e){const t=this._runtimeAnimations;for(let s=0;s<t.length;s++)if(t[s].animation.targetProperty===e)return t[s];return null}reset(){const e=this._runtimeAnimations;for(let t=0;t<e.length;t++)e[t].reset(!0);this._localDelayOffset=null,this._pausedDelay=null}enableBlending(e){const t=this._runtimeAnimations;for(let s=0;s<t.length;s++)t[s].animation.enableBlending=!0,t[s].animation.blendingSpeed=e}disableBlending(){const e=this._runtimeAnimations;for(let t=0;t<e.length;t++)e[t].animation.enableBlending=!1}goToFrame(e){const t=this._runtimeAnimations;if(t[0]){const s=t[0].animation.framePerSecond;this._frameToSyncFromJump=this._frameToSyncFromJump??t[0].currentFrame;const i=0===this.speedRatio?0:(e-this._frameToSyncFromJump)/s*1e3/this.speedRatio;this._manualJumpDelay=-i}for(let s=0;s<t.length;s++)t[s].goToFrame(e,this._weight);this._goToFrame=e}get paused(){return this._paused}pause(){this._paused||(this._paused=!0)}restart(){this._paused=!1}_raiseOnAnimationEnd(){this.onAnimationEnd&&this.onAnimationEnd(),this.onAnimationEndObservable.notifyObservers(this)}stop(e,t,s=!1,i=!1){if(e||t){const r=this._scene._activeAnimatables.indexOf(this);if(r>-1){const n=this._runtimeAnimations;for(let s=n.length-1;s>=0;s--){const i=n[s];e&&i.animation.name!=e||(t&&!t(i.target)||(i.dispose(),n.splice(s,1)))}0==n.length&&(s||this._scene._activeAnimatables.splice(r,1),i||this._raiseOnAnimationEnd())}}else{const e=this._scene._activeAnimatables.indexOf(this);if(e>-1){s||this._scene._activeAnimatables.splice(e,1);const t=this._runtimeAnimations;for(let e=0;e<t.length;e++)t[e].dispose();this._runtimeAnimations.length=0,i||this._raiseOnAnimationEnd()}}}waitAsync(){return new Promise((e=>{this.onAnimationEndObservable.add((()=>{e(this)}),void 0,void 0,this,!0)}))}_animate(e){if(this._paused)return this.animationStarted=!1,null===this._pausedDelay&&(this._pausedDelay=e),!0;if(null===this._localDelayOffset?(this._localDelayOffset=e,this._pausedDelay=null):null!==this._pausedDelay&&(this._localDelayOffset+=e-this._pausedDelay,this._pausedDelay=null),null!==this._manualJumpDelay&&(this._localDelayOffset+=this._manualJumpDelay,this._manualJumpDelay=null,this._frameToSyncFromJump=null),this._goToFrame=null,0===this._weight)return!0;let t=!1;const s=this._runtimeAnimations;let i;for(i=0;i<s.length;i++){const r=s[i].animate(e-this._localDelayOffset,this.fromFrame,this.toFrame,this.loopAnimation,this._speedRatio,this._weight);t=t||r}if(this.animationStarted=t,!t){if(this.disposeOnEnd)for(i=this._scene._activeAnimatables.indexOf(this),this._scene._activeAnimatables.splice(i,1),i=0;i<s.length;i++)s[i].dispose();this._raiseOnAnimationEnd(),this.disposeOnEnd&&(this.onAnimationEnd=null,this.onAnimationLoop=null,this.onAnimationLoopObservable.clear(),this.onAnimationEndObservable.clear())}return t}}yr.prototype._animate=function(e){if(!this.animationsEnabled)return;const t=fe.Now;if(!this._animationTimeLast){if(this._pendingData.length>0)return;this._animationTimeLast=t}this.deltaTime=void 0!==e?e:this.useConstantAnimationDeltaTime?16:(t-this._animationTimeLast)*this.animationTimeScale,this._animationTimeLast=t;const s=this._activeAnimatables;if(0===s.length)return;this._animationTime+=this.deltaTime;const i=this._animationTime;for(let e=0;e<s.length;e++){const t=s[e];!t._animate(i)&&t.disposeOnEnd&&e--}this._processLateAnimationBindings()},yr.prototype.sortActiveAnimatables=function(){this._activeAnimatables.sort(((e,t)=>e.playOrder-t.playOrder))},yr.prototype.beginWeightedAnimation=function(e,t,s,i=1,r,n=1,a,o,h,l,c=!1){const u=this.beginAnimation(e,t,s,r,n,a,o,!1,h,l,c);return u.weight=i,u},yr.prototype.beginAnimation=function(e,t,s,i,r=1,n,a,o=!0,h,l,c=!1){t>s&&r>0&&(r*=-1),o&&this.stopAnimation(e,void 0,h),a||(a=new la(this,e,t,s,i,r,n,void 0,l,c));const u=!h||h(e);if(e.animations&&u&&a.appendAnimations(e,e.animations),e.getAnimatables){const c=e.getAnimatables();for(let e=0;e<c.length;e++)this.beginAnimation(c[e],t,s,i,r,n,a,o,h,l)}return a.reset(),a},yr.prototype.beginHierarchyAnimation=function(e,t,s,i,r,n=1,a,o,h=!0,l,c,u=!1){const d=e.getDescendants(t),_=[];_.push(this.beginAnimation(e,s,i,r,n,a,o,h,l,void 0,u));for(const e of d)_.push(this.beginAnimation(e,s,i,r,n,a,o,h,l,void 0,u));return _},yr.prototype.beginDirectAnimation=function(e,t,s,i,r,n,a,o,h=!1){if(void 0===n&&(n=1),s>i&&n>0)n*=-1;else if(i>s&&n<0){const e=i;i=s,s=e}return new la(this,e,s,i,r,n,a,t,o,h)},yr.prototype.beginDirectHierarchyAnimation=function(e,t,s,i,r,n,a,o,h,l=!1){const c=e.getDescendants(t),u=[];u.push(this.beginDirectAnimation(e,s,i,r,n,a,o,h,l));for(const e of c)u.push(this.beginDirectAnimation(e,s,i,r,n,a,o,h,l));return u},yr.prototype.getAnimatableByTarget=function(e){for(let t=0;t<this._activeAnimatables.length;t++)if(this._activeAnimatables[t].target===e)return this._activeAnimatables[t];return null},yr.prototype.getAllAnimatablesByTarget=function(e){const t=[];for(let s=0;s<this._activeAnimatables.length;s++)this._activeAnimatables[s].target===e&&t.push(this._activeAnimatables[s]);return t},yr.prototype.stopAnimation=function(e,t,s){const i=this.getAllAnimatablesByTarget(e);for(const e of i)e.stop(t,s)},yr.prototype.stopAllAnimations=function(){if(this._activeAnimatables){for(let e=0;e<this._activeAnimatables.length;e++)this._activeAnimatables[e].stop(void 0,void 0,!0);this._activeAnimatables.length=0}for(const e of this.animationGroups)e.stop()},yr.prototype._registerTargetForLateAnimationBinding=function(e,t){const s=e.target;this._registeredForLateAnimationBindings.pushNoDuplicate(s),s._lateAnimationHolders||(s._lateAnimationHolders={}),s._lateAnimationHolders[e.targetPath]||(s._lateAnimationHolders[e.targetPath]={totalWeight:0,totalAdditiveWeight:0,animations:[],additiveAnimations:[],originalValue:t}),e.isAdditive?(s._lateAnimationHolders[e.targetPath].additiveAnimations.push(e),s._lateAnimationHolders[e.targetPath].totalAdditiveWeight+=e.weight):(s._lateAnimationHolders[e.targetPath].animations.push(e),s._lateAnimationHolders[e.targetPath].totalWeight+=e.weight)},yr.prototype._processLateAnimationBindingsForMatrices=function(e){if(0===e.totalWeight&&0===e.totalAdditiveWeight)return e.originalValue;let t=1;const s=z.Vector3[0],i=z.Vector3[1],r=z.Quaternion[0];let n=0;const a=e.animations[0],o=e.originalValue;let h=1,l=!1;if(e.totalWeight<1)h=1-e.totalWeight,o.decompose(i,r,s);else{if(n=1,t=e.totalWeight,h=a.weight/t,1==h){if(!e.totalAdditiveWeight)return a.currentValue;l=!0}a.currentValue.decompose(i,r,s)}if(!l){i.scaleInPlace(h),s.scaleInPlace(h),r.scaleInPlace(h);for(let a=n;a<e.animations.length;a++){const n=e.animations[a];if(0===n.weight)continue;h=n.weight/t;const o=z.Vector3[2],l=z.Vector3[3],c=z.Quaternion[1];n.currentValue.decompose(l,c,o),l.scaleAndAddToRef(h,i),c.scaleAndAddToRef(G.Dot(r,c)>0?h:-h,r),o.scaleAndAddToRef(h,s)}r.normalize()}for(let t=0;t<e.additiveAnimations.length;t++){const n=e.additiveAnimations[t];if(0===n.weight)continue;const a=z.Vector3[2],o=z.Vector3[3],h=z.Quaternion[1];n.currentValue.decompose(o,h,a),o.multiplyToRef(i,o),U.LerpToRef(i,o,n.weight,i),r.multiplyToRef(h,h),G.SlerpToRef(r,h,n.weight,r),a.scaleAndAddToRef(n.weight,s)}const c=a?a._animationState.workValue:z.Matrix[0].clone();return V.ComposeToRef(i,r,s,c),c},yr.prototype._processLateAnimationBindingsForQuaternions=function(e,t){if(0===e.totalWeight&&0===e.totalAdditiveWeight)return t;const s=e.animations[0],i=e.originalValue;let r=t;if(0===e.totalWeight&&e.totalAdditiveWeight>0)r.copyFrom(i);else if(1===e.animations.length){if(G.SlerpToRef(i,s.currentValue,Math.min(1,e.totalWeight),r),0===e.totalAdditiveWeight)return r}else if(e.animations.length>1){let s,n,a=1;if(e.totalWeight<1){const t=1-e.totalWeight;s=[],n=[],s.push(i),n.push(t)}else{if(2===e.animations.length&&(G.SlerpToRef(e.animations[0].currentValue,e.animations[1].currentValue,e.animations[1].weight/e.totalWeight,t),0===e.totalAdditiveWeight))return t;s=[],n=[],a=e.totalWeight}for(let t=0;t<e.animations.length;t++){const i=e.animations[t];s.push(i.currentValue),n.push(i.weight/a)}let o=0;for(let e=0;e<s.length;)e?(o+=n[e],G.SlerpToRef(r,s[e],n[e]/o,r),e++):(G.SlerpToRef(s[e],s[e+1],n[e+1]/(n[e]+n[e+1]),t),r=t,o=n[e]+n[e+1],e+=2)}for(let t=0;t<e.additiveAnimations.length;t++){const s=e.additiveAnimations[t];0!==s.weight&&(r.multiplyToRef(s.currentValue,z.Quaternion[0]),G.SlerpToRef(r,z.Quaternion[0],s.weight,r))}return r},yr.prototype._processLateAnimationBindings=function(){if(this._registeredForLateAnimationBindings.length){for(let e=0;e<this._registeredForLateAnimationBindings.length;e++){const t=this._registeredForLateAnimationBindings.data[e];for(const e in t._lateAnimationHolders){const s=t._lateAnimationHolders[e],i=s.animations[0],r=s.originalValue;if(null==r)continue;const n=xi.AllowMatrixDecomposeForInterpolation&&r.m;let a=t[e];if(n)a=this._processLateAnimationBindingsForMatrices(s);else{if(void 0!==r.w)a=this._processLateAnimationBindingsForQuaternions(s,a||G.Identity());else{let e=0,t=1;const n=i&&i._animationState.loopMode===xi.ANIMATIONLOOPMODE_RELATIVE_FROM_CURRENT;if(s.totalWeight<1)a=n?r.clone?r.clone():r:i&&r.scale?r.scale(1-s.totalWeight):i?r*(1-s.totalWeight):r.clone?r.clone():r;else if(i){t=s.totalWeight;const o=i.weight/t;a=1!==o?i.currentValue.scale?i.currentValue.scale(o):i.currentValue*o:i.currentValue,n&&(a.addToRef?a.addToRef(r,a):a+=r),e=1}for(let i=e;i<s.animations.length;i++){const e=s.animations[i],r=e.weight/t;r&&(e.currentValue.scaleAndAddToRef?e.currentValue.scaleAndAddToRef(r,a):a+=e.currentValue*r)}for(let e=0;e<s.additiveAnimations.length;e++){const t=s.additiveAnimations[e],i=t.weight;i&&(t.currentValue.scaleAndAddToRef?t.currentValue.scaleAndAddToRef(i,a):a+=t.currentValue*i)}}}t[e]=a}t._lateAnimationHolders={}}this._registeredForLateAnimationBindings.reset()}},ha.prototype.copyAnimationRange=function(e,t,s,i=!1,r=null){0===this.animations.length&&(this.animations.push(new xi(this.name,"_matrix",e.animations[0].framePerSecond,xi.ANIMATIONTYPE_MATRIX,0)),this.animations[0].setKeys([]));const n=e.animations[0].getRange(t);if(!n)return!1;const a=n.from,o=n.to,h=e.animations[0].getKeys(),l=e.length,c=e.getParent(),u=this.getParent(),d=i&&c&&l&&this.length&&l!==this.length,_=d&&u&&c?u.length/c.length:1,f=i&&!u&&r&&(1!==r.x||1!==r.y||1!==r.z),p=this.animations[0].getKeys();let m,g,T;for(let e=0,t=h.length;e<t;e++)m=h[e],m.frame>=a&&m.frame<=o&&(i?(T=m.value.clone(),d?(g=T.getTranslation(),T.setTranslation(g.scaleInPlace(_))):f&&r?(g=T.getTranslation(),T.setTranslation(g.multiplyInPlace(r))):T=m.value):T=m.value,p.push({frame:m.frame+s,value:T}));return this.animations[0].createRange(t,a+s,o+s),!0};const ca="image/png",ua=2,da=[134,22,135,150,246,214,150,54];function _a(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength);let s=0;for(let e=0;e<da.length;e++)if(t.getUint8(s++)!==da[e])return ue.Error("Not a babylon environment map"),null;let i="",r=0;for(;r=t.getUint8(s++);)i+=String.fromCharCode(r);let n=JSON.parse(i);return n=fa(n),n.specular&&(n.specular.specularDataPosition=s,n.specular.lodGenerationScale=n.specular.lodGenerationScale||.8),n}function fa(e){if(e.version>ua)throw new Error(`Unsupported babylon environment map version "${e.version}". Latest supported version is "${ua}".`);return 2===e.version?e:e={...e,version:2,imageType:ca}}function pa(e,t,s){const i=(s=fa(s)).specular;if(!i)return Promise.resolve();e._lodGenerationScale=i.lodGenerationScale;const r=function(e,t){const s=(t=fa(t)).specular;let i=Q.Log2(t.width);if(i=Math.round(i)+1,s.mipmaps.length!==6*i)throw new Error(`Unsupported specular mipmaps number "${s.mipmaps.length}"`);const r=new Array(i);for(let t=0;t<i;t++){r[t]=new Array(6);for(let i=0;i<6;i++){const n=s.mipmaps[6*t+i];r[t][i]=new Uint8Array(e.buffer,e.byteOffset+s.specularDataPosition+n.position,n.length)}}return r}(t,s);return ga(e,r,s.imageType)}function ma(e,t,s,i,r,n,a,o,h,l,c){return new Promise(((u,d)=>{if(s){const s=t.createTexture(null,!0,!0,null,Ze.TEXTURE_NEAREST_SAMPLINGMODE,null,(e=>{d(e)}),e);i?.onEffectCreatedObservable.addOnce((o=>{o.executeWhenCompiled((()=>{i.externalTextureSamplerBinding=!0,i.onApply=i=>{i._bindTexture("textureSampler",s),i.setFloat2("scale",1,t._features.needsInvertingBitmap&&e instanceof ImageBitmap?-1:1)},t.scenes.length&&(t.scenes[0].postProcessManager.directRender([i],l,!0,n,a),t.restoreDefaultFramebuffer(),s.dispose(),URL.revokeObjectURL(r),u())}))}))}else{if(t._uploadImageToTexture(c,e,n,a),o){const s=h[a];s&&t._uploadImageToTexture(s._texture,e,n,0)}u()}}))}async function ga(e,t,s=ca){if(!Yt.IsExponentOfTwo(e.width))throw new Error("Texture size must be a power of two");const i=Q.ILog2(e.width)+1,r=e.getEngine();let n=!1,a=!1,o=null,h=null,l=null;const c=r.getCaps();e.format=Ze.TEXTUREFORMAT_RGBA,e.type=Ze.TEXTURETYPE_UNSIGNED_INT,e.generateMipMaps=!0,e._cachedAnisotropicFilteringLevel=null,r.updateTextureSamplingMode(Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,e),c.textureLOD?r._features.supportRenderAndCopyToLodForFloatTextures?c.textureHalfFloatRender&&c.textureHalfFloatLinearFiltering?(n=!0,e.type=Ze.TEXTURETYPE_HALF_FLOAT):c.textureFloatRender&&c.textureFloatLinearFiltering&&(n=!0,e.type=Ze.TEXTURETYPE_FLOAT):n=!1:(n=!1,a=!0,l={});let u=0;if(n)r.isWebGPU?(u=1,await import("./rgbdDecode.fragment-BdggM8VZ.esm.min.js")):await import("./rgbdDecode.fragment-CnUoEV03.esm.min.js"),o=new kr("rgbdDecode","rgbdDecode",null,null,1,null,Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,r,!1,void 0,e.type,void 0,null,!1,void 0,u),e._isRGBD=!1,e.invertY=!1,h=r.createRenderTargetCubeTexture(e.width,{generateDepthBuffer:!1,generateMipMaps:!0,generateStencilBuffer:!1,samplingMode:Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,type:e.type,format:Ze.TEXTUREFORMAT_RGBA});else if(e._isRGBD=!0,e.invertY=!0,a){const t=3,s=e._lodGenerationScale,n=e._lodGenerationOffset;for(let a=0;a<t;a++){const o=(i-1)*s+n,h=n+(o-n)*(1-a/(t-1)),c=Math.round(Math.min(Math.max(h,0),o)),u=new Tt(r,2);u.isCube=!0,u.invertY=!0,u.generateMipMaps=!1,r.updateTextureSamplingMode(Ze.TEXTURE_LINEAR_LINEAR,u);const d=new Pr(null);switch(d._isCube=!0,d._texture=u,l[c]=d,a){case 0:e._lodTextureLow=d;break;case 1:e._lodTextureMid=d;break;case 2:e._lodTextureHigh=d}}}const d=[];for(let i=0;i<t.length;i++)for(let c=0;c<6;c++){const u=t[i][c],_=new Blob([u],{type:s}),f=URL.createObjectURL(_);let p;if(r._features.forceBitmapOverHTMLImageElement)p=r.createImageBitmap(_,{premultiplyAlpha:"none"}).then((t=>ma(t,r,n,o,f,c,i,a,l,h,e)));else{const t=new Image;t.src=f,p=new Promise(((s,u)=>{t.onload=()=>{ma(t,r,n,o,f,c,i,a,l,h,e).then((()=>s())).catch((e=>{u(e)}))},t.onerror=e=>{u(e)}}))}d.push(p)}if(t.length<i){let s;const n=Math.pow(2,i-1-t.length),a=n*n*4;switch(e.type){case Ze.TEXTURETYPE_UNSIGNED_INT:s=new Uint8Array(a);break;case Ze.TEXTURETYPE_HALF_FLOAT:s=new Uint16Array(a);break;case Ze.TEXTURETYPE_FLOAT:s=new Float32Array(a)}for(let n=t.length;n<i;n++)for(let t=0;t<6;t++)r._uploadArrayBufferViewToTexture(e,s,t,n)}return Promise.all(d).then((()=>{h&&(r._releaseTexture(e),h._swapAndDie(e)),o&&o.dispose(),a&&(e._lodTextureHigh&&e._lodTextureHigh._texture&&(e._lodTextureHigh._texture.isReady=!0),e._lodTextureMid&&e._lodTextureMid._texture&&(e._lodTextureMid._texture.isReady=!0),e._lodTextureLow&&e._lodTextureLow._texture&&(e._lodTextureLow._texture.isReady=!0))}))}function Ta(e,t){const s=(t=fa(t)).irradiance;if(!s)return;const i=new xn;U.FromArrayToRef(s.x,0,i.x),U.FromArrayToRef(s.y,0,i.y),U.FromArrayToRef(s.z,0,i.z),U.FromArrayToRef(s.xx,0,i.xx),U.FromArrayToRef(s.yy,0,i.yy),U.FromArrayToRef(s.zz,0,i.zz),U.FromArrayToRef(s.yz,0,i.yz),U.FromArrayToRef(s.zx,0,i.zx),U.FromArrayToRef(s.xy,0,i.xy),e._sphericalPolynomial=i}class Ea{constructor(){this.keysUp=[38],this.keysUpward=[33],this.keysDown=[40],this.keysDownward=[34],this.keysLeft=[37],this.keysRight=[39],this.rotationSpeed=.5,this.keysRotateLeft=[],this.keysRotateRight=[],this.keysRotateUp=[],this.keysRotateDown=[],this._keys=new Array}attachControl(e){e=Yt.BackCompatCameraNoPreventDefault(arguments),this._onCanvasBlurObserver||(this._scene=this.camera.getScene(),this._engine=this._scene.getEngine(),this._onCanvasBlurObserver=this._engine.onCanvasBlurObservable.add((()=>{this._keys.length=0})),this._onKeyboardObserver=this._scene.onKeyboardObservable.add((t=>{const s=t.event;if(!s.metaKey)if(t.type===Li.KEYDOWN){if(-1!==this.keysUp.indexOf(s.keyCode)||-1!==this.keysDown.indexOf(s.keyCode)||-1!==this.keysLeft.indexOf(s.keyCode)||-1!==this.keysRight.indexOf(s.keyCode)||-1!==this.keysUpward.indexOf(s.keyCode)||-1!==this.keysDownward.indexOf(s.keyCode)||-1!==this.keysRotateLeft.indexOf(s.keyCode)||-1!==this.keysRotateRight.indexOf(s.keyCode)||-1!==this.keysRotateUp.indexOf(s.keyCode)||-1!==this.keysRotateDown.indexOf(s.keyCode)){-1===this._keys.indexOf(s.keyCode)&&this._keys.push(s.keyCode),e||s.preventDefault()}}else if(-1!==this.keysUp.indexOf(s.keyCode)||-1!==this.keysDown.indexOf(s.keyCode)||-1!==this.keysLeft.indexOf(s.keyCode)||-1!==this.keysRight.indexOf(s.keyCode)||-1!==this.keysUpward.indexOf(s.keyCode)||-1!==this.keysDownward.indexOf(s.keyCode)||-1!==this.keysRotateLeft.indexOf(s.keyCode)||-1!==this.keysRotateRight.indexOf(s.keyCode)||-1!==this.keysRotateUp.indexOf(s.keyCode)||-1!==this.keysRotateDown.indexOf(s.keyCode)){const t=this._keys.indexOf(s.keyCode);t>=0&&this._keys.splice(t,1),e||s.preventDefault()}})))}detachControl(){this._scene&&(this._onKeyboardObserver&&this._scene.onKeyboardObservable.remove(this._onKeyboardObserver),this._onCanvasBlurObserver&&this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver),this._onKeyboardObserver=null,this._onCanvasBlurObserver=null),this._keys.length=0}checkInputs(){if(this._onKeyboardObserver){const e=this.camera;for(let t=0;t<this._keys.length;t++){const s=this._keys[t],i=e._computeLocalCameraSpeed();-1!==this.keysLeft.indexOf(s)?e._localDirection.copyFromFloats(-i,0,0):-1!==this.keysUp.indexOf(s)?e._localDirection.copyFromFloats(0,0,i):-1!==this.keysRight.indexOf(s)?e._localDirection.copyFromFloats(i,0,0):-1!==this.keysDown.indexOf(s)?e._localDirection.copyFromFloats(0,0,-i):-1!==this.keysUpward.indexOf(s)?e._localDirection.copyFromFloats(0,i,0):-1!==this.keysDownward.indexOf(s)?e._localDirection.copyFromFloats(0,-i,0):-1!==this.keysRotateLeft.indexOf(s)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y-=this._getLocalRotation()):-1!==this.keysRotateRight.indexOf(s)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.y+=this._getLocalRotation()):-1!==this.keysRotateUp.indexOf(s)?(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x-=this._getLocalRotation()):-1!==this.keysRotateDown.indexOf(s)&&(e._localDirection.copyFromFloats(0,0,0),e.cameraRotation.x+=this._getLocalRotation()),e.getScene().useRightHandedSystem&&(e._localDirection.z*=-1),e.getViewMatrix().invertToRef(e._cameraTransformMatrix),U.TransformNormalToRef(e._localDirection,e._cameraTransformMatrix,e._transformedDirection),e.cameraDirection.addInPlace(e._transformedDirection)}}}getClassName(){return"FreeCameraKeyboardMoveInput"}_onLostFocus(){this._keys.length=0}getSimpleName(){return"keyboard"}_getLocalRotation(){const e=this.camera._calculateHandednessMultiplier();return this.rotationSpeed*this._engine.getDeltaTime()/1e3*e}}e([a()],Ea.prototype,"keysUp",void 0),e([a()],Ea.prototype,"keysUpward",void 0),e([a()],Ea.prototype,"keysDown",void 0),e([a()],Ea.prototype,"keysDownward",void 0),e([a()],Ea.prototype,"keysLeft",void 0),e([a()],Ea.prototype,"keysRight",void 0),e([a()],Ea.prototype,"rotationSpeed",void 0),e([a()],Ea.prototype,"keysRotateLeft",void 0),e([a()],Ea.prototype,"keysRotateRight",void 0),e([a()],Ea.prototype,"keysRotateUp",void 0),e([a()],Ea.prototype,"keysRotateDown",void 0),Ci.FreeCameraKeyboardMoveInput=Ea;class Aa{constructor(e=!0){this.touchEnabled=e,this.buttons=[0,1,2],this.angularSensibility=2e3,this._previousPosition=null,this.onPointerMovedObservable=new g,this._allowCameraRotation=!0,this._currentActiveButton=-1,this._activePointerId=-1}attachControl(e){e=Yt.BackCompatCameraNoPreventDefault(arguments);const t=this.camera.getEngine(),s=t.getInputElement();this._pointerInput||(this._pointerInput=i=>{const r=i.event,n="touch"===r.pointerType;if(!this.touchEnabled&&n)return;if(i.type!==hi.POINTERMOVE&&-1===this.buttons.indexOf(r.button))return;const a=r.target;if(i.type===hi.POINTERDOWN){if(n&&-1!==this._activePointerId||!n&&-1!==this._currentActiveButton)return;this._activePointerId=r.pointerId;try{a?.setPointerCapture(r.pointerId)}catch(e){}-1===this._currentActiveButton&&(this._currentActiveButton=r.button),this._previousPosition={x:r.clientX,y:r.clientY},e||(r.preventDefault(),s&&s.focus()),t.isPointerLock&&this._onMouseMove&&this._onMouseMove(i.event)}else if(i.type===hi.POINTERUP){if(n&&this._activePointerId!==r.pointerId||!n&&this._currentActiveButton!==r.button)return;try{a?.releasePointerCapture(r.pointerId)}catch(e){}this._currentActiveButton=-1,this._previousPosition=null,e||r.preventDefault(),this._activePointerId=-1}else if(i.type===hi.POINTERMOVE&&(this._activePointerId===r.pointerId||!n))if(t.isPointerLock&&this._onMouseMove)this._onMouseMove(i.event);else if(this._previousPosition){const t=this.camera._calculateHandednessMultiplier(),s=(r.clientX-this._previousPosition.x)*t,i=r.clientY-this._previousPosition.y;this._allowCameraRotation&&(this.camera.cameraRotation.y+=s/this.angularSensibility,this.camera.cameraRotation.x+=i/this.angularSensibility),this.onPointerMovedObservable.notifyObservers({offsetX:s,offsetY:i}),this._previousPosition={x:r.clientX,y:r.clientY},e||r.preventDefault()}}),this._onMouseMove=s=>{if(!t.isPointerLock)return;const i=this.camera._calculateHandednessMultiplier(),r=s.movementX*i;this.camera.cameraRotation.y+=r/this.angularSensibility;const n=s.movementY;this.camera.cameraRotation.x+=n/this.angularSensibility,this._previousPosition=null,e||s.preventDefault()},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,hi.POINTERDOWN|hi.POINTERUP|hi.POINTERMOVE),s&&(this._contextMenuBind=e=>this.onContextMenu(e),s.addEventListener("contextmenu",this._contextMenuBind,!1))}onContextMenu(e){e.preventDefault()}detachControl(){if(this._observer){if(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._contextMenuBind){const e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("contextmenu",this._contextMenuBind)}this.onPointerMovedObservable&&this.onPointerMovedObservable.clear(),this._observer=null,this._onMouseMove=null,this._previousPosition=null}this._activePointerId=-1,this._currentActiveButton=-1}getClassName(){return"FreeCameraMouseInput"}getSimpleName(){return"mouse"}}e([a()],Aa.prototype,"buttons",void 0),e([a()],Aa.prototype,"angularSensibility",void 0),Ci.FreeCameraMouseInput=Aa;class ya{constructor(){this.wheelPrecisionX=3,this.wheelPrecisionY=3,this.wheelPrecisionZ=3,this.onChangedObservable=new g,this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0,this._ffMultiplier=12,this._normalize=120}attachControl(e){e=Yt.BackCompatCameraNoPreventDefault(arguments),this._wheel=t=>{if(t.type!==hi.POINTERWHEEL)return;const s=t.event,i=s.deltaMode===Bi.DOM_DELTA_LINE?this._ffMultiplier:1;this._wheelDeltaX+=this.wheelPrecisionX*i*s.deltaX/this._normalize,this._wheelDeltaY-=this.wheelPrecisionY*i*s.deltaY/this._normalize,this._wheelDeltaZ+=this.wheelPrecisionZ*i*s.deltaZ/this._normalize,s.preventDefault&&(e||s.preventDefault())},this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._wheel,hi.POINTERWHEEL)}detachControl(){this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null,this._wheel=null),this.onChangedObservable&&this.onChangedObservable.clear()}checkInputs(){this.onChangedObservable.notifyObservers({wheelDeltaX:this._wheelDeltaX,wheelDeltaY:this._wheelDeltaY,wheelDeltaZ:this._wheelDeltaZ}),this._wheelDeltaX=0,this._wheelDeltaY=0,this._wheelDeltaZ=0}getClassName(){return"BaseCameraMouseWheelInput"}getSimpleName(){return"mousewheel"}}var ba;e([a()],ya.prototype,"wheelPrecisionX",void 0),e([a()],ya.prototype,"wheelPrecisionY",void 0),e([a()],ya.prototype,"wheelPrecisionZ",void 0),function(e){e[e.MoveRelative=0]="MoveRelative",e[e.RotateRelative=1]="RotateRelative",e[e.MoveScene=2]="MoveScene"}(ba||(ba={}));class Ra extends ya{constructor(){super(...arguments),this._moveRelative=U.Zero(),this._rotateRelative=U.Zero(),this._moveScene=U.Zero(),this._wheelXAction=ba.MoveRelative,this._wheelXActionCoordinate=0,this._wheelYAction=ba.MoveRelative,this._wheelYActionCoordinate=2,this._wheelZAction=null,this._wheelZActionCoordinate=null}getClassName(){return"FreeCameraMouseWheelInput"}set wheelXMoveRelative(e){null===e&&this._wheelXAction!==ba.MoveRelative||(this._wheelXAction=ba.MoveRelative,this._wheelXActionCoordinate=e)}get wheelXMoveRelative(){return this._wheelXAction!==ba.MoveRelative?null:this._wheelXActionCoordinate}set wheelYMoveRelative(e){null===e&&this._wheelYAction!==ba.MoveRelative||(this._wheelYAction=ba.MoveRelative,this._wheelYActionCoordinate=e)}get wheelYMoveRelative(){return this._wheelYAction!==ba.MoveRelative?null:this._wheelYActionCoordinate}set wheelZMoveRelative(e){null===e&&this._wheelZAction!==ba.MoveRelative||(this._wheelZAction=ba.MoveRelative,this._wheelZActionCoordinate=e)}get wheelZMoveRelative(){return this._wheelZAction!==ba.MoveRelative?null:this._wheelZActionCoordinate}set wheelXRotateRelative(e){null===e&&this._wheelXAction!==ba.RotateRelative||(this._wheelXAction=ba.RotateRelative,this._wheelXActionCoordinate=e)}get wheelXRotateRelative(){return this._wheelXAction!==ba.RotateRelative?null:this._wheelXActionCoordinate}set wheelYRotateRelative(e){null===e&&this._wheelYAction!==ba.RotateRelative||(this._wheelYAction=ba.RotateRelative,this._wheelYActionCoordinate=e)}get wheelYRotateRelative(){return this._wheelYAction!==ba.RotateRelative?null:this._wheelYActionCoordinate}set wheelZRotateRelative(e){null===e&&this._wheelZAction!==ba.RotateRelative||(this._wheelZAction=ba.RotateRelative,this._wheelZActionCoordinate=e)}get wheelZRotateRelative(){return this._wheelZAction!==ba.RotateRelative?null:this._wheelZActionCoordinate}set wheelXMoveScene(e){null===e&&this._wheelXAction!==ba.MoveScene||(this._wheelXAction=ba.MoveScene,this._wheelXActionCoordinate=e)}get wheelXMoveScene(){return this._wheelXAction!==ba.MoveScene?null:this._wheelXActionCoordinate}set wheelYMoveScene(e){null===e&&this._wheelYAction!==ba.MoveScene||(this._wheelYAction=ba.MoveScene,this._wheelYActionCoordinate=e)}get wheelYMoveScene(){return this._wheelYAction!==ba.MoveScene?null:this._wheelYActionCoordinate}set wheelZMoveScene(e){null===e&&this._wheelZAction!==ba.MoveScene||(this._wheelZAction=ba.MoveScene,this._wheelZActionCoordinate=e)}get wheelZMoveScene(){return this._wheelZAction!==ba.MoveScene?null:this._wheelZActionCoordinate}checkInputs(){if(0===this._wheelDeltaX&&0===this._wheelDeltaY&&0==this._wheelDeltaZ)return;this._moveRelative.setAll(0),this._rotateRelative.setAll(0),this._moveScene.setAll(0),this._updateCamera(),this.camera.getScene().useRightHandedSystem&&(this._moveRelative.z*=-1);const e=V.Zero();this.camera.getViewMatrix().invertToRef(e);const t=U.Zero();U.TransformNormalToRef(this._moveRelative,e,t),this.camera.cameraRotation.x+=this._rotateRelative.x/200,this.camera.cameraRotation.y+=this._rotateRelative.y/200,this.camera.cameraDirection.addInPlace(t),this.camera.cameraDirection.addInPlace(this._moveScene),super.checkInputs()}_updateCamera(){this._updateCameraProperty(this._wheelDeltaX,this._wheelXAction,this._wheelXActionCoordinate),this._updateCameraProperty(this._wheelDeltaY,this._wheelYAction,this._wheelYActionCoordinate),this._updateCameraProperty(this._wheelDeltaZ,this._wheelZAction,this._wheelZActionCoordinate)}_updateCameraProperty(e,t,s){if(0===e)return;if(null===t||null===s)return;let i=null;switch(t){case ba.MoveRelative:i=this._moveRelative;break;case ba.RotateRelative:i=this._rotateRelative;break;case ba.MoveScene:i=this._moveScene}switch(s){case 0:i.set(e,0,0);break;case 1:i.set(0,e,0);break;case 2:i.set(0,0,e)}}}e([a()],Ra.prototype,"wheelXMoveRelative",null),e([a()],Ra.prototype,"wheelYMoveRelative",null),e([a()],Ra.prototype,"wheelZMoveRelative",null),e([a()],Ra.prototype,"wheelXRotateRelative",null),e([a()],Ra.prototype,"wheelYRotateRelative",null),e([a()],Ra.prototype,"wheelZRotateRelative",null),e([a()],Ra.prototype,"wheelXMoveScene",null),e([a()],Ra.prototype,"wheelYMoveScene",null),e([a()],Ra.prototype,"wheelZMoveScene",null),Ci.FreeCameraMouseWheelInput=Ra;class xa{constructor(e=!1){this.allowMouse=e,this.touchAngularSensibility=2e5,this.touchMoveSensibility=250,this.singleFingerRotate=!1,this._offsetX=null,this._offsetY=null,this._pointerPressed=new Array,this._isSafari=Yt.IsSafari()}attachControl(e){e=Yt.BackCompatCameraNoPreventDefault(arguments);let t=null;if(void 0===this._pointerInput&&(this._onLostFocus=()=>{this._offsetX=null,this._offsetY=null},this._pointerInput=s=>{const i=s.event,r="mouse"===i.pointerType||this._isSafari&&void 0===i.pointerType;if(this.allowMouse||!r)if(s.type===hi.POINTERDOWN){if(e||i.preventDefault(),this._pointerPressed.push(i.pointerId),1!==this._pointerPressed.length)return;t={x:i.clientX,y:i.clientY}}else if(s.type===hi.POINTERUP){e||i.preventDefault();const s=this._pointerPressed.indexOf(i.pointerId);if(-1===s)return;if(this._pointerPressed.splice(s,1),0!=s)return;t=null,this._offsetX=null,this._offsetY=null}else if(s.type===hi.POINTERMOVE){if(e||i.preventDefault(),!t)return;if(0!=this._pointerPressed.indexOf(i.pointerId))return;this._offsetX=i.clientX-t.x,this._offsetY=-(i.clientY-t.y)}}),this._observer=this.camera.getScene()._inputManager._addCameraPointerObserver(this._pointerInput,hi.POINTERDOWN|hi.POINTERUP|hi.POINTERMOVE),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.addEventListener("blur",this._onLostFocus)}}detachControl(){if(this._pointerInput){if(this._observer&&(this.camera.getScene()._inputManager._removeCameraPointerObserver(this._observer),this._observer=null),this._onLostFocus){const e=this.camera.getEngine().getInputElement();e&&e.removeEventListener("blur",this._onLostFocus),this._onLostFocus=null}this._pointerPressed.length=0,this._offsetX=null,this._offsetY=null}}checkInputs(){if(null===this._offsetX||null===this._offsetY)return;if(0===this._offsetX&&0===this._offsetY)return;const e=this.camera,t=e._calculateHandednessMultiplier();e.cameraRotation.y=t*this._offsetX/this.touchAngularSensibility;if(this.singleFingerRotate&&1===this._pointerPressed.length||!this.singleFingerRotate&&this._pointerPressed.length>1)e.cameraRotation.x=-this._offsetY/this.touchAngularSensibility;else{const t=e._computeLocalCameraSpeed(),s=new U(0,0,0!==this.touchMoveSensibility?t*this._offsetY/this.touchMoveSensibility:0);V.RotationYawPitchRollToRef(e.rotation.y,e.rotation.x,0,e._cameraRotationMatrix),e.cameraDirection.addInPlace(U.TransformCoordinates(s,e._cameraRotationMatrix))}}getClassName(){return"FreeCameraTouchInput"}getSimpleName(){return"touch"}}e([a()],xa.prototype,"touchAngularSensibility",void 0),e([a()],xa.prototype,"touchMoveSensibility",void 0),Ci.FreeCameraTouchInput=xa;class Ma extends Pi{constructor(e){super(e),this._mouseInput=null,this._mouseWheelInput=null}addKeyboard(){return this.add(new Ea),this}addMouse(e=!0){return this._mouseInput||(this._mouseInput=new Aa(e),this.add(this._mouseInput)),this}removeMouse(){return this._mouseInput&&this.remove(this._mouseInput),this}addMouseWheel(){return this._mouseWheelInput||(this._mouseWheelInput=new Ra,this.add(this._mouseWheelInput)),this}removeMouseWheel(){return this._mouseWheelInput&&this.remove(this._mouseWheelInput),this}addTouch(){return this.add(new xa),this}clear(){super.clear(),this._mouseInput=null}}class Ia extends Si{get angularSensibility(){const e=this.inputs.attached.mouse;return e?e.angularSensibility:0}set angularSensibility(e){const t=this.inputs.attached.mouse;t&&(t.angularSensibility=e)}get keysUp(){const e=this.inputs.attached.keyboard;return e?e.keysUp:[]}set keysUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysUp=e)}get keysUpward(){const e=this.inputs.attached.keyboard;return e?e.keysUpward:[]}set keysUpward(e){const t=this.inputs.attached.keyboard;t&&(t.keysUpward=e)}get keysDown(){const e=this.inputs.attached.keyboard;return e?e.keysDown:[]}set keysDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysDown=e)}get keysDownward(){const e=this.inputs.attached.keyboard;return e?e.keysDownward:[]}set keysDownward(e){const t=this.inputs.attached.keyboard;t&&(t.keysDownward=e)}get keysLeft(){const e=this.inputs.attached.keyboard;return e?e.keysLeft:[]}set keysLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysLeft=e)}get keysRight(){const e=this.inputs.attached.keyboard;return e?e.keysRight:[]}set keysRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRight=e)}get keysRotateLeft(){const e=this.inputs.attached.keyboard;return e?e.keysRotateLeft:[]}set keysRotateLeft(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateLeft=e)}get keysRotateRight(){const e=this.inputs.attached.keyboard;return e?e.keysRotateRight:[]}set keysRotateRight(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateRight=e)}get keysRotateUp(){const e=this.inputs.attached.keyboard;return e?e.keysRotateUp:[]}set keysRotateUp(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateUp=e)}get keysRotateDown(){const e=this.inputs.attached.keyboard;return e?e.keysRotateDown:[]}set keysRotateDown(e){const t=this.inputs.attached.keyboard;t&&(t.keysRotateDown=e)}constructor(e,t,s,i=!0){super(e,t,s,i),this.ellipsoid=new U(.5,1,.5),this.ellipsoidOffset=new U(0,0,0),this.checkCollisions=!1,this.applyGravity=!1,this._needMoveForGravity=!1,this._oldPosition=U.Zero(),this._diffPosition=U.Zero(),this._newPosition=U.Zero(),this._collisionMask=-1,this._onCollisionPositionChange=(e,t,s=null)=>{this._newPosition.copyFrom(t),this._newPosition.subtractToRef(this._oldPosition,this._diffPosition),this._diffPosition.length()>yt.CollisionsEpsilon&&(this.position.addToRef(this._diffPosition,this._deferredPositionUpdate),this._deferOnly?this._deferredUpdated=!0:this.position.copyFrom(this._deferredPositionUpdate),this.onCollide&&s&&this.onCollide(s))},this.inputs=new Ma(this),this.inputs.addKeyboard().addMouse()}attachControl(e,t){t=Yt.BackCompatCameraNoPreventDefault(arguments),this.inputs.attachElement(t)}detachControl(){this.inputs.detachElement(),this.cameraDirection=new U(0,0,0),this.cameraRotation=new B(0,0)}get collisionMask(){return this._collisionMask}set collisionMask(e){this._collisionMask=isNaN(e)?-1:e}_collideWithWorld(e){let t;t=this.parent?U.TransformCoordinates(this.position,this.parent.getWorldMatrix()):this.position,t.subtractFromFloatsToRef(0,this.ellipsoid.y,0,this._oldPosition),this._oldPosition.addInPlace(this.ellipsoidOffset);const s=this.getScene().collisionCoordinator;this._collider||(this._collider=s.createCollider()),this._collider._radius=this.ellipsoid,this._collider.collisionMask=this._collisionMask;let i=e;this.applyGravity&&(i=e.add(this.getScene().gravity)),s.getNewPosition(this._oldPosition,i,this._collider,3,null,this._onCollisionPositionChange,this.uniqueId)}_checkInputs(){this._localDirection||(this._localDirection=U.Zero(),this._transformedDirection=U.Zero()),this.inputs.checkInputs(),super._checkInputs()}set needMoveForGravity(e){this._needMoveForGravity=e}get needMoveForGravity(){return this._needMoveForGravity}_decideIfNeedsToMove(){return this._needMoveForGravity||Math.abs(this.cameraDirection.x)>0||Math.abs(this.cameraDirection.y)>0||Math.abs(this.cameraDirection.z)>0}_updatePosition(){this.checkCollisions&&this.getScene().collisionsEnabled?this._collideWithWorld(this.cameraDirection):super._updatePosition()}dispose(){this.inputs.clear(),super.dispose()}getClassName(){return"FreeCamera"}}e([c()],Ia.prototype,"ellipsoid",void 0),e([c()],Ia.prototype,"ellipsoidOffset",void 0),e([a()],Ia.prototype,"checkCollisions",void 0),e([a()],Ia.prototype,"applyGravity",void 0),I("BABYLON.FreeCamera",Ia);class Sa{getClassName(){return"TargetedAnimation"}serialize(){const e={};return e.animation=this.animation.serialize(),e.targetId=this.target.id,e}}class va{get mask(){return this._mask}set mask(e){this._mask!==e&&(this._mask=e,this.syncWithMask(!0))}syncWithMask(e=!1){if(this.mask||e){this._numActiveAnimatables=0;for(let e=0;e<this._animatables.length;++e){const t=this._animatables[e];!this.mask||this.mask.disabled||this.mask.retainsTarget(t.target.name)?(this._numActiveAnimatables++,t.paused&&t.restart()):t.paused||t.pause()}}else this._numActiveAnimatables=this._targetedAnimations.length}removeUnmaskedAnimations(){if(this.mask&&!this.mask.disabled){for(let e=0;e<this._animatables.length;++e){const t=this._animatables[e];this.mask.retainsTarget(t.target.name)||(t.stop(),this._animatables.splice(e,1),--e)}for(let e=0;e<this._targetedAnimations.length;e++){const t=this._targetedAnimations[e];this.mask.retainsTarget(t.target.name)||(this._targetedAnimations.splice(e,1),--e)}}}get from(){return this._from}set from(e){if(this._from!==e){this._from=e;for(let e=0;e<this._animatables.length;e++){this._animatables[e].fromFrame=this._from}}}get to(){return this._to}set to(e){if(this._to!==e){this._to=e;for(let e=0;e<this._animatables.length;e++){this._animatables[e].toFrame=this._to}}}get isStarted(){return this._isStarted}get isPlaying(){return this._isStarted&&!this._isPaused}get speedRatio(){return this._speedRatio}set speedRatio(e){if(this._speedRatio!==e){this._speedRatio=e;for(let e=0;e<this._animatables.length;e++){this._animatables[e].speedRatio=this._speedRatio}}}get loopAnimation(){return this._loopAnimation}set loopAnimation(e){if(this._loopAnimation!==e){this._loopAnimation=e;for(let e=0;e<this._animatables.length;e++){this._animatables[e].loopAnimation=this._loopAnimation}}}get isAdditive(){return this._isAdditive}set isAdditive(e){if(this._isAdditive!==e){this._isAdditive=e;for(let e=0;e<this._animatables.length;e++){this._animatables[e].isAdditive=this._isAdditive}}}get weight(){return this._weight}set weight(e){this._weight!==e&&(this._weight=e,this.setWeightForAllAnimatables(this._weight))}get targetedAnimations(){return this._targetedAnimations}get animatables(){return this._animatables}get children(){return this._targetedAnimations}get playOrder(){return this._playOrder}set playOrder(e){if(this._playOrder!==e&&(this._playOrder=e,this._animatables.length>0)){for(let e=0;e<this._animatables.length;e++)this._animatables[e].playOrder=this._playOrder;this._scene.sortActiveAnimatables()}}get enableBlending(){return this._enableBlending}set enableBlending(e){if(this._enableBlending!==e&&(this._enableBlending=e,null!==e))for(let t=0;t<this._targetedAnimations.length;++t)this._targetedAnimations[t].animation.enableBlending=e}get blendingSpeed(){return this._blendingSpeed}set blendingSpeed(e){if(this._blendingSpeed!==e&&(this._blendingSpeed=e,null!==e))for(let t=0;t<this._targetedAnimations.length;++t)this._targetedAnimations[t].animation.blendingSpeed=e}getLength(e,t){e=e??this._from;return((t=t??this._to)-e)/(this.targetedAnimations[0].animation.framePerSecond*this._speedRatio)}static MergeAnimationGroups(e,t=!0,s=!1,i){if(0===e.length)return null;i=i??e[0].weight;let r=Number.MAX_VALUE,n=-Number.MAX_VALUE;if(s)for(const t of e)t.from<r&&(r=t.from),t.to>n&&(n=t.to);const a=new va(e[0].name+"_merged",e[0]._scene,i);for(const i of e){s&&i.normalize(r,n);for(const e of i.targetedAnimations)a.addTargetedAnimation(e.animation,e.target);t&&i.dispose()}return a}constructor(e,t=null,s=-1,i=0){this.name=e,this._targetedAnimations=new Array,this._animatables=new Array,this._from=Number.MAX_VALUE,this._to=-Number.MAX_VALUE,this._speedRatio=1,this._loopAnimation=!1,this._isAdditive=!1,this._weight=-1,this._playOrder=0,this._enableBlending=null,this._blendingSpeed=null,this._numActiveAnimatables=0,this._shouldStart=!0,this._parentContainer=null,this.onAnimationEndObservable=new g,this.onAnimationLoopObservable=new g,this.onAnimationGroupLoopObservable=new g,this.onAnimationGroupEndObservable=new g,this.onAnimationGroupPauseObservable=new g,this.onAnimationGroupPlayObservable=new g,this.metadata=null,this._mask=null,this._animationLoopFlags=[],this._scene=t||C.LastCreatedScene,this._weight=s,this._playOrder=i,this.uniqueId=this._scene.getUniqueId(),this._scene.addAnimationGroup(this)}addTargetedAnimation(e,t){const s=new Sa;s.animation=e,s.target=t;const i=e.getKeys();return this._from>i[0].frame&&(this._from=i[0].frame),this._to<i[i.length-1].frame&&(this._to=i[i.length-1].frame),null!==this._enableBlending&&(e.enableBlending=this._enableBlending),null!==this._blendingSpeed&&(e.blendingSpeed=this._blendingSpeed),this._targetedAnimations.push(s),this._shouldStart=!0,s}removeTargetedAnimation(e){for(let t=this._targetedAnimations.length-1;t>-1;t--){this._targetedAnimations[t].animation===e&&this._targetedAnimations.splice(t,1)}}normalize(e=null,t=null){null==e&&(e=this._from),null==t&&(t=this._to);for(let s=0;s<this._targetedAnimations.length;s++){const i=this._targetedAnimations[s].animation.getKeys(),r=i[0],n=i[i.length-1];if(r.frame>e){const t={frame:e,value:r.value,inTangent:r.inTangent,outTangent:r.outTangent,interpolation:r.interpolation};i.splice(0,0,t)}if(n.frame<t){const e={frame:t,value:n.value,inTangent:n.inTangent,outTangent:n.outTangent,interpolation:n.interpolation};i.push(e)}}return this._from=e,this._to=t,this}_processLoop(e,t,s){e.onAnimationLoop=()=>{this.onAnimationLoopObservable.notifyObservers(t),this._animationLoopFlags[s]||(this._animationLoopFlags[s]=!0,this._animationLoopCount++,this._animationLoopCount===this._numActiveAnimatables&&(this.onAnimationGroupLoopObservable.notifyObservers(this),this._animationLoopCount=0,this._animationLoopFlags.length=0))}}start(e=!1,t=1,s,i,r){if(this._isStarted||0===this._targetedAnimations.length)return this;this._loopAnimation=e,this._shouldStart=!1,this._animationLoopCount=0,this._animationLoopFlags.length=0;for(let n=0;n<this._targetedAnimations.length;n++){const a=this._targetedAnimations[n],o=this._scene.beginDirectAnimation(a.target,[a.animation],void 0!==s?s:this._from,void 0!==i?i:this._to,e,t,void 0,void 0,void 0!==r?r:this._isAdditive);o.weight=this._weight,o.playOrder=this._playOrder,o.onAnimationEnd=()=>{this.onAnimationEndObservable.notifyObservers(a),this._checkAnimationGroupEnded(o)},this._processLoop(o,a,n),this._animatables.push(o)}return this.syncWithMask(),this._scene.sortActiveAnimatables(),this._speedRatio=t,this._isStarted=!0,this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}pause(){if(!this._isStarted)return this;this._isPaused=!0;for(let e=0;e<this._animatables.length;e++){this._animatables[e].pause()}return this.onAnimationGroupPauseObservable.notifyObservers(this),this}play(e){return this.isStarted&&this._animatables.length&&!this._shouldStart?(void 0!==e&&(this.loopAnimation=e),this.restart()):(this.stop(),this.start(e,this._speedRatio)),this}reset(){if(!this._isStarted)return this.play(),this.goToFrame(0),this.stop(!0),this;for(let e=0;e<this._animatables.length;e++){this._animatables[e].reset()}return this}restart(){if(!this._isStarted)return this;for(let e=0;e<this._animatables.length;e++){this._animatables[e].restart()}return this.syncWithMask(),this._isPaused=!1,this.onAnimationGroupPlayObservable.notifyObservers(this),this}stop(e=!1){if(!this._isStarted)return this;const t=this._animatables.slice();for(let s=0;s<t.length;s++)t[s].stop(void 0,void 0,!0,e);let s=0;for(let t=0;t<this._scene._activeAnimatables.length;t++){const i=this._scene._activeAnimatables[t];i._runtimeAnimations.length>0?this._scene._activeAnimatables[s++]=i:e&&this._checkAnimationGroupEnded(i,e)}return this._scene._activeAnimatables.length=s,this._isStarted=!1,this}setWeightForAllAnimatables(e){for(let t=0;t<this._animatables.length;t++){this._animatables[t].weight=e}return this}syncAllAnimationsWith(e){for(let t=0;t<this._animatables.length;t++){this._animatables[t].syncWith(e)}return this}goToFrame(e){if(!this._isStarted)return this;for(let t=0;t<this._animatables.length;t++){this._animatables[t].goToFrame(e)}return this}getCurrentFrame(){return this.animatables[0]?.masterFrame||0}dispose(){this.isStarted&&this.stop(),this._targetedAnimations.length=0,this._animatables.length=0;const e=this._scene.animationGroups.indexOf(this);if(e>-1&&this._scene.animationGroups.splice(e,1),this._parentContainer){const e=this._parentContainer.animationGroups.indexOf(this);e>-1&&this._parentContainer.animationGroups.splice(e,1),this._parentContainer=null}this.onAnimationEndObservable.clear(),this.onAnimationGroupEndObservable.clear(),this.onAnimationGroupPauseObservable.clear(),this.onAnimationGroupPlayObservable.clear(),this.onAnimationLoopObservable.clear(),this.onAnimationGroupLoopObservable.clear()}_checkAnimationGroupEnded(e,t=!1){const s=this._animatables.indexOf(e);s>-1&&this._animatables.splice(s,1),0===this._animatables.length&&(this._isStarted=!1,t||this.onAnimationGroupEndObservable.notifyObservers(this))}clone(e,t,s=!1){const i=new va(e||this.name,this._scene,this._weight,this._playOrder);i._from=this.from,i._to=this.to,i._speedRatio=this.speedRatio,i._loopAnimation=this.loopAnimation,i._isAdditive=this.isAdditive,i._enableBlending=this.enableBlending,i._blendingSpeed=this.blendingSpeed,i.metadata=this.metadata,i.mask=this.mask;for(const e of this._targetedAnimations)i.addTargetedAnimation(s?e.animation.clone():e.animation,t?t(e.target):e.target);return i}serialize(){const e={};e.name=this.name,e.from=this.from,e.to=this.to,e.speedRatio=this.speedRatio,e.loopAnimation=this.loopAnimation,e.isAdditive=this.isAdditive,e.weight=this.weight,e.playOrder=this.playOrder,e.enableBlending=this.enableBlending,e.blendingSpeed=this.blendingSpeed,e.targetedAnimations=[];for(let t=0;t<this.targetedAnimations.length;t++){const s=this.targetedAnimations[t];e.targetedAnimations[t]=s.serialize()}return q&&q.HasTags(this)&&(e.tags=q.GetTags(this)),this.metadata&&(e.metadata=this.metadata),e}static Parse(e,t){const s=new va(e.name,t,e.weight,e.playOrder);for(let i=0;i<e.targetedAnimations.length;i++){const r=e.targetedAnimations[i],n=xi.Parse(r.animation),a=r.targetId;if("influence"===r.animation.property){const e=t.getMorphTargetById(a);e&&s.addTargetedAnimation(n,e)}else{const e=t.getNodeById(a);null!=e&&s.addTargetedAnimation(n,e)}}return q&&q.AddTagsTo(s,e.tags),null!==e.from&&null!==e.to&&s.normalize(e.from,e.to),void 0!==e.speedRatio&&(s._speedRatio=e.speedRatio),void 0!==e.loopAnimation&&(s._loopAnimation=e.loopAnimation),void 0!==e.isAdditive&&(s._isAdditive=e.isAdditive),void 0!==e.weight&&(s._weight=e.weight),void 0!==e.playOrder&&(s._playOrder=e.playOrder),void 0!==e.enableBlending&&(s._enableBlending=e.enableBlending),void 0!==e.blendingSpeed&&(s._blendingSpeed=e.blendingSpeed),void 0!==e.metadata&&(s.metadata=e.metadata),s}static MakeAnimationAdditive(e,t,s,i=!1,r){let n;n="object"==typeof t?t:{referenceFrame:t,range:s,cloneOriginalAnimationGroup:i,clonedAnimationName:r};let a=e;n.cloneOriginalAnimationGroup&&(a=e.clone(n.clonedAnimationGroupName||a.name));const o=a.targetedAnimations;for(let e=0;e<o.length;e++){const t=o[e];t.animation=xi.MakeAnimationAdditive(t.animation,n)}if(a.isAdditive=!0,n.clipKeys){let e=Number.MAX_VALUE,t=-Number.MAX_VALUE;const s=a.targetedAnimations;for(let i=0;i<s.length;i++){const r=s[i].animation.getKeys();e>r[0].frame&&(e=r[0].frame),t<r[r.length-1].frame&&(t=r[r.length-1].frame)}a._from=e,a._to=t}return a}static ClipKeys(e,t,s,i,r){const n=e.clone(i||e.name);return va.ClipKeysInPlace(n,t,s,r)}static ClipKeysInPlace(e,t,s,i){return va.ClipInPlace(e,t,s,i,!1)}static ClipFrames(e,t,s,i,r){const n=e.clone(i||e.name);return va.ClipFramesInPlace(n,t,s,r)}static ClipFramesInPlace(e,t,s,i){return va.ClipInPlace(e,t,s,i,!0)}static ClipInPlace(e,t,s,i,r=!1){let n=Number.MAX_VALUE,a=-Number.MAX_VALUE;const o=e.targetedAnimations;for(let e=0;e<o.length;e++){const h=o[e],l=i?h.animation:h.animation.clone();r&&(l.createKeyForFrame(t),l.createKeyForFrame(s));const c=l.getKeys(),u=[];let d=Number.MAX_VALUE;for(let e=0;e<c.length;e++){const i=c[e];if(!r&&e>=t&&e<=s||r&&i.frame>=t&&i.frame<=s){const e={frame:i.frame,value:i.value.clone?i.value.clone():i.value,inTangent:i.inTangent,outTangent:i.outTangent,interpolation:i.interpolation,lockedTangent:i.lockedTangent};d===Number.MAX_VALUE&&(d=e.frame),e.frame-=d,u.push(e)}}0!==u.length?(n>u[0].frame&&(n=u[0].frame),a<u[u.length-1].frame&&(a=u[u.length-1].frame),l.setKeys(u,!0),h.animation=l):(o.splice(e,1),e--)}return e._from=n,e._to=a,e}getClassName(){return"AnimationGroup"}toString(e){let t="Name: "+this.name;return t+=", type: "+this.getClassName(),e&&(t+=", from: "+this._from,t+=", to: "+this._to,t+=", isStarted: "+this._isStarted,t+=", speedRatio: "+this._speedRatio,t+=", targetedAnimations length: "+this._targetedAnimations.length,t+=", animatables length: "+this._animatables),t}}function Ca(e,t,s,i){let r,n=1;i===Ze.TEXTURETYPE_FLOAT?r=new Float32Array(t*s*4):i===Ze.TEXTURETYPE_HALF_FLOAT?(r=new Uint16Array(t*s*4),n=15360):r=i===Ze.TEXTURETYPE_UNSIGNED_INTEGER?new Uint32Array(t*s*4):new Uint8Array(t*s*4);for(let i=0;i<t;i++)for(let a=0;a<s;a++){const s=3*(a*t+i),o=4*(a*t+i);r[o+0]=e[s+0],r[o+1]=e[s+1],r[o+2]=e[s+2],r[o+3]=n}return r}function Pa(e){return function(t,s,i,r,n,a,o,h,l=null,c=Ze.TEXTURETYPE_UNSIGNED_INT){const u=e?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,d=new Tt(this,e?10:11);d.baseWidth=s,d.baseHeight=i,d.baseDepth=r,d.width=s,d.height=i,d.depth=r,d.format=n,d.type=c,d.generateMipMaps=a,d.samplingMode=h,e?d.is3D=!0:d.is2DArray=!0,this._doNotHandleContextLost||(d._bufferView=t),e?this.updateRawTexture3D(d,t,n,o,l,c):this.updateRawTexture2DArray(d,t,n,o,l,c),this._bindTextureDirectly(u,d,!0);const _=this._getSamplingParameters(h,a);return this._gl.texParameteri(u,this._gl.TEXTURE_MAG_FILTER,_.mag),this._gl.texParameteri(u,this._gl.TEXTURE_MIN_FILTER,_.min),a&&this._gl.generateMipmap(u),this._bindTextureDirectly(u,null),this._internalTexturesCache.push(d),d}}function Oa(e){return function(t,s,i,r,n=null,a=Ze.TEXTURETYPE_UNSIGNED_INT){const o=e?this._gl.TEXTURE_3D:this._gl.TEXTURE_2D_ARRAY,h=this._getWebGLTextureType(a),l=this._getInternalFormat(i),c=this._getRGBABufferInternalSizedFormat(a,i);this._bindTextureDirectly(o,t,!0),this._unpackFlipY(void 0===r||!!r),this._doNotHandleContextLost||(t._bufferView=s,t.format=i,t.invertY=r,t._compression=n),t.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),n&&s?this._gl.compressedTexImage3D(o,0,this.getCaps().s3tc[n],t.width,t.height,t.depth,0,s):this._gl.texImage3D(o,0,c,t.width,t.height,t.depth,0,l,h,s),t.generateMipMaps&&this._gl.generateMipmap(o),this._bindTextureDirectly(o,null),t.isReady=!0}}Ds.prototype.updateRawTexture=function(e,t,s,i,r=null,n=Ze.TEXTURETYPE_UNSIGNED_INT,a=!1){if(!e)return;const o=this._getRGBABufferInternalSizedFormat(n,s,a),h=this._getInternalFormat(s),l=this._getWebGLTextureType(n);this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),this._unpackFlipY(void 0===i||!!i),this._doNotHandleContextLost||(e._bufferView=t,e.format=s,e.type=n,e.invertY=i,e._compression=r),e.width%4!=0&&this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT,1),r&&t?this._gl.compressedTexImage2D(this._gl.TEXTURE_2D,0,this.getCaps().s3tc[r],e.width,e.height,0,t):this._gl.texImage2D(this._gl.TEXTURE_2D,0,o,e.width,e.height,0,h,l,t),e.generateMipMaps&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),e.isReady=!0},Ds.prototype.createRawTexture=function(e,t,s,i,r,n,a,o=null,h=Ze.TEXTURETYPE_UNSIGNED_INT,l=0,c=!1){const u=new Tt(this,3);u.baseWidth=t,u.baseHeight=s,u.width=t,u.height=s,u.format=i,u.generateMipMaps=r,u.samplingMode=a,u.invertY=n,u._compression=o,u.type=h,u._useSRGBBuffer=this._getUseSRGBBuffer(c,!r),this._doNotHandleContextLost||(u._bufferView=e),this.updateRawTexture(u,e,i,n,o,h,u._useSRGBBuffer),this._bindTextureDirectly(this._gl.TEXTURE_2D,u,!0);const d=this._getSamplingParameters(a,r);return this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,d.mag),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,d.min),r&&this._gl.generateMipmap(this._gl.TEXTURE_2D),this._bindTextureDirectly(this._gl.TEXTURE_2D,null),this._internalTexturesCache.push(u),u},Ds.prototype.createRawCubeTexture=function(e,t,s,i,r,n,a,o=null){const h=this._gl,l=new Tt(this,8);l.isCube=!0,l.format=s,l.type=i,this._doNotHandleContextLost||(l._bufferViewArray=e);const c=this._getWebGLTextureType(i);let u=this._getInternalFormat(s);u===h.RGB&&(u=h.RGBA),c!==h.FLOAT||this._caps.textureFloatLinearFiltering?c!==this._gl.HALF_FLOAT_OES||this._caps.textureHalfFloatLinearFiltering?c!==h.FLOAT||this._caps.textureFloatRender?c!==h.HALF_FLOAT||this._caps.colorBufferFloat||(r=!1,ue.Warn("Render to half float textures is not supported. Mipmap generation forced to false.")):(r=!1,ue.Warn("Render to float textures is not supported. Mipmap generation forced to false.")):(r=!1,a=Ze.TEXTURE_NEAREST_SAMPLINGMODE,ue.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.")):(r=!1,a=Ze.TEXTURE_NEAREST_SAMPLINGMODE,ue.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively."));const d=t,_=d;l.width=d,l.height=_,l.invertY=n,l._compression=o;if(!this.needPOTTextures||Gt(l.width)&&Gt(l.height)||(r=!1),e)this.updateRawCubeTexture(l,e,s,i,n,o);else{const e=this._getRGBABufferInternalSizedFormat(i),t=0;this._bindTextureDirectly(h.TEXTURE_CUBE_MAP,l,!0);for(let s=0;s<6;s++)o?h.compressedTexImage2D(h.TEXTURE_CUBE_MAP_POSITIVE_X+s,t,this.getCaps().s3tc[o],l.width,l.height,0,void 0):h.texImage2D(h.TEXTURE_CUBE_MAP_POSITIVE_X+s,t,e,l.width,l.height,0,u,c,null);this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)}this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,l,!0),e&&r&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);const f=this._getSamplingParameters(a,r);return h.texParameteri(h.TEXTURE_CUBE_MAP,h.TEXTURE_MAG_FILTER,f.mag),h.texParameteri(h.TEXTURE_CUBE_MAP,h.TEXTURE_MIN_FILTER,f.min),h.texParameteri(h.TEXTURE_CUBE_MAP,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_CUBE_MAP,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),this._bindTextureDirectly(h.TEXTURE_CUBE_MAP,null),l.generateMipMaps=r,l.samplingMode=a,l.isReady=!0,l},Ds.prototype.updateRawCubeTexture=function(e,t,s,i,r,n=null,a=0){e._bufferViewArray=t,e.format=s,e.type=i,e.invertY=r,e._compression=n;const o=this._gl,h=this._getWebGLTextureType(i);let l=this._getInternalFormat(s);const c=this._getRGBABufferInternalSizedFormat(i);let u=!1;l===o.RGB&&(l=o.RGBA,u=!0),this._bindTextureDirectly(o.TEXTURE_CUBE_MAP,e,!0),this._unpackFlipY(void 0===r||!!r),e.width%4!=0&&o.pixelStorei(o.UNPACK_ALIGNMENT,1);for(let s=0;s<6;s++){let r=t[s];n?o.compressedTexImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+s,a,this.getCaps().s3tc[n],e.width,e.height,0,r):(u&&(r=Ca(r,e.width,e.height,i)),o.texImage2D(o.TEXTURE_CUBE_MAP_POSITIVE_X+s,a,c,e.width,e.height,0,l,h,r))}(!this.needPOTTextures||Gt(e.width)&&Gt(e.height))&&e.generateMipMaps&&0===a&&this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null),e.isReady=!0},Ds.prototype.createRawCubeTextureFromUrl=function(e,t,s,i,r,n,a,o,h=null,l=null,c=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,u=!1){const d=this._gl,_=this.createRawCubeTexture(null,s,i,r,!n,u,c,null);t?.addPendingData(_),_.url=e,_.isReady=!1,this._internalTexturesCache.push(_);const f=e=>{const s=_.width,n=a(e);if(n){if(o){const e=this._getWebGLTextureType(r);let t=this._getInternalFormat(i);const a=this._getRGBABufferInternalSizedFormat(r);let h=!1;t===d.RGB&&(t=d.RGBA,h=!0),this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,_,!0),this._unpackFlipY(!1);const l=o(n);for(let i=0;i<l.length;i++){const n=s>>i;for(let s=0;s<6;s++){let o=l[i][s];h&&(o=Ca(o,n,n,r)),d.texImage2D(s,i,a,n,n,0,t,e,o)}}this._bindTextureDirectly(d.TEXTURE_CUBE_MAP,null)}else this.updateRawCubeTexture(_,n,i,r,u);_.isReady=!0,t?.removePendingData(_),_.onLoadedObservable.notifyObservers(_),_.onLoadedObservable.clear(),h&&h()}};return this._loadFile(e,(e=>{f(e)}),void 0,t?.offlineProvider,!0,((e,s)=>{t?.removePendingData(_),l&&e&&l(e.status+" "+e.statusText,s)})),_},Ds.prototype.createRawTexture2DArray=Pa(!1),Ds.prototype.createRawTexture3D=Pa(!0),Ds.prototype.updateRawTexture2DArray=Oa(!1),Ds.prototype.updateRawTexture3D=Oa(!0);class Da extends Dr{constructor(e,t,s,i,r,n=!0,a=!1,o=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,h=Ze.TEXTURETYPE_UNSIGNED_INT,l,c){super(null,r,!n,a,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0,l),this.format=i,this._engine&&(this._engine._caps.textureFloatLinearFiltering||h!==Ze.TEXTURETYPE_FLOAT||(o=Ze.TEXTURE_NEAREST_SAMPLINGMODE),this._engine._caps.textureHalfFloatLinearFiltering||h!==Ze.TEXTURETYPE_HALF_FLOAT||(o=Ze.TEXTURE_NEAREST_SAMPLINGMODE),this._texture=this._engine.createRawTexture(e,t,s,i,n,a,o,null,h,l??0,c??!1),this.wrapU=Dr.CLAMP_ADDRESSMODE,this.wrapV=Dr.CLAMP_ADDRESSMODE)}update(e){this._getEngine().updateRawTexture(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type,this._texture._useSRGBBuffer)}clone(){if(!this._texture)return super.clone();const e=new Da(null,this.getSize().width,this.getSize().height,this.format,this.getScene(),this._texture.generateMipMaps,this._invertY,this.samplingMode,this._texture.type,this._texture._creationFlags,this._useSRGBBuffer);return e._texture=this._texture,this._texture.incrementReferences(),e}static CreateLuminanceTexture(e,t,s,i,r=!0,n=!1,a=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE){return new Da(e,t,s,Ze.TEXTUREFORMAT_LUMINANCE,i,r,n,a)}static CreateLuminanceAlphaTexture(e,t,s,i,r=!0,n=!1,a=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE){return new Da(e,t,s,Ze.TEXTUREFORMAT_LUMINANCE_ALPHA,i,r,n,a)}static CreateAlphaTexture(e,t,s,i,r=!0,n=!1,a=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE){return new Da(e,t,s,Ze.TEXTUREFORMAT_ALPHA,i,r,n,a)}static CreateRGBTexture(e,t,s,i,r=!0,n=!1,a=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,o=Ze.TEXTURETYPE_UNSIGNED_INT,h=0,l=!1){return new Da(e,t,s,Ze.TEXTUREFORMAT_RGB,i,r,n,a,o,h,l)}static CreateRGBATexture(e,t,s,i,r=!0,n=!1,a=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,o=Ze.TEXTURETYPE_UNSIGNED_INT,h=0,l=!1){return new Da(e,t,s,Ze.TEXTUREFORMAT_RGBA,i,r,n,a,o,h,l)}static CreateRGBAStorageTexture(e,t,s,i,r=!0,n=!1,a=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,o=Ze.TEXTURETYPE_UNSIGNED_INT,h=!1){return new Da(e,t,s,Ze.TEXTUREFORMAT_RGBA,i,r,n,a,o,Ze.TEXTURE_CREATIONFLAG_STORAGE,h)}static CreateRTexture(e,t,s,i,r=!0,n=!1,a=Dr.TRILINEAR_SAMPLINGMODE,o=Ze.TEXTURETYPE_FLOAT){return new Da(e,t,s,Ze.TEXTUREFORMAT_R,i,r,n,a,o)}static CreateRStorageTexture(e,t,s,i,r=!0,n=!1,a=Dr.TRILINEAR_SAMPLINGMODE,o=Ze.TEXTURETYPE_FLOAT){return new Da(e,t,s,Ze.TEXTUREFORMAT_R,i,r,n,a,o,Ze.TEXTURE_CREATIONFLAG_STORAGE)}}class La{get useTextureToStoreBoneMatrices(){return this._useTextureToStoreBoneMatrices}set useTextureToStoreBoneMatrices(e){this._useTextureToStoreBoneMatrices=e,this._markAsDirty()}get animationPropertiesOverride(){return this._animationPropertiesOverride?this._animationPropertiesOverride:this._scene.animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}get isUsingTextureForMatrices(){return this.useTextureToStoreBoneMatrices&&this._canUseTextureForBones}get uniqueId(){return this._uniqueId}constructor(e,t,s){this.name=e,this.id=t,this.bones=[],this.needInitialSkinMatrix=!1,this._isDirty=!0,this._meshesWithPoseMatrix=new Array,this._identity=V.Identity(),this._currentRenderId=-1,this._ranges={},this._absoluteTransformIsDirty=!0,this._canUseTextureForBones=!1,this._uniqueId=0,this._numBonesWithLinkedTransformNode=0,this._hasWaitingData=null,this._parentContainer=null,this.doNotSerialize=!1,this._useTextureToStoreBoneMatrices=!0,this._animationPropertiesOverride=null,this.onBeforeComputeObservable=new g,this.bones=[],this._scene=s||C.LastCreatedScene,this._uniqueId=this._scene.getUniqueId(),this._scene.addSkeleton(this),this._isDirty=!0;const i=this._scene.getEngine().getCaps();this._canUseTextureForBones=i.textureFloat&&i.maxVertexTextureImageUnits>0}getClassName(){return"Skeleton"}getChildren(){return this.bones.filter((e=>!e.getParent()))}getTransformMatrices(e){if(this.needInitialSkinMatrix){if(!e)throw new Error("getTransformMatrices: When using the needInitialSkinMatrix flag, a mesh must be provided");return e._bonesTransformMatrices||this.prepare(!0),e._bonesTransformMatrices}return this._transformMatrices&&!this._isDirty||this.prepare(!this._transformMatrices),this._transformMatrices}getTransformMatrixTexture(e){return this.needInitialSkinMatrix&&e._transformMatrixTexture?e._transformMatrixTexture:this._transformMatrixTexture}getScene(){return this._scene}toString(e){let t=`Name: ${this.name}, nBones: ${this.bones.length}`;if(t+=`, nAnimationRanges: ${this._ranges?Object.keys(this._ranges).length:"none"}`,e){t+=", Ranges: {";let e=!0;for(const s in this._ranges)e&&(t+=", ",e=!1),t+=s;t+="}"}return t}getBoneIndexByName(e){for(let t=0,s=this.bones.length;t<s;t++)if(this.bones[t].name===e)return t;return-1}createAnimationRange(e,t,s){if(!this._ranges[e]){this._ranges[e]=new pi(e,t,s);for(let i=0,r=this.bones.length;i<r;i++)this.bones[i].animations[0]&&this.bones[i].animations[0].createRange(e,t,s)}}deleteAnimationRange(e,t=!0){for(let s=0,i=this.bones.length;s<i;s++)this.bones[s].animations[0]&&this.bones[s].animations[0].deleteRange(e,t);this._ranges[e]=null}getAnimationRange(e){return this._ranges[e]||null}getAnimationRanges(){const e=[];let t;for(t in this._ranges)e.push(this._ranges[t]);return e}copyAnimationRange(e,t,s=!1){if(this._ranges[t]||!e.getAnimationRange(t))return!1;let i=!0;const r=this._getHighestAnimationFrame()+1,n={},a=e.bones;let o,h;for(h=0,o=a.length;h<o;h++)n[a[h].name]=a[h];this.bones.length!==a.length&&(ue.Warn(`copyAnimationRange: this rig has ${this.bones.length} bones, while source as ${a.length}`),i=!1);const l=s&&this.dimensionsAtRest&&e.dimensionsAtRest?this.dimensionsAtRest.divide(e.dimensionsAtRest):null;for(h=0,o=this.bones.length;h<o;h++){const e=this.bones[h].name,a=n[e];a?i=i&&this.bones[h].copyAnimationRange(a,t,r,s,l):(ue.Warn("copyAnimationRange: not same rig, missing source bone "+e),i=!1)}const c=e.getAnimationRange(t);return c&&(this._ranges[t]=new pi(t,c.from+r,c.to+r)),i}returnToRest(){for(const e of this.bones)-1!==e._index&&e.returnToRest()}_getHighestAnimationFrame(){let e=0;for(let t=0,s=this.bones.length;t<s;t++)if(this.bones[t].animations[0]){const s=this.bones[t].animations[0].getHighestFrame();e<s&&(e=s)}return e}beginAnimation(e,t,s,i){const r=this.getAnimationRange(e);return r?this._scene.beginAnimation(this,r.from,r.to,t,s,i):null}static MakeAnimationAdditive(e,t=0,s){const i=e.getAnimationRange(s);if(!i)return null;const r=e._scene.getAllAnimatablesByTarget(e);let n=null;for(let e=0;e<r.length;e++){const t=r[e];if(t.fromFrame===i?.from&&t.toFrame===i?.to){n=t;break}}const a=e.getAnimatables();for(let e=0;e<a.length;e++){const i=a[e].animations;if(i)for(let e=0;e<i.length;e++)xi.MakeAnimationAdditive(i[e],t,s)}return n&&(n.isAdditive=!0),e}_markAsDirty(){this._isDirty=!0,this._absoluteTransformIsDirty=!0}_registerMeshWithPoseMatrix(e){this._meshesWithPoseMatrix.push(e)}_unregisterMeshWithPoseMatrix(e){const t=this._meshesWithPoseMatrix.indexOf(e);t>-1&&this._meshesWithPoseMatrix.splice(t,1)}_computeTransformMatrices(e,t){this.onBeforeComputeObservable.notifyObservers(this);for(let s=0;s<this.bones.length;s++){const i=this.bones[s];i._childUpdateId++;const r=i.getParent();if(r?i.getLocalMatrix().multiplyToRef(r.getFinalMatrix(),i.getFinalMatrix()):t?i.getLocalMatrix().multiplyToRef(t,i.getFinalMatrix()):i.getFinalMatrix().copyFrom(i.getLocalMatrix()),-1!==i._index){const t=null===i._index?s:i._index;i.getAbsoluteInverseBindMatrix().multiplyToArray(i.getFinalMatrix(),e,16*t)}}this._identity.copyToArray(e,16*this.bones.length)}prepare(e=!1){if(!e){const e=this.getScene().getRenderId();if(this._currentRenderId===e)return;this._currentRenderId=e}if(this._numBonesWithLinkedTransformNode>0)for(const e of this.bones)if(e._linkedTransformNode){const t=e._linkedTransformNode;e.position=t.position,t.rotationQuaternion?e.rotationQuaternion=t.rotationQuaternion:e.rotation=t.rotation,e.scaling=t.scaling}if(this.needInitialSkinMatrix)for(const e of this._meshesWithPoseMatrix){const t=e.getPoseMatrix();let s=this._isDirty;if(e._bonesTransformMatrices&&e._bonesTransformMatrices.length===16*(this.bones.length+1)||(e._bonesTransformMatrices=new Float32Array(16*(this.bones.length+1)),s=!0),s){if(this._synchronizedWithMesh!==e){this._synchronizedWithMesh=e;for(const e of this.bones)if(!e.getParent()){e.getBindMatrix().multiplyToRef(t,z.Matrix[1]),e._updateAbsoluteBindMatrices(z.Matrix[1])}if(this.isUsingTextureForMatrices){const t=4*(this.bones.length+1);e._transformMatrixTexture&&e._transformMatrixTexture.getSize().width===t||(e._transformMatrixTexture&&e._transformMatrixTexture.dispose(),e._transformMatrixTexture=Da.CreateRGBATexture(e._bonesTransformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,Ze.TEXTURE_NEAREST_SAMPLINGMODE,Ze.TEXTURETYPE_FLOAT))}}this._computeTransformMatrices(e._bonesTransformMatrices,t),this.isUsingTextureForMatrices&&e._transformMatrixTexture&&e._transformMatrixTexture.update(e._bonesTransformMatrices)}}else{if(!this._isDirty)return;this._transformMatrices&&this._transformMatrices.length===16*(this.bones.length+1)||(this._transformMatrices=new Float32Array(16*(this.bones.length+1)),this.isUsingTextureForMatrices&&(this._transformMatrixTexture&&this._transformMatrixTexture.dispose(),this._transformMatrixTexture=Da.CreateRGBATexture(this._transformMatrices,4*(this.bones.length+1),1,this._scene,!1,!1,Ze.TEXTURE_NEAREST_SAMPLINGMODE,Ze.TEXTURETYPE_FLOAT))),this._computeTransformMatrices(this._transformMatrices,null),this.isUsingTextureForMatrices&&this._transformMatrixTexture&&this._transformMatrixTexture.update(this._transformMatrices)}this._isDirty=!1}getAnimatables(){if(!this._animatables||this._animatables.length!==this.bones.length){this._animatables=[];for(let e=0;e<this.bones.length;e++)this._animatables.push(this.bones[e])}return this._animatables}clone(e,t){const s=new La(e,t||e,this._scene);s.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let e=0;e<this.bones.length;e++){const t=this.bones[e];let i=null;const r=t.getParent();if(r){const e=this.bones.indexOf(r);i=s.bones[e]}const n=new ha(t.name,s,i,t.getBindMatrix().clone(),t.getRestMatrix().clone());n._index=t._index,t._linkedTransformNode&&n.linkTransformNode(t._linkedTransformNode),_e.DeepCopy(t.animations,n.animations)}if(this._ranges){s._ranges={};for(const e in this._ranges){const t=this._ranges[e];t&&(s._ranges[e]=t.clone())}}return this._isDirty=!0,s.prepare(!0),s}enableBlending(e=.01){this.bones.forEach((t=>{t.animations.forEach((t=>{t.enableBlending=!0,t.blendingSpeed=e}))}))}dispose(){if(this._meshesWithPoseMatrix.length=0,this.getScene().stopAnimation(this),this.getScene().removeSkeleton(this),this._parentContainer){const e=this._parentContainer.skeletons.indexOf(this);e>-1&&this._parentContainer.skeletons.splice(e,1),this._parentContainer=null}this._transformMatrixTexture&&(this._transformMatrixTexture.dispose(),this._transformMatrixTexture=null)}serialize(){const e={};e.name=this.name,e.id=this.id,this.dimensionsAtRest&&(e.dimensionsAtRest=this.dimensionsAtRest.asArray()),e.bones=[],e.needInitialSkinMatrix=this.needInitialSkinMatrix;for(let t=0;t<this.bones.length;t++){const s=this.bones[t],i=s.getParent(),r={parentBoneIndex:i?this.bones.indexOf(i):-1,index:s.getIndex(),name:s.name,id:s.id,matrix:s.getBindMatrix().asArray(),rest:s.getRestMatrix().asArray(),linkedTransformNodeId:s.getTransformNode()?.id};e.bones.push(r),s.length&&(r.length=s.length),s.metadata&&(r.metadata=s.metadata),s.animations&&s.animations.length>0&&(r.animation=s.animations[0].serialize()),e.ranges=[];for(const t in this._ranges){const s=this._ranges[t];if(!s)continue;const i={};i.name=t,i.from=s.from,i.to=s.to,e.ranges.push(i)}}return e}static Parse(e,t){const s=new La(e.name,e.id,t);let i;for(e.dimensionsAtRest&&(s.dimensionsAtRest=U.FromArray(e.dimensionsAtRest)),s.needInitialSkinMatrix=e.needInitialSkinMatrix,i=0;i<e.bones.length;i++){const t=e.bones[i],r=e.bones[i].index;let n=null;t.parentBoneIndex>-1&&(n=s.bones[t.parentBoneIndex]);const a=t.rest?V.FromArray(t.rest):null,o=new ha(t.name,s,n,V.FromArray(t.matrix),a,null,r);void 0!==t.id&&null!==t.id&&(o.id=t.id),t.length&&(o.length=t.length),t.metadata&&(o.metadata=t.metadata),t.animation&&o.animations.push(xi.Parse(t.animation)),void 0!==t.linkedTransformNodeId&&null!==t.linkedTransformNodeId&&(s._hasWaitingData=!0,o._waitingTransformNodeId=t.linkedTransformNodeId)}if(e.ranges)for(i=0;i<e.ranges.length;i++){const t=e.ranges[i];s.createAnimationRange(t.name,t.from,t.to)}return s}computeAbsoluteMatrices(e=!1){(this._absoluteTransformIsDirty||e)&&(this.bones[0].computeAbsoluteMatrices(),this._absoluteTransformIsDirty=!1)}computeAbsoluteTransforms(e=!1){this.computeAbsoluteMatrices(e)}getPoseMatrix(){let e=null;return this._meshesWithPoseMatrix.length>0&&(e=this._meshesWithPoseMatrix[0].getPoseMatrix()),e}sortBones(){const e=[],t=new Array(this.bones.length);for(let s=0;s<this.bones.length;s++)this._sortBones(s,e,t);this.bones=e}_sortBones(e,t,s){if(s[e])return;s[e]=!0;const i=this.bones[e];if(!i)return;void 0===i._index&&(i._index=e);const r=i.getParent();r&&this._sortBones(this.bones.indexOf(r),t,s),t.push(i)}setCurrentPoseAsRest(){this.bones.forEach((e=>{e.setCurrentPoseAsRest()}))}}class Fa{get influence(){return this._influence}set influence(e){if(this._influence===e)return;const t=this._influence;this._influence=e,this.onInfluenceChanged.hasObservers()&&this.onInfluenceChanged.notifyObservers(0===t||0===e)}get animationPropertiesOverride(){return!this._animationPropertiesOverride&&this._scene?this._scene.animationPropertiesOverride:this._animationPropertiesOverride}set animationPropertiesOverride(e){this._animationPropertiesOverride=e}constructor(e,t=0,s=null){this.name=e,this.animations=[],this._positions=null,this._normals=null,this._tangents=null,this._uvs=null,this._uniqueId=0,this.onInfluenceChanged=new g,this._onDataLayoutChanged=new g,this._animationPropertiesOverride=null,this._scene=s||C.LastCreatedScene,this.influence=t,this._scene&&(this._uniqueId=this._scene.getUniqueId())}get uniqueId(){return this._uniqueId}get hasPositions(){return!!this._positions}get hasNormals(){return!!this._normals}get hasTangents(){return!!this._tangents}get hasUVs(){return!!this._uvs}setPositions(e){const t=this.hasPositions;this._positions=e,t!==this.hasPositions&&this._onDataLayoutChanged.notifyObservers(void 0)}getPositions(){return this._positions}setNormals(e){const t=this.hasNormals;this._normals=e,t!==this.hasNormals&&this._onDataLayoutChanged.notifyObservers(void 0)}getNormals(){return this._normals}setTangents(e){const t=this.hasTangents;this._tangents=e,t!==this.hasTangents&&this._onDataLayoutChanged.notifyObservers(void 0)}getTangents(){return this._tangents}setUVs(e){const t=this.hasUVs;this._uvs=e,t!==this.hasUVs&&this._onDataLayoutChanged.notifyObservers(void 0)}getUVs(){return this._uvs}clone(){const e=re.Clone((()=>new Fa(this.name,this.influence,this._scene)),this);return e._positions=this._positions,e._normals=this._normals,e._tangents=this._tangents,e._uvs=this._uvs,e}serialize(){const e={};return e.name=this.name,e.influence=this.influence,e.positions=Array.prototype.slice.call(this.getPositions()),null!=this.id&&(e.id=this.id),this.hasNormals&&(e.normals=Array.prototype.slice.call(this.getNormals())),this.hasTangents&&(e.tangents=Array.prototype.slice.call(this.getTangents())),this.hasUVs&&(e.uvs=Array.prototype.slice.call(this.getUVs())),re.AppendSerializedAnimations(this,e),e}getClassName(){return"MorphTarget"}static Parse(e,t){const s=new Fa(e.name,e.influence);if(s.setPositions(e.positions),null!=e.id&&(s.id=e.id),e.normals&&s.setNormals(e.normals),e.tangents&&s.setTangents(e.tangents),e.uvs&&s.setUVs(e.uvs),e.animations){for(let t=0;t<e.animations.length;t++){const i=e.animations[t],r=S("BABYLON.Animation");r&&s.animations.push(r.Parse(i))}e.autoAnimate&&t&&t.beginAnimation(s,e.autoAnimateFrom,e.autoAnimateTo,e.autoAnimateLoop,e.autoAnimateSpeed||1)}return s}static FromMesh(e,t,s){t||(t=e.name);const i=new Fa(t,s,e.getScene());return i.setPositions(e.getVerticesData(ns.PositionKind)),e.isVerticesDataPresent(ns.NormalKind)&&i.setNormals(e.getVerticesData(ns.NormalKind)),e.isVerticesDataPresent(ns.TangentKind)&&i.setTangents(e.getVerticesData(ns.TangentKind)),e.isVerticesDataPresent(ns.UVKind)&&i.setUVs(e.getVerticesData(ns.UVKind)),i}}e([a()],Fa.prototype,"id",void 0);class Na extends Dr{get depth(){return this._depth}constructor(e,t,s,i,r,n,a=!0,o=!1,h=Dr.TRILINEAR_SAMPLINGMODE,l=Ze.TEXTURETYPE_UNSIGNED_INT,c){super(null,n,!a,o),this.format=r,this._texture=n.getEngine().createRawTexture2DArray(e,t,s,i,r,a,o,h,null,l,c),this._depth=i,this.is2DArray=!0}update(e){this._texture&&this._getEngine().updateRawTexture2DArray(this._texture,e,this._texture.format,this._texture.invertY,null,this._texture.type)}static CreateRGBATexture(e,t,s,i,r,n=!0,a=!1,o=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,h=Ze.TEXTURETYPE_UNSIGNED_INT){return new Na(e,t,s,i,Ze.TEXTUREFORMAT_RGBA,r,n,a,o,h)}}class wa{set areUpdatesFrozen(e){e?this._blockCounter++:(this._blockCounter--,this._blockCounter<=0&&(this._blockCounter=0,this._syncActiveTargets(!0)))}get areUpdatesFrozen(){return this._blockCounter>0}constructor(e=null){if(this._targets=new Array,this._targetInfluenceChangedObservers=new Array,this._targetDataLayoutChangedObservers=new Array,this._activeTargets=new Zt(16),this._supportsNormals=!1,this._supportsTangents=!1,this._supportsUVs=!1,this._vertexCount=0,this._uniqueId=0,this._tempInfluences=new Array,this._canUseTextureForTargets=!1,this._blockCounter=0,this._textureVertexStride=0,this._textureWidth=0,this._textureHeight=1,this._parentContainer=null,this.optimizeInfluencers=!0,this.enableNormalMorphing=!0,this.enableTangentMorphing=!0,this.enableUVMorphing=!0,this._numMaxInfluencers=0,this._useTextureToStoreTargets=!0,e||(e=C.LastCreatedScene),this._scene=e,this._scene){this._scene.addMorphTargetManager(this),this._uniqueId=this._scene.getUniqueId();const e=this._scene.getEngine().getCaps();this._canUseTextureForTargets=e.canUseGLVertexID&&e.textureFloat&&e.maxVertexTextureImageUnits>0&&e.texture2DArrayMaxLayerCount>1}}get numMaxInfluencers(){return this._numMaxInfluencers}set numMaxInfluencers(e){this._numMaxInfluencers!==e&&(this._numMaxInfluencers=e,this._syncActiveTargets(!0))}get uniqueId(){return this._uniqueId}get vertexCount(){return this._vertexCount}get supportsNormals(){return this._supportsNormals&&this.enableNormalMorphing}get supportsTangents(){return this._supportsTangents&&this.enableTangentMorphing}get supportsUVs(){return this._supportsUVs&&this.enableUVMorphing}get numTargets(){return this._targets.length}get numInfluencers(){return this._activeTargets.length}get influences(){return this._influences}get useTextureToStoreTargets(){return this._useTextureToStoreTargets}set useTextureToStoreTargets(e){this._useTextureToStoreTargets=e}get isUsingTextureForTargets(){return wa.EnableTextureStorage&&this.useTextureToStoreTargets&&this._canUseTextureForTargets&&!this._scene?.getEngine().getCaps().disableMorphTargetTexture}getActiveTarget(e){return this._activeTargets.data[e]}getTarget(e){return this._targets[e]}getTargetByName(e){for(const t of this._targets)if(t.name===e)return t;return null}addTarget(e){this._targets.push(e),this._targetInfluenceChangedObservers.push(e.onInfluenceChanged.add((e=>{this._syncActiveTargets(e)}))),this._targetDataLayoutChangedObservers.push(e._onDataLayoutChanged.add((()=>{this._syncActiveTargets(!0)}))),this._syncActiveTargets(!0)}removeTarget(e){const t=this._targets.indexOf(e);t>=0&&(this._targets.splice(t,1),e.onInfluenceChanged.remove(this._targetInfluenceChangedObservers.splice(t,1)[0]),e._onDataLayoutChanged.remove(this._targetDataLayoutChangedObservers.splice(t,1)[0]),this._syncActiveTargets(!0)),this._scene&&this._scene.stopAnimation(e)}_bind(e){e.setFloat3("morphTargetTextureInfo",this._textureVertexStride,this._textureWidth,this._textureHeight),e.setFloatArray("morphTargetTextureIndices",this._morphTargetTextureIndices),e.setTexture("morphTargets",this._targetStoreTexture),e.setInt("morphTargetCount",this.numInfluencers)}clone(){const e=new wa(this._scene);for(const t of this._targets)e.addTarget(t.clone());return e.enableNormalMorphing=this.enableNormalMorphing,e.enableTangentMorphing=this.enableTangentMorphing,e.enableUVMorphing=this.enableUVMorphing,e}serialize(){const e={};e.id=this.uniqueId,e.targets=[];for(const t of this._targets)e.targets.push(t.serialize());return e}_syncActiveTargets(e){if(this.areUpdatesFrozen)return;let t=0;this._activeTargets.reset(),this._supportsNormals=!0,this._supportsTangents=!0,this._supportsUVs=!0,this._vertexCount=0,this._scene&&this._targets.length>this._scene.getEngine().getCaps().texture2DArrayMaxLayerCount&&(this.useTextureToStoreTargets=!1),this._morphTargetTextureIndices&&this._morphTargetTextureIndices.length===this._targets.length||(this._morphTargetTextureIndices=new Float32Array(this._targets.length));let s=-1;for(const e of this._targets){if(s++,0===e.influence&&this.optimizeInfluencers)continue;if(this._activeTargets.length>=wa.MaxActiveMorphTargetsInVertexAttributeMode&&!this.isUsingTextureForTargets)break;this._activeTargets.push(e),this._morphTargetTextureIndices[t]=s,this._tempInfluences[t++]=e.influence,this._supportsNormals=this._supportsNormals&&e.hasNormals,this._supportsTangents=this._supportsTangents&&e.hasTangents,this._supportsUVs=this._supportsUVs&&e.hasUVs;const i=e.getPositions();if(i){const e=i.length/3;if(0===this._vertexCount)this._vertexCount=e;else if(this._vertexCount!==e)return void ue.Error("Incompatible target. Targets must all have the same vertices count.")}}this._morphTargetTextureIndices.length!==t&&(this._morphTargetTextureIndices=this._morphTargetTextureIndices.slice(0,t)),this._influences&&this._influences.length===t||(this._influences=new Float32Array(t));for(let e=0;e<t;e++)this._influences[e]=this._tempInfluences[e];e&&this.synchronize()}synchronize(){if(this._scene&&!this.areUpdatesFrozen){if(this.isUsingTextureForTargets&&(this._vertexCount||this.numMaxInfluencers>0)){this._textureVertexStride=1,this._supportsNormals&&this._textureVertexStride++,this._supportsTangents&&this._textureVertexStride++,this._supportsUVs&&this._textureVertexStride++,this._textureWidth=this._vertexCount*this._textureVertexStride||1,this._textureHeight=1;const e=this._scene.getEngine().getCaps().maxTextureSize;this._textureWidth>e&&(this._textureHeight=Math.ceil(this._textureWidth/e),this._textureWidth=e);let t=!0;if(this._targetStoreTexture){const e=this._targetStoreTexture.getSize();e.width===this._textureWidth&&e.height===this._textureHeight&&this._targetStoreTexture.depth===this._targets.length&&(t=!1)}if(t){this._targetStoreTexture&&this._targetStoreTexture.dispose();const e=this._targets.length,t=new Float32Array(e*this._textureWidth*this._textureHeight*4);let s=0;for(let i=0;i<e;i++){const e=this._targets[i],r=e.getPositions(),n=e.getNormals(),a=e.getUVs(),o=e.getTangents();if(!r)return void(0===i&&ue.Error("Invalid morph target. Target must have positions."));s=i*this._textureWidth*this._textureHeight*4;for(let e=0;e<this._vertexCount;e++)t[s]=r[3*e],t[s+1]=r[3*e+1],t[s+2]=r[3*e+2],s+=4,this._supportsNormals&&n&&(t[s]=n[3*e],t[s+1]=n[3*e+1],t[s+2]=n[3*e+2],s+=4),this._supportsUVs&&a&&(t[s]=a[2*e],t[s+1]=a[2*e+1],s+=4),this._supportsTangents&&o&&(t[s]=o[3*e],t[s+1]=o[3*e+1],t[s+2]=o[3*e+2],s+=4)}this._targetStoreTexture=Na.CreateRGBATexture(t,this._textureWidth,this._textureHeight,e,this._scene,!1,!1,Ze.TEXTURE_NEAREST_SAMPLINGMODE,Ze.TEXTURETYPE_FLOAT)}}for(const e of this._scene.meshes)e.morphTargetManager===this&&e._syncGeometryWithMorphTargetManager()}}dispose(){if(this._targetStoreTexture&&this._targetStoreTexture.dispose(),this._targetStoreTexture=null,this._scene){if(this._scene.removeMorphTargetManager(this),this._parentContainer){const e=this._parentContainer.morphTargetManagers.indexOf(this);e>-1&&this._parentContainer.morphTargetManagers.splice(e,1),this._parentContainer=null}for(const e of this._targets)this._scene.stopAnimation(e)}}static Parse(e,t){const s=new wa(t);s._uniqueId=e.id;for(const i of e.targets)s.addTarget(Fa.Parse(i,t));return s}}wa.EnableTextureStorage=!0,wa.MaxActiveMorphTargetsInVertexAttributeMode=8,oi._instancedMeshFactory=(e,t)=>{const s=new Ba(e,t);if(t.instancedBuffers){s.instancedBuffers={};for(const e in t.instancedBuffers)s.instancedBuffers[e]=t.instancedBuffers[e]}return s};class Ba extends Gs{constructor(e,t){super(e,t.getScene()),this._indexInSourceMeshInstanceArray=-1,this._distanceToCamera=0,t.addInstance(this),this._sourceMesh=t,this._unIndexed=t._unIndexed,this.position.copyFrom(t.position),this.rotation.copyFrom(t.rotation),this.scaling.copyFrom(t.scaling),t.rotationQuaternion&&(this.rotationQuaternion=t.rotationQuaternion.clone()),this.animations=t.animations.slice();for(const e of t.getAnimationRanges())null!=e&&this.createAnimationRange(e.name,e.from,e.to);this.infiniteDistance=t.infiniteDistance,this.setPivotMatrix(t.getPivotMatrix()),this.refreshBoundingInfo(!0,!0),this._syncSubMeshes()}getClassName(){return"InstancedMesh"}get lightSources(){return this._sourceMesh._lightSources}_resyncLightSources(){}_resyncLightSource(){}_removeLightSource(){}get receiveShadows(){return this._sourceMesh.receiveShadows}set receiveShadows(e){this._sourceMesh?.receiveShadows!==e&&Yt.Warn("Setting receiveShadows on an instanced mesh has no effect")}get material(){return this._sourceMesh.material}set material(e){this._sourceMesh?.material!==e&&Yt.Warn("Setting material on an instanced mesh has no effect")}get visibility(){return this._sourceMesh.visibility}set visibility(e){this._sourceMesh?.visibility!==e&&Yt.Warn("Setting visibility on an instanced mesh has no effect")}get skeleton(){return this._sourceMesh.skeleton}set skeleton(e){this._sourceMesh?.skeleton!==e&&Yt.Warn("Setting skeleton on an instanced mesh has no effect")}get renderingGroupId(){return this._sourceMesh.renderingGroupId}set renderingGroupId(e){this._sourceMesh&&e!==this._sourceMesh.renderingGroupId&&ue.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene")}getTotalVertices(){return this._sourceMesh?this._sourceMesh.getTotalVertices():0}getTotalIndices(){return this._sourceMesh.getTotalIndices()}get sourceMesh(){return this._sourceMesh}createInstance(e){return this._sourceMesh.createInstance(e)}isReady(e=!1){return this._sourceMesh.isReady(e,!0)}getVerticesData(e,t,s){return this._sourceMesh.getVerticesData(e,t,s)}copyVerticesData(e,t){this._sourceMesh.copyVerticesData(e,t)}setVerticesData(e,t,s,i){return this.sourceMesh&&this.sourceMesh.setVerticesData(e,t,s,i),this.sourceMesh}updateVerticesData(e,t,s,i){return this.sourceMesh&&this.sourceMesh.updateVerticesData(e,t,s,i),this.sourceMesh}setIndices(e,t=null){return this.sourceMesh&&this.sourceMesh.setIndices(e,t),this.sourceMesh}isVerticesDataPresent(e){return this._sourceMesh.isVerticesDataPresent(e)}getIndices(){return this._sourceMesh.getIndices()}get _positions(){return this._sourceMesh._positions}refreshBoundingInfo(e=!1,t=!1){if(this.hasBoundingInfo&&this.getBoundingInfo().isLocked)return this;let s;s="object"==typeof e?e:{applySkeleton:e,applyMorph:t};const i=this._sourceMesh.geometry?this._sourceMesh.geometry.boundingBias:null;return this._refreshBoundingInfo(this._sourceMesh._getData(s,null,ns.PositionKind),i),this}_preActivate(){return this._currentLOD&&this._currentLOD._preActivate(),this}_activate(e,t){if(super._activate(e,t),this._sourceMesh.subMeshes||ue.Warn("Instances should only be created for meshes with geometry."),this._currentLOD){if(this._currentLOD._getWorldMatrixDeterminant()>=0!=this._getWorldMatrixDeterminant()>=0)return this._internalAbstractMeshDataInfo._actAsRegularMesh=!0,!0;if(this._internalAbstractMeshDataInfo._actAsRegularMesh=!1,this._currentLOD._registerInstanceForRenderId(this,e),t){if(!this._currentLOD._internalAbstractMeshDataInfo._isActiveIntermediate)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstancesIntermediate=!0,!0}else if(!this._currentLOD._internalAbstractMeshDataInfo._isActive)return this._currentLOD._internalAbstractMeshDataInfo._onlyForInstances=!0,!0}return!1}_postActivate(){this._sourceMesh.edgesShareWithInstances&&this._sourceMesh._edgesRenderer&&this._sourceMesh._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup?(this._sourceMesh._renderingGroup._edgesRenderers.pushNoDuplicate(this._sourceMesh._edgesRenderer),this._sourceMesh._edgesRenderer.customInstances.push(this.getWorldMatrix())):this._edgesRenderer&&this._edgesRenderer.isEnabled&&this._sourceMesh._renderingGroup&&this._sourceMesh._renderingGroup._edgesRenderers.push(this._edgesRenderer)}getWorldMatrix(){if(this._currentLOD&&this._currentLOD.billboardMode!==Rs.BILLBOARDMODE_NONE&&this._currentLOD._masterMesh!==this){this._billboardWorldMatrix||(this._billboardWorldMatrix=new V);const e=this._currentLOD._masterMesh;return this._currentLOD._masterMesh=this,z.Vector3[7].copyFrom(this._currentLOD.position),this._currentLOD.position.set(0,0,0),this._billboardWorldMatrix.copyFrom(this._currentLOD.computeWorldMatrix(!0)),this._currentLOD.position.copyFrom(z.Vector3[7]),this._currentLOD._masterMesh=e,this._billboardWorldMatrix}return super.getWorldMatrix()}get isAnInstance(){return!0}getLOD(e){if(!e)return this;const t=this.sourceMesh.getLODLevels();if(t&&0!==t.length){const t=this.getBoundingInfo();this._currentLOD=this.sourceMesh.getLOD(e,t.boundingSphere)}else this._currentLOD=this.sourceMesh;return this._currentLOD}_preActivateForIntermediateRendering(e){return this.sourceMesh._preActivateForIntermediateRendering(e)}_syncSubMeshes(){if(this.releaseSubMeshes(),this._sourceMesh.subMeshes)for(let e=0;e<this._sourceMesh.subMeshes.length;e++)this._sourceMesh.subMeshes[e].clone(this,this._sourceMesh);return this}_generatePointsArray(){return this._sourceMesh._generatePointsArray()}_updateBoundingInfo(){return this.hasBoundingInfo?this.getBoundingInfo().update(this.worldMatrixFromCache):this.buildBoundingInfo(this.absolutePosition,this.absolutePosition,this.worldMatrixFromCache),this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache),this}clone(e,t=null,s,i){const r=(i||this._sourceMesh).createInstance(e);if(_e.DeepCopy(this,r,["name","subMeshes","uniqueId","parent","lightSources","receiveShadows","material","visibility","skeleton","sourceMesh","isAnInstance","facetNb","isFacetDataEnabled","isBlocked","useBones","hasInstances","collider","edgesRenderer","forward","up","right","absolutePosition","absoluteScaling","absoluteRotationQuaternion","isWorldMatrixFrozen","nonUniformScaling","behaviors","worldMatrixFromCache","hasThinInstances","hasBoundingInfo"],[]),this.refreshBoundingInfo(),t&&(r.parent=t),!s)for(let e=0;e<this.getScene().meshes.length;e++){const t=this.getScene().meshes[e];t.parent===this&&t.clone(t.name,r)}return r.computeWorldMatrix(!0),this.onClonedObservable.notifyObservers(r),r}dispose(e,t=!1){this._sourceMesh.removeInstance(this),super.dispose(e,t)}_serializeAsParent(e){super._serializeAsParent(e),e.parentId=this._sourceMesh.uniqueId,e.parentInstanceIndex=this._indexInSourceMeshInstanceArray}instantiateHierarchy(e=null,t,s){const i=this.clone("Clone of "+(this.name||this.id),e||this.parent,!0,t&&t.newSourcedMesh);i&&s&&s(this,i);for(const e of this.getChildTransformNodes(!0))e.instantiateHierarchy(i,t,s);return i}}oi.prototype.registerInstancedBuffer=function(e,t){if(this._userInstancedBuffersStorage?.vertexBuffers[e]?.dispose(),!this.instancedBuffers){this.instancedBuffers={};for(const e of this.instances)e.instancedBuffers={}}this._userInstancedBuffersStorage||(this._userInstancedBuffersStorage={data:{},vertexBuffers:{},strides:{},sizes:{},vertexArrayObjects:this.getEngine().getCaps().vertexArrayObject?{}:void 0}),this.instancedBuffers[e]=null,this._userInstancedBuffersStorage.strides[e]=t,this._userInstancedBuffersStorage.sizes[e]=32*t,this._userInstancedBuffersStorage.data[e]=new Float32Array(this._userInstancedBuffersStorage.sizes[e]),this._userInstancedBuffersStorage.vertexBuffers[e]=new ns(this.getEngine(),this._userInstancedBuffersStorage.data[e],e,!0,!1,t,!0);for(const t of this.instances)t.instancedBuffers[e]=null;this._invalidateInstanceVertexArrayObject(),this._markSubMeshesAsAttributesDirty()},oi.prototype._processInstancedBuffers=function(e,t){const s=e?e.length:0;for(const i in this.instancedBuffers){let r=this._userInstancedBuffersStorage.sizes[i];const n=this._userInstancedBuffersStorage.strides[i],a=(s+1)*n;for(;r<a;)r*=2;this._userInstancedBuffersStorage.data[i].length!=r&&(this._userInstancedBuffersStorage.data[i]=new Float32Array(r),this._userInstancedBuffersStorage.sizes[i]=r,this._userInstancedBuffersStorage.vertexBuffers[i]&&(this._userInstancedBuffersStorage.vertexBuffers[i].dispose(),this._userInstancedBuffersStorage.vertexBuffers[i]=null));const o=this._userInstancedBuffersStorage.data[i];let h=0;if(t){const e=this.instancedBuffers[i];e.toArray?e.toArray(o,h):e.copyToArray?e.copyToArray(o,h):o[h]=e,h+=n}for(let t=0;t<s;t++){const s=e[t].instancedBuffers[i];s.toArray?s.toArray(o,h):s.copyToArray?s.copyToArray(o,h):o[h]=s,h+=n}this._userInstancedBuffersStorage.vertexBuffers[i]?this._userInstancedBuffersStorage.vertexBuffers[i].updateDirectly(o,0):(this._userInstancedBuffersStorage.vertexBuffers[i]=new ns(this.getEngine(),this._userInstancedBuffersStorage.data[i],i,!0,!1,n,!0),this._invalidateInstanceVertexArrayObject())}},oi.prototype._invalidateInstanceVertexArrayObject=function(){if(this._userInstancedBuffersStorage&&void 0!==this._userInstancedBuffersStorage.vertexArrayObjects){for(const e in this._userInstancedBuffersStorage.vertexArrayObjects)this.getEngine().releaseVertexArrayObject(this._userInstancedBuffersStorage.vertexArrayObjects[e]);this._userInstancedBuffersStorage.vertexArrayObjects={}}},oi.prototype._disposeInstanceSpecificData=function(){for(this._instanceDataStorage.instancesBuffer&&(this._instanceDataStorage.instancesBuffer.dispose(),this._instanceDataStorage.instancesBuffer=null);this.instances.length;)this.instances[0].dispose();for(const e in this.instancedBuffers)this._userInstancedBuffersStorage.vertexBuffers[e]&&this._userInstancedBuffersStorage.vertexBuffers[e].dispose();this._invalidateInstanceVertexArrayObject(),this.instancedBuffers={}},I("BABYLON.InstancedMesh",Ba);class Ua extends Xi{}class ka{constructor(){this.rootNodes=[],this.skeletons=[],this.animationGroups=[]}dispose(){this.rootNodes.slice(0).forEach((e=>{e.dispose()})),this.rootNodes.length=0,this.skeletons.slice(0).forEach((e=>{e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((e=>{e.dispose()})),this.animationGroups.length=0}}class Ga extends Xi{constructor(e){super(),this._wasAddedToScene=!1,(e=e||C.LastCreatedScene)&&(this.scene=e,this.sounds=[],this.effectLayers=[],this.layers=[],this.lensFlareSystems=[],this.proceduralTextures=[],this.reflectionProbes=[],e.onDisposeObservable.add((()=>{this._wasAddedToScene||this.dispose()})),this._onContextRestoredObserver=e.getEngine().onContextRestoredObservable.add((()=>{for(const e of this.geometries)e._rebuild();for(const e of this.meshes)e._rebuild();for(const e of this.particleSystems)e.rebuild();for(const e of this.textures)e._rebuild()})))}_topologicalSort(e){const t=new Map;for(const s of e)t.set(s.uniqueId,s);const s={dependsOn:new Map,dependedBy:new Map};for(const t of e){const e=t.uniqueId;s.dependsOn.set(e,new Set),s.dependedBy.set(e,new Set)}for(const i of e){const e=i.uniqueId,r=s.dependsOn.get(e);if(i instanceof Ba){const n=i.sourceMesh;t.has(n.uniqueId)&&(r.add(n.uniqueId),s.dependedBy.get(n.uniqueId).add(e))}const n=s.dependedBy.get(e);for(const r of i.getDescendants()){const i=r.uniqueId;if(t.has(i)){n.add(i);s.dependsOn.get(i).add(e)}}}const i=[],r=[];for(const i of e){const e=i.uniqueId;0===s.dependsOn.get(e).size&&(r.push(i),t.delete(e))}const n=r;for(;n.length>0;){const e=n.shift();i.push(e);const r=s.dependedBy.get(e.uniqueId);for(const i of Array.from(r.values())){const r=s.dependsOn.get(i);r.delete(e.uniqueId),0===r.size&&t.get(i)&&(n.push(t.get(i)),t.delete(i))}}return t.size>0&&(ue.Error("SceneSerializer._topologicalSort: There were unvisited nodes:"),t.forEach((e=>ue.Error(e.name)))),i}_addNodeAndDescendantsToList(e,t,s,i){if(s&&(!i||i(s))&&!t.has(s.uniqueId)){e.push(s),t.add(s.uniqueId);for(const r of s.getDescendants(!0))this._addNodeAndDescendantsToList(e,t,r,i)}}_isNodeInContainer(e){return e instanceof Gs&&-1!==this.meshes.indexOf(e)||(e instanceof Rs&&-1!==this.transformNodes.indexOf(e)||(e instanceof Vi&&-1!==this.lights.indexOf(e)||e instanceof ss&&-1!==this.cameras.indexOf(e)))}_isValidHierarchy(){for(const e of this.meshes)if(e.parent&&!this._isNodeInContainer(e.parent))return ue.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.transformNodes)if(e.parent&&!this._isNodeInContainer(e.parent))return ue.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.lights)if(e.parent&&!this._isNodeInContainer(e.parent))return ue.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;for(const e of this.cameras)if(e.parent&&!this._isNodeInContainer(e.parent))return ue.Warn(`Node ${e.name} has a parent that is not in the container.`),!1;return!0}instantiateModelsToScene(e,t=!1,s){this._isValidHierarchy()||Yt.Warn("SceneSerializer.InstantiateModelsToScene: The Asset Container hierarchy is not valid.");const i={},r={},n=new ka,a=[],o=[],h={doNotInstantiate:!0,...s},l=[],c=new Set;for(const e of this.transformNodes)null===e.parent&&this._addNodeAndDescendantsToList(l,c,e,h.predicate);for(const e of this.meshes)null===e.parent&&this._addNodeAndDescendantsToList(l,c,e,h.predicate);const u=this._topologicalSort(l),d=(s,a)=>{if(((t,s)=>{if(i[t.uniqueId]=s.uniqueId,r[s.uniqueId]=s,e&&(s.name=e(t.name)),s instanceof oi){const e=s;if(e.morphTargetManager){const s=t.morphTargetManager;e.morphTargetManager=s.clone();for(let t=0;t<s.numTargets;t++){const n=s.getTarget(t),a=e.morphTargetManager.getTarget(t);i[n.uniqueId]=a.uniqueId,r[a.uniqueId]=a}}}})(s,a),s.parent){const e=i[s.parent.uniqueId],t=r[e];a.parent=t||s.parent}if(a.position&&s.position&&a.position.copyFrom(s.position),a.rotationQuaternion&&s.rotationQuaternion&&a.rotationQuaternion.copyFrom(s.rotationQuaternion),a.rotation&&s.rotation&&a.rotation.copyFrom(s.rotation),a.scaling&&s.scaling&&a.scaling.copyFrom(s.scaling),a.material){const n=a;if(n.material)if(t){const t=s.material;if(-1===o.indexOf(t)){let s=t.clone(e?e(t.name):"Clone of "+t.name);if(o.push(t),i[t.uniqueId]=s.uniqueId,r[s.uniqueId]=s,"MultiMaterial"===t.getClassName()){const n=t;for(const t of n.subMaterials)t&&(s=t.clone(e?e(t.name):"Clone of "+t.name),o.push(t),i[t.uniqueId]=s.uniqueId,r[s.uniqueId]=s);n.subMaterials=n.subMaterials.map((e=>e&&r[i[e.uniqueId]]))}}"InstancedMesh"!==n.getClassName()&&(n.material=r[i[t.uniqueId]])}else"MultiMaterial"===n.material.getClassName()?-1===this.scene.multiMaterials.indexOf(n.material)&&this.scene.addMultiMaterial(n.material):-1===this.scene.materials.indexOf(n.material)&&this.scene.addMaterial(n.material)}null===a.parent&&n.rootNodes.push(a)};return u.forEach((e=>{if("InstancedMesh"===e.getClassName()){const t=e,s=t.sourceMesh,n=i[s.uniqueId],a=("number"==typeof n?r[n]:s).createInstance(t.name);d(t,a)}else{let t=!0;"TransformNode"===e.getClassName()||"Node"===e.getClassName()||e.skeleton||!e.getTotalVertices||0===e.getTotalVertices()?t=!1:h.doNotInstantiate&&(t="function"==typeof h.doNotInstantiate?!h.doNotInstantiate(e):!h.doNotInstantiate);const s=t?e.createInstance(`instance of ${e.name}`):e.clone(`Clone of ${e.name}`,null,!0);if(!s)throw new Error(`Could not clone or instantiate node on Asset Container ${e.name}`);d(e,s)}})),this.skeletons.forEach((t=>{if(h.predicate&&!h.predicate(t))return;const s=t.clone(e?e(t.name):"Clone of "+t.name);for(const e of this.meshes)if(e.skeleton===t&&!e.isAnInstance){const t=r[i[e.uniqueId]];if(!t||t.isAnInstance)continue;if(t.skeleton=s,-1!==a.indexOf(s))continue;a.push(s);for(const e of s.bones)e._linkedTransformNode&&(e._linkedTransformNode=r[i[e._linkedTransformNode.uniqueId]])}n.skeletons.push(s)})),this.animationGroups.forEach((t=>{if(h.predicate&&!h.predicate(t))return;const s=t.clone(e?e(t.name):"Clone of "+t.name,(e=>r[i[e.uniqueId]]||e));n.animationGroups.push(s)})),n}addAllToScene(){if(!this._wasAddedToScene){this._isValidHierarchy()||Yt.Warn("SceneSerializer.addAllToScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!0,this.addToScene(null),this.environmentTexture&&(this.scene.environmentTexture=this.environmentTexture);for(const e of this.scene._serializableComponents)e.addFromContainer(this);this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null}}addToScene(e=null){const t=[];this.cameras.forEach((s=>{e&&!e(s)||(this.scene.addCamera(s),t.push(s))})),this.lights.forEach((s=>{e&&!e(s)||(this.scene.addLight(s),t.push(s))})),this.meshes.forEach((s=>{e&&!e(s)||(this.scene.addMesh(s),t.push(s))})),this.skeletons.forEach((t=>{e&&!e(t)||this.scene.addSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.addAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.addAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.addMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.addMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.addMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.addGeometry(t)})),this.transformNodes.forEach((s=>{e&&!e(s)||(this.scene.addTransformNode(s),t.push(s))})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.addActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.addTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.addReflectionProbe(t)}));for(const e of t)e.parent&&-1===this.scene.getNodes().indexOf(e.parent)&&(e.setParent?e.setParent(null):e.parent=null)}removeAllFromScene(){this._isValidHierarchy()||Yt.Warn("SceneSerializer.removeAllFromScene: The Asset Container hierarchy is not valid."),this._wasAddedToScene=!1,this.removeFromScene(null),this.environmentTexture===this.scene.environmentTexture&&(this.scene.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this)}removeFromScene(e=null){this.cameras.forEach((t=>{e&&!e(t)||this.scene.removeCamera(t)})),this.lights.forEach((t=>{e&&!e(t)||this.scene.removeLight(t)})),this.meshes.forEach((t=>{e&&!e(t)||this.scene.removeMesh(t,!0)})),this.skeletons.forEach((t=>{e&&!e(t)||this.scene.removeSkeleton(t)})),this.animations.forEach((t=>{e&&!e(t)||this.scene.removeAnimation(t)})),this.animationGroups.forEach((t=>{e&&!e(t)||this.scene.removeAnimationGroup(t)})),this.multiMaterials.forEach((t=>{e&&!e(t)||this.scene.removeMultiMaterial(t)})),this.materials.forEach((t=>{e&&!e(t)||this.scene.removeMaterial(t)})),this.morphTargetManagers.forEach((t=>{e&&!e(t)||this.scene.removeMorphTargetManager(t)})),this.geometries.forEach((t=>{e&&!e(t)||this.scene.removeGeometry(t)})),this.transformNodes.forEach((t=>{e&&!e(t)||this.scene.removeTransformNode(t)})),this.actionManagers.forEach((t=>{e&&!e(t)||this.scene.removeActionManager(t)})),this.textures.forEach((t=>{e&&!e(t)||this.scene.removeTexture(t)})),this.reflectionProbes.forEach((t=>{e&&!e(t)||this.scene.removeReflectionProbe(t)}))}dispose(){this.cameras.slice(0).forEach((e=>{e.dispose()})),this.cameras.length=0,this.lights.slice(0).forEach((e=>{e.dispose()})),this.lights.length=0,this.meshes.slice(0).forEach((e=>{e.dispose()})),this.meshes.length=0,this.skeletons.slice(0).forEach((e=>{e.dispose()})),this.skeletons.length=0,this.animationGroups.slice(0).forEach((e=>{e.dispose()})),this.animationGroups.length=0,this.multiMaterials.slice(0).forEach((e=>{e.dispose()})),this.multiMaterials.length=0,this.materials.slice(0).forEach((e=>{e.dispose()})),this.materials.length=0,this.geometries.slice(0).forEach((e=>{e.dispose()})),this.geometries.length=0,this.transformNodes.slice(0).forEach((e=>{e.dispose()})),this.transformNodes.length=0,this.actionManagers.slice(0).forEach((e=>{e.dispose()})),this.actionManagers.length=0,this.textures.slice(0).forEach((e=>{e.dispose()})),this.textures.length=0,this.reflectionProbes.slice(0).forEach((e=>{e.dispose()})),this.reflectionProbes.length=0,this.morphTargetManagers.slice(0).forEach((e=>{e.dispose()})),this.morphTargetManagers.length=0,this.environmentTexture&&(this.environmentTexture.dispose(),this.environmentTexture=null);for(const e of this.scene._serializableComponents)e.removeFromContainer(this,!0);this._onContextRestoredObserver&&(this.scene.getEngine().onContextRestoredObservable.remove(this._onContextRestoredObserver),this._onContextRestoredObserver=null)}_moveAssets(e,t,s){if(e&&t)for(const i of e){let e=!0;if(s)for(const t of s)if(i===t){e=!1;break}e&&(t.push(i),i._parentContainer=this)}}moveAllFromScene(e){this._wasAddedToScene=!1,void 0===e&&(e=new Ua);for(const t in this)Object.prototype.hasOwnProperty.call(this,t)&&(this[t]=this[t]||("_environmentTexture"===t?null:[]),this._moveAssets(this.scene[t],this[t],e[t]));this.environmentTexture=this.scene.environmentTexture,this.removeAllFromScene()}createRootMesh(){const e=new oi("assetContainerRootMesh",this.scene);return this.meshes.forEach((t=>{t.parent||e.addChild(t)})),this.meshes.unshift(e),e}mergeAnimationsTo(e=C.LastCreatedScene,t,s=null){if(!e)return ue.Error("No scene available to merge animations to"),[];const i=s||(t=>{let s=null;const i=t.animations.length?t.animations[0].targetProperty:"",r=t.name.split(".").join("").split("_primitive")[0];switch(i){case"position":case"rotationQuaternion":s=e.getTransformNodeByName(t.name)||e.getTransformNodeByName(r);break;case"influence":s=e.getMorphTargetByName(t.name)||e.getMorphTargetByName(r);break;default:s=e.getNodeByName(t.name)||e.getNodeByName(r)}return s});this.getNodes().forEach((e=>{const t=i(e);if(null!==t){for(const s of e.animations){const e=t.animations.filter((e=>e.targetProperty===s.targetProperty));for(const s of e){const e=t.animations.indexOf(s,0);e>-1&&t.animations.splice(e,1)}}t.animations=t.animations.concat(e.animations)}}));const r=[];return this.animationGroups.slice().forEach((e=>{r.push(e.clone(e.name,i)),e.animatables.forEach((e=>{e.stop()}))})),t.forEach((t=>{const s=i(t.target);s&&(e.beginAnimation(s,t.fromFrame,t.toFrame,t.loopAnimation,t.speedRatio,t.onAnimationEnd?t.onAnimationEnd:void 0,void 0,!0,void 0,t.onAnimationLoop?t.onAnimationLoop:void 0),e.stopAnimation(t.target))})),r}populateRootNodes(){this.rootNodes.length=0,this.meshes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.transformNodes.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.lights.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)})),this.cameras.forEach((e=>{e.parent||-1!==this.rootNodes.indexOf(e)||this.rootNodes.push(e)}))}addAllAssetsToContainer(e){if(!e)return;const t=[],s=new Set;for(t.push(e);t.length>0;){const e=t.pop();if(e instanceof oi?(e.geometry&&-1===this.geometries.indexOf(e.geometry)&&this.geometries.push(e.geometry),this.meshes.push(e)):e instanceof Rs?this.transformNodes.push(e):e instanceof Vi?this.lights.push(e):e instanceof ss&&this.cameras.push(e),e instanceof Gs){if(e.material&&-1===this.materials.indexOf(e.material)){this.materials.push(e.material);for(const t of e.material.getActiveTextures())-1===this.textures.indexOf(t)&&this.textures.push(t)}e.skeleton&&-1===this.skeletons.indexOf(e.skeleton)&&this.skeletons.push(e.skeleton),e.morphTargetManager&&-1===this.morphTargetManagers.indexOf(e.morphTargetManager)&&this.morphTargetManagers.push(e.morphTargetManager)}for(const i of e.getChildren())s.has(i)||t.push(i);s.add(e)}this.populateRootNodes()}}class Va{constructor(e){this.byteOffset=0,this.buffer=e}loadAsync(e){return this.buffer.readAsync(this.byteOffset,e).then((e=>{this._dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),this._dataByteOffset=0}))}readUint32(){const e=this._dataView.getUint32(this._dataByteOffset,!0);return this._dataByteOffset+=4,this.byteOffset+=4,e}readUint8Array(e){const t=new Uint8Array(this._dataView.buffer,this._dataView.byteOffset+this._dataByteOffset,e);return this._dataByteOffset+=e,this.byteOffset+=e,t}readString(e){return(e=>{if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);let t="";for(let s=0;s<e.byteLength;s++)t+=String.fromCharCode(e[s]);return t})(this.readUint8Array(e))}skipBytes(e){this._dataByteOffset+=e,this.byteOffset+=e}}function Ha(e,t,s,i){const r={externalResourceFunction:i};return s&&(r.uri="file:"===t?s:t+s),ArrayBuffer.isView(e)?GLTFValidator.validateBytes(e,r):GLTFValidator.validateString(e,r)}function za(){const e=[];onmessage=t=>{const s=t.data;switch(s.id){case"init":importScripts(s.url);break;case"validate":Ha(s.data,s.rootUrl,s.fileName,(t=>new Promise(((s,i)=>{const r=e.length;e.push({resolve:s,reject:i}),postMessage({id:"getExternalResource",index:r,uri:t})})))).then((e=>{postMessage({id:"validate.resolve",value:e})}),(e=>{postMessage({id:"validate.reject",reason:e})}));break;case"getExternalResource.resolve":e[s.index].resolve(s.value);break;case"getExternalResource.reject":e[s.index].reject(s.reason)}}}class Xa{static ValidateAsync(e,t,s,i){return"function"==typeof Worker?new Promise(((r,n)=>{const a=`${Ha}(${za})()`,o=URL.createObjectURL(new Blob([a],{type:"application/javascript"})),h=new Worker(o),l=e=>{h.removeEventListener("error",l),h.removeEventListener("message",c),n(e)},c=e=>{const t=e.data;switch(t.id){case"getExternalResource":i(t.uri).then((e=>{h.postMessage({id:"getExternalResource.resolve",index:t.index,value:e},[e.buffer])}),(e=>{h.postMessage({id:"getExternalResource.reject",index:t.index,reason:e})}));break;case"validate.resolve":h.removeEventListener("error",l),h.removeEventListener("message",c),r(t.value),h.terminate();break;case"validate.reject":h.removeEventListener("error",l),h.removeEventListener("message",c),n(t.reason),h.terminate()}};if(h.addEventListener("error",l),h.addEventListener("message",c),h.postMessage({id:"init",url:Yt.GetBabylonScriptURL(this.Configuration.url)}),ArrayBuffer.isView(e)){const i=e.slice();h.postMessage({id:"validate",data:i,rootUrl:t,fileName:s},[i.buffer])}else h.postMessage({id:"validate",data:e,rootUrl:t,fileName:s})})):(this._LoadScriptPromise||(this._LoadScriptPromise=Yt.LoadBabylonScriptAsync(this.Configuration.url)),this._LoadScriptPromise.then((()=>Ha(e,t,s,i))))}}Xa.Configuration={url:`${Yt._DefaultCdnUrl}/gltf_validator.js`};const Wa="gltf";function Ya(e,t,s){try{return Promise.resolve(new Uint8Array(e,t,s))}catch(e){return Promise.reject(e)}}var Ka,qa,Qa;!function(e){e[e.AUTO=0]="AUTO",e[e.FORCE_RIGHT_HANDED=1]="FORCE_RIGHT_HANDED"}(Ka||(Ka={})),function(e){e[e.NONE=0]="NONE",e[e.FIRST=1]="FIRST",e[e.ALL=2]="ALL"}(qa||(qa={})),function(e){e[e.LOADING=0]="LOADING",e[e.READY=1]="READY",e[e.COMPLETE=2]="COMPLETE"}(Qa||(Qa={}));class ja{constructor(){this.coordinateSystemMode=Ka.AUTO,this.animationStartMode=qa.FIRST,this.loadNodeAnimations=!0,this.loadSkins=!0,this.loadMorphTargets=!0,this.compileMaterials=!1,this.useClipPlane=!1,this.compileShadowGenerators=!1,this.transparencyAsCoverage=!1,this.useRangeRequests=!1,this.createInstances=!0,this.alwaysComputeBoundingBox=!1,this.loadAllMaterials=!1,this.loadOnlyMaterials=!1,this.skipMaterials=!1,this.useSRGBBuffers=!0,this.targetFps=60,this.alwaysComputeSkeletonRootNode=!1,this.preprocessUrlAsync=e=>Promise.resolve(e),this.extensionOptions={}}copyFrom(e){e&&(this.onParsed=e.onParsed,this.coordinateSystemMode=e.coordinateSystemMode??this.coordinateSystemMode,this.animationStartMode=e.animationStartMode??this.animationStartMode,this.loadNodeAnimations=e.loadNodeAnimations??this.loadNodeAnimations,this.loadSkins=e.loadSkins??this.loadSkins,this.loadMorphTargets=e.loadMorphTargets??this.loadMorphTargets,this.compileMaterials=e.compileMaterials??this.compileMaterials,this.useClipPlane=e.useClipPlane??this.useClipPlane,this.compileShadowGenerators=e.compileShadowGenerators??this.compileShadowGenerators,this.transparencyAsCoverage=e.transparencyAsCoverage??this.transparencyAsCoverage,this.useRangeRequests=e.useRangeRequests??this.useRangeRequests,this.createInstances=e.createInstances??this.createInstances,this.alwaysComputeBoundingBox=e.alwaysComputeBoundingBox??this.alwaysComputeBoundingBox,this.loadAllMaterials=e.loadAllMaterials??this.loadAllMaterials,this.loadOnlyMaterials=e.loadOnlyMaterials??this.loadOnlyMaterials,this.skipMaterials=e.skipMaterials??this.skipMaterials,this.useSRGBBuffers=e.useSRGBBuffers??this.useSRGBBuffers,this.targetFps=e.targetFps??this.targetFps,this.alwaysComputeSkeletonRootNode=e.alwaysComputeSkeletonRootNode??this.alwaysComputeSkeletonRootNode,this.preprocessUrlAsync=e.preprocessUrlAsync??this.preprocessUrlAsync,this.customRootNode=e.customRootNode,this.onMeshLoaded=e.onMeshLoaded,this.onSkinLoaded=e.onSkinLoaded,this.onTextureLoaded=e.onTextureLoaded,this.onMaterialLoaded=e.onMaterialLoaded,this.onCameraLoaded=e.onCameraLoaded,this.extensionOptions=e.extensionOptions??this.extensionOptions)}}class Za extends ja{constructor(e){super(),this.onParsedObservable=new g,this.onMeshLoadedObservable=new g,this.onSkinLoadedObservable=new g,this.onTextureLoadedObservable=new g,this.onMaterialLoadedObservable=new g,this.onCameraLoadedObservable=new g,this.onCompleteObservable=new g,this.onErrorObservable=new g,this.onDisposeObservable=new g,this.onExtensionLoadedObservable=new g,this.validate=!1,this.onValidatedObservable=new g,this._loader=null,this._state=null,this._requests=new Array,this.name=Wa,this.extensions={".gltf":{isBinary:!1},".glb":{isBinary:!0}},this.onLoaderStateChangedObservable=new g,this._logIndentLevel=0,this._loggingEnabled=!1,this._log=this._logDisabled,this._capturePerformanceCounters=!1,this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled,this.copyFrom(e)}set onParsed(e){this._onParsedObserver&&this.onParsedObservable.remove(this._onParsedObserver),e&&(this._onParsedObserver=this.onParsedObservable.add(e))}set onMeshLoaded(e){this._onMeshLoadedObserver&&this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver),e&&(this._onMeshLoadedObserver=this.onMeshLoadedObservable.add(e))}set onSkinLoaded(e){this._onSkinLoadedObserver&&this.onSkinLoadedObservable.remove(this._onSkinLoadedObserver),e&&(this._onSkinLoadedObserver=this.onSkinLoadedObservable.add((t=>e(t.node,t.skinnedNode))))}set onTextureLoaded(e){this._onTextureLoadedObserver&&this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver),e&&(this._onTextureLoadedObserver=this.onTextureLoadedObservable.add(e))}set onMaterialLoaded(e){this._onMaterialLoadedObserver&&this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver),e&&(this._onMaterialLoadedObserver=this.onMaterialLoadedObservable.add(e))}set onCameraLoaded(e){this._onCameraLoadedObserver&&this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver),e&&(this._onCameraLoadedObserver=this.onCameraLoadedObservable.add(e))}set onComplete(e){this._onCompleteObserver&&this.onCompleteObservable.remove(this._onCompleteObserver),this._onCompleteObserver=this.onCompleteObservable.add(e)}set onError(e){this._onErrorObserver&&this.onErrorObservable.remove(this._onErrorObserver),this._onErrorObserver=this.onErrorObservable.add(e)}set onDispose(e){this._onDisposeObserver&&this.onDisposeObservable.remove(this._onDisposeObserver),this._onDisposeObserver=this.onDisposeObservable.add(e)}set onExtensionLoaded(e){this._onExtensionLoadedObserver&&this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver),this._onExtensionLoadedObserver=this.onExtensionLoadedObservable.add(e)}get loggingEnabled(){return this._loggingEnabled}set loggingEnabled(e){this._loggingEnabled!==e&&(this._loggingEnabled=e,this._loggingEnabled?this._log=this._logEnabled:this._log=this._logDisabled)}get capturePerformanceCounters(){return this._capturePerformanceCounters}set capturePerformanceCounters(e){this._capturePerformanceCounters!==e&&(this._capturePerformanceCounters=e,this._capturePerformanceCounters?(this._startPerformanceCounter=this._startPerformanceCounterEnabled,this._endPerformanceCounter=this._endPerformanceCounterEnabled):(this._startPerformanceCounter=this._startPerformanceCounterDisabled,this._endPerformanceCounter=this._endPerformanceCounterDisabled))}set onValidated(e){this._onValidatedObserver&&this.onValidatedObservable.remove(this._onValidatedObserver),this._onValidatedObserver=this.onValidatedObservable.add(e)}dispose(){this._loader&&(this._loader.dispose(),this._loader=null);for(const e of this._requests)e.abort();this._requests.length=0,delete this._progressCallback,this.preprocessUrlAsync=e=>Promise.resolve(e),this.onMeshLoadedObservable.clear(),this.onSkinLoadedObservable.clear(),this.onTextureLoadedObservable.clear(),this.onMaterialLoadedObservable.clear(),this.onCameraLoadedObservable.clear(),this.onCompleteObservable.clear(),this.onExtensionLoadedObservable.clear(),this.onDisposeObservable.notifyObservers(void 0),this.onDisposeObservable.clear()}loadFile(e,t,s,i,r,n,a,o){if(ArrayBuffer.isView(t))return this._loadBinary(e,t,s,i,a,o),null;this._progressCallback=r;const h=t.name||Yt.GetFilename(t);if(n){if(this.useRangeRequests){this.validate&&ue.Warn("glTF validation is not supported when range requests are enabled");const s={abort:()=>{},onCompleteObservable:new g},r={readAsync:(s,i)=>new Promise(((r,n)=>{this._loadFile(e,t,(e=>{r(new Uint8Array(e))}),!0,(e=>{n(e)}),(e=>{e.setRequestHeader("Range",`bytes=${s}-${s+i-1}`)}))})),byteLength:0};return this._unpackBinaryAsync(new Va(r)).then((e=>{s.onCompleteObservable.notifyObservers(s),i(e)}),a?e=>a(void 0,e):void 0),s}return this._loadFile(e,t,(t=>{this._validate(e,new Uint8Array(t,0,t.byteLength),s,h),this._unpackBinaryAsync(new Va({readAsync:(e,s)=>Ya(t,e,s),byteLength:t.byteLength})).then((e=>{i(e)}),a?e=>a(void 0,e):void 0)}),!0,a)}return this._loadFile(e,t,(t=>{try{this._validate(e,t,s,h),i({json:this._parseJson(t)})}catch{a&&a()}}),!1,a)}_loadBinary(e,t,s,i,r,n){this._validate(e,new Uint8Array(t.buffer,t.byteOffset,t.byteLength),s,n),this._unpackBinaryAsync(new Va({readAsync:(e,s)=>function(e,t,s){try{if(t<0||t>=e.byteLength)throw new RangeError("Offset is out of range.");if(t+s>e.byteLength)throw new RangeError("Length is out of range.");return Promise.resolve(new Uint8Array(e.buffer,e.byteOffset+t,s))}catch(e){return Promise.reject(e)}}(t,e,s),byteLength:t.byteLength})).then((e=>{i(e)}),r?e=>r(void 0,e):void 0)}importMeshAsync(e,t,s,i,r,n){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(s),this.onParsedObservable.clear(),this._log(`Loading ${n||""}`),this._loader=this._getLoader(s),this._loader.importMeshAsync(e,t,null,s,i,r,n))))}loadAsync(e,t,s,i,r){return Promise.resolve().then((()=>(this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(t),this._loader.loadAsync(e,t,s,i,r))))}loadAssetContainerAsync(e,t,s,i,r){return Promise.resolve().then((()=>{this.onParsedObservable.notifyObservers(t),this.onParsedObservable.clear(),this._log(`Loading ${r||""}`),this._loader=this._getLoader(t);const n=new Ga(e),a=[];this.onMaterialLoadedObservable.add((e=>{a.push(e)}));const o=[];this.onTextureLoadedObservable.add((e=>{o.push(e)}));const h=[];this.onCameraLoadedObservable.add((e=>{h.push(e)}));const l=[];return this.onMeshLoadedObservable.add((e=>{e.morphTargetManager&&l.push(e.morphTargetManager)})),this._loader.importMeshAsync(null,e,n,t,s,i,r).then((e=>(Array.prototype.push.apply(n.geometries,e.geometries),Array.prototype.push.apply(n.meshes,e.meshes),Array.prototype.push.apply(n.particleSystems,e.particleSystems),Array.prototype.push.apply(n.skeletons,e.skeletons),Array.prototype.push.apply(n.animationGroups,e.animationGroups),Array.prototype.push.apply(n.materials,a),Array.prototype.push.apply(n.textures,o),Array.prototype.push.apply(n.lights,e.lights),Array.prototype.push.apply(n.transformNodes,e.transformNodes),Array.prototype.push.apply(n.cameras,h),Array.prototype.push.apply(n.morphTargetManagers,l),n)))}))}canDirectLoad(e){return-1!==e.indexOf("asset")&&-1!==e.indexOf("version")||e.startsWith("data:base64,"+Za._MagicBase64Encoded)||e.startsWith("data:;base64,"+Za._MagicBase64Encoded)||e.startsWith("data:application/octet-stream;base64,"+Za._MagicBase64Encoded)||e.startsWith("data:model/gltf-binary;base64,"+Za._MagicBase64Encoded)}directLoad(e,t){if(t.startsWith("base64,"+Za._MagicBase64Encoded)||t.startsWith(";base64,"+Za._MagicBase64Encoded)||t.startsWith("application/octet-stream;base64,"+Za._MagicBase64Encoded)||t.startsWith("model/gltf-binary;base64,"+Za._MagicBase64Encoded)){const s=Nt(t);return this._validate(e,new Uint8Array(s,0,s.byteLength)),this._unpackBinaryAsync(new Va({readAsync:(e,t)=>Ya(s,e,t),byteLength:s.byteLength}))}return this._validate(e,t),Promise.resolve({json:this._parseJson(t)})}createPlugin(e){return new Za(e[Wa])}get loaderState(){return this._state}whenCompleteAsync(){return new Promise(((e,t)=>{this.onCompleteObservable.addOnce((()=>{e()})),this.onErrorObservable.addOnce((e=>{t(e)}))}))}_setState(e){this._state!==e&&(this._state=e,this.onLoaderStateChangedObservable.notifyObservers(this._state),this._log(Qa[this._state]))}_loadFile(e,t,s,i,r,n){const a=e._loadFile(t,s,(e=>{this._onProgress(e,a)}),!0,i,r,n);return a.onCompleteObservable.add((()=>{a._lengthComputable=!0,a._total=a._loaded})),this._requests.push(a),a}_onProgress(e,t){if(!this._progressCallback)return;t._lengthComputable=e.lengthComputable,t._loaded=e.loaded,t._total=e.total;let s=!0,i=0,r=0;for(const e of this._requests){if(void 0===e._lengthComputable||void 0===e._loaded||void 0===e._total)return;s=s&&e._lengthComputable,i+=e._loaded,r+=e._total}this._progressCallback({lengthComputable:s,loaded:i,total:s?r:0})}_validate(e,t,s="",i=""){this.validate&&(this._startPerformanceCounter("Validate JSON"),Xa.ValidateAsync(t,s,i,(t=>this.preprocessUrlAsync(s+t).then((t=>e._loadFileAsync(t,void 0,!0,!0).then((e=>new Uint8Array(e,0,e.byteLength))))))).then((e=>{this._endPerformanceCounter("Validate JSON"),this.onValidatedObservable.notifyObservers(e),this.onValidatedObservable.clear()}),(e=>{this._endPerformanceCounter("Validate JSON"),Yt.Warn(`Failed to validate: ${e.message}`),this.onValidatedObservable.clear()})))}_getLoader(e){const t=e.json.asset||{};this._log(`Asset version: ${t.version}`),t.minVersion&&this._log(`Asset minimum version: ${t.minVersion}`),t.generator&&this._log(`Asset generator: ${t.generator}`);const s=Za._parseVersion(t.version);if(!s)throw new Error("Invalid version: "+t.version);if(void 0!==t.minVersion){const e=Za._parseVersion(t.minVersion);if(!e)throw new Error("Invalid minimum version: "+t.minVersion);if(Za._compareVersion(e,{major:2,minor:0})>0)throw new Error("Incompatible minimum version: "+t.minVersion)}const i={1:Za._CreateGLTF1Loader,2:Za._CreateGLTF2Loader}[s.major];if(!i)throw new Error("Unsupported version: "+t.version);return i(this)}_parseJson(e){this._startPerformanceCounter("Parse JSON"),this._log(`JSON length: ${e.length}`);const t=JSON.parse(e);return this._endPerformanceCounter("Parse JSON"),t}_unpackBinaryAsync(e){return this._startPerformanceCounter("Unpack Binary"),e.loadAsync(20).then((()=>{const t=e.readUint32();if(1179937895!==t)throw new Ee("Unexpected magic: "+t,Te.GLTFLoaderUnexpectedMagicError);const s=e.readUint32();this.loggingEnabled&&this._log(`Binary version: ${s}`);const i=e.readUint32();let r;switch(this.useRangeRequests||i===e.buffer.byteLength||ue.Warn(`Length in header does not match actual data length: ${i} != ${e.buffer.byteLength}`),s){case 1:r=this._unpackBinaryV1Async(e,i);break;case 2:r=this._unpackBinaryV2Async(e,i);break;default:throw new Error("Unsupported version: "+s)}return this._endPerformanceCounter("Unpack Binary"),r}))}_unpackBinaryV1Async(e,t){const s=e.readUint32(),i=e.readUint32();if(0!==i)throw new Error(`Unexpected content format: ${i}`);const r=t-e.byteOffset,n={json:this._parseJson(e.readString(s)),bin:null};if(0!==r){const t=e.byteOffset;n.bin={readAsync:(s,i)=>e.buffer.readAsync(t+s,i),byteLength:r}}return Promise.resolve(n)}_unpackBinaryV2Async(e,t){const s=1313821514,i=5130562,r=e.readUint32();if(e.readUint32()!==s)throw new Error("First chunk format is not JSON");return e.byteOffset+r===t?e.loadAsync(r).then((()=>({json:this._parseJson(e.readString(r)),bin:null}))):e.loadAsync(r+8).then((()=>{const n={json:this._parseJson(e.readString(r)),bin:null},a=()=>{const r=e.readUint32();switch(e.readUint32()){case s:throw new Error("Unexpected JSON chunk");case i:{const t=e.byteOffset;n.bin={readAsync:(s,i)=>e.buffer.readAsync(t+s,i),byteLength:r},e.skipBytes(r);break}default:e.skipBytes(r)}return e.byteOffset!==t?e.loadAsync(8).then(a):Promise.resolve(n)};return a()}))}static _parseVersion(e){if("1.0"===e||"1.0.1"===e)return{major:1,minor:0};const t=(e+"").match(/^(\d+)\.(\d+)/);return t?{major:parseInt(t[1]),minor:parseInt(t[2])}:null}static _compareVersion(e,t){return e.major>t.major?1:e.major<t.major?-1:e.minor>t.minor?1:e.minor<t.minor?-1:0}_logOpen(e){this._log(e),this._logIndentLevel++}_logClose(){--this._logIndentLevel}_logEnabled(e){const t=Za._logSpaces.substr(0,2*this._logIndentLevel);ue.Log(`${t}${e}`)}_logDisabled(e){}_startPerformanceCounterEnabled(e){Yt.StartPerformanceCounter(e)}_startPerformanceCounterDisabled(e){}_endPerformanceCounterEnabled(e){Yt.EndPerformanceCounter(e)}_endPerformanceCounterDisabled(e){}}function $a(e,t,s,i){return U.FromArray(t,s).scaleInPlace(i)}Za.IncrementalLoading=!0,Za.HomogeneousCoordinates=!1,Za._MagicBase64Encoded="Z2xURg",Za._logSpaces=" ",function(e){if("string"==typeof e.extensions){const t=e.extensions;Rr[t.toLowerCase()]={plugin:e,isBinary:!1}}else{const t=e.extensions;Object.keys(t).forEach((s=>{Rr[s.toLowerCase()]={plugin:e,isBinary:t[s].isBinary}}))}}(new Za);class Ja{constructor(e,t,s,i){this.type=e,this.name=t,this.getValue=s,this.getStride=i}_buildAnimation(e,t,s){const i=new xi(e,this.name,t,this.type);return i.setKeys(s),i}}class eo extends Ja{buildAnimations(e,t,s,i,r){r(e._babylonTransformNode,this._buildAnimation(t,s,i))}}const to={translation:[new eo(xi.ANIMATIONTYPE_VECTOR3,"position",$a,(()=>3))],rotation:[new eo(xi.ANIMATIONTYPE_QUATERNION,"rotationQuaternion",(function(e,t,s,i){return G.FromArray(t,s).scaleInPlace(i)}),(()=>4))],scale:[new eo(xi.ANIMATIONTYPE_VECTOR3,"scaling",$a,(()=>3))],weights:[new class extends Ja{buildAnimations(e,t,s,i,r){if(e._numMorphTargets)for(let n=0;n<e._numMorphTargets;n++){const a=new xi(`${t}_${n}`,this.name,s,this.type);if(a.setKeys(i.map((e=>({frame:e.frame,inTangent:e.inTangent?e.inTangent[n]:void 0,value:e.value[n],outTangent:e.outTangent?e.outTangent[n]:void 0,interpolation:e.interpolation})))),e._primitiveBabylonMeshes)for(const t of e._primitiveBabylonMeshes)if(t.morphTargetManager){const e=t.morphTargetManager.getTarget(n),s=a.clone();e.animations.push(s),r(e,s)}}}}(xi.ANIMATIONTYPE_FLOAT,"influence",(function(e,t,s,i){const r=new Array(e._numMorphTargets);for(let e=0;e<r.length;e++)r[e]=t[s++]*i;return r}),(e=>e._numMorphTargets))]};function so(...e){const t=e=>e&&"object"==typeof e;return e.reduce(((e,s)=>(Object.keys(s).forEach((i=>{const r=e[i],n=s[i];Array.isArray(r)&&Array.isArray(n)?e[i]=r.concat(...n):t(r)&&t(n)?e[i]=so(r,n):e[i]=n})),e)),{})}class io{static Get(e,t,s){if(!t||null==s||!t[s])throw new Error(`${e}: Failed to find index (${s})`);return t[s]}static TryGet(e,t){return e&&null!=t&&e[t]?e[t]:null}static Assign(e){if(e)for(let t=0;t<e.length;t++)e[t].index=t}}class ro{static RegisterExtension(e,t){ro.UnregisterExtension(e)&&ue.Warn(`Extension with the name '${e}' already exists`),ro._RegisteredExtensions[e]={factory:t}}static UnregisterExtension(e){return!!ro._RegisteredExtensions[e]&&(delete ro._RegisteredExtensions[e],!0)}get gltf(){if(!this._gltf)throw new Error("glTF JSON is not available");return this._gltf}get bin(){return this._bin}get parent(){return this._parent}get babylonScene(){if(!this._babylonScene)throw new Error("Scene is not available");return this._babylonScene}get rootBabylonMesh(){return this._rootBabylonMesh}get rootUrl(){return this._rootUrl}constructor(e){this._completePromises=new Array,this._assetContainer=null,this._babylonLights=[],this._disableInstancedMesh=0,this._allMaterialsDirtyRequired=!1,this._extensions=new Array,this._disposed=!1,this._rootUrl=null,this._fileName=null,this._uniqueRootUrl=null,this._bin=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions=new Array,this._parent=e}dispose(){this._disposed||(this._disposed=!0,this._completePromises.length=0,this._extensions.forEach((e=>e.dispose&&e.dispose())),this._extensions.length=0,this._gltf=null,this._bin=null,this._babylonScene=null,this._rootBabylonMesh=null,this._defaultBabylonMaterialData={},this._postSceneLoadActions.length=0,this._parent.dispose())}importMeshAsync(e,t,s,i,r,n,a=""){return Promise.resolve().then((()=>{this._babylonScene=t,this._assetContainer=s,this._loadData(i);let n=null;if(e){const t={};if(this._gltf.nodes)for(const e of this._gltf.nodes)e.name&&(t[e.name]=e.index);n=(e instanceof Array?e:[e]).map((e=>{const s=t[e];if(void 0===s)throw new Error(`Failed to find node '${e}'`);return s}))}return this._loadAsync(r,a,n,(()=>({meshes:this._getMeshes(),particleSystems:[],skeletons:this._getSkeletons(),animationGroups:this._getAnimationGroups(),lights:this._babylonLights,transformNodes:this._getTransformNodes(),geometries:this._getGeometries(),spriteManagers:[]})))}))}loadAsync(e,t,s,i,r=""){return Promise.resolve().then((()=>(this._babylonScene=e,this._loadData(t),this._loadAsync(s,r,null,(()=>{})))))}_loadAsync(e,t,s,i){return Promise.resolve().then((()=>{this._rootUrl=e,this._uniqueRootUrl=!e.startsWith("file:")&&t?e:`${e}${Date.now()}/`,this._fileName=t,this._allMaterialsDirtyRequired=!1,this._loadExtensions(),this._checkExtensions();const r=`${Qa[Qa.LOADING]} => ${Qa[Qa.READY]}`,n=`${Qa[Qa.LOADING]} => ${Qa[Qa.COMPLETE]}`;this._parent._startPerformanceCounter(r),this._parent._startPerformanceCounter(n),this._parent._setState(Qa.LOADING),this._extensionsOnLoading();const a=new Array,o=this._babylonScene.blockMaterialDirtyMechanism;if(this._babylonScene.blockMaterialDirtyMechanism=!0,!this.parent.loadOnlyMaterials)if(s)a.push(this.loadSceneAsync("/nodes",{nodes:s,index:-1}));else if(null!=this._gltf.scene||this._gltf.scenes&&this._gltf.scenes[0]){const e=io.Get("/scene",this._gltf.scenes,this._gltf.scene||0);a.push(this.loadSceneAsync(`/scenes/${e.index}`,e))}if(!this.parent.skipMaterials&&this.parent.loadAllMaterials&&this._gltf.materials)for(let e=0;e<this._gltf.materials.length;++e){const t=this._gltf.materials[e],s="/materials/"+e,i=$s.TriangleFillMode;a.push(this._loadMaterialAsync(s,t,null,i,(()=>{})))}this._allMaterialsDirtyRequired?this._babylonScene.blockMaterialDirtyMechanism=o:this._babylonScene._forceBlockMaterialDirtyMechanism(o),this._parent.compileMaterials&&a.push(this._compileMaterialsAsync()),this._parent.compileShadowGenerators&&a.push(this._compileShadowGeneratorsAsync());return Promise.all(a).then((()=>(this._rootBabylonMesh&&this._rootBabylonMesh!==this._parent.customRootNode&&this._rootBabylonMesh.setEnabled(!0),this._extensionsOnReady(),this._parent._setState(Qa.READY),this._startAnimations(),i()))).then((e=>(this._parent._endPerformanceCounter(r),Yt.SetImmediate((()=>{this._disposed||Promise.all(this._completePromises).then((()=>{this._parent._endPerformanceCounter(n),this._parent._setState(Qa.COMPLETE),this._parent.onCompleteObservable.notifyObservers(void 0),this._parent.onCompleteObservable.clear(),this.dispose()}),(e=>{this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()}))})),e)))})).catch((e=>{throw this._disposed||(this._parent.onErrorObservable.notifyObservers(e),this._parent.onErrorObservable.clear(),this.dispose()),e}))}_loadData(e){if(this._gltf=e.json,this._setupData(),e.bin){const t=this._gltf.buffers;if(t&&t[0]&&!t[0].uri){const s=t[0];(s.byteLength<e.bin.byteLength-3||s.byteLength>e.bin.byteLength)&&ue.Warn(`Binary buffer length (${s.byteLength}) from JSON does not match chunk length (${e.bin.byteLength})`),this._bin=e.bin}else ue.Warn("Unexpected BIN chunk")}}_setupData(){if(io.Assign(this._gltf.accessors),io.Assign(this._gltf.animations),io.Assign(this._gltf.buffers),io.Assign(this._gltf.bufferViews),io.Assign(this._gltf.cameras),io.Assign(this._gltf.images),io.Assign(this._gltf.materials),io.Assign(this._gltf.meshes),io.Assign(this._gltf.nodes),io.Assign(this._gltf.samplers),io.Assign(this._gltf.scenes),io.Assign(this._gltf.skins),io.Assign(this._gltf.textures),this._gltf.nodes){const e={};for(const t of this._gltf.nodes)if(t.children)for(const s of t.children)e[s]=t.index;const t=this._createRootNode();for(const s of this._gltf.nodes){const i=e[s.index];s.parent=void 0===i?t:this._gltf.nodes[i]}}}_loadExtensions(){for(const e in ro._RegisteredExtensions)if(!1===this.parent.extensionOptions[e]?.enabled)this.isExtensionUsed(e)&&ue.Warn(`Extension ${e} is used but has been explicitly disabled.`);else{const t=ro._RegisteredExtensions[e].factory(this);t.name!==e&&ue.Warn(`The name of the glTF loader extension instance does not match the registered name: ${t.name} !== ${e}`),this._extensions.push(t),this._parent.onExtensionLoadedObservable.notifyObservers(t)}this._extensions.sort(((e,t)=>(e.order||Number.MAX_VALUE)-(t.order||Number.MAX_VALUE))),this._parent.onExtensionLoadedObservable.clear()}_checkExtensions(){if(this._gltf.extensionsRequired)for(const e of this._gltf.extensionsRequired){if(!this._extensions.some((t=>t.name===e&&t.enabled))){if(!1===this.parent.extensionOptions[e]?.enabled)throw new Error(`Required extension ${e} is disabled`);throw new Error(`Required extension ${e} is not available`)}}}_createRootNode(){if(void 0!==this._parent.customRootNode)return this._rootBabylonMesh=this._parent.customRootNode,{_babylonTransformNode:null===this._rootBabylonMesh?void 0:this._rootBabylonMesh,index:-1};this._babylonScene._blockEntityCollection=!!this._assetContainer;const e=new oi("__root__",this._babylonScene);this._rootBabylonMesh=e,this._rootBabylonMesh._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._rootBabylonMesh.setEnabled(!1);const t={_babylonTransformNode:this._rootBabylonMesh,index:-1};switch(this._parent.coordinateSystemMode){case Ka.AUTO:this._babylonScene.useRightHandedSystem||(t.rotation=[0,1,0,0],t.scale=[1,1,-1],ro._LoadTransform(t,this._rootBabylonMesh));break;case Ka.FORCE_RIGHT_HANDED:this._babylonScene.useRightHandedSystem=!0;break;default:throw new Error(`Invalid coordinate system mode (${this._parent.coordinateSystemMode})`)}return this._parent.onMeshLoadedObservable.notifyObservers(e),t}loadSceneAsync(e,t){const s=this._extensionsLoadSceneAsync(e,t);if(s)return s;const i=new Array;if(this.logOpen(`${e} ${t.name||""}`),t.nodes)for(const s of t.nodes){const t=io.Get(`${e}/nodes/${s}`,this._gltf.nodes,s);i.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=this._rootBabylonMesh})))}for(const e of this._postSceneLoadActions)e();return i.push(this._loadAnimationsAsync()),this.logClose(),Promise.all(i).then((()=>{}))}_forEachPrimitive(e,t){if(e._primitiveBabylonMeshes)for(const s of e._primitiveBabylonMeshes)t(s)}_getGeometries(){const e=[],t=this._gltf.nodes;if(t)for(const s of t)this._forEachPrimitive(s,(t=>{const s=t.geometry;s&&-1===e.indexOf(s)&&e.push(s)}));return e}_getMeshes(){const e=[];this._rootBabylonMesh instanceof Gs&&e.push(this._rootBabylonMesh);const t=this._gltf.nodes;if(t)for(const s of t)this._forEachPrimitive(s,(t=>{e.push(t)}));return e}_getTransformNodes(){const e=[],t=this._gltf.nodes;if(t)for(const s of t)s._babylonTransformNode&&"TransformNode"===s._babylonTransformNode.getClassName()&&e.push(s._babylonTransformNode),s._babylonTransformNodeForSkin&&e.push(s._babylonTransformNodeForSkin);return e}_getSkeletons(){const e=[],t=this._gltf.skins;if(t)for(const s of t)s._data&&e.push(s._data.babylonSkeleton);return e}_getAnimationGroups(){const e=[],t=this._gltf.animations;if(t)for(const s of t)s._babylonAnimationGroup&&e.push(s._babylonAnimationGroup);return e}_startAnimations(){switch(this._parent.animationStartMode){case qa.NONE:break;case qa.FIRST:{const e=this._getAnimationGroups();0!==e.length&&e[0].start(!0);break}case qa.ALL:{const e=this._getAnimationGroups();for(const t of e)t.start(!0);break}default:return void ue.Error(`Invalid animation start mode (${this._parent.animationStartMode})`)}}loadNodeAsync(e,t,s=()=>{}){const i=this._extensionsLoadNodeAsync(e,t,s);if(i)return i;if(t._babylonTransformNode)throw new Error(`${e}: Invalid recursive node hierarchy`);const r=new Array;this.logOpen(`${e} ${t.name||""}`);const n=i=>{if(ro.AddPointerMetadata(i,e),ro._LoadTransform(t,i),null!=t.camera){const s=io.Get(`${e}/camera`,this._gltf.cameras,t.camera);r.push(this.loadCameraAsync(`/cameras/${s.index}`,s,(e=>{e.parent=i})))}if(t.children)for(const s of t.children){const t=io.Get(`${e}/children/${s}`,this._gltf.nodes,s);r.push(this.loadNodeAsync(`/nodes/${t.index}`,t,(e=>{e.parent=i})))}s(i)},a=null!=t.mesh,o=this._parent.loadSkins&&null!=t.skin;if(!a||o){const e=t.name||`node${t.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const s=new Rs(e,this._babylonScene);s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,null==t.mesh?t._babylonTransformNode=s:t._babylonTransformNodeForSkin=s,n(s)}if(a)if(o){const s=io.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);r.push(this._loadMeshAsync(`/meshes/${s.index}`,t,s,(s=>{const i=t._babylonTransformNodeForSkin;s.metadata=so(i.metadata,s.metadata||{});const n=io.Get(`${e}/skin`,this._gltf.skins,t.skin);r.push(this._loadSkinAsync(`/skins/${n.index}`,t,n,(e=>{this._forEachPrimitive(t,(t=>{t.skeleton=e})),this._postSceneLoadActions.push((()=>{if(null!=n.skeleton){const e=io.Get(`/skins/${n.index}/skeleton`,this._gltf.nodes,n.skeleton).parent;t.index===e.index?s.parent=i.parent:s.parent=e._babylonTransformNode}else s.parent=this._rootBabylonMesh;this._parent.onSkinLoadedObservable.notifyObservers({node:i,skinnedNode:s})}))})))})))}else{const s=io.Get(`${e}/mesh`,this._gltf.meshes,t.mesh);r.push(this._loadMeshAsync(`/meshes/${s.index}`,t,s,n))}return this.logClose(),Promise.all(r).then((()=>(this._forEachPrimitive(t,(e=>{e.geometry&&e.geometry.useBoundingInfoFromGeometry?e._updateBoundingInfo():e.refreshBoundingInfo(!0,!0)})),t._babylonTransformNode)))}_loadMeshAsync(e,t,s,i){const r=s.primitives;if(!r||!r.length)throw new Error(`${e}: Primitives are missing`);null==r[0].index&&io.Assign(r);const n=new Array;this.logOpen(`${e} ${s.name||""}`);const a=t.name||`node${t.index}`;if(1===r.length){const i=s.primitives[0];n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${i.index}`,a,t,s,i,(e=>{t._babylonTransformNode=e,t._primitiveBabylonMeshes=[e]})))}else{this._babylonScene._blockEntityCollection=!!this._assetContainer,t._babylonTransformNode=new Rs(a,this._babylonScene),t._babylonTransformNode._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._primitiveBabylonMeshes=[];for(const i of r)n.push(this._loadMeshPrimitiveAsync(`${e}/primitives/${i.index}`,`${a}_primitive${i.index}`,t,s,i,(e=>{e.parent=t._babylonTransformNode,t._primitiveBabylonMeshes.push(e)})))}return i(t._babylonTransformNode),this.logClose(),Promise.all(n).then((()=>t._babylonTransformNode))}_loadMeshPrimitiveAsync(e,t,s,i,r,n){const a=this._extensionsLoadMeshPrimitiveAsync(e,t,s,i,r,n);if(a)return a;this.logOpen(`${e}`);const o=0===this._disableInstancedMesh&&this._parent.createInstances&&null==s.skin&&!i.primitives[0].targets;let h,l;if(o&&r._instanceData)this._babylonScene._blockEntityCollection=!!this._assetContainer,h=r._instanceData.babylonSourceMesh.createInstance(t),h._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,l=r._instanceData.promise;else{const n=new Array;this._babylonScene._blockEntityCollection=!!this._assetContainer;const a=new oi(t,this._babylonScene);a._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,a.sideOrientation=this._babylonScene.useRightHandedSystem?$s.CounterClockWiseSideOrientation:$s.ClockWiseSideOrientation,this._createMorphTargets(e,s,i,r,a),n.push(this._loadVertexDataAsync(e,r,a).then((t=>this._loadMorphTargetsAsync(e,r,a,t).then((()=>{this._disposed||(this._babylonScene._blockEntityCollection=!!this._assetContainer,t.applyToMesh(a),t._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1)})))));const c=ro._GetDrawMode(e,r.mode);if(null==r.material){let e=this._defaultBabylonMaterialData[c];e||(e=this._createDefaultMaterial("__GLTFLoader._default",c),this._parent.onMaterialLoadedObservable.notifyObservers(e),this._defaultBabylonMaterialData[c]=e),a.material=e}else if(!this.parent.skipMaterials){const t=io.Get(`${e}/material`,this._gltf.materials,r.material);n.push(this._loadMaterialAsync(`/materials/${t.index}`,t,a,c,(e=>{a.material=e})))}l=Promise.all(n),o&&(r._instanceData={babylonSourceMesh:a,promise:l}),h=a}return ro.AddPointerMetadata(h,e),this._parent.onMeshLoadedObservable.notifyObservers(h),n(h),this.logClose(),l.then((()=>h))}_loadVertexDataAsync(e,t,s){const i=this._extensionsLoadVertexDataAsync(e,t,s);if(i)return i;const r=t.attributes;if(!r)throw new Error(`${e}: Attributes are missing`);const n=new Array,a=new ys(s.name,this._babylonScene);if(null==t.indices)s.isUnIndexed=!0;else{const s=io.Get(`${e}/indices`,this._gltf.accessors,t.indices);n.push(this._loadIndicesAccessorAsync(`/accessors/${s.index}`,s).then((e=>{a.setIndices(e)})))}const o=(t,i,o)=>{if(null==r[t])return;s._delayInfo=s._delayInfo||[],-1===s._delayInfo.indexOf(i)&&s._delayInfo.push(i);const h=io.Get(`${e}/attributes/${t}`,this._gltf.accessors,r[t]);n.push(this._loadVertexAccessorAsync(`/accessors/${h.index}`,h,i).then((e=>{if(e.getKind()===ns.PositionKind&&!this.parent.alwaysComputeBoundingBox&&!s.skeleton&&h.min&&h.max){const e=z.Vector3[0].copyFromFloats(...h.min),t=z.Vector3[1].copyFromFloats(...h.max);if(h.normalized&&5126!==h.componentType){let s=1;switch(h.componentType){case 5120:s=127;break;case 5121:s=255;break;case 5122:s=32767;break;case 5123:s=65535}const i=1/s;e.scaleInPlace(i),t.scaleInPlace(i)}a._boundingInfo=new _s(e,t),a.useBoundingInfoFromGeometry=!0}a.setVerticesBuffer(e,h.count)}))),i==ns.MatricesIndicesExtraKind&&(s.numBoneInfluencers=8),o&&o(h)};return o("POSITION",ns.PositionKind),o("NORMAL",ns.NormalKind),o("TANGENT",ns.TangentKind),o("TEXCOORD_0",ns.UVKind),o("TEXCOORD_1",ns.UV2Kind),o("TEXCOORD_2",ns.UV3Kind),o("TEXCOORD_3",ns.UV4Kind),o("TEXCOORD_4",ns.UV5Kind),o("TEXCOORD_5",ns.UV6Kind),o("JOINTS_0",ns.MatricesIndicesKind),o("WEIGHTS_0",ns.MatricesWeightsKind),o("JOINTS_1",ns.MatricesIndicesExtraKind),o("WEIGHTS_1",ns.MatricesWeightsExtraKind),o("COLOR_0",ns.ColorKind,(e=>{"VEC4"===e.type&&(s.hasVertexAlpha=!0)})),Promise.all(n).then((()=>a))}_createMorphTargets(e,t,s,i,r){if(!i.targets||!this._parent.loadMorphTargets)return;if(null==t._numMorphTargets)t._numMorphTargets=i.targets.length;else if(i.targets.length!==t._numMorphTargets)throw new Error(`${e}: Primitives do not have the same number of targets`);const n=s.extras?s.extras.targetNames:null;this._babylonScene._blockEntityCollection=!!this._assetContainer,r.morphTargetManager=new wa(this._babylonScene),r.morphTargetManager._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,r.morphTargetManager.areUpdatesFrozen=!0;for(let e=0;e<i.targets.length;e++){const i=t.weights?t.weights[e]:s.weights?s.weights[e]:0,a=n?n[e]:`morphTarget${e}`;r.morphTargetManager.addTarget(new Fa(a,i,r.getScene()))}}_loadMorphTargetsAsync(e,t,s,i){if(!t.targets||!this._parent.loadMorphTargets)return Promise.resolve();const r=new Array,n=s.morphTargetManager;for(let s=0;s<n.numTargets;s++){const a=n.getTarget(s);r.push(this._loadMorphTargetVertexDataAsync(`${e}/targets/${s}`,i,t.targets[s],a))}return Promise.all(r).then((()=>{n.areUpdatesFrozen=!1}))}_loadMorphTargetVertexDataAsync(e,t,s,i){const r=new Array,n=(i,n,a)=>{if(null==s[i])return;const o=t.getVertexBuffer(n);if(!o)return;const h=io.Get(`${e}/${i}`,this._gltf.accessors,s[i]);r.push(this._loadFloatAccessorAsync(`/accessors/${h.index}`,h).then((e=>{a(o,e)})))};return n("POSITION",ns.PositionKind,((e,t)=>{const s=new Float32Array(t.length);e.forEach(t.length,((e,i)=>{s[i]=t[i]+e})),i.setPositions(s)})),n("NORMAL",ns.NormalKind,((e,t)=>{const s=new Float32Array(t.length);e.forEach(s.length,((e,i)=>{s[i]=t[i]+e})),i.setNormals(s)})),n("TANGENT",ns.TangentKind,((e,t)=>{const s=new Float32Array(t.length/3*4);let r=0;e.forEach(t.length/3*4,((e,i)=>{(i+1)%4!=0&&(s[r]=t[r]+e,r++)})),i.setTangents(s)})),Promise.all(r).then((()=>{}))}static _LoadTransform(e,t){if(null!=e.skin)return;let s=U.Zero(),i=G.Identity(),r=U.One();if(e.matrix){V.FromArray(e.matrix).decompose(r,i,s)}else e.translation&&(s=U.FromArray(e.translation)),e.rotation&&(i=G.FromArray(e.rotation)),e.scale&&(r=U.FromArray(e.scale));t.position=s,t.rotationQuaternion=i,t.scaling=r}_loadSkinAsync(e,t,s,i){if(!this._parent.loadSkins)return Promise.resolve();const r=this._extensionsLoadSkinAsync(e,t,s);if(r)return r;if(s._data)return i(s._data.babylonSkeleton),s._data.promise;const n=`skeleton${s.index}`;this._babylonScene._blockEntityCollection=!!this._assetContainer;const a=new La(s.name||n,n,this._babylonScene);a._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,this._loadBones(e,s,a);const o=this._loadSkinInverseBindMatricesDataAsync(e,s).then((e=>{this._updateBoneMatrices(a,e)}));return s._data={babylonSkeleton:a,promise:o},i(a),o}_loadBones(e,t,s){if(null==t.skeleton||this._parent.alwaysComputeSkeletonRootNode){const s=this._findSkeletonRootNode(`${e}/joints`,t.joints);if(s)if(void 0===t.skeleton)t.skeleton=s.index;else{const i=(e,t)=>{for(;t.parent;t=t.parent)if(t.parent===e)return!0;return!1},r=io.Get(`${e}/skeleton`,this._gltf.nodes,t.skeleton);r===s||i(r,s)||(ue.Warn(`${e}/skeleton: Overriding with nearest common ancestor as skeleton node is not a common root`),t.skeleton=s.index)}else ue.Warn(`${e}: Failed to find common root`)}const i={};for(const r of t.joints){const n=io.Get(`${e}/joints/${r}`,this._gltf.nodes,r);this._loadBone(n,t,s,i)}}_findSkeletonRootNode(e,t){if(0===t.length)return null;const s={};for(const i of t){const t=[];let r=io.Get(`${e}/${i}`,this._gltf.nodes,i);for(;-1!==r.index;)t.unshift(r),r=r.parent;s[i]=t}let i=null;for(let e=0;;++e){let r=s[t[0]];if(e>=r.length)return i;const n=r[e];for(let a=1;a<t.length;++a)if(r=s[t[a]],e>=r.length||n!==r[e])return i;i=n}}_loadBone(e,t,s,i){e._isJoint=!0;let r=i[e.index];if(r)return r;let n=null;e.index!==t.skeleton&&(e.parent&&-1!==e.parent.index?n=this._loadBone(e.parent,t,s,i):void 0!==t.skeleton&&ue.Warn(`/skins/${t.index}/skeleton: Skeleton node is not a common root`));const a=t.joints.indexOf(e.index);return r=new ha(e.name||`joint${e.index}`,s,n,this._getNodeMatrix(e),null,null,a),i[e.index]=r,this._postSceneLoadActions.push((()=>{r.linkTransformNode(e._babylonTransformNode)})),r}_loadSkinInverseBindMatricesDataAsync(e,t){if(null==t.inverseBindMatrices)return Promise.resolve(null);const s=io.Get(`${e}/inverseBindMatrices`,this._gltf.accessors,t.inverseBindMatrices);return this._loadFloatAccessorAsync(`/accessors/${s.index}`,s)}_updateBoneMatrices(e,t){for(const s of e.bones){const e=V.Identity(),i=s._index;t&&-1!==i&&(V.FromArrayToRef(t,16*i,e),e.invertToRef(e));const r=s.getParent();r&&e.multiplyToRef(r.getAbsoluteInverseBindMatrix(),e),s.updateMatrix(e,!1,!1),s._updateAbsoluteBindMatrices(void 0,!1)}}_getNodeMatrix(e){return e.matrix?V.FromArray(e.matrix):V.Compose(e.scale?U.FromArray(e.scale):U.One(),e.rotation?G.FromArray(e.rotation):G.Identity(),e.translation?U.FromArray(e.translation):U.Zero())}loadCameraAsync(e,t,s=()=>{}){const i=this._extensionsLoadCameraAsync(e,t,s);if(i)return i;const r=new Array;this.logOpen(`${e} ${t.name||""}`),this._babylonScene._blockEntityCollection=!!this._assetContainer;const n=new Ia(t.name||`camera${t.index}`,U.Zero(),this._babylonScene,!1);switch(n._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,n.ignoreParentScaling=!0,t._babylonCamera=n,n.rotation.set(0,Math.PI,0),t.type){case"perspective":{const s=t.perspective;if(!s)throw new Error(`${e}: Camera perspective properties are missing`);n.fov=s.yfov,n.minZ=s.znear,n.maxZ=s.zfar||0;break}case"orthographic":if(!t.orthographic)throw new Error(`${e}: Camera orthographic properties are missing`);n.mode=ss.ORTHOGRAPHIC_CAMERA,n.orthoLeft=-t.orthographic.xmag,n.orthoRight=t.orthographic.xmag,n.orthoBottom=-t.orthographic.ymag,n.orthoTop=t.orthographic.ymag,n.minZ=t.orthographic.znear,n.maxZ=t.orthographic.zfar;break;default:throw new Error(`${e}: Invalid camera type (${t.type})`)}return ro.AddPointerMetadata(n,e),this._parent.onCameraLoadedObservable.notifyObservers(n),s(n),this.logClose(),Promise.all(r).then((()=>n))}_loadAnimationsAsync(){const e=this._gltf.animations;if(!e)return Promise.resolve();const t=new Array;for(let s=0;s<e.length;s++){const i=e[s];t.push(this.loadAnimationAsync(`/animations/${i.index}`,i).then((e=>{0===e.targetedAnimations.length&&e.dispose()})))}return Promise.all(t).then((()=>{}))}loadAnimationAsync(e,t){const s=this._extensionsLoadAnimationAsync(e,t);if(s)return s;this._babylonScene._blockEntityCollection=!!this._assetContainer;const i=new va(t.name||`animation${t.index}`,this._babylonScene);i._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,t._babylonAnimationGroup=i;const r=new Array;io.Assign(t.channels),io.Assign(t.samplers);for(const s of t.channels)r.push(this._loadAnimationChannelAsync(`${e}/channels/${s.index}`,e,t,s,((e,t)=>{e.animations=e.animations||[],e.animations.push(t),i.addTargetedAnimation(t,e)})));return Promise.all(r).then((()=>(i.normalize(0),i)))}_loadAnimationChannelAsync(e,t,s,i,r){const n=this._extensionsLoadAnimationChannelAsync(e,t,s,i,r);if(n)return n;if(null==i.target.node)return Promise.resolve();const a=io.Get(`${e}/target/node`,this._gltf.nodes,i.target.node),o=i.target.path,h="weights"===o;if(h&&!a._numMorphTargets||!h&&!a._babylonTransformNode)return Promise.resolve();if(!this._parent.loadNodeAnimations&&!h&&!a._isJoint)return Promise.resolve();let l;switch(o){case"translation":l=to.translation;break;case"rotation":l=to.rotation;break;case"scale":l=to.scale;break;case"weights":l=to.weights;break;default:throw new Error(`${e}/target/path: Invalid value (${i.target.path})`)}const c={object:a,info:l};return this._loadAnimationChannelFromTargetInfoAsync(e,t,s,i,c,r)}_loadAnimationChannelFromTargetInfoAsync(e,t,s,i,r,n){const a=this.parent.targetFps,o=1/a,h=io.Get(`${e}/sampler`,s.samplers,i.sampler);return this._loadAnimationSamplerAsync(`${t}/samplers/${i.sampler}`,h).then((e=>{let t=0;const h=r.object,l=r.info;for(const r of l){const l=r.getStride(h),c=e.input,u=e.output,d=new Array(c.length);let _=0;switch(e.interpolation){case"STEP":for(let e=0;e<c.length;e++){const t=r.getValue(h,u,_,1);_+=l,d[e]={frame:c[e]*a,value:t,interpolation:1}}break;case"CUBICSPLINE":for(let e=0;e<c.length;e++){const t=r.getValue(h,u,_,o);_+=l;const s=r.getValue(h,u,_,1);_+=l;const i=r.getValue(h,u,_,o);_+=l,d[e]={frame:c[e]*a,inTangent:t,value:s,outTangent:i}}break;case"LINEAR":for(let e=0;e<c.length;e++){const t=r.getValue(h,u,_,1);_+=l,d[e]={frame:c[e]*a,value:t}}}if(_>0){const e=`${s.name||`animation${s.index}`}_channel${i.index}_${t}`;r.buildAnimations(h,e,a,d,((e,s)=>{++t,n(e,s)}))}}}))}_loadAnimationSamplerAsync(e,t){if(t._data)return t._data;const s=t.interpolation||"LINEAR";switch(s){case"STEP":case"LINEAR":case"CUBICSPLINE":break;default:throw new Error(`${e}/interpolation: Invalid value (${t.interpolation})`)}const i=io.Get(`${e}/input`,this._gltf.accessors,t.input),r=io.Get(`${e}/output`,this._gltf.accessors,t.output);return t._data=Promise.all([this._loadFloatAccessorAsync(`/accessors/${i.index}`,i),this._loadFloatAccessorAsync(`/accessors/${r.index}`,r)]).then((([e,t])=>({input:e,interpolation:s,output:t}))),t._data}loadBufferAsync(e,t,s,i){const r=this._extensionsLoadBufferAsync(e,t,s,i);if(r)return r;if(!t._data)if(t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{if(!this._bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);t._data=this._bin.readAsync(0,t.byteLength)}return t._data.then((t=>{try{return new Uint8Array(t.buffer,t.byteOffset+s,i)}catch(t){throw new Error(`${e}: ${t.message}`)}}))}loadBufferViewAsync(e,t){const s=this._extensionsLoadBufferViewAsync(e,t);if(s)return s;if(t._data)return t._data;const i=io.Get(`${e}/buffer`,this._gltf.buffers,t.buffer);return t._data=this.loadBufferAsync(`/buffers/${i.index}`,i,t.byteOffset||0,t.byteLength),t._data}_loadAccessorAsync(e,t,s){if(t._data)return t._data;const i=ro._GetNumComponents(e,t.type),r=i*ns.GetTypeByteLength(t.componentType),n=i*t.count;if(null==t.bufferView)t._data=Promise.resolve(new s(n));else{const a=io.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${a.index}`,a).then((o=>{if(5126!==t.componentType||t.normalized||a.byteStride&&a.byteStride!==r){const e=new s(n);return ns.ForEach(o,t.byteOffset||0,a.byteStride||r,i,t.componentType,e.length,t.normalized||!1,((t,s)=>{e[s]=t})),e}return ro._GetTypedArray(e,t.componentType,o,t.byteOffset,n)}))}if(t.sparse){const n=t.sparse;t._data=t._data.then((a=>{const o=a,h=io.Get(`${e}/sparse/indices/bufferView`,this._gltf.bufferViews,n.indices.bufferView),l=io.Get(`${e}/sparse/values/bufferView`,this._gltf.bufferViews,n.values.bufferView);return Promise.all([this.loadBufferViewAsync(`/bufferViews/${h.index}`,h),this.loadBufferViewAsync(`/bufferViews/${l.index}`,l)]).then((([a,h])=>{const l=ro._GetTypedArray(`${e}/sparse/indices`,n.indices.componentType,a,n.indices.byteOffset,n.count),c=i*n.count;let u;if(5126!==t.componentType||t.normalized){const a=ro._GetTypedArray(`${e}/sparse/values`,t.componentType,h,n.values.byteOffset,c);u=new s(c),ns.ForEach(a,0,r,i,t.componentType,u.length,t.normalized||!1,((e,t)=>{u[t]=e}))}else u=ro._GetTypedArray(`${e}/sparse/values`,t.componentType,h,n.values.byteOffset,c);let d=0;for(let e=0;e<l.length;e++){let t=l[e]*i;for(let e=0;e<i;e++)o[t++]=u[d++]}return o}))}))}return t._data}_loadFloatAccessorAsync(e,t){return this._loadAccessorAsync(e,t,Float32Array)}_loadIndicesAccessorAsync(e,t){if("SCALAR"!==t.type)throw new Error(`${e}/type: Invalid value ${t.type}`);if(5121!==t.componentType&&5123!==t.componentType&&5125!==t.componentType)throw new Error(`${e}/componentType: Invalid value ${t.componentType}`);if(t._data)return t._data;if(t.sparse){const s=ro._GetTypedArrayConstructor(`${e}/componentType`,t.componentType);t._data=this._loadAccessorAsync(e,t,s)}else{const s=io.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${s.index}`,s).then((s=>ro._GetTypedArray(e,t.componentType,s,t.byteOffset,t.count)))}return t._data}_loadVertexBufferViewAsync(e){if(e._babylonBuffer)return e._babylonBuffer;const t=this._babylonScene.getEngine();return e._babylonBuffer=this.loadBufferViewAsync(`/bufferViews/${e.index}`,e).then((e=>new rs(t,e,!1))),e._babylonBuffer}_loadVertexAccessorAsync(e,t,s){if(t._babylonVertexBuffer?.[s])return t._babylonVertexBuffer[s];t._babylonVertexBuffer||(t._babylonVertexBuffer={});const i=this._babylonScene.getEngine();if(t.sparse||null==t.bufferView)t._babylonVertexBuffer[s]=this._loadFloatAccessorAsync(e,t).then((e=>new ns(i,e,s,!1)));else{const r=io.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._babylonVertexBuffer[s]=this._loadVertexBufferViewAsync(r).then((n=>{const a=ro._GetNumComponents(e,t.type);return new ns(i,n,s,!1,void 0,r.byteStride,void 0,t.byteOffset,a,t.componentType,t.normalized,!0,void 0,!0)}))}return t._babylonVertexBuffer[s]}_loadMaterialMetallicRoughnessPropertiesAsync(e,t,s){if(!(s instanceof zn))throw new Error(`${e}: Material type not supported`);const i=new Array;return t&&(t.baseColorFactor?(s.albedoColor=ee.FromArray(t.baseColorFactor),s.alpha=t.baseColorFactor[3]):s.albedoColor=ee.White(),s.metallic=null==t.metallicFactor?1:t.metallicFactor,s.roughness=null==t.roughnessFactor?1:t.roughnessFactor,t.baseColorTexture&&i.push(this.loadTextureInfoAsync(`${e}/baseColorTexture`,t.baseColorTexture,(e=>{e.name=`${s.name} (Base Color)`,s.albedoTexture=e}))),t.metallicRoughnessTexture&&(t.metallicRoughnessTexture.nonColorData=!0,i.push(this.loadTextureInfoAsync(`${e}/metallicRoughnessTexture`,t.metallicRoughnessTexture,(e=>{e.name=`${s.name} (Metallic Roughness)`,s.metallicTexture=e}))),s.useMetallnessFromMetallicTextureBlue=!0,s.useRoughnessFromMetallicTextureGreen=!0,s.useRoughnessFromMetallicTextureAlpha=!1)),Promise.all(i).then((()=>{}))}_loadMaterialAsync(e,t,s,i,r=()=>{}){const n=this._extensionsLoadMaterialAsync(e,t,s,i,r);if(n)return n;t._data=t._data||{};let a=t._data[i];if(!a){this.logOpen(`${e} ${t.name||""}`);const s=this.createMaterial(e,t,i);a={babylonMaterial:s,babylonMeshes:[],promise:this.loadMaterialPropertiesAsync(e,t,s)},t._data[i]=a,ro.AddPointerMetadata(s,e),this._parent.onMaterialLoadedObservable.notifyObservers(s),this.logClose()}return s&&(a.babylonMeshes.push(s),s.onDisposeObservable.addOnce((()=>{const e=a.babylonMeshes.indexOf(s);-1!==e&&a.babylonMeshes.splice(e,1)}))),r(a.babylonMaterial),a.promise.then((()=>a.babylonMaterial))}_createDefaultMaterial(e,t){this._babylonScene._blockEntityCollection=!!this._assetContainer;const s=new zn(e,this._babylonScene);return s._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,s.fillMode=t,s.enableSpecularAntiAliasing=!0,s.useRadianceOverAlpha=!this._parent.transparencyAsCoverage,s.useSpecularOverAlpha=!this._parent.transparencyAsCoverage,s.transparencyMode=zn.PBRMATERIAL_OPAQUE,s.metallic=1,s.roughness=1,s}createMaterial(e,t,s){const i=this._extensionsCreateMaterial(e,t,s);if(i)return i;const r=t.name||`material${t.index}`;return this._createDefaultMaterial(r,s)}loadMaterialPropertiesAsync(e,t,s){const i=this._extensionsLoadMaterialPropertiesAsync(e,t,s);if(i)return i;const r=new Array;return r.push(this.loadMaterialBasePropertiesAsync(e,t,s)),t.pbrMetallicRoughness&&r.push(this._loadMaterialMetallicRoughnessPropertiesAsync(`${e}/pbrMetallicRoughness`,t.pbrMetallicRoughness,s)),this.loadMaterialAlphaProperties(e,t,s),Promise.all(r).then((()=>{}))}loadMaterialBasePropertiesAsync(e,t,s){if(!(s instanceof zn))throw new Error(`${e}: Material type not supported`);const i=new Array;return s.emissiveColor=t.emissiveFactor?ee.FromArray(t.emissiveFactor):new ee(0,0,0),t.doubleSided&&(s.backFaceCulling=!1,s.twoSidedLighting=!0),t.normalTexture&&(t.normalTexture.nonColorData=!0,i.push(this.loadTextureInfoAsync(`${e}/normalTexture`,t.normalTexture,(e=>{e.name=`${s.name} (Normal)`,s.bumpTexture=e}))),s.invertNormalMapX=!this._babylonScene.useRightHandedSystem,s.invertNormalMapY=this._babylonScene.useRightHandedSystem,null!=t.normalTexture.scale&&s.bumpTexture&&(s.bumpTexture.level=t.normalTexture.scale),s.forceIrradianceInFragment=!0),t.occlusionTexture&&(t.occlusionTexture.nonColorData=!0,i.push(this.loadTextureInfoAsync(`${e}/occlusionTexture`,t.occlusionTexture,(e=>{e.name=`${s.name} (Occlusion)`,s.ambientTexture=e}))),s.useAmbientInGrayScale=!0,null!=t.occlusionTexture.strength&&(s.ambientTextureStrength=t.occlusionTexture.strength)),t.emissiveTexture&&i.push(this.loadTextureInfoAsync(`${e}/emissiveTexture`,t.emissiveTexture,(e=>{e.name=`${s.name} (Emissive)`,s.emissiveTexture=e}))),Promise.all(i).then((()=>{}))}loadMaterialAlphaProperties(e,t,s){if(!(s instanceof zn))throw new Error(`${e}: Material type not supported`);switch(t.alphaMode||"OPAQUE"){case"OPAQUE":s.transparencyMode=zn.PBRMATERIAL_OPAQUE,s.alpha=1;break;case"MASK":s.transparencyMode=zn.PBRMATERIAL_ALPHATEST,s.alphaCutOff=null==t.alphaCutoff?.5:t.alphaCutoff,s.albedoTexture&&(s.albedoTexture.hasAlpha=!0);break;case"BLEND":s.transparencyMode=zn.PBRMATERIAL_ALPHABLEND,s.albedoTexture&&(s.albedoTexture.hasAlpha=!0,s.useAlphaFromAlbedoTexture=!0);break;default:throw new Error(`${e}/alphaMode: Invalid value (${t.alphaMode})`)}}loadTextureInfoAsync(e,t,s=()=>{}){const i=this._extensionsLoadTextureInfoAsync(e,t,s);if(i)return i;if(this.logOpen(`${e}`),t.texCoord>=6)throw new Error(`${e}/texCoord: Invalid value (${t.texCoord})`);const r=io.Get(`${e}/index`,this._gltf.textures,t.index);r._textureInfo=t;const n=this._loadTextureAsync(`/textures/${t.index}`,r,(i=>{i.coordinatesIndex=t.texCoord||0,ro.AddPointerMetadata(i,e),this._parent.onTextureLoadedObservable.notifyObservers(i),s(i)}));return this.logClose(),n}_loadTextureAsync(e,t,s=()=>{}){const i=this._extensionsLoadTextureAsync(e,t,s);if(i)return i;this.logOpen(`${e} ${t.name||""}`);const r=null==t.sampler?ro.DefaultSampler:io.Get(`${e}/sampler`,this._gltf.samplers,t.sampler),n=io.Get(`${e}/source`,this._gltf.images,t.source),a=this._createTextureAsync(e,r,n,s,void 0,!t._textureInfo.nonColorData);return this.logClose(),a}_createTextureAsync(e,t,s,i=()=>{},r,n){const a=this._loadSampler(`/samplers/${t.index}`,t),o=new Array,h=new na;this._babylonScene._blockEntityCollection=!!this._assetContainer;const l={noMipmap:a.noMipMaps,invertY:!1,samplingMode:a.samplingMode,onLoad:()=>{this._disposed||h.resolve()},onError:(t,s)=>{this._disposed||h.reject(new Error(`${e}: ${s&&s.message?s.message:t||"Failed to load texture"}`))},mimeType:s.mimeType,loaderOptions:r,useSRGBBuffer:!!n&&this._parent.useSRGBBuffers},c=new Dr(null,this._babylonScene,l);return c._parentContainer=this._assetContainer,this._babylonScene._blockEntityCollection=!1,o.push(h.promise),o.push(this.loadImageAsync(`/images/${s.index}`,s).then((e=>{const t=s.uri||`${this._fileName}#image${s.index}`,i=`data:${this._uniqueRootUrl}${t}`;c.updateURL(i,e)}))),c.wrapU=a.wrapU,c.wrapV=a.wrapV,i(c),Promise.all(o).then((()=>c))}_loadSampler(e,t){return t._data||(t._data={noMipMaps:9728===t.minFilter||9729===t.minFilter,samplingMode:ro._GetTextureSamplingMode(e,t),wrapU:ro._GetTextureWrapMode(`${e}/wrapS`,t.wrapS),wrapV:ro._GetTextureWrapMode(`${e}/wrapT`,t.wrapT)}),t._data}loadImageAsync(e,t){if(!t._data){if(this.logOpen(`${e} ${t.name||""}`),t.uri)t._data=this.loadUriAsync(`${e}/uri`,t,t.uri);else{const s=io.Get(`${e}/bufferView`,this._gltf.bufferViews,t.bufferView);t._data=this.loadBufferViewAsync(`/bufferViews/${s.index}`,s)}this.logClose()}return t._data}loadUriAsync(e,t,s){const i=this._extensionsLoadUriAsync(e,t,s);if(i)return i;if(!ro._ValidateUri(s))throw new Error(`${e}: '${s}' is invalid`);if(Lt(s)){const t=new Uint8Array(Nt(s));return this.log(`${e}: Decoded ${s.substr(0,64)}... (${t.length} bytes)`),Promise.resolve(t)}return this.log(`${e}: Loading ${s}`),this._parent.preprocessUrlAsync(this._rootUrl+s).then((t=>new Promise(((i,r)=>{this._parent._loadFile(this._babylonScene,t,(t=>{this._disposed||(this.log(`${e}: Loaded ${s} (${t.byteLength} bytes)`),i(new Uint8Array(t)))}),!0,(t=>{r(new Rt(`${e}: Failed to load '${s}'${t?": "+t.status+" "+t.statusText:""}`,t))}))}))))}static AddPointerMetadata(e,t){e.metadata=e.metadata||{};const s=e._internalMetadata=e._internalMetadata||{},i=s.gltf=s.gltf||{};(i.pointers=i.pointers||[]).push(t)}static _GetTextureWrapMode(e,t){switch(t=null==t?10497:t){case 33071:return Dr.CLAMP_ADDRESSMODE;case 33648:return Dr.MIRROR_ADDRESSMODE;case 10497:return Dr.WRAP_ADDRESSMODE;default:return ue.Warn(`${e}: Invalid value (${t})`),Dr.WRAP_ADDRESSMODE}}static _GetTextureSamplingMode(e,t){const s=null==t.magFilter?9729:t.magFilter,i=null==t.minFilter?9987:t.minFilter;if(9729===s)switch(i){case 9728:return Dr.LINEAR_NEAREST;case 9729:return Dr.LINEAR_LINEAR;case 9984:return Dr.LINEAR_NEAREST_MIPNEAREST;case 9985:return Dr.LINEAR_LINEAR_MIPNEAREST;case 9986:return Dr.LINEAR_NEAREST_MIPLINEAR;case 9987:return Dr.LINEAR_LINEAR_MIPLINEAR;default:return ue.Warn(`${e}/minFilter: Invalid value (${i})`),Dr.LINEAR_LINEAR_MIPLINEAR}else switch(9728!==s&&ue.Warn(`${e}/magFilter: Invalid value (${s})`),i){case 9728:return Dr.NEAREST_NEAREST;case 9729:return Dr.NEAREST_LINEAR;case 9984:return Dr.NEAREST_NEAREST_MIPNEAREST;case 9985:return Dr.NEAREST_LINEAR_MIPNEAREST;case 9986:return Dr.NEAREST_NEAREST_MIPLINEAR;case 9987:return Dr.NEAREST_LINEAR_MIPLINEAR;default:return ue.Warn(`${e}/minFilter: Invalid value (${i})`),Dr.NEAREST_NEAREST_MIPNEAREST}}static _GetTypedArrayConstructor(e,t){switch(t){case 5120:return Int8Array;case 5121:return Uint8Array;case 5122:return Int16Array;case 5123:return Uint16Array;case 5125:return Uint32Array;case 5126:return Float32Array;default:throw new Error(`${e}: Invalid component type ${t}`)}}static _GetTypedArray(e,t,s,i,r){const n=s.buffer;i=s.byteOffset+(i||0);const a=ro._GetTypedArrayConstructor(`${e}/componentType`,t),o=ns.GetTypeByteLength(t);return i%o!=0?(ue.Warn(`${e}: Copying buffer as byte offset (${i}) is not a multiple of component type byte length (${o})`),new a(n.slice(i,i+r*o),0)):new a(n,i,r)}static _GetNumComponents(e,t){switch(t){case"SCALAR":return 1;case"VEC2":return 2;case"VEC3":return 3;case"VEC4":case"MAT2":return 4;case"MAT3":return 9;case"MAT4":return 16}throw new Error(`${e}: Invalid type (${t})`)}static _ValidateUri(e){return Yt.IsBase64(e)||-1===e.indexOf("..")}static _GetDrawMode(e,t){switch(null==t&&(t=4),t){case 0:return $s.PointListDrawMode;case 1:return $s.LineListDrawMode;case 2:return $s.LineLoopDrawMode;case 3:return $s.LineStripDrawMode;case 4:return $s.TriangleFillMode;case 5:return $s.TriangleStripDrawMode;case 6:return $s.TriangleFanDrawMode}throw new Error(`${e}: Invalid mesh primitive mode (${t})`)}_compileMaterialsAsync(){this._parent._startPerformanceCounter("Compile materials");const e=new Array;if(this._gltf.materials)for(const t of this._gltf.materials)if(t._data)for(const s in t._data){const i=t._data[s];for(const t of i.babylonMeshes){t.computeWorldMatrix(!0);const s=i.babylonMaterial;e.push(s.forceCompilationAsync(t)),e.push(s.forceCompilationAsync(t,{useInstances:!0})),this._parent.useClipPlane&&(e.push(s.forceCompilationAsync(t,{clipPlane:!0})),e.push(s.forceCompilationAsync(t,{clipPlane:!0,useInstances:!0})))}}return Promise.all(e).then((()=>{this._parent._endPerformanceCounter("Compile materials")}))}_compileShadowGeneratorsAsync(){this._parent._startPerformanceCounter("Compile shadow generators");const e=new Array,t=this._babylonScene.lights;for(const s of t){const t=s.getShadowGenerator();t&&e.push(t.forceCompilationAsync())}return Promise.all(e).then((()=>{this._parent._endPerformanceCounter("Compile shadow generators")}))}_forEachExtensions(e){for(const t of this._extensions)t.enabled&&e(t)}_applyExtensions(e,t,s){for(const i of this._extensions)if(i.enabled){const r=`${i.name}.${t}`,n=e;n._activeLoaderExtensionFunctions=n._activeLoaderExtensionFunctions||{};const a=n._activeLoaderExtensionFunctions;if(!a[r]){a[r]=!0;try{const e=s(i);if(e)return e}finally{delete a[r]}}}return null}_extensionsOnLoading(){this._forEachExtensions((e=>e.onLoading&&e.onLoading()))}_extensionsOnReady(){this._forEachExtensions((e=>e.onReady&&e.onReady()))}_extensionsLoadSceneAsync(e,t){return this._applyExtensions(t,"loadScene",(s=>s.loadSceneAsync&&s.loadSceneAsync(e,t)))}_extensionsLoadNodeAsync(e,t,s){return this._applyExtensions(t,"loadNode",(i=>i.loadNodeAsync&&i.loadNodeAsync(e,t,s)))}_extensionsLoadCameraAsync(e,t,s){return this._applyExtensions(t,"loadCamera",(i=>i.loadCameraAsync&&i.loadCameraAsync(e,t,s)))}_extensionsLoadVertexDataAsync(e,t,s){return this._applyExtensions(t,"loadVertexData",(i=>i._loadVertexDataAsync&&i._loadVertexDataAsync(e,t,s)))}_extensionsLoadMeshPrimitiveAsync(e,t,s,i,r,n){return this._applyExtensions(r,"loadMeshPrimitive",(a=>a._loadMeshPrimitiveAsync&&a._loadMeshPrimitiveAsync(e,t,s,i,r,n)))}_extensionsLoadMaterialAsync(e,t,s,i,r){return this._applyExtensions(t,"loadMaterial",(n=>n._loadMaterialAsync&&n._loadMaterialAsync(e,t,s,i,r)))}_extensionsCreateMaterial(e,t,s){return this._applyExtensions(t,"createMaterial",(i=>i.createMaterial&&i.createMaterial(e,t,s)))}_extensionsLoadMaterialPropertiesAsync(e,t,s){return this._applyExtensions(t,"loadMaterialProperties",(i=>i.loadMaterialPropertiesAsync&&i.loadMaterialPropertiesAsync(e,t,s)))}_extensionsLoadTextureInfoAsync(e,t,s){return this._applyExtensions(t,"loadTextureInfo",(i=>i.loadTextureInfoAsync&&i.loadTextureInfoAsync(e,t,s)))}_extensionsLoadTextureAsync(e,t,s){return this._applyExtensions(t,"loadTexture",(i=>i._loadTextureAsync&&i._loadTextureAsync(e,t,s)))}_extensionsLoadAnimationAsync(e,t){return this._applyExtensions(t,"loadAnimation",(s=>s.loadAnimationAsync&&s.loadAnimationAsync(e,t)))}_extensionsLoadAnimationChannelAsync(e,t,s,i,r){return this._applyExtensions(s,"loadAnimationChannel",(n=>n._loadAnimationChannelAsync&&n._loadAnimationChannelAsync(e,t,s,i,r)))}_extensionsLoadSkinAsync(e,t,s){return this._applyExtensions(s,"loadSkin",(i=>i._loadSkinAsync&&i._loadSkinAsync(e,t,s)))}_extensionsLoadUriAsync(e,t,s){return this._applyExtensions(t,"loadUri",(i=>i._loadUriAsync&&i._loadUriAsync(e,t,s)))}_extensionsLoadBufferViewAsync(e,t){return this._applyExtensions(t,"loadBufferView",(s=>s.loadBufferViewAsync&&s.loadBufferViewAsync(e,t)))}_extensionsLoadBufferAsync(e,t,s,i){return this._applyExtensions(t,"loadBuffer",(r=>r.loadBufferAsync&&r.loadBufferAsync(e,t,s,i)))}static LoadExtensionAsync(e,t,s,i){if(!t.extensions)return null;const r=t.extensions[s];return r?i(`${e}/extensions/${s}`,r):null}static LoadExtraAsync(e,t,s,i){if(!t.extras)return null;const r=t.extras[s];return r?i(`${e}/extras/${s}`,r):null}isExtensionUsed(e){return!!this._gltf.extensionsUsed&&-1!==this._gltf.extensionsUsed.indexOf(e)}logOpen(e){this._parent._logOpen(e)}logClose(){this._parent._logClose()}log(e){this._parent._log(e)}startPerformanceCounter(e){this._parent._startPerformanceCounter(e)}endPerformanceCounter(e){this._parent._endPerformanceCounter(e)}}ro._RegisteredExtensions={},ro.DefaultSampler={index:-1},Za._CreateGLTF2Loader=e=>new ro(e);class no extends $n{constructor(e,t,s,i=Ze.TEXTUREFORMAT_RGBA,r=Ze.TEXTURETYPE_UNSIGNED_INT,n=!1,a=!1,o=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,h=null){super("",e),this._texture=e.getEngine().createRawCubeTexture(t,s,i,r,n,a,o,h)}update(e,t,s,i,r=null){this._texture.getEngine().updateRawCubeTexture(this._texture,e,t,s,i,r)}updateRGBDAsync(e,t=null,s=.8,i=0){return function(e,t,s,i,r){const n=ga(e.getEngine().createRawCubeTexture(null,e.width,e.format,e.type,e.generateMipMaps,e.invertY,e.samplingMode,e._compression),t).then((()=>e));return e.onRebuildCallback=e=>({proxy:n,isReady:!0,isAsync:!0}),e._source=13,e._bufferViewArrayArray=t,e._lodGenerationScale=i,e._lodGenerationOffset=r,e._sphericalPolynomial=s,ga(e,t).then((()=>(e.isReady=!0,e)))}(this._texture,e,t,s,i).then((()=>{}))}clone(){return re.Clone((()=>{const e=this.getScene(),t=this._texture,s=new no(e,t._bufferViewArray,t.width,t.format,t.type,t.generateMipMaps,t.invertY,t.samplingMode,t._compression);return 13===t.source&&s.updateRGBDAsync(t._bufferViewArrayArray,t._sphericalPolynomial,t._lodGenerationScale,t._lodGenerationOffset),s}),this)}}const ao="EXT_lights_image_based";class oo{constructor(e){this.name=ao,this._loader=e,this.enabled=this._loader.isExtensionUsed(ao)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights}}loadSceneAsync(e,t){return ro.LoadExtensionAsync(e,t,this.name,((s,i)=>{this._loader._allMaterialsDirtyRequired=!0;const r=new Array;r.push(this._loader.loadSceneAsync(e,t)),this._loader.logOpen(`${s}`);const n=io.Get(`${s}/light`,this._lights,i.light);return r.push(this._loadLightAsync(`/extensions/${this.name}/lights/${i.light}`,n).then((e=>{this._loader.babylonScene.environmentTexture=e}))),this._loader.logClose(),Promise.all(r).then((()=>{}))}))}_loadLightAsync(e,t){if(!t._loaded){const s=new Array;this._loader.logOpen(`${e}`);const i=new Array(t.specularImages.length);for(let r=0;r<t.specularImages.length;r++){const n=t.specularImages[r];i[r]=new Array(n.length);for(let t=0;t<n.length;t++){const a=`${e}/specularImages/${r}/${t}`;this._loader.logOpen(`${a}`);const o=n[t],h=io.Get(a,this._loader.gltf.images,o);s.push(this._loader.loadImageAsync(`/images/${o}`,h).then((e=>{i[r][t]=e}))),this._loader.logClose()}}this._loader.logClose(),t._loaded=Promise.all(s).then((()=>{const s=new no(this._loader.babylonScene,null,t.specularImageSize);if(s.name=t.name||"environment",t._babylonTexture=s,null!=t.intensity&&(s.level=t.intensity),t.rotation){let e=G.FromArray(t.rotation);this._loader.babylonScene.useRightHandedSystem||(e=G.Inverse(e)),V.FromQuaternionToRef(e,s.getReflectionTextureMatrix())}if(!t.irradianceCoefficients)throw new Error(`${e}: Irradiance coefficients are missing`);const r=Rn.FromArray(t.irradianceCoefficients);r.scaleInPlace(t.intensity),r.convertIrradianceToLambertianRadiance();const n=xn.FromHarmonics(r),a=(i.length-1)/Q.Log2(t.specularImageSize);return s.updateRGBDAsync(i,n,a)}))}return t._loaded.then((()=>t._babylonTexture))}}ro.RegisterExtension(ao,(e=>new oo(e))),oi.prototype.thinInstanceAdd=function(e,t=!0){if(!this.getScene().getEngine().getCaps().instancedArrays)return ue.Error("Thin Instances are not supported on this device as Instanced Array extension not supported"),-1;this._thinInstanceUpdateBufferSize("matrix",Array.isArray(e)?e.length:1);const s=this._thinInstanceDataStorage.instancesCount;if(Array.isArray(e))for(let s=0;s<e.length;++s)this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++,e[s],s===e.length-1&&t);else this.thinInstanceSetMatrixAt(this._thinInstanceDataStorage.instancesCount++,e,t);return s},oi.prototype.thinInstanceAddSelf=function(e=!0){return this.thinInstanceAdd(V.IdentityReadOnly,e)},oi.prototype.thinInstanceRegisterAttribute=function(e,t){e===ns.ColorKind&&(e=ns.ColorInstanceKind),this.removeVerticesData(e),this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.strides[e]=t,this._userThinInstanceBuffersStorage.sizes[e]=t*Math.max(32,this._thinInstanceDataStorage.instancesCount),this._userThinInstanceBuffersStorage.data[e]=new Float32Array(this._userThinInstanceBuffersStorage.sizes[e]),this._userThinInstanceBuffersStorage.vertexBuffers[e]=new ns(this.getEngine(),this._userThinInstanceBuffersStorage.data[e],e,!0,!1,t,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])},oi.prototype.thinInstanceSetMatrixAt=function(e,t,s=!0){if(!this._thinInstanceDataStorage.matrixData||e>=this._thinInstanceDataStorage.instancesCount)return!1;const i=this._thinInstanceDataStorage.matrixData;return t.copyToArray(i,16*e),this._thinInstanceDataStorage.worldMatrices&&(this._thinInstanceDataStorage.worldMatrices[e]=t),s&&(this.thinInstanceBufferUpdated("matrix"),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)),!0},oi.prototype.thinInstanceSetAttributeAt=function(e,t,s,i=!0){return e===ns.ColorKind&&(e=ns.ColorInstanceKind),!(!this._userThinInstanceBuffersStorage||!this._userThinInstanceBuffersStorage.data[e]||t>=this._thinInstanceDataStorage.instancesCount)&&(this._thinInstanceUpdateBufferSize(e,0),this._userThinInstanceBuffersStorage.data[e].set(s,t*this._userThinInstanceBuffersStorage.strides[e]),i&&this.thinInstanceBufferUpdated(e),!0)},Object.defineProperty(oi.prototype,"thinInstanceCount",{get:function(){return this._thinInstanceDataStorage.instancesCount},set:function(e){const t=this._thinInstanceDataStorage.matrixData??this.source?._thinInstanceDataStorage.matrixData;e<=(t?t.length/16:0)&&(this._thinInstanceDataStorage.instancesCount=e)},enumerable:!0,configurable:!0}),oi.prototype._thinInstanceCreateMatrixBuffer=function(e,t,s=!0){const i=new rs(this.getEngine(),t,!s,16,!1,!0);for(let t=0;t<4;t++)this.setVerticesBuffer(i.createVertexBuffer(e+t,4*t,4));return i},oi.prototype.thinInstanceSetBuffer=function(e,t,s=0,i=!0){s=s||16,"matrix"===e?(this._thinInstanceDataStorage.matrixBuffer?.dispose(),this._thinInstanceDataStorage.matrixBuffer=null,this._thinInstanceDataStorage.matrixBufferSize=t?t.length:32*s,this._thinInstanceDataStorage.matrixData=t,this._thinInstanceDataStorage.worldMatrices=null,null!==t?(this._thinInstanceDataStorage.instancesCount=t.length/s,this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",t,i),this.doNotSyncBoundingInfo||this.thinInstanceRefreshBoundingInfo(!1)):(this._thinInstanceDataStorage.instancesCount=0,this.doNotSyncBoundingInfo||this.refreshBoundingInfo())):"previousMatrix"===e?(this._thinInstanceDataStorage.previousMatrixBuffer?.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=null,this._thinInstanceDataStorage.previousMatrixData=t,null!==t&&(this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",t,i))):(e===ns.ColorKind&&(e=ns.ColorInstanceKind),null===t?this._userThinInstanceBuffersStorage?.data[e]&&(this.removeVerticesData(e),delete this._userThinInstanceBuffersStorage.data[e],delete this._userThinInstanceBuffersStorage.strides[e],delete this._userThinInstanceBuffersStorage.sizes[e],delete this._userThinInstanceBuffersStorage.vertexBuffers[e]):(this._thinInstanceInitializeUserStorage(),this._userThinInstanceBuffersStorage.data[e]=t,this._userThinInstanceBuffersStorage.strides[e]=s,this._userThinInstanceBuffersStorage.sizes[e]=t.length,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new ns(this.getEngine(),t,e,!i,!1,s,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e])))},oi.prototype.thinInstanceBufferUpdated=function(e){"matrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.matrixBuffer&&!this._thinInstanceDataStorage.matrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._thinInstanceDataStorage.matrixBuffer?.updateDirectly(this._thinInstanceDataStorage.matrixData,0,this._thinInstanceDataStorage.instancesCount)):"previousMatrix"===e?(this.thinInstanceAllowAutomaticStaticBufferRecreation&&this._thinInstanceDataStorage.previousMatrixBuffer&&!this._thinInstanceDataStorage.previousMatrixBuffer.isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._thinInstanceDataStorage.previousMatrixBuffer?.updateDirectly(this._thinInstanceDataStorage.previousMatrixData,0,this._thinInstanceDataStorage.instancesCount)):(e===ns.ColorKind&&(e=ns.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&(this.thinInstanceAllowAutomaticStaticBufferRecreation&&!this._userThinInstanceBuffersStorage.vertexBuffers[e].isUpdatable()&&this._thinInstanceRecreateBuffer(e),this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(this._userThinInstanceBuffersStorage.data[e],0)))},oi.prototype.thinInstancePartialBufferUpdate=function(e,t,s){"matrix"===e?this._thinInstanceDataStorage.matrixBuffer&&this._thinInstanceDataStorage.matrixBuffer.updateDirectly(t,s):(e===ns.ColorKind&&(e=ns.ColorInstanceKind),this._userThinInstanceBuffersStorage?.vertexBuffers[e]&&this._userThinInstanceBuffersStorage.vertexBuffers[e].updateDirectly(t,s))},oi.prototype.thinInstanceGetWorldMatrices=function(){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return[];const e=this._thinInstanceDataStorage.matrixData;if(!this._thinInstanceDataStorage.worldMatrices){this._thinInstanceDataStorage.worldMatrices=[];for(let t=0;t<this._thinInstanceDataStorage.instancesCount;++t)this._thinInstanceDataStorage.worldMatrices[t]=V.FromArray(e,16*t)}return this._thinInstanceDataStorage.worldMatrices},oi.prototype.thinInstanceRefreshBoundingInfo=function(e=!1,t=!1,s=!1){if(!this._thinInstanceDataStorage.matrixData||!this._thinInstanceDataStorage.matrixBuffer)return;const i=this._thinInstanceDataStorage.boundingVectors;if(e||!this.rawBoundingInfo){i.length=0,this.refreshBoundingInfo(t,s);const e=this.getBoundingInfo();this.rawBoundingInfo=new _s(e.minimum,e.maximum)}const r=this.getBoundingInfo(),n=this._thinInstanceDataStorage.matrixData;if(0===i.length)for(let e=0;e<r.boundingBox.vectors.length;++e)i.push(r.boundingBox.vectors[e].clone());z.Vector3[0].setAll(Number.POSITIVE_INFINITY),z.Vector3[1].setAll(Number.NEGATIVE_INFINITY);for(let e=0;e<this._thinInstanceDataStorage.instancesCount;++e){V.FromArrayToRef(n,16*e,z.Matrix[0]);for(let e=0;e<i.length;++e)U.TransformCoordinatesToRef(i[e],z.Matrix[0],z.Vector3[2]),z.Vector3[0].minimizeInPlace(z.Vector3[2]),z.Vector3[1].maximizeInPlace(z.Vector3[2])}r.reConstruct(z.Vector3[0],z.Vector3[1]),this._updateBoundingInfo()},oi.prototype._thinInstanceRecreateBuffer=function(e,t=!0){"matrix"===e?(this._thinInstanceDataStorage.matrixBuffer?.dispose(),this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",this._thinInstanceDataStorage.matrixData,t)):"previousMatrix"===e?this._scene.needsPreviousWorldMatrices&&(this._thinInstanceDataStorage.previousMatrixBuffer?.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",this._thinInstanceDataStorage.previousMatrixData??this._thinInstanceDataStorage.matrixData,t)):(e===ns.ColorKind&&(e=ns.ColorInstanceKind),this._userThinInstanceBuffersStorage.vertexBuffers[e]?.dispose(),this._userThinInstanceBuffersStorage.vertexBuffers[e]=new ns(this.getEngine(),this._userThinInstanceBuffersStorage.data[e],e,!t,!1,this._userThinInstanceBuffersStorage.strides[e],!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e]))},oi.prototype._thinInstanceUpdateBufferSize=function(e,t=1){e===ns.ColorKind&&(e=ns.ColorInstanceKind);const s="matrix"===e;if(!(s||this._userThinInstanceBuffersStorage&&this._userThinInstanceBuffersStorage.strides[e]))return;const i=s?16:this._userThinInstanceBuffersStorage.strides[e],r=s?this._thinInstanceDataStorage.matrixBufferSize:this._userThinInstanceBuffersStorage.sizes[e];let n=s?this._thinInstanceDataStorage.matrixData:this._userThinInstanceBuffersStorage.data[e];const a=(this._thinInstanceDataStorage.instancesCount+t)*i;let o=r;for(;o<a;)o*=2;if(!n||r!=o){if(n){const e=new Float32Array(o);e.set(n,0),n=e}else n=new Float32Array(o);s?(this._thinInstanceDataStorage.matrixBuffer?.dispose(),this._thinInstanceDataStorage.matrixBuffer=this._thinInstanceCreateMatrixBuffer("world",n,!1),this._thinInstanceDataStorage.matrixData=n,this._thinInstanceDataStorage.matrixBufferSize=o,this._scene.needsPreviousWorldMatrices&&!this._thinInstanceDataStorage.previousMatrixData&&(this._thinInstanceDataStorage.previousMatrixBuffer?.dispose(),this._thinInstanceDataStorage.previousMatrixBuffer=this._thinInstanceCreateMatrixBuffer("previousWorld",n,!1))):(this._userThinInstanceBuffersStorage.vertexBuffers[e]?.dispose(),this._userThinInstanceBuffersStorage.data[e]=n,this._userThinInstanceBuffersStorage.sizes[e]=o,this._userThinInstanceBuffersStorage.vertexBuffers[e]=new ns(this.getEngine(),n,e,!0,!1,i,!0),this.setVerticesBuffer(this._userThinInstanceBuffersStorage.vertexBuffers[e]))}},oi.prototype._thinInstanceInitializeUserStorage=function(){this._userThinInstanceBuffersStorage||(this._userThinInstanceBuffersStorage={data:{},sizes:{},vertexBuffers:{},strides:{}})},oi.prototype._disposeThinInstanceSpecificData=function(){this._thinInstanceDataStorage?.matrixBuffer&&(this._thinInstanceDataStorage.matrixBuffer.dispose(),this._thinInstanceDataStorage.matrixBuffer=null)};const ho="EXT_mesh_gpu_instancing";class lo{constructor(e){this.name=ho,this._loader=e,this.enabled=this._loader.isExtensionUsed(ho)}dispose(){this._loader=null}loadNodeAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((e,i)=>{this._loader._disableInstancedMesh++;const r=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,s);if(this._loader._disableInstancedMesh--,!t._primitiveBabylonMeshes)return r;const n=new Array;let a=0;const o=t=>{if(null==i.attributes[t])return void n.push(Promise.resolve(null));const s=io.Get(`${e}/attributes/${t}`,this._loader.gltf.accessors,i.attributes[t]);if(n.push(this._loader._loadFloatAccessorAsync(`/accessors/${s.bufferView}`,s)),0===a)a=s.count;else if(a!==s.count)throw new Error(`${e}/attributes: Instance buffer accessors do not have the same count.`)};return o("TRANSLATION"),o("ROTATION"),o("SCALE"),r.then((e=>Promise.all(n).then((([s,i,r])=>{const n=new Float32Array(16*a);z.Vector3[0].copyFromFloats(0,0,0),z.Quaternion[0].copyFromFloats(0,0,0,1),z.Vector3[1].copyFromFloats(1,1,1);for(let e=0;e<a;++e)s&&U.FromArrayToRef(s,3*e,z.Vector3[0]),i&&G.FromArrayToRef(i,4*e,z.Quaternion[0]),r&&U.FromArrayToRef(r,3*e,z.Vector3[1]),V.ComposeToRef(z.Vector3[1],z.Quaternion[0],z.Vector3[0],z.Matrix[0]),z.Matrix[0].copyToArray(n,16*e);for(const e of t._primitiveBabylonMeshes)e.thinInstanceSetBuffer("matrix",n,16,!0);return e}))))}))}}ro.RegisterExtension(ho,(e=>new lo(e)));class co{static get Default(){return co._Default||(co._Default=new co),co._Default}constructor(){const e=co.Configuration.decoder;this._decoderModulePromise=Yt.LoadBabylonScriptAsync(e.url).then((()=>MeshoptDecoder.ready))}dispose(){delete this._decoderModulePromise}decodeGltfBufferAsync(e,t,s,i,r){return this._decoderModulePromise.then((async()=>{MeshoptDecoder.useWorkers(1);const n=await MeshoptDecoder.decodeGltfBufferAsync(t,s,e,i,r);return MeshoptDecoder.useWorkers(0),n}))}}co.Configuration={decoder:{url:`${Yt._DefaultCdnUrl}/meshopt_decoder.js`}},co._Default=null;const uo="EXT_meshopt_compression";class _o{constructor(e){this.name=uo,this.enabled=e.isExtensionUsed(uo),this._loader=e}dispose(){this._loader=null}loadBufferViewAsync(e,t){return ro.LoadExtensionAsync(e,t,this.name,((s,i)=>{const r=t;if(r._meshOptData)return r._meshOptData;const n=io.Get(`${e}/buffer`,this._loader.gltf.buffers,i.buffer);return r._meshOptData=this._loader.loadBufferAsync(`/buffers/${n.index}`,n,i.byteOffset||0,i.byteLength).then((e=>co.Default.decodeGltfBufferAsync(e,i.count,i.byteStride,i.mode,i.filter))),r._meshOptData}))}}ro.RegisterExtension(uo,(e=>new _o(e)));const fo="EXT_texture_webp";class po{constructor(e){this.name=fo,this._loader=e,this.enabled=e.isExtensionUsed(fo)}dispose(){this._loader=null}_loadTextureAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((i,r)=>{const n=null==t.sampler?ro.DefaultSampler:io.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),a=io.Get(`${i}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,a,(e=>{s(e)}),void 0,!t._textureInfo.nonColorData)}))}}ro.RegisterExtension(fo,(e=>new po(e)));const mo="EXT_texture_avif";class go{constructor(e){this.name=mo,this._loader=e,this.enabled=e.isExtensionUsed(mo)}dispose(){this._loader=null}_loadTextureAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((i,r)=>{const n=null==t.sampler?ro.DefaultSampler:io.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),a=io.Get(`${i}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,a,(e=>{s(e)}),void 0,!t._textureInfo.nonColorData)}))}}ro.RegisterExtension(mo,(e=>new go(e)));class To{constructor(e){this._pendingActions=new Array,this._workerInfos=e.map((e=>({workerPromise:Promise.resolve(e),idle:!0})))}dispose(){for(const e of this._workerInfos)e.workerPromise.then((e=>{e.terminate()}));this._workerInfos.length=0,this._pendingActions.length=0}push(e){this._executeOnIdleWorker(e)||this._pendingActions.push(e)}_executeOnIdleWorker(e){for(const t of this._workerInfos)if(t.idle)return this._execute(t,e),!0;return!1}_execute(e,t){e.idle=!1,e.workerPromise.then((s=>{t(s,(()=>{const t=this._pendingActions.shift();t?this._execute(e,t):e.idle=!0}))}))}}class Eo extends To{constructor(e,t,s=Eo.DefaultOptions){super([]),this._maxWorkers=e,this._createWorkerAsync=t,this._options=s}push(e){if(!this._executeOnIdleWorker(e))if(this._workerInfos.length<this._maxWorkers){const t={workerPromise:this._createWorkerAsync(),idle:!1};this._workerInfos.push(t),this._execute(t,e)}else this._pendingActions.push(e)}_execute(e,t){e.timeoutId&&(clearTimeout(e.timeoutId),delete e.timeoutId),super._execute(e,((s,i)=>{t(s,(()=>{i(),e.idle&&(e.timeoutId=setTimeout((()=>{e.workerPromise.then((e=>{e.terminate()}));const t=this._workerInfos.indexOf(e);-1!==t&&this._workerInfos.splice(t,1)}),this._options.idleTimeElapsedBeforeRelease))}))}))}}function Ao(e,t,s,i,r){let n=null,a=null,o=null;try{let h;n=new e.Decoder,a=new e.DecoderBuffer,a.Init(t,t.byteLength);const l=n.GetEncodedGeometryType(a);switch(l){case e.TRIANGULAR_MESH:{const t=new e.Mesh;if(h=n.DecodeBufferToMesh(a,t),!h.ok()||0===t.ptr)throw new Error(h.error_msg());const s=3*t.num_faces(),r=4*s,l=e._malloc(r);try{n.GetTrianglesUInt32Array(t,r,l);const a=new Uint32Array(s);a.set(new Uint32Array(e.HEAPF32.buffer,l,s)),i(a)}finally{e._free(l)}o=t;break}case e.POINT_CLOUD:{const t=new e.PointCloud;if(h=n.DecodeBufferToPointCloud(a,t),!h.ok()||!t.ptr)throw new Error(h.error_msg());o=t;break}default:throw new Error(`Invalid geometry type ${l}`)}const c=o.num_points(),u=(t,s,i,n)=>{const a=n.data_type(),o=n.num_components(),h=n.normalized(),l=n.byte_stride(),u=n.byte_offset(),d={[e.DT_FLOAT32]:{typedArrayConstructor:Float32Array,heap:e.HEAPF32},[e.DT_INT8]:{typedArrayConstructor:Int8Array,heap:e.HEAP8},[e.DT_INT16]:{typedArrayConstructor:Int16Array,heap:e.HEAP16},[e.DT_INT32]:{typedArrayConstructor:Int32Array,heap:e.HEAP32},[e.DT_UINT8]:{typedArrayConstructor:Uint8Array,heap:e.HEAPU8},[e.DT_UINT16]:{typedArrayConstructor:Uint16Array,heap:e.HEAPU16},[e.DT_UINT32]:{typedArrayConstructor:Uint32Array,heap:e.HEAPU32}}[a];if(!d)throw new Error(`Invalid data type ${a}`);const _=c*o,f=_*d.typedArrayConstructor.BYTES_PER_ELEMENT,p=e._malloc(f);try{t.GetAttributeDataArrayForAllPoints(s,n,a,f,p);const e=new d.typedArrayConstructor(d.heap.buffer,p,_);r(i,e.slice(),o,u,l,h)}finally{e._free(p)}};if(s)for(const e in s){const t=s[e],i=n.GetAttributeByUniqueId(o,t);u(n,o,e,i)}else{const t={position:e.POSITION,normal:e.NORMAL,color:e.COLOR,uv:e.TEX_COORD};for(const e in t){const s=n.GetAttributeId(o,t[e]);if(-1!==s){const t=n.GetAttribute(o,s);u(n,o,e,t)}}}return c}finally{o&&e.destroy(o),a&&e.destroy(a),n&&e.destroy(n)}}function yo(){let e;onmessage=t=>{const s=t.data;switch(s.id){case"init":{const t=s.decoder;t.url&&importScripts(t.url);const i=t.wasmBinary?{wasmBinary:t.wasmBinary}:{};e=DracoDecoderModule(i),postMessage({id:"initDone"});break}case"decodeMesh":if(!e)throw new Error("Draco decoder module is not available");e.then((e=>{const t=Ao(e,s.dataView,s.attributes,(e=>{postMessage({id:"indices",data:e},[e.buffer])}),((e,t,s,i,r,n)=>{postMessage({id:"attribute",kind:e,data:t,size:s,byteOffset:i,byteStride:r,normalized:n},[t.buffer])}));postMessage({id:"decodeMeshDone",totalVertices:t})}))}}}Eo.DefaultOptions={idleTimeElapsedBeforeRelease:1e3};class bo{static get DecoderAvailable(){const e=bo.Configuration.decoder;return!!(e.wasmUrl&&e.wasmBinaryUrl&&"object"==typeof WebAssembly||e.fallbackUrl)}static GetDefaultNumWorkers(){return"object"==typeof navigator&&navigator.hardwareConcurrency?Math.min(Math.floor(.5*navigator.hardwareConcurrency),4):1}static get Default(){return bo._Default||(bo._Default=new bo),bo._Default}static ResetDefault(e){bo._Default&&(e||bo._Default.dispose(),bo._Default=null)}constructor(e=bo.DefaultNumWorkers){const t=bo.Configuration.decoder;if(t.workerPool||"object"==typeof e&&e.workerPool)this._workerPoolPromise=Promise.resolve(t.workerPool||e.workerPool);else{const s=t.wasmBinary||"object"==typeof e&&e.wasmBinary,i="number"==typeof e?e:e.numWorkers,r=i&&"function"==typeof Worker&&"function"==typeof URL,n=r||!r&&!t.jsModule,a=t.wasmUrl&&t.wasmBinaryUrl&&"object"==typeof WebAssembly?{url:n?Yt.GetBabylonScriptURL(t.wasmUrl,!0):"",wasmBinaryPromise:s?Promise.resolve(s):Yt.LoadFileAsync(Yt.GetBabylonScriptURL(t.wasmBinaryUrl,!0))}:{url:n?Yt.GetBabylonScriptURL(t.fallbackUrl):"",wasmBinaryPromise:Promise.resolve(void 0)};r?this._workerPoolPromise=a.wasmBinaryPromise.then((e=>{const t=`${Ao}(${yo})()`,s=URL.createObjectURL(new Blob([t],{type:"application/javascript"}));return new Eo(i,(()=>function(e,t,s){return new Promise(((i,r)=>{const n=t=>{e.removeEventListener("error",n),e.removeEventListener("message",a),r(t)},a=t=>{"initDone"===t.data.id&&(e.removeEventListener("error",n),e.removeEventListener("message",a),i(e))};if(e.addEventListener("error",n),e.addEventListener("message",a),t){const i=t.slice(0);e.postMessage({id:"init",decoder:{url:s,wasmBinary:i}},[i])}else e.postMessage({id:"init",decoder:{url:s}})}))}(new Worker(s),e,a.url)))})):this._decoderModulePromise=a.wasmBinaryPromise.then((async e=>{if("undefined"==typeof DracoDecoderModule&&!t.jsModule){if(!a.url)throw new Error("Draco decoder module is not available");await Yt.LoadBabylonScriptAsync(a.url)}return await(s=e,i=t.jsModule,new Promise((e=>{(i||DracoDecoderModule)({wasmBinary:s}).then((t=>{e({module:t})}))})));var s,i}))}}dispose(){this._workerPoolPromise&&this._workerPoolPromise.then((e=>{e.dispose()})),delete this._workerPoolPromise,delete this._decoderModulePromise}async whenReadyAsync(){this._workerPoolPromise?await this._workerPoolPromise:this._decoderModulePromise&&await this._decoderModulePromise}decodeMeshToMeshDataAsync(e,t,s){const i=e instanceof ArrayBuffer?new Int8Array(e):new Int8Array(e.buffer,e.byteOffset,e.byteLength);if(this._workerPoolPromise)return this._workerPoolPromise.then((e=>new Promise(((r,n)=>{e.push(((e,a)=>{let o=null;const h=[],l=t=>{e.removeEventListener("error",l),e.removeEventListener("message",c),n(t),a()},c=t=>{const i=t.data;switch(i.id){case"decodeMeshDone":e.removeEventListener("error",l),e.removeEventListener("message",c),r({indices:o,attributes:h,totalVertices:i.totalVertices}),a();break;case"indices":o=i.data;break;case"attribute":h.push({kind:i.kind,data:i.data,size:i.size,byteOffset:i.byteOffset,byteStride:i.byteStride,normalized:(n=i.kind,u=i.normalized,s&&void 0!==s[n]?(u!==s[n]&&ue.Warn(`Normalized flag from Draco data (${u}) does not match normalized flag from glTF accessor (${s[n]}). Using flag from glTF accessor.`),s[n]):u)})}var n,u};e.addEventListener("error",l),e.addEventListener("message",c);const u=i.slice();e.postMessage({id:"decodeMesh",dataView:u,attributes:t},[u.buffer])}))}))));if(this._decoderModulePromise)return this._decoderModulePromise.then((e=>{let s=null;const r=[],n=Ao(e.module,i,t,(e=>{s=e}),((e,t,s,i,n,a)=>{r.push({kind:e,data:t,size:s,byteOffset:i,byteStride:n,normalized:a})}));return{indices:s,attributes:r,totalVertices:n}}));throw new Error("Draco decoder module is not available")}async decodeMeshToGeometryAsync(e,t,s,i){const r=await this.decodeMeshToMeshDataAsync(s,i),n=new ys(e,t);r.indices&&n.setIndices(r.indices);for(const e of r.attributes)n.setVerticesBuffer(new ns(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),r.totalVertices);return n}async _decodeMeshToGeometryForGltfAsync(e,t,s,i,r){const n=await this.decodeMeshToMeshDataAsync(s,i,r),a=new ys(e,t);n.indices&&a.setIndices(n.indices);for(const e of n.attributes)a.setVerticesBuffer(new ns(t.getEngine(),e.data,e.kind,!1,void 0,e.byteStride,void 0,e.byteOffset,e.size,void 0,e.normalized,!0),n.totalVertices);return a}async decodeMeshAsync(e,t){const s=await this.decodeMeshToMeshDataAsync(e,t),i=new Es;s.indices&&(i.indices=s.indices);for(const e of s.attributes){const t=ns.GetFloatData(e.data,e.size,ns.GetDataType(e.data),e.byteOffset,e.byteStride,e.normalized,s.totalVertices);i.set(t,e.kind)}return i}}bo.Configuration={decoder:{wasmUrl:`${Yt._DefaultCdnUrl}/draco_wasm_wrapper_gltf.js`,wasmBinaryUrl:`${Yt._DefaultCdnUrl}/draco_decoder_gltf.wasm`,fallbackUrl:`${Yt._DefaultCdnUrl}/draco_decoder_gltf.js`}},bo.DefaultNumWorkers=bo.GetDefaultNumWorkers(),bo._Default=null;const Ro="KHR_draco_mesh_compression";class xo{constructor(e){this.name=Ro,this.useNormalizedFlagFromAccessor=!0,this._loader=e,this.enabled=bo.DecoderAvailable&&this._loader.isExtensionUsed(Ro)}dispose(){delete this.dracoCompression,this._loader=null}_loadVertexDataAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((i,r)=>{if(null!=t.mode&&4!==t.mode&&5!==t.mode)throw new Error(`${e}: Unsupported mode ${t.mode}`);const n={},a={},o=(e,i)=>{const o=r.attributes[e];if(null!=o&&(s._delayInfo=s._delayInfo||[],-1===s._delayInfo.indexOf(i)&&s._delayInfo.push(i),n[i]=o,this.useNormalizedFlagFromAccessor)){const s=io.TryGet(this._loader.gltf.accessors,t.attributes[e]);s&&(a[i]=s.normalized||!1)}};o("POSITION",ns.PositionKind),o("NORMAL",ns.NormalKind),o("TANGENT",ns.TangentKind),o("TEXCOORD_0",ns.UVKind),o("TEXCOORD_1",ns.UV2Kind),o("TEXCOORD_2",ns.UV3Kind),o("TEXCOORD_3",ns.UV4Kind),o("TEXCOORD_4",ns.UV5Kind),o("TEXCOORD_5",ns.UV6Kind),o("JOINTS_0",ns.MatricesIndicesKind),o("WEIGHTS_0",ns.MatricesWeightsKind),o("COLOR_0",ns.ColorKind);const h=io.Get(i,this._loader.gltf.bufferViews,r.bufferView);return h._dracoBabylonGeometry||(h._dracoBabylonGeometry=this._loader.loadBufferViewAsync(`/bufferViews/${h.index}`,h).then((t=>(this.dracoCompression||bo.Default)._decodeMeshToGeometryForGltfAsync(s.name,this._loader.babylonScene,t,n,a).catch((t=>{throw new Error(`${e}: ${t.message}`)}))))),h._dracoBabylonGeometry}))}}ro.RegisterExtension(Ro,(e=>new xo(e)));class Mo extends Vi{constructor(){super(...arguments),this._needProjectionMatrixCompute=!0,this._viewMatrix=V.Identity(),this._projectionMatrix=V.Identity()}_setPosition(e){this._position=e}get position(){return this._position}set position(e){this._setPosition(e)}_setDirection(e){this._direction=e}get direction(){return this._direction}set direction(e){this._setDirection(e)}get shadowMinZ(){return this._shadowMinZ}set shadowMinZ(e){this._shadowMinZ=e,this.forceProjectionMatrixCompute()}get shadowMaxZ(){return this._shadowMaxZ}set shadowMaxZ(e){this._shadowMaxZ=e,this.forceProjectionMatrixCompute()}computeTransformedInformation(){return!(!this.parent||!this.parent.getWorldMatrix)&&(this.transformedPosition||(this.transformedPosition=U.Zero()),U.TransformCoordinatesToRef(this.position,this.parent.getWorldMatrix(),this.transformedPosition),this.direction&&(this.transformedDirection||(this.transformedDirection=U.Zero()),U.TransformNormalToRef(this.direction,this.parent.getWorldMatrix(),this.transformedDirection)),!0)}getDepthScale(){return 50}getShadowDirection(e){return this.transformedDirection?this.transformedDirection:this.direction}getAbsolutePosition(){return this.transformedPosition?this.transformedPosition:this.position}setDirectionToTarget(e){return this.direction=U.Normalize(e.subtract(this.position)),this.direction}getRotation(){this.direction.normalize();const e=U.Cross(this.direction,Bs.Y),t=U.Cross(e,this.direction);return U.RotationFromAxis(e,t,this.direction)}needCube(){return!1}needProjectionMatrixCompute(){return this._needProjectionMatrixCompute}forceProjectionMatrixCompute(){this._needProjectionMatrixCompute=!0}_initCache(){super._initCache(),this._cache.position=U.Zero()}_isSynchronized(){return!!this._cache.position.equals(this.position)}computeWorldMatrix(e){return!e&&this.isSynchronized()?(this._currentRenderId=this.getScene().getRenderId(),this._worldMatrix):(this._updateCache(),this._cache.position.copyFrom(this.position),this._worldMatrix||(this._worldMatrix=V.Identity()),V.TranslationToRef(this.position.x,this.position.y,this.position.z,this._worldMatrix),this.parent&&this.parent.getWorldMatrix&&(this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(),this._worldMatrix),this._markSyncedWithParent()),this._worldMatrixDeterminantIsDirty=!0,this._worldMatrix)}getDepthMinZ(e){return void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ}getDepthMaxZ(e){return void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ}setShadowProjectionMatrix(e,t,s){return this.customProjectionMatrixBuilder?this.customProjectionMatrixBuilder(t,s,e):this._setDefaultShadowProjectionMatrix(e,t,s),this}_syncParentEnabledState(){super._syncParentEnabledState(),this.parent&&this.parent.getWorldMatrix||(this.transformedPosition=null,this.transformedDirection=null)}getViewMatrix(e){const t=z.Vector3[0];let s=this.position;this.computeTransformedInformation()&&(s=this.transformedPosition),U.NormalizeToRef(this.getShadowDirection(e),t),1===Math.abs(U.Dot(t,U.Up()))&&(t.z=1e-13);const i=z.Vector3[1];return s.addToRef(t,i),V.LookAtLHToRef(s,i,U.Up(),this._viewMatrix),this._viewMatrix}getProjectionMatrix(e,t){return this.setShadowProjectionMatrix(this._projectionMatrix,e??this._viewMatrix,t??[]),this._projectionMatrix}}e([c()],Mo.prototype,"position",null),e([c()],Mo.prototype,"direction",null),e([a()],Mo.prototype,"shadowMinZ",null),e([a()],Mo.prototype,"shadowMaxZ",null),ae.AddNodeConstructor("Light_Type_1",((e,t)=>()=>new Io(e,U.Zero(),t)));class Io extends Mo{get shadowFrustumSize(){return this._shadowFrustumSize}set shadowFrustumSize(e){this._shadowFrustumSize=e,this.forceProjectionMatrixCompute()}get shadowOrthoScale(){return this._shadowOrthoScale}set shadowOrthoScale(e){this._shadowOrthoScale=e,this.forceProjectionMatrixCompute()}get orthoLeft(){return this._orthoLeft}set orthoLeft(e){this._orthoLeft=e}get orthoRight(){return this._orthoRight}set orthoRight(e){this._orthoRight=e}get orthoTop(){return this._orthoTop}set orthoTop(e){this._orthoTop=e}get orthoBottom(){return this._orthoBottom}set orthoBottom(e){this._orthoBottom=e}constructor(e,t,s){super(e,s),this._shadowFrustumSize=0,this._shadowOrthoScale=.1,this.autoUpdateExtends=!0,this.autoCalcShadowZBounds=!1,this._orthoLeft=Number.MAX_VALUE,this._orthoRight=Number.MIN_VALUE,this._orthoTop=Number.MIN_VALUE,this._orthoBottom=Number.MAX_VALUE,this.position=t.scale(-1),this.direction=t}getClassName(){return"DirectionalLight"}getTypeID(){return Vi.LIGHTTYPEID_DIRECTIONALLIGHT}_setDefaultShadowProjectionMatrix(e,t,s){this.shadowFrustumSize>0?this._setDefaultFixedFrustumShadowProjectionMatrix(e):this._setDefaultAutoExtendShadowProjectionMatrix(e,t,s)}_setDefaultFixedFrustumShadowProjectionMatrix(e){const t=this.getScene().activeCamera;t&&V.OrthoLHToRef(this.shadowFrustumSize,this.shadowFrustumSize,void 0!==this.shadowMinZ?this.shadowMinZ:t.minZ,void 0!==this.shadowMaxZ?this.shadowMaxZ:t.maxZ,e,this.getScene().getEngine().isNDCHalfZRange)}_setDefaultAutoExtendShadowProjectionMatrix(e,t,s){const i=this.getScene().activeCamera;if(!i)return;if(this.autoUpdateExtends||this._orthoLeft===Number.MAX_VALUE){const e=U.Zero();this._orthoLeft=Number.MAX_VALUE,this._orthoRight=-Number.MAX_VALUE,this._orthoTop=-Number.MAX_VALUE,this._orthoBottom=Number.MAX_VALUE;let i=Number.MAX_VALUE,r=-Number.MAX_VALUE;for(let n=0;n<s.length;n++){const a=s[n];if(!a)continue;const o=a.getBoundingInfo().boundingBox;for(let s=0;s<o.vectorsWorld.length;s++)U.TransformCoordinatesToRef(o.vectorsWorld[s],t,e),e.x<this._orthoLeft&&(this._orthoLeft=e.x),e.y<this._orthoBottom&&(this._orthoBottom=e.y),e.x>this._orthoRight&&(this._orthoRight=e.x),e.y>this._orthoTop&&(this._orthoTop=e.y),this.autoCalcShadowZBounds&&(e.z<i&&(i=e.z),e.z>r&&(r=e.z))}this.autoCalcShadowZBounds&&(this._shadowMinZ=i,this._shadowMaxZ=r)}const r=this._orthoRight-this._orthoLeft,n=this._orthoTop-this._orthoBottom,a=void 0!==this.shadowMinZ?this.shadowMinZ:i.minZ,o=void 0!==this.shadowMaxZ?this.shadowMaxZ:i.maxZ,h=this.getScene().getEngine().useReverseDepthBuffer;V.OrthoOffCenterLHToRef(this._orthoLeft-r*this.shadowOrthoScale,this._orthoRight+r*this.shadowOrthoScale,this._orthoBottom-n*this.shadowOrthoScale,this._orthoTop+n*this.shadowOrthoScale,h?o:a,h?a:o,e,this.getScene().getEngine().isNDCHalfZRange)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z,1,t),this):(this._uniformBuffer.updateFloat4("vLightData",this.direction.x,this.direction.y,this.direction.z,1,t),this)}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?(e.setFloat3(t,this.transformedDirection.x,this.transformedDirection.y,this.transformedDirection.z),this):(e.setFloat3(t,this.direction.x,this.direction.y,this.direction.z),this)}getDepthMinZ(e){const t=this._scene.getEngine();return!t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}getDepthMaxZ(e){const t=this._scene.getEngine();return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:1}prepareLightSpecificDefines(e,t){e["DIRLIGHT"+t]=!0}}e([a()],Io.prototype,"shadowFrustumSize",null),e([a()],Io.prototype,"shadowOrthoScale",null),e([a()],Io.prototype,"autoUpdateExtends",void 0),e([a()],Io.prototype,"autoCalcShadowZBounds",void 0),e([a("orthoLeft")],Io.prototype,"_orthoLeft",void 0),e([a("orthoRight")],Io.prototype,"_orthoRight",void 0),e([a("orthoTop")],Io.prototype,"_orthoTop",void 0),e([a("orthoBottom")],Io.prototype,"_orthoBottom",void 0),I("BABYLON.DirectionalLight",Io),ae.AddNodeConstructor("Light_Type_0",((e,t)=>()=>new So(e,U.Zero(),t)));class So extends Mo{get shadowAngle(){return this._shadowAngle}set shadowAngle(e){this._shadowAngle=e,this.forceProjectionMatrixCompute()}get direction(){return this._direction}set direction(e){const t=this.needCube();if(this._direction=e,this.needCube()!==t&&this._shadowGenerators){const e=this._shadowGenerators.values();for(let t=e.next();!0!==t.done;t=e.next()){t.value.recreateShadowMap()}}}constructor(e,t,s){super(e,s),this._shadowAngle=Math.PI/2,this.position=t}getClassName(){return"PointLight"}getTypeID(){return Vi.LIGHTTYPEID_POINTLIGHT}needCube(){return!this.direction}getShadowDirection(e){if(this.direction)return super.getShadowDirection(e);switch(e){case 0:return new U(1,0,0);case 1:return new U(-1,0,0);case 2:return new U(0,-1,0);case 3:return new U(0,1,0);case 4:return new U(0,0,1);case 5:return new U(0,0,-1)}return U.Zero()}_setDefaultShadowProjectionMatrix(e,t,s){const i=this.getScene().activeCamera;if(!i)return;const r=void 0!==this.shadowMinZ?this.shadowMinZ:i.minZ,n=void 0!==this.shadowMaxZ?this.shadowMaxZ:i.maxZ,a=this.getScene().getEngine().useReverseDepthBuffer;V.PerspectiveFovLHToRef(this.shadowAngle,1,a?n:r,a?r:n,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,a)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}transferToEffect(e,t){return this.computeTransformedInformation()?this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,0,t):this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,0,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,0,0,t),this}transferToNodeMaterialEffect(e,t){return this.computeTransformedInformation()?e.setFloat3(t,this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z):e.setFloat3(t,this.position.x,this.position.y,this.position.z),this}prepareLightSpecificDefines(e,t){e["POINTLIGHT"+t]=!0}}e([a()],So.prototype,"shadowAngle",null),I("BABYLON.PointLight",So),ae.AddNodeConstructor("Light_Type_2",((e,t)=>()=>new vo(e,U.Zero(),U.Zero(),0,0,t)));class vo extends Mo{get angle(){return this._angle}set angle(e){this._angle=e,this._cosHalfAngle=Math.cos(.5*e),this._projectionTextureProjectionLightDirty=!0,this.forceProjectionMatrixCompute(),this._computeAngleValues()}get innerAngle(){return this._innerAngle}set innerAngle(e){this._innerAngle=e,this._computeAngleValues()}get shadowAngleScale(){return this._shadowAngleScale}set shadowAngleScale(e){this._shadowAngleScale=e,this.forceProjectionMatrixCompute()}get projectionTextureMatrix(){return this._projectionTextureMatrix}get projectionTextureLightNear(){return this._projectionTextureLightNear}set projectionTextureLightNear(e){this._projectionTextureLightNear=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureLightFar(){return this._projectionTextureLightFar}set projectionTextureLightFar(e){this._projectionTextureLightFar=e,this._projectionTextureProjectionLightDirty=!0}get projectionTextureUpDirection(){return this._projectionTextureUpDirection}set projectionTextureUpDirection(e){this._projectionTextureUpDirection=e,this._projectionTextureProjectionLightDirty=!0}get projectionTexture(){return this._projectionTexture}set projectionTexture(e){this._projectionTexture!==e&&(this._projectionTexture=e,this._projectionTextureDirty=!0,this._projectionTexture&&!this._projectionTexture.isReady()&&(vo._IsProceduralTexture(this._projectionTexture)?this._projectionTexture.getEffect().executeWhenCompiled((()=>{this._markMeshesAsLightDirty()})):vo._IsTexture(this._projectionTexture)&&this._projectionTexture.onLoadObservable.addOnce((()=>{this._markMeshesAsLightDirty()}))))}static _IsProceduralTexture(e){return void 0!==e.onGeneratedObservable}static _IsTexture(e){return void 0!==e.onLoadObservable}get projectionTextureProjectionLightMatrix(){return this._projectionTextureProjectionLightMatrix}set projectionTextureProjectionLightMatrix(e){this._projectionTextureProjectionLightMatrix=e,this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0}constructor(e,t,s,i,r,n){super(e,n),this._innerAngle=0,this._projectionTextureMatrix=V.Zero(),this._projectionTextureLightNear=1e-6,this._projectionTextureLightFar=1e3,this._projectionTextureUpDirection=U.Up(),this._projectionTextureViewLightDirty=!0,this._projectionTextureProjectionLightDirty=!0,this._projectionTextureDirty=!0,this._projectionTextureViewTargetVector=U.Zero(),this._projectionTextureViewLightMatrix=V.Zero(),this._projectionTextureProjectionLightMatrix=V.Zero(),this._projectionTextureScalingMatrix=V.FromValues(.5,0,0,0,0,.5,0,0,0,0,.5,0,.5,.5,.5,1),this.position=t,this.direction=s,this.angle=i,this.exponent=r}getClassName(){return"SpotLight"}getTypeID(){return Vi.LIGHTTYPEID_SPOTLIGHT}_setDirection(e){super._setDirection(e),this._projectionTextureViewLightDirty=!0}_setPosition(e){super._setPosition(e),this._projectionTextureViewLightDirty=!0}_setDefaultShadowProjectionMatrix(e,t,s){const i=this.getScene().activeCamera;if(!i)return;this._shadowAngleScale=this._shadowAngleScale||1;const r=this._shadowAngleScale*this._angle,n=void 0!==this.shadowMinZ?this.shadowMinZ:i.minZ,a=void 0!==this.shadowMaxZ?this.shadowMaxZ:i.maxZ,o=this.getScene().getEngine().useReverseDepthBuffer;V.PerspectiveFovLHToRef(r,1,o?a:n,o?n:a,e,!0,this._scene.getEngine().isNDCHalfZRange,void 0,o)}_computeProjectionTextureViewLightMatrix(){this._projectionTextureViewLightDirty=!1,this._projectionTextureDirty=!0,this.getAbsolutePosition().addToRef(this.getShadowDirection(),this._projectionTextureViewTargetVector),V.LookAtLHToRef(this.getAbsolutePosition(),this._projectionTextureViewTargetVector,this._projectionTextureUpDirection,this._projectionTextureViewLightMatrix)}_computeProjectionTextureProjectionLightMatrix(){this._projectionTextureProjectionLightDirty=!1,this._projectionTextureDirty=!0;const e=this.projectionTextureLightFar,t=this.projectionTextureLightNear,s=e/(e-t),i=-s*t,r=1/Math.tan(this._angle/2);V.FromValuesToRef(r/1,0,0,0,0,r,0,0,0,0,s,1,0,0,i,0,this._projectionTextureProjectionLightMatrix)}_computeProjectionTextureMatrix(){if(this._projectionTextureDirty=!1,this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix,this._projectionTextureMatrix),this._projectionTexture instanceof Dr){const e=this._projectionTexture.uScale/2,t=this._projectionTexture.vScale/2;V.FromValuesToRef(e,0,0,0,0,t,0,0,0,0,.5,0,.5,.5,.5,1,this._projectionTextureScalingMatrix)}this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix,this._projectionTextureMatrix)}_buildUniformLayout(){this._uniformBuffer.addUniform("vLightData",4),this._uniformBuffer.addUniform("vLightDiffuse",4),this._uniformBuffer.addUniform("vLightSpecular",4),this._uniformBuffer.addUniform("vLightDirection",3),this._uniformBuffer.addUniform("vLightFalloff",4),this._uniformBuffer.addUniform("shadowsInfo",3),this._uniformBuffer.addUniform("depthValues",2),this._uniformBuffer.create()}_computeAngleValues(){this._lightAngleScale=1/Math.max(.001,Math.cos(.5*this._innerAngle)-this._cosHalfAngle),this._lightAngleOffset=-this._cosHalfAngle*this._lightAngleScale}transferTexturesToEffect(e,t){return this.projectionTexture&&this.projectionTexture.isReady()&&(this._projectionTextureViewLightDirty&&this._computeProjectionTextureViewLightMatrix(),this._projectionTextureProjectionLightDirty&&this._computeProjectionTextureProjectionLightMatrix(),this._projectionTextureDirty&&this._computeProjectionTextureMatrix(),e.setMatrix("textureProjectionMatrix"+t,this._projectionTextureMatrix),e.setTexture("projectionLightTexture"+t,this.projectionTexture)),this}transferToEffect(e,t){let s;return this.computeTransformedInformation()?(this._uniformBuffer.updateFloat4("vLightData",this.transformedPosition.x,this.transformedPosition.y,this.transformedPosition.z,this.exponent,t),s=U.Normalize(this.transformedDirection)):(this._uniformBuffer.updateFloat4("vLightData",this.position.x,this.position.y,this.position.z,this.exponent,t),s=U.Normalize(this.direction)),this._uniformBuffer.updateFloat4("vLightDirection",s.x,s.y,s.z,this._cosHalfAngle,t),this._uniformBuffer.updateFloat4("vLightFalloff",this.range,this._inverseSquaredRange,this._lightAngleScale,this._lightAngleOffset,t),this}transferToNodeMaterialEffect(e,t){let s;return s=this.computeTransformedInformation()?U.Normalize(this.transformedDirection):U.Normalize(this.direction),this.getScene().useRightHandedSystem?e.setFloat3(t,-s.x,-s.y,-s.z):e.setFloat3(t,s.x,s.y,s.z),this}dispose(){super.dispose(),this._projectionTexture&&this._projectionTexture.dispose()}getDepthMinZ(e){const t=this._scene.getEngine(),s=void 0!==this.shadowMinZ?this.shadowMinZ:e.minZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?s:this._scene.getEngine().isNDCHalfZRange?0:s}getDepthMaxZ(e){const t=this._scene.getEngine(),s=void 0!==this.shadowMaxZ?this.shadowMaxZ:e.maxZ;return t.useReverseDepthBuffer&&t.isNDCHalfZRange?0:s}prepareLightSpecificDefines(e,t){e["SPOTLIGHT"+t]=!0,e["PROJECTEDLIGHTTEXTURE"+t]=!(!this.projectionTexture||!this.projectionTexture.isReady())}}e([a()],vo.prototype,"angle",null),e([a()],vo.prototype,"innerAngle",null),e([a()],vo.prototype,"shadowAngleScale",null),e([a()],vo.prototype,"exponent",void 0),e([a()],vo.prototype,"projectionTextureLightNear",null),e([a()],vo.prototype,"projectionTextureLightFar",null),e([a()],vo.prototype,"projectionTextureUpDirection",null),e([o("projectedLightTexture")],vo.prototype,"_projectionTexture",void 0),I("BABYLON.SpotLight",vo);const Co="KHR_lights_punctual";class Po{constructor(e){this.name=Co,this._loader=e,this.enabled=this._loader.isExtensionUsed(Co)}dispose(){this._loader=null,delete this._lights}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._lights=t.lights,io.Assign(this._lights)}}loadNodeAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((i,r)=>(this._loader._allMaterialsDirtyRequired=!0,this._loader.loadNodeAsync(e,t,(e=>{let t;const n=io.Get(i,this._lights,r.light),a=n.name||e.name;switch(this._loader.babylonScene._blockEntityCollection=!!this._loader._assetContainer,n.type){case"directional":{const e=new Io(a,U.Backward(),this._loader.babylonScene);e.position.setAll(0),t=e;break}case"point":t=new So(a,U.Zero(),this._loader.babylonScene);break;case"spot":{const e=new vo(a,U.Zero(),U.Backward(),0,1,this._loader.babylonScene);e.angle=2*(n.spot&&n.spot.outerConeAngle||Math.PI/4),e.innerAngle=2*(n.spot&&n.spot.innerConeAngle||0),t=e;break}default:throw this._loader.babylonScene._blockEntityCollection=!1,new Error(`${i}: Invalid light type (${n.type})`)}t._parentContainer=this._loader._assetContainer,this._loader.babylonScene._blockEntityCollection=!1,n._babylonLight=t,t.falloffType=Vi.FALLOFF_GLTF,t.diffuse=n.color?ee.FromArray(n.color):ee.White(),t.intensity=null==n.intensity?1:n.intensity,t.range=null==n.range?Number.MAX_VALUE:n.range,t.parent=e,this._loader._babylonLights.push(t),ro.AddPointerMetadata(t,i),s(e)})))))}}ro.RegisterExtension(Co,(e=>new Po(e)));const Oo="KHR_materials_pbrSpecularGlossiness";class Do{constructor(e){this.name=Oo,this.order=200,this._loader=e,this.enabled=this._loader.isExtensionUsed(Oo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((i,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,s)),n.push(this._loadSpecularGlossinessPropertiesAsync(i,r,s)),this._loader.loadMaterialAlphaProperties(e,t,s),Promise.all(n).then((()=>{}))}))}_loadSpecularGlossinessPropertiesAsync(e,t,s){if(!(s instanceof zn))throw new Error(`${e}: Material type not supported`);const i=new Array;return s.metallic=null,s.roughness=null,t.diffuseFactor?(s.albedoColor=ee.FromArray(t.diffuseFactor),s.alpha=t.diffuseFactor[3]):s.albedoColor=ee.White(),s.reflectivityColor=t.specularFactor?ee.FromArray(t.specularFactor):ee.White(),s.microSurface=null==t.glossinessFactor?1:t.glossinessFactor,t.diffuseTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTexture`,t.diffuseTexture,(e=>{e.name=`${s.name} (Diffuse)`,s.albedoTexture=e}))),t.specularGlossinessTexture&&(i.push(this._loader.loadTextureInfoAsync(`${e}/specularGlossinessTexture`,t.specularGlossinessTexture,(e=>{e.name=`${s.name} (Specular Glossiness)`,s.reflectivityTexture=e,s.reflectivityTexture.hasAlpha=!0}))),s.useMicroSurfaceFromReflectivityMapAlpha=!0),Promise.all(i).then((()=>{}))}}ro.RegisterExtension(Oo,(e=>new Do(e)));const Lo="KHR_materials_unlit";class Fo{constructor(e){this.name=Lo,this.order=210,this._loader=e,this.enabled=this._loader.isExtensionUsed(Lo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,(()=>this._loadUnlitPropertiesAsync(e,t,s)))}_loadUnlitPropertiesAsync(e,t,s){if(!(s instanceof zn))throw new Error(`${e}: Material type not supported`);const i=new Array;s.unlit=!0;const r=t.pbrMetallicRoughness;return r&&(r.baseColorFactor?(s.albedoColor=ee.FromArray(r.baseColorFactor),s.alpha=r.baseColorFactor[3]):s.albedoColor=ee.White(),r.baseColorTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/baseColorTexture`,r.baseColorTexture,(e=>{e.name=`${s.name} (Base Color)`,s.albedoTexture=e})))),t.doubleSided&&(s.backFaceCulling=!1,s.twoSidedLighting=!0),this._loader.loadMaterialAlphaProperties(e,t,s),Promise.all(i).then((()=>{}))}}ro.RegisterExtension(Lo,(e=>new Fo(e)));const No="KHR_materials_clearcoat";class wo{constructor(e){this.name=No,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(No)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((i,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,s)),n.push(this._loadClearCoatPropertiesAsync(i,r,s)),Promise.all(n).then((()=>{}))}))}_loadClearCoatPropertiesAsync(e,t,s){if(!(s instanceof zn))throw new Error(`${e}: Material type not supported`);const i=new Array;return s.clearCoat.isEnabled=!0,s.clearCoat.useRoughnessFromMainTexture=!1,s.clearCoat.remapF0OnInterfaceChange=!1,null!=t.clearcoatFactor?s.clearCoat.intensity=t.clearcoatFactor:s.clearCoat.intensity=0,t.clearcoatTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatTexture`,t.clearcoatTexture,(e=>{e.name=`${s.name} (ClearCoat Intensity)`,s.clearCoat.texture=e}))),null!=t.clearcoatRoughnessFactor?s.clearCoat.roughness=t.clearcoatRoughnessFactor:s.clearCoat.roughness=0,t.clearcoatRoughnessTexture&&(t.clearcoatRoughnessTexture.nonColorData=!0,i.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatRoughnessTexture`,t.clearcoatRoughnessTexture,(e=>{e.name=`${s.name} (ClearCoat Roughness)`,s.clearCoat.textureRoughness=e})))),t.clearcoatNormalTexture&&(t.clearcoatNormalTexture.nonColorData=!0,i.push(this._loader.loadTextureInfoAsync(`${e}/clearcoatNormalTexture`,t.clearcoatNormalTexture,(e=>{e.name=`${s.name} (ClearCoat Normal)`,s.clearCoat.bumpTexture=e}))),s.invertNormalMapX=!s.getScene().useRightHandedSystem,s.invertNormalMapY=s.getScene().useRightHandedSystem,null!=t.clearcoatNormalTexture.scale&&(s.clearCoat.bumpTexture.level=t.clearcoatNormalTexture.scale)),Promise.all(i).then((()=>{}))}}ro.RegisterExtension(No,(e=>new wo(e)));const Bo="KHR_materials_iridescence";class Uo{constructor(e){this.name=Bo,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(Bo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((i,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,s)),n.push(this._loadIridescencePropertiesAsync(i,r,s)),Promise.all(n).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,s){if(!(s instanceof zn))throw new Error(`${e}: Material type not supported`);const i=new Array;return s.iridescence.isEnabled=!0,s.iridescence.intensity=t.iridescenceFactor??0,s.iridescence.indexOfRefraction=t.iridescenceIor??t.iridescenceIOR??1.3,s.iridescence.minimumThickness=t.iridescenceThicknessMinimum??100,s.iridescence.maximumThickness=t.iridescenceThicknessMaximum??400,t.iridescenceTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceTexture`,t.iridescenceTexture,(e=>{e.name=`${s.name} (Iridescence Intensity)`,s.iridescence.texture=e}))),t.iridescenceThicknessTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/iridescenceThicknessTexture`,t.iridescenceThicknessTexture,(e=>{e.name=`${s.name} (Iridescence Thickness)`,s.iridescence.thicknessTexture=e}))),Promise.all(i).then((()=>{}))}}ro.RegisterExtension(Bo,(e=>new Uo(e)));const ko="KHR_materials_anisotropy";class Go{constructor(e){this.name=ko,this.order=195,this._loader=e,this.enabled=this._loader.isExtensionUsed(ko)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((i,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,s)),n.push(this._loadIridescencePropertiesAsync(i,r,s)),Promise.all(n).then((()=>{}))}))}_loadIridescencePropertiesAsync(e,t,s){if(!(s instanceof zn))throw new Error(`${e}: Material type not supported`);const i=new Array;return s.anisotropy.isEnabled=!0,s.anisotropy.intensity=t.anisotropyStrength??0,s.anisotropy.angle=t.anisotropyRotation??0,t.anisotropyTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/anisotropyTexture`,t.anisotropyTexture,(e=>{e.name=`${s.name} (Anisotropy Intensity)`,s.anisotropy.texture=e}))),Promise.all(i).then((()=>{}))}}ro.RegisterExtension(ko,(e=>new Go(e)));const Vo="KHR_materials_emissive_strength";class Ho{constructor(e){this.name=Vo,this.order=170,this._loader=e,this.enabled=this._loader.isExtensionUsed(Vo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((i,r)=>this._loader.loadMaterialPropertiesAsync(e,t,s).then((()=>{this._loadEmissiveProperties(i,r,s)}))))}_loadEmissiveProperties(e,t,s){if(!(s instanceof zn))throw new Error(`${e}: Material type not supported`);void 0!==t.emissiveStrength&&(s.emissiveIntensity=t.emissiveStrength)}}ro.RegisterExtension(Vo,(e=>new Ho(e)));const zo="KHR_materials_sheen";class Xo{constructor(e){this.name=zo,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(zo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((i,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,s)),n.push(this._loadSheenPropertiesAsync(i,r,s)),Promise.all(n).then((()=>{}))}))}_loadSheenPropertiesAsync(e,t,s){if(!(s instanceof zn))throw new Error(`${e}: Material type not supported`);const i=new Array;return s.sheen.isEnabled=!0,s.sheen.intensity=1,null!=t.sheenColorFactor?s.sheen.color=ee.FromArray(t.sheenColorFactor):s.sheen.color=ee.Black(),t.sheenColorTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/sheenColorTexture`,t.sheenColorTexture,(e=>{e.name=`${s.name} (Sheen Color)`,s.sheen.texture=e}))),void 0!==t.sheenRoughnessFactor?s.sheen.roughness=t.sheenRoughnessFactor:s.sheen.roughness=0,t.sheenRoughnessTexture&&(t.sheenRoughnessTexture.nonColorData=!0,i.push(this._loader.loadTextureInfoAsync(`${e}/sheenRoughnessTexture`,t.sheenRoughnessTexture,(e=>{e.name=`${s.name} (Sheen Roughness)`,s.sheen.textureRoughness=e})))),s.sheen.albedoScaling=!0,s.sheen.useRoughnessFromMainTexture=!1,Promise.all(i).then((()=>{}))}}ro.RegisterExtension(zo,(e=>new Xo(e)));const Wo="KHR_materials_specular";class Yo{constructor(e){this.name=Wo,this.order=190,this._loader=e,this.enabled=this._loader.isExtensionUsed(Wo)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((i,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,s)),n.push(this._loadSpecularPropertiesAsync(i,r,s)),Promise.all(n).then((()=>{}))}))}_loadSpecularPropertiesAsync(e,t,s){if(!(s instanceof zn))throw new Error(`${e}: Material type not supported`);const i=new Array;return void 0!==t.specularFactor&&(s.metallicF0Factor=t.specularFactor),void 0!==t.specularColorFactor&&(s.metallicReflectanceColor=ee.FromArray(t.specularColorFactor)),t.specularTexture&&(t.specularTexture.nonColorData=!0,i.push(this._loader.loadTextureInfoAsync(`${e}/specularTexture`,t.specularTexture,(e=>{e.name=`${s.name} (Specular F0 Strength)`,s.metallicReflectanceTexture=e,s.useOnlyMetallicFromMetallicReflectanceTexture=!0})))),t.specularColorTexture&&i.push(this._loader.loadTextureInfoAsync(`${e}/specularColorTexture`,t.specularColorTexture,(e=>{e.name=`${s.name} (Specular F0 Color)`,s.reflectanceTexture=e}))),Promise.all(i).then((()=>{}))}}ro.RegisterExtension(Wo,(e=>new Yo(e)));const Ko="KHR_materials_ior";class qo{constructor(e){this.name=Ko,this.order=180,this._loader=e,this.enabled=this._loader.isExtensionUsed(Ko)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((i,r)=>{const n=new Array;return n.push(this._loader.loadMaterialPropertiesAsync(e,t,s)),n.push(this._loadIorPropertiesAsync(i,r,s)),Promise.all(n).then((()=>{}))}))}_loadIorPropertiesAsync(e,t,s){if(!(s instanceof zn))throw new Error(`${e}: Material type not supported`);return void 0!==t.ior?s.indexOfRefraction=t.ior:s.indexOfRefraction=qo._DEFAULT_IOR,Promise.resolve()}}qo._DEFAULT_IOR=1.5,ro.RegisterExtension(Ko,(e=>new qo(e)));const Qo="KHR_materials_variants";class jo{constructor(e){this.name=Qo,this._loader=e,this.enabled=this._loader.isExtensionUsed(Qo)}dispose(){this._loader=null}static GetAvailableVariants(e){const t=this._GetExtensionMetadata(e);return t?Object.keys(t.variants):[]}getAvailableVariants(e){return jo.GetAvailableVariants(e)}static SelectVariant(e,t){const s=this._GetExtensionMetadata(e);if(!s)throw new Error(`Cannot select variant on a glTF mesh that does not have the ${Qo} extension`);const i=e=>{const t=s.variants[e];if(t)for(const e of t)e.mesh.material=e.material};if(t instanceof Array)for(const e of t)i(e);else i(t);s.lastSelected=t}selectVariant(e,t){jo.SelectVariant(e,t)}static Reset(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot reset on a glTF mesh that does not have the ${Qo} extension`);for(const e of t.original)e.mesh.material=e.material;t.lastSelected=null}reset(e){jo.Reset(e)}static GetLastSelectedVariant(e){const t=this._GetExtensionMetadata(e);if(!t)throw new Error(`Cannot get the last selected variant on a glTF mesh that does not have the ${Qo} extension`);return t.lastSelected}getLastSelectedVariant(e){return jo.GetLastSelectedVariant(e)}static _GetExtensionMetadata(e){return e?._internalMetadata?.gltf?.[Qo]||null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._variants=t.variants}}_loadMeshPrimitiveAsync(e,t,s,i,r,n){return ro.LoadExtensionAsync(e,r,this.name,((a,o)=>{const h=new Array;return h.push(this._loader._loadMeshPrimitiveAsync(e,t,s,i,r,(t=>{if(n(t),t instanceof oi){const s=ro._GetDrawMode(e,r.mode),i=this._loader.rootBabylonMesh,n=i?i._internalMetadata=i._internalMetadata||{}:{},l=n.gltf=n.gltf||{},c=l[Qo]=l[Qo]||{lastSelected:null,original:[],variants:{}};c.original.push({mesh:t,material:t.material});for(let e=0;e<o.mappings.length;++e){const r=o.mappings[e],n=io.Get(`${a}/mappings/${e}/material`,this._loader.gltf.materials,r.material);h.push(this._loader._loadMaterialAsync(`#/materials/${r.material}`,n,t,s,(e=>{for(let s=0;s<r.variants.length;++s){const n=r.variants[s],a=io.Get(`/extensions/${Qo}/variants/${n}`,this._variants,n);c.variants[a.name]=c.variants[a.name]||[],c.variants[a.name].push({mesh:t,material:e}),t.onClonedObservable.add((e=>{const s=e;let r=null,n=s;do{if(n=n.parent,!n)return;r=jo._GetExtensionMetadata(n)}while(null===r);if(i&&r===jo._GetExtensionMetadata(i)){n._internalMetadata={};for(const e in i._internalMetadata)n._internalMetadata[e]=i._internalMetadata[e];n._internalMetadata.gltf=[];for(const e in i._internalMetadata.gltf)n._internalMetadata.gltf[e]=i._internalMetadata.gltf[e];n._internalMetadata.gltf[Qo]={lastSelected:null,original:[],variants:{}};for(const e of r.original)n._internalMetadata.gltf[Qo].original.push({mesh:e.mesh,material:e.material});for(const e in r.variants)if(Object.prototype.hasOwnProperty.call(r.variants,e)){n._internalMetadata.gltf[Qo].variants[e]=[];for(const t of r.variants[e])n._internalMetadata.gltf[Qo].variants[e].push({mesh:t.mesh,material:t.material})}r=n._internalMetadata.gltf[Qo]}for(const e of r.original)e.mesh===t&&(e.mesh=s);for(const e of r.variants[a.name])e.mesh===t&&(e.mesh=s)}))}})))}}}))),Promise.all(h).then((([e])=>e))}))}}ro.RegisterExtension(Qo,(e=>new jo(e)));class Zo{static _GetDefaultOptions(){return{renderSize:1024,samples:4,lodGenerationScale:1,lodGenerationOffset:-4,renderTargetTextureType:Ze.TEXTURETYPE_HALF_FLOAT,generateMipmaps:!0}}constructor(e,t){this._opaqueRenderTarget=null,this._opaqueMeshesCache=[],this._transparentMeshesCache=[],this._materialObservers={},this._options={...Zo._GetDefaultOptions(),...e},this._scene=t,this._scene._transmissionHelper=this,this.onErrorObservable=new g,this._scene.onDisposeObservable.addOnce((()=>{this.dispose()})),this._parseScene(),this._setupRenderTargets()}updateOptions(e){if(!Object.keys(e).filter((t=>this._options[t]!==e[t])).length)return;const t={...this._options,...e},s=this._options;this._options=t,t.renderSize===s.renderSize&&t.renderTargetTextureType===s.renderTargetTextureType&&t.generateMipmaps===s.generateMipmaps&&this._opaqueRenderTarget?(this._opaqueRenderTarget.samples=t.samples,this._opaqueRenderTarget.lodGenerationScale=t.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=t.lodGenerationOffset):this._setupRenderTargets()}getOpaqueTarget(){return this._opaqueRenderTarget}_shouldRenderAsTransmission(e){return!!e&&!!(e instanceof zn&&e.subSurface.isRefractionEnabled)}_addMesh(e){this._materialObservers[e.uniqueId]=e.onMaterialChangedObservable.add(this._onMeshMaterialChanged.bind(this)),Yt.SetImmediate((()=>{this._shouldRenderAsTransmission(e.material)?(e.material.refractionTexture=this._opaqueRenderTarget,-1===this._transparentMeshesCache.indexOf(e)&&this._transparentMeshesCache.push(e)):-1===this._opaqueMeshesCache.indexOf(e)&&this._opaqueMeshesCache.push(e)}))}_removeMesh(e){e.onMaterialChangedObservable.remove(this._materialObservers[e.uniqueId]),delete this._materialObservers[e.uniqueId];let t=this._transparentMeshesCache.indexOf(e);-1!==t&&this._transparentMeshesCache.splice(t,1),t=this._opaqueMeshesCache.indexOf(e),-1!==t&&this._opaqueMeshesCache.splice(t,1)}_parseScene(){this._scene.meshes.forEach(this._addMesh.bind(this)),this._scene.onNewMeshAddedObservable.add(this._addMesh.bind(this)),this._scene.onMeshRemovedObservable.add(this._removeMesh.bind(this))}_onMeshMaterialChanged(e){const t=this._transparentMeshesCache.indexOf(e),s=this._opaqueMeshesCache.indexOf(e);this._shouldRenderAsTransmission(e.material)?(e.material instanceof zn&&(e.material.subSurface.refractionTexture=this._opaqueRenderTarget),-1!==s?(this._opaqueMeshesCache.splice(s,1),this._transparentMeshesCache.push(e)):-1===t&&this._transparentMeshesCache.push(e)):-1!==t?(this._transparentMeshesCache.splice(t,1),this._opaqueMeshesCache.push(e)):-1===s&&this._opaqueMeshesCache.push(e)}_isRenderTargetValid(){return null!==this._opaqueRenderTarget?.getInternalTexture()}_setupRenderTargets(){let e,t;this._opaqueRenderTarget&&this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=new $r("opaqueSceneTexture",this._options.renderSize,this._scene,this._options.generateMipmaps,void 0,this._options.renderTargetTextureType),this._opaqueRenderTarget.ignoreCameraViewport=!0,this._opaqueRenderTarget.renderList=this._opaqueMeshesCache,this._opaqueRenderTarget.clearColor=this._options.clearColor?.clone()??this._scene.clearColor.clone(),this._opaqueRenderTarget.gammaSpace=!1,this._opaqueRenderTarget.lodGenerationScale=this._options.lodGenerationScale,this._opaqueRenderTarget.lodGenerationOffset=this._options.lodGenerationOffset,this._opaqueRenderTarget.samples=this._options.samples,this._opaqueRenderTarget.renderSprites=!0,this._opaqueRenderTarget.renderParticles=!0,this._opaqueRenderTarget.onBeforeBindObservable.add((s=>{t=this._scene.environmentIntensity,this._scene.environmentIntensity=1,e=this._scene.imageProcessingConfiguration.applyByPostProcess,this._options.clearColor?s.clearColor.copyFrom(this._options.clearColor):this._scene.clearColor.toLinearSpaceToRef(s.clearColor,this._scene.getEngine().useExactSrgbConversions),this._scene.imageProcessingConfiguration._applyByPostProcess=!0})),this._opaqueRenderTarget.onAfterUnbindObservable.add((()=>{this._scene.environmentIntensity=t,this._scene.imageProcessingConfiguration._applyByPostProcess=e})),this._transparentMeshesCache.forEach((e=>{this._shouldRenderAsTransmission(e.material)&&(e.material.refractionTexture=this._opaqueRenderTarget)}))}dispose(){this._scene._transmissionHelper=void 0,this._opaqueRenderTarget&&(this._opaqueRenderTarget.dispose(),this._opaqueRenderTarget=null),this._transparentMeshesCache=[],this._opaqueMeshesCache=[]}}const $o="KHR_materials_transmission";class Jo{constructor(e){this.name=$o,this.order=175,this._loader=e,this.enabled=this._loader.isExtensionUsed($o),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((i,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,s)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,s)),n.push(this._loadTransparentPropertiesAsync(i,t,s,r)),Promise.all(n).then((()=>{}))}))}_loadTransparentPropertiesAsync(e,t,s,i){if(!(s instanceof zn))throw new Error(`${e}: Material type not supported`);const r=s;if(r.subSurface.isRefractionEnabled=!0,r.subSurface.volumeIndexOfRefraction=1,r.subSurface.useAlbedoToTintRefraction=!0,void 0===i.transmissionFactor)return r.subSurface.refractionIntensity=0,r.subSurface.isRefractionEnabled=!1,Promise.resolve();{r.subSurface.refractionIntensity=i.transmissionFactor;const e=r.getScene();r.subSurface.refractionIntensity&&!e._transmissionHelper?new Zo({},r.getScene()):r.subSurface.refractionIntensity&&!e._transmissionHelper?._isRenderTargetValid()&&e._transmissionHelper?._setupRenderTargets()}return r.subSurface.minimumThickness=0,r.subSurface.maximumThickness=0,i.transmissionTexture?(i.transmissionTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/transmissionTexture`,i.transmissionTexture,void 0).then((e=>{r.subSurface.refractionIntensityTexture=e,r.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}ro.RegisterExtension($o,(e=>new Jo(e)));const eh="KHR_materials_diffuse_transmission";class th{constructor(e){this.name=eh,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(eh),this.enabled&&(e.parent.transparencyAsCoverage=!0)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((i,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,s)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,s)),n.push(this._loadTranslucentPropertiesAsync(i,t,s,r)),Promise.all(n).then((()=>{}))}))}_loadTranslucentPropertiesAsync(e,t,s,i){if(!(s instanceof zn))throw new Error(`${e}: Material type not supported`);const r=s;if(r.subSurface.isTranslucencyEnabled=!0,r.subSurface.volumeIndexOfRefraction=1,r.subSurface.minimumThickness=0,r.subSurface.maximumThickness=0,r.subSurface.useAlbedoToTintTranslucency=!1,void 0===i.diffuseTransmissionFactor)return r.subSurface.translucencyIntensity=0,r.subSurface.isTranslucencyEnabled=!1,Promise.resolve();r.subSurface.translucencyIntensity=i.diffuseTransmissionFactor;const n=new Array;return r.subSurface.useGltfStyleTextures=!0,i.diffuseTransmissionTexture&&(i.diffuseTransmissionTexture.nonColorData=!0,n.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionTexture`,i.diffuseTransmissionTexture).then((e=>{r.subSurface.translucencyIntensityTexture=e})))),void 0!==i.diffuseTransmissionColorFactor?r.subSurface.translucencyColor=ee.FromArray(i.diffuseTransmissionColorFactor):r.subSurface.translucencyColor=ee.White(),i.diffuseTransmissionColorTexture&&n.push(this._loader.loadTextureInfoAsync(`${e}/diffuseTransmissionColorTexture`,i.diffuseTransmissionColorTexture).then((e=>{r.subSurface.translucencyColorTexture=e}))),Promise.all(n).then((()=>{}))}}ro.RegisterExtension(eh,(e=>new th(e)));const sh="KHR_materials_volume";class ih{constructor(e){this.name=sh,this.order=173,this._loader=e,this.enabled=this._loader.isExtensionUsed(sh),this.enabled&&this._loader._disableInstancedMesh++}dispose(){this.enabled&&this._loader._disableInstancedMesh--,this._loader=null}loadMaterialPropertiesAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((i,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,s)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,s)),n.push(this._loadVolumePropertiesAsync(i,t,s,r)),Promise.all(n).then((()=>{}))}))}_loadVolumePropertiesAsync(e,t,s,i){if(!(s instanceof zn))throw new Error(`${e}: Material type not supported`);if(!s.subSurface.isRefractionEnabled&&!s.subSurface.isTranslucencyEnabled||!i.thicknessFactor)return Promise.resolve();s.subSurface.volumeIndexOfRefraction=s.indexOfRefraction;const r=void 0!==i.attenuationDistance?i.attenuationDistance:Number.MAX_VALUE;return s.subSurface.tintColorAtDistance=r,void 0!==i.attenuationColor&&3==i.attenuationColor.length&&s.subSurface.tintColor.copyFromFloats(i.attenuationColor[0],i.attenuationColor[1],i.attenuationColor[2]),s.subSurface.minimumThickness=0,s.subSurface.maximumThickness=i.thicknessFactor,s.subSurface.useThicknessAsDepth=!0,i.thicknessTexture?(i.thicknessTexture.nonColorData=!0,this._loader.loadTextureInfoAsync(`${e}/thicknessTexture`,i.thicknessTexture).then((e=>{e.name=`${s.name} (thickness)`,s.subSurface.thicknessTexture=e,s.subSurface.useGltfStyleTextures=!0}))):Promise.resolve()}}ro.RegisterExtension(sh,(e=>new ih(e)));const rh="KHR_materials_dispersion";class nh{constructor(e){this.name=rh,this.order=174,this._loader=e,this.enabled=this._loader.isExtensionUsed(rh)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((i,r)=>{const n=new Array;return n.push(this._loader.loadMaterialBasePropertiesAsync(e,t,s)),n.push(this._loader.loadMaterialPropertiesAsync(e,t,s)),n.push(this._loadDispersionPropertiesAsync(i,t,s,r)),Promise.all(n).then((()=>{}))}))}_loadDispersionPropertiesAsync(e,t,s,i){if(!(s instanceof zn))throw new Error(`${e}: Material type not supported`);return s.subSurface.isRefractionEnabled&&i.dispersion?(s.subSurface.isDispersionEnabled=!0,s.subSurface.dispersion=i.dispersion,Promise.resolve()):Promise.resolve()}}ro.RegisterExtension(rh,(e=>new nh(e)));const ah="KHR_mesh_quantization";class oh{constructor(e){this.name=ah,this.enabled=e.isExtensionUsed(ah)}dispose(){}}ro.RegisterExtension(ah,(e=>new oh(e)));const hh="KHR_texture_basisu";class lh{constructor(e){this.name=hh,this._loader=e,this.enabled=e.isExtensionUsed(hh)}dispose(){this._loader=null}_loadTextureAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((i,r)=>{const n=null==t.sampler?ro.DefaultSampler:io.Get(`${e}/sampler`,this._loader.gltf.samplers,t.sampler),a=io.Get(`${i}/source`,this._loader.gltf.images,r.source);return this._loader._createTextureAsync(e,n,a,(e=>{s(e)}),t._textureInfo.nonColorData?{useRGBAIfASTCBC7NotAvailableWhenUASTC:!0}:void 0,!t._textureInfo.nonColorData)}))}}ro.RegisterExtension(hh,(e=>new lh(e)));const ch="KHR_texture_transform";class uh{constructor(e){this.name=ch,this._loader=e,this.enabled=this._loader.isExtensionUsed(ch)}dispose(){this._loader=null}loadTextureInfoAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((i,r)=>this._loader.loadTextureInfoAsync(e,t,(e=>{if(!(e instanceof Dr))throw new Error(`${i}: Texture type not supported`);r.offset&&(e.uOffset=r.offset[0],e.vOffset=r.offset[1]),e.uRotationCenter=0,e.vRotationCenter=0,r.rotation&&(e.wAng=-r.rotation),r.scale&&(e.uScale=r.scale[0],e.vScale=r.scale[1]),null!=r.texCoord&&(e.coordinatesIndex=r.texCoord),s(e)}))))}}ro.RegisterExtension(ch,(e=>new uh(e)));const dh="KHR_xmp_json_ld";class _h{constructor(e){this.name=dh,this.order=100,this._loader=e,this.enabled=this._loader.isExtensionUsed(dh)}dispose(){this._loader=null}onLoading(){if(null===this._loader.rootBabylonMesh)return;const e=this._loader.gltf.extensions?.KHR_xmp_json_ld,t=this._loader.gltf.asset?.extensions?.KHR_xmp_json_ld;if(e&&t){const s=+t.packet;e.packets&&s<e.packets.length&&(this._loader.rootBabylonMesh.metadata=this._loader.rootBabylonMesh.metadata||{},this._loader.rootBabylonMesh.metadata.xmp=e.packets[s])}}}function fh(e,t,s,i){return ee.FromArray(t,s).scale(i)}function ph(e,t,s,i){return t[s]*i}function mh(e,t,s,i){return-t[s]*i}function gh(e,t,s,i){return t[s+1]*i}function Th(e,t,s,i){return t[s]*i*2}function Eh(e){return{scale:[new yh(xi.ANIMATIONTYPE_FLOAT,`${e}.uScale`,ph,(()=>2)),new yh(xi.ANIMATIONTYPE_FLOAT,`${e}.vScale`,gh,(()=>2))],offset:[new yh(xi.ANIMATIONTYPE_FLOAT,`${e}.uOffset`,ph,(()=>2)),new yh(xi.ANIMATIONTYPE_FLOAT,`${e}.vOffset`,gh,(()=>2))],rotation:[new yh(xi.ANIMATIONTYPE_FLOAT,`${e}.wAng`,mh,(()=>1))]}}ro.RegisterExtension(dh,(e=>new _h(e)));class Ah extends Ja{buildAnimations(e,t,s,i,r){r(e._babylonCamera,this._buildAnimation(t,s,i))}}class yh extends Ja{buildAnimations(e,t,s,i,r){for(const n in e._data)r(e._data[n].babylonMaterial,this._buildAnimation(t,s,i))}}class bh extends Ja{buildAnimations(e,t,s,i,r){r(e._babylonLight,this._buildAnimation(t,s,i))}}const Rh={__array__:{__target__:!0,...to}},xh={__array__:{__target__:!0,orthographic:{xmag:[new Ah(xi.ANIMATIONTYPE_FLOAT,"orthoLeft",mh,(()=>1)),new Ah(xi.ANIMATIONTYPE_FLOAT,"orthoRight",gh,(()=>1))],ymag:[new Ah(xi.ANIMATIONTYPE_FLOAT,"orthoBottom",mh,(()=>1)),new Ah(xi.ANIMATIONTYPE_FLOAT,"orthoTop",gh,(()=>1))],zfar:[new Ah(xi.ANIMATIONTYPE_FLOAT,"maxZ",ph,(()=>1))],znear:[new Ah(xi.ANIMATIONTYPE_FLOAT,"minZ",ph,(()=>1))]},perspective:{yfov:[new Ah(xi.ANIMATIONTYPE_FLOAT,"fov",ph,(()=>1))],zfar:[new Ah(xi.ANIMATIONTYPE_FLOAT,"maxZ",ph,(()=>1))],znear:[new Ah(xi.ANIMATIONTYPE_FLOAT,"minZ",ph,(()=>1))]}}},Mh={nodes:Rh,materials:{__array__:{__target__:!0,pbrMetallicRoughness:{baseColorFactor:[new yh(xi.ANIMATIONTYPE_COLOR3,"albedoColor",fh,(()=>4)),new yh(xi.ANIMATIONTYPE_FLOAT,"alpha",(function(e,t,s,i){return t[s+3]*i}),(()=>4))],metallicFactor:[new yh(xi.ANIMATIONTYPE_FLOAT,"metallic",ph,(()=>1))],roughnessFactor:[new yh(xi.ANIMATIONTYPE_FLOAT,"roughness",ph,(()=>1))],baseColorTexture:{extensions:{KHR_texture_transform:Eh("albedoTexture")}},metallicRoughnessTexture:{extensions:{KHR_texture_transform:Eh("metallicTexture")}}},emissiveFactor:[new yh(xi.ANIMATIONTYPE_COLOR3,"emissiveColor",fh,(()=>3))],normalTexture:{scale:[new yh(xi.ANIMATIONTYPE_FLOAT,"bumpTexture.level",ph,(()=>1))],extensions:{KHR_texture_transform:Eh("bumpTexture")}},occlusionTexture:{strength:[new yh(xi.ANIMATIONTYPE_FLOAT,"ambientTextureStrength",ph,(()=>1))],extensions:{KHR_texture_transform:Eh("ambientTexture")}},emissiveTexture:{extensions:{KHR_texture_transform:Eh("emissiveTexture")}},extensions:{KHR_materials_anisotropy:{anisotropyStrength:[new yh(xi.ANIMATIONTYPE_FLOAT,"anisotropy.intensity",ph,(()=>1))],anisotropyRotation:[new yh(xi.ANIMATIONTYPE_FLOAT,"anisotropy.angle",ph,(()=>1))],anisotropyTexture:{extensions:{KHR_texture_transform:Eh("anisotropy.texture")}}},KHR_materials_clearcoat:{clearcoatFactor:[new yh(xi.ANIMATIONTYPE_FLOAT,"clearCoat.intensity",ph,(()=>1))],clearcoatRoughnessFactor:[new yh(xi.ANIMATIONTYPE_FLOAT,"clearCoat.roughness",ph,(()=>1))],clearcoatTexture:{extensions:{KHR_texture_transform:Eh("clearCoat.texture")}},clearcoatNormalTexture:{scale:[new yh(xi.ANIMATIONTYPE_FLOAT,"clearCoat.bumpTexture.level",ph,(()=>1))],extensions:{KHR_texture_transform:Eh("clearCoat.bumpTexture")}},clearcoatRoughnessTexture:{extensions:{KHR_texture_transform:Eh("clearCoat.textureRoughness")}}},KHR_materials_dispersion:{dispersion:[new yh(xi.ANIMATIONTYPE_FLOAT,"subSurface.dispersion",ph,(()=>1))]},KHR_materials_emissive_strength:{emissiveStrength:[new yh(xi.ANIMATIONTYPE_FLOAT,"emissiveIntensity",ph,(()=>1))]},KHR_materials_ior:{ior:[new yh(xi.ANIMATIONTYPE_FLOAT,"indexOfRefraction",ph,(()=>1))]},KHR_materials_iridescence:{iridescenceFactor:[new yh(xi.ANIMATIONTYPE_FLOAT,"iridescence.intensity",ph,(()=>1))],iridescenceIor:[new yh(xi.ANIMATIONTYPE_FLOAT,"iridescence.indexOfRefraction",ph,(()=>1))],iridescenceThicknessMinimum:[new yh(xi.ANIMATIONTYPE_FLOAT,"iridescence.minimumThickness",ph,(()=>1))],iridescenceThicknessMaximum:[new yh(xi.ANIMATIONTYPE_FLOAT,"iridescence.maximumThickness",ph,(()=>1))],iridescenceTexture:{extensions:{KHR_texture_transform:Eh("iridescence.texture")}},iridescenceThicknessTexture:{extensions:{KHR_texture_transform:Eh("iridescence.thicknessTexture")}}},KHR_materials_sheen:{sheenColorFactor:[new yh(xi.ANIMATIONTYPE_COLOR3,"sheen.color",fh,(()=>3))],sheenRoughnessFactor:[new yh(xi.ANIMATIONTYPE_FLOAT,"sheen.roughness",ph,(()=>1))],sheenColorTexture:{extensions:{KHR_texture_transform:Eh("sheen.texture")}},sheenRoughnessTexture:{extensions:{KHR_texture_transform:Eh("sheen.textureRoughness")}}},KHR_materials_specular:{specularFactor:[new yh(xi.ANIMATIONTYPE_FLOAT,"metallicF0Factor",ph,(()=>1))],specularColorFactor:[new yh(xi.ANIMATIONTYPE_COLOR3,"metallicReflectanceColor",fh,(()=>3))],specularTexture:{extensions:{KHR_texture_transform:Eh("metallicReflectanceTexture")}},specularColorTexture:{extensions:{KHR_texture_transform:Eh("reflectanceTexture")}}},KHR_materials_transmission:{transmissionFactor:[new yh(xi.ANIMATIONTYPE_FLOAT,"subSurface.refractionIntensity",ph,(()=>1))],transmissionTexture:{extensions:{KHR_texture_transform:Eh("subSurface.refractionIntensityTexture")}}},KHR_materials_volume:{attenuationColor:[new yh(xi.ANIMATIONTYPE_COLOR3,"subSurface.tintColor",fh,(()=>3))],attenuationDistance:[new yh(xi.ANIMATIONTYPE_FLOAT,"subSurface.tintColorAtDistance",ph,(()=>1))],thicknessFactor:[new yh(xi.ANIMATIONTYPE_FLOAT,"subSurface.maximumThickness",ph,(()=>1))],thicknessTexture:{extensions:{KHR_texture_transform:Eh("subSurface.thicknessTexture")}}},KHR_materials_diffuse_transmission:{diffuseTransmissionFactor:[new yh(xi.ANIMATIONTYPE_FLOAT,"subSurface.translucencyIntensity",ph,(()=>1))],diffuseTransmissionTexture:{extensions:{KHR_texture_transform:Eh("subSurface.translucencyIntensityTexture")}},diffuseTransmissionColorFactor:[new yh(xi.ANIMATIONTYPE_COLOR3,"subSurface.translucencyColor",fh,(()=>3))],diffuseTransmissionColorTexture:{extensions:{KHR_texture_transform:Eh("subSurface.translucencyColorTexture")}}}}}},cameras:xh,extensions:{KHR_lights_punctual:{lights:{__array__:{__target__:!0,color:[new bh(xi.ANIMATIONTYPE_COLOR3,"diffuse",fh,(()=>3))],intensity:[new bh(xi.ANIMATIONTYPE_FLOAT,"intensity",ph,(()=>1))],range:[new bh(xi.ANIMATIONTYPE_FLOAT,"range",ph,(()=>1))],spot:{innerConeAngle:[new bh(xi.ANIMATIONTYPE_FLOAT,"innerAngle",Th,(()=>1))],outerConeAngle:[new bh(xi.ANIMATIONTYPE_FLOAT,"angle",Th,(()=>1))]}}}}}};class Ih{constructor(e,t){this._gltf=e,this._infoTree=t}convert(e){let t,s=this._gltf,i=this._infoTree;if(!e.startsWith("/"))throw new Error("Path must start with a /");const r=e.split("/");r.shift();for(const n of r){if(i.__array__)i=i.__array__;else if(i=i[n],!i)throw new Error(`Path ${e} is invalid`);if(void 0===s)throw new Error(`Path ${e} is invalid`);s=s[n],i.__target__&&(t=s)}return{object:t,info:i}}}const Sh="KHR_animation_pointer";class vh extends Ih{constructor(e){super(e,Mh)}}class Ch{constructor(e){this.name=Sh,this._loader=e,this._pathToObjectConverter=new vh(this._loader.gltf)}get enabled(){return this._loader.isExtensionUsed(Sh)}dispose(){this._loader=null,delete this._pathToObjectConverter}_loadAnimationChannelAsync(e,t,s,i,r){const n=i.target.extensions?.KHR_animation_pointer;if(!n||!this._pathToObjectConverter)return null;"pointer"!==i.target.path&&ue.Warn(`${e}/target/path: Value (${i.target.path}) must be (pointer) when using the ${this.name} extension`),null!=i.target.node&&ue.Warn(`${e}/target/node: Value (${i.target.node}) must not be present when using the ${this.name} extension`);const a=`${e}/extensions/${this.name}`,o=n.pointer;if(!o)throw new Error(`${a}: Pointer is missing`);try{const n=this._pathToObjectConverter.convert(o);return this._loader._loadAnimationChannelFromTargetInfoAsync(e,t,s,i,n,r)}catch(e){return ue.Warn(`${a}/pointer: Invalid pointer (${o}) skipped`),null}}}ro.RegisterExtension(Sh,(e=>new Ch(e)));class Ph{constructor(e,t,s){this.frame=e,this.action=t,this.onlyOnce=s,this.isDone=!1}_clone(){return new Ph(this.frame,this.action,this.onlyOnce)}}class Oh{get loop(){return this._loop}set loop(e){e!==this._loop&&(this._loop=e,this.updateOptions({loop:e}))}get currentTime(){if(this._htmlAudioElement)return this._htmlAudioElement.currentTime;if(yt.audioEngine?.audioContext&&(this.isPlaying||this.isPaused)){const e=this.isPaused?0:yt.audioEngine.audioContext.currentTime-this._startTime;return this._currentTime+e}return 0}get spatialSound(){return this._spatialSound}set spatialSound(e){if(e==this._spatialSound)return;const t=this.isPlaying;this.pause(),e?(this._spatialSound=e,this._updateSpatialParameters()):this._disableSpatialSound(),t&&this.play()}constructor(e,t,s,i=null,r){if(this.autoplay=!1,this._loop=!1,this.useCustomAttenuation=!1,this.isPlaying=!1,this.isPaused=!1,this.refDistance=1,this.rolloffFactor=1,this.maxDistance=100,this.distanceModel="linear",this.metadata=null,this.onEndedObservable=new g,this._spatialSound=!1,this._panningModel="equalpower",this._playbackRate=1,this._streaming=!1,this._startTime=0,this._currentTime=0,this._position=U.Zero(),this._localDirection=new U(1,0,0),this._volume=1,this._isReadyToPlay=!1,this._isDirectional=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._coneOuterGain=0,this._isOutputConnected=!1,this._urlType="Unknown",this.name=e,s=s||C.LastCreatedScene)if(this._scene=s,Oh._SceneComponentInitialization(s),this._readyToPlayCallback=i,this._customAttenuationFunction=(e,t,s,i,r)=>t<s?e*(1-t/s):0,r&&(this.autoplay=r.autoplay||!1,this._loop=r.loop||!1,void 0!==r.volume&&(this._volume=r.volume),this._spatialSound=r.spatialSound??!1,this.maxDistance=r.maxDistance??100,this.useCustomAttenuation=r.useCustomAttenuation??!1,this.rolloffFactor=r.rolloffFactor||1,this.refDistance=r.refDistance||1,this.distanceModel=r.distanceModel||"linear",this._playbackRate=r.playbackRate||1,this._streaming=r.streaming??!1,this._length=r.length,this._offset=r.offset),yt.audioEngine?.canUseWebAudio&&yt.audioEngine.audioContext){this._soundGain=yt.audioEngine.audioContext.createGain(),this._soundGain.gain.value=this._volume,this._inputAudioNode=this._soundGain,this._outputAudioNode=this._soundGain,this._spatialSound&&this._createSpatialParameters(),this._scene.mainSoundTrack.addSound(this);let e=!0;if(t)try{"string"==typeof t?(this._urlType="String",this._url=t):t instanceof ArrayBuffer?this._urlType="ArrayBuffer":t instanceof HTMLMediaElement?this._urlType="MediaElement":t instanceof MediaStream?this._urlType="MediaStream":t instanceof AudioBuffer?this._urlType="AudioBuffer":Array.isArray(t)&&(this._urlType="Array");let s=[],i=!1;switch(this._urlType){case"MediaElement":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=yt.audioEngine.audioContext.createMediaElementSource(t),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"MediaStream":this._streaming=!0,this._isReadyToPlay=!0,this._streamingSource=yt.audioEngine.audioContext.createMediaStreamSource(t),this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback();break;case"ArrayBuffer":t.byteLength>0&&(i=!0,this._soundLoaded(t));break;case"AudioBuffer":this._audioBufferLoaded(t);break;case"String":s.push(t);case"Array":0===s.length&&(s=t);for(let e=0;e<s.length;e++){const t=s[e];if(i=r&&r.skipCodecCheck||-1!==t.indexOf(".mp3",t.length-4)&&yt.audioEngine.isMP3supported||-1!==t.indexOf(".ogg",t.length-4)&&yt.audioEngine.isOGGsupported||-1!==t.indexOf(".wav",t.length-4)||-1!==t.indexOf(".m4a",t.length-4)||-1!==t.indexOf(".mp4",t.length-4)||-1!==t.indexOf("blob:"),i){this._streaming?(this._htmlAudioElement=new Audio(t),this._htmlAudioElement.controls=!1,this._htmlAudioElement.loop=this.loop,Yt.SetCorsBehavior(t,this._htmlAudioElement),this._htmlAudioElement.preload="auto",this._htmlAudioElement.addEventListener("canplaythrough",(()=>{this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback()})),document.body.appendChild(this._htmlAudioElement),this._htmlAudioElement.load()):this._scene._loadFile(t,(e=>{this._soundLoaded(e)}),void 0,!0,!0,(e=>{e&&ue.Error("XHR "+e.status+" error on: "+t+"."),ue.Error("Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}));break}}break;default:e=!1}e?i||(this._isReadyToPlay=!0,this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)):ue.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.")}catch(e){ue.Error("Unexpected error. Sound creation aborted."),this._scene.mainSoundTrack.removeSound(this)}}else this._scene.mainSoundTrack.addSound(this),yt.audioEngine&&!yt.audioEngine.WarnedWebAudioUnsupported&&(ue.Error("Web Audio is not supported by your browser."),yt.audioEngine.WarnedWebAudioUnsupported=!0),this._readyToPlayCallback&&setTimeout((()=>{this._readyToPlayCallback&&this._readyToPlayCallback()}),1e3)}dispose(){yt.audioEngine?.canUseWebAudio&&(this.isPlaying&&this.stop(),this._isReadyToPlay=!1,-1===this.soundTrackId?this._scene.mainSoundTrack.removeSound(this):this._scene.soundTracks&&this._scene.soundTracks[this.soundTrackId].removeSound(this),this._soundGain&&(this._soundGain.disconnect(),this._soundGain=null),this._soundPanner&&(this._soundPanner.disconnect(),this._soundPanner=null),this._soundSource&&(this._soundSource.disconnect(),this._soundSource=null),this._audioBuffer=null,this._htmlAudioElement&&(this._htmlAudioElement.pause(),this._htmlAudioElement.src="",document.body.removeChild(this._htmlAudioElement)),this._streamingSource&&this._streamingSource.disconnect(),this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._connectedTransformNode=null),this._clearTimeoutsAndObservers())}isReady(){return this._isReadyToPlay}getClassName(){return"Sound"}_audioBufferLoaded(e){yt.audioEngine?.audioContext&&(this._audioBuffer=e,this._isReadyToPlay=!0,this.autoplay&&this.play(0,this._offset,this._length),this._readyToPlayCallback&&this._readyToPlayCallback())}_soundLoaded(e){yt.audioEngine?.audioContext&&yt.audioEngine.audioContext.decodeAudioData(e,(e=>{this._audioBufferLoaded(e)}),(e=>{ue.Error("Error while decoding audio data for: "+this.name+" / Error: "+e)}))}setAudioBuffer(e){yt.audioEngine?.canUseWebAudio&&(this._audioBuffer=e,this._isReadyToPlay=!0)}updateOptions(e){e&&(this.loop=e.loop??this.loop,this.maxDistance=e.maxDistance??this.maxDistance,this.useCustomAttenuation=e.useCustomAttenuation??this.useCustomAttenuation,this.rolloffFactor=e.rolloffFactor??this.rolloffFactor,this.refDistance=e.refDistance??this.refDistance,this.distanceModel=e.distanceModel??this.distanceModel,this._playbackRate=e.playbackRate??this._playbackRate,this._length=e.length??void 0,this.spatialSound=e.spatialSound??this._spatialSound,this._setOffset(e.offset??void 0),this.setVolume(e.volume??this._volume),this._updateSpatialParameters(),this.isPlaying&&(this._streaming&&this._htmlAudioElement?(this._htmlAudioElement.playbackRate=this._playbackRate,this._htmlAudioElement.loop!==this.loop&&(this._htmlAudioElement.loop=this.loop)):this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.loop!==this.loop&&(this._soundSource.loop=this.loop),void 0!==this._offset&&this._soundSource.loopStart!==this._offset&&(this._soundSource.loopStart=this._offset),void 0!==this._length&&this._length!==this._soundSource.loopEnd&&(this._soundSource.loopEnd=(0|this._offset)+this._length))))}_createSpatialParameters(){yt.audioEngine?.canUseWebAudio&&yt.audioEngine.audioContext&&(this._scene.headphone&&(this._panningModel="HRTF"),this._soundPanner=this._soundPanner??yt.audioEngine.audioContext.createPanner(),this._soundPanner&&this._outputAudioNode&&(this._updateSpatialParameters(),this._soundPanner.connect(this._outputAudioNode),this._inputAudioNode=this._soundPanner))}_disableSpatialSound(){this._spatialSound&&(this._inputAudioNode=this._soundGain,this._soundPanner?.disconnect(),this._soundPanner=null,this._spatialSound=!1)}_updateSpatialParameters(){this._spatialSound&&(this._soundPanner?this.useCustomAttenuation?(this._soundPanner.distanceModel="linear",this._soundPanner.maxDistance=Number.MAX_VALUE,this._soundPanner.refDistance=1,this._soundPanner.rolloffFactor=1,this._soundPanner.panningModel=this._panningModel):(this._soundPanner.distanceModel=this.distanceModel,this._soundPanner.maxDistance=this.maxDistance,this._soundPanner.refDistance=this.refDistance,this._soundPanner.rolloffFactor=this.rolloffFactor,this._soundPanner.panningModel=this._panningModel):this._createSpatialParameters())}switchPanningModelToHRTF(){this._panningModel="HRTF",this._switchPanningModel()}switchPanningModelToEqualPower(){this._panningModel="equalpower",this._switchPanningModel()}_switchPanningModel(){yt.audioEngine?.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.panningModel=this._panningModel)}connectToSoundTrackAudioNode(e){yt.audioEngine?.canUseWebAudio&&this._outputAudioNode&&(this._isOutputConnected&&this._outputAudioNode.disconnect(),this._outputAudioNode.connect(e),this._isOutputConnected=!0)}setDirectionalCone(e,t,s){t<e?ue.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle."):(this._coneInnerAngle=e,this._coneOuterAngle=t,this._coneOuterGain=s,this._isDirectional=!0,this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length)))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!=this._coneInnerAngle){if(this._coneOuterAngle<e)return void ue.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneInnerAngle=e,yt.audioEngine?.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle)}}get directionalConeOuterAngle(){return this._coneOuterAngle}set directionalConeOuterAngle(e){if(e!=this._coneOuterAngle){if(e<this._coneInnerAngle)return void ue.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneOuterAngle=e,yt.audioEngine?.canUseWebAudio&&this._spatialSound&&this._soundPanner&&(this._soundPanner.coneOuterAngle=this._coneOuterAngle)}}setPosition(e){e.equals(this._position)||(this._position.copyFrom(e),yt.audioEngine?.canUseWebAudio&&this._spatialSound&&this._soundPanner&&!isNaN(this._position.x)&&!isNaN(this._position.y)&&!isNaN(this._position.z)&&(this._soundPanner.positionX.value=this._position.x,this._soundPanner.positionY.value=this._position.y,this._soundPanner.positionZ.value=this._position.z))}setLocalDirectionToMesh(e){this._localDirection=e,yt.audioEngine?.canUseWebAudio&&this._connectedTransformNode&&this.isPlaying&&this._updateDirection()}_updateDirection(){if(!this._connectedTransformNode||!this._soundPanner)return;const e=this._connectedTransformNode.getWorldMatrix(),t=U.TransformNormal(this._localDirection,e);t.normalize(),this._soundPanner.orientationX.value=t.x,this._soundPanner.orientationY.value=t.y,this._soundPanner.orientationZ.value=t.z}updateDistanceFromListener(){if(yt.audioEngine?.canUseWebAudio&&this._connectedTransformNode&&this.useCustomAttenuation&&this._soundGain&&this._scene.activeCamera){const e=this._scene.audioListenerPositionProvider?this._connectedTransformNode.position.subtract(this._scene.audioListenerPositionProvider()).length():this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera);this._soundGain.gain.value=this._customAttenuationFunction(this._volume,e,this.maxDistance,this.refDistance,this.rolloffFactor)}}setAttenuationFunction(e){this._customAttenuationFunction=e}play(e,t,s){if(this._isReadyToPlay&&this._scene.audioEnabled&&yt.audioEngine?.audioContext)try{this._clearTimeoutsAndObservers();let i=e?yt.audioEngine?.audioContext.currentTime+e:yt.audioEngine?.audioContext.currentTime;if(this._soundSource&&this._streamingSource||this._spatialSound&&this._soundPanner&&(isNaN(this._position.x)||isNaN(this._position.y)||isNaN(this._position.z)||(this._soundPanner.positionX.value=this._position.x,this._soundPanner.positionY.value=this._position.y,this._soundPanner.positionZ.value=this._position.z),this._isDirectional&&(this._soundPanner.coneInnerAngle=this._coneInnerAngle,this._soundPanner.coneOuterAngle=this._coneOuterAngle,this._soundPanner.coneOuterGain=this._coneOuterGain,this._connectedTransformNode?this._updateDirection():this._soundPanner.setOrientation(this._localDirection.x,this._localDirection.y,this._localDirection.z))),this._streaming){if(this._streamingSource||(this._streamingSource=yt.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement),this._htmlAudioElement.onended=()=>{this._onended()},this._htmlAudioElement.playbackRate=this._playbackRate),this._streamingSource.disconnect(),this._inputAudioNode&&this._streamingSource.connect(this._inputAudioNode),this._htmlAudioElement){const e=()=>{if(yt.audioEngine?.unlocked){const t=this._htmlAudioElement.play();void 0!==t&&t.catch((()=>{yt.audioEngine?.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=yt.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))}))}else(this.loop||this.autoplay)&&(this._audioUnlockedObserver=yt.audioEngine?.onAudioUnlockedObservable.addOnce((()=>{e()})))};e()}}else{const r=()=>{if(yt.audioEngine?.audioContext){if(s=s||this._length,void 0!==t&&this._setOffset(t),this._soundSource){const e=this._soundSource;e.onended=()=>{e.disconnect()}}if(this._soundSource=yt.audioEngine?.audioContext.createBufferSource(),this._soundSource&&this._inputAudioNode){this._soundSource.buffer=this._audioBuffer,this._soundSource.connect(this._inputAudioNode),this._soundSource.loop=this.loop,void 0!==t&&(this._soundSource.loopStart=t),void 0!==s&&(this._soundSource.loopEnd=(0|t)+s),this._soundSource.playbackRate.value=this._playbackRate,this._soundSource.onended=()=>{this._onended()},i=e?yt.audioEngine?.audioContext.currentTime+e:yt.audioEngine.audioContext.currentTime;const r=((this.isPaused?this.currentTime:0)+(this._offset??0))%this._soundSource.buffer.duration;this._soundSource.start(i,r,this.loop?void 0:s)}}};"suspended"===yt.audioEngine?.audioContext.state?this._tryToPlayTimeout=setTimeout((()=>{"suspended"===yt.audioEngine?.audioContext.state?(yt.audioEngine.lock(),(this.loop||this.autoplay)&&(this._audioUnlockedObserver=yt.audioEngine.onAudioUnlockedObservable.addOnce((()=>{r()})))):r()}),500):r()}this._startTime=i,this.isPlaying=!0,this.isPaused=!1}catch(e){ue.Error("Error while trying to play audio: "+this.name+", "+e.message)}}_onended(){this.isPlaying=!1,this._startTime=0,this._currentTime=0,this.onended&&this.onended(),this.onEndedObservable.notifyObservers(this)}stop(e){if(this.isPlaying)if(this._clearTimeoutsAndObservers(),this._streaming)this._htmlAudioElement?(this._htmlAudioElement.pause(),this._htmlAudioElement.currentTime>0&&(this._htmlAudioElement.currentTime=0)):this._streamingSource.disconnect(),this.isPlaying=!1;else if(yt.audioEngine?.audioContext&&this._soundSource){const t=e?yt.audioEngine.audioContext.currentTime+e:void 0;this._soundSource.onended=()=>{this.isPlaying=!1,this.isPaused=!1,this._startTime=0,this._currentTime=0,this._soundSource&&(this._soundSource.onended=()=>{}),this._onended()},this._soundSource.stop(t)}else this.isPlaying=!1;else this.isPaused&&(this.isPaused=!1,this._startTime=0,this._currentTime=0)}pause(){this.isPlaying&&(this._clearTimeoutsAndObservers(),this._streaming?(this._htmlAudioElement?this._htmlAudioElement.pause():this._streamingSource.disconnect(),this.isPlaying=!1,this.isPaused=!0):yt.audioEngine?.audioContext&&this._soundSource&&(this._soundSource.onended=()=>{},this._soundSource.stop(),this.isPlaying=!1,this.isPaused=!0,this._currentTime+=yt.audioEngine.audioContext.currentTime-this._startTime))}setVolume(e,t){yt.audioEngine?.canUseWebAudio&&this._soundGain&&(t&&yt.audioEngine.audioContext?(this._soundGain.gain.cancelScheduledValues(yt.audioEngine.audioContext.currentTime),this._soundGain.gain.setValueAtTime(this._soundGain.gain.value,yt.audioEngine.audioContext.currentTime),this._soundGain.gain.linearRampToValueAtTime(e,yt.audioEngine.audioContext.currentTime+t)):this._soundGain.gain.value=e),this._volume=e}setPlaybackRate(e){this._playbackRate=e,this.isPlaying&&(this._streaming&&this._htmlAudioElement?this._htmlAudioElement.playbackRate=this._playbackRate:this._soundSource&&(this._soundSource.playbackRate.value=this._playbackRate))}getPlaybackRate(){return this._playbackRate}getVolume(){return this._volume}attachToMesh(e){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null),this._connectedTransformNode=e,this._spatialSound||(this._spatialSound=!0,this._createSpatialParameters(),this.isPlaying&&this.loop&&(this.stop(),this.play(0,this._offset,this._length))),this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode),this._registerFunc=e=>this._onRegisterAfterWorldMatrixUpdate(e),this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc)}detachFromMesh(){this._connectedTransformNode&&this._registerFunc&&(this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc),this._registerFunc=null,this._connectedTransformNode=null)}_onRegisterAfterWorldMatrixUpdate(e){if(e.getBoundingInfo){const t=e.getBoundingInfo();this.setPosition(t.boundingSphere.centerWorld)}else this.setPosition(e.absolutePosition);yt.audioEngine?.canUseWebAudio&&this._isDirectional&&this.isPlaying&&this._updateDirection()}clone(){if(this._streaming)return null;{const e=()=>{this._isReadyToPlay?(s._audioBuffer=this.getAudioBuffer(),s._isReadyToPlay=!0,s.autoplay&&s.play(0,this._offset,this._length)):setTimeout(e,300)},t={autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,useCustomAttenuation:this.useCustomAttenuation,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel},s=new Oh(this.name+"_cloned",new ArrayBuffer(0),this._scene,null,t);return this.useCustomAttenuation&&s.setAttenuationFunction(this._customAttenuationFunction),s.setPosition(this._position),s.setPlaybackRate(this._playbackRate),e(),s}}getAudioBuffer(){return this._audioBuffer}getSoundSource(){return this._soundSource}getSoundGain(){return this._soundGain}serialize(){const e={name:this.name,url:this._url,autoplay:this.autoplay,loop:this.loop,volume:this._volume,spatialSound:this._spatialSound,maxDistance:this.maxDistance,rolloffFactor:this.rolloffFactor,refDistance:this.refDistance,distanceModel:this.distanceModel,playbackRate:this._playbackRate,panningModel:this._panningModel,soundTrackId:this.soundTrackId,metadata:this.metadata};return this._spatialSound&&(this._connectedTransformNode&&(e.connectedMeshId=this._connectedTransformNode.id),e.position=this._position.asArray(),e.refDistance=this.refDistance,e.distanceModel=this.distanceModel,e.isDirectional=this._isDirectional,e.localDirectionToMesh=this._localDirection.asArray(),e.coneInnerAngle=this._coneInnerAngle,e.coneOuterAngle=this._coneOuterAngle,e.coneOuterGain=this._coneOuterGain),e}static Parse(e,t,s,i){const r=e.name;let n;n=e.url?s+e.url:s+r;const a={autoplay:e.autoplay,loop:e.loop,volume:e.volume,spatialSound:e.spatialSound,maxDistance:e.maxDistance,rolloffFactor:e.rolloffFactor,refDistance:e.refDistance,distanceModel:e.distanceModel,playbackRate:e.playbackRate};let o;if(i){const e=()=>{i._isReadyToPlay?(o._audioBuffer=i.getAudioBuffer(),o._isReadyToPlay=!0,o.autoplay&&o.play(0,o._offset,o._length)):setTimeout(e,300)};o=new Oh(r,new ArrayBuffer(0),t,null,a),e()}else o=new Oh(r,n,t,(()=>{t.removePendingData(o)}),a),t.addPendingData(o);if(e.position){const t=U.FromArray(e.position);o.setPosition(t)}if(e.isDirectional&&(o.setDirectionalCone(e.coneInnerAngle||360,e.coneOuterAngle||360,e.coneOuterGain||0),e.localDirectionToMesh)){const t=U.FromArray(e.localDirectionToMesh);o.setLocalDirectionToMesh(t)}if(e.connectedMeshId){const s=t.getMeshById(e.connectedMeshId);s&&o.attachToMesh(s)}return e.metadata&&(o.metadata=e.metadata),o}_setOffset(e){this._offset!==e&&(this.isPaused&&(this.stop(),this.isPaused=!1),this._offset=e)}_clearTimeoutsAndObservers(){this._tryToPlayTimeout&&(clearTimeout(this._tryToPlayTimeout),this._tryToPlayTimeout=null),this._audioUnlockedObserver&&(yt.audioEngine?.onAudioUnlockedObservable.remove(this._audioUnlockedObserver),this._audioUnlockedObserver=null)}}Oh._SceneComponentInitialization=e=>{throw Y("AudioSceneComponent")},I("BABYLON.Sound",Oh);class Dh{constructor(e,t,s){if(this.loop=!1,this._coneInnerAngle=360,this._coneOuterAngle=360,this._volume=1,this.isPlaying=!1,this.isPaused=!1,this._sounds=[],this._weights=[],t.length!==s.length)throw new Error("Sounds length does not equal weights length");this.loop=e,this._weights=s;let i=0;for(const e of s)i+=e;const r=i>0?1/i:0;for(let e=0;e<this._weights.length;e++)this._weights[e]*=r;this._sounds=t;for(const e of this._sounds)e.onEndedObservable.add((()=>{this._onended()}))}get directionalConeInnerAngle(){return this._coneInnerAngle}set directionalConeInnerAngle(e){if(e!==this._coneInnerAngle){if(this._coneOuterAngle<e)return void ue.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneInnerAngle=e;for(const t of this._sounds)t.directionalConeInnerAngle=e}}get directionalConeOuterAngle(){return this._coneOuterAngle}set directionalConeOuterAngle(e){if(e!==this._coneOuterAngle){if(e<this._coneInnerAngle)return void ue.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");this._coneOuterAngle=e;for(const t of this._sounds)t.directionalConeOuterAngle=e}}get volume(){return this._volume}set volume(e){if(e!==this._volume)for(const t of this._sounds)t.setVolume(e)}_onended(){void 0!==this._currentIndex&&(this._sounds[this._currentIndex].autoplay=!1),this.loop&&this.isPlaying?this.play():this.isPlaying=!1}pause(){this.isPaused=!0,void 0!==this._currentIndex&&this._sounds[this._currentIndex].pause()}stop(){this.isPlaying=!1,void 0!==this._currentIndex&&this._sounds[this._currentIndex].stop()}play(e){if(!this.isPaused){this.stop();const e=Math.random();let t=0;for(let s=0;s<this._weights.length;s++)if(t+=this._weights[s],e<=t){this._currentIndex=s;break}}const t=this._sounds[this._currentIndex];t.isReady()?t.play(0,this.isPaused?void 0:e):t.autoplay=!0,this.isPlaying=!0,this.isPaused=!1}}const Lh="MSFT_audio_emitter";class Fh{constructor(e){this.name=Lh,this._loader=e,this.enabled=this._loader.isExtensionUsed(Lh)}dispose(){this._loader=null,this._clips=null,this._emitters=null}onLoading(){const e=this._loader.gltf.extensions;if(e&&e[this.name]){const t=e[this.name];this._clips=t.clips,this._emitters=t.emitters,io.Assign(this._clips),io.Assign(this._emitters)}}loadSceneAsync(e,t){return ro.LoadExtensionAsync(e,t,this.name,((s,i)=>{const r=new Array;r.push(this._loader.loadSceneAsync(e,t));for(const e of i.emitters){const t=io.Get(`${s}/emitters`,this._emitters,e);if(null!=t.refDistance||null!=t.maxDistance||null!=t.rolloffFactor||null!=t.distanceModel||null!=t.innerAngle||null!=t.outerAngle)throw new Error(`${s}: Direction or Distance properties are not allowed on emitters attached to a scene`);r.push(this._loadEmitterAsync(`${s}/emitters/${t.index}`,t))}return Promise.all(r).then((()=>{}))}))}loadNodeAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((e,i)=>{const r=new Array;return this._loader.loadNodeAsync(e,t,(t=>{for(const s of i.emitters){const i=io.Get(`${e}/emitters`,this._emitters,s);r.push(this._loadEmitterAsync(`${e}/emitters/${i.index}`,i).then((()=>{for(const e of i._babylonSounds)e.attachToMesh(t),null==i.innerAngle&&null==i.outerAngle||(e.setLocalDirectionToMesh(U.Forward()),e.setDirectionalCone(2*Yt.ToDegrees(null==i.innerAngle?Math.PI:i.innerAngle),2*Yt.ToDegrees(null==i.outerAngle?Math.PI:i.outerAngle),0))})))}s(t)})).then((e=>Promise.all(r).then((()=>e))))}))}loadAnimationAsync(e,t){return ro.LoadExtensionAsync(e,t,this.name,((s,i)=>this._loader.loadAnimationAsync(e,t).then((r=>{const n=new Array;io.Assign(i.events);for(const a of i.events)n.push(this._loadAnimationEventAsync(`${s}/events/${a.index}`,e,t,a,r));return Promise.all(n).then((()=>r))}))))}_loadClipAsync(e,t){if(t._objectURL)return t._objectURL;let s;if(t.uri)s=this._loader.loadUriAsync(e,t,t.uri);else{const i=io.Get(`${e}/bufferView`,this._loader.gltf.bufferViews,t.bufferView);s=this._loader.loadBufferViewAsync(`/bufferViews/${i.index}`,i)}return t._objectURL=s.then((e=>URL.createObjectURL(new Blob([e],{type:t.mimeType})))),t._objectURL}_loadEmitterAsync(e,t){if(t._babylonSounds=t._babylonSounds||[],!t._babylonData){const e=new Array,s=t.name||`emitter${t.index}`,i={loop:!1,autoplay:!1,volume:null==t.volume?1:t.volume};for(let r=0;r<t.clips.length;r++){const n=`/extensions/${this.name}/clips`,a=io.Get(n,this._clips,t.clips[r].clip);e.push(this._loadClipAsync(`${n}/${t.clips[r].clip}`,a).then((e=>{const n=t._babylonSounds[r]=new Oh(s,e,this._loader.babylonScene,null,i);n.refDistance=t.refDistance||1,n.maxDistance=t.maxDistance||256,n.rolloffFactor=t.rolloffFactor||1,n.distanceModel=t.distanceModel||"exponential"})))}const r=Promise.all(e).then((()=>{const e=t.clips.map((e=>e.weight||1)),s=new Dh(t.loop||!1,t._babylonSounds,e);t.innerAngle&&(s.directionalConeInnerAngle=2*Yt.ToDegrees(t.innerAngle)),t.outerAngle&&(s.directionalConeOuterAngle=2*Yt.ToDegrees(t.outerAngle)),t.volume&&(s.volume=t.volume),t._babylonData.sound=s}));t._babylonData={loaded:r}}return t._babylonData.loaded}_getEventAction(e,t,s,i,r){switch(s){case"play":return e=>{const s=(r||0)+(e-i);t.play(s)};case"stop":return()=>{t.stop()};case"pause":return()=>{t.pause()};default:throw new Error(`${e}: Unsupported action ${s}`)}}_loadAnimationEventAsync(e,t,s,i,r){if(0==r.targetedAnimations.length)return Promise.resolve();const n=r.targetedAnimations[0],a=i.emitter,o=io.Get(`/extensions/${this.name}/emitters`,this._emitters,a);return this._loadEmitterAsync(e,o).then((()=>{const t=o._babylonData.sound;if(t){const s=new Ph(i.time,this._getEventAction(e,t,i.action,i.time,i.startOffset));n.animation.addEvent(s),r.onAnimationGroupEndObservable.add((()=>{t.stop()})),r.onAnimationGroupPauseObservable.add((()=>{t.pause()}))}}))}}ro.RegisterExtension(Lh,(e=>new Fh(e)));const Nh="MSFT_lod";class wh{constructor(e){this.name=Nh,this.order=100,this.maxLODsToLoad=10,this.onNodeLODsLoadedObservable=new g,this.onMaterialLODsLoadedObservable=new g,this._bufferLODs=new Array,this._nodeIndexLOD=null,this._nodeSignalLODs=new Array,this._nodePromiseLODs=new Array,this._nodeBufferLODs=new Array,this._materialIndexLOD=null,this._materialSignalLODs=new Array,this._materialPromiseLODs=new Array,this._materialBufferLODs=new Array,this._loader=e,this.maxLODsToLoad=this._loader.parent.extensionOptions[Nh]?.maxLODsToLoad??this.maxLODsToLoad,this.enabled=this._loader.isExtensionUsed(Nh)}dispose(){this._loader=null,this._nodeIndexLOD=null,this._nodeSignalLODs.length=0,this._nodePromiseLODs.length=0,this._nodeBufferLODs.length=0,this._materialIndexLOD=null,this._materialSignalLODs.length=0,this._materialPromiseLODs.length=0,this._materialBufferLODs.length=0,this.onMaterialLODsLoadedObservable.clear(),this.onNodeLODsLoadedObservable.clear()}onReady(){for(let e=0;e<this._nodePromiseLODs.length;e++){const t=Promise.all(this._nodePromiseLODs[e]).then((()=>{0!==e&&(this._loader.endPerformanceCounter(`Node LOD ${e}`),this._loader.log(`Loaded node LOD ${e}`)),this.onNodeLODsLoadedObservable.notifyObservers(e),e!==this._nodePromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Node LOD ${e+1}`),this._loadBufferLOD(this._nodeBufferLODs,e+1),this._nodeSignalLODs[e]&&this._nodeSignalLODs[e].resolve())}));this._loader._completePromises.push(t)}for(let e=0;e<this._materialPromiseLODs.length;e++){const t=Promise.all(this._materialPromiseLODs[e]).then((()=>{0!==e&&(this._loader.endPerformanceCounter(`Material LOD ${e}`),this._loader.log(`Loaded material LOD ${e}`)),this.onMaterialLODsLoadedObservable.notifyObservers(e),e!==this._materialPromiseLODs.length-1&&(this._loader.startPerformanceCounter(`Material LOD ${e+1}`),this._loadBufferLOD(this._materialBufferLODs,e+1),this._materialSignalLODs[e]&&this._materialSignalLODs[e].resolve())}));this._loader._completePromises.push(t)}}loadSceneAsync(e,t){const s=this._loader.loadSceneAsync(e,t);return this._loadBufferLOD(this._bufferLODs,0),s}loadNodeAsync(e,t,s){return ro.LoadExtensionAsync(e,t,this.name,((e,i)=>{let r;const n=this._getLODs(e,t,this._loader.gltf.nodes,i.ids);this._loader.logOpen(`${e}`);for(let e=0;e<n.length;e++){const t=n[e];0!==e&&(this._nodeIndexLOD=e,this._nodeSignalLODs[e]=this._nodeSignalLODs[e]||new na);const i=e=>{s(e),e.setEnabled(!1)},a=this._loader.loadNodeAsync(`/nodes/${t.index}`,t,i).then((t=>{if(0!==e){const t=n[e-1];t._babylonTransformNode&&(this._disposeTransformNode(t._babylonTransformNode),delete t._babylonTransformNode)}return t.setEnabled(!0),t}));this._nodePromiseLODs[e]=this._nodePromiseLODs[e]||[],0===e?r=a:(this._nodeIndexLOD=null,this._nodePromiseLODs[e].push(a))}return this._loader.logClose(),r}))}_loadMaterialAsync(e,t,s,i,r){return this._nodeIndexLOD?null:ro.LoadExtensionAsync(e,t,this.name,((e,n)=>{let a;const o=this._getLODs(e,t,this._loader.gltf.materials,n.ids);this._loader.logOpen(`${e}`);for(let e=0;e<o.length;e++){const t=o[e];0!==e&&(this._materialIndexLOD=e);const n=this._loader._loadMaterialAsync(`/materials/${t.index}`,t,s,i,(t=>{0===e&&r(t)})).then((t=>{if(0!==e){r(t);const s=o[e-1]._data;s[i]&&(this._disposeMaterials([s[i].babylonMaterial]),delete s[i])}return t}));this._materialPromiseLODs[e]=this._materialPromiseLODs[e]||[],0===e?a=n:(this._materialIndexLOD=null,this._materialPromiseLODs[e].push(n))}return this._loader.logClose(),a}))}_loadUriAsync(e,t,s){if(null!==this._nodeIndexLOD){this._loader.log("deferred");const i=this._nodeIndexLOD-1;return this._nodeSignalLODs[i]=this._nodeSignalLODs[i]||new na,this._nodeSignalLODs[this._nodeIndexLOD-1].promise.then((()=>this._loader.loadUriAsync(e,t,s)))}if(null!==this._materialIndexLOD){this._loader.log("deferred");const i=this._materialIndexLOD-1;return this._materialSignalLODs[i]=this._materialSignalLODs[i]||new na,this._materialSignalLODs[i].promise.then((()=>this._loader.loadUriAsync(e,t,s)))}return null}loadBufferAsync(e,t,s,i){if(this._loader.parent.useRangeRequests&&!t.uri){if(!this._loader.bin)throw new Error(`${e}: Uri is missing or the binary glTF is missing its binary chunk`);const t=(e,t)=>{const r=s,n=r+i-1;let a=e[t];return a?(a.start=Math.min(a.start,r),a.end=Math.max(a.end,n)):(a={start:r,end:n,loaded:new na},e[t]=a),a.loaded.promise.then((e=>new Uint8Array(e.buffer,e.byteOffset+s-a.start,i)))};return this._loader.log("deferred"),null!==this._nodeIndexLOD?t(this._nodeBufferLODs,this._nodeIndexLOD):null!==this._materialIndexLOD?t(this._materialBufferLODs,this._materialIndexLOD):t(this._bufferLODs,0)}return null}_loadBufferLOD(e,t){const s=e[t];s&&(this._loader.log(`Loading buffer range [${s.start}-${s.end}]`),this._loader.bin.readAsync(s.start,s.end-s.start+1).then((e=>{s.loaded.resolve(e)}),(e=>{s.loaded.reject(e)})))}_getLODs(e,t,s,i){if(this.maxLODsToLoad<=0)throw new Error("maxLODsToLoad must be greater than zero");const r=[];for(let t=i.length-1;t>=0;t--)if(r.push(io.Get(`${e}/ids/${i[t]}`,s,i[t])),r.length===this.maxLODsToLoad)return r;return r.push(t),r}_disposeTransformNode(e){const t=[],s=e.material;s&&t.push(s);for(const s of e.getChildMeshes())s.material&&t.push(s.material);e.dispose();const i=t.filter((e=>this._loader.babylonScene.meshes.every((t=>t.material!=e))));this._disposeMaterials(i)}_disposeMaterials(e){const t={};for(const s of e){for(const e of s.getActiveTextures())t[e.uniqueId]=e;s.dispose()}for(const e in t)for(const s of this._loader.babylonScene.materials)s.hasTexture(t[e])&&delete t[e];for(const e in t)t[e].dispose()}}ro.RegisterExtension(Nh,(e=>new wh(e)));const Bh="MSFT_minecraftMesh";class Uh{constructor(e){this.name=Bh,this._loader=e,this.enabled=this._loader.isExtensionUsed(Bh)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,s){return ro.LoadExtraAsync(e,t,this.name,((i,r)=>{if(r){if(!(s instanceof zn))throw new Error(`${i}: Material type not supported`);const r=this._loader.loadMaterialPropertiesAsync(e,t,s);return s.needAlphaBlending()&&(s.forceDepthWrite=!0,s.separateCullingPass=!0),s.backFaceCulling=s.forceDepthWrite,s.twoSidedLighting=!0,r}return null}))}}ro.RegisterExtension(Bh,(e=>new Uh(e)));const kh="MSFT_sRGBFactors";class Gh{constructor(e){this.name=kh,this._loader=e,this.enabled=this._loader.isExtensionUsed(kh)}dispose(){this._loader=null}loadMaterialPropertiesAsync(e,t,s){return ro.LoadExtraAsync(e,t,this.name,((i,r)=>{if(r){if(!(s instanceof zn))throw new Error(`${i}: Material type not supported`);const r=this._loader.loadMaterialPropertiesAsync(e,t,s),n=s.getScene().getEngine().useExactSrgbConversions;return s.albedoTexture||s.albedoColor.toLinearSpaceToRef(s.albedoColor,n),s.reflectivityTexture||s.reflectivityColor.toLinearSpaceToRef(s.reflectivityColor,n),r}return null}))}}var Vh;ro.RegisterExtension(kh,(e=>new Gh(e))),function(e){e[e.Input=0]="Input",e[e.Output=1]="Output"}(Vh||(Vh={}));class Hh{constructor(e,t,s){this._ownerBlock=s,this._connectedPoint=[],this.uniqueId=kt(),this.connectedPointIds=[],this.name=e,this._connectionType=t}get connectionType(){return this._connectionType}_isSingularConnection(){return!0}isConnected(){return this._connectedPoint.length>0}connectTo(e){if(this._connectionType===e._connectionType)throw new Error(`Cannot connect two points of type ${this.connectionType}`);if(this._isSingularConnection()&&this._connectedPoint.length>0||e._isSingularConnection()&&e._connectedPoint.length>0)throw new Error("Max number of connections for point reached");this._connectedPoint.push(e),e._connectedPoint.push(this)}serialize(e={}){e.uniqueId=this.uniqueId,e.name=this.name,e._connectionType=this._connectionType,e.connectedPointIds=[],e.className=this.getClassName();for(const t of this._connectedPoint)e.connectedPointIds.push(t.uniqueId)}getClassName(){return"FGConnection"}deserialize(e){this.uniqueId=e.uniqueId,this.name=e.name,this._connectionType=e._connectionType,this.connectedPointIds=e.connectedPointIds}static Parse(e={},t){const s=new(Yt.Instantiate(e.className))(e.name,e._connectionType,t);return s.deserialize(e),s}}class zh{constructor(e){this.value=this._toInt(e)}_toInt(e){return 0|e}add(e){return new zh(this.value+e.value)}subtract(e){return new zh(this.value-e.value)}multiply(e){return new zh(Math.imul(this.value,e.value))}divide(e){return new zh(this.value/e.value)}getClassName(){return zh.ClassName}equals(e){return this.value===e.value}static Parse(e){return new zh(e.value)}}zh.ClassName="FlowGraphInteger",I("FlowGraphInteger",zh);class Xh{constructor(e,t){this.typeName=e,this.defaultValue=t}serialize(e){e.typeName=this.typeName,e.defaultValue=this.defaultValue}static Parse(e){return new Xh(e.typeName,e.defaultValue)}}const Wh=new Xh("any",void 0),Yh=new Xh("number",0),Kh=new Xh("boolean",!1),qh=new Xh("Vector2",B.Zero()),Qh=new Xh("Vector3",U.Zero());new Xh("Vector4",k.Zero());const jh=new Xh("Matrix",V.Identity());new Xh("Color3",ee.Black()),new Xh("Quaternion",G.Identity());const Zh=new Xh("FlowGraphInteger",new zh(0));class $h extends Hh{constructor(e,t,s,i){super(e,t,s),this.richType=i}_isSingularConnection(){return 0===this.connectionType}setValue(e,t){t._setConnectionValue(this,e)}connectTo(e){super.connectTo(e)}_getValueOrDefault(e){return e._hasConnectionValue(this)?e._getConnectionValue(this):this.richType.defaultValue}getValue(e){return 1===this.connectionType?(e._notifyExecuteNode(this._ownerBlock),this._ownerBlock._updateOutputs(e),this._getValueOrDefault(e)):this.isConnected()?this._connectedPoint[0].getValue(e):this._getValueOrDefault(e)}getClassName(){return"FGDataConnection"}serialize(e={}){super.serialize(e),e.richType={},this.richType.serialize(e.richType)}static Parse(e,t){const s=Hh.Parse(e,t);return s.richType=Xh.Parse(e.richType),s}}function Jh(e){return"Mesh"===e||"AbstractMesh"===e||"GroundMesh"===e||"InstanceMesh"===e||"LinesMesh"===e||"GoldbergMesh"===e||"GreasedLineMesh"===e||"TrailMesh"===e}function el(e){return"Vector2"===e||"Vector3"===e||"Vector4"===e||"Quaternion"===e||"Color3"===e||"Color4"===e}function tl(e,t,s){const i=t?.getClassName?.()??"";Jh(i)?s[e]={name:t.name,className:i}:el(i)?s[e]={value:t.asArray(),className:i}:s[e]=t}function sl(e,t,s){const i=t[e];let r;const n=i?.className;return r=Jh(n)?s.getMeshByName(i.name):el(n)?function(e,t){if("Vector2"===e)return B.FromArray(t);if("Vector3"===e)return U.FromArray(t);if("Vector4"===e)return k.FromArray(t);if("Quaternion"===e)return G.FromArray(t);if("Color3"===e)return new ee(t[0],t[1],t[2]);if("Color4"===e)return new te(t[0],t[1],t[2],t[3]);throw new Error(`Unknown vector class name ${e}`)}(n,i.value):"Matrix"===n?V.FromArray(i.value):n===zh.ClassName?zh.Parse(i):i&&void 0!==i.value?i.value:i,r}I("FGDataConnection",$h);class il{constructor(e){this.config=e,this.uniqueId=kt(),this.name=this.config?.name??this.getClassName(),this.dataInputs=[],this.dataOutputs=[]}_updateOutputs(e){}registerDataInput(e,t){const s=new $h(e,0,this,t);return this.dataInputs.push(s),s}registerDataOutput(e,t){const s=new $h(e,1,this,t);return this.dataOutputs.push(s),s}getDataInput(e){return this.dataInputs.find((t=>t.name===e))}getDataOutput(e){return this.dataOutputs.find((t=>t.name===e))}serialize(e={},t=tl){e.uniqueId=this.uniqueId,e.config={},this.config&&(e.config.name=this.config.name),e.dataInputs=[],e.dataOutputs=[],e.className=this.getClassName();for(const t of this.dataInputs){const s={};t.serialize(s),e.dataInputs.push(s)}for(const t of this.dataOutputs){const s={};t.serialize(s),e.dataOutputs.push(s)}}getClassName(){return"FGBlock"}static Parse(e,t){const s=Yt.Instantiate(e.className),i={},r=t.valueParseFunction??sl;if(e.config)for(const s in e.config)i[s]=r(s,e.config,t.scene);var n;("FGSetPropertyBlock"===(n=e.className)||"FGGetPropertyBlock"===n||"FGPlayAnimationBlock"===n||"FGMeshPickEventBlock"===n)&&(i.pathConverter=t.pathConverter);const a=new s(i);a.uniqueId=e.uniqueId;for(let t=0;t<e.dataInputs.length;t++){const s=a.getDataInput(e.dataInputs[t].name);if(!s)throw new Error("Could not find data input with name "+e.dataInputs[t].name+" in block "+e.className);s.deserialize(e.dataInputs[t])}for(let t=0;t<e.dataOutputs.length;t++){const s=a.getDataOutput(e.dataOutputs[t].name);if(!s)throw new Error("Could not find data output with name "+e.dataOutputs[t].name+" in block "+e.className);s.deserialize(e.dataOutputs[t])}return a.metadata=e.metadata,a.deserialize&&a.deserialize(e),a}}class rl extends Hh{_isSingularConnection(){return 1===this.connectionType}_activateSignal(e){0===this.connectionType?(e._notifyExecuteNode(this._ownerBlock),this._ownerBlock._execute(e,this),e._increaseExecutionId()):this._connectedPoint[0]?._activateSignal(e)}}I("FlowGraphSignalConnection",rl);class nl extends il{constructor(e){super(e),this.signalInputs=[],this.signalOutputs=[],this.in=this._registerSignalInput("in")}_registerSignalInput(e){const t=new rl(e,0,this);return this.signalInputs.push(t),t}_registerSignalOutput(e){const t=new rl(e,1,this);return this.signalOutputs.push(t),t}getSignalInput(e){return this.signalInputs.find((t=>t.name===e))}getSignalOutput(e){return this.signalOutputs.find((t=>t.name===e))}serialize(e={}){super.serialize(e),e.signalInputs=[],e.signalOutputs=[];for(const t of this.signalInputs){const s={};t.serialize(s),e.signalInputs.push(s)}for(const t of this.signalOutputs){const s={};t.serialize(s),e.signalOutputs.push(s)}}deserialize(e){for(let t=0;t<e.signalInputs.length;t++){const s=this.getSignalInput(e.signalInputs[t].name);if(!s)throw new Error("Could not find signal input with name "+e.signalInputs[t].name+" in block "+e.className);s.deserialize(e.signalInputs[t])}for(let t=0;t<e.signalOutputs.length;t++){const s=this.getSignalOutput(e.signalOutputs[t].name);if(!s)throw new Error("Could not find signal output with name "+e.signalOutputs[t].name+" in block "+e.className);s.deserialize(e.signalOutputs[t])}}getClassName(){return"FGExecutionBlock"}}class al extends nl{constructor(e){super(e),this.out=this._registerSignalOutput("out"),this.done=this._registerSignalOutput("done")}_startPendingTasks(e){this._preparePendingTasks(e),e._addPendingBlock(this)}}class ol extends al{_execute(e){e._notifyExecuteNode(this),this.out._activateSignal(e)}}class hl{constructor(e){this.uniqueId=kt(),this._userVariables={},this._executionVariables={},this._connectionValues={},this._pendingBlocks=[],this._executionId=0,this.onNodeExecutedObservable=new g,this._configuration=e}hasVariable(e){return e in this._userVariables}setVariable(e,t){this._userVariables[e]=t}getVariable(e){return this._userVariables[e]}get userVariables(){return this._userVariables}_getUniqueIdPrefixedName(e,t){return`${e.uniqueId}_${t}`}_setExecutionVariable(e,t,s){this._executionVariables[this._getUniqueIdPrefixedName(e,t)]=s}_getExecutionVariable(e,t,s){return this._hasExecutionVariable(e,t)?this._executionVariables[this._getUniqueIdPrefixedName(e,t)]:s}_deleteExecutionVariable(e,t){delete this._executionVariables[this._getUniqueIdPrefixedName(e,t)]}_hasExecutionVariable(e,t){return this._getUniqueIdPrefixedName(e,t)in this._executionVariables}_hasConnectionValue(e){return e.uniqueId in this._connectionValues}_setConnectionValue(e,t){this._connectionValues[e.uniqueId]=t}_getConnectionValue(e){return this._connectionValues[e.uniqueId]}get configuration(){return this._configuration}_addPendingBlock(e){this._pendingBlocks.push(e)}_removePendingBlock(e){const t=this._pendingBlocks.indexOf(e);-1!==t&&this._pendingBlocks.splice(t,1)}_clearPendingBlocks(){for(const e of this._pendingBlocks)e._cancelPendingTasks(this);this._pendingBlocks.length=0}_notifyExecuteNode(e){this.onNodeExecutedObservable.notifyObservers(e)}_increaseExecutionId(){this._executionId++}get executionId(){return this._executionId}serialize(e={},t=tl){e.uniqueId=this.uniqueId,e._userVariables={};for(const s in this._userVariables)t(s,this._userVariables[s],e._userVariables);e._connectionValues={};for(const s in this._connectionValues)t(s,this._connectionValues[s],e._connectionValues)}getClassName(){return"FGContext"}static Parse(e,t){const s=t.graph.createContext(),i=t.valueParseFunction??sl;s.uniqueId=e.uniqueId;for(const t in e._userVariables){const r=i(t,e._userVariables,s._configuration.scene);s._userVariables[t]=r}for(const t in e._connectionValues){const r=i(t,e._connectionValues,s._configuration.scene);s._connectionValues[t]=r}return s}}function ll(e,t){return!(!e.parent||e.parent!==t&&!ll(e.parent,t))}e([a()],hl.prototype,"uniqueId",void 0);class cl extends ol{constructor(e){super(e),this.config=e}_getReferencedMesh(){const e=this.config.pathConverter.convert(this.config.path),t=e.info.getObject(e.object);if(!(t&&t instanceof Gs))throw new Error("Mesh pick event block requires a valid mesh");return t}_preparePendingTasks(e){let t=e._getExecutionVariable(this,"meshPickObserver");if(!t){const s=this._getReferencedMesh();e._setExecutionVariable(this,"mesh",s),t=s.getScene().onPointerObservable.add((t=>{t.type===hi.POINTERPICK&&t.pickInfo?.pickedMesh&&(t.pickInfo?.pickedMesh===s||ll(t.pickInfo?.pickedMesh,s))&&this._execute(e)}));const i=s.onDisposeObservable.add((()=>this._onDispose));e._setExecutionVariable(this,"meshPickObserver",t),e._setExecutionVariable(this,"meshDisposeObserver",i)}}_onDispose(e){this._cancelPendingTasks(e),e._removePendingBlock(this)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"mesh"),s=e._getExecutionVariable(this,"meshPickObserver"),i=e._getExecutionVariable(this,"meshDisposeObserver");t.getScene().onPointerObservable.remove(s),t.onDisposeObservable.remove(i),e._deleteExecutionVariable(this,"mesh"),e._deleteExecutionVariable(this,"meshPickObserver"),e._deleteExecutionVariable(this,"meshDisposeObserver")}getClassName(){return cl.ClassName}serialize(e){super.serialize(e),e.config.path=this.config.path}}var ul,dl;cl.ClassName="FGMeshPickEventBlock",I(cl.ClassName,cl),function(e){e[e.Stopped=0]="Stopped",e[e.Started=1]="Started"}(ul||(ul={}));class _l{constructor(e){this._eventBlocks=[],this._executionContexts=[],this.state=0,this._scene=e.scene,this._coordinator=e.coordinator,this._sceneDisposeObserver=this._scene.onDisposeObservable.add((()=>this.dispose()))}createContext(){const e=new hl({scene:this._scene,coordinator:this._coordinator});return this._executionContexts.push(e),e}getContext(e){return this._executionContexts[e]}addEventBlock(e){this._eventBlocks.push(e)}start(){if(1!==this.state){this.state=1,0===this._executionContexts.length&&this.createContext();for(const e of this._executionContexts){const t=this._getContextualOrder();for(const s of t)s._startPendingTasks(e)}}}_getContextualOrder(){const e=[];for(const t of this._eventBlocks)if(t.getClassName()===cl.ClassName){const s=t._getReferencedMesh();let i=0;for(;i<e.length;i++){const t=e[i]._getReferencedMesh();if(s&&t&&ll(s,t))break}e.splice(i,0,t)}else e.push(t);return e}dispose(){if(0!==this.state){this.state=0;for(const e of this._executionContexts)e._clearPendingBlocks();this._executionContexts.length=0,this._eventBlocks.length=0,this._scene.onDisposeObservable.remove(this._sceneDisposeObserver),this._sceneDisposeObserver=null}}visitAllBlocks(e){const t=[],s=new Set;for(const e of this._eventBlocks)t.push(e),s.add(e.uniqueId);for(;t.length>0;){const i=t.pop();e(i);for(const e of i.dataInputs)for(const i of e._connectedPoint)s.has(i._ownerBlock.uniqueId)||(t.push(i._ownerBlock),s.add(i._ownerBlock.uniqueId));if(i instanceof nl)for(const e of i.signalOutputs)for(const i of e._connectedPoint)s.has(i._ownerBlock.uniqueId)||(t.push(i._ownerBlock),s.add(i._ownerBlock.uniqueId))}}serialize(e={},t){e.allBlocks=[],this.visitAllBlocks((t=>{const s={};t.serialize(s),e.allBlocks.push(s)})),e.executionContexts=[];for(const s of this._executionContexts){const i={};s.serialize(i,t),e.executionContexts.push(i)}}static GetDataOutConnectionByUniqueId(e,t){for(const s of e)for(const e of s.dataOutputs)if(e.uniqueId===t)return e;throw new Error("Could not find data out connection with unique id "+t)}static GetSignalInConnectionByUniqueId(e,t){for(const s of e)if(s instanceof nl)for(const e of s.signalInputs)if(e.uniqueId===t)return e;throw new Error("Could not find signal in connection with unique id "+t)}static Parse(e,t){const s=t.coordinator.createGraph(),i=[],r=t.valueParseFunction??sl;for(const n of e.allBlocks){const e=il.Parse(n,{scene:t.coordinator.config.scene,pathConverter:t.pathConverter,valueParseFunction:r});i.push(e),e instanceof ol&&s.addEventBlock(e)}for(const e of i){for(const t of e.dataInputs)for(const e of t.connectedPointIds){const s=_l.GetDataOutConnectionByUniqueId(i,e);t.connectTo(s)}if(e instanceof nl)for(const t of e.signalOutputs)for(const e of t.connectedPointIds){const s=_l.GetSignalInConnectionByUniqueId(i,e);t.connectTo(s)}}for(const t of e.executionContexts)hl.Parse(t,{graph:s,valueParseFunction:r});return s}}class fl{constructor(e){this.config=e,this._flowGraphs=[],this._customEventsMap=new Map,this.config.scene.onDisposeObservable.add((()=>{this.dispose()}));(fl.SceneCoordinators.get(this.config.scene)??[]).push(this)}createGraph(){const e=new _l({scene:this.config.scene,coordinator:this});return this._flowGraphs.push(e),e}removeGraph(e){const t=this._flowGraphs.indexOf(e);-1!==t&&(e.dispose(),this._flowGraphs.splice(t,1))}start(){this._flowGraphs.forEach((e=>e.start()))}dispose(){this._flowGraphs.forEach((e=>e.dispose())),this._flowGraphs.length=0;const e=fl.SceneCoordinators.get(this.config.scene)??[],t=e.indexOf(this);-1!==t&&e.splice(t,1)}serialize(e,t){e._flowGraphs=[],this._flowGraphs.forEach((s=>{const i={};s.serialize(i,t),e._flowGraphs.push(i)}))}static Parse(e,t){const s=t.valueParseFunction??sl,i=new fl({scene:t.scene});return e._flowGraphs?.forEach((e=>{_l.Parse(e,{coordinator:i,valueParseFunction:s,pathConverter:t.pathConverter})})),i}get flowGraphs(){return this._flowGraphs}getCustomEventObservable(e){let t=this._customEventsMap.get(e);return t||(t=new g,this._customEventsMap.set(e,t)),t}notifyCustomEvent(e,t){const s=this._customEventsMap.get(e);s&&s.notifyObservers(t)}}fl.SceneCoordinators=new Map;class pl extends ol{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneReadyObserver")){const t=e.configuration.scene.onReadyObservable.add((()=>{this._execute(e)}));e._setExecutionVariable(this,"sceneReadyObserver",t)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneReadyObserver");e.configuration.scene.onReadyObservable.remove(t),e._deleteExecutionVariable(this,"sceneReadyObserver")}getClassName(){return pl.ClassName}}pl.ClassName="FGSceneReadyEventBlock",I("FGSceneReadyEventBlock",pl);class ml extends ol{_preparePendingTasks(e){if(!e._getExecutionVariable(this,"sceneBeforeRender")){const t=e.configuration.scene.onBeforeRenderObservable.add((()=>{this._execute(e)}));e._setExecutionVariable(this,"sceneBeforeRender",t)}}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"sceneBeforeRender");e.configuration.scene.onBeforeRenderObservable.remove(t),e._deleteExecutionVariable(this,"sceneBeforeRender")}getClassName(){return ml.ClassName}}ml.ClassName="FGSceneTickEventBlock",I(ml.ClassName,ml);class gl extends nl{constructor(e){super(e),this.out=this._registerSignalOutput("out")}}class Tl extends gl{constructor(e){super(e),this.message=this.registerDataInput("message",Wh)}_execute(e){const t=this.message.getValue(e);ue.Log(t),this.out._activateSignal(e)}getClassName(){return Tl.ClassName}}Tl.ClassName="FGConsoleLogBlock",I(Tl.ClassName,Tl),function(e){e[e.INIT=0]="INIT",e[e.STARTED=1]="STARTED",e[e.ENDED=2]="ENDED"}(dl||(dl={}));class El{constructor(e){this.onEachCountObservable=new g,this.onTimerAbortedObservable=new g,this.onTimerEndedObservable=new g,this.onStateChangedObservable=new g,this._observer=null,this._breakOnNextTick=!1,this._tick=e=>{const t=Date.now();this._timer=t-this._startTime;const s={startTime:this._startTime,currentTime:t,deltaTime:this._timer,completeRate:this._timer/this._timeToEnd,payload:e},i=this._breakOnNextTick||this._breakCondition(s);i||this._timer>=this._timeToEnd?this._stop(s,i):this.onEachCountObservable.notifyObservers(s)},this._setState(0),this._contextObservable=e.contextObservable,this._observableParameters=e.observableParameters??{},this._breakCondition=e.breakCondition??(()=>!1),this._timeToEnd=e.timeout,e.onEnded&&this.onTimerEndedObservable.add(e.onEnded),e.onTick&&this.onEachCountObservable.add(e.onTick),e.onAborted&&this.onTimerAbortedObservable.add(e.onAborted)}set breakCondition(e){this._breakCondition=e}clearObservables(){this.onEachCountObservable.clear(),this.onTimerAbortedObservable.clear(),this.onTimerEndedObservable.clear(),this.onStateChangedObservable.clear()}start(e=this._timeToEnd){if(1===this._state)throw new Error("Timer already started. Please stop it before starting again");this._timeToEnd=e,this._startTime=Date.now(),this._timer=0,this._observer=this._contextObservable.add(this._tick,this._observableParameters.mask,this._observableParameters.insertFirst,this._observableParameters.scope),this._setState(1)}stop(){1===this._state&&(this._breakOnNextTick=!0)}dispose(){this._observer&&this._contextObservable.remove(this._observer),this.clearObservables()}_setState(e){this._state=e,this.onStateChangedObservable.notifyObservers(this._state)}_stop(e,t=!1){this._contextObservable.remove(this._observer),this._setState(2),t?this.onTimerAbortedObservable.notifyObservers(e):this.onTimerEndedObservable.notifyObservers(e)}}class Al extends al{constructor(e){super(e),this.timeout=this.registerDataInput("timeout",Yh)}_preparePendingTasks(e){const t=this.timeout.getValue(e);if(void 0!==t&&t>=0){const s=e._getExecutionVariable(this,"runningTimers")||[],i=e.configuration.scene,r=new El({timeout:t,contextObservable:i.onBeforeRenderObservable,onEnded:()=>this._onEnded(r,e)});r.start(),s.push(r),e._setExecutionVariable(this,"runningTimers",s)}}_execute(e){this._startPendingTasks(e),this.out._activateSignal(e)}_onEnded(e,t){const s=t._getExecutionVariable(this,"runningTimers")||[],i=s.indexOf(e);-1!==i?s.splice(i,1):Yt.Warn("FlowGraphTimerBlock: Timer ended but was not found in the running timers list"),t._removePendingBlock(this),this.done._activateSignal(t)}_cancelPendingTasks(e){const t=e._getExecutionVariable(this,"runningTimers")||[];for(const e of t)e.dispose();e._deleteExecutionVariable(this,"runningTimers")}getClassName(){return Al.ClassName}}Al.ClassName="FGTimerBlock",I("FGTimerBlock",Al);class yl extends gl{constructor(e){super(e),this.config=e;for(let e=0;e<this.config.eventData.length;e++){const t=this.config.eventData[e];this.registerDataInput(t,Wh)}}_execute(e){const t=this.config.eventId,s=this.dataInputs.map((t=>t.getValue(e)));e.configuration.coordinator.notifyCustomEvent(t,s),this.out._activateSignal(e)}getClassName(){return yl.ClassName}}yl.ClassName="FGSendCustomEventBlock",I("FGSendCustomEventBlock",yl);class bl extends ol{constructor(e){super(e),this.config=e;for(let e=0;e<this.config.eventData.length;e++){const t=this.config.eventData[e];this.registerDataOutput(t,Wh)}}_preparePendingTasks(e){const t=e.configuration.coordinator.getCustomEventObservable(this.config.eventId);this._eventObserver=t.add((t=>{for(let s=0;s<t.length;s++)this.dataOutputs[s].setValue(t[s],e);this._execute(e)}))}_cancelPendingTasks(e){const t=e.configuration.coordinator.getCustomEventObservable(this.config.eventId);t?t.remove(this._eventObserver):Yt.Warn(`FlowGraphReceiveCustomEventBlock: Missing observable for event ${this.config.eventId}`)}getClassName(){return bl.ClassName}serialize(e){super.serialize(e),e.eventId=this.config.eventId,e.eventData=this.config.eventData}}bl.ClassName="FGReceiveCustomEventBlock",I(bl.ClassName,bl);class Rl extends nl{constructor(e){super(e),this.config=e,this.outFlows=[];for(let e=0;e<this.config.numberOutputFlows;e++)this.outFlows.push(this._registerSignalOutput(`${e}`))}_execute(e){for(let t=0;t<this.config.numberOutputFlows;t++)this.outFlows[t]._activateSignal(e)}getClassName(){return Rl.ClassName}}Rl.ClassName="FGSequenceBlock",I(Rl.ClassName,Rl);const xl=new RegExp(/\{(\w+)\}/g);class Ml{constructor(e,t){this.path=e,this.ownerBlock=t,this.templatedInputs=[];let s=xl.exec(e);for(;s;){const[,i]=s;this.templatedInputs.push(t.registerDataInput(i,Zh)),s=xl.exec(e)}}getAccessor(e,t){let s=this.path;for(const e of this.templatedInputs){const i=e.getValue(t).value;s=s.replace(`{${e.name}}`,i.toString())}return e.convert(s)}}class Il extends il{constructor(e){super(e),this.config=e,this.value=this.registerDataOutput("value",Wh),this.templateComponent=new Ml(e.path,this)}_updateOutputs(e){const t=this.templateComponent.getAccessor(this.config.pathConverter,e),s=t.info.get(t.object);this.value.setValue(s,e)}getClassName(){return Il.ClassName}serialize(e={}){super.serialize(e),e.config.path=this.config.path}}Il.ClassName="FGGetPropertyBlock",I(Il.ClassName,Il);class Sl extends gl{constructor(e){super(e),this.config=e,this.a=this.registerDataInput("a",Wh),this.templateComponent=new Ml(e.path,this)}_execute(e){const t=this.a.getValue(e),s=this.templateComponent.getAccessor(this.config.pathConverter,e);s.info.set(t,s.object),this.out._activateSignal(e)}serialize(e={}){super.serialize(e),e.config.path=this.config.path}getClassName(){return Sl.ClassName}}Sl.ClassName="FGSetPropertyBlock",I("FGSetPropertyBlock",Sl);const vl="cachedOperationValue",Cl="cachedExecutionId";class Pl extends il{constructor(e,t){super(t),this.value=this.registerDataOutput("value",e)}_updateOutputs(e){const t=e._getExecutionVariable(this,Cl),s=e._getExecutionVariable(this,vl);if(void 0!==s&&t===e.executionId)this.value.setValue(s,e);else{const t=this._doOperation(e);e._setExecutionVariable(this,vl,t),e._setExecutionVariable(this,Cl,e.executionId),this.value.setValue(t,e)}}}class Ol extends Pl{constructor(e,t,s,i,r,n){super(s,n),this._operation=i,this._className=r,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e))}getClassName(){return this._className}}class Dl extends Pl{constructor(e,t,s,i){super(e,i),this._operation=t,this._className=s}_doOperation(e){return this._operation()}getClassName(){return this._className}}class Ll extends Pl{constructor(e,t,s,i,r){super(t,r),this._operation=s,this._className=i,this.a=this.registerDataInput("a",e)}_doOperation(e){return this._operation(this.a.getValue(e))}getClassName(){return this._className}}class Fl extends Pl{constructor(e,t,s,i,r,n,a){super(i,a),this._operation=r,this._className=n,this.a=this.registerDataInput("a",e),this.b=this.registerDataInput("b",t),this.c=this.registerDataInput("c",s)}_doOperation(e){return this._operation(this.a.getValue(e),this.b.getValue(e),this.c.getValue(e))}getClassName(){return this._className}}function Nl(e){return e.getClassName?e.getClassName():""}function wl(e,t){return"Vector2"===e&&"Vector2"===t||"Vector3"===e&&"Vector3"===t||"Vector4"===e&&"Vector4"===t}function Bl(e,t){return"Matrix"===e&&"Matrix"===t}function Ul(e,t){return"FlowGraphInteger"===e&&"FlowGraphInteger"===t}class kl extends Ol{constructor(e){super(Wh,Wh,Wh,((e,t)=>this._polymorphicAdd(e,t)),kl.ClassName,e)}_polymorphicAdd(e,t){const s=Nl(e),i=Nl(t);return wl(s,i)||Bl(s,i)||Ul(s,i)?e.add(t):e+t}}kl.ClassName="FGAddBlock",I(kl.ClassName,kl);class Gl extends Ol{constructor(e){super(Wh,Wh,Wh,((e,t)=>this._polymorphicAdd(e,t)),Gl.ClassName,e)}_polymorphicAdd(e,t){const s=Nl(e),i=Nl(t);return wl(s,i)||Ul(s,i)?e.subtract(t):Bl(s,i)?e.add(t.scale(-1)):e-t}}Gl.ClassName="FGSubBlock",I(Gl.ClassName,Gl);class Vl extends Ol{constructor(e){super(Wh,Wh,Wh,((e,t)=>this._polymorphicMultiply(e,t)),Vl.ClassName,e)}_polymorphicMultiply(e,t){const s=Nl(e),i=Nl(t);return wl(s,i)||Ul(s,i)?e.multiply(t):Bl(s,i)?V.FromValues(e.m[0]*t.m[0],e.m[4]*t.m[4],e.m[8]*t.m[8],e.m[12]*t.m[12],e.m[1]*t.m[1],e.m[5]*t.m[5],e.m[9]*t.m[9],e.m[13]*t.m[13],e.m[2]*t.m[2],e.m[6]*t.m[6],e.m[10]*t.m[10],e.m[14]*t.m[14],e.m[3]*t.m[3],e.m[7]*t.m[7],e.m[11]*t.m[11],e.m[15]*t.m[15]):e*t}}Vl.ClassName="FGMultiplyBlock",I(Vl.ClassName,Vl);class Hl extends Ol{constructor(e){super(Wh,Wh,Wh,((e,t)=>this._polymorphicDivide(e,t)),Hl.ClassName,e)}_polymorphicDivide(e,t){const s=Nl(e),i=Nl(t);return wl(s,i)||Ul(s,i)?e.divide(t):Bl(s,i)?V.FromValues(e.m[0]/t.m[0],e.m[4]/t.m[4],e.m[8]/t.m[8],e.m[12]/t.m[12],e.m[1]/t.m[1],e.m[5]/t.m[5],e.m[9]/t.m[9],e.m[13]/t.m[13],e.m[2]/t.m[2],e.m[6]/t.m[6],e.m[10]/t.m[10],e.m[14]/t.m[14],e.m[3]/t.m[3],e.m[7]/t.m[7],e.m[11]/t.m[11],e.m[15]/t.m[15]):e/t}}Hl.ClassName="FGDivideBlock",I(Hl.ClassName,Hl);class zl extends Dl{constructor(e){super(Yh,(()=>Math.random()),zl.ClassName,e)}}zl.ClassName="FGRandomBlock",I(zl.ClassName,zl);class Xl extends Ol{constructor(e){super(Wh,Wh,Yh,((e,t)=>this._polymorphicDot(e,t)),Xl.ClassName,e)}_polymorphicDot(e,t){switch(Nl(e)){case"Vector2":return B.Dot(e,t);case"Vector3":return U.Dot(e,t);case"Vector4":return k.Dot(e,t);default:throw new Error(`Cannot get dot product of ${e} and ${t}`)}}}Xl.ClassName="FGDotBlock",I(Xl.ClassName,Xl);class Wl extends Dl{constructor(e){super(Yh,(()=>Math.E),Wl.ClassName,e)}}Wl.ClassName="FGEBlock",I(Wl.ClassName,Wl);class Yl extends Dl{constructor(e){super(Yh,(()=>Math.PI),Yl.ClassName,e)}}Yl.ClassName="FGPIBlock",I(Yl.ClassName,Yl);class Kl extends Dl{constructor(e){super(Yh,(()=>Number.POSITIVE_INFINITY),Kl.ClassName,e)}}Kl.ClassName="FGInfBlock",I(Kl.ClassName,Kl);class ql extends Dl{constructor(e){super(Yh,(()=>Number.NaN),ql.ClassName,e)}}function Ql(e,t){switch(Nl(e)){case"FlowGraphInteger":return new zh(t(e.value));case"Vector2":return new B(t(e.x),t(e.y));case"Vector3":return new U(t(e.x),t(e.y),t(e.z));case"Vector4":return new k(t(e.x),t(e.y),t(e.z),t(e.w));case"Matrix":return V.FromValues(t(e.m[0]),t(e.m[4]),t(e.m[8]),t(e.m[12]),t(e.m[1]),t(e.m[5]),t(e.m[9]),t(e.m[13]),t(e.m[2]),t(e.m[6]),t(e.m[10]),t(e.m[14]),t(e.m[3]),t(e.m[7]),t(e.m[11]),t(e.m[15]));default:return t(e)}}ql.ClassName="FGNaNBlock",I(ql.ClassName,ql);class jl extends Ll{constructor(e){super(Wh,Wh,(e=>this._polymorphicAbs(e)),jl.ClassName,e)}_polymorphicAbs(e){return Ql(e,Math.abs)}}jl.ClassName="FGAbsBlock",I(jl.ClassName,jl);class Zl extends Ll{constructor(e){super(Wh,Wh,(e=>this._polymorphicSign(e)),Zl.ClassName,e)}_polymorphicSign(e){return Ql(e,Math.sign)}}Zl.ClassName="FGSignBlock",I(Zl.ClassName,Zl);class $l extends Ll{constructor(e){super(Wh,Wh,(e=>this._polymorphicTrunc(e)),$l.ClassName,e)}_polymorphicTrunc(e){return Ql(e,Math.trunc)}}$l.ClassName="FGTruncBlock",I($l.ClassName,$l);class Jl extends Ll{constructor(e){super(Wh,Wh,(e=>this._polymorphicFloor(e)),Jl.ClassName,e)}_polymorphicFloor(e){return Ql(e,Math.floor)}}Jl.ClassName="FGFloorBlock",I(Jl.ClassName,Jl);class ec extends Ll{constructor(e){super(Wh,Wh,(e=>this._polymorphicCeiling(e)),ec.ClassName,e)}_polymorphicCeiling(e){return Ql(e,Math.ceil)}}ec.ClassName="FGCeilBlock",I(ec.ClassName,ec);class tc extends Ll{constructor(e){super(Wh,Wh,(e=>this._polymorphicFract(e)),tc.ClassName,e)}_polymorphicFract(e){return Ql(e,(e=>e-Math.floor(e)))}}tc.ClassName="FGFractBlock",I(tc.ClassName,tc);class sc extends Ll{constructor(e){super(Wh,Wh,(e=>this._polymorphicNeg(e)),sc.ClassName,e)}_polymorphicNeg(e){return Ql(e,(e=>-e))}}function ic(e,t,s){switch(Nl(e)){case"FlowGraphInteger":return new zh(s(e.value,t.value));case"Vector2":return new B(s(e.x,t.x),s(e.y,t.y));case"Vector3":return new U(s(e.x,t.x),s(e.y,t.y),s(e.z,t.z));case"Vector4":return new k(s(e.x,t.x),s(e.y,t.y),s(e.z,t.z),s(e.w,t.w));case"Matrix":return V.FromValues(s(e.m[0],t.m[0]),s(e.m[4],t.m[4]),s(e.m[8],t.m[8]),s(e.m[12],t.m[12]),s(e.m[1],t.m[1]),s(e.m[5],t.m[5]),s(e.m[9],t.m[9]),s(e.m[13],t.m[13]),s(e.m[2],t.m[2]),s(e.m[6],t.m[6]),s(e.m[10],t.m[10]),s(e.m[14],t.m[14]),s(e.m[3],t.m[3]),s(e.m[7],t.m[7]),s(e.m[11],t.m[11]),s(e.m[15],t.m[15]));default:return s(e,t)}}sc.ClassName="FGNegBlock",I(sc.ClassName,sc);class rc extends Ol{constructor(e){super(Wh,Wh,Wh,((e,t)=>this._polymorphicRemainder(e,t)),rc.ClassName,e)}_polymorphicRemainder(e,t){return ic(e,t,((e,t)=>e%t))}}rc.ClassName="FGRemainderBlock",I(rc.ClassName,rc);class nc extends Ol{constructor(e){super(Wh,Wh,Wh,((e,t)=>this._polymorphicMin(e,t)),nc.ClassName,e)}_polymorphicMin(e,t){return ic(e,t,Math.min)}}nc.ClassName="FGMinBlock",I(nc.ClassName,nc);class ac extends Ol{constructor(e){super(Wh,Wh,Wh,((e,t)=>this._polymorphicMax(e,t)),ac.ClassName,e)}_polymorphicMax(e,t){return ic(e,t,Math.max)}}function oc(e,t,s){return Math.min(Math.max(e,Math.min(t,s)),Math.max(t,s))}function hc(e,t,s,i){switch(Nl(e)){case"FlowGraphInteger":return new zh(i(e.value,t.value,s.value));case"Vector2":return new B(i(e.x,t.x,s.x),i(e.y,t.y,s.y));case"Vector3":return new U(i(e.x,t.x,s.x),i(e.y,t.y,s.y),i(e.z,t.z,s.z));case"Vector4":return new k(i(e.x,t.x,s.x),i(e.y,t.y,s.y),i(e.z,t.z,s.z),i(e.w,t.w,s.w));case"Matrix":return V.FromValues(i(e.m[0],t.m[0],s.m[0]),i(e.m[4],t.m[4],s.m[4]),i(e.m[8],t.m[8],s.m[8]),i(e.m[12],t.m[12],s.m[12]),i(e.m[1],t.m[1],s.m[1]),i(e.m[5],t.m[5],s.m[5]),i(e.m[9],t.m[9],s.m[9]),i(e.m[13],t.m[13],s.m[13]),i(e.m[2],t.m[2],s.m[2]),i(e.m[6],t.m[6],s.m[6]),i(e.m[10],t.m[10],s.m[10]),i(e.m[14],t.m[14],s.m[14]),i(e.m[3],t.m[3],s.m[3]),i(e.m[7],t.m[7],s.m[7]),i(e.m[11],t.m[11],s.m[11]),i(e.m[15],t.m[15],s.m[15]));default:return i(e,t,s)}}ac.ClassName="FGMaxBlock",I(ac.ClassName,ac);class lc extends Fl{constructor(e){super(Wh,Wh,Wh,Wh,((e,t,s)=>this._polymorphicClamp(e,t,s)),lc.ClassName,e)}_polymorphicClamp(e,t,s){return hc(e,t,s,oc)}}function cc(e){return Math.min(Math.max(e,0),1)}lc.ClassName="FGClampBlock",I(lc.ClassName,lc);class uc extends Ll{constructor(e){super(Wh,Wh,(e=>this._polymorphicSaturate(e)),uc.ClassName,e)}_polymorphicSaturate(e){return Ql(e,cc)}}uc.ClassName="FGSaturateBlock",I(uc.ClassName,uc);class dc extends Fl{constructor(e){super(Wh,Wh,Wh,Wh,((e,t,s)=>this._polymorphicInterpolate(e,t,s)),dc.ClassName,e)}_interpolate(e,t,s){return(1-s)*e+s*t}_polymorphicInterpolate(e,t,s){return hc(e,t,s,this._interpolate)}}dc.ClassName="FGInterpolateBlock",I(dc.ClassName,dc);class _c extends Ol{constructor(e){super(Wh,Wh,Kh,((e,t)=>this._polymorphicEq(e,t)),_c.ClassName,e)}_polymorphicEq(e,t){const s=Nl(e),i=Nl(t);return wl(s,i)||Bl(s,i)||Ul(s,i)?e.equals(t):e===t}}function fc(e,t,s){const i=Nl(e);if(i===Nl(t)){if(""===i)return s(e,t);if("FlowGraphInteger"===i)return s(e.value,t.value);throw new Error(`Cannot compare ${e} and ${t}`)}throw new Error(`${e} and ${t} are of different types.`)}_c.ClassName="FGEqBlock",I(_c.ClassName,_c);class pc extends Ol{constructor(e){super(Wh,Wh,Kh,((e,t)=>this._polymorphicLessThan(e,t)),pc.ClassName,e)}_polymorphicLessThan(e,t){return fc(e,t,((e,t)=>e<t))}}pc.ClassName="FGLessThanBlock",I(pc.ClassName,pc);class mc extends Ol{constructor(e){super(Wh,Wh,Kh,((e,t)=>this._polymorphicLessThanOrEqual(e,t)),mc.ClassName,e)}_polymorphicLessThanOrEqual(e,t){return fc(e,t,((e,t)=>e<=t))}}mc.ClassName="FGLessThanOrEqualBlock";class gc extends Ol{constructor(e){super(Wh,Wh,Kh,((e,t)=>this._polymorphicGreaterThan(e,t)),gc.ClassName,e)}_polymorphicGreaterThan(e,t){return fc(e,t,((e,t)=>e>t))}}gc.ClassName="FGGreaterThanBlock",I(gc.ClassName,gc);class Tc extends Ol{constructor(e){super(Wh,Wh,Kh,((e,t)=>this._polymorphicGreaterThanOrEqual(e,t)),Tc.ClassName,e)}_polymorphicGreaterThanOrEqual(e,t){return fc(e,t,((e,t)=>e>=t))}}Tc.ClassName="FGGreaterThanOrEqualBlock",I(Tc.ClassName,Tc);class Ec extends Ll{constructor(e){super(Wh,Kh,(e=>this._polymorphicIsNan(e)),Ec.ClassName,e)}_polymorphicIsNan(e){const t=Nl(e);if(""===t)return isNaN(e);if("FlowGraphInteger"===t)return isNaN(e.value);throw new Error(`Cannot get NaN of ${e}`)}}Ec.ClassName="FGIsNanBlock",I(Ec.ClassName,Ec);class Ac extends Ll{constructor(e){super(Wh,Kh,(e=>this._polymorphicIsInf(e)),Ac.ClassName,e)}_polymorphicIsInf(e){const t=Nl(e);if(""===t)return!isFinite(e);if("FlowGraphInteger"===t)return!isFinite(e.value);throw new Error(`Cannot get isInf of ${e}`)}}Ac.ClassName="FGIsInfBlock";class yc extends Ll{constructor(e){super(Wh,Wh,(e=>this._polymorphicDegToRad(e)),yc.ClassName,e)}_degToRad(e){return e*Math.PI/180}_polymorphicDegToRad(e){return Ql(e,this._degToRad)}}yc.ClassName="FGDegToRadBlock",I(yc.ClassName,yc);class bc extends Ll{constructor(e){super(Wh,Wh,(e=>this._polymorphicRadToDeg(e)),bc.ClassName,e)}_radToDeg(e){return 180*e/Math.PI}_polymorphicRadToDeg(e){return Ql(e,this._radToDeg)}}bc.ClassName="FGRadToDegBlock",I(bc.ClassName,bc);class Rc extends Ll{constructor(e){super(Wh,Wh,(e=>this._polymorphicSin(e)),Rc.ClassName,e)}_polymorphicSin(e){return Ql(e,Math.sin)}}Rc.ClassName="FGSinBlock",I(Rc.ClassName,Rc);class xc extends Ll{constructor(e){super(Wh,Wh,(e=>this._polymorphicCos(e)),xc.ClassName,e)}_polymorphicCos(e){return Ql(e,Math.cos)}}xc.ClassName="FGCosBlock",I(xc.ClassName,xc);class Mc extends Ll{constructor(e){super(Wh,Wh,(e=>this._polymorphicTan(e)),Mc.ClassName,e)}_polymorphicTan(e){return Ql(e,Math.tan)}}Mc.ClassName="FGTanBlock",I(Mc.ClassName,Mc);class Ic extends Ll{constructor(e){super(Wh,Wh,(e=>this._polymorphicAsin(e)),Ic.ClassName,e)}_polymorphicAsin(e){return Ql(e,Math.asin)}}Ic.ClassName="FGAsinBlock",I(Ic.ClassName,Ic);class Sc extends Ll{constructor(e){super(Wh,Wh,(e=>this._polymorphicAcos(e)),Sc.ClassName,e)}_polymorphicAcos(e){return Ql(e,Math.acos)}}Sc.ClassName="FGAcosBlock",I(Sc.ClassName,Sc);class vc extends Ll{constructor(e){super(Wh,Wh,(e=>this._polymorphicAtan(e)),vc.ClassName,e)}_polymorphicAtan(e){return Ql(e,Math.atan)}}vc.ClassName="FGAtanBlock",I(vc.ClassName,vc);class Cc extends Ol{constructor(e){super(Wh,Wh,Wh,((e,t)=>this._polymorphicAtan2(e,t)),Cc.ClassName,e)}_polymorphicAtan2(e,t){return ic(e,t,Math.atan2)}}Cc.ClassName="FGAtan2Block",I(Cc.ClassName,Cc);class Pc extends Ll{constructor(e){super(Wh,Wh,(e=>this._polymorphicSinh(e)),Pc.ClassName,e)}_polymorphicSinh(e){return Ql(e,Math.sinh)}}Pc.ClassName="FGSinhBlock",I(Pc.ClassName,Pc);class Oc extends Ll{constructor(e){super(Wh,Wh,(e=>this._polymorphicCosh(e)),Oc.ClassName,e)}_polymorphicCosh(e){return Ql(e,Math.cosh)}}Oc.ClassName="FGCoshBlock",I(Oc.ClassName,Oc);class Dc extends Ll{constructor(e){super(Wh,Wh,(e=>this._polymorphicTanh(e)),Dc.ClassName,e)}_polymorphicTanh(e){return Ql(e,Math.tanh)}}Dc.ClassName="FGTanhBlock",I(Dc.ClassName,Dc);class Lc extends Ll{constructor(e){super(Wh,Yh,(e=>this._polymorphicAsinh(e)),Lc.ClassName,e)}_polymorphicAsinh(e){return Ql(e,Math.asinh)}}Lc.ClassName="FGAsinhBlock",I(Lc.ClassName,Lc);class Fc extends Ll{constructor(e){super(Wh,Yh,(e=>this._polymorphicAcosh(e)),Fc.ClassName,e)}_polymorphicAcosh(e){return Ql(e,Math.acosh)}}Fc.ClassName="FGAcoshBlock",I(Fc.ClassName,Fc);class Nc extends Ll{constructor(e){super(Wh,Yh,(e=>this._polymorphicAtanh(e)),Nc.ClassName,e)}_polymorphicAtanh(e){return Ql(e,Math.atanh)}}Nc.ClassName="FGAtanhBlock",I(Nc.ClassName,Nc);class wc extends Ll{constructor(e){super(Wh,Yh,(e=>this._polymorphicExp(e)),wc.ClassName,e)}_polymorphicExp(e){return Ql(e,Math.exp)}}wc.ClassName="FGExpBlock",I(wc.ClassName,wc);class Bc extends Ll{constructor(e){super(Wh,Yh,(e=>this._polymorphicLog(e)),Bc.ClassName,e)}_polymorphicLog(e){return Ql(e,Math.log)}}Bc.ClassName="FGLogBlock",I(Bc.ClassName,Bc);class Uc extends Ll{constructor(e){super(Wh,Yh,(e=>this._polymorphicLog2(e)),Uc.ClassName,e)}_polymorphicLog2(e){return Ql(e,Math.log2)}}Uc.ClassName="FGLog2Block",I(Uc.ClassName,Uc);class kc extends Ll{constructor(e){super(Wh,Yh,(e=>this._polymorphicLog10(e)),kc.ClassName,e)}_polymorphicLog10(e){return Ql(e,Math.log10)}}kc.ClassName="FGLog10Block",I(kc.ClassName,kc);class Gc extends Ll{constructor(e){super(Wh,Yh,(e=>this._polymorphicSqrt(e)),Gc.ClassName,e)}_polymorphicSqrt(e){return Ql(e,Math.sqrt)}}Gc.ClassName="FGSqrtBlock",I(Gc.ClassName,Gc);class Vc extends Ll{constructor(e){super(Wh,Yh,(e=>this._polymorphicCubeRoot(e)),Vc.ClassName,e)}_polymorphicCubeRoot(e){return Ql(e,Math.cbrt)}}Vc.ClassName="FGCubeRootBlock",I(Vc.ClassName,Vc);class Hc extends Ol{constructor(e){super(Wh,Yh,Yh,((e,t)=>this._polymorphicPow(e,t)),Hc.ClassName,e)}_polymorphicPow(e,t){return ic(e,t,Math.pow)}}Hc.ClassName="FGPowBlock",I(Hc.ClassName,Hc);class zc extends Ll{constructor(e){super(Wh,Yh,(e=>this._polymorphicLength(e)),zc.ClassName,e)}_polymorphicLength(e){switch(Nl(e)){case"Vector2":case"Vector3":case"Vector4":return e.length();default:throw new Error(`Cannot compute length of value ${e}`)}}}zc.ClassName="FGLengthBlock",I(zc.ClassName,zc);class Xc extends Ll{constructor(e){super(Wh,Wh,(e=>this._polymorphicNormalize(e)),Xc.ClassName,e)}_polymorphicNormalize(e){switch(Nl(e)){case"Vector2":case"Vector3":case"Vector4":return e.normalize();default:throw new Error(`Cannot normalize value ${e}`)}}}Xc.ClassName="FGNormalizeBlock",I(Xc.ClassName,Xc);class Wc extends Ol{constructor(e){super(Qh,Qh,Qh,((e,t)=>U.Cross(e,t)),Wc.ClassName,e)}}Wc.ClassName="FGCrossBlock",I(Wc.ClassName,Wc);class Yc extends Ol{constructor(e){super(qh,Yh,qh,((e,t)=>B.Transform(e,V.RotationZ(t))),Yc.ClassName,e)}}Yc.ClassName="FGRotate2DBlock",I(Yc.ClassName,Yc);class Kc extends Fl{constructor(e){super(Qh,Qh,Yh,Qh,((e,t,s)=>U.TransformCoordinates(e,V.RotationAxis(t,s))),Kc.ClassName,e)}}Kc.ClassName="FGRotate3DBlock",I(Kc.ClassName,Kc);class qc extends Ll{constructor(e){super(jh,jh,(e=>V.Transpose(e)),qc.ClassName,e)}}qc.ClassName="FGTransposeBlock",I(qc.ClassName,qc);class Qc extends Ll{constructor(e){super(jh,Yh,(e=>e.determinant()),Qc.ClassName,e)}}Qc.ClassName="FGDeterminantBlock",I(Qc.ClassName,Qc);class jc extends Ll{constructor(e){super(jh,jh,(e=>V.Invert(e)),jc.ClassName,e)}}jc.ClassName="FGInvertMatrixBlock",I(jc.ClassName,jc);class Zc extends Ol{constructor(e){super(jh,jh,jh,((e,t)=>t.multiply(e)),Zc.ClassName,e)}}Zc.ClassName="FGMatMulBlock",I(Zc.ClassName,Zc);class $c extends Ll{constructor(e){super(Zh,Zh,(e=>new zh(~e.value)),$c.ClassName,e)}}$c.ClassName="FGBitwiseNotBlock",I($c.ClassName,$c);class Jc extends Ol{constructor(e){super(Zh,Zh,Zh,((e,t)=>new zh(e.value&t.value)),Jc.ClassName,e)}}Jc.ClassName="FGBitwiseAndBlock",I(Jc.ClassName,Jc);class eu extends Ol{constructor(e){super(Zh,Zh,Zh,((e,t)=>new zh(e.value|t.value)),eu.ClassName,e)}}eu.ClassName="FGBitwiseOrBlock",I(eu.ClassName,eu);class tu extends Ol{constructor(e){super(Zh,Zh,Zh,((e,t)=>new zh(e.value^t.value)),tu.ClassName,e)}}tu.ClassName="FGBitwiseXorBlock",I(tu.ClassName,tu);class su extends Ol{constructor(e){super(Zh,Zh,Zh,((e,t)=>new zh(e.value<<t.value)),su.ClassName,e)}}su.ClassName="FGBitwiseLeftShiftBlock",I(su.ClassName,su);class iu extends Ol{constructor(e){super(Zh,Zh,Zh,((e,t)=>new zh(e.value>>t.value)),iu.ClassName,e)}}iu.ClassName="FGBitwiseRightShiftBlock",I(iu.ClassName,iu);class ru extends Ll{constructor(e){super(Zh,Zh,(e=>new zh(Math.clz32(e.value))),ru.ClassName,e)}}ru.ClassName="FGCountLeadingZerosBlock",I(ru.ClassName,ru);class nu extends Ll{constructor(e){super(Zh,Zh,(e=>new zh(e.value?31-Math.clz32(e.value&-e.value):32)),nu.ClassName,e)}}nu.ClassName="FGCountTrailingZerosBlock",I(nu.ClassName,nu);class au extends Ll{constructor(e){super(Zh,Zh,(e=>new zh(function(e){let t=0;for(;e;)t+=1&e,e>>=1;return t}(e.value))),au.ClassName,e)}}au.ClassName="FGCountOneBitsBlock",I(au.ClassName,au);class ou extends gl{constructor(e={startIndex:new zh(0)}){super(e),this.config=e,this.reset=this._registerSignalInput("reset"),this.n=this.registerDataInput("n",Zh),this.value=this.registerDataOutput("value",Zh)}_execute(e,t){if(t===this.reset)this.value.setValue(this.config.startIndex,e);else{const t=this.value.getValue(e);t.value<this.n.getValue(e).value&&(this.value.setValue(new zh(t.value+1),e),this.out._activateSignal(e))}}getClassName(){return ou.ClassName}}ou.ClassName="FGDoNBlock",I(ou.ClassName,ou);class hu extends il{constructor(e){super(e),this.config=e,this.output=this.registerDataOutput(e.variableName,Wh)}_updateOutputs(e){const t=this.config.variableName;e.hasVariable(t)&&this.output.setValue(e.getVariable(t),e)}getClassName(){return hu.ClassName}serialize(e){super.serialize(e),e.config.variableName=this.config.variableName}}hu.ClassName="FGGetVariableBlock",I(hu.ClassName,hu);class lu extends gl{constructor(e){super(e),this.config=e,this.input=this.registerDataInput(e.variableName,Wh)}_execute(e){const t=this.config.variableName,s=this.input.getValue(e);e.setVariable(t,s),this.out._activateSignal(e)}getClassName(){return lu.ClassName}}lu.ClassName="FGSetVariableBlock",I(lu.ClassName,lu);class cu extends gl{constructor(e){super(e),this.config=e,this.condition=this.registerDataInput("condition",Kh),this.loopBody=this._registerSignalOutput("loopBody")}_execute(e,t){let s=this.condition.getValue(e);for(this.config?.isDo&&!s&&this.loopBody._activateSignal(e);s;)this.loopBody._activateSignal(e),s=this.condition.getValue(e);this.out._activateSignal(e)}getClassName(){return cu.ClassName}serialize(e){super.serialize(e),e.isDo=this.config?.isDo}}cu.ClassName="FGWhileLoopBlock",I(cu.ClassName,cu);const uu={"lifecycle/onStart":pl.ClassName,"lifecycle/onTick":ml.ClassName,log:Tl.ClassName,"flow/delay":Al.ClassName,"customEvent/send":yl.ClassName,"customEvent/receive":bl.ClassName,"flow/sequence":Rl.ClassName,"world/get":Il.ClassName,"world/set":Sl.ClassName,"flow/doN":ou.ClassName,"variable/get":hu.ClassName,"variable/set":lu.ClassName,"flow/whileLoop":cu.ClassName,"math/random":zl.ClassName,"math/e":Wl.ClassName,"math/pi":Yl.ClassName,"math/inf":Kl.ClassName,"math/nan":ql.ClassName,"math/abs":jl.ClassName,"math/sign":Zl.ClassName,"math/trunc":$l.ClassName,"math/floor":Jl.ClassName,"math/ceil":ec.ClassName,"math/fract":tc.ClassName,"math/neg":sc.ClassName,"math/add":kl.ClassName,"math/sub":Gl.ClassName,"math/mul":Vl.ClassName,"math/div":Hl.ClassName,"math/rem":rc.ClassName,"math/min":nc.ClassName,"math/max":ac.ClassName,"math/clamp":lc.ClassName,"math/saturate":uc.ClassName,"math/mix":dc.ClassName,"math/eq":_c.ClassName,"math/lt":pc.ClassName,"math/le":mc.ClassName,"math/gt":gc.ClassName,"math/ge":Tc.ClassName,"math/isnan":Ec.ClassName,"math/isinf":Ac.ClassName,"math/rad":yc.ClassName,"math/deg":bc.ClassName,"math/sin":Rc.ClassName,"math/cos":xc.ClassName,"math/tan":Mc.ClassName,"math/asin":Ic.ClassName,"math/acos":Sc.ClassName,"math/atan":vc.ClassName,"math/atan2":Cc.ClassName,"math/sinh":Pc.ClassName,"math/cosh":Oc.ClassName,"math/tanh":Dc.ClassName,"math/asinh":Lc.ClassName,"math/acosh":Fc.ClassName,"math/atanh":Nc.ClassName,"math/exp":wc.ClassName,"math/log":Bc.ClassName,"math/log2":Uc.ClassName,"math/log10":kc.ClassName,"math/sqrt":Gc.ClassName,"math/cbrt":Vc.ClassName,"math/pow":Hc.ClassName,"math/length":zc.ClassName,"math/normalize":Xc.ClassName,"math/dot":Xl.ClassName,"math/cross":Wc.ClassName,"math/rotate2d":Yc.ClassName,"math/rotate3d":Kc.ClassName,"math/transpose":qc.ClassName,"math/determinant":Qc.ClassName,"math/inverse":jc.ClassName,"math/matmul":Zc.ClassName,"math/not":$c.ClassName,"math/and":Jc.ClassName,"math/or":eu.ClassName,"math/xor":tu.ClassName,"math/asr":iu.ClassName,"math/lsl":su.ClassName,"math/clz":ru.ClassName,"math/ctz":nu.ClassName,"math/popcnt":au.ClassName},du={float2:"Vector2",float3:"Vector3",float4:"Vector4",float4x4:"Matrix",int:"FlowGraphInteger"};function _u(e,t,s){if(void 0!==e.type){const i=t.types&&t.types[e.type];if(!i)throw new Error(`${s}: Unknown type: ${e.type}`);const r=i.signature;if(!r)throw new Error(`${s}: Type ${e.type} has no signature`);const n=du[r];return{value:e.value,className:n}}return e.value}function fu(e,t,s){const i=uu[t.type];if(!i)throw new Error(`/extensions/KHR_interactivity/nodes/${e}: Unknown block type: ${t.type}`);const r=e.toString(),n=function(e,t,s){const i={},r=e.configuration??[];for(const e of r)if("customEvent"===e.id){const r=t.customEvents&&t.customEvents[e.value];if(!r)throw new Error(`/extensions/KHR_interactivity/nodes/${s}: Unknown custom event: ${e.value}`);i.eventId=r.id,i.eventData=r.values.map((e=>e.id))}else if("variable"===e.id){const r=t.variables&&t.variables[e.value];if(!r)throw new Error(`/extensions/KHR_interactivity/nodes/${s}: Unknown variable: ${e.value}`);i.variableName=r.id}else if("path"===e.id){const t=e.value;i.path=t}else i[e.id]=_u(e,t,`/extensions/KHR_interactivity/nodes/${s}`);return i}(t,s,r);return{className:i,config:n,uniqueId:r,metadata:t.metadata,dataInputs:[],dataOutputs:[],signalInputs:[],signalOutputs:[]}}class pu extends Ih{constructor(e){super(e,mu)}}const mu={nodes:{__array__:{__target__:!0,translation:{type:"Vector3",get:e=>e._babylonTransformNode.position,set:(e,t)=>{t._babylonTransformNode.position=e},getObject:e=>e._babylonTransformNode}}}},gu="KHR_interactivity";class Tu{constructor(e){this._loader=e,this.name=gu,this.enabled=this._loader.isExtensionUsed(gu),this._pathConverter=new pu(this._loader.gltf)}dispose(){this._loader=null,delete this._pathConverter}onReady(){if(!this._loader.babylonScene||!this._pathConverter)return;const e=this._loader.babylonScene,t=this._loader.gltf.extensions?.KHR_interactivity,s=function(e){const t={uniqueId:kt(),_userVariables:{},_connectionValues:{}},s=[t],i=[];for(let t=0;t<e.nodes.length;t++){const s=fu(t,e.nodes[t],e);i.push(s)}for(let s=0;s<e.nodes.length;s++){const r=e.nodes[s],n=i[s],a=r.flows??[];for(const e of a){const t=e.id,r={uniqueId:kt(),name:t,_connectionType:1,connectedPointIds:[]};n.signalOutputs.push(r);const a=e.node,o=e.socket,h=i[a];if(!h)throw new Error(`/extensions/KHR_interactivity/nodes/${s}: Could not find node with id ${a} that connects its input with with node ${s}'s output ${t}`);let l=h.signalInputs.find((e=>e.name===o));l||(l={uniqueId:kt(),name:o,_connectionType:0,connectedPointIds:[]},h.signalInputs.push(l)),l.connectedPointIds.push(r.uniqueId),r.connectedPointIds.push(l.uniqueId)}const o=r.values??[];for(const r of o){const a=r.id,o={uniqueId:kt(),name:a,_connectionType:0,connectedPointIds:[]};if(n.dataInputs.push(o),void 0!==r.value){const i=_u(r,e,`/extensions/KHR_interactivity/nodes/${s}`);t._connectionValues[o.uniqueId]=i}else{if(void 0===r.node||void 0===r.socket)throw new Error(`/extensions/KHR_interactivity/nodes/${s}: Invalid socket ${a} in node ${s}`);{const e=r.node,t=r.socket,n=i[e];if(!n)throw new Error(`/extensions/KHR_interactivity/nodes/${s}: Could not find node with id ${e} that connects its output with node${s}'s input ${a}`);let h=n.dataOutputs.find((e=>e.name===t));h||(h={uniqueId:kt(),name:t,_connectionType:1,connectedPointIds:[]},n.dataOutputs.push(h)),o.connectedPointIds.push(h.uniqueId),h.connectedPointIds.push(o.uniqueId)}}}}const r=e.variables??[];for(let s=0;s<r.length;s++){const i=r[s],n=i.id;t._userVariables[n]=_u(i,e,`/extensions/KHR_interactivity/variables/${s}`)}return{allBlocks:i,executionContexts:s}}(t),i=new fl({scene:e});_l.Parse(s,{coordinator:i,pathConverter:this._pathConverter}),i.start()}}ro.RegisterExtension(gu,(e=>new Tu(e)));const Eu="ExtrasAsMetadata";class Au{_assignExtras(e,t){if(t.extras&&Object.keys(t.extras).length>0){const s=e.metadata=e.metadata||{};(s.gltf=s.gltf||{}).extras=t.extras}}constructor(e){this.name=Eu,this.enabled=!0,this._loader=e}dispose(){this._loader=null}loadNodeAsync(e,t,s){return this._loader.loadNodeAsync(e,t,(e=>{this._assignExtras(e,t),s(e)}))}loadCameraAsync(e,t,s){return this._loader.loadCameraAsync(e,t,(e=>{this._assignExtras(e,t),s(e)}))}createMaterial(e,t,s){const i=this._loader.createMaterial(e,t,s);return this._assignExtras(i,t),i}}function yu(e,t){e?.scaling.setAll((t.maxZ-t.minZ)/2)}ro.RegisterExtension(Eu,(e=>new Au(e)));const bu={backgroundColor:new te(.1,.1,.2,1)};class Ru{constructor(e,t){this._engine=e,this.onModelLoaded=new g,this.onModelError=new g,this.onSelectedAnimationChanged=new g,this.onAnimationSpeedChanged=new g,this.onIsAnimationPlayingChanged=new g,this.onAnimationProgressChanged=new g,this._skybox=null,this._isDisposed=!1,this._loadModelLock=new aa,this._loadModelAbortController=null,this._loadEnvironmentLock=new aa,this._environment=null,this._loadEnvironmentAbortController=null,this._selectedAnimation=-1,this._activeAnimationObservers=[],this._animationSpeed=1;const s={...bu,...t};this._details={scene:new yr(this._engine),model:null},this._details.scene.clearColor=s.backgroundColor,this._camera=new Gi("camera1",0,0,1,U.Zero(),this._details.scene),this._camera.attachControl(),this._updateCamera(),this._autoRotationBehavior=this._camera.getBehaviorByName("AutoRotation"),this.loadEnvironmentAsync(void 0).catch((()=>{}));const i=()=>{this._details.scene.render(),this.isAnimationPlaying&&(this.onAnimationProgressChanged.notifyObservers(),this._autoRotationBehavior.resetLastInteractionTime())};this._engine.runRenderLoop(i),this._renderLoopController={dispose:()=>this._engine.stopRenderLoop(i)},t?.onInitialized?.(this._details)}get animations(){return this._details.model?.animationGroups.map((e=>e.name))??[]}get selectedAnimation(){return this._selectedAnimation}set selectedAnimation(e){if((e=Math.round(Q.Clamp(e,-1,this.animations.length-1)))!==this._selectedAnimation){const t=this.isAnimationPlaying;this._activeAnimation&&(this._activeAnimation.goToFrame(0),this._activeAnimation.stop(),this._activeAnimationObservers.forEach((e=>e.remove())),this._activeAnimationObservers=[]),this._selectedAnimation=e,this._activeAnimation&&(this._activeAnimationObservers=[this._activeAnimation.onAnimationGroupPlayObservable.add((()=>{this.onIsAnimationPlayingChanged.notifyObservers()})),this._activeAnimation.onAnimationGroupPauseObservable.add((()=>{this.onIsAnimationPlayingChanged.notifyObservers()})),this._activeAnimation.onAnimationGroupEndObservable.add((()=>{this.onIsAnimationPlayingChanged.notifyObservers(),this.onAnimationProgressChanged.notifyObservers()}))],this._activeAnimation.start(!0,this._animationSpeed),t||this.pauseAnimation()),this.onSelectedAnimationChanged.notifyObservers()}}get isAnimationPlaying(){return this._activeAnimation?.isPlaying??!1}get animationSpeed(){return this._animationSpeed}set animationSpeed(e){this._animationSpeed=e,this._applyAnimationSpeed(),this.onAnimationSpeedChanged.notifyObservers()}get animationProgress(){return this._activeAnimation?this._activeAnimation.getCurrentFrame()/(this._activeAnimation.to-this._activeAnimation.from):0}set animationProgress(e){this._activeAnimation&&(this._activeAnimation.goToFrame(e*(this._activeAnimation.to-this._activeAnimation.from)),this.onAnimationProgressChanged.notifyObservers(),this._autoRotationBehavior.resetLastInteractionTime())}get _activeAnimation(){return this._details.model?.animationGroups[this._selectedAnimation]??null}async loadModelAsync(e,t,s){this._throwIfDisposedOrAborted(s),this._loadModelAbortController?.abort("New model is being loaded before previous model finished loading.");const i=this._loadModelAbortController=new AbortController;t={...t,pluginOptions:{...t?.pluginOptions,gltf:{...t?.pluginOptions?.gltf,extensionOptions:{...t?.pluginOptions?.gltf?.extensionOptions,KHR_audio:{enabled:!1},MSFT_audio_emitter:{enabled:!1}}}}},await this._loadModelLock.lockAsync((async()=>{this._throwIfDisposedOrAborted(s,i.signal),this._details.model?.dispose(),this.selectedAnimation=-1;try{this._details.model=await vr(e,this._details.scene,t),this._details.model.animationGroups.forEach((e=>e.stop())),this.selectedAnimation=0,this._details.model.addAllToScene(),this._updateCamera(),this._applyAnimationSpeed(),this.onModelLoaded.notifyObservers()}catch(e){throw this.onModelError.notifyObservers(e),e}}))}async loadEnvironmentAsync(e,t,s){this._throwIfDisposedOrAborted(s),this._loadEnvironmentAbortController?.abort("New environment is being loaded before previous environment finished loading.");const i=this._loadEnvironmentAbortController=new AbortController;await this._loadEnvironmentLock.lockAsync((async()=>{this._throwIfDisposedOrAborted(s,i.signal),this._environment?.dispose(),this._environment=await new Promise(((t,s)=>{if(e){const i=$n.CreateFromPrefilteredData(e,this._details.scene);this._details.scene.environmentTexture=i;const r=function(e,t,s,i){const r=ra("hdrSkyBox",void 0,e),n=new zn("skyBox",e);return n.backFaceCulling=!1,n.reflectionTexture=s.clone(),n.reflectionTexture&&(n.reflectionTexture.coordinatesMode=Dr.SKYBOX_MODE),n.microSurface=1-i,n.disableLighting=!0,n.twoSidedLighting=!0,r.material=n,r.isPickable=!1,r.infiniteDistance=!0,r.ignoreCameraMaxZ=!0,yu(r,t),r}(this._details.scene,this._camera,i,.3);this._skybox=r,this._details.scene.autoClear=!1;const n=()=>{i.dispose(),r.dispose(),this._skybox=null},a=i.onLoadObservable.addOnce((()=>{a.remove(),o.remove(),t({dispose:n})})),o=Dr.OnTextureLoadErrorObservable.add((e=>{e===i&&(a.remove(),o.remove(),n(),s(new Error("Failed to load environment texture.")))}))}else{const e=new Hi("hemilight",U.Up(),this._details.scene);this._details.scene.autoClear=!0,t(e)}}))}))}toggleAnimation(){this.isAnimationPlaying?this.pauseAnimation():this.playAnimation()}playAnimation(){this._activeAnimation?.play(!0)}async pauseAnimation(){this._activeAnimation?.pause()}dispose(){this.selectedAnimation=-1,this.animationProgress=0,this._renderLoopController.dispose(),this._details.scene.dispose(),this.onModelLoaded.clear(),this.onModelError.clear(),this.onSelectedAnimationChanged.clear(),this.onAnimationSpeedChanged.clear(),this.onIsAnimationPlayingChanged.clear(),this.onAnimationProgressChanged.clear(),this._isDisposed=!0}_updateCamera(){this._camera.useFramingBehavior=!0;const e=this._camera.getBehaviorByName("Framing");e.framingTime=0,e.elevationReturnTime=-1;let t=1;if(this._details.scene.meshes.length){this._camera.lowerRadiusLimit=null;const s=this._details.scene.getWorldExtends((e=>e.isVisible&&e.isEnabled()));e.zoomOnBoundingInfo(s.min,s.max);const i=s.max.subtract(s.min),r=s.min.add(i.scale(.5));t=1.2*i.length(),isFinite(t)||(t=1,r.copyFromFloats(0,0,0)),this._camera.setTarget(r)}this._camera.lowerRadiusLimit=.01*t,this._camera.wheelPrecision=100/t,this._camera.alpha=Math.PI/2,this._camera.beta=Math.PI/2,this._camera.radius=t,this._camera.minZ=.01*t,this._camera.maxZ=1e3*t,this._camera.speed=.2*t,this._camera.useAutoRotationBehavior=!0,this._camera.pinchPrecision=200/this._camera.radius,this._camera.upperRadiusLimit=5*this._camera.radius,this._camera.wheelDeltaPercentage=.01,this._camera.pinchDeltaPercentage=.01,this._camera.restoreStateInterpolationFactor=.1,yu(this._skybox,this._camera)}_applyAnimationSpeed(){this._details.model?.animationGroups.forEach((e=>e.speedRatio=this._animationSpeed))}_throwIfDisposedOrAborted(...e){if(this._isDisposed)throw new Error("Viewer is disposed.");for(const t of e)t?.throwIfAborted()}}
2
- /**
3
- * @license
4
- * Copyright 2019 Google LLC
5
- * SPDX-License-Identifier: BSD-3-Clause
6
- */const xu=globalThis,Mu=xu.ShadowRoot&&(void 0===xu.ShadyCSS||xu.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Iu=Symbol(),Su=new WeakMap;let vu=class{constructor(e,t,s){if(this._$cssResult$=!0,s!==Iu)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(Mu&&void 0===e){const s=void 0!==t&&1===t.length;s&&(e=Su.get(t)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),s&&Su.set(t,e))}return e}toString(){return this.cssText}};const Cu=Mu?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(const s of e.cssRules)t+=s.cssText;return(e=>new vu("string"==typeof e?e:e+"",void 0,Iu))(t)})(e):e
7
- /**
8
- * @license
9
- * Copyright 2017 Google LLC
10
- * SPDX-License-Identifier: BSD-3-Clause
11
- */,{is:Pu,defineProperty:Ou,getOwnPropertyDescriptor:Du,getOwnPropertyNames:Lu,getOwnPropertySymbols:Fu,getPrototypeOf:Nu}=Object,wu=globalThis,Bu=wu.trustedTypes,Uu=Bu?Bu.emptyScript:"",ku=wu.reactiveElementPolyfillSupport,Gu=(e,t)=>e,Vu={toAttribute(e,t){switch(t){case Boolean:e=e?Uu:null;break;case Object:case Array:e=null==e?e:JSON.stringify(e)}return e},fromAttribute(e,t){let s=e;switch(t){case Boolean:s=null!==e;break;case Number:s=null===e?null:Number(e);break;case Object:case Array:try{s=JSON.parse(e)}catch(e){s=null}}return s}},Hu=(e,t)=>!Pu(e,t),zu={attribute:!0,type:String,converter:Vu,reflect:!1,hasChanged:Hu};Symbol.metadata??=Symbol("metadata"),wu.litPropertyMetadata??=new WeakMap;class Xu extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=zu){if(t.state&&(t.attribute=!1),this._$Ei(),this.elementProperties.set(e,t),!t.noAccessor){const s=Symbol(),i=this.getPropertyDescriptor(e,s,t);void 0!==i&&Ou(this.prototype,e,i)}}static getPropertyDescriptor(e,t,s){const{get:i,set:r}=Du(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get(){return i?.call(this)},set(t){const n=i?.call(this);r.call(this,t),this.requestUpdate(e,n,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??zu}static _$Ei(){if(this.hasOwnProperty(Gu("elementProperties")))return;const e=Nu(this);e.finalize(),void 0!==e.l&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Gu("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Gu("properties"))){const e=this.properties,t=[...Lu(e),...Fu(e)];for(const s of t)this.createProperty(s,e[s])}const e=this[Symbol.metadata];if(null!==e){const t=litPropertyMetadata.get(e);if(void 0!==t)for(const[e,s]of t)this.elementProperties.set(e,s)}this._$Eh=new Map;for(const[e,t]of this.elementProperties){const s=this._$Eu(e,t);void 0!==s&&this._$Eh.set(s,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const s=new Set(e.flat(1/0).reverse());for(const e of s)t.unshift(Cu(e))}else void 0!==e&&t.push(Cu(e));return t}static _$Eu(e,t){const s=t.attribute;return!1===s?void 0:"string"==typeof s?s:"string"==typeof e?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((e=>this.enableUpdating=e)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((e=>e(this)))}addController(e){(this._$EO??=new Set).add(e),void 0!==this.renderRoot&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const s of t.keys())this.hasOwnProperty(s)&&(e.set(s,this[s]),delete this[s]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((e,t)=>{if(Mu)e.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(const s of t){const t=document.createElement("style"),i=xu.litNonce;void 0!==i&&t.setAttribute("nonce",i),t.textContent=s.cssText,e.appendChild(t)}})(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach((e=>e.hostConnected?.()))}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach((e=>e.hostDisconnected?.()))}attributeChangedCallback(e,t,s){this._$AK(e,s)}_$EC(e,t){const s=this.constructor.elementProperties.get(e),i=this.constructor._$Eu(e,s);if(void 0!==i&&!0===s.reflect){const r=(void 0!==s.converter?.toAttribute?s.converter:Vu).toAttribute(t,s.type);this._$Em=e,null==r?this.removeAttribute(i):this.setAttribute(i,r),this._$Em=null}}_$AK(e,t){const s=this.constructor,i=s._$Eh.get(e);if(void 0!==i&&this._$Em!==i){const e=s.getPropertyOptions(i),r="function"==typeof e.converter?{fromAttribute:e.converter}:void 0!==e.converter?.fromAttribute?e.converter:Vu;this._$Em=i,this[i]=r.fromAttribute(t,e.type),this._$Em=null}}requestUpdate(e,t,s){if(void 0!==e){if(s??=this.constructor.getPropertyOptions(e),!(s.hasChanged??Hu)(this[e],t))return;this.P(e,t,s)}!1===this.isUpdatePending&&(this._$ES=this._$ET())}P(e,t,s){this._$AL.has(e)||this._$AL.set(e,t),!0===s.reflect&&this._$Em!==e&&(this._$Ej??=new Set).add(e)}async _$ET(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}const e=this.scheduleUpdate();return null!=e&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}const e=this.constructor.elementProperties;if(e.size>0)for(const[t,s]of e)!0!==s.wrapped||this._$AL.has(t)||void 0===this[t]||this.P(t,this[t],s)}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach((e=>e.hostUpdate?.())),this.update(t)):this._$EU()}catch(t){throw e=!1,this._$EU(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach((e=>e.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EU(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Ej&&=this._$Ej.forEach((e=>this._$EC(e,this[e]))),this._$EU()}updated(e){}firstUpdated(e){}}Xu.elementStyles=[],Xu.shadowRootOptions={mode:"open"},Xu[Gu("elementProperties")]=new Map,Xu[Gu("finalized")]=new Map,ku?.({ReactiveElement:Xu}),(wu.reactiveElementVersions??=[]).push("2.0.4");
12
- /**
13
- * @license
14
- * Copyright 2017 Google LLC
15
- * SPDX-License-Identifier: BSD-3-Clause
16
- */
17
- const Wu=globalThis,Yu=Wu.trustedTypes,Ku=Yu?Yu.createPolicy("lit-html",{createHTML:e=>e}):void 0,qu="$lit$",Qu=`lit$${Math.random().toFixed(9).slice(2)}$`,ju="?"+Qu,Zu=`<${ju}>`,$u=document,Ju=()=>$u.createComment(""),ed=e=>null===e||"object"!=typeof e&&"function"!=typeof e,td=Array.isArray,sd="[ \t\n\f\r]",id=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,rd=/-->/g,nd=/>/g,ad=RegExp(`>|${sd}(?:([^\\s"'>=/]+)(${sd}*=${sd}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),od=/'/g,hd=/"/g,ld=/^(?:script|style|textarea|title)$/i,cd=(e=>(t,...s)=>({_$litType$:e,strings:t,values:s}))(1),ud=Symbol.for("lit-noChange"),dd=Symbol.for("lit-nothing"),_d=new WeakMap,fd=$u.createTreeWalker($u,129);function pd(e,t){if(!td(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==Ku?Ku.createHTML(t):t}class md{constructor({strings:e,_$litType$:t},s){let i;this.parts=[];let r=0,n=0;const a=e.length-1,o=this.parts,[h,l]=((e,t)=>{const s=e.length-1,i=[];let r,n=2===t?"<svg>":3===t?"<math>":"",a=id;for(let t=0;t<s;t++){const s=e[t];let o,h,l=-1,c=0;for(;c<s.length&&(a.lastIndex=c,h=a.exec(s),null!==h);)c=a.lastIndex,a===id?"!--"===h[1]?a=rd:void 0!==h[1]?a=nd:void 0!==h[2]?(ld.test(h[2])&&(r=RegExp("</"+h[2],"g")),a=ad):void 0!==h[3]&&(a=ad):a===ad?">"===h[0]?(a=r??id,l=-1):void 0===h[1]?l=-2:(l=a.lastIndex-h[2].length,o=h[1],a=void 0===h[3]?ad:'"'===h[3]?hd:od):a===hd||a===od?a=ad:a===rd||a===nd?a=id:(a=ad,r=void 0);const u=a===ad&&e[t+1].startsWith("/>")?" ":"";n+=a===id?s+Zu:l>=0?(i.push(o),s.slice(0,l)+qu+s.slice(l)+Qu+u):s+Qu+(-2===l?t:u)}return[pd(e,n+(e[s]||"<?>")+(2===t?"</svg>":3===t?"</math>":"")),i]})(e,t);if(this.el=md.createElement(h,s),fd.currentNode=this.el.content,2===t||3===t){const e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;null!==(i=fd.nextNode())&&o.length<a;){if(1===i.nodeType){if(i.hasAttributes())for(const e of i.getAttributeNames())if(e.endsWith(qu)){const t=l[n++],s=i.getAttribute(e).split(Qu),a=/([.?@])?(.*)/.exec(t);o.push({type:1,index:r,name:a[2],strings:s,ctor:"."===a[1]?yd:"?"===a[1]?bd:"@"===a[1]?Rd:Ad}),i.removeAttribute(e)}else e.startsWith(Qu)&&(o.push({type:6,index:r}),i.removeAttribute(e));if(ld.test(i.tagName)){const e=i.textContent.split(Qu),t=e.length-1;if(t>0){i.textContent=Yu?Yu.emptyScript:"";for(let s=0;s<t;s++)i.append(e[s],Ju()),fd.nextNode(),o.push({type:2,index:++r});i.append(e[t],Ju())}}}else if(8===i.nodeType)if(i.data===ju)o.push({type:2,index:r});else{let e=-1;for(;-1!==(e=i.data.indexOf(Qu,e+1));)o.push({type:7,index:r}),e+=Qu.length-1}r++}}static createElement(e,t){const s=$u.createElement("template");return s.innerHTML=e,s}}function gd(e,t,s=e,i){if(t===ud)return t;let r=void 0!==i?s.o?.[i]:s.l;const n=ed(t)?void 0:t._$litDirective$;return r?.constructor!==n&&(r?._$AO?.(!1),void 0===n?r=void 0:(r=new n(e),r._$AT(e,s,i)),void 0!==i?(s.o??=[])[i]=r:s.l=r),void 0!==r&&(t=gd(e,r._$AS(e,t.values),r,i)),t}class Td{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:t},parts:s}=this._$AD,i=(e?.creationScope??$u).importNode(t,!0);fd.currentNode=i;let r=fd.nextNode(),n=0,a=0,o=s[0];for(;void 0!==o;){if(n===o.index){let t;2===o.type?t=new Ed(r,r.nextSibling,this,e):1===o.type?t=new o.ctor(r,o.name,o.strings,this,e):6===o.type&&(t=new xd(r,this,e)),this._$AV.push(t),o=s[++a]}n!==o?.index&&(r=fd.nextNode(),n++)}return fd.currentNode=$u,i}p(e){let t=0;for(const s of this._$AV)void 0!==s&&(void 0!==s.strings?(s._$AI(e,s,t),t+=s.strings.length-2):s._$AI(e[t])),t++}}class Ed{get _$AU(){return this._$AM?._$AU??this.v}constructor(e,t,s,i){this.type=2,this._$AH=dd,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=s,this.options=i,this.v=i?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return void 0!==t&&11===e?.nodeType&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=gd(this,e,t),ed(e)?e===dd||null==e||""===e?(this._$AH!==dd&&this._$AR(),this._$AH=dd):e!==this._$AH&&e!==ud&&this._(e):void 0!==e._$litType$?this.$(e):void 0!==e.nodeType?this.T(e):(e=>td(e)||"function"==typeof e?.[Symbol.iterator])(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==dd&&ed(this._$AH)?this._$AA.nextSibling.data=e:this.T($u.createTextNode(e)),this._$AH=e}$(e){const{values:t,_$litType$:s}=e,i="number"==typeof s?this._$AC(e):(void 0===s.el&&(s.el=md.createElement(pd(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===i)this._$AH.p(t);else{const e=new Td(i,this),s=e.u(this.options);e.p(t),this.T(s),this._$AH=e}}_$AC(e){let t=_d.get(e.strings);return void 0===t&&_d.set(e.strings,t=new md(e)),t}k(e){td(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let s,i=0;for(const r of e)i===t.length?t.push(s=new Ed(this.O(Ju()),this.O(Ju()),this,this.options)):s=t[i],s._$AI(r),i++;i<t.length&&(this._$AR(s&&s._$AB.nextSibling,i),t.length=i)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e&&e!==this._$AB;){const t=e.nextSibling;e.remove(),e=t}}setConnected(e){void 0===this._$AM&&(this.v=e,this._$AP?.(e))}}class Ad{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,s,i,r){this.type=1,this._$AH=dd,this._$AN=void 0,this.element=e,this.name=t,this._$AM=i,this.options=r,s.length>2||""!==s[0]||""!==s[1]?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=dd}_$AI(e,t=this,s,i){const r=this.strings;let n=!1;if(void 0===r)e=gd(this,e,t,0),n=!ed(e)||e!==this._$AH&&e!==ud,n&&(this._$AH=e);else{const i=e;let a,o;for(e=r[0],a=0;a<r.length-1;a++)o=gd(this,i[s+a],t,a),o===ud&&(o=this._$AH[a]),n||=!ed(o)||o!==this._$AH[a],o===dd?e=dd:e!==dd&&(e+=(o??"")+r[a+1]),this._$AH[a]=o}n&&!i&&this.j(e)}j(e){e===dd?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class yd extends Ad{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===dd?void 0:e}}class bd extends Ad{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==dd)}}class Rd extends Ad{constructor(e,t,s,i,r){super(e,t,s,i,r),this.type=5}_$AI(e,t=this){if((e=gd(this,e,t,0)??dd)===ud)return;const s=this._$AH,i=e===dd&&s!==dd||e.capture!==s.capture||e.once!==s.once||e.passive!==s.passive,r=e!==dd&&(s===dd||i);i&&this.element.removeEventListener(this.name,this,s),r&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){"function"==typeof this._$AH?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}}class xd{constructor(e,t,s){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(e){gd(this,e)}}const Md=Wu.litHtmlPolyfillSupport;Md?.(md,Ed),(Wu.litHtmlVersions??=[]).push("3.2.0");
18
- /**
19
- * @license
20
- * Copyright 2017 Google LLC
21
- * SPDX-License-Identifier: BSD-3-Clause
22
- */
23
- class Id extends Xu{constructor(){super(...arguments),this.renderOptions={host:this},this.o=void 0}createRenderRoot(){const e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this.o=((e,t,s)=>{const i=s?.renderBefore??t;let r=i._$litPart$;if(void 0===r){const e=s?.renderBefore??null;i._$litPart$=r=new Ed(t.insertBefore(Ju(),e),e,void 0,s??{})}return r._$AI(e),r})(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this.o?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this.o?.setConnected(!1)}render(){return ud}}Id._$litElement$=!0,Id.finalized=!0,globalThis.litElementHydrateSupport?.({LitElement:Id});const Sd=globalThis.litElementPolyfillSupport;Sd?.({LitElement:Id}),(globalThis.litElementVersions??=[]).push("4.1.0");
24
- /**
25
- * @license
26
- * Copyright 2017 Google LLC
27
- * SPDX-License-Identifier: BSD-3-Clause
28
- */
29
- const vd={attribute:!0,type:String,converter:Vu,reflect:!1,hasChanged:Hu},Cd=(e=vd,t,s)=>{const{kind:i,metadata:r}=s;let n=globalThis.litPropertyMetadata.get(r);if(void 0===n&&globalThis.litPropertyMetadata.set(r,n=new Map),n.set(s.name,e),"accessor"===i){const{name:i}=s;return{set(s){const r=t.get.call(this);t.set.call(this,s),this.requestUpdate(i,r,e)},init(t){return void 0!==t&&this.P(i,void 0,e),t}}}if("setter"===i){const{name:i}=s;return function(s){const r=this[i];t.call(this,s),this.requestUpdate(i,r,e)}}throw Error("Unsupported decorator location: "+i)};
30
- /**
31
- * @license
32
- * Copyright 2017 Google LLC
33
- * SPDX-License-Identifier: BSD-3-Clause
34
- */function Pd(e){return(t,s)=>"object"==typeof s?Cd(e,t,s):((e,t,s)=>{const i=t.hasOwnProperty(s);return t.constructor.createProperty(s,i?{...e,wrapped:!0}:e),i?Object.getOwnPropertyDescriptor(t,s):void 0})(e,t,s)
35
- /**
36
- * @license
37
- * Copyright 2017 Google LLC
38
- * SPDX-License-Identifier: BSD-3-Clause
39
- */}function Od(e){return Pd({...e,state:!0,attribute:!1})}
40
- /**
41
- * @license
42
- * Copyright 2017 Google LLC
43
- * SPDX-License-Identifier: BSD-3-Clause
44
- */class Dd{constructor(e=30){this._enabled=!0,this._rollingFrameTime=new Ld(e)}sampleFrame(e=fe.Now){if(this._enabled){if(null!=this._lastFrameTimeMs){const t=e-this._lastFrameTimeMs;this._rollingFrameTime.add(t)}this._lastFrameTimeMs=e}}get averageFrameTime(){return this._rollingFrameTime.average}get averageFrameTimeVariance(){return this._rollingFrameTime.variance}get instantaneousFrameTime(){return this._rollingFrameTime.history(0)}get averageFPS(){return 1e3/this._rollingFrameTime.average}get instantaneousFPS(){const e=this._rollingFrameTime.history(0);return 0===e?0:1e3/e}get isSaturated(){return this._rollingFrameTime.isSaturated()}enable(){this._enabled=!0}disable(){this._enabled=!1,this._lastFrameTimeMs=null}get isEnabled(){return this._enabled}reset(){this._lastFrameTimeMs=null,this._rollingFrameTime.reset()}}class Ld{constructor(e){this._samples=new Array(e),this.reset()}add(e){let t;if(this.isSaturated()){const e=this._samples[this._pos];t=e-this.average,this.average-=t/(this._sampleCount-1),this._m2-=t*(e-this.average)}else this._sampleCount++;t=e-this.average,this.average+=t/this._sampleCount,this._m2+=t*(e-this.average),this.variance=this._m2/(this._sampleCount-1),this._samples[this._pos]=e,this._pos++,this._pos%=this._samples.length}history(e){if(e>=this._sampleCount||e>=this._samples.length)return 0;const t=this._wrapPosition(this._pos-1);return this._samples[this._wrapPosition(t-e)]}isSaturated(){return this._sampleCount>=this._samples.length}reset(){this.average=0,this.variance=0,this._sampleCount=0,this._pos=0,this._m2=0}_wrapPosition(e){const t=this._samples.length;return(e%t+t)%t}}function Fd(e){if(e.requestPointerLock){const t=e.requestPointerLock();t instanceof Promise?t.then((()=>{e.focus()})).catch((()=>{})):e.focus()}}Ds.prototype.setAlphaMode=function(e,t=!1){if(this._alphaMode!==e){switch(e){case Ze.ALPHA_DISABLE:this._alphaState.alphaBlend=!1;break;case Ze.ALPHA_PREMULTIPLIED:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_PREMULTIPLIED_PORTERDUFF:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_COMBINE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_ONEONE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_ADD:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_SUBTRACT:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_MULTIPLY:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR,this._gl.ZERO,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_MAXIMIZED:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_INTERPOLATE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR,this._gl.ONE_MINUS_CONSTANT_COLOR,this._gl.CONSTANT_ALPHA,this._gl.ONE_MINUS_CONSTANT_ALPHA),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_SCREENMODE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_ONEONE_ONEONE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_ALPHATOCOLOR:this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA,this._gl.ONE,this._gl.ZERO,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_REVERSEONEMINUS:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ONE_MINUS_DST_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_SRC_DSTONEMINUSSRCALPHA:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_ONEONE_ONEZERO:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE,this._gl.ONE,this._gl.ONE,this._gl.ZERO),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_EXCLUSION:this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR,this._gl.ONE_MINUS_SRC_COLOR,this._gl.ZERO,this._gl.ONE),this._alphaState.alphaBlend=!0;break;case Ze.ALPHA_LAYER_ACCUMULATE:this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA,this._gl.ONE_MINUS_SRC_ALPHA,this._gl.ONE,this._gl.ONE_MINUS_SRC_ALPHA),this._alphaState.alphaBlend=!0}t||(this.depthCullingState.depthMask=e===Ze.ALPHA_DISABLE),this._alphaMode=e}else if(!t){const t=e===Ze.ALPHA_DISABLE;this.depthCullingState.depthMask!==t&&(this.depthCullingState.depthMask=t)}},Ds.prototype.updateDynamicIndexBuffer=function(e,t,s=0){let i;this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER]=null,this.bindIndexBuffer(e),i=e.is32Bits?t instanceof Uint32Array?t:new Uint32Array(t):t instanceof Uint16Array?t:new Uint16Array(t),this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER,i,this._gl.DYNAMIC_DRAW),this._resetIndexBufferBinding()},Ds.prototype.updateDynamicVertexBuffer=function(e,t,s,i){this.bindArrayBuffer(e),void 0===s&&(s=0);const r=t.byteLength||t.length;void 0===i||i>=r&&0===s?t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,s,new Float32Array(t)):this._gl.bufferSubData(this._gl.ARRAY_BUFFER,s,t):t instanceof Array?this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,new Float32Array(t).subarray(s,s+i)):(t=t instanceof ArrayBuffer?new Uint8Array(t,s,i):new Uint8Array(t.buffer,t.byteOffset+s,i),this._gl.bufferSubData(this._gl.ARRAY_BUFFER,0,t)),this._resetVertexBufferBinding()},yt.prototype.displayLoadingUI=function(){if(!oe())return;const e=this.loadingScreen;e&&e.displayLoadingUI()},yt.prototype.hideLoadingUI=function(){if(!oe())return;const e=this._loadingScreen;e&&e.hideLoadingUI()},Object.defineProperty(yt.prototype,"loadingScreen",{get:function(){return!this._loadingScreen&&this._renderingCanvas&&(this._loadingScreen=yt.DefaultLoadingScreenFactory(this._renderingCanvas)),this._loadingScreen},set:function(e){this._loadingScreen=e},enumerable:!0,configurable:!0}),Object.defineProperty(yt.prototype,"loadingUIText",{set:function(e){this.loadingScreen.loadingUIText=e},enumerable:!0,configurable:!0}),Object.defineProperty(yt.prototype,"loadingUIBackgroundColor",{set:function(e){this.loadingScreen.loadingUIBackgroundColor=e},enumerable:!0,configurable:!0}),yt.prototype.getInputElement=function(){return this._renderingCanvas},yt.prototype.getRenderingCanvasClientRect=function(){return this._renderingCanvas?this._renderingCanvas.getBoundingClientRect():null},yt.prototype.getInputElementClientRect=function(){return this._renderingCanvas?this.getInputElement().getBoundingClientRect():null},yt.prototype.getAspectRatio=function(e,t=!1){const s=e.viewport;return this.getRenderWidth(t)*s.width/(this.getRenderHeight(t)*s.height)},yt.prototype.getScreenAspectRatio=function(){return this.getRenderWidth(!0)/this.getRenderHeight(!0)},yt.prototype._verifyPointerLock=function(){this._onPointerLockChange?.()},yt.prototype.setAlphaEquation=function(e){if(this._alphaEquation!==e){switch(e){case Ze.ALPHA_EQUATION_ADD:this._alphaState.setAlphaEquationParameters(Ze.GL_ALPHA_EQUATION_ADD,Ze.GL_ALPHA_EQUATION_ADD);break;case Ze.ALPHA_EQUATION_SUBSTRACT:this._alphaState.setAlphaEquationParameters(Ze.GL_ALPHA_EQUATION_SUBTRACT,Ze.GL_ALPHA_EQUATION_SUBTRACT);break;case Ze.ALPHA_EQUATION_REVERSE_SUBTRACT:this._alphaState.setAlphaEquationParameters(Ze.GL_ALPHA_EQUATION_REVERSE_SUBTRACT,Ze.GL_ALPHA_EQUATION_REVERSE_SUBTRACT);break;case Ze.ALPHA_EQUATION_MAX:this._alphaState.setAlphaEquationParameters(Ze.GL_ALPHA_EQUATION_MAX,Ze.GL_ALPHA_EQUATION_MAX);break;case Ze.ALPHA_EQUATION_MIN:this._alphaState.setAlphaEquationParameters(Ze.GL_ALPHA_EQUATION_MIN,Ze.GL_ALPHA_EQUATION_MIN);break;case Ze.ALPHA_EQUATION_DARKEN:this._alphaState.setAlphaEquationParameters(Ze.GL_ALPHA_EQUATION_MIN,Ze.GL_ALPHA_EQUATION_ADD)}this._alphaEquation=e}},yt.prototype.getInputElement=function(){return this._renderingCanvas},yt.prototype.getDepthFunction=function(){return this._depthCullingState.depthFunc},yt.prototype.setDepthFunction=function(e){this._depthCullingState.depthFunc=e},yt.prototype.setDepthFunctionToGreater=function(){this.setDepthFunction(Ze.GREATER)},yt.prototype.setDepthFunctionToGreaterOrEqual=function(){this.setDepthFunction(Ze.GEQUAL)},yt.prototype.setDepthFunctionToLess=function(){this.setDepthFunction(Ze.LESS)},yt.prototype.setDepthFunctionToLessOrEqual=function(){this.setDepthFunction(Ze.LEQUAL)},yt.prototype.getDepthWrite=function(){return this._depthCullingState.depthMask},yt.prototype.setDepthWrite=function(e){this._depthCullingState.depthMask=e},yt.prototype.getStencilBuffer=function(){return this._stencilState.stencilTest},yt.prototype.setStencilBuffer=function(e){this._stencilState.stencilTest=e},yt.prototype.getStencilMask=function(){return this._stencilState.stencilMask},yt.prototype.setStencilMask=function(e){this._stencilState.stencilMask=e},yt.prototype.getStencilFunction=function(){return this._stencilState.stencilFunc},yt.prototype.getStencilFunctionReference=function(){return this._stencilState.stencilFuncRef},yt.prototype.getStencilFunctionMask=function(){return this._stencilState.stencilFuncMask},yt.prototype.setStencilFunction=function(e){this._stencilState.stencilFunc=e},yt.prototype.setStencilFunctionReference=function(e){this._stencilState.stencilFuncRef=e},yt.prototype.setStencilFunctionMask=function(e){this._stencilState.stencilFuncMask=e},yt.prototype.getStencilOperationFail=function(){return this._stencilState.stencilOpStencilFail},yt.prototype.getStencilOperationDepthFail=function(){return this._stencilState.stencilOpDepthFail},yt.prototype.getStencilOperationPass=function(){return this._stencilState.stencilOpStencilDepthPass},yt.prototype.setStencilOperationFail=function(e){this._stencilState.stencilOpStencilFail=e},yt.prototype.setStencilOperationDepthFail=function(e){this._stencilState.stencilOpDepthFail=e},yt.prototype.setStencilOperationPass=function(e){this._stencilState.stencilOpStencilDepthPass=e},yt.prototype.cacheStencilState=function(){this._cachedStencilBuffer=this.getStencilBuffer(),this._cachedStencilFunction=this.getStencilFunction(),this._cachedStencilMask=this.getStencilMask(),this._cachedStencilOperationPass=this.getStencilOperationPass(),this._cachedStencilOperationFail=this.getStencilOperationFail(),this._cachedStencilOperationDepthFail=this.getStencilOperationDepthFail(),this._cachedStencilReference=this.getStencilFunctionReference()},yt.prototype.restoreStencilState=function(){this.setStencilFunction(this._cachedStencilFunction),this.setStencilMask(this._cachedStencilMask),this.setStencilBuffer(this._cachedStencilBuffer),this.setStencilOperationPass(this._cachedStencilOperationPass),this.setStencilOperationFail(this._cachedStencilOperationFail),this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail),this.setStencilFunctionReference(this._cachedStencilReference)},yt.prototype.setAlphaConstants=function(e,t,s,i){this._alphaState.setAlphaBlendConstants(e,t,s,i)},yt.prototype.getAlphaMode=function(){return this._alphaMode},yt.prototype.getAlphaEquation=function(){return this._alphaEquation},yt.prototype.getRenderPassNames=function(){return this._renderPassNames},yt.prototype.getCurrentRenderPassName=function(){return this._renderPassNames[this.currentRenderPassId]},yt.prototype.createRenderPassId=function(e){const t=++yt._RenderPassIdCounter;return this._renderPassNames[t]=e??"NONAME",t},yt.prototype.releaseRenderPassId=function(e){this._renderPassNames[e]=void 0;for(let t=0;t<this.scenes.length;++t){const s=this.scenes[t];for(let t=0;t<s.meshes.length;++t){const i=s.meshes[t];if(i.subMeshes)for(let t=0;t<i.subMeshes.length;++t){i.subMeshes[t]._removeDrawWrapper(e)}}}},yt.AudioEngineFactory=(e,t,s)=>new Nd(e,t,s);class Nd{get audioContext(){return this._audioContextInitialized||this._initializeAudioContext(),this._audioContext}constructor(e=null,t=null,s=null){if(this._audioContext=null,this._audioContextInitialized=!1,this._muteButton=null,this._audioDestination=null,this.canUseWebAudio=!1,this.WarnedWebAudioUnsupported=!1,this.isMP3supported=!1,this.isOGGsupported=!1,this.unlocked=!1,this.useCustomUnlockedButton=!1,this.onAudioUnlockedObservable=new g,this.onAudioLockedObservable=new g,this._tryToRun=!1,this._onResize=()=>{this._moveButtonToTopLeft()},!oe())return;void 0!==window.AudioContext&&(this.canUseWebAudio=!0);const i=document.createElement("audio");this._hostElement=e,this._audioContext=t,this._audioDestination=s;try{i&&i.canPlayType&&(i.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/,"")||i.canPlayType("audio/mp3").replace(/^no$/,""))&&(this.isMP3supported=!0)}catch(e){}try{i&&i.canPlayType&&i.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(this.isOGGsupported=!0)}catch(e){}}lock(){this._triggerSuspendedState()}unlock(){if("running"===this._audioContext?.state)return this._hideMuteButton(),void(this.unlocked||(this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)));this._tryToRun?this._audioContext?.suspend().then((()=>{this._tryToRun=!1,this._triggerRunningState()})):this._triggerRunningState()}_resumeAudioContextOnStateChange(){this._audioContext?.addEventListener("statechange",(()=>{this.unlocked&&"running"!==this._audioContext?.state&&this._resumeAudioContext()}),{once:!0,passive:!0,signal:AbortSignal.timeout(3e3)})}_resumeAudioContext(){return this._audioContext?.resume?this._audioContext.resume():Promise.resolve()}_initializeAudioContext(){try{this.canUseWebAudio&&(this._audioContext||(this._audioContext=new AudioContext),this.masterGain=this._audioContext.createGain(),this.masterGain.gain.value=1,this._audioDestination||(this._audioDestination=this._audioContext.destination),this.masterGain.connect(this._audioDestination),this._audioContextInitialized=!0,"running"===this._audioContext.state&&this._triggerRunningState())}catch(e){this.canUseWebAudio=!1,ue.Error("Web Audio: "+e.message)}}_triggerRunningState(){this._tryToRun||(this._tryToRun=!0,this._resumeAudioContext().then((()=>{this._tryToRun=!1,this._muteButton&&this._hideMuteButton(),this.unlocked=!0,this.onAudioUnlockedObservable.notifyObservers(this)})).catch((()=>{this._tryToRun=!1,this.unlocked=!1})))}_triggerSuspendedState(){this.unlocked=!1,this.onAudioLockedObservable.notifyObservers(this),this._displayMuteButton()}_displayMuteButton(){if(this.useCustomUnlockedButton||this._muteButton)return;this._muteButton=document.createElement("BUTTON"),this._muteButton.className="babylonUnmuteIcon",this._muteButton.id="babylonUnmuteIconBtn",this._muteButton.title="Unmute";const e=".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url("+(window.SVGSVGElement?"data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E":"https://cdn.babylonjs.com/Assets/audio.png")+"); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }",t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.getElementsByTagName("head")[0].appendChild(t),document.body.appendChild(this._muteButton),this._moveButtonToTopLeft(),this._muteButton.addEventListener("touchend",(()=>{this._triggerRunningState()}),!0),this._muteButton.addEventListener("click",(()=>{this.unlock()}),!0),window.addEventListener("resize",this._onResize)}_moveButtonToTopLeft(){this._hostElement&&this._muteButton&&(this._muteButton.style.top=this._hostElement.offsetTop+20+"px",this._muteButton.style.left=this._hostElement.offsetLeft+20+"px")}_hideMuteButton(){this._muteButton&&(document.body.removeChild(this._muteButton),this._muteButton=null)}dispose(){this.canUseWebAudio&&this._audioContextInitialized&&(this._connectedAnalyser&&this._audioContext&&(this._connectedAnalyser.stopDebugCanvas(),this._connectedAnalyser.dispose(),this.masterGain.disconnect(),this.masterGain.connect(this._audioContext.destination),this._connectedAnalyser=null),this.masterGain.gain.value=1),this.WarnedWebAudioUnsupported=!1,this._hideMuteButton(),window.removeEventListener("resize",this._onResize),this.onAudioUnlockedObservable.clear(),this.onAudioLockedObservable.clear()}getGlobalVolume(){return this.canUseWebAudio&&this._audioContextInitialized?this.masterGain.gain.value:-1}setGlobalVolume(e){this.canUseWebAudio&&this._audioContextInitialized&&(this.masterGain.gain.value=e)}connectToAnalyser(e){this._connectedAnalyser&&this._connectedAnalyser.stopDebugCanvas(),this.canUseWebAudio&&this._audioContextInitialized&&this._audioContext&&(this._connectedAnalyser=e,this.masterGain.disconnect(),this._connectedAnalyser.connectAudioNodes(this.masterGain,this._audioContext.destination))}}class wd extends Ds{static get NpmPackage(){return yt.NpmPackage}static get Version(){return yt.Version}static get Instances(){return C.Instances}static get LastCreatedEngine(){return C.LastCreatedEngine}static get LastCreatedScene(){return C.LastCreatedScene}static DefaultLoadingScreenFactory(e){return yt.DefaultLoadingScreenFactory(e)}get _supportsHardwareTextureRescaling(){return!!wd._RescalePostProcessFactory}_measureFps(){this._performanceMonitor.sampleFrame(),this._fps=this._performanceMonitor.averageFPS,this._deltaTime=this._performanceMonitor.instantaneousFrameTime||0}get performanceMonitor(){return this._performanceMonitor}constructor(e,t,s,i=!1){if(super(e,t,s,i),this.customAnimationFrameRequester=null,this._performanceMonitor=new Dd,this._drawCalls=new mr,e&&(this._features.supportRenderPasses=!0,s=this._creationOptions,e.getContext)){const t=e;this._sharedInit(t)}}_initGLContext(){super._initGLContext(),this._rescalePostProcess=null}_sharedInit(e){super._sharedInit(e),function(e,t,s){e._onCanvasFocus=()=>{e.onCanvasFocusObservable.notifyObservers(e)},e._onCanvasBlur=()=>{e.onCanvasBlurObservable.notifyObservers(e)},e._onCanvasContextMenu=t=>{e.disableContextMenu&&t.preventDefault()},t.addEventListener("focus",e._onCanvasFocus),t.addEventListener("blur",e._onCanvasBlur),t.addEventListener("contextmenu",e._onCanvasContextMenu),e._onBlur=()=>{e.disablePerformanceMonitorInBackground&&e.performanceMonitor.disable(),e._windowIsBackground=!0},e._onFocus=()=>{e.disablePerformanceMonitorInBackground&&e.performanceMonitor.enable(),e._windowIsBackground=!1},e._onCanvasPointerOut=s=>{document.elementFromPoint(s.clientX,s.clientY)!==t&&e.onCanvasPointerOutObservable.notifyObservers(s)};const i=e.getHostWindow();i&&"function"==typeof i.addEventListener&&(i.addEventListener("blur",e._onBlur),i.addEventListener("focus",e._onFocus)),t.addEventListener("pointerout",e._onCanvasPointerOut),s.doNotHandleTouchAction||function(e){e&&e.setAttribute&&(e.setAttribute("touch-action","none"),e.style.touchAction="none",e.style.webkitTapHighlightColor="transparent")}(t),!yt.audioEngine&&s.audioEngine&&yt.AudioEngineFactory&&(yt.audioEngine=yt.AudioEngineFactory(e.getRenderingCanvas(),e.getAudioContext(),e.getAudioDestination())),le()&&(e._onFullscreenChange=()=>{e.isFullscreen=!!document.fullscreenElement,e.isFullscreen&&e._pointerLockRequested&&t&&Fd(t)},document.addEventListener("fullscreenchange",e._onFullscreenChange,!1),document.addEventListener("webkitfullscreenchange",e._onFullscreenChange,!1),e._onPointerLockChange=()=>{e.isPointerLock=document.pointerLockElement===t},document.addEventListener("pointerlockchange",e._onPointerLockChange,!1),document.addEventListener("webkitpointerlockchange",e._onPointerLockChange,!1)),e.enableOfflineSupport=void 0!==yt.OfflineProviderFactory,e._deterministicLockstep=!!s.deterministicLockstep,e._lockstepMaxSteps=s.lockstepMaxSteps||0,e._timeStep=s.timeStep||1/60}(this,e,this._creationOptions)}resizeImageBitmap(e,t,s){return function(e,t,s,i){const r=e.createCanvas(s,i).getContext("2d");if(!r)throw new Error("Unable to get 2d context for resizeImageBitmap");return r.drawImage(t,0,0),r.getImageData(0,0,s,i).data}(this,e,t,s)}_createImageBitmapFromSource(e,t){return function(e,t,s){return new Promise(((i,r)=>{const n=new Image;n.onload=()=>{n.decode().then((()=>{e.createImageBitmap(n,s).then((e=>{i(e)}))}))},n.onerror=()=>{r(`Error loading image ${n.src}`)},n.src=t}))}(this,e,t)}switchFullscreen(e){this.isFullscreen?this.exitFullscreen():this.enterFullscreen(e)}enterFullscreen(e){this.isFullscreen||(this._pointerLockRequested=e,this._renderingCanvas&&function(e){const t=e.requestFullscreen||e.webkitRequestFullscreen;t&&t.call(e)}(this._renderingCanvas))}exitFullscreen(){this.isFullscreen&&function(){const e=document;document.exitFullscreen?document.exitFullscreen():e.webkitCancelFullScreen&&e.webkitCancelFullScreen()}()}setDitheringState(e){e?this._gl.enable(this._gl.DITHER):this._gl.disable(this._gl.DITHER)}setRasterizerState(e){e?this._gl.disable(this._gl.RASTERIZER_DISCARD):this._gl.enable(this._gl.RASTERIZER_DISCARD)}setDirectViewport(e,t,s,i){const r=this._cachedViewport;return this._cachedViewport=null,this._viewport(e,t,s,i),r}scissorClear(e,t,s,i,r){this.enableScissor(e,t,s,i),this.clear(r,!0,!0,!0),this.disableScissor()}enableScissor(e,t,s,i){const r=this._gl;r.enable(r.SCISSOR_TEST),r.scissor(e,t,s,i)}disableScissor(){const e=this._gl;e.disable(e.SCISSOR_TEST)}_loadFileAsync(e,t,s){return new Promise(((i,r)=>{this._loadFile(e,(e=>{i(e)}),void 0,t,s,((e,t)=>{r(t)}))}))}getVertexShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[0]):null}getFragmentShaderSource(e){const t=this._gl.getAttachedShaders(e);return t?this._gl.getShaderSource(t[1]):null}set framebufferDimensionsObject(e){this._framebufferDimensionsObject=e,this._framebufferDimensionsObject&&this.onResizeObservable.notifyObservers(this)}_rebuildBuffers(){for(const e of this.scenes)e.resetCachedMaterial(),e._rebuildGeometries();for(const e of this._virtualScenes)e.resetCachedMaterial(),e._rebuildGeometries();super._rebuildBuffers()}getFontOffset(e){return function(e){const t=document.createElement("span");t.textContent="Hg",t.style.font=e;const s=document.createElement("div");s.style.display="inline-block",s.style.width="1px",s.style.height="0px",s.style.verticalAlign="bottom";const i=document.createElement("div");i.style.whiteSpace="nowrap",i.appendChild(t),i.appendChild(s),document.body.appendChild(i);let r=0,n=0;try{n=s.getBoundingClientRect().top-t.getBoundingClientRect().top,s.style.verticalAlign="baseline",r=s.getBoundingClientRect().top-t.getBoundingClientRect().top}finally{document.body.removeChild(i)}return{ascent:r,height:n,descent:n-r}}(e)}_cancelFrame(){if(this.customAnimationFrameRequester){if(0!==this._frameHandler){this._frameHandler=0;const{cancelAnimationFrame:e}=this.customAnimationFrameRequester;e&&e(this.customAnimationFrameRequester.requestID)}}else super._cancelFrame()}_renderLoop(){if(this._frameHandler=0,!this._contextWasLost){let e=!0;(this.isDisposed||!this.renderEvenInBackground&&this._windowIsBackground)&&(e=!1),e&&(this.beginFrame(),this._renderViews()||this._renderFrame(),this.endFrame())}this._activeRenderLoops.length>0&&0===this._frameHandler&&(this.customAnimationFrameRequester?(this.customAnimationFrameRequester.requestID=this._queueNewFrame(this.customAnimationFrameRequester.renderFunction||this._boundRenderFunction,this.customAnimationFrameRequester),this._frameHandler=this.customAnimationFrameRequester.requestID):this._frameHandler=this._queueNewFrame(this._boundRenderFunction,this.getHostWindow()))}enterPointerlock(){this._renderingCanvas&&Fd(this._renderingCanvas)}exitPointerlock(){document.exitPointerLock&&document.exitPointerLock()}beginFrame(){this._measureFps(),super.beginFrame()}_deletePipelineContext(e){const t=e;t&&t.program&&t.transformFeedback&&(this.deleteTransformFeedback(t.transformFeedback),t.transformFeedback=null),super._deletePipelineContext(e)}createShaderProgram(e,t,s,i,r,n=null){r=r||this._gl,this.onBeforeShaderCompilationObservable.notifyObservers(this);const a=super.createShaderProgram(e,t,s,i,r,n);return this.onAfterShaderCompilationObservable.notifyObservers(this),a}_createShaderProgram(e,t,s,i,r=null){const n=i.createProgram();if(e.program=n,!n)throw new Error("Unable to create program");if(i.attachShader(n,t),i.attachShader(n,s),this.webGLVersion>1&&r){const t=this.createTransformFeedback();this.bindTransformFeedback(t),this.setTranformFeedbackVaryings(n,r),e.transformFeedback=t}return i.linkProgram(n),this.webGLVersion>1&&r&&this.bindTransformFeedback(null),e.context=i,e.vertexShader=t,e.fragmentShader=s,e.isParallelCompiled||this._finalizePipelineContext(e),n}_releaseTexture(e){super._releaseTexture(e)}_releaseRenderTargetWrapper(e){super._releaseRenderTargetWrapper(e),this.scenes.forEach((t=>{t.postProcesses.forEach((t=>{t._outputTexture===e&&(t._outputTexture=null)})),t.cameras.forEach((t=>{t._postProcesses.forEach((t=>{t&&t._outputTexture===e&&(t._outputTexture=null)}))}))}))}_rescaleTexture(e,t,s,i,r){this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MAG_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_MIN_FILTER,this._gl.LINEAR),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_S,this._gl.CLAMP_TO_EDGE),this._gl.texParameteri(this._gl.TEXTURE_2D,this._gl.TEXTURE_WRAP_T,this._gl.CLAMP_TO_EDGE);const n=this.createRenderTargetTexture({width:t.width,height:t.height},{generateMipMaps:!1,type:Ze.TEXTURETYPE_UNSIGNED_INT,samplingMode:Ze.TEXTURE_BILINEAR_SAMPLINGMODE,generateDepthBuffer:!1,generateStencilBuffer:!1});if(!this._rescalePostProcess&&wd._RescalePostProcessFactory&&(this._rescalePostProcess=wd._RescalePostProcessFactory(this)),this._rescalePostProcess){this._rescalePostProcess.externalTextureSamplerBinding=!0;const a=()=>{this._rescalePostProcess.onApply=function(t){t._bindTexture("textureSampler",e)};let a=s;a||(a=this.scenes[this.scenes.length-1]),a.postProcessManager.directRender([this._rescalePostProcess],n,!0),this._bindTextureDirectly(this._gl.TEXTURE_2D,t,!0),this._gl.copyTexImage2D(this._gl.TEXTURE_2D,0,i,0,0,t.width,t.height,0),this.unBindFramebuffer(n),n.dispose(),r&&r()},o=this._rescalePostProcess.getEffect();o?o.executeWhenCompiled(a):this._rescalePostProcess.onEffectCreatedObservable.addOnce((e=>{e.executeWhenCompiled(a)}))}}wrapWebGLTexture(e,t=!1,s=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,i=0,r=0){const n=new Ps(e,this._gl),a=new Tt(this,0,!0);return a._hardwareTexture=n,a.baseWidth=i,a.baseHeight=r,a.width=i,a.height=r,a.isReady=!0,a.useMipMaps=t,this.updateTextureSamplingMode(s,a),a}_uploadImageToTexture(e,t,s=0,i=0){const r=this._gl,n=this._getWebGLTextureType(e.type),a=this._getInternalFormat(e.format),o=this._getRGBABufferInternalSizedFormat(e.type,a),h=e.isCube?r.TEXTURE_CUBE_MAP:r.TEXTURE_2D;this._bindTextureDirectly(h,e,!0),this._unpackFlipY(e.invertY);let l=r.TEXTURE_2D;e.isCube&&(l=r.TEXTURE_CUBE_MAP_POSITIVE_X+s),r.texImage2D(l,i,o,a,n,t),this._bindTextureDirectly(h,null,!0)}updateTextureComparisonFunction(e,t){if(1===this.webGLVersion)return void ue.Error("WebGL 1 does not support texture comparison.");const s=this._gl;e.isCube?(this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,e,!0),0===t?(s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_COMPARE_FUNC,Ze.LEQUAL),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_COMPARE_MODE,s.NONE)):(s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_COMPARE_FUNC,t),s.texParameteri(s.TEXTURE_CUBE_MAP,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP,null)):(this._bindTextureDirectly(this._gl.TEXTURE_2D,e,!0),0===t?(s.texParameteri(s.TEXTURE_2D,s.TEXTURE_COMPARE_FUNC,Ze.LEQUAL),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_COMPARE_MODE,s.NONE)):(s.texParameteri(s.TEXTURE_2D,s.TEXTURE_COMPARE_FUNC,t),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE)),this._bindTextureDirectly(this._gl.TEXTURE_2D,null)),e._comparisonFunction=t}createInstancesBuffer(e){const t=this._gl.createBuffer();if(!t)throw new Error("Unable to create instance buffer");const s=new Cs(t);return s.capacity=e,this.bindArrayBuffer(s),this._gl.bufferData(this._gl.ARRAY_BUFFER,e,this._gl.DYNAMIC_DRAW),s.references=1,s}deleteInstancesBuffer(e){this._gl.deleteBuffer(e)}_clientWaitAsync(e,t=0,s=10){const i=this._gl;return new Promise(((r,n)=>{const a=()=>{const o=i.clientWaitSync(e,t,0);o!=i.WAIT_FAILED?o!=i.TIMEOUT_EXPIRED?r():setTimeout(a,s):n()};a()}))}_readPixelsAsync(e,t,s,i,r,n,a){if(this._webGLVersion<2)throw new Error("_readPixelsAsync only work on WebGL2+");const o=this._gl,h=o.createBuffer();o.bindBuffer(o.PIXEL_PACK_BUFFER,h),o.bufferData(o.PIXEL_PACK_BUFFER,a.byteLength,o.STREAM_READ),o.readPixels(e,t,s,i,r,n,0),o.bindBuffer(o.PIXEL_PACK_BUFFER,null);const l=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);return l?(o.flush(),this._clientWaitAsync(l,0,10).then((()=>(o.deleteSync(l),o.bindBuffer(o.PIXEL_PACK_BUFFER,h),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,a),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),o.deleteBuffer(h),a)))):null}dispose(){this.hideLoadingUI(),this._rescalePostProcess&&this._rescalePostProcess.dispose(),function(e,t){1===C.Instances.length&&yt.audioEngine&&(yt.audioEngine.dispose(),yt.audioEngine=null);const s=e.getHostWindow();s&&"function"==typeof s.removeEventListener&&(s.removeEventListener("blur",e._onBlur),s.removeEventListener("focus",e._onFocus)),t&&(t.removeEventListener("focus",e._onCanvasFocus),t.removeEventListener("blur",e._onCanvasBlur),t.removeEventListener("pointerout",e._onCanvasPointerOut),t.removeEventListener("contextmenu",e._onCanvasContextMenu)),le()&&(document.removeEventListener("fullscreenchange",e._onFullscreenChange),document.removeEventListener("mozfullscreenchange",e._onFullscreenChange),document.removeEventListener("webkitfullscreenchange",e._onFullscreenChange),document.removeEventListener("msfullscreenchange",e._onFullscreenChange),document.removeEventListener("pointerlockchange",e._onPointerLockChange),document.removeEventListener("mspointerlockchange",e._onPointerLockChange),document.removeEventListener("mozpointerlockchange",e._onPointerLockChange),document.removeEventListener("webkitpointerlockchange",e._onPointerLockChange))}(this,this._renderingCanvas),super.dispose()}}wd.ALPHA_DISABLE=Ze.ALPHA_DISABLE,wd.ALPHA_ADD=Ze.ALPHA_ADD,wd.ALPHA_COMBINE=Ze.ALPHA_COMBINE,wd.ALPHA_SUBTRACT=Ze.ALPHA_SUBTRACT,wd.ALPHA_MULTIPLY=Ze.ALPHA_MULTIPLY,wd.ALPHA_MAXIMIZED=Ze.ALPHA_MAXIMIZED,wd.ALPHA_ONEONE=Ze.ALPHA_ONEONE,wd.ALPHA_PREMULTIPLIED=Ze.ALPHA_PREMULTIPLIED,wd.ALPHA_PREMULTIPLIED_PORTERDUFF=Ze.ALPHA_PREMULTIPLIED_PORTERDUFF,wd.ALPHA_INTERPOLATE=Ze.ALPHA_INTERPOLATE,wd.ALPHA_SCREENMODE=Ze.ALPHA_SCREENMODE,wd.DELAYLOADSTATE_NONE=Ze.DELAYLOADSTATE_NONE,wd.DELAYLOADSTATE_LOADED=Ze.DELAYLOADSTATE_LOADED,wd.DELAYLOADSTATE_LOADING=Ze.DELAYLOADSTATE_LOADING,wd.DELAYLOADSTATE_NOTLOADED=Ze.DELAYLOADSTATE_NOTLOADED,wd.NEVER=Ze.NEVER,wd.ALWAYS=Ze.ALWAYS,wd.LESS=Ze.LESS,wd.EQUAL=Ze.EQUAL,wd.LEQUAL=Ze.LEQUAL,wd.GREATER=Ze.GREATER,wd.GEQUAL=Ze.GEQUAL,wd.NOTEQUAL=Ze.NOTEQUAL,wd.KEEP=Ze.KEEP,wd.REPLACE=Ze.REPLACE,wd.INCR=Ze.INCR,wd.DECR=Ze.DECR,wd.INVERT=Ze.INVERT,wd.INCR_WRAP=Ze.INCR_WRAP,wd.DECR_WRAP=Ze.DECR_WRAP,wd.TEXTURE_CLAMP_ADDRESSMODE=Ze.TEXTURE_CLAMP_ADDRESSMODE,wd.TEXTURE_WRAP_ADDRESSMODE=Ze.TEXTURE_WRAP_ADDRESSMODE,wd.TEXTURE_MIRROR_ADDRESSMODE=Ze.TEXTURE_MIRROR_ADDRESSMODE,wd.TEXTUREFORMAT_ALPHA=Ze.TEXTUREFORMAT_ALPHA,wd.TEXTUREFORMAT_LUMINANCE=Ze.TEXTUREFORMAT_LUMINANCE,wd.TEXTUREFORMAT_LUMINANCE_ALPHA=Ze.TEXTUREFORMAT_LUMINANCE_ALPHA,wd.TEXTUREFORMAT_RGB=Ze.TEXTUREFORMAT_RGB,wd.TEXTUREFORMAT_RGBA=Ze.TEXTUREFORMAT_RGBA,wd.TEXTUREFORMAT_RED=Ze.TEXTUREFORMAT_RED,wd.TEXTUREFORMAT_R=Ze.TEXTUREFORMAT_R,wd.TEXTUREFORMAT_RG=Ze.TEXTUREFORMAT_RG,wd.TEXTUREFORMAT_RED_INTEGER=Ze.TEXTUREFORMAT_RED_INTEGER,wd.TEXTUREFORMAT_R_INTEGER=Ze.TEXTUREFORMAT_R_INTEGER,wd.TEXTUREFORMAT_RG_INTEGER=Ze.TEXTUREFORMAT_RG_INTEGER,wd.TEXTUREFORMAT_RGB_INTEGER=Ze.TEXTUREFORMAT_RGB_INTEGER,wd.TEXTUREFORMAT_RGBA_INTEGER=Ze.TEXTUREFORMAT_RGBA_INTEGER,wd.TEXTURETYPE_UNSIGNED_BYTE=Ze.TEXTURETYPE_UNSIGNED_BYTE,wd.TEXTURETYPE_UNSIGNED_INT=Ze.TEXTURETYPE_UNSIGNED_INT,wd.TEXTURETYPE_FLOAT=Ze.TEXTURETYPE_FLOAT,wd.TEXTURETYPE_HALF_FLOAT=Ze.TEXTURETYPE_HALF_FLOAT,wd.TEXTURETYPE_BYTE=Ze.TEXTURETYPE_BYTE,wd.TEXTURETYPE_SHORT=Ze.TEXTURETYPE_SHORT,wd.TEXTURETYPE_UNSIGNED_SHORT=Ze.TEXTURETYPE_UNSIGNED_SHORT,wd.TEXTURETYPE_INT=Ze.TEXTURETYPE_INT,wd.TEXTURETYPE_UNSIGNED_INTEGER=Ze.TEXTURETYPE_UNSIGNED_INTEGER,wd.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4=Ze.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4,wd.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1=Ze.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1,wd.TEXTURETYPE_UNSIGNED_SHORT_5_6_5=Ze.TEXTURETYPE_UNSIGNED_SHORT_5_6_5,wd.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV=Ze.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV,wd.TEXTURETYPE_UNSIGNED_INT_24_8=Ze.TEXTURETYPE_UNSIGNED_INT_24_8,wd.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV=Ze.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV,wd.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV=Ze.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV,wd.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV=Ze.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV,wd.TEXTURE_NEAREST_SAMPLINGMODE=Ze.TEXTURE_NEAREST_SAMPLINGMODE,wd.TEXTURE_BILINEAR_SAMPLINGMODE=Ze.TEXTURE_BILINEAR_SAMPLINGMODE,wd.TEXTURE_TRILINEAR_SAMPLINGMODE=Ze.TEXTURE_TRILINEAR_SAMPLINGMODE,wd.TEXTURE_NEAREST_NEAREST_MIPLINEAR=Ze.TEXTURE_NEAREST_NEAREST_MIPLINEAR,wd.TEXTURE_LINEAR_LINEAR_MIPNEAREST=Ze.TEXTURE_LINEAR_LINEAR_MIPNEAREST,wd.TEXTURE_LINEAR_LINEAR_MIPLINEAR=Ze.TEXTURE_LINEAR_LINEAR_MIPLINEAR,wd.TEXTURE_NEAREST_NEAREST_MIPNEAREST=Ze.TEXTURE_NEAREST_NEAREST_MIPNEAREST,wd.TEXTURE_NEAREST_LINEAR_MIPNEAREST=Ze.TEXTURE_NEAREST_LINEAR_MIPNEAREST,wd.TEXTURE_NEAREST_LINEAR_MIPLINEAR=Ze.TEXTURE_NEAREST_LINEAR_MIPLINEAR,wd.TEXTURE_NEAREST_LINEAR=Ze.TEXTURE_NEAREST_LINEAR,wd.TEXTURE_NEAREST_NEAREST=Ze.TEXTURE_NEAREST_NEAREST,wd.TEXTURE_LINEAR_NEAREST_MIPNEAREST=Ze.TEXTURE_LINEAR_NEAREST_MIPNEAREST,wd.TEXTURE_LINEAR_NEAREST_MIPLINEAR=Ze.TEXTURE_LINEAR_NEAREST_MIPLINEAR,wd.TEXTURE_LINEAR_LINEAR=Ze.TEXTURE_LINEAR_LINEAR,wd.TEXTURE_LINEAR_NEAREST=Ze.TEXTURE_LINEAR_NEAREST,wd.TEXTURE_EXPLICIT_MODE=Ze.TEXTURE_EXPLICIT_MODE,wd.TEXTURE_SPHERICAL_MODE=Ze.TEXTURE_SPHERICAL_MODE,wd.TEXTURE_PLANAR_MODE=Ze.TEXTURE_PLANAR_MODE,wd.TEXTURE_CUBIC_MODE=Ze.TEXTURE_CUBIC_MODE,wd.TEXTURE_PROJECTION_MODE=Ze.TEXTURE_PROJECTION_MODE,wd.TEXTURE_SKYBOX_MODE=Ze.TEXTURE_SKYBOX_MODE,wd.TEXTURE_INVCUBIC_MODE=Ze.TEXTURE_INVCUBIC_MODE,wd.TEXTURE_EQUIRECTANGULAR_MODE=Ze.TEXTURE_EQUIRECTANGULAR_MODE,wd.TEXTURE_FIXED_EQUIRECTANGULAR_MODE=Ze.TEXTURE_FIXED_EQUIRECTANGULAR_MODE,wd.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE=Ze.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE,wd.SCALEMODE_FLOOR=Ze.SCALEMODE_FLOOR,wd.SCALEMODE_NEAREST=Ze.SCALEMODE_NEAREST,wd.SCALEMODE_CEILING=Ze.SCALEMODE_CEILING;const Bd={engine:"WebGL"};function Ud(e,t){const s={...Bd,...t},i=[];let r=!1;const n=new ResizeObserver((()=>r=!0));n.observe(e),i.push((()=>n.disconnect()));const a=new wd(e,void 0,t),o=s.onInitialized;s.onInitialized=e=>{const t=e.scene.onBeforeRenderObservable.add((()=>{r&&(a.resize(),r=!1)}));i.push((()=>t.remove())),o?.(e)};const h=new Ru(a,s);return i.push(h.dispose.bind(h)),i.push((()=>a.dispose())),h.dispose=()=>i.forEach((e=>e())),h}const kd=[.5,1,1.5,2];let Gd=class extends Id{constructor(){super(...arguments),this.src="",this.env="",this.animationSpeed=1,this.animationProgress=0,this._animations=[],this._selectedAnimation=-1,this._isAnimationPlaying=!1}get animations(){return this._animations}get selectedAnimation(){return this._selectedAnimation}get isAnimationPlaying(){return this._isAnimationPlaying}toggleAnimation(){this.viewer?.toggleAnimation()}connectedCallback(){super.connectedCallback(),this._setupViewer()}firstUpdated(e){super.firstUpdated(e),this._setupViewer()}disconnectedCallback(){super.disconnectedCallback(),this._tearDownViewer()}update(e){super.update(e),e.has("animationSpeed")&&this._updateAnimationSpeed(),e.has("_selectedAnimation")&&this._updateSelectedAnimation(),e.has("src")&&this._updateModel(),e.has("env")&&this._updateEnv()}render(){return cd`<div class="full-size"><canvas id="renderCanvas" class="full-size" touch-action="none"></canvas>${0===this.animations.length?"":cd`<slot name="tool-bar"><div part="tool-bar" class="tool-bar"><div class="progress-control"><button aria-label="${this.isAnimationPlaying?"Pause":"Play"}" @click="${this.toggleAnimation}">${this.isAnimationPlaying?cd`<svg viewBox="-3 -2 24 24"><path d="${"M5 2a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h2a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H5Zm8 0a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h2a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2h-2Z"}" fill="currentColor"></path></svg>`:cd`<svg viewBox="0 0 20 20"><path d="${"M17.22 8.68a1.5 1.5 0 0 1 0 2.63l-10 5.5A1.5 1.5 0 0 1 5 15.5v-11A1.5 1.5 0 0 1 7.22 3.2l10 5.5Z"}" fill="currentColor"></path></svg>`}</button> <input aria-label="Animation Progress" class="progress-wrapper" type="range" min="0" max="1" step="0.0001" .value="${this.animationProgress}" @input="${this._onProgressChanged}" @pointerdown="${this._onProgressPointerDown}"></div><select aria-label="Select Animation Speed" @change="${this._onAnimationSpeedChanged}">${kd.map((e=>cd`<option value="${e}" .selected="${this.animationSpeed===e}">${e}x</option>`))}</select> ${this.animations.length>1?cd`<select aria-label="Select Animation" @change="${this._onSelectedAnimationChanged}">${this.animations.map(((e,t)=>cd`<option value="${t}" .selected="${this.selectedAnimation==t}">${e}</option>`))}</select>`:""}</div></slot>`}</div>`}addEventListener(e,t,s){super.addEventListener(e,t,s)}_dispatchCustomEvent(e){this.dispatchEvent(new Event(e))}_onSelectedAnimationChanged(e){const t=e.target;this._selectedAnimation=Number(t.value)}_onAnimationSpeedChanged(e){const t=e.target;this.animationSpeed=Number(t.value)}_onProgressChanged(e){if(this.viewer){const t=e.target,s=Number(t.value);s!==this.animationProgress&&(this.viewer.animationProgress=s)}}_onProgressPointerDown(e){if(this.viewer?.isAnimationPlaying){this.viewer.pauseAnimation();e.target.addEventListener("pointerup",(()=>this.viewer?.playAnimation()),{once:!0})}}_setupViewer(){this._canvas&&!this.viewer&&(this.viewer=Ud(this._canvas),this.viewer.onModelLoaded.add((()=>{this._animations=[...this.viewer?.animations??[]],this._dispatchCustomEvent("modelchange")})),this.viewer.onModelError.add((()=>{this._dispatchCustomEvent("modelerror")})),this.viewer.onSelectedAnimationChanged.add((()=>{this._selectedAnimation=this.viewer?.selectedAnimation??-1,this._dispatchCustomEvent("selectedanimationchange")})),this.viewer.onAnimationSpeedChanged.add((()=>{let e=this.viewer?.animationSpeed??1;e=kd.reduce(((t,s)=>Math.abs(s-e)<Math.abs(t-e)?s:t)),this.animationSpeed=e,this._dispatchCustomEvent("animationspeedchange")})),this.viewer.onIsAnimationPlayingChanged.add((()=>{this._isAnimationPlaying=this.viewer?.isAnimationPlaying??!1,this._dispatchCustomEvent("animationplayingchange")})),this.viewer.onAnimationProgressChanged.add((()=>{this.animationProgress=this.viewer?.animationProgress??0,this._dispatchCustomEvent("animationprogresschange")})),this._updateSelectedAnimation(),this._updateAnimationSpeed(),this._updateModel(),this._updateEnv())}_tearDownViewer(){this.viewer&&(this.viewer.dispose(),this.viewer=void 0)}_updateAnimationSpeed(){this.viewer&&(this.viewer.animationSpeed=this.animationSpeed)}_updateSelectedAnimation(){this.viewer&&(this.viewer.selectedAnimation=this._selectedAnimation)}async _updateModel(){this.src&&await(this.viewer?.loadModelAsync(this.src).catch(ue.Log))}_updateEnv(){this.viewer?.loadEnvironmentAsync(this.env||void 0).catch(ue.Log)}};Gd.styles=((e,...t)=>{const s=1===e.length?e[0]:t.reduce(((t,s,i)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if("number"==typeof e)return e;throw Error("Value passed to 'css' function must be a 'css' function result: "+e+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(s)+e[i+1]),e[0]);return new vu(s,e,Iu)})`:host{--ui-foreground-color:white;--ui-background-hue:233;--ui-background-saturation:8%;--ui-background-lightness:39%;--ui-background-opacity:0.75;--ui-background-color:hsla(var(--ui-background-hue), var(--ui-background-saturation), var(--ui-background-lightness), var(--ui-background-opacity));--ui-background-color-hover:hsla(
45
- var(--ui-background-hue),
46
- var(--ui-background-saturation),
47
- calc(var(--ui-background-lightness) - 10%),
48
- calc(var(--ui-background-opacity) - 0.1)
49
- )}*{box-sizing:border-box}.full-size{display:block;width:100%;height:100%}.tool-bar{position:absolute;display:flex;flex-direction:row;border-radius:12px;border-color:var(--ui-foreground-color);height:48px;width:calc(100% - 24px);min-width:150px;max-width:1280px;bottom:12px;left:50%;transform:translateX(-50%);background-color:var(--ui-background-color);color:var(--ui-foreground-color);-webkit-tap-highlight-color:transparent}.tool-bar *{height:100%;min-width:48px}.tool-bar select{background:0 0;min-width:52px;max-width:128px;border:1px solid transparent;border-radius:inherit;color:inherit;font-size:14px;padding:12px;cursor:pointer;outline:0;appearance:none;-webkit-appearance:none;-moz-appearance:none}.tool-bar select:focus,.tool-bar select:hover{background-color:var(--ui-background-color-hover)}.tool-bar select option{background-color:var(--ui-background-color);color:var(--ui-foreground-color)}.tool-bar select:focus-visible{border-color:inherit}.tool-bar button{background:0 0;border:1px solid transparent;border-radius:inherit;color:inherit;padding:0;cursor:pointer;outline:0}.tool-bar button:hover{background-color:var(--ui-background-color-hover)}.tool-bar button:focus-visible{border-color:inherit}.tool-bar button svg{width:32px;height:32px}.progress-control{display:flex;flex:1;position:relative;overflow:hidden;cursor:pointer;align-items:center;border-radius:inherit;border-color:inherit}.progress-wrapper{-webkit-appearance:none;cursor:pointer;width:100%;height:100%;outline:0;border:1px solid transparent;border-radius:inherit;padding:0 12px;background-color:transparent}.progress-wrapper:focus-visible{border-color:inherit}.progress-wrapper::-webkit-slider-thumb{-webkit-appearance:none;width:20px;height:20px;border:2px solid;color:var(--ui-foreground-color);border-radius:50%;background:hsla(var(--ui-background-hue),var(--ui-background-saturation),var(--ui-background-lightness),1);margin-top:-10px}.progress-wrapper::-webkit-slider-runnable-track{height:2px;-webkit-appearance:none;background-color:var(--ui-foreground-color)}.progress-wrapper::-moz-range-progress{height:2px;background-color:var(--ui-foreground-color)}.progress-wrapper::-moz-range-thumb{width:16px;height:16px;border:2px solid var(--ui-foreground-color);border-radius:50%;background:hsla(var(--ui-background-hue),var(--ui-background-saturation),var(--ui-background-lightness),1)}.progress-wrapper::-moz-range-track{height:2px;background:var(--ui-foreground-color)}`,e([Pd()],Gd.prototype,"src",void 0),e([Pd()],Gd.prototype,"env",void 0),e([Pd({attribute:"animation-speed"})],Gd.prototype,"animationSpeed",void 0),e([Pd({attribute:!1})],Gd.prototype,"animationProgress",void 0),e([Od()],Gd.prototype,"_animations",void 0),e([Od()],Gd.prototype,"_selectedAnimation",void 0),e([Od()],Gd.prototype,"_isAnimationPlaying",void 0),e([
50
- /**
51
- * @license
52
- * Copyright 2017 Google LLC
53
- * SPDX-License-Identifier: BSD-3-Clause
54
- */
55
- function(e){return(t,s,i)=>((e,t,s)=>(s.configurable=!0,s.enumerable=!0,Reflect.decorate&&"object"!=typeof t&&Object.defineProperty(e,t,s),s))(t,s,{get(){return(t=>t.renderRoot?.querySelector(e)??null)(this)}})}("#renderCanvas")],Gd.prototype,"_canvas",void 0),Gd=e([(e=>(t,s)=>{void 0!==s?s.addInitializer((()=>{customElements.define(e,t)})):customElements.define(e,t)})("babylon-viewer")],Gd);export{Eo as A,Ze as C,Zn as D,_a as G,Gd as H,Tt as I,ue as L,$e as S,Yt as T,Ta as U,Ru as V,xn as a,Q as b,Dr as c,pa as d,L as e,Ud as f};
56
- //# sourceMappingURL=index-EA8kJjBu.esm.min.js.map